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
@@ -156,6 +156,48 @@ export function recordGoodsProvenance(body) {
156
156
  return { operation: "undocumented", field: "none" };
157
157
  }
158
158
 
159
+ /**
160
+ * The goods of one official record body AS THE REGISTER HOLDS THEM, for a reader who asks for the original wording:
161
+ * [{classes, text, language, translation}], one entry per class statement. `text` is the statement in its own
162
+ * language, copied; `language` is that language where the record names it, else null; `translation` is the
163
+ * provider's machine translation with its language, or null. A provider's marker for no goods is no statement.
164
+ * PURE, over the same shapes recordGoods reads; a statement the record holds in several languages gives one entry
165
+ * per language.
166
+ */
167
+ export function recordGoodsAsRegistered(body) {
168
+ const b = Array.isArray(body) ? body[0] : body;
169
+ if (!b || typeof b !== "object") return [];
170
+ const out = [];
171
+ const lang = (l) => String(l ?? "").trim() || null;
172
+ const push = (classes, text, language, translation = null) => {
173
+ const t = String(text ?? "").trim();
174
+ if (!t || isNoGoodsMarker(t, language)) return;
175
+ out.push({ classes: [...new Set((classes ?? []).map(niceClass).filter(Boolean))], text: t, language: lang(language), translation });
176
+ };
177
+ if (Array.isArray(b.goodsServices)) {
178
+ for (const g of b.goodsServices) {
179
+ const tr = String(textOf(g?.translation) ?? "").trim();
180
+ push(g?.classes, textOf(g?.description), g?.language,
181
+ tr && !isNoGoodsMarker(tr, g?.translation_language) ? { text: tr, language: lang(g?.translation_language) } : null);
182
+ }
183
+ }
184
+ if (out.length === 0 && Array.isArray(b?._raw?.classifications))
185
+ for (const c of b._raw.classifications) push([c?.nice_class], c?.goods_services_text, c?.goods_services_language);
186
+ if (out.length === 0 && b.goodsAndServices != null) {
187
+ const gs = b.goodsAndServices;
188
+ if (typeof gs === "string") push([], gs, null);
189
+ else if (Array.isArray(gs)) {
190
+ for (const g of gs) {
191
+ if (typeof g === "string") { push([], g, null); continue; }
192
+ const classes = [g?.classNumber ?? g?.class ?? g?.niceClass ?? g?.nice_class];
193
+ if (Array.isArray(g?.description)) for (const d of g.description) push(classes, textOf(d), d?.language);
194
+ else push(classes, textOf(g?.description ?? g?.text ?? g?.goods), null);
195
+ }
196
+ }
197
+ }
198
+ return out;
199
+ }
200
+
159
201
  // THE RAW GOODS LIST SAYS NOTHING THE NORMALISED ONE DOES NOT. A Clarivate record holds its goods twice: as the
160
202
  // register wrote them (`_raw.goodsServices.intClassDescriptions`) and as the provider maps them, item for item,
161
203
  // into `goodsServices` beside it (providers/clarivate/src/core.js `normalizeGoodsServices`). On a crowded test
@@ -1867,7 +1867,10 @@ export function readJxLanes(doc) {
1867
1867
  return { recorded: true, asked: v.asked ?? null, ran: v.ran ?? null,
1868
1868
  shortfall: typeof v.shortfall === "boolean" ? v.shortfall : null,
1869
1869
  cause: typeof v.cause === "string" ? v.cause : null,
1870
- why: typeof v.why === "string" ? v.why : null };
1870
+ why: typeof v.why === "string" ? v.why : null,
1871
+ // A depth the record cannot confirm says so to the client in the owner's sentence; what the record does say,
1872
+ // slice by slice, rides beside it as `detail` (jx.mjs), and the scorer keeps it.
1873
+ ...(typeof v.detail === "string" ? { detail: v.detail } : {}) };
1871
1874
  })(),
1872
1875
  // ONLY the fold can state fold health. The declaration is frozen before the fold runs, so a
1873
1876
  // `degraded` there would be a health claim about work not yet done — the fallback leg that used
@@ -97,6 +97,7 @@ import { variantForms, VARIANT_RULES, VARIANT_CAP } from "./register-variants.mj
97
97
  import { isCapabilityGap } from "../providers/_shared/execute-plan.mjs";
98
98
  import { plainDeferralReason, plainCause } from "./deferral-row.mjs"; // — the reader's line for a count left open
99
99
  import { readJson } from "./run-record.mjs";
100
+ import { RunCancelled } from "./cancel.mjs";
100
101
 
101
102
  /** The three questions, in report order. `matchMode` is the provider-neutral predicate name.
102
103
  *
@@ -335,7 +336,10 @@ export async function countRegisterHits({
335
336
  const started = Date.now();
336
337
  let r;
337
338
  try { r = await counter(term, p, { classes: scoped, regions }); }
338
- catch (e) { r = { ok: false, total: null, reason: `count threw: ${String(e?.message ?? e).slice(0, 200)}` }; }
339
+ catch (e) {
340
+ if (e instanceof RunCancelled) throw e; // a stop is not a failed count: the run ends, and counts no more
341
+ r = { ok: false, total: null, reason: `count threw: ${String(e?.message ?? e).slice(0, 200)}` };
342
+ }
339
343
  const ok = Boolean(r?.ok) && Number.isFinite(r?.total);
340
344
  // A DISCLOSED APPROXIMATION IS AN ANSWER, AND IT WAS BEING READ AS A FAILURE. When the register
341
345
  // says "more than ten thousand", it has answered — it has answered with a floor instead of a
@@ -0,0 +1,39 @@
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
+ // register-reach.mjs — what the run's register service reaches, against the markets the order is for. PURE.
4
+ //
5
+ // A worldwide order's coverage line read "registers: worldwide (Signa)" while the service searches 15 offices, and
6
+ // whether a market outside them was named anywhere depended on what the writer chose to write: on three deliveries
7
+ // of one order, Vietnam was named on none. The line now states the reach and names the markets outside it, and code
8
+ // writes a "Not searched" row for each of those markets (owner, 2026-11-18).
9
+ //
10
+ // THE REACH IS THE SERVICE'S OWN CONTRACT: the covered office list its capabilities declare, which is the list it
11
+ // searches, and a market is outside it when the contract cannot translate it to an office. The coverage line and
12
+ // the rows both read this one answer, so they cannot disagree. A service that declares no office list (Corsearch)
13
+ // has no reach to state, and the answer is null.
14
+ import { capabilitiesFor } from "./register-capabilities.mjs";
15
+ import { territoryKey } from "./territory-tiers.mjs";
16
+
17
+ /**
18
+ * `{ service, offices, uncovered }` for a provider and the order's markets, or null when the provider declares no
19
+ * office list. `uncovered` keeps the markets' own order, folded to the territory vocabulary's codes, once each.
20
+ */
21
+ export function registerReach(providerId, markets = []) {
22
+ if (!providerId) return null;
23
+ let caps;
24
+ try { caps = capabilitiesFor(providerId); } catch { return null; }
25
+ const offices = caps?.offices;
26
+ if (!Array.isArray(offices?.covered) || !offices.covered.length || typeof offices.translate !== "function") return null;
27
+ const seen = new Set();
28
+ const uncovered = [];
29
+ for (const m of Array.isArray(markets) ? markets : []) {
30
+ const code = territoryKey(m);
31
+ if (!code || seen.has(code)) continue;
32
+ seen.add(code);
33
+ if (offices.translate(code) == null) uncovered.push(code);
34
+ }
35
+ return { service: caps.label ?? providerId, offices: offices.covered.length, uncovered };
36
+ }
37
+
38
+ /** The reason a code-written "Not searched" row gives, in the words approved for it (owner, 2026-11-18). */
39
+ export const NOT_COVERED_REASON = "the register service does not cover this office";
@@ -15,10 +15,11 @@
15
15
  // ordering, and renewal/expiry cycle arithmetic (renewals fall at year 10/20/… from registration — the
16
16
  // check that catches "registration 2013 … renewed 2025" from the document alone).
17
17
 
18
- import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, openSync, readSync, closeSync } from "node:fs"; import { runPrefixSpellings } from "../shared/pre-rename-spellings.mjs";
18
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, openSync, readSync, closeSync, fstatSync } from "node:fs"; import { runPrefixSpellings } from "../shared/pre-rename-spellings.mjs";
19
19
  import { join } from "node:path";
20
20
  import { ledgerPath, runRecordLogPath, ledgerDeprecationNotice, retiredGlobalRecordLogNotice }
21
21
  from "../providers/_shared/ledger-path.mjs";
22
+ import { normalizeRecordUri } from "../providers/_shared/record-uri.mjs"; // one record key for every reader of the record log
22
23
  import { recordedRegister } from "./engine/run-choices.mjs"; // the register the run recorded, which named its receipts
23
24
  import { envFrom } from "../shared/env-aliases.mjs"; // — resolves EITHER spelling; names the retired one because that is the live-writable half
24
25
  import { USE_SOURCE_QUALITY } from "./findings-model.mjs"; // — the attested vocabulary; an unknown value falls back to the heuristic
@@ -77,6 +78,10 @@ export function lineMayMatchRun(runPrefix) {
77
78
  // · a read that FAILS is reported. `catch { return map }` on a present, readable, correct file is an
78
79
  // absence presented as a pass — the exact class the hard rules exist for. The reason travels to the
79
80
  // caller, which logs it.
81
+ // · a line is DECODED WHOLE. Decoding each chunk on its own turned a character split by a chunk
82
+ // boundary into two replacement characters, and the garbled text reached the record bodies a run
83
+ // writes: on the two largest record logs of a test deployment, 7 and 6 lines (measured 2026-11-19). The split is
84
+ // on the newline byte, which never occurs inside a UTF-8 character, and each line is decoded once.
80
85
 
81
86
  const LEDGER_CHUNK = 8 * 1024 * 1024;
82
87
 
@@ -88,29 +93,47 @@ const LEDGER_CHUNK = 8 * 1024 * 1024;
88
93
  * a file that exists and cannot be read is.
89
94
  * Never throws: the callers are gates, and a gate that dies on telemetry is worse than one that reports.
90
95
  */
91
- export function forEachLedgerLine(path, onLine) {
96
+ export function forEachLedgerLine(path, onLine, { chunk = LEDGER_CHUNK } = {}) {
92
97
  let fd = null;
93
98
  try { fd = openSync(path, "r"); }
94
99
  catch (e) { return { lines: 0, error: e?.code === "ENOENT" ? null : `${e?.code ?? "read failed"}` }; }
95
100
  try {
96
- const buf = Buffer.allocUnsafe(LEDGER_CHUNK);
97
- let carry = "";
98
- let lines = 0;
99
- for (;;) {
100
- const n = readSync(fd, buf, 0, LEDGER_CHUNK, null);
101
- if (n <= 0) break;
102
- const text = carry + buf.toString("utf8", 0, n);
103
- const parts = text.split("\n");
104
- carry = parts.pop() ?? ""; // the tail may be a partial line; it rides to the next chunk
105
- for (const ln of parts) { if (ln.trim()) { onLine(ln); lines++; } }
106
- }
107
- if (carry.trim()) { onLine(carry); lines++; }
101
+ const { lines } = walkFd(fd, 0, chunk, onLine, onLine);
108
102
  return { lines, error: null };
109
103
  } catch (e) {
110
104
  return { lines: 0, error: String(e?.code ?? e?.message ?? "read failed").slice(0, 80) };
111
105
  } finally { try { closeSync(fd); } catch { /* nothing left to do about it */ } }
112
106
  }
113
107
 
108
+ /**
109
+ * Walk an open ledger from byte `start`: each complete line to `onLine`, then a last line with no newline, if any,
110
+ * to `onTail`. Returns the line count and `end`, the byte after the last newline read. Throws on a read failure.
111
+ */
112
+ function walkFd(fd, start, chunk, onLine, onTail) {
113
+ const buf = Buffer.allocUnsafe(chunk);
114
+ let carry = null; // the bytes after the last newline: a line still being read, kept as bytes
115
+ let lines = 0;
116
+ let pos = start; // where the next read starts
117
+ let end = start; // the byte after the last newline
118
+ const text = (bytes, from, to) => bytes.toString("utf8", from, to);
119
+ for (;;) {
120
+ const n = readSync(fd, buf, 0, chunk, pos);
121
+ if (n <= 0) break;
122
+ pos += n;
123
+ const data = carry ? Buffer.concat([carry, buf.subarray(0, n)]) : buf.subarray(0, n);
124
+ let from = 0;
125
+ for (let nl = data.indexOf(10, from); nl !== -1; nl = data.indexOf(10, from)) {
126
+ const ln = text(data, from, nl);
127
+ if (ln.trim()) { onLine(ln); lines++; }
128
+ from = nl + 1;
129
+ }
130
+ end += from; // `data` starts where the last newline left off
131
+ carry = from < data.length ? Buffer.from(data.subarray(from)) : null; // copied: the next read reuses `buf`
132
+ }
133
+ if (carry) { const ln = text(carry, 0, carry.length); if (ln.trim()) { onTail(ln); lines++; } }
134
+ return { lines, end };
135
+ }
136
+
114
137
  /** The last ledger read's failure reason, or null. Read by assembleRunRecords so the caller can LOG it. */
115
138
  let lastLedgerError = null;
116
139
  export const ledgerReadError = () => lastLedgerError;
@@ -155,6 +178,77 @@ export function collectRecordBodies(recordLogPath, runPrefix) {
155
178
  }
156
179
 
157
180
  // Each row of a log that belongs to the run, parsed, in file order. A read failure is noted for the caller.
181
+ // ── THE RECORD SET, READ FROM WHERE THE LAST ASSEMBLY STOPPED ──────────────────────────────────────────
182
+ //
183
+ // A run assembles its record set 8 to 14 times, and each assembly read the run's whole record log and the machine's
184
+ // whole call log from the first byte: about 2 s a pass on a test deployment's largest record log (292 MB, measured
185
+ // 2026-11-19), most of it the read itself. The logs are appended to, so what the last assembly folded still
186
+ // holds. The driver keeps the folded state per log and run, and reads only the lines appended since. The fold is
187
+ // the same fold over the same lines in the same order, so the state is the one a read from the start would give.
188
+ //
189
+ // IT STARTS AGAIN whenever the file is not the one it read: another inode (the writer rewrites a run's log
190
+ // through a rename), a size below where it stopped, or bytes before that point that are not the bytes it read.
191
+ // All three are checked on the descriptor it then reads, so a rename between check and read cannot slip past.
192
+ // A last line with no newline yet is folded into a copy, and read again next time, as a read from the start reads
193
+ // it. What a caller is given is built fresh on every call, so no caller can change what the next one is given: a
194
+ // record body is kept as the line it came on, and parsed again when it is handed out, the same parse a read from
195
+ // the start makes.
196
+ //
197
+ // IT IS BOUNDED BY SIZE, because the driver is one long-lived process and a record body is kept as its line. On a
198
+ // test deployment's largest record log (527 MB) the kept lines held 729 MB of heap between assemblies (measured
199
+ // 2026-11-19). The lines kept across every log stay under FOLDED_TEXT; a log whose own lines would pass it is not
200
+ // kept at all, and is read from the start each time, as before, and the least recent log goes first.
201
+ const FOLDED = new Map(); // `${kind}\0${path}\0${runPrefix}` → { ino, offset, mark, state }; insertion order is recency
202
+ let FOLDED_TEXT = 128 * 1024 * 1024; // characters of kept lines, across every log
203
+ /** @internal — set the bound, for the test that drives it, and return the one it replaced. */
204
+ export function setFoldedTextLimit(n) { const was = FOLDED_TEXT; FOLDED_TEXT = n; return was; }
205
+ /** @internal — the logs kept now, oldest first, with the characters each holds. */
206
+ export const foldedLogs = () => [...FOLDED].map(([key, e]) => ({ path: key.split("\0")[1], text: e.state?.text ?? 0 }));
207
+ const MARK_BYTES = 256;
208
+
209
+ function foldLedger(kind, path, runPrefix, { init, fold, copy, result, text = () => 0 }) {
210
+ const key = `${kind}\0${path}\0${runPrefix}`;
211
+ let entry = FOLDED.get(key) ?? null;
212
+ FOLDED.delete(key);
213
+ let fd = null;
214
+ try { fd = openSync(path, "r"); }
215
+ catch (e) { return { state: result(init()), read: noteLedger({ lines: 0, error: e?.code === "ENOENT" ? null : `${e?.code ?? "read failed"}` }) }; }
216
+ try {
217
+ const { ino, size } = fstatSync(fd);
218
+ if (entry && (entry.ino !== ino || size < entry.offset || !markHolds(fd, entry))) entry = null;
219
+ entry ??= { ino, offset: 0, mark: null, state: init() };
220
+ const mayMatch = lineMayMatchRun(runPrefix);
221
+ const rowOf = (line) => {
222
+ if (!mayMatch(line)) return null;
223
+ let row;
224
+ try { row = JSON.parse(line); } catch { return null; }
225
+ return runPrefix && rowMatchesRun(row, runPrefix) ? row : null;
226
+ };
227
+ const tail = [];
228
+ const { lines, end } = walkFd(fd, entry.offset, LEDGER_CHUNK, (line) => { const row = rowOf(line); if (row) fold(entry.state, row, line); }, (line) => tail.push(line));
229
+ entry.offset = end;
230
+ entry.mark = markAt(fd, end);
231
+ if (text(entry.state) <= FOLDED_TEXT) {
232
+ FOLDED.set(key, entry);
233
+ let held = [...FOLDED.values()].reduce((sum, e) => sum + text(e.state), 0);
234
+ for (const [k, e] of FOLDED) { if (held <= FOLDED_TEXT || k === key) break; held -= text(e.state); FOLDED.delete(k); }
235
+ }
236
+ const state = tail.length ? copy(entry.state) : entry.state;
237
+ for (const line of tail) { const row = rowOf(line); if (row) fold(state, row, line); }
238
+ return { state: result(state), read: noteLedger({ lines, error: null }) };
239
+ } catch (e) {
240
+ // What was folded before the failure goes out, uncached, with the reason: what a read from the start gave.
241
+ return { state: result(entry?.state ?? init()), read: noteLedger({ lines: 0, error: String(e?.code ?? e?.message ?? "read failed").slice(0, 80) }) };
242
+ } finally { try { closeSync(fd); } catch { /* nothing left to do about it */ } }
243
+ }
244
+ function markAt(fd, end) {
245
+ const n = Math.min(MARK_BYTES, end);
246
+ const b = Buffer.alloc(n);
247
+ if (n) readSync(fd, b, 0, n, end - n);
248
+ return b;
249
+ }
250
+ const markHolds = (fd, entry) => markAt(fd, entry.offset).equals(entry.mark ?? Buffer.alloc(0));
251
+
158
252
  function walkRunRows(path, runPrefix, onRow) {
159
253
  const mayMatch = lineMayMatchRun(runPrefix);
160
254
  noteLedger(forEachLedgerLine(path, (line) => {
@@ -166,10 +260,30 @@ function walkRunRows(path, runPrefix, onRow) {
166
260
  }));
167
261
  }
168
262
 
263
+ const bodyOf = (row) => (Array.isArray(row.body) ? row.body[0] : row.body);
169
264
  function foldBody(map, row) {
170
- const body = Array.isArray(row.body) ? row.body[0] : row.body;
265
+ const body = bodyOf(row);
171
266
  if (row.target && body && typeof body === "object") keepRecord(map, String(row.target).toLowerCase(), body);
172
267
  }
268
+ // keepRecord's rule over the lines the bodies came on: a body with content replaces, and one without replaces only
269
+ // a body without content. The line is kept, not the object, and parsed again when the record set is handed out.
270
+ function foldBodyLine(st, row, line) {
271
+ const body = bodyOf(row);
272
+ if (!row.target || !body || typeof body !== "object") return;
273
+ const uri = String(row.target).toLowerCase();
274
+ const content = recordBodyHasContent(body);
275
+ const held = st.bodies.get(uri);
276
+ if (!content && held?.content) return;
277
+ st.text += line.length - (held?.line.length ?? 0);
278
+ st.bodies.set(uri, { line, content, fresh: body });
279
+ }
280
+ // A body parsed by this read goes out as it is, once: nothing else holds it. After that it is parsed again from its
281
+ // line, so a read that found nothing new still hands out objects no earlier caller has.
282
+ function handOut(kept) {
283
+ const body = kept.fresh ?? bodyOf(JSON.parse(kept.line));
284
+ delete kept.fresh;
285
+ return body;
286
+ }
173
287
 
174
288
  // WP-receipts (2026-07-05): the fetch RECEIPT per record URI — when the record was pulled and under
175
289
  // which run context. Captured from the same record-body ledger rows the fetch ALREADY writes (zero new
@@ -193,26 +307,36 @@ function foldReceipt(map, real, row) {
193
307
  // The bodies and the receipts from ONE pass over the record log: the same two maps the two readers above
194
308
  // return, for the price of one read.
195
309
  export function collectRecordBodiesAndReceipts(recordLogPath, runPrefix) {
196
- const bodies = new Map();
197
- const receipts = new Map();
198
- const real = new Set();
199
- walkRunRows(recordLogPath, runPrefix, (row) => { foldBody(bodies, row); foldReceipt(receipts, real, row); });
200
- return { bodies, receipts };
310
+ const { state } = foldLedger("bodies", recordLogPath, runPrefix, {
311
+ init: () => ({ bodies: new Map(), receipts: new Map(), real: new Set(), text: 0 }),
312
+ fold: (st, row, line) => { foldBodyLine(st, row, line); foldReceipt(st.receipts, st.real, row); },
313
+ copy: (st) => ({ bodies: new Map(st.bodies), receipts: new Map(st.receipts), real: new Set(st.real), text: st.text }),
314
+ text: (st) => st.text,
315
+ result: (st) => ({
316
+ bodies: new Map([...st.bodies].map(([uri, kept]) => [uri, handOut(kept)])),
317
+ receipts: new Map([...st.receipts].map(([uri, receipt]) => [uri, { ...receipt }])),
318
+ }),
319
+ });
320
+ return state;
201
321
  }
202
322
 
203
323
  // Per-URI fetch call metadata (http_status / ok / cache_hit) from the CALL ledger the plugin already
204
324
  // writes — joined into receipts.json so "verified" is provable with the transport outcome attached.
205
325
  export function collectFetchCallMeta(callLogPath, runPrefix) {
206
- const map = new Map();
207
- walkRunRows(callLogPath, runPrefix, (row) => {
208
- if (row.tool !== "record_fetch" || !row.target) return;
209
- map.set(String(row.target).toLowerCase(), {
210
- ...(row.http_status !== undefined ? { http_status: row.http_status } : {}),
211
- ...(row.ok !== undefined ? { ok: row.ok } : {}),
212
- ...(row.cache_hit !== undefined ? { cache_hit: row.cache_hit } : {}),
213
- });
326
+ const { state } = foldLedger("fetches", callLogPath, runPrefix, {
327
+ init: () => new Map(),
328
+ fold: (map, row) => {
329
+ if (row.tool !== "record_fetch" || !row.target) return;
330
+ map.set(String(row.target).toLowerCase(), {
331
+ ...(row.http_status !== undefined ? { http_status: row.http_status } : {}),
332
+ ...(row.ok !== undefined ? { ok: row.ok } : {}),
333
+ ...(row.cache_hit !== undefined ? { cache_hit: row.cache_hit } : {}),
334
+ });
335
+ },
336
+ copy: (map) => new Map(map),
337
+ result: (map) => new Map([...map].map(([uri, meta]) => [uri, { ...meta }])),
214
338
  });
215
- return map;
339
+ return state;
216
340
  }
217
341
 
218
342
  // Archive the run's fetched records as individual artifacts — the auditor-visible substrate the A1 check
@@ -625,14 +749,8 @@ export function classifyUseSource(url, ownerName = "") {
625
749
  // use meter whose use_check source is a register mirror (register listing ≠ use evidence) — by URL
626
750
  // host OR by the model's own `quality` attestation, whichever is stricter. PURE
627
751
  // (mutates only the private `_status`/`_useSourceClass` display fields, like bindFindingsToRecords).
628
- // WP-receipts W2 (the VENZY join defect): meter sources sometimes arrive as FULL provider URLs
629
- // (https://tm.corsearch.com/mark/ae/229552) while the record set keys on /mark/ paths — without
630
- // normalization a genuinely FETCHED record demotes to "assumed" at render, with a false integrity
631
- // flag on top. Same broad id shape as pipeline.mjs CITED_URI_RE.
632
- export function normalizeRecordUri(src) {
633
- const m = String(src ?? "").trim().match(/\/mark\/[a-z]{2,6}\/[a-z0-9][a-z0-9_-]*/i);
634
- return m ? m[0].toLowerCase() : "";
635
- }
752
+ // The record key, kept beside the run record log's index so the two cannot drift (record-uri.mjs says why).
753
+ export { normalizeRecordUri };
636
754
 
637
755
  // ── spec 64 (B3) — opposition-window extraction ─────────────────────────────────────────────────────────
638
756
  // The DEMVENZY drop: teal-conduit recorded "CH opposition window open to 2026-07-13"; copper-causeway's
@@ -181,7 +181,7 @@ const correctiveRules = ({ narrative, findings, placement, rulingsTail, adds = f
181
181
  `CORRECT ONLY THE FLAGGED COVERAGE ACCOUNT. Preserve true, relevant coverage facts already in ${narrative}. Where a flagged passage mixes a true fact with an error, correct only the error; you may restate the supported part or correct its factual details from an identified record held at this step. Read that record before relying on it, and keep its question, territory, class, mode and outcome limits. A zero for one question is not a general absence of rights, and a failed, skipped or unread question is not a zero. If the supporting record is unavailable or does not settle the claim, remove the unsupported part and keep the uncertainty explicit. Reconcile the corresponding coverage fields. Do not reopen unrelated coverage, add a new search or claim more than the held record establishes.`,
182
182
  `IF YOU REMOVE THE SUPPORT FOR A CLAIM, THE CLAIM GOES WITH IT. Deleting the evidence and leaving the sentence standing does not make it safer, it makes it unsupported and therefore stronger than the record allows. A run was refused for exactly this.`,
183
183
  `1. Correct the flagged narrative sections — send back ONLY the sections a flag names, and every section the flags do not name is left out and comes back byte-identical;`,
184
- `2. mirror every correction into the finding objects the flags name (owner names, levels/composites, meters). A finding the review KILLS is not deleted: keep its object, set "disposition": "withdrawn" and add "withdrawn_reason": "<the review flag that killed it>". Add a "corrections": {"applied": true, "note": "<one line per flagged entity: corrected / withdrawn / no-change-because-…>"} marker inside the call's \`findings\` object.`,
184
+ `2. mirror every correction into the finding objects the flags name (owner names, levels/composites, meters). A finding the review KILLS is not deleted: keep its object, set "disposition": "withdrawn" and add "withdrawn_reason": "<the review flag that killed it>". If the right stands and only its rating is withdrawn, because its goods wording cannot be used, also set "rating_withdrawn_ground": "goods-wording-unavailable". When you withdraw a finding or maintain a record's declination, reassess the actions that depended on it, by their text and named parties as well as their ordinals. Remove an unsupported action or its unsupported part. Retain a party or a demand only where surviving evidence supports it; another live finding with a similar name is not that support by itself. Keep an otherwise eligible unidentified-proprietor lead visible through the existing open identification route, without restoring its withdrawn rating. Add a "corrections": {"applied": true, "note": "<one line per flagged entity: corrected / withdrawn / no-change-because-…>"} marker inside the call's \`findings\` object.`,
185
185
  // THE LINES THAT ARE NOT A FINDING. A coverage note, an action and the mark assessment carry no
186
186
  // ordinal, so step 2 cannot reach them, and nothing said where a rewrite of one goes: seven such
187
187
  // flags survived one clearance on the test box, each recorded as naming nothing (2026-09-11). The
@@ -189,7 +189,11 @@ const correctiveRules = ({ narrative, findings, placement, rulingsTail, adds = f
189
189
  // — and this names it. The coverage-account rule above forbids claims the held record does not establish;
190
190
  // a wording change keeps a note's facts and a factual error in one is corrected under that rule. The text
191
191
  // says both, or the seat reads the two as a conflict and does nothing, which is what it did.
192
- `3. A flag about a line the reader sees that is NOT a finding — a coverage row's "note", an action's "text", or the mark assessment's "distinctiveness" or "connotation" — is applied in the same PATCH, inside the call's \`findings\` object beside the "corrections" marker: send the complete \`coverage\` array (every row, the unflagged ones exactly as you last sent them), the complete \`actions\` array, or the complete \`mark_assessment\` object, with the flagged line rewritten. A row left out of the array is a row deleted, so send every row. A wording-only change to a coverage note preserves its area, state and supported facts. If the flag identifies a factual error, correct that error and any corresponding coverage fields under the flagged-coverage rule above; preserve the supported facts and the limits of the identified held record. Leave unrelated coverage unchanged. A flagged line you leave as written is named in the "corrections" note with the reason, as the flag names it — for example: the coverage line for "<area>": no-change-because …`,
192
+ // A STEP RESTING ON A CHANGED FINDING IS IN SCOPE, AND A ROW IS REMOVED ON PURPOSE. Step 2 withdraws a finding and
193
+ // step 3 reached only the lines a flag named, while telling the writer to send every row: in testing (2026-11-17) the
194
+ // correction kept steps whose support it had just rejected. Steps 2 and 3 now reassess those steps by their text and
195
+ // the parties they name, and the complete array still carries the change. Design's wording (2026-11-17).
196
+ `3. A flag about a line the reader sees that is NOT a finding — a coverage row's "note", an action's "text", or the mark assessment's "distinctiveness" or "connotation" — and actions dependent on a finding or disposition changed by the correction are applied in the same PATCH, inside the call's \`findings\` object beside the "corrections" marker: send the complete \`coverage\` array (every row, the unflagged ones exactly as you last sent them), the complete \`actions\` array, or the complete \`mark_assessment\` object, with the flagged line rewritten. A row omitted from an array is deleted. Preserve every unaffected row; remove an action, or its unsupported part, when its support has been rejected. Do not preserve an unsupported action merely to keep the array complete. A wording-only change to a coverage note preserves its area, state and supported facts. If the flag identifies a factual error, correct that error and any corresponding coverage fields under the flagged-coverage rule above; preserve the supported facts and the limits of the identified held record. Leave unrelated coverage unchanged. A flagged line you leave as written is named in the "corrections" note with the reason, as the flag names it — for example: the coverage line for "<area>": no-change-because …`,
193
197
  // THE ANSWERS THAT NAME THE FINDINGS. The four answers cite the findings they rest on by ordinal, and step 3 names
194
198
  // the other registers a correction may send but not this one, so a correction that raised a finding to High left
195
199
  // the third-party-rights answer naming findings 1 to 3 (test run, 2026-11-03). The transport always took it. Design's
@@ -230,7 +234,7 @@ export const REPAIR_COMPOSERS = [
230
234
  // name; the correction after the review of a repair is handed none, and its follow-up keeps the words for a replacement.
231
235
  compose: ({ findings, named, seniorEyeReview, adds = false }) => lines(
232
236
  `This is a fresh session: your earlier synthesis is not in your context, and the driver holds the record it last accepted from you. Your corrective pass updated the narrative but did NOT re-emit ${findings} — the structured findings record this correction updates. The review named: ${named.join(", ")}. Its flags are in ${seniorEyeReview}; open it and ${findings} for the findings it names.`,
233
- `Apply each flag to the finding objects it names: correct the fields, or set "disposition": "withdrawn" + "withdrawn_reason" for a killed finding, and add the "corrections": {"applied": true, "note": "…"} marker inside the call's \`findings\` object. Change only the flagged findings and the answers that depend on those changes.`,
237
+ `Apply each flag to the finding objects it names: correct the fields, or set "disposition": "withdrawn" + "withdrawn_reason" for a killed finding, and add the "corrections": {"applied": true, "note": "…"} marker inside the call's \`findings\` object. If the right stands and only its rating is withdrawn, because its goods wording cannot be used, also set "rating_withdrawn_ground": "goods-wording-unavailable". Change only the flagged findings and the answers that depend on those changes.`,
234
238
  `${ANSWERS_STEP}`,
235
239
  `Send the correction with \`record_synthesis\`, sending only the change: a PATCH call carrying \`findings_patch\` — ${patchRows(adds)} — and \`findings\` carrying the "corrections" marker and, when affected, the complete \`four_answers\` object. The driver merges this patch into the last accepted record, keeps the values the patch does not replace, and renders both files. There is no file for you to write or edit and nothing you write by hand is read.`,
236
240
  ),
@@ -130,11 +130,14 @@ const CITATION_CORRECTION = "The listed references point to findings that have b
130
130
  + "Reassess the affected answers, actions, and conclusions against the surviving findings. "
131
131
  + "Cite a surviving finding only where its evidence supports the statement; otherwise correct the statement. "
132
132
  + "Preserve unaffected work and record the corrections through the existing correction tool.";
133
+ // A forward step's repair adds design's instruction for the step itself (2026-11-17), word for word: a step is read by its
134
+ // text and the parties it names as well as its citations. The overview's repair keeps the general instruction alone.
135
+ const ACTION_REASSESSMENT = "Reassess the action's text as well as its citations, including each party it names. If its only support was withdrawn or rejected, remove the action; removing its citations or making it a run-level action does not preserve a valid basis. Where surviving evidence supports only part of an action, keep that part and remove the unsupported part, including names that belonged only to it. Do not restore a withdrawn finding or promote a declined record merely to introduce a name. Preserve any independently supported open identification task through the existing unidentified-proprietor route, with its held source and named open coverage row.";
133
136
 
134
137
  /** A forward step's citations in the same words, each reference naming the step that holds it. PURE. */
135
138
  function actionCitationDetail(cites) {
136
139
  const each = cites.map((c) => `action ${c.action}, finding ${c.ordinal} (${c.withdrawn ? "withdrawn" : "absent"})`);
137
- return `References: ${each.join("; ")}. ${CITATION_CORRECTION}`;
140
+ return `References: ${each.join("; ")}. ${CITATION_CORRECTION} ${ACTION_REASSESSMENT}`;
138
141
  }
139
142
 
140
143
  /** The overview's citation fault in words, for its repair. PURE. */
@@ -32,11 +32,12 @@ import { readFileSync, writeFileSync, readdirSync, existsSync, statSync } from "
32
32
  import { join, basename } from "node:path"; import { studioDirFor } from "../shared/pre-rename-spellings.mjs";
33
33
  import { homedir } from "node:os";
34
34
  import { validators } from "./verify.mjs";
35
- import { runLint, clientSummaryShape } from "./predelivery-lint.mjs"; import { emailConditionsOfReport } from "./publish/email-conditions.mjs"; // what the cover email carries
35
+ import { runLint, clientSummaryShape } from "./predelivery-lint.mjs"; import { emailConditionsOfReport } from "./publish/email-conditions.mjs"; import { readPartNotCompleted } from "./parts-not-completed.mjs"; // what the cover email carries, and whether the assessment completed
36
36
  import { config } from "./driver.config.mjs";
37
37
  import { GRID_HALVES } from "./common-law-receipts.mjs";
38
38
  import { isEntrypoint } from "../shared/is-entrypoint.mjs"; // — one entry-point test, all spellings
39
39
  import { DRIVER_DIR, paths, readJson } from "./run-record.mjs";
40
+ import { followUpKindsOf } from "./follow-up-twins.mjs"; // the search each deferred directive recorded
40
41
 
41
42
  // Artifact filename → verify.mjs validator key. notify receipts are trivial and skipped.
42
43
  const FILE_CHECKS = {
@@ -184,12 +185,12 @@ export function replayRun(runDir) {
184
185
  let verdictDoc = null;
185
186
  try { verdictDoc = readJson(paths(runDir).verdict); } catch { /* legacy run */ }
186
187
  const lint = runLint({
187
- reportMd, clientSummaryMd: csMd, narrativeMd,
188
+ reportMd, clientSummaryMd: csMd, narrativeMd, followUpKinds: followUpKindsOf(runDir),
188
189
  recordsByUri: recordsFor(runDir, reportMd + "\n" + csMd),
189
190
  searchedNames,
190
191
  headerName: shape.headerName || searchedNames.join(" / "),
191
192
  ratedNames: searchedNames,
192
- extraPlatformNames, verdictDoc, emailConditions: emailConditionsOfReport(reportMd, verdictDoc?.verdict),
193
+ extraPlatformNames, verdictDoc, emailConditions: emailConditionsOfReport(reportMd, verdictDoc?.verdict, { assessmentNotCompleted: readPartNotCompleted(runDir, "assessment") != null }),
193
194
  });
194
195
  out.predeliveryLint = lint.failures.length === 0
195
196
  ? "ok"
@@ -15,11 +15,12 @@ import { degradedParts, writeDegradedParts } from "./degraded-parts.mjs";
15
15
  import { config } from "./driver.config.mjs";
16
16
  import { registerAdapter } from "./engine/run-choices.mjs"; // the run's register adapter, from ctx.register
17
17
  import { note, runLog } from "./log.mjs";
18
+ import { markLogos, logosStep } from "./mark-logos.mjs";
18
19
  import { NOT_COMPLETED_DIR } from "./parts-not-completed.mjs";
19
20
  import { deliveryForRun } from "./profiles.mjs";
20
21
  import { finalStepFields, readRunStatus, recordTransition, signoffPatch, writeRunStatus } from "./progress.mjs";
21
22
  import { DEFAULT_LEDGER_PATH, tallyRegisterCalls } from "./provider-usage.mjs";
22
- import { composeEmailHtml, coverNoteOptions, deliverySubject, publishReport } from "./publish/index.mjs";
23
+ import { composeCoverNote, coverNoteInputs, deliverySubject, publishReport } from "./publish/index.mjs";
23
24
  import { noteRegisterServed, providerUsageCaveat, registersServedFrom } from "./register-served.mjs";
24
25
  import { renderReportOverview } from "./report-overview-record.mjs";
25
26
  import { atomicWrite } from "./run-record.mjs";
@@ -31,7 +32,7 @@ import { stampTokenRollup } from "./tokens.mjs";
31
32
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
32
33
  import { join } from "node:path";
33
34
 
34
- export async function deliveryEndState({ P, agent, ctx, job, run }, helpers) {
35
+ export async function deliveryEndState({ P, agent, ctx, job, run, opts = {} }, helpers) {
35
36
  const { applyScopeFrontMatterOf, archive, assessmentCoverageOfRun, localLanguageStateOf, reportIdentityRecord, searchLogAuditMd, sentinel, setAsideTheAssessment, writeScopeFactsOf } = helpers;
36
37
  // ── PUBLISHING AND DELIVERING: ONE PATH, FOR EVERY RUN THAT DELIVERS ─────────────────────────────────
37
38
  //
@@ -66,6 +67,10 @@ export async function deliveryEndState({ P, agent, ctx, job, run }, helpers) {
66
67
  const degraded = writeDegradedParts(run.runDir, degradedParts(run.runDir, { localLanguage }));
67
68
  runLog(run.runDir, { event: "degraded-parts", parts: degraded.parts.map((d) => ({ part: d.part, cause: d.cause })) });
68
69
  } catch (e) { runLog(run.runDir, { event: "degraded-parts-failed", cause: String(e?.message ?? e).slice(0, 200) }); }
70
+ // THE LOGOS, once the findings are final and before the page is built (mark-logos.mjs): one image request per
71
+ // cited registration whose record carries a logo, from this run's own register. It never stops the publish.
72
+ logosStep(run.runDir, await markLogos(run.runDir, { findingsPath: P.findings, provider: (() => { try { return registerAdapter(ctx.register ?? null); } catch { return null; } })(),
73
+ injectedFetcher: Boolean(opts.recordFetcher), agentId: agent }));
69
74
  published = await publishReport({
70
75
  runId: `${run.slug}-${run.date}-${run.codename}`, codename: run.codename,
71
76
  reportMd: P.report, auditMd: P.audit, findingsJson: P.findings, poolRoot: config.poolRoot, poolUrl: config.poolUrl,
@@ -195,11 +200,12 @@ export async function deliveryEndState({ P, agent, ctx, job, run }, helpers) {
195
200
  // name two different products. Null on a run with no sidecar ⇒ both surfaces say nothing rather
196
201
  // than asserting one.
197
202
  const emailProductName = reportIdentityFor(ctx.searchPolicy ?? null).identity;
198
- // The email's options, read from the run's frozen files by the publisher's one function (coverNoteOptions), which the
199
- // report document carries too: the verdict record as written and the band ladder. Read from the files rather than from
200
- // `published`, because a resume that finds the run already published has no document. The product's name stays the one
201
- // the subject takes, which names a run with no frozen policy as the legacy clearance it was.
202
- const emailVerdictOpts = { ...coverNoteOptions(run.runDir), productName: emailProductName ?? undefined };
203
+ // The email reads the run's report document from its record (composeCoverNote): the report's sections, the verdict
204
+ // record as written and the band ladder. Read from the record rather than from `published`, because a resume that finds
205
+ // the run already published has nothing in memory; a run published before the document existed is read from its files.
206
+ // The product's name stays the one the subject takes, which names a run with no frozen policy as the legacy clearance it was.
207
+ const cover = coverNoteInputs(run.runDir);
208
+ const emailVerdictOpts = { ...cover.opts, productName: emailProductName ?? undefined };
203
209
  // ONE report (spec 2026-07-30 §6): the cover note is a cover note — verdict, one-line summary, link.
204
210
  // A10 (addendum, 2026-07-30) NARROWS the old "machine-QC never on the email" rule rather than
205
211
  // restating it: surviving predelivery machine-check failures are enumerated on BOTH delivery
@@ -215,7 +221,7 @@ export async function deliveryEndState({ P, agent, ctx, job, run }, helpers) {
215
221
  // on the last thirty days of production, the report carries neither the heading nor that sentence since
216
222
  // that ruling, and the email carries both. The record is still written beside the report for the
217
223
  // reviewing lawyer; nothing reads it onto a client surface.
218
- writeFileSync(P.emailBody, composeEmailHtml(P.report, published.url, published.auditFile, emailNames, deliveryForRun(ctx), emailVerdictOpts));
224
+ writeFileSync(P.emailBody, composeCoverNote(cover, { url: published.url, auditFile: published.auditFile, names: emailNames, delivery: deliveryForRun(ctx), productName: emailVerdictOpts.productName }));
219
225
  // ctx.verdict is set BEFORE the packet is composed, because the packet's copy reads it.
220
226
  ctx.verdict = verdict;
221
227
  // DELIVERY (Phase 2). The driver writes a self-contained delivery packet and leaves
@@ -330,6 +330,7 @@ export function paths(runDir) {
330
330
  registerXcheck: p(driverRel("register-xcheck.json")),
331
331
  repairs: p(driverRel("repairs.json")),
332
332
  reportCardCalls: p(driverRel("report-card-calls")),
333
+ reportDocument: p(driverRel("report-document.json")), // the run's report as one document (publish/report-document.mjs)
333
334
  reportOverviewCalls: p(driverRel("report-overview-calls")),
334
335
  researchAnswers: p(driverRel("research-answers.jsonl")),
335
336
  reviewAfterRepair: p(driverRel("review-after-repair.md")),