clearotron 0.7.0-beta.2 → 0.7.0-beta.3

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 (131) hide show
  1. package/INSTALL.md +5 -5
  2. package/QUICKSTART.md +4 -4
  3. package/README.md +2 -2
  4. package/bin/README.md +3 -4
  5. package/bin/clearotron.mjs +1 -1
  6. package/bin/onboard.mjs +28 -40
  7. package/bin/status.mjs +11 -0
  8. package/build-info.json +2 -2
  9. package/docs/DELIVERY.md +30 -6
  10. package/docs/architecture/04-configuration-reference.md +1 -0
  11. package/driver/CHANGELOG.md +21 -0
  12. package/driver/compose-read.mjs +4 -3
  13. package/driver/contract-arm2-baseline.json +1 -2
  14. package/driver/contract-dictation-registry.mjs +7 -48
  15. package/driver/contract-e3-backlog.mjs +55 -52
  16. package/driver/contract-e3-baseline.json +22 -7
  17. package/driver/contract-vocabulary.mjs +4 -2
  18. package/driver/coverage-form.mjs +4 -0
  19. package/driver/coverage-rows-run.mjs +68 -4
  20. package/driver/engine/anthropic-agent.mjs +10 -13
  21. package/driver/engine/common.mjs +34 -22
  22. package/driver/engine/health.mjs +251 -0
  23. package/driver/engine/jx-turn.mjs +2 -1
  24. package/driver/engine/mcp/codex-config.mjs +16 -1
  25. package/driver/engine/mcp/crowd-note.mjs +1 -1
  26. package/driver/engine/mcp/gather-config.mjs +34 -9
  27. package/driver/engine/mcp/perplexity-server.mjs +33 -23
  28. package/driver/engine/mcp/recording-server.mjs +67 -58
  29. package/driver/engine/mcp/unit-note-server.mjs +2 -0
  30. package/driver/engine/openai-agent.mjs +9 -24
  31. package/driver/engine/probe.mjs +24 -7
  32. package/driver/findings-model.mjs +54 -0
  33. package/driver/jx-units.mjs +139 -30
  34. package/driver/knockout-assess-record.mjs +2 -2
  35. package/driver/knockout-correction-check.mjs +119 -0
  36. package/driver/knockout-correction-record.mjs +1 -1
  37. package/driver/knockout-frame-record.mjs +24 -10
  38. package/driver/knockout-review-record.mjs +35 -430
  39. package/driver/ladder/dispatch.mjs +4 -2
  40. package/driver/ladder/form-repair.mjs +5 -5
  41. package/driver/ladder/form-sync.mjs +4 -6
  42. package/driver/ladder/next-rung.mjs +10 -0
  43. package/driver/ladder/repair-messages.mjs +37 -65
  44. package/driver/ladder/stage.mjs +3 -3
  45. package/driver/ladder/turn-signals.mjs +4 -14
  46. package/driver/manual-paragraphs.mjs +22 -2
  47. package/driver/mark-logos.mjs +20 -5
  48. package/driver/package.json +1 -1
  49. package/driver/pipeline-knockout.mjs +2 -2
  50. package/driver/predelivery-lint.mjs +39 -7
  51. package/driver/product-fault.mjs +53 -0
  52. package/driver/publish/knockout.mjs +2 -1
  53. package/driver/publish/render.mjs +13 -7
  54. package/driver/recording-agreement.mjs +6 -4
  55. package/driver/register-band-run.mjs +2 -2
  56. package/driver/register-digest-record.mjs +31 -9
  57. package/driver/register-unit-record.mjs +10 -1
  58. package/driver/repair-composers.mjs +12 -11
  59. package/driver/repair-contract.mjs +6 -6
  60. package/driver/repair-targets.mjs +7 -6
  61. package/driver/run-outcome.mjs +8 -0
  62. package/driver/runner.mjs +42 -3
  63. package/driver/skills/README.md +5 -4
  64. package/driver/skills/blind-frame/SKILL.md +1 -1
  65. package/driver/skills/case-law-citation/SKILL.md +1 -1
  66. package/driver/skills/clearance-common-law/SKILL.md +6 -423
  67. package/driver/skills/clearance-common-law/grid.md +272 -0
  68. package/driver/skills/clearance-common-law/meaning.md +142 -0
  69. package/driver/skills/clearance-common-law/perplexity-prompts.md +4 -2
  70. package/driver/skills/clearance-register/SKILL.md +7 -174
  71. package/driver/skills/clearance-register/digest.md +89 -25
  72. package/driver/skills/clearance-register/providers/clarivate-questions.md +154 -0
  73. package/driver/skills/clearance-register/providers/clarivate.md +5 -149
  74. package/driver/skills/clearance-register/providers/signa-questions.md +120 -0
  75. package/driver/skills/clearance-register/providers/signa.md +3 -114
  76. package/driver/skills/clearance-register/providers/uspto-local.md +3 -3
  77. package/driver/skills/clearance-register/register-recipes.md +10 -10
  78. package/driver/skills/clearance-register/status-rules.md +2 -2
  79. package/driver/skills/clearance-register/unit.md +96 -54
  80. package/driver/skills/clearance-search/delivery-contract.md +11 -49
  81. package/driver/skills/clearance-search/firm-wide-reasoning.md +10 -13
  82. package/driver/skills/clearance-search/look-at-what-you-have.md +7 -0
  83. package/driver/skills/clearance-search/phase2-execution.md +12 -117
  84. package/driver/skills/clearance-search/report-card-rules.md +2 -2
  85. package/driver/skills/clearance-search/report-prose.md +30 -23
  86. package/driver/skills/clearance-search/synthesis-rules.md +27 -69
  87. package/driver/skills/clearance-search/worked-examples.md +11 -16
  88. package/driver/skills/clearance-variants/SKILL.md +7 -7
  89. package/driver/skills/clearance-variants/transliteration-scripts.md +2 -2
  90. package/driver/skills/frame-diff/SKILL.md +1 -1
  91. package/driver/skills/knockout-assess/SKILL.md +54 -41
  92. package/driver/skills/knockout-frame/SKILL.md +13 -12
  93. package/driver/skills/knockout-register-read/SKILL.md +2 -10
  94. package/driver/skills/matter-frame/SKILL.md +2 -2
  95. package/driver/skills/narrative-refutation/SKILL.md +7 -6
  96. package/driver/skills/placement-inquiry/SKILL.md +3 -3
  97. package/driver/skills/skeptic/SKILL.md +111 -0
  98. package/driver/skills/whatif-memo/SKILL.md +5 -2
  99. package/driver/stage-declarations.mjs +6 -0
  100. package/driver/stages-knockout.mjs +36 -38
  101. package/driver/stages.mjs +69 -64
  102. package/driver/steps/delivery.mjs +6 -4
  103. package/driver/steps/open-run.mjs +2 -0
  104. package/driver/steps/overview-and-cards.mjs +2 -2
  105. package/driver/steps/register-sweep.mjs +20 -1
  106. package/driver/steps/synthesis.mjs +28 -11
  107. package/driver/suite-census.json +213 -57
  108. package/driver/synthesis-record.mjs +24 -2
  109. package/driver/verify-knockout.mjs +23 -3
  110. package/driver/whatif-memo-run.mjs +39 -10
  111. package/driver/whatif-queue.mjs +53 -7
  112. package/mcp-server/CHANGELOG.md +4 -0
  113. package/mcp-server/lib/ops.mjs +19 -10
  114. package/mcp-server/lib/whatif.mjs +7 -6
  115. package/mcp-server/package.json +1 -1
  116. package/mcp-server/server.mjs +55 -19
  117. package/package.json +1 -1
  118. package/portal-ui/package.json +1 -1
  119. package/providers/clarivate/src/adapter.js +3 -0
  120. package/providers/jx/src/nativeread.js +5 -3
  121. package/providers/oauth-mcp-bridge/CHANGELOG.md +4 -0
  122. package/providers/oauth-mcp-bridge/package.json +1 -1
  123. package/providers/perplexity/src/core.js +7 -2
  124. package/providers/signa/src/adapter.js +3 -0
  125. package/scripts/e2e-first-time.mjs +2 -2
  126. package/shared/connector-signin-probe.mjs +1 -1
  127. package/shared/names-in-force.mjs +1 -0
  128. package/skills/clearotron-account/SKILL.md +21 -11
  129. package/skills/clearotron-client/SKILL.md +15 -15
  130. package/skills/clearotron-ops/COURIER.md +5 -1
  131. package/skills/clearotron-ops/SKILL.md +21 -14
@@ -0,0 +1,53 @@
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
+ // product-fault.mjs — a call that failed because of the product, not because of the step's work.
5
+ //
6
+ // ONE ANSWER, WORDED ONCE (ruled 2026-11-24). Every place that establishes a product fault hands the step this message
7
+ // and nothing else of the fault: what failed, and why, stays in the run's own record. The step is not asked to repeat
8
+ // the call, the retry ladder does not ask it either, and the run delivers what the call could not produce as a gap it
9
+ // states. The record rule a recording step carries (engine/common.mjs, `recordRule`) tells it to stop on a refusal that
10
+ // says the failure is a product fault, so the message keeps those words.
11
+ //
12
+ // A FAULT IS ESTABLISHED FROM THE RUN'S OWN RECORD, never inferred from an absence. The register's call log
13
+ // (tool-calls.mjs) holds a start line for every register call and a settle line for every one that returned, so a call
14
+ // that started and never settled was sent and never came back. No log, or a call that returned, is not a fault.
15
+ import { existsSync } from "node:fs";
16
+ import { paths } from "./run-record.mjs";
17
+ import { registerPlanCallKilled } from "./tool-calls.mjs";
18
+ import { plainCause } from "./deferral-row.mjs";
19
+
20
+ export const PRODUCT_FAULT_MESSAGE =
21
+ "This failed because of a product fault, not your work. Don't repeat the call. Finish the rest of your task and hand back what you have.";
22
+
23
+ /** The register unit's axis a stage label names, or null for any other stage. PURE. */
24
+ const registerUnitAxis = (label) => /^register-unit:([a-z0-9-]+)$/.exec(String(label ?? ""))?.[1] ?? null;
25
+
26
+ /**
27
+ * The product fault a failed attempt ended on, or null when its failure is the step's own to correct.
28
+ *
29
+ * A register unit whose plan call was sent and never returned has no band, and its note cannot be filed without one, so
30
+ * the attempt ends as `tool_timeout` (the note was there), as a missing note, or as a turn that ended with the call
31
+ * still out. Each is the call that never came back: the call log says so for that unit's axis, and the band is absent.
32
+ * A rate limit is not one of these; it keeps its own wait-and-resume path. Returns `{ cause, axis, tool }`.
33
+ */
34
+ export function productFaultOf({ fail, runDir = null, label = null } = {}) {
35
+ const f = String(fail ?? "");
36
+ if (!f || f === "rate_limited") return null;
37
+ const timeout = /(?:^|:)tool_timeout:([a-z_]+):([a-z0-9-]+)/.exec(f);
38
+ if (timeout) return { cause: "tool_timeout", tool: timeout[1], axis: timeout[2] };
39
+ const axis = registerUnitAxis(label);
40
+ if (axis && runDir && !existsSync(paths(runDir).registerBand(axis))) {
41
+ const killed = registerPlanCallKilled(runDir, axis);
42
+ if (killed) return { cause: "tool_timeout", tool: String(killed.tool ?? ""), axis };
43
+ }
44
+ return null;
45
+ }
46
+
47
+ /**
48
+ * The reader's line for a slice a product fault left open: the shipped line for a search left open. A call that started and
49
+ * never returned shows only that no answer was recorded. It does not show whether the source received the request, timed
50
+ * out, or answered after our process stopped (even `tool_timeout` is minted from the missing return), so the line says
51
+ * what is known and no more. The attempt's own failure stays in the run's record. PURE.
52
+ */
53
+ export const productFaultReason = () => plainCause("unfinished");
@@ -14,6 +14,7 @@ import { join } from 'node:path';
14
14
  import { EMAIL_TIER } from '../../shared/brand.mjs';
15
15
  import { riskTier, TONE_TIER, regenIndex, regenSurfaces, auditRouteFor, markReportRouteFor, reportRouteFor } from './index.mjs';
16
16
  import { runKnockoutLint, deliveryFlagLines } from '../predelivery-lint.mjs';
17
+ import { knockoutCorrectionChecks, readCorrectionRound } from '../knockout-correction-check.mjs'; // a corrected Knockout delivers its correction
17
18
  import { note } from '../log.mjs';
18
19
  import { addSheet } from './xlsx.mjs';
19
20
  import { KNOCKOUT_EMAIL as KO, KNOCKOUT_WORKBOOK as KW, KNOCKOUT_PAGE as KP } from './strings.mjs';
@@ -639,7 +640,7 @@ function readTheMachineChecks({ runDir, findings, receipts }) {
639
640
  // rewriting history; where the run store is read-only it simply does not land.
640
641
  let qcFlags = [], machineChecksFailed = null;
641
642
  try {
642
- const lint = runKnockoutLint({ findings });
643
+ const lint = runKnockoutLint({ findings, correction: knockoutCorrectionChecks({ findings, round: readCorrectionRound(runDir) }) });
643
644
  qcFlags = deliveryFlagLines(lint.failures.filter((c) => c.surface === 'report'));
644
645
  try {
645
646
  ensureDriverDir(runDir);
@@ -1945,6 +1945,14 @@ function fullDetail(f, card, recordsByUri = new Map()) {
1945
1945
  // AT MOST EIGHT ENTRIES, in the card's order, then the line that sends the reader to the audit workbook for all of
1946
1946
  // them (owner, 2026-11-18). A card citing dozens of registrations otherwise runs to pages.
1947
1947
  const RECORD_CAP = 8;
1948
+ /**
1949
+ * The registrations a card's logo line draws, in the card's order: those whose record the run saved, at most RECORD_CAP,
1950
+ * as its register record lists them. The logo step asks for logos for these alone (mark-logos.mjs), so no logo is paid for
1951
+ * that no reader sees. `hasRecord` takes a registration's lower-cased address. PURE.
1952
+ */
1953
+ export function shownRegistrations(f, hasRecord) {
1954
+ return (f?.owner?.registrations || []).filter((r) => r?.uri && hasRecord(String(r.uri).toLowerCase())).slice(0, RECORD_CAP);
1955
+ }
1948
1956
  function registerRecordBlock(f, recordsByUri, numberOf) {
1949
1957
  const cited = (f.owner?.registrations || [])
1950
1958
  .map((r) => ({ r, rec: r?.uri ? recordsByUri.get(String(r.uri).toLowerCase()) : null }))
@@ -1965,9 +1973,7 @@ function registerRecordBlock(f, recordsByUri, numberOf) {
1965
1973
  // logos and "+N" under its text. The image travels inside the report; nothing points at the register's image.
1966
1974
  function logoLine(f, recordsByUri, { small = false } = {}) {
1967
1975
  if (!LOGOS.size) return '';
1968
- const figures = (f.owner?.registrations || [])
1969
- .filter((r) => r?.uri && recordsByUri.get(String(r.uri).toLowerCase()))
1970
- .slice(0, RECORD_CAP)
1976
+ const figures = shownRegistrations(f, (uri) => Boolean(recordsByUri.get(uri)))
1971
1977
  .map((r) => {
1972
1978
  const rec = recordsByUri.get(String(r.uri).toLowerCase());
1973
1979
  const href = hrefAttr(RECORD_LINKS?.get(String(r.uri).toLowerCase())?.href) || hrefAttr(registerRecordView(rec, { uri: r.uri }).logo.href);
@@ -2460,8 +2466,8 @@ function markAssessmentBlock(ma) {
2460
2466
  if (!dist && !conn) return '';
2461
2467
  return `${SEC}
2462
2468
  <div class="markassess">
2463
- ${dist ? `<p><strong>${R.markItself.distinctiveness}</strong> ${esc(dist)}</p>` : ''}
2464
- ${conn ? `<p><strong>${esc(R.markItself.connotation)}</strong> ${esc(conn)}</p>` : ''}
2469
+ ${dist ? `<p><strong>${R.markItself.distinctiveness}</strong> ${inline(dist)}</p>` : ''}
2470
+ ${conn ? `<p><strong>${esc(R.markItself.connotation)}</strong> ${inline(conn)}</p>` : ''}
2465
2471
  </div>`;
2466
2472
  }
2467
2473
  const lead = (v) => {
@@ -2487,8 +2493,8 @@ function markAssessmentBlock(ma) {
2487
2493
  const toggle = (label, rows) => rows.length ? `<details class="ma-more"><summary>${label} (${rows.length})</summary><ul class="ma-rows">${rows.join('')}</ul></details>` : '';
2488
2494
  return `${SEC}
2489
2495
  <div class="markassess">
2490
- ${dist ? `<p><strong>${R.markItself.distinctiveness}</strong> ${esc(dist)}</p>` : ''}
2491
- ${conn ? `<p><strong>${esc(R.markItself.connotation)}</strong> ${esc(conn)}</p>` : ''}
2496
+ ${dist ? `<p><strong>${R.markItself.distinctiveness}</strong> ${inline(dist)}</p>` : ''}
2497
+ ${conn ? `<p><strong>${esc(R.markItself.connotation)}</strong> ${inline(conn)}</p>` : ''}
2492
2498
  ${toggle(R.markItself.byClassAndMarket, cmRows)}
2493
2499
  ${toggle(R.markItself.registrationsConsidered, crRows)}
2494
2500
  </div>`;
@@ -131,16 +131,18 @@ export function blockAround(text, needle) {
131
131
  export const WRITE_ORDER_MARKERS = Object.freeze([
132
132
  { id: "writeReturn:absolute-path", re: /ABSOLUTE path/ },
133
133
  { id: "writeReturn:you-owe", re: /YOU OWE \d+ FILES/ },
134
- { id: "repair-tail:write-tool", re: /with the Write tool/ },
135
- { id: "repair-tail:edit-tool", re: /using the Edit tool/ },
136
- { id: "corrective:max-tokens-write-tool", re: /CALL THE WRITE TOOL/ },
134
+ // The repair tails and the output-ceiling corrective name no engine's tool: both engines write files, each with its own
135
+ // operation. So the markers are the orders themselves.
136
+ { id: "repair-tail:write-complete", re: /Write the COMPLETE file now/ },
137
+ { id: "repair-tail:targeted-edits", re: /by TARGETED EDITS to/ },
138
+ { id: "corrective:max-tokens-write", re: /write the required file\(s\) as soon/ },
137
139
  // ADDED BY THE THIRD CONVERSION, and the way it was found is the argument for the anti-rot arm below.
138
140
  // `warmPatchMessage`'s sibling branch orders "Re-save the COMPLETE corrected JSON at <path>" — a
139
141
  // hand-write with no Write/Edit token and no `ABSOLUTE path` in it, so the four markers above were all
140
142
  // blind to it. On frame-diff the sibling IS the tool-written artifact, so that branch was ordering a
141
143
  // hand-write of a driver-owned file on every `framediff_*` token, and direction (b) reported clean.
142
144
  // A marker list is only as good as the composers it has met; this is the fifth composer it has met.
143
- { id: "warm-sibling:re-save-complete", re: /Re-save the COMPLETE/ },
145
+ { id: "warm-sibling:re-save-complete", re: /re-save the COMPLETE/i },
144
146
  ]);
145
147
 
146
148
  // THE RESIDUAL GAP, STATED RATHER THAN LEFT FOR SOMEBODY TO DISCOVER. This list is the composers as they
@@ -914,12 +914,12 @@ export function noteChannelCoverageAtStageExit(P, mergedGrid) {
914
914
  * search that never reached the register. A slice with a block, a timed-out one included, is not among them: the band
915
915
  * already accounts for it. A guarded child is left to the plan join, which reads it off its parent. PURE but for the read.
916
916
  */
917
- export function slicesUnitNeverReached(P, plan, axis) { // @internal
917
+ export function slicesUnitNeverReached(P, plan, axis, reason = plainDeferralReason("slice-not-landed")) { // @internal
918
918
  let band = [];
919
919
  try { const parsed = JSON.parse(readFileSync(P.registerBand(axis), "utf8")); band = Array.isArray(parsed) ? parsed : []; } catch { band = []; }
920
920
  const held = new Set(band.map((b) => b?.qid).filter(Boolean).map(String));
921
921
  return (plan?.entries ?? []).filter((e) => e?.axis === axis && e?.qid && !e.when && !held.has(String(e.qid)))
922
- .map((e) => ({ axis, qid: String(e.qid), reason: plainDeferralReason("slice-not-landed") }));
922
+ .map((e) => ({ axis, qid: String(e.qid), reason }));
923
923
  }
924
924
 
925
925
  /** The unit a run records as unfinished, taken as its band stands: its note rendered from it, nothing dispatched. */
@@ -424,7 +424,9 @@ const table = (columns, rows) => [row(columns), `|${columns.map(() => "---").joi
424
424
  * recordHost → the full clickable record URL (code-rendered)
425
425
  * counts → ## Summary counts (code-extracted)
426
426
  * auditRows → Audit trail (code-extracted)
427
- * readIds → the record ids read while answering each instructed check (code-extracted)
427
+ * readIds → every record id this run's reading audit logged as read, rendered once under the audit trail
428
+ * (code-extracted). It is no answer's support: a read proves a record was opened, not which
429
+ * answer it bears on, so each answer carries its own `records`.
428
430
  * positions → the crowd row's counted denominator (code-rendered, via the coverage form)
429
431
  */
430
432
  export function emptyFacts() {
@@ -599,14 +601,15 @@ export function renderRegisterFindings(model, facts = emptyFacts()) {
599
601
  for (const [heading, body] of [[DIGEST_SECTIONS.crossChecks, model.cross_checks], [DIGEST_SECTIONS.openFlags, model.open_flags]])
600
602
  if (body) out.push(heading, "", body, "");
601
603
 
602
- // ### Answers to the instructed checks — the ANSWER is the seat's, the record ids it read while
603
- // answering are the reading audit's. doubt-ledger's answerWatchlistLines scans this section by its
604
- // /answer|watchlist/i heading test, so every line under it is a line that join can reach.
604
+ // ### Answers to the instructed checks — the ANSWER and the records it relies on are the seat's. An answer
605
+ // recorded before it could name them shows none: its attribution is unknown, and the run's reads are no
606
+ // stand-in for it. doubt-ledger's answerWatchlistLines scans this section by its /answer|watchlist/i heading
607
+ // test, so every line under it is a line that join can reach.
605
608
  if (model.instructed_checks.length) {
606
609
  out.push(DIGEST_SECTIONS.instructed, "");
607
610
  for (const c of model.instructed_checks) {
608
611
  out.push(`- You asked: ${c.ask} → ${c.answer}`);
609
- if (facts.readIds?.length) out.push(` - records read: ${facts.readIds.join(", ")}`);
612
+ if (c.records?.length) out.push(` - Records relied on: ${c.records.join(", ")}`);
610
613
  }
611
614
  out.push("");
612
615
  }
@@ -618,10 +621,15 @@ export function renderRegisterFindings(model, facts = emptyFacts()) {
618
621
  out.push("");
619
622
  }
620
623
 
621
- if (facts.auditRows?.length) {
622
- out.push(DIGEST_SECTIONS.auditTrail, "",
623
- table(["Unit", "Searches", "Detail fetches", "_query"], facts.auditRows.map((a) =>
624
+ // The run's reads, once, for audit, where a run answers instructed checks: what was opened, not what any
625
+ // answer rests on. A line, not a table, so the published audit's table reader leaves it here.
626
+ const reads = model.instructed_checks.length && facts.readIds?.length ? facts.readIds : [];
627
+ if (facts.auditRows?.length || reads.length) {
628
+ out.push(DIGEST_SECTIONS.auditTrail, "");
629
+ if (facts.auditRows?.length)
630
+ out.push(table(["Unit", "Searches", "Detail fetches", "_query"], facts.auditRows.map((a) =>
624
631
  [a.unit, a.searches, a.detail_fetches, a.query ?? ""])), "");
632
+ if (reads.length) out.push(`- records read: ${reads.join(", ")}`, "");
625
633
  }
626
634
  if (facts.counts) {
627
635
  const statusRow = facts.counts.find(([l]) => /status/i.test(l));
@@ -785,12 +793,26 @@ export function acceptRegisterDigest(params, facts = emptyFacts()) {
785
793
  screen_verdict: verdict });
786
794
  }
787
795
 
796
+ // THE RECORDS AN ANSWER RELIES ON are the seat's to name and the driver's to resolve. The reading audit proves a
797
+ // record was opened somewhere in the run, not which answer it supports, so it is no answer's citation. Each named
798
+ // record must be one the run holds, and is kept as the band carries it. An answer resting on a search's count, a
799
+ // verified zero or an open question names none: its receipt is its basis.
788
800
  const instructed_checks = [];
789
801
  for (const c of Array.isArray(params?.instructed_checks) ? params.instructed_checks : []) {
790
802
  const ask = str(c?.ask), answer = str(c?.answer);
791
803
  if (!ask || !answer)
792
804
  return { ok: false, reason: `registerdigest_instructed_incomplete:${(ask || answer).slice(0, 60) || "(empty)"} — every instructed check carries the ask AND the answer, including the honest "the frozen material cannot answer this"` };
793
- instructed_checks.push({ ask, answer });
805
+ if (c?.records != null && !Array.isArray(c.records))
806
+ return { ok: false, reason: `registerdigest_relied_records_invalid:${ask.slice(0, 60)} — \`records\` is a list of the held record uris this answer relies on` };
807
+ const records = [];
808
+ for (const id of c?.records ?? []) {
809
+ const rec = byUri.get(joinKey(id));
810
+ if (!rec)
811
+ return { ok: false, reason: `registerdigest_relied_record_unknown:${str(id).slice(0, 60) || "(empty)"} (${ask.slice(0, 60)}) — no record in this run's band carries that uri. Name only held records this answer relies on, and none where it rests on a search rather than a record` };
812
+ const uri = identifierCells(rec, facts.recordHost).uri;
813
+ if (!records.includes(uri)) records.push(uri);
814
+ }
815
+ instructed_checks.push({ ask, answer, ...(records.length ? { records } : {}) });
794
816
  }
795
817
 
796
818
  const disagreement_resolutions = [];
@@ -34,6 +34,7 @@ import { captureCall, stampVerdict } from "./call-capture.mjs";
34
34
  import { join, dirname, basename } from "node:path";
35
35
  import { refuseUndeclared as refuseUndeclaredShared, keepIfAbsent, lastAccepted, acceptedEnvelope } from "./preserve-merge.mjs";
36
36
  import { paths, readJson } from "./run-record.mjs";
37
+ import { registerPlanCallKilled } from "./tool-calls.mjs";
37
38
 
38
39
  /**
39
40
  * THE REPAIR TAIL FOR THIS STAGE'S BESPOKE FOLLOWUPS — one implementation, used by all of them.
@@ -275,7 +276,15 @@ export function recordUnitNote(runDir, received, { now = () => new Date().toISOS
275
276
  return { written: null, refused: undeclared, captured: closeCapture({ ok: false, refused: undeclared }), capture_failed: captureFailed };
276
277
  }
277
278
  const call = mergeUnitNoteCall(lastAcceptedUnitNote(dir0, axis), received);
278
- const v = acceptUnitNote(call, { account: readBandAccount(dir0, axis), planned: plannedEntries(dir0, axis) });
279
+ const account = readBandAccount(dir0, axis);
280
+ // NO BAND BECAUSE THE PLAN CALL NEVER CAME BACK is a product fault, not a unit that has not run: the call log holds
281
+ // its start and no return. The step is told so, and is not sent back to make the call again (product-fault.mjs).
282
+ if (!account) {
283
+ const killed = registerPlanCallKilled(dir0, axis);
284
+ if (killed) return { written: null, refused: null, product_fault: `${killed.tool ?? "register call"} for ${axis} never returned`,
285
+ captured: closeCapture({ ok: false, product_fault: true }), capture_failed: captureFailed };
286
+ }
287
+ const v = acceptUnitNote(call, { account, planned: plannedEntries(dir0, axis) });
279
288
  if (!v.ok) {
280
289
  // BEST-EFFORT, and it must stay that way: a journal write that failed a refusal would turn a defect
281
290
  // the seat can fix into one it cannot see. The refusal is the return value; this is the audit trail.
@@ -42,6 +42,7 @@
42
42
  // "no unregistered composers" and read as a pass.
43
43
 
44
44
  import { lines } from "./stages.mjs";
45
+ import { FINDINGS_SCHEMA_VERSION } from "./findings-model.mjs";
45
46
  import { editRepairTail, abbrev } from "./repair-contract.mjs";
46
47
  // `connotation-remedy` quotes the refusal token and turns it into a fix instruction. Both helpers
47
48
  // are the gateway's, and calling them here rather than re-deriving the text is the point: one
@@ -210,7 +211,7 @@ const correctiveRules = ({ narrative, findings, placement, rulingsTail, adds = f
210
211
  // 2026-07-04 (the VENZY corrective thrash): three attempts died inventing three different keys
211
212
  // while trying to EXPRESS a hold. The contract is closed and every correction is expressible
212
213
  // inside it — say so.
213
- `THE FINDINGS CONTRACT IS CLOSED — MINIMAL CHANGE ONLY: start from the finding objects as you last sent them and change the smallest set of existing fields the flags require; NEVER invent a key, a state, or an enum value (any unknown key fails the file and, repeated, fails the WHOLE RUN). Every correction the reviewer can ask for is expressible with existing fields: an unsourced/confabulated attribution ⇒ that finding gets "disposition":"withdrawn" + "withdrawn_reason", OR its owner/prose is re-attributed to what the sources actually support — an identity that needs the applicant's confirmation is stated in the finding's prose/impact text, NEVER as a new field or note-type; use_check.quality is EXACTLY one of owner-site | independent | register-mirror or omitted; context_notes entries are EXACTLY {"type","mark","owner","context"}. RE-TYPING A DISPOSITION CARRIES ITS FIELDS WITH IT — this is the one case where a minimal edit MUST add a key, and these are the only keys it may add: re-typing a finding TO "off-field" also sets "off_field_ground" (EXACTLY "different-field" — only where that finding's own goods_proximity meter reads "low" — or "no-material-risk"), and re-typing AWAY from "off-field" REMOVES it; any finding that is not "withdrawn" keeps a non-empty "legal_position" and "practical_position", so a re-type that lands on a finding missing either must write both. Nothing else may be added.`,
214
+ `THE FINDINGS CONTRACT IS CLOSED — MINIMAL CHANGE ONLY: start from the finding objects as you last sent them and change the smallest set of existing fields the flags require; NEVER invent a key, a state, or an enum value (any unknown key fails the file and, repeated, fails the WHOLE RUN). Every correction the reviewer can ask for is expressible with existing fields: an unsourced/confabulated attribution ⇒ that finding gets "disposition":"withdrawn" + "withdrawn_reason", OR its owner/prose is re-attributed to what the sources actually support — an identity that needs the applicant's confirmation is stated in the finding's prose/impact text, NEVER as a new field or note-type; use_check.quality is EXACTLY one of owner-site | independent | register-mirror or omitted; context_notes entries are EXACTLY {"type","mark","context"} plus an OPTIONAL "owner". RE-TYPING A DISPOSITION CARRIES ITS FIELDS WITH IT — this is the one case where a minimal edit MUST add a key, and these are the only keys it may add: re-typing a finding TO "off-field" also sets "off_field_ground" (EXACTLY "different-field" — only where that finding's own goods_proximity meter reads "low" — or "no-material-risk"), and re-typing AWAY from "off-field" REMOVES it; any finding that is not "withdrawn" keeps a non-empty "legal_position" and "practical_position", so a re-type that lands on a finding missing either must write both. Nothing else may be added.`,
214
215
  rulingsTail ? lines(
215
216
  `PLACEMENT RULINGS TAIL (verbatim from ${placement}, provided AS DATA — do NOT re-read the placement file; where a flagged correction touches a coverage disposition, a coverage[] row, or a placement call, adjudicate it against these rulings — adopt each ruling or counter-reason it, never silently drop one):`,
216
217
  "```markdown",
@@ -302,8 +303,8 @@ export const REPAIR_COMPOSERS = [
302
303
  stage: "synthesis",
303
304
  key: "synthesis:schema-downlevel",
304
305
  compose: ({ findings, declaredSv, frameworkKey, bandLabels }) => lines(
305
- `This is a fresh session: your earlier synthesis is not in your context. The findings file you emitted (${findings}) declares "schema_version": ${declaredSv}, but the dictation requires "schema_version": 4 — rated in the framework's band WORDS with a top-level "rated_under_framework": "${frameworkKey}", and NO composite/level/dispute_type keys (that scale is retired).`,
306
- `Re-emit the COMPLETE record through \`record_synthesis\` at schema_version 4 — same findings, same judgments, each rated finding carrying "band" (EXACTLY one of: ${bandLabels.join(" / ")}) per the original dictation. Change nothing else. This one is a whole re-send rather than a patch, because the key set itself changes shape: there is no set of named findings to correct.`,
306
+ `This is a fresh session: your earlier synthesis is not in your context. The findings file you emitted (${findings}) declares "schema_version": ${declaredSv}, but the dictation requires "schema_version": ${FINDINGS_SCHEMA_VERSION} — rated in the framework's band WORDS with a top-level "rated_under_framework": "${frameworkKey}", and NO composite/level/dispute_type keys (that scale is retired).`,
307
+ `Re-emit the COMPLETE record through \`record_synthesis\` at schema_version ${FINDINGS_SCHEMA_VERSION}, each rated finding carrying "band" (EXACTLY one of: ${bandLabels.join(" / ")}) per the original dictation. Keep the findings and their judgments. Supply the fields the current record requires. This one is a whole re-send rather than a patch, because the key set itself changes shape: there is no set of named findings to correct.`,
307
308
  ),
308
309
  // A WHOLE-FILE EMISSION WITH NO REPAIR TAIL, AND THE SITE SAYS WHY: the key set changes shape, so
309
310
  // there is no small set of named lines to patch. Declared "none" with that reason rather than left
@@ -318,9 +319,9 @@ export const REPAIR_COMPOSERS = [
318
319
  // `narrative` is named because a fresh session has not read it, and the register it is asked for is the
319
320
  // forward steps that narrative names.
320
321
  compose: ({ findings, narrative }) => lines(
321
- `This is a fresh session: your earlier synthesis is not in your context. The findings file you emitted (${findings}) has no top-level "actions" array, but the dictation requires the ACTIONS REGISTER: ONE object per forward step your opinion names that a HUMAN must still take, each EXACTLY {"id","kind","text","ordinals"} (+ optional "deadline":{"kind","date"}) — kinds: conditions consent / coexistence-agreement / territorial-delimitation / goods-amendment / mark-modification / senior-clearance / proceeding-response / counsel-opinion-required; advisory client-fact / commercial-decision / monitoring / filing-routine.`,
322
- `Add ONE top-level "actions": [...] key that registers every forward step your own narrative (${narrative}) names ("actions": [] ONLY if the opinion genuinely demands nothing beyond ordinary filing). Same findings, same judgments — the findings themselves do not change.`,
323
- `Send it with \`record_synthesis\` as a PATCH call carrying only "actions". The driver merges this patch into the last accepted record, keeps the values the patch does not replace, and renders both files. There is no file for you to write or edit.`,
322
+ `This is a fresh session: your earlier synthesis is not in your context. The findings file you emitted (${findings}) has no top-level "actions" array, but the dictation requires the ACTIONS REGISTER: ONE object per forward step your opinion names that a HUMAN must still take, each EXACTLY {"id","kind","text","ordinals"} plus an OPTIONAL "deadline" {"kind","date"} and an OPTIONAL "condition" (CONDITION kinds only) — kinds: conditions consent / coexistence-agreement / territorial-delimitation / goods-amendment / mark-modification / senior-clearance / proceeding-response / counsel-opinion-required; advisory client-fact / commercial-decision / monitoring / filing-routine. A deadline, when present, needs a date and may include a kind.`,
323
+ `Add ONE "actions": [...] field to the findings document that registers every forward step your own narrative (${narrative}) names ("actions": [] ONLY if the opinion genuinely demands nothing beyond ordinary filing). Same findings, same judgments — the findings themselves do not change.`,
324
+ `Send the complete actions list in \`findings.actions\` through \`record_synthesis\`. The driver merges this patch into the last accepted record, keeps the values the patch does not replace, and renders both files. There is no file for you to write or edit.`,
324
325
  ),
325
326
  samples: [{ name: "the actions register demand", tail: "tool", args: { findings: "findings.json", narrative: "narrative.md" } }],
326
327
  },
@@ -674,8 +675,8 @@ export const REPAIR_COMPOSERS = [
674
675
  // The id is what the seat can find its own row by; `kind` is echoed because a kind defect is
675
676
  // the one case where the id alone does not locate the fault in the seat's own reading.
676
677
  ...bad.map((q) => `- action id ${q.id ?? "(unreadable)"}${q.kind ? ` (kind "${String(q.kind).slice(0, 40)}")` : ""} at index ${q.index}: ${String(q.error ?? "invalid shape").slice(0, 160)}`),
677
- `THE ACTION CONTRACT IS CLOSED — MINIMAL EDIT ONLY. Each action is EXACTLY {"id","kind","text","ordinals"} plus an OPTIONAL "deadline" {"kind","date"} and an OPTIONAL "condition" (CONDITION kinds only). Change the smallest set of existing fields these errors require and NEVER invent a key. Do not resolve a defect by DELETING the action: a forward legal step your own opinion names must survive this edit, and a dropped condition changes the delivered verdict.`,
678
- `Send the corrected action(s) with \`record_synthesis\` as a PATCH call carrying only "actions" — the complete register with these objects fixed. The driver is holding your findings and re-renders from them; nothing else moves, and there is no file for you to write or edit.`,
678
+ `THE ACTION CONTRACT IS CLOSED — MINIMAL EDIT ONLY. Each action is EXACTLY {"id","kind","text","ordinals"} plus an OPTIONAL "deadline" {"kind","date"} and an OPTIONAL "condition" (CONDITION kinds only). A deadline, when present, needs a date and may include a kind. Change the smallest set of existing fields these errors require and NEVER invent a key. Do not resolve a defect by DELETING the action: a forward legal step your own opinion names must survive this edit, and a dropped condition changes the delivered verdict.`,
679
+ `Send the complete actions list in \`findings.actions\` through \`record_synthesis\`. Send every existing action and all its fields, including any condition and deadline. Change only the fields this repair identifies. The driver is holding your findings and re-renders from them; nothing else moves, and there is no file for you to write or edit.`,
679
680
  ),
680
681
  samples: [{ name: "one malformed action", tail: "tool", args: { findings: "findings.json", bad: [{ id: "a1", kind: "consent", index: 0, error: "no ordinals" }] } }],
681
682
  },
@@ -777,7 +778,7 @@ export const REPAIR_COMPOSERS = [
777
778
  key: "common-law:grid-ledger",
778
779
  compose: ({ gridLedger, gridSpecPath }) => lines(
779
780
  `This is a fresh session: your earlier common-law work is not in your context. Your findings file is already written and stands.`,
780
- `The grid ledger ${gridLedger} is missing — the deterministic grid call did not complete. Call perplexity_research again with enable_sandbox:true and grid_spec_path: ${gridSpecPath}. The tool writes the ledger itself from the API response; do NOT write it yourself and do NOT re-emit the grid JSON.`,
781
+ `The grid ledger ${gridLedger} is missing — the deterministic grid call did not complete. Call perplexity_research again with grid_spec_path: ${gridSpecPath}. The tool writes the ledger itself from the API response; do NOT write it yourself and do NOT re-emit the grid JSON.`,
781
782
  `Then return ONLY: the grid ledger path + one line confirming the tool reported it written.`,
782
783
  ),
783
784
  samples: [{ name: "the ledger the grid call never wrote", tail: "tool", args: { gridLedger: "grid-ledger.json", gridSpecPath: "grid-spec.json" } }],
@@ -788,7 +789,7 @@ export const REPAIR_COMPOSERS = [
788
789
  key: "common-law:coverage-closure",
789
790
  compose: ({ findingsFile, suppSpec, suppSpecPath, closable, cellKey }) => lines(
790
791
  `This is a fresh session: your earlier common-law work is not in your context, and your findings file is ${findingsFile}. Do NOT redo the full sweep.`,
791
- suppSpec ? `These ${closable.length} grid cells are recorded as not-executed/coverage-limited with NO mechanical failure behind them — they are closable now. Run them via the DETERMINISTIC supplementary search-as-code grid: call perplexity_research with enable_sandbox:true and grid_spec_path: ${suppSpecPath}. The tool runs EXACTLY the dictated cells and WRITES the supplementary ledger to its output_path itself — do NOT save it yourself and do NOT re-emit the grid JSON. The cells:` : "",
792
+ suppSpec ? `These ${closable.length} grid cells are recorded as not-executed/coverage-limited with NO mechanical failure behind them — they are closable now. Run them via the DETERMINISTIC supplementary search-as-code grid: call perplexity_research with grid_spec_path: ${suppSpecPath}. The tool runs EXACTLY the dictated cells and WRITES the supplementary ledger to its output_path itself — do NOT save it yourself and do NOT re-emit the grid JSON. The cells:` : "",
792
793
  ...(suppSpec ? closable.map((c) => `- ${cellKey(c)}`) : []),
793
794
  // The edit direction has to be SCOPED here: this prompt already forbids saving the grid JSON,
794
795
  // and the tail below is the first thing in it that hands over the Edit tool. A model that reads
@@ -805,7 +806,7 @@ export const REPAIR_COMPOSERS = [
805
806
  key: "common-law-half:coverage-closure",
806
807
  compose: ({ findingsFile, gridSpecPath, suppSpec, suppSpecPath, cells, cellKey }) => lines(
807
808
  `This is a fresh session: your earlier common-law work is not in your context, and your findings file is ${findingsFile}. Do NOT redo the full sweep. You own ONE HALF of this matter's grid (your half-grid spec: ${gridSpecPath}).`,
808
- suppSpec ? `These ${cells.length} grid cells are recorded as not-executed/coverage-limited with NO mechanical failure behind them — they are closable now. Run them via the DETERMINISTIC supplementary search-as-code grid: call perplexity_research with enable_sandbox:true and grid_spec_path: ${suppSpecPath}. The tool runs EXACTLY the dictated cells and WRITES the supplementary ledger to its output_path itself — do NOT save it yourself and do NOT re-emit the grid JSON. The cells:` : "",
809
+ suppSpec ? `These ${cells.length} grid cells are recorded as not-executed/coverage-limited with NO mechanical failure behind them — they are closable now. Run them via the DETERMINISTIC supplementary search-as-code grid: call perplexity_research with grid_spec_path: ${suppSpecPath}. The tool runs EXACTLY the dictated cells and WRITES the supplementary ledger to its output_path itself — do NOT save it yourself and do NOT re-emit the grid JSON. The cells:` : "",
809
810
  ...(suppSpec ? cells.map((c) => `- ${cellKey(c)}`) : []),
810
811
  `Then update ONLY those Negative-results matrix rows with their real receipts ("No results" / "No similar listings (N candidates reviewed)" / "Similar listing(s) found — see Findings") and reconcile the Coverage ledger rows they close, preserving everything else. The driver validates grid completeness from the ledgers the tool wrote — never from your prose. The edit direction below covers ${findingsFile} ONLY; the machine ledgers stay the tool's.`,
811
812
  editRepairTail(findingsFile),
@@ -24,7 +24,7 @@
24
24
  //
25
25
  // — THAT IS NO LONGER UNIVERSAL, and a tail composed here can now name a tool its reader does not
26
26
  // hold. A recording stage whose artifact the DRIVER writes is seeded `Read` alone, so `editRepairTail`'s
27
- // "using the Edit tool" and `fullWriteTail`'s "with the Write tool" are wrong for it — gateway.mjs
27
+ // targeted edits and `fullWriteTail`'s whole-file write are wrong for it — gateway.mjs
28
28
  // intercepts those stages before either tail is reached and orders a re-call of the typed tool instead.
29
29
  // blind-frame is the first; every conversion adds one. If you are adding a tail here, the question is no
30
30
  // longer "what should it say" but "which stages can obey it". The models were simply told, in the
@@ -72,10 +72,10 @@ export const ABBREVIATED_VALUE_NOTE =
72
72
 
73
73
  export function editRepairTail(target) {
74
74
  const what = target || "the stage output";
75
- return `Apply the fix by TARGETED EDITS to ${what} using the Edit tool: change ONLY what the correction ` +
75
+ return `Apply the fix by TARGETED EDITS to ${what} with your file-editing operation: change ONLY what the correction ` +
76
76
  `above names, and leave every other line of the file byte-identical. Do NOT rewrite, re-emit or re-type ` +
77
77
  `the whole file — everything not named above already passed, a full rewrite risks degrading it, and an ` +
78
- `unexplained size jump is flagged. If ${what} does not exist, create it in full with the Write tool. ` +
78
+ `unexplained size jump is flagged. If ${what} does not exist, create it in full. ` +
79
79
  `Do not stop until it is corrected and valid.`;
80
80
  }
81
81
 
@@ -89,11 +89,11 @@ export function editRepairTail(target) {
89
89
  // against the file. Same write mode, different truth about why.
90
90
  export function appendRepairTail(target) {
91
91
  const what = target || "the stage output";
92
- return `Apply this by TARGETED EDITS to ${what} using the Edit tool: ADD exactly what the correction ` +
92
+ return `Apply this by TARGETED EDITS to ${what} with your file-editing operation: ADD exactly what the correction ` +
93
93
  `above names and leave every other line of the file byte-identical. This correction ADDS what is ` +
94
94
  `missing — it does not replace what is there — so do NOT rewrite, re-emit or re-type the whole file: ` +
95
95
  `a full rewrite risks degrading prose that is already correct, and growth beyond the additions ` +
96
- `themselves is flagged. If ${what} does not exist, create it in full with the Write tool. Do not stop ` +
96
+ `themselves is flagged. If ${what} does not exist, create it in full. Do not stop ` +
97
97
  `until the additions are in place and the file is valid.`;
98
98
  }
99
99
 
@@ -101,7 +101,7 @@ export function appendRepairTail(target) {
101
101
  // missing is the file itself, so there is nothing to patch.
102
102
  export function fullWriteTail(target) {
103
103
  const what = target || "the stage output";
104
- return `Write the COMPLETE file now at ${what} with the Write tool — full file, from the work already in ` +
104
+ return `Write the COMPLETE file now at ${what} — full file, from the work already in ` +
105
105
  `your context. Do not stop until it exists and is complete.`;
106
106
  }
107
107
 
@@ -16,8 +16,8 @@
16
16
  // single part holds (two cards counting one owner's registrations differently), or one whose check cannot be run on a
17
17
  // part, keeps the overview's repair it always had.
18
18
  //
19
- // Two faults are placed by what they cite. A citation held in a register of the record (the four answers' findings) is
20
- // the writer's, since no card or overview repair can change the record. A citation of a withdrawn or absent finding in
19
+ // Two faults are placed by what they cite. A citation held in a register of the record (the four answers' findings, a
20
+ // forward step's, an open coverage row's) is the writer's, since no card or overview repair can change the record. A citation of a withdrawn or absent finding in
21
21
  // the overview's own prose is the overview's: a check of its own reads the overview as its writer wrote it.
22
22
  import { readFileSync } from "node:fs";
23
23
  import { prescriptionProseChecks, scopeNumberProseChecks, wipoLanguageChecks, countingChecks, countsFromFindings, OVERVIEW_CITATION_ID } from "./predelivery-lint.mjs";
@@ -88,13 +88,14 @@ const withdrawnCitationLine = (ordinal) => `Your text cites finding ${ordinal},
88
88
  * The faults the writer's repair is given for one a register of the record holds, each finding named by the number the
89
89
  * writer's record carries. The check judged the delivered record, which the fold may have renumbered; `toModel` maps a
90
90
  * delivered ordinal to the writer's, or to null for one the fold does not know, which keeps its number as written.
91
- * In the four answers each withdrawn finding gets its ruled line, and the findings the run does not have get the general
92
- * instruction together, since the ruled line says "withdrew". A forward step gets the general instruction, with the
91
+ * In the four answers and the coverage rows each withdrawn finding gets its ruled line, and the findings the run does not
92
+ * have get the general instruction together, since the ruled line says "withdrew". A forward step gets the general instruction, with the
93
93
  * step it concerns named, because the step's support is what is rechecked. PURE.
94
94
  */
95
95
  export function writersCitationFaults(fault, toModel) {
96
- if (!["four_answers", "actions"].includes(fault?.register) || !Array.isArray(fault.cites)) return [fault];
97
- const number = (c) => toModel(c.ordinal) ?? c.ordinal;
96
+ if (!["four_answers", "actions", "coverage"].includes(fault?.register) || !Array.isArray(fault.cites)) return [fault];
97
+ // A coverage row's numbers are the writer's already (predelivery-lint.mjs coverageCitationChecks); the others are mapped.
98
+ const number = fault.writersNumbering ? (c) => c.ordinal : (c) => toModel(c.ordinal) ?? c.ordinal;
98
99
  if (fault.register === "actions") {
99
100
  const seen = new Map(fault.cites.map((c) => [`${c.action}:${number(c)}`, { action: c.action, ordinal: number(c), withdrawn: Boolean(c.withdrawn) }]));
100
101
  return [{ ...fault, detail: actionCitationDetail([...seen.values()]) }];
@@ -98,6 +98,14 @@ export function terminalReasonFields(reason, { cap = 200, fullCap = 4000 } = {})
98
98
  return { reason: abbrev(full, cap), reasonTruncated: truncated, reasonFull: truncated ? abbrev(full, fullCap) : null };
99
99
  }
100
100
 
101
+ // The client's sentence for an order that never became a run: the words of the client failure email's
102
+ // `refused` branch below, without its markup, because a notice filed before any run exists is relayed as
103
+ // text. It names what was ordered from `job.product` exactly as that branch does.
104
+ export function clientNotStartedText(job, mark) {
105
+ const ordered = reportIdentityFor(job?.product ?? null).identity;
106
+ return `${ordered ? `The ${ordered}` : "The search"} for ${mark} was not started, and nothing was delivered. ${CLIENT_ACTION}`;
107
+ }
108
+
101
109
  // (enforcement check E11 in the family) — `reasonDetail` and `reasonQuantity` are PACKET FIELDS.
102
110
  //
103
111
  // The merge gate computes WHICH dictated connotation query dropped and hands it over as StageFailure.detail
package/driver/runner.mjs CHANGED
@@ -48,6 +48,9 @@ import { orderedQueueFiles } from "./queue-order.mjs"; // the order jobs are a
48
48
  import { isCancelled } from "./cancel.mjs"; // a stopped run must not come back through any resume path
49
49
  import { whatsappRouting } from "./stages.mjs";
50
50
  import { writeOutboxPacket } from "./outbox.mjs";
51
+ import { maybeCheckEngine } from "./engine/health.mjs"; // the engine proven between jobs, on a tick with nothing to run
52
+ import { engineCommit } from "./engine-build.mjs";
53
+ import { clientNotStartedText } from "./run-outcome.mjs";
51
54
  import { writeRunStatus, terminalRunState } from "./progress.mjs"; // A5 — grace-exit park + reclaim-bound terminal go through the guarded status writer; terminalRunState is the run record's own terminal vocabulary (2155)
52
55
  import { identitySeed } from "./progress.mjs"; // — the same stamp a run seeds, for the process that runs them
53
56
  import { writeDrainerStamp } from "./drainer-identity.mjs"; // — deploy health cannot interrogate a running process; it says so itself
@@ -346,6 +349,18 @@ function dropMatter(qdir, msgId) {
346
349
  // Exported for unit tests (the integration path exercises them via claimAndRun).
347
350
  export { matterSignature, matterLedgerPath, findDuplicateMatter, recordMatter, dropMatter, readMatterLedger };
348
351
 
352
+ // WHOSE NOTICE THIS IS, for the three notices filed before any run exists. A run's account is read from
353
+ // the profile frozen into it; these notices have no run, so the door could not tell whose they were and
354
+ // dropped every one for a token scoped to named companies (server.mjs filterByAccounts) — which is how a
355
+ // failure before start reached no courier at all. The account is the one the order NAMED: a scoped door
356
+ // always writes it (resolveScopedProfileKey). An order that named none carries null, which only a full
357
+ // grant sees, because the runner may still resolve such an order to a company from the sender's domain.
358
+ function noticeAccount(job) {
359
+ const account = typeof job?.profileKey === "string" && job.profileKey.trim() ? job.profileKey.trim() : null;
360
+ const organisation = account === "generic" && typeof job?.tenant === "string" && job.tenant ? job.tenant : null;
361
+ return { account, organisation };
362
+ }
363
+
349
364
  // Best-effort intake-reject notice. The silent-intake failure mode (live slogan-mark matter, 2026-06-10): a
350
365
  // job that dies at validation never reaches pipeline(), so no run-level failure event fires and the
351
366
  // requester hears nothing. This is the runner-side backstop: the rejection rides the outbox as a
@@ -363,6 +378,7 @@ async function intakeNotify(agentId, base, job, v) {
363
378
  `Job parked as ${base}.failed in the ${agentId} queue.`;
364
379
  const p = writeOutboxPacket(`intake-${base}.failed`, {
365
380
  kind: "intake-rejected", classify: v?.classify ?? "reject", base, agent: agentId,
381
+ ...noticeAccount(job),
366
382
  jobId: job?.id ?? null, msgId: job?.msgId ?? null,
367
383
  forwarder: job?.forwarder ?? null, forwarderEmail: job?.forwarderEmail ?? null,
368
384
  markName: (job?.markName ?? job?.name ?? job?.marks?.[0]?.name) || null,
@@ -634,6 +650,7 @@ async function duplicateNotify(agentId, base, job, prior = null, sig = null) {
634
650
  + ` command line) and it will go through.`;
635
651
  const p = writeOutboxPacket(`intake-${base}.duplicate`, {
636
652
  kind: "duplicate-skipped", base, agent: agentId,
653
+ ...noticeAccount(job),
637
654
  jobId: job?.id ?? null, msgId: job?.msgId ?? null,
638
655
  forwarder: job?.forwarder ?? null, forwarderEmail: job?.forwarderEmail ?? null,
639
656
  markName: (job?.markName ?? job?.name ?? job?.marks?.[0]?.name) || null,
@@ -696,13 +713,19 @@ function preRunFailNotify(agentId, base, job, reason) {
696
713
  // terminalReasonFields `reason`, so this cut is a no-op today — which is exactly why it survived: a
697
714
  // latent second cap, unmarked, waiting for the next caller to pass a raw reason. It collapses and
698
715
  // trims identically, so this is the same string with the cut made visible when there is one.
699
- const text = `❌ Clearotron request "${mark}" FAILED before the run could start: ${terminalReasonFields(reason).reason} — ` +
700
- `nothing has been searched or delivered. Job parked as ${base}.failed in the ${agentId} queue.`;
716
+ // A CLIENT'S ORDER IS TOLD IN THE CLIENT'S WORDS. Once a courier scoped to the client's company can see
717
+ // this notice, `text` can reach the client, and the staff line quotes the machine reason and the queue.
718
+ // The client gets the shipped not-started sentence the failure email uses; the reason stays a field.
719
+ const text = job?.clientPrincipal === true
720
+ ? clientNotStartedText(job, mark)
721
+ : `❌ Clearotron request "${mark}" FAILED before the run could start: ${terminalReasonFields(reason).reason} — ` +
722
+ `nothing has been searched or delivered. Job parked as ${base}.failed in the ${agentId} queue.`;
701
723
  // `intake-${base}.` PREFIX, not a third scheme: scripts/e2e.mjs's outboxPackets matches by runId
702
724
  // first and by that prefix second, so a name outside it is a notice the harness reports as
703
725
  // never sent. The queue base is the routing key; `kind` carries what actually happened.
704
726
  const p = writeOutboxPacket(`intake-${base}.prerun-failed`, {
705
727
  kind: "pre-run-failed", base, agent: agentId,
728
+ ...noticeAccount(job),
706
729
  jobId: job?.id ?? null, msgId: job?.msgId ?? null,
707
730
  forwarder: job?.forwarder ?? null, forwarderEmail: job?.forwarderEmail ?? null,
708
731
  markName: (job?.markName ?? job?.name ?? job?.marks?.[0]?.name) || null,
@@ -713,6 +736,8 @@ function preRunFailNotify(agentId, base, job, reason) {
713
736
  return Boolean(p);
714
737
  }
715
738
 
739
+ export { intakeNotify, duplicateNotify, preRunFailNotify }; // exported for the run-less notice test
740
+
716
741
  // B3 — guaranteed failure-notice backstop for PRE-TRY throws. The run-level catch in `runShell` owns every
717
742
  // failure inside its try{} (it RETURNS {ok:false, failedStage, …} after notifying — the
718
743
  // _driver/failure.json + outbox packet); a throw that reaches runPrepared's catch instead (res.failedStage
@@ -2288,6 +2313,19 @@ function hasQueuedWork() {
2288
2313
  });
2289
2314
  }
2290
2315
 
2316
+ // THE ENGINE IS PROVEN BETWEEN JOBS TOO (engine/health.mjs): when the worker starts, after the installed build
2317
+ // changes, and when it has had no successful call for the routine interval. Only on a tick with nothing to run, so
2318
+ // it never delays a job; an empty tick costs one read of the installed build. Isolated: a check that throws
2319
+ // must not end the activation. `checkOnStart` is set by the watch entrypoint alone: a systemd one-shot starts a
2320
+ // process every tick, and a start there is not a restart.
2321
+ let checkOnStart = false;
2322
+ async function idleEngineCheck() {
2323
+ const starting = checkOnStart;
2324
+ checkOnStart = false;
2325
+ try { await maybeCheckEngine({ build: engineCommit(), starting }); }
2326
+ catch (e) { note(`[runner] engine check FAILED to run (isolated): ${e?.message ?? e}`); }
2327
+ }
2328
+
2291
2329
  export async function main({ once = true } = {}) {
2292
2330
  // `once:false` is the no-systemd deployment: loop instead of returning, and let the SAME per-activation
2293
2331
  // body below run once per tick. Delegated rather than inlined so the systemd path (once:true, always)
@@ -2303,7 +2341,7 @@ export async function main({ once = true } = {}) {
2303
2341
  // happens to be down but there's no work anyway. A DUE run-dir POSTPONED orphan counts as work too.
2304
2342
  const dueOrphans = scanDueRunDirOrphans();
2305
2343
  const whatIfDue = hasPendingWhatIf();
2306
- if (!hasQueuedWork() && dueOrphans.length === 0 && !whatIfDue) return;
2344
+ if (!hasQueuedWork() && dueOrphans.length === 0 && !whatIfDue) return await idleEngineCheck();
2307
2345
  // Deployment config check — this is the DEPLOYMENT entrypoint, the layer that owns "what is this
2308
2346
  // install's public hostname" (not the pipeline, which is also driven by tests and by --resume with no
2309
2347
  // deployment around it). Reports only: a missing hostname costs a link, not the deliverable, so it must
@@ -2508,6 +2546,7 @@ if (isEntrypoint(import.meta.url)) {
2508
2546
  // BEST-EFFORT AND NEVER FATAL — a drainer that cannot write its stamp still drains. The absence is a
2509
2547
  // finding where it is READ (scripts/live-surface-check.mjs), which costs no client a report.
2510
2548
  const watching = argv.includes("--watch");
2549
+ checkOnStart = watching;
2511
2550
  writeDrainerStamp(config.workspaceRoot, {
2512
2551
  ...identitySeed(),
2513
2552
  mode: watching ? "watch" : "once",
@@ -21,7 +21,8 @@ instead; and `clearance-search/templates/search-request-form.html`, named only i
21
21
  | `matter-frame` | Phase 0. Writes the matter's commercial context — sector, customer base, channels of trade, jurisdictions that materially matter, off-field sectors, watchlist seeds — before any search runs. `watchlist-reference.md` is enrichment, not authority. |
22
22
  | `clearance-variants` | Classifies the mark into one of six archetypes, derives a risk theory from that, emits the variant manifest both execution skills read. Non-Latin scripts: `transliteration-scripts.md`. |
23
23
  | `blind-frame`, `frame-diff` | Re-derives the threat model from the raw instruction alone, deliberately starved of the matter frame, then diffs that model against what the run actually scoped and emits reopen directives the driver acts on. Something has to test the frame instead of reasoning inside it. |
24
- | `clearance-common-law` | The marketplace / web / social sweep, as structured Perplexity research over the platform list the stage dictates. Prompt templates: `perplexity-prompts.md`. |
24
+ | `clearance-common-law` | The marketplace / web / social sweep, as structured Perplexity research over the platform list the stage dictates. A shared spine plus one file per seat: `grid.md` (the marketplace grid) and `meaning.md` (the meaning sweep and its PR / reputational section); a single session reads both. Prompt templates: `perplexity-prompts.md`. |
25
+ | `skeptic` | The fresh-eyes review of the gathered findings before they are trusted. Hands back its flags and escalation decisions through `record_skeptic`. |
25
26
  | `clearance-register` | Register execution in the two modes a spawn selects: `unit.md` (the funnel — enumerate one axis to completion) and `digest.md` (judgment over the merged band). Plus `register-recipes.md`, `status-rules.md`, `stealth-filer-indicators.md`, `providers/`. |
26
27
  | `placement-inquiry` | Applies commercial relevance per candidate — headline-candidate / sheet-2 / watchlist-annex / out-of-scope-filtered — before any tiering runs. |
27
28
  | `case-law-citation` | Grounds risk-relevant findings in precedent fetched in-session, never from memory. One thin adapter per source in `sources/`; `evals.md` defines what working means. |
@@ -62,8 +63,8 @@ are clean. The authoring rules and the empirical-verification checklist a new pr
62
63
  ## Where to start
63
64
 
64
65
  `clearance-register/SKILL.md`, the more elaborated of the two execution skills: a spine plus per-mode files
65
- (`unit.md`, `digest.md`) and per-provider files (`providers/`). The other, `clearance-common-law`, is one spine plus
66
- `perplexity-prompts.md` — the per-mode split and `providers/` are register-only, not a shape every
67
- execution skill shares. `clearance-search/phase2-execution.md` is methodology, not sequencing — the pipeline is
66
+ (`unit.md`, `digest.md`) and per-provider files (`providers/`). The other, `clearance-common-law`, is a spine plus
67
+ one file per seat (`grid.md`, `meaning.md`) and `perplexity-prompts.md`; `providers/` is register-only, not a
68
+ shape every execution skill shares. `clearance-search/phase2-execution.md` is methodology, not sequencing — the pipeline is
68
69
  sequenced in code, in `../stages.mjs` and `../pipeline.mjs`. The old orchestrator manual is kept as a record at
69
70
  [clearance-search-spine.md](../../docs/architecture/retired-manuals/clearance-search-spine.md); no stage reads it.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: blind-frame
3
- description: The frame-STARVED independent re-derivation for the v3 preliminary trademark search workflow. **Run by the driver**, in parallel with the gather sweeps — do not call directly. Reads ONLY the raw instruction (mark, goods, classes, territories, manner of use) and NOT the matter frame, then re-derives the threat model cold across four layers — element + neighbours both directions, field by goods-overlap, sources by real channel, ranking by goods-overlap — and emits a structured model the frame-diff stage diffs against what the run actually scoped. Its job is to test the frame, not to reason inside it.
3
+ description: The frame-STARVED independent re-derivation for the trademark search workflow. **Run by the driver**, in parallel with the gather sweeps — do not call directly. Reads ONLY the raw instruction (mark, goods, classes, territories, manner of use) and NOT the matter frame, then re-derives the threat model cold across four layers — element + neighbours both directions, field by goods-overlap, sources by real channel, ranking by goods-overlap — and emits a structured model the frame-diff stage diffs against what the run actually scoped. Its job is to test the frame, not to reason inside it.
4
4
  ---
5
5
 
6
6
  ## Purpose