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
@@ -103,7 +103,7 @@ export function clearanceReportData({
103
103
  auditFile: auditFile || null,
104
104
  level: { searchLevel: searchLevel ?? null, stageLabel: stageLabel ?? null },
105
105
  framework: framework ? { key: framework.framework_key, title: framework.title, bands: framework.bands.map((b) => ({ label: b.label, tone: b.tone })) } : null,
106
- // The rating + the one risk statement — the exact record every other surface joins (spec 64). Named
106
+ // The rating + the one risk statement — the exact record every other surface joins. Named
107
107
  // `rating` (ruled 2026-09-22): as `verdict` it read as the clearance's answer and carried the reviewer's
108
108
  // sign-off word beside the band. The sign-off stays in the review stage's own record, not the client's.
109
109
  rating: verdictInfo ? {
@@ -0,0 +1,353 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ // publish/report-document.mjs — the run's report as one versioned JSON document, `report-document/clearance-1`.
4
+ //
5
+ // Every surface a run publishes (the page, the workbook, the cover emails, meta.json, the data file and the
6
+ // connector) reads its facts from what publish assembles. Today each surface takes them by its own route; this
7
+ // document is the one route they move to, one surface at a time, each move proved byte-equal. It is written to
8
+ // the run's own record (`_driver/report-document.json`), never the pool: the pool is the delivered archive, and
9
+ // the reviewer and staff sections do not belong in it.
10
+ //
11
+ // THE SECTION IS THE AUDIENCE. `client` is what reaches the client page, the email, the data file and the
12
+ // portal; `reviewer` is what only the workbook and the reviewing lawyer see; `staff` is the run record's alone.
13
+ // `run`, `scope`, `framework`, `verdict` and `prose` are read by every surface. A value sits in one place.
14
+ //
15
+ // VALUES ARE STORED RAW, as publish read them. The client scrub, a surface's own fallback (the data file's
16
+ // `matter || runId`, meta.json's frozen stage label) and its own field names are the projection's work, so
17
+ // two surfaces that default differently today still can from one document.
18
+ //
19
+ // JSON-SAFE BY CONSTRUCTION: a Map is stored as its [key, value] entries in insertion order (an object would
20
+ // turn ordinal keys into strings and reorder them), a Set as its members in insertion order, a Set inside a Map's
21
+ // value included (JSON writes a Set as `{}`). The register's
22
+ // records and the saved logos are stored by reference: their bodies stay in the run's `_records/` and
23
+ // `_driver/logos/`, which can hold thousands of records.
24
+ //
25
+ // PURE: no IO and no clock. publishReport hands it the values readClearanceDocument read.
26
+ import { clearanceReportData, knockoutReportData } from './report-data.mjs';
27
+ import { deriveActionConditions } from '../findings-model.mjs';
28
+ import { deliveryFlagLines } from '../predelivery-lint.mjs';
29
+ import { NOT_COMPLETED } from '../degraded-parts.mjs';
30
+
31
+ export const CLEARANCE_DOCUMENT = 'report-document/clearance-1';
32
+
33
+ const entries = (m) => (m instanceof Map ? [...m].map(([k, v]) => [k, v instanceof Set ? [...v] : v]) : null);
34
+ const members = (s) => (s instanceof Set ? [...s] : null);
35
+ const orNull = (v) => (v === undefined ? null : v);
36
+
37
+ /**
38
+ * The clearance run as one document. `d` is readClearanceDocument's return; `codename`, `customerKey` and
39
+ * `auditFile` are known only to publishReport (the last once the workbook is built).
40
+ */
41
+ export function clearanceReportDocument(d, { codename = null, customerKey = null, auditFile = null, auditError = null } = {}) {
42
+ const all = Array.isArray(d.findings) ? d.findings : [];
43
+ const isWithdrawn = (f) => f?.disposition === 'withdrawn';
44
+ // The forward asks as the report partitions them. An ask whose findings were all withdrawn is dropped
45
+ // here, so the client section never needs the withdrawn findings to read its own asks.
46
+ const { conditionActions, advisoryActions } = deriveActionConditions(d.actionsRegister ?? [], all);
47
+ const pol = d.searchPolicy ?? null;
48
+ return {
49
+ document: CLEARANCE_DOCUMENT,
50
+ build: { engineCommit: orNull(d.engineCommit), renderedAt: orNull(d.renderedAt), tokens: orNull(d.tokenRollup?.total) },
51
+ run: {
52
+ runId: d.runId ?? null,
53
+ codename: codename || null,
54
+ customerKey: customerKey || null,
55
+ organisation: orNull(d.organisation),
56
+ project: orNull(d.project),
57
+ markName: orNull(d.markName),
58
+ issued: orNull(d.issued),
59
+ issuedAt: orNull(d.issuedAt),
60
+ asOf: orNull(d.asOf),
61
+ url: orNull(d.reportRoute),
62
+ auditFile: auditFile || null,
63
+ product: {
64
+ name: orNull(d.productName),
65
+ level: orNull(pol?.level),
66
+ // Today's registry's label and the one frozen with the run, apart: the page and the data file read the
67
+ // first, meta.json the second.
68
+ stageLabel: orNull(d.stageLabel),
69
+ frozenStageLabel: orNull(d.frozenStageLabel),
70
+ depthNote: orNull(d.depthNote),
71
+ },
72
+ provenance: {
73
+ recipe: orNull(pol?.recipe), enqueuedVia: orNull(pol?.enqueuedVia),
74
+ enqueuedBy: orNull(pol?.enqueuedBy), parentRunId: orNull(pol?.parentRunId),
75
+ },
76
+ // The register the run read: its name, its citation rule, and where its records are published.
77
+ provider: {
78
+ label: orNull(d.providerLabel),
79
+ citation: orNull(d.runProviderConf?.recordCitation),
80
+ origin: orNull(d.recordOrigin),
81
+ origins: orNull(d.runOrigins),
82
+ },
83
+ // The findings record's declared version; the page chooses the grouped negatives' layout by it.
84
+ findingsVersion: orNull(d.findingsSchemaVersion),
85
+ },
86
+ scope: {
87
+ jurisdiction: orNull(d.jurisdiction),
88
+ scopeBasis: orNull(d.scopeBasis),
89
+ searchedJurisdictions: orNull(d.searchedJurisdictions),
90
+ planTerritories: orNull(d.planTerritories),
91
+ registerReach: orNull(d.registerReach),
92
+ registerScope: orNull(d.registerScope),
93
+ registerOnly: Boolean(d.registerOnly),
94
+ noMarketplacesPicked: Boolean(d.noMarketplacesPicked),
95
+ searchDepth: orNull(d.searchDepth),
96
+ },
97
+ framework: { manifest: orNull(d.framework), method: orNull(d.frameworkMethod) },
98
+ verdict: {
99
+ // The verdict record whole. Its sign-off is the reviewer's word, but the page prints it as the recommendation
100
+ // on a record with no statement, so it is read here with the rest.
101
+ record: orNull(d.verdictInfo),
102
+ // The record as written in the run's verdict file, which the cover email reads. It differs from `record` on a record
103
+ // older than the derived display fields, and where the assessment was not completed.
104
+ written: orNull(d.verdictWritten),
105
+ assessmentNotCompleted: Boolean(d.assessmentNotCompleted),
106
+ },
107
+ client: {
108
+ findings: all.filter((f) => !isWithdrawn(f)),
109
+ coverage: d.coverage ?? [],
110
+ contextNotes: d.contextNotes ?? [],
111
+ markAssessment: orNull(d.markAssessment),
112
+ fourAnswers: orNull(d.fourAnswers),
113
+ askAnswers: orNull(d.askAnswers),
114
+ actions: { conditions: conditionActions, advisories: advisoryActions },
115
+ coverageJudgment: orNull(d.coverageJudgmentDisplay),
116
+ // Each finding's court decisions. The session-wide notice is not carried: no surface prints it.
117
+ caseLaw: { byOrdinal: entries(d.caseLawByOrdinal) ?? [] },
118
+ enforcerSignals: d.enforcerSignals ?? [],
119
+ seniorRights: orNull(d.seniorRights),
120
+ records: d.recordsByUri instanceof Map ? [...d.recordsByUri.keys()] : [],
121
+ recordLinks: d.officeLinks ? { byUri: entries(d.officeLinks.byUri), tally: orNull(d.officeLinks.tally), summary: orNull(d.officeLinks.summary) } : null,
122
+ logos: d.logos instanceof Map ? [...d.logos].map(([ref, l]) => [ref, l?.state ?? null]) : [],
123
+ followUpKinds: entries(d.followUpKinds) ?? [],
124
+ servedModels: orNull(d.served),
125
+ },
126
+ reviewer: {
127
+ // Each withdrawn finding with its place in the run's list, so a reader can restore the list's order.
128
+ withdrawn: all.flatMap((f, at) => (isWithdrawn(f) ? [{ at, finding: f }] : [])),
129
+ quarantined: d.quarantined ?? [],
130
+ coverageJudgment: orNull(d.coverageJudgment),
131
+ corrections: orNull(d.correctionsDoc),
132
+ // The predelivery checks that failed, with their raw detail, which stays here: the workbook is handed their delivery
133
+ // lines. The run's other review receipts reach no surface, so they are not carried.
134
+ lint: d.reviewReceipts?.lint ?? [],
135
+ droppedConditions: d.droppedConditions ?? [],
136
+ undispatchedProbes: d.undispatchedProbes ?? [],
137
+ withheldFamilies: d.withheldFamilies ?? [],
138
+ releasedFamilies: d.releasedFamilies ?? [],
139
+ setAside: d.setAside ?? [],
140
+ fetchState: orNull(d.fetchState),
141
+ clientGate: orNull(d.clientGate),
142
+ degradedParts: d.degradedRows ?? [],
143
+ commonLawJoinedTerms: members(d.commonLawJoinedTerms),
144
+ // audit.md as parsed: the search log the workbook sets out.
145
+ audit: orNull(d.auditParsed),
146
+ },
147
+ staff: {
148
+ inputsAbsent: d.inputsAbsent ?? [],
149
+ publishParts: d.publishParts ?? [],
150
+ findingsError: orNull(d.findingsError),
151
+ auditError: auditError ?? null,
152
+ },
153
+ // report.md as parsed: its front matter, its sections by heading and the finding cards. Raw, as the page reads it.
154
+ prose: {
155
+ frontMatter: d.parsed?.fm ?? {},
156
+ sections: d.parsed?.secs ?? {},
157
+ cards: d.parsed?.cards ?? [],
158
+ },
159
+ };
160
+ }
161
+
162
+ /**
163
+ * The data file (`report-data/clearance-1`) as the document's client projection: the same producer, handed
164
+ * the document's values. Equal byte for byte to the file publish writes today.
165
+ */
166
+ export function clearanceReportDataOf(doc) {
167
+ const fm = doc.prose.frontMatter;
168
+ const { run, scope, verdict, client } = doc;
169
+ return clearanceReportData({
170
+ runId: run.runId, codename: run.codename, matter: fm.matter, markName: run.markName, title: fm.title,
171
+ customerKey: run.customerKey || 'generic', issued: run.issued, url: run.url, auditFile: run.auditFile,
172
+ // The stage label REGISTRY-FIRST: today's registry's label, the one report.html renders, so a republished
173
+ // pre-renumber run cannot carry one label on its page and another in its data file. The label frozen with the run
174
+ // is the last resort, for a level today's registry no longer knows; meta.json keeps the frozen one by design.
175
+ searchLevel: run.product.level, stageLabel: run.product.stageLabel ?? run.product.frozenStageLabel ?? null,
176
+ engineCommit: doc.build.engineCommit, servedModels: client.servedModels,
177
+ framework: doc.framework.manifest, verdictInfo: verdict.record, findings: client.findings,
178
+ coverage: client.coverage, contextNotes: client.contextNotes, markAssessment: client.markAssessment,
179
+ fourAnswers: client.fourAnswers, askAnswers: client.askAnswers,
180
+ actions: [...client.actions.conditions, ...client.actions.advisories],
181
+ jurisdiction: scope.jurisdiction, searchedJurisdictions: scope.searchedJurisdictions, scopeBasis: scope.scopeBasis,
182
+ caption: fm.overall_caption || null, assessmentNotCompleted: verdict.assessmentNotCompleted,
183
+ });
184
+ }
185
+
186
+ /**
187
+ * The rating a clearance's surfaces state, and its badge: the verdict record's as the page reads it, the report's front
188
+ * matter on a run older than the record, and none where the assessment was not completed. The page, the run record and
189
+ * the cover email read it here, so a saved verdict from an assessment that did not complete rates nothing on any of them.
190
+ */
191
+ export function clearanceRatingOf(doc) {
192
+ const fm = doc.prose.frontMatter, { record, assessmentNotCompleted } = doc.verdict;
193
+ if (assessmentNotCompleted) return { word: undefined, badge: undefined };
194
+ return { word: record?.tier ?? fm.overall_label, badge: record?.badge ?? fm.overall_badge };
195
+ }
196
+
197
+ /** The run's findings in their own order: the withdrawn ones are put back where they were. */
198
+ export function allFindingsOf(doc) {
199
+ const out = [...doc.client.findings];
200
+ for (const { at, finding } of doc.reviewer.withdrawn) out.splice(at, 0, finding);
201
+ return out;
202
+ }
203
+
204
+ /**
205
+ * The document with the workbook publishing wrote, or why there is none. The document is built before the workbook,
206
+ * which reads it, so the workbook's file name is set on it afterwards.
207
+ */
208
+ export const withWorkbook = (doc, { auditFile = null, auditError = null } = {}) => ({
209
+ ...doc, run: { ...doc.run, auditFile: auditFile || null }, staff: { ...doc.staff, auditError: auditError ?? null },
210
+ });
211
+
212
+ /**
213
+ * The audit workbook's inputs from the document: buildAudit's contract, the search log, and the front matter. The failing
214
+ * predelivery checks are handed over as their delivery lines, never their raw detail: the workbook's download link rides
215
+ * in the cover note a client principal reads, so the workbook is a delivery surface under the same rule.
216
+ */
217
+ export function clearanceWorkbookOf(doc) {
218
+ const { run, scope, verdict, client, reviewer } = doc;
219
+ const origins = run.provider.origins;
220
+ return {
221
+ contract: {
222
+ degradedParts: reviewer.degradedParts, droppedConditions: reviewer.droppedConditions,
223
+ undispatchedProbes: reviewer.undispatchedProbes, withheldFamilies: reviewer.withheldFamilies,
224
+ releasedFamilies: reviewer.releasedFamilies, setAside: reviewer.setAside, findings: allFindingsOf(doc),
225
+ frameworkMethod: doc.framework.method, coverage: client.coverage, contextNotes: client.contextNotes,
226
+ coverageJudgment: reviewer.coverageJudgment, markAssessment: client.markAssessment, corrections: reviewer.corrections,
227
+ fetchState: reviewer.fetchState, verdict: verdict.record, jurisdiction: scope.jurisdiction,
228
+ commonLawJoinedTerms: reviewer.commonLawJoinedTerms, registerOnly: scope.registerOnly, clientGate: reviewer.clientGate,
229
+ lintFailures: deliveryFlagLines(reviewer.lint), productName: run.product.name,
230
+ registerPublishesRecordPages: origins == null ? null : origins.length > 0,
231
+ recordLinks: client.recordLinks?.byUri ? new Map(client.recordLinks.byUri) : null,
232
+ assessmentNotCompleted: verdict.assessmentNotCompleted, registerReach: scope.registerReach, registerScope: scope.registerScope,
233
+ },
234
+ audit: reviewer.audit,
235
+ title: doc.prose.frontMatter.title,
236
+ frontMatter: doc.prose.frontMatter,
237
+ };
238
+ }
239
+
240
+ export const KNOCKOUT_DOCUMENT = 'report-document/knockout-1';
241
+
242
+ /**
243
+ * The Knockout run as one document: every name in the batch, with each name's report as publishing wrote it.
244
+ * `d` is readKnockoutDocument's return; `reports` is each name's report ({ mark, slug, file, url, band }), in
245
+ * the order publishing wrote them.
246
+ *
247
+ * The run's findings record is kept whole, under its own names. The data file renames four of a mark's fields
248
+ * (rating, ratingQualifier, bullets, purpleNotes) and goes on doing so in its projection: a rename here would be
249
+ * one more way for the build to fail, and the record is what the page reads.
250
+ */
251
+ export function knockoutReportDocument(d, { runId, codename = null, customerKey = null, findings, framework = null, overall = null, searchPolicy = null, depthNote = null, tokens = null, reports = [], auditFile = null, auditError = null }) {
252
+ const identity = d.identity ?? {};
253
+ return {
254
+ document: KNOCKOUT_DOCUMENT,
255
+ build: { engineCommit: orNull(d.engineCommit), renderedAt: orNull(d.dates?.renderedAt), tokens: orNull(tokens) },
256
+ run: {
257
+ runId: runId ?? null,
258
+ codename: codename ?? null,
259
+ customerKey: customerKey || null,
260
+ organisation: orNull(d.organisation),
261
+ title: orNull(d.title),
262
+ markNames: d.markNames ?? [],
263
+ issued: orNull(d.issued),
264
+ issuedAt: orNull(d.dates?.issuedAt),
265
+ searched: orNull(d.searched),
266
+ origin: orNull(d.origin),
267
+ auditFile: auditFile || null,
268
+ single: Boolean(d.single),
269
+ // Each name's report, with the band it carries: the name's own on a batch, the run's on one name.
270
+ reports: reports.map(({ mark, slug, file, url, band }) => ({ mark, slug, file, url: orNull(url), band: band ?? null })),
271
+ product: {
272
+ name: orNull(identity.identity), stageLabel: orNull(identity.stageLabel), template: orNull(identity.template),
273
+ banner: orNull(identity.banner), level: orNull(searchPolicy?.level), depthNote: orNull(depthNote),
274
+ },
275
+ provenance: {
276
+ recipe: orNull(searchPolicy?.recipe), enqueuedVia: orNull(searchPolicy?.enqueuedVia),
277
+ enqueuedBy: orNull(searchPolicy?.enqueuedBy), parentRunId: orNull(searchPolicy?.parentRunId),
278
+ },
279
+ },
280
+ scope: {
281
+ instructedScope: orNull(d.instructedScope),
282
+ scopeUnreadable: Boolean(d.scopeUnreadable),
283
+ // The frozen policy whole: the page composes "About this request" and the masthead from it.
284
+ policy: orNull(searchPolicy),
285
+ probeRan: Boolean(d.probeRan),
286
+ // The searches that did not complete, which the page's Left open and the workbook's part rows read.
287
+ steps: orNull(d.steps),
288
+ },
289
+ framework: { manifest: orNull(framework), method: orNull(d.frameworkMethod) },
290
+ verdict: { overall: orNull(overall), badge: orNull(d.overallBadge), statement: orNull(d.statement) },
291
+ client: {
292
+ findings: orNull(findings),
293
+ registerCounts: orNull(d.registerCounts),
294
+ registerRecords: orNull(d.registerRecords),
295
+ registerRecordsUnreadable: Boolean(d.registerRecordsUnreadable),
296
+ // By reference: each filing's saved record stays in the run's `_records/` or its record log.
297
+ filingRecords: d.filingRecords instanceof Map ? [...d.filingRecords.keys()] : [],
298
+ logos: d.logos instanceof Map ? [...d.logos].map(([ref, l]) => [ref, l?.state ?? null]) : [],
299
+ ownerChecks: d.ownerChecks ?? [],
300
+ recordLinks: d.officeLinks ? { tally: orNull(d.officeLinks.tally), summary: orNull(d.officeLinks.summary) } : null,
301
+ servedModels: orNull(d.served),
302
+ },
303
+ reviewer: {
304
+ sweepReceipts: d.sweepReceipts ?? [],
305
+ qcFlags: d.qcFlags ?? [],
306
+ machineChecksFailed: orNull(d.machineChecksFailed),
307
+ lookupsNotRun: d.lookupsNotRun ?? [],
308
+ recordsNotKept: d.recordsNotKept ?? [],
309
+ openPoints: d.openPoints ?? [],
310
+ recordLinksDropped: orNull(d.recordLinksDropped),
311
+ registerCountsUnreadable: Boolean(d.registerCountsUnreadable),
312
+ },
313
+ staff: { auditError: auditError ?? null },
314
+ };
315
+ }
316
+
317
+ /**
318
+ * One name's data file (`report-data/knockout-1`) as the document's client projection, by the name's place in
319
+ * the batch. Equal byte for byte to the file publishing writes for that name today.
320
+ */
321
+ export function knockoutReportDataOf(doc, at) {
322
+ const { run, client } = doc;
323
+ const findings = client.findings ?? {};
324
+ const m = (findings.marks ?? [])[at];
325
+ // The name's own slice, as publishing builds it: on a batch, the page opens with the name's own assessment.
326
+ const one = {
327
+ ...findings, marks: [m],
328
+ batch: { ...(findings.batch ?? {}), ...(run.single ? {} : { executiveSummary: String(m.assessment ?? '').trim() }) },
329
+ };
330
+ const report = run.reports[at];
331
+ return knockoutReportData(one, doc.framework.manifest, {
332
+ runId: run.runId, codename: run.codename, overall: report.band, issued: run.issued,
333
+ registerCounts: client.registerCounts, registerRecords: client.registerRecords, ownerChecks: client.ownerChecks,
334
+ auditFile: run.auditFile, customerKey: run.customerKey, matter: run.runId, servedModels: client.servedModels,
335
+ identity: { identity: run.product.name, stageLabel: run.product.stageLabel, level: run.product.level },
336
+ url: report.url,
337
+ });
338
+ }
339
+
340
+ /** The Knockout workbook's inputs from the document, under the names buildKnockoutWorkbook takes them. */
341
+ export function knockoutWorkbookOf(doc) {
342
+ const { client, reviewer, scope } = doc;
343
+ return {
344
+ findings: client.findings, sweepReceipts: reviewer.sweepReceipts, registerCounts: client.registerCounts,
345
+ qcFlags: reviewer.qcFlags, framework: doc.framework.manifest, registerRecords: client.registerRecords,
346
+ frameworkMethod: doc.framework.method, ownerChecks: [...client.ownerChecks, ...reviewer.lookupsNotRun],
347
+ parts: {
348
+ listing: client.registerRecords ? null : scope.steps.listing, reading: scope.steps.reading, review: scope.steps.review,
349
+ machineChecks: reviewer.machineChecksFailed, aboutThisRequest: scope.scopeUnreadable ? { reason: NOT_COMPLETED } : null,
350
+ droppedLinks: reviewer.recordLinksDropped, recordsNotKept: reviewer.recordsNotKept, openPoints: reviewer.openPoints,
351
+ },
352
+ };
353
+ }
@@ -37,6 +37,8 @@
37
37
  // · court decisions distinguishes four states → break: collapse none-found into not-checked, arm 6 red
38
38
 
39
39
  import { parseCaseLawLedger, ledgerSeparatesUnsentQueries } from "../case-law-ledger.mjs"; // pure, like this module
40
+ import { normRegion, regionName } from "./regions.mjs"; // pure: the page's own folding of a territory's spellings
41
+ import { capabilitiesFor } from "../register-capabilities.mjs"; // a register's own territory-to-office translate
40
42
 
41
43
  /** The closed set a group key may take. The renderer's headings are keyed on these, never on prose. */
42
44
  export const CLEARED_GROUPS = Object.freeze(["dead-filing", "different-goods", "other"]);
@@ -344,10 +346,89 @@ export function localLanguageDepth(verdicts) {
344
346
  return { state: short ? "ran-shallow" : "ran", lanes };
345
347
  }
346
348
 
347
- /** Was the name searched in a non-Latin script? Read off the plan's own terms, never asserted. PURE. */
348
- export function localScriptSearched(registerPlan) {
349
- const entries = Array.isArray(registerPlan?.entries) ? registerPlan.entries : [];
350
- return entries.some((e) => /[^\x00-\x7F]/.test(String(e?.term ?? "")));
349
+ // WHICH NATIVE SCRIPTS THE RUN SEARCHED, READ OFF WHAT RAN (owner, 2026-11-19). This read the plan alone, and any
350
+ // non-ASCII character made the page claim local script: an accented Latin spelling did, and so did a native-script
351
+ // term that was planned and never ran. Measured on the test instance's saved runs: the claim was fully borne out on 18 of
352
+ // 80; on 59 a native-script search ran while another planned one did not, and on 3 none ran at all. Now a script
353
+ // counts as searched only when a plan term in it COMPLETED: its row in the run's execution record is `enumerated`. A
354
+ // row the record keeps as `incomplete` (1,193 of 11,813 on those runs), or with no state, did not complete and does not
355
+ // count. A Latin term names no native script however it is accented, and a run that kept no execution record says
356
+ // nothing either way.
357
+ const NATIVE_SCRIPTS = [
358
+ ["Hani", /\p{Script=Han}/u], ["Hira", /\p{Script=Hiragana}/u], ["Kana", /\p{Script=Katakana}/u], ["Hang", /\p{Script=Hangul}/u],
359
+ ["Cyrl", /\p{Script=Cyrillic}/u], ["Arab", /\p{Script=Arabic}/u], ["Grek", /\p{Script=Greek}/u], ["Hebr", /\p{Script=Hebrew}/u],
360
+ ["Thai", /\p{Script=Thai}/u], ["Deva", /\p{Script=Devanagari}/u],
361
+ ];
362
+ // WHERE EACH SCRIPT COMPLETED, so a script searched in one territory and not in another keeps that gap (2026-11-19).
363
+ // A territory is a plan term's region, folded the way the page folds the plan's territories (`normRegion`: EM and
364
+ // euipo are EU, GB is UK), so one territory under two spellings is never a gap. A term that names no region is placed
365
+ // nowhere: on the test instance's 88 saved plans, 464 of 1,492 native-script terms name none. Those are kept apart, under
366
+ // `unnamed`, rather than read as searching nowhere or everywhere.
367
+ // A WORLDWIDE SEARCH IS ONE THE PLAN SAYS IS WORLDWIDE, never one inferred from a long list. The plan stamps
368
+ // `scope_basis: "worldwide"` when the matter was unrestricted, because on some registers a worldwide matter compiles to
369
+ // the register's full office list, which reads by shape like 186 hand-picked territories. On such a plan, a term asking
370
+ // the plan's whole territory list is the worldwide search, kept under `worldwide` ("searched" or "missed"); its
371
+ // territories are not listed as planned one by one, and when it completed they all count as searched. 210 of the
372
+ // 1,492 terms are of this kind.
373
+ // A PLAN ON A REGISTER WITH ITS OWN OFFICE KEYS NAMES OFFICES, NOT TERRITORIES: `uspto`, `ipi`, `inpi-fr`. The page has
374
+ // no name for those, and a territory it cannot name would reach a reader as the key. Each is read back as the territory
375
+ // it serves through that register's own translate, territory to office, run in reverse over every two-letter code. It
376
+ // is asked only of a key the page cannot name, so a code that is already a territory keeps its meaning: one register
377
+ // files Benelux under BX, which its translate also reaches from Belgium. A key nothing translates to stays as written.
378
+ function officeTerritories(provider) {
379
+ const out = new Map();
380
+ let translate = null;
381
+ try { translate = provider ? capabilitiesFor(provider)?.offices?.translate : null; } catch { translate = null; }
382
+ if (typeof translate !== "function") return out;
383
+ for (let a = 65; a < 91; a++) for (let b = 65; b < 91; b++) {
384
+ const code = String.fromCharCode(a, b);
385
+ let key = null;
386
+ try { key = translate(code); } catch { key = null; }
387
+ const k = String(key ?? "").toUpperCase();
388
+ if (k && k !== code && !out.has(k)) out.set(k, code);
389
+ }
390
+ return out;
391
+ }
392
+
393
+ /**
394
+ * The native scripts the run's plan searched in, `{ searched, missed, territories }`, keyed by ISO 15924 code: a script
395
+ * is searched when a plan term written in it completed, and missed when terms in it were planned and none completed.
396
+ * `territories` holds, per script, the territories where a term in it completed (`searched`) and those where terms in
397
+ * it were planned and none completed (`missed`), plus `unnamed` ("searched" or "missed") when terms in it named no
398
+ * region, and `worldwide` ("searched" or "missed") when a term in it asked the whole of a plan stamped worldwide. Null
399
+ * when the run kept no execution record, so none of it can be said. PURE.
400
+ */
401
+ export function localScripts(registerPlan, planExecution) {
402
+ if (!planExecution || !Array.isArray(planExecution.executed)) return null;
403
+ const ran = new Set(planExecution.executed.filter((x) => x?.state === "enumerated").map((x) => x?.qid).filter(Boolean));
404
+ const office = officeTerritories(registerPlan?.provider);
405
+ const fold = (list) => [...new Set((Array.isArray(list) ? list : []).map((r) => {
406
+ const code = normRegion(r);
407
+ return regionName(code) === code && office.has(code) ? normRegion(office.get(code)) : code;
408
+ }).filter(Boolean))];
409
+ const whole = registerPlan?.scope_basis === "worldwide" ? new Set(fold(registerPlan?.regions)) : new Set();
410
+ const searched = new Set(), planned = new Set(), at = {};
411
+ for (const e of Array.isArray(registerPlan?.entries) ? registerPlan.entries : []) {
412
+ const regions = fold(e?.regions);
413
+ const worldwide = whole.size > 0 && regions.length === whole.size && regions.every((r) => whole.has(r));
414
+ const done = ran.has(e?.qid);
415
+ for (const [code, re] of NATIVE_SCRIPTS) {
416
+ if (!re.test(String(e?.term ?? ""))) continue;
417
+ planned.add(code);
418
+ if (done) searched.add(code);
419
+ const t = (at[code] ??= { searched: new Set(), planned: new Set(), unnamed: null, worldwide: null });
420
+ if (worldwide) t.worldwide = done || t.worldwide === "searched" ? "searched" : "missed";
421
+ for (const r of regions) { if (!worldwide) t.planned.add(r); if (done) t.searched.add(r); }
422
+ if (!regions.length) t.unnamed = done || t.unnamed === "searched" ? "searched" : "missed";
423
+ }
424
+ }
425
+ const territories = {};
426
+ for (const code of Object.keys(at).sort()) {
427
+ const t = at[code];
428
+ territories[code] = { searched: [...t.searched].sort(), missed: [...t.planned].filter((r) => !t.searched.has(r)).sort(),
429
+ ...(t.unnamed ? { unnamed: t.unnamed } : {}), ...(t.worldwide ? { worldwide: t.worldwide } : {}) };
430
+ }
431
+ return { searched: [...searched].sort(), missed: [...planned].filter((c) => !searched.has(c)).sort(), territories };
351
432
  }
352
433
 
353
434
  /**
@@ -355,7 +436,7 @@ export function localScriptSearched(registerPlan) {
355
436
  *
356
437
  * @returns {{schemaVersion: number, cleared: object, counts: object}}
357
438
  */
358
- export function searchDepthRecord({ auditMd = "", recordIndex = {}, recordFileNames = [], bandRecordIds = null, commonLawGrid = null, caseLawText = "", caseLawRecord = null, registerPlan = null, laneDepthVerdicts = null, noMarketplacesPicked = false } = {}) {
439
+ export function searchDepthRecord({ auditMd = "", recordIndex = {}, recordFileNames = [], bandRecordIds = null, commonLawGrid = null, caseLawText = "", caseLawRecord = null, registerPlan = null, planExecution = null, laneDepthVerdicts = null, noMarketplacesPicked = false } = {}) {
359
440
  // `recordFileNames: null` travels all the way to the page — see recordsByCountry. The default stays `[]`
360
441
  // because that is "the caller said nothing", not "the store is absent"; only the publish path knows the
361
442
  // difference and it is the one producer.
@@ -378,9 +459,9 @@ export function searchDepthRecord({ auditMd = "", recordIndex = {}, recordFileNa
378
459
  // The company picked no marketplaces: the report says the general web ran plus any stores chosen for
379
460
  // the matter. Stamped only when true, so every other run's record is unchanged.
380
461
  sweep: { ...sweepCounts(commonLawGrid, auditMd), ...(noMarketplacesPicked ? { noMarketplacesPicked: true } : {}) },
381
- localScriptSearched: localScriptSearched(registerPlan),
462
+ localScripts: localScripts(registerPlan, planExecution),
382
463
  courtDecisions: courtDecisionsState(caseLawText, caseLawRecord ?? undefined),
383
- // `localScriptSearched` above answers whether the spellings were searched; this answers how deep
464
+ // `localScripts` above answers which scripts' spellings were searched; this answers how deep
384
465
  // the investigation went against what was configured. Two different facts, and the row the report
385
466
  // reserves is for the second.
386
467
  localLanguage: localLanguageDepth(laneDepthVerdicts),
@@ -11,7 +11,8 @@ import { chmodSync, copyFileSync, mkdirSync, rmSync, writeFileSync } from 'node:
11
11
  import { join } from 'node:path';
12
12
 
13
13
  import { runLog } from '../log.mjs';
14
- import { RUN_DIR_MODE } from '../run-record.mjs';
14
+ import { RUN_DIR_MODE, atomicWrite, ensureDriverDir, paths } from '../run-record.mjs';
15
+ import { withWorkbook } from './report-document.mjs';
15
16
 
16
17
  export const grpRead = (p, mode) => { try { chmodSync(p, mode); } catch { /* best-effort */ } };
17
18
 
@@ -104,3 +105,42 @@ export async function refreshStaffPages({ regenSurfaces, poolRoot, skipRegen, ru
104
105
  return error;
105
106
  }
106
107
  }
108
+
109
+ /**
110
+ * Publish one run, in the order every report shape follows. `shape` supplies what differs between the shapes; this holds
111
+ * the order, so a step added to publishing is added once:
112
+ *
113
+ * read the run → open its pool folder → keep the run's working record there → build the report document → build the
114
+ * workbook → name the workbook on the document → write the document to the run → write the pages and data files →
115
+ * write `meta.json` → refresh the staff pages.
116
+ *
117
+ * The document is built once and kept in the run's own record, never the pool. A build that throws costs every surface
118
+ * that reads it, as a throw in any of them always has: `shape.surfaces` and `shape.meta` read only the document, and the
119
+ * record fails the publish when there is none. `shape.warn(what, error)` says so in the shape's own words, `what` being
120
+ * 'not built' or 'not written'. `regenIndex` and `regenSurfaces` come with the shape for the reason `finishPoolRun` takes
121
+ * them as arguments.
122
+ *
123
+ * @param {{ read(input): Promise<object>, keep(pool, read): object|void, document(read, kept): object,
124
+ * workbook(pool, document, read): Promise<{auditFile: string|null, auditError: string|null, built: any}>,
125
+ * surfaces(pool, document, read, kept, workbook): object, meta(document, surfaces): object,
126
+ * result(parts): object, warn(what: string, e: unknown): void, regenIndex: Function, regenSurfaces: Function }} shape
127
+ * @param {{ poolRoot: string, runId: string, runDir?: string|null, skipRegen?: boolean }} input the publisher's arguments
128
+ */
129
+ export async function publishRun(shape, input) {
130
+ const { poolRoot, runId, runDir = null, skipRegen = false } = input;
131
+ const read = await shape.read(input);
132
+ const pool = openPoolRun(poolRoot, runId, { runDir });
133
+ const kept = shape.keep(pool, read) ?? {};
134
+ let document = null;
135
+ try { document = shape.document(read, kept); } catch (e) { shape.warn('not built', e); }
136
+ const workbook = await shape.workbook(pool, document, read);
137
+ if (document) document = withWorkbook(document, { auditFile: workbook.auditFile, auditError: workbook.auditError });
138
+ if (document && runDir) {
139
+ try { ensureDriverDir(runDir); atomicWrite(paths(runDir).reportDocument, JSON.stringify(document, null, 1) + '\n'); }
140
+ catch (e) { shape.warn('not written', e); }
141
+ }
142
+ const surfaces = shape.surfaces(pool, document, read, kept, workbook);
143
+ const total = finishPoolRun({ writeRO: pool.writeRO, poolRoot, skipRegen, regenIndex: shape.regenIndex, meta: shape.meta(document, surfaces) });
144
+ await refreshStaffPages({ regenSurfaces: shape.regenSurfaces, poolRoot, skipRegen, runDir });
145
+ return shape.result({ read, pool, kept, workbook, surfaces, total });
146
+ }