Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
fix(reporting): describe a failed Tier 3 arm as incomplete, not as not run (#407)
Narendran Raghavan12b387f7a62b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f56aa6db..efbd6394 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,22 @@ All notable changes to SkillEvaluator are documented in this file.### Added+- Tier 3 reports show token usage per case, per agent and over all agents, as+ a measurement that is not scored. The JSON payload gains `token_usage`;+ `BENCHMARK.md` gains a **Token Usage** section; the Markdown report, the HTML+ report (under Measured Agent Resources), `validate --verbose` and+ `tier3 evaluate --verbose` show the same numbers. Cached tokens are part of+ the prompt and are not added again. Attempts that failed before scoring count+ as usage. Missing counters leave a partial total and are never estimated.+ The with-skill change needs complete counts for the same attempts in both+ arms, and both arms must have succeeded. Token usage never displaces score+ evidence: it joins the report payload last, and its case rows, then its sums,+ are left out, with a note, when the payload would pass its size or node+ limits, also after the run's next steps, `tier3 evaluate`'s case findings and+ `validate`'s applicability fields join it. A baseline that did not run is+ shown as not run, and a reused baseline's tokens are marked as used in the+ run it came from.+- Capability-gated CI onboarding for protected Tier 1 `--llm`/SkillSpectorchecks, independent Tier 3 gateway/judge settings and native agent models.Combined reports retain source-bound `BENCHMARK.md` cards for every outcome;@@ -660,6 +676,23 @@ All notable changes to SkillEvaluator are documented in this file.leaves its arm's LLM and tool totals `N/A` (`null` in JSON). Native ATIFtiming is unchanged.+- Tier 3 reports no longer say `baseline not run` for an agent whose baseline+ arm ran but failed, for example after one baseline attempt hit the agent+ timeout. `BENCHMARK.md` now shows that agent's with-skill scores as+ `90.0% — baseline incomplete (1 of 2 attempts scored); uplift unavailable`,+ or `baseline unavailable` when no baseline attempt scored, and keeps+ `baseline not run` for a skipped baseline. An **Agent coverage** list under+ the score table names each failed arm, including a failed with-skill arm,+ with its scored and expected attempts and the first Harbor exception type in+ words, such as `agent timeout error`; the Tier 3 row of the tier status+ table names the agent and arm. The JSON payload records the same facts in+ `coverage_notices`, which the HTML report shows under+ **Agent coverage notes** and the full terminal report+ (`validate --verbose` or `-r cli`) prints in the Tier 3 block, also when+ Tier 3 is non-blocking. The compact default `validate` view leaves them to+ the HTML and JSON reports and `BENCHMARK.md`. A failed arm still fails the+ agent and the run, and the notes say so.+- Tier 3 standard judges under `LLM_JUDGE_RETRY_POLICY=strict` with Bedrockas the provider no longer label a Bedrock error that the policy treats as anunavailable model, such as throttling, a missing or inaccessible model, ordiff --git a/docs/reports.mdx b/docs/reports.mdxindex eb14f99a..8c57052b 100644--- a/docs/reports.mdx+++ b/docs/reports.mdx@@ -931,9 +931,11 @@ Score, and publication eligibility.When the HTML report has no lift for an agent or dimension, its label sayswhy. **no baseline** means that row has no baseline score, for example after-`--skip-baseline`. **comparison unavailable** means a baseline score was-recorded but cannot be compared with the with-skill score, for example because-the arms used different score policies or no case kept matching judge models.+`--skip-baseline`, or after a baseline arm that ran but failed; the+**Agent coverage notes** described below tell the two apart.+**comparison unavailable** means a baseline score was recorded but cannot be+compared with the with-skill score, for example because the arms used+different score policies or no case kept matching judge models.For each LLM metric (`accuracy`, `goal_accuracy`, and `behavior_check`), casesthat used different judge models across the arms are excluded from that@@ -965,6 +967,47 @@ count as activation opportunities; missing or unsupported evidence remainsunknown. Eligibility is determined separately for each agent, so anotheragent with observed activation can still contribute a comparison.+An arm that ran but failed, for example because one baseline attempt hit the+agent timeout, fails the agent and the run, and the other arm keeps its+scores. Reports describe such an arm by how many of its attempts scored,+never as not run. In `BENCHMARK.md`, the agent's Overall and dimension cells+read `90.0% — baseline incomplete (1 of 2 attempts scored); uplift unavailable`, or+`baseline unavailable` when no baseline attempt scored. They read+`baseline failed (2 of 2 attempts scored)` when the arm failed with no attempt+missing, and `baseline failed` with no counts when its recorded counts are+unusable. A baseline skipped with `--skip-baseline` still reads+`baseline not run`. An **Agent coverage** list under the table names each+failed arm, how many of its attempts scored, and the first Harbor exception+type it recorded, in words such as `agent timeout error`. When the agent is+marked failed, the entry also says that the agent and the Tier 3 run are+marked failed. The Tier 3 row of the tier status table names the agent and+arm.++The canonical JSON payload lists the same facts in `coverage_notices`, one+entry per failed arm:++- `code`: `baseline_failed` or `with_skill_failed`, the arm whose recorded+ status is `failed`.+- `agent` and `condition` (`without_skill` or `with_skill`).+- `state`: `incomplete` when some attempts scored, `unavailable` when none+ scored, or `failed` when no attempt is missing or the counts are unusable.+- `scored_attempts` and `expected_attempts`: `null`, with `state` `failed`,+ when the arm's counters are missing or inconsistent, for example more scored+ than expected attempts, or no expected attempts after a job failure.+- `failure`: the first Harbor exception type in words, or `null`.+- `message`: the sentence the reports show.++The HTML report lists each message under **Agent coverage notes** at the top+of the Tier 3 section. Its agent details label an agent whose baseline arm+failed the way they label a skipped baseline, for example **no baseline** and+`baseline N/A`, so the callout is what tells the two apart. The full terminal+report, from `validate --verbose` or an explicit `-r cli`, prints the notes+under **Agent coverage notes** in the Tier 3 block, also when Tier 3 is+non-blocking (the default). The compact default view of `validate` does not+print them and leaves them to the HTML and JSON reports and `BENCHMARK.md`.+`tier3 evaluate` lists each agent's failed condition with its errors, as+before.+### Measured agent resourcesEach agent's canonical JSON payload contains a `resources` object. The HTML@@ -1014,6 +1057,80 @@ Missing timing stays `N/A` (`null` in JSON), never zero, and follows the samecomplete-arm and matching-case rules as tokens. Timing is diagnostic and doesnot change scores, verdicts, or gates.+### Token usage++The canonical JSON payload also carries a `token_usage` object when at least+one attempt recorded token counts and the report limits leave room for it (see+below). It sums the agent's own tokens per case, per+agent arm, and over all agents, and says how many attempts each sum covers. It+is a measurement: it is not scored and changes no metric, dimension, verdict,+or gate.++- Tokens are prompt plus completion (`total_tokens`). Prompt counts include+ cached tokens, so cached tokens are never added again;+ `uncached_prompt_tokens` is prompt minus cached. A missing cache counter+ counts as 0.+- Attempts that failed before scoring, such as an attempt that hit the agent+ timeout, still used tokens and are counted. So are the scored attempts of an+ arm that failed. `coverage.unscored_attempts` counts the attempts without a+ score. Such an attempt belongs to the case whose task directory its Harbor+ `result.json` or `config.json` names, or else to the case its trial name+ starts with. `resources` keeps its own totals, which need every attempt of an+ arm scored and measured.+- Nothing is estimated. An attempt with a missing or invalid counter adds no+ tokens. Its arm's `coverage.status` is then `partial` (other attempts were+ measured) or `unavailable` (none were), and the totals cover only the measured+ attempts. An arm that did not run is `not_run`, and its `totals` are `null`:+ a skipped arm, or an arm without attempts that the agent has no record of or+ that the payload `mode` leaves out (`with_skill_only` or `baseline_only`).+ The score tables show such a baseline as not run. A sum above+ 9,007,199,254,740,991 (`2^53 - 1`), the largest integer JSON keeps exact, is+ `unavailable` with `total_out_of_range` and `null` totals.+- `coverage` also gives `expected_attempts`, `observed_attempts`,+ `measured_attempts`, and `reason_codes` such as `missing_token_counters`,+ `invalid_token_counters`, and `missing_attempts`.+- `delta.total_tokens` is with skill minus baseline, and+ `delta.total_tokens_change_percent` divides it by the baseline. A change needs+ complete counts in both arms for the same cases and attempts, and both arms+ must have succeeded, because the report withholds the scores of any other arm.+ Otherwise `delta.status` is `unavailable` and `delta.reason_codes` and+ `delta.reason` say why, for example `baseline_not_run`, `baseline_failed`,+ `baseline_status_unknown` (the arm ran attempts without a recognized run+ status), `baseline_tokens_incomplete`, `baseline_total_out_of_range`,+ `case_scope_mismatch` (both arms ran attempts, for different cases or+ numbers of attempts per case), or `agent_scope_mismatch` for the sum over all+ agents.+- A run that reused an earlier run's baseline+ (`tier3 evaluate --reuse-baseline`) has `baseline_reused: true`. Its baseline+ counts come from the trajectories copied from that run: they are the tokens+ the baseline used there, not tokens used in this run, and every token usage+ table says so.++Token usage joins the payload after the report size budget, so it never+displaces trials or other score evidence. It also never pushes the payload past+the embedded size budget or the report limits that every report checks, such as+100,000 JSON values, including after the run's next steps, the case findings+that `tier3 evaluate` adds and `validate`'s applicability fields join it. When+it does not fit, its case rows go first: `token_usage.case_rows_omitted` and+`report_truncation.omitted.token_usage_case_rows` count them, and every report+says so. If the agent sums do not fit either, `token_usage` is left out and+`report_truncation.omitted.token_usage` is 1. If the payload cannot carry even+that record, for example because it exceeds the report limits without token+usage, `token_usage` is left out without a record, and every report marks the+payload as it would without token usage.++`BENCHMARK.md` has a **Token Usage** section after Results at a Glance: one row+per agent and one for all agents, with the case rows in a collapsed table that+shows the first 50 case rows. The Markdown report has the same table under its+Tier 3 section. The HTML report lists the case rows under **Measured Agent+Resources**, at most 64 per agent, read from the full Tier 3 data rather than+its bounded preview. Each table says how many more case rows are in the JSON+payload. The full terminal report (`validate --verbose` or `-r cli`) and+`tier3 evaluate --verbose` print the agent rows only and name the files that+hold the case rows: the HTML, Markdown and JSON reports for `validate`, and+`report.html` and `tier3-benchmark.md` in the run directory for+`tier3 evaluate`.+### Failure reasons and per-trial rowsEach evaluator card lists its per-trial evidence by eval case with thediff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.pyindex ca1b8151..4d521129 100644--- a/src/skillevaluator/cli.py+++ b/src/skillevaluator/cli.py@@ -2742,6 +2742,10 @@ def validate(agent_eval_payload.setdefault("applicability", "required")agent_eval_payload.setdefault("reason_code", "tier3_source_present")agent_eval_payload.setdefault("source_kind", source_kind)+ from skillevaluator.evaluation.tier3_report import fit_token_usage++ # Measured token usage makes room for these keys when the payload is at its limits.+ fit_token_usage(agent_eval_payload)tier3_result.metadata["gating"] = {"tier": 3, "blocking": block_on_agent_eval_effective}# Reporters and the exit gate consume the same finalized result objects.diff --git a/src/skillevaluator/evaluation/tier3_report.py b/src/skillevaluator/evaluation/tier3_report.pyindex ae81656f..29644819 100644--- a/src/skillevaluator/evaluation/tier3_report.py+++ b/src/skillevaluator/evaluation/tier3_report.py@@ -649,6 +649,8 @@ def render_agent_eval_html_report(_apply_saved_feedback(canonical_payload, saved_feedback, engine_result, run_dir, skill_path)else:_apply_case_findings(canonical_payload, engine_result, run_dir, skill_path, use_llm=use_llm_judge)+ # Restored feedback and fresh findings both join after the initial size budget.+ fit_token_usage(canonical_payload)if engine_result is not None and isinstance(canonical_payload, dict):# Persist only the compact feedback contract needed by the CLI. The# complete canonical payload remains in the HTML report and can be much@@ -657,6 +659,13 @@ def render_agent_eval_html_report("schema_version": _TIER3_FEEDBACK_SCHEMA_VERSION,**{field: list(canonical_payload.get(field) or []) for field in _TIER3_FEEDBACK_FIELDS},}+ from skillevaluator.tier3.token_usage import per_agent_token_usage++ # The terminal summary prints token usage per agent; per-case rows stay in the report files.+ if token_usage := per_agent_token_usage(canonical_payload.get("token_usage")):+ engine_result["token_usage"] = token_usage+ else:+ engine_result.pop("token_usage", None)target = output_path.expanduser().resolve() if output_path is not None else run_dir / "report.html"from skillevaluator.publication_identity import publication_target_name@@ -1142,6 +1151,27 @@ def build_agent_eval_payload(payload["case_selection"] = dict(case_selection)if harbor_summary:payload["harbor_viewer"] = harbor_summary+ from skillevaluator.reporting.tier3_coverage import coverage_notices++ # Name each arm that ran but failed, so no report reads its missing scores+ # as an arm that never ran.+ if notices := coverage_notices(agent_payloads):+ payload["coverage_notices"] = notices+ from skillevaluator.tier3.token_usage import USAGE_ONLY_ATTEMPT_KEYS, build_token_usage++ # Measured, never scored: token usage per case and agent, counting attempts+ # that failed before scoring. Scores and ``resources`` do not read it. It+ # joins the payload after the budget, so it never displaces score evidence.+ baseline_record = (run_config or {}).get("baseline")+ token_usage = build_token_usage(+ {+ name: {**agent, **{key: agents.get(name, {}).get(key) for key in USAGE_ONLY_ATTEMPT_KEYS}}+ for name, agent in agent_payloads.items()+ },+ mode=mode,+ # A reused baseline's copied trajectories hold the tokens of the run it came from.+ baseline_reused=isinstance(baseline_record, dict) and baseline_record.get("mode") == "reused",+ )_layer_llm_insights(payload,@@ -1173,6 +1203,10 @@ def build_agent_eval_payload()payload = _sanitize_json_numbers(payload)_enforce_report_payload_budget(payload, report_budget, enforce_size=enforce_embedded_size)+ if token_usage:+ payload["token_usage"] = _sanitize_json_numbers(token_usage)+ if enforce_embedded_size:+ fit_token_usage(payload)return payload@@ -1611,6 +1645,89 @@ def _enforce_report_payload_budget(refresh_signal()+# ``report_truncation.omitted`` keys that only token usage adds.+_TOKEN_USAGE_OMISSIONS = ("token_usage", "token_usage_case_rows")+++def fit_token_usage(payload: dict[str, Any]) -> None:+ """Keep measured token usage from costing a bounded payload its report limits.++ Token usage is unscored, so it may never push a payload past the embedded+ size budget or make it fail the report serialization limits (nodes, depth+ and text) that every reporter checks. It joins the payload last, after the+ size budget, so it gives way first: its per-case rows, then its sums, each+ drop recorded in ``report_truncation``. If not even that record fits, the+ token usage and its records go, which leaves the payload as it is without+ token usage. Code that adds fields to a built payload, such as case findings+ or ``validate``'s applicability keys, calls this again.+ """+ omitted = _report_omissions(payload)+ if "token_usage" not in payload and not (omitted and any(key in omitted for key in _TOKEN_USAGE_OMISSIONS)):+ return+ if _token_usage_fits(payload):+ return+ if "token_usage" in payload:+ from skillevaluator.tier3.token_usage import drop_token_usage_cases++ dropped = drop_token_usage_cases(payload["token_usage"])+ if (+ dropped+ and _record_token_usage_omission(payload, "token_usage_case_rows", dropped)+ and _token_usage_fits(payload)+ ):+ return+ del payload["token_usage"]+ if _record_token_usage_omission(payload, "token_usage", 1) and _token_usage_fits(payload):+ return+ _remove_token_usage_omissions(payload)+++def _report_omissions(payload: dict[str, Any]) -> dict[str, Any] | None:+ truncation = payload.get("report_truncation")+ omitted = truncation.get("omitted") if isinstance(truncation, dict) else None+ return omitted if isinstance(omitted, dict) else None+++def _token_usage_fits(payload: dict[str, Any]) -> bool:+ from skillevaluator.reporting.base import agent_eval_report_serialization_issue++ # The minimal last-resort payload carries no details.+ if "payload_sections" in (_report_omissions(payload) or {}):+ return False+ try:+ size = _serialized_payload_size(payload)+ except (TypeError, ValueError):+ return False+ return size <= _MAX_EMBEDDED_REPORT_BYTES and agent_eval_report_serialization_issue(payload) is None+++def _record_token_usage_omission(payload: dict[str, Any], section: str, count: int) -> bool:+ """Count a token usage drop in ``report_truncation``; ``False`` when its record cannot take it."""+ if "report_truncation" not in payload:+ payload["report_truncation"] = _ReportBudget(omitted={section: count}).signal()+ return True+ omitted = _report_omissions(payload)+ if omitted is None:+ return False+ previous = omitted.get(section)+ total = count + (previous if isinstance(previous, int) and not isinstance(previous, bool) else 0)+ payload["report_truncation"]["omitted"] = dict(sorted({**omitted, section: total}.items()))+ return True+++def _remove_token_usage_omissions(payload: dict[str, Any]) -> None:+ """Take token usage's keys out of ``report_truncation``, and the record when only they made it."""+ omitted = _report_omissions(payload)+ if omitted is None or not any(key in omitted for key in _TOKEN_USAGE_OMISSIONS):+ return+ remaining = {key: value for key, value in omitted.items() if key not in _TOKEN_USAGE_OMISSIONS}+ truncation = payload["report_truncation"]+ if remaining or truncation.get("artifact_loading"):+ truncation["omitted"] = remaining+ else:+ del payload["report_truncation"]++def _serialized_payload_size(payload: dict[str, Any]) -> int:return len(json.dumps(payload, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8"))diff --git a/src/skillevaluator/reporting/benchmark.py b/src/skillevaluator/reporting/benchmark.pyindex df594be0..ea475dd4 100644--- a/src/skillevaluator/reporting/benchmark.py+++ b/src/skillevaluator/reporting/benchmark.py@@ -53,7 +53,9 @@ from skillevaluator.reporting.base import ()from skillevaluator.reporting.run_status import resolve_run_statusfrom skillevaluator.reporting.summary_copy import SKILL_LIFT_DEFINITION, pass_at_k_summary+from skillevaluator.reporting.tier3_coverage import IncompleteArm, incomplete_armsfrom skillevaluator.reporting.tier3_scope import completed_agent_result, validate_report_scope+from skillevaluator.reporting.tier3_token_usage import token_usage_markdown_linesfrom skillevaluator.source_identity import evaluated_source_revision, recorded_evaluated_sourcefrom skillevaluator.tier3.baseline_store import baseline_descriptionfrom skillevaluator.tier3.dataset_provenance import dataset_provenance_display@@ -68,6 +70,8 @@ if TYPE_CHECKING:# These fields are empty because the orchestration input did not supply them,# which is a different cause from the legacy/non-live wording used elsewhere._SOURCE_UNRECORDED = "not recorded (not supplied by the orchestration input)"+# Case rows of the token usage table. The card has a size limit; the JSON payload keeps every case.+_MAX_TOKEN_USAGE_CASE_ROWS = 50_SIGNAL_DESCRIPTIONS = {"security": "unsafe operations, secret leakage, and unauthorized access",@@ -283,6 +287,8 @@ class BenchmarkReporter(ReporterBase):)self._render_report_purpose(lines)self._render_results_at_a_glance(lines, ae, private_labels)+ lines.extend(_agent_coverage_lines(ae, private_labels))+ lines.extend(_token_usage_lines(ae, private_labels))self._render_tier_status(lines,results,@@ -499,7 +505,7 @@ class BenchmarkReporter(ReporterBase):private_labels: tuple[str, ...],) -> None:lines.extend(["## Results at a Glance", ""])- agents = _agents(ae)+ agents = {name: _with_incomplete_baseline(agent) for name, agent in _agents(ae).items()}if not agents:lines.extend([@@ -787,6 +793,8 @@ class BenchmarkReporter(ReporterBase):evidence = "Completed-agent quality result; publication not assessed"if completed["needs_attention"]:evidence += "; other execution failures need attention"+ if tier == "Tier 3" and tier_results and (incomplete := _incomplete_arm_evidence(ae, private_labels)):+ evidence = f"{evidence}; {incomplete}"lines.append(f"| {tier} | {purpose} | **{status}** | {_md_cell(evidence, private_labels)} |")lines.append("")@@ -1241,6 +1249,61 @@ def _human_agent_name(name: str) -> str:return humanized.replace("Skill" + "evaluator", "SkillEvaluator")+def _with_incomplete_baseline(agent: dict[str, Any]) -> dict[str, Any]:+ """Return ``agent`` for the score table, with a failed baseline arm in place of its baseline scores.++ A baseline arm that ran but failed has no baseline score, which the table+ would otherwise print as ``baseline not run``. With the arm in its place,+ each cell says how many baseline attempts scored instead.+ """+ arm = next((arm for arm in incomplete_arms(agent) if arm.condition == "without_skill"), None)+ if arm is None:+ return agent+ dimensions = agent.get("dimensions")+ if isinstance(dimensions, list):+ dimensions = [{**item, "baseline": arm} if isinstance(item, dict) else item for item in dimensions]+ return {**agent, "baseline": arm, "dimensions": dimensions}+++def _agent_coverage_lines(ae: dict[str, Any] | None, private_labels: tuple[str, ...]) -> list[str]:+ """List each agent arm that ran but failed, with its scored attempts and first recorded failure."""+ notes = [+ f"{_agent_display_label(name, agent, private_labels)}: {arm.describe()}"+ for name, agent in _agents(ae).items()+ for arm in incomplete_arms(agent)+ ]+ if not notes:+ return []+ return ["### Agent coverage", "", *(f"- {_publication_safe_inline(note, private_labels)}" for note in notes), ""]+++def _token_usage_lines(ae: dict[str, Any] | None, private_labels: tuple[str, ...]) -> list[str]:+ """Show measured token usage per agent and per case; it is not scored."""+ agents = _mapping(ae.get("agents")) if ae else {}++ def agent_label(name: str | None) -> str:+ if name is None:+ return "All agents"+ return _md_cell(_agent_display_label(name, _mapping(agents.get(name)), private_labels), private_labels)++ return token_usage_markdown_lines(+ (ae or {}).get("token_usage"),+ heading="## Token Usage",+ agent_label=agent_label,+ cell=lambda value: _md_cell(value, private_labels),+ max_case_rows=_MAX_TOKEN_USAGE_CASE_ROWS,+ )+++def _incomplete_arm_evidence(ae: dict[str, Any] | None, private_labels: tuple[str, ...]) -> str:+ """Name each agent arm that ran but failed, for the Tier 3 evidence cell."""+ return ", ".join(+ f"{_agent_display_label(name, agent, private_labels)} {arm}"+ for name, agent in _agents(ae).items()+ for arm in incomplete_arms(agent)+ )++def _evaluated_at(ae: dict[str, Any] | None) -> str | None:return agent_eval_publication_evaluated_at(ae)@@ -1552,7 +1615,12 @@ def _score_transition_values(if skill_never_activated:# No uplift is shown, so the baseline neither sets the precision nor withholds the score.parsed_baseline = None- elif baseline is not None and (parsed_baseline is None or not 0 <= parsed_baseline <= 1):+ elif (+ baseline is not None+ # A failed baseline arm (see ``_with_incomplete_baseline``) is described below, not scored.+ and not isinstance(baseline, IncompleteArm)+ and (parsed_baseline is None or not 0 <= parsed_baseline <= 1)+ ):return "Not available"endpoints = (parsed_score,) if parsed_baseline is None else (parsed_baseline, parsed_score)decimal_places = _score_display_decimal_places(*endpoints)@@ -1560,6 +1628,8 @@ def _score_transition_values(skill_label = _format_percentage(displayed_score, decimal_places)if skill_never_activated:return f"{skill_label} — INCONCLUSIVE: skill never activated; uplift unavailable"+ if isinstance(baseline, IncompleteArm):+ return f"{skill_label} — {baseline}; uplift unavailable"if parsed_baseline is None:if baseline_not_applicable:return f"{skill_label} — baseline N/A (no skill in the baseline arm)"diff --git a/src/skillevaluator/reporting/cli.py b/src/skillevaluator/reporting/cli.pyindex 1a2d94cf..1fdd881f 100644--- a/src/skillevaluator/reporting/cli.py+++ b/src/skillevaluator/reporting/cli.py@@ -108,6 +108,16 @@ def _rich_skip_reason(result: ValidationResult) -> str:return _rich_line(get_skip_reason(result))+def _coverage_notice_messages(agent_eval: object) -> list[str]:+ """Return the Tier 3 coverage notice messages the Tier 3 block prints."""+ notices = agent_eval.get("coverage_notices") if isinstance(agent_eval, dict) else None+ return [+ notice["message"]+ for notice in (notices if isinstance(notices, list) else [])+ if isinstance(notice, dict) and isinstance(notice.get("message"), str) and notice["message"]+ ]++class CLIReporter(ReporterBase):"""Terminal-based reporter with Rich formatting.@@ -190,7 +200,14 @@ class CLIReporter(ReporterBase):console.print()failed = [result for result in results if not passes_required_gate(result)]- non_blocking = [result for result in results if passes_required_gate(result) and result.findings]+ # A non-blocking Tier 3 result (the ``validate`` default) can fail with+ # no findings; its coverage notes still say which agent arm failed.+ non_blocking = [+ result+ for result in results+ if passes_required_gate(result)+ and (result.findings or _coverage_notice_messages((result.metadata or {}).get("agent_eval")))+ ]rendered_result_ids = {id(result) for result in (*failed, *non_blocking)}for result in results:metadata = result.metadata if isinstance(result.metadata, dict) else {}@@ -612,6 +629,19 @@ class CLIReporter(ReporterBase):console.print(table)console.print()+ # Name arms that ran but failed, so a missing baseline or score is not read as an arm that never ran.+ coverage_messages = _coverage_notice_messages(agent_eval)+ if coverage_messages:+ console.print("[bold]Agent coverage notes[/bold]")+ for message in coverage_messages:+ console.print(f" • {escape_markup(message)}", soft_wrap=True)+ console.print()++ from skillevaluator.reporting.tier3_token_usage import VALIDATE_CASE_POINTER, render_token_usage_table++ if render_token_usage_table(console, agent_eval.get("token_usage"), case_pointer=VALIDATE_CASE_POINTER):+ console.print()+recommendations = agent_eval.get("recommendations") or []if recommendations:printed = Falsediff --git a/src/skillevaluator/reporting/dashboard_data.py b/src/skillevaluator/reporting/dashboard_data.pyindex d5294bd4..3f18cb8d 100644--- a/src/skillevaluator/reporting/dashboard_data.py+++ b/src/skillevaluator/reporting/dashboard_data.py@@ -129,6 +129,9 @@ def _trial_coverage_truncated(marker: dict[str, Any]) -> bool:# Non-best detail pruning is checked per agent against its declared counts.diagnostics = {"raw_trial_rewards",+ # Token usage is measured, not scored, and the trials stay.+ "token_usage_case_rows",+ "token_usage","raw_detail_fields","raw_reward_fields","raw_metric_values",diff --git a/src/skillevaluator/reporting/html.py b/src/skillevaluator/reporting/html.pyindex 7f23b21b..49da6560 100644--- a/src/skillevaluator/reporting/html.py+++ b/src/skillevaluator/reporting/html.py@@ -99,6 +99,7 @@ from skillevaluator.reporting.presentation import (from skillevaluator.reporting.run_status import Status, result_status, result_tierfrom skillevaluator.reporting.tier2_views import tier2_scope_viewsfrom skillevaluator.reporting.tier3_scope import completed_agent_result, validate_report_scope+from skillevaluator.reporting.tier3_token_usage import token_usage_tablefrom skillevaluator.reporting.trial_charts import steps_by_case_chartfrom skillevaluator.skillspector_provenance import skillspector_provenance_recordsfrom skillevaluator.source_identity import recorded_evaluated_source@@ -131,6 +132,9 @@ _TIER3_JSON_SAFE_PRIORITY_KEYS = ("schema_version","verdict","execution_status",+ # A few hundred bytes that explain a failed agent arm. Walked before the+ # bulky keys, so the bounded HTML preview keeps every message whole.+ "coverage_notices","summary","correct_answers","skill_name",@@ -1299,6 +1303,16 @@ def _sanitize_tier3_display_payload(value: dict[str, Any]) -> dict[str, Any]:payload[key] = _tier3_identifier_list(payload.get(key))for key in ("execution_errors", "suggestions"):payload[key] = _string_list(payload.get(key))+ # The template lists each notice's message; drop entries without one.+ coverage_notices = [+ notice+ for notice in _dict_list(payload.get("coverage_notices"))+ if isinstance(notice.get("message"), str) and notice["message"]+ ]+ if coverage_notices:+ payload["coverage_notices"] = coverage_notices+ else:+ payload.pop("coverage_notices", None)# ``skill_name`` was already validated above as an exact NFC filesystem# identity. Do not pass it through compatibility-normalizing display text.for key in ("best_agent", "verdict", "execution_status"):@@ -1463,7 +1477,9 @@ def _bounded_tier3_preview(payload: dict[str, Any] | None) -> tuple[dict[str, Anif not payload:return payload, {}# A private copy: the caller embeds ``payload`` itself as the canonical data.- slim = json.loads(_compact_json(payload))+ # The token usage table reads the full payload, so ``token_usage`` neither+ # triggers the preview nor spends its budget.+ slim = json.loads(_compact_json({key: value for key, value in payload.items() if key != "token_usage"}))# Activation diagnostics belong to the canonical export. The template does# not render them, so duplicate per-trial copies must not spend overview or# failure-reason space before the preview budget is applied.@@ -3595,6 +3611,11 @@ class HTMLReporter(ReporterBase):tier3_truncation=tier3_truncation,tier3_dataset_sufficiency=tier3_dataset_sufficiency,tier3_preview_notice=tier3_preview_notice,+ # Measured, not scored. From the full display payload, with its own+ # per-agent cap: the preview walk can blank strings of late keys.+ tier3_token_usage=token_usage_table(+ tier3_data.get("token_usage") if isinstance(tier3_data, dict) else None+ ),# From the full display payload: the bounded preview can cap rows# unevenly per condition and blank identity fields of late rows.steps_by_case_chart=steps_by_case_chart(diff --git a/src/skillevaluator/reporting/markdown.py b/src/skillevaluator/reporting/markdown.pyindex 353d9948..8207bec2 100644--- a/src/skillevaluator/reporting/markdown.py+++ b/src/skillevaluator/reporting/markdown.py@@ -54,6 +54,8 @@ if TYPE_CHECKING:_SKIP_REASON_MAX_CHARS = 1024+# Case rows of the Tier 3 token usage table; the JSON payload keeps every case.+_MAX_TOKEN_USAGE_CASE_ROWS = 50def _markdown_safe_characters(value: str, *, preserve_newlines: bool = False) -> str:@@ -442,6 +444,18 @@ class MarkdownReporter(ReporterBase):)lines.append("")+ from skillevaluator.reporting.tier3_token_usage import token_usage_markdown_lines++ lines.extend(+ token_usage_markdown_lines(+ ae.get("token_usage"),+ heading="### Token Usage",+ agent_label=lambda agent: _markdown_untrusted_table_cell("All agents" if agent is None else agent),+ cell=_markdown_untrusted_table_cell,+ max_case_rows=_MAX_TOKEN_USAGE_CASE_ROWS,+ )+ )+insights = _mapping(ae.get("insights"))insight_rows = [(dimension, info)diff --git a/src/skillevaluator/reporting/templates/report.html.j2 b/src/skillevaluator/reporting/templates/report.html.j2index de96aad8..486dd882 100644--- a/src/skillevaluator/reporting/templates/report.html.j2+++ b/src/skillevaluator/reporting/templates/report.html.j2@@ -2430,6 +2430,7 @@.t3-truncation-notice { background:var(--badge-warn-bg); border:1px solid var(--warning-color); border-left:4px solid var(--warning-color); border-radius:10px; color:var(--dark-text); margin:0 0 1rem; padding:0.8rem 1rem; }.t3-truncation-notice strong { display:block; margin-bottom:0.3rem; }.t3-truncation-notice ul { display:flex; flex-wrap:wrap; gap:0.25rem 1rem; margin:0.35rem 0 0; padding-left:1.2rem; font-size:0.82rem; color:var(--text-secondary); }+ .t3-coverage-notice ul { display:block; font-size:0.88rem; color:var(--dark-text); }/* Insight source tag (deterministic vs LLM) */.t3-insight-source { display:inline-block; padding:0.05rem 0.4rem; border-radius:4px; font-size:0.65rem; font-weight:800; text-transform:uppercase; letter-spacing:0.04em; vertical-align:middle; margin-left:0.35rem; }.insight-source-deterministic { background:var(--bg-secondary); color:var(--text-secondary); border:1px solid var(--border-color); }@@ -2517,6 +2518,18 @@</div>{% endif %}+ {% set t3_coverage_messages = (tier3.coverage_notices or []) | selectattr('message', 'string') | map(attribute='message') | select | list %}+ {% if t3_coverage_messages %}+ <div class="t3-truncation-notice t3-coverage-notice" id="tier3-coverage-notices" role="status">+ <strong>Agent coverage notes</strong>+ <ul>+ {% for message in t3_coverage_messages %}+ <li>{{ message }}</li>+ {% endfor %}+ </ul>+ </div>+ {% endif %}+{# ---------- Overview ---------- #}<section class="t3-page active" id="tier3-page-overview" role="tabpanel" aria-labelledby="tier3-tab-overview" tabindex="0">{% set t3_effect = (tier3.conclusions or []) | selectattr('title', 'equalto', 'Skill effect') | first %}@@ -3174,6 +3187,27 @@<p class="t3-section-hint">{{ name }} timing source: with skill {{ t3_timing_source_text(t3_timing_sources.with_skill or []) }}; baseline {{ t3_timing_source_text(t3_timing_sources.baseline or []) }}.{% if 'mixed_timing_sources' in (agent.resources.caveats or []) %} The measurements mix native and inferred timing, so LLM and tool seconds are not like-for-like.{% endif %}</p>{% endif %}{% endfor %}+ {% if tier3_token_usage %}+ <div id="t3-token-usage">+ <p class="t3-section-hint"><strong>Token usage by case.</strong> {{ tier3_token_usage.note }}</p>+ <div class="table-scroll"><table class="summary-table">+ <thead><tr><th>Agent</th><th>Case</th><th>With skill</th><th>Baseline</th><th>Change</th><th>Measured attempts</th></tr></thead>+ <tbody>+ {% for row in tier3_token_usage.rows %}+ <tr{% if not row.is_case %} style="font-weight:600"{% endif %}><td>{{ row.agent if row.agent is not none else 'All agents' }}</td><td>{{ row.case }}</td><td>{{ row.with_skill }}</td><td>{{ row.baseline }}</td><td>{{ row.change }}</td><td>{{ row.coverage }}</td></tr>+ {% endfor %}+ </tbody>+ </table></div>+ <p class="t3-section-hint">{{ tier3_token_usage.coverage_note }}</p>+ {% if tier3_token_usage.reused_baseline %}<p class="t3-section-hint">{{ tier3_token_usage.reused_baseline }}</p>{% endif %}+ {% for row in tier3_token_usage.rows if row.note %}+ <p class="t3-section-hint">{{ row.agent if row.agent is not none else 'All agents' }}: {{ row.note }}</p>+ {% endfor %}+ {% for note in [tier3_token_usage.more_cases, tier3_token_usage.dropped_cases] if note %}+ <p class="t3-section-hint">{{ note }}</p>+ {% endfor %}+ </div>+ {% endif %}</div></details>{% endif %}diff --git a/src/skillevaluator/reporting/tier3_coverage.py b/src/skillevaluator/reporting/tier3_coverage.pynew file mode 100644index 00000000..97c3069f--- /dev/null+++ b/src/skillevaluator/reporting/tier3_coverage.py@@ -0,0 +1,154 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+"""Describe Tier 3 agent arms that ran but did not complete.++Each Tier 3 agent runs a with-skill arm and a no-skill baseline arm. When one+arm fails, for example because an attempt hit the agent timeout, the other arm+keeps its scores and the failed arm has none. Reports must not read that gap+as an arm that never ran. These helpers read the per-condition counters the+collector records (``conditions.<arm>.execution_status``, ``scored_attempts``+and ``expected_attempts``), so the JSON payload, the HTML report, the terminal+and ``BENCHMARK.md`` describe the gap in the same words.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from typing import Any++_ARM_LABELS = {"with_skill": "with-skill run", "without_skill": "baseline"}+_NOT_REPORTED = {+ "with_skill": "With-skill scores and uplift are not reported for this agent.",+ "without_skill": "Baseline and uplift are not reported for this agent.",+}+# The code names the arm whose recorded status is ``failed``; ``state`` says how+# many of its attempts scored.+_NOTICE_CODES = {"with_skill": "with_skill_failed", "without_skill": "baseline_failed"}+# Harbor records a failed trial as ``ExceptionType: message`` after the trial+# label. Only the type name is kept, as plain words, so it is safe to publish.+_EXCEPTION_TYPE = re.compile(r"(?:^|: )(?:[A-Za-z_]\w{0,63}\.){0,8}([A-Z][A-Za-z0-9]{0,63}(?:Error|Exception))(?=:|$)")+# An acronym keeps its trailing digits: ``S3UploadFailedError`` gives ``s3 upload+# failed error`` and ``HTTP2Error`` gives ``http2 error``.+_CAMEL_WORD = re.compile(r"[A-Z]+[0-9]*(?![a-z])|[A-Z][a-z0-9]*")+# The collector's case-coverage diagnostics list case IDs after the colon, and a+# case ID can look like an exception type. They never name a failure.+_CASE_LIST_DIAGNOSTICS = (+ "Missing scored attempts for cases",+ "Excess scored attempts for cases",+ "Unexpected scored cases",+)+_MAX_COUNT = 2**63 - 1+++@dataclass(frozen=True)+class IncompleteArm:+ """One agent arm that ran but failed, with how many of its attempts scored.++ ``str()`` gives the short form used in report cells, such as+ ``baseline incomplete (1 of 2 attempts scored)``.+ """++ condition: str+ scored: int | None+ expected: int | None+ failure: str | None = None+ agent_failed: bool = False++ @property+ def counts_known(self) -> bool:+ """Whether the counters are usable: attempts were expected and the scored count does not exceed them."""+ if self.scored is None or self.expected is None:+ return False+ return self.expected > 0 and self.scored <= self.expected++ @property+ def state(self) -> str:+ """``incomplete`` (some attempts scored), ``unavailable`` (none scored) or ``failed``.++ ``failed`` means no attempt is missing, or the counters are unusable.+ """+ if not self.counts_known or self.scored == self.expected:+ return "failed"+ return "incomplete" if self.scored else "unavailable"++ def __str__(self) -> str:+ counts = f" ({self.scored} of {self.expected} attempts scored)" if self.counts_known else ""+ return f"{_ARM_LABELS[self.condition]} {self.state}{counts}"++ def describe(self) -> str:+ """Return the arm, its state, its counts and the first recorded failure, then what is not reported.++ When the agent's recorded status is ``failed``, the text also says that+ the agent and the Tier 3 run are marked failed: any failed agent fails+ the run.+ """+ details = [f"{self.scored} of {self.expected} attempts scored"] if self.counts_known else []+ if self.failure:+ details.append(f"first failure: {self.failure}")+ detail_text = f" ({'; '.join(details)})" if details else ""+ outcome = " The agent and the Tier 3 run are marked failed." if self.agent_failed else ""+ return f"{_ARM_LABELS[self.condition]} {self.state}{detail_text}.{outcome} {_NOT_REPORTED[self.condition]}"+++def incomplete_arms(agent: object) -> list[IncompleteArm]:+ """Return the agent's arms whose recorded ``execution_status`` is ``failed``.++ A skipped arm (``--skip-baseline`` or ``--skip-with-skill``) did not run,+ so it is not incomplete. Missing or malformed condition records give no+ arms rather than a guess.+ """+ if not isinstance(agent, dict) or not isinstance(conditions := agent.get("conditions"), dict):+ return []+ agent_failed = agent.get("execution_status") == "failed"+ arms = []+ for condition in _ARM_LABELS:+ record = conditions.get(condition)+ if not isinstance(record, dict) or record.get("execution_status") != "failed":+ continue+ arms.append(+ IncompleteArm(+ condition,+ _count(record.get("scored_attempts")),+ _count(record.get("expected_attempts")),+ _first_failure(record.get("execution_errors")),+ agent_failed,+ )+ )+ return arms+++def coverage_notices(agents: dict[str, Any]) -> list[dict[str, Any]]:+ """Return one notice per incomplete arm, in agent order, for the canonical payload."""+ notices = []+ for name, agent in agents.items():+ for arm in incomplete_arms(agent):+ notices.append(+ {+ "code": _NOTICE_CODES[arm.condition],+ "agent": name,+ "condition": arm.condition,+ "state": arm.state,+ "scored_attempts": arm.scored if arm.counts_known else None,+ "expected_attempts": arm.expected if arm.counts_known else None,+ "failure": arm.failure,+ "message": f"{name} {arm.describe()}",+ }+ )+ return notices+++def _count(value: object) -> int | None:+ return value if type(value) is int and 0 <= value <= _MAX_COUNT else None+++def _first_failure(errors: object) -> str | None:+ """Name the first Harbor exception type in an arm's errors, in words (``agent timeout error``)."""+ if not isinstance(errors, list):+ return None+ for error in errors:+ if not isinstance(error, str) or error.startswith(_CASE_LIST_DIAGNOSTICS):+ continue+ if match := _EXCEPTION_TYPE.search(error):+ return " ".join(word.lower() for word in _CAMEL_WORD.findall(match.group(1)))+ return Nonediff --git a/src/skillevaluator/reporting/tier3_token_usage.py b/src/skillevaluator/reporting/tier3_token_usage.pynew file mode 100644index 00000000..8c9bd9cb--- /dev/null+++ b/src/skillevaluator/reporting/tier3_token_usage.py@@ -0,0 +1,286 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+"""Table rows for the Tier 3 ``token_usage`` payload, shared by every report.++The terminal, the Markdown report, ``BENCHMARK.md`` and the HTML report all+render the same cells from these rows, so the reports agree word for word.+Each renderer escapes the agent and case names for its own format.+"""++from __future__ import annotations++from collections.abc import Callable, Mapping+from dataclasses import dataclass+from typing import TYPE_CHECKING, Any++from rich.table import Table+from rich.text import Text++if TYPE_CHECKING:+ from rich.console import Console++#: The explanation printed with every token usage table.+TOKEN_USAGE_NOTE = (+ "Measured agent token usage. It is not scored and changes no score or verdict. "+ "Tokens are prompt plus completion; prompt tokens include cached tokens, which are not added again. "+ "Attempts that failed before scoring are counted. A partial total covers only the attempts with "+ "token counts; nothing is estimated. Change is with skill minus baseline, as a share of the baseline, "+ "and needs complete counts for the same attempts in both arms."+)+#: Header of the coverage column: measured attempts of the expected ones in each arm.+COVERAGE_HEADER = "Measured attempts"+#: Explains the coverage column under every table.+COVERAGE_NOTE = (+ "Measured attempts: attempts with token counts, of those expected, in each arm. "+ "Unscored attempts failed before scoring."+)+#: Said under the table of a run that reused an earlier run's baseline (``--reuse-baseline``).+REUSED_BASELINE_NOTE = (+ "This run reused the baseline of an earlier run, so the baseline tokens were used in that run, not in this one."+)+#: Where ``validate``'s terminal report, which prints agent rows only, sends readers for case rows.+VALIDATE_CASE_POINTER = "Token usage per case is in the HTML, Markdown and JSON reports (-r html, markdown or json)."+#: Where ``tier3 evaluate``'s terminal summary sends readers for case rows.+EVALUATE_CASE_POINTER = "Token usage per case is in report.html and tier3-benchmark.md in the run directory."+#: Case rows per agent in the HTML table; the JSON payload keeps the rest.+HTML_CASE_ROWS_PER_AGENT = 64+++@dataclass(frozen=True)+class TokenUsageRow:+ """One row: an agent's case, an agent's ``All cases`` sum, or the all-agent sum (``agent`` is ``None``)."""++ agent: str | None+ case: str+ is_case: bool+ with_skill: str+ baseline: str+ change: str+ coverage: str+ note: str | None = None+++def _mapping(value: object) -> Mapping[str, Any]:+ return value if isinstance(value, Mapping) else {}+++def _count(value: object) -> int | None:+ return value if type(value) is int and value >= 0 else None+++def _coverage(arm: object) -> Mapping[str, Any]:+ return _mapping(_mapping(arm).get("coverage"))+++def _arm_cell(arm: object) -> str:+ coverage = _coverage(arm)+ if coverage.get("status") == "not_run":+ return "not run"+ total = _count(_mapping(_mapping(arm).get("totals")).get("total_tokens"))+ if total is None or not _count(coverage.get("measured_attempts")):+ return "N/A"+ return f"{total:,}" if coverage.get("status") == "complete" else f"{total:,} (partial)"+++def _change_cell(delta: object) -> str:+ delta = _mapping(delta)+ difference = delta.get("total_tokens")+ if delta.get("status") != "available" or type(difference) is not int:+ return "N/A"+ percent = delta.get("total_tokens_change_percent")+ if isinstance(percent, int | float) and not isinstance(percent, bool):+ return f"{difference:+,} ({percent:+.1f}%)"+ return f"{difference:+,}"+++def _coverage_part(label: str, arm: object) -> str:+ coverage = _coverage(arm)+ if coverage.get("status") == "not_run":+ return f"{label} not run"+ measured = _count(coverage.get("measured_attempts")) or 0+ expected = _count(coverage.get("expected_attempts")) or 0+ unscored = _count(coverage.get("unscored_attempts")) or 0+ return f"{label} {measured}/{expected}" + (f" ({unscored} unscored)" if unscored else "")+++def _row(agent: str | None, case: str | None, item: Mapping[str, Any]) -> TokenUsageRow:+ """Build one row; ``case`` is ``None`` for an ``All cases`` sum, which alone carries a note."""+ delta = _mapping(item.get("delta"))+ reason = delta.get("reason")+ not_run = any(_coverage(item.get(arm)).get("status") == "not_run" for arm in ("with_skill", "baseline"))+ note = reason if case is None and isinstance(reason, str) and reason and not not_run else None+ return TokenUsageRow(+ agent,+ "All cases" if case is None else case,+ case is not None,+ _arm_cell(item.get("with_skill")),+ _arm_cell(item.get("baseline")),+ _change_cell(delta),+ "; ".join((_coverage_part("skill", item.get("with_skill")), _coverage_part("baseline", item.get("baseline")))),+ note,+ )+++def more_case_rows_note(count: int, *, code: Callable[[str], str] = lambda text: f"`{text}`") -> str | None:+ """Say how many case rows a table left out; ``code`` formats the payload key."""+ return f"{count} more case row(s) are in the JSON payload under {code('token_usage')}." if count else None+++def reused_baseline_note(usage: object) -> str | None:+ """Say that the baseline tokens come from an earlier run when this run reused its baseline."""+ return REUSED_BASELINE_NOTE if _mapping(usage).get("baseline_reused") is True else None+++def dropped_case_rows_note(usage: object) -> str | None:+ """Say how many case rows the report payload dropped to stay within the report limits, if any."""+ count = _count(_mapping(usage).get("case_rows_omitted"))+ if not count:+ return None+ return (+ f"{count:,} case row(s) were left out of this report to keep it within the report size limits; "+ "the agent sums cover every attempt."+ )+++def token_usage_rows(+ usage: object,+ *,+ include_cases: bool = True,+ max_case_rows: int | None = None,+ max_case_rows_per_agent: int | None = None,+) -> tuple[list[TokenUsageRow], int]:+ """Return the rows of ``usage`` and how many case rows the caps left out.++ Each agent gets an ``All cases`` row followed by its case rows; the+ all-agent row comes last when more than one agent ran. ``max_case_rows``+ caps the case rows of all agents together and ``max_case_rows_per_agent``+ those of each agent. Only agent and all-agent rows carry a note: a case's+ change is unavailable for the same reasons, which its cells already show.+ """+ usage = _mapping(usage)+ agents = _mapping(usage.get("agents"))+ rows: list[TokenUsageRow] = []+ omitted = 0+ case_rows = 0+ for name, agent in agents.items():+ if not isinstance(name, str) or not isinstance(agent, Mapping):+ continue+ rows.append(_row(name, None, agent))+ if not include_cases:+ continue+ cases = agent.get("cases")+ agent_rows = 0+ for case in cases if isinstance(cases, list) else []:+ if not isinstance(case, Mapping):+ continue+ if (max_case_rows is not None and case_rows >= max_case_rows) or (+ max_case_rows_per_agent is not None and agent_rows >= max_case_rows_per_agent+ ):+ omitted += 1+ continue+ case_rows += 1+ agent_rows += 1+ rows.append(_row(name, str(case.get("entry_id") or "unknown"), case))+ dataset = usage.get("dataset")+ if isinstance(dataset, Mapping) and sum(not row.is_case for row in rows) > 1:+ rows.append(_row(None, None, dataset))+ return rows, omitted+++def token_usage_markdown_lines(+ usage: object,+ *,+ heading: str,+ agent_label: Callable[[str | None], str],+ cell: Callable[[str], str],+ max_case_rows: int,+) -> list[str]:+ """Return a Markdown token usage section: agent rows, then case rows in a collapsed table.++ ``agent_label`` gives the display name of an agent (``None`` is all+ agents) and ``cell`` escapes an untrusted case name for a table cell.+ """+ rows, omitted = token_usage_rows(usage, max_case_rows=max_case_rows)+ if not rows:+ return []+ header = f"| Agent | Case | With skill | Baseline | Change | {COVERAGE_HEADER} |"+ separator = "|---|---|---:|---:|---:|---|"++ def line(row: TokenUsageRow) -> str:+ cells = (agent_label(row.agent), cell(row.case), row.with_skill, row.baseline, row.change, row.coverage)+ return "| " + " | ".join(cells) + " |"++ summary = [row for row in rows if not row.is_case]+ cases = [row for row in rows if row.is_case]+ lines = [heading, "", TOKEN_USAGE_NOTE, "", header, separator, *(line(row) for row in summary), ""]+ lines.extend([COVERAGE_NOTE, ""])+ if reused := reused_baseline_note(usage):+ lines.extend([reused, ""])+ notes = [f"- {agent_label(row.agent)}: {row.note}" for row in summary if row.note]+ if notes:+ lines.extend([*notes, ""])+ if dropped := dropped_case_rows_note(usage):+ lines.extend([dropped, ""])+ if cases:+ lines.extend(["<details>", "<summary>Show token usage per case</summary>", "", header, separator])+ lines.extend(line(row) for row in cases)+ lines.append("")+ if more := more_case_rows_note(omitted):+ lines.extend([more, ""])+ lines.extend(["</details>", ""])+ return lines+++def render_token_usage_table(+ console: Console, usage: object, *, case_pointer: str, text: Callable[[str], str] = str+) -> bool:+ """Print one row per agent and the all-agent row, then the notes; return whether anything printed.++ ``case_pointer`` names the files of the calling command that hold the+ case rows. ``text`` makes agent names and notes safe for the console, for+ example by redacting secrets. Cells are plain text, never console markup.+ """+ rows, _omitted = token_usage_rows(usage, include_cases=False)+ if not rows:+ return False+ table = Table(title="Token Usage (measured, not scored)", show_header=True, header_style="bold")+ table.add_column("Agent", style="bold")+ for column in ("With skill", "Baseline", "Change"):+ table.add_column(column, justify="right")+ table.add_column(COVERAGE_HEADER)+ for row in rows:+ table.add_row(+ Text(text(row.agent if row.agent is not None else "All agents")),+ Text(row.with_skill),+ Text(row.baseline),+ Text(row.change),+ Text(row.coverage),+ )+ console.print(table)+ if reused := reused_baseline_note(usage):+ console.print(Text(f" {reused}"))+ for row in rows:+ if row.note:+ console.print(Text(f" {text(row.agent if row.agent is not None else 'All agents')}: {text(row.note)}"))+ pointer = " ".join(part for part in (case_pointer, dropped_case_rows_note(usage)) if part)+ console.print(Text(f" {TOKEN_USAGE_NOTE} {COVERAGE_NOTE} {pointer}", style="dim"))+ return True+++def token_usage_table(usage: object) -> dict[str, Any] | None:+ """Return the HTML report's token usage table, or ``None`` without rows.++ Each agent shows its first :data:`HTML_CASE_ROWS_PER_AGENT` case rows;+ ``more_cases`` says how many more are in the JSON payload.+ """+ rows, omitted = token_usage_rows(usage, max_case_rows_per_agent=HTML_CASE_ROWS_PER_AGENT)+ if not rows:+ return None+ return {+ "rows": rows,+ "note": TOKEN_USAGE_NOTE,+ "coverage_note": COVERAGE_NOTE,+ "reused_baseline": reused_baseline_note(usage),+ "more_cases": more_case_rows_note(omitted, code=str),+ "dropped_cases": dropped_case_rows_note(usage),+ }diff --git a/src/skillevaluator/tier3/harbor/report_data.py b/src/skillevaluator/tier3/harbor/report_data.pyindex 902691dd..bdf38352 100644--- a/src/skillevaluator/tier3/harbor/report_data.py+++ b/src/skillevaluator/tier3/harbor/report_data.py@@ -646,6 +646,12 @@ def aggregate_execution_error_details(}+_USAGE_COUNTERS = ("prompt_tokens", "completion_tokens", "cached_tokens")+# Attempts that count for token usage only, per arm: they never reach scores,+# pass@k or resource totals. See ``skillevaluator.tier3.token_usage``.+_USAGE_ONLY_KEYS = {"with_skill": "usage_only_attempts", "without_skill": "usage_only_attempts_baseline"}++def _trajectory_token_counter(value: Any) -> int | None:"""Return a browser-safe token counter without inventing zero usage."""return (@@ -688,6 +694,89 @@ def _condition_status(agent_info: dict[str, Any], condition: str) -> str:return str(data.get("execution_status") or "unknown") if isinstance(data, dict) else "unknown"+def _usage_tokens(counters: dict[str, Any]) -> dict[str, int] | None:+ """Return a report trial's ``tokens`` object, or ``None`` without prompt and completion counts."""+ prompt = _trajectory_token_counter(counters.get("prompt_tokens"))+ completion = _trajectory_token_counter(counters.get("completion_tokens"))+ if prompt is None or completion is None:+ return None+ tokens = {"prompt": prompt, "completion": completion}+ raw_cached = counters.get("cached_tokens")+ cached = _trajectory_token_counter(raw_cached)+ if raw_cached is not None and cached is None:+ # An invalid recorded counter is not Harbor's omitted zero cache.+ return None+ if cached is not None:+ tokens["cached"] = cached+ return tokens+++def _harbor_task_directory(trial_dir: Path) -> str | None:+ """Return the task directory a Harbor trial ran, from its copied ``result.json`` or ``config.json``.++ A generated task's directory is named after its case. The files are+ optional, so an unreadable or oversized one only gives ``None``.+ """+ for artifact, keys in (("result", (("task_id",), ("config", "task"))), ("config", (("task",),))):+ path = trial_dir / f"{artifact}.json"+ data = _load_bounded_json(path, [], artifact=artifact) if path.is_file() else None+ for key_path in keys if isinstance(data, dict) else ():+ task: Any = data+ for key in key_path:+ task = task.get(key) if isinstance(task, dict) else None+ task_path = task.get("path") if isinstance(task, dict) else None+ if not isinstance(task_path, str):+ continue+ # The run may have used either path separator.+ directory = task_path.replace("\\", "/").strip().rstrip("/").rsplit("/", 1)[-1]+ if directory:+ return directory+ return None+++def _unscored_attempt_usage(trial_dir: Path) -> dict[str, Any]:+ """Read the token counters of an attempt that has no usable reward.++ The attempt is not scored, but it ran and used tokens. Its case is the task+ directory its Harbor result or config names. Without one, it is the trial+ name before Harbor's ``__<id>`` suffix, which never contains ``__`` while a+ case ID may. Its trajectory is optional telemetry, so an unreadable or+ oversized file only leaves the counters out and does not mark score+ evidence truncated.+ """+ attempt: dict[str, Any] = {+ "entry_id": _harbor_task_directory(trial_dir) or trial_dir.name.rsplit("__", 1)[0] or "unknown",+ "trial_id": trial_dir.name,+ "scored": False,+ }+ trajectory_file = trial_dir / "trajectory.json"+ trajectory = _load_bounded_json(trajectory_file, [], artifact="trajectory") if trajectory_file.exists() else None+ final_metrics = trajectory.get("final_metrics") if isinstance(trajectory, dict) else None+ if isinstance(final_metrics, dict):+ tokens = _usage_tokens({name: final_metrics.get(f"total_{name}") for name in _USAGE_COUNTERS})+ if tokens is not None:+ attempt["tokens"] = tokens+ return attempt+++def _withheld_attempt_usage(rewards: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Return the token usage of scored attempts whose arm's scores are not reported.++ One row per logical attempt. As in report trials, an attempt scored over+ several reward rows has no token counts.+ """+ rows = []+ for group in logical_trial_reward_groups(rewards):+ reward = group[0]+ row: dict[str, Any] = {"entry_id": reward.get("entry_id"), "trial_id": reward.get("trial_id"), "scored": True}+ counters = reward.get("_traj")+ tokens = _usage_tokens(counters) if len(group) == 1 and isinstance(counters, dict) else None+ if tokens is not None:+ row["tokens"] = tokens+ rows.append(row)+ return rows++def load_agent_data(results_dir: Path,*,@@ -863,6 +952,7 @@ def load_agent_data(for variant_key, variant_dir_name in (("rewards", "with-skill"), ("rewards_baseline", "without-skill")):trial_list: list[dict[str, Any]] = []+ unscored_attempts: list[dict[str, Any]] = []count_key = "num_trials" if variant_key == "rewards" else "num_trials_baseline"reward_row_count_key = "num_reward_rows" if variant_key == "rewards" else "num_reward_rows_baseline"expected_logical_trials = agent_info.get(count_key)@@ -900,10 +990,13 @@ def load_agent_data(reward_file = trial_dir / "reward.json"if not reward_file.exists():rewards_complete = False+ # Not scored, but its token usage still counts.+ unscored_attempts.append(_unscored_attempt_usage(trial_dir))continuereward = _load_bounded_json(reward_file, agent_diagnostics, artifact="reward")if not isinstance(reward, dict):rewards_complete = False+ unscored_attempts.append(_unscored_attempt_usage(trial_dir))continue# Derive links from the bounded, admitted on-disk layout rather# than accepting verifier-authored paths as provenance.@@ -955,6 +1048,9 @@ def load_agent_data(rewards_complete = Falseagent_info[variant_key] = trial_listagent_info[f"{variant_key}_complete"] = rewards_complete+ agent_info[_USAGE_ONLY_KEYS["with_skill" if variant_key == "rewards" else "without_skill"]] = (+ unscored_attempts+ )if "with_skill" not in agent_info:continue@@ -1023,6 +1119,11 @@ def load_agent_data(condition_status = _condition_status(agent_info, condition)if condition_status == "succeeded":continue+ # The arm's scores are withheld below, but its scored attempts used tokens.+ agent_info[_USAGE_ONLY_KEYS[condition]] = [+ *_withheld_attempt_usage(agent_info.get(fields[-1]) or []),+ *agent_info.get(_USAGE_ONLY_KEYS[condition], []),+ ]condition_info = condition_execution.get(condition, {})for field in fields:if field.startswith("pass_") and condition_status in {"failed", "unknown"}:diff --git a/src/skillevaluator/tier3/result_display.py b/src/skillevaluator/tier3/result_display.pyindex 6aca2642..49399100 100644--- a/src/skillevaluator/tier3/result_display.py+++ b/src/skillevaluator/tier3/result_display.py@@ -1184,6 +1184,11 @@ def render_evaluation_result(_render_dimensions(console=console, agents=agents, safe=safe)+ from skillevaluator.reporting.tier3_token_usage import EVALUATE_CASE_POINTER, render_token_usage_table++ # Measured, not scored: per-agent token sums the report step recorded.+ render_token_usage_table(console, result.get("token_usage"), case_pointer=EVALUATE_CASE_POINTER, text=safe)+# The per-evaluator findings report — evaluator reasonings, evidence# pointers, and next-step suggestions — is the feedback surface that# follows the score tables.diff --git a/src/skillevaluator/tier3/token_usage.py b/src/skillevaluator/tier3/token_usage.pynew file mode 100644index 00000000..556324f7--- /dev/null+++ b/src/skillevaluator/tier3/token_usage.py@@ -0,0 +1,533 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Tier 3 token usage per case, per agent and over all agents.++Each Tier 3 attempt records the agent's token counters in its ATIF trajectory.+This module adds them up per case, per agent arm and over all agents, and says+how many attempts the sums cover. It is a measurement only: it changes no+metric, dimension, overall score, verdict or gate.++- Prompt counters include cached tokens (ATIF ``total_prompt_tokens`` does), so+ cached tokens are a part of the prompt and are never added again.+ ``total_tokens`` is prompt plus completion, and ``uncached_prompt_tokens`` is+ prompt minus cached.+- Nothing is estimated. An attempt with a missing or invalid counter adds no+ tokens. Its arm's coverage is then ``partial`` (other attempts were measured)+ or ``unavailable`` (none were), and the totals cover only measured attempts.+- An attempt that failed before it was scored still used tokens. It is counted+ here as an unscored attempt and nowhere else: scores never include it.+- A change (with skill minus baseline) needs complete counts in both arms for+ the same cases and attempts, and both arms must have succeeded: the report+ withholds the scores of an arm that failed or has no known run status.+- A sum above 2**53 - 1, the largest integer JSON keeps exact, is not reported.++``resource_comparison`` keeps its own totals, which need every attempt of an+arm scored and measured; this module does not change them.+"""++from __future__ import annotations++import re+from collections import Counter+from collections.abc import Mapping+from dataclasses import dataclass+from typing import Any++from skillevaluator.tier3.harbor.resource_usage import _MAX_SAFE_INTEGER, _is_measurement++TOKEN_USAGE_SCHEMA_VERSION = "1"+TOKEN_MEASURES = (+ "prompt_tokens",+ "cached_tokens",+ "uncached_prompt_tokens",+ "completion_tokens",+ "total_tokens",+)+# Loaded agent data keeps, per arm, the attempts whose usage no report trial+# carries: attempts without a usable reward (``scored`` false) and scored+# attempts of an arm whose scores are withheld. See ``report_data.load_agent_data``.+USAGE_ONLY_ATTEMPT_KEYS = ("usage_only_attempts", "usage_only_attempts_baseline")+# (payload arm, condition key, report trials key, usage-only attempts key)+_ARMS = (+ ("with_skill", "with_skill", "trials", "usage_only_attempts"),+ ("baseline", "without_skill", "trials_baseline", "usage_only_attempts_baseline"),+)+_ARM_NAMES = {"with_skill": "with-skill run", "baseline": "baseline"}+# Harbor names a trial after its task, cut to 32 characters, and the task after+# its case. A failed attempt without a Harbor result carries only that trial name.+_HARBOR_TRIAL_NAME_CHARS = 32+# A stop-on-pass attempt's trial is named ``<skill>-<agent>-<with|without>-<case>-attemptNNN__<Harbor trial>``.+_STOP_ON_PASS_ATTEMPT = re.compile(r"-attempt0*[1-9][0-9]*__.")+# Run statuses whose scores the report reads (``succeeded``), that never ran+# (``skipped``), or that the coverage notices name (``failed``).+_KNOWN_ARM_STATUSES = {"succeeded", "skipped", "failed"}+# The condition each payload ``mode`` leaves out, as the reports read it.+_UNEXECUTED_CONDITIONS = {+ "with_skill_only": frozenset({"without_skill"}),+ "baseline_only": frozenset({"with_skill"}),+}+_ACCOUNTING = {+ "prompt_includes_cached": True,+ "total_tokens": "prompt_tokens + completion_tokens",+ "uncached_prompt_tokens": "prompt_tokens - cached_tokens",+ "change": "with_skill - baseline total_tokens; percent of the baseline total",+}+++def _count(value: object) -> int | None:+ """Return a non-negative whole token count; bools, strings, fractions and NaN are not counts."""+ return int(value) if _is_measurement(value) and float(value).is_integer() else None+++def normalize_token_counts(raw: object) -> dict[str, Any] | None:+ """Normalize one attempt's token counters, or return ``None`` when it recorded none.++ ``raw`` is a report trial's ``tokens`` object (``prompt``, ``completion``,+ ``cached``) or ATIF-style counters (``prompt_tokens`` and so on). Harbor+ omits a zero cache counter, so a missing cached count is 0 once the prompt+ count is present. ``complete`` is ``False`` when a counter is missing or+ invalid, or when cached exceeds prompt; ``invalid_counters`` names the+ rejected fields, never their values.+ """+ if not isinstance(raw, Mapping):+ return None+ counts: dict[str, int | None] = {}+ invalid: list[str] = []+ for field, short in (("prompt_tokens", "prompt"), ("completion_tokens", "completion"), ("cached_tokens", "cached")):+ value = raw.get(short, raw.get(field))+ counts[field] = _count(value)+ if value is not None and counts[field] is None:+ invalid.append(field)+ if all(count is None for count in counts.values()) and not invalid:+ return None+ prompt, completion, cached = counts["prompt_tokens"], counts["completion_tokens"], counts["cached_tokens"]+ if cached is None and prompt is not None and "cached_tokens" not in invalid:+ cached = 0+ if prompt is not None and cached is not None and cached > prompt:+ invalid.append("cached_tokens")+ cached = None+ normalized: dict[str, Any] = {+ "prompt_tokens": prompt,+ "cached_tokens": cached,+ "uncached_prompt_tokens": prompt - cached if prompt is not None and cached is not None else None,+ "completion_tokens": completion,+ "total_tokens": prompt + completion if prompt is not None and completion is not None else None,+ "complete": not invalid and all(value is not None for value in (prompt, completion, cached)),+ }+ if invalid:+ normalized["invalid_counters"] = sorted(invalid)+ return normalized+++@dataclass(frozen=True)+class _Attempt:+ case: str+ tokens: dict[str, Any] | None+ scored: bool+++def _mapping(value: object) -> Mapping[str, Any]:+ return value if isinstance(value, Mapping) else {}+++def _rows(value: object) -> list[Mapping[str, Any]]:+ return [item for item in value if isinstance(item, Mapping)] if isinstance(value, list) else []+++def _case_label(trial: Mapping[str, Any]) -> str:+ for key in ("entry_id", "trial_id"):+ value = trial.get(key)+ if isinstance(value, str) and value:+ return value+ return "unknown"+++def _stop_on_pass_case(trial_id: str, case: str) -> bool:+ """Whether ``trial_id`` is a stop-on-pass attempt of ``case``: ``...-<with|without>-<case>-attemptNNN__...``."""+ marker = f"-{case}"+ index = trial_id.rfind(marker + "-attempt")+ return (+ index >= 0+ and trial_id[:index].endswith(("-with", "-without"))+ and _STOP_ON_PASS_ATTEMPT.match(trial_id, index + len(marker)) is not None+ )+++def _matching_case(label: str, trial_id: str, known_cases: set[str]) -> str:+ """Map an unscored attempt to its case when exactly one case matches.++ ``label`` is the case directory the attempt's Harbor result names, or its+ trial name without Harbor's ``__<id>`` suffix. Without a known case of that+ name, a stop-on-pass trial name or Harbor's 32-character cut of the case+ name decides.+ """+ if label in known_cases:+ return label+ for matches in (+ [case for case in known_cases if _stop_on_pass_case(trial_id, case)],+ [case for case in known_cases if case[:_HARBOR_TRIAL_NAME_CHARS].rstrip("_-") == label],+ ):+ if len(matches) == 1:+ return matches[0]+ return label+++def _pass_at_k_branch(agent: Mapping[str, Any], condition: str) -> Mapping[str, Any]:+ return _mapping(_mapping(agent.get("pass_at_k")).get(condition))+++def _agent_attempts(agent: Mapping[str, Any]) -> dict[str, list[_Attempt]]:+ known_cases = {_case_label(trial) for _arm, _condition, key, _usage in _ARMS for trial in _rows(agent.get(key))}+ for _arm, condition, _key, usage_key in _ARMS:+ known_cases.update(str(case) for case in _mapping(_pass_at_k_branch(agent, condition).get("cases")))+ known_cases.update(_case_label(row) for row in _rows(agent.get(usage_key)) if row.get("scored") is True)+ attempts: dict[str, list[_Attempt]] = {}+ for arm, _condition, key, usage_key in _ARMS:+ attempts[arm] = [+ _Attempt(_case_label(trial), normalize_token_counts(trial.get("tokens")), True)+ for trial in _rows(agent.get(key))+ ]+ for row in _rows(agent.get(usage_key)):+ scored = row.get("scored") is True+ # A scored attempt names its case; an unscored one has its task directory or trial name.+ trial_id = row.get("trial_id")+ case = (+ _case_label(row)+ if scored+ else _matching_case(_case_label(row), trial_id if isinstance(trial_id, str) else "", known_cases)+ )+ attempts[arm].append(_Attempt(case, normalize_token_counts(row.get("tokens")), scored))+ return attempts+++def _condition(agent: Mapping[str, Any], condition: str) -> Mapping[str, Any]:+ return _mapping(_mapping(agent.get("conditions")).get(condition))+++def _condition_not_run(agent: Mapping[str, Any], condition: str, *, attempted: bool, unexecuted: bool) -> bool:+ """Whether the arm is known not to have run.++ It was skipped, or it had no planned work and no recorded status. An arm+ without attempts also did not run when the payload ``mode`` leaves it out+ (``unexecuted``) or the agent has no record of it; the score tables show+ such a baseline as not run.+ """+ record = _condition(agent, condition)+ status = record.get("execution_status")+ if status == "skipped":+ return True+ if status in {"succeeded", "failed"} or (_count(record.get("scored_attempts")) or 0) > 0:+ return False+ if not attempted and (unexecuted or condition not in _mapping(agent.get("conditions"))):+ return True+ return _count(record.get("expected_attempts")) == 0+++def _arm_expected(agent: Mapping[str, Any], condition: str, observed: int) -> int:+ """Return the attempts the arm should have run: its recorded expected attempts plus recovered ones.++ A timed-out attempt that a later attempt recovered is not expected for+ scoring, but it ran and used tokens. Observed attempts never count as+ missing, so the expected count is at least the observed one.+ """+ record = _condition(agent, condition)+ expected = _count(record.get("expected_attempts"))+ if expected is None:+ return observed+ return max(observed, expected + (_count(record.get("recovered_attempts_total")) or 0))+++def _case_expected(agent: Mapping[str, Any], condition: str, case: str, observed: int) -> int:+ """Return the attempts a case should have run, from pass@k: ``k`` minus attempts skipped after a pass."""+ branch = _pass_at_k_branch(agent, condition)+ record = _mapping(_mapping(branch.get("cases")).get(case))+ k = _count(branch.get("k"))+ if not record or k is None:+ return observed+ return max(observed, k - min(k, _count(record.get("attempts_skipped")) or 0))+++def _arm_summary(attempts: list[_Attempt], *, expected: int, not_run: bool) -> dict[str, Any]:+ totals = dict.fromkeys(TOKEN_MEASURES, 0)+ measured = 0+ reasons: set[str] = set()+ for attempt in attempts:+ tokens = attempt.tokens+ if tokens is None or not tokens["complete"]:+ # An incomplete attempt adds none of its counters, so every total+ # keeps total = prompt + completion over the same attempts.+ reasons.add(+ "invalid_token_counters" if tokens and "invalid_counters" in tokens else "missing_token_counters"+ )+ continue+ measured += 1+ for measure in TOKEN_MEASURES:+ totals[measure] += tokens[measure]+ observed = len(attempts)+ # ``total_tokens`` is the largest sum, so it alone can pass the exact JSON range.+ if measured and totals["total_tokens"] > _MAX_SAFE_INTEGER:+ reasons.add("total_out_of_range")+ if "total_out_of_range" in reasons:+ status = "unavailable"+ elif not attempts and expected == 0:+ status = "not_run" if not_run else "unavailable"+ if not not_run:+ reasons.add("no_attempts_recorded")+ elif measured == observed == expected:+ status = "complete"+ else:+ status = "partial" if measured else "unavailable"+ if observed < expected:+ reasons.add("missing_attempts")+ return {+ "totals": totals if measured and "total_out_of_range" not in reasons else None,+ "coverage": {+ "status": status,+ "expected_attempts": expected,+ "observed_attempts": observed,+ "measured_attempts": measured,+ "unscored_attempts": sum(not attempt.scored for attempt in attempts),+ "reason_codes": sorted(reasons),+ },+ }+++def _combine(summaries: list[dict[str, Any]]) -> dict[str, Any]:+ """Sum arm summaries of several agents; the sum is complete only when every part is.++ A part whose total is out of the exact JSON range makes the sum out of range too.+ """+ totals = dict.fromkeys(TOKEN_MEASURES, 0)+ coverage = dict.fromkeys(("expected_attempts", "observed_attempts", "measured_attempts", "unscored_attempts"), 0)+ reasons: set[str] = set()+ for summary in summaries:+ for measure in TOKEN_MEASURES:+ totals[measure] += (summary["totals"] or {}).get(measure, 0)+ for key in coverage:+ coverage[key] += summary["coverage"][key]+ reasons.update(summary["coverage"]["reason_codes"])+ statuses = {summary["coverage"]["status"] for summary in summaries}+ if totals["total_tokens"] > _MAX_SAFE_INTEGER:+ reasons.add("total_out_of_range")+ if "total_out_of_range" in reasons:+ status = "unavailable"+ elif not summaries or statuses == {"not_run"}:+ status = "not_run"+ elif statuses <= {"complete", "not_run"}:+ status = "complete"+ else:+ status = "partial" if coverage["measured_attempts"] else "unavailable"+ return {+ "totals": totals if coverage["measured_attempts"] and "total_out_of_range" not in reasons else None,+ "coverage": {"status": status, **coverage, "reason_codes": sorted(reasons)},+ }+++def _delta(+ with_skill: dict[str, Any],+ baseline: dict[str, Any],+ *,+ blockers: list[tuple[str, str]],+) -> dict[str, Any]:+ """Return with skill minus baseline total tokens, or why there is none.++ ``blockers`` are ``(code, sentence)`` pairs found by the caller, such as a+ failed arm or arms that ran different cases.+ """+ reasons: list[tuple[str, str]] = []+ for arm, summary in (("with_skill", with_skill), ("baseline", baseline)):+ status = summary["coverage"]["status"]+ if status == "not_run":+ reasons.append((f"{arm}_not_run", f"The {_ARM_NAMES[arm]} did not run."))+ elif "total_out_of_range" in summary["coverage"]["reason_codes"]:+ reasons.append(+ (+ f"{arm}_total_out_of_range",+ f"{_ARM_NAMES[arm].capitalize()} token total is above {_MAX_SAFE_INTEGER:,}, "+ "the largest integer JSON keeps exact.",+ )+ )+ elif status != "complete":+ coverage = summary["coverage"]+ reasons.append(+ (+ f"{arm}_tokens_incomplete",+ f"{_ARM_NAMES[arm].capitalize()} token counts cover {coverage['measured_attempts']} of "+ f"{coverage['expected_attempts']} attempts."+ if coverage["observed_attempts"]+ else f"No {_ARM_NAMES[arm]} attempts were recorded.",+ )+ )+ reasons.extend(blockers)+ if not reasons and with_skill["coverage"]["observed_attempts"] != baseline["coverage"]["observed_attempts"]:+ reasons.append(("attempt_scope_mismatch", "The arms ran different numbers of attempts."))+ if reasons:+ return {+ "status": "unavailable",+ "total_tokens": None,+ "total_tokens_change_percent": None,+ "reason_codes": [code for code, _sentence in reasons],+ "reason": " ".join(sentence for _code, sentence in reasons),+ }+ difference = with_skill["totals"]["total_tokens"] - baseline["totals"]["total_tokens"]+ baseline_total = baseline["totals"]["total_tokens"]+ return {+ "status": "available",+ "total_tokens": difference,+ "total_tokens_change_percent": round(difference / baseline_total * 100.0, 2) if baseline_total else None,+ "reason_codes": [] if baseline_total else ["zero_baseline"],+ "reason": None if baseline_total else "The baseline used no tokens, so there is no percentage change.",+ }+++def _withheld_arm_blockers(agent: Mapping[str, Any], arms: Mapping[str, Mapping[str, Any]]) -> list[tuple[str, str]]:+ """Name each arm whose scores the report withholds: its usage is real but not comparable.++ A failed arm reuses the coverage notice's short form, such as ``No change:+ baseline incomplete (1 of 2 attempts scored).`` An arm that ran attempts+ without a recognized run status (``unknown``) gets ``<arm>_status_unknown``.+ An arm without attempts already has ``<arm>_not_run`` or+ ``<arm>_tokens_incomplete``.+ """+ from skillevaluator.reporting.tier3_coverage import incomplete_arms++ codes = {"with_skill": "with_skill_failed", "without_skill": "baseline_failed"}+ blockers = [(codes[arm.condition], f"No change: {arm}.") for arm in incomplete_arms(dict(agent))]+ for arm, condition, _key, _usage in _ARMS:+ status = _condition(agent, condition).get("execution_status")+ if status not in _KNOWN_ARM_STATUSES and arms[arm]["coverage"]["observed_attempts"]:+ blockers.append((f"{arm}_status_unknown", f"No change: {_ARM_NAMES[arm]} status unknown."))+ return blockers+++def _agent_usage(agent: Mapping[str, Any], unexecuted: frozenset[str]) -> dict[str, Any] | None:+ attempts = _agent_attempts(agent)+ arms: dict[str, dict[str, Any]] = {}+ for arm, condition, _key, _unscored in _ARMS:+ not_run = _condition_not_run(+ agent, condition, attempted=bool(attempts[arm]), unexecuted=condition in unexecuted+ )+ arms[arm] = _arm_summary(+ attempts[arm],+ # An arm that did not run expects nothing, whatever its record planned.+ expected=0 if not_run and not attempts[arm] else _arm_expected(agent, condition, len(attempts[arm])),+ not_run=not_run,+ )+ if all(summary["coverage"]["status"] == "not_run" for summary in arms.values()):+ return None+ withheld = _withheld_arm_blockers(agent, arms)+ cases_by_arm = {arm: Counter(attempt.case for attempt in attempts[arm]) for arm in arms}+ # An arm without attempts already says why there is no change.+ scope = (+ [("case_scope_mismatch", "The arms ran different cases or attempts per case.")]+ if all(cases_by_arm.values()) and cases_by_arm["with_skill"] != cases_by_arm["baseline"]+ else []+ )+ case_rows = []+ for case in sorted(+ {*cases_by_arm["with_skill"], *cases_by_arm["baseline"]}+ | {+ str(case)+ for _a, condition, _k, _u in _ARMS+ for case in _mapping(_pass_at_k_branch(agent, condition).get("cases"))+ }+ ):+ case_arms = {}+ for arm, condition, _key, _unscored in _ARMS:+ case_attempts = [attempt for attempt in attempts[arm] if attempt.case == case]+ case_arms[arm] = _arm_summary(+ case_attempts,+ expected=0+ if arms[arm]["coverage"]["status"] == "not_run"+ else _case_expected(agent, condition, case, len(case_attempts)),+ not_run=arms[arm]["coverage"]["status"] == "not_run",+ )+ case_rows.append(+ {+ "entry_id": case,+ **case_arms,+ "delta": _delta(case_arms["with_skill"], case_arms["baseline"], blockers=withheld),+ }+ )+ return {+ **arms,+ "delta": _delta(arms["with_skill"], arms["baseline"], blockers=[*withheld, *scope]),+ "cases": case_rows,+ }+++def build_token_usage(+ agents: Mapping[str, Mapping[str, Any]], *, mode: str = "both", baseline_reused: bool = False+) -> dict[str, Any] | None:+ """Return token usage per case, per agent and over all agents, or ``None`` when no attempt was measured.++ ``agents`` maps each agent to its report payload (``trials``,+ ``trials_baseline``, ``conditions``, ``pass_at_k`` and ``execution_status``)+ plus the loader's usage-only attempts under :data:`USAGE_ONLY_ATTEMPT_KEYS`.+ ``mode`` is the payload's ``mode``: an arm that ``with_skill_only`` or+ ``baseline_only`` leaves out is ``not_run`` for every agent without attempts in it.+ ``baseline_reused`` marks a run that reused an earlier run's baseline+ (``--reuse-baseline``): its baseline counts are that run's usage, so the+ result says so with ``baseline_reused``.+ """+ unexecuted = _UNEXECUTED_CONDITIONS.get(mode, frozenset())+ usage: dict[str, dict[str, Any]] = {}+ for name in sorted(agents):+ agent_usage = _agent_usage(_mapping(agents[name]), unexecuted)+ if agent_usage is not None:+ usage[name] = agent_usage+ if not any(+ agent_usage[arm]["coverage"]["measured_attempts"]+ for agent_usage in usage.values()+ for arm in ("with_skill", "baseline")+ ):+ return None+ dataset = {+ arm: _combine([agent_usage[arm] for agent_usage in usage.values()]) for arm in ("with_skill", "baseline")+ }+ agents_without_change = (+ []+ if all(item["delta"]["status"] == "available" for item in usage.values())+ else [("agent_scope_mismatch", "Not every agent has a token change, so there is no change over all agents.")]+ )+ return {+ "schema_version": TOKEN_USAGE_SCHEMA_VERSION,+ "scored": False,+ "accounting": dict(_ACCOUNTING),+ **({"baseline_reused": True} if baseline_reused else {}),+ "agents": usage,+ "dataset": {+ **dataset,+ "delta": _delta(dataset["with_skill"], dataset["baseline"], blockers=agents_without_change),+ },+ }+++def per_agent_token_usage(usage: object) -> dict[str, Any] | None:+ """Return ``usage`` without its per-case rows, for the terminal summary of a run."""+ if not isinstance(usage, Mapping) or not isinstance(usage.get("agents"), Mapping):+ return None+ agents = {+ name: {key: value for key, value in agent.items() if key != "cases"}+ for name, agent in usage["agents"].items()+ if isinstance(agent, Mapping)+ }+ return {**usage, "agents": agents}+++def drop_token_usage_cases(usage: object) -> int:+ """Empty the per-case rows of ``usage`` in place and return how many were dropped.++ The report payload drops them first when it would pass its limits; the+ agent and all-agent sums stay, and ``case_rows_omitted`` counts the rows.+ """+ agents = usage.get("agents") if isinstance(usage, dict) else None+ dropped = 0+ for agent in agents.values() if isinstance(agents, dict) else []:+ if isinstance(agent, dict) and isinstance(agent.get("cases"), list) and agent["cases"]:+ dropped += len(agent["cases"])+ agent["cases"] = []+ if dropped and isinstance(usage, dict):+ usage["case_rows_omitted"] = dropped+ return droppeddiff --git a/tests/golden/benchmark_token_usage/TOKEN_USAGE.md b/tests/golden/benchmark_token_usage/TOKEN_USAGE.mdnew file mode 100644index 00000000..89e6bb4e--- /dev/null+++ b/tests/golden/benchmark_token_usage/TOKEN_USAGE.md@@ -0,0 +1,26 @@+## Token Usage++Measured agent token usage. It is not scored and changes no score or verdict. Tokens are prompt plus completion; prompt tokens include cached tokens, which are not added again. Attempts that failed before scoring are counted. A partial total covers only the attempts with token counts; nothing is estimated. Change is with skill minus baseline, as a share of the baseline, and needs complete counts for the same attempts in both arms.++| Agent | Case | With skill | Baseline | Change | Measured attempts |+|---|---|---:|---:|---:|---|+| Claude Code | All cases | 3,300 | 50,072 | N/A | skill 2/2; baseline 2/2 (1 unscored) |+| Codex | All cases | 1,210 | 1,650 | -440 (-26.7%) | skill 2/2; baseline 2/2 |+| All agents | All cases | 4,510 | 51,722 | N/A | skill 4/4; baseline 4/4 (1 unscored) |++Measured attempts: attempts with token counts, of those expected, in each arm. Unscored attempts failed before scoring.++- Claude Code: No change: baseline incomplete (1 of 2 attempts scored).+- All agents: Not every agent has a token change, so there is no change over all agents.++<details>+<summary>Show token usage per case</summary>++| Agent | Case | With skill | Baseline | Change | Measured attempts |+|---|---|---:|---:|---:|---|+| Claude Code | case-1 | 1,100 | 1,650 | N/A | skill 1/1; baseline 1/1 |+| Claude Code | case-2 | 2,200 | 48,422 | N/A | skill 1/1; baseline 1/1 (1 unscored) |+| Codex | case-1 | 550 | 770 | -220 (-28.6%) | skill 1/1; baseline 1/1 |+| Codex | case-2 | 660 | 880 | -220 (-25.0%) | skill 1/1; baseline 1/1 |++</details>diff --git a/tests/reporting/test_dashboard_data.py b/tests/reporting/test_dashboard_data.pyindex e7d6c9a7..b93cc687 100644--- a/tests/reporting/test_dashboard_data.py+++ b/tests/reporting/test_dashboard_data.py@@ -854,7 +854,9 @@ def test_retained_run_keeps_non_best_agent_trials_beyond_embedded_budget(tmp_patsummary["agent"] = "codex"summary_path.write_text(json.dumps(summary), encoding="utf-8")# A budget just below the full payload prunes only the non-best agent's details.- budget = tier3_report._serialized_payload_size(_canonical_export(run)) - 200+ # Token usage joins after the budget and drops its own rows first, so it is not measured.+ export = {key: value for key, value in _canonical_export(run).items() if key != "token_usage"}+ budget = tier3_report._serialized_payload_size(export) - 200monkeypatch.setattr(tier3_report, "_MAX_EMBEDDED_REPORT_BYTES", budget)canonical = _canonical_export(run)assert canonical["report_truncation"]["omitted"]["non_best_agent_details"]diff --git a/tests/reporting/test_tier3_incomplete_arms.py b/tests/reporting/test_tier3_incomplete_arms.pynew file mode 100644index 00000000..6be9b236--- /dev/null+++ b/tests/reporting/test_tier3_incomplete_arms.py@@ -0,0 +1,535 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""An agent arm that ran but failed is reported as incomplete, never as not run.++When one attempt of an agent's no-skill baseline times out, the baseline arm+fails while the with-skill arm keeps its scores. Every report must say that the+baseline ran but did not finish, how many of its attempts scored and what+failed first, instead of printing ``baseline not run``.+"""++from __future__ import annotations++import copy+import html as html_lib+import io+import json+import re+from pathlib import Path+from typing import TYPE_CHECKING, Any++import pytest+from rich.console import Console++from skillevaluator.cli import _effective_report_formats+from skillevaluator.constants import DIMENSION_MAPPING+from skillevaluator.evaluation.tier3_report import (+ _validation_result_from_payload,+ agent_eval_result_from_directory,+ build_agent_eval_payload,+)+from skillevaluator.reporting import BenchmarkReporter, CLIReporter, HTMLReporter+from skillevaluator.reporting.console_ui import summarize_tier3+from skillevaluator.reporting.html import _TIER3_HTML_PREVIEW_TRIGGER_BYTES+from skillevaluator.reporting.tier3_coverage import IncompleteArm, coverage_notices, incomplete_arms+from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS++if TYPE_CHECKING:+ from skillevaluator.models import ValidationResult++TIMEOUT_ERROR = (+ "Without skill trial case-1__attempt2: AgentTimeoutError: Agent execution timed out after 1200.0 seconds"+)+SETUP_ERROR = (+ "Agent runtime failed in case-1__attempt1: AgentSetupTimeoutError: Agent setup timed out after 360 seconds"+)+FAILED_AGENT = "The agent and the Tier 3 run are marked failed."+REPO_ROOT = Path(__file__).resolve().parents[2]+++def _condition(status: str, scored: int, expected: int = 2, errors: list[str] | None = None) -> dict[str, Any]:+ return {+ "execution_status": status,+ "execution_errors": list(errors or []),+ "expected_attempts": expected,+ "scored_attempts": scored,+ }+++def _agent(+ *,+ baseline: dict[str, Any] | None,+ with_skill: dict[str, Any] | None = None,+ activated: bool = True,+) -> dict[str, Any]:+ """Return loaded agent data in the shape ``report_data.load_agent_data`` produces."""+ with_skill = with_skill or _condition("succeeded", 2)+ scores = dict.fromkeys(DEFAULT_METRICS, 0.9)+ scores["skill_execution"] = 0.9 if activated else 0.0+ reward = {+ **scores,+ "entry_id": "case-1",+ "trial_id": "case-1__attempt1",+ "details": {"skill_execution": {"activation": {"passed": activated, "score": float(activated)}}},+ }+ conditions = {"with_skill": with_skill}+ agent: dict[str, Any] = {+ "with_skill": scores,+ "rewards": [reward],+ "num_trials": 1,+ "conditions": conditions,+ }+ if baseline is not None:+ conditions["without_skill"] = baseline+ baseline_scores = dict.fromkeys(DEFAULT_METRICS, 0.5)+ agent["without_skill"] = baseline_scores+ agent["rewards_baseline"] = [{**baseline_scores, "entry_id": "case-1", "trial_id": "case-1__attempt1"}]+ agent["num_trials_baseline"] = 1+ active = [condition for condition in conditions.values() if condition["execution_status"] != "skipped"]+ agent["execution_status"] = (+ "succeeded" if all(condition["execution_status"] == "succeeded" for condition in active) else "failed"+ )+ agent["execution_errors"] = [error for condition in active for error in condition["execution_errors"]]+ agent["expected_attempts"] = sum(condition["expected_attempts"] for condition in active)+ agent["scored_attempts"] = sum(condition["scored_attempts"] for condition in active)+ return agent+++def _render(agents: dict[str, dict[str, Any]]) -> tuple[dict[str, Any], ValidationResult, str, str]:+ payload = build_agent_eval_payload("demo", agents, use_llm_judge=False)+ assert payload is not None+ result = _validation_result_from_payload(payload)+ assert result is not None+ benchmark = BenchmarkReporter(include_timestamp=False).render_all([result])+ report = HTMLReporter(include_timestamp=False).render_all([result])+ return payload, result, benchmark, report+++def _benchmark_rows(benchmark: str) -> dict[str, list[str]]:+ """Return the score rows (Overall and each dimension) of the Results at a Glance table.++ The count rows (required checks, goals met, security clean) compare counts,+ not a baseline score, so they are left out.+ """+ score_rows = {"Overall", *(dim_id.title() for dim_id in DIMENSION_MAPPING)}+ section = benchmark.split("## Results at a Glance\n", 1)[1].split("\n## ", 1)[0].split("\n### ", 1)[0]+ return {+ cells[0]: cells[1:]+ for line in section.splitlines()+ if line.startswith("| ")+ for cells in [[cell.strip() for cell in line.strip("|").split("|")]]+ if cells[0] in score_rows+ }+++def _coverage_section(benchmark: str) -> list[str]:+ if "\n### Agent coverage\n" not in benchmark:+ return []+ section = benchmark.split("\n### Agent coverage\n", 1)[1].split("\n## ", 1)[0]+ return [line for line in section.splitlines() if line.startswith("- ")]+++def _tier3_evidence(benchmark: str) -> str:+ row = next(line for line in benchmark.splitlines() if line.startswith("| Tier 3 |"))+ return [cell.strip() for cell in row.strip("|").split("|")][3]+++def _html_coverage_notes(report: str) -> list[str]:+ match = re.search(r'<div[^>]*id="tier3-coverage-notices"[^>]*>(.*?)</div>', report, flags=re.DOTALL)+ if match is None:+ return []+ return [html_lib.unescape(item.strip()) for item in re.findall(r"<li>(.*?)</li>", match.group(1), re.DOTALL)]+++def _cli_output(result: ValidationResult) -> str:+ output = io.StringIO()+ CLIReporter(console=Console(file=output, width=400, color_system=None)).print_all([result])+ return output.getvalue()+++def _doc_block(name: str, lead: str) -> str:+ """Return the one blank-line separated block of ``name`` that starts with ``lead``, whitespace-normalized."""+ blocks = [" ".join(block.split()) for block in (REPO_ROOT / name).read_text(encoding="utf-8").split("\n\n")]+ [block] = [block for block in blocks if block.startswith(lead)]+ return block+++# -- arm classification -------------------------------------------------------+++ ("scored", "expected", "state", "text"),+ [+ (1, 2, "incomplete", "baseline incomplete (1 of 2 attempts scored)"),+ (0, 2, "unavailable", "baseline unavailable (0 of 2 attempts scored)"),+ # The arm failed for another reason although no attempt is missing.+ (2, 2, "failed", "baseline failed (2 of 2 attempts scored)"),+ # Unusable counters are not published.+ (3, 2, "failed", "baseline failed"),+ (0, 0, "failed", "baseline failed"),+ (None, 2, "failed", "baseline failed"),+ ],+)+def test_incomplete_arm_states_and_counts(scored: int | None, expected: int, state: str, text: str) -> None:+ arm = IncompleteArm("without_skill", scored, expected)+ assert arm.state == state+ assert str(arm) == text+++ ("errors", "failure"),+ [+ ([TIMEOUT_ERROR], "agent timeout error"),+ ([SETUP_ERROR], "agent setup timeout error"),+ (["Scored attempt coverage is 1/2", TIMEOUT_ERROR], "agent timeout error"),+ (["Without skill trial case-1__attempt2: harbor.trial.errors.VerifierTimeoutError"], "verifier timeout error"),+ (["Without skill trial case-1__attempt2: HTTPError: 503"], "http error"),+ # An acronym keeps its trailing digits.+ (["Without skill trial case-1__attempt2: S3UploadFailedError: denied"], "s3 upload failed error"),+ (["Without skill aggregate job: HTTP2Error: stream reset"], "http2 error"),+ (["Without skill trial case-1__attempt2: Http2ProtocolError"], "http2 protocol error"),+ # A case ID shaped like an exception type is not a failure type.+ (["Without skill trial FakeError: AgentTimeoutError: timed out"], "agent timeout error"),+ (["Missing scored attempts for cases: ParseError", "Scored attempt coverage is 1/2"], None),+ (["Excess scored attempts for cases: ParseError", TIMEOUT_ERROR], "agent timeout error"),+ (["Unexpected scored cases: ValueError"], None),+ (["Scored attempt coverage is 1/2", "Unscoreable reward in case-1__attempt2: judge failed"], None),+ ("AgentTimeoutError: not a list", None),+ ],+)+def test_first_failure_names_the_first_harbor_exception_type(errors: object, failure: str | None) -> None:+ agent = {"conditions": {"without_skill": {"execution_status": "failed", "execution_errors": errors}}}+ (arm,) = incomplete_arms(agent)+ assert arm.failure == failure+++def test_notice_says_the_agent_failed_only_when_the_agent_is_marked_failed() -> None:+ baseline = _condition("failed", 1, errors=[TIMEOUT_ERROR])+ failed = {"execution_status": "failed", "conditions": {"without_skill": baseline}}+ # An agent kept scored although its baseline arm failed.+ scored = {"execution_status": "succeeded", "conditions": {"without_skill": baseline}}++ notices = coverage_notices({"failed-agent": failed, "scored-agent": scored})++ assert [notice["code"] for notice in notices] == ["baseline_failed", "baseline_failed"]+ assert [notice["message"] for notice in notices] == [+ "failed-agent baseline incomplete (1 of 2 attempts scored; first failure: agent timeout error). "+ f"{FAILED_AGENT} Baseline and uplift are not reported for this agent.",+ "scored-agent baseline incomplete (1 of 2 attempts scored; first failure: agent timeout error). "+ "Baseline and uplift are not reported for this agent.",+ ]+++ "conditions",+ [+ None,+ "failed",+ {"with_skill": _condition("succeeded", 2), "without_skill": _condition("succeeded", 2)},+ {"with_skill": _condition("succeeded", 2), "without_skill": _condition("skipped", 0, 0)},+ {"with_skill": _condition("succeeded", 2), "without_skill": _condition("unknown", 1)},+ {"with_skill": _condition("succeeded", 2), "without_skill": ["failed"]},+ ],+)+def test_completed_skipped_or_malformed_arms_are_not_incomplete(conditions: object) -> None:+ assert incomplete_arms({"conditions": conditions}) == []+ assert coverage_notices({"agent": {"conditions": conditions}}) == []+++# -- canonical payload ----------------------------------------------------------+++def test_payload_records_a_coverage_notice_for_a_failed_baseline_arm() -> None:+ payload, _, _, _ = _render(+ {+ "claude-code": _agent(baseline=_condition("failed", 1, errors=[TIMEOUT_ERROR])),+ "codex": _agent(baseline=_condition("succeeded", 2)),+ }+ )++ assert payload["coverage_notices"] == [+ {+ "code": "baseline_failed",+ "agent": "claude-code",+ "condition": "without_skill",+ "state": "incomplete",+ "scored_attempts": 1,+ "expected_attempts": 2,+ "failure": "agent timeout error",+ "message": (+ "claude-code baseline incomplete (1 of 2 attempts scored; first failure: agent timeout error). "+ f"{FAILED_AGENT} Baseline and uplift are not reported for this agent."+ ),+ }+ ]+ # The with-skill arm keeps its scores; the failed baseline has none.+ agent = payload["agents"]["claude-code"]+ assert agent["with_skill"] == pytest.approx(0.9)+ assert agent["baseline"] is None+ assert agent["lift"] is None+++def test_payload_has_no_coverage_notices_when_every_arm_completed_or_was_skipped() -> None:+ payload, _, benchmark, report = _render(+ {+ "codex": _agent(baseline=_condition("succeeded", 2)),+ "opencode": _agent(baseline=_condition("skipped", 0, 0)),+ }+ )++ assert "coverage_notices" not in payload+ assert _coverage_section(benchmark) == []+ assert _html_coverage_notes(report) == []+ assert "tier3-coverage-notices" not in report+++def test_run_directory_failed_baseline_trial_reaches_the_coverage_notice(tmp_path: Path) -> None:+ """The loader's condition errors carry the Harbor exception type the notice names."""+ skill = tmp_path / "demo"+ skill.mkdir()+ run_dir = tmp_path / "results"+ for variant, status, scored, trial_failures in (+ ("with-skill", "succeeded", 2, []),+ (+ "without-skill",+ "failed",+ 1,+ [{"trial": "case-1__attempt2", "reason": "AgentTimeoutError: Agent execution timed out after 1200.0 s"}],+ ),+ ):+ summary = run_dir / "claude-code" / variant / "summary.json"+ summary.parent.mkdir(parents=True)+ summary.write_text(+ json.dumps(+ {+ "scores": dict.fromkeys(DEFAULT_METRICS, 0.8 if variant == "with-skill" else 0.4),+ "metrics": list(DEFAULT_METRICS),+ "num_trials": scored,+ "execution_status": status,+ "execution_errors": [] if status == "succeeded" else ["Scored attempt coverage is 1/2"],+ "trial_failures": trial_failures,+ "expected_attempts": 2,+ "scored_attempts": scored,+ }+ ),+ encoding="utf-8",+ )++ result = agent_eval_result_from_directory(skill, run_dir, use_llm_judge=False)++ assert result is not None+ payload = result.metadata["agent_eval"]+ assert [(notice["agent"], notice["state"], notice["failure"]) for notice in payload["coverage_notices"]] == [+ ("claude-code", "incomplete", "agent timeout error")+ ]+ benchmark = BenchmarkReporter(include_timestamp=False).render_all([result])+ assert _benchmark_rows(benchmark)["Overall"] == [+ "80.0% — baseline incomplete (1 of 2 attempts scored); uplift unavailable"+ ]+++# -- BENCHMARK.md ---------------------------------------------------------------+++def test_benchmark_says_a_failed_baseline_is_incomplete_not_not_run() -> None:+ _, _, benchmark, _ = _render(+ {+ "claude-code": _agent(baseline=_condition("failed", 1, errors=[TIMEOUT_ERROR])),+ "codex": _agent(baseline=_condition("succeeded", 2)),+ "opencode": _agent(baseline=_condition("skipped", 0, 0)),+ }+ )++ rows = _benchmark_rows(benchmark)+ assert len(rows) == len(DIMENSION_MAPPING) + 1+ for cells in rows.values():+ incomplete, completed, skipped = cells+ assert incomplete == "90.0% — baseline incomplete (1 of 2 attempts scored); uplift unavailable"+ assert completed == "50.0% → 90.0% (+40.0 points)"+ # A skipped baseline still reads as not run.+ assert skipped == "90.0% — baseline not run; uplift unavailable"+ assert _coverage_section(benchmark) == [+ "- Claude Code: baseline incomplete (1 of 2 attempts scored; first failure: agent timeout error). "+ f"{FAILED_AGENT} Baseline and uplift are not reported for this agent."+ ]+ assert _tier3_evidence(benchmark).endswith("; Claude Code baseline incomplete (1 of 2 attempts scored)")+++def test_benchmark_says_baseline_unavailable_when_no_baseline_attempt_scored() -> None:+ _, _, benchmark, _ = _render({"claude-code": _agent(baseline=_condition("failed", 0, errors=[TIMEOUT_ERROR]))})++ for (cell,) in _benchmark_rows(benchmark).values():+ assert cell == "90.0% — baseline unavailable (0 of 2 attempts scored); uplift unavailable"+ assert _tier3_evidence(benchmark).endswith("; Claude Code baseline unavailable (0 of 2 attempts scored)")+++def test_benchmark_explains_a_failed_with_skill_arm_below_the_table() -> None:+ _, _, benchmark, _ = _render(+ {+ "codex": _agent(+ with_skill=_condition("failed", 0, errors=[SETUP_ERROR]),+ baseline=_condition("succeeded", 2),+ ),+ "claude-code": _agent(baseline=_condition("succeeded", 2)),+ }+ )++ # Agents are ordered by name: claude-code, then codex. Codex's with-skill+ # scores (90.0%) and uplift are not published.+ for _completed, failed in _benchmark_rows(benchmark).values():+ assert "90.0%" not in failed+ assert "points" not in failed+ assert _coverage_section(benchmark) == [+ "- Codex: with-skill run unavailable (0 of 2 attempts scored; first failure: agent setup timeout error). "+ f"{FAILED_AGENT} With-skill scores and uplift are not reported for this agent."+ ]+ assert _tier3_evidence(benchmark).endswith("; Codex with-skill run unavailable (0 of 2 attempts scored)")+++def test_benchmark_keeps_never_activated_wording_over_an_incomplete_baseline() -> None:+ _, _, benchmark, _ = _render(+ {"claude-code": _agent(baseline=_condition("failed", 1, errors=[TIMEOUT_ERROR]), activated=False)}+ )++ for (cell,) in _benchmark_rows(benchmark).values():+ assert "INCONCLUSIVE: skill never activated; uplift unavailable" in cell+ assert "baseline" not in cell+ assert len(_coverage_section(benchmark)) == 1+++# -- HTML and terminal ---------------------------------------------------------------+++def test_html_and_terminal_show_agent_coverage_notes() -> None:+ payload, result, _, report = _render(+ {+ "claude-code": _agent(baseline=_condition("failed", 1, errors=[TIMEOUT_ERROR])),+ "codex": _agent(+ with_skill=_condition("failed", 0, errors=[SETUP_ERROR]),+ baseline=_condition("succeeded", 2),+ ),+ }+ )+ messages = [notice["message"] for notice in payload["coverage_notices"]]+ assert len(messages) == 2++ assert _html_coverage_notes(report) == messages++ output = _cli_output(result)+ assert "Agent coverage notes" in output+ for message in messages:+ assert f"• {message}" in output+++def test_html_and_terminal_escape_agent_names_in_coverage_notes() -> None:+ name = "<b>[red]agent"+ payload, result, _, report = _render({name: _agent(baseline=_condition("failed", 1, errors=[TIMEOUT_ERROR]))})+ (message,) = [notice["message"] for notice in payload["coverage_notices"]]+ assert message.startswith(f"{name} baseline incomplete")++ assert "<li><b>" not in report+ assert _html_coverage_notes(report) == [message]+ assert f"• {message}" in _cli_output(result)+++ "notices",+ [5, True, {"message": "claude-code baseline incomplete"}, ["claude-code", None, {"message": 5}, {"message": ""}]],+)+def test_html_drops_malformed_coverage_notices(notices: object) -> None:+ _, result, _, _ = _render({"claude-code": _agent(baseline=_condition("failed", 1, errors=[TIMEOUT_ERROR]))})+ result.metadata["agent_eval"]["coverage_notices"] = notices++ report = HTMLReporter(include_timestamp=False).render_all([result])++ assert "tier3-coverage-notices" not in report+ assert _html_coverage_notes(report) == []+++def test_html_keeps_coverage_notes_whole_in_the_bounded_preview() -> None:+ """A payload above the preview trigger still shows every coverage message in full."""+ payload, result, _, _ = _render(+ {+ "claude-code": _agent(baseline=_condition("failed", 1, errors=[TIMEOUT_ERROR])),+ "codex": _agent(baseline=_condition("succeeded", 2)),+ }+ )+ messages = [notice["message"] for notice in payload["coverage_notices"]]+ large = copy.deepcopy(result)+ prompt = "Summarize the attached quarterly report and list each follow-up action. " * 40+ large.metadata["agent_eval"]["dataset"] = [{"id": f"case-{index}", "prompt": prompt} for index in range(100)]+ assert len(json.dumps(large.metadata["agent_eval"]).encode("utf-8")) > _TIER3_HTML_PREVIEW_TRIGGER_BYTES++ report = HTMLReporter(include_timestamp=False).render_all([large])++ assert "HTML preview omitted" in report+ assert _html_coverage_notes(report) == messages+++def test_terminal_prints_coverage_notes_for_a_non_blocking_tier3_result() -> None:+ """``validate`` runs Tier 3 non-blocking by default; the failed run has errors but no findings.++ The full terminal report (``validate --verbose`` or ``-r cli``) must still print the notes.+ """+ payload, result, _, _ = _render({"claude-code": _agent(baseline=_condition("failed", 1, errors=[TIMEOUT_ERROR]))})+ result.metadata["gating"] = {"tier": 3, "blocking": False}+ assert not result.findings++ output = _cli_output(result)++ # Printed once, with the result's errors, under Non-blocking Findings+ # rather than as a bare agent table above it.+ assert output.count("Agent coverage notes") == 1+ assert "Non-blocking Findings" in output+ assert output.index("Non-blocking Findings") < output.index("Agent coverage notes")+ (notice,) = payload["coverage_notices"]+ assert f"• {notice['message']}" in output+++def test_compact_validate_view_leaves_coverage_notes_to_the_report_files_and_the_docs_say_so() -> None:+ """Only the full terminal report prints the notes; a plain ``validate`` shows the compact view."""+ payload, result, _, _ = _render({"claude-code": _agent(baseline=_condition("failed", 1, errors=[TIMEOUT_ERROR]))})+ result.metadata["gating"] = {"tier": 3, "blocking": False}+ (notice,) = payload["coverage_notices"]++ # A plain ``validate`` swaps the ``cli`` reporter for HTML and JSON; ``--verbose`` keeps it.+ assert "cli" not in _effective_report_formats(("cli",), quiet=True)+ assert _effective_report_formats(("cli",), quiet=False) == ("cli",)+ # The compact Tier 3 rows show at most the first raw execution error, never the notes.+ _, _, rows, _ = summarize_tier3(result, report_formats=("html", "json"))+ compact = " ".join(text for row in rows for text, _ in row.segments)+ assert "AgentTimeoutError" in compact+ assert notice["message"] not in compact+ assert "baseline incomplete" not in compact++ docs = _doc_block("docs/reports.mdx", "The HTML report lists each message under **Agent coverage notes**")+ changelog = _doc_block("CHANGELOG.md", "- Tier 3 reports no longer say `baseline not run`")+ for name, text in (("docs/reports.mdx", docs), ("CHANGELOG.md", changelog)):+ assert "`validate --verbose`" in text, name+ assert "`-r cli`" in text, name+ assert "compact default" in text, name+ assert "`validate` prints" not in text, name+++def test_html_agent_details_label_a_failed_baseline_like_a_skipped_one_and_the_docs_say_so() -> None:+ """Only the callout tells a baseline that ran and failed from one that was skipped."""+ _, _, _, report = _render(+ {+ "claude-code": _agent(baseline=_condition("failed", 1, errors=[TIMEOUT_ERROR])),+ "opencode": _agent(baseline=_condition("skipped", 0, 0)),+ }+ )++ kpi_subs = re.findall(r'<div class="t3-kpi-sub">(.*?)</div>', report)+ assert kpi_subs.count("baseline N/A") == 2+ assert kpi_subs.count("no baseline") == 2+ (note,) = _html_coverage_notes(report)+ assert note.startswith("claude-code baseline incomplete")++ definition = _doc_block("docs/reports.mdx", "When the HTML report has no lift for an agent or dimension")+ assert "**no baseline** means" in definition+ assert "a baseline arm that ran but failed" in definition+ assert "**Agent coverage notes**" in definition+ details = _doc_block("docs/reports.mdx", "The HTML report lists each message under **Agent coverage notes**")+ assert "**no baseline** and `baseline N/A`" in detailsdiff --git a/tests/reporting/test_tier3_token_usage_reports.py b/tests/reporting/test_tier3_token_usage_reports.pynew file mode 100644index 00000000..4285c2e5--- /dev/null+++ b/tests/reporting/test_tier3_token_usage_reports.py@@ -0,0 +1,815 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Tier 3 token usage reaches the payload and every report, and is never scored.++A run directory with a timed-out baseline attempt goes through the loader, the+canonical payload, the terminal, the Markdown report, ``BENCHMARK.md`` and the+HTML report. The failed attempt's tokens count as usage; scores and the+complete-only ``resources`` comparison stay as they were.+"""++from __future__ import annotations++import copy+import io+import json+import re+from pathlib import Path+from typing import Any++import pytest+from click.testing import CliRunner+from rich.console import Console+from scripts.ci import check_public_benchmarks as benchmark_gate++from skillevaluator import cli as cli_module+from skillevaluator.evaluation import tier3_report+from skillevaluator.evaluation.tier3_report import (+ _validation_result_from_payload,+ agent_eval_result_from_directory,+ build_agent_eval_payload,+ render_agent_eval_html_report,+)+from skillevaluator.reporting import BenchmarkReporter, CLIReporter, HTMLReporter, MarkdownReporter+from skillevaluator.reporting import base as reporting_base+from skillevaluator.reporting import html as html_reporting+from skillevaluator.reporting.base import (+ agent_eval_publication_evidence_complete,+ agent_eval_report_serialization_issue,+)+from skillevaluator.reporting.dashboard_data import comparison_rows, parse_dashboard_report+from skillevaluator.reporting.tier3_token_usage import (+ EVALUATE_CASE_POINTER,+ REUSED_BASELINE_NOTE,+ VALIDATE_CASE_POINTER,+)+from skillevaluator.tier3 import token_usage as token_usage_module+from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS+from skillevaluator.tier3.harbor.report_data import load_agent_data+from skillevaluator.tier3.result_display import render_result+from skillevaluator.tier3.token_usage import drop_token_usage_cases, per_agent_token_usage++REPO_ROOT = Path(__file__).resolve().parents[2]+GOLDEN = REPO_ROOT / "tests" / "golden" / "benchmark_token_usage" / "TOKEN_USAGE.md"+++def _arm(+ run: Path,+ agent: str,+ variant: str,+ trials: list[tuple[str, tuple[int, int, int] | None, bool]],+ *,+ status: str = "succeeded",+) -> None:+ """Write one arm: ``trials`` are (trial directory, (prompt, completion, cached), has a reward)."""+ directory = run / agent / variant+ directory.mkdir(parents=True)+ scored = sum(rewarded for _name, _tokens, rewarded in trials)+ scores = dict.fromkeys(DEFAULT_METRICS, 0.9 if variant == "with-skill" else 0.5)+ summary: dict[str, Any] = {+ "scores": scores,+ "metrics": list(DEFAULT_METRICS),+ "num_trials": scored,+ "expected_attempts": len(trials),+ "scored_attempts": scored,+ "execution_status": status,+ }+ if status == "failed":+ summary["execution_errors"] = [f"Scored attempt coverage is {scored}/{len(trials)}"]+ summary["trial_failures"] = [+ {"trial": name, "reason": "AgentTimeoutError: Agent execution timed out after 1200.0 seconds"}+ for name, _tokens, rewarded in trials+ if not rewarded+ ]+ (directory / "summary.json").write_text(json.dumps(summary), encoding="utf-8")+ for name, tokens, rewarded in trials:+ trial = directory / "trials" / name+ trial.mkdir(parents=True)+ if rewarded:+ # Harbor's ``__<id>`` suffix never contains ``__``; a case ID may.+ reward = {"entry_id": name.rsplit("__", 1)[0], "trial_id": name, **scores}+ (trial / "reward.json").write_text(json.dumps(reward), encoding="utf-8")+ else:+ failure = {"status": "unscored", "trial": name, "error": {"type": "AgentTimeoutError"}}+ (trial / "failure.json").write_text(json.dumps(failure), encoding="utf-8")+ if tokens is not None:+ prompt, completion, cached = tokens+ metrics = {+ "total_prompt_tokens": prompt,+ "total_completion_tokens": completion,+ "total_cached_tokens": cached,+ }+ (trial / "trajectory.json").write_text(+ json.dumps({"steps": [{}], "final_metrics": metrics}), encoding="utf-8"+ )+++def _run(tmp_path: Path) -> Path:+ """Claude Code's baseline times out on case-2; Codex completes both arms."""+ run = tmp_path / "run"+ _arm(run, "claude-code", "with-skill", [("case-1__a", (1000, 100, 400), True), ("case-2__a", (2000, 200, 0), True)])+ _arm(+ run,+ "claude-code",+ "without-skill",+ [("case-1__a", (1500, 150, 0), True), ("case-2__b", (900, 47522, 0), False)],+ status="failed",+ )+ _arm(run, "codex", "with-skill", [("case-1__a", (500, 50, 0), True), ("case-2__a", (600, 60, 0), True)])+ _arm(run, "codex", "without-skill", [("case-1__a", (700, 70, 0), True), ("case-2__a", (800, 80, 0), True)])+ return run+++def run_result(tmp_path: Path) -> tuple[Path, Any]:+ skill = tmp_path / "demo"+ skill.mkdir()+ run = _run(tmp_path)+ result = agent_eval_result_from_directory(skill, run, use_llm_judge=False)+ assert result is not None+ return run, result+++def _set_reward_case(run: Path, agent: str, variant: str, trial: str, case: str) -> None:+ reward_file = run / agent / variant / "trials" / trial / "reward.json"+ reward = json.loads(reward_file.read_text(encoding="utf-8"))+ reward_file.write_text(json.dumps({**reward, "entry_id": case}), encoding="utf-8")+++def _nodes(value: Any) -> int:+ """Count JSON values the way the report serialization limit does: every value is one node."""+ if isinstance(value, dict):+ return 1 + sum(_nodes(item) for item in value.values())+ if isinstance(value, list):+ return 1 + sum(_nodes(item) for item in value)+ return 1+++def _without_token_usage(payload: dict[str, Any]) -> dict[str, Any]:+ return {key: value for key, value in payload.items() if key not in {"token_usage", "report_truncation"}}+++def _cli_output(result: Any) -> str:+ output = io.StringIO()+ CLIReporter(console=Console(file=output, width=220, color_system=None)).print_all([result])+ return output.getvalue()+++def _section(text: str, heading: str) -> str:+ return text.split(f"{heading}\n", 1)[1].split("\n## ", 1)[0]+++def _table_rows(section: str) -> list[list[str]]:+ """Split Markdown table rows on unescaped pipes; ``\\|`` is a literal pipe in a cell."""+ return [+ [cell.strip() for cell in re.split(r"(?<!\\)\|", line.strip()[1:-1])]+ for line in section.splitlines()+ if line.startswith("| ") and not line.startswith("| Agent |")+ ]+++# -- loader and payload -----------------------------------------------------------+++def test_loader_keeps_usage_of_attempts_that_scores_never_read(tmp_path: Path) -> None:+ agents = load_agent_data(_run(tmp_path))++ baseline_usage = agents["claude-code"]["usage_only_attempts_baseline"]+ assert baseline_usage == [+ # The failed arm's scored attempt: its scores are withheld, its usage is not.+ {+ "entry_id": "case-1",+ "trial_id": "case-1__a",+ "scored": True,+ "tokens": {"prompt": 1500, "completion": 150, "cached": 0},+ },+ {+ "entry_id": "case-2",+ "trial_id": "case-2__b",+ "scored": False,+ "tokens": {"prompt": 900, "completion": 47522, "cached": 0},+ },+ ]+ # Scoring is unchanged: the failed arm keeps no rewards and stays incomplete.+ assert agents["claude-code"]["rewards_baseline"] == []+ assert agents["claude-code"]["rewards_baseline_complete"] is False+ assert agents["claude-code"]["usage_only_attempts"] == []+ assert agents["codex"]["usage_only_attempts_baseline"] == []++[email protected]("cached", [-1, True, "10", 1.5, 2**60])+def test_unscored_attempt_with_invalid_cached_tokens_is_not_measured(tmp_path: Path, cached: object) -> None:+ run = _run(tmp_path)+ trajectory_path = run / "claude-code/without-skill/trials/case-2__b/trajectory.json"+ trajectory = json.loads(trajectory_path.read_text(encoding="utf-8"))+ trajectory["final_metrics"]["total_cached_tokens"] = cached+ trajectory_path.write_text(json.dumps(trajectory), encoding="utf-8")+ skill = tmp_path / "demo"+ skill.mkdir()++ result = agent_eval_result_from_directory(skill, run, use_llm_judge=False)++ assert result is not None+ baseline = result.metadata["agent_eval"]["token_usage"]["agents"]["claude-code"]["baseline"]+ assert baseline["coverage"]["status"] == "partial"+ assert baseline["coverage"]["measured_attempts"] == 1+ assert baseline["totals"]["total_tokens"] == 1650+++def test_an_unscored_attempt_of_a_case_id_with_double_underscores_keeps_its_case(tmp_path: Path) -> None:+ run = tmp_path / "run"+ _arm(run, "codex", "with-skill", [("auth__login__a1b2c3d", (100, 10, 0), True)])+ _arm(+ run,+ "codex",+ "without-skill",+ [("auth__login__a1b2c3d", (90, 10, 0), True), ("auth__login__e4f5g6h", (400, 40, 0), False)],+ status="failed",+ )++ agents = load_agent_data(run)+ usage = build_agent_eval_payload("demo", agents, use_llm_judge=False)["token_usage"]["agents"]["codex"]++ [case] = usage["cases"]+ assert case["entry_id"] == "auth__login"+ assert case["baseline"]["coverage"]["observed_attempts"] == 2+ assert case["baseline"]["coverage"]["unscored_attempts"] == 1+ assert case["baseline"]["totals"]["total_tokens"] == 540+++def test_a_stop_on_pass_unscored_attempt_takes_its_case_from_its_harbor_files(tmp_path: Path) -> None:+ run = tmp_path / "run"+ task_files = {+ "with-skill": ("result.json", {"task_id": {"path": "/runs/x/tasks/codex/with/case-1"}}),+ "without-skill": ("config.json", {"task": {"path": "C:\\runs\\x\\tasks\\codex\\without\\case-1"}}),+ }+ for variant, arm in (("with-skill", "with"), ("without-skill", "without")):+ timed_out = f"demo-codex-{arm}-case-1-attempt001__case-1__a1b2c3d"+ scored = f"demo-codex-{arm}-case-1-attempt002__case-1__e4f5g6h"+ _arm(run, "codex", variant, [(timed_out, (400, 40, 0), False), (scored, (100, 10, 0), True)])+ _set_reward_case(run, "codex", variant, scored, "case-1")+ name, content = task_files[variant]+ (run / "codex" / variant / "trials" / timed_out / name).write_text(json.dumps(content), encoding="utf-8")++ usage = build_agent_eval_payload("demo", load_agent_data(run), use_llm_judge=False)["token_usage"]++ codex = usage["agents"]["codex"]+ assert [case["entry_id"] for case in codex["cases"]] == ["case-1"]+ assert codex["with_skill"]["coverage"]["unscored_attempts"] == 1+ assert codex["delta"]["status"] == "available"+ assert codex["delta"]["total_tokens"] == 0+++def test_payload_counts_the_failed_attempt_and_keeps_resources_complete_only(run_result: tuple[Path, Any]) -> None:+ _run_dir, result = run_result+ payload = result.metadata["agent_eval"]+ usage = payload["token_usage"]++ claude = usage["agents"]["claude-code"]+ assert claude["baseline"]["totals"]["total_tokens"] == 1650 + 48422+ assert claude["baseline"]["coverage"]["status"] == "complete"+ assert claude["baseline"]["coverage"]["unscored_attempts"] == 1+ assert claude["delta"]["reason_codes"] == ["baseline_failed"]+ assert claude["delta"]["reason"] == "No change: baseline incomplete (1 of 2 attempts scored)."+ codex = usage["agents"]["codex"]+ assert (codex["delta"]["total_tokens"], codex["delta"]["total_tokens_change_percent"]) == (-440, -26.67)+ assert usage["dataset"]["delta"]["reason_codes"] == ["agent_scope_mismatch"]++ # ``resources`` still needs every attempt of an arm scored and measured.+ claude_resources = payload["agents"]["claude-code"]["resources"]["tokens"]+ assert claude_resources["baseline"] == {"status": "unavailable", "measured_trials": 0, "trials": 0, "total": None}+ assert claude_resources["delta"] is None+ codex_resources = payload["agents"]["codex"]["resources"]["tokens"]+ assert codex_resources["with_skill"]["total"] == codex["with_skill"]["totals"]["total_tokens"] == 1210+ assert codex_resources["delta"] == codex["delta"]["total_tokens"]+ # Token usage changes no score.+ assert payload["agents"]["claude-code"]["baseline"] is None+ assert payload["agents"]["codex"]["with_skill"] == pytest.approx(0.9)+++def test_payload_has_no_token_usage_without_token_counts(tmp_path: Path) -> None:+ run = tmp_path / "run"+ _arm(run, "codex", "with-skill", [("case-1__a", None, True)])+ _arm(run, "codex", "without-skill", [("case-1__a", None, True)])++ result = agent_eval_result_from_directory(tmp_path, run, use_llm_judge=False)++ assert result is not None+ assert "token_usage" not in result.metadata["agent_eval"]+++def _cases_run(tmp_path: Path, agents: int, cases: int) -> Path:+ run = tmp_path / "run"+ rows = [(f"case-{index:03d}__a", (100 + index, 10, 0), True) for index in range(cases)]+ for agent in range(agents):+ _arm(run, f"agent-{agent}", "with-skill", rows)+ _arm(run, f"agent-{agent}", "without-skill", rows)+ return run+++def test_token_case_rows_go_before_any_score_evidence_under_the_size_budget(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ agents = load_agent_data(_cases_run(tmp_path, agents=3, cases=10))+ full = build_agent_eval_payload("demo", copy.deepcopy(agents), use_llm_judge=False, enforce_embedded_size=False)+ assert full is not None+ sums = copy.deepcopy(full["token_usage"])+ assert drop_token_usage_cases(sums) == 30+ # Room for every trial and the token sums, but not the token case rows.+ budget = tier3_report._serialized_payload_size({**_without_token_usage(full), "token_usage": sums}) + 2048+ assert tier3_report._serialized_payload_size(full) > budget+ monkeypatch.setattr(tier3_report, "_MAX_EMBEDDED_REPORT_BYTES", budget)++ bounded = build_agent_eval_payload("demo", agents, use_llm_judge=False)++ assert bounded is not None+ assert _without_token_usage(bounded) == _without_token_usage(full)+ assert bounded["report_truncation"]["omitted"] == {"token_usage_case_rows": 30}+ assert bounded["token_usage"] == sums+ assert bounded["token_usage"]["case_rows_omitted"] == 30++[email protected]("room", ["sums", "truncation_record", "none"])+def test_token_usage_never_pushes_a_payload_over_the_report_node_limit(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, room: str+) -> None:+ agents = load_agent_data(_cases_run(tmp_path, agents=2, cases=6))+ full = build_agent_eval_payload("demo", copy.deepcopy(agents), use_llm_judge=False)+ assert full is not None and "report_truncation" not in full+ base = _without_token_usage(full)+ sums = copy.deepcopy(full["token_usage"])+ drop_token_usage_cases(sums)+ # A truncation record is about 20 nodes; the sums are more and the case rows far more.+ extra = {"sums": _nodes(sums) + 40, "truncation_record": 30, "none": 0}[room]+ assert extra < _nodes(full["token_usage"])+ monkeypatch.setattr(reporting_base, "AGENT_EVAL_REPORT_MAX_NODES", _nodes(base) + extra)+ assert agent_eval_report_serialization_issue(full) is not None+ assert agent_eval_report_serialization_issue(base) is None++ bounded = build_agent_eval_payload("demo", agents, use_llm_judge=False)++ assert bounded is not None+ assert agent_eval_report_serialization_issue(bounded) is None+ assert _without_token_usage(bounded) == base+ assert agent_eval_publication_evidence_complete(bounded) == agent_eval_publication_evidence_complete(base)+ if room == "sums":+ assert bounded["report_truncation"]["omitted"] == {"token_usage_case_rows": 12}+ assert bounded["token_usage"] == sums+ benchmark = BenchmarkReporter(include_timestamp=False).render_all([_validation_result_from_payload(bounded)])+ assert "12 case row(s) were left out of this report" in _section(benchmark, "## Token Usage")+ elif room == "truncation_record":+ assert bounded["report_truncation"]["omitted"] == {"token_usage": 1, "token_usage_case_rows": 12}+ assert "token_usage" not in bounded+ else:+ assert bounded == base+++def _failed_case_findings(agent: str, cases: int) -> dict[str, Any]:+ """An engine result whose with-skill attempts of ``agent`` fail, so the report step lists fixes."""++ def attempt(passed: bool) -> dict[str, Any]:+ return {"attempts": [{"attempt": 1, "passed": passed, "score": 0.9 if passed else 0.1}]}++ return {+ "execution_status": "succeeded",+ "agents": {+ agent: {+ "pass_at_k": {+ "with_skill": {"cases": {f"case-{index:03d}": attempt(False) for index in range(cases)}},+ "without_skill": {"cases": {f"case-{index:03d}": attempt(True) for index in range(cases)}},+ }+ }+ },+ }+++def _verdict(html: str) -> str:+ """The HTML hero's Tier 3 verdict chip, the reason for an incomplete verdict, and the score."""+ hero = html.split('class="verdict-chip', 1)[1].split(">", 1)[1].split('<div class="agent-hero-detail"', 1)[0]+ return " ".join(re.sub(r"<[^>]+>", " ", hero).split())++[email protected]("reuse_saved_feedback", [False, True], ids=["fresh-feedback", "saved-feedback"])+def test_case_findings_after_the_budget_never_cost_a_payload_with_token_usage_its_report_limits(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, reuse_saved_feedback: bool+) -> None:+ skill = tmp_path / "demo"+ skill.mkdir()+ run = _cases_run(tmp_path, agents=2, cases=6)+ full = agent_eval_result_from_directory(+ skill, run, engine_result=_failed_case_findings("agent-1", 3), use_llm_judge=False+ )+ assert full is not None and "report_truncation" not in full.metadata["agent_eval"]+ # Token usage fits with one value to spare; the case findings that the report step adds do not.+ monkeypatch.setattr(reporting_base, "AGENT_EVAL_REPORT_MAX_NODES", _nodes(full.metadata["agent_eval"]) + 1)+ rendered: list[dict[str, Any]] = []+ apply_case_findings = tier3_report._apply_case_findings++ def keep_payload(payload: dict[str, Any], *args: Any, **kwargs: Any) -> None:+ apply_case_findings(payload, *args, **kwargs)+ rendered.append(payload)++ monkeypatch.setattr(tier3_report, "_apply_case_findings", keep_payload)+ saved_conclusion = {+ "severity": "fail",+ "title": "Skill effect",+ "message": "per-case result: FAIL (saved-budget-replay).",+ "source": "deterministic",+ }++ def render(name: str) -> tuple[dict[str, Any], str]:+ engine_result = _failed_case_findings("agent-1", 3)+ saved_feedback = {"conclusions": [saved_conclusion]} if reuse_saved_feedback else None+ report = render_agent_eval_html_report(+ skill,+ run,+ output_path=tmp_path / name,+ engine_result=engine_result,+ use_llm_judge=False,+ saved_feedback=saved_feedback,+ )+ return rendered[-1], report.read_text(encoding="utf-8")++ payload, html = render("with-token-usage.html")+ monkeypatch.setattr(token_usage_module, "build_token_usage", lambda *_args, **_kwargs: None)+ plain, plain_html = render("without-token-usage.html")++ assert len(payload["recommendations"]) == 3+ assert payload["next_steps"]+ assert agent_eval_report_serialization_issue(payload) is None+ assert payload["report_truncation"]["omitted"] == {"token_usage_case_rows": 12}+ assert payload["token_usage"]["case_rows_omitted"] == 12+ assert "token_usage" not in plain and "report_truncation" not in plain+ assert _without_token_usage(payload) == plain+ assert _verdict(html) == _verdict(plain_html)+ assert "Passed" in _verdict(html)+ assert "Incomplete" not in _verdict(html)+ if reuse_saved_feedback:+ assert payload["conclusions"] == [saved_conclusion]+ assert "saved-budget-replay" in html++[email protected]("run_next_steps", [False, True])+def test_validate_applicability_keys_never_cost_a_payload_with_token_usage_its_report_limits(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, run_next_steps: bool+) -> None:+ skill = REPO_ROOT / "tests" / "fixtures" / "skills" / "simple"+ run = _cases_run(tmp_path, agents=2, cases=6)+ if run_next_steps:+ # The run's result.json makes the loader add next steps after the payload is built.+ (run / "result.json").write_text(json.dumps(_failed_case_findings("agent-1", 3)), encoding="utf-8")+ full = agent_eval_result_from_directory(skill, run, use_llm_judge=False)+ assert full is not None+ limit = _nodes(full.metadata["agent_eval"]) + 1+ if run_next_steps:+ assert full.metadata["agent_eval"]["next_steps"]+ # Token usage fits when the payload is built; the next steps added after the build do not.+ limit -= _nodes(full.metadata["agent_eval"]["next_steps"])+ # Otherwise token usage fits with one value to spare; validate's three applicability keys do not.+ monkeypatch.setattr(reporting_base, "AGENT_EVAL_REPORT_MAX_NODES", limit)+ result = agent_eval_result_from_directory(skill, run, use_llm_judge=False)+ assert result is not None+ payload = result.metadata["agent_eval"]+ assert "applicability" not in payload and "report_truncation" not in payload+ assert (agent_eval_report_serialization_issue(payload) is not None) is run_next_steps+ monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", lambda *_args, **_kwargs: result)++ outcome = CliRunner().invoke(+ cli_module.cli,+ [+ "validate",+ "--no-autopilot",+ str(skill),+ "--no-llm",+ "--no-tier2",+ "--tier3",+ "--checks",+ "schema",+ "--output-dir",+ str(tmp_path / "reports"),+ ],+ )++ assert outcome.exit_code == 0, outcome.output+ reports = sorted((tmp_path / "reports").iterdir())+ assert {report.suffix for report in reports} == {".html", ".json", ".md"}+ for report in reports:+ assert "Tier 3 payload exceeds" not in report.read_text(encoding="utf-8"), report.name+ assert (payload["applicability"], payload["reason_code"]) == ("required", "tier3_source_present")+ assert agent_eval_report_serialization_issue(payload) is None+ assert payload["report_truncation"]["omitted"] == {"token_usage_case_rows": 12}+ assert _without_token_usage(payload) == {+ **_without_token_usage(full.metadata["agent_eval"]),+ "applicability": "required",+ "reason_code": "tier3_source_present",+ "source_kind": payload["source_kind"],+ }+++def test_a_payload_over_the_limits_without_token_usage_keeps_no_token_record(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ agents = load_agent_data(_cases_run(tmp_path, agents=2, cases=6))+ full = build_agent_eval_payload("demo", copy.deepcopy(agents), use_llm_judge=False)+ assert full is not None+ base = _without_token_usage(full)+ # Token usage fits, then a later writer pushes the payload past the limit with or without it.+ monkeypatch.setattr(reporting_base, "AGENT_EVAL_REPORT_MAX_NODES", _nodes(full) + 1)+ bounded = build_agent_eval_payload("demo", agents, use_llm_judge=False)+ assert bounded is not None and "token_usage" in bounded+ extra = ["x"] * (_nodes(full) + 2 - _nodes({**base, "suggestions": []}))+ bounded["suggestions"] = extra++ tier3_report.fit_token_usage(bounded)++ assert bounded == {**base, "suggestions": extra}+ assert agent_eval_report_serialization_issue(bounded) is not None+ assert agent_eval_report_serialization_issue({**base, "suggestions": extra}) is not None+++def test_a_run_without_a_baseline_reports_its_baseline_tokens_as_not_run(tmp_path: Path) -> None:+ run = tmp_path / "run"+ _arm(run, "codex", "with-skill", [("case-1__a", (100, 10, 0), True), ("case-2__a", (200, 20, 0), True)])++ result = agent_eval_result_from_directory(tmp_path, run, use_llm_judge=False)++ assert result is not None+ payload = result.metadata["agent_eval"]+ assert payload["mode"] == "with_skill_only"+ codex = payload["token_usage"]["agents"]["codex"]+ assert codex["baseline"]["coverage"]["status"] == "not_run"+ assert (codex["delta"]["reason_codes"], codex["delta"]["reason"]) == (+ ["baseline_not_run"],+ "The baseline did not run.",+ )+ benchmark = BenchmarkReporter(include_timestamp=False).render_all([result])+ assert "baseline not run; uplift unavailable" in benchmark+ section = _section(benchmark, "## Token Usage")+ assert ["Codex", "All cases", "330", "not run", "N/A", "skill 2/2; baseline not run"] in _table_rows(section)+ assert "0 of 0" not in section+ assert "status unknown" not in section+ assert "different cases" not in section+++def test_a_reused_baseline_is_labelled_in_every_report(tmp_path: Path) -> None:+ skill = tmp_path / "demo"+ skill.mkdir()+ run = _run(tmp_path)+ # What ``tier3 evaluate --reuse-baseline`` records; the baseline trials are copies from that run.+ baseline = {"mode": "reused", "source_run_id": "run-1", "source_evaluated_at": "2026-11-01T00:00:00Z"}+ (run / "run_config.json").write_text(json.dumps({"baseline": baseline}), encoding="utf-8")++ result = agent_eval_result_from_directory(skill, run, use_llm_judge=False)++ assert result is not None+ usage = result.metadata["agent_eval"]["token_usage"]+ assert usage["baseline_reused"] is True+ assert usage["dataset"]["baseline"]["totals"]["total_tokens"] == 51722+ evaluate_summary = render_result(+ {"execution_status": "succeeded", "agents": {"codex": {}}, "token_usage": per_agent_token_usage(usage)}+ )+ reports = {+ "validate terminal": _cli_output(result),+ "tier3 evaluate terminal": evaluate_summary,+ "Markdown": MarkdownReporter().render_all([result]),+ "BENCHMARK.md": BenchmarkReporter(include_timestamp=False).render_all([result]),+ "HTML": HTMLReporter(include_timestamp=False).render_all([result]),+ }+ for name, report in reports.items():+ assert REUSED_BASELINE_NOTE in " ".join(report.split()), name+++def test_dashboards_do_not_read_dropped_token_rows_as_missing_trials(run_result: tuple[Path, Any]) -> None:+ _run_dir, result = run_result+ report = copy.deepcopy(result.metadata["agent_eval"])+ report["report_truncation"] = {"truncated": True, "omitted": {"token_usage_case_rows": 4, "token_usage": 1}}++ data = parse_dashboard_report(report, "report.json")++ codex = [row for row in comparison_rows(data.rows) if row["_agent_key"] == "codex"]+ assert [row["comparison_status"] for row in codex] == ["comparable"]+++# -- terminal ----------------------------------------------------------------------+++def test_validate_terminal_prints_agent_rows_and_notes(run_result: tuple[Path, Any]) -> None:+ _run_dir, result = run_result+ output = _cli_output(result)++ assert "Token Usage (measured, not scored)" in output+ rows = {+ line.split("│")[1].strip(): [cell.strip() for cell in line.split("│")[2:-1]]+ for line in output.splitlines()+ if line.startswith("│")+ }+ assert rows["claude-code"] == ["3,300", "50,072", "N/A", "skill 2/2; baseline 2/2 (1 unscored)"]+ assert rows["codex"] == ["1,210", "1,650", "-440 (-26.7%)", "skill 2/2; baseline 2/2"]+ assert rows["All agents"] == ["4,510", "51,722", "N/A", "skill 4/4; baseline 4/4 (1 unscored)"]+ assert "claude-code: No change: baseline incomplete (1 of 2 attempts scored)." in output+ assert VALIDATE_CASE_POINTER in output+ assert "case-1" not in output.split("Token Usage (measured, not scored)", 1)[1].split("Token usage per case", 1)[0]+++def test_tier3_evaluate_terminal_prints_the_agent_sums_the_report_step_recorded(tmp_path: Path) -> None:+ skill = tmp_path / "demo"+ skill.mkdir()+ run = _run(tmp_path)+ engine_result: dict[str, Any] = {"execution_status": "failed", "run_dir": str(run)}++ render_agent_eval_html_report(skill, run, engine_result=engine_result, use_llm_judge=False)++ recorded = engine_result["token_usage"]+ assert set(recorded["agents"]) == {"claude-code", "codex"}+ assert all("cases" not in agent for agent in recorded["agents"].values())+ assert recorded["dataset"]["baseline"]["totals"]["total_tokens"] == 51722+ display = {+ "execution_status": "succeeded",+ "agents": {"codex": {"execution_status": "succeeded"}},+ "token_usage": recorded,+ }+ output = render_result(display)+ assert "Token Usage (measured, not scored)" in output+ assert re.search(r"claude-code\s+│\s+3,300\s+│\s+50,072\s+│\s+N/A", output)+ assert EVALUATE_CASE_POINTER in " ".join(output.split())+++def test_terminal_tables_print_agent_names_as_text_not_markup() -> None:+ usage = {+ "agents": {+ "[bold red]agent[/bold red]": {+ "with_skill": {+ "totals": {"total_tokens": 10},+ "coverage": {"status": "complete", "measured_attempts": 1, "expected_attempts": 1},+ },+ "baseline": {"coverage": {"status": "not_run"}},+ "delta": {"status": "unavailable", "reason": "The baseline did not run."},+ }+ }+ }+ output = render_result({"execution_status": "succeeded", "agents": {"codex": {}}, "token_usage": usage})+ assert "[bold red]agent[/bold red]" in output+ assert "not run" in output+++# -- Markdown, BENCHMARK.md and HTML ---------------------------------------------------------+++def test_benchmark_token_usage_section_matches_the_golden_section(run_result: tuple[Path, Any]) -> None:+ _run_dir, result = run_result+ benchmark = BenchmarkReporter(include_timestamp=False).render_all([result])++ section = "## Token Usage\n" + _section(benchmark, "## Token Usage")+ assert section.rstrip("\n") + "\n" == GOLDEN.read_text(encoding="utf-8")+ # It sits after the score table and before the tier status.+ assert (+ benchmark.index("## Results at a Glance")+ < benchmark.index("## Token Usage")+ < benchmark.index("## Tier Status")+ )+++def test_benchmark_with_token_usage_passes_the_public_gate(run_result: tuple[Path, Any], tmp_path: Path) -> None:+ _run_dir, result = run_result+ card = tmp_path / "BENCHMARK.md"+ card.write_text(BenchmarkReporter(include_timestamp=False).render_all([result]), encoding="utf-8")++ assert [offender.reason for offender in benchmark_gate.scan_file(card)] == []+++def test_markdown_report_lists_token_usage_under_tier3(run_result: tuple[Path, Any]) -> None:+ _run_dir, result = run_result+ markdown = MarkdownReporter().render_all([result])++ section = markdown.split("### Token Usage\n", 1)[1].split("\n## ", 1)[0]+ assert "It is not scored" in section+ rows = _table_rows(section)+ assert ["codex", "case-2", "660", "880", "-220 (-25.0%)", "skill 1/1; baseline 1/1"] in rows+ assert ["claude-code", "case-2", "2,200", "48,422", "N/A", "skill 1/1; baseline 1/1 (1 unscored)"] in rows+++def test_html_report_lists_case_rows_under_measured_agent_resources(run_result: tuple[Path, Any]) -> None:+ _run_dir, result = run_result+ report = HTMLReporter(include_timestamp=False).render_all([result])++ resources = report.split("<summary>Measured Agent Resources</summary>", 1)[1].split("</details>", 1)[0]+ block = resources.split('<div id="t3-token-usage">', 1)[1]+ rows = [+ [re.sub(r"<[^>]+>", "", cell).strip() for cell in re.findall(r"<td>(.*?)</td>", row)]+ for row in re.findall(r"<tr[^>]*>(.*?)</tr>", block, flags=re.DOTALL)+ ]+ assert ["claude-code", "All cases", "3,300", "50,072", "N/A", "skill 2/2; baseline 2/2 (1 unscored)"] in rows+ assert ["codex", "case-1", "550", "770", "-220 (-28.6%)", "skill 1/1; baseline 1/1"] in rows+ assert ["All agents", "All cases", "4,510", "51,722", "N/A", "skill 4/4; baseline 4/4 (1 unscored)"] in rows+ assert "claude-code: No change: baseline incomplete (1 of 2 attempts scored)." in block+ # Extends the resources section; no second token chart.+ assert report.count('id="tier3-token-chart"') <= 1+++def test_html_rows_stay_whole_when_the_tier3_payload_is_above_the_preview_trigger(tmp_path: Path) -> None:+ result = agent_eval_result_from_directory(tmp_path, _cases_run(tmp_path, agents=2, cases=70), use_llm_judge=False)+ assert result is not None+ payload = result.metadata["agent_eval"]+ assert tier3_report._serialized_payload_size(payload) > html_reporting._TIER3_HTML_PREVIEW_TRIGGER_BYTES++ report = HTMLReporter(include_timestamp=False).render_all([result])++ assert "HTML preview omitted" in report+ block = report.split('<div id="t3-token-usage">', 1)[1].split("</details>", 1)[0]+ rows = [+ [re.sub(r"<[^>]+>", "", cell).strip() for cell in re.findall(r"<td>(.*?)</td>", row)]+ for row in re.findall(+ r"<tr[^>]*>(.*?)</tr>", block.split("<tbody>", 1)[1].split("</table>", 1)[0], flags=re.DOTALL+ )+ ]+ agent_row = next(row for row in rows if row[:2] == ["agent-0", "All cases"])+ assert agent_row[2:] == ["10,115", "10,115", "+0 (+0.0%)", "skill 70/70; baseline 70/70"]+ case_rows = [row for row in rows if row[0] == "agent-1" and row[1] != "All cases"]+ assert [row[1] for row in case_rows] == [f"case-{index:03d}" for index in range(64)]+ assert all(row[2] == row[3] and "(partial)" not in row[2] for row in case_rows)+ assert "12 more case row(s) are in the JSON payload under token_usage." in block+++def test_untrusted_case_names_are_escaped_in_every_report(tmp_path: Path) -> None:+ hostile = "<img src=x onerror=alert(1)>|`x`"+ run = tmp_path / "run"+ for variant in ("with-skill", "without-skill"):+ _arm(run, "codex", variant, [("case__a", (100, 10, 0), True)])+ reward_file = run / "codex" / variant / "trials" / "case__a" / "reward.json"+ reward = json.loads(reward_file.read_text(encoding="utf-8"))+ reward_file.write_text(json.dumps({**reward, "entry_id": hostile}), encoding="utf-8")+ result = agent_eval_result_from_directory(tmp_path, run, use_llm_judge=False)+ assert result is not None+ assert result.metadata["agent_eval"]["token_usage"]["agents"]["codex"]["cases"][0]["entry_id"] == hostile++ report = HTMLReporter(include_timestamp=False).render_all([result])+ benchmark = BenchmarkReporter(include_timestamp=False).render_all([result])+ markdown = MarkdownReporter().render_all([result])++ block = report.split('<div id="t3-token-usage">', 1)[1].split("</table>", 1)[0]+ assert "<img" not in block+ assert "<img src=x onerror=alert(1)>" in block+ for text, heading in ((benchmark, "## Token Usage"), (markdown, "### Token Usage")):+ section = _section(text, heading)+ assert "<img" not in section+ [row] = [line for line in section.splitlines() if "onerror" in line]+ # The pipe in the case name cannot add a column.+ assert len(_table_rows(row)[0]) == 6+++def test_markdown_tables_cap_case_rows_and_say_where_the_rest_are(tmp_path: Path) -> None:+ run = tmp_path / "run"+ cases = [(f"case-{index:02d}__a", (100, 10, 0), True) for index in range(60)]+ _arm(run, "codex", "with-skill", cases)+ _arm(run, "codex", "without-skill", cases)+ result = agent_eval_result_from_directory(tmp_path, run, use_llm_judge=False)+ assert result is not None++ for text, heading in (+ (BenchmarkReporter(include_timestamp=False).render_all([result]), "## Token Usage"),+ (MarkdownReporter().render_all([result]), "### Token Usage"),+ ):+ section = _section(text, heading)+ assert len([row for row in _table_rows(section) if row[1].startswith("case-")]) == 50+ assert "10 more case row(s) are in the JSON payload under `token_usage`." in section+++def test_docs_and_changelog_describe_the_token_usage_contract() -> None:+ docs = (REPO_ROOT / "docs" / "reports.mdx").read_text(encoding="utf-8")+ section = docs.split("### Token usage\n", 1)[1].split("\n### ", 1)[0]+ for field in (+ "token_usage",+ "total_tokens",+ "uncached_prompt_tokens",+ "expected_attempts",+ "observed_attempts",+ "measured_attempts",+ "unscored_attempts",+ "missing_token_counters",+ "invalid_token_counters",+ "missing_attempts",+ "total_tokens_change_percent",+ "baseline_failed",+ "case_scope_mismatch",+ "agent_scope_mismatch",+ "baseline_status_unknown",+ "total_out_of_range",+ "case_rows_omitted",+ "token_usage_case_rows",+ "validate --verbose",+ "tier3 evaluate --verbose",+ "tier3-benchmark.md",+ "first 50 case rows",+ "at most 64 per agent",+ "baseline_not_run",+ "baseline_reused",+ "--reuse-baseline",+ "case findings",+ "applicability fields",+ "left out without a record",+ ):+ assert field in section, field+ unreleased = (REPO_ROOT / "CHANGELOG.md").read_text(encoding="utf-8").split("\n## ", 2)[1]+ added = unreleased.split("### Added\n", 1)[1].split("\n### ", 1)[0]+ assert "token usage per case" in addeddiff --git a/tests/test_public_benchmark_gate.py b/tests/test_public_benchmark_gate.pyindex 75831da9..ef46ffbe 100644--- a/tests/test_public_benchmark_gate.py+++ b/tests/test_public_benchmark_gate.py@@ -189,6 +189,9 @@ def test_gate_accepts_redesigned_public_card(tmp_path: Path) -> None:"50.0% → 50.0% (±0.0 points)","0.0% → 100.0% (+100.0 points)","92.0% — baseline not run; uplift unavailable",+ "92.0% — baseline incomplete (1 of 2 attempts scored); uplift unavailable",+ "92.0% — baseline unavailable (0 of 2 attempts scored); uplift unavailable",+ "92.0% — baseline failed (2 of 2 attempts scored); uplift unavailable","49.95% — INCONCLUSIVE: skill never activated; uplift unavailable","Not available",],diff --git a/tests/tier3/test_token_usage.py b/tests/tier3/test_token_usage.pynew file mode 100644index 00000000..527157dd--- /dev/null+++ b/tests/tier3/test_token_usage.py@@ -0,0 +1,545 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Token usage per case, agent and run: measured, never estimated and never scored."""++from __future__ import annotations++import json+from typing import Any++import pytest++from skillevaluator.tier3.token_usage import build_token_usage, normalize_token_counts+++def _trial(case: str, prompt: int, completion: int, cached: int | None = None) -> dict[str, Any]:+ tokens = {"prompt": prompt, "completion": completion}+ if cached is not None:+ tokens["cached"] = cached+ return {"entry_id": case, "trial_id": f"{case}__a", "tokens": tokens}+++def _agent(+ with_skill: list[dict[str, Any]],+ baseline: list[dict[str, Any]],+ *,+ with_status: str = "succeeded",+ baseline_status: str = "succeeded",+ unscored: list[dict[str, Any]] | None = None,+ unscored_baseline: list[dict[str, Any]] | None = None,+) -> dict[str, Any]:+ unscored = unscored or []+ unscored_baseline = unscored_baseline or []+ return {+ "trials": with_skill,+ "trials_baseline": baseline,+ "usage_only_attempts": [{**row, "scored": False} for row in unscored],+ "usage_only_attempts_baseline": [{**row, "scored": False} for row in unscored_baseline],+ "conditions": {+ "with_skill": {+ "execution_status": with_status,+ "expected_attempts": len(with_skill) + len(unscored),+ "scored_attempts": len(with_skill),+ },+ "without_skill": {+ "execution_status": baseline_status,+ "expected_attempts": len(baseline) + len(unscored_baseline),+ "scored_attempts": len(baseline),+ },+ },+ "execution_status": "failed" if "failed" in (with_status, baseline_status) else "succeeded",+ }+++def _scopes(usage: dict[str, Any], agent: str = "codex") -> list[dict[str, Any]]:+ return [usage["dataset"], usage["agents"][agent], *usage["agents"][agent]["cases"]]+++# -- one attempt's counters --------------------------------------------------------+++def test_cached_tokens_are_part_of_the_prompt_and_never_added_again() -> None:+ assert normalize_token_counts({"prompt": 100, "completion": 20, "cached": 40}) == {+ "prompt_tokens": 100,+ "cached_tokens": 40,+ "uncached_prompt_tokens": 60,+ "completion_tokens": 20,+ "total_tokens": 120,+ "complete": True,+ }+++def test_an_omitted_cache_counter_is_zero_and_atif_names_are_read() -> None:+ normalized = normalize_token_counts({"prompt_tokens": 100, "completion_tokens": 20})+ assert normalized is not None+ assert (normalized["cached_tokens"], normalized["total_tokens"], normalized["complete"]) == (0, 120, True)+ assert normalize_token_counts({}) is None+ assert normalize_token_counts(None) is None++[email protected]("field", ["prompt", "completion", "cached"])[email protected]("value", [-1, True, "100", float("nan"), 1.5, 2**60])+def test_invalid_counters_are_rejected_and_named_without_their_values(field: str, value: object) -> None:+ raw: dict[str, Any] = {"prompt": 100, "completion": 20, "cached": 10, field: value}++ normalized = normalize_token_counts(raw)++ assert normalized is not None+ assert normalized["complete"] is False+ assert normalized["invalid_counters"] == [f"{field}_tokens"]+ assert "100" not in json.dumps(normalized["invalid_counters"])+++def test_cached_above_prompt_is_invalid() -> None:+ normalized = normalize_token_counts({"prompt": 10, "completion": 5, "cached": 11})+ assert normalized is not None+ assert (normalized["complete"], normalized["invalid_counters"]) == (False, ["cached_tokens"])+++# -- sums per case, agent and run -----------------------------------------------------+++def test_sums_each_case_each_agent_and_all_agents() -> None:+ usage = build_token_usage(+ {+ "codex": _agent(+ [_trial("case-1", 100, 20, 40), _trial("case-2", 200, 30, 50)],+ [_trial("case-1", 150, 25, 30), _trial("case-2", 250, 35, 40)],+ ),+ "opencode": _agent([_trial("case-1", 80, 10, 20)], [_trial("case-1", 90, 15, 10)]),+ }+ )++ assert usage is not None+ assert usage["scored"] is False+ codex = usage["agents"]["codex"]+ assert codex["with_skill"]["totals"] == {+ "prompt_tokens": 300,+ "cached_tokens": 90,+ "uncached_prompt_tokens": 210,+ "completion_tokens": 50,+ "total_tokens": 350,+ }+ cases = {row["entry_id"]: row for row in codex["cases"]}+ assert cases["case-1"]["with_skill"]["totals"]["total_tokens"] == 120+ assert cases["case-1"]["baseline"]["totals"]["total_tokens"] == 175+ assert (cases["case-1"]["delta"]["total_tokens"], cases["case-1"]["delta"]["total_tokens_change_percent"]) == (+ -55,+ -31.43,+ )+ assert codex["delta"]["total_tokens"] == 350 - 460+ assert usage["dataset"]["with_skill"]["totals"]["total_tokens"] == 440+ assert usage["dataset"]["baseline"]["totals"]["total_tokens"] == 565+ assert usage["dataset"]["delta"]["total_tokens"] == -125+ assert usage["dataset"]["with_skill"]["coverage"]["measured_attempts"] == 3+++def test_a_failed_attempt_is_counted_for_usage_but_not_as_a_scored_attempt() -> None:+ failed = {"entry_id": "case-1", "trial_id": "case-1__b", "tokens": {"prompt": 400, "completion": 4000}}+ usage = build_token_usage(+ {+ "codex": _agent(+ [_trial("case-1", 100, 20)],+ [_trial("case-1", 90, 10)],+ unscored=[failed],+ )+ }+ )++ assert usage is not None+ with_skill = usage["agents"]["codex"]["with_skill"]+ assert with_skill["totals"]["total_tokens"] == 120 + 4400+ assert with_skill["coverage"] == {+ "status": "complete",+ "expected_attempts": 2,+ "observed_attempts": 2,+ "measured_attempts": 2,+ "unscored_attempts": 1,+ "reason_codes": [],+ }+++def test_a_failed_attempt_with_a_cut_harbor_trial_name_is_matched_to_its_case() -> None:+ case = "a-very-long-case-identifier-that-harbor-cuts-short"+ trial_prefix = case[:32].rstrip("_-")+ failed = {"entry_id": trial_prefix, "trial_id": f"{trial_prefix}__b", "tokens": {"prompt": 50, "completion": 5}}+ usage = build_token_usage({"codex": _agent([_trial(case, 100, 20)], [_trial(case, 90, 10)], unscored=[failed])})++ assert usage is not None+ [row] = usage["agents"]["codex"]["cases"]+ assert row["entry_id"] == case+ assert row["with_skill"]["totals"]["total_tokens"] == 175+++def test_a_stop_on_pass_trial_name_is_matched_to_its_case() -> None:+ def timed_out(arm: str) -> dict[str, Any]:+ # Without a Harbor result, the loader keeps the trial name before Harbor's ``__<id>``.+ name = f"demo-codex-{arm}-case-1-attempt001__case-1"+ return {"entry_id": name, "trial_id": f"{name}__a", "tokens": {"prompt": 40, "completion": 4}}++ usage = build_token_usage(+ {+ "codex": _agent(+ [_trial("case-1", 100, 20)],+ [_trial("case-1", 90, 10)],+ unscored=[timed_out("with")],+ unscored_baseline=[timed_out("without")],+ )+ }+ )++ assert usage is not None+ codex = usage["agents"]["codex"]+ assert [row["entry_id"] for row in codex["cases"]] == ["case-1"]+ assert codex["delta"]["status"] == "available"+++def test_partial_coverage_sums_only_measured_attempts_and_never_estimates() -> None:+ missing = {"entry_id": "case-2", "trial_id": "case-2__a"}+ invalid = {"entry_id": "case-3", "trial_id": "case-3__a", "tokens": {"prompt": -5, "completion": 9}}+ usage = build_token_usage(+ {+ "codex": _agent(+ [_trial("case-1", 100, 20), missing, invalid],+ [_trial("case-1", 90, 10), _trial("case-2", 90, 10), _trial("case-3", 90, 10)],+ )+ }+ )++ assert usage is not None+ with_skill = usage["agents"]["codex"]["with_skill"]+ assert with_skill["totals"]["total_tokens"] == 120+ assert with_skill["totals"]["prompt_tokens"] == 100+ assert with_skill["coverage"]["status"] == "partial"+ assert (with_skill["coverage"]["measured_attempts"], with_skill["coverage"]["expected_attempts"]) == (1, 3)+ assert with_skill["coverage"]["reason_codes"] == ["invalid_token_counters", "missing_token_counters"]+ for scope in (usage["dataset"], usage["agents"]["codex"]):+ assert scope["with_skill"]["coverage"]["status"] == "partial"+ assert scope["delta"]["status"] == "unavailable"+ assert scope["delta"]["total_tokens"] is None+ assert "with_skill_tokens_incomplete" in scope["delta"]["reason_codes"]+ assert "With-skill run token counts cover 1 of 3 attempts." in usage["agents"]["codex"]["delta"]["reason"]+ cases = {row["entry_id"]: row for row in usage["agents"]["codex"]["cases"]}+ assert cases["case-1"]["delta"]["total_tokens"] == 20+ assert cases["case-2"]["with_skill"]["totals"] is None+ assert cases["case-2"]["with_skill"]["coverage"]["status"] == "unavailable"+++def test_an_attempt_that_never_ran_leaves_the_arm_partial() -> None:+ agent = _agent([_trial("case-1", 100, 20)], [_trial("case-1", 90, 10)])+ agent["conditions"]["with_skill"]["expected_attempts"] = 2+ agent["pass_at_k"] = {"with_skill": {"k": 2, "cases": {"case-1": {"attempts_skipped": 0}}}}++ usage = build_token_usage({"codex": agent})++ assert usage is not None+ coverage = usage["agents"]["codex"]["with_skill"]["coverage"]+ assert (coverage["status"], coverage["observed_attempts"], coverage["reason_codes"]) == (+ "partial",+ 1,+ ["missing_attempts"],+ )+ [case] = usage["agents"]["codex"]["cases"]+ assert case["with_skill"]["coverage"]["expected_attempts"] == 2+ assert case["delta"]["total_tokens"] is None+++def test_a_planned_case_without_attempts_gets_a_row_with_no_tokens() -> None:+ agent = _agent([_trial("case-1", 100, 20)], [])+ agent["pass_at_k"] = {+ "with_skill": {"k": 1, "cases": {"case-1": {"attempts_skipped": 0}, "case-2": {"attempts_skipped": 0}}}+ }+ agent["conditions"]["without_skill"] = {"execution_status": "skipped", "expected_attempts": 0}++ usage = build_token_usage({"codex": agent})++ assert usage is not None+ cases = {row["entry_id"]: row for row in usage["agents"]["codex"]["cases"]}+ assert cases["case-2"]["with_skill"] == {+ "totals": None,+ "coverage": {+ "status": "unavailable",+ "expected_attempts": 1,+ "observed_attempts": 0,+ "measured_attempts": 0,+ "unscored_attempts": 0,+ "reason_codes": ["missing_attempts"],+ },+ }+ assert cases["case-2"]["baseline"]["coverage"]["status"] == "not_run"+++def test_attempts_skipped_after_a_pass_are_not_missing() -> None:+ agent = _agent([_trial("case-1", 100, 20)], [_trial("case-1", 90, 10)])+ agent["pass_at_k"] = {"with_skill": {"k": 3, "cases": {"case-1": {"attempts_skipped": 2}}}}++ usage = build_token_usage({"codex": agent})++ assert usage is not None+ [case] = usage["agents"]["codex"]["cases"]+ assert case["with_skill"]["coverage"]["status"] == "complete"+ assert case["delta"]["total_tokens"] == 20+++def test_a_recovered_timeout_attempt_is_expected_usage() -> None:+ history = {"entry_id": "case-1", "trial_id": "case-1__x", "tokens": {"prompt": 10, "completion": 1}}+ agent = _agent([_trial("case-1", 100, 20)], [_trial("case-1", 90, 10)])+ agent["usage_only_attempts"] = [{**history, "scored": False}]+ agent["conditions"]["with_skill"]["recovered_attempts_total"] = 1++ usage = build_token_usage({"codex": agent})++ assert usage is not None+ with_skill = usage["agents"]["codex"]["with_skill"]+ assert (with_skill["coverage"]["status"], with_skill["coverage"]["expected_attempts"]) == ("complete", 2)+ assert with_skill["totals"]["total_tokens"] == 131+ # The arms ran different attempts, so they are not compared.+ assert usage["agents"]["codex"]["delta"]["reason_codes"] == ["case_scope_mismatch"]+++# -- when a change is given ---------------------------------------------------------------++[email protected](("with_total", "percent"), [(590, -41.0), (1000, 0.0), (1250, 25.0)])+def test_percentage_change_is_given_at_every_scope(with_total: int, percent: float) -> None:+ usage = build_token_usage({"codex": _agent([_trial("case-1", with_total, 0)], [_trial("case-1", 1000, 0)])})++ assert usage is not None+ for scope in _scopes(usage):+ assert scope["delta"] == {+ "status": "available",+ "total_tokens": with_total - 1000,+ "total_tokens_change_percent": percent,+ "reason_codes": [],+ "reason": None,+ }+++def test_a_zero_token_baseline_keeps_the_difference_without_a_percentage() -> None:+ usage = build_token_usage({"codex": _agent([_trial("case-1", 10, 0)], [_trial("case-1", 0, 0)])})++ assert usage is not None+ delta = usage["dataset"]["delta"]+ assert (delta["total_tokens"], delta["total_tokens_change_percent"], delta["reason_codes"]) == (+ 10,+ None,+ ["zero_baseline"],+ )+++def test_a_reused_baseline_is_labelled_and_otherwise_unchanged() -> None:+ agents = {"codex": _agent([_trial("case-1", 100, 10)], [_trial("case-1", 200, 20)])}++ plain = build_token_usage(agents)+ reused = build_token_usage(agents, baseline_reused=True)++ assert plain is not None and reused is not None+ assert "baseline_reused" not in plain+ assert reused["baseline_reused"] is True+ # The reused rows are measurements like any other, so the sums and the change stay.+ assert {key: value for key, value in reused.items() if key != "baseline_reused"} == plain+ assert reused["dataset"]["delta"]["total_tokens"] == -110+++def test_a_skipped_baseline_is_not_run_and_has_no_change() -> None:+ agent = _agent([_trial("case-1", 100, 20)], [])+ agent["conditions"]["without_skill"] = {"execution_status": "skipped", "expected_attempts": 0}++ usage = build_token_usage({"codex": agent})++ assert usage is not None+ for scope in _scopes(usage):+ assert scope["baseline"]["coverage"]["status"] == "not_run"+ assert scope["baseline"]["totals"] is None+ assert scope["delta"]["total_tokens"] is None+ assert scope["delta"]["reason_codes"][0] == "baseline_not_run"+ # The skip is the one reason: the arms did not run different cases.+ codex = usage["agents"]["codex"]+ assert (codex["delta"]["reason_codes"], codex["delta"]["reason"]) == (+ ["baseline_not_run"],+ "The baseline did not run.",+ )++[email protected]("mode", ["both", "with_skill_only"])+def test_a_baseline_without_a_record_or_attempts_did_not_run(mode: str) -> None:+ agent = _agent([_trial("case-1", 100, 20)], [])+ del agent["conditions"]["without_skill"]++ usage = build_token_usage({"codex": agent}, mode=mode)++ assert usage is not None+ for scope in _scopes(usage)[1:]:+ assert scope["baseline"]["coverage"] == {+ "status": "not_run",+ "expected_attempts": 0,+ "observed_attempts": 0,+ "measured_attempts": 0,+ "unscored_attempts": 0,+ "reason_codes": [],+ }+ assert (scope["delta"]["reason_codes"], scope["delta"]["reason"]) == (+ ["baseline_not_run"],+ "The baseline did not run.",+ )+ assert usage["dataset"]["baseline"]["coverage"]["status"] == "not_run"+++def test_an_arm_the_run_mode_leaves_out_did_not_run() -> None:+ agent = _agent([_trial("case-1", 100, 20)], [])+ agent["conditions"]["without_skill"] = {"expected_attempts": 1}++ usage = build_token_usage({"codex": agent}, mode="with_skill_only")++ assert usage is not None+ assert usage["agents"]["codex"]["baseline"]["coverage"]["status"] == "not_run"+ assert usage["agents"]["codex"]["delta"]["reason_codes"] == ["baseline_not_run"]+ # In a run of both arms the same arm planned an attempt and recorded none.+ usage = build_token_usage({"codex": agent})+ assert usage is not None+ codex = usage["agents"]["codex"]+ assert codex["baseline"]["coverage"]["status"] == "unavailable"+ assert (codex["delta"]["reason_codes"], codex["delta"]["reason"]) == (+ ["baseline_tokens_incomplete"],+ "No baseline attempts were recorded.",+ )++ with_skill = _agent([], [_trial("case-1", 100, 20)])+ del with_skill["conditions"]["with_skill"]+ usage = build_token_usage({"codex": with_skill}, mode="baseline_only")+ assert usage is not None+ assert usage["agents"]["codex"]["with_skill"]["coverage"]["status"] == "not_run"+ assert usage["agents"]["codex"]["delta"]["reason_codes"] == ["with_skill_not_run"]+++def test_absent_baseline_evidence_does_not_claim_the_baseline_never_ran() -> None:+ agent = _agent([_trial("case-1", 100, 20)], [])+ for record in ({}, {"execution_status": "succeeded"}, {"scored_attempts": 1}):+ agent["conditions"]["without_skill"] = record+ usage = build_token_usage({"codex": agent})+ assert usage is not None+ baseline = usage["agents"]["codex"]["baseline"]+ assert baseline["coverage"]["status"] == "unavailable"+ assert "no_attempts_recorded" in baseline["coverage"]["reason_codes"]+ # One reason, not a status or case mismatch on top of it.+ assert (usage["agents"]["codex"]["delta"]["reason_codes"], usage["agents"]["codex"]["delta"]["reason"]) == (+ ["baseline_tokens_incomplete"],+ "No baseline attempts were recorded.",+ )+++def test_arms_with_different_attempt_counts_or_cases_are_not_compared() -> None:+ usage = build_token_usage(+ {"codex": _agent([_trial("case-1", 590, 0)], [_trial("case-1", 1000, 0), _trial("case-2", 1000, 0)])}+ )+ assert usage is not None+ assert usage["agents"]["codex"]["delta"]["reason_codes"] == ["case_scope_mismatch"]+ assert usage["dataset"]["delta"]["reason_codes"] == ["agent_scope_mismatch"]++ usage = build_token_usage({"codex": _agent([_trial("case-1", 50, 0)], [_trial("case-2", 100, 0)])})+ assert usage is not None+ assert usage["agents"]["codex"]["delta"]["reason_codes"] == ["case_scope_mismatch"]+ assert usage["dataset"]["delta"]["reason_codes"] == ["agent_scope_mismatch"]+++def test_one_agent_without_a_change_blocks_the_change_over_all_agents() -> None:+ usage = build_token_usage(+ {+ "codex": _agent([_trial("case-1", 100, 0)], [_trial("case-1", 200, 0)]),+ "opencode": _agent([_trial("case-1", 100, 0)], [_trial("case-1", 200, 0)], baseline_status="failed"),+ }+ )++ assert usage is not None+ assert usage["agents"]["codex"]["delta"]["total_tokens"] == -100+ assert usage["dataset"]["baseline"]["totals"]["total_tokens"] == 400+ assert usage["dataset"]["delta"]["reason_codes"] == ["agent_scope_mismatch"]+++def test_a_failed_baseline_arm_keeps_its_usage_but_gets_no_change() -> None:+ timed_out = {"entry_id": "case-1", "trial_id": "case-1__b", "tokens": {"prompt": 400, "completion": 47522}}+ agent = _agent(+ [_trial("case-1", 100, 20), _trial("case-1", 110, 20)],+ [_trial("case-1", 90, 10)],+ baseline_status="failed",+ unscored_baseline=[timed_out],+ )++ usage = build_token_usage({"claude-code": agent})++ assert usage is not None+ agent_usage = usage["agents"]["claude-code"]+ assert agent_usage["baseline"]["totals"]["total_tokens"] == 100 + 47922+ assert agent_usage["baseline"]["coverage"]["status"] == "complete"+ assert agent_usage["baseline"]["coverage"]["unscored_attempts"] == 1+ for delta in (agent_usage["delta"], *(case["delta"] for case in agent_usage["cases"])):+ assert delta["status"] == "unavailable"+ assert delta["reason_codes"] == ["baseline_failed"]+ assert delta["reason"] == "No change: baseline incomplete (1 of 2 attempts scored)."++[email protected]("status", ["unknown", "interrupted", None])+def test_an_arm_without_a_known_run_status_gets_no_change(status: str | None) -> None:+ agent = _agent([_trial("case-1", 100, 20)], [_trial("case-1", 500, 20)], baseline_status="succeeded")+ agent["conditions"]["without_skill"]["execution_status"] = status++ usage = build_token_usage({"codex": agent})++ assert usage is not None+ codex = usage["agents"]["codex"]+ # The usage is still measured, but the report withholds this arm's scores.+ assert codex["baseline"]["coverage"]["status"] == "complete"+ for delta in (codex["delta"], *(case["delta"] for case in codex["cases"]), usage["dataset"]["delta"]):+ assert delta["status"] == "unavailable"+ assert delta["total_tokens"] is None+ assert codex["delta"]["reason_codes"] == ["baseline_status_unknown"]+ assert codex["delta"]["reason"] == "No change: baseline status unknown."+++def test_a_sum_above_the_exact_json_range_is_not_reported() -> None:+ # Each counter is valid, but each arm's sum is above 2**53 - 1.+ half = 2**52+ usage = build_token_usage(+ {+ "codex": _agent(+ [_trial("case-1", half + 2, 0), _trial("case-1", half + 2, 0)],+ [_trial("case-1", half, 0), _trial("case-1", half, 0)],+ )+ }+ )++ assert usage is not None+ codex = usage["agents"]["codex"]+ for scope in (usage["dataset"], codex, codex["cases"][0]):+ for arm in ("with_skill", "baseline"):+ assert scope[arm]["totals"] is None+ assert scope[arm]["coverage"]["status"] == "unavailable"+ assert "total_out_of_range" in scope[arm]["coverage"]["reason_codes"]+ assert scope["delta"]["status"] == "unavailable"+ assert scope["delta"]["total_tokens"] is None+ assert codex["delta"]["reason_codes"] == ["with_skill_total_out_of_range", "baseline_total_out_of_range"]+ assert "largest integer JSON keeps exact" in codex["delta"]["reason"]+++def test_agent_sums_within_range_can_still_pass_it_over_all_agents() -> None:+ half = 2**52+ usage = build_token_usage(+ {+ "codex": _agent([_trial("case-1", half, 0)], [_trial("case-1", half, 0)]),+ "opencode": _agent([_trial("case-1", half, 0)], [_trial("case-1", half, 0)]),+ }+ )++ assert usage is not None+ assert usage["agents"]["codex"]["with_skill"]["totals"]["total_tokens"] == half+ dataset = usage["dataset"]+ assert dataset["with_skill"]["totals"] is None+ assert dataset["with_skill"]["coverage"]["reason_codes"] == ["total_out_of_range"]+ assert "with_skill_total_out_of_range" in dataset["delta"]["reason_codes"]+++def test_no_measured_attempt_gives_no_token_usage() -> None:+ bare = {"entry_id": "case-1", "trial_id": "case-1__a"}+ assert build_token_usage({"codex": _agent([bare], [bare])}) is None+ assert build_token_usage({}) is None