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
@@ -0,0 +1,199 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ //
4
+ // RE-MINT THE CONNECTOR'S DECLARED ANSWER SHAPES — mcp-server/result-shapes.json, one entry per tool.
5
+ //
6
+ // node scripts/mint-result-shapes.mjs # report whether the file is current, change nothing
7
+ // node scripts/mint-result-shapes.mjs --check # ... and exit 1 if it is not
8
+ // node scripts/mint-result-shapes.mjs --apply # write it
9
+ //
10
+ // Each tool lists its shape as an `outputSchema` (mcp-server/lib/result-shapes.mjs), and the SDK's own client checks
11
+ // every answer against it, so a shape is a promise to every program built on the connector. This script is where the
12
+ // shapes are written; the JSON is what ships. Change a tool's answer, change its shape here, run --apply, and the diff
13
+ // of the JSON shows the change. mcp-server/test/a-read-tool-answers-in-the-shape-it-declares.test.mjs and its
14
+ // siblings call every tool and fail when an answer and its shape part.
15
+ //
16
+ // Every shape is self-contained (no $id, $schema, $ref, title or description), because the client compiles each one
17
+ // on its own and caches by $id. A field that means what a published report-data field means takes that field's own
18
+ // definition, copied whole from docs/report-data.
19
+ import { writeFileSync, readFileSync } from "node:fs";
20
+ import { join, dirname } from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+
23
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
24
+ const OUT = join(ROOT, "mcp-server", "result-shapes.json");
25
+ // The published report-data schemas, read from this checkout.
26
+ const DOCS = join(ROOT, "docs", "report-data");
27
+ const RD = { clearance: JSON.parse(readFileSync(join(DOCS, "clearance-1.schema.json"), "utf8")), knockout: JSON.parse(readFileSync(join(DOCS, "knockout-1.schema.json"), "utf8")) };
28
+ const S = { type: "string" }, B = { type: "boolean" }, SN = { type: ["string", "null"] };
29
+ const refused = { type: "object", required: ["outcome", "reason"], additionalProperties: false,
30
+ properties: { outcome: { const: "refused" }, reason: S } };
31
+ // The root is `type: "object"` with the forms beneath it: the protocol's listing refuses any other root, and a refused listing loses every tool.
32
+ const either = (...ok) => ({ type: "object", anyOf: [...ok, refused] });
33
+ const closed = (required, properties) => ({ type: "object", required, additionalProperties: false, properties });
34
+ const immediate = { type: ["object", "null"] };
35
+
36
+ const startRun = closed(["outcome", "ok", "id", "agent", "queue", "queued", "warnings", "queuePath", "queueWatched", "note"], {
37
+ outcome: { const: "queued" }, ok: { const: true }, id: S, agent: S, queue: S, queued: { const: true }, classify: {},
38
+ warnings: { type: "array", items: S }, queuePath: S, queueWatched: S, note: S });
39
+
40
+ const stopRun = [
41
+ closed(["outcome", "ok", "action", "id", "note"], { outcome: { const: "dequeued" }, ok: { const: true }, action: { const: "dequeued" }, id: S, note: S }),
42
+ closed(["outcome", "ok", "action", "id", "note"], { outcome: { const: "already-claimed" }, ok: { const: false }, action: { const: "already-claimed" }, id: S, note: S }),
43
+ closed(["outcome", "ok", "action", "runId", "state", "note"], { outcome: { const: "noop" }, ok: { const: false }, action: { const: "noop" }, runId: S, state: SN, note: S }),
44
+ closed(["outcome", "ok", "action", "runId", "state", "statusWritten", "note"], { outcome: { const: "cancelled" }, ok: { const: true }, action: { const: "cancelled" }, runId: S, state: { const: "cancelled" }, statusWritten: B, immediate, note: S }),
45
+ closed(["outcome", "ok", "action", "runId", "requestedAt", "note"], { outcome: { const: "already-stopping" }, ok: { const: true }, action: { const: "already-stopping" }, runId: S, requestedAt: SN, immediate, note: S }),
46
+ closed(["outcome", "ok", "action", "runId", "requestedAt", "note"], { outcome: { const: "cancel-requested" }, ok: { const: true }, action: { const: "cancel-requested" }, runId: S, requestedAt: SN, immediate, note: S }),
47
+ ];
48
+
49
+ const feedContext = closed(["outcome", "ok", "runId", "wrote", "note"], {
50
+ outcome: { const: "written" }, ok: { const: true }, runId: S, wrote: { type: "array", items: S, minItems: 1 }, note: S });
51
+
52
+ const markSent = closed(["outcome", "ok", "runId", "alreadySent", "note"], {
53
+ outcome: { enum: ["marked-sent", "already-sent"] }, ok: { const: true }, runId: S, alreadySent: B, note: S });
54
+
55
+ const ackEvent = closed(["outcome", "ok", "file", "alreadyGone"], {
56
+ outcome: { enum: ["acknowledged", "already-gone"] }, ok: { const: true }, file: S, alreadyGone: B });
57
+
58
+ // what_if_run: queued (account), completed or failed (ops). The ops results carry the experiment's own fields.
59
+ const queuedFields = { queued: { const: true }, runId: S, experimentId: S, stage: SN, axis: SN, queuedAt: S, next: S };
60
+ const whatIfQueuedClient = closed(["outcome", "queued", "runId", "experimentId", "queuedAt", "next"], { outcome: { const: "queued" }, ...queuedFields });
61
+ const whatIfRan = (outcome, ok) => ({ type: "object", required: ["outcome", "ok"], properties: { outcome: { const: outcome }, ok: { const: ok } } });
62
+
63
+ // ── THE READ TOOLS ─────────────────────────────────────────────────────────────────────────────────────────
64
+ // CLOSED where the connector builds the object as a literal, so its keys are the code's; OPEN, with only the
65
+ // identifying keys required, where the object carries what a run's files or log hold. A leaf is its type or null
66
+ // unless the code guarantees it. A list answer goes out under `items`.
67
+ const N = (ty) => ({ type: [ty, "null"] });
68
+ const A = { type: "array" }, O = { type: "object" }, NUM = { type: "number" }, ANY = {};
69
+ const open = (required, properties = {}) => ({ type: "object", required, properties });
70
+ const items = (row) => closed(["items"], { items: { type: "array", items: row } });
71
+ const channel = closed(["sent", "messageId", "sentAt"], { sent: B, messageId: N("string"), sentAt: N("string") });
72
+ const runRowProps = {
73
+ demo: S, runId: S, slug: SN, codename: SN, date: SN, agent: SN,
74
+ client: closed(["key", "name"], { key: SN, name: SN, known: { const: false }, note: S }),
75
+ project: { anyOf: [{ type: "null" }, closed(["key", "name"], { key: S, name: SN })] },
76
+ product: SN, state: S, location: S, tier: SN, caption: SN, url: SN, markName: SN, ref: ANY, classes: ANY, step: SN,
77
+ startedAt: SN, updatedAt: SN, deliveredAt: SN, failedStage: SN, reason: ANY,
78
+ resetsAt: SN, recoveryResumesAt: SN, parkedKind: SN, terminalKind: SN, sendPending: B, sent: B,
79
+ channels: closed(["email", "whatsapp"], { email: channel, whatsapp: channel }),
80
+ };
81
+ const RUN_ROW_REQUIRED = ["runId", "slug", "codename", "date", "agent", "client", "project", "product", "state", "location", "tier", "caption",
82
+ "url", "markName", "ref", "classes", "step", "startedAt", "updatedAt", "deliveredAt", "failedStage", "reason", "resetsAt",
83
+ "recoveryResumesAt", "parkedKind", "terminalKind", "sendPending", "sent", "channels"];
84
+ const staffRunRow = closed(RUN_ROW_REQUIRED, runRowProps);
85
+ // The client cut (server.mjs sanitizeRunForClient): no `url`, no `agent`; a failed run's reason is the firm's note.
86
+ const { url: _u, agent: _a, ...clientRowProps } = runRowProps;
87
+ const clientRunRow = closed(RUN_ROW_REQUIRED.filter((k) => !["url", "agent", "reason"].includes(k)), { ...clientRowProps, reason: S, reasonRedacted: { const: true } });
88
+
89
+ const reads = {
90
+ server_info: { all: closed(["name", "version", "commit", "sourceRepo", "sourceUrl", "license", "copyright"],
91
+ { name: S, version: SN, commit: SN, sourceRepo: S, sourceUrl: S, license: S, copyright: S }) },
92
+ list_runs: { staff: items(staffRunRow), client: items(clientRunRow) },
93
+ list_profiles: { all: closed(["_note", "clients", "genericFallback"], { _note: S, clients: { type: "array", items: O }, genericFallback: S, storeUnreadable: S, unreadable: A }) },
94
+ get_run: {
95
+ staff: closed(["run", "stages", "failover", "artifacts", "coverageSummary"], { run: staffRunRow, product: { const: "knockout" }, stages: A, failover: A, artifacts: A, coverageSummary: O }),
96
+ client: closed(["run", "stages", "failover", "artifacts", "coverageSummary"], { run: O, stages: A, failover: A, artifacts: A, coverageSummary: N("object") }),
97
+ },
98
+ read_artifact: { all: open(["name"], { _note: S, name: S, file: S, text: S, frontMatter: O, exists: B }) },
99
+ trace: { all: open(["runId", "target"], { runId: S, target: S }) },
100
+ get_telemetry: { all: closed(["runId", "stage", "runEvents", "attempts", "providerUsage"], { runId: S, stage: SN, runEvents: A, attempts: A, providerUsage: N("object") }) },
101
+ get_provider_usage: { all: closed(["runId", "prefix", "live", "cached", "drift", "driftKeys", "comparedCounters", "ledgerStale", "lowConfidence", "note"],
102
+ { runId: S, prefix: S, live: O, cached: N("object"), drift: N("boolean"), driftKeys: A, comparedCounters: A, ledgerStale: B, lowConfidence: B, note: S }) },
103
+ get_coverage: { all: closed(["coverageLedgerPresent", "registerAxes", "findings", "negativeResults", "artifacts", "complete", "note"],
104
+ { coverageLedgerPresent: B, registerAxes: A, findings: NUM, negativeResults: NUM, artifacts: A, complete: B, note: S }) },
105
+ search: { all: closed(["runId", "query", "mode", "hits", "truncated"], { runId: S, query: S, mode: S, hits: A, truncated: B }) },
106
+ decision_timeline: {
107
+ staff: closed(["runId", "state", "tier", "verdictHistory", "timeline", "riskLadderAvailable", "note"],
108
+ { runId: S, state: SN, tier: SN, verdictHistory: A, timeline: A, riskLadderAvailable: B, note: S }),
109
+ client: open(["runId", "timeline"], { runId: S, state: SN, tier: SN, timeline: A, verdictHistory: A }),
110
+ },
111
+ run_changes: { all: closed(["runId", "state", "tier", "since", "cursor", "count", "changes", "note"],
112
+ { runId: S, state: SN, tier: SN, since: SN, cursor: ANY, count: NUM, changes: A, note: S }) },
113
+ diff_artifact: { all: { type: "object", anyOf: [
114
+ closed(["runId", "name", "stage", "axis", "a", "b", "identical", "diff", "snapshotsAvailable", "note"],
115
+ { runId: S, name: S, stage: S, axis: SN, a: ANY, b: ANY, identical: { type: "null" }, diff: { type: "null" }, snapshotsAvailable: ANY, note: S }),
116
+ closed(["runId", "name", "stage", "axis", "a", "b", "identical", "diff", "snapshotsAvailable"],
117
+ { runId: S, name: S, stage: S, axis: SN, a: ANY, b: ANY, identical: B, diff: S, telemetryDelta: ANY, snapshotsAvailable: ANY }),
118
+ ] } },
119
+ search_runs: { all: closed(["query", "mode", "scope", "runsScanned", "hits", "truncated"], { query: S, mode: S, scope: S, runsScanned: NUM, hits: A, truncated: B }) },
120
+ what_if_plan: { all: open(["runnable"], { runnable: B }) },
121
+ what_if_result: { all: open(["runId"], { runId: S }) },
122
+ list_outbox_events: { all: closed(["ok", "count", "events"], { ok: { const: true }, count: NUM, events: { type: "array", items: O } }) },
123
+ get_delivery_packet: { all: closed(["ok", "runId", "state", "sendPending", "sent", "delivery", "failure"],
124
+ { ok: { const: true }, runId: S, state: SN, sendPending: N("boolean"), sent: B, delivery: N("object"), failure: N("object") }) },
125
+ };
126
+
127
+ // ── THE REPORT READERS: a field that means what report-data's published field means takes report-data's own
128
+ // definition, copied whole so each shape stands alone for an offline client; the test holds each copy equal to the
129
+ // published one. Everything else is declared from the connector's own projection.
130
+ const rdKo = (field) => RD.knockout.$defs.webFinding.properties[field];
131
+ const findingItem = { type: "object", properties: {
132
+ name: rdKo("name"), owner: rdKo("owner"), band: rdKo("band"), type: rdKo("type"), net: rdKo("net"), basis: rdKo("basis"), evidence: rdKo("evidence"),
133
+ } };
134
+ const DOC = N("string"); // the report document version the answer was read from, or null where it read the run's files
135
+ const reports = {
136
+ brief: { all: closed(["_note", "runId", "markName", "product", "overall", "tier", "caption", "state", "date", "source", "brief", "document"],
137
+ { _note: S, runId: S, markName: SN, product: SN, overall: SN, tier: SN, caption: RD.clearance.properties.caption, state: SN, date: SN, source: S, brief: S, document: DOC }) },
138
+ list_findings: { all: open(["_note", "kind", "items", "document"],
139
+ { _note: S, kind: S, items: { type: "array", items: findingItem }, source: S, group: S, available: B, product: SN, note: S, document: DOC }) },
140
+ get_finding: { all: open(["id", "document"], { id: S, document: DOC, ...findingItem.properties }) },
141
+ list_evidence: { all: closed(["source", "records", "document"], { source: S, records: { type: "array", items: O }, document: DOC }) },
142
+ list_searches: { all: open(["count", "searches", "document"], { count: NUM, searches: { type: "array", items: O }, totalCount: NUM, source: S, document: DOC }) },
143
+ get_search_coverage: { all: open(["areas", "document"], { areas: { type: "array", items: O }, note: S, source: S, document: DOC }) },
144
+ };
145
+
146
+ // ── THE TWO PRE-ORDER TOOLS: one answer for every kind of session, each built in one place (lib/plan.mjs planRun,
147
+ // lib/options.mjs describeOptions). The top level is closed; a block that describes the order names its keys and
148
+ // stays open, and How soon (the order option this release adds) is closed throughout.
149
+ const strings = { type: "array", items: S };
150
+ const howSoonOption = { type: ["object", "null"], required: ["turnaround", "turnaroundLowHours", "turnaroundHighHours", "searches", "withinAllowance"],
151
+ additionalProperties: false, properties: { turnaround: S, turnaroundLowHours: NUM, turnaroundHighHours: NUM, searches: NUM, withinAllowance: N("boolean") } };
152
+ const planRun = closed(["ok", "wouldRun", "_note", "blockers", "warnings", "caveat", "search", "subject", "scope", "effort", "howSoon", "account"], {
153
+ ok: B, wouldRun: B, _note: S, blockers: strings, warnings: strings, caveat: S,
154
+ search: open(["name", "product", "pipeline", "components", "savedSearch", "turnaround", "maxNames", "caseLaw", "nativeLanguage", "chosenBy", "registerReach"],
155
+ { name: SN, product: SN, pipeline: SN, components: N("object"), savedSearch: N("object"), turnaround: SN, maxNames: N("number"), caseLaw: B,
156
+ nativeLanguage: SN, chosenBy: S, registerReach: N("object") }),
157
+ subject: open(["marks", "markCount", "classes", "classesFrom", "goods"], { marks: strings, markCount: NUM, classes: A, classesFrom: S, goods: SN }),
158
+ scope: open(["jurisdictions", "jurisdictionsFrom", "bindingLayers", "platforms", "platformsAdded", "platformsFrom", "gridCellsPerVariant"],
159
+ { jurisdictions: A, jurisdictionsFrom: S, bindingLayers: A, platforms: A, platformsAdded: A, platformsFrom: S, gridCellsPerVariant: N("number") }),
160
+ effort: N("object"),
161
+ howSoon: closed(["chosen", "urgentAvailable", "standard", "urgent"],
162
+ { chosen: { enum: ["standard", "urgent"] }, urgentAvailable: B, urgentNote: S, standard: howSoonOption, urgent: howSoonOption }),
163
+ account: open(["profileKey", "name", "projectKey", "framework", "caps", "usage", "usageComplete", "dailyRunsEffective", "remainingToday", "allowanceApplies", "origins"],
164
+ { profileKey: SN, name: SN, projectKey: SN, framework: S, caps: N("object"), usage: N("object"), usageComplete: N("boolean"), dailyRunsEffective: N("number"),
165
+ remainingToday: N("number"), allowanceApplies: N("boolean"), origins: N("object") }),
166
+ });
167
+ const describeOptions = closed(["_note", "products", "scopeRules", "urgent", "account"], {
168
+ _note: S, products: { type: "array", items: open(["key", "name", "available"], { key: S, name: S, available: B }) },
169
+ registerTerritories: N("array"), scopeRules: O,
170
+ urgent: closed(["available"], { available: B, note: S }),
171
+ account: { type: ["object", "null"], required: ["profileKey"], properties: { profileKey: S, name: SN, projects: A, defaults: O, savedSearches: A, savedSearchesNote: SN, allowance: N("object") } },
172
+ accountsGranted: { type: "array", items: closed(["profileKey", "name"], { profileKey: S, name: SN }) },
173
+ accountNote: S,
174
+ });
175
+ const preOrder = { plan_run: { all: planRun }, describe_options: { all: describeOptions } };
176
+
177
+ const shapes = {
178
+ start_run: { all: either(startRun) },
179
+ stop_run: { all: either(...stopRun) },
180
+ feed_context: { all: either(feedContext) },
181
+ mark_sent: { all: either(markSent) },
182
+ ack_event: { all: either(ackEvent) },
183
+ what_if_run: { staff: either(whatIfRan("completed", true), whatIfRan("failed", false)), client: either(whatIfQueuedClient) },
184
+ ...reads,
185
+ ...reports,
186
+ ...preOrder,
187
+ };
188
+
189
+ const minted = JSON.stringify(shapes, null, 2) + "\n";
190
+ let onDisk = null;
191
+ try { onDisk = readFileSync(OUT, "utf8"); } catch { /* absent: stale */ }
192
+ const current = onDisk === minted;
193
+ if (process.argv.includes("--apply")) {
194
+ if (!current) writeFileSync(OUT, minted);
195
+ console.log(`mint-result-shapes: ${current ? "already current" : "wrote"} ${Object.keys(shapes).length} tools`);
196
+ process.exit(0);
197
+ }
198
+ console.log(`mint-result-shapes: ${Object.keys(shapes).length} tools; mcp-server/result-shapes.json is ${current ? "current" : "STALE: run node scripts/mint-result-shapes.mjs --apply"}`);
199
+ process.exit(process.argv.includes("--check") && !current ? 1 : 0);
@@ -0,0 +1,227 @@
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
+ //
5
+ // readme-pictures.mjs — retake the README's three portal pictures from this checkout's own demo.
6
+ //
7
+ // npm run build:ui && node scripts/readme-pictures.mjs [--out <dir>]
8
+ //
9
+ // Writes, light theme, 1,332 × 778 CSS pixels at device scale 1.5 (1,998 × 1,167, the size and type scale of the
10
+ // pictures it replaces):
11
+ // portal-new-clearance.png New clearance as it opens
12
+ // portal-clearance-report.jpg the demo's Global preliminary search report, at its top
13
+ // portal-conflict-landscape.jpg the same report's conflict landscape
14
+ // into docs/assets/ unless --out names another folder, and prints the provenance line for
15
+ // docs/assets/README.md.
16
+ //
17
+ // WHEN TO RUN IT: a release that changes New clearance, the report page or the conflict landscape, and
18
+ // every regeneration of demo/. docs/RELEASES.md names it as a step of the checklist.
19
+ //
20
+ // ONLY THE PUBLIC DEMO IS ON SCREEN. The demo is SPAWNED (bin/example.mjs, the replay `npx clearotron demo`
21
+ // serves) in a throwaway home with a minimal environment, so no setting of this machine, no pool and no
22
+ // profile store reaches it, and bin/example.mjs's own containment refusal still applies. The sign-in is a
23
+ // passphrase minted for that home alone; it is never printed and leaves with the home.
24
+ //
25
+ // NETWORK IS ALLOWED, as in report-screenshot.mjs: these are pictures of what a reader sees, so the brand
26
+ // webfonts load. The render checks block it on purpose; the two intents differ.
27
+ import { spawn } from "node:child_process";
28
+ import { randomBytes } from "node:crypto";
29
+ import { mkdtempSync, rmSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
30
+ import { createServer } from "node:net";
31
+ import { tmpdir } from "node:os";
32
+ import { join, dirname, resolve } from "node:path";
33
+ import { fileURLToPath } from "node:url";
34
+ import { establishCredential } from "../driver/portal-local-auth.mjs";
35
+ import { browserRun } from "../shared/browser-temp-root.mjs";
36
+ import { reapOnExit } from "../shared/reap-on-exit.mjs"; // a detached group dies with this script
37
+
38
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
39
+ const argv = process.argv.slice(2);
40
+ const OUT = resolve(argv.includes("--out") ? argv[argv.indexOf("--out") + 1] : join(ROOT, "docs", "assets"));
41
+ const WIDTH = 1332, HEIGHT = 778, SCALE = 1.5;
42
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
43
+ const die = (msg) => { console.error(`readme-pictures: ${msg}`); cleanup(); process.exit(1); };
44
+
45
+ const home = mkdtempSync(join(tmpdir(), "readme-pictures-"));
46
+ let demo = null, chrome = null;
47
+ function cleanup() {
48
+ for (const child of [chrome, demo]) {
49
+ if (!child?.pid) continue;
50
+ try { process.kill(-child.pid, "SIGTERM"); } catch { try { child.kill("SIGTERM"); } catch { /* already gone */ } }
51
+ }
52
+ try { rmSync(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); } catch { /* a stray temp folder is not a result */ }
53
+ }
54
+ process.on("SIGINT", () => { cleanup(); process.exit(130); });
55
+
56
+ // ── the demo, in a home of its own ────────────────────────────────────────────────────────────────────
57
+ const port = await new Promise((r) => { const s = createServer(); s.listen(0, "127.0.0.1", () => { const p = s.address().port; s.close(() => r(p)); }); });
58
+ const passphrase = randomBytes(18).toString("base64url");
59
+ // THE DEMO SIGNS IN WITH THE CREDENTIAL IN ITS OWN BASE (bin/start.mjs sets PORTAL_LOCAL_CREDENTIAL to it). It
60
+ // replaces that credential on every start and prints the passphrase only to a terminal, so once it is up this
61
+ // script resets it the way `clearotron passphrase --reset` does, remove then mint, and the portal reads the
62
+ // file on each sign-in. The demo's own address is kept (bin/start.mjs signs a demo in as demo@localhost).
63
+ const credential = join(home, "trademark-demo", "portal-local-credential.json");
64
+ // A MINIMAL ENVIRONMENT, named field by field: nothing this machine's own install reads is inherited.
65
+ const demoEnv = { PATH: process.env.PATH ?? "", HOME: home, TMPDIR: home, LANG: "en_US.UTF-8" };
66
+ demo = spawn(process.execPath, [join(ROOT, "bin", "example.mjs"), "--no-open", "--port", String(port)],
67
+ { cwd: ROOT, env: demoEnv, stdio: ["ignore", "pipe", "pipe"], detached: true });
68
+ reapOnExit(demo);
69
+ let demoLog = "";
70
+ demo.stdout.setEncoding("utf8"); demo.stderr.setEncoding("utf8");
71
+ demo.stdout.on("data", (c) => { demoLog += c; }); demo.stderr.on("data", (c) => { demoLog += c; });
72
+ const origin = `http://127.0.0.1:${port}`;
73
+ const up = await (async () => {
74
+ for (const t0 = Date.now(); Date.now() - t0 < 180000; await sleep(500)) {
75
+ if (demo.exitCode != null) return false;
76
+ try { const r = await fetch(`${origin}/portal/login`, { headers: { accept: "text/html" } }); if (r.status === 200) return true; } catch { /* not yet */ }
77
+ }
78
+ return false;
79
+ })();
80
+ if (!up) die(`the demo did not serve its sign-in page on ${origin}. Its output:\n${demoLog.replace(passphrase, "[passphrase]").slice(-1500)}`);
81
+
82
+ rmSync(credential, { force: true });
83
+ establishCredential({ path: credential, email: "demo@localhost", passphrase });
84
+ const login = await fetch(`${origin}/portal/login`, { method: "POST", redirect: "manual",
85
+ headers: { "content-type": "application/x-www-form-urlencoded", origin, accept: "text/html" },
86
+ body: new URLSearchParams({ passphrase }).toString() });
87
+ const cookieLine = (login.headers.getSetCookie?.() ?? []).find((c) => /=/.test(c));
88
+ if (!cookieLine) die(`signing in to the demo returned ${login.status} and no session cookie: ${((await login.text()).match(/(No passphrase is set[^<]*|That passphrase[^<]*|could not be read[^<]*|not available[^<]*)/) ?? ["(no reason on the page)"])[0]}\n${demoLog.replaceAll(passphrase, "[passphrase]").slice(-1200)}`);
89
+ const [cookieName, ...rest] = cookieLine.split(";")[0].split("=");
90
+ const cookieValue = rest.join("=");
91
+
92
+ // The demo's Global preliminary search, the report the README has always shown.
93
+ const runs = await (await fetch(`${origin}/portal/api/runs?scope=mine`, { headers: { cookie: `${cookieName}=${cookieValue}`, accept: "application/json" } })).json().catch(() => null);
94
+ const all = Array.isArray(runs?.runs) ? runs.runs : [];
95
+ const report = all.find((r) => /global-preliminary/.test(String(r.product ?? r.productKey ?? r.level ?? "")) || /Global preliminary/.test(String(r.productName ?? "")));
96
+ if (!report?.runId) die(`the demo lists no Global preliminary search (it lists ${all.length} runs${all[0] ? `; the first carries ${Object.keys(all[0]).join(", ")}` : ""})`);
97
+
98
+ // ── the browser ──────────────────────────────────────────────────────────────────────────────────────
99
+ const { profile, env: chromeEnv } = browserRun("readme-pictures-");
100
+ chrome = spawn("google-chrome", ["--headless=new", "--disable-gpu", "--no-sandbox", "--hide-scrollbars",
101
+ `--user-data-dir=${profile}`, `--window-size=${WIDTH},${HEIGHT}`, "--remote-debugging-port=0", "about:blank"], {
102
+ stdio: ["ignore", "pipe", "pipe"], env: chromeEnv, detached: true });
103
+ reapOnExit(chrome);
104
+ let chromeErr = "";
105
+ const wsUrl = await new Promise((res, rej) => {
106
+ const t = setTimeout(() => rej(new Error(`chrome reported no devtools endpoint in 60s:\n${chromeErr || "(nothing)"}`)), 60000);
107
+ chrome.stderr.setEncoding("utf8");
108
+ chrome.stderr.on("data", (c) => { chromeErr += c; const m = chromeErr.match(/ws:\/\/[^\s]+/); if (m) { clearTimeout(t); res(m[0]); } });
109
+ }).catch((e) => die(e.message));
110
+ const ws = new WebSocket(wsUrl);
111
+ let id = 0; const pending = new Map();
112
+ // The report's frame attaches as a target of its own (see inFrame); the newest one is the document on screen.
113
+ let frameSession = null;
114
+ ws.addEventListener("message", (e) => { const m = JSON.parse(e.data);
115
+ if (m.method === "Target.attachedToTarget" && m.params?.targetInfo?.type === "iframe") frameSession = m.params.sessionId;
116
+ if (m.id && pending.has(m.id)) { pending.get(m.id)(m); pending.delete(m.id); } });
117
+ await new Promise((r) => ws.addEventListener("open", r));
118
+ const send = (method, params = {}, sessionId) => new Promise((r) => { const n = ++id; pending.set(n, r);
119
+ ws.send(JSON.stringify({ id: n, method, params, ...(sessionId ? { sessionId } : {}) })); });
120
+ const target = (await send("Target.getTargets")).result.targetInfos.find((t) => t.type === "page");
121
+ if (!target) die("chrome opened no page target");
122
+ const sessionId = (await send("Target.attachToTarget", { targetId: target.targetId, flatten: true })).result.sessionId;
123
+ const cmd = (method, params = {}) => send(method, params, sessionId);
124
+ const evaluate = async (expression) => (await cmd("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true }))?.result?.result?.value;
125
+ await cmd("Page.enable");
126
+ await cmd("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: false, flatten: true });
127
+ await cmd("Network.enable");
128
+ await cmd("Network.setCookie", { name: cookieName, value: cookieValue, url: origin, httpOnly: true });
129
+ await cmd("Emulation.setEmulatedMedia", { features: [{ name: "prefers-color-scheme", value: "light" }] });
130
+ await cmd("Emulation.setDeviceMetricsOverride", { width: WIDTH, height: HEIGHT, deviceScaleFactor: SCALE, mobile: false });
131
+
132
+ // THE REPORT IS A SANDBOXED FRAME with a null origin, so the page cannot read into it, and Chrome runs it as a
133
+ // target of its own. DevTools attaches to that target and reads its document without changing it.
134
+ const inFrame = async (expression) => frameSession
135
+ ? (await send("Runtime.evaluate", { expression, returnByValue: true }, frameSession))?.result?.result?.value ?? null
136
+ : null;
137
+ const open = async (path, ready, what, prepare = null) => {
138
+ await cmd("Page.navigate", { url: `${origin}${path}` });
139
+ for (const t0 = Date.now(); Date.now() - t0 < 30000; await sleep(300)) {
140
+ if (prepare) await evaluate(prepare);
141
+ if (typeof ready === "function" ? await ready() : await evaluate(ready)) {
142
+ await evaluate("document.documentElement.removeAttribute('data-theme'); document.fonts.ready.then(() => true)");
143
+ await sleep(1200); // layout settles after the faces swap in
144
+ return;
145
+ }
146
+ }
147
+ die(`${what} never appeared at ${path}; the page reads: ${String(await evaluate("location.pathname + ' | ' + (document.body ? document.body.innerText : '')")).replace(/\s+/g, " ").slice(0, 300)}`);
148
+ };
149
+ const shoot = async (file) => {
150
+ const jpg = file.endsWith(".jpg");
151
+ const shot = await cmd("Page.captureScreenshot", { format: jpg ? "jpeg" : "png", ...(jpg ? { quality: 88 } : {}) });
152
+ if (!shot?.result?.data) die(`chrome returned no image for ${file}`);
153
+ writeFileSync(join(OUT, file), Buffer.from(shot.result.data, "base64"));
154
+ };
155
+ if (!existsSync(OUT)) mkdirSync(OUT, { recursive: true });
156
+
157
+ // THE DEMO'S COMPANY, chosen in the sidebar as a reader chooses it: a person who sees every company is
158
+ // otherwise asked to pick one first, and the shell holds the choice in memory only.
159
+ const pickDemoCompany = `(() => {
160
+ const s = document.querySelector('select[aria-label="Company"]');
161
+ if (!s || s.value === 'demo-brand-owner' || ![...s.options].some((o) => o.value === 'demo-brand-owner')) return false;
162
+ Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value').set.call(s, 'demo-brand-owner');
163
+ s.dispatchEvent(new Event('change', { bubbles: true }));
164
+ return true;
165
+ })()`;
166
+ await open("/portal/new", "Boolean(document.querySelector('textarea[aria-label=\"Names to clear\"]'))", "New clearance", pickDemoCompany);
167
+ // WHAT THE README'S CAPTION NAMES: the company's classes and marketplaces, and the four searches. The company line
168
+ // states the first two; the four searches sit behind "All four searches", opened as a reader opens it. The line
169
+ // is brought just under the top bar.
170
+ const folds = await evaluate(`(async () => {
171
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
172
+ const b = [...document.querySelectorAll('button')].find((x) => /^All four searches$/.test((x.innerText || '').trim()));
173
+ if (b) b.click();
174
+ await sleep(400);
175
+ const line = document.querySelector('.nc-company-line');
176
+ const bar = document.querySelector('.topbar, header');
177
+ const below = bar ? Math.max(0, bar.getBoundingClientRect().bottom) : 0;
178
+ if (line) window.scrollBy(0, line.getBoundingClientRect().top - below - 20);
179
+ return { four: Boolean(b), line: Boolean(line), searches: document.querySelectorAll('.pick-row').length };
180
+ })()`);
181
+ if (!folds?.four || !folds?.line || folds.searches !== 4) die(`New clearance did not show its company line and four searches: ${JSON.stringify(folds)}`);
182
+ await sleep(600);
183
+ await shoot("portal-new-clearance.png");
184
+
185
+ const reportPath = `/portal/result/${encodeURIComponent(report.runId)}`;
186
+ // Ready when the frame holds THIS run's report with its sections drawn, and has posted its height to the page.
187
+ const frameReady = async () => (await inFrame(`location.pathname.includes(${JSON.stringify(`/${encodeURIComponent(report.runId)}`)}) && document.querySelectorAll('h2').length > 3`)) === true
188
+ && (await evaluate("(document.querySelector('iframe')?.getBoundingClientRect().height ?? 0) > 1000")) === true;
189
+ await open(reportPath, frameReady, "the demo report");
190
+ // WHAT THE CAPTION NAMES: the verdict, the risk band and the four answers, which the report's summary holds
191
+ // (`.heroGrid` inside `#summary`). Brought just under the header that stays on screen.
192
+ const placeUnderHeader = async (frameY, what) => {
193
+ if (typeof frameY !== "number") die(`the demo report has no ${what}`);
194
+ for (let pass = 0; pass < 3; pass++) {
195
+ await evaluate(`(() => {
196
+ const f = document.querySelector('iframe').getBoundingClientRect();
197
+ const head = document.querySelector('.report-head');
198
+ const below = head ? Math.max(0, head.getBoundingClientRect().bottom) : 0;
199
+ window.scrollBy(0, f.top + ${frameY} - below - 24);
200
+ return true;
201
+ })()`);
202
+ await sleep(500);
203
+ }
204
+ };
205
+ await placeUnderHeader(await inFrame(`(() => { const g = document.querySelector('#summary .heroGrid'); return g ? g.getBoundingClientRect().top + window.scrollY : null; })()`),
206
+ "verdict and risk band (#summary .heroGrid)");
207
+ await shoot("portal-clearance-report.jpg");
208
+
209
+ // The conflict landscape, brought to the top of the view the way a reader's section link brings it.
210
+ const headingTop = await inFrame(`(() => {
211
+ const h = [...document.querySelectorAll('h2, h3')].find((e) => /conflict landscape/i.test(e.textContent || ''));
212
+ return h ? h.getBoundingClientRect().top + window.scrollY : null;
213
+ })()`);
214
+ // The frame is as tall as the report, so the page scrolls; the header that stays on screen changes height once
215
+ // the page has scrolled, so the placement is measured again after each move.
216
+ await placeUnderHeader(headingTop, "conflict landscape heading");
217
+ await sleep(800);
218
+ await shoot("portal-conflict-landscape.jpg");
219
+
220
+ let commit = "";
221
+ try { const { execFileSync } = await import("node:child_process"); commit = execFileSync("git", ["rev-parse", "--short", "HEAD"], { cwd: ROOT, encoding: "utf8" }).trim(); } catch { /* not a checkout */ }
222
+ const { version } = JSON.parse(await (await import("node:fs/promises")).readFile(join(ROOT, "package.json"), "utf8"));
223
+ cleanup();
224
+ console.log(`readme-pictures: wrote portal-new-clearance.png, portal-clearance-report.jpg and portal-conflict-landscape.jpg to ${OUT}`);
225
+ console.log(` from the demo's run ${report.runId}, at ${WIDTH}×${HEIGHT} CSS px, device scale ${SCALE}, light theme`);
226
+ console.log(` provenance: Clearotron ${version}${commit ? ` (${commit})` : ""}, \`node scripts/readme-pictures.mjs\``);
227
+ process.exit(0);
@@ -252,7 +252,10 @@ const SHELL = `<!doctype html><html><head><meta charset="utf-8"><title>render-ch
252
252
  <body><div class="app"><aside class="sidebar"></aside><div class="main">
253
253
  <header class="topbar"><h1>Clearances</h1></header>
254
254
  <div class="screen report">
255
- <div class="report-head" id="hdr"><div style="display:flex;align-items:center;gap:12px">
255
+ <!-- THE PINNED STATE. On a desktop width the report header pins as one row once the reader is past it
256
+ (board ReportHeader, approved 2026-11-25), which the portal's script marks with \`compact\`; this
257
+ shell has no script, so it draws that state from the start. -->
258
+ <div class="report-head compact" id="hdr"><div style="display:flex;align-items:center;gap:12px">
256
259
  <h1 style="font-size:19px;margin:0">Mark</h1><span style="flex:1"></span>
257
260
  <button class="nav-item" id="exp" style="width:auto">Export</button></div></div>
258
261
  <div data-anon="mark" style="margin-top:12px">