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
feat(tier3): split measured agent time into LLM and tool seconds (#344)
Narendran Raghavan55d2d046595e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2a4311de..25d28880 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -307,6 +307,18 @@ All notable changes to SkillEvaluator are documented in this file.upgrade, or not matched by the LLM stage, are reported instead of silentlysuppressing nothing; fingerprints only match static-only runs.+- Tier 3 **Measured Agent Resources** split each trial's trajectory time into+ LLM seconds and tool seconds, plus LLM milliseconds per prompt + completion+ token, with with-skill-minus-baseline deltas in the HTML report and the+ `resources` JSON object. Native ATIF timing is used when present; otherwise+ the time is inferred from step timestamps and the `Wall time` header of Codex+ shell and `apply_patch` output, so the default Codex agent on Harbor 0.24+ gets real values. Each trial records its timing source, and a comparison that+ mixes native and inferred timing carries a `mixed_timing_sources` caveat.+ Trials with unmeasured tool calls (for example `update_plan`, web search or+ MCP tools) stay `N/A`, and the time between multi-step Harbor steps is not+ counted. Deltas keep the existing complete-arm and matching-case rules;+ scores, verdicts and gates do not change.- `scripts/ci/check_public_benchmarks.py` accepts `--expected-source-repository`,`--expected-source-revision` and `--expected-evaluator-container-revision`,so a publishing pipeline can check that each card names the source it askeddiff --git a/docs/reports.mdx b/docs/reports.mdxindex 397175ca..cfdccfac 100644--- a/docs/reports.mdx+++ b/docs/reports.mdx@@ -528,13 +528,47 @@ agent with observed activation can still contribute a comparison.### Measured agent resourcesEach agent's canonical JSON payload contains a `resources` object. The HTML-table shows total prompt plus completion tokens and agent execution seconds for-each arm, telemetry coverage, and the with-skill-minus-baseline difference.+table shows total prompt plus completion tokens, agent execution seconds, LLM+seconds, tool seconds, and LLM milliseconds per token for each arm, telemetry+coverage, and the with-skill-minus-baseline difference. A negative difference+means less use with the skill; the HTML percentage divides it by the baseline.Routing/tool-productivity efficiency remains a separate score. Missing countersand incomplete arms produce null totals or deltas (`N/A` in HTML). Resourcedeltas require matching case counts and complete measurements in both arms;they do not measure evaluator tokens, setup time, price, or statistical savings.+| Measurement | Meaning |+| --- | --- |+| Agent execution seconds (`agent_seconds`) | Harbor's measured agent phase from the trial's `result.json`. Environment setup, agent installation, and verifier time are excluded. |+| LLM seconds (`llm_seconds`) | Model time from the trial's ATIF trajectory. With native ATIF timing (source `atif`), the sum of `llm_duration_ms` when every agent step records it. Otherwise it is inferred from step timestamps (source `step_timestamps`): each gap between steps counts once, and the part not spent in a tool is LLM time, which then also includes harness and queue time. |+| Tool seconds (`tool_seconds`) | Tool execution time. Native timing takes the union of tool-call intervals, so overlapping calls count once. Inferred timing reads the `Wall time` that Codex writes in the header of its shell and `apply_patch` tool output, never from the command output, or the `duration_seconds` Harbor keeps for those calls; parallel calls on one step count their longest wall time. A trajectory without tool calls measures 0 seconds. |+| LLM ms per token (`llm_ms_per_token`) | `1000 × LLM seconds / (prompt + completion tokens)` over the arm's totals. It needs complete LLM-time and token totals and a positive token count. |++Each trial's `timing` object records `llm_seconds`, `tool_seconds`, and+`source`, and `resources.timing_sources` lists the sources each arm used. If+the measurements mix native and inferred timing, `resources.caveats` contains+`mixed_timing_sources` and the HTML report says the LLM and tool seconds are+not like-for-like.++Inference covers trajectories whose tool calls are all Codex shell tools+(`exec_command`, `write_stdin`, `wait`, `wait_command`, `shell`, and+`shell_command`) or `apply_patch`, each with a recorded wall time. A trial that+also calls a tool with no recorded duration, such as web search,+`update_plan`, or an MCP tool, or whose step timestamps are missing, lack a UTC+offset, or run backwards, has no LLM or tool time. Agents without native timing+or Codex `Wall time` headers are timed only when their trajectory has no tool+calls.+Each step of a multi-step task is timed on its own, so the time between Harbor+steps is not counted. Steps marked `is_copied_context` repeat context from an+earlier trajectory and are not timed; a copied step after new steps leaves the+trial without timing. Copied timestamps do not show when the first new response+started, so inferred timing also leaves the trial without timing when the new+steps after copied context start with an agent step. Trials whose `trajectory.json` was omitted (too large, or+redaction or validation failed) and multi-step trials scored per step have no+timing. Missing timing stays `N/A` (`null` in JSON), never zero, and follows the+same complete-arm and matching-case rules as tokens. Timing is diagnostic and+does not change scores, verdicts, or gates.+### Failure reasons and per-trial rowsEach evaluator card lists its per-trial evidence by eval case with thediff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdxindex e06f5d12..293ea51e 100644--- a/docs/tier3-live-evaluation.mdx+++ b/docs/tier3-live-evaluation.mdx@@ -1030,6 +1030,10 @@ with-skill total minus baseline total: negative values indicate less observeduse. A delta requires complete telemetry, complete successful arms, and matchingcase counts including repeated attempts. Missing measurements, skipped baselines,partial runs, and unsupported multi-step timing remain `N/A`; they are not zero.+The same table splits each trial's trajectory time into LLM seconds and tool+seconds, from native ATIF timing or inferred from step timestamps and Codex+tool wall times, and says which source each arm used. See+[Reports & Results](reports.mdx) for the timing rules.These are observations for this run, not a graded efficiency or cost claim.Each dimension receives a score and a diagnostic band: **PASS** at 0.50 ordiff --git a/src/skillevaluator/evaluation/tier3_report.py b/src/skillevaluator/evaluation/tier3_report.pyindex ed884a87..031a0c61 100644--- a/src/skillevaluator/evaluation/tier3_report.py+++ b/src/skillevaluator/evaluation/tier3_report.py@@ -2884,6 +2884,7 @@ def _normalize_trials(rewards: list[dict[str, Any]], metrics: list[str]) -> listoverall_score,)from skillevaluator.tier3.harbor.report_data import logical_trial_reward_groups+ from skillevaluator.tier3.harbor.resource_usage import normalized_trial_timingout: list[dict[str, Any]] = []reward_groups = logical_trial_reward_groups([reward for reward in rewards if isinstance(reward, dict)])@@ -2943,6 +2944,9 @@ def _normalize_trials(rewards: list[dict[str, Any]], metrics: list[str]) -> list}if cached_tokens is not None:trial["tokens"]["cached"] = cached_tokens+ timing = normalized_trial_timing(traj.get("timing"))+ if timing is not None:+ trial["timing"] = timingwarnings = list(dict.fromkeys(str(warning) for item in group if isinstance(item.get("warnings"), list) for warning in item["warnings"]diff --git a/src/skillevaluator/reporting/templates/report.html.j2 b/src/skillevaluator/reporting/templates/report.html.j2index 982c7322..11e731e5 100644--- a/src/skillevaluator/reporting/templates/report.html.j2+++ b/src/skillevaluator/reporting/templates/report.html.j2@@ -2946,26 +2946,43 @@<details class="t3-details" open><summary>Measured Agent Resources</summary><div class="t3-details-body">- <p class="t3-section-hint">Efficiency scores measure routing and productive tool use. These separate measurements show observed agent resource use. Delta = with skill minus baseline; negative means less use. Judge and setup time are excluded. Deltas require complete telemetry and matching case counts in both arms.</p>+ <p class="t3-section-hint">Efficiency scores measure routing and productive tool use. These separate measurements show observed agent resource use. Delta = with skill minus baseline; negative means less use. Judge and setup time are excluded. Deltas require complete telemetry and matching case counts in both arms. LLM and tool seconds split the agent's trajectory time; inferred LLM time also includes harness and queue time.</p>+ {% set t3_resource_rows = [+ ('tokens', 'Prompt + completion tokens (cache included)', '{:,.0f}', 'total'),+ ('agent_seconds', 'Agent execution seconds', '{:,.1f} s', 'total'),+ ('llm_seconds', 'LLM seconds', '{:,.1f} s', 'total'),+ ('tool_seconds', 'Tool seconds', '{:,.1f} s', 'total'),+ ('llm_ms_per_token', 'LLM ms per token', '{:,.2f} ms', 'value'),+ ] %}+ {% macro t3_timing_source_text(sources) %}{% for source in sources %}{{ ' and ' if not loop.first }}{{ 'native ATIF timing' if source == 'atif' else ('inferred from step timestamps' if source == 'step_timestamps' else source) }}{% endfor %}{% if not sources %}none{% endif %}{% endmacro %}<div class="table-scroll"><table class="summary-table"><thead><tr><th>Agent</th><th>Measurement</th><th>With skill total</th><th>Baseline total</th><th>Delta</th><th>Measured trials (skill / baseline)</th></tr></thead><tbody>{% for name, agent in t3_agents.items() %}{% if agent.resources is defined %}- {% for field, label in [('tokens', 'Prompt + completion tokens (cache included)'), ('agent_seconds', 'Agent execution seconds')] %}+ {% for field, label, unit_fmt, key in t3_resource_rows %}+ {% if agent.resources[field] is defined %}{% set measured = agent.resources[field] %}+ {% set with_value = measured.with_skill[key] %}+ {% set baseline_value = measured.baseline[key] %}<tr><td>{{ name }}</td><td>{{ label }}</td>- {% set unit_fmt = '{:,.1f} s' if field == 'agent_seconds' else '{:,.0f}' %}- <td>{{ unit_fmt.format(measured.with_skill.total) if measured.with_skill.total is not none else 'N/A' }}</td>- <td>{{ unit_fmt.format(measured.baseline.total) if measured.baseline.total is not none else 'N/A' }}</td>- <td>{% if measured.delta is not none %}{{ ('+' if measured.delta >= 0 else '') ~ unit_fmt.format(measured.delta) }}{% if measured.baseline.total %} ({{ '%+.0f' | format(measured.delta / measured.baseline.total * 100) }}%){% endif %}{% else %}N/A{% endif %}</td>+ <td>{{ unit_fmt.format(with_value) if with_value is not none else 'N/A' }}</td>+ <td>{{ unit_fmt.format(baseline_value) if baseline_value is not none else 'N/A' }}</td>+ <td>{% if measured.delta is not none %}{{ ('+' if measured.delta >= 0 else '') ~ unit_fmt.format(measured.delta) }}{% if baseline_value %} ({{ '%+.0f' | format(measured.delta / baseline_value * 100) }}%){% endif %}{% else %}N/A{% endif %}</td><td>{{ measured.with_skill.measured_trials }}/{{ measured.with_skill.trials }} / {{ measured.baseline.measured_trials }}/{{ measured.baseline.trials }}</td></tr>+ {% endif %}{% endfor %}{% endif %}{% endfor %}</tbody></table></div>+ {% for name, agent in t3_agents.items() %}+ {% set t3_timing_sources = agent.resources.timing_sources if agent.resources is defined and agent.resources.timing_sources is mapping else {} %}+ {% if t3_timing_sources.with_skill or t3_timing_sources.baseline %}+ <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 %}</div></details>{% endif %}diff --git a/src/skillevaluator/tier3/harbor/report_data.py b/src/skillevaluator/tier3/harbor/report_data.pyindex cdb16eb9..2ff6948e 100644--- a/src/skillevaluator/tier3/harbor/report_data.py+++ b/src/skillevaluator/tier3/harbor/report_data.py@@ -34,6 +34,7 @@ from skillevaluator.tier3.harbor.metrics import (score_value,)from skillevaluator.tier3.harbor.resource_usage import agent_execution_seconds+from skillevaluator.tier3.harbor.trajectory_timing import trajectory_timinglogger = logging.getLogger(__name__)@@ -859,6 +860,9 @@ def load_agent_data(),"cached_tokens": _trajectory_token_counter(final_metrics.get("total_cached_tokens")),}+ timing = trajectory_timing(trajectory)+ if timing is not None:+ reward["_traj"]["timing"] = timingtrial_list.append(reward)else:rewards_complete = expected_logical_trials == 0diff --git a/src/skillevaluator/tier3/harbor/resource_usage.py b/src/skillevaluator/tier3/harbor/resource_usage.pyindex 2db05cd3..be0b8e47 100644--- a/src/skillevaluator/tier3/harbor/resource_usage.py+++ b/src/skillevaluator/tier3/harbor/resource_usage.py@@ -10,6 +10,30 @@ from collections import Counterfrom datetime import datetimefrom typing import Any+from skillevaluator.tier3.harbor.trajectory_timing import TIMING_SOURCES++_MAX_SAFE_INTEGER = (1 << 53) - 1+_TIMING_FIELDS = ("llm_seconds", "tool_seconds")+++def _is_measurement(value: Any) -> bool:+ """A JSON-safe, finite, non-negative counter; bools, strings and NaN are not measurements."""+ return type(value) in (int, float) and 0 <= value <= _MAX_SAFE_INTEGER and math.isfinite(value)+++def normalized_trial_timing(raw: Any) -> dict[str, Any] | None:+ """Validate one trial's ``timing``; invalid or untagged values stay unavailable, not zero."""+ if not isinstance(raw, dict) or raw.get("source") not in TIMING_SOURCES:+ return None+ timing: dict[str, Any] = {}+ for field in _TIMING_FIELDS:+ value = raw.get(field)+ timing[field] = float(value) if _is_measurement(value) else None+ if all(timing[field] is None for field in _TIMING_FIELDS):+ return None+ timing["source"] = raw["source"]+ return timing+def agent_execution_seconds(result: dict[str, Any]) -> float | None:"""Read Harbor's measured agent phase; never substitute total job/verifier time."""@@ -43,25 +67,37 @@ def resource_comparison(paired = with_complete and baseline_complete and identity(with_trials) is not Nonepaired = paired and identity(with_trials) == identity(baseline_trials)+ def trial_value(trial: dict[str, Any], field: str) -> Any:+ if field in _TIMING_FIELDS:+ timing = normalized_trial_timing(trial.get("timing"))+ return timing[field] if timing is not None else None+ value = trial.get("agent_seconds")+ if field == "tokens":+ tokens = trial.get("tokens", {})+ if not isinstance(tokens, dict):+ tokens = {}+ prompt, completion = tokens.get("prompt"), tokens.get("completion")+ value = (+ prompt + completion+ if type(prompt) is int and type(completion) is int and min(prompt, completion) >= 0+ else None+ )+ return value+def measure(trials: list[dict[str, Any]], field: str, complete: bool) -> dict[str, Any]:values = []for trial in trials:- value = trial.get("agent_seconds")- if field == "tokens":- tokens = trial.get("tokens", {})- if not isinstance(tokens, dict):- tokens = {}- prompt, completion = tokens.get("prompt"), tokens.get("completion")- value = (- prompt + completion- if type(prompt) is int and type(completion) is int and min(prompt, completion) >= 0- else None- )- if type(value) in (int, float) and 0 <= value <= (1 << 53) - 1 and math.isfinite(value):+ value = trial_value(trial, field)+ if _is_measurement(value):values.append(value)- total = sum(values)+ # Millisecond precision keeps float noise out of the timing totals.+ total = round(math.fsum(values), 3) if field in _TIMING_FIELDS else sum(values)available = (- complete and bool(trials) and len(values) == len(trials) and math.isfinite(total) and total <= (1 << 53) - 1+ complete+ and bool(trials)+ and len(values) == len(trials)+ and math.isfinite(total)+ and total <= _MAX_SAFE_INTEGER)return {"status": "complete" if available else "unavailable",@@ -71,16 +107,61 @@ def resource_comparison(}measurements = {}- for field in ("tokens", "agent_seconds"):+ for field in ("tokens", "agent_seconds", *_TIMING_FIELDS):with_measure = measure(with_trials, field, with_complete)baseline_measure = measure(baseline_trials, field, baseline_complete)delta = Noneif paired and with_measure["total"] is not None and baseline_measure["total"] is not None:delta = with_measure["total"] - baseline_measure["total"]+ if field in _TIMING_FIELDS:+ delta = round(delta, 3)measurements[field] = {"with_skill": with_measure, "baseline": baseline_measure, "delta": delta}++ def per_token(trials: list[dict[str, Any]], arm: str) -> dict[str, Any]:+ """LLM milliseconds per prompt + completion token, from the arm's complete totals only."""+ llm_total = measurements["llm_seconds"][arm]["total"]+ token_total = measurements["tokens"][arm]["total"]+ value = round(llm_total * 1000 / token_total, 3) if llm_total is not None and token_total else None+ measured = sum(+ 1+ for trial in trials+ if _is_measurement(trial_value(trial, "llm_seconds")) and _is_measurement(trial_value(trial, "tokens"))+ )+ return {+ "status": "complete" if value is not None else "unavailable",+ "measured_trials": measured,+ "trials": len(trials),+ "value": value,+ }++ with_per_token = per_token(with_trials, "with_skill")+ baseline_per_token = per_token(baseline_trials, "baseline")+ per_token_delta = None+ if paired and with_per_token["value"] is not None and baseline_per_token["value"] is not None:+ per_token_delta = round(with_per_token["value"] - baseline_per_token["value"], 3)+ measurements["llm_ms_per_token"] = {+ "with_skill": with_per_token,+ "baseline": baseline_per_token,+ "delta": per_token_delta,+ }++ def sources(trials: list[dict[str, Any]]) -> list[str]:+ found = {timing["source"] for trial in trials if (timing := normalized_trial_timing(trial.get("timing")))}+ return sorted(found)++ timing_sources = {"with_skill": sources(with_trials), "baseline": sources(baseline_trials)}+ mixed = len({*timing_sources["with_skill"], *timing_sources["baseline"]}) > 1return {"scope": "observed agent-only trial totals; prompt + completion tokens (cache included), excluding judge/setup time","pairing": "matching case counts" if paired else "unavailable","delta_definition": "with skill minus baseline; negative means less observed resource use",+ "timing_definition": (+ "llm_seconds and tool_seconds split each trial's ATIF trajectory time; source atif reads native "+ "timing extras, source step_timestamps infers it from step timestamps and the wall time of Codex "+ "shell and apply_patch calls (LLM time then includes harness and queue time); llm_ms_per_token is "+ "1000 * llm_seconds / (prompt + completion tokens)"+ ),+ "timing_sources": timing_sources,+ "caveats": ["mixed_timing_sources"] if mixed else [],**measurements,}diff --git a/src/skillevaluator/tier3/harbor/trajectory_timing.py b/src/skillevaluator/tier3/harbor/trajectory_timing.pynew file mode 100644index 00000000..007641d4--- /dev/null+++ b/src/skillevaluator/tier3/harbor/trajectory_timing.py@@ -0,0 +1,382 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Split one Harbor ATIF trajectory's time into LLM seconds and tool seconds.++Two sources are used, never mixed within one trajectory:++* ``atif``: native timing extras. ``step.extra.llm_duration_ms`` gives LLM+ time only when every agent step carries it. Tool time is the union of each+ call's ``tool_calls[].extra`` ``started_at``/``ended_at`` interval, with+ ``duration_ms`` for calls without an interval, and only when every call is+ timed. When any native extra is present, nothing is inferred.+* ``step_timestamps``: inferred from the ISO ``timestamp`` on every step plus+ the ``Wall time: N seconds`` line that Codex writes in the header of the+ output of its shell tools (``exec_command``, ``write_stdin``, ``wait``,+ ``shell_command`` ...) and ``apply_patch``, or the ``duration_seconds`` that+ Harbor keeps in the structured tool metadata of those calls. Each gap+ between consecutive steps is counted once. Tool time is the wall time of the+ step's calls (parallel calls count their longest); the rest of the gap,+ which also includes harness and queue time, is LLM time. A trajectory with+ any other tool call (``update_plan``, web search, MCP tools ...), or a call+ whose output has no such header, has no measured duration for that call, so+ nothing is inferred.++Each step of a merged multi-step trajectory is timed on its own, so the gap+between Harbor steps (verifier and setup time) is never counted. Steps marked+``is_copied_context`` repeat earlier work, so each Harbor step's copied prefix+is dropped before timing; a copied step after new work, or a Harbor step with+only copied steps, leaves the trajectory unmeasured. Copied timestamps do not+show when the first new response started, so inference also leaves a Harbor+step unmeasured when its new work starts with an agent step. Missing,+malformed, unordered or inconsistent evidence makes a component ``None``; it+is never reported as zero. A trajectory with no tool calls measures zero tool+seconds.+"""++from __future__ import annotations++import math+import re+from datetime import datetime+from typing import Any, NamedTuple++TIMING_SOURCES = ("atif", "step_timestamps")++# Codex built-in tools whose output starts with Codex's own status header. The+# name may carry a namespace prefix such as ``functions.exec_command``.+_CODEX_TIMED_TOOL_NAMES = frozenset(+ {"exec_command", "write_stdin", "wait", "wait_command", "shell", "shell_command", "apply_patch"}+)+_WALL_TIME_RE = re.compile(+ r"^Wall time:[ \t]*([0-9]+(?:\.[0-9]+)?)[ \t]*seconds[ \t]*\r?$",+ re.IGNORECASE | re.MULTILINE,+)+# Everything after the first ``Output:`` line is the command's own output.+_OUTPUT_LINE_RE = re.compile(r"^Output:", re.MULTILINE)+_MAX_TOOL_CALL_SECONDS = 86400.0+_NATIVE_TOOL_KEYS = ("started_at", "ended_at", "duration_ms")+++def trajectory_timing(trajectory: Any) -> dict[str, Any] | None:+ """Return ``{"llm_seconds", "tool_seconds", "source"}`` or ``None``."""+ if not isinstance(trajectory, dict):+ return None+ steps = trajectory.get("steps")+ if not isinstance(steps, list) or not steps or not all(isinstance(step, dict) for step in steps):+ return None+ segments = _new_work_segments(steps)+ if segments is None:+ return None+ new_steps = [step for segment in segments for step in segment.steps]+ if _has_native_timing(new_steps):+ measured = _native_timing_ms(new_steps)+ source = "atif"+ else:+ measured = _inferred_timing_ms(segments)+ source = "step_timestamps"+ if measured is None:+ return None+ llm_ms, tool_ms = measured+ llm_seconds = _seconds(llm_ms)+ tool_seconds = _seconds(tool_ms)+ if llm_seconds is None and tool_seconds is None:+ return None+ return {"llm_seconds": llm_seconds, "tool_seconds": tool_seconds, "source": source}+++def _seconds(milliseconds: float | None) -> float | None:+ if milliseconds is None or not math.isfinite(milliseconds) or milliseconds < 0:+ return None+ return round(milliseconds / 1000.0, 3)+++def _tool_calls(step: dict[str, Any]) -> list[Any] | None:+ """Return the step's tool calls (``[]`` when it has none), or ``None`` if malformed."""+ calls = step.get("tool_calls")+ if calls is None:+ return []+ return calls if isinstance(calls, list) else None+++def _has_native_timing(steps: list[dict[str, Any]]) -> bool:+ for step in steps:+ extra = step.get("extra")+ if isinstance(extra, dict) and "llm_duration_ms" in extra:+ return True+ for call in _tool_calls(step) or []:+ call_extra = call.get("extra") if isinstance(call, dict) else None+ if isinstance(call_extra, dict) and any(key in call_extra for key in _NATIVE_TOOL_KEYS):+ return True+ return False+++def _non_negative_ms(value: Any) -> float | None:+ if isinstance(value, bool) or not isinstance(value, int | float):+ return None+ try:+ number = float(value)+ except OverflowError:+ return None+ return number if math.isfinite(number) and number >= 0 else None+++def _timestamp_ms(value: Any) -> float | None:+ """Parse an ISO timestamp with a UTC offset; naive local times are rejected."""+ if not isinstance(value, str):+ return None+ try:+ parsed = datetime.fromisoformat(value)+ if parsed.utcoffset() is None:+ return None+ milliseconds = parsed.timestamp() * 1000.0+ except (ValueError, OverflowError, OSError):+ return None+ return milliseconds if math.isfinite(milliseconds) else None+++def _interval_ms(extra: Any) -> tuple[float, float] | None:+ if not isinstance(extra, dict):+ return None+ start = _timestamp_ms(extra.get("started_at"))+ end = _timestamp_ms(extra.get("ended_at"))+ if start is None or end is None or end < start:+ return None+ return start, end+++def _union_ms(intervals: list[tuple[float, float]]) -> float:+ """Wall-clock length of the union of ``[start, end]`` intervals."""+ total = 0.0+ current: tuple[float, float] | None = None+ for start, end in sorted(intervals):+ if current is None or start > current[1]:+ if current is not None:+ total += current[1] - current[0]+ current = (start, end)+ else:+ current = (current[0], max(current[1], end))+ if current is not None:+ total += current[1] - current[0]+ return total+++def _native_timing_ms(steps: list[dict[str, Any]]) -> tuple[float | None, float | None] | None:+ agent_steps = [step for step in steps if step.get("source") == "agent"]+ llm_values = [+ _non_negative_ms(extra.get("llm_duration_ms")) if isinstance((extra := step.get("extra")), dict) else None+ for step in agent_steps+ ]+ llm_ms = (+ math.fsum(value for value in llm_values if value is not None)+ if agent_steps and all(value is not None for value in llm_values)+ else None+ )++ calls: list[Any] = []+ for step in steps:+ step_calls = _tool_calls(step)+ if step_calls is None:+ return None+ calls.extend(step_calls)+ intervals: list[tuple[float, float]] = []+ durations: list[float] = []+ tool_ms: float | None = 0.0 if llm_ms is not None else None+ for call in calls:+ extra = call.get("extra") if isinstance(call, dict) else None+ interval = _interval_ms(extra)+ if interval is not None:+ intervals.append(interval)+ continue+ duration = _non_negative_ms(extra.get("duration_ms")) if isinstance(extra, dict) else None+ if duration is None:+ tool_ms = None+ break+ durations.append(duration)+ else:+ if calls:+ tool_ms = _union_ms(intervals) + math.fsum(durations)+ if llm_ms is None and tool_ms is None:+ return None+ return llm_ms, tool_ms+++def _wall_time_seconds(value: float) -> float | None:+ return value if math.isfinite(value) and 0 <= value <= _MAX_TOOL_CALL_SECONDS else None+++def _header_wall_time_seconds(content: Any) -> float | None:+ """Read ``Wall time`` from the status header, never from the command output."""+ if not isinstance(content, str):+ return None+ output_line = _OUTPUT_LINE_RE.search(content)+ if output_line is None:+ return None+ matches = _WALL_TIME_RE.findall(content[: output_line.start()])+ if len(matches) != 1:+ return None+ return _wall_time_seconds(float(matches[0]))+++def _metadata_duration_seconds(step: dict[str, Any], call_id: Any, *, single_call: bool) -> float | None:+ """Read ``duration_seconds`` from the structured tool metadata Harbor keeps for Codex."""+ extra = step.get("extra")+ if not isinstance(extra, dict):+ return None+ metadata: Any = None+ details = extra.get("tool_call_details")+ if isinstance(call_id, str) and call_id and isinstance(details, dict):+ detail = details.get(call_id)+ metadata = detail.get("metadata") if isinstance(detail, dict) else None+ if metadata is None and single_call:+ metadata = extra.get("tool_metadata")+ if not isinstance(metadata, dict):+ return None+ value = _non_negative_ms(metadata.get("duration_seconds"))+ return _wall_time_seconds(value) if value is not None else None+++def _tool_call_seconds(step: dict[str, Any]) -> list[float] | None:+ """Measured wall time for each tool call on the step, or ``None`` if any call is unmeasured."""+ calls = _tool_calls(step)+ if calls is None:+ return None+ if not calls:+ return []+ observation = step.get("observation")+ results = observation.get("results") if isinstance(observation, dict) else None+ if not isinstance(results, list):+ results = []++ by_call_id: dict[str, float] = {}+ unidentified: list[float] = []+ for result in results:+ if not isinstance(result, dict):+ continue+ seconds = _header_wall_time_seconds(result.get("content"))+ if seconds is None:+ continue+ call_id = result.get("source_call_id")+ if isinstance(call_id, str) and call_id.strip():+ if call_id in by_call_id:+ return None+ by_call_id[call_id] = seconds+ else:+ unidentified.append(seconds)++ durations: list[float] = []+ seen_ids: set[str] = set()+ for call in calls:+ if not isinstance(call, dict):+ return None+ name = call.get("function_name")+ if not isinstance(name, str) or name.rsplit(".", 1)[-1] not in _CODEX_TIMED_TOOL_NAMES:+ return None+ call_id = call.get("tool_call_id") or call.get("id")+ if isinstance(call_id, str) and call_id:+ if call_id in seen_ids:+ return None+ seen_ids.add(call_id)+ if call_id in by_call_id:+ durations.append(by_call_id[call_id])+ continue+ seconds = _metadata_duration_seconds(step, call_id, single_call=len(calls) == 1)+ if seconds is None and len(calls) == 1 and len(results) == 1 and len(unidentified) == 1:+ seconds = unidentified[0]+ if seconds is None:+ return None+ durations.append(seconds)+ return durations+++def _segment_timing_ms(steps: list[dict[str, Any]]) -> tuple[float, float] | None:+ """Attribute each timestamp gap of one Harbor step's trajectory once."""+ stamped: list[tuple[dict[str, Any], float]] = []+ for step in steps:+ timestamp = _timestamp_ms(step.get("timestamp"))+ if timestamp is None or (stamped and timestamp < stamped[-1][1]):+ return None+ stamped.append((step, timestamp))+ if len(stamped) < 2:+ return None++ llm_ms = 0.0+ tool_ms = 0.0+ saw_agent = False+ previous_had_tools = False+ for index, (step, timestamp) in enumerate(stamped):+ if step.get("source") != "agent":+ previous_had_tools = False+ continue+ saw_agent = True+ durations = _tool_call_seconds(step)+ if durations is None:+ return None+ # A preceding tool step already accounted for the gap that ends here.+ if index and not previous_had_tools:+ llm_ms += timestamp - stamped[index - 1][1]+ has_tools = bool(durations)+ if has_tools:+ if index + 1 == len(stamped):+ return None+ gap_ms = stamped[index + 1][1] - timestamp+ step_tool_ms = max(durations) * 1000.0+ if step_tool_ms > gap_ms:+ return None+ llm_ms += gap_ms - step_tool_ms+ tool_ms += step_tool_ms+ previous_had_tools = has_tools+ if not saw_agent:+ return None+ return llm_ms, tool_ms+++def _harbor_step_segments(steps: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:+ """Split a merged multi-step trajectory at each change of ``extra.harbor_step_name``."""+ segments: list[list[dict[str, Any]]] = []+ current: Any = None+ for step in steps:+ extra = step.get("extra")+ name = extra.get("harbor_step_name") if isinstance(extra, dict) else None+ if not segments or name != current:+ segments.append([])+ current = name+ segments[-1].append(step)+ return segments+++class _NewWorkSegment(NamedTuple):+ """One Harbor step's steps after its ``is_copied_context`` prefix."""++ steps: list[dict[str, Any]]+ after_copied_context: bool+++def _new_work_segments(steps: list[dict[str, Any]]) -> list[_NewWorkSegment] | None:+ """Drop each Harbor step's copied prefix, or ``None`` if copied steps are not a prefix."""+ segments: list[_NewWorkSegment] = []+ for segment in _harbor_step_segments(steps):+ prefix_length = 0+ while prefix_length < len(segment) and segment[prefix_length].get("is_copied_context") is True:+ prefix_length += 1+ segment_new_steps = segment[prefix_length:]+ if not segment_new_steps or any(step.get("is_copied_context") is True for step in segment_new_steps):+ return None+ segments.append(_NewWorkSegment(segment_new_steps, after_copied_context=prefix_length > 0))+ return segments+++def _inferred_timing_ms(segments: list[_NewWorkSegment]) -> tuple[float, float] | None:+ llm_ms = 0.0+ tool_ms = 0.0+ for segment in segments:+ # A copied timestamp does not show when the first new response started, so+ # timing from that response would silently drop its model time.+ if segment.after_copied_context and segment.steps[0].get("source") == "agent":+ return None+ measured = _segment_timing_ms(segment.steps)+ if measured is None:+ return None+ llm_ms += measured[0]+ tool_ms += measured[1]+ return llm_ms, tool_msdiff --git a/tests/reporting/test_resource_comparison.py b/tests/reporting/test_resource_comparison.pyindex d08fe012..3aef8e70 100644--- a/tests/reporting/test_resource_comparison.py+++ b/tests/reporting/test_resource_comparison.py@@ -10,7 +10,7 @@ from skillevaluator.reporting import HTMLReporter, JSONReporterfrom skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS-def write_arm(run, arm, tokens, seconds):+def write_arm(run, arm, tokens, seconds, steps=None):directory = run / "opencode" / armdirectory.mkdir(parents=True)scores = dict.fromkeys(DEFAULT_METRICS, 1.0)@@ -32,7 +32,7 @@ def write_arm(run, arm, tokens, seconds):(trial / "trajectory.json").write_text(json.dumps({- "steps": [{}],+ "steps": steps if steps is not None else [{}],"final_metrics": {"total_prompt_tokens": tokens,"total_completion_tokens": 2,@@ -68,3 +68,107 @@ def test_resources_flow_from_harbor_artifacts_to_json_and_html(tmp_path, missingassert "N/A" in html if missing_tokens else "-10 (-" in htmloutput = json.loads(JSONReporter().render_all([result]))assert "resources" in json.dumps(output)+++def codex_steps(tool, llm_after, name="exec_command"):+ """A user prompt, a model call that runs one tool 2 s later, and a final answer."""+ final = 2 + tool + llm_after+ return [+ {"step_id": 1, "source": "user", "message": "go", "timestamp": "2026-10-11T00:00:00.000Z"},+ {+ "step_id": 2,+ "source": "agent",+ "message": "",+ "timestamp": "2026-10-11T00:00:02.000Z",+ "tool_calls": [{"tool_call_id": "call_1", "function_name": name, "arguments": {"cmd": "ls"}}],+ "observation": {+ "results": [+ {+ "source_call_id": "call_1",+ "content": f"Chunk ID: 0a1b2c\nWall time: {tool:.4f} seconds\n"+ "Process exited with code 0\nOutput:\nok\n",+ }+ ]+ },+ },+ {"step_id": 3, "source": "agent", "message": "done", "timestamp": f"2026-10-11T00:00:{final:06.3f}Z"},+ ]+++def native_steps(llm_ms, tool_ms):+ return [+ {"step_id": 1, "source": "user", "message": "go"},+ {+ "step_id": 2,+ "source": "agent",+ "message": "done",+ "extra": {"llm_duration_ms": llm_ms},+ "tool_calls": [{"tool_call_id": "call_1", "function_name": "Bash", "extra": {"duration_ms": tool_ms}}],+ },+ ]+++def render(tmp_path, run):+ result = agent_eval_result_from_directory(tmp_path, run, use_llm_judge=False)+ resources = result.metadata["agent_eval"]["agents"]["opencode"]["resources"]+ html = HTMLReporter(target_path=str(tmp_path)).render_all([result])+ output = json.loads(JSONReporter().render_all([result]))+ return result, resources, html, output+++def test_llm_and_tool_seconds_flow_from_trajectories_to_json_and_html(tmp_path):+ run = tmp_path / "run"+ write_arm(run, "with-skill", 10, 3, steps=codex_steps(tool=1.5, llm_after=4.5))+ write_arm(run, "without-skill", 20, 5, steps=codex_steps(tool=2.5, llm_after=6.5))+ result, resources, html, output = render(tmp_path, run)+ trials = result.metadata["agent_eval"]["agents"]["opencode"]["trials"]+ assert trials[0]["timing"] == {"llm_seconds": 6.5, "tool_seconds": 1.5, "source": "step_timestamps"}+ assert resources["llm_seconds"]["with_skill"]["total"] == 6.5+ assert resources["llm_seconds"]["baseline"]["total"] == 8.5+ assert resources["llm_seconds"]["delta"] == -2.0+ assert resources["tool_seconds"]["delta"] == -1.0+ # write_arm records prompt + 2 completion tokens: 12 with the skill, 22 without.+ assert resources["llm_ms_per_token"]["with_skill"]["value"] == round(6500 / 12, 3)+ assert resources["llm_ms_per_token"]["baseline"]["value"] == round(8500 / 22, 3)+ assert resources["timing_sources"] == {"with_skill": ["step_timestamps"], "baseline": ["step_timestamps"]}+ assert resources["caveats"] == []+ for label in ("LLM seconds", "Tool seconds", "LLM ms per token"):+ assert label in html+ assert "-2.0 s (-24%)" in html+ assert "-1.0 s (-40%)" in html+ assert "541.67 ms" in html+ assert (+ "opencode timing source: with skill inferred from step timestamps; baseline inferred from step timestamps."+ in html+ )+ assert "not like-for-like" not in html+ assert '"llm_seconds"' in json.dumps(output)+++def test_unmeasured_arm_timing_is_na_without_a_delta(tmp_path):+ run = tmp_path / "run"+ write_arm(run, "with-skill", 10, 3, steps=codex_steps(tool=1.5, llm_after=4.5))+ write_arm(run, "without-skill", 20, 5, steps=codex_steps(tool=2.5, llm_after=6.5, name="update_plan"))+ _result, resources, html, _output = render(tmp_path, run)+ assert resources["llm_seconds"]["baseline"] == {+ "status": "unavailable",+ "measured_trials": 0,+ "trials": 1,+ "total": None,+ }+ assert resources["llm_seconds"]["delta"] is None+ assert resources["agent_seconds"]["delta"] == -2+ assert "<td>opencode</td><td>LLM seconds</td>" in html+ assert "1/1 / 0/1" in html+ assert "baseline none." in html+++def test_mixed_timing_sources_are_flagged_in_html(tmp_path):+ run = tmp_path / "run"+ write_arm(run, "with-skill", 10, 3, steps=codex_steps(tool=1.5, llm_after=4.5))+ write_arm(run, "without-skill", 20, 5, steps=native_steps(llm_ms=7000, tool_ms=2000))+ _result, resources, html, _output = render(tmp_path, run)+ assert resources["llm_seconds"]["delta"] == -0.5+ assert resources["caveats"] == ["mixed_timing_sources"]+ assert "with skill inferred from step timestamps; baseline native ATIF timing." in html+ assert "so LLM and tool seconds are not like-for-like" in htmldiff --git a/tests/tier3/fixtures/harbor_0_24_codex_trajectory.json b/tests/tier3/fixtures/harbor_0_24_codex_trajectory.jsonnew file mode 100644index 00000000..664fdbe4--- /dev/null+++ b/tests/tier3/fixtures/harbor_0_24_codex_trajectory.json@@ -0,0 +1,269 @@+{+ "schema_version": "ATIF-v1.7",+ "session_id": "00000000-0000-4000-8000-000000000001",+ "agent": {+ "name": "codex",+ "version": "0.0.0-test",+ "model_name": "gpt-5-mini",+ "extra": {+ "originator": "codex_exec",+ "cwd": "/workspace"+ }+ },+ "steps": [+ {+ "step_id": 1,+ "timestamp": "2026-05-01T12:00:00.020Z",+ "source": "system",+ "message": "Follow the workspace rules."+ },+ {+ "step_id": 2,+ "timestamp": "2026-05-01T12:00:00.030Z",+ "source": "user",+ "message": "<environment_context>cwd=/workspace</environment_context>"+ },+ {+ "step_id": 3,+ "timestamp": "2026-05-01T12:00:00.040Z",+ "source": "user",+ "message": "Summarize README.md."+ },+ {+ "step_id": 4,+ "timestamp": "2026-05-01T12:00:03.100Z",+ "source": "agent",+ "model_name": "gpt-5-mini",+ "message": "I'll read the file.",+ "reasoning_content": "Read the file first.",+ "tool_calls": [+ {+ "tool_call_id": "call_1",+ "function_name": "exec_command",+ "arguments": {+ "cmd": "cat README.md"+ }+ }+ ],+ "observation": {+ "results": [+ {+ "source_call_id": "call_1",+ "content": "Chunk ID: a1b2c3\nWall time: 1.4000 seconds\nProcess exited with code 0\nOriginal token count: 3\nOutput:\n# Demo\nWall time: 999 seconds\n"+ }+ ]+ },+ "metrics": {+ "prompt_tokens": 400,+ "completion_tokens": 40,+ "cost_usd": 0.00017999999999999998,+ "extra": {+ "reasoning_output_tokens": null,+ "total_tokens": 440+ }+ },+ "llm_call_count": 1,+ "extra": {+ "api_call_id": "api_call_1",+ "codex_turn_id": "turn-1",+ "tool_call_details": {+ "call_1": {+ "raw_arguments": "{\"cmd\": \"cat README.md\"}",+ "item_type": "function_call"+ }+ }+ }+ },+ {+ "step_id": 5,+ "timestamp": "2026-05-01T12:00:06.000Z",+ "source": "agent",+ "model_name": "gpt-5-mini",+ "message": "",+ "tool_calls": [+ {+ "tool_call_id": "call_2",+ "function_name": "exec_command",+ "arguments": {+ "cmd": "wc -l README.md"+ }+ },+ {+ "tool_call_id": "call_3",+ "function_name": "exec_command",+ "arguments": {+ "cmd": "ls"+ }+ }+ ],+ "observation": {+ "results": [+ {+ "source_call_id": "call_2",+ "content": "Chunk ID: d4e5f6\nWall time: 0.7000 seconds\nProcess exited with code 0\nOriginal token count: 3\nOutput:\n12 README.md\n"+ },+ {+ "source_call_id": "call_3",+ "content": "Chunk ID: 0a1b2c\nWall time: 1.1000 seconds\nProcess exited with code 0\nOriginal token count: 3\nOutput:\nREADME.md\n"+ }+ ]+ },+ "metrics": {+ "prompt_tokens": 400,+ "completion_tokens": 40,+ "cost_usd": 0.00017999999999999998,+ "extra": {+ "reasoning_output_tokens": null,+ "total_tokens": 440+ }+ },+ "llm_call_count": 1,+ "extra": {+ "api_call_id": "api_call_2",+ "codex_turn_id": "turn-1",+ "tool_call_details": {+ "call_2": {+ "raw_arguments": "{\"cmd\": \"wc -l README.md\"}",+ "item_type": "function_call"+ },+ "call_3": {+ "raw_arguments": "{\"cmd\": \"ls\"}",+ "item_type": "function_call"+ }+ }+ }+ },+ {+ "step_id": 6,+ "timestamp": "2026-05-01T12:00:09.000Z",+ "source": "agent",+ "model_name": "gpt-5-mini",+ "message": "",+ "tool_calls": [+ {+ "tool_call_id": "call_4",+ "function_name": "shell",+ "arguments": {+ "command": [+ "bash",+ "-lc",+ "ls"+ ]+ }+ }+ ],+ "observation": {+ "results": [+ {+ "source_call_id": "call_4",+ "content": "README.md\n"+ }+ ]+ },+ "metrics": {+ "prompt_tokens": 400,+ "completion_tokens": 40,+ "cost_usd": 0.00017999999999999998,+ "extra": {+ "reasoning_output_tokens": null,+ "total_tokens": 440+ }+ },+ "llm_call_count": 1,+ "extra": {+ "api_call_id": "api_call_3",+ "codex_turn_id": "turn-1",+ "tool_call_details": {+ "call_4": {+ "metadata": {+ "exit_code": 0,+ "duration_seconds": 0.8+ },+ "raw_arguments": "{\"command\": [\"bash\", \"-lc\", \"ls\"]}",+ "item_type": "function_call"+ }+ }+ }+ },+ {+ "step_id": 7,+ "timestamp": "2026-05-01T12:00:12.000Z",+ "source": "agent",+ "model_name": "gpt-5-mini",+ "message": "",+ "tool_calls": [+ {+ "tool_call_id": "call_5",+ "function_name": "apply_patch",+ "arguments": {+ "input": "*** Begin Patch\n*** Update File: README.md\n@@\n-# Demo\n+# Demo project\n*** End Patch\n"+ }+ }+ ],+ "observation": {+ "results": [+ {+ "source_call_id": "call_5",+ "content": "Exit code: 0\nWall time: 0.1 seconds\nOutput:\nSuccess. Updated the following files:\nM README.md\n"+ }+ ]+ },+ "metrics": {+ "prompt_tokens": 400,+ "completion_tokens": 40,+ "cost_usd": 0.00017999999999999998,+ "extra": {+ "reasoning_output_tokens": null,+ "total_tokens": 440+ }+ },+ "llm_call_count": 1,+ "extra": {+ "api_call_id": "api_call_4",+ "codex_turn_id": "turn-1",+ "tool_call_details": {+ "call_5": {+ "raw_arguments": "*** Begin Patch\n*** Update File: README.md\n@@\n-# Demo\n+# Demo project\n*** End Patch\n",+ "item_type": "custom_tool_call"+ }+ }+ }+ },+ {+ "step_id": 8,+ "timestamp": "2026-05-01T12:00:14.000Z",+ "source": "agent",+ "model_name": "gpt-5-mini",+ "message": "README.md describes a demo project.",+ "metrics": {+ "prompt_tokens": 400,+ "completion_tokens": 40,+ "cost_usd": 0.00017999999999999998,+ "extra": {+ "reasoning_output_tokens": null,+ "total_tokens": 440+ }+ },+ "llm_call_count": 1,+ "extra": {+ "api_call_id": "api_call_5",+ "codex_turn_id": "turn-1"+ }+ }+ ],+ "final_metrics": {+ "total_prompt_tokens": 2000,+ "total_completion_tokens": 200,+ "total_cost_usd": 0.0009,+ "total_steps": 8,+ "extra": {+ "reasoning_output_tokens": null,+ "total_tokens": 2200,+ "last_token_usage": {+ "input_tokens": 400,+ "output_tokens": 40,+ "total_tokens": 440+ }+ }+ }+}diff --git a/tests/tier3/test_resource_usage.py b/tests/tier3/test_resource_usage.pyindex 607c31b1..9f9699cf 100644--- a/tests/tier3/test_resource_usage.py+++ b/tests/tier3/test_resource_usage.py@@ -3,7 +3,11 @@import pytest-from skillevaluator.tier3.harbor.resource_usage import agent_execution_seconds, resource_comparison+from skillevaluator.tier3.harbor.resource_usage import (+ agent_execution_seconds,+ normalized_trial_timing,+ resource_comparison,+)def trial(entry="case", tokens=100, seconds=2):@@ -73,3 +77,161 @@ def test_agent_phase_excludes_build_and_verifier():)== 3)+++def timed(entry="case", llm=10.0, tool=2.0, source="step_timestamps", prompt=100, completion=20):+ item = trial(entry=entry, tokens=prompt)+ item["tokens"]["completion"] = completion+ item["timing"] = {"llm_seconds": llm, "tool_seconds": tool, "source": source}+ return item+++def test_normalized_trial_timing_rejects_empty_and_untagged_values():+ assert normalized_trial_timing({}) is None+ assert normalized_trial_timing({"llm_seconds": 1.0}) is None+ assert normalized_trial_timing({"llm_seconds": 1.0, "source": "reward"}) is None+ assert normalized_trial_timing({"llm_seconds": 1.0, "source": "atif"}) == {+ "llm_seconds": 1.0,+ "tool_seconds": None,+ "source": "atif",+ }+++def test_timing_pairs_arms_and_derives_ms_per_token():+ resources = resource_comparison(+ [timed(llm=10.0, tool=2.0, prompt=100, completion=20)],+ [timed(llm=20.0, tool=4.0, prompt=150, completion=30)],+ with_complete=True,+ baseline_complete=True,+ )+ assert resources["llm_seconds"]["with_skill"]["total"] == 10.0+ assert resources["llm_seconds"]["baseline"]["total"] == 20.0+ assert resources["llm_seconds"]["delta"] == -10.0+ assert resources["tool_seconds"]["delta"] == -2.0+ per_token = resources["llm_ms_per_token"]+ assert per_token["with_skill"]["value"] == round(10.0 * 1000 / 120, 3)+ assert per_token["baseline"]["value"] == round(20.0 * 1000 / 180, 3)+ assert per_token["delta"] == round(per_token["with_skill"]["value"] - per_token["baseline"]["value"], 3)+ assert per_token["with_skill"]["measured_trials"] == 1+ assert resources["timing_sources"] == {"with_skill": ["step_timestamps"], "baseline": ["step_timestamps"]}+ assert resources["caveats"] == []+++def test_timing_totals_are_rounded_to_milliseconds():+ resources = resource_comparison(+ [timed(entry="a", llm=0.1), timed(entry="b", llm=0.2)],+ [timed(entry="a", llm=0.1), timed(entry="b", llm=0.1)],+ with_complete=True,+ baseline_complete=True,+ )+ assert resources["llm_seconds"]["with_skill"]["total"] == 0.3+ assert resources["llm_seconds"]["delta"] == 0.1+++def test_tool_total_requires_every_trial():+ resources = resource_comparison(+ [timed(entry="a", llm=10.0, tool=2.0), timed(entry="b", llm=8.0, tool=None)],+ [timed(entry="a", llm=5.0, tool=1.0), timed(entry="b", llm=4.0, tool=1.0)],+ with_complete=True,+ baseline_complete=True,+ )+ assert resources["llm_seconds"]["with_skill"]["total"] == 18.0+ assert resources["llm_seconds"]["delta"] == 9.0+ assert resources["tool_seconds"]["with_skill"] == {+ "status": "unavailable",+ "measured_trials": 1,+ "trials": 2,+ "total": None,+ }+ assert resources["tool_seconds"]["delta"] is None+++def test_timing_comparison_does_not_require_token_counters():+ with_trial, baseline_trial = timed(llm=10.0), timed(llm=20.0)+ del with_trial["tokens"], baseline_trial["tokens"]+ resources = resource_comparison([with_trial], [baseline_trial], with_complete=True, baseline_complete=True)+ assert resources["llm_seconds"]["delta"] == -10.0+ assert resources["tokens"]["delta"] is None+ assert resources["llm_ms_per_token"]["with_skill"]["value"] is None+ assert resources["llm_ms_per_token"]["delta"] is None+++ "baseline,complete",+ [([], False), ([timed(entry="other")], True), ([timed(), timed()], True), ([timed()], False)],+)+def test_partial_or_mismatched_cases_do_not_get_timing_deltas(baseline, complete):+ resources = resource_comparison([timed()], baseline, with_complete=True, baseline_complete=complete)+ for field in ("llm_seconds", "tool_seconds", "llm_ms_per_token"):+ assert resources[field]["delta"] is None+ assert resources["llm_seconds"]["with_skill"]["total"] == 10.0+++def test_missing_timing_is_not_zero():+ untimed = trial()+ resources = resource_comparison([untimed], [timed()], with_complete=True, baseline_complete=True)+ assert resources["llm_seconds"]["with_skill"] == {+ "status": "unavailable",+ "measured_trials": 0,+ "trials": 1,+ "total": None,+ }+ assert resources["llm_seconds"]["delta"] is None+ assert resources["timing_sources"] == {"with_skill": [], "baseline": ["step_timestamps"]}+ assert resources["caveats"] == []+++def test_measured_zero_timing_is_preserved():+ resources = resource_comparison([timed(llm=0.0, tool=0.0)], [timed()], with_complete=True, baseline_complete=True)+ assert resources["llm_seconds"]["with_skill"]["total"] == 0.0+ assert resources["tool_seconds"]["delta"] == -2.0+ assert resources["llm_ms_per_token"]["with_skill"]["value"] == 0.0+++def test_mixed_timing_source_comparison_is_flagged():+ resources = resource_comparison(+ [timed(llm=12.0, source="step_timestamps")],+ [timed(llm=9.0, source="atif")],+ with_complete=True,+ baseline_complete=True,+ )+ assert resources["llm_seconds"]["delta"] == 3.0+ assert resources["timing_sources"] == {"with_skill": ["step_timestamps"], "baseline": ["atif"]}+ assert resources["caveats"] == ["mixed_timing_sources"]+++def test_mixed_sources_within_one_arm_are_flagged():+ resources = resource_comparison(+ [timed(entry="a", source="atif"), timed(entry="b", source="step_timestamps")],+ [timed(entry="a", source="atif"), timed(entry="b", source="atif")],+ with_complete=True,+ baseline_complete=True,+ )+ assert resources["timing_sources"]["with_skill"] == ["atif", "step_timestamps"]+ assert resources["caveats"] == ["mixed_timing_sources"]++[email protected]("source", ["atif", "step_timestamps"])+def test_consistent_timing_sources_are_not_flagged(source):+ resources = resource_comparison(+ [timed(llm=10.0, source=source)], [timed(llm=12.0, source=source)], with_complete=True, baseline_complete=True+ )+ assert resources["llm_seconds"]["delta"] == -2.0+ assert resources["timing_sources"] == {"with_skill": [source], "baseline": [source]}+ assert resources["caveats"] == []++[email protected]("value", [True, -1, "1.0", float("nan"), float("inf"), 10**1000, None])+def test_invalid_timing_stays_unavailable(value):+ assert normalized_trial_timing({"llm_seconds": value, "source": "atif"}) is None+ assert normalized_trial_timing({"llm_seconds": value, "tool_seconds": 1.0, "source": "atif"}) == {+ "llm_seconds": None,+ "tool_seconds": 1.0,+ "source": "atif",+ }+ item = timed()+ item["timing"]["llm_seconds"] = value+ resources = resource_comparison([item], [timed()], with_complete=True, baseline_complete=True)+ assert resources["llm_seconds"]["with_skill"]["total"] is None+ assert resources["llm_seconds"]["delta"] is None+ assert resources["tool_seconds"]["delta"] == 0.0diff --git a/tests/tier3/test_trajectory_timing.py b/tests/tier3/test_trajectory_timing.pynew file mode 100644index 00000000..411c0d3b--- /dev/null+++ b/tests/tier3/test_trajectory_timing.py@@ -0,0 +1,485 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""LLM and tool time from Harbor ATIF trajectories."""++from __future__ import annotations++import copy+import json+from pathlib import Path+from typing import Any++import pytest++from skillevaluator.tier3.harbor.collector import _merged_step_trajectory, _redacted_trajectory_data+from skillevaluator.tier3.harbor.trajectory_timing import trajectory_timing++FIXTURE = Path(__file__).parent / "fixtures" / "harbor_0_24_codex_trajectory.json"+++def _codex_fixture() -> dict[str, Any]:+ return json.loads(FIXTURE.read_text(encoding="utf-8"))+++def _inferred(llm: float, tool: float) -> dict[str, Any]:+ return {"llm_seconds": llm, "tool_seconds": tool, "source": "step_timestamps"}+++def _tool_step(second: int, durations: list[float]) -> dict[str, Any]:+ return {+ "source": "agent",+ "timestamp": f"2026-01-01T00:00:{second:02d}+00:00",+ "tool_calls": [{"tool_call_id": f"call-{i}", "function_name": "exec_command"} for i in range(len(durations))],+ "observation": {+ "results": [+ {"source_call_id": f"call-{i}", "content": f"Wall time: {duration} seconds\nOutput:\nok"}+ for i, duration in enumerate(durations)+ ]+ },+ }+++def _user(second: int = 0) -> dict[str, Any]:+ return {"source": "user", "timestamp": f"2026-01-01T00:00:{second:02d}+00:00"}+++def _agent(second: int) -> dict[str, Any]:+ return {"source": "agent", "timestamp": f"2026-01-01T00:00:{second:02d}+00:00"}+++def test_codex_like_trajectory_infers_llm_from_step_timestamps() -> None:+ trajectory = {+ "steps": [+ {"source": "user", "timestamp": "2026-10-21T22:09:21.777Z"},+ {+ "source": "agent",+ "timestamp": "2026-10-21T22:09:25.199Z",+ "tool_calls": [{"function_name": "exec_command", "arguments": {}}],+ "observation": {+ "results": [{"content": "Wall time: 1.5000 seconds\nProcess exited with code 0\nOutput:\nok\n"}]+ },+ },+ {"source": "agent", "timestamp": "2026-10-21T22:09:30.143Z"},+ ]+ }+ # 3.422 s before the tool step, then 4.944 s minus 1.5 s of tool time.+ assert trajectory_timing(trajectory) == _inferred(6.866, 1.5)++[email protected]("wall_time", ["9" * 400, "86400.5"])+def test_unbounded_wall_time_is_rejected(wall_time: str) -> None:+ trajectory = {+ "steps": [+ {"source": "user", "timestamp": "2026-10-21T22:09:21.777Z"},+ {+ "source": "agent",+ "timestamp": "2026-10-21T22:09:25.199Z",+ "tool_calls": [{"function_name": "exec_command"}],+ "observation": {"results": [{"content": f"Wall time: {wall_time} seconds\nOutput:\n"}]},+ },+ {"source": "agent", "timestamp": "2026-10-23T22:09:25.199Z"},+ ]+ }+ assert trajectory_timing(trajectory) is None+++def test_claude_like_trajectory_without_wall_time_is_not_inferred() -> None:+ trajectory = {+ "steps": [+ {"source": "user", "timestamp": "2026-10-20T17:33:50.301Z"},+ {+ "source": "agent",+ "timestamp": "2026-10-20T17:34:05.177Z",+ "tool_calls": [{"function_name": "Bash", "tool_call_id": "call-1", "arguments": {}}],+ "observation": {"results": [{"source_call_id": "call-1", "content": "done\n"}]},+ },+ {"source": "agent", "timestamp": "2026-10-20T17:34:09.000Z"},+ ]+ }+ assert trajectory_timing(trajectory) is None+++def test_wall_time_in_output_is_not_counted() -> None:+ trajectory = {+ "steps": [+ _user(),+ {+ "source": "agent",+ "timestamp": "2026-01-01T00:00:03+00:00",+ "tool_calls": [{"function_name": "exec_command", "arguments": {}}],+ "observation": {+ "results": [+ {+ "content": (+ "Wall time: 0.5000 seconds\nOutput:\n"+ + "\n".join(f"iteration {i}: Wall time: 30 seconds" for i in range(5))+ + "\nWall time: 9 seconds\n"+ )+ }+ ]+ },+ },+ _agent(10),+ ]+ }+ assert trajectory_timing(trajectory) == _inferred(9.5, 0.5)+++def test_partial_native_agent_llm_does_not_report_subtotal() -> None:+ trajectory = {+ "steps": [+ {+ "source": "agent",+ "extra": {"llm_duration_ms": 1200},+ "tool_calls": [{"extra": {"duration_ms": 500}}],+ },+ {"source": "agent"},+ ]+ }+ assert trajectory_timing(trajectory) == {"llm_seconds": None, "tool_seconds": 0.5, "source": "atif"}+++def test_partial_native_tool_timing_does_not_report_subtotal() -> None:+ trajectory = {+ "steps": [+ {+ "source": "agent",+ "extra": {"llm_duration_ms": 1200},+ "tool_calls": [{"extra": {"duration_ms": 500}}, {"function_name": "Bash"}],+ }+ ]+ }+ assert trajectory_timing(trajectory) == {"llm_seconds": 1.2, "tool_seconds": None, "source": "atif"}+++def test_native_atif_extras_win_over_inference() -> None:+ trajectory = {+ "steps": [+ _user(),+ {"source": "agent", "timestamp": "2026-01-01T00:00:10+00:00", "extra": {"llm_duration_ms": 500}},+ ]+ }+ # Inference alone would report 10 s of LLM time.+ assert trajectory_timing(trajectory) == {"llm_seconds": 0.5, "tool_seconds": 0.0, "source": "atif"}+++def test_native_parallel_tool_intervals_are_counted_once() -> None:+ trajectory = {+ "steps": [+ {+ "source": "agent",+ "extra": {"llm_duration_ms": 250},+ "tool_calls": [+ {"extra": {"started_at": "2026-01-01T00:00:00Z", "ended_at": "2026-01-01T00:00:02Z"}},+ {"extra": {"started_at": "2026-01-01T00:00:01Z", "ended_at": "2026-01-01T00:00:03Z"}},+ {"extra": {"duration_ms": 400}},+ ],+ }+ ]+ }+ assert trajectory_timing(trajectory) == {"llm_seconds": 0.25, "tool_seconds": 3.4, "source": "atif"}+++ "extra",+ [+ {"started_at": "2026-01-01T00:00:00", "ended_at": "2026-01-01T00:00:02"},+ {"started_at": "2026-01-01T00:00:02Z", "ended_at": "2026-01-01T00:00:01Z"},+ {"duration_ms": float("nan")},+ {"duration_ms": True},+ {"duration_ms": -1},+ ],+)+def test_invalid_native_tool_timing_is_not_a_measurement(extra: dict[str, Any]) -> None:+ trajectory = {"steps": [{"source": "agent", "tool_calls": [{"extra": extra}]}]}+ assert trajectory_timing(trajectory) is None+++def test_consecutive_tool_steps_count_each_gap_once() -> None:+ trajectory = {"steps": [_user(), _tool_step(3, [1.0]), _tool_step(7, [2.0]), _agent(12)]}+ assert trajectory_timing(trajectory) == _inferred(9.0, 3.0)+++def test_parallel_timestamp_tools_use_longest_wall_time() -> None:+ trajectory = {"steps": [_user(), _tool_step(3, [1.0, 2.0]), _agent(10)]}+ assert trajectory_timing(trajectory) == _inferred(8.0, 2.0)+++ "final_timestamp",+ [None, "2026-01-01T00:00:02+00:00", "2026-01-01T00:00:04+00:00", "2026-01-01T00:00:12", "not a time"],+)+def test_inconsistent_or_missing_timestamps_do_not_fabricate_latency(final_timestamp: str | None) -> None:+ # Missing, earlier, too short for the 2 s tool call, naive, or unparsable.+ trajectory = {+ "steps": [_user(), _tool_step(3, [2.0]), {"source": "agent", "timestamp": final_timestamp}],+ }+ assert trajectory_timing(trajectory) is None+++def test_trailing_tool_step_without_a_later_timestamp_is_rejected() -> None:+ assert trajectory_timing({"steps": [_user(), _tool_step(3, [1.0])]}) is None+++def test_measured_zero_tool_duration_is_preserved() -> None:+ trajectory = {"steps": [_user(), _tool_step(3, [0.0]), _agent(10)]}+ assert trajectory_timing(trajectory) == _inferred(10.0, 0.0)+++def test_trajectory_without_tool_calls_measures_zero_tool_time() -> None:+ assert trajectory_timing({"steps": [_user(), _agent(4), _agent(9)]}) == _inferred(9.0, 0.0)+++def test_non_codex_tool_output_cannot_supply_timing_metadata() -> None:+ tool_step = _tool_step(3, [1.0])+ tool_step["tool_calls"][0]["function_name"] = "Bash"+ trajectory = {"steps": [_user(), tool_step, _agent(10)]}+ assert trajectory_timing(trajectory) is None++[email protected]("name", ["web_search_call", "update_plan", "search_docs", "exec", "view_image"])+def test_unmeasured_codex_tools_leave_the_trial_unmeasured(name: str) -> None:+ # Even with a Wall time header, only Codex's own shell and apply_patch output is trusted.+ unmeasured = _tool_step(5, [0.2])+ unmeasured["tool_calls"][0]["function_name"] = name+ trajectory = {"steps": [_user(), _tool_step(3, [1.0]), unmeasured, _agent(10)]}+ assert trajectory_timing(trajectory) is None+++def test_apply_patch_header_counts_as_tool_time() -> None:+ patch = _tool_step(5, [0.0])+ patch["tool_calls"][0]["function_name"] = "apply_patch"+ patch["observation"]["results"][0]["content"] = (+ "Exit code: 0\nWall time: 0.2 seconds\nOutput:\nSuccess. Updated the following files:\nM a.py\n"+ )+ trajectory = {"steps": [_user(), _tool_step(3, [1.0]), patch, _agent(10)]}+ assert trajectory_timing(trajectory) == _inferred(8.8, 1.2)+ # Older Codex releases return the bare result, which has no duration.+ patch["observation"]["results"][0]["content"] = "Success. Updated the following files:\nM a.py\n"+ assert trajectory_timing(trajectory) is None+++def test_namespaced_codex_shell_tools_are_measured() -> None:+ step = _tool_step(3, [1.0, 0.5])+ step["tool_calls"][0]["function_name"] = "functions.shell_command"+ step["tool_calls"][1]["function_name"] = "wait_command"+ assert trajectory_timing({"steps": [_user(), step, _agent(10)]}) == _inferred(9.0, 1.0)+++def test_duplicate_call_ids_are_rejected() -> None:+ step = _tool_step(3, [1.0, 2.0])+ step["tool_calls"][1]["tool_call_id"] = "call-0"+ assert trajectory_timing({"steps": [_user(), step, _agent(10)]}) is None+ step = _tool_step(3, [1.0, 2.0])+ step["observation"]["results"][1]["source_call_id"] = "call-0"+ assert trajectory_timing({"steps": [_user(), step, _agent(10)]}) is None+++def test_header_with_two_wall_time_lines_is_rejected() -> None:+ step = _tool_step(3, [1.0])+ step["observation"]["results"][0]["content"] = "Wall time: 1 seconds\nWall time: 2 seconds\nOutput:\nok"+ assert trajectory_timing({"steps": [_user(), step, _agent(10)]}) is None+++def _write_stdin_trajectory(content: str) -> dict[str, Any]:+ write_stdin_step = _tool_step(7, [0.0])+ write_stdin_step["tool_calls"][0]["function_name"] = "write_stdin"+ write_stdin_step["observation"]["results"][0]["content"] = content+ return {"steps": [_user(), _tool_step(3, [1.0]), write_stdin_step, _agent(15)]}+++def test_codex_write_stdin_with_exec_header_counts_as_tool_time() -> None:+ trajectory = _write_stdin_trajectory(+ "Chunk ID: 638ae2\nWall time: 5.0000 seconds\nProcess exited with code 0\nOriginal token count: 4\nOutput:\nok\n"+ )+ assert trajectory_timing(trajectory) == _inferred(9.0, 6.0)+++ "content",+ [+ "write_stdin failed: stdin is closed for this session",+ "Chunk ID: 638ae2\nProcess exited with code 0\nOutput:\nWall time: 5.0000 seconds\n",+ "Chunk ID: 638ae2\nWall time: 5.0000 seconds\nProcess exited with code 0\n",+ ],+)+def test_codex_write_stdin_without_exec_header_is_rejected(content: str) -> None:+ assert trajectory_timing(_write_stdin_trajectory(content)) is None+++def test_single_call_tool_metadata_supplies_duration() -> None:+ step = _tool_step(3, [0.0])+ step["tool_calls"][0]["function_name"] = "shell"+ step["observation"]["results"][0]["content"] = "README.md\n"+ step["extra"] = {"tool_metadata": {"exit_code": 0, "duration_seconds": 1.25}}+ assert trajectory_timing({"steps": [_user(), step, _agent(10)]}) == _inferred(8.75, 1.25)+ step["extra"]["tool_metadata"]["duration_seconds"] = float("inf")+ assert trajectory_timing({"steps": [_user(), step, _agent(10)]}) is None+++def test_harbor_codex_trajectory_fixture_is_timed_after_redaction() -> None:+ trajectory = _codex_fixture()+ redacted = _redacted_trajectory_data(trajectory)+ assert redacted is not None+ # 3.06 s to the first model output, then each tool step's gap minus its tool time:+ # exec_command 1.4 s, parallel exec_command calls max(0.7, 1.1) s, shell metadata 0.8 s,+ # apply_patch 0.1 s.+ assert trajectory_timing(trajectory) == _inferred(10.56, 3.4)+ assert trajectory_timing(redacted) == trajectory_timing(trajectory)+++def test_harbor_codex_fixture_with_an_unmeasured_call_stays_unmeasured() -> None:+ trajectory = _codex_fixture()+ del trajectory["steps"][5]["extra"]["tool_call_details"]["call_4"]["metadata"]+ assert trajectory_timing(trajectory) is None+++def _write_multistep_trial(trial_root: Path, trajectories: list[tuple[str, dict[str, Any]]]) -> None:+ (trial_root / "result.json").write_text(+ json.dumps({"config": {"agent": {}}, "step_results": [{"step_name": name} for name, _ in trajectories]}),+ encoding="utf-8",+ )+ for name, trajectory in trajectories:+ agent_dir = trial_root / "steps" / name / "agent"+ agent_dir.mkdir(parents=True)+ (agent_dir / "trajectory.json").write_text(json.dumps(trajectory), encoding="utf-8")+++def test_merged_multistep_trajectory_excludes_the_gap_between_harbor_steps(tmp_path: Path) -> None:+ first = _codex_fixture()+ second = copy.deepcopy(first)+ second["session_id"] = "00000000-0000-4000-8000-000000000002"+ # The second Harbor step starts ten minutes later, after verifier and setup time.+ for step in second["steps"]:+ step["timestamp"] = step["timestamp"].replace("T12:00:", "T12:10:")+ _write_multistep_trial(tmp_path, [("prepare", first), ("finish", second)])+ merged = _merged_step_trajectory(tmp_path)+ assert merged is not None+ assert {step["extra"]["harbor_step_name"] for step in merged["steps"]} == {"prepare", "finish"}+ assert trajectory_timing(merged) == _inferred(21.12, 6.8)+++def _named(name: str, steps: list[dict[str, Any]]) -> list[dict[str, Any]]:+ return [{**step, "extra": {"harbor_step_name": name}} for step in steps]+++def test_continuation_step_does_not_count_the_gap_before_it() -> None:+ first = [_user(), _tool_step(3, [1.0]), _agent(10)]+ # A resumed Harbor step can start with an agent step 30 s after the previous one ended.+ second = [_agent(40), _agent(45)]+ merged = [*_named("prepare", first), *_named("finish", second)]+ assert trajectory_timing({"steps": merged}) == _inferred(14.0, 1.0)+ # Read as one Harbor step, the 30 s between the steps would count as LLM time.+ assert trajectory_timing({"steps": [*first, *second]}) == _inferred(44.0, 1.0)+++def test_merged_multistep_trajectory_needs_every_harbor_step_timed() -> None:+ first = [_user(), _tool_step(3, [1.0]), _agent(10)]+ second = [_user(40), _tool_step(43, [1.0])]+ assert trajectory_timing({"steps": [*_named("prepare", first), *_named("finish", second)]}) is None+++def _copied(step: dict[str, Any]) -> dict[str, Any]:+ return {**step, "is_copied_context": True}+++def _exec_step(timestamp: str, call_id: str) -> dict[str, Any]:+ return {+ "source": "agent",+ "timestamp": timestamp,+ "tool_calls": [{"tool_call_id": call_id, "function_name": "exec_command"}],+ "observation": {"results": [{"source_call_id": call_id, "content": "Wall time: 1.0 seconds\nOutput:\nok"}]},+ }+++def test_copied_context_steps_are_not_timed_as_new_work() -> None:+ trajectory = {+ "steps": [+ _copied(_exec_step("2026-01-01T11:00:02Z", "call-old")),+ {"source": "user", "timestamp": "2026-01-01T12:00:00Z"},+ _exec_step("2026-01-01T12:00:02Z", "call-new"),+ {"source": "agent", "timestamp": "2026-01-01T12:00:05Z"},+ ]+ }+ # Timing the copied step would count its 1 s again and the hour after it as LLM time.+ assert trajectory_timing(trajectory) == _inferred(4.0, 1.0)+++def test_copied_context_native_timing_is_not_counted_twice() -> None:+ copied_extra = {"llm_duration_ms": 1000}+ trajectory = {+ "steps": [+ _copied({"source": "agent", "extra": copied_extra, "tool_calls": [{"extra": {"duration_ms": 300}}]}),+ {"source": "user"},+ {"source": "agent", "extra": {"llm_duration_ms": 2000}, "tool_calls": [{"extra": {"duration_ms": 500}}]},+ ]+ }+ assert trajectory_timing(trajectory) == {"llm_seconds": 2.0, "tool_seconds": 0.5, "source": "atif"}+++def test_native_extras_on_copied_context_only_do_not_block_inference() -> None:+ copied = _copied({"source": "agent", "timestamp": "2026-01-01T00:00:00+00:00", "extra": {"llm_duration_ms": 9}})+ assert trajectory_timing({"steps": [copied, _user(1), _agent(4)]}) == _inferred(3.0, 0.0)+++def test_each_harbor_step_drops_its_own_copied_context_prefix() -> None:+ first = [_user(), _tool_step(3, [1.0]), _agent(10)]+ # An untrusted continuation keeps the copied prefix in the merged trajectory.+ second = [*(_copied(step) for step in first), _user(40), _tool_step(43, [2.0]), _agent(50)]+ merged = [*_named("prepare", first), *_named("finish", second)]+ assert trajectory_timing({"steps": merged}) == _inferred(17.0, 3.0)+++def _after_copied_context(first_new_step: dict[str, Any] | None) -> list[dict[str, Any]]:+ copied = [+ _copied({"source": "user", "timestamp": "2026-01-01T11:00:00Z"}),+ _copied({"source": "user", "timestamp": "2026-01-01T12:00:00Z"}),+ ]+ new_work = [+ _exec_step("2026-01-01T12:00:10Z", "call-new"),+ {"source": "agent", "timestamp": "2026-01-01T12:00:15Z"},+ ]+ return [*copied, *([first_new_step] if first_new_step else []), *new_work]+++def test_new_work_that_starts_with_an_agent_step_after_copied_context_is_unmeasured() -> None:+ # The copied timestamps do not show when the first new response started, so timing from it would+ # report 4.0 LLM seconds and drop the 10 s spent producing the first tool call.+ assert trajectory_timing({"steps": _after_copied_context(None)}) is None+ first = [_user(), _tool_step(3, [1.0]), _agent(10)]+ second = _after_copied_context(None)+ assert trajectory_timing({"steps": [*_named("prepare", first), *_named("finish", second)]}) is None++[email protected]("source", ["user", "system"])+def test_new_user_or_system_step_after_copied_context_starts_the_timing(source: str) -> None:+ steps = _after_copied_context({"source": source, "timestamp": "2026-01-01T12:00:00Z"})+ assert trajectory_timing({"steps": steps}) == _inferred(14.0, 1.0)+++def test_native_timing_after_copied_context_needs_no_new_user_step() -> None:+ trajectory = {+ "steps": [+ _copied({"source": "user"}),+ {"source": "agent", "extra": {"llm_duration_ms": 2000}, "tool_calls": [{"extra": {"duration_ms": 500}}]},+ ]+ }+ assert trajectory_timing(trajectory) == {"llm_seconds": 2.0, "tool_seconds": 0.5, "source": "atif"}+++ "steps",+ [+ [_user(), _tool_step(3, [1.0]), _copied(_agent(5)), _agent(10)],+ [_copied(_user()), _copied(_agent(5))],+ ],+ ids=["copied-after-new-step", "only-copied-steps"],+)+def test_copied_context_that_is_not_a_prefix_of_new_work_is_unmeasured(steps: list[dict[str, Any]]) -> None:+ assert trajectory_timing({"steps": steps}) is None++[email protected]("value", [None, [], {}, {"steps": "x"}, {"steps": [None]}, {"steps": []}])+def test_malformed_trajectories_have_no_timing(value: Any) -> None:+ assert trajectory_timing(value) is None