clearotron 0.7.0-beta.4 → 0.8.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/THIRD-PARTY-NOTICES.md +71 -2
  2. package/build-info.json +2 -2
  3. package/demo/multi-country-focus-search/run/common-law-grid.json +1 -1
  4. package/docs/CLIENT-MCP.md +17 -0
  5. package/docs/assets/README.md +19 -3
  6. package/docs/assets/portal-clearance-report.jpg +0 -0
  7. package/docs/assets/portal-conflict-landscape.jpg +0 -0
  8. package/docs/assets/portal-new-clearance.png +0 -0
  9. package/driver/CHANGELOG.md +162 -0
  10. package/driver/config-inventory.mjs +15 -2
  11. package/driver/dev-portal.mjs +2 -0
  12. package/driver/effort-model.mjs +34 -4
  13. package/driver/engine/CONTRACT.md +8 -0
  14. package/driver/engine/anthropic-agent.mjs +74 -16
  15. package/driver/engine/jx-turn.mjs +11 -3
  16. package/driver/engine/openai-agent.mjs +33 -7
  17. package/driver/engine/run-choices.mjs +28 -7
  18. package/driver/engine/speed.mjs +107 -0
  19. package/driver/enqueue-schema.mjs +8 -0
  20. package/driver/enqueue.mjs +14 -2
  21. package/driver/jx-units.mjs +2 -2
  22. package/driver/jx.mjs +1 -1
  23. package/driver/knockout-plain-language.mjs +96 -0
  24. package/driver/ladder/attempt-record.mjs +14 -2
  25. package/driver/ladder/dispatch.mjs +2 -2
  26. package/driver/ladder/form-repair.mjs +1 -1
  27. package/driver/ladder/stage.mjs +7 -1
  28. package/driver/mark-logos.mjs +6 -1
  29. package/driver/order-receipt.mjs +184 -0
  30. package/driver/package.json +4 -1
  31. package/driver/picture-shrink-worker.mjs +21 -0
  32. package/driver/picture-thumbnail.mjs +132 -0
  33. package/driver/pipeline-knockout.mjs +14 -0
  34. package/driver/portal-confirmation.mjs +3 -0
  35. package/driver/portal-report.mjs +44 -1
  36. package/driver/portal-routes/run.mjs +19 -9
  37. package/driver/portal-runs.mjs +118 -63
  38. package/driver/portal-service.mjs +17 -2
  39. package/driver/predelivery-lint.mjs +3 -3
  40. package/driver/progress.mjs +33 -5
  41. package/driver/publish/column-queries.mjs +86 -0
  42. package/driver/publish/index.mjs +4 -4
  43. package/driver/publish/knockout.mjs +35 -8
  44. package/driver/publish/page-shell.mjs +5 -1
  45. package/driver/publish/read-document.mjs +3 -0
  46. package/driver/publish/render-knockout.mjs +61 -16
  47. package/driver/publish/render.mjs +171 -30
  48. package/driver/publish/search-depth.mjs +45 -1
  49. package/driver/publish/strings.mjs +23 -0
  50. package/driver/publish/templates/report.css +73 -0
  51. package/driver/research-answers.mjs +17 -6
  52. package/driver/research-checks.mjs +22 -4
  53. package/driver/research-records.mjs +81 -0
  54. package/driver/run-quote.mjs +3 -0
  55. package/driver/run-speed.mjs +89 -0
  56. package/driver/runner.mjs +50 -21
  57. package/driver/saved-register-pages.mjs +23 -22
  58. package/driver/stage-freshness.mjs +5 -0
  59. package/driver/stages.mjs +2 -2
  60. package/driver/steps/open-run.mjs +12 -1
  61. package/driver/suite-census.json +199 -37
  62. package/driver/tokens.mjs +3 -0
  63. package/driver/urgent-count.mjs +54 -0
  64. package/driver/usage-ledger.mjs +8 -2
  65. package/driver/web-pictures.mjs +532 -0
  66. package/mcp-server/CHANGELOG.md +22 -0
  67. package/mcp-server/lib/document-reads.mjs +28 -0
  68. package/mcp-server/lib/events.mjs +21 -12
  69. package/mcp-server/lib/findings.mjs +2 -1
  70. package/mcp-server/lib/knockout.mjs +3 -2
  71. package/mcp-server/lib/ops.mjs +103 -6
  72. package/mcp-server/lib/options.mjs +4 -0
  73. package/mcp-server/lib/plan.mjs +38 -4
  74. package/mcp-server/lib/result-shapes.mjs +66 -0
  75. package/mcp-server/lib/runs.mjs +46 -44
  76. package/mcp-server/lib/urgent.mjs +29 -0
  77. package/mcp-server/package.json +1 -1
  78. package/mcp-server/result-shapes.json +2978 -0
  79. package/mcp-server/server.mjs +67 -14
  80. package/package.json +4 -1
  81. package/portal-ui/dist/assets/{index-qNDhqCw9.js → index-DEkVU2FD.js} +1909 -766
  82. package/portal-ui/dist/assets/{index-CxAkJXIT.css → index-W6SAoDkS.css} +238 -1
  83. package/portal-ui/dist/index.html +2 -2
  84. package/portal-ui/package.json +1 -1
  85. package/providers/jx/src/turn-envelope.mjs +3 -1
  86. package/providers/oauth-mcp-bridge/CHANGELOG.md +8 -0
  87. package/providers/oauth-mcp-bridge/package.json +1 -1
  88. package/providers/signa/src/core.js +54 -12
  89. package/scripts/README.md +3 -0
  90. package/scripts/e2e-first-time.mjs +2 -2
  91. package/scripts/mint-result-shapes.mjs +199 -0
  92. package/scripts/readme-pictures.mjs +227 -0
  93. package/scripts/render-check.mjs +4 -1
  94. package/scripts/report-sections-render-check.mjs +191 -0
  95. package/scripts/settings-render-check.mjs +68 -11
  96. package/shared/brand.mjs +8 -0
  97. package/skills/clearotron-account/SKILL.md +24 -0
  98. package/skills/clearotron-ops/SKILL.md +23 -9
@@ -20,7 +20,8 @@ import { tmpdir } from "node:os";
20
20
  import { join, dirname } from "node:path";
21
21
  import { fileURLToPath } from "node:url";
22
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
- import { resolveEngineProgram, resolveModel } from "../driver.config.mjs"; // — the one place that finds the program; it reads every spelling of the setting
23
+ import { resolveEngineProgram, resolveModel } from "../driver.config.mjs";
24
+ import { sessionSpeed } from "./speed.mjs"; // — whether this session's model can take the speed its run asks for // — the one place that finds the program; it reads every spelling of the setting
24
25
  import { authorityTrees } from "../authority-trees.mjs";
25
26
  import { clearEngineChild } from "./child-record.mjs"; // the shared child (startGovernedChild) writes the record; this clears it at settle
26
27
  import { engineEnv } from "./engine-env.mjs"; // — the program's environment, by list (see spawnEnv)
@@ -338,14 +339,17 @@ export const OWN_SEARCH_TOOLS = Object.freeze(["WebSearch"]);
338
339
  /** The program's tools that write a file. A result that comes back an error is a write that failed. */
339
340
  const FILE_WRITE_TOOLS = Object.freeze(["Write", "Edit", "MultiEdit", "NotebookEdit"]);
340
341
 
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
+ export function buildClaudeArgs({ message, model, thinking, speed = "standard", resumeRef, mcpConfig, allowedTools, builtinTools = null, output = FILE_OUTPUT, maxBudgetUsd, cwd, skillsDir, skillsGrantRoots, profilesDir, resolveSkill, runDir, seatWrites = null, grantDispatch = null }) {
342
343
  const input = absolutizeSkillRefs(message, skillsDir, resolveSkill);
343
344
  const args = ["-p", "--output-format", "stream-json", "--verbose", "--include-partial-messages"];
344
345
  const m = claudeModel(model); if (m) args.push("--model", m);
345
346
  args.push("--effort", effortFor(thinking));
346
- // FAST MODE REMOVED (2026-06-17): the Opus `--settings {"fastMode":true}` knob ~2.5×'d subscription-billed
347
- // usage and tripped the Claude 5-hour session cap mid-run (overage org-disabled → hard 429 → every stage
348
- // nonzero_exit_1). Reverted everywhere; HIGH effort is retained on the verdict/safety stages.
347
+ // THE SPEED is a setting, not a flag: `fastMode` in the one `--settings` value below (stageSettings), the vendor's
348
+ // unattended form (https://code.claude.com/docs/en/fast-mode, "Toggle fast mode": `claude -p --settings
349
+ // '{"fastMode": true}'`, v2.1.205 or later). Every session of an Urgent run asks for it where the model sent above has
350
+ // a faster setting (engine/speed.mjs, sessionSpeed); on any other model it is not asked for, so the model stays the
351
+ // one the stage chose, and the turn's record says why it ran at standard speed.
352
+ const sp = sessionSpeed({ ordered: speed, engine: "anthropic-agent", model: m });
349
353
  // Stages WRITE their output file; acceptEdits auto-approves Write/Edit in non-interactive -p (Read is
350
354
  // always allowed). Gather tools (E3) ride --allowedTools so they never prompt either.
351
355
  args.push("--permission-mode", "acceptEdits");
@@ -399,8 +403,8 @@ export function buildClaudeArgs({ message, model, thinking, resumeRef, mcpConfig
399
403
  const granted = rd.grant ? runDir : null;
400
404
  if (granted) args.push("--add-dir", granted);
401
405
  const boundary = writeBoundarySettings({ skillsRoots: grantRoots, profilesDir, runDir: granted });
402
- args.push("--settings", stageSettings(boundary));
403
- return { args, input, grantNote: rd.note };
406
+ args.push("--settings", stageSettings(boundary, { fast: sp.sent === "fast" }));
407
+ return { args, input, grantNote: rd.note, speed: sp };
404
408
  }
405
409
 
406
410
  /**
@@ -416,9 +420,13 @@ export function buildClaudeArgs({ message, model, thinking, resumeRef, mcpConfig
416
420
  */
417
421
  export const READ_FENCE = Object.freeze({ blockReadsOutsideWorkingDirectories: true });
418
422
 
419
- /** The one `--settings` value a turn carries: the read fence, and the write boundary's hook when there is one. */
420
- export function stageSettings(boundary) {
421
- return JSON.stringify({ permissions: { ...READ_FENCE }, ...(boundary ? JSON.parse(boundary) : {}) });
423
+ /**
424
+ * The one `--settings` value a turn carries: the read fence, the write boundary's hook when there is one, and the faster
425
+ * speed when the turn asks for it. One value, because the program reads one `--settings`: a second would replace the
426
+ * first, and the boundary with it.
427
+ */
428
+ export function stageSettings(boundary, { fast = false } = {}) {
429
+ return JSON.stringify({ permissions: { ...READ_FENCE }, ...(boundary ? JSON.parse(boundary) : {}), ...(fast ? { fastMode: true } : {}) });
422
430
  }
423
431
 
424
432
  /**
@@ -495,9 +503,9 @@ export const anthropicAgentEngine = {
495
503
  writeBoundary: "enforced",
496
504
  // The id a turn's rows record as asked for: the tier through Claude's catalog, `opus` → `anthropic/claude-opus`.
497
505
  resolveModelId(model) { return resolveModel(model); },
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 } = {}) {
506
+ async runTurn({ message, model, thinking, speed = "standard", timeoutSec, resumeRef, mcpConfig, allowedTools, builtinTools = null, output = FILE_OUTPUT, cwd, skillsDir, skillsGrantRoots, profilesDir, resolveSkill, runDir, seatWrites = null, grantDispatch = null, stallSec, progressFiles, streamFile = null } = {}) {
499
507
  if (!message) throw new Error("anthropic-agent.runTurn: message is required");
500
- const { args, input, grantNote } = buildClaudeArgs({ message, model, thinking, resumeRef, mcpConfig, allowedTools, builtinTools, output, cwd, skillsDir, skillsGrantRoots, profilesDir, resolveSkill, runDir, seatWrites, grantDispatch });
508
+ const { args, input, grantNote, speed: sent } = buildClaudeArgs({ message, model, thinking, speed, resumeRef, mcpConfig, allowedTools, builtinTools, output, cwd, skillsDir, skillsGrantRoots, profilesDir, resolveSkill, runDir, seatWrites, grantDispatch });
501
509
  // the cross-check speaks. Driver stderr is what an operator reads, and it is where the other
502
510
  // drift notices in this engine already land ([ledger], [env-aliases], [queue-watch]).
503
511
  if (grantNote) process.stderr.write(`${grantNote}\n`);
@@ -521,7 +529,7 @@ export const anthropicAgentEngine = {
521
529
  const pollMs = Math.max(50, Math.min(1000, Math.floor(Math.min(STALL, NOPROG) / 2))); // tight enough for fast tests, ≤1s in prod
522
530
  return await new Promise((resolve) => {
523
531
  // The turn's state, which every phase below reads and writes (the phases follow the adapter).
524
- const st = { resolve, resumeRef, cwd, runDir, progressFiles, streamFile, args, input, t0, STALL, NOPROG, MIN_RATE, WARMUP, hardMs, pollMs };
532
+ const st = { resolve, resumeRef, cwd, runDir, progressFiles, streamFile, args, input, t0, STALL, NOPROG, MIN_RATE, WARMUP, hardMs, pollMs, speed: sent.sent, standardBecause: sent.standardBecause };
525
533
  st.settle = (code) => settle(st, code); // declared before any phase, as the hoisted function it was
526
534
  if (!spawnTurn(st)) return;
527
535
  streamState(st);
@@ -597,6 +605,13 @@ function streamState(st) {
597
605
  // and no open message is a call of its own, as it always was.
598
606
  st.perMessage = new Map();
599
607
  st.openMessage = null; st.anonMessages = 0;
608
+ // SPEED GAUGE: the speed each API call reports it was served at (`usage.speed`), by message, as the usage above is.
609
+ // Read from the program's own output, never from what the turn asked for (engine/speed.mjs).
610
+ st.speedByMessage = new Map();
611
+ st.noteSpeed = (key, u) => { if (typeof u?.speed === "string" && u.speed) st.speedByMessage.set(key, u.speed); };
612
+ st.fastInit = null; // init's fast_mode_state and fast_mode_disabled_reason: the session's start
613
+ st.fastNotice = null; // the program's own notice about fast mode (out of usage credits), first one
614
+ st.sessionInit = null; // the session's id as init states it: what a turn killed before its result resumes
600
615
  st.foldUsage = (key, u) => {
601
616
  if (!u) return;
602
617
  const was = st.perMessage.get(key);
@@ -845,6 +860,19 @@ function lineParser(st) {
845
860
  else if (ev.type === "system" && ev.subtype === "init") {
846
861
  // MODEL GAUGE — the session's configured model, the earliest wire statement of what will run.
847
862
  if (typeof ev.model === "string" && ev.model && !isCliLabel(ev.model)) st.wireModelInit ??= ev.model;
863
+ st.fastInit ??= { state: ev.fast_mode_state ?? null, reason: ev.fast_mode_disabled_reason ?? null };
864
+ // THE SESSION'S ID, as the program states it when the session opens. The result event repeats it at the end, but a
865
+ // turn stopped at its time limit never sends one, and the warm resume of a turn stopped while working needs the id
866
+ // of the session to resume: handed the stage's own key instead, the program refuses it ("requires a valid session
867
+ // ID"), and the retry is spent on the refusal (measured in testing, 2026-11-26).
868
+ if (typeof ev.session_id === "string" && ev.session_id) st.sessionInit ??= ev.session_id;
869
+ }
870
+ // THE PROGRAM'S NOTICE ABOUT FAST MODE. Out of usage credits, it retries each fast request at standard speed and says so
871
+ // "on the message stream as a `system` message with subtype `notification`" (the vendor's fast-mode page, "Handle rate
872
+ // limits"). The first such notice is kept, bounded, as the row's reason.
873
+ else if (ev.type === "system" && ev.subtype === "notification") {
874
+ const text = [ev.text, ev.message, ev.notification, ev.title].find((x) => typeof x === "string" && x) ?? "";
875
+ if (!st.fastNotice && /fast/i.test(text)) st.fastNotice = text.slice(0, 300);
848
876
  }
849
877
  else if (ev.type === "assistant") {
850
878
  // MODEL GAUGE — the model that served THIS API call. Authoritative over init (see above).
@@ -897,7 +925,9 @@ function lineParser(st) {
897
925
  st.syncOpenAsk();
898
926
  // This block's usage, folded into its own call: the largest reading wins, so a block's early count
899
927
  // never replaces the delta's running total, and a second block of the same call adds nothing twice.
900
- st.foldUsage(ev.message?.id ?? st.openMessage ?? `__assistant_${++st.anonMessages}`, mapUsage(ev.message?.usage));
928
+ const usageKey = ev.message?.id ?? st.openMessage ?? `__assistant_${++st.anonMessages}`;
929
+ st.foldUsage(usageKey, mapUsage(ev.message?.usage));
930
+ st.noteSpeed(usageKey, ev.message?.usage);
901
931
  if (!st.firstCall && ev.message?.usage) st.firstCall = mapUsage(ev.message.usage);
902
932
  st.progress();
903
933
  }
@@ -937,9 +967,10 @@ function lineParser(st) {
937
967
  if (t === "message_start") {
938
968
  st.openMessage = ev.event.message?.id ?? `__start_${++st.anonMessages}`;
939
969
  st.foldUsage(st.openMessage, mapUsage(ev.event.message?.usage));
970
+ st.noteSpeed(st.openMessage, ev.event.message?.usage);
940
971
  st.progress();
941
972
  }
942
- else if (t === "message_delta") { st.foldUsage(st.openMessage ?? "__delta_without_start", mapUsage(ev.event?.usage)); st.progress(); }
973
+ else if (t === "message_delta") { st.foldUsage(st.openMessage ?? "__delta_without_start", mapUsage(ev.event?.usage)); st.noteSpeed(st.openMessage ?? "__delta_without_start", ev.event?.usage); st.progress(); }
943
974
  else if (t === "content_block_delta" || t === "content_block_start") st.progress();
944
975
  // THINKING GAUGE (partials): the earliest tells. Any one is sufficient; belt-and-braces so a
945
976
  // display-mode or CLI-version change cannot silently blind the gauge.
@@ -1250,11 +1281,13 @@ function wireStreams(st) {
1250
1281
  // Never the requested alias, and never init's answer for a turn only the CLI answered — see the
1251
1282
  // declaration above.
1252
1283
  modelWire: st.wireModelAssistant ?? (st.answeredItself ? null : st.wireModelInit),
1284
+ // SPEED GAUGE: what the turn asked for beside what the program reported serving (speedOfClaudeTurn).
1285
+ speed: speedOfClaudeTurn({ requested: st.speed, standardBecause: st.standardBecause, result: st.resultEvent, init: st.fastInit, calls: st.speedByMessage, notice: st.fastNotice }),
1253
1286
  // PROVIDER GAUGE: the program's own word for who served the turn, read from the result's per-model
1254
1287
  // usage ("firstParty" on Anthropic's own API and "foundry" on Azure Foundry, measured 2026-09-14),
1255
1288
  // or null when the stream never said or its models disagree. Recorded, never inferred from config.
1256
1289
  providerWire: providerOf(st.resultEvent),
1257
- sessionRef: st.resultEvent?.session_id ?? st.resumeRef ?? null,
1290
+ sessionRef: st.resultEvent?.session_id ?? st.sessionInit ?? st.resumeRef ?? null,
1258
1291
  // The raw result event's total_cost_usd is a provider-side field and stays in the provider's
1259
1292
  // own stream; the tuple carries no currency (tokens-only directive 2026-07-11) — `usage` is
1260
1293
  // the telemetry.
@@ -1282,6 +1315,31 @@ function wireStreams(st) {
1282
1315
  }
1283
1316
 
1284
1317
 
1318
+ /**
1319
+ * One turn's speed record: what it asked for and what the program reported serving. PURE.
1320
+ *
1321
+ * `served` is the result's `usage.speed`, the program's word for the turn; where the result says nothing, the calls'
1322
+ * own words decide it (`mixed` when they disagree), and null where none spoke. `calls` counts the turn's API calls by
1323
+ * the speed each reported, so a run can say how many of its calls ran fast. `state` and `disabledReason`
1324
+ * are the program's `fast_mode_state` and `fast_mode_disabled_reason` (measured on 2.1.295 and 2.1.326: `on`; `off` with
1325
+ * `sdk_opt_in_required` when the turn did not ask), and `notice` its own words when it ran a fast request at standard
1326
+ * speed for want of usage credits. `standardBecause` is why a session of a fast run asked for standard (engine/speed.mjs,
1327
+ * sessionSpeed), null otherwise. Nothing here is inferred from what the turn asked for.
1328
+ */
1329
+ export function speedOfClaudeTurn({ requested = "standard", standardBecause = null, result = null, init = null, calls = new Map(), notice = null } = {}) {
1330
+ const count = { fast: 0, standard: 0, unknown: 0 };
1331
+ for (const v of calls.values()) count[v === "fast" ? "fast" : v === "standard" ? "standard" : "unknown"]++;
1332
+ const reported = typeof result?.usage?.speed === "string" && result.usage.speed ? result.usage.speed : null;
1333
+ const fromCalls = count.fast && count.standard ? "mixed" : count.fast ? "fast" : count.standard ? "standard" : null;
1334
+ const served = reported ?? fromCalls;
1335
+ return {
1336
+ requested, standardBecause: standardBecause ?? null, served, basis: served ? "reported" : "unknown", calls: count,
1337
+ state: result?.fast_mode_state ?? init?.state ?? null,
1338
+ disabledReason: result?.fast_mode_disabled_reason ?? init?.reason ?? null,
1339
+ notice: notice ?? null,
1340
+ };
1341
+ }
1342
+
1285
1343
  function errResult(t0, e, resumeRef) {
1286
1344
  return {
1287
1345
  code: 1, killed: false, wall: (Date.now() - t0) / 1000, stdout: "",
@@ -83,7 +83,9 @@ export function readJxTuple(tuple, { vendor, authMode, cloud = null, engine }) {
83
83
  // the receipt names who did the native-language work, and an alias does not name anyone. Both adapters
84
84
  // populate it (anthropic-agent from the assistant/init events, openai-agent from `ev.model`).
85
85
  const model = tuple?.modelWire ?? null;
86
- const base = { model, vendor, authMode, cloud, usage, engine };
86
+ // The turn's speed record as the adapter wrote it: what it asked for, why standard where the run asked fast, and what
87
+ // the program reported serving. Null where no turn ran.
88
+ const base = { model, vendor, authMode, cloud, usage, engine, speed: tuple?.speed ?? null };
87
89
  // WHETHER TRUNCATION IS OBSERVABLE IS A FACT ABOUT THE ADAPTER, NOT ABOUT THIS TURN. It is keyed on the
88
90
  // engine deliberately: `anthropic-agent` writes `stopReason: r?.stop_reason` unconditionally, so the
89
91
  // KEY is present on every one of its turns whether or not the wire said anything — testing for the key
@@ -137,7 +139,13 @@ export async function makeJxTurnRunner({
137
139
  // machine's setting, read as below.
138
140
  runDir = null,
139
141
  } = {}) {
140
- const rec = runDir ? (await import("./run-choices.mjs")).readRunChoices(runDir) : { state: "none" };
142
+ const choices = runDir ? await import("./run-choices.mjs") : null;
143
+ const rec = choices ? choices.readRunChoices(runDir) : { state: "none" };
144
+ // THE RUN'S SPEED. A lane serving a run ordered Urgent asks for the faster setting as the run's stages do; the adapter
145
+ // sends it where the lane's model has one and records why where it does not (engine/speed.mjs). A turn that serves no
146
+ // run, the portal's brief reader, is not part of any order and runs at standard speed.
147
+ const { turnSpeed } = await import("./speed.mjs");
148
+ const speed = choices ? turnSpeed({ urgent: choices.urgentForRun(runDir) }) : "standard";
141
149
  if (rec.state === "unreadable") return { error: `this run's engine record ${rec.detail}, so ${lane} do not run on the machine's engine in its place` };
142
150
  if (rec.state === "recorded" && !ENGINE_BINARIES[rec.engine])
143
151
  return { error: `this run started on the "${rec.engine}" engine, which this driver does not ship; ${lane} keep that engine rather than switch` };
@@ -171,7 +179,7 @@ export async function makeJxTurnRunner({
171
179
  async turn({ prompt }) {
172
180
  let tuple;
173
181
  // 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" } }); }
182
+ try { tuple = await runTurn({ message: prompt, model, thinking, speed, timeoutSec, stallSec, output: { kind: "reply" } }); }
175
183
  catch (e) {
176
184
  return { ok: false, cause: `the engine turn threw: ${String(e?.message ?? e).slice(0, 200)}`,
177
185
  model: null, vendor, authMode, cloud, engine: id, usage: { input: 0, output: 0 }, truncationObservable: false };
@@ -31,6 +31,7 @@ import { join, dirname, sep } from "node:path";
31
31
  import { runStreamingChild, absolutizeSkillRefs, outputRule, FILE_OUTPUT, EVIDENCE_RULE, buildEnvelope, resolveSpawnCwd, isRecordTool } from "./common.mjs";
32
32
  import { renderCodexConfigToml } from "./mcp/codex-config.mjs";
33
33
  import { resolveAuthMode } from "./auth.mjs";
34
+ import { sessionSpeed } from "./speed.mjs"; // — whether this session's model can take the speed its run asks for
34
35
  import { engineEnv, codexCommandWithheld } from "./engine-env.mjs";
35
36
  import { resolveEngineProgram } from "../driver.config.mjs"; // — the one place that finds the program; it reads every spelling of the setting
36
37
 
@@ -432,15 +433,28 @@ export function codexProgramRoot(bin, home = homedir()) {
432
433
  const dir = dirname(real);
433
434
  return dir === home || home.startsWith(dir.endsWith(sep) ? dir : dir + sep) ? null : dir;
434
435
  }
435
- export function buildCodexArgs({ model, thinking, resumeRef, runDir } = {}) {
436
+ /**
437
+ * THE FASTER TIER, as two overrides on the call: `service_tier = "fast"` (Codex's config reference; the program sends
438
+ * it as the request's `priority` tier) and the feature switch that lets it ask. Measured on 0.162.0 against a local
439
+ * stand-in for the service, 2026-11-25: with both, the tier went out on the wire, with or without the user's own
440
+ * config; without them it did not. They sit among the global flags, before `resume`, so a resumed turn keeps its speed.
441
+ * A standard turn passes neither: the per-run CODEX_HOME holds this driver's config alone, so no user preference for the
442
+ * faster tier reaches it.
443
+ */
444
+ export const CODEX_FAST_OVERRIDES = Object.freeze(["-c", 'service_tier="fast"', "-c", "features.fast_mode=true"]);
445
+ export function buildCodexArgs({ model, thinking, speed = "standard", resumeRef, runDir } = {}) {
436
446
  const bypassSandbox = codexSandboxBypassed();
437
447
  const base = ["exec", "--json", "--skip-git-repo-check",
438
448
  ...(bypassSandbox ? ["--dangerously-bypass-approvals-and-sandbox"] : [])];
439
449
  if (runDir) base.push("--add-dir", runDir); // writable root for the stage's absolute output path
440
450
  const m = openaiModel(model); if (m) base.push("-m", m);
441
451
  base.push("-c", `model_reasoning_effort=${effortFor(thinking)}`);
442
- if (resumeRef) return { args: [...base, "resume", resumeRef, "-"] };
443
- return { args: [...base, "-"] };
452
+ // Every session of an Urgent run asks for the faster tier where the model sent above has one (engine/speed.mjs,
453
+ // sessionSpeed); on any other model it is not asked for, and the turn's record says why it ran at standard speed.
454
+ const sp = sessionSpeed({ ordered: speed, engine: "openai-agent", model: m });
455
+ if (sp.sent === "fast") base.push(...CODEX_FAST_OVERRIDES);
456
+ if (resumeRef) return { args: [...base, "resume", resumeRef, "-"], speed: sp };
457
+ return { args: [...base, "-"], speed: sp };
444
458
  }
445
459
 
446
460
  // Fold ONE codex --json line into the running event accumulator. `atMs` is when the line arrived, in ms from the
@@ -866,7 +880,17 @@ export function parseResetHint(text, now = Date.now()) {
866
880
  return undefined;
867
881
  }
868
882
 
869
- function settleTuple({ r, ev, resumeRef }) {
883
+ /**
884
+ * One Codex turn's speed record, in the Claude adapter's shape (anthropic-agent.mjs, speedOfClaudeTurn). Codex reports no
885
+ * served tier: neither `exec --json` nor its session record names one (measured on 0.162.0, 2026-11-25), so `served` is
886
+ * null and `basis` says "unknown" on every turn, fast or not. `standardBecause` is why a session of a fast run asked for
887
+ * standard (engine/speed.mjs, sessionSpeed), null otherwise. PURE.
888
+ */
889
+ export function speedOfCodexTurn(requested = "standard", standardBecause = null) {
890
+ return { requested, standardBecause, served: null, basis: "unknown", calls: null, state: null, disabledReason: null, notice: null };
891
+ }
892
+
893
+ function settleTuple({ r, ev, resumeRef, speed = { sent: "standard", standardBecause: null } }) {
870
894
  const killed = !!r.killed, overflow = !!r.overflow, stallKill = !!r.stallKill;
871
895
  // A turn is OK iff it reached turn.completed, did not turn.failed, and was not killed/overflowed. The
872
896
  // file-truth gate (runStage) validates the actual output file separately — an empty agent_message is fine.
@@ -905,6 +929,8 @@ function settleTuple({ r, ev, resumeRef }) {
905
929
  // null = "this engine did not report", never the requested tier wearing the word "actual".
906
930
  // gateway.mjs records the absence as modelBasis:"unknown".
907
931
  modelWire: ev.model ?? null,
932
+ // SPEED GAUGE: what the turn asked for, and that the program did not say what it served (speedOfCodexTurn).
933
+ speed: speedOfCodexTurn(speed.sent, speed.standardBecause),
908
934
  sessionRef: ev.threadId ?? resumeRef ?? null,
909
935
  // hardWall vs stall: same null-usage kill shape, distinguished for classifyWedge (a hard-wall grind is
910
936
  // a `timeout`, a 0-token stall is a `lane_wedge`).
@@ -1008,7 +1034,7 @@ export const openaiAgentEngine = {
1008
1034
  // `thread/resume failed: no rollout found for thread id ... (code -32600)`, exit 1 — with the control
1009
1035
  // (same id, same binary, its own home) resuming cleanly. So every warm-patch retry and every
1010
1036
  // form-repair sub-turn on the codex arm has been failing.
1011
- async runTurn({ message, model, thinking, timeoutSec, resumeRef, mcpConfig, allowedTools, cwd, skillsDir, skillsGrantRoots, profilesDir, resolveSkill, runDir, output = FILE_OUTPUT, stallSec, stageHome: providedHome, streamFile = null } = {}) {
1037
+ async runTurn({ message, model, thinking, speed = "standard", timeoutSec, resumeRef, mcpConfig, allowedTools, cwd, skillsDir, skillsGrantRoots, profilesDir, resolveSkill, runDir, output = FILE_OUTPUT, stallSec, stageHome: providedHome, streamFile = null } = {}) {
1012
1038
  if (!message) throw new Error("openai-agent.runTurn: message is required");
1013
1039
  const t0 = Date.now();
1014
1040
  let codexHome;
@@ -1059,7 +1085,7 @@ export const openaiAgentEngine = {
1059
1085
  withheldFromCommands: codexCommandWithheld() }));
1060
1086
 
1061
1087
  const input = absolutizeSkillRefs(message, skillsDir, resolveSkill);
1062
- const { args } = buildCodexArgs({ model, thinking, resumeRef, runDir });
1088
+ const { args, speed: sent } = buildCodexArgs({ model, thinking, speed, resumeRef, runDir });
1063
1089
  // Stamped HERE, not at function entry: everything above is file writes that can take a moment, and
1064
1090
  // a floor set too early would let a previous turn's rollout back in on a shared home.
1065
1091
  const spawnedAtMs = Date.now();
@@ -1091,7 +1117,7 @@ export const openaiAgentEngine = {
1091
1117
  if (!ev.usage) { ev.usage = readRolloutUsage(codexHome, spawnedAtMs); ev.usageFromRollout = ev.usage != null; }
1092
1118
  // A resumed turn's turn.completed states its thread's running total, earlier turns included. Its own share is in the same rollout; where that cannot be read the total stands, overstated and never understated.
1093
1119
  else if (resumeRef) ev.usage = readRolloutUsage(codexHome, spawnedAtMs) ?? ev.usage;
1094
- return settleTuple({ r, ev, resumeRef });
1120
+ return settleTuple({ r, ev, resumeRef, speed: sent });
1095
1121
  } finally {
1096
1122
  // BEFORE the home can be deleted, here or by the ladder that owns it. A failed write-back leaves the
1097
1123
  // turn's result as it was; the next turn is seeded from the master either way.
@@ -12,8 +12,9 @@
12
12
  // - a run with no record is left without one. Nothing here writes a record for a run that has already started,
13
13
  // because that would date today's setting back to a start nobody recorded.
14
14
  //
15
- // The record holds the two names and nothing else. Each must name an engine this driver ships or a register it
16
- // knows, so no other string (a credential included) can be written into it.
15
+ // The record holds the two names and the run's Urgent decision, nothing else. Each name must name an engine this driver
16
+ // ships or a register it knows, and the decision is two booleans and a fixed word (engine/speed.mjs), so no other
17
+ // string (a credential included) can be written into it.
17
18
  //
18
19
  // A LEAF: it reads the shipped-engine table, not the engine registry. The jurisdiction lanes' turn runner reads the
19
20
  // record, tool servers reach that runner, and the registry would bring both engine adapters and every setting they
@@ -31,7 +32,7 @@ const nameOf = (v) => (v == null ? null : String(v).trim().toLowerCase() || null
31
32
  * with what is there and `written: false`, so a cold start that is retried keeps its first choice.
32
33
  * `register` is null when the machine has none set; that is recorded as it was, not guessed.
33
34
  */
34
- export function recordRunChoices(runDir, { engine, register }) {
35
+ export function recordRunChoices(runDir, { engine, register, urgent = null }) {
35
36
  const held = readRunChoices(runDir);
36
37
  if (held.state !== "none") return { written: false, ...held };
37
38
  const e = nameOf(engine), r = nameOf(register);
@@ -39,15 +40,34 @@ export function recordRunChoices(runDir, { engine, register }) {
39
40
  throw new Error(`run-choices: "${e}" is not an engine this driver ships (${Object.keys(ENGINE_BINARIES).join(", ")})`);
40
41
  if (r !== null && !Object.hasOwn(PROVIDERS, r))
41
42
  throw new Error(`run-choices: "${r}" is not a register this driver knows (${Object.keys(PROVIDERS).join(", ")})`);
43
+ const u = urgentOf(urgent);
42
44
  ensureDriverDir(runDir);
43
45
  const p = driverDir(runDir, RUN_CHOICES_FILE);
44
- writeFileSync(`${p}.tmp`, JSON.stringify({ schema: 1, engine: e, register: r }, null, 2) + "\n");
46
+ writeFileSync(`${p}.tmp`, JSON.stringify({ schema: 1, engine: e, register: r, ...(u ? { urgent: u } : {}) }, null, 2) + "\n");
45
47
  renameSync(`${p}.tmp`, p);
46
- return { written: true, state: "recorded", engine: e, register: r };
48
+ return { written: true, state: "recorded", engine: e, register: r, ...(u ? { urgent: u } : {}) };
47
49
  }
48
50
 
49
51
  /**
50
- * What the run recorded: `{ state: "recorded", engine, register }`, `{ state: "none" }` for a run that has no
52
+ * The Urgent decision in the one shape the record holds (engine/speed.mjs urgentDecision), or null for none or for
53
+ * anything else. A record that predates the decision, or holds one in another shape, runs at standard speed: nothing
54
+ * here parks or fails a run over its speed. PURE.
55
+ */
56
+ function urgentOf(u) {
57
+ if (!u || typeof u !== "object" || typeof u.ordered !== "boolean" || typeof u.fast !== "boolean") return null;
58
+ const reason = u.reason == null ? null : String(u.reason);
59
+ if (reason !== null && !/^[a-z-]{1,40}$/.test(reason)) return null;
60
+ return { ordered: u.ordered, fast: u.ordered && u.fast, reason };
61
+ }
62
+
63
+ /** The run's recorded Urgent decision, or null for a run with no record or none in it. PURE but for the read. */
64
+ export function urgentForRun(runDir) {
65
+ const rec = readRunChoices(runDir);
66
+ return rec.state === "recorded" ? rec.urgent ?? null : null;
67
+ }
68
+
69
+ /**
70
+ * What the run recorded: `{ state: "recorded", engine, register, urgent? }`, `{ state: "none" }` for a run that has no
51
71
  * record, or `{ state: "unreadable", detail }` for one whose record does not read back as the two names.
52
72
  */
53
73
  export function readRunChoices(runDir) {
@@ -60,7 +80,8 @@ export function readRunChoices(runDir) {
60
80
  const engine = nameOf(o?.engine), register = nameOf(o?.register);
61
81
  if (!engine) return { state: "unreadable", detail: "names no engine" };
62
82
  if (o?.register != null && typeof o.register !== "string") return { state: "unreadable", detail: "its register is not a name" };
63
- return { state: "recorded", engine, register };
83
+ const urgent = urgentOf(o?.urgent);
84
+ return { state: "recorded", engine, register, ...(urgent ? { urgent } : {}) };
64
85
  }
65
86
 
66
87
  /**
@@ -0,0 +1,107 @@
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/speed.mjs — the speed a session asks its vendor for, and whether this installation can ask for the faster one.
4
+ //
5
+ // An order placed Urgent runs every session it starts on the vendor's faster setting wherever the session's model has
6
+ // one: every stage, its retries, warm resumes and repairs, and the native-language turns. A session whose model has no
7
+ // faster setting runs at its usual speed and its record says why. The model, effort, tools and work stay as they are.
8
+ // The choice is made once, when the run starts, and recorded with the run (engine/run-choices.mjs), so every retry,
9
+ // warm resume and repair asks for the speed its first attempt asked for. Fast and standard keep separate prompt caches,
10
+ // so a session that changed speed partway would pay for its whole context again.
11
+ //
12
+ // A LEAF: it reads the billing answer and the model it is handed, never the environment or a vendor. The order screens
13
+ // and the connector ask it whether this installation can run Urgent, before any run exists.
14
+
15
+ /** The two speeds a turn can ask for. */
16
+ export const SPEEDS = Object.freeze(["standard", "fast"]);
17
+
18
+ /** Why a session of an Urgent order runs at standard speed although the installation can run fast. */
19
+ export const STANDARD_BECAUSE = Object.freeze({ modelNotFast: "model-not-fast" });
20
+
21
+ /**
22
+ * Does this model have the faster setting? Asked of the model the adapter is about to send (`--model` on Claude, `-m`
23
+ * on Codex), never of the tier a stage declares: on Codex a tier's model is a setting, and on Claude a pinned id is
24
+ * sent as itself. An absent model is not one the vendor lists, so it answers no. PURE.
25
+ *
26
+ * Claude, from the vendor's fast-mode page (https://code.claude.com/docs/en/fast-mode, read 2026-11-26), its opening
27
+ * section: "On the Anthropic API, fast mode is supported on Fable 5.2, Opus 5.5, Opus 5, and Opus 4.8, but not on
28
+ * Sonnet, Haiku, or other models", and "Opus 4.7 doesn't support fast mode". The rolling aliases `opus` and `fable`
29
+ * name Opus 5.5 and Fable 5.2 today. The same page says fast mode for Opus 4.8 "will be removed on November 30, 2026";
30
+ * a session pinned to it after that runs at standard speed by the vendor's own fallback, and its record says so.
31
+ *
32
+ * Codex, from its speed page (https://learn.chatgpt.com/docs/agent-configuration/speed.md, read 2026-11-26), section
33
+ * "Fast mode": "Fast mode supports GPT-6.2 Astra and GPT-6.2 Sol. You can also use it with GPT-6.1 Sol, GPT-6.1 Terra,
34
+ * GPT-6 Astra, GPT-6 Sol, and GPT-6 Luna." Those are the three models the Codex tiers default to, and four more.
35
+ */
36
+ const CLAUDE_FAST = [/^(?:opus|fable)$/, /^claude-fable-5-2(?:-\d{8})?$/, /^claude-opus-5(?:-5)?(?:-\d{8})?$/, /^claude-opus-4-8(?:-\d{8})?$/];
37
+ const CODEX_FAST = new Set(["gpt-6.2-astra", "gpt-6.2-sol", "gpt-6.1-sol", "gpt-6.1-terra", "gpt-6-astra", "gpt-6-sol", "gpt-6-luna"]);
38
+ export function fastSupported({ engine, model } = {}) {
39
+ const id = String(engine ?? "").trim().toLowerCase();
40
+ // A context-window suffix ("[1m]") names the same model.
41
+ const m = String(model ?? "").trim().toLowerCase().replace(/\[[^\]]*\]$/, "");
42
+ if (!m) return false;
43
+ if (id === "anthropic-agent") return CLAUDE_FAST.some((re) => re.test(m.replace(/^anthropic\//, "")));
44
+ if (id === "openai-agent") return CODEX_FAST.has(m.replace(/^openai\//, ""));
45
+ return false;
46
+ }
47
+
48
+ /**
49
+ * What one session sends: `{ sent, standardBecause }`. `ordered` is the speed the run asks of every session
50
+ * (`turnSpeed`); `model` the one the adapter is about to send. A session of a fast run whose model has no faster
51
+ * setting sends standard and names why; a standard run's sessions send standard with nothing to explain. PURE.
52
+ */
53
+ export function sessionSpeed({ ordered = "standard", engine, model } = {}) {
54
+ if (ordered !== "fast") return { sent: "standard", standardBecause: null };
55
+ return fastSupported({ engine, model }) ? { sent: "fast", standardBecause: null } : { sent: "standard", standardBecause: STANDARD_BECAUSE.modelNotFast };
56
+ }
57
+
58
+ /**
59
+ * Can this installation run Urgent: `{ available, reason }`. `engine` is the engine id, `auth` the billing answer the
60
+ * run would use (engine/auth.mjs resolveAuthMode: `{ mode, cloud }`). `reason` is null when available, otherwise a
61
+ * fixed word naming why. Nothing here calls a vendor. PURE.
62
+ *
63
+ * Claude, from the vendor's fast-mode page (https://code.claude.com/docs/en/fast-mode, read 2026-11-26), section
64
+ * "Requirements": fast mode "is available through the Anthropic Console API, for Claude subscription plans using usage
65
+ * credits, and on Google Cloud's Agent Platform with conditions", and "It is not available on Amazon Bedrock, Microsoft
66
+ * Foundry, or Claude Platform on AWS". Section "Use fast mode on Agent Platform": there it can be turned on "for
67
+ * Fable 5.2" only, and the stages run Opus, so Agent Platform answers no. A subscription without usage credits,
68
+ * or an organisation that has switched fast mode off, still answers yes here: the program then runs the turn at
69
+ * standard speed (section "Handle rate limits"), and the turn's own record says so.
70
+ *
71
+ * Codex: the faster tier is a per-call setting on every billing route Codex offers (its config reference,
72
+ * `service_tier`); the program reports no served tier, which the turn's record says rather than this answer.
73
+ */
74
+ export function urgentAvailability({ engine, auth } = {}) {
75
+ const id = String(engine ?? "").trim().toLowerCase();
76
+ if (id === "openai-agent") return { available: true, reason: null };
77
+ if (id !== "anthropic-agent") return { available: false, reason: "unknown-engine" };
78
+ if (auth?.mode === "cloud") {
79
+ if (auth.cloud === "vertex") return { available: false, reason: "fable-only-on-this-cloud" };
80
+ // Bedrock, Foundry, and a gateway in front of either: the vendor names the first two as not available, and a
81
+ // gateway gives no way to know which provider serves it.
82
+ return { available: false, reason: "not-on-this-cloud" };
83
+ }
84
+ if (auth?.mode === "api-key" || auth?.mode === "subscription") return { available: true, reason: null };
85
+ return { available: false, reason: "unknown-billing" };
86
+ }
87
+
88
+ /**
89
+ * What a run records about Urgent when it starts: `{ ordered, fast, reason }`. `fast` is true only when the order
90
+ * asked for Urgent and the installation can run it; an order this installation cannot serve runs at standard speed and
91
+ * says why. PURE.
92
+ */
93
+ export function urgentDecision({ ordered, engine, auth } = {}) {
94
+ const asked = ordered === true;
95
+ if (!asked) return { ordered: false, fast: false, reason: null };
96
+ const a = urgentAvailability({ engine, auth });
97
+ return { ordered: true, fast: a.available, reason: a.reason };
98
+ }
99
+
100
+ /**
101
+ * The speed a run asks of every session it starts: `fast` for a run recorded fast, `standard` otherwise. `urgent` is the
102
+ * run's recorded decision (`urgentDecision`), or null for a run with none. Whether a session's model can take it is the
103
+ * adapter's question (`sessionSpeed`), asked of the model it resolves. PURE.
104
+ */
105
+ export function turnSpeed({ urgent = null } = {}) {
106
+ return urgent?.fast === true ? "fast" : "standard";
107
+ }
@@ -149,6 +149,10 @@ export const DECLARED_JOB_FIELDS = Object.freeze([
149
149
  // `{ counts?: "<dir>", records?: "<dir>" }`. Absent ⇒ the provider is called, which is the only
150
150
  // behaviour a production job has ever had.
151
151
  "registerFixtures",
152
+ // — AN URGENT ORDER: `true` runs every session of the order on the vendor's faster setting where this installation
153
+ // and the session's model can (engine/speed.mjs). Read once, when the run starts, as `job.urgent === true`; any other value is a standard
154
+ // order. Declared so each door classifies it; the order screens and the connector carry it with their order option.
155
+ "urgent",
152
156
  ]);
153
157
 
154
158
  // — WHAT A JOB CARRIES THAT NOBODY DECLARED, said out loud instead of dropped in silence.
@@ -694,6 +698,10 @@ export function validateJob(job, { atClaim = false } = {}) {
694
698
  // nativeLanguage: the ONE toggle in the offering. Shape first, then the two ways it can be wrong.
695
699
  if ("nativeLanguage" in job && job.nativeLanguage != null && typeof job.nativeLanguage !== "boolean")
696
700
  errs.push(`nativeLanguage ${JSON.stringify(job.nativeLanguage)} must be a boolean — true adds the native-language investigation to a ${productName("multi-country-focus-search")}`);
701
+ // urgent: an ORDER OPTION, so a value that is not a boolean is refused rather than run, and counted, as a standard
702
+ // order: the engine reads only `job.urgent === true`, and a client who sent "yes" would lose the option silently.
703
+ if ("urgent" in job && job.urgent != null && typeof job.urgent !== "boolean")
704
+ errs.push(`urgent ${JSON.stringify(job.urgent)} must be a boolean`);
697
705
  // `false` is REFUSED, not dropped — the caseLaw rule on the sibling toggle. The toggle only ever added,
698
706
  // so `false` asked to remove something no product runs conditionally, and all four assembling doors
699
707
  // dropped it: a requester who sent it on a Full country search believed they had switched the
@@ -16,7 +16,7 @@
16
16
  // Exit codes (machine-consumable; one JSON result object on stdout, human notes on stderr):
17
17
  // 0 queued (or --dry-run and the job classifies "run")
18
18
  // 2 validation refused it (classify "clarify"/"reject" — errors listed; fix the request, don't force it)
19
- // 3 id collision (a job with this id is already queued/processing — re-delivery no-op, mirror start_run)
19
+ // 3 id collision (a job with this id already exists, in any state — a re-delivery or a retry resolves to that order)
20
20
  // 1 anything else (bad flags, unreadable --job file, fs errors)
21
21
  //
22
22
  // The CLI serializes proper JSON, so prose fields (brief, goods, instructions…) ride INLINE — the
@@ -24,7 +24,8 @@
24
24
  // assembleJob treats a self-contained job identically (the overlay loop is a no-op).
25
25
 
26
26
  import "../shared/env-local.mjs"; // side effect: apply <repo>/.env when THIS file is the CLI entry (never on library import)
27
- import { readFileSync, writeFileSync, existsSync, mkdirSync, renameSync } from "node:fs";
27
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, renameSync, readdirSync } from "node:fs";
28
+ import { receiptIn, RECEIPT_STATES } from "./order-receipt.mjs"; // an id in ANY state is the same order, not a new one
28
29
  import { join } from "node:path";
29
30
  import { fileURLToPath } from "node:url";
30
31
  import { randomUUID } from "node:crypto";
@@ -339,6 +340,17 @@ async function main(argv) {
339
340
  // re-uses its id); refusing here mirrors start_run and keeps a double-submit from racing the claim.
340
341
  if (existsSync(dest) || existsSync(join(qdir, `${job.id}.processing`)))
341
342
  fail(`a job with id "${job.id}" is already queued/processing in ${qdir}`, 3);
343
+ // AN ID IN ANY STATE IS THAT ORDER, not room for a second one. The check above saw only a waiting or claimed job, so
344
+ // the same submission retried after it was refused, parked or finished wrote a second order under the same reference.
345
+ // Same exit, and the answer carries what became of the first.
346
+ let names = [];
347
+ try { names = readdirSync(qdir); } catch { /* a queue directory that will not list cannot hold the id either */ }
348
+ const existing = receiptIn(qdir, job.id, names);
349
+ if (existing) {
350
+ process.stdout.write(JSON.stringify({ ok: false, id: job.id, existing: { state: existing.state, stateText: RECEIPT_STATES[existing.state],
351
+ reason: existing.reason ?? null, runId: existing.runId ?? null } }, null, 2) + "\n");
352
+ fail(`a job with id "${job.id}" already exists in ${qdir}: ${RECEIPT_STATES[existing.state]}`, 3);
353
+ }
342
354
  const tmp = `${dest}.tmp`;
343
355
  writeFileSync(tmp, JSON.stringify(job, null, 2) + "\n");
344
356
  renameSync(tmp, dest); // atomic publish — the runner claims *.json, never a half-written file
@@ -397,7 +397,7 @@ export async function runJxSerpGrid(ctx, job, opts = {}, { runLog = () => {}, no
397
397
  ...jxBillingStamp(judgeSource, jr),
398
398
  took_ms: jr?.tookMs ?? (Date.now() - started), ok: Boolean(jr?.ok), judged: jr?.ok ? (jr.judgments?.length ?? 0) : 0,
399
399
  ...jxModelFields(judgeSource, jr),
400
- ...(jr?.usage ? { usage: jr.usage } : {}), ...(jr?.ok ? {} : { cause: String(jr?.cause ?? "unknown").slice(0, 300) }) });
400
+ ...(jr?.usage ? { usage: jr.usage } : {}), ...(jr?.speed ? { speed: jr.speed } : {}), ...(jr?.ok ? {} : { cause: String(jr?.cause ?? "unknown").slice(0, 300) }) });
401
401
  if (!jr?.ok) { judgeDegraded = String(jr?.cause ?? "unknown").slice(0, 200); break; }
402
402
  const byId = new Map(jr.judgments.map((j) => [j.id, j]));
403
403
  for (const h of batch) {
@@ -639,7 +639,7 @@ export async function runJxNativeread(ctx, job, opts = {}, { runLog = () => {},
639
639
  ...jxBillingStamp(source, r),
640
640
  took_ms: r?.tookMs ?? (Date.now() - started), ok: Boolean(r?.ok), items: r?.ok ? (r.items?.length ?? 0) : 0,
641
641
  ...jxModelFields(source, r),
642
- ...(r?.usage ? { usage: r.usage } : {}), ...(r?.ok ? {} : { cause: String(r?.cause ?? "unknown").slice(0, 300) }) });
642
+ ...(r?.usage ? { usage: r.usage } : {}), ...(r?.speed ? { speed: r.speed } : {}), ...(r?.ok ? {} : { cause: String(r?.cause ?? "unknown").slice(0, 300) }) });
643
643
  if (!r?.ok) {
644
644
  degradeUnit(run.runDir, key, st.attempts, r?.cause ?? "unknown");
645
645
  note(shadowLaneNote("jx nativeread", "degraded", String(r?.cause ?? "unknown"), `attempt ${st.attempts + 1}/${MAX_UNIT_ATTEMPTS}`));
package/driver/jx.mjs CHANGED
@@ -534,7 +534,7 @@ export async function runJxCandidateFold(ctx, job, opts = {}, { runLog = () => {
534
534
  // the model the turn reported, as `model` and `modelActual`, or `modelActual: null` for a turn
535
535
  // that ran and named none — see jxModelFields.
536
536
  ...jxModelFields(source, r),
537
- ...(r?.usage ? { usage: r.usage } : {}), ...(r?.ok ? {} : { cause: String(r?.cause ?? "unknown").slice(0, 300) }) };
537
+ ...(r?.usage ? { usage: r.usage } : {}), ...(r?.speed ? { speed: r.speed } : {}), ...(r?.ok ? {} : { cause: String(r?.cause ?? "unknown").slice(0, 300) }) };
538
538
  try { appendFileSync(ledgerPath, JSON.stringify(row) + "\n"); } catch { /* receipts best-effort */ }
539
539
  // Before the degraded-lane `continue` below: a lane that FAILED still ran a turn, and the model
540
540
  // that produced the failure is part of who did this run's native-language work.