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
@@ -8,21 +8,21 @@
8
8
  // This is deterministic Node — NOT an LLM turn — so it cannot hang/timeout. The driver calls it directly
9
9
  // (not via runStage). Run identity (runId/codename) comes from the driver's ctx.run; do NOT regenerate it.
10
10
  import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, chmodSync } from 'node:fs';
11
- import { finishPoolRun, grpRead, openPoolRun, refreshStaffPages } from './shell.mjs';
11
+ import { grpRead, publishRun } from './shell.mjs';
12
12
  import { join, dirname } from 'node:path';
13
13
  import { readFold } from '../record-fold.mjs'; import { parseReport, parseAudit, stripInternal, parseCaseLawProfiles, parseCaseLawPreamble, joinCaseLawProfiles } from './parse.mjs';
14
- import { renderHtml } from './render.mjs'; import { emailConditionsOf } from './email-conditions.mjs'; // the box's conditions, read the same way by the delivery check
14
+ import { renderClearanceDocument } from './render.mjs'; import { emailConditionsOf } from './email-conditions.mjs'; // the box's conditions, read the same way by the delivery check
15
15
  import { buildAudit } from './xlsx.mjs'; import { readDegradedPartRows, degradedPartRows, degradedAtPublish, storeStates, readDeliveredStores, mergeDegradedRows } from '../degraded-parts.mjs'; import { readDeclinations } from '../declination-tool.mjs'; import { frameSetAsideRows } from '../web-grid.mjs'; // — what synthesis set aside, with its grounds; and the stores the matter frame set aside, with its reason
16
16
  import { parseFindingsJson, parseFindingsJsonLenient, deriveDisplayVerdict, projectCoverageJudgment, COVERAGE_AREA_STATES } from '../findings-model.mjs';
17
17
  import { recordsOfDeliveredPositions } from '../declination-duty.mjs'; import { findingUris } from '../record-carry.mjs'; // — a position a finding delivers is not listed as set aside
18
18
  import { readStore, requiredAbsent, nonClosingAbsences } from './publish-inputs.mjs'; import { coverageFormStamp, readCoverageForm } from '../coverage-form-io.mjs'; import { readReleasedFamilies, readWithheldFamilies } from '../withheld-families.mjs'; import { unitLabel } from '../coverage-form.mjs'; import { coverageUnitLabel } from '../coverage-ledger.mjs'; import { recallReceiptForOwnCompany } from '../recall-receipt.mjs'; // — and why an absence did not close; whose recall checks an audit lists
19
- import { clearanceReportData } from './report-data.mjs';
19
+ import { clearanceReportDocument, clearanceReportDataOf, clearanceRatingOf, clearanceWorkbookOf } from './report-document.mjs'; // the run's report as one document, and what it carries
20
20
  import { searchDepthRecord, planTerritoriesOf, caseLawPassRecord } from './search-depth.mjs'; import { bandRecords } from '../named-band.mjs'; import { CASELAW_BRIDGES } from '../engine/mcp/gather-config.mjs'; // how much was read to reach the answer, as counts and tokens; and the case-law sources whose calls the court state reads
21
21
  import { parseFrameworkManifest } from '../framework.mjs'; import { readFrozenMethod, FROZEN_METHOD_FILE } from '../framework-method.mjs';
22
22
  import { rollupTokens, servedModels } from '../tokens.mjs';
23
23
  import { reportIdentityFor, productCoverageNote, isRegisterOnly } from '../search-policy.mjs';
24
24
  import { readRecordArtifacts, bindFindingsToRecords, joinEvidenceStatus } from '../registry-fidelity.mjs';
25
- import { deliveryFlagLines, deliveredFailure } from '../predelivery-lint.mjs';
25
+ import { deliveredFailure } from '../predelivery-lint.mjs';
26
26
  import { unrenderableConditions, clientStatement, clientConditions } from '../terminal-clamp.mjs'; // — the conditions that reach no client surface; the cover note's
27
27
  import { runLog } from '../log.mjs'; // — one line in the run record when one does
28
28
  import { PROVIDERS, config } from '../driver.config.mjs';
@@ -30,7 +30,7 @@ import { declaredRecordOrigins } from '../record-origins.mjs';
30
30
  import { NEUTRAL_DELIVERY, loadProfiles } from '../profiles.mjs';
31
31
  import { resolveDemoData, demoBannerMd } from './demo-marking.mjs'; // — one demo question, every product; 2134 — every SURFACE
32
32
  import { engineCommit } from '../engine-build.mjs';
33
- import { WARM_ROOT, WARM_ROOT_DARK, WARM_ROOT_DARK_EXPLICIT, THEME_INIT, THEME_INIT_EXPLICIT, FAVICON_LINK, BRAND } from '../../shared/brand.mjs'; import { TEXT_FONT_STYLE } from '../../shared/brand-fonts.mjs'; // the text face, carried in the page rather than fetched
33
+ import { WARM_ROOT, WARM_ROOT_DARK, WARM_ROOT_DARK_EXPLICIT, THEME_INIT, THEME_INIT_EXPLICIT, FAVICON_LINK, BRAND, EMAIL_TIER, EMAIL_COLOURS as EC, BAND_BY_TONE } from '../../shared/brand.mjs'; import { TEXT_FONT_STYLE } from '../../shared/brand-fonts.mjs'; // the text face, carried in the page rather than fetched
34
34
  import { NAV_CSS, siteNav, siteFab } from '../../shared/site-nav.mjs';
35
35
  import { anonAssets, anonClient, anonMark } from '../../shared/anon-overlay.mjs';
36
36
 
@@ -82,7 +82,7 @@ export function evaluateClientGate({ coverage = [], lintFailingIds = [], escalat
82
82
  // surfaces render from (the corrective pass left findings.json stale after a followup demand):
83
83
  // the client cards may carry facts the review already corrected or killed.
84
84
  if (Array.isArray(findingsStale) && findingsStale.length)
85
- push("findings-stale", `the reviewer's corrections did not reach the client-facing findings (${findingsStale.slice(0, 3).join(", ")}${findingsStale.length > 3 ? ", …" : ""}) — re-run the correction before this goes out`);
85
+ push("findings-stale", W.heldBecause.findingsStale(`${findingsStale.slice(0, 3).join(", ")}${findingsStale.length > 3 ? ", …" : ""}`));
86
86
  // (1) doc-35 close-the-loop: a core search layer in state "not-searched" NO LONGER closes the client
87
87
  // export. An in-scope channel a search layer CAN reach is a CLOSE target (run it) or a clean forward
88
88
  // action — never a ⛔ CLOSE-BEFORE-FILING banner. The gate now closes ONLY when the data cannot be
@@ -91,16 +91,16 @@ export function evaluateClientGate({ coverage = [], lintFailingIds = [], escalat
91
91
  // Plain English — these reasons are read by a lawyer, not the people who built the pipeline. The internal
92
92
  // axis ids stay in the run log / audit; the surfaced reason says what happened in words a reader understands.
93
93
  if (Array.isArray(escalationFailed) && escalationFailed.length)
94
- push("escalation-failed", `the main search didn't finish — it needs to be re-run before this can be relied on`);
94
+ push("escalation-failed", W.heldBecause.escalationFailed);
95
95
  // (3) internally-inconsistent registration facts survive in the delivered report (A2). record-coverage
96
96
  // (an unverified/unfetched URL, E1) is flag-only — it cannot change the answer, it just isn't confirmed.
97
97
  const ids = (lintFailingIds || []).map(String);
98
- if (ids.includes('registry-record-match')) push('lint:registry-record-match', 'a registration detail in the report does not match its official record');
99
- if (ids.includes('registry-arithmetic')) push('lint:registry-arithmetic', 'the registration counts in the report do not add up');
98
+ if (ids.includes('registry-record-match')) push('lint:registry-record-match', W.heldBecause.recordMismatch);
99
+ if (ids.includes('registry-arithmetic')) push('lint:registry-arithmetic', W.heldBecause.countsDoNotAddUp);
100
100
  // (3b) A1 — a finding the reviewer WITHDREW still appears on a delivered surface after the
101
101
  // redo attempts (ids are per-ordinal: correction-consistency:<ord> / :client:<ord>): the reader
102
102
  // would see a conflict the review already killed.
103
- if (ids.some((id) => id.startsWith('correction-consistency:'))) push('lint:correction-consistency', 'a conflict the reviewer withdrew still appears in the deliverable — the correction did not stick');
103
+ if (ids.some((id) => id.startsWith('correction-consistency:'))) push('lint:correction-consistency', W.heldBecause.withdrawnStillShown);
104
104
  // (3c) ION/copper-foundry (2026-07-22): the deliverable states a search tool was blocked/permission-denied.
105
105
  // That is not a disclosed gap — it is a false explanation for one, and it excused count-only sampling over
106
106
  // high-volume owner queries. It CANNOT be flag-only: a lawyer reading "the tool was blocked" reads
@@ -116,13 +116,13 @@ export function evaluateClientGate({ coverage = [], lintFailingIds = [], escalat
116
116
  // by-design exclusion, and either way the coverage has to be re-established.
117
117
  const isPermissionProse = (id) => id === 'permission-prose' || id.startsWith('permission-prose:');
118
118
  if (ids.some((id) => isPermissionProse(id) && !id.startsWith('permission-prose:narrative')))
119
- push('lint:permission-prose', 'the deliverable explains missing coverage by saying a search tool was blocked or lacked permission — on this configuration that is normally a by-design exclusion rather than an outage, so both the explanation and the coverage it excuses must be re-established before this can be relied on');
119
+ push('lint:permission-prose', W.heldBecause.permissionProse);
120
120
  // (4) the machine findings could not be parsed — the data-driven surfaces are unverifiable.
121
- if (findingsError) push('findings-unreadable', `the results could not be read back to build the report`);
121
+ if (findingsError) push('findings-unreadable', W.heldBecause.findingsUnreadable);
122
122
  // (5) A3 — a malformed finding was quarantined (dropped from the rendered set): the client export must never
123
123
  // ship silently missing a finding, so it closes for review (the internal report shows the exclusion + the audit records it).
124
124
  if (Array.isArray(quarantined) && quarantined.length)
125
- push('finding-quarantined', `a result could not be read and had to be set aside, so the report would be missing it`);
125
+ push('finding-quarantined', W.heldBecause.findingQuarantined);
126
126
  // (6) — A PUBLISH INPUT WAS NOT THERE AT ALL. Distinct from (4): findingsError means the file was
127
127
  // present and could not be read back, this means it was never there, and until this arm existed the
128
128
  // second case set no signal whatsoever — an absent findings.json produced findings=[]/coverage=[] and
@@ -135,14 +135,14 @@ export function evaluateClientGate({ coverage = [], lintFailingIds = [], escalat
135
135
  // the recording above it is what actually does the work today.
136
136
  const closing = requiredAbsent(inputsAbsent);
137
137
  if (closing.length)
138
- push('publish-input-absent', `a required input to this report was not there (${closing.join(', ')}) — the report was built without it, which is not the same as a search that found nothing`);
138
+ push('publish-input-absent', W.heldBecause.inputAbsent(closing.join(', ')));
139
139
  return { released: reasons.length === 0, reasons, reasonCodes, inputsAbsent: [...(Array.isArray(inputsAbsent) ? inputsAbsent : [])], notClosing: nonClosingAbsences(inputsAbsent) }; // `notClosing` EXPLAINS a recorded absence that did not hold the release (publish-inputs.mjs nonClosingAbsences) — it decides nothing
140
140
  }
141
141
 
142
142
  // T3 (H3) — the machine-QC INPUT assembly. Mirrors publishReport's own reads exactly (the
143
143
  // strict→lenient findings degrade + the _driver sinks) so an out-of-band evaluation (tests, tooling)
144
144
  // judges with the same pair of eyes as publish. The pipeline preflight that used to call this is gone
145
- // (one report, spec 2026-07-30 §5) — publishReport's in-publish evaluation is the single live caller.
145
+ // (one report) — publishReport's in-publish evaluation is the single live caller.
146
146
  export function assembleReleaseInputs(reportMdPath, findingsJsonPath) {
147
147
  let coverage = [], quarantined = [], findingsError = null;
148
148
  const base = dirname(reportMdPath);
@@ -203,7 +203,7 @@ const INDEX_CSS = `
203
203
  th{background:var(--crimson-deep);color:#f0e8d8;font-size:11px;letter-spacing:.08em;text-transform:uppercase}
204
204
  tr:last-child td{border-bottom:none}
205
205
  .b{display:inline-block;color:#fff;font-weight:700;font-size:12px;padding:2px 9px;border-radius:999px}
206
- .b-mh,.b-l3{background:var(--h-amber)}.b-l4{background:var(--crimson)}.b-l2{background:var(--h-green)}.b-l1{background:var(--h-grey)}
206
+ .b-clear{background:var(--clear);color:var(--clear-on)}.b-low,.b-l2{background:var(--low);color:var(--low-on)}.b-med,.b-mh,.b-l3{background:var(--med);color:var(--med-on)}.b-high,.b-l4{background:var(--high);color:var(--high-on)}.b-severe{background:var(--severe);color:var(--severe-on)}.b-l1{background:var(--h-grey)}
207
207
  .stmt{display:block;margin-top:3px;font-size:11.5px;color:var(--muted,#6b5d50);max-width:340px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
208
208
  .hold{display:inline-block;background:var(--crimson);color:#fff;font-weight:700;font-size:11px;padding:1px 7px;border-radius:999px;margin-left:6px} .disc{display:inline-block;border:1px solid var(--line);color:var(--muted);font-size:11px;padding:1px 7px;border-radius:999px;margin-left:6px}
209
209
  .hpill{display:inline-block;color:#fff;font-weight:700;font-size:11.5px;padding:3px 11px;border-radius:999px;white-space:nowrap}
@@ -233,7 +233,7 @@ function indexRows(runs, { reportFile, linkPrefix = '', showAudit = true, client
233
233
  return runs.map(r => {
234
234
  // Machine-QC state (meta.clientGate is the historical stamp name): a STAFF-surface pill pointing the
235
235
  // reviewer at the audit workbook. It no longer decides anything — one report, always listed, always
236
- // linked (spec 2026-07-30 §5); the delivery-language "⛔ on hold" pill is retired with the split.
236
+ // linked; the delivery-language "⛔ on hold" pill is retired with the split.
237
237
  const qcFailed = !client && r.clientGate && r.clientGate.released === false;
238
238
  // Demo anonymisation (inert on the client-facing per-customer index — no overlay there): the matter
239
239
  // (slug) + project (title) are marks → blur; the report/audit links carry the slug in the runId → the
@@ -251,7 +251,7 @@ function indexRows(runs, { reportFile, linkPrefix = '', showAudit = true, client
251
251
  <td>${matterCell}</td>
252
252
  <td>${anonMark(r.title, { key: ck, run: r.runId })}</td>
253
253
  <td>${anonClient(r.client, ck)}</td>
254
- <td><span class="b b-${attrValue(r.badge)}">${esc(r.overall)}</span>${qcFailed ? ' <span class="hold" title="machine QC checks failed — see the audit workbook">⚠ QC</span>' : ''}${!client && !qcFailed && r.clientGate?.inputsAbsent?.length ? ` <span class="disc" title="${escAttr(`published without ${r.clientGate.inputsAbsent.join(', ')} — each declared optional, so the release stands; the report was built without it`)}">◦ built without an input</span>` : ''}${
254
+ <td><span class="b b-${attrValue(bandClassOf(r))}">${esc(r.overall)}</span>${qcFailed ? ' <span class="hold" title="machine QC checks failed — see the audit workbook">⚠ QC</span>' : ''}${!client && !qcFailed && r.clientGate?.inputsAbsent?.length ? ` <span class="disc" title="${escAttr(`published without ${r.clientGate.inputsAbsent.join(', ')} — each declared optional, so the release stands; the report was built without it`)}">◦ built without an input</span>` : ''}${
255
255
  // The report's own conclusion beside the band pill (ruled 2026-09-22: the report is the master),
256
256
  // never a second summary. A meta.json written before the caption was kept shows the pill alone:
257
257
  // its stored statement could say "on hold", which was never true. The pill carries the rating,
@@ -263,7 +263,7 @@ function indexRows(runs, { reportFile, linkPrefix = '', showAudit = true, client
263
263
  }).join('\n');
264
264
  }
265
265
 
266
- // ONE report (spec 2026-07-30 §5): the "Review & iteration version · internal" / "Clean final version ·
266
+ // ONE report: the "Review & iteration version · internal" / "Clean final version ·
267
267
  // client-facing" header pills are retired with the split they printed on the page. Both indexes link the
268
268
  // same report.html; what still differs between them is audience presentation (staff nav/filter/audit
269
269
  // column vs the customer page's date-only rows and explicit-light theme), not the document.
@@ -285,9 +285,9 @@ function clientFilterBar(clients) {
285
285
  // per-customer indexes — customer/generic already holds >20 runs). Ships `hidden`: no-JS pages degrade to
286
286
  // the flat, fully-visible table with no dead buttons.
287
287
  const PAGER_BAR = `<div class="pager" id="pager" hidden>
288
- <button type="button" id="pgPrev">&#8249; Prev</button>
288
+ <button type="button" id="pgPrev">&#8249; ${IX.previous}</button>
289
289
  <span class="pcount" id="pcount"></span>
290
- <button type="button" id="pgNext">Next &#8250;</button>
290
+ <button type="button" id="pgNext">${IX.next} &#8250;</button>
291
291
  </div>`;
292
292
 
293
293
  // Report search — a text box that filters rows by their content (matter, project, verdict, date), composing
@@ -295,9 +295,9 @@ const PAGER_BAR = `<div class="pager" id="pager" hidden>
295
295
  // PAGER_SCRIPT reveals it only when the table is large enough to warrant searching (>8 rows). Emitted on every
296
296
  // index (staff + per-customer), so it scales the client-facing matter history to many reports.
297
297
  const SEARCH_BAR = `<div class="filterbar" id="repSearchBar" hidden>
298
- <label class="flbl" for="repSearch">Search</label>
299
- <input id="repSearch" type="search" placeholder="Filter by matter, project or verdict…" autocomplete="off" aria-label="Filter reports">
300
- <span class="nomatch" id="repNoMatch" hidden>No matching reports</span>
298
+ <label class="flbl" for="repSearch">${IX.search}</label>
299
+ <input id="repSearch" type="search" placeholder="${IX.searchPlaceholder}" autocomplete="off" aria-label="${IX.searchLabel}">
300
+ <span class="nomatch" id="repNoMatch" hidden>${IX.noMatch}</span>
301
301
  </div>`;
302
302
 
303
303
  // One apply() = filter-then-page. Rows are queried LAZILY on every pass (the parse-time cache was the
@@ -333,9 +333,9 @@ if(!bar)return;
333
333
  bar.hidden=!paged&&!active;
334
334
  prev.hidden=next.hidden=!paged;
335
335
  prev.disabled=page<=1;next.disabled=page>=P;
336
- var t=paged?(a+1)+"\\u2013"+b+" of "+M:String(M);
337
- if(active)t+=" shown";
338
- if(active&&fold)t+=" \\u00b7 "+fold+" retired";
336
+ var t=paged?(a+1)+"\\u2013"+b+${JSON.stringify(IX.of)}+M:String(M);
337
+ if(active)t+=${JSON.stringify(IX.shown)};
338
+ if(active&&fold)t+=" \\u00b7 "+fold+${JSON.stringify(IX.retired)};
339
339
  cnt.textContent=(active||paged)?t:"";
340
340
  }
341
341
  if(sbar&&document.querySelectorAll("tr[data-client]").length>8)sbar.hidden=false;
@@ -361,7 +361,7 @@ ${TEXT_FONT_STYLE}${FAVICON_LINK}${client ? THEME_INIT_EXPLICIT : THEME_INIT}
361
361
  ${SEARCH_BAR}
362
362
  ${filter}
363
363
  <table>
364
- <tr><th>Matter</th><th>Project</th><th>Client</th><th>Overall</th><th>Run</th>${auditCol ? '<th>Audit</th>' : ''}</tr>
364
+ <tr><th>${IX.columns.matter}</th><th>${IX.columns.project}</th><th>${IX.columns.client}</th><th>${IX.columns.overall}</th><th>${IX.columns.run}</th>${auditCol ? `<th>${IX.columns.audit}</th>` : ''}</tr>
365
365
  ${rows}
366
366
  </table>
367
367
  ${PAGER_BAR}
@@ -400,7 +400,7 @@ ${indexRows(archivedRuns, { reportFile: 'report.html', showAudit: true })}
400
400
 
401
401
  // Rebuild the pool index from every run's meta.json (newest first): the STAFF all-runs index (links
402
402
  // report.html + audit) AND, additively (D3), one per-customer index per account linking the SAME
403
- // report.html — one report (spec 2026-07-30 §5); the per-customer pages differ in chrome, not document.
403
+ // report.html — one report; the per-customer pages differ in chrome, not document.
404
404
  export function regenIndex(poolDir) {
405
405
  const runs = readdirSync(poolDir, { withFileTypes: true })
406
406
  .filter(d => d.isDirectory() && d.name !== 'customer' && existsSync(join(poolDir, d.name, 'meta.json')))
@@ -461,7 +461,7 @@ export function regenIndex(poolDir) {
461
461
  try { chmodSync(idx, 0o640); } catch { /* best-effort; group-read via set-gid pool */ }
462
462
 
463
463
  // D3 — per-customer indexes at customer/<key>/index.html: only that account's runs, linking THE report
464
- // (report.html — one report, spec 2026-07-30 §5) two levels up. The page is template-identical to the
464
+ // (report.html — one report) two levels up. The page is template-identical to the
465
465
  // staff index minus the staff chrome. NO staff nav here — internal surfaces never reach a
466
466
  // customer-facing page.
467
467
  // Do NOT chmod the customer dirs: they inherit the set-gid pool group (an explicit dir chmod here was the
@@ -479,13 +479,13 @@ export function regenIndex(poolDir) {
479
479
  const dir = join(poolDir, 'customer', key);
480
480
  mkdirSync(dir, { recursive: true }); // inherits the set-gid group; never chmod the dir
481
481
  const cidx = join(dir, 'index.html');
482
- // ONE report (spec 2026-07-30 §5): a run you have rights to is always listed and always linked. The
482
+ // ONE report: a run you have rights to is always listed and always linked. The
483
483
  // old clientGate suppression (a held run vanished from this page) is gone — the machine checks live
484
484
  // on the audit workbook now and decide nothing about who may read. The precedent is the knockout
485
485
  // lane's own collapse note: two renderings of one run is how the wrong link gets sent.
486
486
  writeFileSync(cidx, indexPage({
487
- heading: `Trademark clearance — ${displayOf.get(key) || key}`,
488
- sub: `${crs.length} report(s) for this account · access-controlled · noindex.`,
487
+ heading: IX.heading(displayOf.get(key) || key),
488
+ sub: IX.subheading(crs.length),
489
489
  rows: indexRows(crs, { reportFile: 'report.html', linkPrefix: '../../', showAudit: false, client: true }),
490
490
  auditCol: false,
491
491
  theme: 'client', // explicit-light: toggle only, NO @media auto-dark on a customer page
@@ -695,7 +695,7 @@ export async function readClearanceDocument({ runId, reportMd, auditMd, findings
695
695
  // input left NO trace anywhere: findings=[]/coverage=[]/findingsError=null is exactly what a search
696
696
  // that ran and found nothing produces, so "we read nothing" and "we read everything and it was clean"
697
697
  // were the same delivered artifact. Recording is the whole fix here — the gate withholds nothing
698
- // (spec 2026-07-30 §5) and the report's own face is the frozen renderer's, not this file's.
698
+ // and the report's own face is the frozen renderer's, not this file's.
699
699
  const inputsAbsent = [];
700
700
  // THE OVERALL ASSESSMENT NOT COMPLETED (driver/parts-not-completed.mjs). A stated state, read from the run's own
701
701
  // record and never inferred from an absence: the report is built from what the run held, with no rating, no
@@ -745,8 +745,8 @@ export async function readClearanceDocument({ runId, reportMd, auditMd, findings
745
745
  : [];
746
746
  }
747
747
  coverage = withoutRepeatedRows(coverage); // one recorded row, repeated, prints once (see withoutRepeatedRows)
748
- // PR-9 (E9) — the STRING PROJECTION for coverage_judgment stays. mark_assessment is NO LONGER
749
- // projected on the RENDER path (spec 2026-07-30 §3): render.mjs takes the structured object and shows
748
+ // The STRING PROJECTION for coverage_judgment stays. mark_assessment is NO LONGER
749
+ // projected on the RENDER path: render.mjs takes the structured object and shows
750
750
  // the one-sentence `read` with the typed rows collapsed. projectAssessmentField/projectMarkAssessment
751
751
  // remain the projection for the workbook, report-data's client text, the lint and legacy string runs.
752
752
  const coverageJudgmentDisplay = projectCoverageJudgment(coverageJudgment);
@@ -757,7 +757,7 @@ export async function readClearanceDocument({ runId, reportMd, auditMd, findings
757
757
  // (materialized by the lint-pass assembleRunRecords); absent ⇒ empty map ⇒ a NO-OP (back-compat: archived /
758
758
  // replay runs with no record set keep the model's fields). The persisted findings.json copy above is the
759
759
  // model's original (kept for forensics); the records are archived alongside in _records/.
760
- const recordsByUri = runDir ? readRecordArtifacts(runDir) : new Map();
760
+ const recordsByUri = runDir ? readRecordArtifacts(runDir) : new Map(), logos = logosForReport(runDir), followUpKinds = followUpKindsOf(runDir); // and each cited registration's saved logo; none on a run that fetched none
761
761
  // WP-receipts W2 — the run's fetch-receipt index (written by assembleRunRecords). Its `provider` names
762
762
  // the register THIS run actually used — the link origin + label come from THAT provider's config, never
763
763
  // the currently-configured one (a re-published archive keeps its own register). Legacy runs: null ⇒
@@ -860,13 +860,7 @@ export async function readClearanceDocument({ runId, reportMd, auditMd, findings
860
860
  // which publishes without one: the throw left publishReport at `published → null` and the runner
861
861
  // exited 1. Reading from the report's own directory is also the right answer for a republish.
862
862
  const recallStore = readStore(runDir ?? dirname(reportMd), '_driver/register-recall.json');
863
- const undispatchedProbes = (recallReceiptForOwnCompany(recallStore.value)?.overflow ?? []) // never another company's remembered conflict
864
- .filter((o) => o && (o.term || o.qid))
865
- .map((o) => ({
866
- area: String(o.term ?? o.qid),
867
- state: 'not-searched',
868
- note: `over the cap, never dispatched (${String(o.qid ?? 'no probe id recorded')})`,
869
- }));
863
+ const undispatchedProbes = undispatchedProbeRows(recallReceiptForOwnCompany(recallStore.value)); // never another company's remembered conflict
870
864
  if (recallStore.state === 'damaged' && runDir) {
871
865
  try {
872
866
  runLog(runDir, { event: 'probe-over-cap-unreadable', store: recallStore.name, error: recallStore.error });
@@ -954,6 +948,20 @@ export async function readClearanceDocument({ runId, reportMd, auditMd, findings
954
948
  // rendering worldwide runs have always had: chips from the coverage ledger and the findings' own
955
949
  // regions — the citation focus, which is exactly what the worldwide notes beneath them promise.
956
950
  if (scopeBasis === 'worldwide') searchedJurisdictions = [];
951
+ // THE REGISTER SERVICE'S REACH, as the run recorded it when it stamped the coverage line (scope-facts.mjs): the
952
+ // service and how many offices it searched. Read, never recomputed, so a republish states what the line states.
953
+ // Null when the run recorded none, which is every run before the record and every service with no office list.
954
+ let registerReach = null;
955
+ {
956
+ const r = readStore(runDir ?? dirname(reportMd), '_driver/scope-facts.json').value?.register_reach;
957
+ if (typeof r?.service === 'string' && r.service && Number.isInteger(r.offices) && r.offices > 0) registerReach = { service: r.service, offices: r.offices };
958
+ }
959
+ // WHAT THE ORDER COVERED, for the register rows' head: 'worldwide', or 'named' for an order that names its
960
+ // countries, so the head does not call that search worldwide. Read from the same plan and instructed scope as the
961
+ // searched set above; null when the run's record cannot say.
962
+ const registerScope = scopeBasis === 'worldwide' ? 'worldwide'
963
+ : searchedJurisdictions.length && searchedJurisdictions.every((j) => !/^(worldwide|world|ww|global)$/i.test(String(j).trim())) ? 'named'
964
+ : null;
957
965
  // T7 (E5) — the case-law layer joins DETERMINISTICALLY (was: a prompt fished in the md and
958
966
  // hit 2 of 3 copper-spire cards): parse the grounded profiles, join by ordinal (fresh runs dictate
959
967
  // "- ord:") falling back to mark/owner (archived runs) — every matched card gets its strand.
@@ -964,7 +972,7 @@ export async function readClearanceDocument({ runId, reportMd, auditMd, findings
964
972
  if (existsSync(clPath)) {
965
973
  const clMd = readFileSync(clPath, 'utf8');
966
974
  caseLawByOrdinal = joinCaseLawProfiles(parseCaseLawProfiles(clMd), findings, readFold(runDir ?? dirname(reportMd))?.map?.modelToFolded ?? null);
967
- caseLawNotice = parseCaseLawPreamble(clMd); // session-wide outage notice — rendered once in §04
975
+ caseLawNotice = parseCaseLawPreamble(clMd); // session-wide outage notice — kept in the report document; no page prints it
968
976
  }
969
977
  } catch { /* no case-law layer this run */ }
970
978
  // T7 (E6) — the Corsearch enforcement telemetry (onomaticsAggression/oppositions, extracted
@@ -1035,7 +1043,7 @@ export async function readClearanceDocument({ runId, reportMd, auditMd, findings
1035
1043
  };
1036
1044
 
1037
1045
  // Machine QC (the evaluateClientGate checks — arithmetic, record fidelity, stale corrections). The
1038
- // checks SURVIVE; what they decide is gone: one report (spec 2026-07-30 §5), so they no longer choose
1046
+ // checks SURVIVE; what they decide is gone: one report, so they no longer choose
1039
1047
  // who may read anything. Evaluated HERE — before the audit workbook build — because the workbook is
1040
1048
  // where their result lands (a plain internal QC row) alongside the run telemetry; failures also stamp
1041
1049
  // meta.json for the staff index's ⚠ QC pill. The rendered report carries no banner either way, and a
@@ -1092,12 +1100,12 @@ export async function readClearanceDocument({ runId, reportMd, auditMd, findings
1092
1100
  } catch { /* no frozen profile — a legacy run keeps its wording */ }
1093
1101
 
1094
1102
  // Jurisdiction line for the Summary — searched register scope + the common-law surface layer.
1095
- const regScope = (searchedJurisdictions && searchedJurisdictions.length) ? searchedJurisdictions.join('/') : 'Worldwide';
1103
+ const regScope = (searchedJurisdictions && searchedJurisdictions.length) ? searchedJurisdictions.join('/') : W.jurisdictionLine.worldwide;
1096
1104
  const jurisdiction = registerOnly
1097
- ? `${regScope} (register only — no common-law / marketplace search)`
1105
+ ? W.jurisdictionLine.registerOnly(regScope)
1098
1106
  : noMarketplacesPicked
1099
- ? `${regScope} (register) + common-law (Western web / social, plus any stores chosen for this matter)`
1100
- : `${regScope} (register) + common-law (Western web / marketplace / social)`;
1107
+ ? W.jurisdictionLine.noMarketplaces(regScope)
1108
+ : W.jurisdictionLine.withCommonLaw(regScope);
1101
1109
 
1102
1110
  // Common-law URL-join: a grid hit whose candidate URL resolves to a finding's own link PROVES that search
1103
1111
  // term became a finding (rescues an anchor term whose finding wears a different name). Best-effort; absent
@@ -1140,7 +1148,7 @@ export async function readClearanceDocument({ runId, reportMd, auditMd, findings
1140
1148
  // The NAME is still never stored: the sidecar holds the product ID, and the string comes off
1141
1149
  // today's registry row on every render — which is what lets a renamed product re-render honestly.
1142
1150
  productName = reportIdentityFor(pol).identity ?? undefined;
1143
- // charter ruling 1 (2026-07-30) — the masthead names what this depth covers and what it omits,
1151
+ // The masthead names what this depth covers and what it omits (2026-07-30),
1144
1152
  // from the run's OWN frozen components. No sidecar ⇒ undefined ⇒ no strip (archived byte-identity).
1145
1153
  depthNote = productCoverageNote(pol) ?? undefined;
1146
1154
  } catch { stageLabel = undefined; depthNote = undefined; productName = undefined; }
@@ -1231,7 +1239,7 @@ export async function readClearanceDocument({ runId, reportMd, auditMd, findings
1231
1239
  bridges: CASELAW_BRIDGES,
1232
1240
  });
1233
1241
  })(),
1234
- registerPlan: rdJson(paths(runBase).registerPlan),
1242
+ registerPlan: rdJson(paths(runBase).registerPlan), planExecution: readStore(runBase, '_driver/plan-execution.json').value ?? null,
1235
1243
  laneDepthVerdicts,
1236
1244
  noMarketplacesPicked,
1237
1245
  });
@@ -1263,7 +1271,7 @@ export async function readClearanceDocument({ runId, reportMd, auditMd, findings
1263
1271
  // same reason: the fact exists on the way IN and was lost on the way out.
1264
1272
  //
1265
1273
  // The composer has a project picker, portal-service stamps `projectKey` onto the job, and freezeProfile
1266
- // records the key AND the resolved name in _driver/profile.json (spec 62). The sidecar does not travel
1274
+ // records the key AND the resolved name in _driver/profile.json. The sidecar does not travel
1267
1275
  // with a pool dir, so once a run was delivered nothing could say which matter it belonged to — not the
1268
1276
  // run list, not Clearances, not a report. "What was I working on" had no answer anywhere in the portal.
1269
1277
  //
@@ -1283,9 +1291,9 @@ export async function readClearanceDocument({ runId, reportMd, auditMd, findings
1283
1291
  return {
1284
1292
  parsed, fm, deliv, dates, issued, asOf, demoData, demoMd, inputsAbsent, findings, coverage, contextNotes,
1285
1293
  quarantined, findingsError, coverageJudgment, markAssessment, actionsRegister, askAnswers, correctionsDoc,
1286
- fourAnswers, findingsSchemaVersion, findingsKept, assessmentNotCompleted, coverageJudgmentDisplay, recordsByUri,
1294
+ fourAnswers, findingsSchemaVersion, findingsKept, assessmentNotCompleted, coverageJudgmentDisplay, recordsByUri, logos, followUpKinds,
1287
1295
  runProviderConf, recordOrigin, providerLabel, runOrigins, seniorRights, verdictInfo, droppedConditions,
1288
- undispatchedProbes, withheldFamilies, setAside, framework, frameworkMethod, scopeBasis, searchedJurisdictions,
1296
+ undispatchedProbes, withheldFamilies, setAside, framework, frameworkMethod, scopeBasis, searchedJurisdictions, registerReach, registerScope,
1289
1297
  planTerritories, caseLawByOrdinal, caseLawNotice, enforcerSignals, officeLinks, reviewReceipts, clientGate,
1290
1298
  fetchState, searchPolicy, registerOnly, noMarketplacesPicked, jurisdiction, commonLawJoinedTerms, stageLabel,
1291
1299
  depthNote, productName, publishParts, auditParsed, degradedRows, releasedFamilies, served, searchDepth, issuedAt,
@@ -1306,8 +1314,9 @@ export async function readClearanceDocument({ runId, reportMd, auditMd, findings
1306
1314
  // The headline caption as the front matter states it, empty as null. The email, the data file, meta.json and the run
1307
1315
  // record take it; the page takes the report's Summary instead (render.mjs).
1308
1316
  caption: fm.overall_caption || null,
1309
- // The email's options (coverNoteOptions): the delivery composes the email after publishing, from the same function.
1310
- cover: coverNoteOptions(runDir ?? dirname(reportMd)),
1317
+ // The verdict record as written, which the cover email reads. `verdictInfo` above is the record as the page reads it:
1318
+ // the two differ on a record older than the derived display fields, and where the assessment was not completed.
1319
+ verdictWritten: (() => { try { return readJson(paths(runDir ?? dirname(reportMd)).verdict); } catch { return null; } })(),
1311
1320
  };
1312
1321
  }
1313
1322
 
@@ -1324,92 +1333,98 @@ export async function readClearanceDocument({ runId, reportMd, auditMd, findings
1324
1333
  */
1325
1334
  // skipRegen — do NOT re-render index.html + the staff pages at the end. The batch backfill passes this and does
1326
1335
  // ONE regen after the whole loop instead of N redundant ones (per-run publish leaves it false, as before).
1327
- // (skipClient is retired with report.client.html — one report, spec 2026-07-30 §5.)
1328
- export async function publishReport({ runId, codename, reportMd, auditMd, findingsJson, poolRoot, poolUrl, customerKey, delivery, runDir, skipRegen = false }) {
1329
- const doc = await readClearanceDocument({ runId, reportMd, auditMd, findingsJson, poolRoot, poolUrl, customerKey, delivery, runDir });
1330
- const { parsed, fm, deliv, issued, asOf, demoData, demoMd, findings, coverage, contextNotes, findingsError,
1331
- coverageJudgment, markAssessment, actionsRegister, askAnswers, correctionsDoc, fourAnswers, findingsSchemaVersion,
1332
- findingsKept, assessmentNotCompleted, coverageJudgmentDisplay, recordsByUri, runProviderConf, recordOrigin, providerLabel,
1333
- runOrigins, seniorRights, verdictInfo, droppedConditions, undispatchedProbes, withheldFamilies, setAside, framework,
1334
- frameworkMethod, scopeBasis, searchedJurisdictions, planTerritories, caseLawByOrdinal, caseLawNotice, enforcerSignals,
1335
- officeLinks, reviewReceipts, clientGate, fetchState, searchPolicy, registerOnly, jurisdiction, commonLawJoinedTerms,
1336
- stageLabel, depthNote, productName, publishParts, auditParsed, degradedRows, releasedFamilies, served, searchDepth,
1337
- issuedAt, renderedAt, markName, project, organisation, tokenRollup, reportRoute, frozenStageLabel, ratingWord,
1338
- ratingBadge, caption } = doc;
1339
- const { poolRunDir, writeRO, copyRO, copyPart, buildWorkbook, writeDataFile } = openPoolRun(poolRoot, runId, { runDir });
1340
- // The pool's copy of report.md, marked as demo data where the document says it is (the answer and its argument are
1341
- // with `demoData` in readClearanceDocument).
1342
- writeRO('report.md', (demoMd ? `${demoMd}\n` : '') + stripInternal(readFileSync(reportMd, 'utf8'), { client: false }));
1343
- // The findings.json the document read, kept beside the report for forensics. A copy that fails leaves the report in
1344
- // place and is recorded, as a data file is (shell.mjs).
1345
- if (findingsKept) copyPart(findingsKept, 'findings.json');
1346
- if (auditMd && existsSync(auditMd)) copyRO(auditMd, 'audit.md'); // durable source (kept even if the xlsx fails)
1347
- let auditFile = null, counts = null, auditError = null;
1348
- // In the state the workbook is built even with no finding and no search log: it carries the part that was not
1349
- // completed, and the coverage the run did record.
1350
- if (findings.length || auditParsed || assessmentNotCompleted) {
1351
- ({ auditFile, auditError, built: counts } = await buildWorkbook(`${runId}-audit.xlsx`, async (at) => {
1336
+ // (skipClient is retired with report.client.html — one report.)
1337
+ export async function publishReport(input) {
1338
+ return publishRun(CLEARANCE_SHAPE, input);
1339
+ }
1340
+
1341
+ // The clearance's parts of the publishing order (shell.mjs publishRun).
1342
+ const CLEARANCE_SHAPE = {
1343
+ regenIndex, regenSurfaces,
1344
+ read: async ({ runId, reportMd, auditMd, findingsJson, poolRoot, poolUrl, customerKey, delivery, runDir, codename }) => ({
1345
+ doc: await readClearanceDocument({ runId, reportMd, auditMd, findingsJson, poolRoot, poolUrl, customerKey, delivery, runDir }),
1346
+ runId, codename, customerKey, reportMd, auditMd,
1347
+ }),
1348
+ keep({ writeRO, copyRO, copyPart }, { doc: { demoMd, findingsKept }, reportMd, auditMd }) {
1349
+ // The pool's copy of report.md, marked as demo data where the document says it is (the answer and its argument are
1350
+ // with `demoData` in readClearanceDocument).
1351
+ writeRO('report.md', (demoMd ? `${demoMd}\n` : '') + stripInternal(readFileSync(reportMd, 'utf8'), { client: false }));
1352
+ // The findings.json the document read, kept beside the report for forensics. A copy that fails leaves the report in
1353
+ // place and is recorded, as a data file is (shell.mjs).
1354
+ if (findingsKept) copyPart(findingsKept, 'findings.json');
1355
+ if (auditMd && existsSync(auditMd)) copyRO(auditMd, 'audit.md'); // durable source (kept even if the xlsx fails)
1356
+ },
1357
+ document: ({ doc, runId, codename, customerKey }) => clearanceReportDocument({ ...doc, runId }, { codename, customerKey }),
1358
+ warn: (what, e) => console.warn(`[report-document] ${what}: ${e?.message ?? e}`),
1359
+ async workbook({ buildWorkbook }, reportDocument, { doc: { findings, auditParsed, assessmentNotCompleted }, runId }) {
1360
+ // In the state the workbook is built even with no finding and no search log: it carries the part that was not
1361
+ // completed, and the coverage the run did record.
1362
+ if (!(findings.length || auditParsed || assessmentNotCompleted)) return { auditFile: null, auditError: null, built: null };
1363
+ return buildWorkbook(`${runId}-audit.xlsx`, async (at) => {
1352
1364
  // A10 — the failing predelivery checks ride into the workbook and are ENUMERATED on its Summary
1353
- // sheet (with the cover note, the delivery surfaces that reach the reviewing lawyer). The
1354
- // reviewReceipts assembly above claimed for two releases that these "land on the audit workbook's
1355
- // Review-receipts sheet"; nothing ever threaded them through — the sink was a flag nobody read.
1356
- // The workbook is handed the PROJECTED lines, never the checks: the audit download link rides in
1357
- // the same cover note that reaches a client principal, so it is a delivery surface under exactly
1358
- // the same rule (the workbook's own BANNED gate had already started firing on the raw detail —
1359
- // advisory, so CI stayed green). reviewReceipts.lint keeps its raw detail for the internal
1360
- // readers above (fetchState reads registry-record-coverage's URIs out of it).
1361
- const built = await buildAudit({ degradedParts: degradedRows, droppedConditions, undispatchedProbes, withheldFamilies, releasedFamilies, setAside, findings, frameworkMethod, coverage, contextNotes, coverageJudgment, markAssessment, corrections: correctionsDoc, fetchState, verdict: verdictInfo, jurisdiction, commonLawJoinedTerms, registerOnly, clientGate, lintFailures: deliveryFlagLines(reviewReceipts.lint), productName, registerPublishesRecordPages: runOrigins == null ? null : runOrigins.length > 0, recordLinks: officeLinks?.byUri ?? null, assessmentNotCompleted }, auditParsed, at, fm.title, fm);
1365
+ // sheet (with the cover note, the delivery surfaces that reach the reviewing lawyer), as their delivery
1366
+ // lines (clearanceWorkbookOf).
1367
+ const w = clearanceWorkbookOf(reportDocument);
1368
+ const built = await buildAudit(w.contract, w.audit, at, w.title, w.frontMatter);
1362
1369
  if (built?.gateViolations?.length) console.warn(`[audit-workbook] advisory: ${built.gateViolations.join(' | ')}`);
1363
1370
  return built;
1364
- })); // a REAL exception only — the report ships without the workbook, and nothing names it
1365
- }
1366
-
1371
+ }); // a REAL exception only — the report ships without the workbook, and nothing names it
1372
+ },
1373
+ surfaces({ writeRO, writeDataFile }, reportDocument, { doc: { searchDepth, recordsByUri, logos, deliv, demoData } }) {
1374
+ // THE report. The render receives no QC flags — the report a lawyer signs carries no
1375
+ // caveat banner (H1/H2); the receipts live on audit.xlsx. The machine QC above decides nothing
1376
+ // about this write.
1377
+ // homeHref — the floating "← All reports" pill returns to the listing (the staff index one level up).
1378
+ // NO SITE NAV IS BUILT FOR A REPORT. One was, from a walk of the pool on every publish, and handed to a
1379
+ // renderer that never read it; reports published before that carry one, and the portal still strips it.
1380
+ // How much was read to reach the answer, written where the document holds it (an additive record: a publish never
1381
+ // fails for want of it).
1382
+ if (searchDepth) { try { writeRO('search-depth.json', JSON.stringify(searchDepth, null, 2)); } catch { /* additive */ } }
1383
+
1384
+ writeRO('report.html', renderClearanceDocument(pageDocument(reportDocument), { recordsByUri, logos, homeHref: '../index.html', chromeHref: '../assets/chrome.css', delivery: deliv, demoData })); // the page reads the report document, with its surface beside it
1385
+ // ONE report: report.client.html is no longer written. The knockout lane's own
1386
+ // collapse note is the precedent: "two renderings of one run is how the wrong link gets sent". The
1387
+ // client host serves the same report.html through the portal's readReport() (cleaning built in) — its
1388
+ // repoint deployed before this change merged.
1389
+ //
1390
+ // The four-answers panel was once passed to BOTH renders. There is one render now, so `fourAnswers`
1391
+ // rides the one call — the panel reaches the client through the same cleaning path as every other
1392
+ // reader-facing block.
1393
+ // The clearance run as data: the client-cut projection the assistant drafts mail from, built from the
1394
+ // document (clearanceReportDataOf). BEST-EFFORT with a hard receipt rule: meta.reportSchema is stamped ONLY when the
1395
+ // file actually wrote, so a meta never names a data file that is not there. A producer throw never blocks the
1396
+ // report (the baked HTML above is already on disk).
1397
+ const reportSchema = writeDataFile('report-data.json', () => clearanceReportDataOf(reportDocument)) ? 'report-data/clearance-1' : null;
1398
+ return { reportSchema, template: deliv?.template ?? 'standard' };
1399
+ },
1400
+ // The run's record, from the document. A document that could not be built fails the publish here, after the page
1401
+ // and before the record, as a throw in the record always has.
1402
+ meta: (reportDocument, { template, reportSchema }) => clearanceMetaOf(reportDocument, { template, reportSchema }),
1403
+ result: ({ read: { doc: { reportRoute, findingsError, clientGate, caption }, runId, customerKey }, pool: { poolRunDir }, workbook: { auditFile, auditError, built: counts }, total }) => ({
1404
+ // THE PORTAL ROUTE, not the pool's directory layout. This was
1405
+ // `<origin>/<runId>/report.html` — where the documents sit on disk, which is not an application route.
1406
+ // Composed rather than spelled here so the report link is built the same way the audit link always was.
1407
+ runId, auditFile, counts, total, url: reportRoute, poolRunDir, auditError, findingsError, customerKey: customerKey || 'generic', clientGate,
1408
+ caption, // the report's own conclusion, for the run record's short surfaces
1409
+ }),
1410
+ };
1367
1411
 
1368
- // THE report. T4: the render receives no QC flags — the report a lawyer signs carries no
1369
- // caveat banner (H1/H2); the receipts live on audit.xlsx. The machine QC above decides nothing
1370
- // about this write.
1371
- // homeHref — the floating "← All reports" pill returns to the listing (the staff index one level up).
1372
- // The floating cross-page nav on the INTERNAL report too (jump to Archive/Status from a report).
1373
- // '../' prefix — a report lives one level down at <pool>/<runId>/report.html; existence-gating stays poolRoot-
1374
- // absolute. portal-report.mjs strips the nav at serve time (it lists every customer key).
1375
- // anon:false — the demo-privacy toggle is a STAFF-INDEX feature (its __ANON__ config + overlay JS are
1376
- // injected there only); on a report page the button rendered "Privacy ON" while doing nothing. Omit it
1377
- // rather than wire the overlay in: client names saturate privileged report prose — a partial blur is a
1378
- // worse demo than no toggle.
1379
- const reportNav = siteNav(poolRoot, 'report', null, '../', { anon: false });
1380
- // How much was read to reach the answer, written where the document holds it (an additive record: a publish never
1381
- // fails for want of it).
1382
- if (searchDepth) { try { writeRO('search-depth.json', JSON.stringify(searchDepth, null, 2)); } catch { /* additive */ } }
1383
-
1384
- writeRO('report.html', renderHtml(parsed, findings, coverage, { demoData, frameworkMethod, servedModels: served, productName, depthNote, scopeBasis, auditFile: auditFile || undefined, runId, delivery: deliv, recordsByUri, contextNotes, coverageJudgment: coverageJudgmentDisplay, markAssessment, fourAnswers, homeHref: '../index.html', nav: reportNav, chromeHref: '../assets/chrome.css', issued, asOf, verdictInfo, framework, searchedJurisdictions, planTerritories, caseLawByOrdinal, caseLawNotice, enforcerSignals, recordOrigin, recordOrigins: runOrigins, recordCitation: runProviderConf?.recordCitation ?? null, recordLinks: officeLinks?.byUri ?? null, providerLabel, seniorRights, findingsSchemaVersion, searchDepth, assessmentNotCompleted }));
1385
- // ONE report (spec 2026-07-30 §5): report.client.html is no longer written. The knockout lane's own
1386
- // collapse note is the precedent: "two renderings of one run is how the wrong link gets sent". The
1387
- // client host serves the same report.html through the portal's readReport() (cleaning built in) — its
1388
- // repoint deploys BEFORE this change merges (charter ruling 2a).
1389
- //
1390
- // P5 rebase note: this package was written against the pre-collapse tree, where the four-answers panel
1391
- // had to be passed to BOTH renders. There is one render now, so `fourAnswers` rides the one call — the
1392
- // panel reaches the client through the same cleaning path as every other reader-facing block.
1393
- // PR-9 — the clearance run as data (publish/report-data.mjs): the client-cut projection the assistant
1394
- // drafts mail from and the portal's native-render path reads. BEST-EFFORT with a hard receipt rule:
1395
- // meta.reportSchema is stamped ONLY when the file actually wrote — a run whose meta advertises a data
1396
- // file that is not there would break the portal's presence branch. A producer throw never blocks the
1397
- // report (the baked HTML above is already on disk).
1398
- const reportSchema = writeDataFile('report-data.json', () => clearanceReportData({
1399
- runId, codename, matter: fm.matter, markName, title: fm.title, customerKey: customerKey || 'generic',
1400
- issued, url: reportRoute,
1401
- // stageLabel REGISTRY-FIRST ( residual, audit item 4): `stageLabel` is reportIdentityFor's
1402
- // read-time derivation — the same label report.html renders — so a republished pre-renumber run
1403
- // cannot mint report.html "Depth 2" beside report-data.json "Stage 0.5". The frozen sidecar label
1404
- // is the LAST resort (a level today's registry no longer knows). meta.json below keeps the frozen
1405
- // stamp BY DESIGN — its readers re-derive.
1406
- auditFile, searchLevel: searchPolicy?.level ?? null, stageLabel: stageLabel ?? frozenStageLabel ?? null,
1407
- engineCommit: doc.engineCommit, servedModels: served,
1408
- framework, verdictInfo, findings, coverage, contextNotes, markAssessment, fourAnswers, askAnswers,
1409
- actions: actionsRegister, jurisdiction, searchedJurisdictions, scopeBasis, caption,
1410
- assessmentNotCompleted,
1411
- })) ? 'report-data/1' : null;
1412
- const total = finishPoolRun({ writeRO, poolRoot, skipRegen, regenIndex, meta: {
1412
+ /**
1413
+ * The run's record in the pool (meta.json), from the report document. `template`, the delivery's named variant, and
1414
+ * `reportSchema`, whether the data file wrote, are publishing's own facts and not the run's.
1415
+ */
1416
+ function clearanceMetaOf(document, { template, reportSchema }) {
1417
+ if (!document) throw new Error('the report document could not be built, so the run record cannot be written');
1418
+ const { run, verdict, client, reviewer, staff, build } = document;
1419
+ const fm = document.prose.frontMatter;
1420
+ const { runId, codename, markName, project, organisation, customerKey, issuedAt, auditFile } = run;
1421
+ const { renderedAt } = build;
1422
+ const served = client.servedModels, framework = document.framework.manifest, clientGate = reviewer.clientGate;
1423
+ const verdictInfo = verdict.record, assessmentNotCompleted = verdict.assessmentNotCompleted;
1424
+ // The rating word and its badge as the page states them (clearanceRatingOf). The headline caption, empty as null.
1425
+ const { word: ratingWord, badge: ratingBadge } = clearanceRatingOf(document);
1426
+ const caption = fm.overall_caption || null;
1427
+ return {
1413
1428
  runId, codename: codename || '', matter: fm.matter, title: fm.title, client: fm.client,
1414
1429
  // The mark as typed — see above. Distinct from `title`, which is the report's own headline.
1415
1430
  markName: markName ?? undefined,
@@ -1425,34 +1440,34 @@ export async function publishReport({ runId, codename, reportMd, auditMd, findin
1425
1440
  issuedAt,
1426
1441
  renderedAt,
1427
1442
  // WHICH BUILD produced this. null off a git checkout — a provenance stamp never fails a publish.
1428
- engineCommit: doc.engineCommit,
1443
+ engineCommit: build.engineCommit,
1429
1444
  // The models that served the run, named as a client may read them (tokens.mjs servedModels). Absent when
1430
1445
  // nothing was read, so a meta from before the record keeps its shape; [] when turns ran and named none a client may read.
1431
1446
  servedModels: served ?? undefined,
1432
- kind: 'clearance', recordLinks: officeLinks?.tally ?? undefined, // per office: linked, or cited by number and why; only where the register has no record pages
1433
- searchLevel: searchPolicy?.level ?? undefined,
1447
+ kind: 'clearance', recordLinks: client.recordLinks?.tally ?? undefined, // per office: linked, or cited by number and why; only where the register has no record pages
1448
+ searchLevel: run.product.level ?? undefined,
1434
1449
  // Display-only face of the level ("Depth 4"), frozen alongside it so the list can show which reads
1435
1450
  // have run on a name without the browser having to know the level registry.
1436
- stageLabel: frozenStageLabel ?? undefined,
1437
- recipe: searchPolicy?.recipe ?? undefined,
1438
- enqueuedVia: searchPolicy?.enqueuedVia ?? undefined,
1439
- enqueuedBy: searchPolicy?.enqueuedBy ?? undefined,
1440
- parentRunId: searchPolicy?.parentRunId ?? undefined,
1441
- tokens: (() => { const t = tokenRollup?.total; return t && (t.input || t.output || t.cacheRead || t.cacheWrite) ? t : undefined; })(),
1451
+ stageLabel: run.product.frozenStageLabel ?? undefined,
1452
+ recipe: run.provenance.recipe ?? undefined,
1453
+ enqueuedVia: run.provenance.enqueuedVia ?? undefined,
1454
+ enqueuedBy: run.provenance.enqueuedBy ?? undefined,
1455
+ parentRunId: run.provenance.parentRunId ?? undefined,
1456
+ tokens: (() => { const t = build.tokens; return t && (t.input || t.output || t.cacheRead || t.cacheWrite) ? t : undefined; })(),
1442
1457
  // delivery.template: the named deliverable-template variant this run used. Default "standard"
1443
1458
  // (today's render). Recorded here so the choice is observable + a live consumer of the profile field
1444
1459
  // (not a dead knob); the registry currently holds one variant, ready to grow when a 2nd format ships.
1445
- template: deliv?.template ?? 'standard',
1460
+ template,
1446
1461
  // T2 (H5): the derived display verdict is THE authority when the sidecar exists; the
1447
1462
  // model-authored fm fields are the pre-A2 legacy fallback only.
1448
1463
  // No rating at all in the state where the assessment was not completed, whatever a report's front matter says.
1449
1464
  overall: ratingWord,
1450
1465
  badge: ratingBadge, run: fm.run, date: dateOf(fm.run), auditFile,
1451
1466
  // WHY THERE IS NO WORKBOOK, when the build threw. Absent when it built, so such a meta is unchanged.
1452
- auditError: auditError ?? undefined,
1467
+ auditError: staff.auditError ?? undefined,
1453
1468
  // THE PARTS PUBLISHING FOUND DEGRADED, with their raw causes, which no cell carries. Absent when none.
1454
- degradedAtPublish: publishParts.length ? publishParts.map((d) => ({ part: d.part, name: d.name, cause: d.cause })) : undefined,
1455
- // spec 64 — THE one risk statement (band + stance in one sentence, composed once by the sidecar
1469
+ degradedAtPublish: staff.publishParts.length ? staff.publishParts.map((d) => ({ part: d.part, name: d.name, cause: d.cause })) : undefined,
1470
+ // THE one risk statement (band + stance in one sentence, composed once by the sidecar
1456
1471
  // writer). Absent on legacy runs — regenIndex re-reads every historical meta.json, so consumers
1457
1472
  // null-guard and old rows render byte-identically.
1458
1473
  statement: verdictInfo?.statement ?? undefined,
@@ -1476,18 +1491,11 @@ export async function publishReport({ runId, codename, reportMd, auditMd, findin
1476
1491
  clientGate: { released: clientGate.released, reasons: clientGate.reasons,
1477
1492
  inputsAbsent: clientGate.inputsAbsent?.length ? clientGate.inputsAbsent : undefined, notClosing: clientGate.notClosing?.length ? clientGate.notClosing : undefined,
1478
1493
  evaluationError: clientGate.evaluationError ?? undefined },
1479
- // PR-9 — present ⇒ report-data.json is beside the report and the portal can render natively (the
1480
- // same stamp the knockout lane writes; the consumer branch had readers before it had a writer).
1481
- // undefined on a producer miss, so the meta never advertises a file that is not there.
1494
+ // Present ⇒ report-data.json is beside the report, in the shape the string names
1495
+ // (`report-data/clearance-1`; a Knockout stamps `report-data/knockout-1`). undefined on a producer
1496
+ // miss, so the meta never advertises a file that is not there.
1482
1497
  reportSchema: reportSchema ?? undefined,
1483
- } });
1484
- await refreshStaffPages({ regenSurfaces, poolRoot, skipRegen, runDir });
1485
- // THE PORTAL ROUTE, not the pool's directory layout. This was
1486
- // `<origin>/<runId>/report.html` — where the documents sit on disk, which is not an application route.
1487
- // Composed rather than spelled here so the report link is built the same way the audit link always was.
1488
- const url = reportRoute;
1489
- return { runId, auditFile, counts, total, url, poolRunDir, auditError, findingsError, customerKey: customerKey || 'generic', clientGate,
1490
- caption }; // the report's own conclusion, for the run record's short surfaces
1498
+ };
1491
1499
  }
1492
1500
 
1493
1501
  // Compose the notification email body — MARKDOWN (the mail tool renders markdown→HTML; raw HTML gets escaped).
@@ -1499,12 +1507,13 @@ const BADGE_EMOJI = { l4: '🔴', l3: '🟠', mh: '🟠', l2: '🟢', l1: '⚪'
1499
1507
  // config, NOT a literal: this string was hardcoded, so the 2026-07-17 repo split rewrote it to a
1500
1508
  // example.com domain and both 2026-07-19 deliveries told the reader to sign in with an account that
1501
1509
  // does not exist. Unset ⇒ NO note: silence beats confidently wrong sign-in instructions.
1510
+ import { EMAIL, CLIENT_INDEX as IX, WORKBOOK as W } from './strings.mjs'; // kept down here, below every line the tree cites in this file by number
1502
1511
  export function accessNoteMd(domain = config.accessDomain) {
1503
- return domain ? `*Access-controlled — sign in with a **${domain}** account. Reply to this email with any questions.*` : '';
1512
+ return domain ? `*${EMAIL.accessNote(`**${domain}**`)}*` : '';
1504
1513
  }
1505
1514
  export function accessNoteHtml(font, domain = config.accessDomain) {
1506
1515
  return domain
1507
- ? `<p style="${font};font-size:9.5pt;color:#7a8290;margin:14px 0 0"><i>Access-controlled — sign in with a <b>${domain}</b> account. Reply to this email with any questions.</i></p>`
1516
+ ? `<p style="${font};font-size:9.5pt;color:${EC.quiet};margin:14px 0 0"><i>${EMAIL.accessNote(`<b>${domain}</b>`)}</i></p>`
1508
1517
  : '';
1509
1518
  }
1510
1519
 
@@ -1654,14 +1663,14 @@ export function composeEmailBody(reportMdPath, url, auditFile, productName = nul
1654
1663
 
1655
1664
  // A scannable meta line — only the fields that are present.
1656
1665
  const meta = [
1657
- fm.client && `**Client:** ${fm.client}`,
1658
- fm.classes && `**Classes:** ${fm.classes}`,
1659
- fm.run && `**Basis:** ${fm.run}`,
1666
+ fm.client && `**${EMAIL.client}** ${fm.client}`,
1667
+ fm.classes && `**${EMAIL.classes}** ${fm.classes}`,
1668
+ fm.run && `**${EMAIL.basis}** ${fm.run}`,
1660
1669
  ].filter(Boolean).join(' · ');
1661
1670
 
1662
1671
  const links = [
1663
- url && `[**▶ Open the full report**](${url})`,
1664
- auditUrl && `[Download audit (Excel)](${auditUrl})`,
1672
+ url && `[**${EMAIL.openReport}**](${url})`,
1673
+ auditUrl && `[${EMAIL.downloadAudit}](${auditUrl})`,
1665
1674
  ].filter(Boolean).join(' · ');
1666
1675
 
1667
1676
  return [
@@ -1686,9 +1695,9 @@ export function composeEmailBody(reportMdPath, url, auditFile, productName = nul
1686
1695
  // failure mode here was a pointer written before its target, and one true sentence beats two where
1687
1696
  // the second is a promise. When a surface exists that renders open floors in client language, this is
1688
1697
  // where the pointer to it belongs.
1689
- fm.envelope_note ? `**Search scope:** Some scoped searches remained open at delivery.` : '',
1698
+ fm.envelope_note ? `**${EMAIL.scopeLabel}** ${EMAIL.scopeOpen}` : '',
1690
1699
  fm.overall_label
1691
- ? `${dot} **Overall risk: ${fm.overall_label}**${fm.overall_caption ? `\n\n${fm.overall_caption}` : ''}`
1700
+ ? `${dot} **${EMAIL.overallRisk} ${fm.overall_label}**${fm.overall_caption ? `\n\n${fm.overall_caption}` : ''}`
1692
1701
  : '',
1693
1702
  meta || '',
1694
1703
  links || '',
@@ -1708,37 +1717,55 @@ export function composeEmailBody(reportMdPath, url, auditFile, productName = nul
1708
1717
  // ---------------------------------------------------------------------------------------------------
1709
1718
  const FONT = "font-family:Calibri,'Segoe UI',Arial,sans-serif";
1710
1719
 
1711
- // 5-tier reporting-template risk scheme — the whole left "NAME / RISK RATING" cell takes the bg colour.
1712
- // Matches skills/clearance-search/templates/search-request-form.html + knockout-searches/template-formatting.md.
1720
+ // 5-tier risk scheme on the report's ramp (shared/brand.mjs EMAIL_TIER) — the whole left "NAME / RISK RATING"
1721
+ // cell takes the bg colour, and `txt` colours a band's word on a light ground.
1713
1722
  // `txt` = a readable text-colour version of the tier (for the EXECUTIVE SUMMARY risk phrase, where a bright
1714
1723
  // fill like yellow/red is unreadable as text). Order matters: VERY HIGH before HIGH.
1724
+ const tier = (t, label) => ({ bg: t.bg, fg: t.fg, label, txt: t.txt });
1715
1725
  export const RISK_TIERS = [
1716
- [/VERY[\s-]?HIGH/, { bg: '#ff0000', fg: '#fff', label: 'VERY HIGH', txt: '#d10000' }],
1717
- [/HIGH/, { bg: '#ED7D31', fg: '#fff', label: 'HIGH', txt: '#c75b13' }],
1718
- [/MEDIUM/, { bg: '#ffff00', fg: '#000', label: 'MEDIUM', txt: '#9a8400' }],
1719
- [/MANAGEABLE/, { bg: '#70AD47', fg: '#fff', label: 'MANAGEABLE', txt: '#4e7a31' }],
1720
- [/LOW/, { bg: '#4472C4', fg: '#fff', label: 'LOW', txt: '#2f55a4' }],
1726
+ [/VERY[\s-]?HIGH/, tier(EMAIL_TIER.veryHigh, EMAIL.tiers.veryHigh)],
1727
+ [/HIGH/, tier(EMAIL_TIER.high, EMAIL.tiers.high)],
1728
+ [/MEDIUM/, tier(EMAIL_TIER.medium, EMAIL.tiers.medium)],
1729
+ [/MANAGEABLE/, tier(EMAIL_TIER.manageable, EMAIL.tiers.manageable)],
1730
+ [/LOW/, tier(EMAIL_TIER.low, EMAIL.tiers.low)],
1721
1731
  ];
1722
1732
  // doc 50 — the run's band LADDER (from opts.bands / meta.framework.bands): per-run vocabulary with the
1723
1733
  // same template palette keyed by TONE, so "Moderate" (house) and "Medium" (a customer ladder) both colour correctly
1724
1734
  // and a 5-band matrix framework (incl. "Low") lands on the same ramp. Set per compose; null = legacy.
1725
1735
  let EMAIL_BANDS = null;
1736
+ // THE INDEX'S BAND PILL TAKES THE REPORT'S RAMP: the run's band, its tone on the run's own frozen ladder, then
1737
+ // that tone's stop (2026-11-18). A run recorded before its ladder was kept falls back to its badge, a coarser
1738
+ // step: l2 reads as the low stop, l3 as medium, l4 as high, and l1, no rated band, stays grey.
1739
+ function bandClassOf(r) {
1740
+ const word = String(r?.overall ?? '').trim().toLowerCase();
1741
+ const tone = (Array.isArray(r?.framework?.bands) ? r.framework.bands : []).find((b) => String(b?.label ?? '').toLowerCase() === word)?.tone;
1742
+ return BAND_BY_TONE[tone] ?? r?.badge;
1743
+ }
1726
1744
  export const TONE_TIER = {
1727
- severe: { bg: '#ff0000', fg: '#fff', txt: '#d10000' },
1728
- high: { bg: '#ED7D31', fg: '#fff', txt: '#c75b13' },
1729
- medium: { bg: '#ffff00', fg: '#000', txt: '#9a8400' },
1730
- low: { bg: '#70AD47', fg: '#fff', txt: '#4e7a31' },
1731
- minimal: { bg: '#4472C4', fg: '#fff', txt: '#2f55a4' },
1745
+ severe: EMAIL_TIER.veryHigh,
1746
+ high: EMAIL_TIER.high,
1747
+ medium: EMAIL_TIER.medium,
1748
+ low: EMAIL_TIER.manageable,
1749
+ minimal: EMAIL_TIER.low,
1732
1750
  };
1751
+ /**
1752
+ * The gaps-sheet rows for the recall probes a run left over the cap. The probe id is the engine's: it stays in the
1753
+ * receipt and the run record, and the cell gets nothing in its place.
1754
+ */
1755
+ export function undispatchedProbeRows(receipt) {
1756
+ return (receipt?.overflow ?? [])
1757
+ .filter((o) => o && (o.term || o.qid))
1758
+ .map((o) => ({ area: String(o.term ?? o.qid), state: 'not-searched', note: W.overTheCap }));
1759
+ }
1733
1760
  export function riskTier(word) {
1734
1761
  const u = String(word || '').toUpperCase();
1735
1762
  if (EMAIL_BANDS) {
1736
1763
  const b = EMAIL_BANDS.find((x) => String(x.label).toUpperCase() === u);
1737
1764
  if (b) return { ...(TONE_TIER[b.tone] ?? TONE_TIER.medium), label: u };
1738
1765
  }
1739
- if (/NO RATED CONFLICTS/.test(u)) return { bg: '#4472C4', fg: '#fff', label: u, txt: '#2f55a4' };
1766
+ if (/NO RATED CONFLICTS/.test(u)) return tier(EMAIL_TIER.low, u);
1740
1767
  for (const [re, t] of RISK_TIERS) if (re.test(u)) return t;
1741
- return { bg: '#bfbfbf', fg: '#000', label: u || '—', txt: '#555' };
1768
+ return tier(EMAIL_TIER.unrated, u || '—');
1742
1769
  }
1743
1770
  // minimal inline markdown -> HTML for a table cell (escape FIRST; drop any stray internal ::p:: defensively)
1744
1771
  function cell(s) {
@@ -1777,23 +1804,70 @@ function mdBlock(block) {
1777
1804
  /**
1778
1805
  * THE EMAIL'S OPTIONS, read from the run's frozen files: the product's name off the frozen search policy, the verdict
1779
1806
  * record's sign-off word, conditions, rating and statement as the record wrote them, and the band ladder of the frozen
1780
- * framework. The report document carries them as `cover`, and the delivery passes them to composeEmailHtml, on a fresh
1781
- * publish and on a resume that finds the run already published. The statement is the record's own, which the run's status
1782
- * keeps; the report's surfaces print the client form. Never throws: a file it cannot read leaves its options out.
1807
+ * framework. The cover email reads them for a run published before the report document existed (coverNoteInputs). The
1808
+ * statement is the record's own, which the run's status keeps; the report's surfaces print the client form. Never throws: a
1809
+ * file it cannot read leaves its options out.
1783
1810
  */
1784
1811
  export function coverNoteOptions(runDir) {
1785
1812
  const frozen = (key, parse = JSON.parse) => { try { return parse(readFileSync(paths(runDir)[key], 'utf8')); } catch { return null; } };
1786
1813
  const opts = { productName: reportIdentityFor(frozen('searchPolicy')).identity ?? undefined };
1814
+ // The run's own record that its assessment did not complete decides, as it does for the page: then no verdict saved
1815
+ // by that assessment supplies a rating, and the rating stays unknown.
1816
+ if (readStore(runDir, '_driver/not-completed/assessment.json').state !== 'absent') return Object.assign(opts, frameworkBands(frozen), { assessmentNotCompleted: true, rating: null });
1787
1817
  const v = frozen('verdict');
1788
1818
  if (v) Object.assign(opts, { verdict: v.verdict, conditions: clientConditions(v), tier: v.tier, statement: v.statement ?? null });
1819
+ return Object.assign(opts, frameworkBands(frozen));
1820
+ }
1821
+
1822
+ /** The run's band ladder for the email, from its frozen framework; nothing where it has none. */
1823
+ function frameworkBands(frozen) {
1789
1824
  const framework = frozen('framework', parseFrameworkManifest);
1825
+ return framework ? { bands: framework.bands.map((b) => ({ label: b.label, tone: b.tone })) } : {};
1826
+ }
1827
+
1828
+ export function composeEmailHtml(reportMdPath, url, auditFile, names = [], delivery = NEUTRAL_DELIVERY, opts = {}) {
1829
+ return composeEmailHtmlFrom(parseReport(reportMdPath), url, auditFile, names, delivery, opts);
1830
+ }
1831
+
1832
+ /**
1833
+ * The cover email for a run, as the delivery sends it, from what coverNoteInputs read. `productName` is the name the
1834
+ * subject takes, which the caller resolves.
1835
+ */
1836
+ export function composeCoverNote({ report, opts }, { url, auditFile, names = [], delivery = NEUTRAL_DELIVERY, productName } = {}) {
1837
+ return composeEmailHtmlFrom(report, url, auditFile, names, delivery, { ...opts, productName });
1838
+ }
1839
+
1840
+ /**
1841
+ * What the cover email reads: the report's front matter and sections, and its options. From the run's report document
1842
+ * where it has one, and from the run's own files where it has none (a run published before the document existed).
1843
+ */
1844
+ export function coverNoteInputs(runDir) {
1845
+ let document = null;
1846
+ try { document = readJson(paths(runDir).reportDocument); } catch { /* a run published before the document */ }
1847
+ // A document written before it carried the verdict record as written is read from the files too.
1848
+ if (!document || !('written' in (document.verdict ?? {}))) return { report: parseReport(join(runDir, 'report.md')), opts: coverNoteOptions(runDir) };
1849
+ return { report: { fm: document.prose.frontMatter, secs: document.prose.sections }, opts: coverNoteOptionsOf(document) };
1850
+ }
1851
+
1852
+ /**
1853
+ * coverNoteOptions, read from the document: the verdict record and the rating as the page reads them, and the run's band
1854
+ * ladder. An older record gains its derived rating, as on the page, and a run whose assessment was not completed has no
1855
+ * record, so a verdict saved from that assessment raises neither a rating nor the close-box, and leaves the run's status no
1856
+ * statement. Where there is a record, the statement is the record's as written, which the run's status keeps.
1857
+ */
1858
+ function coverNoteOptionsOf(document) {
1859
+ const opts = { productName: document.run.product.name ?? undefined };
1860
+ if (document.verdict.assessmentNotCompleted === true) opts.assessmentNotCompleted = true;
1861
+ const v = document.verdict.record;
1862
+ if (v) Object.assign(opts, { verdict: v.verdict, conditions: clientConditions(v), tier: v.tier, statement: document.verdict.written?.statement ?? null });
1863
+ opts.rating = clearanceRatingOf(document).word ?? null;
1864
+ const framework = document.framework.manifest;
1790
1865
  if (framework) opts.bands = framework.bands.map((b) => ({ label: b.label, tone: b.tone }));
1791
1866
  return opts;
1792
1867
  }
1793
1868
 
1794
- export function composeEmailHtml(reportMdPath, url, auditFile, names = [], delivery = NEUTRAL_DELIVERY, opts = {}) {
1869
+ function composeEmailHtmlFrom({ fm, secs }, url, auditFile, names = [], delivery = NEUTRAL_DELIVERY, opts = {}) {
1795
1870
  EMAIL_BANDS = Array.isArray(opts?.bands) && opts.bands.length ? opts.bands : null; // doc 50 — per-run vocabulary
1796
- const { fm, secs } = parseReport(reportMdPath);
1797
1871
  const auditUrl = auditUrlFor(url, auditFile);
1798
1872
 
1799
1873
  // 1) internal review headline — short: the bottom line, and nothing of the reviewer's own notes.
@@ -1805,8 +1879,8 @@ export function composeEmailHtml(reportMdPath, url, auditFile, names = [], deliv
1805
1879
  // this goes with it.
1806
1880
  // The report link rides HIGH — right under the bottom line in the headline, not buried below the table.
1807
1881
  const reportLink = hrefAttr(url)
1808
- ? `<p style="margin:0 0 10px"><a href="${hrefAttr(url)}" style="color:#1a4fd6;font-weight:bold;font-size:12pt;text-decoration:none">▶ Open the full report</a>`
1809
- + (hrefAttr(auditUrl) ? ` &nbsp;·&nbsp; <a href="${hrefAttr(auditUrl)}" style="color:#3b4fd6;text-decoration:none">Download audit (Excel)</a>` : '')
1882
+ ? `<p style="margin:0 0 10px"><a href="${hrefAttr(url)}" style="color:${EC.reportLink};font-weight:bold;font-size:12pt;text-decoration:none">${EMAIL.openReport}</a>`
1883
+ + (hrefAttr(auditUrl) ? ` &nbsp;·&nbsp; <a href="${hrefAttr(auditUrl)}" style="color:${EC.auditLink};text-decoration:none">${EMAIL.downloadAudit}</a>` : '')
1810
1884
  + `</p>`
1811
1885
  : '';
1812
1886
  // The search-scope signal leads the email. The 2026-06-12 "lint flags do not render on the email" rule
@@ -1823,9 +1897,9 @@ export function composeEmailHtml(reportMdPath, url, auditFile, names = [], deliv
1823
1897
  // are one message in two renderings, and a client reading the HTML must not be told something the
1824
1898
  // markdown does not say.
1825
1899
  const flagBanner =
1826
- (fm.envelope_note ? `<p style="margin:0 0 6px"><b>Search scope:</b> Some scoped searches remained open at delivery.</p>` : '');
1900
+ (fm.envelope_note ? `<p style="margin:0 0 6px"><b>${EMAIL.scopeLabel}</b> ${EMAIL.scopeOpen}</p>` : '');
1827
1901
 
1828
- // ONE report (spec 2026-07-30 §6): the "Not client-ready — for your review only" block is deleted with
1902
+ // ONE report: the "Not client-ready — for your review only" block is deleted with
1829
1903
  // the two-bit delivery it narrated. The cover note is a cover note — verdict, one-line summary, link —
1830
1904
  // plus, since A10 (below), the surviving machine-check failures in the projection's own words. The
1831
1905
  // "machine-QC lives on the workbook, never the email" rule that used to stand here was written when a
@@ -1880,31 +1954,40 @@ export function composeEmailHtml(reportMdPath, url, auditFile, names = [], deliv
1880
1954
  // A BLOCKING RESULT KEEPS THE REPORT'S ITEMS TOO (ruled 2026-10-27). The box showed only on a CONDITIONAL result, so
1881
1955
  // a blocking one lost the client's own actions the report lists. It shows them under the report's heading in the
1882
1956
  // report's words, and only where the report names any: no empty box, no fallback line.
1883
- const emailConditions = emailConditionsOf(secs['Actions'], opts?.verdict);
1957
+ // AN ASSESSMENT THAT DID NOT COMPLETE HAS NO RESULT TO CONDITION (2026-11-19). Its box lists what the report lists under
1958
+ // "Before you can rely on this result", under that heading, in the report's order, and is left out where the report
1959
+ // names nothing there: a heading saying only the client can close these would claim more than the run knows.
1960
+ const notCompleted = opts?.assessmentNotCompleted === true;
1961
+ const emailConditions = emailConditionsOf(secs['Actions'], opts?.verdict, { assessmentNotCompleted: notCompleted });
1884
1962
  // THE REPORT IS THE MASTER (ruled 2026-09-22). The banner used to print a second summary composed
1885
1963
  // beside the report — "On hold — …" on a run the report called conditional, although nothing is ever
1886
1964
  // held — and before that the delivery gate's word. It now quotes the report: the rating, then the
1887
1965
  // report's own conclusion (below), and where the report names what only the client can close, those
1888
1966
  // items under the report's own heading. Nothing here composes a sentence of its own.
1889
- const closeBox = (items) => `<p style="margin:0 0 8px;padding:8px 10px;background:#fdeeee;border:1px solid #c98a86;color:#6e1512"><b>Only you can close these</b><br>${items.map((r) => `• ${cell(String(r))}`).join('<br>')}</p>`;
1890
- const verdictBound = opts?.verdict === 'CONDITIONAL'
1891
- ? closeBox(emailConditions.length ? emailConditions : ['the open items set out in the report, before relying on a clean result'])
1892
- : opts?.verdict === 'BLOCKING' && emailConditions.length ? closeBox(emailConditions) : '';
1893
-
1894
- const reviewHeadline = `<div style="${FONT};font-size:11pt;color:#1a1a2e;margin:0 0 14px">`
1967
+ const closeBox = (items, head = EMAIL.onlyYouCanClose) => `<p style="margin:0 0 8px;padding:8px 10px;background:${EC.closeBoxFill};border:1px solid ${EC.closeBoxLine};color:${EC.closeBoxText}"><b>${head}</b><br>${items.map((r) => `• ${cell(String(r))}`).join('<br>')}</p>`;
1968
+ const verdictBound = notCompleted
1969
+ ? (emailConditions.length ? closeBox(emailConditions, EMAIL.beforeYouCanRely) : '')
1970
+ : opts?.verdict === 'CONDITIONAL'
1971
+ ? closeBox(emailConditions.length ? emailConditions : [EMAIL.onlyYouCanCloseDefault])
1972
+ : opts?.verdict === 'BLOCKING' && emailConditions.length ? closeBox(emailConditions) : '';
1973
+
1974
+ // The rating as the page states it where the options carry it (from the report document); otherwise the record's, then
1975
+ // the front matter's, as a run published before the document reads.
1976
+ const rating = opts && 'rating' in opts ? opts.rating : (opts?.tier ?? fm.overall_label);
1977
+ const reviewHeadline = `<div style="${FONT};font-size:11pt;color:${EC.headline};margin:0 0 14px">`
1895
1978
  + flagBanner
1896
1979
  + verdictBound
1897
1980
  + `<p style="margin:0 0 8px"><b>${[opts?.productName ? esc(String(opts.productName)) : '', esc(fm.title || '')].filter(Boolean).join(' — ')} (${esc(fm.matter || '')})</b></p>`
1898
1981
  // T2 (H5): the derived tier (verdict sidecar, passed by the driver) outranks the
1899
1982
  // model-authored fm label — one authority on every surface. The rating leads, then the report's own
1900
1983
  // conclusion verbatim (ruling 244); with no rating recorded, the conclusion stands alone.
1901
- + ((opts?.tier ?? fm.overall_label)
1902
- ? `<p style="margin:0 0 6px"><b>Overall risk: ${esc(opts?.tier ?? fm.overall_label)}.</b> ${cell(fm.overall_caption || '')}</p>`
1984
+ + (rating
1985
+ ? `<p style="margin:0 0 6px"><b>${EMAIL.overallRisk} ${esc(rating)}.</b> ${cell(fm.overall_caption || '')}</p>`
1903
1986
  : (fm.overall_caption ? `<p style="margin:0 0 6px">${cell(fm.overall_caption)}</p>` : ''))
1904
1987
  + reportLink
1905
- + (fm.handling_note ? `<p style="margin:0 0 8px;color:#7a2b12"><b>Handling note:</b> ${cell(fm.handling_note)}</p>` : '')
1906
- // T9 (K3): methodology identity — which profile/framework rated this run (+ verifiable sha).
1907
- + (fm.rated_under ? `<p style="margin:0 0 6px;font-size:9.5pt;color:#7a8290">Rated under: ${cell(fm.rated_under)}</p>` : '')
1988
+ + (fm.handling_note ? `<p style="margin:0 0 8px;color:${EC.warning}"><b>${EMAIL.handlingNote}</b> ${cell(fm.handling_note)}</p>` : '')
1989
+ // No "Rated under" line: the report a client reads is cleaned of it, so the note covering it is too
1990
+ // (2026-11-18). The scale stays named on the report's gauge and in the run's record.
1908
1991
  // compute-don't-author (PR-4, review issue 2): the per-class register-coverage truth is computed
1909
1992
  // by the driver (scope-facts.mjs) and stamped as `coverage_line:` front-matter — but the frozen
1910
1993
  // report renderer only renders known keys, so without THIS line the join never reached a surface
@@ -1912,12 +1995,12 @@ export function composeEmailHtml(reportMdPath, url, auditFile, names = [], deliv
1912
1995
  // "Class 30: 76 of 99 slices fully searched — the remaining 23 are non-Latin script forms" (the
1913
1996
  // spec-B4 proportion form) rides beside the report link. Facts about what ran, never a caveat;
1914
1997
  // absent on legacy runs ⇒ byte-identical mail.
1915
- + (fm.coverage_line ? `<p style="margin:0 0 6px;font-size:9.5pt;color:#7a8290">Register coverage — ${cell(fm.coverage_line)}</p>` : '')
1998
+ + (fm.coverage_line ? `<p style="margin:0 0 6px;font-size:9.5pt;color:${EC.quiet}">${EMAIL.registerCoverage} ${cell(fm.coverage_line)}</p>` : '')
1916
1999
  // The WS1c "Model failover:" line stood here and is DELETED: no code path writes `failover_note`
1917
2000
  // into front-matter any more, because the model-failover chain that would have produced one never had a
1918
2001
  // second rung on any shipped build. Nothing renders a failover note into a report.
1919
2002
  // B5b checkpoint 4 — a customer named after the analysis was written ships as a delivery note, never silently.
1920
- + (fm.late_bind_note ? `<p style="margin:0 0 8px;color:#7a2b12"><b>Applicant named mid-run:</b> ${cell(fm.late_bind_note)}</p>` : '')
2003
+ + (fm.late_bind_note ? `<p style="margin:0 0 8px;color:${EC.warning}"><b>${EMAIL.applicantMidRun}</b> ${cell(fm.late_bind_note)}</p>` : '')
1921
2004
  // The reviewer's open points stood here, from the run record. They do not ride the cover any more
1922
2005
  // (owner ruling, 2026-10-01): the sentence naming the independent reviewer reads as a human declining
1923
2006
  // to sign, and the points themselves are the engine's own vocabulary. Both stay on the run, beside the
@@ -1949,6 +2032,8 @@ export function composeEmailHtml(reportMdPath, url, auditFile, names = [], deliv
1949
2032
  import { recordLinksFor } from './office-record-links.mjs';
1950
2033
  import { reportDates, zurichStamp } from './report-dates.mjs'; // the dates a report prints, from its record
1951
2034
  import { driverDir, paths, readJson } from "../run-record.mjs";
2035
+ import { logosForReport } from "../mark-logos.mjs"; // the saved logo of each cited registration, embedded in the report
2036
+ import { followUpKindsOf } from "../follow-up-twins.mjs"; // the search each deferred directive recorded
1952
2037
  function officeLinksFor(findings, recordsByUri, runOrigins) {
1953
2038
  const links = recordLinksFor(findings, recordsByUri, runOrigins);
1954
2039
  if (links) console.log(`[record-links] ${links.summary}`);
@@ -2020,8 +2105,8 @@ export function setAsideRows(runDir, { findings = null } = {}) {
2020
2105
  const ended = recordsOfDeliveredPositions(read('declination-spec.json')?.rows ?? [], [...findingUris(delivered.filter((f) => f?.disposition !== 'withdrawn')).keys()]);
2021
2106
  const label = (x) => [x.mark, x.owner].filter((v) => typeof v === 'string' && v.trim()).join(' — ') || x.uri;
2022
2107
  return [
2023
- ...[...d.byUri.entries()].filter(([u]) => !ended.has(u)).map(([, x]) => ({ area: `Set aside: ${label(x)}`, note: String(x.grounds ?? '') })),
2024
- ...[...d.byPage.values()].map((x) => ({ area: `Set aside: ${x.url ?? x.page}`, note: String(x.grounds ?? '') })),
2108
+ ...[...d.byUri.entries()].filter(([u]) => !ended.has(u)).map(([, x]) => ({ area: W.setAside(label(x)), note: String(x.grounds ?? '') })),
2109
+ ...[...d.byPage.values()].map((x) => ({ area: W.setAside(x.url ?? x.page), note: String(x.grounds ?? '') })),
2025
2110
  ];
2026
2111
  } catch { return []; }
2027
2112
  }
@@ -2051,3 +2136,11 @@ export function withoutRepeatedRows(rows) {
2051
2136
  return true;
2052
2137
  });
2053
2138
  }
2139
+
2140
+ // THE PAGE READS THE RUN'S REPORT DOCUMENT AS WRITTEN: the JSON the run keeps, parsed back, so the page can read nothing
2141
+ // the file does not hold. A document that could not be built leaves the page nothing to read, and the publish stops
2142
+ // there rather than print a page from another source.
2143
+ function pageDocument(doc) {
2144
+ if (!doc) throw new Error('[report-document] not built, so report.html has nothing to read');
2145
+ return JSON.parse(JSON.stringify(doc));
2146
+ }