clearotron 0.5.0-beta.8 → 0.5.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 (39) hide show
  1. package/.env.example +2 -1
  2. package/INSTALL.md +4 -3
  3. package/QUICKSTART.md +78 -0
  4. package/bin/onboard.mjs +9 -4
  5. package/build-info.json +2 -2
  6. package/docs/releases/0.5.0.md +77 -0
  7. package/driver/CHANGELOG.md +103 -0
  8. package/driver/contract-vocabulary.mjs +3 -3
  9. package/driver/corrections-delivered.mjs +7 -5
  10. package/driver/corrections-feedforward.mjs +89 -3
  11. package/driver/coverage-form.mjs +61 -2
  12. package/driver/degraded-parts.mjs +4 -0
  13. package/driver/engine/mcp/band-server.mjs +16 -6
  14. package/driver/engine/openai-agent.mjs +24 -1
  15. package/driver/engine/probe.mjs +64 -9
  16. package/driver/goods-evidence.mjs +33 -6
  17. package/driver/narrative-refutation-record.mjs +17 -2
  18. package/driver/package.json +1 -1
  19. package/driver/pipeline.mjs +373 -38
  20. package/driver/predelivery-lint.mjs +160 -10
  21. package/driver/publish/index.mjs +2 -2
  22. package/driver/record-fold.mjs +17 -0
  23. package/driver/record-goods.mjs +24 -8
  24. package/driver/register-plan.mjs +8 -3
  25. package/driver/repair-composers.mjs +61 -7
  26. package/driver/saved-register-pages.mjs +144 -0
  27. package/driver/stage-context.mjs +4 -0
  28. package/driver/suite-census.json +122 -14
  29. package/driver/terminal-clamp.mjs +21 -0
  30. package/driver/verify.mjs +6 -3
  31. package/mcp-server/CHANGELOG.md +12 -0
  32. package/mcp-server/package.json +1 -1
  33. package/package.json +2 -1
  34. package/portal-ui/package.json +1 -1
  35. package/providers/oauth-mcp-bridge/CHANGELOG.md +12 -0
  36. package/providers/oauth-mcp-bridge/package.json +1 -1
  37. package/providers/signa/src/core.js +18 -4
  38. package/scripts/e2e-first-time.mjs +10 -6
  39. package/scripts/release-duplicate-notes.mjs +5 -0
@@ -12,7 +12,7 @@ import { join, dirname, basename, resolve, relative } from "node:path"; // res
12
12
  import { driverDir, driverRel, ensureDriverDir } from "../shared/driver-dir.mjs";
13
13
  import { REVIEWER_OPEN_QUESTIONS_FILE } from "./reviewer-open-points.mjs"; // the run-record file the reviewer's open points go to, and the only thing that reads them now
14
14
  import { goodsOf } from "./queue-markers.mjs"; // — one reading of "does this job name goods", shared with the intake gate
15
- import { terminalClampDecision, orderClausesForLede, clientConditions, clauseForDefect, gapPositivelyClosed, verdictWithoutTheClosedGap, jointUnaccounted } from "./terminal-clamp.mjs"; // — deliver and clamp, never withhold
15
+ import { terminalClampDecision, orderClausesForLede, clientConditions, clauseForDefect, gapPositivelyClosed, verdictWithoutTheClosedGap, verdictWhenTheStepsAreWithdrawn, jointUnaccounted } from "./terminal-clamp.mjs"; // — deliver and clamp, never withhold
16
16
  import { recordSpan } from "./attributed-span.mjs"; // — driver work the decomposition can attribute
17
17
  import { fileURLToPath } from "node:url";
18
18
  import { runStage, correctionHint, gridLedgerNameFor, draftCarryEligible, toolWrittenArtifact, selectEngine, saidBackOnly } from "./gateway.mjs";
@@ -47,7 +47,7 @@ import { derivedStateOf, recordedDerivedState, replayOfDerivation } from "./deri
47
47
  import { parseVerdict, countCitedDefects, parseCorrectionKinds, parseCorrections, validators, findReviewerCoherenceFlags, lateReviewAgainst, VERDICT_RANK } from "./verify.mjs";
48
48
  import { readAcceptedFlags, nextRefutationSeq, readAcceptedReviewSince, REVIEW_EXCLUSIONS_FILE, listedExclusionPositions } from "./narrative-refutation-record.mjs"; // T3b — the typed flags, not the re-parse
49
49
  import { evidenceClaimViolations, evidenceClaimTable } from "./evidence-claim-invariant.mjs"; //
50
- import { buildCorrectionsApplied, correctionsWorklist, correctionsAppliedTable, correctionScope, flaggedPositions, scopeDrift, unresolvedFlags, reportLines, linesOf, REPORT_LINE_KEY, REPORT_LINE_LABEL } from "./corrections-feedforward.mjs";
50
+ import { buildCorrectionsApplied, correctionsWorklist, correctionsAppliedTable, correctionScope, flaggedPositions, scopeDrift, unresolvedFlags, reportLines, linesOf, REPORT_LINE_KEY, REPORT_LINE_LABEL, answersLeftBehind } from "./corrections-feedforward.mjs";
51
51
  import { correctionTargets, deliveredOutcomes } from "./corrections-delivered.mjs"; // whether each correction reached the record the report was built from
52
52
  import { parseCoverageLedgerJson, parseCoverageLedgerFull, deriveCoverageStatus, classTokensFromScopeText, coerceToolAbsenceDeferred, applyTaintDeferred, decideRegisterGap, splitDeferredByCloseability, heldForNothingToSend, formRowUnitKey, coverageLedgerTableRows, coverageUnitLabel, NON_MATERIAL_AXES, COVERAGE_STATUSES } from "./coverage-ledger.mjs";
53
53
  import { receiptSettled, readEnvelopeDecision, settleReceipt, settledDeferralsSection, readStickyGaps } from "./envelope-settle.mjs";
@@ -80,7 +80,7 @@ import { classifyGroundsNote } from "./grounds-grammar.mjs"; // — a charged
80
80
  // — the register coverage form: the driver writes it before the digest dispatches, renders the
81
81
  // `## Coverage ledger` table and the machine ledger FROM it after the pass, and unions it across passes.
82
82
  import { documentCoverage, renderDocumentCoverageSection, spliceDocumentCoverage } from "./document-coverage.mjs"; //
83
- import { buildCoverageAbsenceForm, coverageAbsenceGaps, coverageFormAbsence, coverageFormBrief, renderCoverageAbsenceSection, renderCoverageLedgerSection, spliceCoverageLedger, renderCoverageLedgerJsonFromForm, unitLabel, buildCoverageForm, formLedgerRows } from "./coverage-form.mjs";
83
+ import { buildCoverageAbsenceForm, coverageAbsenceGaps, coverageFormAbsence, coverageFormBrief, renderCoverageAbsenceSection, renderCoverageLedgerSection, spliceCoverageLedger, renderCoverageLedgerJsonFromForm, unitLabel, buildCoverageForm, formLedgerRows, isLayerRow, nationalRegistersNotSearched, nationalRegistersNote, orderFormName } from "./coverage-form.mjs";
84
84
  import { unionCoverageForm } from "./coverage-union.mjs";
85
85
  import { armCoverageForm, coverageFormInput, coverageFormPaths, coverageFormStamp, readCoverageForm, readCoverageFormInput, waitingFamilyStates, writeCoverageForm } from "./coverage-form-io.mjs";
86
86
  import { releasedFamilyQids, readWithheldFamilies } from "./withheld-families.mjs"; // the waiting families the reading turn released join as dictated entries
@@ -162,7 +162,7 @@ import { RECORD_CARRY_SCHEMA_VERSION, traceRecordCarry, parseStageOutcomes, reco
162
162
  import { reconcileSurfaceDuty, surfaceDutyNote } from "./surface-duty.mjs"; // item 3 — silence at the findings surface, read off the rows above
163
163
  import { DISCARD_LEDGER_NAME, seamRows, appendDiscardRows, foldDiscardLedger } from "./record-discard.mjs";
164
164
  import { citedFindingNumbers } from "./finding-citations.mjs"; // the findings an exclusion's ground cites
165
- import { deriveGoodsEvidence, recordGoodsEvidence, heldRecordProvenance, heldBodiesOf, recordFetchOutcomes, readRunCallRows, recordReads, linesRead, registerCallAccount, readGoodsEvidence, GOODS_EVIDENCE_FILE, goodsFromLabel } from "./goods-evidence.mjs"; // — what each band record's goods rest on, written beside the shape and served by no band tool
165
+ import { deriveGoodsEvidence, recordGoodsEvidence, heldRecordProvenance, heldBodiesOf, recordFetchOutcomes, readRunCallRows, recordReads, linesRead, registerCallAccount, readGoodsEvidence, readGoodsEvidenceAsWritten, GOODS_EVIDENCE_FILE, GOODS_EVIDENCE_AS_WRITTEN_FILE, goodsFromLabel } from "./goods-evidence.mjs"; // — what each band record's goods rest on, written beside the shape and served by no band tool
166
166
  import { readDeclinations, declinationCallPaths } from "./declination-tool.mjs"; // — synthesis's own stated declines
167
167
  import { seamReasonFor } from "./declination-call.mjs"; // — the per-record judgment, pure and separately tested
168
168
  import { traceCommonLawCarry, commonLawCarryEvent, mintCommonLawCarryDoubts, reconciliationVerdict, planVsExecutedChannels, CL_STAGES } from "./commonlaw-carry.mjs";
@@ -183,7 +183,7 @@ import { beginAnswerMemory, endAnswerMemory } from "../providers/_shared/answer-
183
183
  import { findScreenGateViolations, findScreenGateParseGaps, screenGateZeroCause, screenGateEvidence, policedDropUris } from "./screen-gate.mjs";
184
184
  import { emptyQueue, coerceQueue, mintItem, pendingItems, markFlushed, receiptKeyFor,
185
185
  buildFlushFollowup, runPostFlushGateRepair } from "./digest-queue.mjs"; // (t1cd) — the digest-trigger funnel
186
- import { foldFindingsFile, foldAfterSave, openPass, modelRecordPath, snapshotFold, restoreFold, readFold, keptModelOrdinal } from "./record-fold.mjs"; // the folded record from the delivery seam on
186
+ import { foldFindingsFile, foldAfterSave, openPass, modelRecordPath, snapshotFold, restoreFold, readFold, keptModelOrdinal, citingModelOrdinal, FOLD_FILE } from "./record-fold.mjs"; // the folded record from the delivery seam on
187
187
  import { writeStamp, stageStaleness, restamp, restampStage, staleOnPath, reconcileStamps, shaOf, readStamp } from "./stage-freshness.mjs";
188
188
  import { locateReportFaults, reportPartsOf, overviewCitationFault, writersCitationFaults } from "./repair-targets.mjs"; // a delivery-check fault reaches the part of the report that holds it
189
189
  import { parseManifestVariants, variantsParseFailure, findCoverageLimitedCells, partitionClosableCells, findSimilarListingSignals,
@@ -194,7 +194,7 @@ import { recordRunConsumption } from "./consumption-ledger.mjs";
194
194
  import { quoteForJob, reconcileTurnaround } from "./run-quote.mjs";
195
195
  import { assembleRunRecords, recordBodyHasContent, readRecordArtifacts, findRegistryArithmeticIssues, findRegistryViolations, applyRegistryCorrections, extractEnforcerSignals, collectOppositionDeadlines, normalizeRecordUri } from "./registry-fidelity.mjs";
196
196
  import { recallReceiptForOwnCompany } from "./recall-receipt.mjs"; // a past run's recall receipt, as one company's audit may list it
197
- import { runLint, flagLines, properNameCandidates, OVERVIEW_CITATION_ID } from "./predelivery-lint.mjs";
197
+ import { runLint, flagLines, properNameCandidates, OVERVIEW_CITATION_ID, goodsRepairLine } from "./predelivery-lint.mjs";
198
198
  import { parsePlacementsJson } from "./placement-model.mjs"; // B2 — the structured tier mirror; the lint reads it only to flag an EMPTY one
199
199
  import { readAnchors } from "./anchor-reader.mjs";
200
200
  import { findEngagementReceipts } from "./engagement-receipt.mjs";
@@ -1259,6 +1259,19 @@ function goodsEvidenceDocFor(ctx, band, goods = null) {
1259
1259
  return doc;
1260
1260
  }
1261
1261
 
1262
+ // THE RECORDS A DELIVERY REPAIR WAS HANDED THE WHOLE GOODS TEXT FOR (predelivery-lint.mjs, goodsHeldWholeChecks), kept
1263
+ // beside the run so the check after that repair, and a resume, do not name them again. A missing or unreadable file is
1264
+ // an empty set: the check then names them, which costs a repair and never hides a finding.
1265
+ const GOODS_HANDED_FILE = "goods-held-whole-handed.json";
1266
+ function readGoodsHanded(runDir) {
1267
+ try { return new Set(JSON.parse(readFileSync(driverDir(runDir, GOODS_HANDED_FILE), "utf8"))?.records ?? []); } catch { return new Set(); }
1268
+ }
1269
+ function recordGoodsHanded(runDir, uris) {
1270
+ const all = new Set([...readGoodsHanded(runDir), ...uris]);
1271
+ ensureDriverDir(runDir);
1272
+ atomicWrite(driverDir(runDir, GOODS_HANDED_FILE), JSON.stringify({ records: [...all].sort() }, null, 2) + "\n");
1273
+ }
1274
+
1262
1275
  function recordGoodsEvidenceFor(ctx, band, derived = null) {
1263
1276
  const P = ctx.paths;
1264
1277
  try {
@@ -3563,7 +3576,7 @@ export function withGoodsFrom(ctx, P, rows, read = null) { // @internal — dr
3563
3576
  const evidence = read ?? goodsEvidenceOfDrops(P, runPrefix, uris);
3564
3577
  return rows.map((r) => {
3565
3578
  const e = r?.kind !== "page" && r?.uri ? evidence.get(r.uri) : null;
3566
- return e ? { ...r, goods_from: goodsFromLabel({ state: e.goods, source: e.source }) } : r;
3579
+ return e ? { ...r, goods_from: goodsFromLabel({ state: e.goods, source: e.source, question: e.question }) } : r;
3567
3580
  });
3568
3581
  } catch (e) { return unlabelled(e?.message ?? e); }
3569
3582
  }
@@ -5654,11 +5667,48 @@ function sweepStrayArtifacts(ctx, stageName) {
5654
5667
  } catch { /* a hygiene sweep must never be able to affect a run */ }
5655
5668
  }
5656
5669
 
5670
+ // ── THE GOODS EVIDENCE AS THE WRITER HAD IT (goods-evidence.mjs GOODS_EVIDENCE_AS_WRITTEN_FILE) ─────────────────────
5671
+ //
5672
+ // The delivery check compares a finding that says its goods are cut with the goods evidence the writer was given. That
5673
+ // evidence is derived again with every band merge, and the first merge of a resumed pass reads the record bodies the
5674
+ // run holds by then: a record the writer had as a cut search answer read as an official record, and the check found no
5675
+ // outcome for a record it had handed to the repair, or no longer found a claim the repair left standing.
5676
+ //
5677
+ // So the evidence a cold dispatch of the writer is given is kept, as it stood when the dispatch began, once the stage
5678
+ // has returned a record. A writer that skipped wrote nothing new and leaves the copy as it was. A followup, the delivery
5679
+ // check's own repair among them, corrects a record written on the copy already kept, so it leaves the copy too: the
5680
+ // check after that repair compares the corrected findings with what they were first written on. A writer dispatched
5681
+ // with no evidence leaves no copy, so none can describe an earlier writer.
5682
+ //
5683
+ // The text of the evidence a cold writer dispatch is given, null where it is given none, and undefined where no copy is
5684
+ // to be kept. Never throws.
5685
+ export function goodsEvidenceForTheWriter(name, ctx, opts = {}) { // @internal — driven by its test
5686
+ if (name !== "synthesis" || opts.followup || !ctx?.paths?.runDir) return undefined;
5687
+ try { return readFileSync(driverDir(ctx.paths.runDir, GOODS_EVIDENCE_FILE), "utf8"); } catch { return null; }
5688
+ }
5689
+ /** Keep the evidence `goodsEvidenceForTheWriter` read, once the writer's stage returned a record it wrote. Never throws. */
5690
+ export function keepGoodsEvidenceAsWritten(ctx, r, evidence) { // @internal — driven by its test
5691
+ if (evidence === undefined || !r?.ok || r.skipped) return;
5692
+ const at = driverDir(ctx.paths.runDir, GOODS_EVIDENCE_AS_WRITTEN_FILE);
5693
+ try {
5694
+ if (evidence == null) rmSync(at, { force: true });
5695
+ else { ensureDriverDir(ctx.paths.runDir); atomicWrite(at, evidence); }
5696
+ } catch (e) {
5697
+ note(`[synthesis] the goods evidence the writer was given could not be kept (${String(e?.message ?? e).slice(0, 100)}) — the delivery check reads the evidence as it stands`);
5698
+ }
5699
+ }
5700
+
5657
5701
  async function stage(name, ctx, opts = {}) {
5702
+ const writersEvidence = goodsEvidenceForTheWriter(name, ctx, opts);
5658
5703
  let wedgeCycles = 0;
5659
5704
  for (;;) {
5660
5705
  const r = await stageWithChain(name, ctx, opts);
5661
- if (r.ok || r.fail !== "lane_wedge" || wedgeCycles >= LANE_WEDGE_CHAIN_RETRIES) { sweepStrayArtifacts(ctx, name); await afterLateSynthesisSave(name, ctx, r); return r; }
5706
+ if (r.ok || r.fail !== "lane_wedge" || wedgeCycles >= LANE_WEDGE_CHAIN_RETRIES) {
5707
+ sweepStrayArtifacts(ctx, name);
5708
+ keepGoodsEvidenceAsWritten(ctx, r, writersEvidence);
5709
+ await afterLateSynthesisSave(name, ctx, r);
5710
+ return r;
5711
+ }
5662
5712
  wedgeCycles++;
5663
5713
  note(`[${name}] command-lane wedge — the stage timed out with zero progress (saturated lane). Waiting ${Math.round(LANE_WEDGE_BACKOFF_MS / 1000)}s for it to clear, then re-dispatching (${wedgeCycles}/${LANE_WEDGE_CHAIN_RETRIES}); full per-attempt timeouts preserved.`);
5664
5714
  try { runLog(ctx.paths.runDir, { event: "lane-wedge-retry", stage: name + (ctx.axis ? `:${ctx.axis}` : ""), cycle: wedgeCycles, max: LANE_WEDGE_CHAIN_RETRIES }); } catch { /* telemetry best-effort */ }
@@ -7237,6 +7287,46 @@ export function withdrawByToken(reasons = [], clauses = [], guard = new Set(), t
7237
7287
  return out;
7238
7288
  }
7239
7289
 
7290
+ /**
7291
+ * THE CONDITIONS THE RECORD'S ACTIONS STATE, AS THE RECORD NOW STANDS. A repair can rewrite, withdraw or add a forward
7292
+ * legal step, and the list follows it: the entries the record's actions put there (`fromRecord`, by reason) are
7293
+ * replaced by the steps it states now (`now`, each `{ reason, clause }`, in the record's order), at the place the first
7294
+ * of them stood, or at the end where none stood. Every other entry keeps its place, and a step whose reason another
7295
+ * entry carries is left to that entry. Returns the index-aligned arrays as they now stand, the reasons the record now
7296
+ * holds there (`held`), and which reasons went and came. PURE.
7297
+ */
7298
+ export function conditionsFollowingTheRecord({ reasons = [], clauses = [], fromRecord = new Set(), now = [] } = {}) { // @internal — driven by its test
7299
+ const kept = [];
7300
+ let at = -1;
7301
+ for (const [i, r] of reasons.entries()) {
7302
+ if (fromRecord.has(r)) { if (at < 0) at = kept.length; continue; }
7303
+ kept.push([r, clauses[i]]);
7304
+ }
7305
+ const others = new Set(kept.map(([r]) => r));
7306
+ const placed = [];
7307
+ for (const n of now) {
7308
+ if (others.has(n.reason) || placed.some(([r]) => r === n.reason)) continue;
7309
+ placed.push([n.reason, n.clause ?? n.reason]);
7310
+ }
7311
+ const pos = at < 0 ? kept.length : at;
7312
+ const rows = [...kept.slice(0, pos), ...placed, ...kept.slice(pos)];
7313
+ const before = reasons.filter((r) => fromRecord.has(r));
7314
+ const clauseWas = new Map(reasons.map((r, i) => [r, clauses[i]]));
7315
+ const held = placed.map(([r]) => r);
7316
+ return { reasons: rows.map(([r]) => r), clauses: rows.map(([, c]) => c), held: new Set(held),
7317
+ withdrawn: before.filter((r) => !held.includes(r)), added: held.filter((r) => !before.includes(r)),
7318
+ restated: placed.filter(([r, c]) => before.includes(r) && clauseWas.get(r) !== c).map(([r]) => r) };
7319
+ }
7320
+
7321
+ /**
7322
+ * IS THE RECORD'S ACTIONS REGISTER A LIST? The one positive sign that a record holding no forward legal step has
7323
+ * withdrawn them, rather than lost them: an unreadable record, a missing register and one that is not a list are not a
7324
+ * withdrawal. Entries dropped as unreadable are the caller's to weigh. PURE.
7325
+ */
7326
+ export function actionsRegisterListed(raw) { // @internal — driven by its test
7327
+ try { return Array.isArray(JSON.parse(String(raw ?? ""))?.actions); } catch { return false; }
7328
+ }
7329
+
7240
7330
  /**
7241
7331
  * WHAT A REPAIR IN THE DELIVERY CHECK LEFT STALE, AND WHAT OF IT IS QUEUED. A stage is this repair's when it is stale now
7242
7332
  * and was not before the repair, or is stale on an input that has moved since; a stage stale before for the same reasons
@@ -7676,7 +7766,7 @@ async function enforceCorrectionsReachFindings(ctx, P, pre, resume) {
7676
7766
  const sha = createHash("sha256").update(raw).digest("hex");
7677
7767
  return { stale: named.length > 0 && sha === (pre.model?.sha ?? pre.sha) && !(corrections && corrections.applied), sha };
7678
7768
  };
7679
- if (!readState().stale) return;
7769
+ if (!readState().stale) return answerFollowsCorrection(ctx, P, pre, resume);
7680
7770
  note(`[corrections] findings.json unchanged after the corrective pass (review names: ${named.join(", ")}) — demanding the re-emit`);
7681
7771
  await stage("synthesis", ctx, {
7682
7772
  force: true, sessionKey: resume.synthesisKey, model: resume.synthesisModel, thinking: resume.synthesisThinking,
@@ -7696,6 +7786,33 @@ async function enforceCorrectionsReachFindings(ctx, P, pre, resume) {
7696
7786
  }
7697
7787
  }
7698
7788
 
7789
+ // THE ANSWERS FOLLOW THE FINDINGS THEY NAME, asked once, as the gate's one repair. A correction that moved findings an
7790
+ // answer citing findings may depend on (`answersLeftBehind`) is handed those findings and the answers that may miss them.
7791
+ // The writer updates the answers that depend on them or says why not in the corrections note; nothing is forced. Run
7792
+ // only where the findings did reach the record: where they did not, the re-emit above is the one repair, and it may
7793
+ // update the answers in the same PATCH. What remains afterwards is recorded, not judged; the recheck reads the answers.
7794
+ async function answerFollowsCorrection(ctx, P, pre, resume) {
7795
+ const { run } = ctx;
7796
+ const leftBehind = () => {
7797
+ try {
7798
+ return answersLeftBehind(JSON.parse(pre.model?.raw ?? pre.raw), JSON.parse(readFileSync(modelRecordPath(run.runDir, P.findings), "utf8")),
7799
+ ctx.framework?.bands);
7800
+ } catch { return []; } // an unreadable record is the ladder's business, not this check's
7801
+ };
7802
+ const answers = leftBehind();
7803
+ if (!answers.length) return;
7804
+ runLog(run.runDir, { event: "corrective-answers-left-behind", answers });
7805
+ note(`[corrections] ${answers.length} answer(s) in four_answers may miss findings the correction moved (${answers.map((a) => a.answer).join(", ")}) — asking once`);
7806
+ await stage("synthesis", ctx, {
7807
+ force: true, sessionKey: resume.synthesisKey, model: resume.synthesisModel, thinking: resume.synthesisThinking,
7808
+ trigger: "corrective-answers",
7809
+ followup: repairFollowup("synthesis:corrective-answers", { findings: modelRecordPath(run.runDir, P.findings), answers }) + stageCharter("synthesis", ctx.depth, ctx.framework),
7810
+ });
7811
+ const still = leftBehind();
7812
+ runLog(run.runDir, { event: "corrective-answers-after", answers: still });
7813
+ if (still.length) note(`[corrections] ${still.map((a) => a.answer).join(", ")} still name(s) the findings as before — recorded; any reason the writer gave is in the corrections note, and the recheck reads the answers`);
7814
+ }
7815
+
7699
7816
  // (T3a, ruling 2026-08-26 — "Deliver always, with open points printed. The refusal on a blocking
7700
7817
  // review goes." That REVERSES T3, which had retired "delivered-with-open-questions" and deleted
7701
7818
  // the extra this comment used to be a tombstone for. Both decisions are the owner's; this is the standing
@@ -8478,8 +8595,34 @@ export function coverageRowAreaLabel(axis, unit) { // @internal
8478
8595
  return coverageRowAreaFrom(axis, unit, labelled, "(all of it)");
8479
8596
  }
8480
8597
 
8481
- export function coverageJudgmentRows(ledgerRows, planExecution, plan = null) { // @internal
8598
+ // A LAYER ROW NAMES EVERY REGISTER IT LEFT, FROM ITS RECEIPT. The machine ledger keeps a row's axis, status
8599
+ // and reason, not its receipt, so the coverage form's layer row is found again by those three: the ledger is
8600
+ // rendered from the form, and they are the form row's own. A match must be one form row to one ledger row; any
8601
+ // other count leaves the row as it was. Its label is the territory's: the unit has no scope, so the axis's label
8602
+ // would say the whole main sweep stood open.
8603
+ const normReason = (s) => String(s ?? "").replace(/\s+/g, " ").trim();
8604
+ function layerRowNotes(ledgerRows, formRows) {
8605
+ const keyOf = (r) => `${String(r?.axis ?? "").trim().toLowerCase()}\u0000${String(r?.status ?? "").trim().toLowerCase()}\u0000${normReason(r?.reason)}`;
8606
+ const ledgerCount = new Map();
8607
+ for (const r of ledgerRows ?? []) ledgerCount.set(keyOf(r), (ledgerCount.get(keyOf(r)) ?? 0) + 1);
8608
+ const byKey = new Map();
8609
+ for (const f of (formRows ?? []).filter(isLayerRow)) {
8610
+ const k = keyOf(f);
8611
+ byKey.set(k, byKey.has(k) ? null : f);
8612
+ }
8613
+ const notes = new Map();
8614
+ for (const [k, f] of byKey) {
8615
+ if (!f || ledgerCount.get(k) !== 1) continue;
8616
+ const note = nationalRegistersNote(nationalRegistersNotSearched(f.receipt_reason));
8617
+ const territory = orderFormName(String(f.unit ?? "").split(" — ")[0]);
8618
+ if (note && territory) notes.set(k, { note, areaLabel: `${territory}: national registers` });
8619
+ }
8620
+ return { keyOf, notes };
8621
+ }
8622
+
8623
+ export function coverageJudgmentRows(ledgerRows, planExecution, plan = null, formRows = null) { // @internal
8482
8624
  const open = [];
8625
+ const layers = layerRowNotes(ledgerRows, formRows);
8483
8626
  for (const r of ledgerRows ?? []) {
8484
8627
  // `withheld-by-judgment` joins `confirmed-clean` in NOT reaching the reader, and for the opposite
8485
8628
  // reason. A clean row has nothing to disclose. A withheld one has something to say, and it is
@@ -8491,8 +8634,10 @@ export function coverageJudgmentRows(ledgerRows, planExecution, plan = null) {
8491
8634
  if (!r || status === "confirmed-clean" || status === "withheld-by-judgment") continue;
8492
8635
  const reason = String(r.reason ?? "").replace(/\s+/g, " ").trim().slice(0, 160);
8493
8636
  const axis = String(r.axis ?? "").toLowerCase();
8494
- open.push({ axis, area: coverageRowArea(axis, r.unit), areaLabel: coverageRowAreaLabel(axis, r.unit),
8495
- note: `${r.status}${reason ? ` — ${reason}` : ""}`, qids: [] });
8637
+ const layer = layers.notes.get(layers.keyOf(r));
8638
+ open.push({ axis, area: coverageRowArea(axis, r.unit),
8639
+ areaLabel: layer ? layer.areaLabel : coverageRowAreaLabel(axis, r.unit),
8640
+ note: `${r.status}${layer ? ` — ${layer.note}` : reason ? ` — ${reason}` : ""}`, qids: [] });
8496
8641
  }
8497
8642
  const skeleton = Array.isArray(planExecution?.skeleton) ? planExecution.skeleton : null;
8498
8643
  const axisOf = new Map();
@@ -8524,7 +8669,8 @@ export function stampCoverageJudgmentRows(P, runDir, note, ctx) { // @internal
8524
8669
  runLog(runDir, { event: "coverage-judgment-rows", judgment: false, reason: "synthesis emitted no coverage_judgment — none is invented here" });
8525
8670
  return;
8526
8671
  }
8527
- const rows = coverageJudgmentRows(loadCoverageLedger(runDir).rows, readPlanExecution(ctx), ctx?.registerPlan ?? null);
8672
+ const rows = coverageJudgmentRows(loadCoverageLedger(runDir).rows, readPlanExecution(ctx), ctx?.registerPlan ?? null,
8673
+ readCoverageForm(runDir).rows);
8528
8674
  const discarded = Array.isArray(cj.rows) ? cj.rows.length : 0;
8529
8675
  const next = { ...doc, coverage_judgment: { ...cj } };
8530
8676
  if (rows.length) next.coverage_judgment.rows = rows;
@@ -8543,7 +8689,7 @@ export function stampCoverageJudgmentRows(P, runDir, note, ctx) { // @internal
8543
8689
  }
8544
8690
  }
8545
8691
 
8546
- function injectDeferralCoverage(P, runDir, note) {
8692
+ export function injectDeferralCoverage(P, runDir, note) { // @internal — exported so a second pass is testable without a run
8547
8693
  try {
8548
8694
  const rp = driverDir(runDir, "frame-reopen.json");
8549
8695
  if (!existsSync(rp) || !existsSync(P.findings)) return;
@@ -8554,14 +8700,29 @@ function injectDeferralCoverage(P, runDir, note) {
8554
8700
  // rows — the reader-visible disclosure is the whole point of "can't close → disclose".
8555
8701
  if (!Array.isArray(doc.coverage)) doc.coverage = [];
8556
8702
  const normTxt = (s) => String(s ?? "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
8557
- const covText = normTxt(doc.coverage.map((c) => `${c.area} ${c.note ?? ""}`).join(" "));
8703
+ // A row may stand in for this one only as the report page lets it (`dedupeFollowUps`, publish/render.mjs): the
8704
+ // driver's own row, or the writer's row restating the gap. A searched-clean row reports the opposite, and an
8705
+ // axis-labelled one ("Register / …") is a plan unit that may only share the words.
8706
+ const standsIn = (c) => String(c.area ?? "").startsWith("Follow-up / ")
8707
+ || (c.state !== "confirmed-clean" && !/\s\/\s/.test(String(c.area ?? "")));
8708
+ const wordsOf = (c) => new Set(normTxt(`${c.area} ${c.note ?? ""}`).split(" "));
8709
+ const rows = doc.coverage.filter(standsIn).map(wordsOf);
8558
8710
  let added = 0;
8559
8711
  for (const d of deferrals) {
8560
8712
  const directive = String(d?.directive ?? "").trim();
8561
8713
  if (!directive) continue;
8562
- const slice = normTxt(directive).split(" ").filter((w) => w.length >= 4).slice(0, 4).join(" ");
8563
- if (slice && covText.includes(slice)) continue; // synthesis already weighed it in
8564
- doc.coverage.push(deferralCoverageRow(directive, d?.reason)); // — word-boundary heading, full directive in the note
8714
+ // THE WORDS ARE THE ONES A ROW CARRIES, AND ONE ROW CARRIES ALL OF THEM. A directive is minted with its axis prefix
8715
+ // ("source:…"), and every row, this function's own included, prints it through `plainDirective`. This looked
8716
+ // for the raw directive's first four long words as one phrase across the whole coverage: the prefix was the
8717
+ // first of them, and a short word between two others ("eu", "and") broke the phrase anyway, so no row matched,
8718
+ // not even the row this function had just added. Each seam pass added it again: twice over in a record, and
8719
+ // back after a save that removed it. Measured on two test runs, 2026-11-03: 9 of 9 directives carried the
8720
+ // prefix, and 4 of one run's 7 a short word between their long ones.
8721
+ const want = normTxt(plainDirective(directive)).split(" ").filter((w) => w.length >= 4).slice(0, 4);
8722
+ if (want.length && rows.some((ws) => want.every((w) => ws.has(w)))) continue; // synthesis already weighed it in
8723
+ const row = deferralCoverageRow(directive, d?.reason); // — word-boundary heading, full directive in the note
8724
+ doc.coverage.push(row);
8725
+ rows.push(wordsOf(row));
8565
8726
  added++;
8566
8727
  }
8567
8728
  if (!added) return;
@@ -8884,7 +9045,8 @@ function goodsEvidenceOfDrops(P, runPrefix, uris, gateFetched = null) {
8884
9045
  }
8885
9046
  for (const uri of uris) {
8886
9047
  const e = recordGoodsEvidence(rowOf.get(normalizeRecordUri(uri)) ?? { record_id: uri }, { goods, held, fetches });
8887
- out.set(uri, { goods: e.state, source: e.source });
9048
+ // A register page the research saved is named by the question that saved it, which the write-up's label carries.
9049
+ out.set(uri, { goods: e.state, source: e.source, ...(e.question != null ? { question: e.question } : {}) });
8888
9050
  }
8889
9051
  return out;
8890
9052
  }
@@ -9521,6 +9683,9 @@ export function buildReasonedNegativesSection(findings) { // @internal
9521
9683
  // built from and writes the outcome beside it (corrections-delivered.mjs). The last assembly's answer stands.
9522
9684
  // corrections-applied.json, which the open points and the verdict re-check read, is not touched.
9523
9685
  export const CORRECTIONS_DELIVERED_FILE = "corrections-delivered.json";
9686
+ // Whether the recheck after the correction saved an accepted review (`read`) or not (`unread`, with why), with the
9687
+ // entry verdict and the verdict that stood. An unread recheck is a correction nobody verified.
9688
+ export const CORRECTIVE_RECHECK_FILE = "corrective-recheck.json";
9524
9689
 
9525
9690
  /** Keep the basis at the corrective pass, from the two records the applied table was built from. Throws on a write failure; the caller is never-kill. */
9526
9691
  export function recordCorrectionsBasis(runDir, rows, preDoc, postDoc) { // @internal
@@ -10229,7 +10394,9 @@ async function pipelineInner(job, opts = {}) {
10229
10394
  let engineTurnStartedMs = null, engineTurnEndedMs = null;
10230
10395
  if (!opts.recordFetcher && !koSelector) {
10231
10396
  engineTurnStartedMs = Date.now();
10232
- engineTurn = await preflightEngineTurn();
10397
+ // `opts.engineTurnWait` stands in for the door's wait before it checks a locked sign-in refresh again,
10398
+ // in tests; a run passes none and waits.
10399
+ engineTurn = await preflightEngineTurn({ wait: opts.engineTurnWait });
10233
10400
  engineTurnEndedMs = Date.now();
10234
10401
  if (engineTurn.warning) console.error(engineTurn.warning);
10235
10402
  }
@@ -10374,11 +10541,13 @@ async function pipelineInner(job, opts = {}) {
10374
10541
  // — the engine-turn door's verdict, beside the run it let through. A refusal never reaches here (it
10375
10542
  // throws before any of this exists), so this row answers the two questions that survive: did the door
10376
10543
  // run at all on this lane, and — when it failed open on weather — WHAT it decided to let past. Without
10377
- // it a proceeded-past-weather run is indistinguishable on the record from one that probed clean.
10544
+ // it a proceeded-past-weather run is indistinguishable on the record from one that probed clean. A door
10545
+ // that checked twice, because the first check met a locked sign-in refresh, says so beside the second.
10378
10546
  try {
10379
10547
  if (engineTurn) runLog(run.runDir, { event: "engine-turn-probe", ok: engineTurn.ok === true,
10380
10548
  engine: engineTurn.engine ?? null, mode: engineTurn.mode ?? null, basis: engineTurn.basis ?? null,
10381
- lane: engineTurn.ok === true ? "ok" : "weather", detail: engineTurn.detail ?? null });
10549
+ lane: engineTurn.ok === true ? "ok" : "weather", detail: engineTurn.detail ?? null,
10550
+ ...(engineTurn.recheckedAfter ? { recheckedAfter: engineTurn.recheckedAfter } : {}) });
10382
10551
  // — and the same probe as a SPAN the wall decomposition can attribute. Same measurement, second
10383
10552
  // reader: the row above goes to run.jsonl, which that instrument skips by name.
10384
10553
  if (engineTurn) recordSpan(run.runDir, "engine-turn", { startedMs: engineTurnStartedMs, endedMs: engineTurnEndedMs },
@@ -14350,8 +14519,13 @@ async function pipelineInner(job, opts = {}) {
14350
14519
  // passes below run on a record that exists, and their failures are theirs. A failure named here, once its recovery
14351
14520
  // is spent, is recorded as the assessment not completed and delivered without it (the run-level catch), never
14352
14521
  // ended on.
14522
+ // The goods evidence this writer is given is kept as written by its stage (around `stage`), and kept here too where
14523
+ // the record comes from the salvage after a failed dispatch: a re-emit, or the record taken with its foreign links
14524
+ // blanked, completes the record that dispatch wrote on that evidence.
14525
+ const writersEvidence = goodsEvidenceForTheWriter("synthesis", ctx);
14353
14526
  const synth = await asPartNotCompleted("assessment", async () =>
14354
14527
  quarantineSynth(await stage("synthesis", ctx, synthExtra ? { extra: synthExtra } : {}), ctx, "synthesis")); // A3: last-resort quarantine instead of must(); A4: one targeted re-emit inside
14528
+ keepGoodsEvidenceAsWritten(ctx, synth, writersEvidence);
14355
14529
  recordSynthesisSeam(ctx, synth); // half one — which surfaced records this pass delivered, and which it did not
14356
14530
  // The corrective re-synthesis is dispatched on the WINNING attempt's key AND model/thinking. A followup's first
14357
14531
  // attempt starts fresh, and it never resumes the synthesis session (no engine resumes by key); but if synthesis
@@ -14789,6 +14963,8 @@ async function pipelineInner(job, opts = {}) {
14789
14963
  const planAuditCarry = (ctx.registerPlan && existsSync(P.planExecution))
14790
14964
  ? `Your rewritten review MUST again contain the section titled exactly "PLAN-EXECUTION CHECK" — carry your prior section forward, updated for the corrected narrative/findings (the deterministic validator requires it whenever the plan-execution receipt exists).`
14791
14965
  : "";
14966
+ const recheckSeq0 = nextRefutationSeq(run.runDir);
14967
+ const reviewShaBefore = shaOf(P.seniorEyeReview);
14792
14968
  const rc = firstRef.key
14793
14969
  ? await stage("narrative-refutation", ctx, {
14794
14970
  force: true, sessionKey: firstRef.key, model: firstRef.model, thinking: firstRef.thinking, trigger: "verdict-recheck",
@@ -14801,9 +14977,31 @@ async function pipelineInner(job, opts = {}) {
14801
14977
  }),
14802
14978
  })
14803
14979
  : await stage("narrative-refutation", ctx, { force: true, model: firstRef.model, thinking: firstRef.thinking, trigger: "verdict-recheck", ...(planAuditExtra(ctx) ? { extra: planAuditExtra(ctx) } : {}) });
14804
- verdict = rc.ok ? (parseVerdict(readFileSync(P.seniorEyeReview, "utf8")) ?? entryVerdict) : entryVerdict;
14805
- correctiveRecheckOk = rc.ok === true;
14806
- runLog(run.runDir, { event: "verdict-2", verdict });
14980
+ // A RECHECK COUNTS ONLY WHEN THIS DISPATCH SAVED A REVIEW. A reviewer whose every save was refused writes
14981
+ // nothing, and the stage still reads ok on the review that stands from before the correction, so its verdict and
14982
+ // its points would pass as the review of the corrected record, and the receipt would stop a resume from finishing
14983
+ // a verification nobody made. Such a recheck is a failed one: the entry verdict stands, the record says the
14984
+ // correction was not verified, no receipt is written, and the earlier review stays in place as the earlier review.
14985
+ //
14986
+ // TWO WAYS TO SAVE, BOTH COUNTED. The message above orders the review file rewritten, and a seat may do that or
14987
+ // record the review through its tool; both are seen on test runs. So a save is an accepted tool call made since
14988
+ // this dispatch began, or review bytes that differ from the ones before it. A byte-identical rewrite reads as no
14989
+ // save, which costs only a cycle run again on a resume: the same bytes carry the same verdict.
14990
+ const recheckCall = rc.ok ? readAcceptedReviewSince(run.runDir, recheckSeq0) : null;
14991
+ const recheckRewrote = rc.ok && !recheckCall && shaOf(P.seniorEyeReview) !== reviewShaBefore && shaOf(P.seniorEyeReview) != null;
14992
+ const recheckRead = recheckCall ? { by: "tool", seq: recheckCall.seq } : recheckRewrote ? { by: "file", seq: null } : null;
14993
+ if (rc.ok && !recheckRead) {
14994
+ runLog(run.runDir, { event: "verdict-recheck-unread", fail: "no-accepted-call", seq0: recheckSeq0, entryVerdict });
14995
+ note(`[corrections] the recheck after the correction recorded no review — the correction is not verified, the entry verdict (${entryVerdict}) stands, and the review in place is the one from before the correction`);
14996
+ }
14997
+ verdict = recheckRead ? (parseVerdict(readFileSync(P.seniorEyeReview, "utf8")) ?? entryVerdict) : entryVerdict;
14998
+ correctiveRecheckOk = rc.ok === true && Boolean(recheckRead);
14999
+ try {
15000
+ atomicWrite(driverDir(run.runDir, CORRECTIVE_RECHECK_FILE), JSON.stringify({ ts: new Date().toISOString(),
15001
+ status: correctiveRecheckOk ? "read" : "unread", by: recheckRead?.by ?? null, entryVerdict, verdict, seq0: recheckSeq0, seq: recheckRead?.seq ?? null,
15002
+ ...(correctiveRecheckOk ? {} : { fail: rc.ok ? "no-accepted-call" : String(rc.fail ?? "failed").slice(0, 160) }) }, null, 2) + "\n");
15003
+ } catch (e) { note(`[corrections] the recheck's record could not be written (${String(e?.message ?? e).slice(0, 100)}) — the run log still holds the outcome`); }
15004
+ runLog(run.runDir, { event: "verdict-2", verdict, read: correctiveRecheckOk });
14807
15005
  writeRunStatus(ctx, signoffPatch(verdict));
14808
15006
  }
14809
15007
  // AD-2 A1 — the completion receipt, written ONLY when the cycle finished with a verified recheck:
@@ -14955,6 +15153,17 @@ async function pipelineInner(job, opts = {}) {
14955
15153
  // withdrawn against it (ruled 2026-10-19).
14956
15154
  let assessed = verdict;
14957
15155
  let restoredClear = false; // a closed gap took this run back to CLEAR, so a later writer's judgment meets the floor again
15156
+ // THE REASONS THE RECORD'S OWN ACTIONS PUT IN THE LIST, by the floor's legal-actions arm, so the list can follow the
15157
+ // record when a repair in the delivery check rewrites, withdraws or adds a step (conditionsFollowingTheRecord).
15158
+ let recordConditionReasons = new Set();
15159
+ // WHAT A WITHDRAWAL OF THOSE STEPS NEEDS TO GIVE THE REVIEW'S CLEAR BACK (verdictWhenTheStepsAreWithdrawn): that the
15160
+ // steps raised the result, that none was ever dropped as unreadable, when a readable record last held none of them,
15161
+ // and when a correction in the delivery check was last rejected.
15162
+ let stepsRaisedTheResult = false;
15163
+ let stepsUnreadable = false;
15164
+ let stepsWithdrawnAt = null;
15165
+ let correctionRejectedAt = null;
15166
+ const DROPPED_CONDITIONS_REASON = "a forward legal step this opinion named could not be recorded, so the conditions listed here are incomplete";
14958
15167
 
14959
15168
  /**
14960
15169
  * Deliver, clamp conservatively, and name the defect in the run record.
@@ -15235,10 +15444,12 @@ async function pipelineInner(job, opts = {}) {
15235
15444
  // (the degenerate re-ask re-runs this floor; dedup is by the reason TEXT for both).
15236
15445
  for (const c of fresh) clampClauses.push(conditionClauses[conditions.indexOf(c)] ?? c);
15237
15446
  clampReasons.push(...fresh);
15447
+ for (const c of fresh) recordConditionReasons.add(c);
15238
15448
  if (verdict === "CLEAR") {
15239
15449
  runLog(run.runDir, { event: "coverage-floor-clamp", cause: "forward-actions", from: "CLEAR", to: "CONDITIONAL", legalActions: conditions.length });
15240
15450
  note(`deliver-conditional floor: the opinion names ${conditions.length} forward legal action(s) a human must take (${conditions[0].slice(0, 140)}${conditions.length > 1 ? `; +${conditions.length - 1} more` : ""}) — clamping CLEAR→CONDITIONAL (spec 64: the disposition is derived from the findings' named actions).`);
15241
15451
  verdict = "CONDITIONAL";
15452
+ stepsRaisedTheResult = true;
15242
15453
  writeRunStatus(ctx, signoffPatch(verdict));
15243
15454
  } else if (fresh.length) {
15244
15455
  runLog(run.runDir, { event: "verdict-conditions-recorded", legalActions: fresh.length });
@@ -15258,7 +15469,8 @@ async function pipelineInner(job, opts = {}) {
15258
15469
  // do is read as complete — so the reason says INCOMPLETE in the client's own words, and the
15259
15470
  // engine-side detail (ids, defect tokens) rides the note and the log where an engineer reads.
15260
15471
  const droppedConditions = quarantinedConditionRows(fdoc?.actionsQuarantined);
15261
- const droppedReason = "a forward legal step this opinion named could not be recorded, so the conditions listed here are incomplete";
15472
+ if (droppedConditions.length) stepsUnreadable = true; // a step nobody can read is never shown withdrawn
15473
+ const droppedReason = DROPPED_CONDITIONS_REASON;
15262
15474
  // ONCE, not once per entry. This floor is re-entered — the degenerate re-ask and the delivery
15263
15475
  // block both call it again — so the reason, the clause and the telemetry are guarded by the
15264
15476
  // reason's own presence. An event emitted on every re-entry would inflate any count keyed on
@@ -15267,6 +15479,7 @@ async function pipelineInner(job, opts = {}) {
15267
15479
  clampKinds.actionsDropped = true;
15268
15480
  clampClauses.push(droppedReason);
15269
15481
  clampReasons.push(droppedReason);
15482
+ recordConditionReasons.add(droppedReason);
15270
15483
  runLog(run.runDir, { event: "verdict-conditions-dropped", n: droppedConditions.length,
15271
15484
  ids: droppedConditions.map((q) => q.id), kinds: droppedConditions.map((q) => q.kind),
15272
15485
  errors: droppedConditions.map((q) => String(q.error ?? "").slice(0, 80)) });
@@ -15562,6 +15775,74 @@ async function pipelineInner(job, opts = {}) {
15562
15775
  try { displayVerdict = composeVerdictSidecar().doc; } catch { /* composed again when it is saved */ }
15563
15776
  return false;
15564
15777
  };
15778
+ // THE LABEL OWED IS SAVED before anything is published from it, and the report's own label follows it. Only a run
15779
+ // directory that refuses every save of it ends the run, and then nothing the run writes can be published.
15780
+ const saveTheOwedLabel = () => {
15781
+ if (!labelOwed) return;
15782
+ const owed = labelOwed;
15783
+ labelOwed = null;
15784
+ if (!saveTheLabel(`${owed}, saved again before delivery`))
15785
+ throw new StageFailure("verdict", `the run directory refused every save of the result's label (${owed}) — no surface can be published with it`);
15786
+ applyVerdictFrontMatter();
15787
+ };
15788
+ // THE CONDITIONS FOLLOW THE RECORD AFTER A REPAIR IN THE DELIVERY CHECK. Every surface reads the list from the label,
15789
+ // and the list states the record's forward legal steps as the record stands: a repair that rewrites, withdraws or
15790
+ // adds one moves the list with it, in the record's own words. The result moves only where the floor any result meets
15791
+ // moves it: a CLEAR the repaired steps now condition becomes CONDITIONAL, and nothing is relaxed. A BLOCKING result
15792
+ // states no step of its own, so only a list already stating the record's steps follows it. The caller saves the
15793
+ // label. Returns whether the list, its kinds or the result changed.
15794
+ const followTheRecordsActions = (why) => {
15795
+ if (verdict === "BLOCKING" && !recordConditionReasons.size) return false;
15796
+ let raw = null, fdoc = null;
15797
+ try { if (existsSync(P.findings)) { raw = readFileSync(P.findings, "utf8"); fdoc = parseFindingsJsonLenient(raw); } }
15798
+ catch { fdoc = null; }
15799
+ if (!fdoc) return false; // no record to read: the list stands as stated, and the coherence checks judge it
15800
+ const { conditions, conditionClauses } = deriveActionConditions(fdoc.actions, fdoc.findings);
15801
+ const now = conditions.map((c) => ({ reason: c, clause: conditionClauses[conditions.indexOf(c)] ?? c }));
15802
+ const dropped = quarantinedConditionRows(fdoc.actionsQuarantined).length > 0;
15803
+ if (dropped && recordConditionReasons.has(DROPPED_CONDITIONS_REASON)) now.push({ reason: DROPPED_CONDITIONS_REASON, clause: DROPPED_CONDITIONS_REASON });
15804
+ const state = () => JSON.stringify([clampReasons, clampClauses, Boolean(clampKinds.legalActions), Boolean(clampKinds.actionsDropped)]);
15805
+ const stood = state(), was = verdict;
15806
+ const f = conditionsFollowingTheRecord({ reasons: clampReasons, clauses: clampClauses, fromRecord: recordConditionReasons, now });
15807
+ clampReasons = f.reasons;
15808
+ clampClauses = f.clauses;
15809
+ recordConditionReasons = f.held;
15810
+ if (!conditions.length) delete clampKinds.legalActions;
15811
+ if (!dropped) delete clampKinds.actionsDropped;
15812
+ // A WITHDRAWAL IS POSITIVE ONLY ON A RECORD WHOSE ACTIONS REGISTER IS A LIST that holds none of the steps. A missing
15813
+ // or malformed register, or one with an entry dropped as unreadable, withdraws nothing.
15814
+ if (f.held.size || conditions.length || dropped) stepsWithdrawnAt = null;
15815
+ else if (f.withdrawn.length) stepsWithdrawnAt = actionsRegisterListed(raw) ? new Date().toISOString() : null;
15816
+ // The floor runs again only where the repaired steps reach it, as the coherence repair runs it.
15817
+ if (state() !== stood || (verdict === "CLEAR" && (conditions.length || dropped))) applyCoverageFloor();
15818
+ restoreTheReviewsClear();
15819
+ if (state() === stood && verdict === was) return false;
15820
+ runLog(run.runDir, { event: "verdict-conditions-followed", why, withdrawn: f.withdrawn.length, added: f.added.length,
15821
+ restated: f.restated.length, conditions: recordConditionReasons.size, from: was, to: verdict });
15822
+ note(`the conditions follow the record ${why} (${f.withdrawn.length} withdrawn, ${f.added.length} added, ${f.restated.length} restated${verdict === was ? "" : `; ${was} → ${verdict}`})`);
15823
+ return true;
15824
+ };
15825
+ // A CORRECTION THAT WITHDREW EVERY STEP THAT ALONE MADE THE RESULT CONDITIONAL gives the review's CLEAR back, once the
15826
+ // review of that change has been read and no correction since was rejected (the owner's decision, 2026-11-04). The
15827
+ // result is recomputed as a closed gap's is, and that CLEAR meets the floor any CLEAR meets. The caller saves the label.
15828
+ const restoreTheReviewsClear = () => {
15829
+ let review = null;
15830
+ try { review = JSON.parse(readFileSync(postRepairRecordPath(run.runDir), "utf8")); } catch { review = null; }
15831
+ const now = verdictWhenTheStepsAreWithdrawn({ verdict, assessed, reasons: clampReasons, raisedBySteps: stepsRaisedTheResult,
15832
+ stepsUnreadable, withdrawnAt: stepsWithdrawnAt, reviewReadAt: review?.status === "read" ? review.ts : null,
15833
+ reviewUnread: review?.status === "unread", correctionRejectedAt,
15834
+ // The correction of the first review owed a recheck the cycle did not get accepted: the assessment is not verified.
15835
+ recheckUnaccepted: (correctiveEntryVerdict === "CONDITIONAL" || correctiveEntryVerdict === "BLOCKING") && !correctiveCycleSettled && !correctiveRecheckOk });
15836
+ if (now === verdict) return false;
15837
+ runLog(run.runDir, { event: "verdict-recomputed-steps-withdrawn", from: verdict, to: now, withdrawnAt: stepsWithdrawnAt, reviewReadAt: review?.ts ?? null });
15838
+ note(`every forward legal step that made the result conditional was withdrawn, the review of that change was read, and nothing else conditions the result — ${verdict} goes back to ${now}, the result the review reached`);
15839
+ verdict = now;
15840
+ restoredClear = now === "CLEAR";
15841
+ stepsRaisedTheResult = false;
15842
+ writeRunStatus(ctx, signoffPatch(verdict));
15843
+ applyCoverageFloor(); // the floor any CLEAR meets
15844
+ return true;
15845
+ };
15565
15846
  try { writeVerdictSidecar(); }
15566
15847
  catch (e) { throw new StageFailure("verdict", `verdict sidecar write failed (the single label authority): ${String(e.message).slice(0, 120)}`); }
15567
15848
 
@@ -15721,6 +16002,8 @@ async function pipelineInner(job, opts = {}) {
15721
16002
  // afterwards and therefore never read it as staleness.
15722
16003
  stampCoverageJudgmentRows(P, run.runDir, note, ctx);
15723
16004
  consolidateFindingsFile(P, note, ctx.framework);
16005
+ // The conditions too: a save that rewrote, withdrew or added a forward legal step moves the list with it.
16006
+ followTheRecordsActions("after a save of the record");
15724
16007
  // T2: consolidation can change the live composite set — re-derive the sidecar so every
15725
16008
  // surface joins the FINAL findings (the sidecar must never describe a superseded set).
15726
16009
  // review fix: consolidation can also surface CONDITIONS the floor never saw (a lenient-
@@ -16651,6 +16934,11 @@ async function pipelineInner(job, opts = {}) {
16651
16934
  // is presence-gated and simply emits nothing here; they stay alive for replay-archive.mjs,
16652
16935
  // which passes the archived summary.
16653
16936
  reportMd, narrativeMd, auditMd, recordsByUri: assembled.records, searchedNames,
16937
+ // What each record's goods rested on when the writer wrote, and the records whose whole text a delivery repair
16938
+ // was already handed: a finding written on goods the register cut, whose whole body the run holds now. The
16939
+ // evidence is the copy kept when the writer was dispatched cold, which no later band merge rewrites; a run that
16940
+ // kept none, written before the copy existed, is read on the evidence as it stands.
16941
+ goodsEvidence: readGoodsEvidenceAsWritten(run.runDir) ?? readGoodsEvidence(run.runDir), goodsHanded: readGoodsHanded(run.runDir),
16654
16942
  // The overview as its writer wrote it, read for a citation of a finding the report does not carry; and the
16655
16943
  // conditions the email carries, as the email composes them.
16656
16944
  overviewMd: (() => { try { return readFileSync(P.reportOverview, "utf8"); } catch { return null; } })(), emailConditions: emailConditionsOfReport(reportMd, lintVerdict?.verdict),
@@ -16720,6 +17008,7 @@ async function pipelineInner(job, opts = {}) {
16720
17008
  // an edit to the actions. One attempt; a residual failure ships as the structural banner flag.
16721
17009
  if (lint.failures.some((f) => f.id === "verdict-actions-coherence" || f.id === "verdict-actions-stale" || f.id === "statement-tier" || f.id === "statement-unconditional" || f.id === "statement-stance" || f.id === "statement-conditional-form")) {
16722
17010
  const beforeVerdict = verdict;
17011
+ followTheRecordsActions("in the delivery check's re-derive"); // a stale step goes, as a missing one arrives
16723
17012
  applyCoverageFloor();
16724
17013
  try { writeVerdictSidecar(); }
16725
17014
  catch (e) { throw new StageFailure("verdict", `verdict sidecar re-derive failed (spec-64 coherence repair): ${String(e.message).slice(0, 120)}`); }
@@ -16882,13 +17171,47 @@ async function pipelineInner(job, opts = {}) {
16882
17171
  const fold = readFold(run.runDir);
16883
17172
  const sentenceFixable = targets.stamped.flatMap((f) => (f.parts ?? []).map((x) => ({ ...f, finding: keptModelOrdinal(fold, x.ordinal), detail: x.detail })));
16884
17173
  const recordFixable = targets.record.flatMap((f) => writersCitationFaults(f, (o) => keptModelOrdinal(fold, o)));
16885
- const narrativeFixable = [...modelFixable(bySurface("narrative")), ...sentenceFixable, ...recordFixable];
17174
+ // A finding named for goods the register cut, whose whole text the run holds now, is named in the writer's
17175
+ // numbering, in the line's own words: it opens with the finding it names, so the list puts no "finding N:" before it.
17176
+ // Under a fold the report displays the text of the member the fold kept, and the citation of the record can come
17177
+ // from another member: the line then names both, so the repair reaches the text the report displays (design,
17178
+ // 2026-11-04). Where the fold cannot be read, or no member is read citing the record, the line is not handed: a
17179
+ // member is never guessed, and the run records each finding left unhanded.
17180
+ const foldUnreadable = fold == null && existsSync(driverDir(run.runDir, FOLD_FILE));
17181
+ let writersFindings = null; // the writer's record, read once and only for a goods line
17182
+ const writersRecord = () => {
17183
+ if (writersFindings) return writersFindings;
17184
+ try { writersFindings = parseFindingsJsonLenient(readFileSync(modelRecordPath(run.runDir, P.findings), "utf8")).findings ?? []; }
17185
+ catch { writersFindings = []; }
17186
+ return writersFindings;
17187
+ };
17188
+ const citesRecord = (wf, uri) => (Array.isArray(wf?.owner?.registrations) ? wf.owner.registrations : [])
17189
+ .some((reg) => normalizeRecordUri(reg?.uri ?? reg) === uri);
17190
+ const goodsUnhanded = [];
17191
+ const inWritersNumbering = (f) => {
17192
+ if (!String(f.id).startsWith("goods-held-whole:")) return f;
17193
+ const shown = foldUnreadable ? null : keptModelOrdinal(fold, f.ordinal);
17194
+ const citing = shown == null ? null : citingModelOrdinal(fold, f.ordinal, f.uri, writersRecord(), citesRecord);
17195
+ const detail = goodsRepairLine({ shown, citing, uri: f.uri, goods: f.goods, state: f.state });
17196
+ if (detail == null) { goodsUnhanded.push({ id: f.id, why: shown == null ? "fold-not-read" : "no-member-read-citing" }); return null; }
17197
+ return { ...f, detail };
17198
+ };
17199
+ const narrativeFixable = [...modelFixable(bySurface("narrative")).map(inWritersNumbering).filter(Boolean), ...sentenceFixable, ...recordFixable];
17200
+ if (goodsUnhanded.length) runLog(run.runDir, { event: "goods-held-whole-not-handed", unhanded: goodsUnhanded });
16886
17201
  if (narrativeFixable.length && synthesisKey) repairBaseKept = snapshotRepairBase(run.runDir);
16887
17202
  // A writer fault with no writer session to repair it is not repaired, and the run says so.
16888
17203
  if (narrativeFixable.length && !synthesisKey)
16889
17204
  runLog(run.runDir, { event: "lint-redo-skipped", surface: "writer", why: "no-writer-session", failures: narrativeFixable.map((f) => f.id) });
16890
17205
  if (narrativeFixable.length) await redo("synthesis", narrativeFixable, synthesisKey, synthesisModel, synthesisThinking, P.narrative,
16891
17206
  { findings: modelRecordPath(run.runDir, P.findings), narrative: P.narrative });
17207
+ // The records whose whole goods text this repair was handed, kept so the check after it does not name them again.
17208
+ const goodsHandedNow = narrativeFixable.filter((f) => String(f.id).startsWith("goods-held-whole:")).map((f) => f.uri);
17209
+ if (goodsHandedNow.length && repaired.includes("synthesis")) {
17210
+ try {
17211
+ recordGoodsHanded(run.runDir, goodsHandedNow);
17212
+ runLog(run.runDir, { event: "goods-held-whole-handed", records: [...new Set(goodsHandedNow)].sort() });
17213
+ } catch (e) { note(`pre-delivery lint: the records handed their whole goods text were not recorded: ${e?.message ?? e}`); }
17214
+ }
16892
17215
  if (reassembled) assembleReportMd(P, findingsForCards, assembledOrdinals, { grouped: groupedMembers, byRight });
16893
17216
  // The client-summary redo arm is retired with the stage (2026-08-01). Its `email`-surface
16894
17217
  // failures have not gone unowned: the `:email` reference check now runs over the report-derived
@@ -16905,6 +17228,17 @@ async function pipelineInner(job, opts = {}) {
16905
17228
  autoCorrectRegistry(); // doc-27 Item 1b: a re-emission may have reintroduced a wrong identifier — overwrite from the record again
16906
17229
  }
16907
17230
  }
17231
+ // THE GOODS REFRESH'S OUTCOME, kept in the run record whatever this pass did (predelivery-lint.mjs,
17232
+ // goodsHeldWholeChecks): the findings named for the repair, those still saying their goods are cut or unread after
17233
+ // it, and the check's own count of the ones that no longer say so.
17234
+ try {
17235
+ const rows = (lint?.checks ?? []).filter((c) => /^goods-held-whole(?::|-unresolved:|$)/.test(String(c.id)));
17236
+ if (rows.some((c) => c.id !== "goods-held-whole") || readGoodsHanded(run.runDir).size)
17237
+ runLog(run.runDir, { event: "goods-held-whole",
17238
+ named: rows.filter((c) => c.id.startsWith("goods-held-whole:")).map((c) => c.id.slice("goods-held-whole:".length)),
17239
+ unresolved: rows.filter((c) => c.id.startsWith("goods-held-whole-unresolved:")).map((c) => c.id.slice("goods-held-whole-unresolved:".length)),
17240
+ summary: rows.find((c) => c.id === "goods-held-whole")?.detail ?? null });
17241
+ } catch { /* the run record's row is best-effort; the check's own rows are in the receipt below */ }
16908
17242
  // The receipt artifact — ALWAYS written, pass or fail (spec A2's auditor evidence).
16909
17243
  // V4-1: the receipt states the ARTIFACT SET evaluated — surfaces, record set + sources, and the
16910
17244
  // stage labels this session inherited via skip — so an auditor can see the gates ran over
@@ -17134,6 +17468,7 @@ async function pipelineInner(job, opts = {}) {
17134
17468
  if (review.rec.flags.length) {
17135
17469
  const pass = await runPostRepairCorrection(ctx, P, run, { rec: review.rec, items: review.items, points: review.points,
17136
17470
  grounds: Boolean(hardened), whole: review.base?.whole === true, synthesisRef: { key: synthesisKey, model: synthesisModel, thinking: synthesisThinking } });
17471
+ if (!pass.ok) correctionRejectedAt = new Date().toISOString(); // a rejected correction gives no result back
17137
17472
  // NOTHING REVIEWS THE CORRECTION: the reviewer's stamp takes what it changed as accounted for, and so
17138
17473
  // does the first cycle's receipt, so a resume re-fires neither.
17139
17474
  settleOneShotStamp(run.runDir, "narrative-refutation", [P.narrative], "post-repair-fix");
@@ -17354,17 +17689,17 @@ async function pipelineInner(job, opts = {}) {
17354
17689
  note(`stale-repair: ${staleStages.map((x) => x.label).join(", ")} could not be re-run for the changed decision — the run delivers, and the approved clauses name what they find`);
17355
17690
  staleStages = [];
17356
17691
  }
17357
- // THE LABEL OWED IS SAVED NOW, before anything is published from it, and the report's own label follows it. Only
17358
- // a run directory that refuses every save of it ends the run here, and then nothing the run writes can be published.
17359
- if (labelOwed) {
17360
- const owed = labelOwed;
17361
- labelOwed = null;
17362
- if (!saveTheLabel(`${owed}, saved again before delivery`))
17363
- throw new StageFailure("verdict", `the run directory refused every save of the result's label (${owed}) — no surface can be published with it`);
17364
- applyVerdictFrontMatter();
17365
- }
17692
+ saveTheOwedLabel(); // before anything is published from it
17366
17693
  note(`stale-repair: re-did ${staleRepaired.length} stage(s) in-pass (${staleRepaired.join(", ") || "none"}) — ${staleStages.length ? `${staleStages.length} still stale, the delivery guard blocks` : "the delivery path is fresh"}`);
17367
17694
  }
17695
+ // THE CONDITIONS FOLLOW THE RECORD AS IT IS DELIVERED, whichever repair above moved it last, and the label owed is
17696
+ // saved before the receipt below and anything published from it. A list that moved is judged again.
17697
+ if (followTheRecordsActions("as the record is delivered")) {
17698
+ saveTheLabel("as the record is delivered");
17699
+ applyVerdictFrontMatter();
17700
+ lint = lintNow();
17701
+ }
17702
+ saveTheOwedLabel();
17368
17703
  // P2 — record the delivery-BLOCKING stale labels the moment they are known (not only at the throw
17369
17704
  // below), so ANY later exit from this pass — the staleness throw, a core-artifact throw between here
17370
17705
  // and it, an auto-recovery park — carries the set into reconcilePassStamps. Reconcile must leave these
@@ -18194,8 +18529,8 @@ function assessmentArtifacts(P, runDir) {
18194
18529
  P.findings, P.narrative, P.report, P.reportOverview, P.reportCardsDir, P.audit, P.seniorEyeReview, P.caseLaw,
18195
18530
  P.caseLawCitations, P.doubtClosure, P.clientSummary, P.emailBody, P.correctionsApplied,
18196
18531
  join(runDir, REPORT_IDENTITY_FILE), join(runDir, ".published"),
18197
- ...["verdict.json", "senior-rights.json", "corrections-state.json", "corrective-cycle.json", "predelivery-lint.json",
18198
- "reasoning-integrity.json"].map((n) => driverDir(runDir, n)),
18532
+ ...["verdict.json", "senior-rights.json", "corrections-state.json", "corrective-cycle.json", CORRECTIVE_RECHECK_FILE,
18533
+ "predelivery-lint.json", "reasoning-integrity.json"].map((n) => driverDir(runDir, n)),
18199
18534
  declinationCallPaths(runDir, 0).ledger,
18200
18535
  ].filter(Boolean);
18201
18536
  }