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,184 @@
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
+ // order-receipt.mjs — what became of an accepted order, looked up by the reference its door returned, for the account
4
+ // that placed it. Internal: nothing here sends a notice, and no door shows it yet.
5
+ //
6
+ // WHY A LOOKUP AND NOT A NEW RECORD. Everything a receipt needs is already on disk, in the queue directory, under the
7
+ // order's own reference (`<id>`, the queue file's name, which every door returns):
8
+ //
9
+ // <id>.json accepted, waiting for a worker
10
+ // <id>.processing.claimed-<tok> a worker took it and stopped mid-claim; it is reclaimed under the same reference
11
+ // <id>.processing claimed, its pre-start checks under way
12
+ // <id>.processing.meta written at dispatch, AFTER those checks passed: the run's identity is minted
13
+ // <id>.postponed (+ .meta) parked, by a provider cap or our own recovery backoff; it resumes by itself
14
+ // <id>.failed + .failed.reason refused at the claim, before any run existed (failAtIntake)
15
+ // <id>.duplicate + .reason refused as the same matter as an earlier order (parkDuplicate)
16
+ // <id>.{done,failed,cancelled}.result the run's own outcome, with its run directory
17
+ //
18
+ // Nothing in the driver or the scripts deletes a terminal marker or its `.reason` / `.result`, so they last as long
19
+ // as the queue directory does. Reading them is therefore the durable receipt; a second store would be a second answer
20
+ // to the same question.
21
+ //
22
+ // THREE ANSWERS, NOT TWO, as `accountUsage` keeps them: `found`, `not-found`, and `could-not-look` (a queue directory
23
+ // that would not open is not "no such order"). An order that belongs to another account answers `not-found`, exactly
24
+ // as one that does not exist: neither its existence nor its reason is anybody else's to learn.
25
+ import { readdirSync, readFileSync, existsSync, statSync } from "node:fs";
26
+ import { join, basename, dirname } from "node:path";
27
+ import { deriveSlug } from "./phase0.mjs";
28
+ import { stopReason } from "../shared/stop-reason.mjs"; // a cancelled order says it was stopped, never a blank reason
29
+
30
+ /**
31
+ * The reference an order is known by: its queue file's name. The connector's start_run admits exactly these ids, so a
32
+ * reference outside this set names no order, and is refused before it reaches a path. Mirrors start_run's validator.
33
+ */
34
+ export const ORDER_REF_MAX = 128;
35
+ export const ORDER_REF_RE = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._@-]{0,${ORDER_REF_MAX - 1}}$`);
36
+
37
+ /** The states an order can be in, in the words the receipt uses. */
38
+ export const RECEIPT_STATES = Object.freeze({
39
+ waiting: "accepted and waiting for a worker",
40
+ checking: "taken by a worker; its checks before starting are under way",
41
+ running: "passed its checks; its run has started",
42
+ resumable: "parked, and will resume by itself",
43
+ refused: "refused before a run started",
44
+ failed: "its run stopped before delivering",
45
+ delivered: "its run finished",
46
+ cancelled: "stopped on request",
47
+ });
48
+ const TERMINAL = new Set(["refused", "failed", "delivered", "cancelled"]);
49
+
50
+ /**
51
+ * May this caller see this order? The scope `checkRunCaps` counts a lane by: the job's account, and for Generic the
52
+ * organisation it was filed under. A job that names no account (an email order before its claim) is visible only to
53
+ * a caller who sees everything. PURE.
54
+ */
55
+ export function orderInScope(job, scope) {
56
+ if (scope?.everything === true) return true;
57
+ const account = scope?.account ?? null;
58
+ if (!account || !job || (job.profileKey ?? null) !== account) return false;
59
+ return account !== "generic" || (job.tenant ?? null) === (scope?.organisation ?? null);
60
+ }
61
+
62
+ const readJsonSafe = (p) => { try { return JSON.parse(readFileSync(p, "utf8")); } catch { return null; } };
63
+ const readTextSafe = (p) => { try { return readFileSync(p, "utf8"); } catch { return null; } };
64
+
65
+ /** A refusal's reason as the runner wrote it, without its own bookkeeping line ("notify: …"). */
66
+ function reasonFrom(text) {
67
+ if (text == null) return null;
68
+ const lines = String(text).split("\n").map((l) => l.trim()).filter((l) => l && !/^notify:/i.test(l));
69
+ return lines.length ? lines.join("\n") : null;
70
+ }
71
+
72
+ /** The canonical run id, `<slug>-<date>-<codename>`, from a run directory (`…/<slug>/<date>-<codename>`). */
73
+ const runIdFromDir = (runDir) => (runDir ? `${basename(dirname(runDir))}-${basename(runDir)}` : null);
74
+
75
+ /** The run id a dispatch minted, from the job and its `.meta`, before any `.result` exists. */
76
+ function runIdFromMeta(job, meta) {
77
+ if (!meta?.codename || !meta?.dateISO) return null;
78
+ try { return `${deriveSlug(job)}-${meta.dateISO}-${meta.codename}`; } catch { return null; }
79
+ }
80
+
81
+ /** The marker files for one reference in one queue directory, by the name they carry. */
82
+ function markersFor(qdir, names, ref) {
83
+ const own = names.filter((n) => n === `${ref}.json` || n.startsWith(`${ref}.`));
84
+ const has = (s) => own.includes(`${ref}.${s}`);
85
+ const claimed = own.find((n) => n.startsWith(`${ref}.processing.claimed-`) && !/\.(pid|meta|skips|tmp)$/.test(n)) ?? null;
86
+ return { own, has, claimed };
87
+ }
88
+
89
+ /**
90
+ * Read one order's receipt out of one queue directory, or null when the directory holds nothing for this reference.
91
+ * The job is read from whichever marker carries it; `.result` decides before `.meta`, so a refusal after dispatch reads
92
+ * as a refusal, and a run directory holding a park sentinel reads as resumable whatever the queue marker says.
93
+ */
94
+ export function receiptIn(qdir, ref, names) {
95
+ const { has, claimed } = markersFor(qdir, names, ref);
96
+ const at = (s) => join(qdir, `${ref}.${s}`);
97
+ const terminal = ["done", "failed", "cancelled", "duplicate"].find((s) => has(s)) ?? null;
98
+ const live = has("postponed") ? "postponed" : has("processing") ? "processing" : claimed ? "claimed" : has("json") ? "json" : null;
99
+ if (!terminal && !live) return null;
100
+ const markerPath = terminal ? at(terminal) : live === "claimed" ? join(qdir, claimed) : at(live);
101
+ const job = readJsonSafe(markerPath);
102
+ let updatedAt = null;
103
+ try { updatedAt = statSync(markerPath).mtime.toISOString(); } catch { /* the marker moved under us; the next read sees it */ }
104
+ const base = { reference: ref, job, updatedAt };
105
+
106
+ if (terminal) {
107
+ const result = readJsonSafe(at(`${terminal}.result`));
108
+ const reason = reasonFrom(readTextSafe(at(`${terminal}.reason`)));
109
+ // A CANCELLED ORDER SAYS IT WAS STOPPED: the stop's own recorded reason, or, where none was written (an order taken
110
+ // off the queue before it started), the shared stop sentence with nothing invented (shared/stop-reason.mjs).
111
+ if (terminal === "cancelled") return { ...base, state: "cancelled", reason: result?.reason ?? stopReason(), runId: runIdFromDir(result?.runDir) };
112
+ // A DUPLICATE'S RECORDED REASON NAMES THE EARLIER ORDER it matched (its message id), and that order may be another
113
+ // account's: the matter signature does not include the account. Only its first line, which says what happened,
114
+ // is the receipt's. Pointing to the earlier order is for a later increment, which can ask whether this caller may see it.
115
+ if (terminal === "duplicate") return { ...base, state: "refused", reason: reason ? reason.split("\n")[0] : null, runId: null, kind: "duplicate" };
116
+ if (terminal === "done") return { ...base, state: "delivered", reason: null, runId: runIdFromDir(result?.runDir) };
117
+ // `.failed`: refused at the claim (a reason, no result), refused at dispatch (a pre-run result), or a run that
118
+ // stopped. A run directory still holding a park sentinel is a run that will come back, not a failure.
119
+ const runDir = result?.runDir ?? null;
120
+ if (runDir && (existsSync(join(runDir, ".postponed")) || existsSync(join(runDir, ".resuming")))) {
121
+ return { ...base, state: "resumable", reason: null, runId: runIdFromDir(runDir) };
122
+ }
123
+ const beforeStart = !result || result.failedStage === "pre-run" || !runDir;
124
+ const why = reason ?? result?.reason ?? (result?.failedStage ? `stopped at ${result.failedStage}` : null);
125
+ return beforeStart
126
+ ? { ...base, state: "refused", reason: why, runId: null }
127
+ : { ...base, state: "failed", reason: why, runId: runIdFromDir(runDir) };
128
+ }
129
+ if (live === "postponed") {
130
+ const meta = readJsonSafe(at("postponed.meta"));
131
+ return { ...base, state: "resumable", reason: null, runId: runIdFromDir(meta?.runDir) ?? runIdFromMeta(job, meta) };
132
+ }
133
+ if (live === "processing") {
134
+ // CLAIMING IS NOT PASSING: `.meta` lands only at dispatch, after the checks. Without it the order is still being
135
+ // checked, and nothing here says it started.
136
+ const meta = readJsonSafe(at("processing.meta"));
137
+ return meta?.codename
138
+ ? { ...base, state: "running", reason: null, runId: runIdFromMeta(job, meta) }
139
+ : { ...base, state: "checking", reason: null, runId: null };
140
+ }
141
+ if (live === "claimed") return { ...base, state: "checking", reason: null, runId: null };
142
+ return { ...base, state: "waiting", reason: null, runId: null };
143
+ }
144
+
145
+ /**
146
+ * The receipt for `reference`, as `scope` may see it.
147
+ *
148
+ * scope { account, organisation } for a company's caller, or { everything: true } for one who sees every order.
149
+ *
150
+ * Returns one of:
151
+ * { found: true, receipt: { reference, state, stateText, terminal, reason, runId, account, organisation, updatedAt } }
152
+ * { found: false, basis: "not-found" } no order by that reference that this caller may see
153
+ * { found: false, basis: "invalid-reference" } not a reference any door issues
154
+ * { found: false, basis: "could-not-look", unreadable } a queue directory would not open: not an answer
155
+ * { found: false, basis: "ambiguous" } two queue directories hold it; neither is picked
156
+ */
157
+ export function orderReceipt({ queueDirs, reference, scope } = {}) {
158
+ const ref = String(reference ?? "");
159
+ if (!ORDER_REF_RE.test(ref) || ref.includes("..")) return { found: false, basis: "invalid-reference" };
160
+ const dirs = (Array.isArray(queueDirs) ? queueDirs : []).filter((d) => typeof d === "string" && d);
161
+ const hits = [];
162
+ let unreadable = 0;
163
+ for (const qdir of dirs) {
164
+ let names;
165
+ try { names = readdirSync(qdir); }
166
+ catch (e) { if (e?.code !== "ENOENT") unreadable++; continue; }
167
+ const r = receiptIn(qdir, ref, names);
168
+ if (r) hits.push(r);
169
+ }
170
+ const visible = hits.filter((r) => orderInScope(r.job, scope));
171
+ if (visible.length > 1) return { found: false, basis: "ambiguous" };
172
+ if (visible.length === 1) {
173
+ const r = visible[0];
174
+ return { found: true, receipt: {
175
+ reference: r.reference, state: r.state, stateText: RECEIPT_STATES[r.state], terminal: TERMINAL.has(r.state),
176
+ reason: r.reason ?? null, runId: r.runId ?? null, ...(r.kind ? { kind: r.kind } : {}),
177
+ account: r.job?.profileKey ?? null, ...(r.job?.profileKey === "generic" ? { organisation: r.job?.tenant ?? null } : {}),
178
+ updatedAt: r.updatedAt,
179
+ } };
180
+ }
181
+ // Not found by this caller. A directory that would not open makes that a floor, not an answer.
182
+ if (unreadable) return { found: false, basis: "could-not-look", unreadable };
183
+ return { found: false, basis: "not-found" };
184
+ }
@@ -2,7 +2,7 @@
2
2
  "name": "clearotron-driver",
3
3
  "private": true,
4
4
  "type": "module",
5
- "version": "0.7.0",
5
+ "version": "0.8.0-beta.0",
6
6
  "license": "AGPL-3.0-only",
7
7
  "description": "Deterministic driver for the trademark clearance workflow: orchestration in code (fan-out, fan-in barrier, gating, retries); the model does judgment leaves only, through a reasoning CLI spawned per stage.",
8
8
  "engines": {
@@ -14,6 +14,9 @@
14
14
  },
15
15
  "dependencies": {
16
16
  "exceljs": "^4.4.0",
17
+ "jpeg-js": "^0.4.4",
18
+ "omggif": "^1.0.10",
19
+ "pngjs": "^7.0.0",
17
20
  "undici": "^7.29.1"
18
21
  }
19
22
  }
@@ -0,0 +1,21 @@
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
+ // picture-shrink-worker.mjs — brings one web picture down to its box, off the main thread (web-pictures.mjs).
5
+ //
6
+ // Decoding holds the thread that does it. Run here, it leaves the picture step's own clock free to end the step at its
7
+ // limit: the step stops this worker there, and a picture still being shrunk is recorded as not shrunk in time.
8
+ import { parentPort } from "node:worker_threads";
9
+ import { thumbnailOf, declaredSize } from "./picture-thumbnail.mjs";
10
+ import { imageTypeOf } from "./mark-logos.mjs";
11
+
12
+ parentPort.on("message", ({ id, bytes }) => {
13
+ const t0 = performance.now();
14
+ const picture = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
15
+ const served = declaredSize(picture, imageTypeOf(picture)?.type);
16
+ const t = thumbnailOf(picture);
17
+ const ms = Math.round(performance.now() - t0);
18
+ if (t.refused) { parentPort.postMessage({ id, ms, served, refused: t.refused }); return; }
19
+ const out = new Uint8Array(t.bytes);
20
+ parentPort.postMessage({ id, ms, served, contentType: t.contentType, width: t.width, height: t.height, kept: t.kept, bytes: out }, [out.buffer]);
21
+ });
@@ -0,0 +1,132 @@
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
+ // picture-thumbnail.mjs — a web picture brought down to what its box on the report needs, on this machine.
5
+ //
6
+ // A site's preview picture is served for a social card, often 1200 pixels wide and hundreds of kilobytes, and the report
7
+ // draws it in a box of PICTURE_BOX CSS pixels. Embedded as served, the pictures of two measured clearances grew their
8
+ // reports from 316 KB to 3,765 KB and from 267 KB to 686 KB (measured in testing, 2026-11-26). So each picture is decoded
9
+ // here, scaled down by averaging every source pixel it covers, kept in proportion, laid on the white its box shows, and
10
+ // written as a JPEG. No service and no AI program is asked.
11
+ //
12
+ // THE BYTES COME FROM ANY SITE. A picture's width and height are read before it is decoded, and one above
13
+ // PICTURE_MAX_PIXELS is not decoded at all: a few megabytes can declare a picture that would take gigabytes to hold.
14
+ // JPEG, PNG and GIF (its first frame) are decoded. A WebP is not, as the engine ships no WebP decoder: it is kept as
15
+ // served only where it is already as small as SERVED_WEBP_MAX_BYTES, and is otherwise not shown. Nothing here throws.
16
+ import jpeg from "jpeg-js";
17
+ import pngjs from "pngjs";
18
+ import omggif from "omggif";
19
+ import { imageTypeOf } from "./mark-logos.mjs";
20
+
21
+ // The box a web picture is drawn in: `.rr-lg img` in the report's stylesheet, 94 by 72, less its padding and border.
22
+ export const PICTURE_BOX = Object.freeze({ width: 82, height: 60 });
23
+ export const PICTURE_PIXEL_RATIO = 3; // pixels per CSS pixel: sharp on a phone's screen and on paper
24
+ export const PICTURE_MAX_PIXELS = 25_000_000; // a picture larger than this is not decoded
25
+ export const SERVED_WEBP_MAX_BYTES = 48 * 1024; // a WebP no larger than this is kept as served
26
+ const JPEG_QUALITY = 82;
27
+
28
+ /** The width and height a picture's header declares, without decoding it; null where it cannot be read. PURE. */
29
+ export function declaredSize(bytes, type) {
30
+ const b = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes ?? []);
31
+ if (type === "image/png" && b.length >= 24 && b.subarray(12, 16).toString("latin1") === "IHDR") return { width: b.readUInt32BE(16), height: b.readUInt32BE(20) };
32
+ if (type === "image/gif" && b.length >= 10) return { width: b.readUInt16LE(6), height: b.readUInt16LE(8) };
33
+ if (type === "image/jpeg") {
34
+ for (let i = 2; i + 9 < b.length;) {
35
+ if (b[i] !== 0xff) return null;
36
+ const marker = b[i + 1];
37
+ if (marker === 0xff) { i++; continue; }
38
+ const length = b.readUInt16BE(i + 2);
39
+ // Every start-of-frame marker but the three that are not frames (DHT, JPG, DAC) carries the size.
40
+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) return { width: b.readUInt16BE(i + 7), height: b.readUInt16BE(i + 5) };
41
+ i += 2 + length;
42
+ }
43
+ }
44
+ return null;
45
+ }
46
+
47
+ function decodeRgba(bytes, type) {
48
+ if (type === "image/jpeg") {
49
+ const img = jpeg.decode(bytes, { formatAsRGBA: true, useTArray: true, maxResolutionInMP: PICTURE_MAX_PIXELS / 1e6, maxMemoryUsageInMB: 512 });
50
+ return { width: img.width, height: img.height, data: img.data };
51
+ }
52
+ if (type === "image/png") { const img = pngjs.PNG.sync.read(bytes); return { width: img.width, height: img.height, data: img.data }; }
53
+ if (type === "image/gif") {
54
+ const gif = new omggif.GifReader(new Uint8Array(bytes));
55
+ const data = new Uint8Array(gif.width * gif.height * 4);
56
+ gif.decodeAndBlitFrameRGBA(0, data);
57
+ return { width: gif.width, height: gif.height, data };
58
+ }
59
+ return null;
60
+ }
61
+
62
+ /** The size a picture is drawn at: within the box at PICTURE_PIXEL_RATIO, in proportion, never enlarged. PURE. */
63
+ export function fittedSize(width, height, box = PICTURE_BOX, ratio = PICTURE_PIXEL_RATIO) {
64
+ const scale = Math.min((box.width * ratio) / width, (box.height * ratio) / height, 1);
65
+ return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
66
+ }
67
+
68
+ // Each target pixel is the average of the source pixels it covers, a pixel cut by its edge counted by the part inside.
69
+ // Run along each row, then down each column. The picture is laid on white first, as its box shows it.
70
+ function spans(from, to) {
71
+ const k = from / to, first = new Int32Array(to), count = new Int32Array(to), weights = [];
72
+ for (let d = 0; d < to; d++) {
73
+ const a = d * k, z = (d + 1) * k, lo = Math.floor(a), hi = Math.min(from, Math.ceil(z));
74
+ first[d] = lo; count[d] = hi - lo;
75
+ for (let s = lo; s < hi; s++) weights.push((Math.min(z, s + 1) - Math.max(a, s)) / k);
76
+ }
77
+ return { first, count, weight: Float32Array.from(weights) };
78
+ }
79
+
80
+ function downscaleOnWhite({ width: sw, height: sh, data }, dw, dh) {
81
+ const xs = spans(sw, dw), ys = spans(sh, dh);
82
+ const rgb = new Float32Array(sw * 3);
83
+ const rows = new Float32Array(dw * sh * 3);
84
+ for (let y = 0; y < sh; y++) {
85
+ for (let x = 0, i = y * sw * 4; x < sw; x++, i += 4) {
86
+ const a = data[i + 3] / 255, white = 255 - data[i + 3];
87
+ rgb[x * 3] = data[i] * a + white; rgb[x * 3 + 1] = data[i + 1] * a + white; rgb[x * 3 + 2] = data[i + 2] * a + white;
88
+ }
89
+ for (let x = 0, w = 0; x < dw; x++) {
90
+ let r = 0, g = 0, b = 0;
91
+ for (let s = xs.first[x], n = xs.count[x]; n > 0; s++, n--, w++) { const f = xs.weight[w], j = s * 3; r += rgb[j] * f; g += rgb[j + 1] * f; b += rgb[j + 2] * f; }
92
+ const o = (y * dw + x) * 3; rows[o] = r; rows[o + 1] = g; rows[o + 2] = b;
93
+ }
94
+ }
95
+ const out = new Uint8ClampedArray(dw * dh * 4); // rounds and clamps each channel as it is written
96
+ for (let y = 0, w = 0; y < dh; y++) {
97
+ const acc = new Float32Array(dw * 3);
98
+ for (let s = ys.first[y], n = ys.count[y]; n > 0; s++, n--, w++) {
99
+ const f = ys.weight[w], base = s * dw * 3;
100
+ for (let j = 0; j < dw * 3; j++) acc[j] += rows[base + j] * f;
101
+ }
102
+ for (let x = 0; x < dw; x++) { const o = (y * dw + x) * 4; out[o] = acc[x * 3]; out[o + 1] = acc[x * 3 + 1]; out[o + 2] = acc[x * 3 + 2]; out[o + 3] = 255; }
103
+ }
104
+ return out;
105
+ }
106
+
107
+ /**
108
+ * The picture as the report embeds it: `{ bytes, contentType, width, height, kept }`, where `kept` is "as served" when the
109
+ * picture already fitted its box and was no larger than a thumbnail of it, and "thumbnail" otherwise; or `{ refused }`
110
+ * with the reason it is not shown. Never throws. PURE.
111
+ */
112
+ export function thumbnailOf(bytes) {
113
+ const type = imageTypeOf(bytes)?.type ?? null;
114
+ if (!type) return { refused: "not a PNG, JPEG, GIF or WebP" };
115
+ if (type === "image/webp") {
116
+ return bytes.length <= SERVED_WEBP_MAX_BYTES ? { bytes, contentType: type, width: null, height: null, kept: "as served" }
117
+ : { refused: `a WebP larger than ${SERVED_WEBP_MAX_BYTES / 1024} KB, which is not decoded here` };
118
+ }
119
+ const declared = declaredSize(bytes, type);
120
+ if (!declared || !declared.width || !declared.height) return { refused: "its size cannot be read" };
121
+ if (declared.width * declared.height > PICTURE_MAX_PIXELS) return { refused: `larger than ${PICTURE_MAX_PIXELS / 1e6} million pixels` };
122
+ let img;
123
+ try { img = decodeRgba(bytes, type); } catch (e) { return { refused: `it does not decode: ${String(e?.message ?? e).slice(0, 80)}` }; }
124
+ if (!img?.width || !img?.height) return { refused: "it does not decode" };
125
+ const size = fittedSize(img.width, img.height);
126
+ let out;
127
+ try { out = jpeg.encode({ width: size.width, height: size.height, data: downscaleOnWhite(img, size.width, size.height) }, JPEG_QUALITY).data; }
128
+ catch (e) { return { refused: `it could not be written: ${String(e?.message ?? e).slice(0, 80)}` }; }
129
+ const fits = img.width <= PICTURE_BOX.width * PICTURE_PIXEL_RATIO && img.height <= PICTURE_BOX.height * PICTURE_PIXEL_RATIO;
130
+ if (fits && bytes.length <= out.length) return { bytes, contentType: type, width: img.width, height: img.height, kept: "as served" };
131
+ return { bytes: out, contentType: "image/jpeg", width: size.width, height: size.height, kept: "thumbnail" };
132
+ }
@@ -36,6 +36,7 @@ import { endTheDeliveredRun, runShell } from "./run-shell.mjs"; // — the run
36
36
  import { logTurnaroundReconciliation } from "./run-quote.mjs";
37
37
  import { RunCancelled, assertNotCancelledBeforePublish, isCancelled, readCancel, stopsWithTheRun } from "./cancel.mjs"; // stop-by-user: never the failure lane below
38
38
  import { attachFramework } from "./run-attachments.mjs"; // the one framework freeze, both products'
39
+ import { stampKnockoutPlainLanguage } from "./knockout-plain-language.mjs";
39
40
  import { KO_STAGES, KO_STEPS, KO_STEP_REGISTER_COUNT, koSteps, koPaths, kebab, knockoutGridSpec, KNOCKOUT_WEB, KNOCKOUT_MINUTES_BAR, knockoutBarVerdict, koChunks, groupRecordsDoc, filingsOnce, expandFilingsOnce, sameRecord, calibrationExcerptOf, readerProviderDoc } from "./stages-knockout.mjs";
40
41
  import { workedExamplesFor } from "./framework.mjs"; // which worked examples the rating's calibration comes from
41
42
  import { familiesDefect } from "./knockout-frame-record.mjs";
@@ -603,6 +604,14 @@ function checkedFamilies(runDir, rows, plan) {
603
604
  if (defect) { runLog(runDir, { event: "knockout-families-refused", defect: defect.slice(0, 300) }); return null; }
604
605
  return families;
605
606
  }
607
+ /**
608
+ * The readers that did not finish, in reader order rather than the order they settled in, sorted in place. The failure
609
+ * rethrown, the note and the run log's cause then name the lowest-numbered reader, so two runs of one order record the
610
+ * same one.
611
+ */
612
+ export function inReaderOrder(failures) { // @internal — driven by its test
613
+ return failures.sort((a, b) => a.c - b.c);
614
+ }
606
615
  function orderFamilies(runDir, names, plan) {
607
616
  const groups = koChunks(names, checkedFamilies(runDir, names, plan));
608
617
  runLog(runDir, { event: "knockout-families", source: plan?.batch?.families ? "intake" : "none", groups: groups.map((g) => g.length) });
@@ -681,6 +690,7 @@ async function readTheRegister({ ctx, job, K, run, agent, markRows, plan, counts
681
690
  } });
682
691
  } catch (e) { readerFailures.push({ c, e }); }
683
692
  }, { stop: () => readerFailures.some((f) => rateLimited(f) || f.e instanceof RunCancelled) });
693
+ inReaderOrder(readerFailures);
684
694
  const hard = readerFailures.find((f) => rateLimited(f) || f.e instanceof RunCancelled);
685
695
  if (hard) throw hard.e;
686
696
  // A STOP RECORDED WHILE THE READERS RAN ends the run here as a stop: a reader it cut short is not a reading that failed.
@@ -1105,6 +1115,8 @@ export async function knockoutInner(ctx, job, opts = {}) {
1105
1115
  // for reconcile-runs' exact liveness test. The stepper and the identity are separate calls now.
1106
1116
  ...identitySeed(),
1107
1117
  stepIndex: 0, stepLabel: STEPS[0], stepN: 1, stepTotal: STEPS.length,
1118
+ // Every step this run walks, by name and in order, as the clearance seed writes its own.
1119
+ steps: [...STEPS],
1108
1120
  review: null, url: null, failedStage: null, reason: null, deliveredAt: null,
1109
1121
  // A5/A3: a re-run of a previously-terminal knockout may reopen the state ONLY because the resume
1110
1122
  // guard cleared the sentinel (ctx.stateReset threads that authority); startedAt is no longer
@@ -1658,6 +1670,8 @@ export async function knockoutInner(ctx, job, opts = {}) {
1658
1670
  });
1659
1671
  sentinel(run.runDir, ".published", published);
1660
1672
  runLog(run.runDir, { event: "knockout-published", url: published.url, reports: published.reports.map((r) => ({ mark: r.mark, url: r.url })), overall, marks: merged.marks.length });
1673
+ // The plain-language counts by rating group and field, as saved and as published (knockout-plain-language.mjs).
1674
+ stampKnockoutPlainLanguage(run.runDir, merged);
1661
1675
  }
1662
1676
  // The knockout lane put its token total in the PUBLISHED ARTIFACT but never stamped the run itself,
1663
1677
  // so `status.json.tokens` was empty for every Stage-0 run however it ended (fixed 2026-07-28) — and
@@ -20,6 +20,9 @@ export function jobHashOf(job) {
20
20
  marks: JSON.stringify(marks), markName: String(job.markName ?? "").toLowerCase(),
21
21
  classes: JSON.stringify([...(job.classes ?? [])].sort()), goods: String(job.goods ?? ""),
22
22
  product: job.product ?? null, recipeKey: job.recipeKey ?? null,
23
+ // An Urgent order counts twice, so a review confirmed at Standard must not start it. Present only when true,
24
+ // so every Standard job hashes exactly as it did before the field existed.
25
+ ...(job.urgent === true ? { urgent: true } : {}),
23
26
  })).digest("base64url");
24
27
  }
25
28
  export function mintConfirmation({ secret, account, email, jobHash, now = Date.now(), ttlMs = 10 * 60 * 1000 }) {
@@ -645,6 +645,15 @@ const EMBED_JS = `
645
645
  // dark rules key on. That control sits in the top bar embedding strips, and a sandboxed frame cannot
646
646
  // read the portal's saved choice, so this is the one route by which an embedded report turns dark.
647
647
  // Two values and nothing else; the answer says which was applied, so the shell knows it took.
648
+ // THE PORTAL SAYS A COPY LANDED. The card's "Copy link" asked it to (below); only a copy that landed shows the tick
649
+ // and says "Copied" to a screen reader, and both go after a moment.
650
+ if(d.command==='copied'){
651
+ if(copyBtn&&d.value===true&&copyLive){
652
+ var cb=copyBtn; cb.classList.add('copied'); copyLive.textContent=cb.getAttribute('data-copied')||'';
653
+ clearTimeout(copyTimer); copyTimer=setTimeout(function(){cb.classList.remove('copied');copyLive.textContent='';},1600);
654
+ }
655
+ return;
656
+ }
648
657
  if(d.command==='theme'){
649
658
  var th=d.value==='dark'?'dark':'light';
650
659
  document.documentElement.setAttribute('data-theme',th);
@@ -701,6 +710,38 @@ const EMBED_JS = `
701
710
  // (the one that measurably needs the delegation) working, and only ever degrades to native scrolling
702
711
  // when we can positively see there is no other window.
703
712
  var framed=false; try{framed=window.parent!==window;}catch(err){framed=true;}
713
+ // COPY LINK (owner, 2026-11-25). A card's "Copy link" is drawn hidden; inside the portal this marks the page so the
714
+ // stylesheet shows it, and a press asks the portal, which alone knows its own address and may write the clipboard, to
715
+ // copy the address of its report screen at this card. The card is named by its id; a card copied into the conflict
716
+ // panel carries its original's id as data-card-of. Un-framed nobody can answer, so the page is not marked.
717
+ // THE CONFLICT PANEL MOVES THE PAGE. Narrowing the column beside it reflows everything, and the pressed number has to
718
+ // stay at the same height on screen. The page cannot scroll the portal, so it asks: un-framed it scrolls itself. Any
719
+ // reflow it makes re-posts the height and the section tops.
720
+ document.addEventListener('rep-shift',function(e){
721
+ if(!framed)return;
722
+ e.preventDefault();
723
+ try{parent.postMessage({source:TAG,type:'scrollBy',dy:Math.round((e.detail&&e.detail.dy)||0)},'*');}catch(err){}
724
+ });
725
+ document.addEventListener('rep-reflow',function(){schedule();});
726
+ var copyBtn=null, copyLive=null, copyTimer=null;
727
+ if(framed){
728
+ try{document.documentElement.classList.add('rep-portal');}catch(err){}
729
+ copyLive=document.createElement('span'); copyLive.className='copy-said'; copyLive.setAttribute('role','status');
730
+ copyLive.style.cssText='position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap';
731
+ document.body.appendChild(copyLive);
732
+ }
733
+ document.addEventListener('click',function(e){
734
+ var b=e.target.closest?e.target.closest('.copy-fi'):null;
735
+ if(!b||!framed)return;
736
+ var card=b.closest('.card'); if(!card)return;
737
+ var id=card.id||card.getAttribute('data-card-of')||'';
738
+ var whole=function(v){var n=parseInt(v,10);return String(n)===String(v)&&n>=0?n:null;};
739
+ var koOrd=card.getAttribute('data-ko-ord'), koMark=card.getAttribute('data-ko-mark');
740
+ var ord=koOrd!==null?whole(koOrd):(id.charAt(0)==='c'?whole(id.slice(1)):null);
741
+ copyBtn=b;
742
+ try{parent.postMessage({source:TAG,type:'copyLink',card:id,ordinal:ord,markIndex:koMark!==null?whole(koMark):null},'*');}
743
+ catch(err){try{console.warn('Copy link could not reach the page: '+(err&&err.message||err));}catch(e2){}}
744
+ });
704
745
  function revealTarget(el){var p=el.parentElement;while(p){if(p.tagName==='DETAILS'&&!p.open)p.open=true;p=p.parentElement;}}
705
746
  document.addEventListener('click',function(e){
706
747
  var a=e.target.closest?e.target.closest('a[href^="#"]'):null;
@@ -731,7 +772,9 @@ const EMBED_JS = `
731
772
  var card=b.closest('.card');
732
773
  var whole=function(v){var n=parseInt(v,10);return String(n)===String(v)&&n>=0?n:null;};
733
774
  var koOrd=card?card.getAttribute('data-ko-ord'):null;
734
- var idOrd=card&&(card.id||'').charAt(0)==='c'?card.id.slice(1):null;
775
+ // A card copied into the conflict panel has no id of its own; it carries its original's as data-card-of.
776
+ var cid=card?(card.id||card.getAttribute('data-card-of')||''):'';
777
+ var idOrd=cid.charAt(0)==='c'?cid.slice(1):null;
735
778
  var ord=koOrd!==null?whole(koOrd):(idOrd!==null?whole(idOrd):null);
736
779
  var koMark=card?card.getAttribute('data-ko-mark'):null;
737
780
  var mi=koMark!==null?whole(koMark):null;
@@ -18,8 +18,9 @@ import { quoteForJob } from "../run-quote.mjs";
18
18
  import { readJson } from "../run-record.mjs";
19
19
  import { countJobMarks, coverageDisclosure, kebabCollisions, policyFor, productAvailability, UNAVAILABLE_NOTE } from "../search-policy.mjs";
20
20
  import { accountUsage, DEFAULT_CLIENT_DAILY_RUNS } from "../usage-ledger.mjs";
21
+ import { admittedSearches, oneLeftRefusal } from "../urgent-count.mjs"; // what an order counts against its allowance, as the runner's wall counts it
21
22
 
22
- export async function runRoutes({ poolRoot, workspaceRoot, secret, queueDirs, trigger, stopRun, demo, orderRefusal, audit, upstream, readBuilt, readCanCount, readTerritories, loadProfilesImpl, usedJtis, sweepJtis, jobFor, selectorOf, refusalFor, allowanceExhaustedLine }, { method, parts, principal, body, query }) {
23
+ export async function runRoutes({ poolRoot, workspaceRoot, secret, queueDirs, trigger, stopRun, demo, orderRefusal, urgentAvailable = () => false, audit, upstream, readBuilt, readCanCount, readTerritories, loadProfilesImpl, usedJtis, sweepJtis, jobFor, selectorOf, refusalFor, allowanceExhaustedLine }, { method, parts, principal, body, query }) {
23
24
  // shared plan-time gates — run at BOTH doors so a body that would 422 at plan can never be
24
25
  // submitted at run behind a token minted for a clean body (review 2026-07-18)
25
26
  const planGates = (job) => {
@@ -132,10 +133,13 @@ export async function runRoutes({ poolRoot, workspaceRoot, secret, queueDirs, tr
132
133
  const resolveFor = resolveForDoor;
133
134
  const effortFrom = ({ job, profile, resolved }) => {
134
135
  if (!profile || !resolved || resolved.clarify) return null;
135
- try { return quoteForJob({ job, profile, searchPolicy: resolved }); } catch { return null; }
136
+ // Quoted as admission will count it: an Urgent order this installation cannot run fast is a Standard one.
137
+ const asAdmitted = job?.urgent === true && urgentAvailable() !== true ? { ...job, urgent: false } : job;
138
+ try { return quoteForJob({ job: asAdmitted, profile, searchPolicy: resolved }); } catch { return null; }
136
139
  };
137
140
 
138
- const quotaRefusal = async (account, organisation = null) => {
141
+ // `searches` is what the order counts (urgent-count.mjs admittedSearches), the number the runner's wall charges.
142
+ const quotaRefusal = async (account, organisation = null, searches = 1) => {
139
143
  if (seesEverything(principal) || !upstream) return null;
140
144
  let caps = null, capsRead = false;
141
145
  try {
@@ -173,8 +177,11 @@ export async function runRoutes({ poolRoot, workspaceRoot, secret, queueDirs, tr
173
177
  audit({ event: "quota-precheck-blind", by: principal.email, account, basis: used.basis });
174
178
  return null;
175
179
  }
176
- if (used.today + 1 <= limit) return null;
177
- return { status: 429, json: { ok: false, errors: [allowanceExhaustedLine(limit, BRAND.name)] } };
180
+ if (used.today + searches <= limit) return null;
181
+ // One left and an order that counts two is not an account that has used everything: it is told so in the
182
+ // order screen's own words, the same the runner's wall gives (urgent-count.mjs oneLeftRefusal).
183
+ const oneLeft = oneLeftRefusal({ used: used.today, limit, searches });
184
+ return { status: 429, json: { ok: false, errors: [oneLeft ?? allowanceExhaustedLine(limit, BRAND.name)] } };
178
185
  };
179
186
 
180
187
  // ── AN INSTALL THAT CANNOT SEARCH REFUSES HERE, WHERE THE PERSON IS ─────────────────────────
@@ -206,7 +213,7 @@ export async function runRoutes({ poolRoot, workspaceRoot, secret, queueDirs, tr
206
213
  if (notConfigured) return notConfigured;
207
214
  const gates = planGates(job);
208
215
  if (gates.fail) return gates.fail;
209
- const overQuota = await quotaRefusal(account, job.tenant ?? null);
216
+ const overQuota = await quotaRefusal(account, job.tenant ?? null, admittedSearches(job, { runsHere: urgentAvailable }));
210
217
  if (overQuota) return overQuota;
211
218
  // ONE resolution, and the name, the stage, the turnaround and the effort all come off it.
212
219
  const { profile: planProfile, resolved: planResolved, scope: planScope } = resolveFor(job);
@@ -261,7 +268,7 @@ export async function runRoutes({ poolRoot, workspaceRoot, secret, queueDirs, tr
261
268
  if (gates.fail) return gates.fail;
262
269
  // re-checked for the same reason the gates are: a token minted while the account still had
263
270
  // allowance must not spend it after another tab has used the last one.
264
- const overQuota = await quotaRefusal(account, job.tenant ?? null);
271
+ const overQuota = await quotaRefusal(account, job.tenant ?? null, admittedSearches(job, { runsHere: urgentAvailable }));
265
272
  if (overQuota) return overQuota;
266
273
  sweepJtis();
267
274
  const bad = verifyConfirmation({ secret, token: body.confirmationToken, account, email: principal.email,
@@ -384,8 +391,11 @@ export async function runRoutes({ poolRoot, workspaceRoot, secret, queueDirs, tr
384
391
  : `The run could not be started just now. Nothing was started, and nothing was charged — ${BRAND.name} can see what happened.`);
385
392
  return { status: 502, json: { ok: false, error, unwired } };
386
393
  }
387
- audit({ event: "trigger", by: principal.email, account, selector, id: job.id, ok: Boolean(r?.ok ?? r?.queued) });
388
- return { status: 200, json: { ok: true, queued: true, id: job.id, upstream: r ?? null } };
394
+ // THE REFERENCE THE ORDER IS FILED UNDER, as the engine door filed it: a door that does not see every account files
395
+ // an order under its account's own reference (mcp-server/lib/ops.mjs filedReference), not the one minted here.
396
+ const filed = typeof r?.id === "string" && r.id ? r.id : job.id;
397
+ audit({ event: "trigger", by: principal.email, account, selector, id: filed, ok: Boolean(r?.ok ?? r?.queued) });
398
+ return { status: 200, json: { ok: true, queued: true, id: filed, upstream: r ?? null } };
389
399
  }
390
400
 
391
401
  // ── STOPPING ───────────────────────────────────────────────────────────────────────────────