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
@@ -0,0 +1,98 @@
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
+ // A STAGE'S MANUALS RIDE ITS OPENING MESSAGE. A stage message starts by telling the model which manuals to
5
+ // read ("First, read and follow exactly: …"), and every session then spent turns and tokens opening the same
6
+ // files with its own read tool: the same manual, re-read by each card, half and register unit of a run.
7
+ // Here the gateway puts each named manual's text into the message itself, in the order named and with the
8
+ // company's overrides applied, so the session starts holding them and two sessions of one stage send the
9
+ // same leading text. Design set the sentence and the order (2026-11-19): the manuals first, then the stage's own
10
+ // instructions and the run's material, as the message already has them.
11
+ //
12
+ // ONE PLACE, BOTH ENGINES. It runs in the gateway on the text handed to `engine.runTurn`, so the Claude and
13
+ // Codex adapters receive the same bytes by construction. Each adapter still rewrites `skills/…md` references
14
+ // to absolute paths afterwards, so a supporting file a manual points at stays readable by path.
15
+ //
16
+ // WHAT IT DOES NOT TOUCH:
17
+ // - a continuation: a resumed session already holds its opening message, so the gateway does not call this
18
+ // for a warm resume or a warm patch;
19
+ // - a manual that will not resolve or read: it stays named in today's read sentence, so the model meets
20
+ // the missing file exactly as before and the run's existing recovery sees it. No new way to fail;
21
+ // - the dispatch record and the methodology witness: both keep reading the composed message, the record
22
+ // of what the stage asked for. What this inlined is returned beside the text, for the run log.
23
+ import { createHash } from "node:crypto";
24
+ import { readFileSync } from "node:fs";
25
+ import { dirname, join } from "node:path";
26
+
27
+ /** The sentence that replaces the read instruction, word for word as design set it (2026-11-19). */
28
+ export const MANUALS_SENTENCE = "Apply the following manuals to this stage, in the order given.";
29
+
30
+ const READ_SENTENCE = "First, read and follow exactly: ";
31
+ const SKILL_REF = /(?<![\w/.])skills\/[A-Za-z0-9._/-]+\.md/g;
32
+ // The read sentence as stages compose it: `reads()` writes a comma list, and the two register stages write
33
+ // "… SKILL.md (the shared spine) then … unit.md (MODE A — UNIT)." It ends at the first full stop that
34
+ // follows a manual's name or its parenthesis.
35
+ const READ_SENTENCE_RE = /First, read and follow exactly: (.*?\.md(?: \([^)]*\))?)\.(?=\s|$)/;
36
+
37
+ /** Where a manual's text is, for the engine's resolver or, without one, the skills folder. null when neither. */
38
+ const locate = (ref, { resolve, skillsDir }) => (resolve ? resolve(ref) : skillsDir ? join(dirname(skillsDir), ref) : null);
39
+
40
+ /**
41
+ * The message with its read sentence replaced by the manuals' text, and what went in. PURE but for reading
42
+ * the manual files. Never throws: a manual that cannot be read is left to the read sentence.
43
+ *
44
+ * @returns {{ text: string, inlined: {ref: string, bytes: number, sha256: string}[], missing: string[] }}
45
+ */
46
+ export function inlineManuals(message, { resolve = null, skillsDir = null, read = (p) => readFileSync(p, "utf8") } = {}) {
47
+ const text = String(message ?? "");
48
+ const m = text.match(READ_SENTENCE_RE);
49
+ if (!m || (!resolve && !skillsDir)) return { text, inlined: [], missing: [] };
50
+ const refs = [...new Set(m[1].match(SKILL_REF) ?? [])];
51
+ const inlined = [], missing = [], blocks = [];
52
+ for (const ref of refs) {
53
+ let body = null;
54
+ try { const p = locate(ref, { resolve, skillsDir }); body = p ? read(p) : null; } catch { body = null; }
55
+ // A manual that cannot be read keeps its place in the order given, as a read of that one manual.
56
+ if (typeof body !== "string") { missing.push(ref); blocks.push(`${READ_SENTENCE}${ref}.`); continue; }
57
+ inlined.push({ ref, bytes: Buffer.byteLength(body), sha256: createHash("sha256").update(body).digest("hex") });
58
+ blocks.push(`=== MANUAL: ${ref} ===\n${body.replace(/\s+$/, "")}\n=== END MANUAL: ${ref} ===`);
59
+ }
60
+ if (!inlined.length) return { text, inlined: [], missing };
61
+ const parts = [MANUALS_SENTENCE, ...blocks];
62
+ // A sentence that continued on the same line (the register stages' exclusion) starts on its own line after the manuals.
63
+ const at = m.index + m[0].length;
64
+ const tail = text.slice(at).replace(/^ (?=\S)/, "\n\n");
65
+ return { text: text.slice(0, m.index) + parts.join("\n\n") + tail, inlined, missing };
66
+ }
67
+
68
+ // The engine adapters rewrite each `skills/…md` reference to an absolute path after this module runs, the block headers
69
+ // included, so a header names either form. The absolute form is joined with the platform's separator: on Windows the header
70
+ // reads `C:\…\skills\a\SKILL.md`, so a manual's name takes either separator.
71
+ const MANUAL_NAME = String.raw`\S*?skills[\\/][A-Za-z0-9._\\/-]+\.md`;
72
+ const BLOCK_RE = new RegExp(String.raw`=== MANUAL: (${MANUAL_NAME}) ===\n[\s\S]*?\n=== END MANUAL: \1 ===`, "g");
73
+ const LEFT_RE = new RegExp(String.raw`^\s*First, read and follow exactly: (${MANUAL_NAME})\.(?=\s|$)`);
74
+
75
+ /**
76
+ * The stage's own text from a message this module filled: the manual blocks taken out again, and the read
77
+ * sentence put back naming the same manuals in the same order, each as the message names it (relative, or absolute once
78
+ * an engine adapter has rewritten it). For a reader that must tell a stage's
79
+ * instructions from its manuals, as the mock engines do when they decide which stage they are answering.
80
+ * A message with no manual blocks comes back unchanged. PURE.
81
+ */
82
+ export function stageTextOf(message) {
83
+ const text = String(message ?? "");
84
+ const at = text.indexOf(MANUALS_SENTENCE);
85
+ if (at < 0) return text;
86
+ const refs = [];
87
+ let end = at + MANUALS_SENTENCE.length;
88
+ // The blocks, and a read sentence in the place of each manual that could not be read, in the order given.
89
+ for (;;) {
90
+ BLOCK_RE.lastIndex = end;
91
+ const b = BLOCK_RE.exec(text);
92
+ if (b && /^\s*$/.test(text.slice(end, b.index))) { refs.push(b[1]); end = b.index + b[0].length; continue; }
93
+ const left = text.slice(end).match(LEFT_RE);
94
+ if (left) { refs.push(left[1]); end += left[0].length; continue; }
95
+ break;
96
+ }
97
+ return `${text.slice(0, at)}${READ_SENTENCE}${refs.join(", ")}.${text.slice(end)}`;
98
+ }
@@ -21,8 +21,9 @@
21
21
  // same. A manual that changed since the stage was told it, or that holds no line long enough to count, is null on its
22
22
  // own. Recording only, and it never throws: the attempt's result does not depend on it.
23
23
  import { createHash } from "node:crypto";
24
- import { closeSync, openSync, readFileSync, readSync } from "node:fs";
24
+ import { readFileSync } from "node:fs";
25
25
  import { CODEX_SHOWN_OUTPUT_BYTES } from "./engine/mcp/codex-config.mjs";
26
+ import { streamLines } from "./engine/session-record.mjs";
26
27
 
27
28
  const MIN_CHARS = 20;
28
29
  const NUMBERED = /^\s*\d+(?:\t|→|:)/;
@@ -67,20 +68,6 @@ const READERS = {
67
68
  },
68
69
  };
69
70
 
70
- /** Each line of a saved stream as bytes, read a megabyte at a time, so a long stream is never held whole. */
71
- function* fileLines(file) {
72
- const fd = openSync(file, "r");
73
- try {
74
- const chunk = Buffer.alloc(1 << 20);
75
- let rest = Buffer.alloc(0);
76
- for (let n; (n = readSync(fd, chunk, 0, chunk.length, null)) > 0;) {
77
- let buf = Buffer.concat([rest, chunk.subarray(0, n)]), at;
78
- while ((at = buf.indexOf(10)) >= 0) { yield buf.subarray(0, at); buf = buf.subarray(at + 1); }
79
- rest = Buffer.from(buf);
80
- }
81
- if (rest.length) yield rest;
82
- } finally { closeSync(fd); }
83
- }
84
71
 
85
72
  const textLines = function* (text) { for (const l of String(text ?? "").split("\n")) yield Buffer.from(l); };
86
73
 
@@ -141,6 +128,7 @@ export function measureManualsSeen(turn, told, engine, { readManual } = {}) {
141
128
  if (!Array.isArray(told) || !told.length) return null;
142
129
  const s = turn?.stream;
143
130
  if (!s?.file || s.present !== true || s.reason) return null;
144
- return manualShares(told, shownFrom(fileLines(s.file), engine), readManual ? { readManual } : {});
131
+ // A closed session's stream is gzipped and a killed one's is plain; the session record's own reader reads either.
132
+ return manualShares(told, shownFrom(streamLines(s.file), engine), readManual ? { readManual } : {});
145
133
  } catch { return null; }
146
134
  }
@@ -27,7 +27,7 @@
27
27
  //
28
28
  // RECORDING ONLY, and it never throws: a logo that could not be had never stops a report.
29
29
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
30
- import { join } from "node:path";
30
+ import { join, resolve, sep } from "node:path";
31
31
  import { normalizeRecordUri } from "../providers/_shared/record-uri.mjs";
32
32
  import { readRecordArtifacts } from "./registry-fidelity.mjs";
33
33
  import { DRIVER_DIR, driverDir, ensureDriverDir } from "./run-record.mjs";
@@ -142,3 +142,33 @@ export function logosStep(runDir, doc) {
142
142
  try { runLog(runDir, doc ? { event: "logos", register: doc.register, ...counts } : { event: "logos-not-written" }); } catch { /* a log line never stops a publish */ }
143
143
  return counts;
144
144
  }
145
+
146
+ const SHOWN_TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
147
+
148
+ /**
149
+ * The logos a report shows, by registration: `fetched` rows carry the image as a data address, so the delivered
150
+ * report fetches nothing and never names the register's image address; `failed` rows carry no image and read "Logo
151
+ * not retrieved"; every other row is left out, since it draws nothing. A row's file must sit inside the run's logo
152
+ * folder and open as the image type it was saved as, or it is left out. Never throws. IMPURE: it reads the run.
153
+ */
154
+ export function logosForReport(runDir) {
155
+ const out = new Map();
156
+ if (!runDir) return out;
157
+ let doc = null;
158
+ try { doc = JSON.parse(readFileSync(driverDir(runDir, LOGOS_FILE), "utf8")); } catch { return out; }
159
+ const folder = resolve(runDir, DRIVER_DIR, LOGOS_DIR) + sep;
160
+ for (const row of Array.isArray(doc?.rows) ? doc.rows : []) {
161
+ const ref = normalizeRecordUri(row?.ref);
162
+ if (!ref) continue;
163
+ if (row.state === "failed") { out.set(ref, { state: "failed" }); continue; }
164
+ if (row.state !== "fetched" || typeof row.file !== "string" || !SHOWN_TYPES.has(row.contentType)) continue;
165
+ const at = resolve(runDir, row.file);
166
+ if (!at.startsWith(folder)) continue;
167
+ try {
168
+ const bytes = readFileSync(at);
169
+ if (imageTypeOf(bytes)?.type !== row.contentType) continue;
170
+ out.set(ref, { state: "fetched", src: `data:${row.contentType};base64,${bytes.toString("base64")}` });
171
+ } catch { /* an image that cannot be read is not shown */ }
172
+ }
173
+ return out;
174
+ }
@@ -50,6 +50,7 @@ import { createHash } from "node:crypto";
50
50
 
51
51
  import { promotableRecords } from "./publish/render-knockout.mjs";
52
52
  import { isResearchAnswer } from "./research-answers.mjs"; // a reply the formatter could not read is no answer
53
+ import { RunCancelled } from "./cancel.mjs";
53
54
 
54
55
  /** The literal the clearance lane uses for an honest non-answer. Copied, not re-worded. */
55
56
  export const NO_RESULT = "perplexity_research — no result";
@@ -153,7 +154,10 @@ export async function runOwnerChecks({ owners, exec, runDir, ledgerPath = null,
153
154
  const started = Date.now();
154
155
  let r;
155
156
  try { r = await exec(query, { mark: o.mark, preset }); }
156
- catch (e) { r = { ok: false, cause: `executor threw: ${String(e?.message ?? e).slice(0, 200)}` }; }
157
+ catch (e) {
158
+ if (e instanceof RunCancelled) throw e; // a stop is not an unanswered check: the run ends, and asks no more
159
+ r = { ok: false, cause: `executor threw: ${String(e?.message ?? e).slice(0, 200)}` };
160
+ }
157
161
 
158
162
  // THE SEARCHES BEHIND THE ANSWER ARE KEPT, answered or not, beside the answer's own name: the answer
159
163
  // alone cannot say which pages the lookup was handed.
@@ -2,7 +2,7 @@
2
2
  "name": "clearotron-driver",
3
3
  "private": true,
4
4
  "type": "module",
5
- "version": "0.7.0-beta.0",
5
+ "version": "0.7.0-beta.1",
6
6
  "license": "AGPL-3.0-only",
7
7
  "description": "Deterministic driver for the trademark clearance workflow: orchestration in code (fan-out, fan-in barrier, gating, retries); the model does judgment leaves only, through a reasoning CLI spawned per stage.",
8
8
  "engines": {
@@ -34,7 +34,7 @@ import { registerAdapter as adapterForRegister } from "./engine/run-choices.mjs"
34
34
  import { StageFailure, stageWallFields } from "./run-outcome.mjs"; // — the wall fields the spine already carries
35
35
  import { endTheDeliveredRun, runShell } from "./run-shell.mjs"; // — the runner and the delivered ending both products share
36
36
  import { logTurnaroundReconciliation } from "./run-quote.mjs";
37
- import { RunCancelled, assertNotCancelledBeforePublish, isCancelled, readCancel } from "./cancel.mjs"; // stop-by-user: never the failure lane below
37
+ import { RunCancelled, assertNotCancelledBeforePublish, isCancelled, readCancel, stopsWithTheRun } from "./cancel.mjs"; // stop-by-user: never the failure lane below
38
38
  import { loadFrameworkManifest, parseFrameworkManifest, frameworkFor, DEFAULT_FRAMEWORK } from "./framework.mjs";
39
39
  import { attachFrameworkMethod, methodPathFor, FROZEN_METHOD_FILE } from "./framework-method.mjs";
40
40
  import { KO_STAGES, KO_STEPS, KO_STEP_REGISTER_COUNT, koSteps, koPaths, kebab, knockoutGridSpec, KNOCKOUT_WEB, KNOCKOUT_MINUTES_BAR, knockoutBarVerdict, koChunks } from "./stages-knockout.mjs";
@@ -56,7 +56,7 @@ import { knockoutAssessSourceDefects } from "./knockout-assess-record.mjs";
56
56
  import { correctionsAppliedTable, unresolvedFlags } from "./corrections-feedforward.mjs";
57
57
  import { settledKnockoutReading } from "./knockout-register-record.mjs";
58
58
  import { stripNextStepSections } from "./knockout-next-step.mjs";
59
- import { publishKnockout, composeKnockoutEmail, knockoutName } from "./publish/knockout.mjs";
59
+ import { publishKnockout, composeKnockoutCoverNote, knockoutName } from "./publish/knockout.mjs";
60
60
  import { markLogos, logosStep } from "./mark-logos.mjs";
61
61
  import { writeRunStatus, readRunStatus, rollupStatus, identitySeed, recordTransition, resumeRecord } from "./progress.mjs"; // — the identity seed is shared; the stepper is not
62
62
  import { batchMarkName } from "./mark-name.mjs";
@@ -595,6 +595,8 @@ async function readTheRegister({ ctx, job, K, run, agent, markRows, plan, counts
595
595
  offline: countExec.source.startsWith("fixtures:"),
596
596
  fixtureDir: job?.registerFixtures?.records ?? null,
597
597
  });
598
+ // The questions the code asks the register itself read the stop first, as the counts do; a model turn's are the gateway's.
599
+ if (typeof exec.execute === "function") exec.execute = stopsWithTheRun(run.runDir, "knockout-register-read", exec.execute);
598
600
  const refusal = countExec.source.startsWith("fixtures:") && exec.source === "none"
599
601
  ? "this run counted from fixtures and its job declares no `registerFixtures.records` directory, so the "
600
602
  + "filings behind the counts were not listed — a fixture run never reaches a live register."
@@ -646,6 +648,9 @@ async function readTheRegister({ ctx, job, K, run, agent, markRows, plan, counts
646
648
  }
647
649
  } catch (e) {
648
650
  if (e instanceof StageFailure && (e.rateLimited || e.resetsAt)) throw e;
651
+ // A STOP IS NOT A STEP THAT DID NOT FINISH. Read as one, the lane settled the reading and went on to the owner checks,
652
+ // and paid for them after the stop (measured 2026-11-19).
653
+ if (e instanceof RunCancelled) throw e;
649
654
  note(`register reading step did not finish (non-fatal): ${String(e?.message ?? e).slice(0, 200)}`);
650
655
  runLog(run.runDir, { event: "knockout-register-read-failed", cause: String(e?.message ?? e).slice(0, 300) });
651
656
  reading = settledKnockoutReading(run.runDir);
@@ -864,6 +869,9 @@ export async function knockoutInner(ctx, job, opts = {}) {
864
869
  // frame turn" is exactly what a skip prevents, and prevents earlier than a throw did.
865
870
  // (pipelineInner's register preflight is skipped for this lane — knockout has no register machinery.)
866
871
  sweep = resolveSweepExecutor(opts);
872
+ // Every paid call the lane makes itself reads the stop first (cancel.mjs stopsWithTheRun): the web grid, the owner
873
+ // checks that share its executor, and below, the register counts and listings.
874
+ sweep = { ...sweep, grid: stopsWithTheRun(run.runDir, "knockout-sweep", sweep.grid), exec: stopsWithTheRun(run.runDir, "knockout-owner-checks", sweep.exec) };
867
875
 
868
876
  // Depth 2 preflight — the SAME discipline, for the register count. Both refusals it can return
869
877
  // are structural (a provider that cannot count; a territory scope it cannot express), so they are
@@ -892,6 +900,7 @@ export async function knockoutInner(ctx, job, opts = {}) {
892
900
  // is a fact about the run, so it arrives with the run and lands on its record.
893
901
  fixtureDir: job?.registerFixtures?.counts ?? null,
894
902
  });
903
+ countExec = { ...countExec, count: stopsWithTheRun(run.runDir, "knockout-register-count", countExec.count) };
895
904
  // EVERY required variable. `Boolean(process.env[credEnv])` here was a half-check: it
896
905
  // reported "credential present" for a euipo instance holding the id and no secret, and would
897
906
  // have done the same for a free-tier instance holding one member of two. fixed the
@@ -1093,7 +1102,10 @@ export async function knockoutInner(ctx, job, opts = {}) {
1093
1102
  while (attempts < 2) {
1094
1103
  attempts++;
1095
1104
  try { r = await grid(spec, { mark: m.name, preset, reasoning }); }
1096
- catch (e) { r = { ok: false, cause: `executor threw: ${String(e?.message ?? e).slice(0, 200)}` }; }
1105
+ catch (e) {
1106
+ if (e instanceof RunCancelled) throw e; // a stop is not a degraded mark
1107
+ r = { ok: false, cause: `executor threw: ${String(e?.message ?? e).slice(0, 200)}` };
1108
+ }
1097
1109
  if (Array.isArray(r?.raw) && r.raw.length) raw.push({ attempt: attempts, items: r.raw });
1098
1110
  if (r?.ok || r?.outage === true || !/^grid: /.test(String(r?.cause ?? ""))) break;
1099
1111
  }
@@ -1243,6 +1255,7 @@ export async function knockoutInner(ctx, job, opts = {}) {
1243
1255
  } catch (e) {
1244
1256
  // Structural only — runOwnerChecks itself never throws. Non-fatal by the same rule as the
1245
1257
  // listing above: a report is never withheld for a check that could not run.
1258
+ if (e instanceof RunCancelled) throw e;
1246
1259
  note(`owner use-check failed (non-fatal): ${e.message}`);
1247
1260
  runLog(run.runDir, { event: "knockout-owner-checks-failed", cause: String(e?.message ?? e).slice(0, 300) });
1248
1261
  }
@@ -1514,7 +1527,9 @@ export async function knockoutInner(ctx, job, opts = {}) {
1514
1527
  // They are FLAGS: the packet, the state and the send below are byte-identical with or without them.
1515
1528
  // The product's name, from the run's frozen policy, for the email's first line and its subject alike.
1516
1529
  const productName = knockoutName(policy);
1517
- const emailHtml = composeKnockoutEmail({ findings: merged, framework: ctx.framework, overall, reports: published.reports, auditUrl: published.auditUrl, job, registerCounts, qcFlags: published.qcFlags, productName });
1530
+ // From the run's report document where it has one (composeKnockoutCoverNote); the lane's own values are what a run
1531
+ // published before the document is composed from.
1532
+ const emailHtml = composeKnockoutCoverNote(run.runDir, { findings: merged, framework: ctx.framework, overall, reports: published.reports, auditUrl: published.auditUrl, job, registerCounts, qcFlags: published.qcFlags, productName });
1518
1533
  writeFileSync(K.emailBody, emailHtml);
1519
1534
  const nMarks = merged.marks.length;
1520
1535
  const refTag = job.ref ? ` (${job.ref})` : "";
@@ -204,7 +204,7 @@ import { recordedScopeLedgerRows } from "./clearance-variants-record.mjs";
204
204
  import { renderFormNeighbourhoodJson, parseFormNeighbourhoodJson, dispatchedQueriesFromBand, formGapDirectives, markText } from "./form-neighbourhood.mjs"; import { loadOrdinaryWords } from "./ordinary-words.mjs";
205
205
  import { createRepairLedger, retryCannotHelpWith, isContentShapedFail, isFallbackEligible } from "./repairs.mjs";
206
206
  import { isEntrypoint } from "../shared/is-entrypoint.mjs"; // — one entry-point test, all spellings
207
- import { isCancelled } from "./cancel.mjs"; // stop-by-user: a distinct class, never classified as a failure; isCancelled is the resume door's own refusal (2155)
207
+ import { isCancelled, stopsWithTheRun } from "./cancel.mjs"; // stop-by-user: a distinct class, never classified as a failure; isCancelled is the resume door's own refusal
208
208
  import { reachableCommand } from "../shared/invocation.mjs"; // — a printed command the reader can type later, from anywhere
209
209
  export { StageFailure, buildFailurePacket, isDesignedRefusal, stageWallFields, terminalReasonFields }; // moved to run-outcome.mjs; importers read them here as before
210
210
  export { correctionReading, correctionRows, flagOrdinals, recordCorrectionsBasis, repairUnnamedRemovals, rollbackCorrectivePass }; // moved to steps/corrections.mjs; importers read them here as before
@@ -1652,7 +1652,21 @@ for (const x of DISPATCH_EXTRAS) {
1652
1652
 
1653
1653
  // The case-law profiles joined to the findings as they stand: the profiles carry the writer's numbers, and after a
1654
1654
  // grouping the delivered record has its own (joinCaseLawProfiles).
1655
- const caseLawJoin = (P, findings) => joinCaseLawProfiles(parseCaseLawProfiles(readFileSync(P.caseLaw, "utf8")), findings, readFold(P.runDir)?.map?.modelToFolded ?? null);
1655
+ //
1656
+ // A JOIN THAT FAILS IS RECORDED BEFORE IT IS THROWN. Every caller asks only when the case-law file is there, and catches
1657
+ // the throw as "no case-law layer", so a join that failed on a file that exists read exactly like a run with no case law:
1658
+ // the cards and the delivery checks went on without it and nothing said so. The run log now carries the failure; what
1659
+ // each caller does next is unchanged.
1660
+ export const caseLawJoin = (P, findings) => {
1661
+ try {
1662
+ return joinCaseLawProfiles(parseCaseLawProfiles(readFileSync(P.caseLaw, "utf8")), findings, readFold(P.runDir)?.map?.modelToFolded ?? null);
1663
+ } catch (e) {
1664
+ const error = String(e?.message ?? e).replace(/\s+/g, " ").slice(0, 200);
1665
+ try { runLog(P.runDir, { event: "case-law-join-failed", error }); } catch { /* the note below still says it */ }
1666
+ note(`case law: the profiles could not be joined to the findings (${error}); this step goes on without them`);
1667
+ throw e;
1668
+ }
1669
+ };
1656
1670
 
1657
1671
  // The runnable half of INLINE_CONTEXT. Reads the CANONICAL run (`ctx.paths`), because that is the run
1658
1672
  // pipelineInner would have been reading when it built this payload.
@@ -1669,7 +1683,7 @@ const INLINE_RESOLVERS = {
1669
1683
  try {
1670
1684
  if (finding && existsSync(P.caseLaw))
1671
1685
  caseLawProfile = caseLawJoin(P, findings).get(ord) ?? null;
1672
- } catch { /* no case-law layer — production passes null here too */ }
1686
+ } catch { /* no case-law layer, or a join that failed, which caseLawJoin has recorded — production passes null here too */ }
1673
1687
  return { finding, caseLawProfile };
1674
1688
  },
1675
1689
  };
@@ -2747,7 +2761,7 @@ async function verifyAndRecordHouseElement(ctx, opts = {}) {
2747
2761
  // "verified by owner, not asserted" means — there is no owner-predicate listing on this interface
2748
2762
  // and inventing one would be a second way to ask the same question.
2749
2763
  const lookup = typeof rec.list !== "function" ? null : async ({ element, classes: cls }) => {
2750
- const r = await rec.list(element, { classes: cls, regions, limit: 50 });
2764
+ const r = await stopsWithTheRun(P.runDir, "own-registrations", rec.list)(element, { classes: cls, regions, limit: 50 });
2751
2765
  if (!r || r.ok === false) return { ok: false, reason: String(r?.reason ?? "the register listing did not answer") };
2752
2766
  return { ok: true, records: Array.isArray(r.records) ? r.records : [] };
2753
2767
  };
@@ -7935,8 +7949,10 @@ export function injectDeferralCoverage(P, runDir, note) { // @internal — exp
7935
7949
  try {
7936
7950
  const rp = paths(runDir).frameReopenReceipt;
7937
7951
  if (!existsSync(rp) || !existsSync(P.findings)) return;
7938
- const deferrals = JSON.parse(readFileSync(rp, "utf8"))?.deferrals ?? [];
7952
+ const receipt = JSON.parse(readFileSync(rp, "utf8"));
7953
+ const deferrals = receipt?.deferrals ?? [];
7939
7954
  if (!deferrals.length) return;
7955
+ const kinds = followUpKinds(receipt); // the search each deferred directive recorded (follow-up-twins.mjs)
7940
7956
  const doc = JSON.parse(readFileSync(P.findings, "utf8"));
7941
7957
  // T1 (G8): a findings.json without a coverage array must not silently LOSE the deferral
7942
7958
  // rows — the reader-visible disclosure is the whole point of "can't close → disclose".
@@ -7963,6 +7979,8 @@ export function injectDeferralCoverage(P, runDir, note) { // @internal — exp
7963
7979
  const want = normTxt(plainDirective(directive)).split(" ").filter((w) => w.length >= 4).slice(0, 4);
7964
7980
  if (want.length && rows.some((ws) => want.every((w) => ws.has(w)))) continue; // synthesis already weighed it in
7965
7981
  const row = deferralCoverageRow(directive, d?.reason); // — word-boundary heading, full directive in the note
7982
+ // An axis-labelled row stands in only on the search the run recorded for this directive, as the page decides.
7983
+ if (axisTwin(plainDirective(directive), kindsForFollowUp(row, kinds), doc.coverage.filter((c) => !String(c.area ?? "").startsWith("Follow-up / ")))) continue;
7966
7984
  doc.coverage.push(row);
7967
7985
  rows.push(wordsOf(row));
7968
7986
  added++;
@@ -8142,7 +8160,12 @@ export function zhLaneRanOnRun(runDir, opts = {}) { // @internal
8142
8160
  export function injectScriptScopeCoverage(P, runDir, note, { searchPolicy = null, job = null, profile = null, env = process.env, lanes = Object.keys(LANGUAGE_LANES), localLanguage = null } = {}) { // @internal
8143
8161
  try {
8144
8162
  if (!existsSync(P.findings)) return;
8145
- const scope = jxScopeJurisdictions(job ?? {}, profile ?? {});
8163
+ // A WORLDWIDE ORDER IS SEARCHED WORLDWIDE, and its native-script rows are owed on that scope. The lane scope below falls
8164
+ // back to the account's default territories when an order names none, which is right for the paid lanes it chooses and
8165
+ // wrong here: a worldwide order under an account whose defaults hold no Chinese, Japanese or Korean territory wrote no
8166
+ // native-script row at all, and its report said nothing of a search it never ran. The account's defaults are the
8167
+ // customer's priorities, never the order's scope (ruled 2026-09-26, effective-scope.mjs).
8168
+ const scope = job?.geography?.mode === "worldwide" ? [] : jxScopeJurisdictions(job ?? {}, profile ?? {});
8146
8169
  const pending = [];
8147
8170
  // AN INVESTIGATION THE CLIENT ORDERED IS NEVER OFFERED BACK TO THEM (ruled 2026-09-25). The row below
8148
8171
  // says where the native-language investigation can be bought, which is true of a search that did not
@@ -9372,7 +9395,7 @@ export async function acquireRunSlot(agent = null) { // @internal
9372
9395
  // P2 — reconcile every stage stamp against the artifacts as they finally stand for this pass, so the NEXT
9373
9396
  // pass pays only for material that actually changed between passes (not for this pass's own driver-side
9374
9397
  // re-merges/normalizations). Runs on success and failure alike, and always after the delivery precondition.
9375
- function reconcilePassStamps(runRef, ctx) {
9398
+ export function reconcilePassStamps(runRef, ctx) { // @internal, exported for its test
9376
9399
  try {
9377
9400
  const P = ctx?.paths ?? runRef?.paths;
9378
9401
  if (!P?.runDir) return;
@@ -9387,7 +9410,11 @@ function reconcilePassStamps(runRef, ctx) {
9387
9410
  try {
9388
9411
  const q = coerceQueue(JSON.parse(readFileSync(P.digestQueue, "utf8")));
9389
9412
  if (pendingItems(q).length) exclude.add("register-digest");
9390
- } catch { /* no queue on disk — nothing pending */ }
9413
+ } catch {
9414
+ // No queue on disk is nothing pending. A queue that is there and does not read may still owe a re-digest, so the
9415
+ // digest stays stale and the resume recomputes it, rather than being reconciled as though nothing were owed.
9416
+ if (existsSync(P.digestQueue)) exclude.add("register-digest");
9417
+ }
9391
9418
  const n = reconcileStamps(P.runDir, (label) => {
9392
9419
  const bare = label.replace(/:.*$/, "");
9393
9420
  const axis = label.includes(":") ? label.slice(label.indexOf(":") + 1) : null;
@@ -11775,3 +11802,4 @@ export function reassembleFromTheRecord(P, findings, depth) { // @internal
11775
11802
  // Hoisted, so placed last: an import at the top would move every line citation into this file.
11776
11803
  import { commandLineRefusal } from "./run-requirements.mjs";
11777
11804
  import { runTables } from "./order-tables.mjs";
11805
+ import { axisTwin, followUpKinds, kindsForFollowUp } from "./follow-up-twins.mjs"; // when a written row stands in for a Follow-up row, as the page decides
@@ -335,7 +335,7 @@ const REVIEWER_LEGEND_RE =
335
335
 
336
336
  // ── the Ask-your-AI block: STAFF ONLY, and this one IS a boundary ────────────────────────────────────
337
337
  //
338
- // The report embeds a "paste this into your own AI" connector URL. ONE report (spec 2026-07-30 §5):
338
+ // The report embeds a "paste this into your own AI" connector URL. ONE report:
339
339
  // the renderer has one path and always bakes the STAFF surface — CLEAROTRON_MCP_URL plus a run-scoped
340
340
  // read-only token — or FAILS CLOSED and omits the block entirely when the env is unset, rather than
341
341
  // falling back to a placeholder host. That is critic finding 4, written into the renderer as
@@ -1028,7 +1028,7 @@ export function prepareReportForEmbed(html, { staff = false, poolRoot = null, fe
1028
1028
  /**
1029
1029
  * Read a run's report from the pool and prepare it.
1030
1030
  *
1031
- * ONE file: `report.html`, the full report. The cutover is complete (spec 2026-07-30 §5):
1031
+ * ONE file: `report.html`, the full report. The cutover is complete:
1032
1032
  * `report.client.html` is no longer produced at publish, the per-customer index pages link
1033
1033
  * `report.html`, and the client-access service at clients.example.com serves reports through THIS
1034
1034
  * function (staff:false) rather than reading any file by path. Old pool dirs may still hold a stale
@@ -225,10 +225,16 @@ export function scanAccountRuns({ poolRoot, workspaceRoot, account = null, gener
225
225
  const readRun = (dir) => {
226
226
  try {
227
227
  const s = readJson(join(dir, "status.json"));
228
- const p = readJson(paths(dir).profile);
228
+ // A DELIVERED RUN IS SKIPPED BEFORE ITS PROFILE IS READ: the pool row is its face, and every path
229
+ // below returns for it either way, so reading the profile first only cost a file per delivered run.
230
+ if (s.state === "delivered") return; // the pool row is the delivered face
231
+ // ONE `paths()` PER RUN STILL IN FLIGHT. It joins every path of a run's record, 164 of them, and this
232
+ // walk called it twice for every workspace run, delivered or not: on a test deployment's 33 workspace runs
233
+ // that was most of this walk's time on every poll (measured 2026-11-19).
234
+ const P = paths(dir);
235
+ const p = readJson(P.profile);
229
236
  const owner = p.profileKey ?? p.key ?? "generic";
230
237
  if (!mine(owner, p.organisation ?? null)) return;
231
- if (s.state === "delivered") return; // the pool row is the delivered face
232
238
  // ── — RETIREMENT REACHES A RUN THAT NEVER PUBLISHED ──────────────────
233
239
  //
234
240
  // The pool branch above has honoured the sidecar since; this branch never did, so a tag
@@ -246,7 +252,7 @@ export function scanAccountRuns({ poolRoot, workspaceRoot, account = null, gener
246
252
  // search-policy sidecar carries the stage. Both are read here so a run does not change identity
247
253
  // when it crosses from live to delivered: same mark, same stage, same thread.
248
254
  let sp = null;
249
- try { sp = readJson(paths(dir).searchPolicy); } catch { /* legacy/early run */ }
255
+ try { sp = readJson(P.searchPolicy); } catch { /* legacy/early run */ }
250
256
  // A PAUSE IS NOT A RUN. The engine writes `postponed` (a rate-limit park, auto-resuming at
251
257
  // `resetsAt`) and `recovering` (an auto-retry backing off), and the portal contract knows neither
252
258
  // — its coercion treats anything unrecognised as `running`. So a run parked for five hours showed
@@ -276,8 +282,8 @@ export function scanAccountRuns({ poolRoot, workspaceRoot, account = null, gener
276
282
  kind: (policyFor(sp?.level)?.pipeline ?? (s.lane === "knockout" ? "knockout" : null)) === "knockout" ? "knockout-batch" : "clearance",
277
283
  markName: typeof s.markName === "string" ? s.markName : null,
278
284
  // The project, straight off the frozen sidecar this branch already reads as `p`. A LIVE run needs
279
- // no publish stamp and no back-fill — the sidecar is right there, and freezeProfile has written
280
- // both fields since spec 62.
285
+ // no publish stamp and no back-fill — the sidecar is right there, and freezeProfile writes
286
+ // both fields.
281
287
  projectKey: typeof p.projectKey === "string" ? p.projectKey : null,
282
288
  projectName: typeof p.projectName === "string" ? p.projectName : null,
283
289
  // Registry first here too — a live run's frozen policy sidecar names WHICH level is running; what
@@ -460,7 +466,7 @@ export function scanAccountRuns({ poolRoot, workspaceRoot, account = null, gener
460
466
  // THE CANONICAL INTAKE FIRST, and it is why this parameter exists. `CLEAROTRON_QUEUE_DIR` is where the
461
467
  // enqueue CLI and ops-MCP `start_run` write — which is where the PORTAL's own submissions land, since
462
468
  // its `trigger` is an ops-MCP hop. The walk below finds only `workspace-*/studio/clearance-search/queue`,
463
- // and a documented headless install has no workspaces at all: measured on the test box, the only queue
469
+ // and a documented headless install has no workspaces at all: measured on a test deployment, the only queue
464
470
  // under the whole tree is the configured one, and it holds portal-prefixed jobs. So this scan ran ZERO
465
471
  // times there, and a submitted search was invisible on the dashboard from submit until claim — a
466
472
  // minute and a half of a client believing their order was lost.
@@ -529,7 +535,7 @@ export const concurrentRunsCap = () => {
529
535
 
530
536
  export function forRole(runs, principal) {
531
537
  // A person who sees everything reads failure reasons verbatim; everyone else gets the plain note. That redaction is the ONLY
532
- // role-shaping left: the held-run suppression is retired (one report, spec 2026-07-30 §5 — a run you
538
+ // role-shaping left: the held-run suppression is retired (one report — a run you
533
539
  // have rights to is always listed; the machine-QC record lives on the audit workbook).
534
540
  if (seesEverything(principal)) return runs;
535
541
  return runs.map((r) => {
@@ -40,6 +40,7 @@ import { normalizeBand } from "./framework.mjs";
40
40
  import { clientConditions, unrenderableConditions, ENGINE_TOKEN_RE, ENGINE_PHRASE_RE } from "./terminal-clamp.mjs"; // the reader's clause per condition, and the token shape it may never carry
41
41
  import { knockoutNoteView, REQUEST_NOTE_WORDS, REQUEST_SUBJECT_WORDS } from "./findings-model.mjs"; // one reader for where a note prints
42
42
  import { isEngineAppendedCaveat } from "./knockout-caveats.mjs"; // ONE derivation for "the engine appended this caveat, not a seat"
43
+ import { axisTwin, kindsForFollowUp } from "./follow-up-twins.mjs"; // when a written row stands in for a Follow-up row, as the page decides
43
44
 
44
45
  // V4-3: diacritics FOLD (NFD strip) instead of being deleted — "Televisión" must normalize to
45
46
  // "television" (deletion made it "televisin", so a diacritic mention never matched its introduction).
@@ -226,13 +227,14 @@ const PAGE_COV_STOPWORDS = new Set(["the", "a", "an", "as", "for", "of", "in", "
226
227
  "was", "it", "its", "this", "that", "with", "by", "at", "be", "been", "run", "search", "searched"]);
227
228
  const pageCovWords = (t) => new Set(String(t || "").toLowerCase().match(/[a-z0-9]+/g)?.filter((w) => !PAGE_COV_STOPWORDS.has(w)) ?? []);
228
229
  /** The coverage rows the page draws: not clean, and not a follow-up row another open row restates (render.mjs dedupeFollowUps). PURE. */
229
- function pageDrawnCoverage(coverage) {
230
+ function pageDrawnCoverage(coverage, followUpKinds = null) {
230
231
  const open = (Array.isArray(coverage) ? coverage : []).filter((c) => c && typeof c === "object" && c.state !== "confirmed-clean");
231
232
  const composed = (c) => String(c?.area || "").startsWith(PAGE_FOLLOW_UP_PREFIX);
232
233
  const written = open.filter((c) => !composed(c));
233
234
  if (!written.length) return open;
234
235
  return open.filter((c) => {
235
236
  if (!composed(c)) return true;
237
+ if (axisTwin(String(c.note || "").split("\u2014")[0], kindsForFollowUp(c, followUpKinds), written)) return false; // the page's rule, follow-up-twins.mjs
236
238
  const directive = pageCovWords(String(c.note || "").split("\u2014")[0]);
237
239
  if (!directive.size) return true;
238
240
  return !written.some((w) => {
@@ -244,9 +246,9 @@ function pageDrawnCoverage(coverage) {
244
246
  });
245
247
  }
246
248
  /** Every line the page draws from the record that can name a party: the drawn coverage rows, and the names it lists. PURE. */
247
- export function pageNameLines({ coverage = [], webNames = [] } = {}) {
249
+ export function pageNameLines({ coverage = [], webNames = [], followUpKinds = null } = {}) {
248
250
  return [
249
- ...pageDrawnCoverage(coverage).map((c) => `${c.area ?? ""} ${c.note ?? ""}`),
251
+ ...pageDrawnCoverage(coverage, followUpKinds).map((c) => `${c.area ?? ""} ${c.note ?? ""}`),
250
252
  ...(Array.isArray(webNames) ? webNames : []).slice(0, PAGE_WEB_NAMES_SHOWN).map((w) => String(w?.title ?? "")),
251
253
  ];
252
254
  }
@@ -2501,7 +2503,7 @@ export function cardBudgetChecks({ cardFolds }) {
2501
2503
  `assembly folded ${folds.length} surface(s) to the level budgets (moved, never deleted): ${folds.map((f) => `${f.surface} → +${f.movedSentences} sentence(s)/${f.movedWords} word(s) into depth`).join("; ")}`)];
2502
2504
  }
2503
2505
 
2504
- export function runLint({ depth, commonLawGrid, matterContext, clientPartyName, reportMd, overviewMd = null, emailConditions = null, clientSummaryMd, narrativeMd, auditMd, recordsByUri, searchedNames, headerName, ratedNames, actionsText, fetchFailures, extraPlatformNames, findings, narrativeFindings = null, findingsRaw, actionsRegister, actionsExpected, intakeAsks, askAnswers, cardFolds, verdictDoc, manifest, seniorRights, seniorRightsExpected, markAssessment, markAssessmentExpected, fourAnswers, contentModelExpected, findingsSchemaVersion, placements, ownerScreen, recordCarry, commonLawCarries, searchedJurisdictions = null, goodsEvidence = null, goodsHanded = null }) {
2506
+ export function runLint({ followUpKinds = null, depth, commonLawGrid, matterContext, clientPartyName, reportMd, overviewMd = null, emailConditions = null, clientSummaryMd, narrativeMd, auditMd, recordsByUri, searchedNames, headerName, ratedNames, actionsText, fetchFailures, extraPlatformNames, findings, narrativeFindings = null, findingsRaw, actionsRegister, actionsExpected, intakeAsks, askAnswers, cardFolds, verdictDoc, manifest, seniorRights, seniorRightsExpected, markAssessment, markAssessmentExpected, fourAnswers, contentModelExpected, findingsSchemaVersion, placements, ownerScreen, recordCarry, commonLawCarries, searchedJurisdictions = null, goodsEvidence = null, goodsHanded = null }) {
2505
2507
  // WS-B: the run's profile platforms join the vocabulary for this run. Profiles carry store
2506
2508
  // DOMAINS by contract, so derive the name tokens a report would actually print: the raw norm
2507
2509
  // ("thomasnetcom"), the separator-spaced phrase ("thomasnet com" / "made in china com"), and the
@@ -2541,7 +2543,7 @@ export function runLint({ depth, commonLawGrid, matterContext, clientPartyName,
2541
2543
  try { coverage = JSON.parse(findingsRaw)?.coverage ?? []; } catch { /* no record: the page draws no row from it */ }
2542
2544
  let webNames = [];
2543
2545
  try { webNames = auditMd ? clearedNames(auditMd).web : []; } catch { /* an unreadable audit lists no names */ }
2544
- return pageNameLines({ coverage, webNames }).join("\n");
2546
+ return pageNameLines({ coverage, webNames, followUpKinds }).join("\n");
2545
2547
  })();
2546
2548
  checks.push(...referenceChecks({ actionsText: onlyYou, fullSurface: reportMd, searchedNames, surface: "report", extraVocab, markNames, structural: actionsExpected === true, introducedIn: onThePage }));
2547
2549
  // V4-5 (+ PR-3): with a typed register the reachability check asserts over the STORE the
@@ -11,11 +11,28 @@
11
11
  // the tool servers too, and the renderer would bring the brand settings into every server's environment.
12
12
  import { parseActionBuckets, actYouConditions } from './render.mjs';
13
13
  import { parseFront, parseSections } from './parse.mjs';
14
+ import { EMAIL } from './strings.mjs';
14
15
 
15
- /** The report's only-you items, on a conditional or blocking result only. PURE. */
16
- export function emailConditionsOf(actionsSection, verdict) {
16
+ /**
17
+ * The items the report lists under its own "Before you can rely on this result" heading, in order. That group alone: a
18
+ * question for the client or a watch item is not a condition of reliance. Empty where the report names none. PURE.
19
+ */
20
+ export function relyBeforeOf(actionsSection) {
21
+ const you = parseActionBuckets(actionsSection).you;
22
+ if (!you?.body) return [];
23
+ const groups = String(you.body).split(/^(?=\s*\*\*.+\*\*\s*$)/m);
24
+ const group = groups.find((g) => g.trim().replace(/\n[\s\S]*$/, '').replace(/\*\*/g, '').trim() === EMAIL.beforeYouCanRely);
25
+ return group ? actYouConditions({ body: group }) : [];
26
+ }
27
+
28
+ /**
29
+ * The report's only-you items, on a conditional or blocking result only. Where the assessment did not complete there is
30
+ * no result to condition, and the items are the report's own conditions of reliance (relyBeforeOf). PURE.
31
+ */
32
+ export function emailConditionsOf(actionsSection, verdict, { assessmentNotCompleted = false } = {}) {
33
+ if (assessmentNotCompleted) return relyBeforeOf(actionsSection);
17
34
  return verdict === 'CONDITIONAL' || verdict === 'BLOCKING' ? actYouConditions(parseActionBuckets(actionsSection).you) : [];
18
35
  }
19
36
 
20
37
  /** The same list, from the report's markdown, as the email reads its `# Actions` section. PURE. */
21
- export const emailConditionsOfReport = (reportMd, verdict) => emailConditionsOf(parseSections(parseFront(String(reportMd ?? '')).body).Actions, verdict);
38
+ export const emailConditionsOfReport = (reportMd, verdict, opts = {}) => emailConditionsOf(parseSections(parseFront(String(reportMd ?? '')).body).Actions, verdict, opts);