clearotron 0.5.0 → 0.5.1-beta.0

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 (123) hide show
  1. package/CONTRIBUTING.md +2 -2
  2. package/INSTALL.md +334 -302
  3. package/QUICKSTART.md +12 -4
  4. package/README.md +12 -7
  5. package/THIRD-PARTY-NOTICES.md +4 -4
  6. package/bin/README.md +14 -11
  7. package/bin/clearotron.mjs +1 -1
  8. package/bin/connect.mjs +73 -25
  9. package/bin/example.mjs +4 -2
  10. package/bin/onboard.mjs +562 -336
  11. package/bin/start.mjs +184 -36
  12. package/bin/update.mjs +26 -13
  13. package/build-info.json +2 -2
  14. package/docs/PORTAL.md +2 -2
  15. package/docs/architecture/02-architecture.md +3 -3
  16. package/docs/architecture/04-configuration-reference.md +1 -2
  17. package/docs/architecture/05-config-governance.md +1 -1
  18. package/docs/architecture/06-operations-runbook.md +1 -1
  19. package/driver/CHANGELOG.md +77 -0
  20. package/driver/README.md +2 -2
  21. package/driver/config-inventory.mjs +20 -11
  22. package/driver/contract-e3-backlog.mjs +27 -27
  23. package/driver/contract-e3-baseline.json +2 -2
  24. package/driver/contract-vocabulary.mjs +1 -1
  25. package/driver/degraded-parts.mjs +67 -3
  26. package/driver/dev-portal.mjs +1 -1
  27. package/driver/digest-queue.mjs +5 -5
  28. package/driver/driver.config.mjs +9 -9
  29. package/driver/engine/CONTRACT.md +1 -1
  30. package/driver/engine/anthropic-agent.mjs +4 -2
  31. package/driver/engine/mcp/band-server.mjs +1 -21
  32. package/driver/engine/mcp/clarivate-propose-tool.mjs +26 -0
  33. package/driver/engine/mcp/clarivate-server.mjs +2 -18
  34. package/driver/engine/mcp/fixture-register-server.mjs +33 -0
  35. package/driver/engine/mcp/gather-config.mjs +48 -7
  36. package/driver/engine/mcp/recording-server.mjs +206 -14
  37. package/driver/engine/mcp/supplemental.mjs +4 -2
  38. package/driver/engine/openai-agent.mjs +3 -1
  39. package/driver/engine/probe.mjs +10 -0
  40. package/driver/filing-goods.mjs +95 -0
  41. package/driver/findings-model.mjs +3 -0
  42. package/driver/gateway.mjs +42 -40
  43. package/driver/knockout-assess-record.mjs +54 -4
  44. package/driver/knockout-correction-record.mjs +342 -0
  45. package/driver/knockout-frame-record.mjs +4 -2
  46. package/driver/knockout-register-read.mjs +705 -0
  47. package/driver/knockout-register-record.mjs +222 -0
  48. package/driver/knockout-review-record.mjs +96 -25
  49. package/driver/narrative-refutation-record.mjs +87 -1
  50. package/driver/order-tables.mjs +23 -0
  51. package/driver/owner-use-check.mjs +5 -2
  52. package/driver/package.json +1 -1
  53. package/driver/partial-payload-baseline.json +8 -0
  54. package/driver/pipeline-knockout.mjs +506 -313
  55. package/driver/pipeline.mjs +179 -86
  56. package/driver/portal-local-auth.mjs +7 -1
  57. package/driver/portal-service.mjs +62 -6
  58. package/driver/progress.mjs +2 -2
  59. package/driver/publish/index.mjs +18 -21
  60. package/driver/publish/knockout.mjs +40 -18
  61. package/driver/publish/render-knockout.mjs +40 -27
  62. package/driver/publish/report-dates.mjs +43 -0
  63. package/driver/recall-reconciliation.mjs +2 -2
  64. package/driver/record-goods.mjs +50 -9
  65. package/driver/register-count.mjs +12 -59
  66. package/driver/register-fixture-marker.mjs +22 -0
  67. package/driver/register-plan.mjs +48 -0
  68. package/driver/register-records.mjs +84 -266
  69. package/driver/register-taint.mjs +2 -2
  70. package/driver/repair-composers.mjs +15 -8
  71. package/driver/result-noun-fields.mjs +6 -2
  72. package/driver/run-requirements.mjs +54 -4
  73. package/driver/runner.mjs +4 -13
  74. package/driver/skills/clearance-register/providers/clarivate.md +2 -2
  75. package/driver/skills/knockout-assess/SKILL.md +101 -100
  76. package/driver/skills/knockout-frame/SKILL.md +3 -1
  77. package/driver/skills/knockout-register-read/SKILL.md +77 -0
  78. package/driver/stages-knockout.mjs +159 -98
  79. package/driver/stages.mjs +4 -2
  80. package/driver/suite-census.json +389 -71
  81. package/driver/systemd/README.md +2 -2
  82. package/driver/verify-knockout.mjs +175 -39
  83. package/driver/verify.mjs +10 -9
  84. package/mcp-server/CHANGELOG.md +4 -0
  85. package/mcp-server/CONNECT.md +4 -0
  86. package/mcp-server/demo-mode.mjs +6 -0
  87. package/mcp-server/lib/demo-texts.mjs +38 -0
  88. package/mcp-server/lib/http-handler.mjs +7 -1
  89. package/mcp-server/lib/knockout.mjs +3 -2
  90. package/mcp-server/lib/options.mjs +3 -1
  91. package/mcp-server/lib/plan.mjs +6 -1
  92. package/mcp-server/mint-token.mjs +1 -1
  93. package/mcp-server/package.json +1 -1
  94. package/mcp-server/serve.mjs +11 -0
  95. package/mcp-server/server.mjs +13 -5
  96. package/package.json +1 -1
  97. package/portal-ui/dist/assets/{index-D2wrw9cH.css → index-AtB9ZpDH.css} +29 -0
  98. package/portal-ui/dist/assets/{index-DcLbvFmQ.js → index-C1oE78Wk.js} +161 -195
  99. package/portal-ui/dist/index.html +2 -2
  100. package/portal-ui/package.json +4 -4
  101. package/providers/README.md +4 -4
  102. package/providers/_shared/execute-plan.mjs +45 -1
  103. package/providers/_shared/term-shape.mjs +1 -1
  104. package/providers/clarivate/src/capabilities.js +7 -6
  105. package/providers/clarivate/src/core.js +11 -7
  106. package/providers/clarivate/src/wider-list.js +104 -0
  107. package/providers/oauth-mcp-bridge/CHANGELOG.md +4 -0
  108. package/providers/oauth-mcp-bridge/package.json +1 -1
  109. package/providers/signa/src/capabilities.js +0 -9
  110. package/scripts/e2e-first-time.mjs +8 -7
  111. package/scripts/freeze-example-run.mjs +2 -2
  112. package/scripts/settings-render-check.mjs +5 -3
  113. package/scripts/test-run.mjs +8 -2
  114. package/shared/client-door.mjs +11 -8
  115. package/shared/connect-clients.mjs +10 -4
  116. package/shared/demo-connection.mjs +43 -0
  117. package/shared/demo-start-args.mjs +7 -2
  118. package/shared/invocation.mjs +18 -3
  119. package/shared/permanent-install.mjs +14 -0
  120. package/shared/scope.mjs +8 -1
  121. package/shared/stdio-connect.mjs +43 -21
  122. package/shared/trigger-lane.mjs +7 -0
  123. package/shared/tty-style.mjs +21 -5
@@ -0,0 +1,705 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ //
4
+ // knockout-register-read.mjs — the knockout's register moment: the counts, then a reading step that asks what the
5
+ // reading rule calls for, name by name.
6
+ //
7
+ // WHAT IT REPLACED. The lane listed the name and up to twelve forms from a fixed table, each with an equal share of
8
+ // 100 records, cut in the register's own order. Measured on an eight-name production batch: 160 records read, 125 of
9
+ // them on a mechanical form and none of those on the reviewing lawyer's list; one exact answer held 903 filings and
10
+ // 25 reached the rating step; five names answered zero on all three counts while she listed 97 rows for them.
11
+ //
12
+ // ONE SEARCH SHAPE WITH THE CLEARANCE (ruled 2026-09-26: a knockout is a clearance with less effort and depth). The
13
+ // run writes a small frozen plan, one register axis per instructed name, and the questions go through the clearance's
14
+ // own mint and executor: `register_propose_supplemental`, with its goods, market and class narrowing, its 600-record
15
+ // fetch limit, its capability gaps and its safety net. What differs is the lever: the plan holds only the name itself.
16
+ //
17
+ // THE MODEL SEES THE COUNT BEFORE ANYTHING IS READ. Code takes the counts and fetches nothing; the step then reads a list
18
+ // it can read in full or narrows the question, and the name's own question is one it must ask. Code reads a name's own
19
+ // list itself only when no model turn can: the step failed, or a test injected its register in-process.
20
+ //
21
+ // WHAT THE RECORD SAYS. A zero, a failure, a question not asked and a crowd not read are four different facts, and
22
+ // `terms` keeps them four. Counts come from the register. What the reading step carried forward goes to the rating
23
+ // step; what it set aside stays on the record with its reason, and in the band with its rows.
24
+ //
25
+ // NO MODEL TOUCHES A ROW. The step names record ids; this module joins them to what the register answered.
26
+
27
+ import { appendFileSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
28
+ import { dirname, join } from "node:path";
29
+
30
+ import { driverDir } from "../shared/driver-dir.mjs";
31
+ import { kebab } from "./search-policy.mjs";
32
+ import { resolveRegions } from "./register-plan.mjs";
33
+ import { reachableRegions } from "./register-availability.mjs";
34
+ import { RECORD_BASIS, fixtureLister, toRecord } from "./register-records.mjs";
35
+ import { ENUMERATE_CEILING_DEFAULT } from "../providers/_shared/enumerate.mjs";
36
+ export { writeFixtureMarker } from "./register-fixture-marker.mjs";
37
+ import { withFilingGoods } from "./filing-goods.mjs";
38
+
39
+ export const QUESTION_PLAN_FILE = "register-plan.json";
40
+ export const BAND_DIR = "register-units";
41
+
42
+ /** The register axis of one instructed name. The research key, so two names can never share one. PURE. */
43
+ export const knockoutAxis = (name) => `ko-${kebab(name)}`;
44
+
45
+ /**
46
+ * The forms a name is asked as: its written alternatives where the request gives one item in more than one spelling or
47
+ * word order (the frame's `alternatives`), each its own question and all tied to the name; else the name itself. PURE.
48
+ */
49
+ export function formsOfName(name, framed = null) {
50
+ const alternatives = (Array.isArray(framed?.alternatives) ? framed.alternatives : []).map((t) => String(t ?? "").trim()).filter(Boolean);
51
+ return alternatives.length ? alternatives : [String(name ?? "").trim()];
52
+ }
53
+
54
+ /** The qid of one form's own question: the name's identical qid, or that with its position after the first. PURE. */
55
+ export const formQid = (name, i = 0) => (i ? `${openingQid(name, "identical")}:${i}` : openingQid(name, "identical"));
56
+
57
+ /** The band one name's questions are written to, inside this run's folder. PURE. */
58
+ export const knockoutBandPath = (runDir, name) => join(String(runDir ?? ""), BAND_DIR, `${knockoutAxis(name)}-band.json`);
59
+
60
+ /** The qid of a name's opening question, the name each row of the reading record answers to. PURE. */
61
+ export const openingQid = (name, key) => `${knockoutAxis(name)}:${key}`;
62
+
63
+ const ints = (v) => (Array.isArray(v) ? v : []).filter((n) => Number.isInteger(n));
64
+ const sameClassList = (a, b) => JSON.stringify([...a].map(String).sort()) === JSON.stringify([...b].map(String).sort());
65
+
66
+ /** The classes one name is searched in: its own where the request names them, else the batch's, else the frame's. PURE. */
67
+ export function classesForName(row, batchClasses, framed = null) {
68
+ const own = ints(row?.classes);
69
+ if (own.length) return own;
70
+ const batch = ints(batchClasses);
71
+ return batch.length ? batch : ints(framed?.classes);
72
+ }
73
+
74
+ /**
75
+ * The run's frozen question plan: the name itself, per instructed name, on that name's own axis. PURE.
76
+ *
77
+ * Provenance "mark" is what tells the safety net these are the identical mark's own required read, and regions on an
78
+ * entry stay empty so each inherits the plan's: the order's offices, less any this deployment cannot reach. Classes the
79
+ * frame added carry the question the bound allows them, the identical mark in that class (ruled 2026-09-21), and a class
80
+ * another name was instructed in is not an addition.
81
+ */
82
+ export function knockoutQuestionPlan({ marks, classes = null, jurisdictions = null, capabilities = null, unreachable = [], framedMarks = [] }) {
83
+ const { regions: covered, worldwide } = resolveRegions(jurisdictions, capabilities);
84
+ const { regions } = reachableRegions(covered, unreachable, capabilities?.offices?.covered, worldwide === true);
85
+ const framedByName = new Map((framedMarks ?? []).map((f) => [String(f?.name ?? "").trim().toLowerCase(), f]));
86
+ const rows = (marks ?? []).map((m) => {
87
+ const name = String(m?.name ?? "").trim();
88
+ const framed = framedByName.get(name.toLowerCase()) ?? null;
89
+ return { name, framed, nice: classesForName(m, classes, framed).map(String) };
90
+ });
91
+ const instructed = new Set(rows.flatMap((r) => r.nice));
92
+ const entries = [];
93
+ const added = new Map();
94
+ for (const { name, framed, nice } of rows) {
95
+ const axis = knockoutAxis(name);
96
+ formsOfName(name, framed).forEach((term, i) => entries.push({ qid: formQid(name, i), axis, predicate: "exact", term, nice_classes: nice, regions: [],
97
+ provenance: "mark", expected_kind: "enumerate", origin: "plan" }));
98
+ for (const c of ints(framed?.beltAndBraces).map(String)) {
99
+ if (instructed.has(c)) continue;
100
+ const reason = String(framed?.classesPlain ?? "").trim() || "added by the frame for the client's own goods";
101
+ entries.push({ qid: openingQid(name, `added-class-${c}`), axis, predicate: "exact", term: name, nice_classes: [c], regions: [],
102
+ provenance: "mark", expected_kind: "enumerate", origin: "plan", added_class_reason: reason });
103
+ if (!added.has(c)) added.set(c, reason);
104
+ }
105
+ }
106
+ return {
107
+ schema: "register-plan/1", plan_version: 1,
108
+ derived_from: { job_key: "knockout", variants_fingerprint: "knockout" },
109
+ regions, nice_classes: [...instructed],
110
+ added_classes: [...added].map(([cls, reason]) => ({ class: cls, reason })),
111
+ entries,
112
+ };
113
+ }
114
+
115
+ /** The questions the frame's added classes owe one name, from the run's frozen plan: each class's identical-name question. */
116
+ export function addedClassQuestions(runDir, name) {
117
+ let plan = null;
118
+ try { plan = JSON.parse(readFileSync(questionPlanPath(runDir), "utf8")); } catch { return []; }
119
+ return addedOf(plan, name);
120
+ }
121
+ const addedOf = (plan, name) => (plan?.entries ?? []).filter((e) => e?.axis === knockoutAxis(name) && e?.added_class_reason)
122
+ .map((e) => ({ qid: String(e.qid), class: String(e.nice_classes?.[0]) }));
123
+
124
+ /** The blocks of one name's band as they stand, by qid. A band not yet written holds none. */
125
+ export function knockoutBandBlocks(runDir, name) {
126
+ const out = new Map();
127
+ let doc;
128
+ try { doc = JSON.parse(readFileSync(knockoutBandPath(runDir, name), "utf8")); } catch { return out; }
129
+ for (const b of Array.isArray(doc) ? doc : []) if (b?.qid) out.set(String(b.qid), b);
130
+ return out;
131
+ }
132
+
133
+ /** The questions a name's reading step asked, in the order it asked them. A file not yet written holds none. */
134
+ export function knockoutProposals(runDir, name) {
135
+ const path = join(String(runDir ?? ""), BAND_DIR, `${knockoutAxis(name)}-supplemental-plan.json`);
136
+ try {
137
+ const doc = JSON.parse(readFileSync(path, "utf8"));
138
+ return { entries: Array.isArray(doc?.entries) ? doc.entries : [], rejected: Array.isArray(doc?.rejected) ? doc.rejected : [] };
139
+ } catch { return { entries: [], rejected: [] }; }
140
+ }
141
+
142
+ /** Does this row of a reading record speak for that added class's question: by its qid, or by naming the class? PURE. */
143
+ export const namesAddedClass = (question, owed) => {
144
+ const said = String(question ?? "");
145
+ return said === owed.question || new RegExp(`\\bclass(?:es)?\\s*${owed.addedClass}\\b`, "i").test(said);
146
+ };
147
+
148
+ /** The record ids a reading record's `carried` groups hold, flattened. PURE. */
149
+ export const carriedIds = (row) => new Set((row?.carried ?? []).flatMap((g) => (Array.isArray(g?.records) ? g.records : [])).map(String));
150
+
151
+ const rowsOf = (block) => (Array.isArray(block?.records) ? block.records : []);
152
+ /** Was this block answered with the rows the register holds under it? */
153
+ const wasRead = (block) => block?.state === "enumerated" && block?.error !== true;
154
+ /** A block with no answer: a failure, or a refusal the register's rules make permanent. Never a zero. */
155
+ const hasFailed = (block) => Boolean(block) && block.error === true;
156
+ /** A block the register answered with a count too large to fetch. */
157
+ const isCrowd = (block) => Boolean(block) && block.state === "incomplete" && block.error !== true;
158
+ /** Every term one question named, trimmed and in lower case. PURE. */
159
+ const termsAsked = (e) => (Array.isArray(e?.terms) ? e.terms : [e?.term]).map((t) => String(t ?? "").trim().toLowerCase()).filter(Boolean);
160
+ /** Does this question reach only classes the frame added? It then has no bearing on the name's original scope. PURE. */
161
+ const onlyAddedClasses = (e, framed) => {
162
+ const added = new Set(ints(framed?.beltAndBraces).map(String));
163
+ for (const c of ints(framed?.classes)) added.delete(String(c));
164
+ const asked = Array.isArray(e?.nice_classes) ? e.nice_classes.map(String) : [];
165
+ return asked.length > 0 && asked.every((c) => added.has(c));
166
+ };
167
+
168
+ /**
169
+ * Which questions the reading record must say something about, per name: every list read whose rows were not all
170
+ * carried, and every count or crowd nothing narrowed or read. A zero and a failure are not on it: the first says
171
+ * itself, and the second is the engine's to report, not the model's to excuse. PURE over its inputs.
172
+ */
173
+ export function questionsOwed({ name, countsEntry = null, blocks = new Map(), proposals = [], carried = new Set(), framed = null, addedQuestions = [] }) {
174
+ const owed = [];
175
+ const answered = (e) => wasRead(blocks.get(String(e?.qid)));
176
+ const narrowedBy = (qid) => proposals.some((e) => e?.narrows === qid && answered(e));
177
+ const norm = (v) => String(v ?? "").trim().toLowerCase();
178
+ const forms = formsOfName(name, framed);
179
+ const isForm = (e, form) => termsAsked(e).includes(norm(form));
180
+ const identical = countsEntry?.counts?.identical;
181
+ const figures = Array.isArray(identical?.alternatives) ? identical.alternatives : [{ term: forms[0], total: identical?.total }];
182
+
183
+ // A FORM'S OWN QUESTION IS ASKED WHATEVER ITS COUNT. A count above zero with no question on the form is not work that
184
+ // can be set aside with a reason: the rule reads the identical mark first, narrowing it if it is a crowd. A question
185
+ // the register then failed to answer has been asked.
186
+ forms.forEach((form, i) => {
187
+ const total = figures.find((f) => norm(f?.term) === norm(form))?.total;
188
+ if (!(Number.isFinite(total) && total > 0)) return;
189
+ const qid = formQid(name, i);
190
+ const onForm = proposals.filter((e) => e?.predicate === "exact" && isForm(e, form) && !onlyAddedClasses(e, framed));
191
+ if (!blocks.has(qid) && !onForm.some((e) => blocks.has(String(e?.qid)))) {
192
+ owed.push({ question: qid, count: total, kind: "identical-not-asked", mustAsk: true });
193
+ return;
194
+ }
195
+ const read = wasRead(blocks.get(qid)) || onForm.some(answered);
196
+ const failed = hasFailed(blocks.get(qid)) || onForm.some((e) => hasFailed(blocks.get(String(e?.qid))));
197
+ if (!read && !failed && !narrowedBy(qid)) owed.push({ question: qid, count: total, kind: "counted-not-read" });
198
+ });
199
+
200
+ // A COMBINED COUNT IS ANSWERED FORM BY FORM. Reading one variant says nothing about the others under the same number, so
201
+ // the count stays owed until every form that can hold a filing has been read, or a row says why not.
202
+ const heldTerms = (predicate) => new Set(proposals.filter((e) => e?.predicate === predicate && answered(e)).flatMap(termsAsked));
203
+ const opening = [
204
+ ["containing", countsEntry?.counts?.containing, "default", (c) => (Array.isArray(c?.alternatives) ? c.alternatives.map((a) => ({ form: a?.term, holds: a?.total > 0 })) : [{ form: forms[0], holds: true }])],
205
+ ["close", countsEntry?.counts?.close, "exact", (c) => (Array.isArray(c?.forms) ? c.forms : []).map((f) => ({ form: f?.form, holds: c.joined === true || f?.total > 0 || f?.approximate === true }))],
206
+ ];
207
+ for (const [key, cell, predicate, formsUnder] of opening) {
208
+ const total = cell?.total;
209
+ if (!(Number.isFinite(total) && total > 0)) continue;
210
+ const qid = openingQid(name, key);
211
+ const under = formsUnder(cell);
212
+ const read = heldTerms(predicate);
213
+ const unread = under.filter((f) => f.holds && !read.has(norm(f.form))).map((f) => String(f.form));
214
+ if (under.length ? !unread.length : narrowedBy(qid)) continue;
215
+ owed.push({ question: qid, count: total, kind: "counted-not-read", ...(under.length > 1 && unread.length ? { unread } : {}) });
216
+ }
217
+ // AN ADDED CLASS OWES AN OUTCOME THOUGH NOTHING WAS COUNTED IN IT: the plan took it on. An answer of any kind is one; a crowd
218
+ // or a failure goes on as any other question's does.
219
+ for (const q of addedQuestions) {
220
+ if (!blocks.has(q.qid) && !proposals.some((e) => e?.predicate === "exact" && forms.some((f) => isForm(e, f)) && (e?.nice_classes ?? []).map(String).includes(q.class) && blocks.has(String(e?.qid)))) {
221
+ owed.push({ question: q.qid, count: null, kind: "added-class-no-outcome", addedClass: q.class });
222
+ }
223
+ }
224
+ const byQid = new Map(proposals.map((e) => [String(e?.qid), e]));
225
+ const formOfQid = (qid) => forms.find((_, i) => formQid(name, i) === qid) ?? forms.find((f) => isForm(byQid.get(qid), f)) ?? null;
226
+ for (const [qid, block] of blocks) {
227
+ if (hasFailed(block)) continue;
228
+ if (isCrowd(block)) {
229
+ // A crowd on a form's own question is answered by any list read on that form; any other by what names it.
230
+ const form = byQid.get(qid)?.predicate === "exact" || !byQid.has(qid) ? formOfQid(qid) : null;
231
+ if (narrowedBy(qid) || (form && proposals.some((e) => e?.predicate === "exact" && isForm(e, form) && !onlyAddedClasses(e, framed) && answered(e)))) continue;
232
+ if (owed.some((o) => o.question === qid)) continue;
233
+ owed.push({ question: qid, count: block.total_hits ?? null, kind: "crowd-not-read" });
234
+ continue;
235
+ }
236
+ if (!wasRead(block)) continue;
237
+ const unread = rowsOf(block).map((r) => String(r?.record_id ?? "")).filter((id) => !carried.has(id));
238
+ if (unread.length) owed.push({ question: qid, count: unread.length, kind: "read-not-carried", records: unread });
239
+ }
240
+ return owed;
241
+ }
242
+
243
+ /**
244
+ * One band row as the neutral record's mapper reads it. A row holds the office's numbers on its screen row where the
245
+ * register hydrates (Clarivate), or in its own raw body where the search row is the record (Signa). PURE.
246
+ */
247
+ function neutralRow(r) {
248
+ const s = r?.screen && typeof r.screen === "object" ? r.screen : {};
249
+ const raw = r?.raw && typeof r.raw === "object" ? r.raw : {};
250
+ return { ...r,
251
+ application_number: r?.application_number ?? s.application_number ?? raw.application_number ?? null,
252
+ registration_number: r?.registration_number ?? s.registration_number ?? raw.registration_number ?? raw.ir_number ?? null,
253
+ ir_number: r?.ir_number ?? s.ir_number ?? raw.ir_number ?? null,
254
+ filing_route: r?.filing_route ?? s.filing_route ?? raw.filing_route ?? null,
255
+ office_url: r?.office_url ?? s.office_url ?? raw.office_url ?? null };
256
+ }
257
+
258
+ /** What one question was, for the record's `terms` row and for the basis a report prints. PURE. */
259
+ function questionRow({ entry, block, formKeys = new Set() }) {
260
+ const term = entry?.term ?? (Array.isArray(entry?.terms) ? entry.terms.join(" | ") : null);
261
+ const isExactName = entry?.predicate === "exact" && formKeys.has(String(entry?.term ?? "").trim().toLowerCase());
262
+ const failed = hasFailed(block);
263
+ const crowd = isCrowd(block);
264
+ const fetched = wasRead(block) ? rowsOf(block).length : 0;
265
+ const total = Number.isFinite(block?.total_hits) ? block.total_hits : null;
266
+ return {
267
+ term, basis: isExactName ? "identical" : "close",
268
+ qid: entry?.qid ?? null, predicate: entry?.predicate ?? null,
269
+ ...(Array.isArray(entry?.goods_text) && entry.goods_text.length ? { goods: entry.goods_text } : {}),
270
+ ...(Array.isArray(entry?.regions) && entry.regions.length ? { regions: entry.regions } : {}),
271
+ ...(Array.isArray(entry?.nice_classes) && entry.nice_classes.length ? { classes: entry.nice_classes } : {}),
272
+ ...(entry?.narrows ? { narrows: entry.narrows } : {}),
273
+ ...(entry?.rationale ? { purpose: entry.rationale } : {}),
274
+ ok: !failed && Boolean(block), fetched, total,
275
+ ...(Array.isArray(block?.warnings) && block.warnings.length ? { warnings: block.warnings } : {}),
276
+ state: !block ? "not-asked" : failed ? "failed" : crowd ? "crowd-not-read" : total === 0 ? "zero" : "read",
277
+ ...(crowd ? { setAside: true } : {}),
278
+ ...(failed ? { reason: String(block?.reason ?? "the register did not answer this question").slice(0, 300) } : {}),
279
+ };
280
+ }
281
+
282
+ /** The name's own question, from its count and, where it was read, its block. A failed read is a failure whatever was counted. PURE. */
283
+ function identicalRow({ term: form, qid, cell, block, plainRead = false, narrowed = false, askFailed = false }) {
284
+ const counted = Number.isFinite(cell?.total);
285
+ const approximate = cell?.approximate === true;
286
+ const answered = counted || approximate;
287
+ const failed = hasFailed(block) || (!answered && !wasRead(block));
288
+ // Read under its own qid, or by a question on the name that kept the name's scope. A list a narrowing answered keeps
289
+ // its own count and its own state: the crowd it replaced stays on the record.
290
+ const read = wasRead(block) || plainRead;
291
+ const total = counted ? cell.total : (Number.isFinite(block?.total_hits) ? block.total_hits : null);
292
+ return { term: form.toUpperCase(), basis: "identical", label: "the name itself", qid, predicate: "exact",
293
+ ok: !failed, fetched: wasRead(block) ? rowsOf(block).length : 0, total: approximate ? null : total,
294
+ state: failed ? "failed" : read ? "read" : total === 0 ? "zero" : narrowed ? "narrowed" : askFailed ? "failed" : "crowd-not-read",
295
+ ...(approximate ? { approximate: true, floor: Number.isFinite(cell?.floor) ? cell.floor : null } : {}),
296
+ ...(Array.isArray(block?.warnings) && block.warnings.length ? { warnings: block.warnings } : {}),
297
+ ...(failed ? { reason: String(block?.reason ?? cell?.cause ?? cell?.unavailable ?? "the register did not answer this question").slice(0, 300) } : {}),
298
+ // THE COUNT STANDS, AND THE QUESTION ASKED ON IT HAS ITS OWN ROW SAYING IT FAILED, so this one is neither a crowd set aside nor a second failure.
299
+ ...(!failed && !read && !narrowed && !askFailed && (total > 0 || approximate) ? { setAside: true } : {}) };
300
+ }
301
+
302
+ /**
303
+ * The run's record of its filings, as every later stage reads it: one row per question, the rows the reading step
304
+ * carried forward, and what it set aside. PURE over its inputs.
305
+ *
306
+ * `reading` is what the reading step had settled when it ended. A name with no row in it carries every row its questions
307
+ * hold, so the rating step still has what the run paid for, and the step's absence is on the record.
308
+ */
309
+ export function knockoutRecordsDoc({ marks, classes = null, jurisdictions = null, provider, capabilities = null, unreachable = [],
310
+ counts = null, reading = null, readBlocks, readProposals, framedMarks = [], now = () => new Date() }) {
311
+ const { regions: covered, deferred, worldwide } = resolveRegions(jurisdictions, capabilities);
312
+ const { regions, dropped } = reachableRegions(covered, unreachable, capabilities?.offices?.covered, worldwide === true);
313
+ const officeScope = dropped.length
314
+ ? { listed: regions, unlisted: dropped.map((d) => ({ office: d.office, memberId: d.memberId, missing: [...(d.missing ?? [])] })) } : null;
315
+ const batchClasses = ints(classes);
316
+ const plan = knockoutQuestionPlan({ marks, classes, jurisdictions, capabilities, unreachable, framedMarks });
317
+ const countsByName = new Map((counts?.marks ?? []).map((m) => [String(m?.name ?? "").trim().toLowerCase(), m]));
318
+ const readingByName = new Map((reading?.marks ?? []).map((m) => [String(m?.name ?? "").trim().toLowerCase(), m]));
319
+ const framedByName = new Map((framedMarks ?? []).map((f) => [String(f?.name ?? "").trim().toLowerCase(), f]));
320
+
321
+ const rows = (marks ?? []).map((m) => {
322
+ const name = String(m?.name ?? "").trim();
323
+ const own = ints(m?.classes);
324
+ const scoped = own.length ? own : batchClasses;
325
+ const key = name.toLowerCase();
326
+ const blocks = readBlocks(name);
327
+ const { entries, rejected = [] } = readProposals(name);
328
+ const countsEntry = countsByName.get(key) ?? null;
329
+ const read = readingByName.get(key) ?? null;
330
+
331
+ const terms = [];
332
+ const identicalCell = countsEntry?.counts?.identical;
333
+ // ONE ROW PER FORM OF THE NAME, all tied to it. A name given in two word orders is asked as each, and neither is a
334
+ // near form of the other.
335
+ const forms = formsOfName(name, framedByName.get(key));
336
+ const formKeys = new Set(forms.map((f) => f.toLowerCase()));
337
+ const ownLists = [];
338
+ forms.forEach((form, i) => {
339
+ const qid = formQid(name, i);
340
+ const block = blocks.get(qid);
341
+ const figure = Array.isArray(identicalCell?.alternatives) ? identicalCell.alternatives.find((a) => String(a?.term).toLowerCase() === form.toLowerCase()) : identicalCell;
342
+ const onForm = entries.filter((e) => e?.predicate === "exact" && termsAsked(e).includes(form.toLowerCase()) && !onlyAddedClasses(e, framedByName.get(key)) && wasRead(blocks.get(String(e?.qid))));
343
+ const sameScope = (e) => !e?.nice_classes?.length || sameClassList(e.nice_classes, scoped);
344
+ const isPlain = (e) => !e?.goods_text?.length && !e?.regions?.length && sameScope(e);
345
+ const askedOnForm = entries.filter((e) => e?.predicate === "exact" && termsAsked(e).includes(form.toLowerCase()) && !onlyAddedClasses(e, framedByName.get(key)));
346
+ const askFailed = !onForm.length && askedOnForm.some((e) => hasFailed(blocks.get(String(e?.qid))));
347
+ terms.push(identicalRow({ term: form, qid, cell: figure, block, plainRead: onForm.some(isPlain), narrowed: onForm.some((e) => !isPlain(e)), askFailed }));
348
+ ownLists.push({ form, qid, block });
349
+ });
350
+ // THE COUNTED FORMS, each as the question it was. Counted, not listed: a form with filings under it that nothing
351
+ // read is a crowd not read, which is what stops a report saying no filing stands. A joined count holds no per-form
352
+ // figure, so its total is the question's and its forms ride beside it.
353
+ const formsCell = countsEntry?.counts?.close;
354
+ const stackRead = entries.some((e) => e?.predicate === "exact" && !formKeys.has(String(e?.term ?? "").trim().toLowerCase()) && wasRead(blocks.get(String(e?.qid))));
355
+ const formsTotal = Number.isFinite(formsCell?.total) ? formsCell.total : null;
356
+ for (const f of Array.isArray(formsCell?.forms) ? formsCell.forms : []) {
357
+ const n = formsCell.joined ? null : (Number.isFinite(f?.total) ? f.total : null);
358
+ const approx = f?.approximate === true;
359
+ const answered = formsCell.joined ? formsTotal !== null : (n !== null || approx);
360
+ const holds = formsCell.joined ? formsTotal > 0 : (n > 0 || approx);
361
+ terms.push({ term: f?.form ?? null, basis: "close", label: `close variation (${(f?.rules ?? []).join(", ")})`, qid: openingQid(name, "close"), predicate: "exact",
362
+ ok: answered, fetched: 0, total: n, state: !answered ? "failed" : holds ? "crowd-not-read" : "zero",
363
+ ...(approx ? { approximate: true, floor: Number.isFinite(f?.floor) ? f.floor : null } : {}),
364
+ ...(!answered ? { reason: String(f?.cause ?? f?.unavailable ?? formsCell?.cause ?? formsCell?.unavailable ?? "the register did not answer this question").slice(0, 300) } : {}),
365
+ ...(holds && !stackRead ? { setAside: true } : {}) });
366
+ }
367
+ for (const e of entries) terms.push(questionRow({ entry: e, block: blocks.get(String(e?.qid)), formKeys }));
368
+ // AN ADDED CLASS WITH NO ANSWER STAYS ON THE RECORD UNRESOLVED, with the reason where one was given: neither searched nor
369
+ // clean. A reading that did not finish leaves the same gap, recorded the same way.
370
+ const owedAdded = questionsOwed({ name, countsEntry: null, blocks, proposals: entries, framed: framedByName.get(key) ?? null, addedQuestions: addedOf(plan, name) }).filter((o) => o.addedClass != null);
371
+ for (const o of owedAdded) {
372
+ const said = [...(read?.not_asked ?? []), ...(read?.set_aside ?? [])].find((r) => namesAddedClass(r?.question, o));
373
+ terms.push({ term: name.toUpperCase(), basis: "identical", label: "the name itself", qid: o.question, predicate: "exact", classes: [Number(o.addedClass)], ok: true, fetched: 0, total: null,
374
+ state: "not-asked", unresolved: true, setAside: true, ...(said ? { reason: String(said.why).slice(0, 300) } : {}) });
375
+ }
376
+
377
+ // A QUESTION THE STEP ASKED AND THE RUN DID NOT SEND is on the record as one, the safety net's refusal included:
378
+ // never a clean answer, and never missing.
379
+ for (const r of rejected) {
380
+ const q = r?.proposal ?? {};
381
+ terms.push({ term: q.term ?? (Array.isArray(q.terms) ? q.terms.join(" | ") : null), basis: "close", predicate: q.predicate ?? null,
382
+ ok: false, fetched: 0, total: null, state: "not-asked", ...(r?.issue ? { refused: String(r.issue).slice(0, 300) } : {}) });
383
+ }
384
+
385
+ // THE ROWS. Carried by the reading step with its reason, or, with no row for the name, all it held. Every other row
386
+ // read stays with the question that found it, so a later step can reach it.
387
+ const carried = read ? carriedIds(read) : null;
388
+ const groupOf = new Map((read?.carried ?? []).flatMap((g) => (g?.records ?? []).map((id) => [String(id), g])));
389
+ const found = new Map();
390
+ const setAside = new Map();
391
+ const take = (block, term, basis, qid) => {
392
+ if (!wasRead(block)) return;
393
+ for (const raw of rowsOf(block)) {
394
+ const id = String(raw?.record_id ?? "");
395
+ if (!id || found.has(id)) continue;
396
+ const row = { ...toRecord(neutralRow(raw), { term, basis, provider }), question: qid };
397
+ if (carried && !carried.has(id)) { if (!setAside.has(id)) setAside.set(id, row); continue; }
398
+ found.set(id, { ...row, ...(groupOf.get(id)?.why ? { carriedBecause: groupOf.get(id).why } : {}) });
399
+ }
400
+ };
401
+ for (const { form, qid, block } of ownLists) take(block, form.toUpperCase(), "identical", qid);
402
+ for (const e of entries) {
403
+ const row = questionRow({ entry: e, block: blocks.get(String(e?.qid)), formKeys });
404
+ take(blocks.get(String(e?.qid)), row.term, row.basis, row.qid);
405
+ }
406
+ const records = [...found.values()];
407
+ // A row carried under one question and read again under another is carried, whichever came first.
408
+ for (const id of found.keys()) setAside.delete(id);
409
+ const setAsideRecords = [...setAside.values()];
410
+ // A ROW NAMING FILINGS HOLDS THOSE; A ROW NAMING NONE ANSWERS FOR THE REST OF THAT QUESTION'S LIST.
411
+ const namedUnder = (qid) => new Set((read?.set_aside ?? []).filter((g) => g.question === qid).flatMap((g) => g.records ?? []));
412
+ const setAsideIds = (qid) => rowsOf(blocks.get(qid)).map((r) => String(r?.record_id ?? "")).filter((id) => setAside.has(id) && !namedUnder(qid).has(id));
413
+
414
+ // WHAT THE LIST CAN BE COMPARED WITH: the distinct filings the name's questions returned, stated only where every question was read
415
+ // or answered zero. A sum across questions counted one filing once per question, and the name's own count again beside the
416
+ // re-ask that read it, and a question not read holds filings no one can say apart from these. A fraction compares one population.
417
+ const wholeRead = terms.length > 0 && terms.every((t) => t.ok && (t.state === "read" || t.state === "zero"));
418
+ const available = wholeRead ? records.length + setAsideRecords.length : null;
419
+ return {
420
+ name,
421
+ classes: scoped.length ? scoped : null,
422
+ classScope: scoped.length ? (own.length ? "mark" : "batch") : "all-classes",
423
+ terms,
424
+ records,
425
+ fetched: records.length,
426
+ available,
427
+ capped: false,
428
+ // WHAT THE STEP READ AND DID NOT CARRY, whole, so the rating step and the review can reach it and cite it.
429
+ ...(setAsideRecords.length ? { setAsideRecords } : {}),
430
+ reading: read
431
+ ? { setAside: (read.set_aside ?? []).map((g) => ({ ...g, records: g.records ?? setAsideIds(g.question) })),
432
+ notAsked: read.not_asked ?? [], openQuestions: read.open_questions ?? [],
433
+ ownerChecks: (read.carried ?? []).filter((g) => g?.check_owner === true).flatMap((g) => g.records ?? []) }
434
+ : { notFinished: true },
435
+ ...(officeScope ? { officeScope } : {}),
436
+ ...(deferred.length ? { deferredScope: deferred.map((d) => d.jurisdiction) } : {}),
437
+ };
438
+ });
439
+
440
+ return {
441
+ schema: 2,
442
+ provider, providerLabel: capabilities?.label ?? provider,
443
+ takenAt: now().toISOString(),
444
+ basis: RECORD_BASIS,
445
+ listedPredicates: ["identical", "close", "containing", "phonetic"],
446
+ scope: {
447
+ jurisdictions: (jurisdictions ?? []).length ? jurisdictions : null,
448
+ regions: regions.length ? regions : null,
449
+ deferredJurisdictions: deferred.length ? deferred.map((d) => d.jurisdiction) : null,
450
+ ...(officeScope ? { unreachableOffices: officeScope.unlisted } : {}),
451
+ classes: batchClasses.length ? batchClasses : null,
452
+ },
453
+ marks: rows,
454
+ };
455
+ }
456
+
457
+ /**
458
+ * The counts of a name given in several forms, one row per name. The count lane counted each form as its own name, because
459
+ * no register can count a list as one; the name's cells are their sum and say where the number came from, and a form with
460
+ * no answer leaves the cell open, as a partial sweep does. The forms' own rows stay on it, so a resume re-bills none. PURE.
461
+ */
462
+ export function foldFormCounts(counts, marks, framedMarks = []) {
463
+ const framedByName = new Map((framedMarks ?? []).map((f) => [String(f?.name ?? "").trim().toLowerCase(), f]));
464
+ const rowsByName = new Map((counts?.marks ?? []).map((m) => [String(m?.name ?? "").trim().toLowerCase(), m]));
465
+ const folded = (marks ?? []).flatMap((m) => {
466
+ const name = String(m?.name ?? "").trim();
467
+ const forms = formsOfName(name, framedByName.get(name.toLowerCase()));
468
+ const rows = forms.map((f) => rowsByName.get(f.toLowerCase())).filter(Boolean);
469
+ if (forms.length === 1 && forms[0].toLowerCase() === name.toLowerCase()) return rows;
470
+ if (!rows.length) return [];
471
+ const cell = (key) => {
472
+ const each = rows.map((r) => ({ term: r.name, total: r.counts?.[key]?.total ?? null, ...(r.counts?.[key]?.unavailable ? { unavailable: r.counts[key].unavailable } : {}) }));
473
+ const open = each.find((a) => !Number.isFinite(a.total));
474
+ return { total: open ? null : each.reduce((n, a) => n + a.total, 0), source: "alternatives", alternatives: each, ...(open ? { unavailable: open.unavailable ?? "not every written form could be counted" } : {}) };
475
+ };
476
+ const closeForms = rows.flatMap((r) => r.counts?.close?.forms ?? []);
477
+ return [{ ...rows[0], name, formRows: rows,
478
+ counts: { identical: cell("identical"), containing: cell("containing"), close: { ...cell("close"), forms: closeForms,
479
+ generated: rows.reduce((n, r) => n + (r.counts?.close?.generated ?? 0), 0), counted: rows.reduce((n, r) => n + (r.counts?.close?.counted ?? 0), 0),
480
+ truncated: rows.some((r) => r.counts?.close?.truncated), ...(rows.every((r) => r.counts?.close?.joined) ? { joined: true } : {}) } } }];
481
+ });
482
+ return { ...counts, marks: folded };
483
+ }
484
+
485
+ /** A folded counts record back to the rows the count lane reuses on a resume. PURE. */
486
+ export const unfoldFormCounts = (counts) => (counts ? { ...counts, marks: (counts.marks ?? []).flatMap((m) => m?.formRows ?? [m]) } : counts);
487
+
488
+ /** The rows the count lane counts: each written form of each name, on its own. PURE. */
489
+ export const countRowsOf = (marks, framedMarks = []) => {
490
+ const framedByName = new Map((framedMarks ?? []).map((f) => [String(f?.name ?? "").trim().toLowerCase(), f]));
491
+ return (marks ?? []).flatMap((m) => formsOfName(m?.name, framedByName.get(String(m?.name ?? "").trim().toLowerCase())).map((form) => ({ ...m, name: form })));
492
+ };
493
+
494
+ /**
495
+ * The record once the rating step has spoken, so the report has a row for what the rating rests on. A set-aside filing it cited
496
+ * moves up with the carried ones: a later step may overturn a set-aside, and this is how that reaches the page. A filing held
497
+ * under another name that it cited is copied under the name it was weighed for, and stays where it was found. The copy claims no
498
+ * search for this name: it carries where it was found apart from the fields that would say so, and counts as nothing here. PURE.
499
+ */
500
+ export function withCitedFilings(doc, findings) {
501
+ const marksByName = new Map((findings?.marks ?? []).map((m) => [String(m?.name ?? "").trim().toLowerCase(), m]));
502
+ const anywhere = new Map((doc?.marks ?? []).flatMap((m) => [...(m?.records ?? []), ...(m?.setAsideRecords ?? [])].map((r) => [String(r?.recordId), { row: r, name: m.name }])));
503
+ let changed = false;
504
+ const marks = (doc?.marks ?? []).map((entry) => {
505
+ const rated = marksByName.get(String(entry?.name ?? "").trim().toLowerCase());
506
+ if (!rated) return entry;
507
+ const cited = new Set([...(rated.registerReads ?? []).map((r) => r?.recordId), ...(rated.findings ?? []).flatMap((f) => f?.weighedFilings ?? [])].filter(Boolean).map(String));
508
+ const moved = (entry.setAsideRecords ?? []).filter((r) => cited.has(String(r?.recordId)));
509
+ const own = new Set([...(entry.records ?? []), ...(entry.setAsideRecords ?? [])].map((r) => String(r?.recordId)));
510
+ const fromOthers = [...cited].filter((id) => !own.has(id) && anywhere.has(id)).map((id) => {
511
+ const { row, name } = anywhere.get(id);
512
+ const { carriedBecause: _why, citedFromSetAside: _aside, question, matchedForm, matchedBasis, ...rest } = row;
513
+ return { ...rest, matchedForm: null, matchedBasis: null, foundUnder: { name, question: question ?? null, form: matchedForm ?? null, basis: matchedBasis ?? null } };
514
+ });
515
+ if (!moved.length && !fromOthers.length) return entry;
516
+ changed = true;
517
+ const left = (entry.setAsideRecords ?? []).filter((r) => !cited.has(String(r?.recordId)));
518
+ const { setAsideRecords: _old, ...rest } = entry;
519
+ const raised = moved.map((r) => ({ ...r, citedFromSetAside: true }));
520
+ return { ...rest, records: [...(entry.records ?? []), ...raised, ...fromOthers], fetched: (entry.records ?? []).length + raised.length, ...(left.length ? { setAsideRecords: left } : {}) };
521
+ });
522
+ return changed ? { ...doc, marks } : doc;
523
+ }
524
+
525
+ /** One ledger line per question, beside the counts' own, so one file answers what the register lane asked. */
526
+ export function appendQuestionReceipts(ledgerPath, doc, { provider, now = () => new Date() } = {}) {
527
+ if (!ledgerPath) return;
528
+ for (const m of doc?.marks ?? []) {
529
+ for (const t of m?.terms ?? []) {
530
+ if (t?.predicate === "exact" && t?.qid?.endsWith(":close")) continue; // counted by the count lane, which wrote its own line
531
+ try {
532
+ appendFileSync(ledgerPath, JSON.stringify({ ts: now().toISOString(), stage: "records", mark: m.name, term: t.term, basis: t.basis,
533
+ qid: t.qid ?? null, predicate: t.predicate ?? null, classes: m.classes, provider, ok: Boolean(t.ok), fetched: t.fetched ?? 0,
534
+ total: Number.isFinite(t.total) ? t.total : null, state: t.state ?? null,
535
+ ...(Array.isArray(t.warnings) && t.warnings.length ? { warnings: t.warnings } : {}),
536
+ ...(t.ok ? {} : { cause: String(t.reason ?? "unknown").slice(0, 300) }) }) + "\n");
537
+ } catch { /* receipts are best-effort, never fatal */ }
538
+ }
539
+ }
540
+ }
541
+
542
+ /** The lines the reading step opens on, code-owned and one per name: what it may ask under, and the counts. Nothing is read yet. PURE. */
543
+ export function readingTableLines({ marks, counts, classes = null, framedMarks = [], runDir }) {
544
+ const framedByName = new Map((framedMarks ?? []).map((f) => [String(f?.name ?? "").trim().toLowerCase(), f]));
545
+ const countsByName = new Map((counts?.marks ?? []).map((m) => [String(m?.name ?? "").trim().toLowerCase(), m]));
546
+ const cell = (c) => (Number.isFinite(c?.total) ? String(c.total) : "not available");
547
+ const instructed = new Set((marks ?? []).flatMap((m) => classesForName(m, classes, framedByName.get(String(m?.name ?? "").trim().toLowerCase()) ?? null)));
548
+ return (marks ?? []).map((m) => {
549
+ const name = String(m?.name ?? "").trim();
550
+ const key = name.toLowerCase();
551
+ const framed = framedByName.get(key) ?? null;
552
+ const c = countsByName.get(key)?.counts ?? {};
553
+ const nearSpellings = (c.close?.forms ?? []).map((f) => f?.form).filter(Boolean).join(" · ");
554
+ const nice = classesForName(m, classes, framed);
555
+ const added = ints(framed?.beltAndBraces).filter((n) => !instructed.has(n));
556
+ const forms = formsOfName(name, framed);
557
+ const own = c.identical?.alternatives
558
+ ? forms.map((f, i) => `"${f}" (\`${formQid(name, i)}\`): ${cell(c.identical.alternatives.find((a) => String(a?.term).toLowerCase() === f.toLowerCase()))}`).join("; ")
559
+ : `(\`${openingQid(name, "identical")}\`): ${cell(c.identical)}`;
560
+ return [
561
+ `- "${name}": axis \`${knockoutAxis(name)}\`, band \`${knockoutBandPath(runDir, name)}\`, classes [${nice.join(", ")}]${added.length ? `, added by the frame: ${added.map((n) => `class ${n} (\`${openingQid(name, `added-class-${n}`)}\`)`).join(", ")}` : ""}.`,
562
+ ` Identical ${own}. Containing (\`${openingQid(name, "containing")}\`): ${cell(c.containing)}. Mechanical near-spellings${nearSpellings ? ` ${nearSpellings}` : ""} (\`${openingQid(name, "close")}\`): ${cell(c.close)}.`,
563
+ ].join("\n");
564
+ });
565
+ }
566
+
567
+ /**
568
+ * One list in full, as a later step reads it: every row the question returned, each with the goods the run holds for it
569
+ * in the shipped evidence states (filing-goods.mjs). With `record_id`, all the wording this run holds for that one filing.
570
+ * Nothing is fetched. A row with no goods on file says so, and that is not a mismatch with the client's goods.
571
+ */
572
+ export function knockoutListView(runDir, { qid, record_id: recordId = null }, goodsOptions = {}) {
573
+ const want = String(qid ?? "").trim();
574
+ if (!want) return { error: "qid is required: the question whose list you are reading, as the propose tool or your opening message named it." };
575
+ const dir = join(String(runDir ?? ""), BAND_DIR);
576
+ let found = null;
577
+ let files = [];
578
+ try { files = readdirSync(dir).filter((f) => f.endsWith("-band.json")); } catch { files = []; }
579
+ for (const f of files) {
580
+ let doc;
581
+ try { doc = JSON.parse(readFileSync(join(dir, f), "utf8")); } catch { continue; }
582
+ for (const b of Array.isArray(doc) ? doc : []) if (String(b?.qid ?? "") === want) found = b;
583
+ if (found) break;
584
+ }
585
+ if (!found) return { error: `no question "${want}" has an answer in this run's bands. Ask it first; a name's counted opening questions have no list until one is read.` };
586
+ const records = rowsOf(found).map((r) => toRecord(neutralRow(r), { term: null, basis: null, provider: null }));
587
+ const held = withFilingGoods({ marks: [{ records }] }, runDir, goodsOptions).marks[0].records;
588
+ if (recordId != null && String(recordId).trim()) {
589
+ const one = held.find((r) => r.recordId === String(recordId).trim());
590
+ if (!one) return { error: `no filing "${String(recordId).slice(0, 120)}" under question "${want}". Copy record_id from that question's list.` };
591
+ return { qid: want, record_id: one.recordId, goods_state: one.goodsState, goods_from: one.goodsFrom, ...heldWording(one, runDir) };
592
+ }
593
+ return {
594
+ qid: want, state: found.state ?? null, total_hits: found.total_hits ?? null,
595
+ ...(found.reason ? { reason: String(found.reason).slice(0, 300) } : {}),
596
+ ...(found.error ? { error_answer: true } : {}),
597
+ ...(found.per_office_counts ? { per_office_counts: found.per_office_counts } : {}),
598
+ rows: held.map((r) => ({ record_id: r.recordId, mark: r.mark, owner: r.owner, owner_country: r.ownerCountry, status: r.status, office: r.territory, classes: r.classes,
599
+ filed: r.applicationDate, registered: r.registrationDate, goods: r.goods, goods_state: r.goodsState, goods_from: r.goodsFrom, goods_shortened: r.goodsShortened })),
600
+ };
601
+ }
602
+
603
+ /** All the wording held for one filing: its whole held record where one was written, else the statements its view carries. */
604
+ function heldWording(record, runDir) {
605
+ try { if (record.fullRecord) return { full_record: JSON.parse(readFileSync(join(String(runDir ?? ""), record.fullRecord), "utf8")) }; }
606
+ catch { /* the view below is what is left to read */ }
607
+ return { goods: record.goods };
608
+ }
609
+
610
+ /**
611
+ * The record with its goods on every row it holds, the carried and the set aside alike. Sends nothing. `runPrefix` is what
612
+ * lets a fetch that failed read as failed, not as a record never held: the call ledger answers it by run.
613
+ */
614
+ export function withHeldGoods(doc, runDir, goodsOptions = {}) {
615
+ const carried = withFilingGoods(doc, runDir, goodsOptions);
616
+ const setAside = withFilingGoods({ marks: (carried?.marks ?? []).map((m) => ({ records: m?.setAsideRecords ?? [] })) }, runDir, goodsOptions);
617
+ return { ...carried, marks: (carried?.marks ?? []).map((m, i) => (m?.setAsideRecords?.length ? { ...m, setAsideRecords: setAside.marks[i].records } : m)) };
618
+ }
619
+
620
+ /** The run a stage's session key belongs to: the key as the lane composes it, without its stage label. PURE. */
621
+ export const runPrefixOfSession = (sessionKey) => String(sessionKey ?? "").replace(/-knockout-[a-z-]+(#\d+)?(-rerun\d+)?$/, "") || null;
622
+
623
+ export const questionPlanPath = (runDir) => driverDir(runDir, QUESTION_PLAN_FILE);
624
+
625
+ // ── THE QUESTIONS' EXECUTOR: injected (tests) → a fixtures dir (the $0 offline guarantee) → the live register ─────────
626
+
627
+ const MATCH_MODES = Object.freeze({ exact: "exact", default: "default", phonetic: "phonetic", wildcard: "wildcard" });
628
+
629
+ /**
630
+ * A plan's questions, answered by a lister instead of a register, under the executor's own contract: one block per
631
+ * question merged into the band, a list over the fetch limit answered as a crowd, a failure answered as a failure and
632
+ * never as a zero. For offline runs and tests alone, and it sends nothing anywhere. Returns the executor's summary text.
633
+ */
634
+ export async function executeQuestionsWithLister(lister, { plan_path: planPath, axis, output_path: outputPath, qids = null }) {
635
+ const plan = JSON.parse(readFileSync(planPath, "utf8"));
636
+ const wanted = Array.isArray(qids) && qids.length ? new Set(qids.map(String)) : null;
637
+ const entries = (plan?.entries ?? []).filter((e) => e?.axis === axis && (!wanted || wanted.has(String(e?.qid))));
638
+ if (!entries.length) return { type: "text", text: `ERROR: the plan carries no entries for axis "${axis}".` };
639
+ let band = [];
640
+ try { const had = JSON.parse(readFileSync(outputPath, "utf8")); if (Array.isArray(had)) band = had; } catch { /* first write */ }
641
+ const owned = new Set(entries.map((e) => String(e.qid)));
642
+ const states = {};
643
+ const blocks = [];
644
+ // What the name's own question was asked over: a question over other classes is a narrower one, and is keyed as one.
645
+ let nameClasses = null;
646
+ try {
647
+ const frozen = JSON.parse(readFileSync(driverDir(dirname(dirname(outputPath)), QUESTION_PLAN_FILE), "utf8"));
648
+ nameClasses = (frozen?.entries ?? []).find((f) => f?.axis === axis && f?.provenance === "mark" && !f?.added_class_reason)?.nice_classes ?? null;
649
+ } catch { nameClasses = null; }
650
+ const sameClasses = (a) => JSON.stringify([...(a ?? [])].map(String).sort()) === JSON.stringify([...(nameClasses ?? [])].map(String).sort());
651
+ for (const e of entries) {
652
+ const terms = Array.isArray(e?.terms) ? e.terms : [e?.term];
653
+ const base = { qid: e.qid, query: { term: e.term ?? null, terms: e.terms ?? null, predicate: e.predicate ?? null } };
654
+ const rows = [];
655
+ const seen = new Set();
656
+ const warnings = [];
657
+ let total = 0;
658
+ let failure = null;
659
+ if (e?.unsupported) failure = String(e.unsupported_reason ?? "this register cannot express this question");
660
+ for (const t of failure ? [] : terms) {
661
+ let r;
662
+ try {
663
+ r = await lister(t, { classes: sameClasses(e.nice_classes) ? [] : (e.nice_classes ?? []), regions: e.regions ?? [],
664
+ matchMode: MATCH_MODES[e?.predicate] ?? "default", goods: e.goods_text ?? null, scoped: true });
665
+ } catch (err) { r = { ok: false, reason: `record listing threw: ${String(err?.message ?? err).slice(0, 200)}` }; }
666
+ if (!r?.ok || !Array.isArray(r?.records)) { failure = String(r?.reason ?? "the question was not answered"); break; }
667
+ total += Number.isFinite(r.total) ? r.total : r.records.length;
668
+ if (Array.isArray(r.warnings)) warnings.push(...r.warnings);
669
+ for (const row of r.records) {
670
+ const id = String(row?.record_id ?? "");
671
+ if (id && !seen.has(id)) { seen.add(id); rows.push(row); }
672
+ }
673
+ }
674
+ if (failure) {
675
+ blocks.push({ state: "incomplete", ...base, total_hits: 0, fetched: 0, sample: [], error: true, reason: `provider error: ${failure}` });
676
+ states[e.qid] = "error";
677
+ } else if (total > ENUMERATE_CEILING_DEFAULT) {
678
+ blocks.push({ state: "incomplete", ...base, total_hits: total, fetched: 0, sample: [], reason: `total_hits ${total} exceeds the enumerate ceiling ${ENUMERATE_CEILING_DEFAULT}` });
679
+ states[e.qid] = "incomplete";
680
+ } else {
681
+ blocks.push({ state: "enumerated", ...base, total_hits: total, count: rows.length, records: rows, ...(warnings.length ? { warnings } : {}) });
682
+ states[e.qid] = "enumerated";
683
+ }
684
+ }
685
+ mkdirSync(dirname(outputPath), { recursive: true });
686
+ writeFileSync(`${outputPath}.tmp`, JSON.stringify([...band.filter((b) => !owned.has(String(b?.qid))), ...blocks], null, 2) + "\n");
687
+ renameSync(`${outputPath}.tmp`, outputPath);
688
+ return { type: "text", text: JSON.stringify({ skipped: [], states }) };
689
+ }
690
+
691
+ /**
692
+ * Who answers this run's questions, and how. A fixture run never falls through to a live register: `offline` with no
693
+ * directory is `none`, and the lane says the filings were not listed.
694
+ */
695
+ export function resolveQuestionExecutor({ lister = null, adapter = null, agentId = null, sessionKey = null, recordLog = null, fixtureDir = null, offline = false } = {}) {
696
+ const viaLister = (fn) => async ({ planPath, axis, outputPath, qids }) => {
697
+ const r = await executeQuestionsWithLister(fn, { plan_path: planPath, axis, output_path: outputPath, qids });
698
+ return String(r?.text ?? "").startsWith("ERROR") ? { ok: false, cause: r.text } : { ok: true };
699
+ };
700
+ if (typeof lister === "function") return { source: "injected", execute: viaLister(lister) };
701
+ if (fixtureDir) return { source: `fixtures:${fixtureDir}`, fixtureDir, execute: viaLister(fixtureLister(fixtureDir)) };
702
+ if (offline || typeof adapter?.executePlan !== "function") return { source: "none", execute: null };
703
+ return { source: "provider", execute: ({ planPath, axis, outputPath, qids }) =>
704
+ adapter.executePlan({ planPath, axis, outputPath, qids }, { agentId, sessionKey, recordLog }) };
705
+ }