clearotron 0.7.0-beta.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 (82) hide show
  1. package/build-info.json +2 -2
  2. package/docs/architecture/04-configuration-reference.md +105 -8
  3. package/driver/CHANGELOG.md +38 -0
  4. package/driver/cancel.mjs +19 -0
  5. package/driver/contract-e3-backlog.mjs +40 -40
  6. package/driver/contract-vocabulary.mjs +1 -1
  7. package/driver/driver.config.mjs +1 -2
  8. package/driver/engine/session-record.mjs +44 -2
  9. package/driver/findings-model.mjs +14 -2
  10. package/driver/follow-up-twins.mjs +86 -0
  11. package/driver/gateway.mjs +10 -2
  12. package/driver/jx-units.mjs +3 -1
  13. package/driver/manuals-inline.mjs +98 -0
  14. package/driver/manuals-seen.mjs +4 -16
  15. package/driver/mark-logos.mjs +31 -1
  16. package/driver/owner-use-check.mjs +5 -1
  17. package/driver/package.json +1 -1
  18. package/driver/pipeline-knockout.mjs +19 -4
  19. package/driver/pipeline.mjs +36 -8
  20. package/driver/portal-report.mjs +2 -2
  21. package/driver/portal-runs.mjs +13 -7
  22. package/driver/predelivery-lint.mjs +7 -5
  23. package/driver/publish/email-conditions.mjs +20 -3
  24. package/driver/publish/index.mjs +218 -139
  25. package/driver/publish/knockout.mjs +252 -228
  26. package/driver/publish/pool-admin.mjs +2 -2
  27. package/driver/publish/regions.mjs +4 -0
  28. package/driver/publish/register-record-html.mjs +105 -0
  29. package/driver/publish/register-record.mjs +26 -11
  30. package/driver/publish/render-knockout.mjs +108 -33
  31. package/driver/publish/render.mjs +311 -149
  32. package/driver/publish/report-data.mjs +1 -1
  33. package/driver/publish/report-document.mjs +353 -0
  34. package/driver/publish/search-depth.mjs +88 -7
  35. package/driver/publish/shell.mjs +41 -1
  36. package/driver/publish/strings.mjs +152 -4
  37. package/driver/publish/templates/clearance-print.css +23 -0
  38. package/driver/publish/templates/knockout.css +24 -0
  39. package/driver/publish/templates/report.css +40 -1
  40. package/driver/publish/xlsx.mjs +16 -20
  41. package/driver/register-count.mjs +5 -1
  42. package/driver/registry-fidelity.mjs +152 -29
  43. package/driver/repair-composers.mjs +2 -2
  44. package/driver/replay-archive.mjs +4 -3
  45. package/driver/run-delivered.mjs +8 -7
  46. package/driver/run-record.mjs +1 -0
  47. package/driver/skills/clearance-search/report-prose.md +3 -0
  48. package/driver/skills/knockout-assess/SKILL.md +8 -0
  49. package/driver/stage-freshness.mjs +8 -5
  50. package/driver/stages.mjs +66 -40
  51. package/driver/steps/delivery.mjs +9 -5
  52. package/driver/steps/overview-and-cards.mjs +4 -1
  53. package/driver/steps/register-sweep.mjs +5 -4
  54. package/driver/steps/skeptic-and-follow-up.mjs +3 -2
  55. package/driver/steps/verdict-gate.mjs +2 -1
  56. package/driver/suite-census.json +224 -32
  57. package/driver/synthesis-record.mjs +4 -3
  58. package/driver/withdrawn-rating.mjs +72 -0
  59. package/mcp-server/CHANGELOG.md +4 -0
  60. package/mcp-server/lib/brief.mjs +4 -1
  61. package/mcp-server/lib/evidence.mjs +66 -22
  62. package/mcp-server/lib/findings.mjs +19 -2
  63. package/mcp-server/lib/knockout.mjs +12 -3
  64. package/mcp-server/package.json +1 -1
  65. package/mcp-server/server.mjs +19 -2
  66. package/package.json +1 -1
  67. package/portal-ui/dist/assets/{index-CtkllKJ2.js → index-BBlN4CYq.js} +13 -3
  68. package/portal-ui/dist/index.html +1 -1
  69. package/portal-ui/package.json +1 -1
  70. package/providers/jx/src/core.js +4 -4
  71. package/providers/jx/src/judge.js +1 -3
  72. package/providers/jx/src/nativeread.js +1 -3
  73. package/providers/oauth-mcp-bridge/CHANGELOG.md +4 -0
  74. package/providers/oauth-mcp-bridge/package.json +1 -1
  75. package/scripts/added-reference-check.mjs +35 -7
  76. package/scripts/e2e-first-time.mjs +1 -1
  77. package/scripts/env-audit.mjs +16 -9
  78. package/scripts/mint-public-residue.mjs +3 -3
  79. package/shared/brand.mjs +8 -1
  80. package/shared/names-in-force.mjs +0 -1
  81. package/shared/reference-guard-classes.mjs +43 -2
  82. package/shared/source-spans.mjs +91 -0
@@ -8,7 +8,7 @@
8
8
  // palette (TONE_TIER, resolved against the run's FROZEN framework) so driver and interactive output
9
9
  // can never drift and a knockout never reads the clearance composer's module state.
10
10
  import { readFileSync, writeFileSync, existsSync } from 'node:fs';
11
- import { finishPoolRun, openPoolRun, refreshStaffPages } from './shell.mjs';
11
+ import { publishRun } from './shell.mjs';
12
12
  import { plainDeferralReason, plainCause } from '../deferral-row.mjs'; import { knockoutStepFailures, PART_NAMES, RULED_WORDS, NOT_COMPLETED, linkNotOnRegisterSite } from '../degraded-parts.mjs'; import { ownersOwedACheck, composeOwnerQuery } from '../owner-use-check.mjs'; import { KNOCKOUT_WEB } from '../stages-knockout.mjs'; // — the reader's words for a search left open; and the parts that failed as a whole
13
13
  import { join } from 'node:path';
14
14
  import { EMAIL_TIER } from '../../shared/brand.mjs';
@@ -16,13 +16,13 @@ import { riskTier, TONE_TIER, regenIndex, regenSurfaces, auditRouteFor, markRepo
16
16
  import { runKnockoutLint, deliveryFlagLines } from '../predelivery-lint.mjs';
17
17
  import { note } from '../log.mjs';
18
18
  import { addSheet } from './xlsx.mjs';
19
- import { KNOCKOUT_EMAIL as KO, KNOCKOUT_WORKBOOK as KW } from './strings.mjs';
19
+ import { KNOCKOUT_EMAIL as KO, KNOCKOUT_WORKBOOK as KW, KNOCKOUT_PAGE as KP } from './strings.mjs';
20
20
  import { COUNT_PREDICATES, COUNT_BASIS, countsForMark, countLine, countedMarks, variantFormsLine, disclosedFloor, moreThan, countNote } from '../register-count.mjs';
21
21
  import { noneCarriedForward, recordsForMark, recordsLine, normalizeRegisterRecordLinks } from '../register-records.mjs';
22
22
  import { reportIdentityFor, productCoverageNote, kebab } from '../search-policy.mjs';
23
23
  import { batchMarkName } from '../mark-name.mjs';
24
- import { renderKnockoutHtml, DEGRADED_NOTE } from './render-knockout.mjs';
25
- import { knockoutReportData } from './report-data.mjs';
24
+ import { renderKnockoutDocument, DEGRADED_NOTE } from './render-knockout.mjs';
25
+ import { knockoutReportDocument, knockoutReportDataOf, knockoutWorkbookOf } from './report-document.mjs'; // the run's report as one document, and what it carries
26
26
  import { readFrozenMethod, inputsLine, FROZEN_METHOD_FILE } from '../framework-method.mjs';
27
27
  import { resolveDemoData, demoBannerMd } from './demo-marking.mjs'; //
28
28
  import { engineCommit } from '../engine-build.mjs';
@@ -66,7 +66,7 @@ const bandCounts = (framework, marks) => {
66
66
  return [...counts].filter(([, n]) => n > 0);
67
67
  };
68
68
  export const knockoutStatement = (framework, marks) =>
69
- `Knockout screen — ${marks.length} mark${marks.length === 1 ? '' : 's'}: ${bandCounts(framework, marks).map(([l, n]) => `${n} ${l}`).join(', ') || 'no rated marks'}.`;
69
+ KP.statement(marks.length, bandCounts(framework, marks).map(([l, n]) => `${n} ${l}`).join(', ') || KP.noRatedMarks);
70
70
 
71
71
  // The MSO review table and its bare-<div> page wrapper are DELETED (2026-07-28). They were a
72
72
  // byte-faithful port of the interactive skill's Word template — `border:solid windowtext 1pt`, Calibri
@@ -100,23 +100,8 @@ export const knockoutStatement = (framework, marks) =>
100
100
  // than "never asked for". 'Impact' goes with them: it was the second rating scale. What replaces them is
101
101
  // what the typed record actually carries. A `—` means the shape that produced the row never had the
102
102
  // field (an archived prose finding), which is a different fact from an empty cell.
103
- /**
104
- * WHAT A KNOCKOUT LEFT OPEN, from the run's own record (design's rule, approved by the owner 2026-11-18). PURE.
105
- *
106
- * A register step that failed is a row under the report's "Register" name: the listing that never came back is not
107
- * searched, and a reading that stopped part-way is partly covered. A name whose automated research was unavailable is a
108
- * row under its own name, not searched. The notes are the shipped lines, the deferral row's for a step and the page's
109
- * own for a name, so nothing here is a new sentence and nothing comes from model prose. A refused listing is not a
110
- * search that failed (the run never offered it), and a run with nothing left open returns no rows.
111
- */
112
- export function knockoutLeftOpen(steps, marks = []) {
113
- return [
114
- ...(steps?.listing ? [{ area: PART_NAMES.register, state: 'not-searched', note: plainDeferralReason(steps.listing.reason) }] : []),
115
- ...(steps?.reading ? [{ area: PART_NAMES.register, state: 'coverage-limited', note: plainDeferralReason(steps.reading.reason) }] : []),
116
- ...(Array.isArray(marks) ? marks : []).filter((m) => m?.degraded === true && String(m?.name ?? '').trim())
117
- .map((m) => ({ area: String(m.name).trim(), state: 'not-searched', note: DEGRADED_NOTE })),
118
- ];
119
- }
103
+ // What a Knockout left open is drawn by the page (render-knockout.mjs), which reads it from the run's report document.
104
+ export { knockoutLeftOpen } from './render-knockout.mjs';
120
105
 
121
106
  export async function buildKnockoutWorkbook(findings, receipts, outPath, registerCounts = null, qcFlags = [], framework = null, registerRecords = null, frameworkMethod = null, ownerChecks = [], degraded = {}) {
122
107
  const ExcelJS = (await import('exceljs')).default;
@@ -413,6 +398,23 @@ export const knockoutName = (searchPolicy) => reportIdentityFor(searchPolicy ??
413
398
  export const knockoutRecordTitle = (searchPolicy, runId) =>
414
399
  `${[knockoutName(searchPolicy)?.toUpperCase(), 'REPORT'].filter(Boolean).join(' ')} — ${runId}`;
415
400
 
401
+ /**
402
+ * The Knockout's cover email as the delivery sends it: the findings, the band ladder, the batch's band, the machine-check
403
+ * lines, the register counts and the product's name from the run's report document where it has one, and as the lane holds
404
+ * them where it has none (a run published before the document existed). The counts are the ones the page states, from the
405
+ * run's saved count record, so the email cannot state figures the page does not, and a count the record lacks is left out
406
+ * rather than read as none.
407
+ */
408
+ export function composeKnockoutCoverNote(runDir, { findings, framework, overall, reports, auditUrl, job, registerCounts, qcFlags, productName }) {
409
+ let document = null;
410
+ try { document = readJson(paths(runDir).reportDocument); } catch { /* a run published before the document */ }
411
+ if (!document) return composeKnockoutEmail({ findings, framework, overall, reports, auditUrl, job, registerCounts, qcFlags, productName });
412
+ return composeKnockoutEmail({
413
+ findings: document.client.findings, framework: document.framework.manifest, overall: document.verdict.overall,
414
+ reports, auditUrl, job, registerCounts: document.client.registerCounts, qcFlags: document.reviewer.qcFlags, productName: document.run.product.name,
415
+ });
416
+ }
417
+
416
418
  export function composeKnockoutEmail({ findings, framework, overall, reports = [], auditUrl = null, job, registerCounts = null, qcFlags = [], productName = null }) {
417
419
  const t = bandTier(framework, overall);
418
420
  const n = (findings.marks ?? []).length;
@@ -526,6 +528,9 @@ export async function readKnockoutDocument({ runId, runDir, findings, plan, fram
526
528
  let registerRecords = null, registerRecordsUnreadable = false;
527
529
  try { registerRecords = readJson(paths(runDir).registerRecords); }
528
530
  catch { registerRecords = null; registerRecordsUnreadable = existsSync(paths(runDir).registerRecords); }
531
+ // Each listed filing's saved record, which its register record drop-down is built from, and each one's saved logo.
532
+ // A run that saved no records, or fetched no logos, has none, and its table renders as before.
533
+ const filingRecords = filingRecordBodies(runDir, registerRecords), logos = logosForReport(runDir);
529
534
  // The owner lookups this run made, read the same tolerant way as the records above:
530
535
  // an archived run that predates the lane has no file, and its cards then render exactly as they were
531
536
  // delivered. The source line the report prints comes from HERE, not from anything the seat typed.
@@ -726,7 +731,7 @@ export async function readKnockoutDocument({ runId, runDir, findings, plan, fram
726
731
  const organisation = (() => { try { const f = readJson(paths(runDir).profile); return typeof f?.organisation === 'string' && f.organisation ? f.organisation : undefined; } catch { return undefined; } })();
727
732
  return {
728
733
  receipts, dates, issued, searched, sweepReceipts, registerCounts, registerCountsUnreadable, registerRecords,
729
- registerRecordsUnreadable, ownerChecks, instructedScope, scopeUnreadable, frameworkMethod, recordLinksDropped,
734
+ registerRecordsUnreadable, filingRecords, logos, ownerChecks, instructedScope, scopeUnreadable, frameworkMethod, recordLinksDropped,
730
735
  officeLinks, qcFlags, machineChecksFailed, steps, lookupsNotRun, recordsNotKept, openPoints, identity, probeRan,
731
736
  markRows, single, origin, reportUrlFor, demoData, served, statement, markNames, organisation,
732
737
  // WHICH BUILD produced this, read once for every surface that records it. null off a git checkout.
@@ -758,148 +763,220 @@ export async function readKnockoutDocument({ runId, runDir, findings, plan, fram
758
763
  // SAME three-state confidentiality rule the clearance does. It defaults to null — the no-opinion state,
759
764
  // which renders the plain marking this template always printed — so the ~15 fixtures in
760
765
  // knockout-units.test.mjs that call this without one are unaffected by its arrival.
761
- export async function publishKnockout({ runId, codename, runDir, findings, plan, framework, overall, poolRoot, poolUrl, customerKey, searchPolicy, tokens, registerCounts: givenCounts = null, skipRegen = false, delivery = null }) {
762
- // `givenCounts`: counts the lane already holds; the document reads the run's own when none are given.
763
- const doc = await readKnockoutDocument({ runId, runDir, findings, plan, framework, overall, poolRoot, poolUrl, customerKey, searchPolicy, registerCounts: givenCounts });
764
- const { receipts, dates, issued, searched, sweepReceipts, registerCounts, registerRecords, registerRecordsUnreadable,
765
- ownerChecks, instructedScope, scopeUnreadable, frameworkMethod, recordLinksDropped, officeLinks, qcFlags,
766
- machineChecksFailed, steps, lookupsNotRun, recordsNotKept, openPoints, identity, probeRan, markRows, single, origin,
767
- reportUrlFor, demoData, served, statement, markNames, organisation, issuedDateUtc, title, overallBadge } = doc;
768
- const { poolRunDir, writeRO, copyRO, buildWorkbook, writeDataFile } = openPoolRun(poolRoot, runId, { runDir });
766
+ export async function publishKnockout(input) {
767
+ return publishRun(KNOCKOUT_SHAPE, input);
768
+ }
769
769
 
770
- // ── THE RUN'S WORKING RECORD TRAVELS WITH THE REPORT ──────────────────────────────────────────────
771
- //
772
- // The delivered directory held the report, its data and the workbook, and nothing the engine itself
773
- // wrote. That is what the acceptance read needs to tell a line the ENGINE wrote from a line the
774
- // RENDERER invented: without it the check can still place a line as report text or as a sanctioned
775
- // label, so it passes — and cannot fail in the way it exists to fail. A clearance run's record is
776
- // `audit.md` and `findings.json`; this lane's own names are these two, and they are copied rather
777
- // than rebuilt so the pool carries the bytes the stages wrote.
778
- //
779
- // AN ABSENT ONE IS SAID, NOT SKIPPED. A run whose stage never wrote its assessment is a different
780
- // thing from a run that wrote one, and a publisher that copies what it finds and says nothing about
781
- // what it does not makes the two look identical to the next reader — which is the whole defect this
782
- // closes, one directory along.
783
- for (const name of ['knockout-findings.json', 'knockout-assessment.md']) {
784
- const src = join(runDir, name);
785
- if (existsSync(src)) {
786
- copyRO(src, name);
787
- } else {
788
- note(`knockout working record: ${name} is not in the run directory, so the delivered report has no engine text to be checked against`);
770
+ // The Knockout's parts of the publishing order (shell.mjs publishRun).
771
+ const KNOCKOUT_SHAPE = {
772
+ regenIndex, regenSurfaces,
773
+ async read({ runId, codename, runDir, findings, plan, framework, overall, poolRoot, poolUrl, customerKey, searchPolicy, tokens, registerCounts: givenCounts = null, delivery = null }) {
774
+ // `givenCounts`: counts the lane already holds; the document reads the run's own when none are given.
775
+ const doc = await readKnockoutDocument({ runId, runDir, findings, plan, framework, overall, poolRoot, poolUrl, customerKey, searchPolicy, registerCounts: givenCounts });
776
+ const { markRows, single, reportUrlFor } = doc;
777
+ // Each name's report: its file, its address, and its band. `overall` on a one-mark document is that mark's rating,
778
+ // never the batch's worst, or a clean name would inherit a blocking name's colour.
779
+ const named = markRows.map((m) => {
780
+ const slug = kebab(m.name);
781
+ return { mark: m.name, slug, file: single ? 'report.html' : `report-${slug}.html`, url: reportUrlFor(slug), band: single ? overall : worstBand(framework, [m]) };
782
+ });
783
+ return { doc, named, runId, codename, runDir, findings, framework, overall, customerKey, searchPolicy, tokens, delivery };
784
+ },
785
+ keep({ copyRO }, { runDir }) {
786
+ // ── THE RUN'S WORKING RECORD TRAVELS WITH THE REPORT ──────────────────────────────────────────────
787
+ //
788
+ // The delivered directory held the report, its data and the workbook, and nothing the engine itself
789
+ // wrote. That is what a check of the delivered report needs to tell a line the ENGINE wrote from a line
790
+ // the RENDERER invented: without it the check can still place a line as report text or as a sanctioned
791
+ // label, so it passes — and cannot fail in the way it exists to fail. A clearance run's record is
792
+ // `audit.md` and `findings.json`; this lane's own names are these two, and they are copied rather
793
+ // than rebuilt so the pool carries the bytes the stages wrote.
794
+ //
795
+ // AN ABSENT ONE IS SAID, NOT SKIPPED. A run whose stage never wrote its assessment is a different
796
+ // thing from a run that wrote one, and a publisher that copies what it finds and says nothing about
797
+ // what it does not makes the two look identical to the next reader — which is the whole defect this
798
+ // closes, one directory along.
799
+ for (const name of ['knockout-findings.json', 'knockout-assessment.md']) {
800
+ const src = join(runDir, name);
801
+ if (existsSync(src)) {
802
+ copyRO(src, name);
803
+ } else {
804
+ note(`knockout working record: ${name} is not in the run directory, so the delivered report has no engine text to be checked against`);
805
+ }
789
806
  }
790
- }
807
+ },
808
+ document: ({ doc, named, runId, codename, customerKey, findings, framework, overall, searchPolicy, tokens }) => knockoutReportDocument(doc, {
809
+ runId, codename, customerKey, findings, framework, overall, searchPolicy: searchPolicy ?? null,
810
+ depthNote: productCoverageNote(searchPolicy ?? null), tokens, reports: named,
811
+ }),
812
+ warn: (what, e) => note(what === 'not built'
813
+ ? `knockout report document not built (non-fatal): ${e?.message ?? e}`
814
+ : `knockout report document not written (non-fatal): ${e?.message ?? e}`),
791
815
  // A workbook that cannot be built no longer stops the batch: every name's report ships, and nothing names the workbook.
792
- const { auditFile, auditError } = await buildWorkbook(`knockout-audit-${codename ?? runId}.xlsx`, (at) => buildKnockoutWorkbook(findings, sweepReceipts, at, registerCounts, qcFlags, framework, registerRecords, frameworkMethod, [...ownerChecks, ...lookupsNotRun], {
793
- listing: registerRecords ? null : steps.listing, reading: steps.reading, review: steps.review, machineChecks: machineChecksFailed,
794
- aboutThisRequest: scopeUnreadable ? { reason: NOT_COMPLETED } : null, droppedLinks: recordLinksDropped, recordsNotKept, openPoints,
795
- }));
816
+ workbook: ({ buildWorkbook }, reportDocument, { codename, runId }) => buildWorkbook(`knockout-audit-${codename ?? runId}.xlsx`, (at) => {
817
+ const w = knockoutWorkbookOf(reportDocument);
818
+ return buildKnockoutWorkbook(w.findings, w.sweepReceipts, at, w.registerCounts, w.qcFlags, w.framework, w.registerRecords, w.frameworkMethod, w.ownerChecks, w.parts);
819
+ }),
820
+ surfaces({ writeRO, writeDataFile }, reportDocument, { doc: { markRows, single, reportUrlFor, filingRecords, logos, demoData, origin, overallBadge }, named, runId, findings, overall, searchPolicy, delivery }, _kept, { auditFile }) {
821
+ const reports = markRows.map((m, at) => {
822
+ const { slug, file, band: markBand } = named[at];
823
+ // The page reads the run's report document as written, for this name, with its surface beside it.
824
+ writeRO(file, renderKnockoutDocument(pageDocument(reportDocument), at, {
825
+ filingRecords, logos, demoData, delivery,
826
+ // The page's workbook control links the portal's audit route, the one the cover note links: the pool path to the
827
+ // file reaches no handler. Null when the workbook could not be written, and then no control is drawn.
828
+ auditHref: auditFile ? auditRouteFor(origin, runId) : null,
829
+ }));
830
+ // The run as data — what the assistant drafts client-facing mail from. One per report, so a per-mark
831
+ // document's data is that mark's and not the batch's. A data file that cannot be written leaves this
832
+ // name's report in place and the other names publishing; `dataFile` is null for it, so nothing points
833
+ // at a file that is not there.
834
+ const dataFile = writeDataFile(single ? 'report-data.json' : `report-data-${slug}.json`, () => knockoutReportDataOf(reportDocument, at));
835
+ return { mark: m.name, slug, file, dataFile, url: reportUrlFor(slug), band: markBand ?? null };
836
+ });
837
+ // report.md — front-matter compatible with archive greps (title/matter/overall_label)
838
+ //
839
+ // — AND IT NAMES THE DOCUMENTS (knockoutDocumentRoutes, below).
840
+ const routes = knockoutDocumentRoutes(reports, { auditFile });
841
+ writeRO('report.md', [
842
+ '---',
843
+ `title: "${knockoutRecordTitle(searchPolicy, runId)}"`,
844
+ `matter: "${runId}"`,
845
+ `overall_label: "${overall ?? ''}"`,
846
+ `overall_badge: "${overallBadge}"`,
847
+ '---',
848
+ '',
849
+ // — THE CROSS-MARK SURFACE, MARKED. The demo banner belongs on the page that groups every mark,
850
+ // and there is no such page — this file's own header states that a multi-mark
851
+ // run "writes no `report.html` AT ALL" and that report.md "is the ONLY file that names every mark
852
+ // together". It is served from the pool and reachable by URL: it is the cross-mark document a
853
+ // reader actually meets, and the banner goes on it.
854
+ ...(demoBannerMd(demoData) ? [demoBannerMd(demoData).trimEnd(), ''] : []),
855
+ `# Summary`,
856
+ '',
857
+ String(findings.batch?.executiveSummary ?? ''),
858
+ ...routes,
859
+ ].join('\n'));
860
+ return { reports };
861
+ },
862
+ // The batch's record, from the document. A document that could not be built fails the publish here, after the pages
863
+ // and before the record, as a throw in the record always has.
864
+ meta: (reportDocument, { reports }) => knockoutMetaOf(reportDocument, { reports }),
865
+ result({ read: { doc: { single, origin, statement, qcFlags, receipts }, runId }, pool: { poolRunDir }, workbook: { auditFile, auditError }, surfaces: { reports }, total }) {
866
+ // `url` IS NULL FOR A BATCH, and that is the honest answer rather than a convenient one. A multi-name
867
+ // knockout has no single report, so any one URL here would be the first name standing for all of them —
868
+ // the very defect `reports` ended, re-entering through the delivery packet. Readers take `reports`; a
869
+ // reader that only knows `url` gets null and fails visibly instead of linking one name in eight.
870
+ const url = single ? reports[0]?.url ?? null : null;
871
+ // qcFlags rides the result so the cover note enumerates the SAME projected lines the workbook does —
872
+ // one projection, two surfaces (never a second one composed at the mail).
873
+ // Composed HERE, from the pool URL this function already holds, so the mail never does string surgery
874
+ // on a report URL to guess where the workbook is. One workbook per RUN — the batch's audit trail is one
875
+ // document by design (it carries a Mark column), which is not the same question as the reports.
876
+ //
877
+ // `auditRouteFor`, not a pool path. Removing the string surgery fixed the DERIVATION and left the
878
+ // DESTINATION exactly as dead — `<pool>/<runId>/<auditFile>` reaches no handler, on a batch and on a
879
+ // single alike, which is every knockout ever delivered. `audit.xlsx` is the route literal; the portal
880
+ // reads the run's real filename out of meta.json and sends it as the download name.
881
+ const auditUrl = auditFile ? auditRouteFor(origin, runId) : null;
882
+ return { runId, auditFile, auditError, auditUrl, url, reports, poolRunDir, statement, total, qcFlags, receipts: receipts.checked };
883
+ },
884
+ };
796
885
 
797
- const reports = markRows.map((m) => {
798
- const slug = kebab(m.name);
799
- const file = single ? 'report.html' : `report-${slug}.html`;
800
- // The mark's own slice. Its band is the document's band — `overall` on a one-mark document is that
801
- // mark's rating, never the batch's worst, or a clean name would inherit a blocking name's colour.
802
- const one = {
803
- ...findings,
804
- marks: [m],
805
- // ── THE PER-MARK DOCUMENT OPENS WITH ITS OWN ASSESSMENT ────────────────
806
- //
807
- // This blanked `executiveSummary` on every per-mark document, and the blank was right: the batch
808
- // paragraph names every mark in the batch, and a reader who ordered one name must not be handed a
809
- // summary about other clients' marks. What it left behind was a page opening with nothing.
810
- //
811
- // The assess stage writes a model-authored paragraph per mark now (ruling, full length), so
812
- // the blank has a replacement rather than being merely correct. Substituting it HERE, into the
813
- // per-mark COPY, is what makes one line serve both surfaces: the rendered `<div class="sub">` and
814
- // `report-data-<slug>.json`'s `.summary` both read `batch.executiveSummary`, so neither the
815
- // renderer nor the data builder needs to change.
816
- //
817
- // THE BATCH PARAGRAPH ITSELF IS UNTOUCHED — `findings.batch.executiveSummary` still holds the
818
- // cross-mark read and still owns the grouped page. This substitutes only in the single-mark copy
819
- // this loop is building. An archived run whose marks carry no `assessment` falls back to the blank
820
- // and re-renders exactly as it was delivered.
821
- batch: { ...(findings.batch ?? {}), ...(single ? {} : { executiveSummary: String(m.assessment ?? '').trim() }) },
822
- };
823
- const markBand = single ? overall : worstBand(framework, [m]);
824
- writeRO(file, renderKnockoutHtml(one, framework, {
825
- runId, overall: markBand, issued, searched, auditFile, probeRan, registerCounts, registerRecords, ownerChecks, instructedScope, identity, matter: runId,
826
- // The page's workbook control links the portal's audit route, the one the cover note links: the pool path to the
827
- // file reaches no handler. Null when the workbook could not be written, and then no control is drawn.
828
- auditHref: auditFile ? auditRouteFor(origin, runId) : null,
829
- // The searches this run did not complete, for this page's names: the Knockout's own Left open grid.
830
- // A listing failure counts only where no filings came back, as the workbook's own part rows read it.
831
- leftOpen: knockoutLeftOpen({ listing: registerRecords ? null : steps.listing, reading: steps.reading }, one.marks),
832
- // Carried as its own value rather than folded into `registerRecords`, because three sites PRINT
833
- // `registerRecords.unavailable` and a marker invented here would become client-facing wording.
834
- registerRecordsUnreadable,
835
- // — an invented mark says so on its own report. Resolved ONCE above the loop:
836
- // the answer is a property of the run, and asking per mark would let a multi-mark demo mark some
837
- // documents and not others if the roster moved mid-publish.
838
- demoData,
839
- // charter ruling 1 — the masthead names what this depth covers, from the run's own frozen policy.
840
- depthNote: productCoverageNote(searchPolicy ?? null),
841
- // — and the scope section is composed from the same frozen policy, so what the
842
- // document says it did not search is what the run was instructed not to search.
843
- searchPolicy: searchPolicy ?? null,
844
- delivery,
845
- servedModels: served,
846
- frameworkMethod,
847
- }));
848
- // The run as data — what the assistant drafts client-facing mail from. One per report, so a per-mark
849
- // document's data is that mark's and not the batch's. A data file that cannot be written leaves this
850
- // name's report in place and the other names publishing; `dataFile` is null for it, so nothing points
851
- // at a file that is not there.
852
- const dataFile = writeDataFile(single ? 'report-data.json' : `report-data-${slug}.json`, () => knockoutReportData(one, framework, {
853
- runId, codename, overall: markBand, issued, registerCounts, registerRecords, ownerChecks, auditFile, customerKey, matter: runId, servedModels: served,
854
- identity: { ...identity, level: searchPolicy?.level ?? null },
855
- url: reportUrlFor(slug),
856
- }));
857
- return { mark: m.name, slug, file, dataFile, url: reportUrlFor(slug), band: markBand ?? null };
858
- });
859
- // report.md — front-matter compatible with archive greps (title/matter/overall_label)
860
- //
861
- // — AND IT NAMES THE DOCUMENTS (knockoutDocumentRoutes, below).
862
- const routes = knockoutDocumentRoutes(reports, { auditFile });
863
- writeRO('report.md', [
864
- '---',
865
- `title: "${knockoutRecordTitle(searchPolicy, runId)}"`,
866
- `matter: "${runId}"`,
867
- `overall_label: "${overall ?? ''}"`,
868
- `overall_badge: "${overallBadge}"`,
869
- '---',
870
- '',
871
- // — THE CROSS-MARK SURFACE, MARKED. Acceptance 3 asks for the banner on "the
872
- // grouped knockout page"; there is no such page — this file's own header states that a multi-mark
873
- // run "writes no `report.html` AT ALL" and that report.md "is the ONLY file that names every mark
874
- // together". It is served from the pool and reachable by URL, so it is the cross-mark document a
875
- // reader actually meets. The criterion's intent is met on the file that holds that role; its letter
876
- // cannot be, because its subject is not built. Recorded on the issue, not just here.
877
- ...(demoBannerMd(demoData) ? [demoBannerMd(demoData).trimEnd(), ''] : []),
878
- `# Summary`,
886
+ /**
887
+ * THE ROUTE FROM THE SUMMARY TO THE DOCUMENTS.
888
+ *
889
+ * On a multi-mark run `report.md` is the ONLY file that names every mark together, and it was a dead
890
+ * end: nothing in it said the per-mark documents exist, let alone what they are called.
891
+ *
892
+ * That absence is what produced the reported defect, and the report was wrong about the cause. The claim
893
+ * was that no register count reaches the client. Measured on the two runs it was about, `report.html`
894
+ * carries "0 identical, 5 containing, 0 on close variations", and "Register search pending" — the
895
+ * `registerEstimate` example wording — appears ZERO times in any delivered file, because registerEstimate
896
+ * is workbook-only. What is true is that a multi-mark run writes no `report.html` AT ALL: the documents
897
+ * are `report-<slug>.html`, one per mark. Look for the conventional name, find nothing, fall back to this
898
+ * file, find prose with no counts. A filename convention read as a rendering defect.
899
+ *
900
+ * SO THIS RETURNS A ROUTE AND NEVER THE COUNTS. They are rendered once, in the documents named here. A
901
+ * second render site for the same numbers is the drift this round has deleted four times over, and a
902
+ * summary that restates a number it does not compute is the next thing to go stale.
903
+ *
904
+ * `report.md` is written into the served pool directory — reachable by URL though linked from nowhere —
905
+ * so this doubles as the honest redirect for a reader who lands on it by mistake.
906
+ *
907
+ * Returns [] when there are no documents, so the caller appends nothing rather than an empty heading:
908
+ * a "## Documents" section listing none would state an absence it cannot explain.
909
+ * PURE.
910
+ *
911
+ * @param {Array<{mark:string, file:string, band:string|null}>} reports one per published document
912
+ * @param {{auditFile?:string|null}} [opts]
913
+ * @returns {string[]} markdown lines to append, or []
914
+ */
915
+ export function knockoutDocumentRoutes(reports, { auditFile = null } = {}) {
916
+ const rows = (Array.isArray(reports) ? reports : []).filter((r) => r && r.file);
917
+ if (!rows.length) return [];
918
+ return [
919
+ // — AN H1, BECAUSE IT IS A SIBLING SECTION AND NOT PART OF THE SUMMARY.
920
+ // As `## Documents` this heading sat INSIDE the `# Summary` section: parseSections splits on /^# /m,
921
+ // so `secs['Summary']` carried this list of pool filenames, and batchSummaryOf had to guess the
922
+ // boundary by heading DEPTH instead of reading one. That guess is what broke the moment the summary
923
+ // gained sub-headers of its own — it terminated the client's entry point at the first of them.
924
+ // Promoted, the boundary is the section boundary, and both readers stop in the right place.
925
+ '', `# ${KP.documents}`, '',
926
+ ...rows.map((r) => `- **${r.mark ?? KP.unnamedMark}**${r.band ? ` — ${r.band}` : ''}: \`${r.file}\``),
879
927
  '',
880
- String(findings.batch?.executiveSummary ?? ''),
881
- ...routes,
882
- ].join('\n'));
883
- const total = finishPoolRun({ writeRO, poolRoot, skipRegen, regenIndex, meta: {
928
+ rows.length === 1
929
+ ? KP.oneDocument
930
+ : KP.manyDocuments,
931
+ ...(auditFile ? [KP.receiptsIn(auditFile)] : []),
932
+ ];
933
+ }
934
+
935
+ // The office's own page for each listed filing (office-record-links.mjs). Kept down here, below every
936
+ // line the rest of the tree cites by number.
937
+ import { addressListedFilings, reasonCellFor } from './office-record-links.mjs';
938
+ import { reportDates, zurichStamp } from './report-dates.mjs'; // the dates a report prints, from its record
939
+ import { declaredRecordOrigins } from '../record-origins.mjs';
940
+ import { driverDir, ensureDriverDir, paths, readJson } from "../run-record.mjs";
941
+ import { readRecordArtifacts, normalizeRecordUri } from "../registry-fidelity.mjs";
942
+ import { recordBodyFromLog } from "../../providers/_shared/ledger.mjs"; // the run record log's own index
943
+ import { logosForReport } from "../mark-logos.mjs"; // the saved logo of each listed filing, embedded in the report
944
+
945
+ /**
946
+ * The saved record of each filing the Knockout lists, by its normalised record id: the run's `_records/` copy where
947
+ * there is one, else the body the run's record log holds. A filing whose record the run never saved is absent, and
948
+ * its table row draws no register record. IMPURE: it reads the run.
949
+ */
950
+ /**
951
+ * The batch's record in the pool (meta.json), from the report document. `reports` is what publishing wrote for each
952
+ * name, its data file included, which is publishing's own fact and not the run's.
953
+ */
954
+ function knockoutMetaOf(document, { reports }) {
955
+ if (!document) throw new Error('the report document could not be built, so the run record cannot be written');
956
+ const { run, verdict, client, staff, build } = document;
957
+ const { runId, codename, title, markNames, customerKey } = run;
958
+ const served = client.servedModels, registerCounts = client.registerCounts, framework = document.framework.manifest;
959
+ const tokens = build.tokens;
960
+ return {
884
961
  runId, codename: codename ?? '', matter: runId,
885
962
  title, // the product's name and how many names (readKnockoutDocument)
886
963
  markName: batchMarkName(markNames) ?? undefined,
887
- engineCommit: doc.engineCommit,
964
+ engineCommit: build.engineCommit,
888
965
  // The models that served the batch, named as a client may read them (tokens.mjs servedModels). Absent when
889
966
  // nothing was read, so a meta from before the record keeps its shape; [] when turns ran and named none a client may read.
890
967
  servedModels: served ?? undefined,
891
968
  client: null, customerKey: customerKey || 'generic',
892
969
  // WHICH ORGANISATION'S GENERIC this batch was filed under (readKnockoutDocument).
893
- organisation,
894
- issuedAt: dates.issuedAt,
895
- renderedAt: dates.renderedAt,
970
+ organisation: run.organisation ?? undefined,
971
+ issuedAt: run.issuedAt,
972
+ renderedAt: build.renderedAt,
896
973
  kind: 'knockout-batch',
897
- marks: (findings.marks ?? []).map((m) => ({ name: m.name, band: m.rating })),
898
- searchLevel: searchPolicy?.level ?? 'knockout',
974
+ marks: (client.findings?.marks ?? []).map((m) => ({ name: m.name, band: m.rating })),
975
+ searchLevel: run.product.level ?? 'knockout',
899
976
  // The level's DISPLAY identity, stamped at publish exactly as the clearance lane stamps it. The
900
977
  // portal re-derived this from the level word because the knockout meta never carried it; a reader of
901
978
  // an archived meta had to know the registry by heart to tell Depth 1 from Depth 2.
902
- stageLabel: identity.stageLabel ?? undefined,
979
+ stageLabel: run.product.stageLabel ?? undefined,
903
980
  // `reportIdentity` WAS written here and read NOWHERE — one occurrence in the whole repository, this
904
981
  // one. A stored display label with no reader is not harmless: it is a second answer to "what is this
905
982
  // product called", frozen at publish, that would have started disagreeing with the registry the first
@@ -910,10 +987,10 @@ export async function publishKnockout({ runId, codename, runDir, findings, plan,
910
987
  registerCounts: registerCounts
911
988
  ? { provider: registerCounts.provider, takenAt: registerCounts.takenAt, marks: registerCounts.marks?.length ?? 0, counted: countedMarks(registerCounts) }
912
989
  : undefined,
913
- recordLinks: officeLinks?.tally ?? undefined, // per office: linked, or cited by number and why; only where the register has no record pages
914
- recipe: searchPolicy?.recipe ?? undefined,
915
- enqueuedVia: searchPolicy?.enqueuedVia ?? undefined,
916
- parentRunId: searchPolicy?.parentRunId ?? undefined,
990
+ recordLinks: client.recordLinks?.tally ?? undefined, // per office: linked, or cited by number and why; only where the register has no record pages
991
+ recipe: run.provenance.recipe ?? undefined,
992
+ enqueuedVia: run.provenance.enqueuedVia ?? undefined,
993
+ parentRunId: run.provenance.parentRunId ?? undefined,
917
994
  tokens: tokens && (tokens.input || tokens.output) ? tokens : undefined,
918
995
  template: 'knockout',
919
996
  // `run` IS GONE. It carried the literal 'Knockout screen (Depth 1)' — a product name that is not the
@@ -921,10 +998,10 @@ export async function publishKnockout({ runId, codename, runDir, findings, plan,
921
998
  // read it. The one `.run` reader in the tree parses report.html front matter and uses it as a DATE
922
999
  // fallback, so had this field ever been joined to that one it would have printed a product name where
923
1000
  // a date belongs. The product is `meta.product`, written from the run's own frozen policy.
924
- overall: overall ?? '', badge: overallBadge, date: issuedDateUtc,
925
- auditFile, statement,
1001
+ overall: verdict.overall ?? '', badge: verdict.badge, date: run.issuedAt.slice(0, 10),
1002
+ auditFile: run.auditFile, statement: verdict.statement,
926
1003
  // WHY THERE IS NO WORKBOOK, when the build threw. Absent when it built, so such a meta is unchanged.
927
- auditError: auditError ?? undefined,
1004
+ auditError: staff.auditError ?? undefined,
928
1005
  framework: framework ? { key: framework.framework_key, title: framework.title, custom: framework.framework_key !== 'house-triage', bands: framework.bands.map((b) => ({ label: b.label, tone: b.tone })) } : undefined,
929
1006
  // Present ⇒ this run has a report-data.json beside each name's report, in the Knockout's shape.
930
1007
  // Stamped only when every name's data file wrote, as the clearance stamps it only when its one file wrote.
@@ -942,80 +1019,27 @@ export async function publishKnockout({ runId, codename, runDir, findings, plan,
942
1019
  // for by design (a batch has no run-level document) — so every per-mark link 404'd, and the
943
1020
  // clearances row printed a fallback saying the report was with us for a final read.
944
1021
  reports: reports.map(({ mark, slug, file, dataFile, band, url }) => ({ mark, slug, file, dataFile, band, url })),
945
- } });
946
- await refreshStaffPages({ regenSurfaces, poolRoot, skipRegen, runDir });
947
- // `url` IS NULL FOR A BATCH, and that is the honest answer rather than a convenient one. A multi-name
948
- // knockout has no single report, so any one URL here would be the first name standing for all of them —
949
- // the defect exists to end, re-entering through the delivery packet. Readers take `reports`; a
950
- // reader that only knows `url` gets null and fails visibly instead of linking one name in eight.
951
- const url = single ? reports[0]?.url ?? null : null;
952
- // qcFlags rides the result so the cover note enumerates the SAME projected lines the workbook does —
953
- // one projection, two surfaces (never a second one composed at the mail).
954
- // Composed HERE, from the pool URL this function already holds, so the mail never does string surgery
955
- // on a report URL to guess where the workbook is. One workbook per RUN — the batch's audit trail is one
956
- // document by design (it carries a Mark column), which is not the same question as the reports.
957
- //
958
- // `auditRouteFor`, not a pool path. Removing the string surgery fixed the DERIVATION and left the
959
- // DESTINATION exactly as dead — `<pool>/<runId>/<auditFile>` reaches no handler, on a batch and on a
960
- // single alike, which is every knockout ever delivered. `audit.xlsx` is the route literal; the portal
961
- // reads the run's real filename out of meta.json and sends it as the download name.
962
- const auditUrl = auditFile ? auditRouteFor(origin, runId) : null;
963
- return { runId, auditFile, auditError, auditUrl, url, reports, poolRunDir, statement, total, qcFlags, receipts: receipts.checked };
1022
+ };
964
1023
  }
965
1024
 
966
- /**
967
- * THE ROUTE FROM THE SUMMARY TO THE DOCUMENTS.
968
- *
969
- * On a multi-mark run `report.md` is the ONLY file that names every mark together, and it was a dead
970
- * end: nothing in it said the per-mark documents exist, let alone what they are called.
971
- *
972
- * That absence is what produced the reported defect, and the report was wrong about the cause. The claim
973
- * was that no register count reaches the client. Measured on the two runs it was about, `report.html`
974
- * carries "0 identical, 5 containing, 0 on close variations", and "Register search pending" — the
975
- * `registerEstimate` example wording — appears ZERO times in any delivered file, because registerEstimate
976
- * is workbook-only. What is true is that a multi-mark run writes no `report.html` AT ALL: the documents
977
- * are `report-<slug>.html`, one per mark. Look for the conventional name, find nothing, fall back to this
978
- * file, find prose with no counts. A filename convention read as a rendering defect.
979
- *
980
- * SO THIS RETURNS A ROUTE AND NEVER THE COUNTS. They are rendered once, in the documents named here. A
981
- * second render site for the same numbers is the drift this round has deleted four times over, and a
982
- * summary that restates a number it does not compute is the next thing to go stale.
983
- *
984
- * `report.md` is written into the served pool directory — reachable by URL though linked from nowhere —
985
- * so this doubles as the honest redirect for a reader who lands on it by mistake.
986
- *
987
- * Returns [] when there are no documents, so the caller appends nothing rather than an empty heading:
988
- * a "## Documents" section listing none would state an absence it cannot explain.
989
- * PURE.
990
- *
991
- * @param {Array<{mark:string, file:string, band:string|null}>} reports one per published document
992
- * @param {{auditFile?:string|null}} [opts]
993
- * @returns {string[]} markdown lines to append, or []
994
- */
995
- export function knockoutDocumentRoutes(reports, { auditFile = null } = {}) {
996
- const rows = (Array.isArray(reports) ? reports : []).filter((r) => r && r.file);
997
- if (!rows.length) return [];
998
- return [
999
- // — AN H1, BECAUSE IT IS A SIBLING SECTION AND NOT PART OF THE SUMMARY.
1000
- // As `## Documents` this heading sat INSIDE the `# Summary` section: parseSections splits on /^# /m,
1001
- // so `secs['Summary']` carried this list of pool filenames, and batchSummaryOf had to guess the
1002
- // boundary by heading DEPTH instead of reading one. That guess is what broke the moment the summary
1003
- // gained sub-headers of its own — it terminated the client's entry point at the first of them.
1004
- // Promoted, the boundary is the section boundary, and both readers stop in the right place.
1005
- '', '# Documents', '',
1006
- ...rows.map((r) => `- **${r.mark ?? '(unnamed mark)'}**${r.band ? ` — ${r.band}` : ''}: \`${r.file}\``),
1007
- '',
1008
- rows.length === 1
1009
- ? 'The register counts, the records and the coverage are in that document.'
1010
- : 'One document per mark, each carrying its own register counts, records and coverage. There is no '
1011
- + 'combined report: this summary is the only place the marks appear together.',
1012
- ...(auditFile ? [`The receipts are in the audit workbook: \`${auditFile}\`.`] : []),
1013
- ];
1025
+ function filingRecordBodies(runDir, registerRecords) {
1026
+ const out = new Map();
1027
+ if (!runDir || !registerRecords) return out;
1028
+ const saved = readRecordArtifacts(runDir);
1029
+ for (const m of Array.isArray(registerRecords.marks) ? registerRecords.marks : []) {
1030
+ for (const r of Array.isArray(m?.records) ? m.records : []) {
1031
+ const key = normalizeRecordUri(r?.recordId);
1032
+ if (!key || out.has(key)) continue;
1033
+ const body = saved.get(key) ?? recordBodyFromLog(paths(runDir).registerRecordBodies, r.recordId);
1034
+ if (body && typeof body === 'object' && !Array.isArray(body)) out.set(key, body);
1035
+ }
1036
+ }
1037
+ return out;
1014
1038
  }
1015
1039
 
1016
- // The office's own page for each listed filing (office-record-links.mjs). Kept down here, below every
1017
- // line the rest of the tree cites by number.
1018
- import { addressListedFilings, reasonCellFor } from './office-record-links.mjs';
1019
- import { reportDates, zurichStamp } from './report-dates.mjs'; // the dates a report prints, from its record
1020
- import { declaredRecordOrigins } from '../record-origins.mjs';
1021
- import { driverDir, ensureDriverDir, paths, readJson } from "../run-record.mjs";
1040
+ // THE PAGE READS THE RUN'S REPORT DOCUMENT AS WRITTEN: the JSON the run keeps, parsed back, so a page can read nothing
1041
+ // the file does not hold. A document that could not be built leaves the pages nothing to read, and the publish stops.
1042
+ function pageDocument(doc) {
1043
+ if (!doc) throw new Error('[report-document] not built, so the Knockout pages have nothing to read');
1044
+ return JSON.parse(JSON.stringify(doc));
1045
+ }