clearotron 0.5.0-beta.7 → 0.5.0-beta.9

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 (46) hide show
  1. package/.env.example +9 -1
  2. package/INSTALL.md +1 -1
  3. package/bin/signa-sync.mjs +1 -1
  4. package/build-info.json +2 -2
  5. package/docs/architecture/04-configuration-reference.md +1 -0
  6. package/docs/configuration.md +1 -1
  7. package/driver/CHANGELOG.md +20 -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/engine/mcp/band-server.mjs +16 -6
  13. package/driver/engine/mcp/correction-positions.mjs +18 -0
  14. package/driver/engine/mcp/gather-config.mjs +7 -3
  15. package/driver/engine/mcp/recording-server.mjs +7 -4
  16. package/driver/engine/openai-agent.mjs +24 -1
  17. package/driver/engine/probe.mjs +64 -9
  18. package/driver/findings-model.mjs +4 -2
  19. package/driver/gateway.mjs +26 -16
  20. package/driver/goods-evidence.mjs +16 -3
  21. package/driver/narrative-refutation-record.mjs +17 -2
  22. package/driver/package.json +1 -1
  23. package/driver/pipeline.mjs +283 -41
  24. package/driver/predelivery-lint.mjs +91 -2
  25. package/driver/record-fold.mjs +16 -0
  26. package/driver/record-goods.mjs +24 -8
  27. package/driver/repair-composers.mjs +72 -12
  28. package/driver/saved-register-pages.mjs +144 -0
  29. package/driver/skills/clearance-register/providers/signa.md +6 -4
  30. package/driver/stage-context.mjs +7 -0
  31. package/driver/suite-census.json +96 -12
  32. package/driver/synthesis-record.mjs +165 -33
  33. package/driver/verify.mjs +6 -3
  34. package/mcp-server/CHANGELOG.md +8 -0
  35. package/mcp-server/package.json +1 -1
  36. package/package.json +1 -1
  37. package/portal-ui/package.json +1 -1
  38. package/providers/README.md +1 -1
  39. package/providers/oauth-mcp-bridge/CHANGELOG.md +8 -0
  40. package/providers/oauth-mcp-bridge/package.json +1 -1
  41. package/providers/signa/src/core.js +18 -4
  42. package/providers/signa/src/offices.generated.js +15 -13
  43. package/scripts/e2e-first-time.mjs +6 -4
  44. package/scripts/release-duplicate-notes.mjs +5 -0
  45. package/shared/names-in-force.mjs +1 -0
  46. package/shared/register-selection.mjs +2 -2
package/.env.example CHANGED
@@ -191,6 +191,14 @@ CLEAROTRON_DATABASE=clarivate
191
191
  # effect: tuning
192
192
  CLEAROTRON_GATHER_SEND_UNTIL_MS=
193
193
  #
194
+ # The records a correction's flags name, as a JSON list: the writer's save may add a finding for an
195
+ # excluded position that holds one of them. The driver writes it into the tool servers' env when it
196
+ # dispatches the correction and the correction's re-emit, and leaves it out of every other dispatch.
197
+ # Leave it empty: a stage's program starts with a listed environment that does not carry this name
198
+ # (driver/engine/engine-env.mjs), so a value set here reaches no tool server.
199
+ # effect: silent-output-change
200
+ CLEAROTRON_CORRECTION_POSITIONS=
201
+ #
194
202
  # THERE IS NO RETENTION SETTING AND NO CLEANUP JOB. CLEAROTRON_REGISTER_LEDGER_MAX_BYTES,
195
203
  # CLEAROTRON_REGISTER_LEDGER_KEEP and `npm run prune:ledger` are gone with the rotation tool, because the
196
204
  # thing they bounded no longer grows: RECORD BODIES ARE WRITTEN INTO THE RUN'S OWN DIRECTORY
@@ -279,7 +287,7 @@ OPENAI_API_KEY=
279
287
  # reason worth knowing before you leave it unset: an unset variable took Corsearch in silence, and the
280
288
  # credential guard could not catch it because both boxes carried CORSEARCH_SESSION_KEY.
281
289
  #
282
- # ADR-0001 recommends Signa, not Corsearch: one self-serve key, US + EU + WIPO and eight more offices.
290
+ # ADR-0001 recommends Signa, not Corsearch: one self-serve key, US + EU + WIPO and ten more offices.
283
291
  #
284
292
  # Corsearch.
285
293
  CORSEARCH_SESSION_KEY=changeme
package/INSTALL.md CHANGED
@@ -117,7 +117,7 @@ run is [mcp-server/CONNECT.md](mcp-server/CONNECT.md), and why something is the
117
117
  Which register you pick is the first real decision, and the tiers are not equally easy to reach.
118
118
  [providers/README.md](providers/README.md) is the canonical ladder and
119
119
  [ADR-0001](docs/decisions/0001-register-ladder.md) is the reasoning. The short version: **Signa** is
120
- the recommended route (one self-serve key, eleven offices), **`free-tier`** is EU + US with no vendor
120
+ the recommended route (one self-serve key, thirteen offices), **`free-tier`** is EU + US with no vendor
121
121
  contract but a 41.5 GB build for the US half (§3a), and **Corsearch / Clarivate** are the widest
122
122
  coverage on a vendor-issued credential. Whatever the chosen register cannot reach becomes a disclosed
123
123
  deferred-coverage row rather than a silent gap, at every tier.
@@ -104,7 +104,7 @@ if (!live.length) die(`${offices.length} office(s) returned and NONE is status:l
104
104
  const stamp = String(process.env.SIGNA_SYNC_STAMP ?? "").trim() || new Date().toISOString();
105
105
 
106
106
  const body = `// SPDX-License-Identifier: AGPL-3.0-only
107
- // Copyright 2026 Cordillera Sàrl
107
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
108
108
  // GENERATED by bin/signa-sync.mjs — do not edit by hand.
109
109
  //
110
110
  // This is the vendor's own office list, fetched and committed so that a change in what we claim to
package/build-info.json CHANGED
@@ -1,4 +1,4 @@
1
1
  {
2
- "commit": "918c71c56484cf580cd12b2722b71f1ec54e873d",
3
- "version": "0.5.0-beta.7"
2
+ "commit": "a133cbb3001da9c7c037168cf2e4dfeafab02770",
3
+ "version": "0.5.0-beta.9"
4
4
  }
@@ -375,6 +375,7 @@ cannot be read as one list.
375
375
  | `CLEAROTRON_GATHER_SESSION_KEY` / `CLEAROTRON_GATHER_AGENT` / `CLEAROTRON_GATHER_SESSION_ID` | set per stage | Telemetry attribution into the provider-call ledger (set by the gather config; not operator-set). |
376
376
  | `CLEAROTRON_GATHER_SEND_UNTIL_MS` | set per turn | When a turn's register tools stop sending new questions: a quarter of the turn, at most five minutes, ahead of its deadline (set by the gather config; not operator-set). |
377
377
  | `CLEAROTRON_RECORD_AXIS` | set per dispatch (unset ⇒ the stage is not fanned out) | Binds one fan-out turn of a recording stage to the single member it may write. `stageOnce` suffixes a fan-out stage's label with its axis, the gather config resolves `<stage>:<axis>` back to the base stage's tool group, and this carries the axis to the recording server. A call whose payload names a different member than the turn is bound to is REFUSED, so a seat cannot write into a sibling's file — without the binding every turn of the fan-out would record over member one. Set by the driver; not operator-set. |
378
+ | `CLEAROTRON_CORRECTION_POSITIONS` | set per dispatch (unset ⇒ the dispatch is not a correction's) | The excluded positions named by the review flags a correction answers, as a JSON list of record ids, carried to the recording server for that correction's dispatch and its retries. The writer's save may add a finding for one of those positions; on any other dispatch it adds none (set by the gather config; not operator-set). |
378
379
  | `PORTAL_READ_MODEL` | `sonnet` | The model the portal's own compose-read turn uses. Distinct from the pipeline's tiers: this is a portal surface, not a stage. |
379
380
  | `CLEAROTRON_ORDER_PROBE_SEED` | unset | Seed for `scripts/band-shape-probe.mjs`, so an ordering probe can be replayed. A diagnostic script's knob, not a run's. |
380
381
  | `PROBE_TERM` | `DELTA` | The mark word `providers/uspto-local/bin/verify-index.mjs` searches when verifying a built local USPTO index. A diagnostic script's knob, not a run's. Change it when a row reports MEASURES NOTHING: that means the term had no exact hit, so the row's timing is not a result. |
@@ -22,7 +22,7 @@ that:
22
22
 
23
23
  | | Provider | How you get it | Coverage |
24
24
  |---|---|---|---|
25
- | **1 — recommended** | `signa` | **Self-serve API key**, issued from the vendor's site. No sales call | 11 offices: US, EU, WIPO/Madrid + 8 |
25
+ | **1 — recommended** | `signa` | **Self-serve API key**, issued from the vendor's site. No sales call | 13 offices: US, EU, WIPO/Madrid + 10 |
26
26
  | **2 — free, with real limits** | `free-tier` (`euipo` + `uspto-local`) | Two free accounts, and a 41.5 GB local build for the US half | EU + US, and nothing else. No sound-alike search |
27
27
  | **3 — widest coverage** | `corsearch`, `clarivate` | Credential issued by the vendor | Global; Clarivate reaches 186 offices |
28
28
 
@@ -1,5 +1,25 @@
1
1
  # clearotron-driver
2
2
 
3
+ ## 0.5.0-beta.9
4
+
5
+ ### Patch Changes
6
+
7
+ - Fixed: A clearance on the Claude engine no longer stops with a false "not signed in" message before the search begins, while the Claude sign-in is being renewed.
8
+ - Fixed: A clearance on the Codex engine no longer stops as if signed out when the Codex sign-in fails to renew for a moment.
9
+ - Fixed: A report's list of conditions now shows each legal step as the last correction before delivery left the step, not as first written.
10
+ - Fixed: The audit workbook no longer lists the same open search twice, once in the report's words and once as a follow-up row with a shortened title.
11
+ - Fixed: The reviewing lawyer's open questions no longer say a coverage line was removed when a correction gave it the new title the review asked for.
12
+ - Fixed: Searches on the Signa register now ask for each goods statement in full, so a report weighs an owner's whole goods rather than the first 280 characters.
13
+ - Fixed: When a late correction adds, changes, or withdraws a finding, the answers in the report's summary panel are now checked against that finding and updated where they rest on it.
14
+ - Fixed: For a European Union order, the audit workbook now names every national register that was not searched, instead of only the first few.
15
+
16
+ ## 0.5.0-beta.8
17
+
18
+ ### Patch Changes
19
+
20
+ - Fixed: A conflict the reviewing step sends back for correction can now be reported as a finding; the correction could previously change only findings already in the report.
21
+ - New: Searches on the Signa register now reach Spain and Mexico, so an order naming either country is searched there rather than reported as not covered.
22
+
3
23
  ## 0.5.0-beta.7
4
24
 
5
25
  ### Patch Changes
@@ -530,9 +530,9 @@ export const INNER_CODES = Object.freeze([
530
530
  // ONE CODE, TWO TOKENS, and the split is by `cause` rather than by code: verify.mjs peels the
531
531
  // `axis_invalid` cause into its own family before counting the rest. A ruling naming only
532
532
  // `coverage_no_status` would be true of most `no_status` records and false of the ones that matter most.
533
- { code: "no_status", mints: ["driver/coverage-form.mjs:939"], rollsUpTo: ["coverage_no_status", "coverage_form_axis_invalid"],
533
+ { code: "no_status", mints: ["driver/coverage-form.mjs:998"], rollsUpTo: ["coverage_no_status", "coverage_form_axis_invalid"],
534
534
  why: "Two composites, split on the record's `cause`: coverageFormFail() in verify.mjs for cause `axis_invalid`, and the same function for the rest. NOT the `@returns` annotation of findCoverageFormViolations() in coverage-form.mjs — that is the annotation, not the mint." },
535
- { code: "engine_vocabulary", mints: ["driver/coverage-form.mjs:929"], rollsUpTo: ["coverage_form_engine_vocabulary"],
535
+ { code: "engine_vocabulary", mints: ["driver/coverage-form.mjs:988"], rollsUpTo: ["coverage_form_engine_vocabulary"],
536
536
  why: "#669 — the seat wrote an engine token into the `reason` sentence that reaches the reader's page. Checked on settled rows too, because a row the seat considers finished is exactly the one whose sentence gets printed. Namespaced by coverageFormFail() in verify.mjs; the bare code names a row, never a stage." },
537
537
 
538
538
  // ── ONE CODE, TWO MODULES ────────────────────────────────────────────────────────────────────────
@@ -544,7 +544,7 @@ export const INNER_CODES = Object.freeze([
544
544
  // failure tokens" already states the rule this row records: `coverage_form_damaged`, never a bare
545
545
  // `form_damaged`.
546
546
  { code: "form_damaged",
547
- mints: ["driver/connotation-search.mjs:2002", "driver/connotation-search.mjs:2078", "driver/coverage-form.mjs:921"],
547
+ mints: ["driver/connotation-search.mjs:2002", "driver/connotation-search.mjs:2078", "driver/coverage-form.mjs:980"],
548
548
  rollsUpTo: ["connotation_form_damaged", "coverage_form_damaged"],
549
549
  why: "Minted in two lanes and namespaced per lane: connotationDispositionFail() in verify.mjs for the meaning sweep, coverageFormFail() in verify.mjs for the register digest. The namespacing is what keeps them apart — see verify.mjs's block headed \"the register coverage-form failure tokens\"." },
550
550
  ]);
@@ -29,7 +29,7 @@
29
29
  // finding has a card is the assembly's choice, not the correction's fate.
30
30
  //
31
31
  // PURE — no node imports. The pipeline reads and writes the files.
32
- import { reportLines, linesOf } from "./corrections-feedforward.mjs";
32
+ import { reportLines, linesOf, renamedAs } from "./corrections-feedforward.mjs";
33
33
 
34
34
  /** The finding fields a correction can change that a report prints from the record. */
35
35
  export const DELIVERED_FINDING_FIELDS = Object.freeze(["net", "legal_position", "practical_position"]);
@@ -55,8 +55,8 @@ export function correctionTargets(rows, preDoc, postDoc) {
55
55
  const checkable = Boolean(preDoc && postDoc);
56
56
  const preOrd = byOrdinal(preDoc), postOrd = byOrdinal(postDoc);
57
57
  const preName = byName(preDoc), postName = byName(postDoc);
58
- const preLines = reportLines(preDoc);
59
- const postLines = new Map(reportLines(postDoc).map((l) => [l.key, l.text]));
58
+ const preLines = reportLines(preDoc), postList = reportLines(postDoc);
59
+ const postLines = new Map(postList.map((l) => [l.key, l.text]));
60
60
  return (Array.isArray(rows) ? rows : []).map((r) => {
61
61
  const out = { n: r?.n ?? null, kind: r?.kind ?? null, applied: r?.outcome ?? null, changes: [] };
62
62
  if (!checkable || r?.outcome === "not-checkable") return { ...out, why: "not-checkable" };
@@ -64,8 +64,10 @@ export function correctionTargets(rows, preDoc, postDoc) {
64
64
  const add = (c, key) => { if (!seen.has(key)) { seen.add(key); out.changes.push(c); } };
65
65
  if (r.outcome === "line-changed") {
66
66
  for (const l of linesOf(r.text, preLines)) {
67
- const now = postLines.get(l.key);
68
- if (now !== undefined && squash(now) !== squash(l.text)) add({ line: l.key, text: now }, l.key);
67
+ // A line the pass renamed is looked for under its new key, as the applied table joined it.
68
+ const moved = postLines.has(l.key) ? null : renamedAs(l, preLines, postList);
69
+ const now = moved ? moved.text : postLines.get(l.key);
70
+ if (now !== undefined && (moved || squash(now) !== squash(l.text))) add({ line: moved?.key ?? l.key, text: now }, moved?.key ?? l.key);
69
71
  }
70
72
  } else if (r.outcome === "findings-changed") {
71
73
  const declared = (Array.isArray(r.ordinals) ? r.ordinals : []).filter((o) => preOrd.has(o) || postOrd.has(o));
@@ -136,6 +136,46 @@ export function linesOf(flagText, lines) {
136
136
  return (lines ?? []).filter((l) => namesLine(hay, l) || quotesLine(hay, l.text));
137
137
  }
138
138
 
139
+ /**
140
+ * THE LINE A PASS PUT IN A GONE LINE'S PLACE: the same line, renamed. A coverage line is known by its title and an
141
+ * action by its id, so a flag asking for a new title, answered, left no line under the old key and the line read as
142
+ * deleted. The reviewing lawyer was then told "removed rather than corrected" of two coverage lines the writer had
143
+ * retitled as asked (two flags of one test run, 2026-11-03).
144
+ *
145
+ * CLAIMED ONLY WHERE THE RECORD SHOWS IT. Among lines of the same kind, the gone line must be the only one gone
146
+ * between its nearest neighbours the pass kept. Of the lines the pass added between those neighbours, exactly one
147
+ * must carry at least two in five of the gone line's words, title and text together. A writer can split a line,
148
+ * so one added line beside it is not enough; the successor is the one that keeps its words. On that run the two
149
+ * successors kept 0.88 and 0.55 of them, and no other line kept more than 0.18. Anything else (two gone, no
150
+ * successor, two candidates, the neighbours reordered) stays a removal: a deletion read as a rename would hide it
151
+ * from the lawyer. The mark assessment's two reads have fixed keys, so neither is ever a rename. Returns the
152
+ * post-pass line, or null. PURE.
153
+ */
154
+ const RENAME_SHARE = 0.4;
155
+ const lineWords = (l) => new Set(norm(`${String(l.key).slice(String(l.key).indexOf(":") + 1)} ${l.text}`)
156
+ .split(" ").filter((w) => w.length > 2));
157
+ export function renamedAs(line, preLines, postLines) {
158
+ const kindOf = (l) => String(l?.key ?? "").slice(0, Math.max(0, String(l?.key ?? "").indexOf(":")));
159
+ const kind = kindOf(line);
160
+ if (kind !== "coverage" && kind !== "action") return null;
161
+ const before = (preLines ?? []).filter((l) => kindOf(l) === kind);
162
+ const after = (postLines ?? []).filter((l) => kindOf(l) === kind);
163
+ const kept = new Set(after.map((l) => l.key));
164
+ const had = new Set(before.map((l) => l.key));
165
+ const at = before.findIndex((l) => l.key === line.key);
166
+ if (at < 0 || kept.has(line.key)) return null;
167
+ let lo = at - 1; while (lo >= 0 && !kept.has(before[lo].key)) lo--;
168
+ let hi = at + 1; while (hi < before.length && !kept.has(before[hi].key)) hi++;
169
+ if (hi - lo !== 2) return null; // another line went from the same gap
170
+ const from = lo >= 0 ? after.findIndex((l) => l.key === before[lo].key) : -1;
171
+ const to = hi < before.length ? after.findIndex((l) => l.key === before[hi].key) : after.length;
172
+ const added = (to > from ? after.slice(from + 1, to) : []).filter((l) => !had.has(l.key));
173
+ const mine = lineWords(line);
174
+ if (!mine.size) return null;
175
+ const keeps = added.filter((l) => { const theirs = lineWords(l); let n = 0; for (const w of mine) if (theirs.has(w)) n++; return n / mine.size >= RENAME_SHARE; });
176
+ return keeps.length === 1 ? keeps[0] : null;
177
+ }
178
+
139
179
  /** The corrective pass's own words about a line it was flagged on, from the `corrections` register. PURE. */
140
180
  function reasonFor(hit, doc) {
141
181
  const c = doc?.corrections;
@@ -281,7 +321,7 @@ export function buildCorrectionsApplied(rows, preDoc, postDoc, { sections = null
281
321
  const known = knownEntities(preDoc, postDoc);
282
322
  const pre = byName(preDoc), post = byName(postDoc);
283
323
  const preOrd = byOrdinal(preDoc), postOrd = byOrdinal(postDoc);
284
- const preLines = reportLines(preDoc), postLine = new Map(reportLines(postDoc).map((l) => [l.key, l]));
324
+ const preLines = reportLines(preDoc), postLines = reportLines(postDoc), postLine = new Map(postLines.map((l) => [l.key, l]));
285
325
  return (rows ?? []).map((r) => {
286
326
  // — a DECLARED ordinal wins over the name match. `targetsOf` is a normalised prose join and it
287
327
  // is why six of nine flags on a delivered run resolved to nothing; the declaration is the reviewer's
@@ -320,9 +360,11 @@ export function buildCorrectionsApplied(rows, preDoc, postDoc, { sections = null
320
360
  else if (hit.length) {
321
361
  // The same three answers a finding gets, asked of the line's own text. REMOVAL WINS, as it does
322
362
  // for a finding: a line gone after the pass was answered by deletion, and that is the question.
323
- const gone = hit.filter((l) => !postLine.has(l.key));
363
+ // A line renamed in place is still there, and a new title is a change (`renamedAs`).
364
+ const now = (l) => postLine.get(l.key) ?? renamedAs(l, preLines, postLines);
365
+ const gone = hit.filter((l) => !now(l));
324
366
  if (gone.length) { outcome = "line-removed"; removed = gone.map((l) => l.label); }
325
- else outcome = hit.some((l) => squash(postLine.get(l.key).text) !== squash(l.text)) ? "line-changed" : "line-unchanged";
367
+ else outcome = hit.some((l) => now(l).key !== l.key || squash(now(l).text) !== squash(l.text)) ? "line-changed" : "line-unchanged";
326
368
  }
327
369
  else if (declaredOrds.length) {
328
370
  // The certain path. Every question below is asked of the finding the reviewer NAMED, by ordinal.
@@ -371,6 +413,50 @@ export function buildCorrectionsApplied(rows, preDoc, postDoc, { sections = null
371
413
  });
372
414
  }
373
415
 
416
+ /**
417
+ * THE ANSWERS A CORRECTION MAY HAVE LEFT BEHIND: findings the pass moved that an answer citing findings may depend on.
418
+ *
419
+ * Each of the four answers that cites findings names them by ordinal (`four_answers.<answer>.ordinals`). On a test run
420
+ * (2026-11-03) a correction raised a finding from Moderate to High and updated the verdict, and the third-party-rights
421
+ * answer kept naming findings 1 to 3. The recheck saw it, but no pass follows the recheck, so the report kept the answer.
422
+ *
423
+ * A REASON TO ASK, NEVER A REQUIRED CITATION (design, 2026-11-03). For each answer that names findings, two things
424
+ * suggest a missing dependency:
425
+ * - a live adversarial finding the pass added, re-banded or re-typed, rated at or above the lowest band among the
426
+ * live findings the answer names, and not named by it: a shared band is a reason to check, not a rule;
427
+ * - a finding the answer names that the pass withdrew.
428
+ * A finding the pass did not move is never listed: what the writer cited before the correction is its own judgment. An
429
+ * answer that names no finding is not checked here, which is not a pass, and no absent answer is invented. Current
430
+ * citations do not make an answer's prose current; the recheck reads that. `bands` is the framework's ladder, most
431
+ * severe first. Returns `[{answer, cited, floor, uncited: [{ordinal, band}], withdrawn: [ordinal]}]`, empty when none. PURE.
432
+ */
433
+ export function answersLeftBehind(preDoc, postDoc, bands) {
434
+ const labels = (bands ?? []).map((b) => String(b?.label ?? b ?? "").trim());
435
+ const ladder = labels.map((b) => b.toLowerCase());
436
+ const rank = (band) => ladder.indexOf(String(band ?? "").trim().toLowerCase());
437
+ const answers = postDoc?.four_answers ?? postDoc?.fourAnswers;
438
+ if (!answers || typeof answers !== "object") return [];
439
+ const live = (f) => f && f.disposition !== "withdrawn";
440
+ const before = byOrdinal(preDoc), after = byOrdinal(postDoc);
441
+ const moved = (f) => { const was = before.get(f.ordinal); return !was || was.band !== f.band || was.disposition !== f.disposition; };
442
+ const out = [];
443
+ for (const [answer, a] of Object.entries(answers)) {
444
+ if (!a || !Array.isArray(a.ordinals) || !a.ordinals.length) continue;
445
+ const cited = new Set(a.ordinals.map(Number));
446
+ const withdrawn = [...cited].filter((o) => after.get(o)?.disposition === "withdrawn" && before.get(o)?.disposition !== "withdrawn");
447
+ const ranks = [...cited].map((o) => after.get(o)).filter(live).map((f) => rank(f.band)).filter((i) => i >= 0);
448
+ const floor = ranks.length ? Math.max(...ranks) : -1;
449
+ const uncited = floor < 0 ? [] : [...after.values()].filter((f) => {
450
+ if (cited.has(f.ordinal) || !live(f) || f.disposition !== "adversarial") return false;
451
+ const i = rank(f.band);
452
+ return i >= 0 && i <= floor && moved(f);
453
+ }).map((f) => ({ ordinal: f.ordinal, band: f.band }));
454
+ if (uncited.length || withdrawn.length)
455
+ out.push({ answer, cited: [...cited].sort((x, y) => x - y), floor: floor < 0 ? null : labels[floor], uncited, withdrawn });
456
+ }
457
+ return out;
458
+ }
459
+
374
460
  /**
375
461
  *, T3b — WHICH OF THE REVIEWER'S OBJECTIONS THE RUN COULD NOT SHOW IT CLOSED.
376
462
  *
@@ -33,6 +33,7 @@ import { REGISTER_AXES, COVERAGE_STATUSES, normalizeAxis, CROWD_RULING_TOKEN,
33
33
  import { shortId } from "./connotation-search.mjs";
34
34
  import { openBlocksByAxis, crowdNarrowing, blocksByQidOf, isProviderHardErrorReason, refusedSearchSentence, notSearchedSentence } from "./register-plan.mjs";
35
35
  import { territoryLayerReport, unsearchedLayerReason } from "./binding-layers.mjs"; import { goodsTermsList } from "../providers/_shared/term-shape.mjs";
36
+ import OFFERED from "../shared/offered-territories.json" with { type: "json" }; // the order form's own territory names
36
37
 
37
38
  const STATUS_SET = new Set(COVERAGE_STATUSES);
38
39
  const DRIVER_KINDS = new Set(["axis", "block", "deferred", "family"]);
@@ -556,8 +557,7 @@ export function coverageFormRows({ skeleton = [], activeAxes = null, plan = null
556
557
  axis: "primary-sweep", kind: "deferred",
557
558
  unit: `${report.territory} — binding registers not all searched`,
558
559
  qid: null,
559
- receipt_reason: report.unsearched
560
- .map((u) => `${u.layer} (${u.office}): ${u.state}`).join("; "),
560
+ receipt_reason: layerReceipt(report),
561
561
  open: true,
562
562
  open_because: unsearchedLayerReason(report),
563
563
  status: null, reason: null,
@@ -585,6 +585,65 @@ export function coverageFormRows({ skeleton = [], activeAxes = null, plan = null
585
585
  };
586
586
  }
587
587
 
588
+ // ── THE REGISTERS A LAYER ROW LEFT UNSEARCHED, NAMED IN FULL ────────────────────────────────────────
589
+ //
590
+ // The layer row's receipt holds every register the plan did not search: on an EU order through a provider
591
+ // that holds three member registers, 22 of them. The reader saw a handful. The writer's brief cuts a receipt
592
+ // at 160 characters, so the writer named the first five or so after "including", and the workbook's
593
+ // coverage-judgment row cut the writer's reason at 160 characters again, mid-word. Measured on two test
594
+ // runs, 2026-11-03: 5 to 7 of 22 named, on both engines.
595
+ //
596
+ // The list is the driver's to state, from the receipt, so no model retypes it and none can drop one. The
597
+ // receipt is written and read here, in one module, so the two cannot disagree about its shape.
598
+
599
+ /** A layer row's receipt: one `layer (OFFICE): state` entry per register the plan did not search. PURE. */
600
+ export function layerReceipt(report) {
601
+ return report.unsearched.map((u) => `${u.layer} (${u.office}): ${u.state}`).join("; ");
602
+ }
603
+
604
+ const LAYER_RECEIPT_ENTRY_RE = /^(national|regional|international) \(([A-Z]{2})\): (excludes|unestablished)$/;
605
+
606
+ /**
607
+ * The national registers a layer row's receipt names, as office codes, in the receipt's order. null when
608
+ * the receipt is not one `layerReceipt` wrote, or when it names a register of another layer: an EU-wide or
609
+ * international gap is a different sentence, and this one does not stretch to it. PURE.
610
+ */
611
+ export function nationalRegistersNotSearched(receipt) {
612
+ const entries = String(receipt ?? "").split("; ").filter(Boolean);
613
+ if (!entries.length) return null;
614
+ const offices = [];
615
+ for (const e of entries) {
616
+ const m = LAYER_RECEIPT_ENTRY_RE.exec(e);
617
+ if (!m || m[1] !== "national") return null;
618
+ offices.push(m[2]);
619
+ }
620
+ return offices;
621
+ }
622
+
623
+ const ORDER_FORM_NAMES = new Map([...OFFERED.regions, ...OFFERED.countries].map((t) => [t.code, t.name]));
624
+
625
+ /** A register or territory code in the order form's words, or "" when the form has no such code. PURE. */
626
+ export function orderFormName(code) {
627
+ return ORDER_FORM_NAMES.get(String(code ?? "").trim().toUpperCase()) ?? "";
628
+ }
629
+
630
+ /**
631
+ * "the national registers of A, B, and C were not searched", every name the order form's own, sorted. null
632
+ * when a code has no name: a list with a gap in it is the defect this replaces, so the row stays as it was. PURE.
633
+ */
634
+ export function nationalRegistersNote(offices) {
635
+ const names = (offices ?? []).map(orderFormName);
636
+ if (!names.length || names.some((n) => !n)) return null;
637
+ const sorted = [...new Set(names)].sort((a, b) => a.localeCompare(b, "en"));
638
+ if (sorted.length === 1) return `the national register of ${sorted[0]} was not searched`;
639
+ const list = sorted.length === 2 ? `${sorted[0]} and ${sorted[1]}`
640
+ : `${sorted.slice(0, -1).join(", ")}, and ${sorted[sorted.length - 1]}`;
641
+ return `the national registers of ${list} were not searched`;
642
+ }
643
+
644
+ /** Is this form row a binding-layer row (`buildCoverageForm`, stage 1)? PURE. */
645
+ export const isLayerRow = (r) => String(r?.row_id ?? "").startsWith("CL-") && r?.kind === "deferred";
646
+
588
647
  // ── M6 — THE ABSENCE IS AN ARTIFACT, NOT A MISSING ONE ──────────────────────────────────────────
589
648
  //
590
649
  // A run whose plan apparatus is out of reach can carry no coverage ROWS: there is no frozen plan to
@@ -25,7 +25,8 @@ import { classifyRecord, prepareTargets, SHAPE_TIERS, isLiveRecord, niceClassKey
25
25
  import { recordQids } from "../../named-band.mjs";
26
26
  import { normalizeRecordUri } from "../../registry-fidelity.mjs";
27
27
  import { bandGoodsIndex, goodsFor, goodsWordCounter, goodsWordsMatched, rawGoodsCarried, untaggedIsEnglish, rowGoods } from "../../record-goods.mjs";
28
- import { recordGoodsEvidence, heldRecordProvenance, recordFetchOutcomes, readRunCallRows, goodsFromLabel } from "../../goods-evidence.mjs";
28
+ import { recordGoodsEvidence, heldRecordProvenance, recordFetchOutcomes, readRunCallRows, goodsFromLabel, registerPageLabel } from "../../goods-evidence.mjs";
29
+ import { savedStatusPages } from "../../saved-register-pages.mjs";
29
30
  import { DEFAULT_LEDGER_PATH } from "../../provider-usage.mjs";
30
31
 
31
32
  const RUN_DIR = process.env.CLEAROTRON_BAND_RUN_DIR || "";
@@ -301,9 +302,15 @@ const shapeGoodsTest = () => {
301
302
  testCache = { words, matched: goodsWordsMatched(words, { stems: true }) };
302
303
  return testCache;
303
304
  };
305
+ // THE REGISTER'S OWN PAGES THE RUN'S RESEARCH SAVED (saved-register-pages.mjs), read again at the start of each lookup
306
+ // and each record call, never once per server as the held bodies are: a stage's own research question can save a
307
+ // record's page after the stage's first lookup, and the stage reads it from its next one.
308
+ const statusPages = savedStatusPages(RUN_DIR);
309
+ let pagesNow = new Map();
304
310
  // The record's body first; where the run holds none, the statements the row carries, as the shape reads them
305
- // (`rowGoods`, a statement the register cut marked so); a row that carries its goods as one string stands in last.
306
- const goodsOfRow = (r) => goodsFor(goodsIndex(), r) ?? rowGoods(r)
311
+ // (`rowGoods`, a statement the register cut marked so, or continued from a saved page); a row that carries its goods as
312
+ // one string stands in last.
313
+ const goodsOfRow = (r) => goodsFor(goodsIndex(), r) ?? rowGoods(r, pagesNow)
307
314
  ?? (typeof r?.goods === "string" && r.goods.trim() ? [{ classes: [], text: r.goods.trim(), ...(untaggedIsEnglish(r?.record_id) ? {} : { en: false }) }] : null);
308
315
  // WHAT A RECORD'S GOODS REST ON, from the run's own files and its fetches, by the shared reader's one rule
309
316
  // (goods-evidence.mjs `recordGoodsEvidence`): the supporting evidence the record holds, never the last call made
@@ -386,6 +393,7 @@ function bandLookup(params = {}) {
386
393
  }
387
394
 
388
395
  const all = Array.isArray(band?.enumerated) ? band.enumerated : [];
396
+ pagesNow = statusPages();
389
397
  const hits = [];
390
398
  let matched = 0;
391
399
  for (const r of all) {
@@ -557,7 +565,8 @@ function bandRecord(params = {}) {
557
565
  const parsed = hit.miss !== "unparsable-uri";
558
566
  const key = normalizeRecordUri(uri) || normalizeRecordUri(`/${String(uri ?? "").trim().replace(/^\/+/, "")}`);
559
567
  const bandRow = parsed && key ? bandRowFor(key) : null;
560
- const statements = bandRow ? rowGoods(bandRow) : null;
568
+ if (bandRow) pagesNow = statusPages();
569
+ const statements = bandRow ? rowGoods(bandRow, pagesNow) : null;
561
570
  const fetched = parsed ? runEvidence().fetches : null;
562
571
  const fetch = fetched && key ? (fetched.get(key) ?? fetched.get(key.split("/").pop())) : null;
563
572
  const failed = Boolean(fetch?.failed && !fetch.ok);
@@ -572,7 +581,8 @@ function bandRecord(params = {}) {
572
581
  return { isError: true, text: `${why} ${rest}` };
573
582
  }
574
583
  const goodsLines = statements.map((g) => JSON.stringify({ class: g.classes.join(",") || null, text: g.text,
575
- goods_from: g.cut ? "search answer, cut by the register" : g.unknown ? "search answer, completeness not established" : "search answer" }));
584
+ goods_from: g.cut ? "search answer, cut by the register" : g.unknown ? "search answer, completeness not established"
585
+ : g.page ? registerPageLabel(g.page.question) : "search answer" }));
576
586
  const text = [why, ...goodsLines, rest].join("\n");
577
587
  const parts = splitAtLines(text, RESPONSE_CHARS);
578
588
  const wanted = Number(params.part ?? 1);
@@ -610,7 +620,7 @@ const GROUP_PAGES = process.env.CLEAROTRON_BAND_GROUPS === "1";
610
620
  // served the shape without them (the owner's ruling, 2026-10-14). Each is removed with the space before it, inside
611
621
  // its line, so no line moves and the line each listed mark is printed on, which `linesByPart` reads, still holds.
612
622
  // (band-shape.mjs `withoutPlacementOrders` removes them, with the shape's other placement-only orders and its group-page commands.)
613
- const LOOKUP_DESCRIPTION = "Look up enumerated records in this run's frozen register band (read-only; logged to the reading audit). Filters AND together: record_id (exact uri), owner (substring), nice_class, tier (identical|near-identical|same-family|other|unclassifiable — classified against the shape's frozen targets), qid (exact plan-entry id — the plan-execution ledger join; a record surfaced by several slices matches under EVERY one of them), query (the _query slice that surfaced the record), text (substring of mark_text), status (substring), live_only, goods (words: records whose goods contain any of them, as whole words, singular or plural; a record with no goods on file matches too), group (a, b, c, d, rest or no_goods: that list's lines in the shape's order, one per mark of an owner), limit (default 20, max 100), offset (default 0: where in the matching records or lines to start — a capped answer names the offset where the next page starts). On each record served, `goods_words` gives the client's goods words its goods hold, as the shape tests them (k of N: the words), or null where its goods cannot be read; `goods_from` says what those goods rest on: official record; official record, cut by the register; official record, completeness not established; official record, no goods listed; search answer; search answer, cut by the register; search answer, completeness not established; fetch failed; or nothing held. The goods text is in band_record. Matching un-enumerated crowd descriptors ride along so a lookup can never mistake a counted-only zone for a clean.";
623
+ const LOOKUP_DESCRIPTION = "Look up enumerated records in this run's frozen register band (read-only; logged to the reading audit). Filters AND together: record_id (exact uri), owner (substring), nice_class, tier (identical|near-identical|same-family|other|unclassifiable — classified against the shape's frozen targets), qid (exact plan-entry id — the plan-execution ledger join; a record surfaced by several slices matches under EVERY one of them), query (the _query slice that surfaced the record), text (substring of mark_text), status (substring), live_only, goods (words: records whose goods contain any of them, as whole words, singular or plural; a record with no goods on file matches too), group (a, b, c, d, rest or no_goods: that list's lines in the shape's order, one per mark of an owner), limit (default 20, max 100), offset (default 0: where in the matching records or lines to start — a capped answer names the offset where the next page starts). On each record served, `goods_words` gives the client's goods words its goods hold, as the shape tests them (k of N: the words), or null where its goods cannot be read; `goods_from` says what those goods rest on: official record; official record, cut by the register; official record, completeness not established; official record, no goods listed; search answer; search answer, cut by the register; search answer, completeness not established; the register's own page, saved by research question <N>; fetch failed; or nothing held. The goods text is in band_record. Matching un-enumerated crowd descriptors ride along so a lookup can never mistake a counted-only zone for a clean.";
614
624
  const LOOKUP_GROUP_CLAUSE = "group (a, b, c, d, rest or no_goods: that list's lines in the shape's order, one per mark of an owner), ";
615
625
  const LOOKUP_OFFSET_GROUPS = "offset (default 0: where in the matching records or lines to start — a capped answer names the offset where the next page starts)";
616
626
  const LOOKUP_OFFSET_BAND = "offset (default 0: where in the matching records to start — a capped answer names the offset where the next page starts)";
@@ -0,0 +1,18 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ //
4
+ // THE POSITIONS A CORRECTION HANDS ITS SAVE: the excluded positions its review flags name, for which the writer's save
5
+ // may add a finding (synthesis-record.mjs, `correctionPositions`). The driver writes them into the tool servers' env
6
+ // for that correction's dispatch (gather-config.mjs), and the save tool's server reads them there, never from the
7
+ // payload (recording-server.mjs). Their own module, so a server reading them imports nothing else.
8
+
9
+ /** Where a correction's positions reach the save tool's server. */
10
+ export const CORRECTION_POSITIONS_ENV = "CLEAROTRON_CORRECTION_POSITIONS";
11
+
12
+ /** The positions a server was handed, or null where it was handed none it can read: no correction's dispatch. PURE. */
13
+ export function correctionPositionsFrom(env = process.env) {
14
+ if (!env) return null;
15
+ let v;
16
+ try { v = JSON.parse(String(env.CLEAROTRON_CORRECTION_POSITIONS ?? "")); } catch { return null; }
17
+ return Array.isArray(v) && v.length && v.every((u) => typeof u === "string") ? v : null;
18
+ }
@@ -11,6 +11,7 @@ import { fileURLToPath } from "node:url";
11
11
  import { dirname, join } from "node:path";
12
12
  import { requireRegisterProvider } from "../../driver.config.mjs";
13
13
  import { ledgerPath, runRecordLogPath } from "../../../providers/_shared/ledger-path.mjs";
14
+ import { CORRECTION_POSITIONS_ENV } from "./correction-positions.mjs"; // the positions a correction hands its save
14
15
 
15
16
  const MCP_DIR = dirname(fileURLToPath(import.meta.url));
16
17
  const NODE = process.execPath;
@@ -849,7 +850,7 @@ export const claudeToolAnswerBytes = (env = process.env) =>
849
850
  // The mcp-config server env carries ONLY the per-run, non-secret values (session key + ledger paths +
850
851
  // agent + the run dir the band tools serve, and the answer size above). Creds (CORSEARCH_SESSION_KEY /
851
852
  // PERPLEXITY_API_KEY / EUIPO_*) are inherited from the engine env.
852
- function serverEnv({ sessionKey, agent, runDir, recordAxis, bandGroups = false }) {
853
+ function serverEnv({ sessionKey, agent, runDir, recordAxis, bandGroups = false, correctionPositions = null }) {
853
854
  const e = {};
854
855
  // — see buildGatherMcpConfig: a register server without a run is refused there, so by the time
855
856
  // the record-log line below runs, `runDir` is present for every config that could use it.
@@ -862,6 +863,9 @@ function serverEnv({ sessionKey, agent, runDir, recordAxis, bandGroups = false }
862
863
  // the server per turn so the acceptance boundary can refuse a payload naming any other index, which
863
864
  // turns O3c's measured 224/0 habit into a structure. Absent for every non-fan-out stage.
864
865
  if (recordAxis) e.CLEAROTRON_RECORD_AXIS = String(recordAxis);
866
+ // THE POSITIONS A CORRECTION'S FLAGS NAME, for which the writer's save may add a finding (synthesis-record.mjs,
867
+ // `correctionPositions`). The driver's answer for the correction it dispatches, and absent on every other dispatch.
868
+ if (Array.isArray(correctionPositions) && correctionPositions.length) e[CORRECTION_POSITIONS_ENV] = JSON.stringify(correctionPositions);
865
869
  // — THE RUN'S REGISTER, so a recording tool gates a record link at the call as verify.mjs gates the
866
870
  // saved file (record-origins.mjs). Handed over explicitly: Codex gives a server only its own `env` and
867
871
  // the names it forwards, so a value left to inheritance reaches a Claude server and never a Codex one.
@@ -915,7 +919,7 @@ export function withSendUntil(mcpConfigJson, sendUntilMs) {
915
919
  return JSON.stringify(cfg);
916
920
  }
917
921
 
918
- export function buildGatherMcpConfig(groups = [], { sessionKey, agent, runDir, recordAxis, bandGroups = false } = {}) {
922
+ export function buildGatherMcpConfig(groups = [], { sessionKey, agent, runDir, recordAxis, bandGroups = false, correctionPositions = null } = {}) {
919
923
  const localKeys = new Set(), bridgeKeys = new Set();
920
924
  for (const g of groups) { const r = resolveGroup(g); r.local.forEach((k) => localKeys.add(k)); r.bridges.forEach((k) => bridgeKeys.add(k)); }
921
925
  const mcpServers = {};
@@ -945,7 +949,7 @@ export function buildGatherMcpConfig(groups = [], { sessionKey, agent, runDir, r
945
949
  + "belong to their run, and the box-global ledger is retired. Pass runDir.");
946
950
  }
947
951
  }
948
- const env = serverEnv({ sessionKey, agent, runDir, recordAxis, bandGroups });
952
+ const env = serverEnv({ sessionKey, agent, runDir, recordAxis, bandGroups, correctionPositions });
949
953
  for (const k of localKeys) mcpServers[k] = { command: NODE, args: [join(MCP_DIR, localEntry(k).script)], env };
950
954
  // — THE BRIDGES GET THE AUDIT ENV, AND ONLY THAT. Until now they were spawned with no env at
951
955
  // all, so a case-law tool call had nowhere to log: `tool-calls.jsonl` recorded server/tool/ok and the
@@ -37,6 +37,7 @@
37
37
  // same served-vs-granted delta as the record tools, pinned by the same census.
38
38
  import { serve } from "./stdio-server.mjs";
39
39
  import { recordSynthesis } from "../../synthesis-record.mjs"; // the writer
40
+ import { correctionPositionsFrom } from "./correction-positions.mjs"; // the positions a correction's dispatch hands its save
40
41
  import { recordRegisterDigest } from "../../register-digest-record.mjs"; // conversion 11 — the findings document
41
42
  import { FINDING_KEYS_CURRENT, COVERAGE_AREA_STATES } from "../../findings-model.mjs";
42
43
  import { recordBlindFrame } from "../../blind-frame-record.mjs";
@@ -234,7 +235,9 @@ async function record_synthesis(params) {
234
235
  // The intake asks, the plan-execution receipt and the frozen framework are read from the RUN by
235
236
  // `recordSynthesis` itself. They are not parameters and there is nothing to thread here: a seat that
236
237
  // could hand us its own receipt could waive its own coverage join.
237
- return recordSynthesis(runDir, params);
238
+ // THE CORRECTION'S POSITIONS ARE THE DRIVER'S AND ARE READ HERE, never taken from the payload: a seat that could name
239
+ // them could add a finding for any position it chose. Absent on every dispatch that is not a correction's.
240
+ return recordSynthesis(runDir, params, { correction: correctionPositionsFrom(process.env) });
238
241
  }
239
242
 
240
243
  async function search_run_artifacts(params) {
@@ -1098,13 +1101,13 @@ serve({
1098
1101
  findings_patch: {
1099
1102
  type: "array",
1100
1103
  description:
1101
- "A TARGETED CORRECTION, and the shape the repair prompts ask for. Send the complete corrected finding object(s), each carrying the `ordinal` of the finding it replaces, and send NOTHING else — no `findings[]` list, no `narrative` unless you also corrected a section, and a `findings` object only to carry the registers you changed or the \"corrections\" marker. The driver merges this patch into the last accepted record, keeps the values the patch does not replace, and renders both files. It cannot remove a finding: an ordinal names one to replace, and there is no way to express a deletion. Sending a `findings` document that carries its `findings[]` list instead REPLACES the record, which is how fifteen findings were lost once — if you mean to correct four findings, send four rows here, not a document containing four.",
1104
+ "A TARGETED CORRECTION. Send complete finding objects in `findings_patch`. To change an existing finding, use its current `ordinal`. To add a finding for an excluded position named in this correction's review flags, use a new `ordinal` after the highest in the current record and cite a record from that position. Include `narrative` only for sections you changed, and a `findings` object only for changed registers or the corrections marker. Do not send a `findings[]` list. The driver keeps everything the patch does not change. A patch does not delete findings; withdraw a finding using its existing disposition fields.",
1102
1105
  items: {
1103
1106
  type: "object",
1104
1107
  required: ["ordinal"],
1105
- description: "One complete finding object. `ordinal` is not optional here: it is the only thing that says WHICH finding this replaces, and a row without one has nowhere to land.",
1108
+ description: "One complete finding object. `ordinal` identifies the finding being changed or the new finding being added for a flagged excluded position.",
1106
1109
  properties: {
1107
- ordinal: { type: "number", description: "The ordinal of the finding this row replaces, exactly as it appears in the record you emitted. An ordinal this run does not hold is refused rather than appended — a patch corrects, it is not a way to add." },
1110
+ ordinal: { type: "number", description: "For an existing finding, use its current ordinal. For a new finding answering a review flag about an excluded position in this correction, use an unused positive whole number after the highest ordinal in the current record." },
1108
1111
  // ── — THE ROW IS A FINDING, AND THE SCHEMA NOW SAYS WHICH KEYS THAT MEANS ──
1109
1112
  //
1110
1113
  // The description above has always called this "one complete finding object" while the
@@ -726,7 +726,26 @@ const RATE_LIMIT_RE = /\b429\b|rate.?limit|usage limit|quota|too many requests|i
726
726
  // A SIGN-IN THAT CAN NO LONGER BE REFRESHED, in codex's own words (measured on a live install, 2026-09-11).
727
727
  // Narrow on purpose: a register provider's 401 or 403 can land in a stage's stderr too, and reading that as
728
728
  // the operator's codex login having expired would send them to sign in again for nothing.
729
- const REFRESH_FAILED_RE = /refresh token (?:has|was) already been used|access token could not be refreshed|failed to refresh token/i;
729
+ //
730
+ // A REFUSED RENEWAL ONLY: a 401 at renewal, or codex's words for a token spent, expired or revoked. 0.162.0
731
+ // says "Failed to refresh token status=401 …" and "Your access token could not be refreshed because …"; the
732
+ // live capture of 2026-09-11 said "Failed to refresh token: 401 Unauthorized: …already been used…". A bare
733
+ // "failed to refresh token" also matched every renewal that failed for a passing reason, because 0.162.0
734
+ // writes that line for each one: a 503, a dropped connection, and an outage the renewal recovered from
735
+ // within the same turn (measured offline, 2026-11-03). Read as a sign-out, each of those ended the stage's
736
+ // retries on its first attempt.
737
+ const REFRESH_FAILED_RE = /refresh token (?:has|was) already been used|access token could not be refreshed|failed to refresh token(?::| status=) ?401\b/i;
738
+ // …AND A RENEWAL THAT FAILED WITHOUT BEING REFUSED, which is not a sign-out: the line codex writes for any
739
+ // renewal attempt that did not succeed. Its own signal, read only where the refusal above is absent, so the
740
+ // run door can check again after a wait (engine/probe.mjs) while a stage retries as on any failed turn.
741
+ //
742
+ // READ ON A KILLED TURN TOO. On a dropped connection codex does not end the turn: it retries the renewal, 44
743
+ // times in the door's 60 s probe on one measured run, until the watchdog stops it. The stopped turn's text
744
+ // still names the renewal address, ".../oauth/token", and the door's sign-in pattern reads that `oauth` as a
745
+ // sign-out, so a signal kept off killed turns let the door refuse the job (measured offline on 0.162.0,
746
+ // 2026-11-03). The signal stays off wherever the refusal above appears, whatever ended the turn, so a 401
747
+ // stays a sign-out.
748
+ const REFRESH_ATTEMPT_FAILED_RE = /failed to refresh token/i;
730
749
 
731
750
  // A retry hint, WHEN THE MESSAGE HAPPENS TO CARRY ONE. Two anchored shapes and nothing clever: an
732
751
  // explicit timestamp, or a relative delay with a unit. Anything else yields undefined and the driver
@@ -805,6 +824,7 @@ function settleTuple({ r, ev, resumeRef }) {
805
824
  const rateLimitText = `${ev.turnFailed || ""}\n${ev.streamError || ""}\n${r.stderr || ""}`;
806
825
  const rateLimited = !killed && RATE_LIMIT_RE.test(rateLimitText);
807
826
  const signedOut = !killed && REFRESH_FAILED_RE.test(rateLimitText);
827
+ const refreshFailed = !REFRESH_FAILED_RE.test(rateLimitText) && REFRESH_ATTEMPT_FAILED_RE.test(rateLimitText);
808
828
  const resetsAt = rateLimited ? parseResetHint(rateLimitText) : undefined;
809
829
  return {
810
830
  code: killed ? 137 : (failed ? (r.rawCode || 1) : 0),
@@ -859,6 +879,9 @@ function settleTuple({ r, ev, resumeRef }) {
859
879
  // The engine's sign-in could not be refreshed: what the operator runs to fix it. The gateway names the
860
880
  // stage's failure with it.
861
881
  signedOut: signedOut ? "codex sign-in expired — run `codex login`, then start the search again" : undefined,
882
+ // A renewal attempt failed and was not refused, on a turn that ended or one the watchdog stopped. Read by the
883
+ // run door only; a stage's ladder treats the turn as any failed turn.
884
+ refreshFailed: refreshFailed || undefined,
862
885
  // Every tool call refused and none completed: codex's own sandbox on this host, and what fixes it. The
863
886
  // turn is still `ok` here; when the stage then fails, the gateway names its failure with this, as it
864
887
  // names a sign-in, instead of the missing file the refusal left behind.