clearotron 0.6.0 → 0.7.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 (110) hide show
  1. package/INSTALL.md +7 -4
  2. package/QUICKSTART.md +1 -0
  3. package/README.md +5 -2
  4. package/THIRD-PARTY-NOTICES.md +1 -1
  5. package/bin/clearotron.mjs +4 -2
  6. package/bin/onboard.mjs +158 -29
  7. package/build-info.json +2 -2
  8. package/docs/CLIENT-MCP.md +3 -1
  9. package/docs/DELIVERY.md +6 -3
  10. package/docs/architecture/02-architecture.md +1 -1
  11. package/docs/branding.md +4 -4
  12. package/docs/report-data/clearance-1.schema.json +320 -0
  13. package/docs/report-data/knockout-1.schema.json +268 -0
  14. package/driver/CHANGELOG.md +39 -0
  15. package/driver/connotation-search.mjs +1 -1
  16. package/driver/contract-e3-backlog.mjs +1 -1
  17. package/driver/coverage-ledger.mjs +18 -2
  18. package/driver/deferral-row.mjs +1 -1
  19. package/driver/degraded-parts.mjs +1 -0
  20. package/driver/driver.config.mjs +4 -3
  21. package/driver/effective-scope.mjs +3 -1
  22. package/driver/engagement-receipt.mjs +3 -3
  23. package/driver/engine/anthropic-agent.mjs +15 -1
  24. package/driver/engine/common.mjs +7 -0
  25. package/driver/engine/mcp/band-server.mjs +7 -16
  26. package/driver/engine/mcp/codex-config.mjs +3 -0
  27. package/driver/engine/mcp/recording-server.mjs +45 -34
  28. package/driver/engine/openai-agent.mjs +74 -7
  29. package/driver/gateway.mjs +67 -10
  30. package/driver/jx.mjs +13 -5
  31. package/driver/manuals-seen.mjs +146 -0
  32. package/driver/mark-logos.mjs +144 -0
  33. package/driver/methodology-witness.mjs +2 -1
  34. package/driver/owner-use-check.mjs +3 -3
  35. package/driver/package.json +1 -1
  36. package/driver/pipeline-knockout.mjs +4 -0
  37. package/driver/pipeline.mjs +92 -7
  38. package/driver/portal-local-auth.mjs +6 -2
  39. package/driver/portal-report.mjs +43 -12
  40. package/driver/portal-routes/me.mjs +4 -1
  41. package/driver/portal-runs.mjs +6 -9
  42. package/driver/profiles.mjs +4 -4
  43. package/driver/publish/README.md +9 -7
  44. package/driver/publish/email-conditions.mjs +2 -2
  45. package/driver/publish/evidence-words.mjs +21 -0
  46. package/driver/publish/index.mjs +104 -90
  47. package/driver/publish/knockout.mjs +75 -49
  48. package/driver/publish/office-record-links.mjs +11 -9
  49. package/driver/publish/page-shell.mjs +98 -0
  50. package/driver/publish/publish-inputs.mjs +4 -0
  51. package/driver/publish/regions.mjs +24 -3
  52. package/driver/publish/register-record.mjs +150 -0
  53. package/driver/publish/render-knockout.mjs +195 -642
  54. package/driver/publish/render.mjs +270 -363
  55. package/driver/publish/report-data.mjs +225 -12
  56. package/driver/publish/strings.mjs +662 -0
  57. package/driver/publish/templates/knockout.css +200 -0
  58. package/driver/publish/templates/report.css +72 -52
  59. package/driver/publish/xlsx.mjs +148 -125
  60. package/driver/record-goods.mjs +42 -0
  61. package/driver/reference-score.mjs +4 -1
  62. package/driver/register-reach.mjs +39 -0
  63. package/driver/registry-fidelity.mjs +3 -8
  64. package/driver/repair-composers.mjs +6 -2
  65. package/driver/repair-targets.mjs +4 -1
  66. package/driver/run-delivered.mjs +6 -1
  67. package/driver/runner.mjs +73 -29
  68. package/driver/scope-facts.mjs +27 -6
  69. package/driver/search-policy.mjs +9 -4
  70. package/driver/stages.mjs +3 -3
  71. package/driver/steps/overview-and-cards.mjs +50 -14
  72. package/driver/steps/verdict-gate.mjs +33 -13
  73. package/driver/suite-census.json +368 -68
  74. package/driver/terminal-clamp.mjs +6 -1
  75. package/mcp-server/CHANGELOG.md +4 -0
  76. package/mcp-server/lib/audit-view.mjs +5 -2
  77. package/mcp-server/lib/brief.mjs +2 -1
  78. package/mcp-server/lib/evidence.mjs +31 -4
  79. package/mcp-server/lib/knockout.mjs +1 -1
  80. package/mcp-server/lib/scrub.mjs +1 -1
  81. package/mcp-server/package.json +1 -1
  82. package/mcp-server/server.mjs +5 -3
  83. package/package.json +4 -1
  84. package/portal-ui/dist/assets/{index-CYaO2ygd.js → index-CtkllKJ2.js} +225 -77
  85. package/portal-ui/dist/assets/{index-izLa9apq.css → index-CxAkJXIT.css} +25 -5
  86. package/portal-ui/dist/index.html +2 -2
  87. package/portal-ui/package.json +3 -3
  88. package/providers/_shared/ledger.mjs +30 -2
  89. package/providers/_shared/record-uri.mjs +15 -0
  90. package/providers/clarivate/src/adapter.js +11 -0
  91. package/providers/clarivate/src/core.js +17 -1
  92. package/providers/oauth-mcp-bridge/CHANGELOG.md +4 -0
  93. package/providers/oauth-mcp-bridge/package.json +1 -1
  94. package/scripts/README.md +147 -3
  95. package/scripts/e2e-first-time.mjs +3 -3
  96. package/scripts/freeze-example-run.mjs +3 -3
  97. package/scripts/mint-search-level-tags.mjs +61 -0
  98. package/scripts/mint-source-pin-census.mjs +89 -0
  99. package/scripts/release-note-required.mjs +65 -6
  100. package/scripts/test-durations-reporter.mjs +25 -0
  101. package/scripts/test-full.mjs +72 -18
  102. package/scripts/test-run.mjs +18 -1
  103. package/shared/brand.mjs +85 -5
  104. package/shared/inline-markdown.mjs +53 -0
  105. package/shared/portal-tokens.mjs +2 -1
  106. package/shared/register-selection.mjs +8 -3
  107. package/shared/search-level-tags.json +25 -0
  108. package/shared/tools/derive-band-pairs.mjs +10 -0
  109. package/driver/own-rights.mjs +0 -83
  110. package/driver/use-check.mjs +0 -85
@@ -1,5 +1,44 @@
1
1
  # clearotron-driver
2
2
 
3
+ ## 0.7.0-beta.0
4
+
5
+ ### Minor Changes
6
+
7
+ - New: The data file published beside each report now names which of its two shapes it is: `report-data/clearance-1` for a clearance, `report-data/knockout-1` for a Knockout. Each shape has a JSON Schema in the documentation, so a firm building its own screens on the data can check a file against it. Reports published before this keep `report-data/1`: a published file is never rewritten.
8
+
9
+ ### Patch Changes
10
+
11
+ - Fixed: A search ordered while the worker is idle now starts within a few seconds. It used to wait for the worker's next check, up to 90 seconds later, wherever the worker is started by `clearotron start` rather than by systemd, which includes every Mac.
12
+ - Fixed: A large search no longer slows down each time a step looks up a register record the search has already fetched. On the largest searches these lookups could add several minutes, and a search that had fetched a very large number of records could fail to find them at all.
13
+ - Fixed: When a report's overall assessment could not be completed, its "Left open" list states a shared reason once, followed by the searches it covers. It printed the same sentence once for every search.
14
+ - Fixed: On clearance and Knockout reports, the band word on a risk pill and the small grey labels now meet the WCAG AA contrast minimum, in both themes and in print. Pills on the lighter bands print dark text, where they printed white.
15
+ - Fixed: A clearance's "conditional on" list no longer includes three notes the search wrote about its own steps, such as "the lawyer judged a material slice not fully cleared" or "follow-ups left open this run". Those notes stay in the run's own record. Nothing is written in their place, and the report, the portal, the email and the assistant's summary all leave them out.
16
+ - Fixed: A clearance report now names a country where it printed a bare code, such as AR, CO or CZ. The names show in the rows of where the mark stands and when you point at a country's chip. The register counts also read EU and UK where they printed the register's own EM and GB, and two counts for one country show as one.
17
+ - Fixed: A Knockout conflict card now cites a register filing by its office and number, such as EU 018765432, linked to the office's own page where it has one. It printed the register service's internal record path, which opens nothing, while the filings table on the same page already named the filing this way.
18
+ - Fixed: A Knockout report labels things as a clearance report does. The links under a conflict read "Sources:", where they read "Evidence:", which the clearance uses only for how well a value is evidenced. The fold that argues a rating is "Risk assessment", and the rating line reads "Overall risk" followed by the framework's name.
19
+ - Fixed: A Knockout report now lists under "Left open" each register search that did not complete, and each name whose automated research was unavailable, as a clearance report does. A name whose register search failed no longer reads as a clean name.
20
+ - Fixed: A Knockout report's export menu offers "Download full audit (Excel)", as a clearance report's does. The page referred readers to the audit workbook and gave no way to open it.
21
+ - Fixed: A link the assessment writes into a report now shows as a link, not as bracketed text with its address. This covers the ruled-out names, the coverage notes left open and the mark assessment on a clearance report, the Knockout's assessment, and the same paragraphs in the portal. Bold, italic and code read the same way on both reports.
22
+ - Fixed: A worldwide clearance report lists the Chinese-, Japanese- and Korean-script register equivalents it did not search as one item under "Left open", with the offer of the native-language investigation once. It listed three near-identical items.
23
+ - Fixed: On a clearance report, "What happens next" now comes directly after the verdict, before the conflicts, so a reader who forwards the first pages forwards the actions too. Its words are unchanged, and the section links at the top follow the new order.
24
+ - Fixed: A clearance report's "Left open" list groups its items under their state, such as "Partially covered" or "Open item", with a count for each group. Every item is still listed.
25
+ - Fixed: A report's "Left open" list reads in plain words. A search not run is "Not searched", the list's heading is "Next steps & monitoring" alone, and a question from the client's request is headed "Question from the request", not by an internal label. A source left unsearched, and a full native-language search that ran only its first step, each say so in one plain sentence. Under a conflict, "If enforced:" no longer ends "for the client to consider", and the client's own marks are cited as "Search of the client's own marks."
26
+ - Fixed: On a Knockout of several names, each name's page no longer repeats its full assessment in a "Read the full assessment" fold under the one it opens with.
27
+ - Fixed: On clearance and Knockout reports, each finding's title is now a heading, so a screen reader can move from finding to finding, and the report's content is marked as the page's main region. A report also stops scrolling smoothly when the reader's system asks for reduced motion. The page looks the same.
28
+ - Fixed: A clearance report's footer no longer ends with the "Rated under" and "Run under project" lines. They showed only when the report file was opened outside the portal. The run keeps both facts in its own record.
29
+ - Fixed: On a worldwide clearance report, "Where searched" in About this request gives the number of focus territories, and the full list moves to "What was searched". Places where nothing was found read as one list of names, not a chip each with codes past twelve. "XS" reads "US state registers", and the unspecified code "ZZ" no longer appears in these lists. Each conflict's export checkbox and the conflict chart now have names a screen reader announces.
30
+ - Fixed: A printed or exported report no longer ends a page on a section heading whose content starts the next page. A report's page source also no longer carries the developers' stylesheet notes, which made each report about 17 KB larger.
31
+ - Fixed: A report exported to PDF now prints on A4 paper. It followed the browser's own paper setting, which could be Letter.
32
+ - Fixed: Setup now picks the one AI it finds ready on the machine as the default. When the free tier's EU credential is skipped, it offers the US-only register instead of leaving none. It asks for the USPTO download key before offering to build the US index, and says a US index not built yet is only present, not that its check passed. It says nothing about the EU register when the chosen register has no EU half. `clearotron run` with nothing after it, or with `--help`, now says how to run a clearance from a job file. In the portal, a suggested search names the project when the places came from the project, and removing all of a company's places shows Worldwide. A project that lists fewer marketplaces than its company can now be saved; the company's marketplaces are still searched. A company's run limits read "Runs a day" and "Waiting at once".
33
+ - Fixed: On a clearance report, the Similarity meter no longer prints an evidence word under it, matching the audit workbook. The other meters keep theirs.
34
+ - Fixed: In the audit workbooks, the Knockout's long text columns are now wide enough to read. A search left over its limit no longer shows an internal identifier in its note. The Use column no longer says a website's evidence was checked against the register, and a value nobody checked now reads "not checked", as the report says.
35
+ - Fixed: The audit workbook now uses the report's words. Each driver says how its value is evidenced as the report does: "verified", "not yet verified", "inferred" or "not checked", with no evidence word under Similarity. Coverage notes open with "Partially covered" or "Not searched", the main search is "main register search", and the coverage block is headed "How coverage was judged". The Knockout workbook's Audit Trail no longer shows the engine's call number, timing and OK/Degraded columns.
36
+ - New: The Clearances list shows which kind of search is behind each name: a tag under the name for each kind it has (KO, Prelim, Multi or Full), with the search's full name on hover. A new filter beside the status filter shows one kind of search at a time, and each name then shows the result of that kind of search.
37
+ - Fixed: In the dark theme, the outline that shows which control has keyboard focus was a dark red that was hard to see against the page, menus and dialogs. It is now a lighter red that stands out on all of them. The portal also marks its main content area, so a screen reader can jump straight to it.
38
+ - For operators: An installation given its own name in the brand-name setting now shows that name throughout the portal: in the logo, in the browser tab, and in every sentence that names the installation, such as "Remove from …" on the access screens. An installation that sets no name still shows Clearotron, and the sentences that said "this Clearotron" now say "Clearotron".
39
+ - Fixed: When a search's record cannot confirm whether the full-depth native-language search ran, the report's "Left open" list now says so in one plain sentence and treats that search as not done. The sentence used to be written in the engine's internal terms.
40
+ - Fixed: On a worldwide clearance, the coverage line now states how many offices the register service searched and names the ordered markets it does not cover, such as "Japan, the Philippines, Indonesia and Vietnam not covered". Each of those markets is listed as not searched. The line read "registers: worldwide", whatever the service reached.
41
+
3
42
  ## 0.6.0
4
43
 
5
44
  ### Minor Changes
@@ -1,7 +1,7 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-only
2
2
  // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
3
  // connotation-search.mjs — the meaning/connotation sweep: its DICTATED queries (driver side) and the
4
- // searched-not-asserted enforcement (validator side). Sister of use-check.mjs (spec 11): a "clean" claim
4
+ // searched-not-asserted enforcement (validator side). Sister of the retired use-check gate (spec 11): a "clean" claim
5
5
  // is sayable ONLY when a search produced it.
6
6
  //
7
7
  // The bug this closes (live incident: a mark reading as a benign given name one letter off the Mara
@@ -519,7 +519,7 @@ export const E3_BACKLOG = [
519
519
  where: "driver/stages.mjs:3121",
520
520
  surface: "stage-message",
521
521
  evidence: "use_check = {\"source\",\"quality\",\"question\"}: … quality: OPTIONAL, EXACTLY one of owner-site / independent / register-mirror … own_rights = {\"source\"}",
522
- reparsedBy: "driver/verify.mjs checkFindingsSibling (finding_use_check_missing); driver/own-rights.mjs:19-22",
522
+ reparsedBy: "driver/verify.mjs checkFindingsSibling (finding_use_check_missing, finding_own_rights_source_missing)",
523
523
  removedByMove: "NOTHING ON THE #850 PLAN REMOVES THIS",
524
524
  },
525
525
  {
@@ -44,12 +44,28 @@ export const REGISTER_AXES = ["saturation-probe", "primary-sweep", "transliterat
44
44
  // a structural substitution on a grammar this module owns, not a search through text. The scope tail
45
45
  // rides verbatim, which is where a mark actually appears.
46
46
  export const AXIS_READER_LABEL = Object.freeze({
47
- "primary-sweep": "main register sweep",
47
+ "primary-sweep": "main register search",
48
48
  "saturation-probe": "field-size count",
49
49
  "transliteration-numeric": "transliterations and numeric forms",
50
50
  "incumbent-class": "owner portfolio sweep",
51
51
  });
52
52
 
53
+ // A ROW HEAD THAT IS AN ENGINE TOKEN, in the reader's words (owner, 2026-11-18). The synthesis
54
+ // writes an open intake question's row under the ask register's own token (`intake-ask`, ask-ledger.mjs), and the page
55
+ // printed it capitalised, "Intake-ask". Same one position as an axis head, read the same way: equality on the head.
56
+ export const ROW_HEAD_READER_LABEL = Object.freeze({
57
+ "intake-ask": "Question from the request",
58
+ });
59
+
60
+ /** A row's area with an engine-token head in the reader's words; any other area rides back unchanged. PURE. */
61
+ export function readerRowHead(area) {
62
+ const a = String(area ?? "");
63
+ const cut = a.indexOf(" / ");
64
+ const head = (cut < 0 ? a : a.slice(0, cut)).trim().toLowerCase();
65
+ const label = Object.hasOwn(ROW_HEAD_READER_LABEL, head) ? ROW_HEAD_READER_LABEL[head] : null;
66
+ return label ? (cut < 0 ? label : `${label}${a.slice(cut)}`) : a;
67
+ }
68
+
53
69
  /**
54
70
  * A coverage unit in the reader's words. `<axis> / <scope>` → `<label> / <scope>`; a bare axis → its
55
71
  * label; anything whose head is not one of the four closed axes rides back UNCHANGED.
@@ -66,7 +82,7 @@ export function coverageUnitLabel(unit) {
66
82
  const cut = u.indexOf(" / ");
67
83
  const head = cut < 0 ? u : u.slice(0, cut);
68
84
  const label = Object.hasOwn(AXIS_READER_LABEL, head) ? AXIS_READER_LABEL[head] : null;
69
- if (!label) return u;
85
+ if (!label) return readerRowHead(u);
70
86
  return cut < 0 ? label : `${label}${u.slice(cut)}`;
71
87
  }
72
88
 
@@ -55,7 +55,7 @@ export const plainDeferralReason = (r) => {
55
55
  if (/^not-verified-closed\b/i.test(t))
56
56
  return "nothing in the run's own record confirms it was searched, so it is left open rather than assumed done";
57
57
  if (/^source-not-swept\b/i.test(t))
58
- return "the channel it needed was never swept this run, so nothing is known about it either way";
58
+ return "the source it needed was not searched, so nothing is known about it either way"; // owner, 2026-11-18
59
59
  if (/^digest-locked-resume\b/i.test(t))
60
60
  return "the earlier pass was still holding the record when the re-run was attempted, so it could not be completed this run";
61
61
  if (/^resume-arm-unverifiable\b/i.test(t))
@@ -419,6 +419,7 @@ export const STORES_WITHOUT_A_PART = {
419
419
  "status.json": "the pool's mark name and a machine note, neither of them a part of the report",
420
420
  "_driver/search-policy.json": "the product's identity, which no shipped name describes",
421
421
  "_driver/profile.json": "the pool's profile stamp, not a part of the report",
422
+ "_driver/scope-facts.json": "the register service's reach, which heads the register rows; without it the head keeps its earlier words",
422
423
  };
423
424
 
424
425
  // The record set is a folder, not a named store (publish-inputs.mjs NOT_READ_BY_NAME), and is read as one.
@@ -435,10 +435,11 @@ export const config = {
435
435
  // library reached by CLI entries AND by unit-booted services, and a service read no file of its own.
436
436
  // Null there is correct and says nothing — the wizard offer stands alone, as it did.
437
437
  const cliEnv = envFileRead();
438
+ // NO DEFAULT, AND WHY. Unset is not "no pool": this used to fall back to /srv/trademark-archive, a
439
+ // deployed server's real client archive, so a forgotten export published into somebody else's matter.
440
+ // That history stays here; the reader is told what to set.
438
441
  throw new Error(
439
- `CLEAROTRON_REPORTS_DIR is not set, and it has NO default. Unset is not "no pool": this used to fall `
440
- + "back to /srv/trademark-archive, a deployed server's real client archive, so a forgotten export "
441
- + "published into somebody else's matter. Set it to the pool this install owns, e.g. "
442
+ "CLEAROTRON_REPORTS_DIR is not set, and it has no default. Set it to the folder this install publishes into, e.g. "
442
443
  + `CLEAROTRON_REPORTS_DIR=$HOME/trademark/pool — \`${invoke("install")}\` writes one for you` // backticked: issue 1916 can return a `cd … && npx …` form, which runs into the next words unquoted
443
444
  + (cliEnv ? `, or set it by hand in ${cliEnv} — the file this command reads, and the wizard refuses `
444
445
  + `when stdin is not a terminal.` : "."),
@@ -49,6 +49,8 @@ const FROM = {
49
49
  project: "this project",
50
50
  account: (noun) => `the account's default ${noun}`,
51
51
  none: "not set anywhere",
52
+ // No class anywhere, and the request describes its goods: the search is scoped by that description.
53
+ goodsOnly: "none — the goods description sets the scope",
52
54
  };
53
55
 
54
56
  const nonEmpty = (a) => Array.isArray(a) && a.length > 0;
@@ -284,7 +286,7 @@ export function resolveEffectiveScope(job = {}, profile = null, resolved = null)
284
286
  if (nonEmpty(job.classes)) { classes = job.classes; classesFrom = FROM.request; }
285
287
  else if (nonEmpty(saved?.classes)) { classes = saved.classes; classesFrom = FROM.savedSearch; }
286
288
  else if (nonEmpty(profile?.defaultClasses)) { classes = profile.defaultClasses; classesFrom = accountClFrom; }
287
- else { classes = []; classesFrom = FROM.none; }
289
+ else { classes = []; classesFrom = String(job.goods ?? "").trim() ? FROM.goodsOnly : FROM.none; }
288
290
 
289
291
  // Platforms UNION rather than replace, and they union in BOTH directions: the saved search's stores are
290
292
  // folded in first so a per-run addition sits on top of them, and neither can remove an account's own.
@@ -12,7 +12,7 @@
12
12
  // optimises toward sprinkling anchor tokens into boilerplate without genuine engagement. The pipeline
13
13
  // writes the sidecar and moves on; nothing gates on it.
14
14
  //
15
- // Same enforcement substrate and block-scan shape as use-check.mjs / own-rights.mjs: PURE over the
15
+ // The block-scan shape of the retired use-check and own-rights gates, now findings-record fields: PURE over the
16
16
  // narrative text (no node imports, tests offline); empty/missing input → no receipts, never throws.
17
17
 
18
18
  const STOP = new Set([
@@ -20,13 +20,13 @@ const STOP = new Set([
20
20
  "worldwide", "global", "mark", "marks", "your", "n/a", "none", "class", "classes",
21
21
  ]);
22
22
 
23
- // Composite digit from a finding block — same anchor as use-check.mjs.
23
+ // Composite digit from a finding block — the anchor the retired use-check gate used.
24
24
  function parseComposite(block) {
25
25
  const m = block.match(/\bComposite\b[^\d\n]{0,14}(\d)/i);
26
26
  return m ? Number(m[1]) : null;
27
27
  }
28
28
  // A block is a rated FINDING if its heading names a Finding or its body carries the BOLD Composite
29
- // marker — same gate as use-check.mjs, so the "## Actions" / "## Bottom line" paraphrases (which mention
29
+ // marker — the retired use-check gate's test, so the "## Actions" / "## Bottom line" paraphrases (which mention
30
30
  // composite in prose but not as the rated finding) never false-trigger.
31
31
  // EXPORTED so the write-up check identifies blocks by the same predicate this file already uses.
32
32
  // Two answers to "which blocks in narrative.md are per-finding write-ups" would drift, and the one that
@@ -21,7 +21,7 @@ import { statSync } from "node:fs";
21
21
  import { tmpdir } from "node:os";
22
22
  import { join, dirname } from "node:path";
23
23
  import { fileURLToPath } from "node:url";
24
- import { WRITE_DISCIPLINE, absolutizeSkillRefs, resolveSpawnCwd, spawnGraceMs } from "./common.mjs";
24
+ import { WRITE_DISCIPLINE, absolutizeSkillRefs, resolveSpawnCwd, spawnGraceMs, isRecordTool } from "./common.mjs";
25
25
  import { resolveEngineProgram, resolveModel } from "../driver.config.mjs"; // — the one place that finds the program; it reads every spelling of the setting
26
26
  import { authorityTrees } from "../authority-trees.mjs";
27
27
  import { recordEngineChild, clearEngineChild } from "./child-record.mjs"; //
@@ -623,6 +623,10 @@ export const anthropicAgentEngine = {
623
623
  // "omitted" on Opus 5, so an ENGAGED block streams with a zero-length `thinking` string and a real
624
624
  // `signature` — reading the text would report "no thinking" on every production turn.
625
625
  let thought = false;
626
+ // THE FIRST CALL'S CACHE SPLIT: how much of the opening prompt the provider served from its cache and how much it wrote
627
+ // to it, read off the first assistant message's usage. Every caching claim about a stage was rebuilt from raw streams
628
+ // by hand; this puts the first call's figures on the attempt. null when the stream carried no assistant message.
629
+ let firstCall = null;
626
630
  // MODEL GAUGE (corruption 3): which model the PROVIDER says served this turn. Until now
627
631
  // nothing on any record was a function of the provider's response — `modelUsed` was
628
632
  // `resolveModel(<the alias we asked for>)`, a pure function of the request, so a substitution or a
@@ -709,6 +713,9 @@ export const anthropicAgentEngine = {
709
713
  const writeAsks = new Set();
710
714
  let toolWaitMs = 0;
711
715
  let toolAskedAt = null;
716
+ // The last time this turn asked for a tool, apart from its own record write, and the last time it asked for that write:
717
+ // what the gateway reads to tell a turn killed while still working from one killed silent or finishing (`lastToolAsk`).
718
+ let lastWorkAskAt = null, lastRecordAskAt = null;
712
719
  // WHAT THE WAIT IS MADE OF, keyed by the tool(s) that caused it.
713
720
  //
714
721
  // The total alone cannot answer the question it was collected for. "Exclude tool wait from the kill
@@ -868,6 +875,7 @@ export const anthropicAgentEngine = {
868
875
  toolAskedNames = asked.length ? [...new Set(asked)].sort().join("+") : null;
869
876
  if (asked.length) {
870
877
  const now = Date.now();
878
+ if (asked.some((n) => !isRecordTool(n))) lastWorkAskAt = now; else lastRecordAskAt = now;
871
879
  closePeriod(now, false); // the outstanding set is about to change
872
880
  const rec = { names: asked.slice() };
873
881
  openAsks.push(rec);
@@ -881,6 +889,7 @@ export const anthropicAgentEngine = {
881
889
  // This block's usage, folded into its own call: the largest reading wins, so a block's early count
882
890
  // never replaces the delta's running total, and a second block of the same call adds nothing twice.
883
891
  foldUsage(ev.message?.id ?? openMessage ?? `__assistant_${++anonMessages}`, mapUsage(ev.message?.usage));
892
+ if (!firstCall && ev.message?.usage) firstCall = mapUsage(ev.message.usage);
884
893
  progress();
885
894
  }
886
895
  else if (ev.type === "user") {
@@ -1192,6 +1201,8 @@ export const anthropicAgentEngine = {
1192
1201
  // true = the 500-path cap dropped at least one further distinct file (so a `read:false` derived
1193
1202
  // from this list is unreliable and the consumer must downgrade it to "not observed").
1194
1203
  reads: [...reads], readsTruncated,
1204
+ // The first call's cache read and cache write, in tokens (see `firstCall`); null when it was never seen.
1205
+ firstCallCache: firstCall ? { read: firstCall.cacheRead, creation: firstCall.cacheWrite } : null,
1195
1206
  toolCalls, toolWaitMs: settledToolWaitMs, // two integers, no content
1196
1207
  // The same calls by tool name (values sum to toolCalls), and what the session went through: every
1197
1208
  // result, cut, refusal and restart (session-record.mjs). `stream` is the raw stream's file and size,
@@ -1209,6 +1220,9 @@ export const anthropicAgentEngine = {
1209
1220
  // ONLY: nothing branches on it. A recording field is protected by a test or by nothing, so
1210
1221
  // engine.anthropic.test.mjs pins it — deleting it must red something.
1211
1222
  firstByteMs: firstOutputAt === null ? null : Math.round(firstOutputAt - t0),
1223
+ // ms from spawn to the last tool ask that was not the stage's own record write, and to the last that was; null where
1224
+ // the turn made none. RECORDING, and read by the gateway only to choose how a hard-wall kill is retried.
1225
+ lastToolAsk: { workMs: lastWorkAskAt === null ? null : Math.round(lastWorkAskAt - t0), recordMs: lastRecordAskAt === null ? null : Math.round(lastRecordAskAt - t0) },
1212
1226
  // WHICH SIDE OF THE KILL a byte or a tool ask fell on. RECORDING ONLY, like firstByteMs. The
1213
1227
  // totals above keep counting after the decision, because what a dying child already wrote is
1214
1228
  // still read (streamed usage depends on it). On Windows the kill blocks this process while it
@@ -85,6 +85,13 @@ export const WRITE_DISCIPLINE =
85
85
  // to a layered overlay-over-base path (driver.config.resolveSkillPath); without it the legacy single-dir
86
86
  // behaviour stands.
87
87
  const SKILL_REF = /(?<![\w/.])skills\/[A-Za-z0-9._/-]+\.md/g;
88
+ /**
89
+ * Is this tool a stage's own record tool, the call that hands its result back? Any `record_*` tool, by its bare name or under
90
+ * an MCP server (`mcp__recording-<stage>__record_<stage>`). Both engines name a kill's last tool ask with it: a turn whose
91
+ * last asks were only its own record write was finishing, not working, when it was stopped. PURE.
92
+ */
93
+ export const isRecordTool = (name) => /(^|__)record_/.test(String(name ?? ""));
94
+
88
95
  export function absolutizeSkillRefs(message, skillsDir, resolve = null) {
89
96
  if (!message || (!skillsDir && !resolve)) return message;
90
97
  const base = skillsDir ? dirname(skillsDir) : null; // skillsDir ends in /skills; refs carry their own `skills/` prefix
@@ -24,6 +24,7 @@ import { answerBudget, quotedBytes } from "../../../shared/answer-parts.mjs";
24
24
  import { classifyRecord, prepareTargets, SHAPE_TIERS, isLiveRecord, niceClassKey, withoutPlacementOrders } from "../../band-shape.mjs";
25
25
  import { recordQids } from "../../named-band.mjs";
26
26
  import { normalizeRecordUri } from "../../registry-fidelity.mjs";
27
+ import { recordBodyFromLog } from "../../../providers/_shared/ledger.mjs"; // the run record log's own index, which the fetches write through
27
28
  import { bandGoodsIndex, goodsFor, goodsWordCounter, goodsWordsMatched, recordAsServed, untaggedIsEnglish, rowGoods } from "../../record-goods.mjs";
28
29
  import { recordGoodsEvidence, heldRecordProvenance, recordFetchOutcomes, readRunCallRows, goodsFromLabel, registerPageLabel } from "../../goods-evidence.mjs";
29
30
  import { savedStatusPages } from "../../saved-register-pages.mjs";
@@ -53,27 +54,17 @@ const recordLedgerPath = () => paths(RUN_DIR).registerRecordBodies;
53
54
  /**
54
55
  * The record body this run has already fetched, or null.
55
56
  *
56
- * Scanned only on a `_records/` miss — six times on the measured round, against 2,842 lines — so the
57
- * cost falls on the path that was previously answering wrongly, and never on the common one.
57
+ * Asked only on a `_records/` miss, and every record a stage reads before the end-of-run union is one.
58
+ * This read and parsed the whole log on each: a median 0.80 s, up to 147 s, measured on production's 0.4.x
59
+ * clearances, inside serial stages whose model waited for each answer. The answer now comes from the run
60
+ * record log's own index (`recordBodyFromLog`), which reads only what was appended since the last look.
58
61
  *
59
62
  * LAST WRITE WINS, matching `assembleRunRecords`: the ledger leg overrides the run-dir leg there, so a
60
63
  * later body is the current one here too. Two readers of one ledger must not disagree about which row
61
- * is authoritative.
64
+ * is authoritative, which is why there is one index and not a second one here.
62
65
  */
63
66
  function recordFromLedger(uri) {
64
- const p = recordLedgerPath();
65
- if (!existsSync(p)) return null;
66
- const want = normalizeRecordUri(uri) || String(uri).toLowerCase();
67
- let found = null;
68
- try {
69
- for (const line of readFileSync(p, "utf8").split("\n")) {
70
- if (!line.trim()) continue;
71
- let row; try { row = JSON.parse(line); } catch { continue; }
72
- const t = normalizeRecordUri(row?.target) || String(row?.target ?? "").toLowerCase();
73
- if (t && t === want && row?.body) found = row.body;
74
- }
75
- } catch { return null; }
76
- return found;
67
+ return recordBodyFromLog(recordLedgerPath(), uri);
77
68
  }
78
69
 
79
70
  // ── the reading log: EVERY lookup lands here, success or failure — the audit is the point ──────────
@@ -62,6 +62,9 @@ export const TOOL_SERVER_SETTINGS = Object.freeze([
62
62
  // characters: printed with its escapes and banner it stays under the general answer size below, and so under
63
63
  // the cut. An install's own smaller size still wins.
64
64
  export const CODEX_BAND_ANSWER_CHARS = 30000;
65
+ // The cut above in bytes, as the product measures it: 10,000 tokens at 4 bytes a token. The model is shown the first
66
+ // and last half of it. driver/manuals-seen.mjs reads a saved session's outputs through it; an estimate, not the vendor's.
67
+ export const CODEX_SHOWN_OUTPUT_BYTES = 10000 * 4;
65
68
  export const codexBandAnswerChars = (env = process.env) =>
66
69
  Math.min(CODEX_BAND_ANSWER_CHARS, Number(env.CLEAROTRON_BAND_RESPONSE_CHARS) || CODEX_BAND_ANSWER_CHARS);
67
70
 
@@ -39,7 +39,7 @@ import { serve } from "./stdio-server.mjs";
39
39
  import { recordSynthesis } from "../../synthesis-record.mjs"; // the writer
40
40
  import { correctionPositionsFrom } from "./correction-positions.mjs"; // the positions a correction's dispatch hands its save
41
41
  import { recordRegisterDigest } from "../../register-digest-record.mjs"; // conversion 11 — the findings document
42
- import { FINDING_KEYS_CURRENT, COVERAGE_AREA_STATES } from "../../findings-model.mjs";
42
+ import { FINDING_KEYS_CURRENT, COVERAGE_AREA_STATES, KNOCKOUT_FINDING_KEYS } from "../../findings-model.mjs";
43
43
  import { recordBlindFrame } from "../../blind-frame-record.mjs";
44
44
  import { VARIANT_DIRECTIONS, RANKING_BASES } from "../../blind-frame-model.mjs";
45
45
  import { recordSkeptic } from "../../skeptic-record.mjs";
@@ -275,6 +275,46 @@ async function search_run_artifacts(params) {
275
275
  return searchRunArtifacts(runDir, params);
276
276
  }
277
277
 
278
+ // ── THE KNOCKOUT FINDING, DECLARED FROM ITS KEY LIST ─────────────────────────────────────────────────────
279
+ //
280
+ // The two tools that carry a Knockout finding list its keys from `KNOCKOUT_FINDING_KEYS`, the list the
281
+ // recorder enforces, as `record_synthesis` lists the clearance's from its own ladder. Each tool keeps its own
282
+ // schema for a key, because the model reads each one's words and they are not the same words. A key on the
283
+ // list with no schema here is left out of what the tool lists, and the test that lists both tools names it.
284
+ const KNOCKOUT_ASSESS_FINDING_FIELDS = {
285
+ ordinal: { type: "integer", minimum: 1, description: "Unique within the mark, most blocking first. The code renumbers contiguously; yours breaks ties inside a band. Never cite a finding by number in prose." },
286
+ name: { type: "string", description: "The CONFLICTING name, verbatim." },
287
+ owner: { type: "string" },
288
+ band: { type: "string" },
289
+ // The framework's inputs behind the band, when the framework states a method: required on every finding
290
+ // then, refused otherwise (findings-model.mjs validateKnockoutFinding).
291
+ inputs: { type: "object", additionalProperties: { type: "string" }, description: "The framework's own inputs for this finding, keyed by its labels, each one of the values it lists." },
292
+ net: { type: "string", description: "One conclusion sentence." },
293
+ type: { type: "string" },
294
+ evidence: { type: "array", items: { type: "string" } },
295
+ basis: { type: "string", description: "The ground THIS FINDING's band rests on — not the mark's `basis`, which is a different field one level up." },
296
+ // The ninth key. This schema once said "all eight, no others" and forbade it while the recorder enforced
297
+ // nine, two closed sets that disagreed; listing the keys from the recorder's own list ends that.
298
+ weighedFilings: {
299
+ type: "array", items: { type: "string" },
300
+ description: "The register record ids whose evidence THIS finding's reasoning actually used, copied verbatim from the filings you were given. The report derives this finding's source labelling from it, and the driver joins every id against the run's own record store — so a Register label can never appear on a finding with no register evidence. Optional; omit it rather than guessing.",
301
+ },
302
+ };
303
+ const KNOCKOUT_CORRECTION_FINDING_FIELDS = {
304
+ ordinal: { type: "integer", description: "An existing finding's ordinal, or the next one for a new finding." },
305
+ name: { type: "string", description: "The conflicting name, verbatim." },
306
+ owner: { type: "string", description: "The party behind it, or \"not established on the searched material\"." },
307
+ band: { type: "string", description: "A word from the framework's ladder." },
308
+ inputs: { type: "object", description: "The framework's own inputs for this finding, where it states a method." },
309
+ net: { type: "string", description: "One conclusion sentence." },
310
+ type: { type: "string", description: "Famous Brand, Active Business, Cultural Reference, Domain, Descriptive Use, Negative Association or Competitor Intelligence." },
311
+ evidence: { type: "array", items: { type: "string" }, description: "URLs held for this name." },
312
+ basis: { type: "string", description: "The ground the band rests on." },
313
+ weighedFilings: { type: "array", items: { type: "string" }, description: "The register record ids this finding's reasoning used." },
314
+ };
315
+ const knockoutFindingProperties = (fields) =>
316
+ Object.fromEntries(KNOCKOUT_FINDING_KEYS.filter((k) => k in fields).map((k) => [k, fields[k]]));
317
+
278
318
  serve({
279
319
  name: "recording",
280
320
  tools: [{
@@ -1332,27 +1372,7 @@ serve({
1332
1372
  items: {
1333
1373
  type: "object", additionalProperties: false,
1334
1374
  required: ["ordinal", "name"],
1335
- properties: {
1336
- ordinal: { type: "integer", minimum: 1, description: "Unique within the mark, most blocking first. The code renumbers contiguously; yours breaks ties inside a band. Never cite a finding by number in prose." },
1337
- name: { type: "string", description: "The CONFLICTING name, verbatim." },
1338
- owner: { type: "string" },
1339
- band: { type: "string" },
1340
- // The framework's inputs behind the band, when the framework states a method: required on
1341
- // every finding then, refused otherwise (findings-model.mjs validateKnockoutFinding).
1342
- inputs: { type: "object", additionalProperties: { type: "string" }, description: "The framework's own inputs for this finding, keyed by its labels, each one of the values it lists." },
1343
- net: { type: "string", description: "One conclusion sentence." },
1344
- type: { type: "string" },
1345
- evidence: { type: "array", items: { type: "string" } },
1346
- basis: { type: "string", description: "The ground THIS FINDING's band rests on — not the mark's `basis`, which is a different field one level up." },
1347
- // — the ninth key, and the count above moved with it. The
1348
- // recorder's own DECLARED list has carried this field since
1349
- // while this object said eight and forbade it, so "all eight, no others" was a
1350
- // closed set that disagreed with the closed set actually enforced.
1351
- weighedFilings: {
1352
- type: "array", items: { type: "string" },
1353
- description: "The register record ids whose evidence THIS finding's reasoning actually used, copied verbatim from the filings you were given. The report derives this finding's source labelling from it, and the driver joins every id against the run's own record store — so a Register label can never appear on a finding with no register evidence. Optional; omit it rather than guessing.",
1354
- },
1355
- },
1375
+ properties: knockoutFindingProperties(KNOCKOUT_ASSESS_FINDING_FIELDS),
1356
1376
  },
1357
1377
  },
1358
1378
  },
@@ -1493,18 +1513,9 @@ serve({
1493
1513
  findings: {
1494
1514
  type: "array",
1495
1515
  description: "Only the findings you change or add, each whole.",
1496
- items: { type: "object", required: ["ordinal", "name", "owner", "band", "net", "type", "evidence", "basis"], properties: {
1497
- ordinal: { type: "integer", description: "An existing finding's ordinal, or the next one for a new finding." },
1498
- name: { type: "string", description: "The conflicting name, verbatim." },
1499
- owner: { type: "string", description: "The party behind it, or \"not established on the searched material\"." },
1500
- band: { type: "string", description: "A word from the framework's ladder." },
1501
- inputs: { type: "object", description: "The framework's own inputs for this finding, where it states a method." },
1502
- net: { type: "string", description: "One conclusion sentence." },
1503
- type: { type: "string", description: "Famous Brand, Active Business, Cultural Reference, Domain, Descriptive Use, Negative Association or Competitor Intelligence." },
1504
- evidence: { type: "array", items: { type: "string" }, description: "URLs held for this name." },
1505
- basis: { type: "string", description: "The ground the band rests on." },
1506
- weighedFilings: { type: "array", items: { type: "string" }, description: "The register record ids this finding's reasoning used." },
1507
- } },
1516
+ // The `required` list is kept as data: `inputs` and `weighedFilings` stay optional here, and no
1517
+ // `additionalProperties: false`, because either change would alter what the model may send.
1518
+ items: { type: "object", required: ["ordinal", "name", "owner", "band", "net", "type", "evidence", "basis"], properties: knockoutFindingProperties(KNOCKOUT_CORRECTION_FINDING_FIELDS) },
1508
1519
  },
1509
1520
  remove_findings: { type: "array", items: { type: "integer" }, description: "Ordinals the evidence shows should not be there." },
1510
1521
  },
@@ -28,7 +28,7 @@ import { newSessionRecord, noteCodexEvent, sessionSummary, countTool, streamSink
28
28
  import { writeSecretFile } from "../../shared/secret-file.mjs"; // the rotated login goes back the way every credential is written
29
29
  import { tmpdir, homedir } from "node:os";
30
30
  import { join, dirname, sep } from "node:path";
31
- import { runStreamingChild, absolutizeSkillRefs, WRITE_DISCIPLINE, buildEnvelope, resolveSpawnCwd } from "./common.mjs";
31
+ import { runStreamingChild, absolutizeSkillRefs, WRITE_DISCIPLINE, buildEnvelope, resolveSpawnCwd, isRecordTool } from "./common.mjs";
32
32
  import { renderCodexConfigToml } from "./mcp/codex-config.mjs";
33
33
  import { resolveAuthMode } from "./auth.mjs";
34
34
  import { engineEnv, codexCommandWithheld } from "./engine-env.mjs";
@@ -438,8 +438,10 @@ export function buildCodexArgs({ model, thinking, resumeRef, runDir } = {}) {
438
438
  return { args: [...base, "-"] };
439
439
  }
440
440
 
441
- // Fold ONE codex --json line into the running event accumulator.
442
- export function parseCodexEvent(line, ev) {
441
+ // Fold ONE codex --json line into the running event accumulator. `atMs` is when the line arrived, in ms from the
442
+ // spawn; given, it times the turn (see codexTiming), and a line that is not JSON still counts as the child speaking.
443
+ export function parseCodexEvent(line, ev, atMs = null) {
444
+ if (Number.isFinite(atMs)) ev.firstLineAtMs ??= atMs;
443
445
  let e; try { e = JSON.parse(line); } catch { return; }
444
446
  // MODEL GAUGE ( corruption 3) — OPPORTUNISTIC on the stream, and its answer here is "nothing".
445
447
  //
@@ -475,6 +477,7 @@ export function parseCodexEvent(line, ev) {
475
477
  }
476
478
  noteMcpToolCall(e.item, ev);
477
479
  noteToolItem(e.item, ev);
480
+ noteToolTiming(e.type, e.item, ev, atMs);
478
481
  break;
479
482
  // ── — AN MCP CALL THAT WAS REFUSED IS NOT A CALL NOBODY MADE ──────────
480
483
  //
@@ -498,6 +501,7 @@ export function parseCodexEvent(line, ev) {
498
501
  case "item.started":
499
502
  noteMcpToolCall(e.item, ev);
500
503
  noteToolItem(e.item, ev);
504
+ noteToolTiming(e.type, e.item, ev, atMs);
501
505
  break;
502
506
  default: break;
503
507
  }
@@ -533,12 +537,72 @@ const TOOL_ITEM_KINDS = new Set(["command_execution", "file_change", "web_search
533
537
  */
534
538
  export function noteToolItem(item, ev) {
535
539
  if (!item?.id) return;
536
- const name = item.type === "mcp_tool_call" ? `mcp__${item.server ?? "?"}__${item.tool ?? "?"}`
537
- : TOOL_ITEM_KINDS.has(item.type) ? item.type : null;
540
+ const name = toolItemName(item);
538
541
  if (!name) return;
539
542
  (ev.toolItems ??= new Map()).set(item.id, name);
540
543
  }
541
544
 
545
+ /** A tool-shaped item's name, as the per-name count and the wait split key it; null for anything else. */
546
+ const toolItemName = (item) => (item?.type === "mcp_tool_call" ? `mcp__${item.server ?? "?"}__${item.tool ?? "?"}`
547
+ : TOOL_ITEM_KINDS.has(item?.type) ? item.type : null);
548
+
549
+ // ── WHERE A CODEX TURN'S TIME WENT, ON THE ANTHROPIC ENGINE'S TERMS ─────────────────────────────────────────
550
+ //
551
+ // Codex attempts carried no start-up, tool-wait or active time, so a Codex turn's time could not be split between
552
+ // the engine starting, the model working and its tools running, and its stall window could not be set from any
553
+ // record. Its stream already says when each tool item opens (`item.started`) and closes (`item.completed`); what it
554
+ // lacked was the time each line arrived. Every line is now read with its arrival in ms from the spawn, and the
555
+ // fields mean what they mean on the Anthropic engine (anthropic-agent.mjs, the settled timing):
556
+ // - `firstByteMs`: spawn to the child's first line, null when it never spoke;
557
+ // - `toolWaitMs`: time with at least one tool item open, so two concurrent items count their overlap once, and an
558
+ // item still open when the turn ended counts up to the end;
559
+ // - `toolWaitByTool`: each resolved item's own open time under its name, which can sum past `toolWaitMs` for the
560
+ // same reason as on the Anthropic engine (concurrent items), and leaves out an item that never resolved;
561
+ // - `activeMs`: the wall less `toolWaitMs`, so the two tile the wall.
562
+ // The items counted as tool wait are the kinds this file counts as tool calls: MCP calls, shell commands, file
563
+ // changes and web searches; the Anthropic engine counts every tool it asks for, which covers the same kinds.
564
+ // RECORDING ONLY: nothing in the kill clocks, walls or retries reads these.
565
+ export function noteToolTiming(type, item, ev, atMs) {
566
+ if (!Number.isFinite(atMs) || !item?.id) return;
567
+ const name = toolItemName(item);
568
+ if (!name) return;
569
+ const t = (ev.toolTiming ??= { open: new Map(), since: null, waitMs: 0, byTool: Object.create(null) });
570
+ if (type === "item.started") {
571
+ if (t.open.has(item.id)) return;
572
+ // The last tool asked for, apart from the stage's own record write, and the last record write (see codexTiming).
573
+ if (isRecordTool(name)) ev.lastRecordAskMs = atMs; else ev.lastWorkAskMs = atMs;
574
+ if (t.open.size === 0) t.since = atMs;
575
+ t.open.set(item.id, atMs);
576
+ return;
577
+ }
578
+ if (type !== "item.completed") return;
579
+ const opened = t.open.get(item.id);
580
+ // An item that arrives already complete was never seen open: it is a call, with no wait anybody could time.
581
+ t.byTool[name] = (t.byTool[name] ?? 0) + (opened == null ? 0 : Math.max(0, atMs - opened));
582
+ if (opened == null) return;
583
+ t.open.delete(item.id);
584
+ if (t.open.size === 0) { t.waitMs += Math.max(0, atMs - t.since); t.since = null; }
585
+ }
586
+
587
+ /**
588
+ * The settled timing of a turn `wallMs` long (see above). An accumulator that was never timed reports null for each
589
+ * field: this engine could not measure, which is not "no wait". PURE.
590
+ */
591
+ export function codexTiming(ev, wallMs) {
592
+ if (!ev?.timed || !Number.isFinite(wallMs)) return { firstByteMs: null, toolWaitMs: null, activeMs: null, toolWaitByTool: null, lastToolAsk: null };
593
+ const t = ev.toolTiming;
594
+ const open = t?.open.size ? Math.max(0, wallMs - t.since) : 0;
595
+ const toolWaitMs = Math.min(Math.round(wallMs), Math.round((t?.waitMs ?? 0) + open));
596
+ return {
597
+ firstByteMs: Number.isFinite(ev.firstLineAtMs) ? Math.round(ev.firstLineAtMs) : null,
598
+ toolWaitMs, activeMs: Math.max(0, Math.round(wallMs) - toolWaitMs),
599
+ toolWaitByTool: Object.fromEntries(Object.entries(t?.byTool ?? {}).map(([k, v]) => [k, Math.round(v)])),
600
+ // ms from spawn to the last tool item opened that was not the stage's own record write, and to the last that was, as the
601
+ // Anthropic engine reports them; the gateway reads them to choose how a hard-wall kill is retried.
602
+ lastToolAsk: { workMs: Number.isFinite(ev.lastWorkAskMs) ? Math.round(ev.lastWorkAskMs) : null, recordMs: Number.isFinite(ev.lastRecordAskMs) ? Math.round(ev.lastRecordAskMs) : null },
603
+ };
604
+ }
605
+
542
606
  /**
543
607
  * The turn's tool calls by name, in the shape anthropic-agent records: an MCP call under
544
608
  * `mcp__<server>__<tool>`, and codex's own tool items under its own word for them. Counted once per item
@@ -863,6 +927,8 @@ function settleTuple({ r, ev, resumeRef }) {
863
927
  // through (session-record.mjs: every turn ending and stream error, in order), and the raw stream.
864
928
  toolCallsByName: codexToolCallsByName(ev), toolCallsErroredByName: codexToolServerErrors(ev),
865
929
  session: sessionSummary(ev.session), stream: ev.stream ?? null,
930
+ // Start-up, tool wait and active time, as the Anthropic engine reports them (codexTiming).
931
+ ...codexTiming(ev, r.wall * 1000),
866
932
  writesFailed: ev.writesFailed ?? 0,
867
933
  commandsFailed: ev.commandsFailed ?? 0,
868
934
  commandFailures: ev.commandFailures ?? [],
@@ -992,8 +1058,9 @@ export const openaiAgentEngine = {
992
1058
  // Stamped HERE, not at function entry: everything above is file writes that can take a moment, and
993
1059
  // a floor set too early would let a previous turn's rollout back in on a shared home.
994
1060
  const spawnedAtMs = Date.now();
1061
+ // `timed`: this turn's lines are read with their arrival times, so its timing fields are measurements.
995
1062
  const ev = { threadId: null, usage: null, agentText: "", turnCompleted: false, turnFailed: null, streamError: null, model: null, mcpCalls: new Map(),
996
- session: newSessionRecord() };
1063
+ session: newSessionRecord(), timed: true };
997
1064
  // The raw stream, one file per session beside its dispatch; every line codex wrote on stdout.
998
1065
  const sink = streamSink(streamFile);
999
1066
  const r = await runStreamingChild({
@@ -1004,7 +1071,7 @@ export const openaiAgentEngine = {
1004
1071
  env, stallSec, timeoutSec,
1005
1072
  onStdoutLine: (line) => {
1006
1073
  sink.write(`${line}\n`);
1007
- parseCodexEvent(line, ev);
1074
+ parseCodexEvent(line, ev, Date.now() - spawnedAtMs);
1008
1075
  let e; try { e = JSON.parse(line); } catch { return; }
1009
1076
  noteCodexEvent(ev.session, e, Date.now() - t0);
1010
1077
  },