clearotron 0.7.0 → 0.8.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 (98) hide show
  1. package/THIRD-PARTY-NOTICES.md +71 -2
  2. package/build-info.json +2 -2
  3. package/demo/multi-country-focus-search/run/common-law-grid.json +1 -1
  4. package/docs/CLIENT-MCP.md +17 -0
  5. package/docs/assets/README.md +19 -3
  6. package/docs/assets/portal-clearance-report.jpg +0 -0
  7. package/docs/assets/portal-conflict-landscape.jpg +0 -0
  8. package/docs/assets/portal-new-clearance.png +0 -0
  9. package/driver/CHANGELOG.md +48 -0
  10. package/driver/config-inventory.mjs +15 -2
  11. package/driver/dev-portal.mjs +2 -0
  12. package/driver/effort-model.mjs +34 -4
  13. package/driver/engine/CONTRACT.md +8 -0
  14. package/driver/engine/anthropic-agent.mjs +74 -16
  15. package/driver/engine/jx-turn.mjs +11 -3
  16. package/driver/engine/openai-agent.mjs +33 -7
  17. package/driver/engine/run-choices.mjs +28 -7
  18. package/driver/engine/speed.mjs +107 -0
  19. package/driver/enqueue-schema.mjs +8 -0
  20. package/driver/enqueue.mjs +14 -2
  21. package/driver/jx-units.mjs +2 -2
  22. package/driver/jx.mjs +1 -1
  23. package/driver/knockout-plain-language.mjs +96 -0
  24. package/driver/ladder/attempt-record.mjs +14 -2
  25. package/driver/ladder/dispatch.mjs +2 -2
  26. package/driver/ladder/form-repair.mjs +1 -1
  27. package/driver/ladder/stage.mjs +7 -1
  28. package/driver/mark-logos.mjs +6 -1
  29. package/driver/order-receipt.mjs +184 -0
  30. package/driver/package.json +4 -1
  31. package/driver/picture-shrink-worker.mjs +21 -0
  32. package/driver/picture-thumbnail.mjs +132 -0
  33. package/driver/pipeline-knockout.mjs +14 -0
  34. package/driver/portal-confirmation.mjs +3 -0
  35. package/driver/portal-report.mjs +44 -1
  36. package/driver/portal-routes/run.mjs +19 -9
  37. package/driver/portal-runs.mjs +118 -63
  38. package/driver/portal-service.mjs +17 -2
  39. package/driver/predelivery-lint.mjs +3 -3
  40. package/driver/progress.mjs +33 -5
  41. package/driver/publish/column-queries.mjs +86 -0
  42. package/driver/publish/index.mjs +4 -4
  43. package/driver/publish/knockout.mjs +35 -8
  44. package/driver/publish/page-shell.mjs +5 -1
  45. package/driver/publish/read-document.mjs +3 -0
  46. package/driver/publish/render-knockout.mjs +61 -16
  47. package/driver/publish/render.mjs +171 -30
  48. package/driver/publish/search-depth.mjs +45 -1
  49. package/driver/publish/strings.mjs +23 -0
  50. package/driver/publish/templates/report.css +73 -0
  51. package/driver/research-answers.mjs +17 -6
  52. package/driver/research-checks.mjs +22 -4
  53. package/driver/research-records.mjs +81 -0
  54. package/driver/run-quote.mjs +3 -0
  55. package/driver/run-speed.mjs +89 -0
  56. package/driver/runner.mjs +50 -21
  57. package/driver/saved-register-pages.mjs +23 -22
  58. package/driver/stage-freshness.mjs +5 -0
  59. package/driver/stages.mjs +2 -2
  60. package/driver/steps/open-run.mjs +12 -1
  61. package/driver/suite-census.json +199 -37
  62. package/driver/tokens.mjs +3 -0
  63. package/driver/urgent-count.mjs +54 -0
  64. package/driver/usage-ledger.mjs +8 -2
  65. package/driver/web-pictures.mjs +532 -0
  66. package/mcp-server/CHANGELOG.md +16 -0
  67. package/mcp-server/lib/document-reads.mjs +28 -0
  68. package/mcp-server/lib/events.mjs +21 -12
  69. package/mcp-server/lib/findings.mjs +2 -1
  70. package/mcp-server/lib/knockout.mjs +3 -2
  71. package/mcp-server/lib/ops.mjs +103 -6
  72. package/mcp-server/lib/options.mjs +4 -0
  73. package/mcp-server/lib/plan.mjs +38 -4
  74. package/mcp-server/lib/result-shapes.mjs +66 -0
  75. package/mcp-server/lib/runs.mjs +46 -44
  76. package/mcp-server/lib/urgent.mjs +29 -0
  77. package/mcp-server/package.json +1 -1
  78. package/mcp-server/result-shapes.json +2978 -0
  79. package/mcp-server/server.mjs +67 -14
  80. package/package.json +4 -1
  81. package/portal-ui/dist/assets/{index-qNDhqCw9.js → index-DEkVU2FD.js} +1909 -766
  82. package/portal-ui/dist/assets/{index-CxAkJXIT.css → index-W6SAoDkS.css} +238 -1
  83. package/portal-ui/dist/index.html +2 -2
  84. package/portal-ui/package.json +1 -1
  85. package/providers/jx/src/turn-envelope.mjs +3 -1
  86. package/providers/oauth-mcp-bridge/CHANGELOG.md +4 -0
  87. package/providers/oauth-mcp-bridge/package.json +1 -1
  88. package/providers/signa/src/core.js +54 -12
  89. package/scripts/README.md +3 -0
  90. package/scripts/e2e-first-time.mjs +2 -2
  91. package/scripts/mint-result-shapes.mjs +199 -0
  92. package/scripts/readme-pictures.mjs +227 -0
  93. package/scripts/render-check.mjs +4 -1
  94. package/scripts/report-sections-render-check.mjs +191 -0
  95. package/scripts/settings-render-check.mjs +68 -11
  96. package/shared/brand.mjs +8 -0
  97. package/skills/clearotron-account/SKILL.md +24 -0
  98. package/skills/clearotron-ops/SKILL.md +23 -9
@@ -1,5 +1,21 @@
1
1
  # trademark-artifacts-mcp
2
2
 
3
+ ## 0.8.0-beta.0
4
+
5
+ ### Minor Changes
6
+
7
+ - New: The connector's six actions now declare the shape of their answer: starting, stopping or adding context to a search, running a what-if, marking a delivery sent and acknowledging an event. Each answer says in a field whether the action happened, or why it was refused, so a program built on the connector reads the outcome without parsing a sentence. The text an assistant reads is unchanged.
8
+ - New: The connector's tools that list searches and read a search's record now declare the shape of their answer too, and return it as structured data beside the same text as before. That covers the run list, a run's steps, its timeline, its changes, its telemetry, its coverage, the search tools, an order's free preview and the list of searches that can be ordered. A program built on the connector can rely on the fields each answer carries.
9
+ - New: The connector's tools that answer from a delivered report (the brief, the findings, a single finding, the evidence, the searches and the coverage) now declare the shape of their answer. Each answer names the version of the report record it was read from. Where a field means what the published report data means, it is declared the same way.
10
+ - New: An assistant connected to the connector can order a search Urgent. Before it orders, it can see whether this installation can run Urgent, and both options' turnaround and count of searches. Where the installation cannot run Urgent, the search starts at Standard, counts as one search, and the reply says so.
11
+ - New: An assistant connected to the connector now lists a search a company has just ordered, as queued, before a worker starts it. The portal already showed it this way, in the same words, "Waiting to start". Another company's order stays out of the list.
12
+ - New: When a request's deadline is tight, or it says urgent, today or ASAP, an assistant connected to the connector offers Urgent. It gives Urgent's turnaround, its cost of 2 searches and what is left today, then asks Urgent or Standard, and orders Urgent only when you say so. Where Urgent cannot run or does not fit today's searches, it says so and offers Standard.
13
+
14
+ ### Patch Changes
15
+
16
+ - Fixed: An order a company sends through the connector under its own reference is now filed under that reference with a mark of the company added, and the reply gives the reference it is filed under. Two companies that choose the same reference no longer meet. A company that sends its reference again is told its own order is already filed, and nothing is spent. It is never told anything of another company's order.
17
+ - Fixed: A search retired from the portal's list no longer appears in the run list an assistant reads through the connector. It can still be read by name, so a link already sent keeps working, and it comes back when it is restored.
18
+
3
19
  ## 0.7.0
4
20
 
5
21
  ### Patch Changes
@@ -0,0 +1,28 @@
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
+ // lib/document-reads.mjs — which version of a run's report document a call actually read.
4
+ //
5
+ // An answer read from a run's report document names the version it was read from (`report-document/clearance-1`,
6
+ // `report-document/knockout-1`). Which version that is, and whether the call read the document at all or the run's own
7
+ // files, is known only where the document is read, several modules down. So each place that reads it notes the
8
+ // version here, and the call's dispatcher collects what its own call noted.
9
+ //
10
+ // PER CALL, NOT PER PROCESS. The HTTP doors serve concurrent calls in one process, so the notes live in the call's
11
+ // async context (AsyncLocalStorage): one call's read can never be credited to another's answer.
12
+ import { AsyncLocalStorage } from "node:async_hooks";
13
+
14
+ const reads = new AsyncLocalStorage();
15
+
16
+ /** Run `fn` and return its value with the document versions it read, in the order first read. */
17
+ export async function withDocumentReads(fn) {
18
+ const seen = new Set();
19
+ const value = await reads.run(seen, fn);
20
+ return { value, documents: [...seen] };
21
+ }
22
+
23
+ /** Note that the current call read `doc`, and hand it back. Outside a dispatched call it notes nothing. */
24
+ export function noteDocumentRead(doc) {
25
+ const seen = reads.getStore();
26
+ if (seen && typeof doc?.document === "string") seen.add(doc.document);
27
+ return doc;
28
+ }
@@ -15,7 +15,7 @@
15
15
  import { existsSync, readFileSync } from "node:fs";
16
16
  import { join } from "node:path";
17
17
  import { readCapped } from "./util.mjs";
18
- import { stepForStage } from "./driver.mjs";
18
+ import { stepForStage, DISPLAY_STEPS } from "./driver.mjs";
19
19
  import { paths } from "../../driver/run-record.mjs";
20
20
 
21
21
  export function readEvents(runDir) {
@@ -30,7 +30,15 @@ export function readEvents(runDir) {
30
30
  // the bytes, so a paraphrase fails there rather than reaching a client.
31
31
  export const CLIENT_INCOMPLETE = "Screening: incomplete — flagged for review";
32
32
 
33
- function phaseFor(stage) { const s = stepForStage(stage); return s ? s.label : null; }
33
+ // THE RUN'S OWN STEP NAMES where it wrote a clearance list (status.json `steps`), so a Global preliminary's
34
+ // sixth step reads here as it does on Home and in the run's status. The stage-to-step map is the clearance
35
+ // stepper's, so a Knockout's own list (five or six steps) is never indexed by it, and a run recorded before
36
+ // the field keeps the shipped list.
37
+ function phaseFor(stage, steps) {
38
+ const own = Array.isArray(steps) && steps.length === DISPLAY_STEPS.length ? steps : DISPLAY_STEPS;
39
+ const s = stepForStage(stage, own);
40
+ return s ? s.label : null;
41
+ }
34
42
  function ratObj(source, text) { return text ? { source, text } : null; }
35
43
 
36
44
  // Lazily read + cache the small run-local rationale source files (escalation reasons, the verdict head line).
@@ -82,25 +90,25 @@ function classify(e, st, rat) {
82
90
  if (sha != null) st.prevSha.set(label, sha);
83
91
  const decision = e.event === "skip" ? "stage-skipped" : seen ? "stage-recomputed" : "stage-completed";
84
92
  return {
85
- ts, kind: e.event, phase: phaseFor(label), stage: label, decision,
93
+ ts, kind: e.event, phase: phaseFor(label, st.steps), stage: label, decision,
86
94
  trigger: e.trigger ?? null,
87
95
  ok: e.ok ?? (e.event === "skip" ? true : null), outputSha: sha, changedFromPrevious,
88
96
  };
89
97
  }
90
98
  case "failover":
91
- return { ts, kind: "failover", phase: phaseFor(e.stage), stage: e.stage ?? null, decision: "model-failover", attempt: e.attempt ?? null };
99
+ return { ts, kind: "failover", phase: phaseFor(e.stage, st.steps), stage: e.stage ?? null, decision: "model-failover", attempt: e.attempt ?? null };
92
100
  case "attempt": // AD-4: the per-dispatch spine (gateway runStage) — projected compactly, cause kept
93
- return { ts, kind: "attempt", phase: phaseFor(e.stage), stage: e.stage ?? null,
101
+ return { ts, kind: "attempt", phase: phaseFor(e.stage, st.steps), stage: e.stage ?? null,
94
102
  decision: e.ok ? "attempt-succeeded" : "attempt-failed", attempt: e.attempt ?? null, fail: e.fail ?? null };
95
103
  case "skeptic-escalation":
96
- return { ts, kind: "skeptic-escalation", phase: phaseFor("skeptic"), decision: "escalated-axes", escalated: e.escalated ?? [], rationale: ratObj("skeptic-flags.md", rat.escalation()) };
104
+ return { ts, kind: "skeptic-escalation", phase: phaseFor("skeptic", st.steps), decision: "escalated-axes", escalated: e.escalated ?? [], rationale: ratObj("skeptic-flags.md", rat.escalation()) };
97
105
  case "escalation-skipped":
98
106
  return { ts, kind: "escalation-skipped", decision: "escalation-skipped", axis: e.axis ?? null, reason: e.reason ?? null };
99
107
  case "escalation-noop":
100
108
  return { ts, kind: "escalation-noop", decision: "axis-defended-in-place", axis: e.axis ?? null };
101
109
  case "verdict":
102
110
  case "verdict-2":
103
- return { ts, kind: e.event, phase: phaseFor("narrative-refutation"), decision: "verdict-emitted", verdict: e.verdict ?? null, rationale: ratObj("senior-eye-review.md", rat.verdictHead()) };
111
+ return { ts, kind: e.event, phase: phaseFor("narrative-refutation", st.steps), decision: "verdict-emitted", verdict: e.verdict ?? null, rationale: ratObj("senior-eye-review.md", rat.verdictHead()) };
104
112
  case "delivered-with-open-questions":
105
113
  return { ts, kind: e.event, decision: "delivered-with-open-questions", verdict: e.verdict ?? null };
106
114
  // ── — THREE WRITERS, FIVE CAUSES, AND THIS SURFACE SAID ONE WORD ──────────────────────────
@@ -149,9 +157,9 @@ function classify(e, st, rat) {
149
157
  case "provider-usage":
150
158
  return { ts, kind: "provider-usage", decision: "usage-recorded", summary: { total: e.total ?? null, search: e.search ?? null, record_fetch: e.record_fetch ?? null } };
151
159
  case "manual-rerun":
152
- return { ts, kind: "manual-rerun", phase: phaseFor(e.stage), stage: e.stage ?? null, decision: "manual-rerun", snapshot: e.snapshot ?? null };
160
+ return { ts, kind: "manual-rerun", phase: phaseFor(e.stage, st.steps), stage: e.stage ?? null, decision: "manual-rerun", snapshot: e.snapshot ?? null };
153
161
  case "failed":
154
- return { ts, kind: "failed", phase: phaseFor(e.stage), stage: e.stage ?? null, decision: "run-failed", reason: e.reason ?? null };
162
+ return { ts, kind: "failed", phase: phaseFor(e.stage, st.steps), stage: e.stage ?? null, decision: "run-failed", reason: e.reason ?? null };
155
163
  // AN ENGINE-INTERNAL RECORD, NEVER A DECISION. How the synthesis transport read a call — a marker decoded, rows
156
164
  // lifted, keys a call carried that the transport ignores — is a fact about the engine's own plumbing, and
157
165
  // whether each reviewer correction reached the delivered record is the reviewer's business, which never
@@ -198,12 +206,13 @@ const isNoiseEntry = (t) => t.kind === "attempt" && t.decision === "attempt-succ
198
206
  const isInternalEntry = (t) => t.internal === true;
199
207
 
200
208
  /**
201
- * projectTimeline(events, P, {sinceTs}) → { timeline, verdictHistory }.
209
+ * projectTimeline(events, P, {sinceTs, sinceSeq, steps}) → { timeline, verdictHistory }. `steps` is the run's own
210
+ * step list (status.json), which names each entry's phase.
202
211
  * `seq` is assigned over the FULL ordered log (stable), THEN sinceTs filters — so a poll cursor never
203
212
  * renumbers earlier entries. verdictHistory is [verdict, verdict-2?] in emission order.
204
213
  */
205
- export function projectTimeline(events, P, { sinceTs, sinceSeq } = {}) {
206
- const st = { prevSha: new Map() };
214
+ export function projectTimeline(events, P, { sinceTs, sinceSeq, steps = null } = {}) {
215
+ const st = { prevSha: new Map(), steps };
207
216
  const rat = makeRationale(P);
208
217
  const full = [];
209
218
  let seq = 0;
@@ -10,6 +10,7 @@
10
10
  import { existsSync, readFileSync } from "node:fs";
11
11
  import { parseAudit, parseReport, parseBlocks, parseFront, parseSections, buildAuditMd, placementAuditRows } from "./driver.mjs";
12
12
  import { readJson } from "../../driver/run-record.mjs";
13
+ import { noteDocumentRead } from "./document-reads.mjs"; // the answer names the document version it was read from
13
14
 
14
15
  // id-stamp the three block lists so callers (get_finding / trace) can address a single record.
15
16
  function idStamp(lists) {
@@ -53,7 +54,7 @@ export function reportDocumentOf(P, kind = "clearance") {
53
54
  try {
54
55
  if (!P?.reportDocument || !existsSync(P.reportDocument)) return null;
55
56
  const doc = readJson(P.reportDocument);
56
- return doc?.document === `report-document/${kind}-1` ? doc : null;
57
+ return doc?.document === `report-document/${kind}-1` ? noteDocumentRead(doc) : null;
57
58
  } catch { return null; }
58
59
  }
59
60
 
@@ -34,6 +34,7 @@ import { PART_NAMES } from "../../driver/degraded-parts.mjs";
34
34
  import { readerRowHead } from "../../driver/coverage-ledger.mjs";
35
35
  import { knockoutLeftOpenOf } from "../../driver/publish/knockout-left-open.mjs"; // a name's Left open rows, as its page lists them
36
36
  import { REPORT_PAGE } from "../../driver/publish/strings.mjs";
37
+ import { noteDocumentRead } from "./document-reads.mjs"; // the answer names the document version it was read from
37
38
 
38
39
 
39
40
  /**
@@ -54,7 +55,7 @@ export function knockoutDoc(run) {
54
55
  if (!run?.runDir) return null;
55
56
  // The findings record as publishing held it, where the run's report document has it; the run's own file otherwise.
56
57
  const document = readJsonOrNull(paths(run.runDir).reportDocument);
57
- if (document?.document === "report-document/knockout-1" && document.client?.findings) return document.client.findings;
58
+ if (document?.document === "report-document/knockout-1" && document.client?.findings) return noteDocumentRead(document).client.findings;
58
59
  return readJsonOrNull(koPaths(run.runDir).findings);
59
60
  }
60
61
 
@@ -334,7 +335,7 @@ export function knockoutSearches(run) {
334
335
  // evidence, and the answers below state the edition the report delivered. null for a run published before the document.
335
336
  const deliveredDocument = (run) => {
336
337
  const document = run?.runDir ? readJsonOrNull(paths(run.runDir).reportDocument) : null;
337
- return document?.document === "report-document/knockout-1" ? document : null;
338
+ return document?.document === "report-document/knockout-1" ? noteDocumentRead(document) : null;
338
339
  };
339
340
  const registerRecordsOf = (run) => {
340
341
  const document = deliveredDocument(run);
@@ -10,11 +10,16 @@
10
10
 
11
11
  import { writeFileSync, existsSync, mkdirSync, rmSync, renameSync, readFileSync, readdirSync } from "node:fs";
12
12
  import { join, basename } from "node:path";
13
- import { randomUUID } from "node:crypto";
13
+ import { createHash, randomUUID } from "node:crypto";
14
14
  import { config } from "./driver.mjs";
15
15
  import { validateJob } from "../../driver/enqueue-schema.mjs";
16
16
  import { doorGates } from "../../driver/door-gates.mjs"; // the resolved-product checks every door runs
17
- import { probeQueueWatch, unwatchedQueueWarning } from "../../driver/queue-watch-probe.mjs"; //
17
+ import { probeQueueWatch, unwatchedQueueWarning } from "../../driver/queue-watch-probe.mjs";
18
+ import { accountUsage, DEFAULT_CLIENT_DAILY_RUNS } from "../../driver/usage-ledger.mjs"; // the ledger the wall counts
19
+ import { resolveEffectiveProfile } from "../../driver/profiles.mjs";
20
+ import { admittedSearches, oneLeftRefusal } from "../../driver/urgent-count.mjs"; // one search left and an Urgent order
21
+ import { receiptIn, RECEIPT_STATES } from "../../driver/order-receipt.mjs"; // an id in any state is that order, not a new one
22
+ import { orderUrgency } from "./urgent.mjs"; // whether this installation can run an Urgent order, as the run asks it //
18
23
  import { resolveRun, runAccountKey } from "./runs.mjs";
19
24
  import { accountVisible, assertAccountAccess, attributionOf, grantsGeneric, GENERIC_NOT_GRANTED } from "../../shared/scope.mjs";
20
25
  import { requestCancel, isCancelled } from "../../driver/cancel.mjs"; // one marker shape, shared with the engine
@@ -66,8 +71,41 @@ export function enqueuedViaFor(scope) {
66
71
  // three mornings before it made one up that fit. stop_run's queue form holds a queued id to the same rule.
67
72
  const QUEUE_ID_MAX = 128;
68
73
  const QUEUE_ID_RE = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._@-]{0,${QUEUE_ID_MAX - 1}}$`);
69
- const queueIdRefusal = (id) => `id ${JSON.stringify(id)}: Use an ID of 1–${QUEUE_ID_MAX} characters. Start with an ASCII letter or digit. `
70
- + `The remaining characters may also include a dot, underscore, @ or hyphen.${id.length > QUEUE_ID_MAX ? ` This one has ${id.length} characters.` : ""}`;
74
+ const queueIdRefusal = (id, max = QUEUE_ID_MAX) => `id ${JSON.stringify(id)}: Use an ID of 1–${max} characters. Start with an ASCII letter or digit. `
75
+ + `The remaining characters may also include a dot, underscore, @ or hyphen.${id.length > max ? ` This one has ${id.length} characters.` : ""}`;
76
+
77
+ // ── AN ACCOUNT'S REFERENCE IS ITS OWN (design, 2026-11-26) ──────────────────────────────────────────────────────────
78
+ //
79
+ // A session that does not see every account names its order by a reference it may have chosen itself, and a session of
80
+ // another account may choose the same one. Any answer that differed only when they met (a refusal, a fresh reference,
81
+ // the order's state) would tell one account about the other's order, and the file could only hold one of them. So
82
+ // every order such a session files carries a fixed mark of its account, and of the organisation for Generic: two
83
+ // accounts' references never meet, and a retry by the same account meets its own order and spends nothing. The reply
84
+ // gives the reference the order is filed under; a reference that already ends in the session's own mark is that
85
+ // reference, not a new one. A session that sees every account (an operator) files the reference as sent.
86
+ const ACCOUNT_MARK_LEN = 12;
87
+ const seesEveryAccount = (scope) => scope?.accounts == null || scope.accounts === "*";
88
+ function accountMark(job) {
89
+ const account = job.profileKey ?? "generic";
90
+ const organisation = account === "generic" ? (job.tenant ?? "") : "";
91
+ return createHash("sha256").update(`${account}\u0000${organisation}`).digest("hex").slice(0, ACCOUNT_MARK_LEN);
92
+ }
93
+ /** The reference an order is filed under: as sent for a session that sees every account, else carrying its account's mark. */
94
+ function filedReference(asked, job, scope) {
95
+ if (seesEveryAccount(scope)) return asked;
96
+ const mark = `@${accountMark(job)}`;
97
+ if (asked.endsWith(mark)) return asked;
98
+ const max = QUEUE_ID_MAX - mark.length;
99
+ if (asked.length > max) throw new Error(queueIdRefusal(asked, max));
100
+ return `${asked}${mark}`;
101
+ }
102
+ /** Whether this session may see an order already filed: its account, and its organisation for Generic. */
103
+ function mayseeOrder(scope, job) {
104
+ if (seesEveryAccount(scope)) return true;
105
+ if (!job) return false;
106
+ const account = job.profileKey ?? "generic";
107
+ return accountVisible(scope, account, account === "generic" ? (job.tenant ?? null) : null);
108
+ }
71
109
 
72
110
  export function buildJob(args = {}, { scope } = {}) {
73
111
  // marks[] (search-depth spine): a knockout BATCH is ONE job carrying every mark — accept an explicit
@@ -146,6 +184,9 @@ export function buildJob(args = {}, { scope } = {}) {
146
184
  // field and silently ignores it. validateJob owns the vocabulary (see the note above); it refuses,
147
185
  // in the same sentence the portal and the CLI refuse with.
148
186
  ...("caseLaw" in args && args.caseLaw != null ? { caseLaw: args.caseLaw } : {}),
187
+ // URGENT, carried verbatim like the toggle above: `true` orders the faster setting, `false` and absence are a
188
+ // standard order, and any other value reaches validateJob, which refuses it rather than run it as Standard.
189
+ ...("urgent" in args && args.urgent != null ? { urgent: args.urgent } : {}),
149
190
  ...("searchLevel" in args ? { searchLevel: args.searchLevel } : {}), // presence, null included
150
191
  ...(args.customerUnknown === true ? { customerUnknown: true } : {}),
151
192
  ...(args.dupOverride === true ? { dupOverride: true } : {}),
@@ -209,6 +250,8 @@ export const START_RUN_JOB_FIELDS = Object.freeze({
209
250
  // and "I said nothing" are two different searches and only a positive instruction can tell them apart.
210
251
  "geography",
211
252
  "product", "recipeKey", "nativeLanguage", "caseLaw", "searchLevel", "deliveryRoute", "parentRunId",
253
+ // the order's How soon option: true is Urgent. Carried as sent; validateJob refuses a value that is not a boolean.
254
+ "urgent",
212
255
  "customer", "profileKey", "projectKey", "customerUnknown", "tenant",
213
256
  "upfrontInstructions", "brief", "rawRequest", "deliverableSpec", "commercialFlexibility",
214
257
  "priorUse", "campaignShape", "deadline",
@@ -256,15 +299,55 @@ export function resolveScopedProfileKey(args, scope, verb) {
256
299
 
257
300
  // start_run — enqueue a clearotron job the runner will drain. Returns the queue id + slug; the runId/codename is
258
301
  // assigned by the runner on claim, so the caller polls list_runs(slug) / run_changes for it.
302
+ /**
303
+ * The one-left sentence for a session the daily allowance binds, or null. The same count the preview reads (plan.mjs
304
+ * allowanceFor) and the same rule the wall applies (urgent-count.mjs). A ledger or profile that cannot be read refuses
305
+ * nothing: the wall still holds. Generic is answered as the preview answers it, by the wall alone.
306
+ */
307
+ function oneLeftAtStart(job, scope) {
308
+ if (scope?.kind !== "account" || scope?.everything === true) return null;
309
+ try {
310
+ const profile = resolveEffectiveProfile(job).profile;
311
+ if (!profile?.key || profile.key === "generic") return null;
312
+ const limit = Number.isInteger(profile.runCaps?.dailyRuns) ? profile.runCaps.dailyRuns : DEFAULT_CLIENT_DAILY_RUNS;
313
+ const used = accountUsage({ queueDirs: config.queueDirs, account: profile.key });
314
+ if (!used?.complete) return null;
315
+ return oneLeftRefusal({ used: used.today, limit, searches: admittedSearches(job) });
316
+ } catch { return null; }
317
+ }
318
+
259
319
  export function startRun(args = {}, { scope } = {}) {
260
320
  const agent = args.agent ? String(args.agent) : "";
261
321
  args = resolveScopedProfileKey(args, scope, "start_run");
262
322
  const qdir = queueDir(agent);
263
323
  // ONE builder shared with plan_run, so the preview a caller confirms is the job that actually runs.
264
324
  let job;
265
- try { job = buildJob(args, { scope }); }
325
+ try { job = buildJob(args, { scope }); job.id = filedReference(job.id, job, scope); }
266
326
  catch (e) { throw new Error(`start_run: ${e.message}`); }
267
327
  const { id } = job;
328
+ // AN ID IN ANY STATE IS THAT ORDER, asked before anything else so a retry is recognised as one: before validation, and
329
+ // before the allowance is counted again for an order already counted. The check before the write below saw only a
330
+ // waiting or claimed job, so a retry after a refusal, a park or a delivery wrote a second order under the same id.
331
+ //
332
+ // ONLY AN ORDER THIS SESSION MAY SEE IS ANSWERED FOR. An order filed under the bare reference before references carried
333
+ // an account's mark is this order where the session may see it, and nothing at all where it may not. Under the marked
334
+ // reference only the same account's order can be found; were another found (two marks the same), the refusal names
335
+ // nothing of it.
336
+ {
337
+ let names = [];
338
+ try { names = readdirSync(qdir); } catch { /* no queue directory yet holds no order */ }
339
+ const bare = String(args.id ?? "");
340
+ for (const ref of bare && bare !== id ? [id, bare] : [id]) {
341
+ const existing = receiptIn(qdir, ref, names);
342
+ if (!existing) continue;
343
+ if (!mayseeOrder(scope, existing.job)) {
344
+ if (ref === id) throw new Error(`start_run: a job with id "${id}" is already queued/processing`);
345
+ continue;
346
+ }
347
+ if (["waiting", "checking", "running"].includes(existing.state)) throw new Error(`start_run: a job with id "${ref}" is already queued/processing`);
348
+ throw new Error(`start_run: a job with id "${ref}" already exists: ${RECEIPT_STATES[existing.state]}`);
349
+ }
350
+ }
268
351
 
269
352
  const v = validateJob(job);
270
353
  if (v.classify === "reject" || !v.ok) {
@@ -292,6 +375,20 @@ export function startRun(args = {}, { scope } = {}) {
292
375
  e.classify = "clarify";
293
376
  throw e;
294
377
  }
378
+ // AN URGENT ORDER THIS INSTALLATION CANNOT RUN starts at Standard, counts one search, and says so; it is never
379
+ // refused and never held. The job is written as Standard, so the run and its count agree with the reply.
380
+ const urgency = orderUrgency(job);
381
+ job = urgency.job;
382
+ // ONE SEARCH LEFT AND AN ORDER THAT COUNTS TWO (design, 2026-11-26): refused here in the order screen's words, as the
383
+ // portal's start and the runner's wall refuse it, rather than queued for the wall to refuse at claim, where this
384
+ // caller never sees it. Never written as Standard instead.
385
+ const oneLeft = oneLeftAtStart(job, scope);
386
+ if (oneLeft) {
387
+ const e = new Error(`start_run: job rejected — ${oneLeft}`);
388
+ e.errors = [oneLeft];
389
+ e.classify = "clarify";
390
+ throw e;
391
+ }
295
392
 
296
393
  mkdirSync(qdir, { recursive: true });
297
394
  const tmp = join(qdir, `${id}.json.tmp`);
@@ -304,7 +401,7 @@ export function startRun(args = {}, { scope } = {}) {
304
401
  const watch = probeQueueWatch({ queueDirs: [qdir] });
305
402
  return {
306
403
  ok: true, id, agent: agent || config.defaultAgent, queue: qdir, queued: true, classify: v.classify,
307
- warnings: [...(v.warnings || []), ...gates.warnings,
404
+ warnings: [...(v.warnings || []), ...gates.warnings, ...urgency.warnings,
308
405
  ...(watch.state === "fail" ? [unwatchedQueueWarning(qdir, watch.unitPath)] : [])],
309
406
  queuePath: dest, queueWatched: watch.state,
310
407
  note: "Queued. The runner assigns a runId/codename on claim — poll list_runs (filter by markName) or run_changes for progress.",
@@ -45,6 +45,7 @@ import { loadProfiles, loadProjects, recipeProseGuard } from "../../driver/profi
45
45
  import { accountUsage, DEFAULT_CLIENT_DAILY_RUNS } from "../../driver/usage-ledger.mjs";
46
46
  import { config } from "./driver.mjs";
47
47
  import { BRAND } from "../../shared/brand.mjs"; // — the operator name in the allowance notes, from the tenant seam
48
+ import { urgentHere, URGENT_UNAVAILABLE } from "./urgent.mjs"; // the How soon option, as this installation can run it
48
49
 
49
50
  // What each product IS, in the words a requester uses. The registry knows its components; a client does
50
51
  // not, and must not have to: `jxLanes`, `commonLawGrid` and `registerProbe` are the machinery's names for
@@ -362,6 +363,9 @@ export function describeOptions(args = {}, { scope, now = Date.now() } = {}) {
362
363
  // disclosed deferred coverage rows, which is what the engine already does with them.
363
364
  ...(territories === undefined ? {} : { registerTerritories: territories }),
364
365
  scopeRules: SCOPE_RULES,
366
+ // WHETHER THIS INSTALLATION CAN RUN AN URGENT ORDER, from the same answer the run itself reads (lib/urgent.mjs).
367
+ // Where it cannot, the board's own sentence says what an Urgent order does instead.
368
+ urgent: urgentHere().available ? { available: true } : { available: false, note: URGENT_UNAVAILABLE },
365
369
  account,
366
370
  ...(accountsGranted ? { accountsGranted } : {}),
367
371
  ...(account || accountsGranted ? {} : {
@@ -32,8 +32,10 @@ import { productRow, baseTurnaroundFor } from "../../driver/product-rows.mjs";
32
32
  import { resolveRequest } from "../../driver/resolve-request.mjs";
33
33
  import { readFlagSnapshot, builtFor, registerCanCountFor, registerTerritoriesFor } from "../../driver/flag-snapshot.mjs";
34
34
  import { gateResolvedRequest } from "../../driver/door-gates.mjs"; // the resolved-product checks every door runs
35
+ import { oneLeftRefusal } from "../../driver/urgent-count.mjs"; // one search left and an Urgent order: the wall's own words
35
36
  import { quoteForJob } from "../../driver/run-quote.mjs";
36
37
  import { accountUsage, DEFAULT_CLIENT_DAILY_RUNS } from "../../driver/usage-ledger.mjs";
38
+ import { orderUrgency, urgentHere, URGENT_UNAVAILABLE } from "./urgent.mjs"; // the How soon option, as this installation can run it
37
39
  import { config } from "./driver.mjs";
38
40
  import { demoServing } from "../demo-mode.mjs"; // — a demo's preview names no tool it withholds
39
41
  import { buildJob, resolveScopedProfileKey } from "./ops.mjs";
@@ -187,16 +189,32 @@ function bindingLayersForOrder(jurisdictions) {
187
189
  *
188
190
  * Takes the SAME args as start_run. Confirming is a separate, explicit start_run call with the same args.
189
191
  */
192
+ /**
193
+ * WHETHER AN OPTION FITS WHAT THE ACCOUNT HAS LEFT TODAY, by the wall's own rule: admission refuses an order whose
194
+ * count would take the day past the cap (`today + searches > dailyRuns`, driver/urgent-count.mjs). An Urgent order
195
+ * counts two, so with one search left Standard fits and Urgent does not. Null where no cap applies to this session,
196
+ * or where today's usage could not be read: a preview must not claim either answer on no evidence.
197
+ */
198
+ export function withinAllowance(allowance, searches) {
199
+ if (!allowance?.capped || !allowance.complete || typeof searches !== "number") return null;
200
+ return allowance.today + searches <= allowance.dailyRunsEffective;
201
+ }
202
+
190
203
  export function planRun(args = {}, { scope, now = Date.now() } = {}) {
191
204
  // Resolved, not merely checked — and BEFORE buildJob, so the preview describes the job start_run
192
205
  // would build, including the account it would run under when the request named none.
193
206
  args = resolveScopedProfileKey(args, scope, "plan_run");
194
207
  // The EXACT job start_run would build — not a lookalike assembled here, which could drift from it.
195
- const job = buildJob(args, { scope });
208
+ const built = buildJob(args, { scope });
196
209
 
197
210
  // validateJob NORMALIZES in place (jurisdiction dedupe, the bare-string fix, deadline shape), so what
198
211
  // is reported below is what the engine would actually receive, not what the caller typed.
199
- const v = validateJob(job);
212
+ const v = validateJob(built);
213
+ // THE ORDER AS THIS INSTALLATION WOULD RUN IT, the same answer start_run applies: an Urgent order it cannot run is
214
+ // previewed as Standard, with the board's sentence among the warnings.
215
+ const urgency = v.ok ? orderUrgency(built) : { job: built, warnings: [] };
216
+ const job = urgency.job;
217
+ const urgentHereNow = urgentHere();
200
218
 
201
219
  let profile = null, projectKey = null, origins = null;
202
220
  // Profile resolution reads the roster off disk; infra trouble must degrade the PREVIEW, never throw —
@@ -305,9 +323,18 @@ export function planRun(args = {}, { scope, now = Date.now() } = {}) {
305
323
  // is worth nothing. `effort: null` says honestly that we could not size it.
306
324
  // `eff` is passed so the scope is not resolved twice; quoteForJob would resolve the same thing itself.
307
325
  const effort = quoteForJob({ job, profile, searchPolicy: resolved, scope: eff });
326
+ // HOW SOON: both options' turnaround and count, each from the shared effort model for this search as configured —
327
+ // the same quote the portal's footer reads — so the preview never carries a second copy of either figure.
328
+ const quoteAs = (urgent) => quoteForJob({ job: { ...job, urgent }, profile, searchPolicy: resolved, scope: eff });
329
+ const option = (q) => (q ? { turnaround: q.turnaround, turnaroundLowHours: q.turnaroundLowHours, turnaroundHighHours: q.turnaroundHighHours,
330
+ searches: q.searches, withinAllowance: withinAllowance(allowance, q.searches) } : null);
308
331
  // The daily allowance, reported for every principal and BLOCKING only for a client account (the one
309
332
  // kind the wall actually caps). Advice, not a gate — see allowanceFor.
310
333
  const allowance = allowanceFor(profile, { scope, now });
334
+ // ONE SEARCH LEFT, AND AN URGENT ORDER THAT COUNTS TWO: the wall refuses it in the order screen's words, so the
335
+ // preview blocks it in the same words (driver/urgent-count.mjs). Standard still fits, and How soon says so.
336
+ const oneLeftBlocker = allowance?.capped && allowance.complete && !allowance.exhausted
337
+ ? oneLeftRefusal({ used: allowance.today, limit: allowance.dailyRunsEffective, searches: effort?.searches ?? 1 }) : null;
311
338
  const quotaBlocker = allowance?.exhausted
312
339
  ? `this account has used all ${allowance.dailyRunsEffective} of today's client-started searches — start_run would be refused at admission. The allowance resets at midnight UTC; your ${BRAND.name} contact can run this one today.`
313
340
  : null;
@@ -339,7 +366,7 @@ export function planRun(args = {}, { scope, now = Date.now() } = {}) {
339
366
  // the fold against what it RESOLVES TO, and when the two are the same product they are the same
340
367
  // sentence. Read aloud to a requester, "this request names 2 countries" twice is a defect; deduping
341
368
  // where they are joined keeps every source honest and says it once.
342
- const blocking = [...new Set([...(rosterRefusal ? [rosterRefusal] : []), ...(v.classify === "reject" || !v.ok ? v.errors : []), ...gates.errors, ...(unavailable ? [unavailable] : []), ...(quotaBlocker ? [quotaBlocker] : []), ...(routeBlocker ? [routeBlocker] : []), ...(demoBlocker ? [demoBlocker] : [])])];
369
+ const blocking = [...new Set([...(rosterRefusal ? [rosterRefusal] : []), ...(v.classify === "reject" || !v.ok ? v.errors : []), ...gates.errors, ...(unavailable ? [unavailable] : []), ...(quotaBlocker ? [quotaBlocker] : []), ...(oneLeftBlocker ? [oneLeftBlocker] : []), ...(routeBlocker ? [routeBlocker] : []), ...(demoBlocker ? [demoBlocker] : [])])];
343
370
 
344
371
  // ONE lookup, and the fields below come off it — the same shape portal-service's plan door was fixed
345
372
  // into. productRow computes a turnaround on every call; asking twice for one answer is how two answers
@@ -372,7 +399,7 @@ export function planRun(args = {}, { scope, now = Date.now() } = {}) {
372
399
  : "NOTHING HAS BEEN STARTED and nothing has been charged. This is what would run. Show it to the requester, and call start_run with the SAME arguments only once they have confirmed it.")
373
400
  : "NOTHING HAS BEEN STARTED. This request cannot run as stated — the blockers below are questions to put back to the requester, not failures to retry.",
374
401
  blockers: blocking,
375
- warnings: [...(v.warnings ?? []), ...gates.warnings, ...(quotaWarning ? [quotaWarning] : []),
402
+ warnings: [...(v.warnings ?? []), ...gates.warnings, ...urgency.warnings, ...(quotaWarning ? [quotaWarning] : []),
376
403
  ...(coverage ? [coverage.note] : [])],
377
404
  caveat: PLAN_CAVEAT,
378
405
  search: {
@@ -428,6 +455,13 @@ export function planRun(args = {}, { scope, now = Date.now() } = {}) {
428
455
  // accounts and must never be used as a billing quantity; `raw` is the absolute figure. `unitsVersion`
429
456
  // says which weight set produced them, so a later re-fit cannot make this quote unreadable.
430
457
  effort,
458
+ howSoon: {
459
+ chosen: job.urgent === true ? "urgent" : "standard",
460
+ urgentAvailable: urgentHereNow.available,
461
+ ...(urgentHereNow.available ? {} : { urgentNote: URGENT_UNAVAILABLE }),
462
+ standard: option(quoteAs(false)),
463
+ urgent: urgentHereNow.available ? option(quoteAs(true)) : null,
464
+ },
431
465
  account: {
432
466
  profileKey: profile?.key ?? null,
433
467
  name: profile?.name ?? null,
@@ -0,0 +1,66 @@
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
+ // lib/result-shapes.mjs — what each tool declares its result to be, and the result in that shape.
4
+ //
5
+ // THE DECLARATIONS LIVE IN ONE FILE, `mcp-server/result-shapes.json`, so a changed shape is a diff to that file and
6
+ // nothing else. This module reads it and does three things with it: it hands each tool's declared shape to the
7
+ // listing, it builds the structured result a call returns beside its text, and it builds the structured refusal.
8
+ //
9
+ // THE TEXT BLOCK IS NOT TOUCHED HERE. A host that reads only text keeps reading exactly what it read before. What is
10
+ // new (a write verb's `outcome`, a refusal's `reason`) is carried by the structured result alone.
11
+ //
12
+ // WHY THE SHAPES ARE PLAIN DRAFT-07, WITH NO `$schema`, `$id`, `description` OR `title`. A client compiles every
13
+ // declared shape when it lists the tools, and the SDK's client compiles with a draft-07 validator that caches by
14
+ // `$id`: a schema it cannot compile fails the listing, and loses the whole connector rather than one tool. A
15
+ // `description` would be a new sentence an assistant reads, and those are not this file's to add.
16
+ //
17
+ // A REFUSAL IS PART OF THE DECLARED SHAPE. The SDK's client validates a structured result whenever one is present,
18
+ // refusals included, so a verb that refuses with a structured reason declares the refusal as one of its forms.
19
+ import { readFileSync } from "node:fs";
20
+
21
+ const SHAPES = JSON.parse(readFileSync(new URL("../result-shapes.json", import.meta.url), "utf8"));
22
+
23
+ /**
24
+ * The shape `name` declares to a session, or null where it declares none. `client` is true for the two client kinds,
25
+ * whose answers are the scrubbed cut (server.mjs CLIENT_KINDS), so they are declared the scrubbed shape.
26
+ */
27
+ export function outputSchemaFor(name, { client = false } = {}) {
28
+ const entry = SHAPES[name];
29
+ if (!entry) return null;
30
+ return entry.all ?? entry[client ? "client" : "staff"] ?? null;
31
+ }
32
+
33
+ // THE SIX VERBS THAT CHANGE SOMETHING, and how each says whether it happened. Each reads a field the verb already
34
+ // returns, so the outcome is the verb's own fact under one name, never a second judgement of it.
35
+ const OUTCOMES = {
36
+ start_run: (r) => (r?.queued === true ? "queued" : null),
37
+ stop_run: (r) => (typeof r?.action === "string" ? r.action : null),
38
+ feed_context: (r) => (r?.ok === true ? "written" : null),
39
+ mark_sent: (r) => (r?.alreadySent === true ? "already-sent" : r?.alreadySent === false ? "marked-sent" : null),
40
+ ack_event: (r) => (r?.alreadyGone === true ? "already-gone" : r?.alreadyGone === false ? "acknowledged" : null),
41
+ what_if_run: (r) => (r?.queued === true ? "queued" : r?.ok === true ? "completed" : r?.ok === false ? "failed" : null),
42
+ };
43
+ export const WRITE_VERBS = Object.freeze(Object.keys(OUTCOMES));
44
+
45
+ // THE TOOLS THAT ANSWER FROM A RUN'S REPORT DOCUMENT, where it has one. Each answer names the version it was read from
46
+ // (`report-document/clearance-1`), or null where the call read the run's own files instead.
47
+ export const DOCUMENT_READERS = Object.freeze(["brief", "list_findings", "get_finding", "list_evidence", "list_searches", "get_search_coverage"]);
48
+
49
+ /**
50
+ * The structured result a call returns beside its text, or null for a tool that declares no shape. A verb's result
51
+ * gains its `outcome`; a report reader's gains `document`; a list goes out under `items`, because the protocol's
52
+ * structured result is an object. `documents` is what the call noted it read (lib/document-reads.mjs).
53
+ */
54
+ export function structuredResult(name, result, { documents = [] } = {}) {
55
+ if (!SHAPES[name]) return null;
56
+ if (OUTCOMES[name]) return { outcome: OUTCOMES[name](result), ...result };
57
+ if (DOCUMENT_READERS.includes(name) && result && typeof result === "object" && !Array.isArray(result))
58
+ return { ...result, document: documents[0] ?? null };
59
+ return Array.isArray(result) ? { items: result } : result;
60
+ }
61
+
62
+ /** A write verb's refusal as a structured result: the outcome and the refusal's own sentence. Null for any other tool. */
63
+ export function structuredRefusal(name, reason) {
64
+ if (!OUTCOMES[name] || !SHAPES[name]) return null;
65
+ return { outcome: "refused", reason: String(reason) };
66
+ }