clearotron 0.6.0 → 0.7.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/INSTALL.md +7 -4
  2. package/QUICKSTART.md +1 -0
  3. package/README.md +5 -2
  4. package/THIRD-PARTY-NOTICES.md +1 -1
  5. package/bin/clearotron.mjs +4 -2
  6. package/bin/onboard.mjs +158 -29
  7. package/build-info.json +2 -2
  8. package/docs/CLIENT-MCP.md +3 -1
  9. package/docs/DELIVERY.md +6 -3
  10. package/docs/architecture/02-architecture.md +1 -1
  11. package/docs/architecture/04-configuration-reference.md +105 -8
  12. package/docs/branding.md +4 -4
  13. package/docs/report-data/clearance-1.schema.json +320 -0
  14. package/docs/report-data/knockout-1.schema.json +268 -0
  15. package/driver/CHANGELOG.md +77 -0
  16. package/driver/cancel.mjs +19 -0
  17. package/driver/connotation-search.mjs +1 -1
  18. package/driver/contract-e3-backlog.mjs +41 -41
  19. package/driver/contract-vocabulary.mjs +1 -1
  20. package/driver/coverage-ledger.mjs +18 -2
  21. package/driver/deferral-row.mjs +1 -1
  22. package/driver/degraded-parts.mjs +1 -0
  23. package/driver/driver.config.mjs +5 -5
  24. package/driver/effective-scope.mjs +3 -1
  25. package/driver/engagement-receipt.mjs +3 -3
  26. package/driver/engine/anthropic-agent.mjs +15 -1
  27. package/driver/engine/common.mjs +7 -0
  28. package/driver/engine/mcp/band-server.mjs +7 -16
  29. package/driver/engine/mcp/codex-config.mjs +3 -0
  30. package/driver/engine/mcp/recording-server.mjs +45 -34
  31. package/driver/engine/openai-agent.mjs +74 -7
  32. package/driver/engine/session-record.mjs +44 -2
  33. package/driver/findings-model.mjs +14 -2
  34. package/driver/follow-up-twins.mjs +86 -0
  35. package/driver/gateway.mjs +77 -12
  36. package/driver/jx-units.mjs +3 -1
  37. package/driver/jx.mjs +13 -5
  38. package/driver/manuals-inline.mjs +98 -0
  39. package/driver/manuals-seen.mjs +134 -0
  40. package/driver/mark-logos.mjs +174 -0
  41. package/driver/methodology-witness.mjs +2 -1
  42. package/driver/owner-use-check.mjs +8 -4
  43. package/driver/package.json +1 -1
  44. package/driver/pipeline-knockout.mjs +23 -4
  45. package/driver/pipeline.mjs +128 -15
  46. package/driver/portal-local-auth.mjs +6 -2
  47. package/driver/portal-report.mjs +45 -14
  48. package/driver/portal-routes/me.mjs +4 -1
  49. package/driver/portal-runs.mjs +19 -16
  50. package/driver/predelivery-lint.mjs +7 -5
  51. package/driver/profiles.mjs +4 -4
  52. package/driver/publish/README.md +9 -7
  53. package/driver/publish/email-conditions.mjs +22 -5
  54. package/driver/publish/evidence-words.mjs +21 -0
  55. package/driver/publish/index.mjs +304 -211
  56. package/driver/publish/knockout.mjs +297 -247
  57. package/driver/publish/office-record-links.mjs +11 -9
  58. package/driver/publish/page-shell.mjs +98 -0
  59. package/driver/publish/pool-admin.mjs +2 -2
  60. package/driver/publish/publish-inputs.mjs +4 -0
  61. package/driver/publish/regions.mjs +28 -3
  62. package/driver/publish/register-record-html.mjs +105 -0
  63. package/driver/publish/register-record.mjs +165 -0
  64. package/driver/publish/render-knockout.mjs +299 -671
  65. package/driver/publish/render.mjs +561 -492
  66. package/driver/publish/report-data.mjs +226 -13
  67. package/driver/publish/report-document.mjs +353 -0
  68. package/driver/publish/search-depth.mjs +88 -7
  69. package/driver/publish/shell.mjs +41 -1
  70. package/driver/publish/strings.mjs +810 -0
  71. package/driver/publish/templates/clearance-print.css +23 -0
  72. package/driver/publish/templates/knockout.css +224 -0
  73. package/driver/publish/templates/report.css +112 -53
  74. package/driver/publish/xlsx.mjs +158 -139
  75. package/driver/record-goods.mjs +42 -0
  76. package/driver/reference-score.mjs +4 -1
  77. package/driver/register-count.mjs +5 -1
  78. package/driver/register-reach.mjs +39 -0
  79. package/driver/registry-fidelity.mjs +155 -37
  80. package/driver/repair-composers.mjs +7 -3
  81. package/driver/repair-targets.mjs +4 -1
  82. package/driver/replay-archive.mjs +4 -3
  83. package/driver/run-delivered.mjs +14 -8
  84. package/driver/run-record.mjs +1 -0
  85. package/driver/runner.mjs +73 -29
  86. package/driver/scope-facts.mjs +27 -6
  87. package/driver/search-policy.mjs +9 -4
  88. package/driver/skills/clearance-search/report-prose.md +3 -0
  89. package/driver/skills/knockout-assess/SKILL.md +8 -0
  90. package/driver/stage-freshness.mjs +8 -5
  91. package/driver/stages.mjs +69 -43
  92. package/driver/steps/delivery.mjs +9 -5
  93. package/driver/steps/overview-and-cards.mjs +54 -15
  94. package/driver/steps/register-sweep.mjs +5 -4
  95. package/driver/steps/skeptic-and-follow-up.mjs +3 -2
  96. package/driver/steps/verdict-gate.mjs +35 -14
  97. package/driver/suite-census.json +579 -87
  98. package/driver/synthesis-record.mjs +4 -3
  99. package/driver/terminal-clamp.mjs +6 -1
  100. package/driver/withdrawn-rating.mjs +72 -0
  101. package/mcp-server/CHANGELOG.md +8 -0
  102. package/mcp-server/lib/audit-view.mjs +5 -2
  103. package/mcp-server/lib/brief.mjs +6 -2
  104. package/mcp-server/lib/evidence.mjs +94 -23
  105. package/mcp-server/lib/findings.mjs +19 -2
  106. package/mcp-server/lib/knockout.mjs +13 -4
  107. package/mcp-server/lib/scrub.mjs +1 -1
  108. package/mcp-server/package.json +1 -1
  109. package/mcp-server/server.mjs +22 -3
  110. package/package.json +4 -1
  111. package/portal-ui/dist/assets/{index-CYaO2ygd.js → index-BBlN4CYq.js} +238 -80
  112. package/portal-ui/dist/assets/{index-izLa9apq.css → index-CxAkJXIT.css} +25 -5
  113. package/portal-ui/dist/index.html +2 -2
  114. package/portal-ui/package.json +3 -3
  115. package/providers/_shared/ledger.mjs +30 -2
  116. package/providers/_shared/record-uri.mjs +15 -0
  117. package/providers/clarivate/src/adapter.js +11 -0
  118. package/providers/clarivate/src/core.js +17 -1
  119. package/providers/jx/src/core.js +4 -4
  120. package/providers/jx/src/judge.js +1 -3
  121. package/providers/jx/src/nativeread.js +1 -3
  122. package/providers/oauth-mcp-bridge/CHANGELOG.md +8 -0
  123. package/providers/oauth-mcp-bridge/package.json +1 -1
  124. package/scripts/README.md +147 -3
  125. package/scripts/added-reference-check.mjs +35 -7
  126. package/scripts/e2e-first-time.mjs +4 -4
  127. package/scripts/env-audit.mjs +16 -9
  128. package/scripts/freeze-example-run.mjs +3 -3
  129. package/scripts/mint-public-residue.mjs +3 -3
  130. package/scripts/mint-search-level-tags.mjs +61 -0
  131. package/scripts/mint-source-pin-census.mjs +89 -0
  132. package/scripts/release-note-required.mjs +65 -6
  133. package/scripts/test-durations-reporter.mjs +25 -0
  134. package/scripts/test-full.mjs +72 -18
  135. package/scripts/test-run.mjs +18 -1
  136. package/shared/brand.mjs +93 -6
  137. package/shared/inline-markdown.mjs +53 -0
  138. package/shared/names-in-force.mjs +0 -1
  139. package/shared/portal-tokens.mjs +2 -1
  140. package/shared/reference-guard-classes.mjs +43 -2
  141. package/shared/register-selection.mjs +8 -3
  142. package/shared/search-level-tags.json +25 -0
  143. package/shared/source-spans.mjs +91 -0
  144. package/shared/tools/derive-band-pairs.mjs +10 -0
  145. package/driver/own-rights.mjs +0 -83
  146. package/driver/use-check.mjs +0 -85
@@ -262,6 +262,8 @@ import { progressQuantity } from "./repairs.mjs";
262
262
  // SIBLING ARTIFACT rather than the fail string, because the fail string is cut at 160 chars.
263
263
  import { undispatchableFiringDirectives } from "./frame-diff-model.mjs";
264
264
  import { witnessStageMethodology, describeMethodologyDrift } from "./methodology-witness.mjs";
265
+ import { inlineManuals } from "./manuals-inline.mjs";
266
+ import { measureManualsSeen } from "./manuals-seen.mjs";
265
267
  // — the meaning-sweep form and its accumulator. Both PURE and acyclic: connotation-search.mjs
266
268
  // imports nothing, disposition-union.mjs imports only it, and neither reaches back here.
267
269
  import { parsePrRiskResults, connotationObligations, parseDispositionForm, CONNOTATION_FORM_TOKEN_SRC,
@@ -351,10 +353,11 @@ export function spentBudgetCleanly({ fail, killed, code, wall, derivedLimitSec }
351
353
  // — THE TOOL GAUGE, AND WHY NULL IS NOT ZERO HERE EITHER.
352
354
  //
353
355
  // `toolCalls` and `toolWaitMs` say how much of a turn was tool wait rather than generation. An engine
354
- // that cannot report them is NOT a turn that called no tools: `openai-agent` carries no tool references
355
- // at all, so every codex attempt is unmeasured. Writing 0 for those would make every codex turn read as
356
- // "called no tools", and a cross-engine comparison would then conclude tool wait is an Anthropic-only
357
- // phenomenon — from an instrument that had simply gone quiet.
356
+ // that cannot report them is NOT a turn that called no tools: `openai-agent` reports no whole-turn tool
357
+ // count, so a codex attempt's `toolCalls` is unmeasured. Writing 0 for it would make every codex turn read
358
+ // as "called no tools", and a cross-engine comparison would then conclude tool calls are an Anthropic-only
359
+ // phenomenon — from an instrument that had simply gone quiet. Its tool wait it does time, from when each
360
+ // tool item opens and closes in its stream (openai-agent.mjs, codexTiming).
358
361
  //
359
362
  // PRESENT AND NULL, never absent, which is this file's own house rule: a field written even when null
360
363
  // keeps "this engine cannot report" visibly different from "this record predates the gauge". The first
@@ -397,6 +400,14 @@ export function toolGauge(turn) {
397
400
  // model asked for. An OBJECT is a measurement (`{}`: none); null is "this engine cannot report".
398
401
  toolCallsByName: turn?.toolCallsByName && typeof turn.toolCallsByName === "object" && !Array.isArray(turn.toolCallsByName)
399
402
  ? { ...turn.toolCallsByName } : null,
403
+ // ms from spawn to the engine's first output, on both engines; null when it never spoke or cannot report. With
404
+ // `toolWaitMs` and `activeMs` it splits a turn into start-up, tool wait and work. RECORDING ONLY.
405
+ firstByteMs: n(turn?.firstByteMs),
406
+ // The first call's cache read and write in tokens, where the engine reports them (Claude), and how many times the turn
407
+ // searched for a tool to load (`ToolSearch`), read off its own per-name counts. null where the engine cannot say.
408
+ firstCallCache: turn?.firstCallCache && Number.isFinite(turn.firstCallCache.read) && Number.isFinite(turn.firstCallCache.creation)
409
+ ? { read: turn.firstCallCache.read, creation: turn.firstCallCache.creation } : null,
410
+ toolSearchCalls: turn?.toolCallsByName && typeof turn.toolCallsByName === "object" ? (turn.toolCallsByName.ToolSearch ?? 0) : null,
400
411
  };
401
412
  }
402
413
 
@@ -797,6 +808,7 @@ async function runStageLadder(name, opts, stageHome = null, engine = selectEngin
797
808
  let lastJson = null; // the failed attempt's parsed envelope — warm eligibility needs its status
798
809
  let lastKey = sessionKey; // the failed attempt's session key — the warm patch resumes exactly it
799
810
  let lastSessionRef = sessionKey; // the failed attempt's engine sessionRef — anthropic warm-resume (--resume) reuses it
811
+ let lastKillClass = null; // how the failed attempt's hard-wall kill read (killedWhile): a working one is resumed warm
800
812
  // statOf feeds the ONE artifact-state snapshot both the exit-1 rescue and AD-4's emitted-vs-landed
801
813
  // gauge read. It is taken PER ATTEMPT, just before the turn is dispatched — it used to be taken
802
814
  // once before the whole ladder, which is the cross-attempt rescue hole post-merge audit 2 found: a
@@ -873,7 +885,12 @@ async function runStageLadder(name, opts, stageHome = null, engine = selectEngin
873
885
  // lane: if attempt 2 comes back with rows ruled (`call_partial` — a seat that has now recorded
874
886
  // rulings), attempt 3 can still warm, which is the case warm is good at.
875
887
  const vetoedResume = vetoResumeRuledNone(attempt, lastUnion);
876
- const warm = attempt > 1 && !warmUsed && process.env.CLEAROTRON_WARM_RETRY !== "0" && !vetoedResume && warmEligible(lastFail, lastJson);
888
+ // A TURN STOPPED AT ITS HARD WALL WHILE STILL WORKING IS RESUMED, NOT RESTARTED. Its single extended retry (ladder/next-rung.mjs)
889
+ // continues the same session with the message design wrote, so an hour of work is not done again; a kill that was silent, or
890
+ // was only making its own record write, is retried fresh as before. The classification is killedWhile, below.
891
+ const timeoutResume = lastFail === "timeout" && lastKillClass === "working";
892
+ const warm = attempt > 1 && !warmUsed && process.env.CLEAROTRON_WARM_RETRY !== "0" && (timeoutResume || (!vetoedResume && warmEligible(lastFail, lastJson)));
893
+ const timeoutWarm = warm && timeoutResume;
877
894
  if (warm) warmUsed = true;
878
895
  else if (vetoedResume && !warmUsed && process.env.CLEAROTRON_WARM_RETRY !== "0" && warmEligible(lastFail, lastJson))
879
896
  note(`[${name}] attempt ${attempt - 1} left this stage's meaning population with ZERO ruled rows (${String(lastFail).slice(0, 100)}) — a resumed session re-reads its own output and cannot rule what it did not rule; SKIPPING the warm patch and dispatching attempt ${attempt} FRESH (the warm attempt is not spent: a partial failure later in this ladder still gets it)`);
@@ -913,8 +930,8 @@ async function runStageLadder(name, opts, stageHome = null, engine = selectEngin
913
930
  try { const fresh = refreshMessage(attempt); if (typeof fresh === "string" && fresh) base = fresh; }
914
931
  catch (e) { note(`[${name}] refreshMessage failed on attempt ${attempt}, dispatching the original text: ${String(e?.message ?? e).slice(0, 120)}`); }
915
932
  }
916
- const effMessage = warm ? warmPatchMessage(lastFail, files, { supplementalLane, adds }) : correctiveMessage(base, attempt, lastFail, files, { supplementalLane, adds });
917
- note(`[${name}] attempt ${attempt}/${maxRetries + 1}${warm ? " [warm patch]" : ""} (engine=${engine.name} agent=${agent} model=${model ?? "default"} key=${key} timeout=${effTimeout}s)`);
933
+ const effMessage = timeoutWarm ? warmTimeoutMessage(files) : warm ? warmPatchMessage(lastFail, files, { supplementalLane, adds }) : correctiveMessage(base, attempt, lastFail, files, { supplementalLane, adds });
934
+ note(`[${name}] attempt ${attempt}/${maxRetries + 1}${timeoutWarm ? " [warm resume: the timed-out turn was still working]" : warm ? " [warm patch]" : ""} (engine=${engine.name} agent=${agent} model=${model ?? "default"} key=${key} timeout=${effTimeout}s)`);
918
935
  // The engine runs ONE turn and returns the normalized tuple. Every adapter returns the same shape
919
936
  // (zero change); anthropic-agent = claude -p off-gateway with the stall-watchdog. A warm retry threads
920
937
  // the prior attempt's sessionRef so the engine resumes the SAME session (anthropic: via
@@ -938,7 +955,7 @@ async function runStageLadder(name, opts, stageHome = null, engine = selectEngin
938
955
  const dispatch = envGateOn("CLEAROTRON_DISPATCH_RECORD")
939
956
  ? recordDispatch(runDir, name, {
940
957
  attempt,
941
- kind: warm ? "warm-patch" : followup ? "followup" : attempt === warmEscalatedAt ? "fresh-escalation" : vetoedResume ? "fresh-total-defect" : attempt > 1 ? "corrective" : "fresh",
958
+ kind: timeoutWarm ? "warm-timeout" : warm ? "warm-patch" : followup ? "followup" : attempt === warmEscalatedAt ? "fresh-escalation" : vetoedResume ? "fresh-total-defect" : attempt > 1 ? "corrective" : "fresh",
942
959
  message: effMessage,
943
960
  // — THE RESOLVED GRANT, recorded beside the sha of the message it went out with. This is
944
961
  // the value handed to `engine.runTurn` below as `allowedTools`, not a re-derivation of it: a
@@ -953,13 +970,17 @@ async function runStageLadder(name, opts, stageHome = null, engine = selectEngin
953
970
  // precede its own settle, so they stay outside it.
954
971
  const dispatchedAt = Date.now();
955
972
  const mcpConfig = turnConfig(effTimeout); // this turn's copy, with its time to stop sending
956
- for (const line of describeMethodologyDrift(witnessStageMethodology(runDir, name, effMessage, engineResolveSkill)))
957
- note(`[${name}] ${line}`);
973
+ const witnessed = witnessStageMethodology(runDir, name, effMessage, engineResolveSkill);
974
+ for (const line of describeMethodologyDrift(witnessed)) note(`[${name}] ${line}`);
958
975
  // — the frozen judged-by set, hashed into THIS PROCESS'S MEMORY before the seat runs. Never
959
976
  // written to disk before the comparison, so the thing being watched cannot reach it. See
960
977
  // run-integrity.mjs for why it is not a manifest file and why the append-only journals are excluded.
961
978
  const integrityBefore = frozenSnapshot(runDir);
962
- const turn = await engine.runTurn({ agent, sessionKey: key, message: effMessage, grantDispatch: base, model, thinking, timeoutSec: effTimeout, resumeRef: warm ? lastSessionRef : undefined, stageHome, mcpConfig, allowedTools: gatherAllowedTools, seatWrites: gatherSeatWrites, skillsDir: engineSkillsDir, skillsGrantRoots: engineSkillsGrantRoots, profilesDir: profilesStoreDir, resolveSkill: engineResolveSkill, runDir, stallSec,
979
+ // THE STAGE'S MANUALS RIDE A FRESH SESSION'S OPENING MESSAGE (manuals-inline.mjs), for both engines alike. A resumed session
980
+ // already holds them, and its message names none. The dispatch record and the witness above keep the composed text.
981
+ const wire = warm || timeoutWarm ? { text: effMessage, inlined: [], missing: [] }
982
+ : inlineManuals(effMessage, { resolve: engineResolveSkill, skillsDir: engineSkillsDir });
983
+ const turn = await engine.runTurn({ agent, sessionKey: key, message: wire.text, grantDispatch: base, model, thinking, timeoutSec: effTimeout, resumeRef: warm ? lastSessionRef : undefined, stageHome, mcpConfig, allowedTools: gatherAllowedTools, seatWrites: gatherSeatWrites, skillsDir: engineSkillsDir, skillsGrantRoots: engineSkillsGrantRoots, profilesDir: profilesStoreDir, resolveSkill: engineResolveSkill, runDir, stallSec,
963
984
  progressFiles: files, // the no-progress watchdog's artifact-advance signal (anthropic-agent; other adapters ignore it)
964
985
  // The raw stream of this session, beside its dispatch record (engine/session-record.mjs). The engines
965
986
  // keep it while the disk has room and say on the tuple's `stream` what landed.
@@ -1245,6 +1266,8 @@ async function runStageLadder(name, opts, stageHome = null, engine = selectEngin
1245
1266
  if (killClass) killSeen = true;
1246
1267
  fail = nameTheFailure(fail, { usage, json, stdout: turn.stdout, stderr, signals: turn.signals, name,
1247
1268
  gauge: { modelMismatch, famRequested, famActual, modelRequested, modelActual } });
1269
+ // How a hard-wall kill read (killedWhile), once per attempt: both rows record it and the next rung reads it. null otherwise.
1270
+ const attemptKilledWhile = fail === "timeout" ? killedWhile(turn, stallSec ?? Number(process.env.CLEAROTRON_STALL_MS || 120000) / 1000) : null;
1248
1271
 
1249
1272
  // AD-4 house rule — both computed UNCONDITIONALLY, three-valued on purpose:
1250
1273
  // wrote: did THIS attempt move any expected artifact? true/false when the stage has expected files,
@@ -1450,6 +1473,10 @@ async function runStageLadder(name, opts, stageHome = null, engine = selectEngin
1450
1473
  // not left looking like an artifact problem. It names a fact; it moves no retry policy. See
1451
1474
  // `spentBudgetCleanly`.
1452
1475
  budgetSpentCleanly: spentBudgetCleanly({ fail, killed, code, wall, derivedLimitSec: derivedLimit?.sec }),
1476
+ killedWhile: attemptKilledWhile,
1477
+ // The share of each told manual this turn's model was shown, read off its saved stream (manuals-seen.mjs); null
1478
+ // where the stream cannot say. A resumed turn is shown only what it read after resuming, so read it beside `warm`.
1479
+ manualsSeen: measureManualsSeen(turn, witnessed.told, engine.name),
1453
1480
  // AD-4 emitted-vs-landed, UNCONDITIONAL (was success-only, which made a failed attempt's mid-write
1454
1481
  // artifact invisible): `output` = what LANDED on disk after this attempt (null when the stage has no
1455
1482
  // expected file); `wrote` = whether THIS attempt emitted it (see the computation above the runDir
@@ -1503,6 +1530,9 @@ async function runStageLadder(name, opts, stageHome = null, engine = selectEngin
1503
1530
  //: the spine carries the POINTER and the sha, not the text — enough to find the file and
1504
1531
  // to tell two attempts apart without opening either.
1505
1532
  dispatch: dispatch?.file ?? null, dispatchSha: dispatch?.sha ?? null,
1533
+ // The manuals this attempt's opening message carried, by name, size and sha, and any left to a read: what was sent
1534
+ // stays apart from what the session read with its tools afterwards.
1535
+ manualsInline: wire.inlined.length ? wire.inlined : undefined, manualsLeftToRead: wire.missing.length ? wire.missing : undefined,
1506
1536
  //: the spine carries the convergence pair too — the ladder's shape (25 → 9 → 9 vs
1507
1537
  // 29 → 11 → pass) is readable from run.jsonl alone, without joining the per-stage log.
1508
1538
  quantity, noChange: noChange || undefined,
@@ -1520,6 +1550,7 @@ async function runStageLadder(name, opts, stageHome = null, engine = selectEngin
1520
1550
  // …and the same fact on this row, because one of the two carrying it records half the runs and
1521
1551
  // reads as done. Three-valued and beside the numbers it is about. See `spentBudgetCleanly`.
1522
1552
  budgetSpentCleanly: spentBudgetCleanly({ fail, killed, code, wall, derivedLimitSec: derivedLimit?.sec }),
1553
+ killedWhile: attemptKilledWhile,
1523
1554
  formRepairs: formRepairsThisAttempt || undefined, //, see the stage row above
1524
1555
  });
1525
1556
  } catch { /* telemetry best-effort — never fail a turn over a journal line */ }
@@ -1535,6 +1566,7 @@ async function runStageLadder(name, opts, stageHome = null, engine = selectEngin
1535
1566
  lastKey = key;
1536
1567
  lastQuantity = quantity; //: rides the ladder's final return, so the run-level catch stamps the exact count
1537
1568
  lastSessionRef = turn.sessionRef ?? lastSessionRef; // anthropic warm-resume target for the next attempt
1569
+ lastKillClass = attemptKilledWhile;
1538
1570
  note(`[${name}] attempt ${attempt} FAILED: ${fail}${quantity === null ? "" : ` (count ${quantity}${noChange ? ", unchanged" : ""})`}`);
1539
1571
 
1540
1572
  // What the ladder does next after this failure — escalate, retry, break, or return — is ladder/next-rung.mjs.
@@ -1844,7 +1876,7 @@ const REPAIR_HINTS = [
1844
1876
  `${POSITION_REQUIRED_DISPOSITIONS.join(", ").replace(/, ([^,]+)$/, " AND $1")} alike (only a review-killed ${
1845
1877
  DISPOSITIONS.filter((d) => !POSITION_REQUIRED_DISPOSITIONS.includes(d)).map((d) => `"${d}"`).join(" / ")
1846
1878
  } finding is ` +
1847
- `outside this, and it carries "withdrawn_reason" instead). An off-field finding additionally carries ` +
1879
+ `outside this, and it carries "withdrawn_reason" instead). If the right stands and only its rating is withdrawn, because its goods wording cannot be used, also set "rating_withdrawn_ground": "goods-wording-unavailable". An off-field finding additionally carries ` +
1848
1880
  `"off_field_ground" = "different-field" (the goods do not meet — its own goods_proximity meter must then read ` +
1849
1881
  `"low") or "no-material-risk" (a clear win, carrying no field claim). A mark argued apart on sound, rhythm, ` +
1850
1882
  `orthography or connotation is "distinguished", never off-field. ` +
@@ -2805,6 +2837,39 @@ export function warmEligible(fail, json) {
2805
2837
  return json?.status === "ok" && WARM_ELIGIBLE_RE.test(fail ?? "");
2806
2838
  }
2807
2839
 
2840
+ /**
2841
+ * How a turn stopped at its hard wall read when it was stopped: "working" when it asked for a tool other than its own record
2842
+ * write within the stage's last stall window, "record-only" when its only asks there were that write, "silent" when it asked
2843
+ * for none, and null for anything that is not a hard-wall kill or a turn whose engine could not say. The window is the stage's
2844
+ * own `stallSec`, 120 s where it sets none, read back from the end of the turn. Measured before this was built, over saved
2845
+ * hard-wall kills: 10 of 14 on production and 18 of 24 on a test machine were working. PURE.
2846
+ */
2847
+ export function killedWhile(turn, stallSec) {
2848
+ if (!turn?.killed || !turn?.signals?.hardWall || turn?.signals?.stalled) return null;
2849
+ const asked = turn.lastToolAsk;
2850
+ const wallMs = Number(turn.wall) * 1000;
2851
+ if (!asked || !Number.isFinite(wallMs)) return null;
2852
+ const windowMs = (Number.isFinite(stallSec) && stallSec > 0 ? stallSec : 120) * 1000;
2853
+ const within = (ms) => Number.isFinite(ms) && wallMs - ms <= windowMs;
2854
+ return within(asked.workMs) ? "working" : within(asked.recordMs) ? "record-only" : "silent";
2855
+ }
2856
+
2857
+ /**
2858
+ * What a session resumed after a working hard-wall kill reads: design's words, with the stage's own closing tail, the record
2859
+ * tool's for a tool-written stage and the whole-file write for any other. Approved word for word. PURE.
2860
+ */
2861
+ export function warmTimeoutMessage(expectFile) {
2862
+ const files = (Array.isArray(expectFile) ? expectFile : [expectFile]).filter(Boolean);
2863
+ const names = files.map(rel).join(", ");
2864
+ const toolWritten = files.length ? toolWrittenArtifact(files[0]) : null;
2865
+ const tail = toolWritten
2866
+ ? `Call \`${toolWritten.tool}\` with the values from the work already in your context — never by writing or editing any file. Do not stop until the tool accepts the call.`
2867
+ : fullWriteTail(names || "the stage output");
2868
+ return `You are RESUMING your own session for this stage — your prior work and inputs are already in your context. Do NOT redo the work from scratch.\n` +
2869
+ `Your previous turn was stopped at the stage's time limit while you were still working. Everything you already recorded through the stage's tools is kept; do not record it again. Continue from the last step you completed, finish what remains, and then ` +
2870
+ tail + ` This attempt has a longer limit, but not an unlimited one: finish the remaining work rather than revisiting finished steps.`;
2871
+ }
2872
+
2808
2873
  // ── — THE FIRST RETRY IS ROUTED BY THE RUN'S OWN COUNTED STATE, NOT BY A TOKEN NAME ────────────
2809
2874
  //
2810
2875
  // Two m-seat failures in the same hour, on the same engine, with opposite correct answers:
@@ -39,6 +39,7 @@ import { kebab } from "./search-policy.mjs";
39
39
  import { SERP_PROVIDERS, JX_PROVIDERS } from "./driver.config.mjs";
40
40
  import { findGridLedgerViolations, findPlatformIdentityViolations } from "./common-law-receipts.mjs";
41
41
  import { paths, readJson } from "./run-record.mjs";
42
+ import { stopsWithTheRun } from "./cancel.mjs";
42
43
 
43
44
  export const MAX_UNIT_ATTEMPTS = 3; // degraded-unit retries across resumes (repairable, never terminal)
44
45
  export const SERP_TERM_CAP = 12; // terms per grid — 12 × 7 cells = 84 paid calls, the hard ceiling
@@ -287,7 +288,8 @@ export async function runJxSerpGrid(ctx, job, opts = {}, { runLog = () => {}, no
287
288
  // wall-clock deadline on top of the per-call transport timeout: past it, remaining cells become
288
289
  // honest "deadline exceeded" gaps (the floor logic then decides degraded-vs-done) — a stalled
289
290
  // provider can never stall the paid run it shadows.
290
- const { exec, source } = resolveSerpExecutor(opts, { mark: markName, lane });
291
+ const { exec: serpExec, source } = resolveSerpExecutor(opts, { mark: markName, lane });
292
+ const exec = stopsWithTheRun(run.runDir, `jx-serp-${lane}`, serpExec); // every paid call the code makes itself reads the stop first
291
293
  const callsLedger = join(jxDir(run.runDir), "serp-calls.jsonl");
292
294
  const sessionKey = `${runPrefix(run)}jx-serp-${lane}`;
293
295
  const outPath = join(jxDir(run.runDir), spec.output ?? `${lane}-grid.json`); // legacy absolute output_path is ignored — always run-local
package/driver/jx.mjs CHANGED
@@ -191,7 +191,7 @@ export function deriveLaneDepthVerdicts({ sidecar, slices } = {}) {
191
191
 
192
192
  const ran = deepRan.length ? "full" : candidatesState === "ran" ? "candidates" : null;
193
193
  const shortfall = asked === "full" && ran !== "full";
194
- let cause = null, why = null;
194
+ let cause = null, why = null, detail = null;
195
195
  if (shortfall) {
196
196
  // "The lane ran as a slice-1 candidate lane" is said only of a lane whose candidates ran: a lane
197
197
  // that ran nothing is not established, whatever this build carries for it.
@@ -202,15 +202,23 @@ export function deriveLaneDepthVerdicts({ sidecar, slices } = {}) {
202
202
  + `Only the candidate search ran; the deeper web search and native-language review were not performed.`;
203
203
  } else if (ran === null) {
204
204
  cause = "not-established";
205
- why = `${deep.length ? `the deep slice(s) ${deepStates.map((d) => `${d.name}=${d.state ?? "no record"}`).join(", ")} did not state that they ran, and ` : ""}`
205
+ // THE CLIENT READS THIS UNDER "LEFT OPEN" too: the owner's sentence (2026-11-18), in place of
206
+ // the record's own terms. What the record does say, slice by slice, stays beside it as `detail`, for the run
207
+ // record and whoever reads it. Not reported as candidates: that would be a claim no artifact supports.
208
+ why = `Whether the full-depth ${languageOfLane(lane)}-language search ran cannot be confirmed from this search's record, `
209
+ + `so it is treated as not done.`;
210
+ detail = `${deep.length ? `the deep slice(s) ${deepStates.map((d) => `${d.name}=${d.state ?? "no record"}`).join(", ")} did not state that they ran, and ` : ""}`
206
211
  + `slice 1 for this lane is ${candidatesState ?? "unrecorded"} — what this lane delivered CANNOT be established from `
207
- + `this run's own record. Not reported as candidates: that would be a claim no artifact supports.`;
212
+ + `this run's own record.`;
208
213
  } else {
209
214
  cause = "requested-full-ran-candidates";
210
- why = `asked for full and ran candidates only — ${deepStates.map((d) => `${d.name} ${d.state ?? "no record"}`).join(", ")}`;
215
+ // The owner's 2026-11-11 sentence pattern, ruled for this cause on 2026-11-18; the slices' own states stay as `detail`.
216
+ why = `A full-depth ${languageOfLane(lane)}-language search was requested, but only the candidate search ran; `
217
+ + `the deeper web search and native-language review were not performed.`;
218
+ detail = `asked for full and ran candidates only — ${deepStates.map((d) => `${d.name} ${d.state ?? "no record"}`).join(", ")}`;
211
219
  }
212
220
  }
213
- out[lane] = { asked, ran, shortfall, cause, why,
221
+ out[lane] = { asked, ran, shortfall, cause, why, ...(detail ? { detail } : {}),
214
222
  basis: "_driver/jx-lanes.json:lanes[].depth (asked) vs fold.slices (ran)" };
215
223
  }
216
224
  return out;
@@ -0,0 +1,98 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ //
4
+ // A STAGE'S MANUALS RIDE ITS OPENING MESSAGE. A stage message starts by telling the model which manuals to
5
+ // read ("First, read and follow exactly: …"), and every session then spent turns and tokens opening the same
6
+ // files with its own read tool: the same manual, re-read by each card, half and register unit of a run.
7
+ // Here the gateway puts each named manual's text into the message itself, in the order named and with the
8
+ // company's overrides applied, so the session starts holding them and two sessions of one stage send the
9
+ // same leading text. Design set the sentence and the order (2026-11-19): the manuals first, then the stage's own
10
+ // instructions and the run's material, as the message already has them.
11
+ //
12
+ // ONE PLACE, BOTH ENGINES. It runs in the gateway on the text handed to `engine.runTurn`, so the Claude and
13
+ // Codex adapters receive the same bytes by construction. Each adapter still rewrites `skills/…md` references
14
+ // to absolute paths afterwards, so a supporting file a manual points at stays readable by path.
15
+ //
16
+ // WHAT IT DOES NOT TOUCH:
17
+ // - a continuation: a resumed session already holds its opening message, so the gateway does not call this
18
+ // for a warm resume or a warm patch;
19
+ // - a manual that will not resolve or read: it stays named in today's read sentence, so the model meets
20
+ // the missing file exactly as before and the run's existing recovery sees it. No new way to fail;
21
+ // - the dispatch record and the methodology witness: both keep reading the composed message, the record
22
+ // of what the stage asked for. What this inlined is returned beside the text, for the run log.
23
+ import { createHash } from "node:crypto";
24
+ import { readFileSync } from "node:fs";
25
+ import { dirname, join } from "node:path";
26
+
27
+ /** The sentence that replaces the read instruction, word for word as design set it (2026-11-19). */
28
+ export const MANUALS_SENTENCE = "Apply the following manuals to this stage, in the order given.";
29
+
30
+ const READ_SENTENCE = "First, read and follow exactly: ";
31
+ const SKILL_REF = /(?<![\w/.])skills\/[A-Za-z0-9._/-]+\.md/g;
32
+ // The read sentence as stages compose it: `reads()` writes a comma list, and the two register stages write
33
+ // "… SKILL.md (the shared spine) then … unit.md (MODE A — UNIT)." It ends at the first full stop that
34
+ // follows a manual's name or its parenthesis.
35
+ const READ_SENTENCE_RE = /First, read and follow exactly: (.*?\.md(?: \([^)]*\))?)\.(?=\s|$)/;
36
+
37
+ /** Where a manual's text is, for the engine's resolver or, without one, the skills folder. null when neither. */
38
+ const locate = (ref, { resolve, skillsDir }) => (resolve ? resolve(ref) : skillsDir ? join(dirname(skillsDir), ref) : null);
39
+
40
+ /**
41
+ * The message with its read sentence replaced by the manuals' text, and what went in. PURE but for reading
42
+ * the manual files. Never throws: a manual that cannot be read is left to the read sentence.
43
+ *
44
+ * @returns {{ text: string, inlined: {ref: string, bytes: number, sha256: string}[], missing: string[] }}
45
+ */
46
+ export function inlineManuals(message, { resolve = null, skillsDir = null, read = (p) => readFileSync(p, "utf8") } = {}) {
47
+ const text = String(message ?? "");
48
+ const m = text.match(READ_SENTENCE_RE);
49
+ if (!m || (!resolve && !skillsDir)) return { text, inlined: [], missing: [] };
50
+ const refs = [...new Set(m[1].match(SKILL_REF) ?? [])];
51
+ const inlined = [], missing = [], blocks = [];
52
+ for (const ref of refs) {
53
+ let body = null;
54
+ try { const p = locate(ref, { resolve, skillsDir }); body = p ? read(p) : null; } catch { body = null; }
55
+ // A manual that cannot be read keeps its place in the order given, as a read of that one manual.
56
+ if (typeof body !== "string") { missing.push(ref); blocks.push(`${READ_SENTENCE}${ref}.`); continue; }
57
+ inlined.push({ ref, bytes: Buffer.byteLength(body), sha256: createHash("sha256").update(body).digest("hex") });
58
+ blocks.push(`=== MANUAL: ${ref} ===\n${body.replace(/\s+$/, "")}\n=== END MANUAL: ${ref} ===`);
59
+ }
60
+ if (!inlined.length) return { text, inlined: [], missing };
61
+ const parts = [MANUALS_SENTENCE, ...blocks];
62
+ // A sentence that continued on the same line (the register stages' exclusion) starts on its own line after the manuals.
63
+ const at = m.index + m[0].length;
64
+ const tail = text.slice(at).replace(/^ (?=\S)/, "\n\n");
65
+ return { text: text.slice(0, m.index) + parts.join("\n\n") + tail, inlined, missing };
66
+ }
67
+
68
+ // The engine adapters rewrite each `skills/…md` reference to an absolute path after this module runs, the block headers
69
+ // included, so a header names either form. The absolute form is joined with the platform's separator: on Windows the header
70
+ // reads `C:\…\skills\a\SKILL.md`, so a manual's name takes either separator.
71
+ const MANUAL_NAME = String.raw`\S*?skills[\\/][A-Za-z0-9._\\/-]+\.md`;
72
+ const BLOCK_RE = new RegExp(String.raw`=== MANUAL: (${MANUAL_NAME}) ===\n[\s\S]*?\n=== END MANUAL: \1 ===`, "g");
73
+ const LEFT_RE = new RegExp(String.raw`^\s*First, read and follow exactly: (${MANUAL_NAME})\.(?=\s|$)`);
74
+
75
+ /**
76
+ * The stage's own text from a message this module filled: the manual blocks taken out again, and the read
77
+ * sentence put back naming the same manuals in the same order, each as the message names it (relative, or absolute once
78
+ * an engine adapter has rewritten it). For a reader that must tell a stage's
79
+ * instructions from its manuals, as the mock engines do when they decide which stage they are answering.
80
+ * A message with no manual blocks comes back unchanged. PURE.
81
+ */
82
+ export function stageTextOf(message) {
83
+ const text = String(message ?? "");
84
+ const at = text.indexOf(MANUALS_SENTENCE);
85
+ if (at < 0) return text;
86
+ const refs = [];
87
+ let end = at + MANUALS_SENTENCE.length;
88
+ // The blocks, and a read sentence in the place of each manual that could not be read, in the order given.
89
+ for (;;) {
90
+ BLOCK_RE.lastIndex = end;
91
+ const b = BLOCK_RE.exec(text);
92
+ if (b && /^\s*$/.test(text.slice(end, b.index))) { refs.push(b[1]); end = b.index + b[0].length; continue; }
93
+ const left = text.slice(end).match(LEFT_RE);
94
+ if (left) { refs.push(left[1]); end += left[0].length; continue; }
95
+ break;
96
+ }
97
+ return `${text.slice(0, at)}${READ_SENTENCE}${refs.join(", ")}.${text.slice(end)}`;
98
+ }
@@ -0,0 +1,134 @@
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
+ // HOW MUCH OF EACH MANUAL A STAGE WAS TOLD TO READ REACHED THE MODEL.
5
+ //
6
+ // methodology-witness.mjs records which manuals a stage is told to read, with the path and sha it resolved. It cannot say
7
+ // what the model saw of them. On Codex a long read loses its middle: the model is shown the first and last part of a tool
8
+ // output (engine/mcp/codex-config.mjs, CODEX_SHOWN_OUTPUT_BYTES). On Claude the model is shown what its Read calls
9
+ // returned. So after each attempt this reads the attempt's saved stream for the text the model was shown and records, per
10
+ // told manual, the share of the manual's lines that appear in it. Measured on saved streams before this was built
11
+ // (production, 2026-11-18): about a quarter of the told bytes of a Codex common-law half or register unit, and half of a
12
+ // report overview's, never reached the model under the cut.
13
+ //
14
+ // THE RULE, said once. A manual line counts when it holds 20 characters or more after its surrounding spaces are trimmed;
15
+ // it was seen when the same trimmed line appears in what the model was shown, after a line-number prefix (`cat -n`,
16
+ // `nl`, `grep -n`, Claude's Read) is taken off. A line repeated in a manual counts each time. The share is a lower bound
17
+ // on Codex, where the cut's size is the product's own measurement, not the vendor's.
18
+ //
19
+ // UNKNOWN IS null, NEVER 0. A stream that was not saved, was cut short, holds a line carrying a tool output that is not
20
+ // JSON before its last, or holds no event of the engine's own shape, says nothing about what was seen, and an engine this does not read is the
21
+ // same. A manual that changed since the stage was told it, or that holds no line long enough to count, is null on its
22
+ // own. Recording only, and it never throws: the attempt's result does not depend on it.
23
+ import { createHash } from "node:crypto";
24
+ import { readFileSync } from "node:fs";
25
+ import { CODEX_SHOWN_OUTPUT_BYTES } from "./engine/mcp/codex-config.mjs";
26
+ import { streamLines } from "./engine/session-record.mjs";
27
+
28
+ const MIN_CHARS = 20;
29
+ const NUMBERED = /^\s*\d+(?:\t|→|:)/;
30
+
31
+ /** The countable form of one line: its line-number prefix off, its spaces trimmed; null when too short to count. PURE. */
32
+ export function countable(line, { numbered = false } = {}) {
33
+ const raw = String(line ?? "");
34
+ const s = (numbered ? raw.replace(NUMBERED, "") : raw).trim();
35
+ return s.length >= MIN_CHARS ? s : null;
36
+ }
37
+
38
+ /** What a Codex model was shown of one output: all of it under the cut, else its first and last half of the cut. PURE. */
39
+ export function codexShown(output, cutBytes = CODEX_SHOWN_OUTPUT_BYTES) {
40
+ const b = Buffer.from(String(output ?? ""), "utf8");
41
+ if (b.length <= cutBytes) return b.toString("utf8");
42
+ const half = Math.floor(cutBytes / 2);
43
+ return `${b.subarray(0, half).toString("utf8")}\n${b.subarray(b.length - half).toString("utf8")}`;
44
+ }
45
+
46
+ // A synthesis stream runs to tens of megabytes, and this runs in the driver after every attempt: so a line is parsed only
47
+ // when it can carry what is read (measured 2026-11-18 on a 64 MB stream: 306 MB at peak when every line was parsed).
48
+ const READERS = {
49
+ // Codex: every command's output, under the cut. Its events are `thread.*`, `turn.*` and `item.*`.
50
+ "openai-agent": {
51
+ ours: /"type"\s*:\s*"(thread|turn|item)\./,
52
+ carries: (l) => l.includes('"command_execution"'),
53
+ read: (e, add, { cutBytes }) => {
54
+ if (e?.type === "item.completed" && e.item?.type === "command_execution") add(codexShown(e.item.aggregated_output, cutBytes));
55
+ },
56
+ },
57
+ // Claude: what each Read call returned, matched to the call by its id.
58
+ "anthropic-agent": {
59
+ ours: /"type"\s*:\s*"(system|assistant|user|result)"/,
60
+ carries: (l) => l.includes('"tool_use"') || l.includes('"tool_result"'),
61
+ read: (e, add, _opts, reads) => {
62
+ for (const c of Array.isArray(e?.message?.content) ? e.message.content : []) {
63
+ if (e.type === "assistant" && c?.type === "tool_use" && c.name === "Read") reads.add(c.id);
64
+ if (e.type === "user" && c?.type === "tool_result" && reads.has(c.tool_use_id))
65
+ add(typeof c.content === "string" ? c.content : Array.isArray(c.content) ? c.content.map((x) => x?.text ?? "").join("\n") : "");
66
+ }
67
+ },
68
+ },
69
+ };
70
+
71
+
72
+ const textLines = function* (text) { for (const l of String(text ?? "").split("\n")) yield Buffer.from(l); };
73
+
74
+ /**
75
+ * The countable lines a session showed its model, from its stream's lines as bytes, or null when the stream cannot say:
76
+ * no event of the engine's own shape, or a line that carries what is read and is not JSON before the last line (a killed
77
+ * turn may tear its last). Only such a line is parsed. PURE but for the lines it is handed.
78
+ */
79
+ function shownFrom(lines, engine, { cutBytes = CODEX_SHOWN_OUTPUT_BYTES } = {}) {
80
+ const reader = READERS[engine];
81
+ if (!reader) return null;
82
+ const set = new Set();
83
+ const add = (shown) => { for (const l of shown.split("\n")) { const c = countable(l, { numbered: true }); if (c) set.add(c); } };
84
+ const reads = new Set();
85
+ let ours = false, torn = false;
86
+ for (const line of lines) {
87
+ if (!line.toString("utf8", 0, 64).trim()) continue;
88
+ if (torn) return null;
89
+ if (!ours && reader.ours.test(line.toString("utf8", 0, 200))) ours = true;
90
+ if (!reader.carries(line)) continue;
91
+ let e;
92
+ try { e = JSON.parse(line.toString("utf8")); } catch { torn = true; continue; }
93
+ reader.read(e, add, { cutBytes }, reads);
94
+ }
95
+ return ours ? set : null;
96
+ }
97
+
98
+ /** The countable lines a session showed its model, from its stream's text; see shownFrom. PURE. */
99
+ export const shownLines = (streamText, engine, opts) => shownFrom(textLines(streamText), engine, opts);
100
+
101
+ const sha12 = (buf) => createHash("sha256").update(buf).digest("hex").slice(0, 12);
102
+
103
+ /**
104
+ * `{ [ref]: share }` for the told rows (methodology-witness.mjs), each share from 0 to 1 at three places, or null for a
105
+ * manual that changed since it was told or holds nothing countable; null in whole when `shown` is null. PURE but for
106
+ * `readManual`.
107
+ */
108
+ export function manualShares(told, shown, { readManual = (p) => readFileSync(p) } = {}) {
109
+ if (!shown || !Array.isArray(told)) return null;
110
+ const out = {};
111
+ for (const row of told) {
112
+ if (!row?.ref) continue;
113
+ let buf = null;
114
+ try { buf = row.path ? readManual(row.path) : null; } catch { buf = null; }
115
+ if (!buf || (row.sha && sha12(buf) !== row.sha)) { out[row.ref] = null; continue; }
116
+ const lines = String(buf).split("\n").map((l) => countable(l)).filter(Boolean);
117
+ out[row.ref] = lines.length ? Math.round((lines.filter((l) => shown.has(l)).length / lines.length) * 1000) / 1000 : null;
118
+ }
119
+ return out;
120
+ }
121
+
122
+ /**
123
+ * The attempt row's `manualsSeen`: the shares for what this turn was told, read from the stream the engine saved, or
124
+ * null when nothing was told or the stream cannot say. Never throws.
125
+ */
126
+ export function measureManualsSeen(turn, told, engine, { readManual } = {}) {
127
+ try {
128
+ if (!Array.isArray(told) || !told.length) return null;
129
+ const s = turn?.stream;
130
+ if (!s?.file || s.present !== true || s.reason) return null;
131
+ // A closed session's stream is gzipped and a killed one's is plain; the session record's own reader reads either.
132
+ return manualShares(told, shownFrom(streamLines(s.file), engine), readManual ? { readManual } : {});
133
+ } catch { return null; }
134
+ }