clearotron 0.6.0 → 0.7.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/INSTALL.md +7 -4
  2. package/QUICKSTART.md +1 -0
  3. package/README.md +5 -2
  4. package/THIRD-PARTY-NOTICES.md +1 -1
  5. package/bin/clearotron.mjs +4 -2
  6. package/bin/onboard.mjs +158 -29
  7. package/build-info.json +2 -2
  8. package/docs/CLIENT-MCP.md +3 -1
  9. package/docs/DELIVERY.md +6 -3
  10. package/docs/architecture/02-architecture.md +1 -1
  11. package/docs/architecture/04-configuration-reference.md +105 -8
  12. package/docs/branding.md +4 -4
  13. package/docs/report-data/clearance-1.schema.json +320 -0
  14. package/docs/report-data/knockout-1.schema.json +268 -0
  15. package/driver/CHANGELOG.md +77 -0
  16. package/driver/cancel.mjs +19 -0
  17. package/driver/connotation-search.mjs +1 -1
  18. package/driver/contract-e3-backlog.mjs +41 -41
  19. package/driver/contract-vocabulary.mjs +1 -1
  20. package/driver/coverage-ledger.mjs +18 -2
  21. package/driver/deferral-row.mjs +1 -1
  22. package/driver/degraded-parts.mjs +1 -0
  23. package/driver/driver.config.mjs +5 -5
  24. package/driver/effective-scope.mjs +3 -1
  25. package/driver/engagement-receipt.mjs +3 -3
  26. package/driver/engine/anthropic-agent.mjs +15 -1
  27. package/driver/engine/common.mjs +7 -0
  28. package/driver/engine/mcp/band-server.mjs +7 -16
  29. package/driver/engine/mcp/codex-config.mjs +3 -0
  30. package/driver/engine/mcp/recording-server.mjs +45 -34
  31. package/driver/engine/openai-agent.mjs +74 -7
  32. package/driver/engine/session-record.mjs +44 -2
  33. package/driver/findings-model.mjs +14 -2
  34. package/driver/follow-up-twins.mjs +86 -0
  35. package/driver/gateway.mjs +77 -12
  36. package/driver/jx-units.mjs +3 -1
  37. package/driver/jx.mjs +13 -5
  38. package/driver/manuals-inline.mjs +98 -0
  39. package/driver/manuals-seen.mjs +134 -0
  40. package/driver/mark-logos.mjs +174 -0
  41. package/driver/methodology-witness.mjs +2 -1
  42. package/driver/owner-use-check.mjs +8 -4
  43. package/driver/package.json +1 -1
  44. package/driver/pipeline-knockout.mjs +23 -4
  45. package/driver/pipeline.mjs +128 -15
  46. package/driver/portal-local-auth.mjs +6 -2
  47. package/driver/portal-report.mjs +45 -14
  48. package/driver/portal-routes/me.mjs +4 -1
  49. package/driver/portal-runs.mjs +19 -16
  50. package/driver/predelivery-lint.mjs +7 -5
  51. package/driver/profiles.mjs +4 -4
  52. package/driver/publish/README.md +9 -7
  53. package/driver/publish/email-conditions.mjs +22 -5
  54. package/driver/publish/evidence-words.mjs +21 -0
  55. package/driver/publish/index.mjs +304 -211
  56. package/driver/publish/knockout.mjs +297 -247
  57. package/driver/publish/office-record-links.mjs +11 -9
  58. package/driver/publish/page-shell.mjs +98 -0
  59. package/driver/publish/pool-admin.mjs +2 -2
  60. package/driver/publish/publish-inputs.mjs +4 -0
  61. package/driver/publish/regions.mjs +28 -3
  62. package/driver/publish/register-record-html.mjs +105 -0
  63. package/driver/publish/register-record.mjs +165 -0
  64. package/driver/publish/render-knockout.mjs +299 -671
  65. package/driver/publish/render.mjs +561 -492
  66. package/driver/publish/report-data.mjs +226 -13
  67. package/driver/publish/report-document.mjs +353 -0
  68. package/driver/publish/search-depth.mjs +88 -7
  69. package/driver/publish/shell.mjs +41 -1
  70. package/driver/publish/strings.mjs +810 -0
  71. package/driver/publish/templates/clearance-print.css +23 -0
  72. package/driver/publish/templates/knockout.css +224 -0
  73. package/driver/publish/templates/report.css +112 -53
  74. package/driver/publish/xlsx.mjs +158 -139
  75. package/driver/record-goods.mjs +42 -0
  76. package/driver/reference-score.mjs +4 -1
  77. package/driver/register-count.mjs +5 -1
  78. package/driver/register-reach.mjs +39 -0
  79. package/driver/registry-fidelity.mjs +155 -37
  80. package/driver/repair-composers.mjs +7 -3
  81. package/driver/repair-targets.mjs +4 -1
  82. package/driver/replay-archive.mjs +4 -3
  83. package/driver/run-delivered.mjs +14 -8
  84. package/driver/run-record.mjs +1 -0
  85. package/driver/runner.mjs +73 -29
  86. package/driver/scope-facts.mjs +27 -6
  87. package/driver/search-policy.mjs +9 -4
  88. package/driver/skills/clearance-search/report-prose.md +3 -0
  89. package/driver/skills/knockout-assess/SKILL.md +8 -0
  90. package/driver/stage-freshness.mjs +8 -5
  91. package/driver/stages.mjs +69 -43
  92. package/driver/steps/delivery.mjs +9 -5
  93. package/driver/steps/overview-and-cards.mjs +54 -15
  94. package/driver/steps/register-sweep.mjs +5 -4
  95. package/driver/steps/skeptic-and-follow-up.mjs +3 -2
  96. package/driver/steps/verdict-gate.mjs +35 -14
  97. package/driver/suite-census.json +579 -87
  98. package/driver/synthesis-record.mjs +4 -3
  99. package/driver/terminal-clamp.mjs +6 -1
  100. package/driver/withdrawn-rating.mjs +72 -0
  101. package/mcp-server/CHANGELOG.md +8 -0
  102. package/mcp-server/lib/audit-view.mjs +5 -2
  103. package/mcp-server/lib/brief.mjs +6 -2
  104. package/mcp-server/lib/evidence.mjs +94 -23
  105. package/mcp-server/lib/findings.mjs +19 -2
  106. package/mcp-server/lib/knockout.mjs +13 -4
  107. package/mcp-server/lib/scrub.mjs +1 -1
  108. package/mcp-server/package.json +1 -1
  109. package/mcp-server/server.mjs +22 -3
  110. package/package.json +4 -1
  111. package/portal-ui/dist/assets/{index-CYaO2ygd.js → index-BBlN4CYq.js} +238 -80
  112. package/portal-ui/dist/assets/{index-izLa9apq.css → index-CxAkJXIT.css} +25 -5
  113. package/portal-ui/dist/index.html +2 -2
  114. package/portal-ui/package.json +3 -3
  115. package/providers/_shared/ledger.mjs +30 -2
  116. package/providers/_shared/record-uri.mjs +15 -0
  117. package/providers/clarivate/src/adapter.js +11 -0
  118. package/providers/clarivate/src/core.js +17 -1
  119. package/providers/jx/src/core.js +4 -4
  120. package/providers/jx/src/judge.js +1 -3
  121. package/providers/jx/src/nativeread.js +1 -3
  122. package/providers/oauth-mcp-bridge/CHANGELOG.md +8 -0
  123. package/providers/oauth-mcp-bridge/package.json +1 -1
  124. package/scripts/README.md +147 -3
  125. package/scripts/added-reference-check.mjs +35 -7
  126. package/scripts/e2e-first-time.mjs +4 -4
  127. package/scripts/env-audit.mjs +16 -9
  128. package/scripts/freeze-example-run.mjs +3 -3
  129. package/scripts/mint-public-residue.mjs +3 -3
  130. package/scripts/mint-search-level-tags.mjs +61 -0
  131. package/scripts/mint-source-pin-census.mjs +89 -0
  132. package/scripts/release-note-required.mjs +65 -6
  133. package/scripts/test-durations-reporter.mjs +25 -0
  134. package/scripts/test-full.mjs +72 -18
  135. package/scripts/test-run.mjs +18 -1
  136. package/shared/brand.mjs +93 -6
  137. package/shared/inline-markdown.mjs +53 -0
  138. package/shared/names-in-force.mjs +0 -1
  139. package/shared/portal-tokens.mjs +2 -1
  140. package/shared/reference-guard-classes.mjs +43 -2
  141. package/shared/register-selection.mjs +8 -3
  142. package/shared/search-level-tags.json +25 -0
  143. package/shared/source-spans.mjs +91 -0
  144. package/shared/tools/derive-band-pairs.mjs +10 -0
  145. package/driver/own-rights.mjs +0 -83
  146. package/driver/use-check.mjs +0 -85
@@ -0,0 +1,174 @@
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
+ // mark-logos.mjs — the logo of each cited registration, fetched once the findings are final and saved with the run.
5
+ //
6
+ // A lawyer compares logos first, and the report showed none. So after the record is final and before the report is
7
+ // published, both pipelines run this one step: for each registration the report will show, it reads the run's saved
8
+ // record, and where that record says the mark is figurative and that an image exists, it asks the register the run is
9
+ // set to use for that one image. It writes what happened to each registration in `_driver/logos.json`, which the report
10
+ // reads, and the images under `_driver/logos/`.
11
+ //
12
+ // WHICH REGISTRATIONS. The ones the report shows and no others: a clearance's findings, withdrawn ones left out, and
13
+ // the registrations each cites; a Knockout's listed filings. Measured on a 55-finding global preliminary of 2026-11-03:
14
+ // 28 of the 3,497 records it held, so 28 image requests (that count approved 2026-11-18).
15
+ //
16
+ // WHAT A ROW SAYS, and only `failed` reads as "Logo not retrieved" on the page:
17
+ // fetched the image is saved; `file` is relative to the run folder, `contentType` PNG, JPEG, GIF or WebP
18
+ // failed a request was made and did not land, or brought back something that is not one of those images
19
+ // no-logo the record says a word mark, or that no image exists
20
+ // unknown the record cannot say, or this run makes no register call: a replay, an injected fetcher, no credential,
21
+ // or a register whose adapter fetches no image. Nothing is requested.
22
+ //
23
+ // THE REGISTER THE RUN IS SET TO USE, AND NO OTHER (ruled 2026-11-18: one run never mixes registers). A register that
24
+ // cannot fetch an image leaves its rows `unknown`; no second service is asked.
25
+ //
26
+ // A RESUME OR A REPUBLISH ASKS NOTHING AGAIN. A row already `fetched` whose file is still there is kept as it is.
27
+ //
28
+ // RECORDING ONLY, and it never throws: a logo that could not be had never stops a report.
29
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
30
+ import { join, resolve, sep } from "node:path";
31
+ import { normalizeRecordUri } from "../providers/_shared/record-uri.mjs";
32
+ import { readRecordArtifacts } from "./registry-fidelity.mjs";
33
+ import { DRIVER_DIR, driverDir, ensureDriverDir } from "./run-record.mjs";
34
+ import { runLog } from "./log.mjs";
35
+
36
+ export const LOGOS_FILE = "logos.json";
37
+ export const LOGOS_DIR = "logos";
38
+
39
+ // The register's own words for the kind of mark, as saved records carry them (counted on the test machine,
40
+ // 2026-11-18: Clarivate's eight values and Signa's three). Any other value is unknown and fetches nothing.
41
+ const FIGURATIVE = new Set(["WORD AND DESIGN", "DESIGN MARK", "DESIGN AND COLOR", "STYLIZED LETTERS", "COMBINED", "FIGURATIVE"]);
42
+ const WORD = new Set(["WORD ONLY", "WORD MARK", "BLOCK LETTERS", "WORD"]);
43
+
44
+ /** Whether a saved record carries a logo: "logo", "no-logo" or "unknown". PURE. */
45
+ export function logoOf(record) {
46
+ if (!record || typeof record !== "object") return "unknown";
47
+ const feature = String(record.markFeature ?? "").trim().toUpperCase();
48
+ if (record.imageAvailable === false || WORD.has(feature)) return "no-logo";
49
+ return FIGURATIVE.has(feature) && record.imageAvailable === true ? "logo" : "unknown";
50
+ }
51
+
52
+ /** The image type the bytes open as, by their first bytes, or null for anything else. PURE. */
53
+ export function imageTypeOf(bytes) {
54
+ const b = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes ?? []);
55
+ if (b.length >= 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return { type: "image/png", ext: "png" };
56
+ if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return { type: "image/jpeg", ext: "jpg" };
57
+ if (b.length >= 6 && /^GIF8[79]a$/.test(b.subarray(0, 6).toString("latin1"))) return { type: "image/gif", ext: "gif" };
58
+ if (b.length >= 12 && b.subarray(0, 4).toString("latin1") === "RIFF" && b.subarray(8, 12).toString("latin1") === "WEBP") return { type: "image/webp", ext: "webp" };
59
+ return null;
60
+ }
61
+
62
+ /** The registrations the report will show, in its order and once each. PURE. */
63
+ export function citedRefs({ findings = null, registerRecords = null } = {}) {
64
+ const out = [];
65
+ const add = (ref) => { const k = normalizeRecordUri(ref); if (k && !out.includes(k)) out.push(k); };
66
+ for (const f of Array.isArray(findings) ? findings : []) {
67
+ if (f?.disposition === "withdrawn") continue;
68
+ for (const r of Array.isArray(f?.owner?.registrations) ? f.owner.registrations : []) add(r?.uri);
69
+ }
70
+ for (const m of Array.isArray(registerRecords?.marks) ? registerRecords.marks : [])
71
+ for (const r of Array.isArray(m?.records) ? m.records : []) add(r?.recordId);
72
+ return out;
73
+ }
74
+
75
+ const fileFor = (ref, ext) => `${ref.replace(/^\/mark\//, "").replace(/[^a-z0-9_-]+/gi, "-")}.${ext}`;
76
+
77
+ /**
78
+ * The rows for these registrations: kept where an earlier pass saved the image, fetched where the record carries a logo
79
+ * and a request may be made, and said for the rest. `fetchImage(ref)` resolves `{ ok, bytes, contentType }` or
80
+ * `{ ok: false, cause }`; `mayCall` is `{ ok }` or `{ ok: false, why }`. Writes the images it fetched. IMPURE.
81
+ */
82
+ export async function logoRows({ runDir, refs, records, register, fetchImage, mayCall, prior = [] }) {
83
+ const kept = new Map(prior.filter((r) => r?.state === "fetched" && r.file && existsSync(join(runDir, r.file))).map((r) => [r.ref, r]));
84
+ const rows = [];
85
+ for (const ref of refs) {
86
+ if (kept.has(ref)) { rows.push(kept.get(ref)); continue; }
87
+ const record = records.get(ref);
88
+ if (!record) { rows.push({ ref, register, state: "unknown", cause: "the run holds no saved record of this registration" }); continue; }
89
+ const has = logoOf(record);
90
+ if (has !== "logo") {
91
+ rows.push({ ref, register, state: has, ...(has === "unknown" ? { cause: "the record does not say whether the mark has a logo" } : {}) });
92
+ continue;
93
+ }
94
+ if (!mayCall?.ok) { rows.push({ ref, register, state: "unknown", cause: mayCall?.why ?? "this run makes no register call" }); continue; }
95
+ if (typeof fetchImage !== "function") { rows.push({ ref, register, state: "unknown", cause: "this register's adapter fetches no image" }); continue; }
96
+ let got;
97
+ try { got = await fetchImage(ref); } catch (e) { got = { ok: false, cause: `the request threw: ${String(e?.message ?? e).slice(0, 120)}` }; }
98
+ if (!got?.ok) { rows.push({ ref, register, state: "failed", cause: String(got?.cause ?? "the request did not land").slice(0, 200) }); continue; }
99
+ const kind = imageTypeOf(got.bytes);
100
+ if (!kind) { rows.push({ ref, register, state: "failed", cause: "the answer is not a PNG, JPEG, GIF or WebP image" }); continue; }
101
+ const file = `${DRIVER_DIR}/${LOGOS_DIR}/${fileFor(ref, kind.ext)}`; // relative to the run folder, the same on every system
102
+ try {
103
+ ensureDriverDir(runDir, LOGOS_DIR);
104
+ writeFileSync(join(runDir, file), got.bytes);
105
+ rows.push({ ref, register, state: "fetched", file, contentType: kind.type, bytes: got.bytes.length });
106
+ } catch (e) { rows.push({ ref, register, state: "failed", cause: `the image could not be saved: ${String(e?.message ?? e).slice(0, 120)}` }); }
107
+ }
108
+ return rows;
109
+ }
110
+
111
+ /**
112
+ * The step both pipelines run before publishing. `findingsPath` for a clearance, `registerRecordsPath` for a Knockout;
113
+ * `provider` is the run's register adapter; `injectedFetcher` true when the run answers its record fetches itself (a
114
+ * replay, a test). Writes `_driver/logos.json`; returns it, or null when it could not. Never throws.
115
+ */
116
+ export async function markLogos(runDir, { findingsPath = null, registerRecordsPath = null, provider = null, injectedFetcher = false,
117
+ env = process.env, agentId = null, sessionKey = null } = {}) {
118
+ try {
119
+ const read = (p) => { try { return p ? JSON.parse(readFileSync(p, "utf8")) : null; } catch { return null; } };
120
+ const findings = read(findingsPath)?.findings ?? null;
121
+ const refs = citedRefs({ findings, registerRecords: read(registerRecordsPath) });
122
+ const at = driverDir(runDir, LOGOS_FILE);
123
+ const prior = read(at)?.rows ?? [];
124
+ const register = provider?.id ?? null;
125
+ const credential = provider?.credEnv ? String(env[provider.credEnv] ?? "").trim() : "";
126
+ const mayCall = injectedFetcher ? { ok: false, why: "this run answers its record fetches from saved records and makes no register call" }
127
+ : !provider ? { ok: false, why: "no register is set for this run" }
128
+ : !credential ? { ok: false, why: `${provider.credEnv ?? "the register's credential"} is not set, so no register call is made` }
129
+ : { ok: true };
130
+ const fetchImage = typeof provider?.markImage === "function" ? (ref) => provider.markImage(ref, { agentId, sessionKey }) : null;
131
+ const rows = await logoRows({ runDir, refs, records: readRecordArtifacts(runDir), register, fetchImage, mayCall, prior });
132
+ const doc = { schema: 1, register, takenAt: new Date().toISOString(), rows };
133
+ writeFileSync(at, JSON.stringify(doc, null, 2) + "\n");
134
+ return doc;
135
+ } catch { return null; }
136
+ }
137
+
138
+ /** The run's log line for the step: how many registrations ended in each state, or that the step could not write. */
139
+ export function logosStep(runDir, doc) {
140
+ const counts = {};
141
+ for (const r of doc?.rows ?? []) counts[r.state] = (counts[r.state] ?? 0) + 1;
142
+ try { runLog(runDir, doc ? { event: "logos", register: doc.register, ...counts } : { event: "logos-not-written" }); } catch { /* a log line never stops a publish */ }
143
+ return counts;
144
+ }
145
+
146
+ const SHOWN_TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
147
+
148
+ /**
149
+ * The logos a report shows, by registration: `fetched` rows carry the image as a data address, so the delivered
150
+ * report fetches nothing and never names the register's image address; `failed` rows carry no image and read "Logo
151
+ * not retrieved"; every other row is left out, since it draws nothing. A row's file must sit inside the run's logo
152
+ * folder and open as the image type it was saved as, or it is left out. Never throws. IMPURE: it reads the run.
153
+ */
154
+ export function logosForReport(runDir) {
155
+ const out = new Map();
156
+ if (!runDir) return out;
157
+ let doc = null;
158
+ try { doc = JSON.parse(readFileSync(driverDir(runDir, LOGOS_FILE), "utf8")); } catch { return out; }
159
+ const folder = resolve(runDir, DRIVER_DIR, LOGOS_DIR) + sep;
160
+ for (const row of Array.isArray(doc?.rows) ? doc.rows : []) {
161
+ const ref = normalizeRecordUri(row?.ref);
162
+ if (!ref) continue;
163
+ if (row.state === "failed") { out.set(ref, { state: "failed" }); continue; }
164
+ if (row.state !== "fetched" || typeof row.file !== "string" || !SHOWN_TYPES.has(row.contentType)) continue;
165
+ const at = resolve(runDir, row.file);
166
+ if (!at.startsWith(folder)) continue;
167
+ try {
168
+ const bytes = readFileSync(at);
169
+ if (imageTypeOf(bytes)?.type !== row.contentType) continue;
170
+ out.set(ref, { state: "fetched", src: `data:${row.contentType};base64,${bytes.toString("base64")}` });
171
+ } catch { /* an image that cannot be read is not shown */ }
172
+ }
173
+ return out;
174
+ }
@@ -59,7 +59,7 @@ export function skillRefsIn(message) {
59
59
  * the invisibility it is fixing.
60
60
  */
61
61
  export function witnessStageMethodology(runDir, stage, message, resolveSkill, { platform = process.platform } = {}) {
62
- const out = { drift: [], fellBackToBase: [], recorded: 0 };
62
+ const out = { drift: [], fellBackToBase: [], recorded: 0, told: [] };
63
63
  const underSkills = new RegExp(`${sepClass(platform)}skills${sepClass(platform)}`);
64
64
  const nameOf = platform === "win32" ? win32.basename : basename;
65
65
  try {
@@ -97,6 +97,7 @@ export function witnessStageMethodology(runDir, stage, message, resolveSkill, {
97
97
 
98
98
  doc.stages[stage] = seen;
99
99
  out.recorded = seen.length;
100
+ out.told = seen; // the rows themselves, so the caller measures this turn against what IT was told (manuals-seen.mjs)
100
101
  ensureDriverDir(runDir);
101
102
  writeFileSync(`${path}.tmp`, JSON.stringify(doc, null, 2) + "\n");
102
103
  renameSync(`${path}.tmp`, path); // atomic: a torn witness must never look like drift
@@ -16,9 +16,9 @@
16
16
  //
17
17
  // ── WHY THE DRIVER RUNS THE QUERY, RATHER THAN THE SEAT BEING TOLD TO ───────────────────────────────
18
18
  //
19
- // The clearance lane enforces its use-check on the DOCUMENT SHAPE of the narrative, and `use-check.mjs`
20
- // says plainly why: "There is no perplexity call ledger … so the cited result inside the narrative is the
21
- // only proof a query ran." That was the best substrate available there.
19
+ // The clearance lane enforced its use-check on the DOCUMENT SHAPE of the narrative, and the retired gate
20
+ // said plainly why: "There is no perplexity call ledger … so the cited result inside the narrative is the
21
+ // only proof a query ran." That was the best substrate available there; it is a findings-record field now.
22
22
  //
23
23
  // This lane has a better one. The driver already owns the register store, already runs the sweep, and
24
24
  // already writes a receipts ledger — so it can issue the query ITSELF and record the outcome at the
@@ -50,6 +50,7 @@ import { createHash } from "node:crypto";
50
50
 
51
51
  import { promotableRecords } from "./publish/render-knockout.mjs";
52
52
  import { isResearchAnswer } from "./research-answers.mjs"; // a reply the formatter could not read is no answer
53
+ import { RunCancelled } from "./cancel.mjs";
53
54
 
54
55
  /** The literal the clearance lane uses for an honest non-answer. Copied, not re-worded. */
55
56
  export const NO_RESULT = "perplexity_research — no result";
@@ -153,7 +154,10 @@ export async function runOwnerChecks({ owners, exec, runDir, ledgerPath = null,
153
154
  const started = Date.now();
154
155
  let r;
155
156
  try { r = await exec(query, { mark: o.mark, preset }); }
156
- catch (e) { r = { ok: false, cause: `executor threw: ${String(e?.message ?? e).slice(0, 200)}` }; }
157
+ catch (e) {
158
+ if (e instanceof RunCancelled) throw e; // a stop is not an unanswered check: the run ends, and asks no more
159
+ r = { ok: false, cause: `executor threw: ${String(e?.message ?? e).slice(0, 200)}` };
160
+ }
157
161
 
158
162
  // THE SEARCHES BEHIND THE ANSWER ARE KEPT, answered or not, beside the answer's own name: the answer
159
163
  // alone cannot say which pages the lookup was handed.
@@ -2,7 +2,7 @@
2
2
  "name": "clearotron-driver",
3
3
  "private": true,
4
4
  "type": "module",
5
- "version": "0.6.0",
5
+ "version": "0.7.0-beta.1",
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": {
@@ -34,7 +34,7 @@ import { registerAdapter as adapterForRegister } from "./engine/run-choices.mjs"
34
34
  import { StageFailure, stageWallFields } from "./run-outcome.mjs"; // — the wall fields the spine already carries
35
35
  import { endTheDeliveredRun, runShell } from "./run-shell.mjs"; // — the runner and the delivered ending both products share
36
36
  import { logTurnaroundReconciliation } from "./run-quote.mjs";
37
- import { RunCancelled, assertNotCancelledBeforePublish, isCancelled, readCancel } from "./cancel.mjs"; // stop-by-user: never the failure lane below
37
+ import { RunCancelled, assertNotCancelledBeforePublish, isCancelled, readCancel, stopsWithTheRun } from "./cancel.mjs"; // stop-by-user: never the failure lane below
38
38
  import { loadFrameworkManifest, parseFrameworkManifest, frameworkFor, DEFAULT_FRAMEWORK } from "./framework.mjs";
39
39
  import { attachFrameworkMethod, methodPathFor, FROZEN_METHOD_FILE } from "./framework-method.mjs";
40
40
  import { KO_STAGES, KO_STEPS, KO_STEP_REGISTER_COUNT, koSteps, koPaths, kebab, knockoutGridSpec, KNOCKOUT_WEB, KNOCKOUT_MINUTES_BAR, knockoutBarVerdict, koChunks } from "./stages-knockout.mjs";
@@ -56,7 +56,8 @@ import { knockoutAssessSourceDefects } from "./knockout-assess-record.mjs";
56
56
  import { correctionsAppliedTable, unresolvedFlags } from "./corrections-feedforward.mjs";
57
57
  import { settledKnockoutReading } from "./knockout-register-record.mjs";
58
58
  import { stripNextStepSections } from "./knockout-next-step.mjs";
59
- import { publishKnockout, composeKnockoutEmail, knockoutName } from "./publish/knockout.mjs";
59
+ import { publishKnockout, composeKnockoutCoverNote, knockoutName } from "./publish/knockout.mjs";
60
+ import { markLogos, logosStep } from "./mark-logos.mjs";
60
61
  import { writeRunStatus, readRunStatus, rollupStatus, identitySeed, recordTransition, resumeRecord } from "./progress.mjs"; // — the identity seed is shared; the stepper is not
61
62
  import { batchMarkName } from "./mark-name.mjs";
62
63
  import { runLog, note, outputMeta } from "./log.mjs";
@@ -594,6 +595,8 @@ async function readTheRegister({ ctx, job, K, run, agent, markRows, plan, counts
594
595
  offline: countExec.source.startsWith("fixtures:"),
595
596
  fixtureDir: job?.registerFixtures?.records ?? null,
596
597
  });
598
+ // The questions the code asks the register itself read the stop first, as the counts do; a model turn's are the gateway's.
599
+ if (typeof exec.execute === "function") exec.execute = stopsWithTheRun(run.runDir, "knockout-register-read", exec.execute);
597
600
  const refusal = countExec.source.startsWith("fixtures:") && exec.source === "none"
598
601
  ? "this run counted from fixtures and its job declares no `registerFixtures.records` directory, so the "
599
602
  + "filings behind the counts were not listed — a fixture run never reaches a live register."
@@ -645,6 +648,9 @@ async function readTheRegister({ ctx, job, K, run, agent, markRows, plan, counts
645
648
  }
646
649
  } catch (e) {
647
650
  if (e instanceof StageFailure && (e.rateLimited || e.resetsAt)) throw e;
651
+ // A STOP IS NOT A STEP THAT DID NOT FINISH. Read as one, the lane settled the reading and went on to the owner checks,
652
+ // and paid for them after the stop (measured 2026-11-19).
653
+ if (e instanceof RunCancelled) throw e;
648
654
  note(`register reading step did not finish (non-fatal): ${String(e?.message ?? e).slice(0, 200)}`);
649
655
  runLog(run.runDir, { event: "knockout-register-read-failed", cause: String(e?.message ?? e).slice(0, 300) });
650
656
  reading = settledKnockoutReading(run.runDir);
@@ -863,6 +869,9 @@ export async function knockoutInner(ctx, job, opts = {}) {
863
869
  // frame turn" is exactly what a skip prevents, and prevents earlier than a throw did.
864
870
  // (pipelineInner's register preflight is skipped for this lane — knockout has no register machinery.)
865
871
  sweep = resolveSweepExecutor(opts);
872
+ // Every paid call the lane makes itself reads the stop first (cancel.mjs stopsWithTheRun): the web grid, the owner
873
+ // checks that share its executor, and below, the register counts and listings.
874
+ sweep = { ...sweep, grid: stopsWithTheRun(run.runDir, "knockout-sweep", sweep.grid), exec: stopsWithTheRun(run.runDir, "knockout-owner-checks", sweep.exec) };
866
875
 
867
876
  // Depth 2 preflight — the SAME discipline, for the register count. Both refusals it can return
868
877
  // are structural (a provider that cannot count; a territory scope it cannot express), so they are
@@ -891,6 +900,7 @@ export async function knockoutInner(ctx, job, opts = {}) {
891
900
  // is a fact about the run, so it arrives with the run and lands on its record.
892
901
  fixtureDir: job?.registerFixtures?.counts ?? null,
893
902
  });
903
+ countExec = { ...countExec, count: stopsWithTheRun(run.runDir, "knockout-register-count", countExec.count) };
894
904
  // EVERY required variable. `Boolean(process.env[credEnv])` here was a half-check: it
895
905
  // reported "credential present" for a euipo instance holding the id and no secret, and would
896
906
  // have done the same for a free-tier instance holding one member of two. fixed the
@@ -1092,7 +1102,10 @@ export async function knockoutInner(ctx, job, opts = {}) {
1092
1102
  while (attempts < 2) {
1093
1103
  attempts++;
1094
1104
  try { r = await grid(spec, { mark: m.name, preset, reasoning }); }
1095
- catch (e) { r = { ok: false, cause: `executor threw: ${String(e?.message ?? e).slice(0, 200)}` }; }
1105
+ catch (e) {
1106
+ if (e instanceof RunCancelled) throw e; // a stop is not a degraded mark
1107
+ r = { ok: false, cause: `executor threw: ${String(e?.message ?? e).slice(0, 200)}` };
1108
+ }
1096
1109
  if (Array.isArray(r?.raw) && r.raw.length) raw.push({ attempt: attempts, items: r.raw });
1097
1110
  if (r?.ok || r?.outage === true || !/^grid: /.test(String(r?.cause ?? ""))) break;
1098
1111
  }
@@ -1242,6 +1255,7 @@ export async function knockoutInner(ctx, job, opts = {}) {
1242
1255
  } catch (e) {
1243
1256
  // Structural only — runOwnerChecks itself never throws. Non-fatal by the same rule as the
1244
1257
  // listing above: a report is never withheld for a check that could not run.
1258
+ if (e instanceof RunCancelled) throw e;
1245
1259
  note(`owner use-check failed (non-fatal): ${e.message}`);
1246
1260
  runLog(run.runDir, { event: "knockout-owner-checks-failed", cause: String(e?.message ?? e).slice(0, 300) });
1247
1261
  }
@@ -1471,6 +1485,9 @@ export async function knockoutInner(ctx, job, opts = {}) {
1471
1485
  const moved = withCitedFilings(held, merged);
1472
1486
  if (moved !== held) atomicWrite(K.registerRecords, JSON.stringify(moved, null, 2) + "\n");
1473
1487
  } catch { /* no record on this run, or none readable: publish says which */ }
1488
+ // THE LOGOS of the listed filings, as the clearance's are fetched (mark-logos.mjs), before the page is built.
1489
+ logosStep(run.runDir, await markLogos(run.runDir, { registerRecordsPath: K.registerRecords, provider: (() => { try { return adapterForRegister(ctx.register ?? null); } catch { return null; } })(),
1490
+ injectedFetcher: Boolean(opts.recordFetcher), agentId: ctx.agent ?? null }));
1474
1491
  published = await publishKnockout({
1475
1492
  runId, codename: run.codename, runDir: run.runDir,
1476
1493
  findings: merged, plan, framework: ctx.framework, overall,
@@ -1510,7 +1527,9 @@ export async function knockoutInner(ctx, job, opts = {}) {
1510
1527
  // They are FLAGS: the packet, the state and the send below are byte-identical with or without them.
1511
1528
  // The product's name, from the run's frozen policy, for the email's first line and its subject alike.
1512
1529
  const productName = knockoutName(policy);
1513
- const emailHtml = composeKnockoutEmail({ findings: merged, framework: ctx.framework, overall, reports: published.reports, auditUrl: published.auditUrl, job, registerCounts, qcFlags: published.qcFlags, productName });
1530
+ // From the run's report document where it has one (composeKnockoutCoverNote); the lane's own values are what a run
1531
+ // published before the document is composed from.
1532
+ const emailHtml = composeKnockoutCoverNote(run.runDir, { findings: merged, framework: ctx.framework, overall, reports: published.reports, auditUrl: published.auditUrl, job, registerCounts, qcFlags: published.qcFlags, productName });
1514
1533
  writeFileSync(K.emailBody, emailHtml);
1515
1534
  const nMarks = merged.marks.length;
1516
1535
  const refTag = job.ref ? ` (${job.ref})` : "";
@@ -204,7 +204,7 @@ import { recordedScopeLedgerRows } from "./clearance-variants-record.mjs";
204
204
  import { renderFormNeighbourhoodJson, parseFormNeighbourhoodJson, dispatchedQueriesFromBand, formGapDirectives, markText } from "./form-neighbourhood.mjs"; import { loadOrdinaryWords } from "./ordinary-words.mjs";
205
205
  import { createRepairLedger, retryCannotHelpWith, isContentShapedFail, isFallbackEligible } from "./repairs.mjs";
206
206
  import { isEntrypoint } from "../shared/is-entrypoint.mjs"; // — one entry-point test, all spellings
207
- import { isCancelled } from "./cancel.mjs"; // stop-by-user: a distinct class, never classified as a failure; isCancelled is the resume door's own refusal (2155)
207
+ import { isCancelled, stopsWithTheRun } from "./cancel.mjs"; // stop-by-user: a distinct class, never classified as a failure; isCancelled is the resume door's own refusal
208
208
  import { reachableCommand } from "../shared/invocation.mjs"; // — a printed command the reader can type later, from anywhere
209
209
  export { StageFailure, buildFailurePacket, isDesignedRefusal, stageWallFields, terminalReasonFields }; // moved to run-outcome.mjs; importers read them here as before
210
210
  export { correctionReading, correctionRows, flagOrdinals, recordCorrectionsBasis, repairUnnamedRemovals, rollbackCorrectivePass }; // moved to steps/corrections.mjs; importers read them here as before
@@ -1652,7 +1652,21 @@ for (const x of DISPATCH_EXTRAS) {
1652
1652
 
1653
1653
  // The case-law profiles joined to the findings as they stand: the profiles carry the writer's numbers, and after a
1654
1654
  // grouping the delivered record has its own (joinCaseLawProfiles).
1655
- const caseLawJoin = (P, findings) => joinCaseLawProfiles(parseCaseLawProfiles(readFileSync(P.caseLaw, "utf8")), findings, readFold(P.runDir)?.map?.modelToFolded ?? null);
1655
+ //
1656
+ // A JOIN THAT FAILS IS RECORDED BEFORE IT IS THROWN. Every caller asks only when the case-law file is there, and catches
1657
+ // the throw as "no case-law layer", so a join that failed on a file that exists read exactly like a run with no case law:
1658
+ // the cards and the delivery checks went on without it and nothing said so. The run log now carries the failure; what
1659
+ // each caller does next is unchanged.
1660
+ export const caseLawJoin = (P, findings) => {
1661
+ try {
1662
+ return joinCaseLawProfiles(parseCaseLawProfiles(readFileSync(P.caseLaw, "utf8")), findings, readFold(P.runDir)?.map?.modelToFolded ?? null);
1663
+ } catch (e) {
1664
+ const error = String(e?.message ?? e).replace(/\s+/g, " ").slice(0, 200);
1665
+ try { runLog(P.runDir, { event: "case-law-join-failed", error }); } catch { /* the note below still says it */ }
1666
+ note(`case law: the profiles could not be joined to the findings (${error}); this step goes on without them`);
1667
+ throw e;
1668
+ }
1669
+ };
1656
1670
 
1657
1671
  // The runnable half of INLINE_CONTEXT. Reads the CANONICAL run (`ctx.paths`), because that is the run
1658
1672
  // pipelineInner would have been reading when it built this payload.
@@ -1669,7 +1683,7 @@ const INLINE_RESOLVERS = {
1669
1683
  try {
1670
1684
  if (finding && existsSync(P.caseLaw))
1671
1685
  caseLawProfile = caseLawJoin(P, findings).get(ord) ?? null;
1672
- } catch { /* no case-law layer — production passes null here too */ }
1686
+ } catch { /* no case-law layer, or a join that failed, which caseLawJoin has recorded — production passes null here too */ }
1673
1687
  return { finding, caseLawProfile };
1674
1688
  },
1675
1689
  };
@@ -2747,7 +2761,7 @@ async function verifyAndRecordHouseElement(ctx, opts = {}) {
2747
2761
  // "verified by owner, not asserted" means — there is no owner-predicate listing on this interface
2748
2762
  // and inventing one would be a second way to ask the same question.
2749
2763
  const lookup = typeof rec.list !== "function" ? null : async ({ element, classes: cls }) => {
2750
- const r = await rec.list(element, { classes: cls, regions, limit: 50 });
2764
+ const r = await stopsWithTheRun(P.runDir, "own-registrations", rec.list)(element, { classes: cls, regions, limit: 50 });
2751
2765
  if (!r || r.ok === false) return { ok: false, reason: String(r?.reason ?? "the register listing did not answer") };
2752
2766
  return { ok: true, records: Array.isArray(r.records) ? r.records : [] };
2753
2767
  };
@@ -7935,8 +7949,10 @@ export function injectDeferralCoverage(P, runDir, note) { // @internal — exp
7935
7949
  try {
7936
7950
  const rp = paths(runDir).frameReopenReceipt;
7937
7951
  if (!existsSync(rp) || !existsSync(P.findings)) return;
7938
- const deferrals = JSON.parse(readFileSync(rp, "utf8"))?.deferrals ?? [];
7952
+ const receipt = JSON.parse(readFileSync(rp, "utf8"));
7953
+ const deferrals = receipt?.deferrals ?? [];
7939
7954
  if (!deferrals.length) return;
7955
+ const kinds = followUpKinds(receipt); // the search each deferred directive recorded (follow-up-twins.mjs)
7940
7956
  const doc = JSON.parse(readFileSync(P.findings, "utf8"));
7941
7957
  // T1 (G8): a findings.json without a coverage array must not silently LOSE the deferral
7942
7958
  // rows — the reader-visible disclosure is the whole point of "can't close → disclose".
@@ -7963,6 +7979,8 @@ export function injectDeferralCoverage(P, runDir, note) { // @internal — exp
7963
7979
  const want = normTxt(plainDirective(directive)).split(" ").filter((w) => w.length >= 4).slice(0, 4);
7964
7980
  if (want.length && rows.some((ws) => want.every((w) => ws.has(w)))) continue; // synthesis already weighed it in
7965
7981
  const row = deferralCoverageRow(directive, d?.reason); // — word-boundary heading, full directive in the note
7982
+ // An axis-labelled row stands in only on the search the run recorded for this directive, as the page decides.
7983
+ if (axisTwin(plainDirective(directive), kindsForFollowUp(row, kinds), doc.coverage.filter((c) => !String(c.area ?? "").startsWith("Follow-up / ")))) continue;
7966
7984
  doc.coverage.push(row);
7967
7985
  rows.push(wordsOf(row));
7968
7986
  added++;
@@ -8042,6 +8060,19 @@ export function scriptScopeDisclosure(lane) { // @internal
8042
8060
  };
8043
8061
  }
8044
8062
 
8063
+ /** Several script lanes' rows as one, in the approved words: the lanes' names and their territories joined, the
8064
+ * sentence and the offer once. PURE. */
8065
+ export function mergedScriptScopeRow(lanes, state = "coverage-limited") { // @internal
8066
+ const parts = lanes.map((lane) => scriptScopeDisclosure(lane)).filter(Boolean);
8067
+ const names = parts.map((d) => d.area.replace(/\s*register equivalents\s*\(.*\)$/, ""));
8068
+ const joined = names.length <= 1 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
8069
+ return {
8070
+ area: `${joined} register equivalents (${parts.flatMap((d) => d.territories).join(" / ")})`,
8071
+ state,
8072
+ note: `${joined} same-meaning/phonetic register equivalents not searched on this search — ${NATIVE_LANGUAGE_REMEDY}`,
8073
+ };
8074
+ }
8075
+
8045
8076
  /** The pure decision: should the honesty row be injected, and what row. Exported for the unit tests.
8046
8077
  * `scope` is the requested-territory list (jxScopeJurisdictions precedence: instructed wins, else
8047
8078
  * profile defaults); the zh match is EXACTLY the codes decideJxLanes would have matched with the lane
@@ -8129,7 +8160,12 @@ export function zhLaneRanOnRun(runDir, opts = {}) { // @internal
8129
8160
  export function injectScriptScopeCoverage(P, runDir, note, { searchPolicy = null, job = null, profile = null, env = process.env, lanes = Object.keys(LANGUAGE_LANES), localLanguage = null } = {}) { // @internal
8130
8161
  try {
8131
8162
  if (!existsSync(P.findings)) return;
8132
- const scope = jxScopeJurisdictions(job ?? {}, profile ?? {});
8163
+ // A WORLDWIDE ORDER IS SEARCHED WORLDWIDE, and its native-script rows are owed on that scope. The lane scope below falls
8164
+ // back to the account's default territories when an order names none, which is right for the paid lanes it chooses and
8165
+ // wrong here: a worldwide order under an account whose defaults hold no Chinese, Japanese or Korean territory wrote no
8166
+ // native-script row at all, and its report said nothing of a search it never ran. The account's defaults are the
8167
+ // customer's priorities, never the order's scope (ruled 2026-09-26, effective-scope.mjs).
8168
+ const scope = job?.geography?.mode === "worldwide" ? [] : jxScopeJurisdictions(job ?? {}, profile ?? {});
8133
8169
  const pending = [];
8134
8170
  // AN INVESTIGATION THE CLIENT ORDERED IS NEVER OFFERED BACK TO THEM (ruled 2026-09-25). The row below
8135
8171
  // says where the native-language investigation can be bought, which is true of a search that did not
@@ -8153,7 +8189,7 @@ export function injectScriptScopeCoverage(P, runDir, note, { searchPolicy = null
8153
8189
  const doc = JSON.parse(readFileSync(P.findings, "utf8"));
8154
8190
  if (!Array.isArray(doc.coverage)) doc.coverage = []; // T1 (G8) posture: never silently lose the disclosure
8155
8191
  const rowText = (c) => `${c?.area ?? ""} ${c?.note ?? ""}`.toLowerCase();
8156
- const added = [];
8192
+ const added = [], owed = [];
8157
8193
  for (const p of pending) {
8158
8194
  // Suppression is PER LANE. The old check treated any coverage row mentioning "clearance-jx" as
8159
8195
  // covering the disclosure, which was harmless while zh was the only lane and is a silent row-
@@ -8171,9 +8207,18 @@ export function injectScriptScopeCoverage(P, runDir, note, { searchPolicy = null
8171
8207
  || (p.marker != null && t.includes(p.marker) && SCRIPT_SCOPE_RECOMMENDATION_TOKENS.some((tok) => t.includes(tok)));
8172
8208
  });
8173
8209
  if (already) continue;
8174
- doc.coverage.push(p.row);
8175
- added.push(p.lane);
8210
+ owed.push(p);
8176
8211
  }
8212
+ // THE SCRIPT ROWS ARE ONE ROW (owner, 2026-11-18). A worldwide order owed a row per script lane, each ending
8213
+ // in the same offer, so "Left open" said it three times. The lanes still owed a row are now one row: their
8214
+ // names and territories joined, the same approved sentence once. One lane writes the row it always wrote.
8215
+ // The merged row carries every lane's marker and the offer's own words, so the per-lane check above finds
8216
+ // it on a second pass and writes nothing more.
8217
+ const scriptRows = owed.filter((p) => p.marker != null);
8218
+ const rows = [...owed.filter((p) => p.marker == null).map((p) => p.row),
8219
+ ...(scriptRows.length > 1 ? [mergedScriptScopeRow(scriptRows.map((p) => p.lane), scriptRows[0].row.state)] : scriptRows.map((p) => p.row))];
8220
+ doc.coverage.push(...rows);
8221
+ added.push(...owed.map((p) => p.lane));
8177
8222
  if (!added.length) return;
8178
8223
  parseFindingsJson(JSON.stringify(doc)); // re-validate the shape (throws → catch keeps original)
8179
8224
  writeFindings(runDir, doc, { why: "script-scope-coverage-row", settles: [] }); // B5 — never a truncated findings.json
@@ -8240,7 +8285,10 @@ export function injectLaneDepthCoverage(P, runDir, note) { // @internal
8240
8285
  // `jx.mjs` writes them as this cause's `why`, and the reader gets them as they are, under a label in words: no
8241
8286
  // opening that restates them in the code's terms, and no closing line about verdicts, which belongs to the run's
8242
8287
  // own coverage judgment. Every other cause keeps the fuller note below.
8243
- const plain = v.cause === "not-built-for-lane" && v.ran === "candidates" && typeof v.why === "string" && v.why;
8288
+ // A depth the record cannot confirm, and a full ask that ran candidates only, are said the same way, each in the
8289
+ // owner's sentence (2026-11-18).
8290
+ const plain = (v.cause === "not-built-for-lane" && v.ran === "candidates" || v.cause === "not-established"
8291
+ || v.cause === "requested-full-ran-candidates") && typeof v.why === "string" && v.why;
8244
8292
  const language = String(LANGUAGE_LANES[lane]?.label ?? "").replace(/-script deepening$/, "") || lane; // as jx.mjs names it
8245
8293
  const area = plain ? `${language}-language search depth` : `Native-language investigation depth / ${lane}`;
8246
8294
  const areas = [area, `Native-language investigation depth / ${lane}`, `${language}-language search depth`].map((a) => a.toLowerCase());
@@ -8393,6 +8441,54 @@ export function injectScreenGateCoverage(P, runDir, note, ctx = {}) { // @inte
8393
8441
  }
8394
8442
  }
8395
8443
 
8444
+ // Imported down here, below every line the rest of the tree cites by number, so adding them moved none of those lines.
8445
+ import { registerReach, NOT_COVERED_REASON } from "./register-reach.mjs"; // — what the register service reaches, against the order's markets
8446
+ import { regionName } from "./publish/regions.mjs";
8447
+
8448
+ // THE MARKETS AN ORDER IS FOR, as the register's reach is read against them: a worldwide order's are the client's
8449
+ // markets (the account's default markets, else the major markets, plus any market the order names), and a territorial
8450
+ // order's are its own. Read from the run's frozen order and profile. Never throws: an order it cannot read has no
8451
+ // markets here, and the coverage line and the rows then say what they said before.
8452
+ export function orderMarketsOf(ctx, plan) { // @internal
8453
+ try {
8454
+ const order = instructedOrder(ctx.paths, ctx.job);
8455
+ return plan?.scope_basis === "worldwide" ? clientMarkets(order, ctx.profile) : orderTerritories(order, ctx.profile);
8456
+ } catch { return []; }
8457
+ }
8458
+
8459
+ /** EVERY MARKET THE REGISTER SERVICE DOES NOT REACH GETS A "NOT SEARCHED" ROW, WRITTEN BY CODE (owner, 2026-11-18).
8460
+ * Whether such a market was named used to depend on what the writer chose to write: on three deliveries of one
8461
+ * order, one named Japan alone, and Vietnam was named on none. The reach is register-reach.mjs's, the same answer the
8462
+ * coverage line names, so the row and the line cannot disagree. The area is the country's name and the reason is the
8463
+ * approved one. A row the writer added for the same market stays beside it. Idempotent by area and reason, so a resume
8464
+ * or a second pass never doubles a row; never-kill, as its siblings. */
8465
+ export function injectUncoveredMarketCoverage(P, runDir, note, ctx = {}) { // @internal
8466
+ try {
8467
+ if (!existsSync(P.findings)) return;
8468
+ let plan = ctx.registerPlan ?? null;
8469
+ if (!plan) { try { plan = JSON.parse(readFileSync(P.registerPlan, "utf8")); } catch { return; } }
8470
+ const reach = registerReach(plan?.provider, orderMarketsOf(ctx, plan));
8471
+ if (!reach?.uncovered.length) return;
8472
+ const doc = JSON.parse(readFileSync(P.findings, "utf8"));
8473
+ if (!Array.isArray(doc.coverage)) doc.coverage = [];
8474
+ let added = 0;
8475
+ for (const code of reach.uncovered) {
8476
+ const area = regionName(code);
8477
+ if (doc.coverage.some((c) => String(c?.area ?? "") === area && String(c?.note ?? "") === NOT_COVERED_REASON)) continue;
8478
+ doc.coverage.push({ area, state: "not-searched", note: NOT_COVERED_REASON });
8479
+ added++;
8480
+ }
8481
+ if (!added) return;
8482
+ parseFindingsJson(JSON.stringify(doc)); // re-validate the shape (throws → catch keeps original)
8483
+ writeFindings(runDir, doc, { why: "uncovered-market-rows", settles: [] });
8484
+ runLog(runDir, { event: "uncovered-market-rows", service: reach.service, offices: reach.offices, markets: reach.uncovered, added });
8485
+ note(`[register-reach] ${added} "Not searched" row(s) for market(s) outside ${reach.service}'s ${reach.offices} offices: ${reach.uncovered.join(", ")}`);
8486
+ } catch (e) {
8487
+ note(`[register-reach] coverage rows skipped: ${String(e?.message || e).replace(/\s+/g, " ").slice(0, 100)}`);
8488
+ coverageRowNotAdded(runDir, "register-reach", e);
8489
+ }
8490
+ }
8491
+
8396
8492
  // spec 64 (B3) — within-run deadline propagation (the DEMVENZY drop): the register bands carried
8397
8493
  // oppositionEndDate 2026-07-13 two days before the window closed, and it never reached the delivered
8398
8494
  // findings/prose. Deterministic join: a finding whose registration matches a band/record opposition
@@ -9299,7 +9395,7 @@ export async function acquireRunSlot(agent = null) { // @internal
9299
9395
  // P2 — reconcile every stage stamp against the artifacts as they finally stand for this pass, so the NEXT
9300
9396
  // pass pays only for material that actually changed between passes (not for this pass's own driver-side
9301
9397
  // re-merges/normalizations). Runs on success and failure alike, and always after the delivery precondition.
9302
- function reconcilePassStamps(runRef, ctx) {
9398
+ export function reconcilePassStamps(runRef, ctx) { // @internal, exported for its test
9303
9399
  try {
9304
9400
  const P = ctx?.paths ?? runRef?.paths;
9305
9401
  if (!P?.runDir) return;
@@ -9314,7 +9410,11 @@ function reconcilePassStamps(runRef, ctx) {
9314
9410
  try {
9315
9411
  const q = coerceQueue(JSON.parse(readFileSync(P.digestQueue, "utf8")));
9316
9412
  if (pendingItems(q).length) exclude.add("register-digest");
9317
- } catch { /* no queue on disk — nothing pending */ }
9413
+ } catch {
9414
+ // No queue on disk is nothing pending. A queue that is there and does not read may still owe a re-digest, so the
9415
+ // digest stays stale and the resume recomputes it, rather than being reconciled as though nothing were owed.
9416
+ if (existsSync(P.digestQueue)) exclude.add("register-digest");
9417
+ }
9318
9418
  const n = reconcileStamps(P.runDir, (label) => {
9319
9419
  const bare = label.replace(/:.*$/, "");
9320
9420
  const axis = label.includes(":") ? label.slice(label.indexOf(":") + 1) : null;
@@ -9829,7 +9929,7 @@ async function pipelineInner(job, opts = {}) {
9829
9929
  note(`\n=== clearotron-driver: ${run.slug} / ${run.date}-${run.codename} (agent=${agent}) ===`);
9830
9930
 
9831
9931
  // How the run ends delivered (run-delivered.mjs).
9832
- const { deliverWithoutTheAssessment, publishAndDeliver } = await deliveryEndState({ P, agent, ctx, job, run }, { applyScopeFrontMatterOf, archive, assessmentCoverageOfRun, localLanguageStateOf, reportIdentityRecord, searchLogAuditMd, sentinel, setAsideTheAssessment, writeScopeFactsOf });
9932
+ const { deliverWithoutTheAssessment, publishAndDeliver } = await deliveryEndState({ P, agent, ctx, job, run, opts }, { applyScopeFrontMatterOf, archive, assessmentCoverageOfRun, localLanguageStateOf, reportIdentityRecord, searchLogAuditMd, sentinel, setAsideTheAssessment, writeScopeFactsOf });
9833
9933
 
9834
9934
  // The clearance's own steps, in order, run by run-shell.mjs. A value one step hands a later one is held here, between
9835
9935
  // them; a step that returns a result ends the run with it. A failure in any step ends through run-failed.mjs.
@@ -9932,7 +10032,7 @@ async function pipelineInner(job, opts = {}) {
9932
10032
  } },
9933
10033
  { name: "overview-and-cards", run: async () => {
9934
10034
  // The report's overview and its cards (steps/overview-and-cards.mjs).
9935
- ({ applyRatedUnderFrontMatter, applyScopeFrontMatter, applyVerdictFrontMatter, assembledOrdinals, byRight, cardOrdinals, findingsForCards, groupedMembers, overviewOpen, rebuildTheDeliveredRecord, restoreTheBrokenRecord, rov, writeScopeFacts, writeUps } = await runOverviewAndCards({ P, applyCoverageFloor, clampOnTheWritersDuty, ctx, followTheRecordsActions, job, run, runState, saveTheLabel, writeVerdictSidecar }, { StageFailure, applyScopeFrontMatterOf, asPartNotCompleted, assembleReportMd, caseLawJoin, consolidateFindingsFile, correctionsTheRestoreLacks, deriveCommonLawCarry, deriveRecordCarry, inScopeClassList, injectDeferralCoverage, injectFrontMatter, injectLaneDepthCoverage, injectMeaningGapCoverage, injectScreenGateCoverage, injectScriptScopeCoverage, keepDeliveredRecordAsHistory, localLanguageStateOf, must, openAskForClosure, originRowsForReport, planWriteUps, readFindingsForReport, readReadingLog, rebuildDeliveredRecord, reportIdentityRecord, restoreTheRecordThatPassed, rewriteFromBeforeTheSeam, runBatched, safeReadJson, settleDerivedBases, stage, stampCoverageJudgmentRows, withdrawSupersededAudit, writeScopeFactsOf, writeShortEntries }));
10035
+ ({ applyRatedUnderFrontMatter, applyScopeFrontMatter, applyVerdictFrontMatter, assembledOrdinals, byRight, cardOrdinals, findingsForCards, groupedMembers, overviewOpen, rebuildTheDeliveredRecord, restoreTheBrokenRecord, rov, writeScopeFacts, writeUps } = await runOverviewAndCards({ P, applyCoverageFloor, clampOnTheWritersDuty, ctx, followTheRecordsActions, job, run, runState, saveTheLabel, writeVerdictSidecar }, { StageFailure, applyScopeFrontMatterOf, asPartNotCompleted, assembleReportMd, caseLawJoin, consolidateFindingsFile, correctionsTheRestoreLacks, deriveCommonLawCarry, deriveRecordCarry, inScopeClassList, injectDeferralCoverage, injectFrontMatter, injectLaneDepthCoverage, injectMeaningGapCoverage, injectScreenGateCoverage, injectScriptScopeCoverage, injectUncoveredMarketCoverage, keepDeliveredRecordAsHistory, localLanguageStateOf, must, openAskForClosure, originRowsForReport, planWriteUps, readFindingsForReport, readReadingLog, rebuildDeliveredRecord, reportIdentityRecord, restoreTheRecordThatPassed, rewriteFromBeforeTheSeam, runBatched, safeReadJson, settleDerivedBases, stage, stampCoverageJudgmentRows, withdrawSupersededAudit, writeScopeFactsOf, writeShortEntries }));
9936
10036
  } },
9937
10037
  { name: "delivery", run: async () => {
9938
10038
  // The checks before delivery, their repairs, and the publish (steps/delivery.mjs).
@@ -10049,6 +10149,7 @@ export function writeScopeFactsOf(ctx, P, runDir) { // @internal
10049
10149
  planExecution,
10050
10150
  coverageRows: loadCoverageLedger(runDir).rows,
10051
10151
  withheldQids: waitingFamilyStates(runDir, planExecution?.awaiting).withheld.map((f) => f.qid),
10152
+ markets: orderMarketsOf(ctx, plan),
10052
10153
  });
10053
10154
  facts.derived_from = Object.fromEntries([
10054
10155
  ["instructed_scope", P.instructedScope], ["register_plan", P.registerPlan],
@@ -10860,6 +10961,7 @@ function parseArgv(argv) {
10860
10961
  "--experiment": "experiment", "--model": "model", "--instructions": "instructions",
10861
10962
  "--label": "label", "--axis": "axis", "--dispatch-trigger": "dispatchTrigger", "--research": "research", "--records": "records" };
10862
10963
  for (let i = 0; i < argv.length; i++) {
10964
+ if (argv[i] === "--help" || argv[i] === "-h") { o.help = true; continue; }
10863
10965
  const key = flags[argv[i]];
10864
10966
  if (!key) {
10865
10967
  throw new Error(argv[i].startsWith("-")
@@ -11029,6 +11131,8 @@ export function resumeAdvice({ result = null, error = null, signal = null, jobPa
11029
11131
  return lines;
11030
11132
  }
11031
11133
 
11134
+ // What a reader who typed `clearotron run` is told; the developer usage below stays for `node driver/pipeline.mjs`.
11135
+ const RUN_USAGE = "usage: clearotron run --job <file.json> — runs one clearance from a job file. An example job is examples/job.euipo.json.";
11032
11136
  const USAGE = "usage: node pipeline.mjs --job <file.json> [--agent <id>]\n" +
11033
11137
  " [--resume <codename> [--from <stage>] [--records live|replay]]\n" +
11034
11138
  " [--resume <codename> --experiment <stage> [--model <id>] [--instructions <text>] [--axis <axis>] [--label <text>] [--dispatch-trigger <t>] [--research live|replay]]\n" +
@@ -11076,7 +11180,15 @@ if (isEntrypoint(import.meta.url)) void (async () => {
11076
11180
  let a;
11077
11181
  try { a = parseArgv(process.argv.slice(2)); }
11078
11182
  catch (e) { console.error(`error: ${e.message}`); console.error(USAGE); process.exit(2); }
11079
- if (!a.job && !a.codename) { console.error(USAGE); process.exit(2); } // --resume alone rebuilds the job below
11183
+ const usage = process.env.CLEAROTRON_INVOKED_AS ? RUN_USAGE : USAGE; // reached through `clearotron run`, or directly
11184
+ // Reached through `clearotron run`, the help keeps the dispatcher's spend line, which it printed before this
11185
+ // program had a --help of its own.
11186
+ if (a.help) {
11187
+ console.log(usage);
11188
+ if (process.env.CLEAROTRON_INVOKED_AS) console.log("THIS SPENDS: hours of model time and real register calls. See INSTALL.md §5 and §6.");
11189
+ process.exit(0);
11190
+ }
11191
+ if (!a.job && !a.codename) { console.error(usage); process.exit(2); } // --resume alone rebuilds the job below
11080
11192
  // composition guards
11081
11193
  if (a.fromStage && !a.codename) { console.error("error: --from requires --resume <codename>"); process.exit(2); }
11082
11194
  if (a.experiment && !a.codename) { console.error("error: --experiment requires --resume <codename>"); process.exit(2); }
@@ -11690,3 +11802,4 @@ export function reassembleFromTheRecord(P, findings, depth) { // @internal
11690
11802
  // Hoisted, so placed last: an import at the top would move every line citation into this file.
11691
11803
  import { commandLineRefusal } from "./run-requirements.mjs";
11692
11804
  import { runTables } from "./order-tables.mjs";
11805
+ import { axisTwin, followUpKinds, kindsForFollowUp } from "./follow-up-twins.mjs"; // when a written row stands in for a Follow-up row, as the page decides