clearotron 0.5.0 → 0.5.1-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/CONTRIBUTING.md +2 -2
  2. package/INSTALL.md +334 -302
  3. package/QUICKSTART.md +12 -4
  4. package/README.md +12 -7
  5. package/THIRD-PARTY-NOTICES.md +4 -4
  6. package/bin/README.md +14 -11
  7. package/bin/clearotron.mjs +1 -1
  8. package/bin/connect.mjs +73 -25
  9. package/bin/example.mjs +4 -2
  10. package/bin/onboard.mjs +562 -336
  11. package/bin/start.mjs +184 -36
  12. package/bin/update.mjs +26 -13
  13. package/build-info.json +2 -2
  14. package/docs/PORTAL.md +2 -2
  15. package/docs/architecture/02-architecture.md +3 -3
  16. package/docs/architecture/04-configuration-reference.md +1 -2
  17. package/docs/architecture/05-config-governance.md +1 -1
  18. package/docs/architecture/06-operations-runbook.md +1 -1
  19. package/driver/CHANGELOG.md +77 -0
  20. package/driver/README.md +2 -2
  21. package/driver/config-inventory.mjs +20 -11
  22. package/driver/contract-e3-backlog.mjs +27 -27
  23. package/driver/contract-e3-baseline.json +2 -2
  24. package/driver/contract-vocabulary.mjs +1 -1
  25. package/driver/degraded-parts.mjs +67 -3
  26. package/driver/dev-portal.mjs +1 -1
  27. package/driver/digest-queue.mjs +5 -5
  28. package/driver/driver.config.mjs +9 -9
  29. package/driver/engine/CONTRACT.md +1 -1
  30. package/driver/engine/anthropic-agent.mjs +4 -2
  31. package/driver/engine/mcp/band-server.mjs +1 -21
  32. package/driver/engine/mcp/clarivate-propose-tool.mjs +26 -0
  33. package/driver/engine/mcp/clarivate-server.mjs +2 -18
  34. package/driver/engine/mcp/fixture-register-server.mjs +33 -0
  35. package/driver/engine/mcp/gather-config.mjs +48 -7
  36. package/driver/engine/mcp/recording-server.mjs +206 -14
  37. package/driver/engine/mcp/supplemental.mjs +4 -2
  38. package/driver/engine/openai-agent.mjs +3 -1
  39. package/driver/engine/probe.mjs +10 -0
  40. package/driver/filing-goods.mjs +95 -0
  41. package/driver/findings-model.mjs +3 -0
  42. package/driver/gateway.mjs +42 -40
  43. package/driver/knockout-assess-record.mjs +54 -4
  44. package/driver/knockout-correction-record.mjs +342 -0
  45. package/driver/knockout-frame-record.mjs +4 -2
  46. package/driver/knockout-register-read.mjs +705 -0
  47. package/driver/knockout-register-record.mjs +222 -0
  48. package/driver/knockout-review-record.mjs +96 -25
  49. package/driver/narrative-refutation-record.mjs +87 -1
  50. package/driver/order-tables.mjs +23 -0
  51. package/driver/owner-use-check.mjs +5 -2
  52. package/driver/package.json +1 -1
  53. package/driver/partial-payload-baseline.json +8 -0
  54. package/driver/pipeline-knockout.mjs +506 -313
  55. package/driver/pipeline.mjs +179 -86
  56. package/driver/portal-local-auth.mjs +7 -1
  57. package/driver/portal-service.mjs +62 -6
  58. package/driver/progress.mjs +2 -2
  59. package/driver/publish/index.mjs +18 -21
  60. package/driver/publish/knockout.mjs +40 -18
  61. package/driver/publish/render-knockout.mjs +40 -27
  62. package/driver/publish/report-dates.mjs +43 -0
  63. package/driver/recall-reconciliation.mjs +2 -2
  64. package/driver/record-goods.mjs +50 -9
  65. package/driver/register-count.mjs +12 -59
  66. package/driver/register-fixture-marker.mjs +22 -0
  67. package/driver/register-plan.mjs +48 -0
  68. package/driver/register-records.mjs +84 -266
  69. package/driver/register-taint.mjs +2 -2
  70. package/driver/repair-composers.mjs +15 -8
  71. package/driver/result-noun-fields.mjs +6 -2
  72. package/driver/run-requirements.mjs +54 -4
  73. package/driver/runner.mjs +4 -13
  74. package/driver/skills/clearance-register/providers/clarivate.md +2 -2
  75. package/driver/skills/knockout-assess/SKILL.md +101 -100
  76. package/driver/skills/knockout-frame/SKILL.md +3 -1
  77. package/driver/skills/knockout-register-read/SKILL.md +77 -0
  78. package/driver/stages-knockout.mjs +159 -98
  79. package/driver/stages.mjs +4 -2
  80. package/driver/suite-census.json +389 -71
  81. package/driver/systemd/README.md +2 -2
  82. package/driver/verify-knockout.mjs +175 -39
  83. package/driver/verify.mjs +10 -9
  84. package/mcp-server/CHANGELOG.md +4 -0
  85. package/mcp-server/CONNECT.md +4 -0
  86. package/mcp-server/demo-mode.mjs +6 -0
  87. package/mcp-server/lib/demo-texts.mjs +38 -0
  88. package/mcp-server/lib/http-handler.mjs +7 -1
  89. package/mcp-server/lib/knockout.mjs +3 -2
  90. package/mcp-server/lib/options.mjs +3 -1
  91. package/mcp-server/lib/plan.mjs +6 -1
  92. package/mcp-server/mint-token.mjs +1 -1
  93. package/mcp-server/package.json +1 -1
  94. package/mcp-server/serve.mjs +11 -0
  95. package/mcp-server/server.mjs +13 -5
  96. package/package.json +1 -1
  97. package/portal-ui/dist/assets/{index-D2wrw9cH.css → index-AtB9ZpDH.css} +29 -0
  98. package/portal-ui/dist/assets/{index-DcLbvFmQ.js → index-C1oE78Wk.js} +161 -195
  99. package/portal-ui/dist/index.html +2 -2
  100. package/portal-ui/package.json +4 -4
  101. package/providers/README.md +4 -4
  102. package/providers/_shared/execute-plan.mjs +45 -1
  103. package/providers/_shared/term-shape.mjs +1 -1
  104. package/providers/clarivate/src/capabilities.js +7 -6
  105. package/providers/clarivate/src/core.js +11 -7
  106. package/providers/clarivate/src/wider-list.js +104 -0
  107. package/providers/oauth-mcp-bridge/CHANGELOG.md +4 -0
  108. package/providers/oauth-mcp-bridge/package.json +1 -1
  109. package/providers/signa/src/capabilities.js +0 -9
  110. package/scripts/e2e-first-time.mjs +8 -7
  111. package/scripts/freeze-example-run.mjs +2 -2
  112. package/scripts/settings-render-check.mjs +5 -3
  113. package/scripts/test-run.mjs +8 -2
  114. package/shared/client-door.mjs +11 -8
  115. package/shared/connect-clients.mjs +10 -4
  116. package/shared/demo-connection.mjs +43 -0
  117. package/shared/demo-start-args.mjs +7 -2
  118. package/shared/invocation.mjs +18 -3
  119. package/shared/permanent-install.mjs +14 -0
  120. package/shared/scope.mjs +8 -1
  121. package/shared/stdio-connect.mjs +43 -21
  122. package/shared/trigger-lane.mjs +7 -0
  123. package/shared/tty-style.mjs +21 -5
@@ -44,20 +44,27 @@ import {
44
44
  // implementation; a second copy here would be a second thing to keep true.
45
45
  decideRecovery, failureSignature, classifyFailureReason, countRecoveryLanes, weatherCeilingFor,
46
46
  } from "./repairs.mjs";
47
- import { RunCancelled, assertNotCancelledBeforePublish } from "./cancel.mjs"; // stop-by-user: never the failure lane below
47
+ import { RunCancelled, assertNotCancelledBeforePublish, isCancelled, readCancel } from "./cancel.mjs"; // stop-by-user: never the failure lane below
48
48
  import { loadFrameworkManifest, parseFrameworkManifest, frameworkFor, DEFAULT_FRAMEWORK } from "./framework.mjs";
49
49
  import { attachFrameworkMethod, methodPathFor, FROZEN_METHOD_FILE } from "./framework-method.mjs";
50
50
  import { KO_STAGES, KO_STEPS, KO_STEP_REGISTER_COUNT, koSteps, koPaths, kebab, knockoutGridSpec, KNOCKOUT_WEB, KNOCKOUT_MINUTES_BAR, knockoutBarVerdict, koChunks } from "./stages-knockout.mjs";
51
51
  import { kebabCollisions, reportIdentityFor, CAPABILITY_SKIPPED_CAUSE, CAPABILITY_SKIPPED_NOTE } from "./search-policy.mjs";
52
52
  import { countPreflight, countRegisterHits, countedMarks, resolveCountExecutor } from "./register-count.mjs";
53
- import { recordsPreflight, listRegisterRecords, listedMarks, resolveRecordExecutor } from "./register-records.mjs";
53
+ import { recordsPreflight, listedMarks } from "./register-records.mjs";
54
+ import { knockoutQuestionPlan, knockoutBandPath, knockoutBandBlocks, knockoutProposals, knockoutRecordsDoc, knockoutAxis, openingQid, questionPlanPath,
55
+ readingTableLines, appendQuestionReceipts, resolveQuestionExecutor, writeFixtureMarker, addedClassQuestions, formsOfName, formQid, countRowsOf, foldFormCounts, unfoldFormCounts, withCitedFilings, withHeldGoods } from "./knockout-register-read.mjs";
54
56
  import { capabilitiesFor } from "./register-capabilities.mjs";
55
57
  // — the ONE binding of the office split to this box's env, shared with the plan lane.
56
58
  import { registerUnavailableOffices } from "./register-unreachable.mjs";
57
59
  import { runRecordLogPath } from "../providers/_shared/ledger-path.mjs"; // — this run's record log
58
60
  import { beginAnswerMemory, endAnswerMemory } from "../providers/_shared/answer-memory.mjs";
59
- import { validators as koValidators, validateMergedFindings, worstBand, registerSurfacedFilings, raterCaveats, SURVIVOR_BOUNDARY_RE } from "./verify-knockout.mjs";
60
- import { reviewDispatch, applyKnockoutReview, knockoutReviewFile } from "./knockout-review-record.mjs";
61
+ import { validators as koValidators, validateMergedFindings, worstBand, registerSurfacedFilings, raterCaveats, SURVIVOR_BOUNDARY_RE, REGISTER_LANE_FILE, PERMITTED_SOURCES } from "./verify-knockout.mjs";
62
+ import { KNOCKOUT_CARD_ORDER } from "./findings-model.mjs";
63
+ import { reviewDispatch, applyKnockoutReview, knockoutReviewFile, rewritesThatSurvive } from "./knockout-review-record.mjs";
64
+ import { correctionAnswers, correctionOutcomes, correctionWork, correctionWorkPath, keepChunkBases, knockoutCorrectionFile, movedOutsideScope, readCorrectionWork, restoreChunkBases, rollBackName, sameFinding } from "./knockout-correction-record.mjs";
65
+ import { knockoutAssessSourceDefects } from "./knockout-assess-record.mjs";
66
+ import { correctionsAppliedTable, unresolvedFlags } from "./corrections-feedforward.mjs";
67
+ import { settledKnockoutReading } from "./knockout-register-record.mjs";
61
68
  import { stripNextStepSections } from "./knockout-next-step.mjs";
62
69
  import { publishKnockout, composeKnockoutEmail } from "./publish/knockout.mjs";
63
70
  import { writeRunStatus, readRunStatus, rollupStatus, atomicWrite, identitySeed } from "./progress.mjs"; // — the identity seed is shared; the stepper is not
@@ -195,16 +202,32 @@ export function readBackLadder(ctx, sidecarPath, { minted }) { // exported for
195
202
  * with its counts, so "there was nothing to read" and "the pass never ran" are different rows in the
196
203
  * journal rather than one absent one.
197
204
  */
198
- async function knockoutReviewingPass({ ctx, run, K, merged, plan }) {
205
+ async function knockoutReviewingPass({ ctx, run, K, merged, plan, chunks, composeRecord }) {
206
+ // A ROUND ALREADY BEGUN GOES ON FROM WHERE IT STOOD: a resumed run must not check a half-corrected record as a first look.
207
+ const begun = readCorrectionWork(run.runDir);
208
+ if (begun?.stoodDown) return merged;
209
+ if (begun) return correctAndRecheck({ ctx, run, K, plan, chunks, composeRecord, work: begun, firstReview: readJsonOrNull(knockoutReviewFile(run.runDir)), merged });
210
+ // A SOURCE THE RATING LOST STAYS OPEN: leaving a reference out does not support the claim it stood behind. It goes to the correction
211
+ // with whatever the check raises, and where no check or correction follows, it stays on the record for the reviewing lawyer.
212
+ const sourceDefects = sourceDefectsOf(run.runDir, merged, chunks);
213
+ // A REPAIR THE RATING STEP PROPOSED WAITS FOR THE CHECK, and stays on the record until an accepted read of it. The changed work stays too.
214
+ const sourceAnswered = chunks.flatMap((_, c) => knockoutAssessSourceDefects(run.runDir, c)).filter((x) => x.state === "answered");
215
+ const keepOpen = () => {
216
+ if (!sourceDefects.length && !sourceAnswered.length) return;
217
+ atomicWrite(driverDir(run.runDir, "knockout-corrections.json"), JSON.stringify({ defects: sourceDefects, outcomes: [], recheck: "not-run",
218
+ open: [...sourceDefects.map((x) => ({ kind: x.kind, mark: x.mark, problem: x.problem, state: "not-corrected" })),
219
+ ...sourceAnswered.map((x) => ({ kind: "source", mark: x.mark, problem: sourceProblem(x), state: "not-rechecked" }))] }, null, 2) + "\n");
220
+ };
199
221
  const d = reviewDispatch(merged, plan);
200
222
  const { about } = d;
201
- if (!d.dispatch) {
223
+ if (!d.dispatch && !sourceDefects.length && !sourceAnswered.length) {
202
224
  runLog(run.runDir, { event: "knockout-review", outcome: "nothing-flagged", flagged: 0, listed: 0,
203
225
  marks: merged.marks.length, excludedMarks: about.marks.length, excludedOwners: about.owners.length });
204
226
  return merged;
205
227
  }
206
228
 
207
229
  const keep = (outcome, detail) => {
230
+ keepOpen();
208
231
  runLog(run.runDir, { event: "knockout-review", outcome, flagged: d.flagged, listed: d.listed, applied: 0,
209
232
  delivered: "the rated record, unrewritten", ...detail });
210
233
  note(`reviewing pass: ${outcome} — the rated record ships unrewritten`);
@@ -213,7 +236,7 @@ async function knockoutReviewingPass({ ctx, run, K, merged, plan }) {
213
236
 
214
237
  try {
215
238
  await koStage("knockout-review", ctx, {
216
- msgCtx: d.msgCtx,
239
+ msgCtx: { ...d.msgCtx, sourceAnswers: sourceAnswered.map(sourceAnswerLine) },
217
240
  });
218
241
  } catch (e) {
219
242
  return keep("stage-failed", { reason: String(e?.message ?? e).slice(0, 200) });
@@ -223,6 +246,14 @@ async function knockoutReviewingPass({ ctx, run, K, merged, plan }) {
223
246
  try { review = JSON.parse(readFileSync(knockoutReviewFile(run.runDir), "utf8")); }
224
247
  catch (e) { return keep("artifact-unreadable", { reason: String(e?.message ?? e).slice(0, 200) }); }
225
248
 
249
+ // A MATERIAL DEFECT GOES TO THE STEP THAT CAN REPAIR IT, once, and the corrected record is read again.
250
+ if (review.material?.length || sourceDefects.length) {
251
+ const work = correctionWork({ rated: merged, material: [...(review.material ?? []), ...sourceDefects], chunks });
252
+ keepChunkBases(run.runDir, chunksOf(work));
253
+ atomicWrite(correctionWorkPath(run.runDir), JSON.stringify(work, null, 2) + "\n");
254
+ return correctAndRecheck({ ctx, run, K, plan, chunks, composeRecord, work, firstReview: review, merged });
255
+ }
256
+
226
257
  const { doc, receipt } = applyKnockoutReview(merged, review);
227
258
  // THE REWRITTEN RECORD GOES THROUGH THE SAME GATE. Not a lighter one and not none: this is the record
228
259
  // a client receives, and the only reason it is trusted is that it passed what the rated one passed.
@@ -237,6 +268,111 @@ async function knockoutReviewingPass({ ctx, run, K, merged, plan }) {
237
268
  return doc;
238
269
  }
239
270
 
271
+ /** What the check compares: the source left out and the claim as it stood, beside the record it reads. */
272
+ export const sourceAnswerLine = (d) => `- "${d.mark}", finding "${d.name}"${d.removed ? ", since removed" : ""}: it cited "${d.cited}". The claim then: ${JSON.stringify(d.was?.net ?? "")}, on the ground ${JSON.stringify(d.was?.basis ?? "")}.`;
273
+
274
+ const sourceProblem = (d) => (d.kind === "weighed"
275
+ ? `This finding listed "${d.cited}" among the filings it weighed, which this run does not hold, and it was left out. Give the claim held support, or amend it.`
276
+ : `This finding cited "${d.cited}", which is not traceable to ${PERMITTED_SOURCES}, and the citation was left out. Give the claim held support, or amend it.`);
277
+
278
+ /** The sources the rating step lost and did not address, as defects on the findings they stood behind, in the record's numbering. */
279
+ function sourceDefectsOf(runDir, merged, chunks) {
280
+ return chunks.flatMap((_, c) => knockoutAssessSourceDefects(runDir, c)).filter((d) => d.state !== "answered").map((d) => {
281
+ const mark = merged.marks.find((m) => String(m?.name ?? "") === String(d.mark ?? ""));
282
+ const finding = (mark?.findings ?? []).find((f) => sameFinding(f, d));
283
+ if (!finding) return null;
284
+ return { kind: "source", mark: d.mark, finding: finding.ordinal, rests_on: [],
285
+ problem: sourceProblem(d) };
286
+ }).filter(Boolean);
287
+ }
288
+
289
+ const readJsonOrNull = (p) => { try { return JSON.parse(readFileSync(p, "utf8")); } catch { return null; } };
290
+ const chunksOf = (work) => [...new Set((work?.defects ?? []).map((x) => x.chunk).filter((c) => c != null))];
291
+
292
+ /**
293
+ * One correction and one recheck. Each chunk a defect names goes back to the rating step; the record is composed again through the
294
+ * same steps and gate; and a fresh reader reads the result, with what became of each defect. There is no third look. What it still
295
+ * finds, and any defect no one answered, stays on the record for the reviewing lawyer. Nothing here can cost a client the report,
296
+ * and no defect leaves the record by a step failing: a repair the record cannot stand with goes back name by name, and a stage that
297
+ * fails leaves what it had accepted.
298
+ */
299
+ async function correctAndRecheck({ ctx, run, K, plan, chunks, composeRecord, work, firstReview, merged }) {
300
+ const touched = chunksOf(work);
301
+ const correctedNames = [...new Set(work.defects.map((x) => x.mark))];
302
+ const log = (outcome, detail = {}) => runLog(run.runDir, { event: "knockout-review", outcome, material: work.defects.length, marks: correctedNames.length, ...detail });
303
+ const asOpen = (defects, state, reason = null) => defects.map((x) => ({ kind: x.kind, mark: x.mark, problem: x.problem, state, ...(reason ? { reason } : {}) }));
304
+ const keepRecord = (record) => { try { atomicWrite(driverDir(run.runDir, "knockout-corrections.json"), JSON.stringify(record, null, 2) + "\n"); } catch (e) { note(`corrections record not kept (non-fatal): ${String(e?.message ?? e).slice(0, 160)}`); } };
305
+ const failed = [];
306
+ for (const c of touched) {
307
+ try {
308
+ await koStage("knockout-correct", ctx, { chunkNo: c, msgCtx: { work, chunkMarks: chunks[c], framework: ctx.framework, frameworkMethod: ctx.frameworkMethod ?? null } });
309
+ } catch (e) {
310
+ if (e instanceof StageFailure && e.resetsAt) throw e;
311
+ failed.push({ chunk: c, reason: String(e?.message ?? e).slice(0, 200) });
312
+ }
313
+ }
314
+ // Back to the record as it was rated, through the same gate, with every defect still open and why.
315
+ const standDown = (outcome, detail) => {
316
+ restoreChunkBases(run.runDir, touched);
317
+ atomicWrite(correctionWorkPath(run.runDir), JSON.stringify({ ...work, stoodDown: outcome }, null, 2) + "\n");
318
+ keepRecord({ defects: work.defects, outcomes: [], recheck: "not-run", failure: outcome, failedChunks: failed, open: asOpen(work.defects, "not-corrected", outcome) });
319
+ let rated = merged;
320
+ try { rated = composeRecord(); } catch (e) { note(`the rated record could not be composed again (non-fatal): ${String(e?.message ?? e).slice(0, 160)}`); }
321
+ log(outcome, { applied: 0, delivered: "the rated record, uncorrected", ...detail });
322
+ note(`reviewing pass: ${outcome} — the rated record ships uncorrected`);
323
+ return rated;
324
+ };
325
+ if (failed.length === touched.length && !touched.some((c) => existsSync(knockoutCorrectionFile(run.runDir, c)))) return standDown("correction-failed", { reason: failed[0]?.reason });
326
+
327
+ // A REPAIR THE RECORD CANNOT STAND WITH GOES BACK, name by name, and the others stay.
328
+ let corrected = null, gateCause = null;
329
+ const rolledBack = [];
330
+ try { corrected = composeRecord(); }
331
+ catch (e) {
332
+ gateCause = String(e?.message ?? e).slice(0, 300);
333
+ for (const name of correctedNames) {
334
+ const kept = touched.map((c) => [c, readFileSync(K.assessChunk(c), "utf8"), existsSync(knockoutCorrectionFile(run.runDir, c)) ? readFileSync(knockoutCorrectionFile(run.runDir, c), "utf8") : null]);
335
+ rollBackName(run.runDir, work, name);
336
+ try { corrected = composeRecord(); rolledBack.push(name); break; }
337
+ catch { for (const [c, text, receipt] of kept) { writeFileSync(K.assessChunk(c), text); if (receipt != null) writeFileSync(knockoutCorrectionFile(run.runDir, c), receipt); } }
338
+ }
339
+ if (!corrected) return standDown("correction-refused-by-the-merged-gate", { reason: gateCause });
340
+ }
341
+ const outside = movedOutsideScope(work, corrected);
342
+ if (outside.marks.length || outside.blocks.length) return standDown("correction-moved-what-no-defect-named", { outside });
343
+
344
+ // THE FIRST PASS'S REWRITES STILL STAND WHERE NO DEFECT REOPENED THE LINE. The second pass reads the record with them on it.
345
+ let doc = corrected;
346
+ const { doc: rewritten, receipt } = applyKnockoutReview(corrected, rewritesThatSurvive(firstReview, correctedNames));
347
+ if (validateMergedFindings(run.runDir, rewritten, plan).ok) { doc = rewritten; atomicWrite(K.findings, JSON.stringify(doc, null, 2) + "\n"); }
348
+
349
+ const answers = correctionAnswers(run.runDir, touched);
350
+ const outcomes = correctionOutcomes(work, doc, answers);
351
+ const unresolved = unresolvedFlags(outcomes).map((r) => r.n);
352
+ const notAnswered = work.defects.filter((x) => outcomes.find((o) => o.n === x.n)?.outcome === "not-answered");
353
+ const held = { defects: work.defects, outcomes, failedChunks: failed, rolledBack, ...(gateCause ? { gateCause } : {}) };
354
+
355
+ const d = reviewDispatch(doc, plan);
356
+ try {
357
+ await koStage("knockout-review", ctx, { chunkNo: 1, msgCtx: { ...d.msgCtx, recheckTable: correctionsAppliedTable(outcomes) } });
358
+ } catch (e) {
359
+ if (e instanceof StageFailure && e.resetsAt) throw e;
360
+ // NOBODY READ THE CORRECTED RECORD, so nothing here can call a defect answered.
361
+ const reason = String(e?.message ?? e).slice(0, 200);
362
+ keepRecord({ ...held, recheck: "failed", failure: reason, open: asOpen(work.defects, "not-rechecked", "recheck-failed") });
363
+ log("recheck-failed", { applied: receipt.applied, unresolved: unresolved.length, reason });
364
+ return doc;
365
+ }
366
+ const second = readJsonOrNull(knockoutReviewFile(run.runDir, 1));
367
+ const found = second?.material ?? [];
368
+ const open = [...found, ...asOpen(notAnswered.filter((x) => !found.some((m) => m.mark === x.mark && m.kind === x.kind)), "not-answered")];
369
+ keepRecord({ ...held, recheck: "ran", open });
370
+ const again = applyKnockoutReview(doc, second ?? {});
371
+ if (validateMergedFindings(run.runDir, again.doc, plan).ok) { doc = again.doc; atomicWrite(K.findings, JSON.stringify(doc, null, 2) + "\n"); }
372
+ log("corrected", { applied: receipt.applied + again.receipt.applied, unresolved: unresolved.length, open: open.length, failedChunks: failed.length, rolledBack: rolledBack.length });
373
+ return doc;
374
+ }
375
+
240
376
  async function koStage(name, ctx, { chunkNo = null, msgCtx = {} } = {}) {
241
377
  // — the stage's own start, captured before ANY work: before the existsSync, before the validator
242
378
  // read, before the message composition. states why on the spine — capture it after the await and
@@ -285,6 +421,95 @@ async function koStage(name, ctx, { chunkNo = null, msgCtx = {} } = {}) {
285
421
  return r;
286
422
  }
287
423
 
424
+ // ── THE READING STEP, around its model turn ──────────────────────────────────────────────────────────
425
+ //
426
+ // The counts have landed and nothing has been read. The code writes the run's question plan; the turn looks at the counts,
427
+ // asks what the reading rule calls for, and hands back its judgment. The record every later stage reads is built here,
428
+ // from what the register answered and what the turn said.
429
+ //
430
+ // NEVER TERMINAL, the rule this lane has always held for its filings: the counts are the product, and a run that got
431
+ // them delivers. When a turn fails the record keeps every answer the run holds and every decision the turn had settled,
432
+ // with the failure on it, and nothing more is fetched: listing each smaller count is no recovery. A rate limit is not
433
+ // that failure: it parks and resumes as every stage's does, and the resume reuses each answer held.
434
+ async function readTheRegister({ ctx, job, K, run, agent, markRows, plan, counts, countExec, opts }) {
435
+ const names = markRows.map((m) => ({ name: String(m.name), classes: Array.isArray(m.classes) ? m.classes : null }));
436
+ const exec = resolveQuestionExecutor({
437
+ lister: opts?.recordLister ?? null, adapter: activeProvider(),
438
+ agentId: agent, sessionKey: `clearance-${run.slug}-${run.codename}`, recordLog: runRecordLogPath(run.runDir),
439
+ // A fixture run never reaches a live register: if the counts ran on fixtures this lane may not either.
440
+ offline: countExec.source.startsWith("fixtures:"),
441
+ fixtureDir: job?.registerFixtures?.records ?? null,
442
+ });
443
+ const refusal = countExec.source.startsWith("fixtures:") && exec.source === "none"
444
+ ? "this run counted from fixtures and its job declares no `registerFixtures.records` directory, so the "
445
+ + "filings behind the counts were not listed — a fixture run never reaches a live register."
446
+ : recordsPreflight({ capabilities: ctx.registerCaps, hasAdapter: exec.source !== "none" });
447
+ if (refusal) {
448
+ atomicWrite(K.registerRecords, JSON.stringify({
449
+ schema: 2, provider: REGISTER_PROVIDER, providerLabel: ctx.registerCaps?.label ?? REGISTER_PROVIDER,
450
+ takenAt: new Date().toISOString(), unavailable: refusal, marks: [],
451
+ }, null, 2) + "\n");
452
+ note(`register filings not listed: ${refusal}`);
453
+ runLog(run.runDir, { event: "knockout-register-records-refused", provider: REGISTER_PROVIDER, reason: refusal });
454
+ return null;
455
+ }
456
+ const unreachable = exec.source === "provider" ? (ctx.registerUnreachable ?? []) : [];
457
+ const scope = { marks: names, classes: job.classes ?? null, jurisdictions: job.jurisdictions ?? null, capabilities: ctx.registerCaps, unreachable };
458
+ const build = (reading) => knockoutRecordsDoc({ ...scope, provider: REGISTER_PROVIDER, counts, reading, framedMarks: plan.marks,
459
+ readBlocks: (name) => knockoutBandBlocks(run.runDir, name), readProposals: (name) => knockoutProposals(run.runDir, name) });
460
+ try {
461
+ if (exec.fixtureDir) writeFixtureMarker(run.runDir, exec.fixtureDir);
462
+ atomicWrite(questionPlanPath(run.runDir), JSON.stringify(knockoutQuestionPlan({ ...scope, framedMarks: plan.marks }), null, 2) + "\n");
463
+ mkdirSync(join(run.runDir, "register-units"), { recursive: true });
464
+ } catch (e) {
465
+ note(`register filings listing failed (non-fatal): ${e.message}`);
466
+ runLog(run.runDir, { event: "knockout-register-records-failed", provider: REGISTER_PROVIDER, cause: String(e?.message ?? e).slice(0, 300) });
467
+ return null;
468
+ }
469
+
470
+ let reading = null;
471
+ try {
472
+ // A REGISTER INJECTED IN-PROCESS has no tool server a model turn could reach, so the code asks what the plan owes each name.
473
+ if (exec.source === "injected") {
474
+ const framedOf = (name) => (plan.marks ?? []).find((f) => String(f?.name ?? "").trim().toLowerCase() === name.toLowerCase()) ?? null;
475
+ const owedOf = (name) => [
476
+ ...((counts.marks ?? []).find((m) => String(m?.name) === name)?.counts?.identical?.total > 0 ? formsOfName(name, framedOf(name)).map((_, i) => formQid(name, i)) : []),
477
+ ...addedClassQuestions(run.runDir, name).map((q) => q.qid)];
478
+ await runBatched(names.map((m) => m.name).filter((name) => owedOf(name).length), 3, async (name) => {
479
+ const r = await exec.execute({ planPath: questionPlanPath(run.runDir), axis: knockoutAxis(name), outputPath: knockoutBandPath(run.runDir, name),
480
+ qids: owedOf(name) });
481
+ if (r?.ok === false) note(`register list for one name did not complete (non-fatal): ${String(r.cause ?? "").slice(0, 160)}`);
482
+ });
483
+ } else {
484
+ const inScope = [...new Set(names.flatMap((m) => m.classes ?? []).concat(Array.isArray(job.classes) ? job.classes : []))].join(", ") || null;
485
+ await koStage("knockout-register-read", ctx, { msgCtx: {
486
+ readingLines: readingTableLines({ marks: names, counts, classes: job.classes ?? null, framedMarks: plan.marks, runDir: run.runDir }),
487
+ providerDoc: activeProvider()?.skillDoc ?? null, inScope,
488
+ } });
489
+ reading = JSON.parse(readFileSync(K.registerReading, "utf8"));
490
+ runLog(run.runDir, { event: "knockout-register-read", names: reading.marks?.length ?? 0 });
491
+ }
492
+ } catch (e) {
493
+ if (e instanceof StageFailure && e.resetsAt) throw e;
494
+ note(`register reading step did not finish (non-fatal): ${String(e?.message ?? e).slice(0, 200)}`);
495
+ runLog(run.runDir, { event: "knockout-register-read-failed", cause: String(e?.message ?? e).slice(0, 300) });
496
+ reading = settledKnockoutReading(run.runDir);
497
+ }
498
+ try {
499
+ const doc = withHeldGoods(build(reading), run.runDir, { runPrefix: `clearance-${run.slug}-${run.codename}` });
500
+ atomicWrite(K.registerRecords, JSON.stringify(doc, null, 2) + "\n");
501
+ appendQuestionReceipts(K.countLedger, doc, { provider: REGISTER_PROVIDER });
502
+ runLog(run.runDir, { event: "knockout-register-records", provider: REGISTER_PROVIDER, executor: exec.source,
503
+ marks: doc.marks.length, listed: listedMarks(doc), records: doc.marks.reduce((n, m) => n + m.records.length, 0),
504
+ questions: doc.marks.reduce((n, m) => n + m.terms.filter((t) => t.qid?.startsWith("supp:")).length, 0), reading: reading ? "finished" : "not-finished" });
505
+ return doc;
506
+ } catch (e) {
507
+ note(`register filings listing failed (non-fatal): ${e.message}`);
508
+ runLog(run.runDir, { event: "knockout-register-records-failed", provider: REGISTER_PROVIDER, cause: String(e?.message ?? e).slice(0, 300) });
509
+ return null;
510
+ }
511
+ }
512
+
288
513
  // ── The sweep's executors: injected (tests) → fixtures dir (the $0 offline guarantee) → the live
289
514
  // RESEARCH_PROVIDERS.perplexity adapter. Two of them, because the lane asks the web two kinds of thing:
290
515
  // grid async (spec, {mark, preset, reasoning}) -> { ok, ledgerJson?, requested?, present?, cause?, raw?, tookMs? }
@@ -550,9 +775,19 @@ export async function knockoutInner(ctx, job, opts = {}) {
550
775
  // settled here, once, before the paid frame turn — never twenty identical per-mark failures and a
551
776
  // published report with an empty column where the product should have been.
552
777
  const probeWanted = Boolean(policy.components?.registerProbe);
778
+ // THE RECORD THAT THIS RUN HAS NO REGISTER COMPONENT, so a later step reads a skip from what ran, and never from a missing file.
779
+ if (!probeWanted) atomicWrite(driverDir(run.runDir, REGISTER_LANE_FILE), JSON.stringify({ skipped: true }) + "\n");
553
780
  let countExec = { count: null, source: "none" };
554
781
  if (probeWanted) {
555
- const registerAdapter = activeProvider();
782
+ // — NO REGISTER SET IS A REFUSAL TOO, stamped like the count refusal below. `activeProvider()`
783
+ // throws a plain Error when CLEAROTRON_DATABASE is unset; unstamped, the ladder guessed "unknown"
784
+ // from its prose and parked the run to retry a setting no wait can supply, with the reason only
785
+ // in status.json. The remedy is the deployment, so it ends here, refused, before any spend.
786
+ let registerAdapter;
787
+ try { registerAdapter = activeProvider(); }
788
+ catch (e) {
789
+ throw new StageFailure("knockout-register-count", e.message, null, { refusal: true, failClass: "deterministic" });
790
+ }
556
791
  const caps = capabilitiesFor(REGISTER_PROVIDER);
557
792
  countExec = resolveCountExecutor({
558
793
  counter: opts?.countExecutor ?? null, adapter: registerAdapter,
@@ -698,6 +933,154 @@ export async function knockoutInner(ctx, job, opts = {}) {
698
933
  const plan = JSON.parse(readFileSync(K.plan, "utf8"));
699
934
  const planMarks = plan.marks;
700
935
 
936
+ // THE WEB SWEEP NEEDS ONLY THE PLAN. Where the register is counted it starts once the counts have passed their check, and runs beside
937
+ // the register reading and its owner checks; elsewhere it starts here. The rating waits for both, and a branch that fails waits for the
938
+ // other to settle, so nothing is left running.
939
+ const sweepMarks = async () => {
940
+ koStep(ctx, "Sweeping marks");
941
+ // WHEN THE SWEEP STARTED, for the minutes recorded against the owner's bar after it. The sweep's own
942
+ // wall clock, not the sum of the marks' — they run side by side, so a sum would report minutes nobody
943
+ // waited. Epoch, never a formatted time.
944
+ const sweepStartedAt = Date.now();
945
+ const { grid, source } = sweep;
946
+ const { preset, reasoning } = KNOCKOUT_WEB;
947
+ // step 3 — was a knob; no environment ever set it. The `Number.isFinite` guard beside it went
948
+ // with the read: a constant cannot be typo'd, which is the hazard that guard existed for.
949
+ const concurrency = 3;
950
+ let callNo = 0;
951
+ const degraded = new Map();
952
+ const outaged = new Set(); // the subset of `degraded` whose cause was a 429/5xx — see the all-failed branch
953
+ const recovered = []; // previously-degraded marks whose re-sweep succeeded — their stale assess chunks must be invalidated
954
+ if (sweep.skipped) {
955
+ // acceptance 6 — NOT ATTEMPTED. No executor is called, so nothing is billed, nothing can
956
+ // 429, and no `.failed` sentinel is written: there is no failure here to record, and writing one
957
+ // would tell a resumed run that a sweep was tried.
958
+ //
959
+ // Every mark takes the named cause, and that is the ENTIRE downstream wiring. The assess stage
960
+ // already reads it (stages-knockout.mjs renders "(DEGRADED: … — apply the null-results doctrine,
961
+ // never inflate)"), verify-knockout.mjs already REFUSES a row that holds no payload and does not
962
+ // carry degraded:true plus a manual-verification note, and the renderers already print it. The
963
+ // null-results doctrine carries this case; it needed no new path, only a cause.
964
+ for (const m of planMarks) degraded.set(m.name, CAPABILITY_SKIPPED_CAUSE[sweep.skipped] ?? sweep.skipped);
965
+ runLog(run.runDir, { event: "knockout-sweep-skipped", marks: planMarks.length, executor: source, cause: sweep.skipped });
966
+ note(`knockout sweep: not run (${sweep.skipped}) — the screen delivers its register half and discloses the rest`);
967
+ } else {
968
+ runLog(run.runDir, { event: "knockout-sweep-start", marks: planMarks.length, executor: source, preset, reasoning: reasoning.effort, resultsPerCell: KNOCKOUT_WEB.resultsPerCell, concurrency });
969
+ await runBatched(planMarks, concurrency, async (m) => {
970
+ const out = K.research(kebab(m.name));
971
+ if (existsSync(out)) return; // per-mark resume: only missing payloads re-sweep
972
+ const hadFailed = existsSync(out + ".failed");
973
+ const spec = knockoutGridSpec(m, plan.batch, { outputPath: out });
974
+ const started = Date.now();
975
+ const n = ++callNo;
976
+ // ONE MORE CALL WHEN THE PROGRAM, NOT THE PROVIDER, FAILED. The search program is written by the
977
+ // provider's model each call, and the clearance grid's own guidance retries once when it did not run
978
+ // or printed something unreadable. A provider outage is not retried here: the provider call retried
979
+ // a 429 or 5xx already, and the all-failed branch below parks the batch on it.
980
+ let r = null, attempts = 0;
981
+ const raw = []; // every attempt's, in order: a retried call's first answer is evidence too
982
+ if (!spec.terms.length || !spec.platforms.length) {
983
+ r = { ok: false, cause: "the plan names no spellings or no places for this mark" };
984
+ } else {
985
+ while (attempts < 2) {
986
+ attempts++;
987
+ try { r = await grid(spec, { mark: m.name, preset, reasoning }); }
988
+ catch (e) { r = { ok: false, cause: `executor threw: ${String(e?.message ?? e).slice(0, 200)}` }; }
989
+ if (Array.isArray(r?.raw) && r.raw.length) raw.push({ attempt: attempts, items: r.raw });
990
+ if (r?.ok || r?.outage === true || !/^grid: /.test(String(r?.cause ?? ""))) break;
991
+ }
992
+ }
993
+ // THE RAW RESULTS ARE KEPT, whether the call answered or not: what the provider returned is the only
994
+ // record of which pages a search reached, and the ledger keeps only what each cell asked for.
995
+ if (raw.length) {
996
+ try {
997
+ mkdirSync(dirname(K.webResults(kebab(m.name))), { recursive: true });
998
+ writeFileSync(K.webResults(kebab(m.name)), JSON.stringify({ mark: m.name, callNo: n, attempts: raw }, null, 1) + "\n");
999
+ } catch { /* the ledger below is the receipt; a raw-results write never fails a mark */ }
1000
+ }
1001
+ const row = {
1002
+ ts: new Date().toISOString(), mark: m.name, callNo: n, preset, reasoning: reasoning.effort, executor: source,
1003
+ spellings: spec.terms, places: spec.platforms, ...(spec.use ? { use: spec.use } : {}), resultsPerCell: spec.results_per_cell,
1004
+ cells: r?.requested ?? spec.terms.length * spec.platforms.length,
1005
+ // The mark's whole wall time, both attempts when there were two: what the client waited for.
1006
+ present: r?.present ?? 0, attempts, took_ms: Date.now() - started,
1007
+ bytes: r?.bytes ?? (r?.ledgerJson ? Buffer.byteLength(r.ledgerJson) : 0),
1008
+ ok: Boolean(r?.ok && r?.ledgerJson), ...(r?.ok && r?.ledgerJson ? {} : { cause: String(r?.cause ?? "unknown").slice(0, 300) }),
1009
+ };
1010
+ try { appendFileSync(K.sweepLedger, JSON.stringify(row) + "\n"); } catch { /* receipts best-effort, never fatal */ }
1011
+ if (row.ok) {
1012
+ // THE LEDGER IS THE PAYLOAD. The rating step reads it as it came back: every cell, the listings
1013
+ // each search returned, and any search that could not run. It is data, with no words of ours in it.
1014
+ writeFileSync(out, r.ledgerJson + "\n");
1015
+ if (hadFailed) {
1016
+ try { rmSync(out + ".failed"); } catch { /* best-effort */ }
1017
+ recovered.push(m.name);
1018
+ }
1019
+ } else {
1020
+ degraded.set(m.name, row.cause);
1021
+ if (r?.outage === true) outaged.add(m.name);
1022
+ writeFileSync(out + ".failed", `research failed: ${row.cause}\n`);
1023
+ }
1024
+ });
1025
+ if (degraded.size >= planMarks.length) {
1026
+ // EVERY mark failed. Whether that ends the batch or pauses it depends on why, and until now it
1027
+ // always ended it: the throw carried a prose reason, and StageFailure sets `rateLimited` by an EXACT
1028
+ // string match on `reason === "rate_limited"`, so `rateLimited` was false, the lane's own catch wrote
1029
+ // .failed immediately, so the run reported a hard failure for a provider hiccup. When this was
1030
+ // written the rate-limit re-throw through pipeline()'s outer catch was the lane's ONLY escape
1031
+ // hatch and this path could not reach it. added a second one — the class-aware
1032
+ // ladder in the catch below — and an outage-shaped reason classifies TRANSIENT there, so this
1033
+ // block is no longer the difference between a park and a dead run. It stays because it is the
1034
+ // BETTER answer: `rate_limited` postpones on the provider's own clock through the outer catch,
1035
+ // where the ladder would spend a recovery attempt to learn the same thing.
1036
+ //
1037
+ // ALL of them must be outage-shaped, not merely one. A batch where two marks hit a 429 and one hit a
1038
+ // bad key is a broken configuration wearing an outage's clothes; parking it would auto-resume
1039
+ // forever and bury the real error. Anything mixed, anything unexplained, stays terminal.
1040
+ //
1041
+ // resetsAt is null: the provider does not surface Retry-After through this path, and runner.mjs's
1042
+ // postponedDueAt already applies the default backoff for a null. Better an honest null than a
1043
+ // fabricated deadline.
1044
+ if (outaged.size >= planMarks.length) {
1045
+ note(`knockout sweep: all ${planMarks.length} research calls failed with an outage-shaped status — postponing rather than failing the batch`);
1046
+ runLog(run.runDir, { event: "knockout-sweep-outage", marks: planMarks.length, executor: source });
1047
+ throw new StageFailure("knockout-sweep", "rate_limited", null);
1048
+ }
1049
+ throw new StageFailure("knockout-sweep", `all ${planMarks.length} research calls failed (executor ${source}) — nothing to assess`, null);
1050
+ }
1051
+ if (degraded.size) note(`knockout sweep: ${degraded.size}/${planMarks.length} mark(s) degraded — the batch continues (null-results doctrine)`);
1052
+ // ── WHAT THE SWEEP COST, BESIDE THE BAR (ruling 570) ─────────────────────────────────────────────
1053
+ //
1054
+ // The frame chooses each name's places with no cap, so the only way to know what a knockout costs is
1055
+ // to record it. Cells come from the RECEIPTS ON DISK rather than the loop's own variables: a resumed
1056
+ // run's earlier marks are in the ledger and not in this process, and the ledger is what a reader has
1057
+ // afterwards. The bar is recorded, not applied — nothing above or below this line reads it.
1058
+ try {
1059
+ const rows = readFileSync(K.sweepLedger, "utf8").split("\n").filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
1060
+ const cells = rows.reduce((n, r) => n + (Number.isFinite(r?.cells) ? r.cells : 0), 0);
1061
+ const places = rows.reduce((n, r) => Math.max(n, Array.isArray(r?.places) ? r.places.length : 0), 0);
1062
+ // THE SWEEP'S OWN ELAPSED TIME, UNDER A NAME THAT SAYS SO, and the bar is no longer asserted here.
1063
+ // The bar is about the RUN (ruling 591) and this span is one stage of it: both knockouts of
1064
+ // 2026-09-26 recorded `overBar: false` at 0.6 and 0.8 minutes while the runs took 14.4 minutes
1065
+ // wall, which e2e scored as over. A bar recorded against the wrong quantity is worse than an
1066
+ // unrecorded one, because the field's name says it answered the question. It is recorded at
1067
+ // delivery instead, where the run's own start is readable.
1068
+ const sweepMinutes = Number(((Date.now() - sweepStartedAt) / 60000).toFixed(1));
1069
+ runLog(run.runDir, { event: "knockout-sweep-total", marks: planMarks.length, calls: rows.length,
1070
+ cells, mostPlacesForOneName: places, sweepMinutes });
1071
+ note(`knockout sweep: ${cells} cell(s) across ${rows.length} call(s) in ${sweepMinutes} min`);
1072
+ } catch { /* the receipts are the record; a summary that could not be read never fails a sweep */ }
1073
+ }
1074
+ return { degraded, recovered };
1075
+ };
1076
+ let sweepRun = null;
1077
+ // HANDLED FROM THE START. A sweep that fails while the register is still being read rejects with nothing awaiting it yet, and
1078
+ // an unhandled rejection ends the process with no status written. The reading's `finally` and the await below take its failure.
1079
+ const startSweep = () => {
1080
+ if (!sweepRun) { sweepRun = sweepMarks(); sweepRun.catch(() => {}); }
1081
+ return sweepRun;
1082
+ };
1083
+
701
1084
  // 1.5 — STAGE 0.5: the register hit-counts. Pure code — no stage, no model, no turn. It runs
702
1085
  // BEFORE the sweep because it is the cheap deterministic question and the client sees its answer
703
1086
  // first; it runs after the frame only so the batch's shape is settled and a frame failure costs
@@ -706,73 +1089,6 @@ export async function knockoutInner(ctx, job, opts = {}) {
706
1089
  if (probeWanted) {
707
1090
  koStep(ctx, KO_STEP_REGISTER_COUNT);
708
1091
  ensureDriverDir(run.runDir);
709
- // The listing lane, as a step the count lane can run before or after. It returns the listing it
710
- // wrote, or null when it was refused or failed; either way it has already recorded why.
711
- const listFilings = async () => {
712
- let listedDoc = null;
713
- // ── 1.6 — THE FILINGS BEHIND THE NARROW COUNTS ( part 5) ─────────────────────────────────
714
- //
715
- // NEVER TERMINAL, and that is the difference between this lane and the count lane. The counts
716
- // ARE the product — none of them means no product, so the run dies. The listing EXPLAINS the
717
- // counts: a batch that got its numbers and could not fetch the faces behind them is a smaller
718
- // deliverable, not a wrong one, and killing the run would throw away the part that was paid for.
719
- // Every failure lands as a recorded reason on the surfaces instead.
720
- const recExec = resolveRecordExecutor({
721
- lister: opts?.recordLister ?? null, adapter: activeProvider(),
722
- agentId: agent, sessionKey: `clearance-${run.slug}-${run.codename}`,
723
- // — this run's record log, not the box's. The knockout lane never reads the record bodies
724
- // its batch-screen hydration writes; before this they were pure growth on a global file.
725
- recordLog: runRecordLogPath(run.runDir),
726
- // The $0 guarantee, threaded rather than re-derived: if the COUNTS ran on fixtures, this lane
727
- // may not reach a live register. resolveRecordExecutor refuses instead of falling through.
728
- offline: countExec.source.startsWith("fixtures:"),
729
- fixtureDir: job?.registerFixtures?.records ?? null,
730
- });
731
- const recRefusal = countExec.source.startsWith("fixtures:") && recExec.source === "none"
732
- // NAMES WHAT THE READER CAN ACT ON. This said `CLEAROTRON_KNOCKOUT_RECORD_FIXTURES` — a variable that
733
- // no longer exists — so the sentence now names the job field that does.
734
- ? "this run counted from fixtures and its job declares no `registerFixtures.records` directory, so the "
735
- + "filings behind the counts were not listed — a fixture run never reaches a live register."
736
- : recordsPreflight({ capabilities: ctx.registerCaps, hasAdapter: recExec.source !== "none" });
737
- if (recRefusal) {
738
- // A structural refusal is RECORDED, not swallowed. Without a sidecar the surfaces cannot tell
739
- // "this provider does not list filings" from "nobody asked", and the second reads as an
740
- // omission — the same silence part 2 closed one section up.
741
- atomicWrite(K.registerRecords, JSON.stringify({
742
- schema: 1, provider: REGISTER_PROVIDER, providerLabel: ctx.registerCaps?.label ?? REGISTER_PROVIDER,
743
- takenAt: new Date().toISOString(), unavailable: recRefusal, marks: [],
744
- }, null, 2) + "\n");
745
- note(`register filings not listed: ${recRefusal}`);
746
- runLog(run.runDir, { event: "knockout-register-records-refused", provider: REGISTER_PROVIDER, reason: recRefusal });
747
- } else {
748
- try {
749
- const recDoc = await listRegisterRecords({
750
- marks: markRows.map((m) => ({ name: String(m.name), classes: Array.isArray(m.classes) ? m.classes : null })),
751
- classes: job.classes ?? null, jurisdictions: job.jurisdictions ?? null,
752
- provider: REGISTER_PROVIDER, capabilities: ctx.registerCaps,
753
- lister: recExec.list, ledgerPath: K.countLedger,
754
- // — the SAME split the counts used. Re-deriving it here would let the two halves of one
755
- // report narrow to different scopes; `recExec` can also be a fixture lister while the counts
756
- // ran live, and the offices a fixture holds are not this box's.
757
- unreachable: recExec.source === "provider" ? (ctx.registerUnreachable ?? []) : [],
758
- concurrency: 3, // step 3 — the same constant as the sibling call above
759
- ...(process.env.CLEAROTRON_KNOCKOUT_RECORD_CAP ? { cap: Number(process.env.CLEAROTRON_KNOCKOUT_RECORD_CAP) } : {}),
760
- ...(process.env.CLEAROTRON_KNOCKOUT_VARIANT_CAP ? { variantCap: Number(process.env.CLEAROTRON_KNOCKOUT_VARIANT_CAP) } : {}),
761
- });
762
- atomicWrite(K.registerRecords, JSON.stringify(recDoc, null, 2) + "\n");
763
- listedDoc = recDoc;
764
- runLog(run.runDir, { event: "knockout-register-records", provider: REGISTER_PROVIDER, executor: recExec.source,
765
- marks: recDoc.marks.length, listed: listedMarks(recDoc), records: recDoc.marks.reduce((n, m) => n + m.records.length, 0) });
766
- } catch (e) {
767
- // The lane does not throw per mark, so reaching here means something structural broke. It
768
- // still must not take the counts down with it — but it must not vanish either.
769
- note(`register filings listing failed (non-fatal): ${e.message}`);
770
- runLog(run.runDir, { event: "knockout-register-records-failed", provider: REGISTER_PROVIDER, cause: String(e?.message ?? e).slice(0, 300) });
771
- }
772
- }
773
- return listedDoc;
774
- };
775
-
776
1092
  // ── THE OWNER LOOKUP, ONCE THE LISTING HAS NAMED THE OWNER AND A COUNT HAS LANDED ──────────────
777
1093
  //
778
1094
  // Run after the count gate below, whichever lane went first. A batch where not one mark got a
@@ -816,31 +1132,22 @@ export async function knockoutInner(ctx, job, opts = {}) {
816
1132
  }
817
1133
  };
818
1134
 
819
- // ── THE LISTING FIRST, ON A REGISTER WHOSE LISTING HOLDS THE COUNT ──────────────────────────────
820
- //
821
- // The identical and close columns are the exact predicate over a term, and the listing asks exactly
822
- // that. On a register that declares its listing carries the register's own total for that question
823
- // (`listingAnswersCount`), the listing runs first and the count lane takes those two columns from it
824
- // (register-count.mjs listingAnswers) instead of paying for them again. It still asks what the
825
- // listing never asks — `containing` — and any term the listing did not answer. Every other register
826
- // counts first and lists second, as it always has.
827
- const listFirst = ctx.registerCaps?.listingAnswersCount === true;
828
- const listedFirst = listFirst ? await listFilings() : null;
829
1135
  // resume: a settled prior sidecar is reused cell by cell, so a re-run never re-bills a count that
830
1136
  // already landed — including across a build that ADDED a predicate, where only the new column is
831
1137
  // bought (register-count.mjs cellSettled).
832
1138
  let prior = null;
833
- try { prior = JSON.parse(readFileSync(K.registerCounts, "utf8")); } catch { /* first attempt */ }
834
- const doc = await countRegisterHits({
1139
+ try { prior = unfoldFormCounts(JSON.parse(readFileSync(K.registerCounts, "utf8"))); } catch { /* first attempt */ }
1140
+ const counted0 = await countRegisterHits({
835
1141
  // Scope comes from the REQUEST (markRows / job.classes), never from the frame's plan. The plan
836
1142
  // is a model output, and its per-mark classes may carry the frame's own belt-and-braces
837
1143
  // inference — fine for shaping a research prompt, wrong for a figure the client reads as
838
1144
  // "filings in my classes". The names are identical either way (the frame validator enforces
839
1145
  // one row per instructed mark, verbatim), so this is a scope decision, not a set difference.
840
- marks: markRows.map((m) => ({ name: String(m.name), classes: Array.isArray(m.classes) ? m.classes : null })),
1146
+ marks: countRowsOf(markRows.map((m) => ({ name: String(m.name), classes: Array.isArray(m.classes) ? m.classes : null })), plan.marks),
841
1147
  classes: job.classes ?? null, jurisdictions: job.jurisdictions ?? null,
842
1148
  provider: REGISTER_PROVIDER, capabilities: ctx.registerCaps,
843
1149
  counter: countExec.count, ledgerPath: K.countLedger, prior,
1150
+ joinForms: countExec.source === "provider" && ctx.registerCaps?.exactFormsCountAsOne === true,
844
1151
  unreachable: ctx.registerUnreachable ?? [], // — computed once at preflight, above
845
1152
  concurrency: 3, // step 3 — was a knob; no environment ever set it
846
1153
  // The close-variation fan-out's ceiling. A deployment may buy FEWER forms per mark than the code
@@ -848,8 +1155,9 @@ export async function knockoutInner(ctx, job, opts = {}) {
848
1155
  // to VARIANT_CAP, so this knob can only ever narrow. Unset ⇒ the code cap, which is the answer
849
1156
  // for every deployment that has not thought about it.
850
1157
  ...(process.env.CLEAROTRON_KNOCKOUT_VARIANT_CAP ? { variantCap: Number(process.env.CLEAROTRON_KNOCKOUT_VARIANT_CAP) } : {}),
851
- ...(listedFirst ? { listed: listedFirst } : {}),
852
1158
  });
1159
+ // A name given in several written forms is counted as each, and reads as one row from here on.
1160
+ const doc = foldFormCounts(counted0, markRows.map((m) => ({ name: String(m.name) })), plan.marks);
853
1161
  const counted = countedMarks(doc);
854
1162
  // Not one mark got a number. The count IS this product — a batch published now would be a plain
855
1163
  // knockout wearing a Depth 2 label and price, which is the silent substitution the whole
@@ -866,150 +1174,22 @@ export async function knockoutInner(ctx, job, opts = {}) {
866
1174
  runLog(run.runDir, { event: "knockout-register-counts", provider: REGISTER_PROVIDER, executor: countExec.source, marks: doc.marks.length, counted, regions: doc.scope.regions ?? "worldwide" });
867
1175
  if (counted < doc.marks.length) note(`register counts: ${doc.marks.length - counted}/${doc.marks.length} mark(s) unavailable — the batch continues (they publish as "not available", never as zero)`);
868
1176
 
869
- await checkOwners(listFirst ? listedFirst : await listFilings());
1177
+ const sweeping = startSweep();
1178
+ try { await checkOwners(await readTheRegister({ ctx, job, K, run, agent, markRows, plan, counts: doc, countExec, opts })); }
1179
+ finally { await sweeping.catch(() => {}); }
870
1180
  }
871
1181
 
872
1182
  // 2 — the sweep: ONE grid call per mark, receipted, through the clearance grid's own program path.
873
1183
  // Every spelling the frame named for the mark is searched once on every place it named for the batch,
874
1184
  // and every result is kept, with no summary (stages-knockout.mjs, KNOCKOUT_WEB). A mark whose call
875
1185
  // fails is degraded on its own; the rest of the batch goes on.
876
- koStep(ctx, "Sweeping marks");
877
- // WHEN THE SWEEP STARTED, for the minutes recorded against the owner's bar after it. The sweep's own
878
- // wall clock, not the sum of the marks' — they run side by side, so a sum would report minutes nobody
879
- // waited. Epoch, never a formatted time.
880
- const sweepStartedAt = Date.now();
881
- const { grid, source } = sweep;
882
- const { preset, reasoning } = KNOCKOUT_WEB;
883
- // step 3 — was a knob; no environment ever set it. The `Number.isFinite` guard beside it went
884
- // with the read: a constant cannot be typo'd, which is the hazard that guard existed for.
885
- const concurrency = 3;
886
- let callNo = 0;
887
- const degraded = new Map();
888
- const outaged = new Set(); // the subset of `degraded` whose cause was a 429/5xx — see the all-failed branch
889
- const recovered = []; // previously-degraded marks whose re-sweep succeeded — their stale assess chunks must be invalidated
890
- if (sweep.skipped) {
891
- // acceptance 6 — NOT ATTEMPTED. No executor is called, so nothing is billed, nothing can
892
- // 429, and no `.failed` sentinel is written: there is no failure here to record, and writing one
893
- // would tell a resumed run that a sweep was tried.
894
- //
895
- // Every mark takes the named cause, and that is the ENTIRE downstream wiring. The assess stage
896
- // already reads it (stages-knockout.mjs renders "(DEGRADED: … — apply the null-results doctrine,
897
- // never inflate)"), verify-knockout.mjs already REFUSES a row that holds no payload and does not
898
- // carry degraded:true plus a manual-verification note, and the renderers already print it. The
899
- // null-results doctrine carries this case; it needed no new path, only a cause.
900
- for (const m of planMarks) degraded.set(m.name, CAPABILITY_SKIPPED_CAUSE[sweep.skipped] ?? sweep.skipped);
901
- runLog(run.runDir, { event: "knockout-sweep-skipped", marks: planMarks.length, executor: source, cause: sweep.skipped });
902
- note(`knockout sweep: not run (${sweep.skipped}) — the screen delivers its register half and discloses the rest`);
903
- } else {
904
- runLog(run.runDir, { event: "knockout-sweep-start", marks: planMarks.length, executor: source, preset, reasoning: reasoning.effort, resultsPerCell: KNOCKOUT_WEB.resultsPerCell, concurrency });
905
- await runBatched(planMarks, concurrency, async (m) => {
906
- const out = K.research(kebab(m.name));
907
- if (existsSync(out)) return; // per-mark resume: only missing payloads re-sweep
908
- const hadFailed = existsSync(out + ".failed");
909
- const spec = knockoutGridSpec(m, plan.batch, { outputPath: out });
910
- const started = Date.now();
911
- const n = ++callNo;
912
- // ONE MORE CALL WHEN THE PROGRAM, NOT THE PROVIDER, FAILED. The search program is written by the
913
- // provider's model each call, and the clearance grid's own guidance retries once when it did not run
914
- // or printed something unreadable. A provider outage is not retried here: the provider call retried
915
- // a 429 or 5xx already, and the all-failed branch below parks the batch on it.
916
- let r = null, attempts = 0;
917
- const raw = []; // every attempt's, in order: a retried call's first answer is evidence too
918
- if (!spec.terms.length || !spec.platforms.length) {
919
- r = { ok: false, cause: "the plan names no spellings or no places for this mark" };
920
- } else {
921
- while (attempts < 2) {
922
- attempts++;
923
- try { r = await grid(spec, { mark: m.name, preset, reasoning }); }
924
- catch (e) { r = { ok: false, cause: `executor threw: ${String(e?.message ?? e).slice(0, 200)}` }; }
925
- if (Array.isArray(r?.raw) && r.raw.length) raw.push({ attempt: attempts, items: r.raw });
926
- if (r?.ok || r?.outage === true || !/^grid: /.test(String(r?.cause ?? ""))) break;
927
- }
928
- }
929
- // THE RAW RESULTS ARE KEPT, whether the call answered or not: what the provider returned is the only
930
- // record of which pages a search reached, and the ledger keeps only what each cell asked for.
931
- if (raw.length) {
932
- try {
933
- mkdirSync(dirname(K.webResults(kebab(m.name))), { recursive: true });
934
- writeFileSync(K.webResults(kebab(m.name)), JSON.stringify({ mark: m.name, callNo: n, attempts: raw }, null, 1) + "\n");
935
- } catch { /* the ledger below is the receipt; a raw-results write never fails a mark */ }
936
- }
937
- const row = {
938
- ts: new Date().toISOString(), mark: m.name, callNo: n, preset, reasoning: reasoning.effort, executor: source,
939
- spellings: spec.terms, places: spec.platforms, ...(spec.use ? { use: spec.use } : {}), resultsPerCell: spec.results_per_cell,
940
- cells: r?.requested ?? spec.terms.length * spec.platforms.length,
941
- // The mark's whole wall time, both attempts when there were two: what the client waited for.
942
- present: r?.present ?? 0, attempts, took_ms: Date.now() - started,
943
- bytes: r?.bytes ?? (r?.ledgerJson ? Buffer.byteLength(r.ledgerJson) : 0),
944
- ok: Boolean(r?.ok && r?.ledgerJson), ...(r?.ok && r?.ledgerJson ? {} : { cause: String(r?.cause ?? "unknown").slice(0, 300) }),
945
- };
946
- try { appendFileSync(K.sweepLedger, JSON.stringify(row) + "\n"); } catch { /* receipts best-effort, never fatal */ }
947
- if (row.ok) {
948
- // THE LEDGER IS THE PAYLOAD. The rating step reads it as it came back: every cell, the listings
949
- // each search returned, and any search that could not run. It is data, with no words of ours in it.
950
- writeFileSync(out, r.ledgerJson + "\n");
951
- if (hadFailed) {
952
- try { rmSync(out + ".failed"); } catch { /* best-effort */ }
953
- recovered.push(m.name);
954
- }
955
- } else {
956
- degraded.set(m.name, row.cause);
957
- if (r?.outage === true) outaged.add(m.name);
958
- writeFileSync(out + ".failed", `research failed: ${row.cause}\n`);
959
- }
960
- });
961
- if (degraded.size >= planMarks.length) {
962
- // EVERY mark failed. Whether that ends the batch or pauses it depends on why, and until now it
963
- // always ended it: the throw carried a prose reason, and StageFailure sets `rateLimited` by an EXACT
964
- // string match on `reason === "rate_limited"`, so `rateLimited` was false, the lane's own catch wrote
965
- // .failed immediately, so the run reported a hard failure for a provider hiccup. When this was
966
- // written the rate-limit re-throw through pipeline()'s outer catch was the lane's ONLY escape
967
- // hatch and this path could not reach it. added a second one — the class-aware
968
- // ladder in the catch below — and an outage-shaped reason classifies TRANSIENT there, so this
969
- // block is no longer the difference between a park and a dead run. It stays because it is the
970
- // BETTER answer: `rate_limited` postpones on the provider's own clock through the outer catch,
971
- // where the ladder would spend a recovery attempt to learn the same thing.
972
- //
973
- // ALL of them must be outage-shaped, not merely one. A batch where two marks hit a 429 and one hit a
974
- // bad key is a broken configuration wearing an outage's clothes; parking it would auto-resume
975
- // forever and bury the real error. Anything mixed, anything unexplained, stays terminal.
976
- //
977
- // resetsAt is null: the provider does not surface Retry-After through this path, and runner.mjs's
978
- // postponedDueAt already applies the default backoff for a null. Better an honest null than a
979
- // fabricated deadline.
980
- if (outaged.size >= planMarks.length) {
981
- note(`knockout sweep: all ${planMarks.length} research calls failed with an outage-shaped status — postponing rather than failing the batch`);
982
- runLog(run.runDir, { event: "knockout-sweep-outage", marks: planMarks.length, executor: source });
983
- throw new StageFailure("knockout-sweep", "rate_limited", null);
984
- }
985
- throw new StageFailure("knockout-sweep", `all ${planMarks.length} research calls failed (executor ${source}) — nothing to assess`, null);
986
- }
987
- if (degraded.size) note(`knockout sweep: ${degraded.size}/${planMarks.length} mark(s) degraded — the batch continues (null-results doctrine)`);
988
- // ── WHAT THE SWEEP COST, BESIDE THE BAR (ruling 570) ─────────────────────────────────────────────
989
- //
990
- // The frame chooses each name's places with no cap, so the only way to know what a knockout costs is
991
- // to record it. Cells come from the RECEIPTS ON DISK rather than the loop's own variables: a resumed
992
- // run's earlier marks are in the ledger and not in this process, and the ledger is what a reader has
993
- // afterwards. The bar is recorded, not applied — nothing above or below this line reads it.
994
- try {
995
- const rows = readFileSync(K.sweepLedger, "utf8").split("\n").filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
996
- const cells = rows.reduce((n, r) => n + (Number.isFinite(r?.cells) ? r.cells : 0), 0);
997
- const places = rows.reduce((n, r) => Math.max(n, Array.isArray(r?.places) ? r.places.length : 0), 0);
998
- // THE SWEEP'S OWN ELAPSED TIME, UNDER A NAME THAT SAYS SO, and the bar is no longer asserted here.
999
- // The bar is about the RUN (ruling 591) and this span is one stage of it: both knockouts of
1000
- // 2026-09-26 recorded `overBar: false` at 0.6 and 0.8 minutes while the runs took 14.4 minutes
1001
- // wall, which e2e scored as over. A bar recorded against the wrong quantity is worse than an
1002
- // unrecorded one, because the field's name says it answered the question. It is recorded at
1003
- // delivery instead, where the run's own start is readable.
1004
- const sweepMinutes = Number(((Date.now() - sweepStartedAt) / 60000).toFixed(1));
1005
- runLog(run.runDir, { event: "knockout-sweep-total", marks: planMarks.length, calls: rows.length,
1006
- cells, mostPlacesForOneName: places, sweepMinutes });
1007
- note(`knockout sweep: ${cells} cell(s) across ${rows.length} call(s) in ${sweepMinutes} min`);
1008
- } catch { /* the receipts are the record; a summary that could not be read never fails a sweep */ }
1009
- }
1186
+ const { degraded, recovered } = await startSweep();
1010
1187
 
1011
1188
  // 3 — assess (chunked ≤8/turn; merged + gated in code). DEGRADED per the DISK truth (payload
1012
1189
  // presence), never the in-memory Map alone — resume-proof: a prior attempt's degrades count too.
1190
+ // A STOP ASKED FOR WHILE THE TWO RESEARCH BRANCHES RAN ends the run here, with both settled and their work kept: the rating does
1191
+ // not start, and the status does not name it as begun. The turn boundary would refuse its first turn anyway.
1192
+ if (isCancelled(run.runDir)) throw new RunCancelled("knockout-assess", readCancel(run.runDir));
1013
1193
  koStep(ctx, "Knockout assessment");
1014
1194
  const chunkRows = planMarks.map((m) => {
1015
1195
  const has = existsSync(K.research(kebab(m.name)));
@@ -1034,96 +1214,103 @@ export async function knockoutInner(ctx, job, opts = {}) {
1034
1214
  for (let c = 0; c < chunks.length; c++) {
1035
1215
  await koStage("knockout-assess", ctx, { chunkNo: c, msgCtx: { chunkMarks: chunks[c], chunkTotal: chunks.length, framework: ctx.framework, frameworkMethod: ctx.frameworkMethod ?? null } });
1036
1216
  }
1217
+ // ONE COMPOSITION, for the rated batch and for a corrected one: the chunks read, the summary joined, the engine's caveats,
1218
+ // the merged gate and the write. A correction that took a shorter road would reach a client through a lighter gate.
1219
+ const composeRecord = () => {
1220
+ // cardOrder records how this run's page lists a name's cards, so a delivered report re-renders as it was delivered.
1221
+ const merged = { schema_version: 1, framework: null, batch: null, cardOrder: KNOCKOUT_CARD_ORDER, marks: [] };
1222
+ const summaries = [];
1223
+ for (let c = 0; c < chunks.length; c++) {
1224
+ // READ prefers the new location and falls back to the pre-relocation one, so a run whose chunks
1225
+ // were written before the move (or through the Bash bypass closed) resumes without paying for
1226
+ // a re-dispatch. Nothing writes the legacy path any more — see stages-knockout.mjs.
1227
+ const chunkPath = existsSync(K.assessChunk(c)) ? K.assessChunk(c) : K.assessChunkLegacy(c);
1228
+ const part = JSON.parse(readFileSync(chunkPath, "utf8"));
1229
+ if (c === 0) { merged.framework = part.framework ?? { source: ctx.framework.framework_key, ladder: ctx.framework.bands.map((b) => b.label) }; merged.batch = part.batch ?? null; }
1230
+ if (typeof part.chunkSummary === "string" && part.chunkSummary.trim()) summaries.push(part.chunkSummary.trim());
1231
+ merged.marks.push(...(part.marks ?? []));
1232
+ }
1233
+ if (!merged.batch) merged.batch = { productContext: plan.batch.productContext, standardCaveats: [] };
1234
+ // the WHOLE-batch executive summary = the per-chunk summaries, composed in code (every chunk's
1235
+ // validator required one, so no mark's chunk is silently absent — review 2026-07-17)
1236
+ merged.batch.executiveSummary = summaries.join("\n\n");
1237
+ // ── THE PENDING-REGISTER CAVEAT, CONDITIONAL SINCE RF-10 v3 ────────────────
1238
+ //
1239
+ // "Ratings reflect our common law assessment. Register analysis may adjust ratings in either
1240
+ // direction." This is a CODE DEFAULT that fires when the model supplied no caveat of its own, and
1241
+ // turned it from dormant into the thing that ships.
1242
+ //
1243
+ // BEFORE: a rule in the knockout-assess manual ordered the seat to write that caveat, so the array
1244
+ // arrived non-empty and this default almost never fired. THAT RULE IS RETIRED IN THIS SAME BRANCH —
1245
+ // the seat is no longer told to write it — so the array now arrives EMPTY and this line injects the
1246
+ // sentence unconditionally. Retiring the rule in the doctrine while leaving its default in the code
1247
+ // did not remove the caveat; it made it fire on every run.
1248
+ //
1249
+ // And it is FALSE on the runs it now fires on. The rater is handed this run's fetched register
1250
+ // filings and weighs them, so "register analysis may adjust ratings" describes work that already
1251
+ // happened. RF-10 v3 (synthesis-rules.md): when register analysis ran AND surfaced live filings,
1252
+ // drop the caveat and cite the register evidence directly; where it did not run, it stands and is
1253
+ // the honest thing to say.
1254
+ //
1255
+ // THE DRIVER'S READ, off the run. A seat that could assert whether the register ran could waive its
1256
+ // own caveat. Records present AND non-empty: a file that exists with nothing in it is a register
1257
+ // that surfaced no filings, which is exactly the case the caveat is still true for.
1258
+ // — ONE DERIVATION, shared with the verifier. This was a private copy, and the
1259
+ // lint that checks the result did not have it: it required the caveat unconditionally while this
1260
+ // injected it conditionally, so any run where the seat supplied its own caveats failed by
1261
+ // construction. Two predicates that must agree forever is how they stop agreeing.
1262
+ // — THE SAME DERIVATION THE LINT USES. This counted the array, blanks included, so
1263
+ // `["", " "]` read as "the rater supplied two" here and as "supplied none" in the verifier. The lint
1264
+ // could not see the disagreement because the survivor sentence below silenced it entirely.
1265
+ if (raterCaveats(merged.batch.standardCaveats).length === 0 && !registerSurfacedFilings(K.registerRecords)) {
1266
+ merged.batch.standardCaveats = ["Ratings reflect our common law assessment. Register analysis may adjust ratings in either direction."];
1267
+ }
1268
+ if (!Array.isArray(merged.batch.standardCaveats)) merged.batch.standardCaveats = [];
1269
+ // ── the survivor sentence, in CODE ( fix 3) ────────────────────────────────────────────────────
1270
+ //
1271
+ // A mark this lane did not knock out is a SURVIVOR. It is not clear, and the document must not be
1272
+ // readable as though it were: the knockout screens, the clearance enumerates, and the whole distance
1273
+ // between them is the work that has not happened yet. Two runs on two matters delivered "Medium,
1274
+ // complete" while missing almost every mark the lawyer named, because a screen cannot know what it
1275
+ // did not look for — so the boundary of the screen is stated by the engine rather than left to the
1276
+ // assessing model, which is the one party that cannot see it.
1277
+ //
1278
+ // APPENDED, never prepended: publish/knockout.mjs's email takes standardCaveats[0], so leading with
1279
+ // this would silently replace the standing caveat in the requester's inbox.
1280
+ const survivorNote = survivorBoundaryNote(policy);
1281
+ if (!merged.batch.standardCaveats.some((c) => SURVIVOR_BOUNDARY_RE.test(String(c))))
1282
+ merged.batch.standardCaveats.push(survivorNote);
1283
+ // ── the skipped-capability sentence, in CODE, for the survivor sentence's own reason ──────
1284
+ //
1285
+ // The per-mark degrade above already reaches the client on every row. This is the RUN-level fact
1286
+ // underneath twenty identical rows: not "research was unavailable for this name" twenty times, but
1287
+ // one capability that never ran on this deployment. The assessing model cannot state it — it is
1288
+ // told a mark is degraded, never why the whole screen is — so the engine states it, exactly as it
1289
+ // states the survivor boundary two lines up.
1290
+ //
1291
+ // APPENDED, never prepended, for the same reason the survivor note is: publish/knockout.mjs's email
1292
+ // takes standardCaveats[0], and leading with this would silently replace the standing caveat in the
1293
+ // requester's inbox.
1294
+ const skippedNote = sweep.skipped ? CAPABILITY_SKIPPED_NOTE[sweep.skipped] : null;
1295
+ if (skippedNote && !merged.batch.standardCaveats.some((c) => String(c) === skippedNote))
1296
+ merged.batch.standardCaveats.push(skippedNote);
1297
+ // The merged gate now also validates the TYPED findings and receipts their citations, and it
1298
+ // NORMALISES as it validates — each finding's band comes back in the frozen deck's own casing — so
1299
+ // it runs BEFORE the artifact is written, not after. The counts are logged because a receipts pass
1300
+ // over zero citations is a different fact from a receipts pass, and only the count can tell them
1301
+ // apart afterwards.
1302
+ // BEFORE THE GATE AND THE WRITE, so the record on disk is the record that ships, and the reviewing
1303
+ // pass never addresses a line inside a section that is about to go.
1304
+ removeNextStepSections(run.runDir, merged.marks);
1305
+ const mv = validateMergedFindings(run.runDir, merged, plan);
1306
+ if (!mv.ok) throw new StageFailure("knockout-assess", `merged findings failed the lint: ${mv.failures.join("; ")}`, null);
1307
+ runLog(run.runDir, { event: "knockout-receipts", ...mv.receipts });
1308
+ atomicWrite(K.findings, JSON.stringify(merged, null, 2) + "\n");
1309
+ return merged;
1310
+ };
1037
1311
  // `let`, because the reviewing pass below returns a REWRITTEN record rather than editing this one:
1038
1312
  // the original has to survive intact as the thing that ships if the pass cannot finish cleanly.
1039
- let merged = { schema_version: 1, framework: null, batch: null, marks: [] };
1040
- const summaries = [];
1041
- for (let c = 0; c < chunks.length; c++) {
1042
- // READ prefers the new location and falls back to the pre-relocation one, so a run whose chunks
1043
- // were written before the move (or through the Bash bypass closed) resumes without paying for
1044
- // a re-dispatch. Nothing writes the legacy path any more — see stages-knockout.mjs.
1045
- const chunkPath = existsSync(K.assessChunk(c)) ? K.assessChunk(c) : K.assessChunkLegacy(c);
1046
- const part = JSON.parse(readFileSync(chunkPath, "utf8"));
1047
- if (c === 0) { merged.framework = part.framework ?? { source: ctx.framework.framework_key, ladder: ctx.framework.bands.map((b) => b.label) }; merged.batch = part.batch ?? null; }
1048
- if (typeof part.chunkSummary === "string" && part.chunkSummary.trim()) summaries.push(part.chunkSummary.trim());
1049
- merged.marks.push(...(part.marks ?? []));
1050
- }
1051
- if (!merged.batch) merged.batch = { productContext: plan.batch.productContext, standardCaveats: [] };
1052
- // the WHOLE-batch executive summary = the per-chunk summaries, composed in code (every chunk's
1053
- // validator required one, so no mark's chunk is silently absent — review 2026-07-17)
1054
- merged.batch.executiveSummary = summaries.join("\n\n");
1055
- // ── THE PENDING-REGISTER CAVEAT, CONDITIONAL SINCE RF-10 v3 ────────────────
1056
- //
1057
- // "Ratings reflect our common law assessment. Register analysis may adjust ratings in either
1058
- // direction." This is a CODE DEFAULT that fires when the model supplied no caveat of its own, and
1059
- // turned it from dormant into the thing that ships.
1060
- //
1061
- // BEFORE: knockout-assess calibration rule 4 ordered the seat to write that caveat, so the array
1062
- // arrived non-empty and this default almost never fired. THAT RULE IS RETIRED IN THIS SAME BRANCH —
1063
- // the seat is no longer told to write it — so the array now arrives EMPTY and this line injects the
1064
- // sentence unconditionally. Retiring the rule in the doctrine while leaving its default in the code
1065
- // did not remove the caveat; it made it fire on every run.
1066
- //
1067
- // And it is FALSE on the runs it now fires on. The rater is handed this run's fetched register
1068
- // filings and weighs them, so "register analysis may adjust ratings" describes work that already
1069
- // happened. RF-10 v3 (synthesis-rules.md): when register analysis ran AND surfaced live filings,
1070
- // drop the caveat and cite the register evidence directly; where it did not run, it stands and is
1071
- // the honest thing to say.
1072
- //
1073
- // THE DRIVER'S READ, off the run. A seat that could assert whether the register ran could waive its
1074
- // own caveat. Records present AND non-empty: a file that exists with nothing in it is a register
1075
- // that surfaced no filings, which is exactly the case the caveat is still true for.
1076
- // — ONE DERIVATION, shared with the verifier. This was a private copy, and the
1077
- // lint that checks the result did not have it: it required the caveat unconditionally while this
1078
- // injected it conditionally, so any run where the seat supplied its own caveats failed by
1079
- // construction. Two predicates that must agree forever is how they stop agreeing.
1080
- // — THE SAME DERIVATION THE LINT USES. This counted the array, blanks included, so
1081
- // `["", " "]` read as "the rater supplied two" here and as "supplied none" in the verifier. The lint
1082
- // could not see the disagreement because the survivor sentence below silenced it entirely.
1083
- if (raterCaveats(merged.batch.standardCaveats).length === 0 && !registerSurfacedFilings(K.registerRecords)) {
1084
- merged.batch.standardCaveats = ["Ratings reflect our common law assessment. Register analysis may adjust ratings in either direction."];
1085
- }
1086
- if (!Array.isArray(merged.batch.standardCaveats)) merged.batch.standardCaveats = [];
1087
- // ── the survivor sentence, in CODE ( fix 3) ────────────────────────────────────────────────────
1088
- //
1089
- // A mark this lane did not knock out is a SURVIVOR. It is not clear, and the document must not be
1090
- // readable as though it were: the knockout screens, the clearance enumerates, and the whole distance
1091
- // between them is the work that has not happened yet. Two runs on two matters delivered "Medium,
1092
- // complete" while missing almost every mark the lawyer named, because a screen cannot know what it
1093
- // did not look for — so the boundary of the screen is stated by the engine rather than left to the
1094
- // assessing model, which is the one party that cannot see it.
1095
- //
1096
- // APPENDED, never prepended: publish/knockout.mjs's email takes standardCaveats[0], so leading with
1097
- // this would silently replace the standing caveat in the requester's inbox.
1098
- const survivorNote = survivorBoundaryNote(policy);
1099
- if (!merged.batch.standardCaveats.some((c) => SURVIVOR_BOUNDARY_RE.test(String(c))))
1100
- merged.batch.standardCaveats.push(survivorNote);
1101
- // ── the skipped-capability sentence, in CODE, for the survivor sentence's own reason ──────
1102
- //
1103
- // The per-mark degrade above already reaches the client on every row. This is the RUN-level fact
1104
- // underneath twenty identical rows: not "research was unavailable for this name" twenty times, but
1105
- // one capability that never ran on this deployment. The assessing model cannot state it — it is
1106
- // told a mark is degraded, never why the whole screen is — so the engine states it, exactly as it
1107
- // states the survivor boundary two lines up.
1108
- //
1109
- // APPENDED, never prepended, for the same reason the survivor note is: publish/knockout.mjs's email
1110
- // takes standardCaveats[0], and leading with this would silently replace the standing caveat in the
1111
- // requester's inbox.
1112
- const skippedNote = sweep.skipped ? CAPABILITY_SKIPPED_NOTE[sweep.skipped] : null;
1113
- if (skippedNote && !merged.batch.standardCaveats.some((c) => String(c) === skippedNote))
1114
- merged.batch.standardCaveats.push(skippedNote);
1115
- // The merged gate now also validates the TYPED findings and receipts their citations, and it
1116
- // NORMALISES as it validates — each finding's band comes back in the frozen deck's own casing — so
1117
- // it runs BEFORE the artifact is written, not after. The counts are logged because a receipts pass
1118
- // over zero citations is a different fact from a receipts pass, and only the count can tell them
1119
- // apart afterwards.
1120
- // BEFORE THE GATE AND THE WRITE, so the record on disk is the record that ships, and the reviewing
1121
- // pass never addresses a line inside a section that is about to go.
1122
- removeNextStepSections(run.runDir, merged.marks);
1123
- const mv = validateMergedFindings(run.runDir, merged, plan);
1124
- if (!mv.ok) throw new StageFailure("knockout-assess", `merged findings failed the lint: ${mv.failures.join("; ")}`, null);
1125
- runLog(run.runDir, { event: "knockout-receipts", ...mv.receipts });
1126
- atomicWrite(K.findings, JSON.stringify(merged, null, 2) + "\n");
1313
+ let merged = composeRecord();
1127
1314
  // ── THE REVIEWING PASS, AFTER THE RECORD IS ON DISK AND BEFORE ANYTHING READS IT ─────────────────
1128
1315
  //
1129
1316
  // ORDER MATTERS THREE WAYS. The record is written FIRST so the stage's validator has something to
@@ -1137,7 +1324,7 @@ export async function knockoutInner(ctx, job, opts = {}) {
1137
1324
  // NO NEW STEP LABEL. `stepTotal` is derived from `koSteps()`, so adding one would renumber the
1138
1325
  // progress screen a client watches for a pass that takes a minute. It runs inside "Knockout
1139
1326
  // assessment", which is what it is part of.
1140
- merged = await knockoutReviewingPass({ ctx, run, K, merged, plan });
1327
+ merged = await knockoutReviewingPass({ ctx, run, K, merged, plan, chunks, composeRecord });
1141
1328
  try { writeFileSync(K.assessment, String(merged.batch.executiveSummary ?? "")); } catch { /* prose mirror, best-effort */ }
1142
1329
 
1143
1330
  // 4 — publish (report + workbook + meta + index)
@@ -1154,6 +1341,12 @@ export async function knockoutInner(ctx, job, opts = {}) {
1154
1341
  writeRunStatus(ctx, { stoppable: false });
1155
1342
  koStep(ctx, "Report & publish");
1156
1343
  const overall = worstBand(ctx.framework, merged.marks);
1344
+ // A set-aside filing the rating cites moves up with the carried ones, so the report has its row.
1345
+ try {
1346
+ const held = JSON.parse(readFileSync(K.registerRecords, "utf8"));
1347
+ const moved = withCitedFilings(held, merged);
1348
+ if (moved !== held) atomicWrite(K.registerRecords, JSON.stringify(moved, null, 2) + "\n");
1349
+ } catch { /* no record on this run, or none readable: publish says which */ }
1157
1350
  const published = await publishKnockout({
1158
1351
  runId, codename: run.codename, runDir: run.runDir,
1159
1352
  findings: merged, plan, framework: ctx.framework, overall,