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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/INSTALL.md +5 -5
  2. package/QUICKSTART.md +4 -4
  3. package/README.md +2 -2
  4. package/bin/README.md +3 -4
  5. package/bin/clearotron.mjs +1 -1
  6. package/bin/onboard.mjs +28 -40
  7. package/bin/status.mjs +11 -0
  8. package/build-info.json +2 -2
  9. package/docs/DELIVERY.md +30 -6
  10. package/docs/architecture/04-configuration-reference.md +1 -0
  11. package/driver/CHANGELOG.md +21 -0
  12. package/driver/compose-read.mjs +4 -3
  13. package/driver/contract-arm2-baseline.json +1 -2
  14. package/driver/contract-dictation-registry.mjs +7 -48
  15. package/driver/contract-e3-backlog.mjs +55 -52
  16. package/driver/contract-e3-baseline.json +22 -7
  17. package/driver/contract-vocabulary.mjs +4 -2
  18. package/driver/coverage-form.mjs +4 -0
  19. package/driver/coverage-rows-run.mjs +68 -4
  20. package/driver/engine/anthropic-agent.mjs +10 -13
  21. package/driver/engine/common.mjs +34 -22
  22. package/driver/engine/health.mjs +251 -0
  23. package/driver/engine/jx-turn.mjs +2 -1
  24. package/driver/engine/mcp/codex-config.mjs +16 -1
  25. package/driver/engine/mcp/crowd-note.mjs +1 -1
  26. package/driver/engine/mcp/gather-config.mjs +34 -9
  27. package/driver/engine/mcp/perplexity-server.mjs +33 -23
  28. package/driver/engine/mcp/recording-server.mjs +67 -58
  29. package/driver/engine/mcp/unit-note-server.mjs +2 -0
  30. package/driver/engine/openai-agent.mjs +9 -24
  31. package/driver/engine/probe.mjs +24 -7
  32. package/driver/findings-model.mjs +54 -0
  33. package/driver/jx-units.mjs +139 -30
  34. package/driver/knockout-assess-record.mjs +2 -2
  35. package/driver/knockout-correction-check.mjs +119 -0
  36. package/driver/knockout-correction-record.mjs +1 -1
  37. package/driver/knockout-frame-record.mjs +24 -10
  38. package/driver/knockout-review-record.mjs +35 -430
  39. package/driver/ladder/dispatch.mjs +4 -2
  40. package/driver/ladder/form-repair.mjs +5 -5
  41. package/driver/ladder/form-sync.mjs +4 -6
  42. package/driver/ladder/next-rung.mjs +10 -0
  43. package/driver/ladder/repair-messages.mjs +37 -65
  44. package/driver/ladder/stage.mjs +3 -3
  45. package/driver/ladder/turn-signals.mjs +4 -14
  46. package/driver/manual-paragraphs.mjs +22 -2
  47. package/driver/mark-logos.mjs +20 -5
  48. package/driver/package.json +1 -1
  49. package/driver/pipeline-knockout.mjs +2 -2
  50. package/driver/predelivery-lint.mjs +39 -7
  51. package/driver/product-fault.mjs +53 -0
  52. package/driver/publish/knockout.mjs +2 -1
  53. package/driver/publish/render.mjs +13 -7
  54. package/driver/recording-agreement.mjs +6 -4
  55. package/driver/register-band-run.mjs +2 -2
  56. package/driver/register-digest-record.mjs +31 -9
  57. package/driver/register-unit-record.mjs +10 -1
  58. package/driver/repair-composers.mjs +12 -11
  59. package/driver/repair-contract.mjs +6 -6
  60. package/driver/repair-targets.mjs +7 -6
  61. package/driver/run-outcome.mjs +8 -0
  62. package/driver/runner.mjs +42 -3
  63. package/driver/skills/README.md +5 -4
  64. package/driver/skills/blind-frame/SKILL.md +1 -1
  65. package/driver/skills/case-law-citation/SKILL.md +1 -1
  66. package/driver/skills/clearance-common-law/SKILL.md +6 -423
  67. package/driver/skills/clearance-common-law/grid.md +272 -0
  68. package/driver/skills/clearance-common-law/meaning.md +142 -0
  69. package/driver/skills/clearance-common-law/perplexity-prompts.md +4 -2
  70. package/driver/skills/clearance-register/SKILL.md +7 -174
  71. package/driver/skills/clearance-register/digest.md +89 -25
  72. package/driver/skills/clearance-register/providers/clarivate-questions.md +154 -0
  73. package/driver/skills/clearance-register/providers/clarivate.md +5 -149
  74. package/driver/skills/clearance-register/providers/signa-questions.md +120 -0
  75. package/driver/skills/clearance-register/providers/signa.md +3 -114
  76. package/driver/skills/clearance-register/providers/uspto-local.md +3 -3
  77. package/driver/skills/clearance-register/register-recipes.md +10 -10
  78. package/driver/skills/clearance-register/status-rules.md +2 -2
  79. package/driver/skills/clearance-register/unit.md +96 -54
  80. package/driver/skills/clearance-search/delivery-contract.md +11 -49
  81. package/driver/skills/clearance-search/firm-wide-reasoning.md +10 -13
  82. package/driver/skills/clearance-search/look-at-what-you-have.md +7 -0
  83. package/driver/skills/clearance-search/phase2-execution.md +12 -117
  84. package/driver/skills/clearance-search/report-card-rules.md +2 -2
  85. package/driver/skills/clearance-search/report-prose.md +30 -23
  86. package/driver/skills/clearance-search/synthesis-rules.md +27 -69
  87. package/driver/skills/clearance-search/worked-examples.md +11 -16
  88. package/driver/skills/clearance-variants/SKILL.md +7 -7
  89. package/driver/skills/clearance-variants/transliteration-scripts.md +2 -2
  90. package/driver/skills/frame-diff/SKILL.md +1 -1
  91. package/driver/skills/knockout-assess/SKILL.md +54 -41
  92. package/driver/skills/knockout-frame/SKILL.md +13 -12
  93. package/driver/skills/knockout-register-read/SKILL.md +2 -10
  94. package/driver/skills/matter-frame/SKILL.md +2 -2
  95. package/driver/skills/narrative-refutation/SKILL.md +7 -6
  96. package/driver/skills/placement-inquiry/SKILL.md +3 -3
  97. package/driver/skills/skeptic/SKILL.md +111 -0
  98. package/driver/skills/whatif-memo/SKILL.md +5 -2
  99. package/driver/stage-declarations.mjs +6 -0
  100. package/driver/stages-knockout.mjs +36 -38
  101. package/driver/stages.mjs +69 -64
  102. package/driver/steps/delivery.mjs +6 -4
  103. package/driver/steps/open-run.mjs +2 -0
  104. package/driver/steps/overview-and-cards.mjs +2 -2
  105. package/driver/steps/register-sweep.mjs +20 -1
  106. package/driver/steps/synthesis.mjs +28 -11
  107. package/driver/suite-census.json +213 -57
  108. package/driver/synthesis-record.mjs +24 -2
  109. package/driver/verify-knockout.mjs +23 -3
  110. package/driver/whatif-memo-run.mjs +39 -10
  111. package/driver/whatif-queue.mjs +53 -7
  112. package/mcp-server/CHANGELOG.md +4 -0
  113. package/mcp-server/lib/ops.mjs +19 -10
  114. package/mcp-server/lib/whatif.mjs +7 -6
  115. package/mcp-server/package.json +1 -1
  116. package/mcp-server/server.mjs +55 -19
  117. package/package.json +1 -1
  118. package/portal-ui/package.json +1 -1
  119. package/providers/clarivate/src/adapter.js +3 -0
  120. package/providers/jx/src/nativeread.js +5 -3
  121. package/providers/oauth-mcp-bridge/CHANGELOG.md +4 -0
  122. package/providers/oauth-mcp-bridge/package.json +1 -1
  123. package/providers/perplexity/src/core.js +7 -2
  124. package/providers/signa/src/adapter.js +3 -0
  125. package/scripts/e2e-first-time.mjs +2 -2
  126. package/shared/connector-signin-probe.mjs +1 -1
  127. package/shared/names-in-force.mjs +1 -0
  128. package/skills/clearotron-account/SKILL.md +21 -11
  129. package/skills/clearotron-client/SKILL.md +15 -15
  130. package/skills/clearotron-ops/COURIER.md +5 -1
  131. package/skills/clearotron-ops/SKILL.md +21 -14
@@ -19,7 +19,7 @@ import { statSync } from "node:fs";
19
19
  import { tmpdir } from "node:os";
20
20
  import { join, dirname } from "node:path";
21
21
  import { fileURLToPath } from "node:url";
22
- import { WRITE_DISCIPLINE, absolutizeSkillRefs, resolveSpawnCwd, spawnGraceMs, isRecordTool, stallMs, engineMaxBufferChars, startGovernedChild, governWatchdog, readGovernedStreams } from "./common.mjs"; // the child, its watchdog, its reader, and the stall and buffer limits both engines share
22
+ import { claudeTurnInstructions, FILE_OUTPUT, absolutizeSkillRefs, resolveSpawnCwd, spawnGraceMs, isRecordTool, stallMs, engineMaxBufferChars, startGovernedChild, governWatchdog, readGovernedStreams } from "./common.mjs"; // the child, its watchdog, its reader, and the stall and buffer limits both engines share
23
23
  import { resolveEngineProgram, resolveModel } from "../driver.config.mjs"; // — the one place that finds the program; it reads every spelling of the setting
24
24
  import { authorityTrees } from "../authority-trees.mjs";
25
25
  import { clearEngineChild } from "./child-record.mjs"; // the shared child (startGovernedChild) writes the record; this clears it at settle
@@ -195,7 +195,7 @@ export function claudeModel(model) {
195
195
  // ── thinking tier → `claude --effort` ────────────────────────────────────────────────────────────────
196
196
  // CANONICAL TABLE. `engine/openai-agent.mjs` carries the byte-equal twin for the tiers both vocabularies
197
197
  // can express, and `engine.anthropic.test.mjs` pins the two together — the same duplicate-plus-drift-test
198
- // discipline WRITE_DISCIPLINE already uses here (this module deliberately imports nothing but node
198
+ // discipline the output rules once used here (this module deliberately imports nothing but node
199
199
  // built-ins, so a shared leaf import is not on the table).
200
200
  //
201
201
  // LIVE VOCABULARY (claude 2.1.193 `--help`, checked 2026-08-03): `--effort` takes
@@ -226,8 +226,8 @@ export function mapUsage(u) {
226
226
  return { input, output, cacheRead, cacheWrite, total: input + output + cacheRead + cacheWrite };
227
227
  }
228
228
 
229
- // The Write-tool discipline and the skill-reference rewrite are shared with the Codex adapter: engine/common.mjs.
230
- export { WRITE_DISCIPLINE, absolutizeSkillRefs };
229
+ // The output rules and the skill-reference rewrite are shared with the Codex adapter: engine/common.mjs.
230
+ export { claudeTurnInstructions, absolutizeSkillRefs };
231
231
 
232
232
  // Returns { args, input }: `args` is the flag list with `-p` as a BARE flag (no positional prompt), and
233
233
  // `input` is the absolutized prompt to write to the child's STDIN. The prompt is NOT an argv element:
@@ -338,7 +338,7 @@ export const OWN_SEARCH_TOOLS = Object.freeze(["WebSearch"]);
338
338
  /** The program's tools that write a file. A result that comes back an error is a write that failed. */
339
339
  const FILE_WRITE_TOOLS = Object.freeze(["Write", "Edit", "MultiEdit", "NotebookEdit"]);
340
340
 
341
- export function buildClaudeArgs({ message, model, thinking, resumeRef, mcpConfig, allowedTools, builtinTools = null, maxBudgetUsd, cwd, skillsDir, skillsGrantRoots, profilesDir, resolveSkill, runDir, seatWrites = null, grantDispatch = null }) {
341
+ export function buildClaudeArgs({ message, model, thinking, resumeRef, mcpConfig, allowedTools, builtinTools = null, output = FILE_OUTPUT, maxBudgetUsd, cwd, skillsDir, skillsGrantRoots, profilesDir, resolveSkill, runDir, seatWrites = null, grantDispatch = null }) {
342
342
  const input = absolutizeSkillRefs(message, skillsDir, resolveSkill);
343
343
  const args = ["-p", "--output-format", "stream-json", "--verbose", "--include-partial-messages"];
344
344
  const m = claudeModel(model); if (m) args.push("--model", m);
@@ -349,12 +349,9 @@ export function buildClaudeArgs({ message, model, thinking, resumeRef, mcpConfig
349
349
  // Stages WRITE their output file; acceptEdits auto-approves Write/Edit in non-interactive -p (Read is
350
350
  // always allowed). Gather tools (E3) ride --allowedTools so they never prompt either.
351
351
  args.push("--permission-mode", "acceptEdits");
352
- // OUTPUT DISCIPLINE (engine-localized; the shared stage prompts say "write your output to <path>" which
353
- // a workspace agent executes via its file tool, but claude -p tends to COMPOSE the output as text and
354
- // report "done" without ever calling Write — the matter-frame missing_file failures, 2026-06-16). Force
355
- // the Write-tool behaviour at the system-prompt level so EVERY stage's file actually lands, without
356
- // touching the shared stage prompts. Unconditional — no disable knob.
357
- args.push("--append-system-prompt", WRITE_DISCIPLINE);
352
+ // THE TURN'S OUTPUT RULE, by how it returns its result (common.mjs): its record tool, a file, or its reply, then the
353
+ // evidence rule. On every call, the resumed one included: a resumed turn returns its result the same way.
354
+ args.push("--append-system-prompt", claudeTurnInstructions(output));
358
355
  if (resumeRef) args.push("--resume", resumeRef); // warm-resume → reuses the prompt cache
359
356
  if (mcpConfig) { args.push("--mcp-config", mcpConfig, "--strict-mcp-config"); }
360
357
  if (allowedTools) args.push("--allowedTools", allowedTools);
@@ -498,9 +495,9 @@ export const anthropicAgentEngine = {
498
495
  writeBoundary: "enforced",
499
496
  // The id a turn's rows record as asked for: the tier through Claude's catalog, `opus` → `anthropic/claude-opus`.
500
497
  resolveModelId(model) { return resolveModel(model); },
501
- async runTurn({ message, model, thinking, timeoutSec, resumeRef, mcpConfig, allowedTools, builtinTools = null, cwd, skillsDir, skillsGrantRoots, profilesDir, resolveSkill, runDir, seatWrites = null, grantDispatch = null, stallSec, progressFiles, streamFile = null } = {}) {
498
+ async runTurn({ message, model, thinking, timeoutSec, resumeRef, mcpConfig, allowedTools, builtinTools = null, output = FILE_OUTPUT, cwd, skillsDir, skillsGrantRoots, profilesDir, resolveSkill, runDir, seatWrites = null, grantDispatch = null, stallSec, progressFiles, streamFile = null } = {}) {
502
499
  if (!message) throw new Error("anthropic-agent.runTurn: message is required");
503
- const { args, input, grantNote } = buildClaudeArgs({ message, model, thinking, resumeRef, mcpConfig, allowedTools, builtinTools, cwd, skillsDir, skillsGrantRoots, profilesDir, resolveSkill, runDir, seatWrites, grantDispatch });
500
+ const { args, input, grantNote } = buildClaudeArgs({ message, model, thinking, resumeRef, mcpConfig, allowedTools, builtinTools, output, cwd, skillsDir, skillsGrantRoots, profilesDir, resolveSkill, runDir, seatWrites, grantDispatch });
504
501
  // the cross-check speaks. Driver stderr is what an operator reads, and it is where the other
505
502
  // drift notices in this engine already land ([ledger], [env-aliases], [queue-watch]).
506
503
  if (grantNote) process.stderr.write(`${grantNote}\n`);
@@ -52,28 +52,40 @@ export const spawnGraceMs = () => Math.max(0, Number(process.env.CLEAROTRON_SPAW
52
52
  // runner crash. Default 64MB (gateway parity); CLEAROTRON_ENGINE_MAX_BUFFER shrinks it for tests.
53
53
  export const engineMaxBufferChars = () => Math.max(1024, Number(process.env.CLEAROTRON_ENGINE_MAX_BUFFER || 64 * 1024 * 1024));
54
54
 
55
- // ── Output discipline (Claude's on every turn; Codex's on a turn whose result goes through its recording tool) ──
56
- // The shared stage prompts say "write your output to <path>", which a workspace agent executes via its
57
- // file tool — but a headless coding CLI (`claude -p`, `codex exec`) tends to COMPOSE the output as text
58
- // and report "done" without ever calling the Write tool (the matter-frame missing_file failures,
59
- // 2026-06-16). This system-prompt directive forces the Write-tool behaviour so every stage's file lands.
60
- // The REPAIR EXCEPTION (2026-08-01) is part of the same directive because it corrects the same directive:
61
- // "write every required file via the Write tool (overwrite if it exists)" is right for producing a stage's
62
- // output and wrong for fixing one named defect in a 160 KB document that already passed its other checks.
63
- // Without this sentence a corrective turn retypes the whole file — measured at 3-4x the wall and tokens of
64
- // the patching attempt that actually passed (see repair-contract.mjs for the numbers). Kept byte-identical
65
- // with the anthropic-agent copy; engine.common.test.mjs pins that. A Codex turn that writes a file is given the
66
- // same obligation in its own terms instead, since it has no Write or Edit tool (openai-agent.mjs, CODEX_WRITE_RULE).
67
- export const WRITE_DISCIPLINE =
68
- "OUTPUT DISCIPLINE — read carefully: when the task instructs you to write output to an absolute file path, " +
69
- "you MUST create that file by CALLING THE WRITE TOOL with that exact path and the full content. Output you " +
70
- "place only in your text reply is DISCARDED and the task is scored as FAILED. Do the actual work, write every " +
71
- "required file via the Write tool (overwrite if it exists), and only THEN reply — with just the path(s) you " +
72
- "wrote and a 2-3 line summary. Never claim a file is written unless you invoked the Write tool to write it. " +
73
- "EXCEPTION — REPAIRS: when the task instructs you to FIX or CORRECT an EXISTING file, use the Edit tool and " +
74
- "change only what the correction names — a file corrected with the Edit tool counts as written. Rewriting a " +
75
- "whole file to fix a few lines risks degrading content that already passed. If the file does not exist, the " +
76
- "rule above stands: create it in full with the Write tool.";
55
+ // ── The output rule: one per turn, by how the turn returns its result, the same text on both engines ──
56
+ // A turn hands its result back one of three ways, and its stage's declaration says which (stage-declarations.mjs,
57
+ // `turnOutputOf`): through its record tool, which the driver writes the stage's files from; as a file it writes; or
58
+ // as its reply, which is read as it stands. Each way gets its own rule and no other. Claude carries it as its
59
+ // appended system prompt, Codex as its developer instructions, each followed by the evidence rule. A turn whose
60
+ // reply is its result carries no output rule: its prompt says what to reply.
61
+ // The file rule is design's, of 2026-11-21, character for character, first written for Codex and now carried by
62
+ // both engines. The record rule names the turn's own tool and what to do when the tool refuses a call: correct and call
63
+ // again, except after a product fault, which the turn is told not to repeat.
64
+ export const FILE_RULE =
65
+ "When the task asks you to write output to an absolute file path, use your file-writing operation to write the " +
66
+ "complete content at that exact path, replacing the previous content if necessary. Text in your reply is discarded. " +
67
+ "Write every required file and verify that it exists before reporting it as written. Reply with just the path or " +
68
+ "paths you wrote and a two- or three-line summary. When the task asks you to fix an existing file, edit only what " +
69
+ "the correction names. If the file is missing, create it in full.";
70
+ /** The rule for a turn that hands its result back through its record tool, named. PURE. */
71
+ export const recordRule = (tool) =>
72
+ `Return this step's result by calling \`${tool}\`. The driver writes this step's files from that call and does not ` +
73
+ "read your reply text or any file you write. If the tool refuses a call, correct what it names and call it again, " +
74
+ "unless it says the failure is a product fault. Do not stop until the tool accepts the call or reports a product fault.";
75
+ // The evidence rule, design's of 2026-11-24 for both engines. It names the tools a step is granted so a research step may
76
+ // still gather its evidence; a step held to its supplied evidence says so in its own task.
77
+ export const EVIDENCE_RULE =
78
+ "Use only evidence supplied for this task or obtained through the tools it authorizes, and work already accepted for this run.";
79
+ /** A turn that does not say how it returns its result writes a file, as every turn did before this rule had kinds. */
80
+ export const FILE_OUTPUT = Object.freeze({ kind: "file" });
81
+ /** The output rule for a turn, or null for a turn whose reply is its result. PURE. */
82
+ export function outputRule(output = FILE_OUTPUT) {
83
+ if (output?.kind === "reply") return null;
84
+ if (output?.kind === "record" && output.tool) return recordRule(output.tool);
85
+ return FILE_RULE;
86
+ }
87
+ /** What Claude appends to its system prompt for one turn: the output rule, then the evidence rule. PURE. */
88
+ export const claudeTurnInstructions = (output = FILE_OUTPUT) => [outputRule(output), EVIDENCE_RULE].filter(Boolean).join(" ");
77
89
 
78
90
  // ── Skill-ref absolutization (shared verbatim across engines) ────────────────────────────────────────
79
91
  // The shared stage prompts reference skills by the convention `skills/foo/SKILL.md` — a workspace agent
@@ -0,0 +1,251 @@
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
+ // engine/health.mjs — is the engine still able to answer when nobody is asking it anything?
4
+ //
5
+ // The run door proves the engine with one real turn before a clearance starts (engine/probe.mjs), and that is
6
+ // the only time it was proven. An install with no orders goes unproven for as long as it has none, and a
7
+ // sign-in that stops renewing in that time is found by the next order, which is then refused. Measured on a
8
+ // production install, 2026-11-25: its last successful run was three weeks earlier, its engine program still
9
+ // reported itself signed in, and the first order in that time was refused at the door with nobody told.
10
+ //
11
+ // So the same real turn also runs on its own: when the worker starts, after the installed build changes, and when
12
+ // the engine has had no successful call for longer than CLEAROTRON_ENGINE_CHECK_ROUTINE. It is judged exactly as the door judges
13
+ // it (judgeEngineTurn, probeVerdictLane): a configuration fault, which no search can get past, raises one
14
+ // alert, and anything the run's own park handles better (an overload, a spent quota) is logged.
15
+ //
16
+ // THE CLOCK IS THE LAST SUCCESSFUL CALL, not a calendar. Every turn the engine completes, a stage's or a
17
+ // check's, moves it, so a busy install never runs the routine check: its work is the proof.
18
+ //
19
+ // THE PRODUCT SENDS NOTHING (docs/DELIVERY.md). The alert is a packet in the outbox, for whatever drains it,
20
+ // and the same lines in the worker's log; `doctor` and `status` show the last failure until a check passes.
21
+
22
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
23
+ import { dirname, join } from "node:path";
24
+ import { config, DEFAULT_ENGINE_ID } from "../driver.config.mjs";
25
+ import { judgeEngineTurn, probeFailureText, probeVerdictLane } from "./probe.mjs";
26
+ import { writeOutboxPacket } from "../outbox.mjs";
27
+ import { note } from "../log.mjs";
28
+
29
+ /** The routine check's setting, and its value when unset. */
30
+ export const ROUTINE_SETTING = "CLEAROTRON_ENGINE_CHECK_ROUTINE";
31
+ export const ROUTINE_DEFAULT = "7d";
32
+ /**
33
+ * While a check is failing it runs again at most this often, not on every 90-second tick. A refused turn costs
34
+ * nothing and ends in seconds, and this is how soon `status` stops showing a failure the operator has fixed.
35
+ */
36
+ export const FAILING_RECHECK_MS = 15 * 60 * 1000;
37
+
38
+ const UNIT_MS = { h: 60 * 60 * 1000, d: 24 * 60 * 60 * 1000 };
39
+
40
+ /**
41
+ * A check interval as the settings file spells it: a whole number of hours or days (`12h`, `7d`, `30d`), or
42
+ * `off`. `{ ms }` for a duration, `{ ms: null }` for `off`, `null` for anything else.
43
+ */
44
+ export function parseCheckInterval(raw) {
45
+ const s = String(raw ?? "").trim().toLowerCase();
46
+ if (s === "off") return { ms: null };
47
+ const m = /^([1-9]\d*)([hd])$/.exec(s);
48
+ return m ? { ms: Number(m[1]) * UNIT_MS[m[2]] } : null;
49
+ }
50
+
51
+ /** The routine interval this environment sets: `{ ms, raw, invalid }`. An unreadable value runs at the default. */
52
+ export function routineInterval(env = process.env) {
53
+ const raw = String(env[ROUTINE_SETTING] ?? "").trim();
54
+ if (!raw) return { ms: parseCheckInterval(ROUTINE_DEFAULT).ms, raw: null, invalid: false };
55
+ const parsed = parseCheckInterval(raw);
56
+ return parsed ? { ms: parsed.ms, raw, invalid: false } : { ms: parseCheckInterval(ROUTINE_DEFAULT).ms, raw, invalid: true };
57
+ }
58
+
59
+ /** What a reader is told about a value the setting cannot take. The value is never quoted: a key pasted into the wrong setting would be printed. */
60
+ export const invalidIntervalText = () =>
61
+ `${ROUTINE_SETTING} holds a value that is not a duration; it takes a whole number of hours or days (12h, 7d, 30d) or off. The default, ${ROUTINE_DEFAULT}, is used.`;
62
+
63
+ // ── the record ────────────────────────────────────────────────────────────────────────────────────────
64
+ //
65
+ // TWO FILES PER ENGINE, BECAUSE THERE ARE TWO WRITERS. Every stage of every run writes the last-answer file; only
66
+ // a check writes the check file. One file would be read, changed and written back by both at once, and the one
67
+ // that wrote second would lose the other's field.
68
+
69
+ /** Where this install keeps its engine-check record. */
70
+ export const engineCheckDir = () => join(config.workspaceRoot, "engine-check");
71
+ const lastAnswerPath = (dir, engine) => join(dir, `${engine}.last-answer.json`);
72
+ const checkPath = (dir, engine) => join(dir, `${engine}.check.json`);
73
+ const engineOf = (id) => String(id || DEFAULT_ENGINE_ID).trim().toLowerCase();
74
+
75
+ function writeAtomic(path, value) {
76
+ const tmp = `${path}.${process.pid}.tmp`;
77
+ writeFileSync(tmp, JSON.stringify(value) + "\n");
78
+ renameSync(tmp, path);
79
+ }
80
+ function readJsonOrNull(path) {
81
+ try { return JSON.parse(readFileSync(path, "utf8")); } catch { return null; }
82
+ }
83
+
84
+ /**
85
+ * Record that the engine completed a turn. BEST-EFFORT: a stage that cannot write this must carry on, and the
86
+ * cost of a missed write is a routine check that runs sooner than it needed to.
87
+ *
88
+ * It does not create the work folder it records into. Every run's folder is inside that work folder, so a stage
89
+ * of a real run always finds it; a stage driven with none pointed at it records nothing rather than making one.
90
+ */
91
+ export function recordEngineAnswered(engine, { now = Date.now(), dir = engineCheckDir() } = {}) {
92
+ try {
93
+ if (!existsSync(dirname(dir))) return false;
94
+ mkdirSync(dir, { recursive: true });
95
+ writeAtomic(lastAnswerPath(dir, engineOf(engine)), { at: new Date(now).toISOString() });
96
+ return true;
97
+ } catch { return false; }
98
+ }
99
+
100
+ /** Did this turn reach the engine and come back? A clean exit the engine did not report as signed out. */
101
+ export const turnAnswered = (turn) => !!turn && turn.code === 0 && !turn.killed && !turn.signals?.signedOut;
102
+
103
+ /** When the engine last completed a turn, in epoch ms, or null. */
104
+ export function lastEngineAnswer(engine, { dir = engineCheckDir() } = {}) {
105
+ const t = Date.parse(readJsonOrNull(lastAnswerPath(dir, engineOf(engine)))?.at ?? "");
106
+ return Number.isFinite(t) ? t : null;
107
+ }
108
+
109
+ /** The last check's record, or null when this install has none. */
110
+ export const readEngineCheck = (engine, { dir = engineCheckDir() } = {}) => readJsonOrNull(checkPath(dir, engineOf(engine)));
111
+
112
+ // ── when the worker checks ────────────────────────────────────────────────────────────────────────────
113
+
114
+ /**
115
+ * Why a check is due now, or null. PURE.
116
+ *
117
+ * - `first`: this install has no record yet, on the upgrade that brings the check or on a fresh install. Setup's
118
+ * own turn and `doctor`'s are recorded nowhere, so neither is proof for this build.
119
+ * - `build`: the installed build is not the one last checked, so a deploy by any route is proven within a tick.
120
+ * - `recheck`: the last check failed, FAILING_RECHECK_MS or more ago, or the engine has completed a turn since,
121
+ * a stage's or the door's, which says it was fixed: the check confirms it and withdraws the alert.
122
+ * - `routine`: the engine has had no successful call for the routine interval. `off` turns this one off alone.
123
+ */
124
+ export function engineCheckDue({ now, build, intervalMs, lastAnswer, record }) {
125
+ if (!record) return "first";
126
+ if (record.ok === false) return now - Date.parse(record.at) >= FAILING_RECHECK_MS || (lastAnswer ?? 0) > Date.parse(record.at) ? "recheck" : null;
127
+ if (build && record.build && build !== record.build) return "build";
128
+ if (intervalMs == null) return null;
129
+ const since = Math.max(lastAnswer ?? 0, Date.parse(record.at) || 0);
130
+ return now - since >= intervalMs ? "routine" : null;
131
+ }
132
+
133
+ /**
134
+ * The record's first mark, written before an install's first check. A record folder that cannot take it would
135
+ * otherwise make every idle tick a real turn, each finding no record; false says so, and no call is made.
136
+ */
137
+ export function startEngineCheckClock(engine, { now = Date.now(), build = null, dir = engineCheckDir() } = {}) {
138
+ try {
139
+ mkdirSync(dir, { recursive: true });
140
+ writeAtomic(checkPath(dir, engineOf(engine)), { at: new Date(now).toISOString(), ok: null, build, reason: "first-seen" });
141
+ return true;
142
+ } catch { return false; }
143
+ }
144
+
145
+ // ── what the operator is told ─────────────────────────────────────────────────────────────────────────
146
+
147
+ /** The alert, in four lines. `verdict` is the probe's; its headline and fix are the probe's own sentences. */
148
+ export function engineCheckFailureText(verdict, at) {
149
+ const headline = String(verdict.headline ?? "").replace(/\.$/, "");
150
+ return [
151
+ `The engine check failed at ${new Date(at).toISOString().replace(/\.\d{3}Z$/, "Z")}: ${headline}.`,
152
+ "Searches using this engine cannot start until this is fixed.",
153
+ `To fix it: ${verdict.fix ?? "the engine's own message is in the worker's log."}`,
154
+ "Then run `clearotron doctor` to confirm.",
155
+ ].join("\n");
156
+ }
157
+
158
+ /**
159
+ * What `status` prints while the last check failed for a configuration fault: the alert's own lines, rebuilt from
160
+ * the record. Nothing once a check has passed, once the engine has completed a turn since (`lastAnswer`), or when
161
+ * the failure was not this install's to fix.
162
+ */
163
+ export function failedCheckLines(record, lastAnswer = null) {
164
+ if (record?.ok !== false || record.lane !== "configuration") return [];
165
+ if ((lastAnswer ?? 0) > Date.parse(record.at)) return [];
166
+ return engineCheckFailureText({ headline: record.headline, fix: record.fix }, Date.parse(record.at)).split("\n");
167
+ }
168
+
169
+ /** The packet's name in the outbox: one per engine, so a second failure replaces the first rather than queueing beside it. */
170
+ export const engineCheckPacketName = (engine) => `engine-check-${engineOf(engine)}.failed`;
171
+
172
+ /**
173
+ * Take back an alert nothing has collected yet. A fault already fixed must not be delivered later: whatever drains
174
+ * the outbox would tell the operator of a failure that no longer stands. Best-effort; one already collected is gone.
175
+ */
176
+ export function withdrawEngineCheckPacket(engine) {
177
+ try { rmSync(join(config.outboxDir, `${engineCheckPacketName(engine)}.pending`), { force: true }); return true; }
178
+ catch { return false; }
179
+ }
180
+
181
+ /**
182
+ * Run the check once and record it. Returns `{ verdict, lane, alerted, text }`.
183
+ *
184
+ * ONE ALERT PER FAILURE. A failed check whose previous check had already alerted for a configuration fault
185
+ * writes no second packet; a check that passes clears it and withdraws the packet if it is still waiting, so the
186
+ * next failure alerts again. Weather is logged
187
+ * and never alerted: "no search can run" is not true of an overload, and the run's park recovers from it.
188
+ */
189
+ export async function runEngineCheck({
190
+ env = process.env, reason = "routine", now = () => Date.now(), build = null, dir = engineCheckDir(),
191
+ judge = judgeEngineTurn, write = writeOutboxPacket, withdraw = withdrawEngineCheckPacket, log = note, wait,
192
+ } = {}) {
193
+ const engine = engineOf(env.CLEAROTRON_AI);
194
+ const previous = readEngineCheck(engine, { dir });
195
+ let verdict;
196
+ try { verdict = await judge({ env, ...(wait ? { wait } : {}) }); }
197
+ catch (e) { verdict = { ok: false, engine, mode: "probe-error", basis: "driver-bug", headline: "the engine check itself failed to run", fix: String(e?.message ?? e), detail: null }; }
198
+ const at = now();
199
+ const lane = probeVerdictLane(verdict);
200
+ let alerted = false, text = null;
201
+ if (verdict.ok) {
202
+ recordEngineAnswered(engine, { now: at, dir });
203
+ withdraw(engine);
204
+ log(`[engine-check] ${engine} answered (${reason})`);
205
+ } else if (lane === "configuration") {
206
+ text = engineCheckFailureText(verdict, at);
207
+ const already = previous?.ok === false && previous.lane === "configuration" && !!previous.alertedAt;
208
+ if (!already) {
209
+ alerted = !!write(engineCheckPacketName(engine), {
210
+ kind: "engine-check-failed", audience: "operator", engine, reason,
211
+ mode: verdict.mode, basis: verdict.basis, checkedAt: new Date(at).toISOString(),
212
+ headline: verdict.headline, fix: verdict.fix ?? null, text,
213
+ });
214
+ }
215
+ log(`[engine-check] ${engine} FAILED (${reason}, ${verdict.mode}/${verdict.basis})${already ? " — already alerted" : alerted ? " — alert written to the outbox" : " — the alert could not be written"}\n${text}${verdict.detail ? `\n engine said: ${verdict.detail}` : ""}`);
216
+ } else {
217
+ log(`[engine-check] ${engine} did not complete its turn (${reason}, ${verdict.mode}/${verdict.basis}), and this is not a fault this install can fix: logged, not alerted. ${probeFailureText(verdict)}`);
218
+ }
219
+ try {
220
+ mkdirSync(dir, { recursive: true });
221
+ writeAtomic(checkPath(dir, engine), {
222
+ at: new Date(at).toISOString(), ok: verdict.ok === true, lane, reason, build: build ?? previous?.build ?? null,
223
+ mode: verdict.mode ?? null, basis: verdict.basis ?? null, headline: verdict.headline ?? null, fix: verdict.fix ?? null,
224
+ alertedAt: verdict.ok ? null : alerted ? new Date(at).toISOString() : (lane === "configuration" ? previous?.alertedAt ?? null : null),
225
+ });
226
+ } catch { /* the check's verdict stands; the next tick checks again */ }
227
+ return { verdict, lane, alerted, text };
228
+ }
229
+
230
+ /**
231
+ * The worker's question on a tick with nothing to run: is a check due, and if so run it. Nothing on an install
232
+ * with no engine chosen. Returns the check's result, or `{ due: null }`.
233
+ *
234
+ * `starting`: the worker has just started, after a deploy, an upgrade or a restart, and checks whatever its
235
+ * record says, a failure an hour old included and no record at all: a restart is what an operator does after
236
+ * fixing the engine.
237
+ */
238
+ export async function maybeCheckEngine({ env = process.env, now = () => Date.now(), build = null, starting = false, dir = engineCheckDir(), run = runEngineCheck, log = note } = {}) {
239
+ if (!String(env.CLEAROTRON_AI ?? "").trim()) return { due: null };
240
+ const engine = engineOf(env.CLEAROTRON_AI);
241
+ const record = readEngineCheck(engine, { dir });
242
+ const interval = routineInterval(env);
243
+ if (interval.invalid) log(`[engine-check] ${invalidIntervalText()}`);
244
+ const due = starting ? "start" : engineCheckDue({ now: now(), build, intervalMs: interval.ms, lastAnswer: lastEngineAnswer(engine, { dir }), record });
245
+ if (!due) return { due: null };
246
+ if (!record && !startEngineCheckClock(engine, { now: now(), build, dir })) {
247
+ log(`[engine-check] the check's record folder ${dir} cannot be written, so the engine is not checked until it can be`);
248
+ return { due: null };
249
+ }
250
+ return { due, ...await run({ env, reason: due, now, build, dir }) };
251
+ }
@@ -170,7 +170,8 @@ export async function makeJxTurnRunner({
170
170
  vendor, authMode, cloud, engine: id,
171
171
  async turn({ prompt }) {
172
172
  let tuple;
173
- try { tuple = await runTurn({ message: prompt, model, thinking, timeoutSec, stallSec }); }
173
+ // Its reply is its result, so it carries no output rule (engine/common.mjs, outputRule).
174
+ try { tuple = await runTurn({ message: prompt, model, thinking, timeoutSec, stallSec, output: { kind: "reply" } }); }
174
175
  catch (e) {
175
176
  return { ok: false, cause: `the engine turn threw: ${String(e?.message ?? e).slice(0, 200)}`,
176
177
  model: null, vendor, authMode, cloud, engine: id, usage: { input: 0, output: 0 }, truncationObservable: false };
@@ -4,7 +4,7 @@
4
4
  // engine already builds, so gather-config.mjs stays byte-untouched (merge-safety) and codex reuses the
5
5
  // exact server/tool wiring. Two inputs, both produced today by the gateway gather block:
6
6
  import { fileURLToPath } from "node:url";
7
- import { dirname, join } from "node:path";
7
+ import { basename, dirname, join } from "node:path";
8
8
  import { tomlString } from "../../../shared/toml-string.mjs"; import { driverDir } from "../../run-record.mjs";
9
9
 
10
10
  // • mcpConfig — the claude-shaped JSON string `{mcpServers:{name:{command,args,env,connectionTimeoutMs?}}}`
@@ -77,6 +77,19 @@ export const CODEX_TOOL_ANSWER_BYTES = 36000;
77
77
  export const codexToolAnswerBytes = (env = process.env) =>
78
78
  Math.min(CODEX_TOOL_ANSWER_BYTES, Number(env.CLEAROTRON_TOOL_ANSWER_BYTES) || CODEX_TOOL_ANSWER_BYTES);
79
79
 
80
+ // THE RECORDING TOOLS' FIELD TEXT REACHES CODEX WHOLE. Codex compacts an MCP tool's input schema when it
81
+ // "exceeds this many UTF-8 bytes. The default is 5,000 bytes. Code Mode also uses an explicit value when
82
+ // rendering tool input types" (the vendor's configuration reference, `mcp_servers.<id>.tool_input_schema_max_bytes`).
83
+ // A compacted tool is shown to the model as its field names, types and enum values, with every field
84
+ // description gone; Claude is shown every description whatever the size. Measured in testing, 2026-11-25, on
85
+ // codex 0.162.0 with gpt-6.1-sol: a lookup of the recording tools showed the field text of each tool under the
86
+ // default and none of `record_synthesis`, `record_register_digest` or `record_knockout_assess`, which are over
87
+ // it; with 20,000 on the recording server it showed all three. Its tools are the ones measured over the
88
+ // default, so it alone is given the larger size, and a test holds every recording tool's schema under it.
89
+ export const CODEX_RECORDING_SCHEMA_BYTES = 20000;
90
+ const RECORDING_SERVER_SCRIPT = "recording-server.mjs";
91
+ const isRecordingServer = (s) => (s.args ?? []).some((a) => basename(String(a)) === RECORDING_SERVER_SCRIPT);
92
+
80
93
  // ── TOML value escaping (basic strings) ──────────────────────────────────────────────────────────────
81
94
  // One encoder for every TOML block the product writes; re-exported so this module's callers keep their import.
82
95
  export { tomlString };
@@ -180,6 +193,8 @@ export function renderCodexConfigToml({ mcpConfig, allowedTools, developerInstru
180
193
  // Per-call, and deliberately on EVERY server including the engine-local fetch one: the cap belongs to
181
194
  // the turn's budget, not to any one server's reputation for being slow.
182
195
  if (toolTimeout) lines.push(`tool_timeout_sec = ${toolTimeout}`);
196
+ // The recording tools' field text, shown whole (CODEX_RECORDING_SCHEMA_BYTES, above).
197
+ if (isRecordingServer(s)) lines.push(`tool_input_schema_max_bytes = ${CODEX_RECORDING_SCHEMA_BYTES}`);
183
198
  // A SERVER GRANTED WHOLE GETS NO LIST. On claude `mcp__<server>__*` means every tool that server
184
199
  // serves, and the case-law step's two bridges are granted that way (gather-config's `allowedToolsFor`).
185
200
  // codex matches `enabled_tools` by exact name, so the `["*"]` this once wrote named no tool, both
@@ -7,7 +7,7 @@
7
7
  // the unit's manual — so it carries facts only. How the unit decides on a crowd belongs where the unit reads its
8
8
  // results: a register server adds this line, as a block of its own beside the answer, to an answer that carries one.
9
9
 
10
- export const CROWD_NOTE = "A crowd is decided with the narrowing steps in unit.md, only as far as reading it would change what you "
10
+ export const CROWD_NOTE = "A crowd is decided with the narrowing steps in SKILL.md, only as far as reading it would change what you "
11
11
  + "tell the client; what stays a crowd is recorded with its count.";
12
12
 
13
13
  /**
@@ -843,21 +843,46 @@ export function withSendUntil(mcpConfigJson, sendUntilMs) {
843
843
  return JSON.stringify(cfg);
844
844
  }
845
845
 
846
- // THE ENGINE'S OWN BUILT-IN TOOLS a stage is started with, where a stage names them. Measured in testing, 2026-11-23, on Claude
847
- // readers: they used file read and tool search (and one search-in-files with no result), and the other built-in tools' definitions
848
- // were most of every call's starting context, about 14k tokens of 28k. A stage not named here keeps the engine's full set. Tool
849
- // search stays, or the tool servers' tools load in full on the first call. The tool servers' tools are the grant's, as before; this
850
- // names only the engine's own.
851
- // The rating, the review and the correction record through their tools and write no file; measured on the same runs, they used file
852
- // read, search-in-files, file match and tool search, and none of the other built-in tools.
846
+ // THE ENGINE'S OWN BUILT-IN TOOLS a stage is started with. Measured in testing, 2026-11-23, on Claude readers: they used
847
+ // file read and tool search (and one search-in-files with no result), and the other built-in tools' definitions were most of
848
+ // every call's starting context, about 14k tokens of 28k. Measured again, 2026-11-24, over the clearance stages' saved
849
+ // sessions: every stage used file read, search-in-files, file match and tool search, and the stages that write a file used
850
+ // file write and edit besides; the rest were never needed, and two subagent and messaging tools were called by stages that
851
+ // had no use for them. So a stage that records through its tool is started with those four, and a stage that writes a file
852
+ // with the two writing tools as well. Tool search stays, or the tool servers' tools load in full on the first call. The
853
+ // tool servers' tools are the grant's, as before; this names only the engine's own. A label with no declared stage keeps
854
+ // the engine's full set.
853
855
  const READ_AND_SEARCH = Object.freeze(["Read", "Grep", "Glob", "ToolSearch"]);
856
+ const READ_SEARCH_AND_WRITE = Object.freeze([...READ_AND_SEARCH, "Write", "Edit"]);
857
+ // Named where a stage's own grant differs: the register reader uses file read and tool search alone, and the case-law
858
+ // stage's grant holds the engine's page fetch.
854
859
  const BUILTIN_TOOLS = Object.freeze({ "knockout-register-read": Object.freeze(["Read", "ToolSearch"]),
855
- "knockout-assess": READ_AND_SEARCH,
860
+ "case-law": Object.freeze([...READ_SEARCH_AND_WRITE, "WebFetch"]),
856
861
  // THE REVIEW AND THE CORRECTION ARE HANDED WHAT THEY CHECK, so a consult is one deliberate read: measured in testing, 2026-11-24,
857
862
  // with file search the review searched the run's files call after call, and each call carried everything before it.
858
863
  "knockout-review": Object.freeze(["Read", "ToolSearch"]), "knockout-correct": Object.freeze(["Read", "ToolSearch"]) });
859
864
  export function builtinToolsFor(stage) {
860
- return BUILTIN_TOOLS[String(stage ?? "").replace(/#\d+$/, "")] ?? null;
865
+ const declared = declaredStageOfLabel(stage);
866
+ if (!declared) return null;
867
+ return BUILTIN_TOOLS[declared] ?? (STAGE_DECLARATIONS[declared].recording ? READ_AND_SEARCH : READ_SEARCH_AND_WRITE);
868
+ }
869
+
870
+ /**
871
+ * The declared stage a dispatched label belongs to, the fanned recording labels included: `report-card:<n>` and
872
+ * `knockout-assess#<n>` belong to their base stage where its recording row declares that fan-out (toolGroupsForStage
873
+ * below). Null for a label no stage declares. PURE.
874
+ */
875
+ export function declaredStageOfLabel(label = "") {
876
+ const name = String(label ?? "");
877
+ const stage = declaredStageOf(name);
878
+ if (stage) return stage;
879
+ for (const [sep, flag] of SUFFIX_FORMS) {
880
+ const at = name.lastIndexOf(sep);
881
+ if (at <= 0) continue;
882
+ const base = name.slice(0, at);
883
+ if (RECORDING[base]?.[flag] && name.slice(at + 1) && STAGE_DECLARATIONS[base]) return base;
884
+ }
885
+ return null;
861
886
  }
862
887
 
863
888
  export function buildGatherMcpConfig(groups = [], { sessionKey, agent, runDir, recordAxis, bandGroups = false, correctionPositions = null,