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): add opt-in tolerance for baseline-only agent timeouts (#430)
Narendran Raghavan0f4395db5ff9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 244f8339..b764cd52 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -52,6 +52,23 @@ All notable changes to SkillEvaluator are documented in this file.- Tier 3 evaluations support token, judge-call, attempt, and priced-cost budgets.+- `--tolerate-baseline-timeouts` (and `harbor.tolerate_baseline_timeouts` in+ `evals/config.yml`) keeps a Tier 3 agent scored on its clean with-skill arm+ when its only baseline failures are attempts that hit the agent execution+ timeout while the agent was still producing output. By default one such+ attempt still fails the agent and the whole run. The option needs both arms+ run in the same run (not a `--reuse-baseline` baseline), standard dimension+ grading, every other agent completed (at least one with both arms) and no+ other launch errors; attempts a cost limit left `not_run` are not counted as+ missing. It refuses a timeout whose logs show a known provider overload,+ rate limit, quota or authentication error, and it does not cover native+ multi-step tasks. The baseline condition stays+ `failed`, baseline scores and Skill Lift are not reported for that agent, the+ run's best agent, overall score and verdict come from the agents with a+ complete baseline, reports name the tolerated agent in a "Baseline+ incomplete" note, the run lists a warning, and the run is still not complete+ publication evidence.+- Tier 3 reports list up to three run-level **Next steps** under the per-casefixes in the terminal, `report.html` and the Markdown report: re-run anincomplete run, add attempts for inconsistent cases, add cases or negativediff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdxindex 2f8445ce..cfb04cad 100644--- a/docs/cli-reference.mdx+++ b/docs/cli-reference.mdx@@ -350,6 +350,7 @@ The following flags are forwarded to the live-eval engine when Tier 3 is enabled| `--timeout-multiplier FLOAT` | unset | Scale Harbor's agent, verifier, and environment-build timeouts (built-in default `1.0`). Must be a finite number greater than 0. || `--harbor-keep-jobs` | off | Retain Harbor job dirs and artifacts after the run for inspection. || `--agent-runtime-preflight / --no-agent-runtime-preflight` | disabled | Opt into an extra agent-only execution of the first staged task before the measured A/B matrix. The CLI value overrides `harbor.agent_runtime_preflight`; without either, no extra agent runs. |+| `--tolerate-baseline-timeouts / --no-tolerate-baseline-timeouts` | disabled | Keep an agent scored on its clean with-skill arm when only baseline attempts hit the agent execution timeout; its baseline and Skill Lift are not reported, and the run is not complete publication evidence. The CLI value overrides `harbor.tolerate_baseline_timeouts`. See [Baseline timeouts](/skills/skillevaluator/tier3-live-evaluation#baseline-timeouts). |Flags marked "unset" fall back to their matching keys in `evals/config.yml` where one exists, then to the built-in defaults ([Eval Datasets](eval-datasets.mdx) documents the config keys and precedence). The exception is `--results-dir`, which resolves independently of `evals/config.yml` (see [Reports & Results](reports.mdx)).@@ -584,6 +585,7 @@ Use `skillevaluator tier3 PATH` for the complete workflow with automatic missing| `--harbor-keep-jobs` | off | Retain Harbor job dirs and artifacts for inspection with [harbor-view](#harbor-view). || `--verbose` | off | Also print the per-evaluator and per-dimension tables and the metric findings after the case summary. || `--agent-runtime-preflight / --no-agent-runtime-preflight` | disabled | Opt into an extra agent-only execution of the first staged task before the full A/B evaluation matrix. |+| `--tolerate-baseline-timeouts / --no-tolerate-baseline-timeouts` | disabled | Keep an agent scored on its clean with-skill arm when only baseline attempts hit the agent execution timeout; its baseline and Skill Lift are not reported. The CLI value overrides `harbor.tolerate_baseline_timeouts`. See [Baseline timeouts](/skills/skillevaluator/tier3-live-evaluation#baseline-timeouts). || `--timeout-multiplier FLOAT` | unset | Scale Harbor's agent, verifier, and environment-build timeouts (built-in default `1.0`). Must be a finite number greater than 0. || `--override-cpus INTEGER` | unset | Override eval-environment CPU allocation (passed through to Harbor). || `--override-memory-mb INTEGER` | unset | Override eval-environment memory in MB (passed through to Harbor). |diff --git a/docs/eval-datasets.mdx b/docs/eval-datasets.mdxindex 3ab3bf02..d870136c 100644--- a/docs/eval-datasets.mdx+++ b/docs/eval-datasets.mdx@@ -394,6 +394,7 @@ grading:| `harbor.price_file` | path | JSON price book keyed by exact resolved model identifier. Relative paths resolve from the source skill directory. Each model requires `input_per_mtok` and `output_per_mtok`; optional `cached_input_per_mtok` defaults to the input rate. || `harbor.timeout_multiplier` | finite number > 0 | Scales task timeouts. Values that would overflow Harbor's mandatory lifecycle timeouts are rejected before execution. || `harbor.agent_runtime_preflight` | boolean | Opt-in extra agent-only execution of the first staged task before the measured evaluation. Default: `false`; the CLI flag overrides this value. |+| `harbor.tolerate_baseline_timeouts` | boolean | Keep an agent scored on its with-skill arm when only baseline attempts hit the agent execution timeout; its baseline and Skill Lift are not reported (see [Baseline timeouts](/skills/skillevaluator/tier3-live-evaluation#baseline-timeouts)). Default: `false`; the CLI flag overrides this value. || `harbor.agent_workdir` | string | Working directory for the agent inside the container. || `harbor.resources` | `cpus`, `memory_mb`, `storage_mb` | Per-container resource requests. || `harbor.runtime_env` | list or mapping | Non-credential task values passed into the container. Prefer a list of plain names — each expands to `${NAME}` from your shell; a mapping sets explicit templates. Entries that name or reference operator-owned credentials (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `NVIDIA_API_KEY`, base-URL variables, AWS credential variables) fail with a hard error. Alias: `passthrough_env`. |diff --git a/docs/reports.mdx b/docs/reports.mdxindex 19f9772d..eb14f99a 100644--- a/docs/reports.mdx+++ b/docs/reports.mdx@@ -554,6 +554,13 @@ completed run directly:`behavior_check`, the final-response section limit(`SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT`). For `behavior_check`, therecord's `reason` names each setting that applied.+- **`<agent>/baseline_timeout_tolerance.json`** — written only for an agent+ kept scored by `--tolerate-baseline-timeouts`: the baseline attempts that hit+ the agent execution timeout. `result.json` carries the same record as+ `agents.<agent>.baseline_timeout_tolerance`, a refused agent's+ `agents.<agent>.baseline_timeout_tolerance_rejection` code, and the run-level+ `baseline_timeout_tolerance` (tolerated agents and the launch errors they+ explain). See [Baseline timeouts](/skills/skillevaluator/tier3-live-evaluation#baseline-timeouts).<Note>Read commands (`view`, `compare`, `create-eval-dataset --refine`) honor thediff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdxindex 7015b8c2..d7e2ef2b 100644--- a/docs/tier3-live-evaluation.mdx+++ b/docs/tier3-live-evaluation.mdx@@ -746,6 +746,7 @@ The high-signal flags, with defaults:| `--skip-with-skill` | off | Run only the without-skill arm, for example to calibrate a task set; the report shows baseline scores with no Skill Lift or skill verdict || `--stop-on-pass` | off | Stop a case's remaining attempts once one passes || `--agent-runtime-preflight` | off | Add one agent-only execution of the first staged task per agent before the full A/B matrix; `--no-agent-runtime-preflight` overrides a config value that enables it |+| `--tolerate-baseline-timeouts` | off | Keep an agent scored on its with-skill arm when only baseline attempts hit the agent execution timeout; see [Baseline timeouts](#baseline-timeouts) || `--progress` | `auto` | Progress rendering: `auto`, `rich` (live TTY view with secret redaction), `plain`, or `off` || `--progress-interval` | mode default | Seconds between progress heartbeats: 1 for `rich`, 60 for `plain` lines in CI and redirected output || `--autopilot` | off | When no evaluation source exists, generate exactly one eval case — with the configured provider, falling back to a deterministic keyless template — never overwriting an existing source |@@ -865,6 +866,75 @@ baseline arm must stay isolated from skill-owned setup commands. `validate`does not accept `--skip-with-skill`, so a baseline-only run can never satisfy aTier 3 gate.+### Baseline timeouts++By default, any attempt that errors or goes unscored fails its agent, and any+failed agent fails the whole run: one baseline attempt that hits the agent+execution timeout leaves the run with no overall score or verdict, even though+the verdict reads only with-skill dimensions. `--tolerate-baseline-timeouts` (or+`harbor.tolerate_baseline_timeouts: true` in `evals/config.yml`) keeps such an+agent scored on its with-skill arm. `--no-tolerate-baseline-timeouts`+overrides a config value that enables it.++```bash title="Keep agents whose baseline timed out"+skillevaluator tier3 evaluate ./my-skill --agents claude-code,codex --tolerate-baseline-timeouts+```++The option applies only to an agent whose with-skill arm completed and whose+baseline has at least one attempt that ended in `AgentTimeoutError` (an attempt+a later `--stop-on-pass` attempt recovered does not count). The agent stays+scored only when every one of these holds; otherwise it fails as before, and+the run warning names the rule that did not hold:++- Its with-skill arm scored every attempt with no errors.+- Every missing baseline attempt is a trial that ended in Harbor's+ `AgentTimeoutError`, matched case by case and, with `--stop-on-pass` or a+ cost limit (each attempt then runs as its own job), attempt by attempt.+ Attempts that a [cost limit](#cost-limits) left `not_run` are not expected,+ so they are not missing. A setup timeout,+ process exit, verifier failure or any other baseline error is not+ tolerated. Native multi-step tasks are not covered: Harbor records their+ agent timeouts on the step rather than on the trial, so such a baseline is+ refused (`step_timeout_not_supported`).+- Every timed-out attempt shows agent output (output tokens above zero).+- Each timed-out attempt left an agent log, and no log shows a known provider+ overload, rate limit, quota or authentication error identifier (such as+ `rate_limit_error`, `insufficient_quota`, `Error code: 429` or a `429`+ status field). This is a best-effort check: a provider error worded in a+ way it does not know is not caught.+- Every other agent completed, at least one of them completed both arms, and+ the run has no other launch errors. A single-agent run never qualifies.+- The run grades standard dimensions (not `custom_only`) and runs both arms.+ A baseline reused with `--reuse-baseline` did not run in this run, so the+ option does not apply to it.++For a tolerated agent, the baseline condition stays `failed` with its errors,+and its baseline scores, Skill Lift, pass@k lift and security attribution are+not reported. The reports, and the findings panel that `tier3 evaluate` prints+with `--verbose`, rank it below every agent with a complete baseline, so the+best agent, overall score and lift come from complete evidence. The run's+verdict reads the same agents: a tolerated agent that passes every dimension+does not make the run PASS, and when every agent with a complete baseline+never activated the skill the verdict is INCONCLUSIVE. When the best agent+never activated the skill, the findings panel is left out rather than showing+a tolerated agent's findings. `BENCHMARK.md` and `report.html` keep the "Needs+attention" note and name each tolerated agent on its own line, for example+`Baseline incomplete for opencode (1 of 2 attempts scored)`.++`result.json` records the timed-out attempts under the agent's+`baseline_timeout_tolerance` (also written to+`<agent>/baseline_timeout_tolerance.json`; at most 32 attempts are listed, and+`failed_attempts` is the exact count). An agent that was refused gets+`baseline_timeout_tolerance_rejection` with the rule's code. The run-level+`baseline_timeout_tolerance` lists the tolerated agents and the launch errors+their timeouts explain (at most 32, with `explained_launch_errors_total`). The+run lists a warning for each tolerated or refused agent, and `run_config.json`+records `harbor.tolerate_baseline_timeouts`. The option changes no execution,+so `--reuse-baseline`, `--compare-to` and `tier3 history` do not compare it:+runs with and without it still pair. The missing baseline attempts+still count, so the run is not complete publication evidence and does not+satisfy a blocking Tier 3 gate.+## How standard grading judges a trialWith `default` or `default_plus_custom` grading, SkillEvaluator's verifierdiff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.pyindex 1a6b7f83..ca1b8151 100644--- a/src/skillevaluator/cli.py+++ b/src/skillevaluator/cli.py@@ -968,6 +968,7 @@ def _run_agent_eval_or_skip(timeout_multiplier: float | None = None,harbor_keep_jobs: bool = False,agent_runtime_preflight: bool | None = None,+ tolerate_baseline_timeouts: bool | None = None,block_on_agent_eval: bool = False,validate_source: bool = True,repo_context_exclude_paths: tuple[Path, ...] = (),@@ -1033,6 +1034,7 @@ def _run_agent_eval_or_skip(timeout_multiplier=timeout_multiplier,harbor_keep_jobs=harbor_keep_jobs,agent_runtime_preflight=agent_runtime_preflight,+ tolerate_baseline_timeouts=tolerate_baseline_timeouts,evaluated_source=evaluated_source,repo_context_exclude_paths=repo_context_exclude_paths,)@@ -1456,6 +1458,11 @@ def _catalog_child_argv_from_ctx(argv.append("--agent-runtime-preflight")elif agent_runtime_preflight is False:argv.append("--no-agent-runtime-preflight")+ tolerate_baseline_timeouts = params.get("tolerate_baseline_timeouts")+ if tolerate_baseline_timeouts is True:+ argv.append("--tolerate-baseline-timeouts")+ elif tolerate_baseline_timeouts is False:+ argv.append("--no-tolerate-baseline-timeouts")# Every child renders its own BENCHMARK.md, so the identity has to reach# each one: dropping it here would publish a catalog of cards that all say# the evaluated source was never recorded.@@ -2241,6 +2248,16 @@ def _print_run_banner(target_path: Path, content_type: str, profile: str | None)help_group=_TIER3_GROUP,help="Run an extra agent-only execution of the first staged task before measured Tier 3 [default: disabled].",)+ "--tolerate-baseline-timeouts/--no-tolerate-baseline-timeouts",+ default=None,+ cls=GroupedOption,+ help_group=_TIER3_GROUP,+ help=(+ "Keep an agent scored on its clean with-skill arm when only baseline attempts hit the agent "+ "execution timeout; its baseline and uplift are not reported [default: disabled]."+ ),+)@click.option("--evaluated-source-repository",default=None,@@ -2312,6 +2329,7 @@ def validate(timeout_multiplier: float | None,harbor_keep_jobs: bool,agent_runtime_preflight: bool | None,+ tolerate_baseline_timeouts: bool | None,workers: int,evaluated_source_repository: str | None,evaluated_source_revision: str | None,@@ -2662,6 +2680,7 @@ def validate(timeout_multiplier=timeout_multiplier,harbor_keep_jobs=harbor_keep_jobs,agent_runtime_preflight=agent_runtime_preflight,+ tolerate_baseline_timeouts=tolerate_baseline_timeouts,block_on_agent_eval=block_on_agent_eval_effective,validate_source=preflight_tier3_source,evaluated_source=evaluated_source,@@ -3373,6 +3392,14 @@ def _tier2_workflow(default=None,help="Run an extra agent-only execution of the first staged task before the full matrix [default: disabled].",)+ "--tolerate-baseline-timeouts/--no-tolerate-baseline-timeouts",+ default=None,+ help=(+ "Keep an agent scored on its clean with-skill arm when only baseline attempts hit the agent "+ "execution timeout; its baseline and uplift are not reported [default: disabled]."+ ),+)@click.option("--timeout-multiplier", type=float, default=None)@click.option("--override-cpus", type=int, default=None)@click.option("--override-memory-mb", type=int, default=None)@@ -3445,6 +3472,7 @@ def evaluate(results_dir: Path | None,harbor_keep_jobs: bool,agent_runtime_preflight: bool | None,+ tolerate_baseline_timeouts: bool | None,timeout_multiplier: float | None,override_cpus: int | None,override_memory_mb: int | None,@@ -3533,6 +3561,7 @@ def evaluate(results_dir=results_dir,harbor_keep_jobs=harbor_keep_jobs,agent_runtime_preflight=agent_runtime_preflight,+ tolerate_baseline_timeouts=tolerate_baseline_timeouts,timeout_multiplier=timeout_multiplier,override_cpus=override_cpus,override_memory_mb=override_memory_mb,diff --git a/src/skillevaluator/evaluation/options.py b/src/skillevaluator/evaluation/options.pyindex 8f2c0298..f0f4423c 100644--- a/src/skillevaluator/evaluation/options.py+++ b/src/skillevaluator/evaluation/options.py@@ -64,6 +64,7 @@ class EvaluationOptions:max_attempts_total: int | None = Nonemax_cost_usd: float | None = Noneprice_file: Path | None = None+ tolerate_baseline_timeouts: bool | None = Nonedef engine_kwargs(self) -> dict[str, Any]:"""Return keyword arguments (excluding ``skill_path``) for the engine."""diff --git a/src/skillevaluator/evaluation/tier3_report.py b/src/skillevaluator/evaluation/tier3_report.pyindex 97cd0b55..ae81656f 100644--- a/src/skillevaluator/evaluation/tier3_report.py+++ b/src/skillevaluator/evaluation/tier3_report.py@@ -864,8 +864,10 @@ def build_agent_eval_payload(overall_score = _finite_float(raw_overall_score) if execution_status == "succeeded" else Noneoverall_lift = _finite_float(best.get("lift"))# Baseline calibration scores measure no skill, so they never set a skill verdict.+ # The verdict reads the agents the best agent is picked from.+ verdict_agents = _headline_agents(agent_payloads, score_field=score_field)verdict = (- _overall_verdict_from_agents(agent_payloads)+ _overall_verdict_from_agents(verdict_agents)if overall_score is not None and not baseline_onlyelse VERDICT_NEUTRAL)@@ -953,8 +955,9 @@ def build_agent_eval_payload(if best_agent and _agent_quality_verdict(agent_payloads.get(best_agent, {})) == verdict:verdict_source = agent_payloads[best_agent]else:+ # The reason and counts come from an agent the verdict was read from.verdict_source = next(- (agent for agent in agent_payloads.values() if _agent_quality_verdict(agent) == verdict),+ (agent for agent in verdict_agents.values() if _agent_quality_verdict(agent) == verdict),None,)@@ -1027,7 +1030,12 @@ def build_agent_eval_payload({"severity": "warn","title": "Inconclusive: skill never activated",- "message": "The skill was never activated in any positive with-skill trial. Scores are diagnostic only; no lift verdict was computed.",+ "message": (+ "The skill was never activated in any positive with-skill trial"+ # An agent kept with a failed baseline did not decide this verdict.+ + ("" if len(verdict_agents) == len(agent_payloads) else " of an agent with a complete baseline")+ + ". Scores are diagnostic only; no lift verdict was computed."+ ),}]deterministic_suggestions = ["Check skill loading and agent support, then rerun the evaluation."]@@ -4557,10 +4565,27 @@ def _build_baseline_only_conclusions(return conclusions+def _headline_agents(+ agents: dict[str, dict[str, Any]], *, score_field: str = "with_skill"+) -> dict[str, dict[str, Any]]:+ """Return the agents that set the run's best agent and verdict.++ An agent kept by --tolerate-baseline-timeouts is set aside whenever an+ agent with a complete baseline ranks, so the headline score and verdict+ both come from complete evidence.+ """+ from skillevaluator.tier3.harbor.baseline_timeouts import kept_with_failed_baseline++ complete = {name: agent for name, agent in agents.items() if not kept_with_failed_baseline(agent)}+ if any(_canonical_agent_rank(agent, score_field=score_field) is not None for agent in complete.values()):+ return complete+ return agents++def _pick_best_agent(agents: dict[str, dict[str, Any]], *, score_field: str = "with_skill") -> str:eligible = {name: rank- for name, agent in agents.items()+ for name, agent in _headline_agents(agents, score_field=score_field).items()if (rank := _canonical_agent_rank(agent, score_field=score_field)) is not None}activated = {name: rank for name, rank in eligible.items() if not _never_activated(agents[name])}diff --git a/src/skillevaluator/reporting/benchmark.py b/src/skillevaluator/reporting/benchmark.pyindex b82b953e..df594be0 100644--- a/src/skillevaluator/reporting/benchmark.py+++ b/src/skillevaluator/reporting/benchmark.py@@ -258,6 +258,15 @@ class BenchmarkReporter(ReporterBase):lines.append("**Needs attention:** other execution failures remain. This completed-agent result does not certify the whole run.")+ for tolerated in completed.get("baseline_timeouts_tolerated", ()):+ scored, expected = tolerated["scored_attempts"], tolerated["expected_attempts"]+ counts = (+ f" ({scored} of {expected} attempts scored)" if scored is not None and expected is not None else ""+ )+ lines.append(+ f"Baseline incomplete for **{_publication_safe_inline(tolerated['name'], private_labels)}**"+ f"{counts}: kept by `--tolerate-baseline-timeouts`, so its baseline and uplift are not reported."+ )if completed["recovered_attempts"]:lines.append(f"Recovered timeout attempts: {completed['recovered_attempts']}; failed history is retained and excluded from scoring."diff --git a/src/skillevaluator/reporting/templates/report.html.j2 b/src/skillevaluator/reporting/templates/report.html.j2index 06a167f9..de96aad8 100644--- a/src/skillevaluator/reporting/templates/report.html.j2+++ b/src/skillevaluator/reporting/templates/report.html.j2@@ -2277,6 +2277,7 @@.t3-conclusion.fail { border-left-color:var(--danger-color); }.t3-agent-scorecards-row { display:grid; grid-template-columns:minmax(220px,0.85fr) repeat(2,minmax(260px,1fr)); gap:1.25rem; align-items:stretch; margin-top:0.75rem; }.t3-agent-scorecard-list { display:grid; gap:1rem; align-content:start; }+ .t3-overview-lead .tolerated-baseline { display:block; margin-top:0.35rem; }.t3-overview-lead { background:linear-gradient(135deg,var(--bg),var(--bg-secondary)); border:1px solid var(--border-color); border-left:4px solid var(--secondary-color); border-radius:12px; padding:1rem 1.15rem; box-shadow:var(--shadow); color:var(--dark-text); line-height:1.55; margin:0 0 1rem; }.t3-dataset-provenance { margin:0 0 1rem; padding:0.7rem 0.9rem; border-left:4px solid var(--border-color); border-radius:6px; background:var(--bg-secondary); color:var(--dark-text); }.t3-dataset-provenance.warning { border-left-color:var(--warning-color); background:var(--badge-warn-bg); color:var(--badge-warn-tx); }@@ -2546,6 +2547,9 @@{% endif %}{% endif %}{% endif %}+ {% if completed_agent %}{% for tolerated in completed_agent.baseline_timeouts_tolerated or [] %}+ <span class="tolerated-baseline">Baseline incomplete for <strong>{{ tolerated.name }}</strong>{% if tolerated.scored_attempts is not none and tolerated.expected_attempts is not none %} ({{ tolerated.scored_attempts }} of {{ tolerated.expected_attempts }} attempts scored){% endif %}: kept by <code>--tolerate-baseline-timeouts</code>, so its baseline and uplift are not reported.</span>+ {% endfor %}{% endif %}</div>{% if tier3_dataset_sufficiency and tier3_dataset_sufficiency.coverage_summary %}<p class="t3-dataset-sufficiency{% if tier3_dataset_sufficiency.status == 'provisional' %} warning{% endif %}"diff --git a/src/skillevaluator/reporting/tier3_scope.py b/src/skillevaluator/reporting/tier3_scope.pyindex cb41115c..5c6a8796 100644--- a/src/skillevaluator/reporting/tier3_scope.py+++ b/src/skillevaluator/reporting/tier3_scope.py@@ -114,7 +114,7 @@ def completed_agent_result(payload: dict[str, Any] | None) -> dict[str, Any] | Nreturn Nonefrom skillevaluator.evaluation.tier3_report import _agent_quality_verdict, _agent_quality_verdict_reason- return {+ result: dict[str, Any] = {"name": name,"score": score,"baseline": baseline,@@ -128,3 +128,11 @@ def completed_agent_result(payload: dict[str, Any] | None) -> dict[str, Any] | Nif type(c.get("recovered_attempts_total", 0)) is int and c.get("recovered_attempts_total", 0) >= 0),}+ # Agents kept by --tolerate-baseline-timeouts leave the run succeeded, but+ # their failed baselines still need attention and are named in the report.+ from skillevaluator.tier3.harbor.baseline_timeouts import tolerated_baselines++ tolerated = tolerated_baselines(agents)+ result["baseline_timeouts_tolerated"] = tolerated+ result["needs_attention"] = result["needs_attention"] or bool(tolerated)+ return resultdiff --git a/src/skillevaluator/tier3/baseline_store.py b/src/skillevaluator/tier3/baseline_store.pyindex 11587b83..003c9b5b 100644--- a/src/skillevaluator/tier3/baseline_store.py+++ b/src/skillevaluator/tier3/baseline_store.py@@ -29,6 +29,7 @@ _NON_COMPARISON_FIELDS = frozenset("compare_to","prior_version_comparison","budget",+ "tolerate_baseline_timeouts",})_ARM_TASK_NAME_SUFFIX = re.compile(r"(?m)^(\s*name\s*=\s*['\"][^'\"\r\n]*)-(?:with|without)-skill(['\"]\s*(?:#.*)?)$")diff --git a/src/skillevaluator/tier3/commands.py b/src/skillevaluator/tier3/commands.pyindex 4a164408..036bf536 100644--- a/src/skillevaluator/tier3/commands.py+++ b/src/skillevaluator/tier3/commands.py@@ -691,6 +691,7 @@ def evaluate(results_dir: Path | None,harbor_keep_jobs: bool,agent_runtime_preflight: bool | None = None,+ tolerate_baseline_timeouts: bool | None = None,timeout_multiplier: float | None,override_cpus: int | None,override_memory_mb: int | None,@@ -789,6 +790,7 @@ def evaluate(output_dir=output_dir,keep_harbor_jobs=harbor_keep_jobs,agent_runtime_preflight=agent_runtime_preflight,+ tolerate_baseline_timeouts=tolerate_baseline_timeouts,env_mode=env_mode,env_mode_source="CLI",environment_kwargs=merged_environment_kwargs,diff --git a/src/skillevaluator/tier3/evals_config.py b/src/skillevaluator/tier3/evals_config.pyindex d60de99a..34664c2c 100644--- a/src/skillevaluator/tier3/evals_config.py+++ b/src/skillevaluator/tier3/evals_config.py@@ -46,6 +46,7 @@ _HARBOR_KEYS = {"max_cases","timeout_multiplier","agent_runtime_preflight",+ "tolerate_baseline_timeouts","agent_workdir","resources","runtime_env",@@ -231,6 +232,12 @@ def _validate_config(raw: dict[str, Any], config_path: Path) -> dict[str, Any]:config_path,"harbor.agent_runtime_preflight",)+ if "tolerate_baseline_timeouts" in harbor_raw:+ harbor["tolerate_baseline_timeouts"] = _bool(+ harbor_raw["tolerate_baseline_timeouts"],+ config_path,+ "harbor.tolerate_baseline_timeouts",+ )if "agent_workdir" in harbor_raw:harbor["agent_workdir"] = _non_empty_string(harbor_raw["agent_workdir"],diff --git a/src/skillevaluator/tier3/evals_spec.py b/src/skillevaluator/tier3/evals_spec.pyindex c44889d4..e856e376 100644--- a/src/skillevaluator/tier3/evals_spec.py+++ b/src/skillevaluator/tier3/evals_spec.py@@ -101,7 +101,7 @@ EVALS_SPEC: list[EntrySpec] = [formats=[".yml", ".yaml"],validation_notes=["schema_version must be 1.",- "Supported harbor keys include task_source (auto|evals_json|native_harbor), custom_dockerfile_mode, base_image_mode, n_attempts, pass_threshold, stop_on_pass, n_concurrent, max_agents, max_cases, timeout_multiplier, agent_runtime_preflight, runtime_env, pre_agent_setup, and agents.<name>.model.",+ "Supported harbor keys include task_source (auto|evals_json|native_harbor), custom_dockerfile_mode, base_image_mode, n_attempts, pass_threshold, stop_on_pass, n_concurrent, max_agents, max_cases, timeout_multiplier, agent_runtime_preflight, tolerate_baseline_timeouts, runtime_env, pre_agent_setup, and agents.<name>.model.","passthrough_env and setup_commands are accepted as compatibility aliases for runtime_env and pre_agent_setup.","Supported skill_workspace keys: mode (isolated|group), include.","Supported grading keys: mode (default|default_plus_custom|custom_only).",diff --git a/src/skillevaluator/tier3/harbor/baseline_timeouts.py b/src/skillevaluator/tier3/harbor/baseline_timeouts.pynew file mode 100644index 00000000..f6dd4469--- /dev/null+++ b/src/skillevaluator/tier3/harbor/baseline_timeouts.py@@ -0,0 +1,362 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Opt-in tolerance for Tier 3 baseline attempts that hit the agent execution timeout.++The Tier 3 verdict reads only with-skill dimensions, so a without-skill+(baseline) attempt that ran out of time says nothing about the skill. With+``--tolerate-baseline-timeouts`` (or ``harbor.tolerate_baseline_timeouts``),+an agent whose with-skill arm completed cleanly stays scored when its baseline+fell short only because attempts timed out while the agent was still working.+Its baseline and uplift are not reported; the baseline condition keeps its+``failed`` status and errors.++The collector gathers the evidence (trial results, logs, attempt slots) and+calls the pure rules here. Every rule must hold:++* T1: the with-skill arm is complete and clean.+* T2: the baseline arm failed short of its expected attempts.+* T3: no agent runtime failure other than the timeout: the timed-out trials'+ logs show no provider overload, rate limit or authentication errors, and each+ trial left an agent log to check.+* T4: every failed baseline trial ended in ``AgentTimeoutError``. Native+ multi-step tasks are not covered: Harbor records their agent timeouts on the+ step and counts the trial as completed, so they are refused.+* T5: the timeouts match the missing attempts one for one, per case and, when+ attempts carry labels, per attempt; every trial in the job is scored or timed out.+* T6: every timed-out attempt shows agent output (output tokens > 0).+* T7: every baseline error is one the timeouts produce.+* T8 (run level): every other agent completed, one of them completed both arms,+ and every runner launch error is a tolerated baseline's own. Tolerance is all+ or nothing, so it never applies to a run that fails for another reason.++A tolerated run is still not complete publication evidence: its attempt+coverage stays short, so publication and required-gate checks treat it as+incomplete. Reports rank a tolerated agent below every agent with a complete+baseline (:func:`kept_with_failed_baseline`), so the run's best agent,+headline score and verdict always come from complete evidence.+"""++from __future__ import annotations++from collections import Counter+from collections.abc import Iterable, Mapping, MutableMapping, Sequence+from typing import Any++RECORD_KEY = "baseline_timeout_tolerance"+REJECTION_KEY = "baseline_timeout_tolerance_rejection"+RUN_KEY = "baseline_timeout_tolerance"+RECORD_ARTIFACT = "baseline_timeout_tolerance.json" # beside lift.json in the agent results directory+TOLERATED_EXCEPTION_TYPE = "AgentTimeoutError"+TOLERATED_REASON = "agent_execution_timeout"+JOB_FAILURE = "Harbor job did not complete successfully: {count} errored"+_LAUNCH_PREFIX = "{agent} without-skill Harbor run failed: "+FAILURES_PUBLISHED_MAX = 32+LAUNCH_ERRORS_PUBLISHED_MAX = 32++REJECTION_REASONS = {+ "with_skill_incomplete": "the with-skill arm did not score every attempt",+ "with_skill_not_clean": "the with-skill arm reported failures",+ "custom_only_grading": "custom_only grading has no dimension verdict",+ "baseline_not_short": "the baseline did not fall short of its attempts",+ "no_case_identity": "the run has no expected case identities to match attempts against",+ "agent_runtime_failure": "the baseline logged agent runtime errors",+ "provider_degradation_observed": "a timed-out attempt logged provider overload, rate limit or authentication errors",+ "no_agent_log": "a timed-out attempt left no agent log to check for provider errors",+ "reason_not_tolerated": "a baseline attempt failed with something other than an agent execution timeout",+ "untyped_trial_failure": "a failed baseline trial is not an agent execution timeout",+ "step_timeout_not_supported": "a baseline attempt timed out in a step of a native multi-step task, which the option does not cover",+ "timed_out_trial_scored": "a timed-out baseline trial also has a scored reward",+ "unaccounted_trial": "the baseline job holds a trial that is neither scored nor timed out",+ "failures_do_not_account_for_missing": "the timeouts do not account for every missing attempt",+ "per_case_mismatch": "the timeouts do not match the missing attempts case by case",+ "ordinal_mismatch": "the timeouts do not match the missing attempt numbers",+ "no_progress_evidence": "a timed-out attempt shows no agent output tokens",+ "unbound_error": "the baseline reported other errors",+ "other_agent_failed": "another agent did not complete",+ "no_clean_peer": "no other agent completed both arms",+ "unbound_launch_error": "the run reported other launch errors",+}+++def _count(value: Any, *, minimum: int = 0) -> int | None:+ """Return ``value`` when it is a real integer (never bool) at or above ``minimum``."""+ return value if type(value) is int and value >= minimum else None+++def baseline_status(scored_attempts: int) -> str:+ """Return ``partial`` when some baseline attempts scored, else ``unavailable``."""+ return "partial" if scored_attempts > 0 else "unavailable"+++def check_failures(+ *,+ expected_attempts: int,+ scored_attempts: int,+ slots: Mapping[str, Mapping[str, Any]],+ failures: Sequence[Mapping[str, Any]],+) -> str | None:+ """Check the typed baseline failures against the missing attempts (T4 to T6).++ ``slots`` maps each expected case to ``{"required", "missing",+ "missing_ordinals"}``; ``missing_ordinals`` is None when the case's attempt+ labels are implicit. Each failure is ``{"case_id", "attempt",+ "exception_types", "output_tokens"}``, where ``attempt`` is the attempt+ ordinal or None and ``exception_types`` lists every exception Harbor+ recorded on the trial and its steps. Returns None when the failures are+ exactly the missing attempts, otherwise the first failing code.+ """+ expected = _count(expected_attempts, minimum=1)+ scored = _count(scored_attempts)+ if expected is None or scored is None or scored >= expected:+ return "baseline_not_short"+ for failure in failures:+ types = failure.get("exception_types")+ if not isinstance(types, (list, tuple)) or not types or set(types) != {TOLERATED_EXCEPTION_TYPE}:+ return "reason_not_tolerated"+ if len(failures) != expected - scored:+ return "failures_do_not_account_for_missing"+ missing_by_case = Counter(+ {str(case): count for case, slot in slots.items() if (count := _count(slot.get("missing"), minimum=1))}+ )+ if Counter(str(failure.get("case_id") or "") for failure in failures) != missing_by_case:+ return "per_case_mismatch"+ for case, slot in slots.items():+ ordinals = slot.get("missing_ordinals")+ if ordinals is None:+ continue+ attempts = [failure.get("attempt") for failure in failures if failure.get("case_id") == case]+ if any(_count(attempt, minimum=1) is None for attempt in attempts) or sorted(attempts) != sorted(ordinals):+ return "ordinal_mismatch"+ if any(_count(failure.get("output_tokens"), minimum=1) is None for failure in failures):+ return "no_progress_evidence"+ return None+++def build_record(+ *,+ expected_attempts: int,+ scored_attempts: int,+ failures: Sequence[Mapping[str, Any]],+ timeout_seconds: float | None,+) -> dict[str, Any]:+ """Return the baseline record kept on a tolerated agent.++ Each failure carries the published ``trial`` label, ``case_id``, ``task``+ (the staged task selector), ``attempt`` and ``output_tokens``. Only the+ first :data:`FAILURES_PUBLISHED_MAX` rows are published; ``failed_attempts``+ is the exact count.+ """+ rows = [+ {+ "trial": str(failure.get("trial") or ""),+ "case_id": str(failure.get("case_id") or ""),+ "attempt": failure.get("attempt"),+ "output_tokens": failure.get("output_tokens"),+ }+ for failure in failures+ ]+ return {+ "status": baseline_status(scored_attempts),+ "reason": TOLERATED_REASON,+ "exception_type": TOLERATED_EXCEPTION_TYPE,+ "expected_attempts": expected_attempts,+ "scored_attempts": scored_attempts,+ "failed_attempts": len(rows),+ "timeout_seconds": timeout_seconds,+ "failures": rows[:FAILURES_PUBLISHED_MAX],+ "failures_truncated": len(rows) > FAILURES_PUBLISHED_MAX,+ }+++def _bound_launch_errors(agent: str, errors: Sequence[str], failures: Sequence[Mapping[str, Any]]) -> bool:+ """Return whether ``errors`` are exactly the runner messages the timed-out attempts produce.++ An arm-level job reports one ``<agent> without-skill Harbor run failed:+ Harbor job did not complete successfully: <k> errored`` with ``k`` the+ number of timeouts. Stop-on-pass runs each attempt as its own job and+ reports ``... failed: <task> attempt <n>: Harbor job did not complete+ successfully: 1 errored`` once per timed-out attempt.+ """+ if not errors:+ return True+ prefix = _LAUNCH_PREFIX.format(agent=agent)+ arm_level = prefix + JOB_FAILURE.format(count=len(failures))+ if list(errors) == [arm_level]:+ return True+ expected = Counter(+ f"{prefix}{failure.get('task')} attempt {failure.get('attempt')}: {JOB_FAILURE.format(count=1)}"+ for failure in failures+ if failure.get("task") and _count(failure.get("attempt"), minimum=1) is not None+ )+ observed = Counter(errors)+ return all(expected[error] >= count for error, count in observed.items())+++def _owner(error: str, agents: Iterable[str]) -> str | None:+ """Return the agent a runner launch error names, or None when it names none."""+ for agent in sorted(agents, key=len, reverse=True):+ if error.startswith(f"{agent} "):+ return agent+ return None+++def select_tolerated(+ agents: Mapping[str, Mapping[str, Any]],+ candidates: Mapping[str, Sequence[Mapping[str, Any]]],+ rejected: Mapping[str, str],+ launch_errors: Sequence[str] | None,+) -> tuple[frozenset[str], dict[str, str], list[str]]:+ """Decide the run-level outcome (T8); returns ``(tolerated, rejected, explained_launch_errors)``.++ ``agents`` is the collected agent payloads, ``candidates`` maps each agent+ whose baseline passed T1 to T7 to its full typed failure list, and+ ``rejected`` maps each agent that had a complete with-skill arm and a short+ baseline but failed those rules to its code. Tolerance is all or nothing:+ it applies only when no candidate was rejected, every other agent+ completed, one of them completed both arms, and every launch error is a+ candidate's own timeout message. Otherwise each candidate keeps its failed+ status and gets the run-level code.+ """+ outcome = dict(rejected)+ if not candidates:+ return frozenset(), outcome, []+ others = {name: data for name, data in agents.items() if name not in candidates}+ reason: str | None = None+ if rejected or any(data.get("execution_status") != "succeeded" for data in others.values()):+ reason = "other_agent_failed"+ elif not any(+ ((data.get("conditions") or {}).get("without_skill") or {}).get("execution_status") == "succeeded"+ for data in others.values()+ ):+ reason = "no_clean_peer"+ explained: list[str] = []+ if reason is None:+ by_agent: dict[str, list[str]] = {}+ for error in launch_errors or ():+ owner = _owner(str(error), agents)+ if owner not in candidates:+ reason = "unbound_launch_error"+ break+ by_agent.setdefault(owner, []).append(str(error))+ else:+ for agent, errors in by_agent.items():+ if not _bound_launch_errors(agent, errors, candidates[agent]):+ reason = "unbound_launch_error"+ break+ explained.extend(errors)+ if reason is not None:+ outcome.update(dict.fromkeys(candidates, reason))+ return frozenset(), outcome, []+ return frozenset(candidates), outcome, explained+++def settle(agent_data: MutableMapping[str, Any], record: Mapping[str, Any]) -> None:+ """Keep a tolerated agent scored on its with-skill arm.++ The agent's status becomes ``succeeded`` with no agent-level errors, and+ ``record`` is attached under :data:`RECORD_KEY`. ``conditions.without_skill``+ keeps its ``failed`` status and errors, and the attempt totals still count+ the missing baseline attempts. Baseline scores, lift and security+ attribution were never computed for the failed baseline, so they stay empty.+ """+ agent_data[RECORD_KEY] = dict(record)+ agent_data.pop(REJECTION_KEY, None)+ agent_data["execution_status"] = "succeeded"+ agent_data["execution_errors"] = []+ agent_data["execution_error_details_total"] = 0+ agent_data["execution_error_details_shown"] = 0+ agent_data["execution_error_details_truncated"] = False+++def run_record(tolerated: Iterable[str], explained_launch_errors: Sequence[str]) -> dict[str, Any]:+ """Return the run-level record: the tolerated agents and a bounded sample of the launch errors they explain.++ ``explained_launch_errors_total`` is the exact count; only the first+ :data:`LAUNCH_ERRORS_PUBLISHED_MAX` messages are published, since a+ stop-on-pass baseline that timed out on many cases reports one per attempt.+ """+ explained = [str(error) for error in explained_launch_errors]+ return {+ "tolerated_agents": sorted(tolerated),+ "explained_launch_errors": explained[:LAUNCH_ERRORS_PUBLISHED_MAX],+ "explained_launch_errors_total": len(explained),+ "explained_launch_errors_truncated": len(explained) > LAUNCH_ERRORS_PUBLISHED_MAX,+ }+++def unexplained_launch_errors(results: Mapping[str, Any], launch_errors: Sequence[str]) -> list[str]:+ """Return the launch errors that tolerated baselines do not explain, in order.++ Tolerance applies only when every launch error is a tolerated baseline's+ own timeout message, so those are exactly the errors a tolerated agent+ owns. They are dropped only while their count still equals the recorded+ ``explained_launch_errors_total``; otherwise every error is kept.+ """+ run = results.get(RUN_KEY)+ if not isinstance(run, Mapping):+ return list(launch_errors)+ tolerated = {str(agent) for agent in run.get("tolerated_agents") or ()}+ agents = results.get("agents")+ names = [str(name) for name in agents] if isinstance(agents, Mapping) else []+ remaining = [error for error in launch_errors if _owner(str(error), names) not in tolerated]+ if not tolerated or len(launch_errors) - len(remaining) != _count(run.get("explained_launch_errors_total")):+ return list(launch_errors)+ return remaining+++def kept_with_failed_baseline(agent: Mapping[str, Any]) -> bool:+ """Return whether ``agent`` stays scored although its baseline condition failed.++ Without tolerance a failed arm always fails its agent, so this shape marks+ an agent kept by ``--tolerate-baseline-timeouts``, both in ``result.json``+ and in the report payload built from it.+ """+ conditions = agent.get("conditions")+ baseline = conditions.get("without_skill") if isinstance(conditions, Mapping) else None+ return (+ agent.get("execution_status") == "succeeded"+ and isinstance(baseline, Mapping)+ and baseline.get("execution_status") == "failed"+ )+++def tolerated_baselines(agents: Any) -> list[dict[str, Any]]:+ """Describe each agent kept with a failed baseline: ``{"name", "scored_attempts", "expected_attempts"}``."""+ if not isinstance(agents, Mapping):+ return []+ described: list[dict[str, Any]] = []+ for name in sorted(agents, key=str):+ agent = agents[name]+ if not isinstance(agent, Mapping) or not kept_with_failed_baseline(agent):+ continue+ baseline = agent["conditions"]["without_skill"]+ described.append(+ {+ "name": str(name),+ "scored_attempts": _count(baseline.get("scored_attempts")),+ "expected_attempts": _count(baseline.get("expected_attempts")),+ }+ )+ return described+++def tolerance_warning(agent: str, record: Mapping[str, Any]) -> str:+ """Return the run warning that names a tolerated agent and its missing baseline attempts."""+ failed = record.get("failed_attempts")+ expected = record.get("expected_attempts")+ scored = record.get("scored_attempts")+ timeout = record.get("timeout_seconds")+ after = f" after {timeout:g} seconds" if isinstance(timeout, (int, float)) and not isinstance(timeout, bool) else ""+ return (+ f"{agent} baseline incomplete: {failed} attempt(s) hit the agent execution timeout{after} "+ f"({scored} of {expected} scored). The agent stays scored on its with-skill arm "+ "(--tolerate-baseline-timeouts); its baseline and uplift are not reported, and the run is not "+ "complete publication evidence."+ )+++def rejection_warning(agent: str, code: str) -> str:+ """Return the run warning for an agent whose baseline timeouts were not tolerated."""+ reason = REJECTION_REASONS.get(code, "the baseline evidence did not meet the tolerance rules")+ return f"{agent} baseline timeouts were not tolerated: {reason} ({code})."diff --git a/src/skillevaluator/tier3/harbor/collector.py b/src/skillevaluator/tier3/harbor/collector.pyindex 3c203318..04dabdfe 100644--- a/src/skillevaluator/tier3/harbor/collector.py+++ b/src/skillevaluator/tier3/harbor/collector.py@@ -33,6 +33,7 @@ from skillevaluator.tier3.baseline_store import BASELINE_ANNOTATION_KEYS, load_bfrom skillevaluator.tier3.eval_core.atif_helpers import extract_tool_calls_as_dicts, get_skill_tool_callsfrom skillevaluator.tier3.eval_core.checks import check_negative_casefrom skillevaluator.tier3.eval_core.codex_tool_call_normalizer import atif_content_text+from skillevaluator.tier3.harbor import baseline_timeoutsfrom skillevaluator.tier3.harbor.activation import summarize_skill_activationfrom skillevaluator.tier3.harbor.lift_basis import pair_metric_scoresfrom skillevaluator.tier3.harbor.metrics import (@@ -142,6 +143,7 @@ GENERATED_AGENT_ARTIFACTS = ("pass_at_k_lift.json","security_attribution.json","findings.json",+ "baseline_timeout_tolerance.json",)GENERATED_CONDITION_DIRS = ("with-skill", "without-skill")GENERATED_ROOT_ARTIFACTS = ("attempt_policy.json", "comparison.json")@@ -6756,6 +6758,7 @@ def _condition_execution_summary(skipped: bool = False,stop_on_pass: bool = False,pass_threshold: float = 0.50,+ attempt_slots: dict[str, dict[str, Any]] | None = None,expected_attempts_by_case: Mapping[str, int] | None = None,) -> dict[str, Any]:"""Describe whether a Harbor condition produced complete logical attempts.@@ -6764,6 +6767,10 @@ def _condition_execution_summary(``_trial_root_name`` is therefore the attempt identity; the case id aloneis not sufficient and raw reward-row count would over-count those tasks.Early-stopped cases require attempts only through their first passing trial.+ When ``attempt_slots`` is a dict, it receives ``{"required", "missing",+ "missing_ordinals"}`` for each expected case; ``missing_ordinals`` lists+ the absent attempt ordinals when the case's attempts carry labels, and is+ None when only a count is known."""expected_ids = _validated_expected_case_ids(expected_case_ids)expected_count = len(expected_ids) if expected_ids else int(expected_cases or 0)@@ -6894,7 +6901,22 @@ def _condition_execution_summary(if all_explicit:expected_ordinals = set(range(1, required + 1))actual_ordinals = set(explicit + recovered_ordinals)- return required, bool(expected_ordinals - actual_ordinals), bool(actual_ordinals - expected_ordinals)+ missing_ordinals = sorted(expected_ordinals - actual_ordinals)+ if attempt_slots is not None:+ attempt_slots[case_id] = {+ "required": required,+ "missing": len(missing_ordinals),+ "missing_ordinals": missing_ordinals,+ }+ return required, bool(missing_ordinals), bool(actual_ordinals - expected_ordinals)+ if attempt_slots is not None:+ # Stop-on-pass runs each attempt as its own labelled job, so a case+ # with nothing scored owes every ordinal through the maximum.+ attempt_slots[case_id] = {+ "required": required,+ "missing": max(0, required - len(attempts)),+ "missing_ordinals": list(range(1, required + 1)) if stop_on_pass and not attempts else None,+ }return required, len(attempts) < required, len(attempts) > requiredmissing: list[str] = []@@ -7037,6 +7059,338 @@ def _aggregate_execution(summaries: list[dict[str, Any]]) -> dict[str, Any]:}+# -- opt-in baseline-timeout tolerance (evidence half; rules in baseline_timeouts) --++_AGENT_TIMEOUT_SECONDS_RE = re.compile(r"after (\d+(?:\.\d+)?) seconds")+# Trial logs and trajectories are written by the agent under evaluation, so the+# tolerance checks read them anchored at the trial directory, bounded and+# without following links.+_TOLERANCE_EVIDENCE_MAX_BYTES = 64 * 1024 * 1024+# Provider overload, rate limiting or auth trouble that an agent can retry+# through until the execution timeout kills it, so no terminal error is ever+# written. A best-effort check on known provider error identifiers: Anthropic,+# OpenAI and Google error types and codes, litellm's RateLimitError, Claude+# Code's "API Error: <status>" and "Repeated 529 Overloaded", retry events'+# "error_status", the OpenAI SDK's "Error code: <status>", a JSON or Python+# "status"/"statusCode" field of 429 or 529 (OpenAI-compatible providers,+# OpenCode's APIError), and the "429 Too Many Requests" status line (Codex+# prints "status: 429 Too Many Requests"). Prose such as "rate limit" in+# fetched pages or answers does not count, nor does another bare HTTP status a+# page may print. A brief 5xx retry is common in healthy runs and does not+# count either.+_PROVIDER_DEGRADATION_RE = re.compile(+ rb"overloaded_error|server_is_overloaded|Repeated 529 Overloaded"+ rb"|rate_limit_error|rate_limit_exceeded|\"error\"\s*:\s*\"rate_limit\"|RateLimitError"+ rb"|insufficient_quota|RESOURCE_EXHAUSTED"+ rb"|authentication_error|permission_error|invalid[ _-]api[ _-]key"+ rb"|API Error:?\s*(?:401|403|429|529)\b"+ rb"|Error code:\s*(?:401|403|429|529)\b"+ rb"|\"error_status\"\s*:\s*(?:401|403|429|529)\b"+ rb"|[\"']status(?:_?code)?[\"']?\s*:\s*[\"']?(?:429|529)\b"+ rb"|\b429\s+Too Many Requests"+ rb"|\bstatus:?\s+(?:401|403)\s+(?:Unauthorized|Forbidden)",+ re.IGNORECASE,+)+# Where Harbor keeps a trial's text logs: single-step trials under agent/ or+# the trial root, multi-step native trials under steps/*/agent/. Every *.txt+# there is scanned, so a supported agent's own log name can never go unread.+_TRIAL_TEXT_LOG_GLOBS = ("agent/*.txt", "*.txt", "steps/*/agent/*.txt")+# Harbor's own trial text (exception.txt) is scanned too, but it is not the+# agent's log, so it never shows the agent was free of provider trouble.+_HARBOR_TRIAL_TEXT = frozenset(name for name in TRIAL_DIAGNOSTIC_ARTIFACTS if name.endswith(".txt"))+# The agent can write any number of files next to its log, so the scan reads+# at most this many; a trial over either bound cannot be cleared.+_TOLERANCE_LOG_MAX_FILES = 64+++def _agent_timeout_seconds(reason: str) -> float | None:+ """Return the agent timeout budget named by a Harbor ``AgentTimeoutError`` message."""+ match = _AGENT_TIMEOUT_SECONDS_RE.search(reason)+ if match is None:+ return None+ seconds = float(match.group(1))+ return seconds if math.isfinite(seconds) and seconds > 0 else None+++def _positive_token_count(value: Any) -> int | None:+ """Return a positive whole token count, or None for anything else (never bool)."""+ if isinstance(value, bool) or not isinstance(value, int | float):+ return None+ try:+ if not math.isfinite(value) or value < 1 or value != int(value):+ return None+ except OverflowError:+ # JSON integers can exceed the float range used to check finiteness.+ return None+ return int(value)+++def _read_trial_evidence(+ trial_dir: Path, relative_path: Path, max_bytes: int = _TOLERANCE_EVIDENCE_MAX_BYTES+) -> bytes | None:+ """Read one agent-written trial file safely; None when it does not exist.++ Raises ``SecurePathError`` or ``OSError`` when the file exists but cannot+ be read safely: a link, not a regular file, over ``max_bytes``, or unreadable.+ """+ if not os.path.lexists(trial_dir / relative_path):+ return None+ with SecureRoot(trial_dir) as secure_root:+ raw, _metadata = secure_root.read_bytes(relative_path, max_bytes)+ return raw+++def _trial_output_tokens(trial_dir: Path, harbor_result: Mapping[str, Any]) -> int | None:+ """Return proof that the agent produced output before a trial ended, or None.++ Harbor's ``agent_result.n_output_tokens`` comes first; otherwise any+ trajectory's ``final_metrics.total_completion_tokens`` (root, ``agent/``+ or a native step). A missing or zero counter is no proof, and neither is+ a trajectory that cannot be read bounded and without following links.+ """+ agent_result = harbor_result.get("agent_result")+ tokens = _positive_token_count(agent_result.get("n_output_tokens") if isinstance(agent_result, dict) else None)+ if tokens is not None:+ return tokens+ for path in (+ Path("trajectory.json"),+ Path("agent") / "trajectory.json",+ *(path.relative_to(trial_dir) for path in sorted(trial_dir.glob("steps/*/agent/trajectory.json"))),+ ):+ try:+ raw = _read_trial_evidence(trial_dir, path)+ trajectory = json.loads(raw) if raw is not None else None+ except (SecurePathError, ValueError, OSError, RecursionError, UnicodeError):+ continue+ final_metrics = trajectory.get("final_metrics") if isinstance(trajectory, dict) else None+ if isinstance(final_metrics, dict):+ tokens = _positive_token_count(final_metrics.get("total_completion_tokens"))+ if tokens is not None:+ return tokens+ return None+++def _provider_log_rejection(trial_dir: Path) -> str | None:+ """Return why a timed-out trial's logs cannot clear it of provider trouble, or None when they do.++ ``provider_degradation_observed`` when any text log shows provider+ overload, rate limiting or auth errors. Every line counts: an agent killed+ by the execution timeout while it retried never writes a terminal error. A+ log that cannot be read safely in full, or more logs or bytes than the+ bounds, counts as degradation, since it cannot be cleared. ``no_agent_log``+ when the trial left no agent log at all (Harbor's exception.txt is not one).+ """+ paths = [+ path.relative_to(trial_dir) for pattern in _TRIAL_TEXT_LOG_GLOBS for path in sorted(trial_dir.glob(pattern))+ ]+ if len(paths) > _TOLERANCE_LOG_MAX_FILES:+ return "provider_degradation_observed"+ budget = _TOLERANCE_EVIDENCE_MAX_BYTES+ agent_log_scanned = False+ for path in paths:+ try:+ raw = _read_trial_evidence(trial_dir, path, budget)+ except (SecurePathError, OSError):+ return "provider_degradation_observed"+ if raw is None:+ continue+ if _PROVIDER_DEGRADATION_RE.search(raw):+ return "provider_degradation_observed"+ budget -= len(raw)+ agent_log_scanned = agent_log_scanned or path.name not in _HARBOR_TRIAL_TEXT+ return None if agent_log_scanned else "no_agent_log"+++def _job_has_unrecovered_agent_timeout(job_dir: Path, recovered: list[dict[str, Any]]) -> bool:+ """Return whether a trial of the job, other than a recovered attempt, recorded ``AgentTimeoutError``.++ Checks the trial and each native step. A baseline that failed without an+ agent execution timeout is not a tolerance case, so it gets no rejection+ or warning and fails exactly as it does without the option.+ """+ recovered_labels = {str(item.get("trial") or "") for item in recovered}+ try:+ entries = sorted(job_dir.iterdir())+ except OSError:+ return False+ for ordinal, trial_dir in enumerate(entries, start=1):+ if _inspect_trial_directory(trial_dir)[0] != "directory" or not _looks_like_trial_dir(trial_dir):+ continue+ if _published_trial_label(trial_dir.name, alias_ordinal=ordinal) in recovered_labels:+ continue+ harbor_result = _read_json(trial_dir / "result.json")+ root = harbor_result.get("exception_info") if isinstance(harbor_result, dict) else None+ exception_types = [_exception_details(root)[0], *(kind for kind, _ in _trial_step_exception_details(trial_dir))]+ if baseline_timeouts.TOLERATED_EXCEPTION_TYPE in exception_types:+ return True+ return False+++def _with_skill_tolerance_rejection(+ execution: Mapping[str, Any],+ *,+ policy: str,+ job_failure: str,+ runtime_failures: list[dict[str, str]],+ trial_failures: list[dict[str, str]],+) -> str | None:+ """Check that the with-skill arm is complete and clean (T1); None when it is.++ ``runtime_failures`` and ``trial_failures`` are the active (unrecovered) rows.+ """+ if policy == CUSTOM_SCORE_POLICY:+ return "custom_only_grading"+ expected = execution.get("expected_attempts")+ if (+ execution.get("execution_status") != "succeeded"+ or not isinstance(expected, int)+ or expected < 1+ or execution.get("scored_attempts") != expected+ ):+ return "with_skill_incomplete"+ if execution.get("execution_errors") or job_failure or runtime_failures or trial_failures:+ return "with_skill_not_clean"+ return None+++def _baseline_timeout_failures(+ *,+ job_dir: Path,+ rewards: list[dict[str, Any]],+ execution: Mapping[str, Any],+ slots: Mapping[str, Mapping[str, Any]],+ residual_errors: list[str],+ job_failure: str,+ runtime_failures: list[dict[str, str]],+ trial_failures: list[dict[str, str]],+ recovered: list[dict[str, Any]],+ expected_case_ids: list[str],+ case_id_by_task_selector: dict[str, str] | None,+ arm_suffix: str,+ task_entry_id_map: Mapping[str, str] | None,+) -> tuple[list[dict[str, Any]], str | None]:+ """Gather the typed failures of a short baseline arm and check T2 to T7.++ Returns ``(failures, None)`` when every rule holds, otherwise+ ``([], code)``. ``rewards`` are the arm's scoreable rewards,+ ``execution`` its summary, ``slots`` the per-case attempt slots from+ :func:`_condition_execution_summary`, and ``residual_errors`` that+ summary's errors recomputed without any trial failures or job failure.+ The runtime and trial failure lists include recovered rows; those are+ set aside here, as they are for the summary. Harbor's errored count+ still includes the recovered timeouts, so the job failure may count them.+ """+ if not expected_case_ids:+ return [], "no_case_identity"+ expected_set = set(expected_case_ids)+ recovered_labels = {str(item.get("trial") or "") for item in recovered}+ scored_roots = {str(reward.get("_trial_root_name") or "") for reward in rewards}+ failures: list[dict[str, Any]] = []+ exception_reasons: dict[str, str] = {}+ recovered_timeouts = 0+ for ordinal, trial_dir in enumerate(sorted(job_dir.iterdir()), start=1):+ kind, _reason = _inspect_trial_directory(trial_dir)+ if kind == "link":+ return [], "unaccounted_trial"+ if kind != "directory" or not _looks_like_trial_dir(trial_dir):+ continue+ label = _published_trial_label(trial_dir.name, alias_ordinal=ordinal)+ harbor_result = _read_json(trial_dir / "result.json")+ harbor_result = harbor_result if isinstance(harbor_result, dict) else {}+ root_type, root_reason = _exception_details(harbor_result.get("exception_info"))+ if trial_dir.name in scored_roots:+ if root_type:+ return [], "timed_out_trial_scored"+ continue+ if label in recovered_labels:+ # A recovered attempt is an agent timeout a later attempt scored;+ # it is counted only toward Harbor's errored total below.+ if root_type != baseline_timeouts.TOLERATED_EXCEPTION_TYPE:+ return [], "unaccounted_trial"+ recovered_timeouts += 1+ continue+ if not harbor_result:+ return [], "unaccounted_trial"+ step_details = _trial_step_exception_details(trial_dir)+ if any(kind == baseline_timeouts.TOLERATED_EXCEPTION_TYPE for kind, _detail in step_details):+ # Harbor records a native multi-step task's agent timeout on the+ # step and counts the trial as completed, so the trial carries no+ # root exception or errored count to bind. The option does not+ # cover these tasks.+ return [], "step_timeout_not_supported"+ selector = _task_selector_from_harbor_result(harbor_result)+ entry_id = _entry_id_from_harbor_result(+ harbor_result,+ case_id_by_task_selector,+ arm_suffix=arm_suffix,+ task_entry_id_map=task_entry_id_map,+ )+ if case_id_by_task_selector is None and entry_id:+ entry_id = _canonical_case_id(entry_id, expected_set)+ exception_reasons[label] = redact_sensitive_text(root_reason)+ failures.append(+ {+ "trial": label,+ "case_id": entry_id,+ "task": selector,+ "attempt": _structural_attempt_ordinal(trial_dir.name, selector) if selector else None,+ "exception_types": [+ exception_type+ for exception_type, _detail in ((root_type, root_reason), *step_details)+ if exception_type+ ],+ "output_tokens": _trial_output_tokens(trial_dir, harbor_result),+ "timeout_seconds": _agent_timeout_seconds(root_reason),+ "_trial_dir": trial_dir,+ }+ )++ if code := baseline_timeouts.check_failures(+ expected_attempts=execution.get("expected_attempts"),+ scored_attempts=execution.get("scored_attempts"),+ slots=slots,+ failures=failures,+ ):+ return [], code++ # Every failed trial is a typed timeout, once, and each reports exactly its+ # own timeout: a verifier failure, an invalid reward row or an agent log+ # runtime error on a timed-out trial is evidence these rules cannot explain.+ def _matches(rows: list[dict[str, str]]) -> bool:+ active = [row for row in rows if str(row.get("trial") or "") not in recovered_labels]+ return len(active) == len(exception_reasons) and all(+ exception_reasons.get(str(row.get("trial") or "")) == str(row.get("reason") or "") for row in active+ )++ if not _matches(trial_failures):+ return [], "untyped_trial_failure"+ if not _matches(runtime_failures):+ return [], "agent_runtime_failure"++ # T7: the baseline's errors are only the ones these timeouts produce.+ allowed = {+ _safe_diagnostic_text(+ _sampled_case_id_diagnostic(+ "Missing scored attempts for cases", sorted({str(failure["case_id"]) for failure in failures})+ ),+ max_len=4096,+ ),+ f"Scored attempt coverage is {execution.get('scored_attempts')}/{execution.get('expected_attempts')}",+ }+ if recovered_timeouts != len(recovered_labels) or job_failure not in {+ "",+ baseline_timeouts.JOB_FAILURE.format(count=len(failures) + recovered_timeouts),+ }:+ return [], "unbound_error"+ if any(error not in allowed for error in residual_errors):+ return [], "unbound_error"++ for failure in failures:+ if rejection := _provider_log_rejection(failure.pop("_trial_dir")):+ return [], rejection+ return failures, None++def _observe_private_trials(agent, arm, job_dir, collected, scoreable, selector_map) -> None:"""Hand existing observations to an active private hook without affecting ordinary collection."""runtime = sys.modules.get("skillevaluator.tier3.plugin_execution")@@ -7070,6 +7424,7 @@ def collect_harbor_results(agent_models: dict[str, dict[str, str]] | None = None,launch_errors: list[str] | None = None,grading_mode: str | None = None,+ tolerate_baseline_timeouts: bool = False,budget_not_run: list[dict[str, Any]] | None = None,) -> dict[str, Any]:"""Collect results from Harbor jobs into evals/results/<agent>/ structure.@@ -7080,6 +7435,12 @@ def collect_harbor_results(``grading_mode`` labels a condition with no scoreable reward with therequested metric set and score policy; observed rewards still declaretheir own.+ ``tolerate_baseline_timeouts`` keeps an agent scored on its clean+ with-skill arm when its baseline fell short only through agent execution+ timeouts (see :mod:`skillevaluator.tier3.harbor.baseline_timeouts`); it+ needs both arms run in this collection (no reused baseline) and dimension+ grading, and ``launch_errors`` must be the runner's launch errors so the+ run-level rule can account for them."""if skip_baseline and skip_with_skill:raise ValueError("skip_baseline and skip_with_skill are mutually exclusive (no arm would run)")@@ -7144,6 +7505,17 @@ def collect_harbor_results(}_prepare_generated_outputs(output_dir, agents)+ # A reused baseline did not run here, so it has no timeouts to judge.+ tolerance_on = (+ tolerate_baseline_timeouts+ and not skip_baseline+ and not skip_with_skill+ and reused_baseline_dir is None+ and grading_mode != "custom_only"+ )+ tolerance_candidates: dict[str, list[dict[str, Any]]] = {}+ tolerance_records: dict[str, dict[str, Any]] = {}+ tolerance_rejected: dict[str, str] = {}for agent in agents:with_expected_trials, with_expected_case_ids, with_expected_cases, with_expected_attempts = budget_expectations(@@ -7405,6 +7777,8 @@ def collect_harbor_results(without_summary: dict[str, Any] | None = Nonewithout_not_applicable: list[str] = []without_job_dir: Path | None = None+ without_slots: dict[str, dict[str, Any]] = {}+ without_identity: dict[str, Any] = {}if not skip_baseline:without_job_name = f"{skill_name}-{agent}-without"without_job_dir = (@@ -7434,6 +7808,7 @@ def collect_harbor_results(if case_id_by_task_selector is Noneelse None)+ without_identity = {"arm_suffix": without_arm_suffix, "task_entry_id_map": without_task_entry_ids}without_collected_rewards = (_extract_rewards(without_job_dir,@@ -7500,6 +7875,7 @@ def collect_harbor_results(reward_failures=without_trial_failures,stop_on_pass=stop_on_pass,pass_threshold=pass_threshold,+ attempt_slots=without_slots if tolerance_on else None,expected_attempts_by_case=without_expected_attempts,)if without_policy == "mixed-score-policies":@@ -7903,6 +8279,87 @@ def collect_harbor_results(},"output_dir": str(agent_dir.resolve()),}+ if (+ tolerance_on+ and without_job_dir is not None+ and with_execution.get("execution_status") == "succeeded"+ and without_execution.get("execution_status") == "failed"+ and _job_has_unrecovered_agent_timeout(without_job_dir, without_recovered)+ ):+ with_recovered_names = {item["trial"] for item in with_recovered}+ tolerance_failures: list[dict[str, Any]] = []+ tolerance_code = _with_skill_tolerance_rejection(+ with_execution,+ policy=with_policy,+ job_failure="" if with_job_recovered else with_job_failure,+ runtime_failures=[row for row in with_runtime_failures if row["trial"] not in with_recovered_names],+ trial_failures=with_active_trial_failures,+ )+ if tolerance_code is None and without_policy == "mixed-score-policies":+ tolerance_code = "unbound_error"+ if tolerance_code is None:+ # Attempts a run budget never admitted are not expected, as in the summary.+ residual = _condition_execution_summary(+ without_rewards,+ expected_case_ids=without_expected_case_ids,+ expected_cases=without_expected_cases,+ n_attempts=n_attempts,+ job_failure="",+ recovered_attempts=without_recovered,+ stop_on_pass=stop_on_pass,+ pass_threshold=pass_threshold,+ expected_attempts_by_case=without_expected_attempts,+ )+ tolerance_failures, tolerance_code = _baseline_timeout_failures(+ job_dir=without_job_dir,+ rewards=without_rewards,+ execution=without_execution,+ slots=without_slots,+ residual_errors=(+ residual["execution_errors"]+ if not residual["execution_error_details_truncated"]+ else ["truncated residual errors"]+ ),+ job_failure="" if without_job_recovered else without_job_failure,+ runtime_failures=without_runtime_failures,+ trial_failures=without_trial_failures,+ recovered=without_recovered,+ expected_case_ids=without_expected_case_ids,+ case_id_by_task_selector=case_id_by_task_selector,+ arm_suffix=str(without_identity.get("arm_suffix") or ""),+ task_entry_id_map=without_identity.get("task_entry_id_map"),+ )+ if tolerance_code is not None:+ tolerance_rejected[agent] = tolerance_code+ logger.debug("Baseline timeouts not tolerated for %s: %s", agent, tolerance_code)+ else:+ timeouts = {failure["timeout_seconds"] for failure in tolerance_failures}+ tolerance_candidates[agent] = tolerance_failures+ tolerance_records[agent] = baseline_timeouts.build_record(+ expected_attempts=without_execution["expected_attempts"],+ scored_attempts=without_execution["scored_attempts"],+ failures=tolerance_failures,+ timeout_seconds=next(iter(timeouts)) if len(timeouts) == 1 else None,+ )++ if tolerance_on:+ tolerated, rejected, explained = baseline_timeouts.select_tolerated(+ all_results["agents"], tolerance_candidates, tolerance_rejected, launch_errors+ )+ tolerance_warnings: list[str] = []+ for agent in sorted(tolerated):+ baseline_timeouts.settle(all_results["agents"][agent], tolerance_records[agent])+ # Reports reload agents from disk, so the decision travels with the arms.+ _write_generated_root_json(+ output_dir / agent / baseline_timeouts.RECORD_ARTIFACT, output_dir, tolerance_records[agent]+ )+ tolerance_warnings.append(baseline_timeouts.tolerance_warning(agent, tolerance_records[agent]))+ for agent, code in sorted(rejected.items()):+ all_results["agents"][agent][baseline_timeouts.REJECTION_KEY] = code+ tolerance_warnings.append(baseline_timeouts.rejection_warning(agent, code))+ all_results[baseline_timeouts.RUN_KEY] = baseline_timeouts.run_record(tolerated, explained)+ if tolerance_warnings:+ all_results.setdefault("warnings", []).extend(tolerance_warnings)# A baseline-only run scores only the without-skill arm.scored_arm = "without_skill" if skip_with_skill else "with_skill"diff --git a/src/skillevaluator/tier3/harbor/report.py b/src/skillevaluator/tier3/harbor/report.pyindex 1ed089c7..72e7fc82 100644--- a/src/skillevaluator/tier3/harbor/report.py+++ b/src/skillevaluator/tier3/harbor/report.py@@ -128,17 +128,25 @@ def _pick_best_agent() -> str:"""Select the same best agent identity as the canonical Tier 3 report."""from skillevaluator.evaluation.tier3_report import _canonical_agent_rank_from_info-- best_agent = ""- best_rank: tuple[float, float] | None = None+ from skillevaluator.tier3.harbor.baseline_timeouts import kept_with_failed_baseline++ # Keyed by whether the agent was kept with a failed baseline, which the+ # canonical report ranks below every agent with a complete baseline.+ best: dict[bool, tuple[tuple[float, float], str]] = {}+ # Agents skipped here that were not kept with a failed baseline, for+ # example a complete agent that never activated the skill. The canonical+ # report ranks any of them it can rank above every tolerated agent, so a+ # tolerated agent must not stand in for them.+ skipped_complete: list[dict[str, Any]] = []scored_metric_sets: set[frozenset[str]] = set()for agent in sorted(agents_data):data = agents_data[agent]- if not _findings_eligible(data):- continuepersisted = persisted_agents.get(agent) if isinstance(persisted_agents, dict) else Noneranking_data = persisted if isinstance(persisted, dict) else data- if not _findings_eligible(ranking_data):+ tolerated = kept_with_failed_baseline(ranking_data)+ if not _findings_eligible(data) or not _findings_eligible(ranking_data):+ if not tolerated:+ skipped_complete.append(ranking_data)continuestandard_metrics = report_data.metrics_for_condition(ranking_data, "with_skill")with_scores = ranking_data.get("with_skill")@@ -146,6 +154,8 @@ def _pick_best_agent(not isinstance(with_scores, dict)or any(metric_value(with_scores, metric) is None for metric in standard_metrics)):+ if not tolerated:+ skipped_complete.append(ranking_data)continuerank = _canonical_agent_rank_from_info(ranking_data)if rank is None:@@ -156,10 +166,30 @@ def _pick_best_agent(scored_metric_sets.add(frozenset(standard_metrics))if len(scored_metric_sets) > 1:return ""- if best_rank is None or rank > best_rank:- best_rank = rank- best_agent = agent- return best_agent+ if tolerated not in best or rank > best[tolerated][0]:+ best[tolerated] = (rank, agent)+ if False in best:+ return best[False][1]+ # Like the canonical report, rank every complete agent before any tolerated+ # one. When the canonical best agent is a complete agent skipped here,+ # there are no findings to show.+ if True not in best or any(_canonical_agent_rank_from_info(data) is not None for data in skipped_complete):+ return ""+ return best[True][1]+++def _kept_with_failed_baseline(+ agent: str,+ agents_data: dict[str, dict[str, Any]],+ persisted_agents: dict[str, dict[str, Any]] | None,+) -> bool:+ """Return whether the in-memory or persisted data of ``agent`` keeps it with a failed baseline."""+ from skillevaluator.tier3.harbor.baseline_timeouts import kept_with_failed_baseline++ persisted = persisted_agents.get(agent) if isinstance(persisted_agents, dict) else None+ return any(+ isinstance(data, dict) and kept_with_failed_baseline(data) for data in (agents_data.get(agent), persisted)+ )def _findings_eligible(agent_data: dict[str, Any]) -> bool:@@ -1240,6 +1270,17 @@ def display_findings_report(console.print()else:best_agent = harbor_agents[0] if harbor_agents else ""+ # The terminal summary drops never-activated agents before it calls+ # here, so an agent kept with a failed baseline can be the only one+ # left. Rank it against every agent, as the canonical report does, so+ # it never stands in for a complete agent ranked above it.+ if (+ best_agent+ and len(agents_data) > 1+ and _kept_with_failed_baseline(best_agent, agents_data, loaded_agents)+ and _pick_best_agent(agents_data, loaded_agents) != best_agent+ ):+ best_agent = ""if (not best_agentdiff --git a/src/skillevaluator/tier3/harbor/report_data.py b/src/skillevaluator/tier3/harbor/report_data.pyindex ea84d92f..902691dd 100644--- a/src/skillevaluator/tier3/harbor/report_data.py+++ b/src/skillevaluator/tier3/harbor/report_data.py@@ -22,6 +22,7 @@ from pathlib import Pathfrom typing import Anyfrom skillevaluator.tier3.eval_core.checks import resolve_should_trigger+from skillevaluator.tier3.harbor import baseline_timeoutsfrom skillevaluator.tier3.harbor.metrics import (CUSTOM_ONLY_METRIC_SET,DEFAULT_METRIC_SET,@@ -654,6 +655,33 @@ def _trajectory_token_counter(value: Any) -> int | None:)+def _matching_baseline_tolerance(record: Any, conditions: dict[str, dict[str, Any]]) -> dict[str, Any] | None:+ """Return an agent's baseline-timeout record when it still matches the on-disk arms.++ The collector writes the record only for an agent it kept scored on its+ with-skill arm under ``--tolerate-baseline-timeouts``. It is honored only+ while the with-skill arm succeeded with every attempt scored and no errors,+ and the baseline failed with exactly the recorded attempt counts; anything+ else keeps the agent failed.+ """+ if not isinstance(record, dict):+ return None+ with_skill = conditions.get("with_skill") or {}+ baseline = conditions.get("without_skill") or {}+ expected, scored = record.get("expected_attempts"), record.get("scored_attempts")+ matches = (+ with_skill.get("execution_status") == "succeeded"+ and not with_skill.get("execution_errors")+ and 0 < with_skill.get("expected_attempts", 0) == with_skill.get("scored_attempts")+ and baseline.get("execution_status") == "failed"+ and type(expected) is int+ and type(scored) is int+ and 0 <= scored < expected+ and (baseline.get("expected_attempts"), baseline.get("scored_attempts")) == (expected, scored)+ )+ return dict(record) if matches else None++def _condition_status(agent_info: dict[str, Any], condition: str) -> str:conditions = agent_info.get("conditions")data = conditions.get(condition) if isinstance(conditions, dict) else None@@ -826,6 +854,13 @@ def load_agent_data(if custom_lift is not _INVALID_JSON:agent_info["custom_lift"] = custom_lift if isinstance(custom_lift, dict) else {}+ tolerance_record: Any = None+ tolerance_file = agent_dir / baseline_timeouts.RECORD_ARTIFACT+ if tolerance_file.exists():+ tolerance_record = _load_bounded_json(+ tolerance_file, agent_diagnostics, artifact="baseline_timeout_tolerance"+ )+for variant_key, variant_dir_name in (("rewards", "with-skill"), ("rewards_baseline", "without-skill")):trial_list: list[dict[str, Any]] = []count_key = "num_trials" if variant_key == "rewards" else "num_trials_baseline"@@ -933,24 +968,30 @@ def load_agent_data(agent_info["skill_activation"] = activationactive_conditions = list(condition_execution.values())+ tolerance = _matching_baseline_tolerance(tolerance_record, condition_execution)+ # A tolerated agent's status and errors follow its with-skill arm; the+ # attempt totals below still count both conditions.+ status_conditions = active_conditions if tolerance is None else [condition_execution["with_skill"]]execution_errors = [- error for condition in active_conditions for error in condition.get("execution_errors", []) if error+ error for condition in status_conditions for error in condition.get("execution_errors", []) if error]- if not active_conditions or any(- condition.get("execution_status") in {"failed", "unknown"} for condition in active_conditions+ if not status_conditions or any(+ condition.get("execution_status") in {"failed", "unknown"} for condition in status_conditions):execution_status = "failed" if execution_errors else "unknown"- elif all(condition.get("execution_status") == "skipped" for condition in active_conditions):+ elif all(condition.get("execution_status") == "skipped" for condition in status_conditions):execution_status = "skipped"else:execution_status = "succeeded"public_execution_errors = list(dict.fromkeys(execution_errors))+ if tolerance is not None:+ agent_info[baseline_timeouts.RECORD_KEY] = toleranceagent_info.update({"conditions": condition_execution,"execution_status": execution_status,"execution_errors": public_execution_errors,- **aggregate_execution_error_details(active_conditions, len(public_execution_errors)),+ **aggregate_execution_error_details(status_conditions, len(public_execution_errors)),"expected_attempts": sum(_nonnegative_counter(condition.get("expected_attempts")) for condition in active_conditions),diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.pyindex 8113217a..81767012 100644--- a/src/skillevaluator/tier3/harbor/runner.py+++ b/src/skillevaluator/tier3/harbor/runner.py@@ -92,6 +92,7 @@ from skillevaluator.tier3.harbor import (HERMES_VERSION,LOCAL_CODEX_HOME_DIRNAME,LOCAL_CODEX_SECRETS_DIRNAME,+ baseline_timeouts,)from skillevaluator.tier3.harbor.adapter import (_RUNTIME_PROCESS_CONTROL_ENV_NAMES,@@ -5369,6 +5370,7 @@ def _run_harbor_eval_impl(output_dir: Path | None = None,keep_harbor_jobs: bool = False,agent_runtime_preflight: bool | None = None,+ tolerate_baseline_timeouts: bool | None = None,env_mode: str = DEFAULT_ENV_MODE,env_mode_source: str = "CLI",environment_kwargs: Mapping[str, Any] | None = None,@@ -5497,6 +5499,11 @@ def _run_harbor_eval_impl(if agent_runtime_preflight is not Noneelse harbor_config.get("agent_runtime_preflight", False))+ tolerate_baseline_timeouts = bool(+ tolerate_baseline_timeouts+ if tolerate_baseline_timeouts is not None+ else harbor_config.get("tolerate_baseline_timeouts", False)+ )grading_mode = grading_mode or grading_config.get("mode", "default")workspace_mode = skill_workspace_mode or workspace_config.get("mode", "isolated")dockerfile_mode = custom_dockerfile_mode or harbor_config.get("custom_dockerfile_mode", "rebase")@@ -5914,6 +5921,8 @@ def _run_harbor_eval_impl(# source tree that was evaluated, not the evaluator build that ran it."evaluated_source": normalized_evaluated_source(evaluated_source),}+ if tolerate_baseline_timeouts:+ run_config["harbor"]["tolerate_baseline_timeouts"] = Trueif max_cases is not None:run_config["harbor"]["max_cases"] = max_casesverifier_env = {**configured_runtime_env, **provider_env}@@ -6687,6 +6696,7 @@ def _run_harbor_eval_impl(agent_models=model_resolution,launch_errors=errors,grading_mode=grading_mode,+ tolerate_baseline_timeouts=tolerate_baseline_timeouts,budget_not_run=active_budget.not_run if active_budget is not None else [],)except Exception:@@ -6808,6 +6818,9 @@ def _run_harbor_eval_impl(keep_requested=keep_harbor_jobs,result=results,)+ # A tolerated baseline's own launch errors are its timeouts, already on its+ # baseline condition; every other launch error still fails the run.+ errors = baseline_timeouts.unexplained_launch_errors(results, errors)if errors:_merge_launch_execution_errors(results, errors)if prior_version is not None:diff --git a/src/skillevaluator/tier3/workflow.py b/src/skillevaluator/tier3/workflow.pyindex 4e1296ef..b8cffd80 100644--- a/src/skillevaluator/tier3/workflow.py+++ b/src/skillevaluator/tier3/workflow.py@@ -142,6 +142,7 @@ def _preflight_options(skill_path: Path, params: dict[str, Any]) -> dict[str, An"price_file","timeout_multiplier","agent_runtime_preflight",+ "tolerate_baseline_timeouts","custom_dockerfile_mode",):if params.get(name) is not None:diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.jsonindex 5864a331..caa92709 100644--- a/tests/golden/cli_surface.json+++ b/tests/golden/cli_surface.json@@ -1141,6 +1141,18 @@],"type": "boolean"},+ {+ "is_flag": true,+ "name": "tolerate_baseline_timeouts",+ "opts": [+ "--tolerate-baseline-timeouts"+ ],+ "param_type": "option",+ "secondary_opts": [+ "--no-tolerate-baseline-timeouts"+ ],+ "type": "boolean"+ },{"name": "timeout_multiplier","opts": [@@ -3342,6 +3354,18 @@],"type": "boolean"},+ {+ "is_flag": true,+ "name": "tolerate_baseline_timeouts",+ "opts": [+ "--tolerate-baseline-timeouts"+ ],+ "param_type": "option",+ "secondary_opts": [+ "--no-tolerate-baseline-timeouts"+ ],+ "type": "boolean"+ },{"name": "timeout_multiplier","opts": [@@ -4293,6 +4317,18 @@],"type": "boolean"},+ {+ "is_flag": true,+ "name": "tolerate_baseline_timeouts",+ "opts": [+ "--tolerate-baseline-timeouts"+ ],+ "param_type": "option",+ "secondary_opts": [+ "--no-tolerate-baseline-timeouts"+ ],+ "type": "boolean"+ },{"name": "timeout_multiplier","opts": [@@ -4886,6 +4922,18 @@],"type": "boolean"},+ {+ "is_flag": true,+ "name": "tolerate_baseline_timeouts",+ "opts": [+ "--tolerate-baseline-timeouts"+ ],+ "param_type": "option",+ "secondary_opts": [+ "--no-tolerate-baseline-timeouts"+ ],+ "type": "boolean"+ },{"name": "evaluated_source_repository","opts": [diff --git a/tests/tier3/test_baseline_timeouts.py b/tests/tier3/test_baseline_timeouts.pynew file mode 100644index 00000000..386e356d--- /dev/null+++ b/tests/tier3/test_baseline_timeouts.py@@ -0,0 +1,1486 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Opt-in tolerance for baseline-only agent timeouts (``--tolerate-baseline-timeouts``).++The collector runs on synthetic Harbor jobs: arm-level jobs as Harbor writes+them, and stop-on-pass attempt jobs merged by the runner. The default stays+off, so a baseline timeout still fails the agent and the run unless a user+opts in.+"""++from __future__ import annotations++import json+from datetime import UTC, datetime, timedelta+from pathlib import Path+from typing import Any+from uuid import uuid4++import pytest+from click.testing import CliRunner++from skillevaluator.tier3.harbor import baseline_timeouts+from skillevaluator.tier3.harbor.baseline_timeouts import (+ RECORD_KEY,+ REJECTION_KEY,+ RUN_KEY,+ build_record,+ check_failures,+ run_record,+ select_tolerated,+ settle,+ unexplained_launch_errors,+)+from skillevaluator.tier3.harbor.collector import collect_harbor_results++SKILL = "demo"+CASES = ["case-001", "case-002"]+SCORES = {+ "security": 1.0,+ "skill_execution": 1.0,+ "skill_efficiency": 0.9,+ "accuracy": 0.9,+ "goal_accuracy": 0.8,+ "behavior_check": 1.0,+}+TIMEOUT = "Agent execution timed out after 1200.0 seconds"+CLEAN_LOG = json.dumps({"type": "assistant", "message": "Reading the configuration"}) + "\n"+LAUNCH_ERROR = "{agent} without-skill Harbor run failed: Harbor job did not complete successfully: {count} errored"+# The runner's message when it kills a Harbor job that outlived the Google ADC token on GKE.+ADC_LAUNCH_ERROR = (+ "opencode without-skill Harbor run failed: Harbor job exceeded Google ADC token lifetime (3300s) in gke mode"+)+++# -- synthetic arm-level Harbor jobs ------------------------------------------+++def _write_json(path: Path, data: Any) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(data), encoding="utf-8")+++def _trial_result(name: str, case: str, **fields: Any) -> dict[str, Any]:+ return {+ "trial_name": name,+ "task_name": case,+ "task_id": {"path": f"/tasks/{case}"},+ "config": {"task": {"path": f"/tasks/{case}"}},+ "started_at": "2026-11-01T00:00:00+00:00",+ "finished_at": "2026-11-01T00:20:00+00:00",+ "exception_info": None,+ **fields,+ }+++def _activation(activated: bool) -> dict[str, Any]:+ """Reward details recording whether the with-skill agent activated the skill."""+ score = 1.0 if activated else 0.0+ return {"skill_execution": {"activation": {"supported": True, "score": score, "passed": activated}}}+++def _scored_trial(+ job: Path, name: str, case: str, scores: dict[str, float] | None = None, details: dict[str, Any] | None = None+) -> None:+ scores = scores or SCORES+ reward = {**scores, "entry_id": case, **({"details": details} if details is not None else {})}+ _write_json(job / name / "verifier" / "reward.json", reward)+ _write_json(+ job / name / "result.json",+ _trial_result(name, case, agent_result={"n_output_tokens": 500}, verifier_result={"rewards": scores}),+ )+++def _failed_trial(+ job: Path,+ name: str,+ case: str,+ *,+ exception_type: str = "AgentTimeoutError",+ output_tokens: int | None = 321,+ log: str | None = CLEAN_LOG,+ log_name: str = "opencode.txt",+) -> None:+ trial = job / name+ _write_json(+ trial / "result.json",+ _trial_result(+ name,+ case,+ agent_result={"n_output_tokens": output_tokens} if output_tokens is not None else None,+ exception_info={"exception_type": exception_type, "exception_message": TIMEOUT},+ ),+ )+ (trial / "exception.txt").write_text(f"{exception_type}: {TIMEOUT}\n", encoding="utf-8")+ if log is not None:+ (trial / "agent").mkdir(parents=True, exist_ok=True)+ (trial / "agent" / log_name).write_text(log, encoding="utf-8")+++def _job_result(job: Path, *, errored: int) -> None:+ trials = sorted(path.name for path in job.iterdir() if path.is_dir())+ if errored:+ stats: dict[str, Any] = {+ "n_completed_trials": len(trials),+ "n_errored_trials": errored,+ "n_running_trials": 0,+ "n_pending_trials": 0,+ "n_cancelled_trials": 0,+ "n_retries": 0,+ "evals": {},+ }+ else:+ stats = {+ "n_trials": len(trials),+ "n_errors": 0,+ "evals": {+ "agent__model": {"n_trials": len(trials), "n_errors": 0, "reward_stats": {"reward": {"0.9": trials}}}+ },+ }+ _write_json(job / "result.json", {"n_total_trials": len(trials), "stats": stats})+++def _arm(+ jobs: Path,+ agent: str,+ variant: str,+ outcomes: list[tuple[str, str]],+ *,+ scores: dict[str, float] | None = None,+ details: dict[str, Any] | None = None,+ **failed: Any,+) -> None:+ """Write one arm-level job; each outcome is ``(case, "scored" | "timeout")``."""+ job = jobs / f"{SKILL}-{agent}-{variant}"+ job.mkdir(parents=True, exist_ok=True)+ errored = 0+ for index, (case, outcome) in enumerate(outcomes):+ name = f"{case}__{variant}{index}"+ if outcome == "scored":+ _scored_trial(job, name, case, scores, details)+ else:+ _failed_trial(job, name, case, **failed)+ errored += 1+ _job_result(job, errored=errored)+++def _two_agent_jobs(jobs: Path, *, peer_with: str = "scored", **failed: Any) -> list[str]:+ """opencode's baseline times out on case-002; codex completes both arms. Returns launch errors."""+ _arm(jobs, "opencode", "with", [(case, "scored") for case in CASES])+ _arm(jobs, "opencode", "without", [("case-001", "scored"), ("case-002", "timeout")], **failed)+ _arm(jobs, "codex", "with", [("case-001", "scored"), ("case-002", peer_with)])+ _arm(jobs, "codex", "without", [(case, "scored") for case in CASES])+ errors = [LAUNCH_ERROR.format(agent="opencode", count=1)]+ if peer_with != "scored":+ errors.append("codex with-skill Harbor run failed: Harbor job did not complete successfully: 1 errored")+ return errors+++def _collect(tmp_path: Path, launch_errors: list[str], *, agents: list[str] | None = None, **kwargs: Any):+ kwargs.setdefault("tolerate_baseline_timeouts", True)+ return collect_harbor_results(+ skill_name=SKILL,+ agents=agents or ["opencode", "codex"],+ output_dir=tmp_path / "results",+ jobs_dir=tmp_path / "jobs",+ n_attempts=1,+ expected_cases=len(CASES),+ expected_case_ids=CASES,+ case_id_by_task_selector={case: case for case in CASES},+ expected_trials=len(CASES),+ launch_errors=launch_errors,+ **kwargs,+ )+++# -- collector ------------------------------------------------------------------+++def test_baseline_timeout_still_fails_the_agent_and_run_by_default(tmp_path: Path) -> None:+ launch_errors = _two_agent_jobs(tmp_path / "jobs")++ results = _collect(tmp_path, launch_errors, tolerate_baseline_timeouts=False)++ opencode = results["agents"]["opencode"]+ assert results["execution_status"] == "failed"+ assert opencode["execution_status"] == "failed"+ assert opencode["conditions"]["with_skill"]["execution_status"] == "succeeded"+ assert RECORD_KEY not in opencode+ assert REJECTION_KEY not in opencode+ assert RUN_KEY not in results+ assert "warnings" not in results+++def test_tolerated_agent_stays_scored_on_its_with_skill_arm(tmp_path: Path) -> None:+ launch_errors = _two_agent_jobs(tmp_path / "jobs")++ results = _collect(tmp_path, launch_errors)++ opencode = results["agents"]["opencode"]+ assert results["execution_status"] == "succeeded"+ assert results["execution_errors"] == []+ assert "error" not in results+ assert opencode["execution_status"] == "succeeded"+ assert opencode["execution_errors"] == []+ assert opencode["overall_with_skill"] is not None+ # The baseline stays honest: failed, with its errors, and never scored or compared.+ baseline = opencode["conditions"]["without_skill"]+ assert baseline["execution_status"] == "failed"+ assert (baseline["scored_attempts"], baseline["expected_attempts"]) == (1, 2)+ assert "Scored attempt coverage is 1/2" in baseline["execution_errors"]+ assert opencode["without_skill"] == {}+ assert opencode["overall_without_skill"] is None+ assert opencode["lift"] == {}+ assert opencode["pass_at_k"]["lift"] == {}+ assert opencode["security_attribution"] == {}+ assert (opencode["expected_attempts"], opencode["scored_attempts"]) == (4, 3)+ assert results["comparison"]["metrics"]["accuracy"]["opencode"]["without_skill"] is None+ assert results["comparison"]["metrics"]["accuracy"]["opencode"]["lift"] is None+ assert opencode[RECORD_KEY] == {+ "status": "partial",+ "reason": "agent_execution_timeout",+ "exception_type": "AgentTimeoutError",+ "expected_attempts": 2,+ "scored_attempts": 1,+ "failed_attempts": 1,+ "timeout_seconds": 1200.0,+ "failures": [{"trial": "case-002__without1", "case_id": "case-002", "attempt": None, "output_tokens": 321}],+ "failures_truncated": False,+ }+ assert results[RUN_KEY] == {+ "tolerated_agents": ["opencode"],+ "explained_launch_errors": launch_errors,+ "explained_launch_errors_total": 1,+ "explained_launch_errors_truncated": False,+ }+ assert results["warnings"] == [+ "opencode baseline incomplete: 1 attempt(s) hit the agent execution timeout after 1200 seconds "+ "(1 of 2 scored). The agent stays scored on its with-skill arm (--tolerate-baseline-timeouts); its "+ "baseline and uplift are not reported, and the run is not complete publication evidence."+ ]+ assert results["agents"]["codex"]["execution_status"] == "succeeded"+ assert results["agents"]["codex"]["lift"]+++def test_reports_reload_the_tolerated_agent_from_disk(tmp_path: Path) -> None:+ from skillevaluator.evaluation.tier3_report import build_agent_eval_payload+ from skillevaluator.reporting.base import (+ _agent_eval_attempt_coverage_complete,+ agent_eval_publication_evidence_complete,+ )+ from skillevaluator.tier3.harbor.report_data import load_agent_data++ _collect(tmp_path, _two_agent_jobs(tmp_path / "jobs"))+ record_file = tmp_path / "results" / "opencode" / baseline_timeouts.RECORD_ARTIFACT++ agents = load_agent_data(tmp_path / "results")+ assert agents["opencode"]["execution_status"] == "succeeded"+ assert agents["opencode"]["execution_errors"] == []+ assert agents["opencode"]["conditions"]["without_skill"]["execution_status"] == "failed"+ assert agents["opencode"][RECORD_KEY]["failed_attempts"] == 1+ payload = build_agent_eval_payload(+ SKILL,+ agents,+ attempt_policy={"max_attempts": 1, "pass_threshold": 0.5, "stop_on_pass": False},+ use_llm_judge=False,+ )+ assert payload is not None+ assert payload["execution_status"] == "succeeded"+ assert payload["overall_score"] is not None+ assert payload["agents"]["opencode"]["baseline"] is None+ assert payload["agents"]["opencode"]["lift"] is None+ # The missing baseline attempts still keep the run out of publication evidence+ # and short of the attempt coverage a blocking Tier 3 gate requires.+ assert agent_eval_publication_evidence_complete(payload) is False+ assert _agent_eval_attempt_coverage_complete(payload, require_baseline=False) is False++ # A record that no longer matches the baseline arm on disk is ignored.+ record = json.loads(record_file.read_text(encoding="utf-8"))+ record_file.write_text(json.dumps({**record, "scored_attempts": 0}), encoding="utf-8")+ assert load_agent_data(tmp_path / "results")["opencode"]["execution_status"] == "failed"++ # A rerun without the option removes the stale record.+ _collect(tmp_path, _two_agent_jobs(tmp_path / "jobs"), tolerate_baseline_timeouts=False)+ assert not record_file.exists()+ assert load_agent_data(tmp_path / "results")["opencode"]["execution_status"] == "failed"++[email protected]("source", ["harbor_result", "trajectory"])+def test_oversized_completion_counter_rejects_tolerance_without_aborting_collection(+ tmp_path: Path, source: str+) -> None:+ huge_count = 10**400+ launch_errors = _two_agent_jobs(tmp_path / "jobs", output_tokens=huge_count if source == "harbor_result" else None)+ if source == "trajectory":+ trial = tmp_path / "jobs" / f"{SKILL}-opencode-without" / "case-002__without1"+ _write_json(+ trial / "agent" / "trajectory.json",+ {"steps": [], "final_metrics": {"total_completion_tokens": huge_count}},+ )++ results = _collect(tmp_path, launch_errors)++ assert results["execution_status"] == "failed"+ assert RECORD_KEY not in results["agents"]["opencode"]+ assert results["agents"]["opencode"][REJECTION_KEY] == "no_progress_evidence"+++def test_trajectory_completion_tokens_prove_progress(tmp_path: Path) -> None:+ launch_errors = _two_agent_jobs(tmp_path / "jobs", output_tokens=None)+ trial = tmp_path / "jobs" / f"{SKILL}-opencode-without" / "case-002__without1"+ _write_json(trial / "agent" / "trajectory.json", {"steps": [], "final_metrics": {"total_completion_tokens": 42}})++ results = _collect(tmp_path, launch_errors)++ assert results["execution_status"] == "succeeded"+ assert results["agents"]["opencode"][RECORD_KEY]["failures"][0]["output_tokens"] == 42+++ ("failed", "code"),+ [+ ({"output_tokens": None}, "no_progress_evidence"),+ ({"output_tokens": 0}, "no_progress_evidence"),+ ({"log": None}, "no_agent_log"),+ (+ {"log": CLEAN_LOG + '{"type":"error","error":{"type":"rate_limit_error"}}\n'},+ "provider_degradation_observed",+ ),+ (+ {"log": CLEAN_LOG + '{"type":"system","subtype":"api_retry","error_status":529}\n'},+ "provider_degradation_observed",+ ),+ ({"log": CLEAN_LOG + "unexpected status: 429 Too Many Requests\n"}, "provider_degradation_observed"),+ # OpenAI-compatible providers through the OpenAI SDK, and OpenCode's APIError.+ (+ {+ "log": CLEAN_LOG + "Error code: 429 - {'status': 429, 'title': 'Too Many Requests', "+ "'detail': 'Rate limit exceeded'}\n"+ },+ "provider_degradation_observed",+ ),+ (+ {+ "log": CLEAN_LOG + '{"type":"error","error":{"name":"APIError","data":'+ '{"message":"Too Many Requests","statusCode":429}}}\n'+ },+ "provider_degradation_observed",+ ),+ ({"log": CLEAN_LOG + "429 Too Many Requests\n"}, "provider_degradation_observed"),+ ({"log": CLEAN_LOG + '{"error":{"code":"insufficient_quota"}}\n'}, "provider_degradation_observed"),+ ({"log": CLEAN_LOG + '{"error":{"status":"RESOURCE_EXHAUSTED"}}\n'}, "provider_degradation_observed"),+ ({"log": CLEAN_LOG + "API Error: 529 Overloaded\n"}, "agent_runtime_failure"),+ ({"log": CLEAN_LOG + "Error: invalid_api_key\n"}, "agent_runtime_failure"),+ ],+)+def test_untrusted_baseline_timeouts_keep_the_agent_failed(tmp_path: Path, failed: dict[str, Any], code: str) -> None:+ launch_errors = _two_agent_jobs(tmp_path / "jobs", **failed)++ results = _collect(tmp_path, launch_errors)++ opencode = results["agents"]["opencode"]+ assert results["execution_status"] == "failed"+ assert opencode["execution_status"] == "failed"+ assert RECORD_KEY not in opencode+ assert opencode[REJECTION_KEY] == code+ assert results[RUN_KEY] == run_record((), [])+ assert results["warnings"] == [+ f"opencode baseline timeouts were not tolerated: {baseline_timeouts.REJECTION_REASONS[code]} ({code})."+ ]++[email protected]("exception_type", ["VerifierTimeoutError", "NonZeroAgentExitCodeError"])+def test_baseline_without_an_agent_timeout_is_left_as_on_main(tmp_path: Path, exception_type: str) -> None:+ launch_errors = _two_agent_jobs(tmp_path / "jobs", exception_type=exception_type)++ results = _collect(tmp_path, launch_errors)++ # No attempt timed out, so the option has nothing to judge: no rejection+ # code or warning names a timeout that never happened.+ opencode = results["agents"]["opencode"]+ assert results["execution_status"] == "failed"+ assert opencode["execution_status"] == "failed"+ assert RECORD_KEY not in opencode+ assert REJECTION_KEY not in opencode+ assert "warnings" not in results+ assert results[RUN_KEY] == run_record((), [])+++def test_another_baseline_failure_beside_a_timeout_is_refused(tmp_path: Path) -> None:+ jobs = tmp_path / "jobs"+ _arm(jobs, "opencode", "with", [(case, "scored") for case in CASES])+ _arm(jobs, "opencode", "without", [(case, "timeout") for case in CASES])+ # case-001 failed another way; case-002 still timed out.+ job = jobs / f"{SKILL}-opencode-without"+ _failed_trial(job, "case-001__without0", "case-001", exception_type="NonZeroAgentExitCodeError")+ _arm(jobs, "codex", "with", [(case, "scored") for case in CASES])+ _arm(jobs, "codex", "without", [(case, "scored") for case in CASES])++ results = _collect(tmp_path, [LAUNCH_ERROR.format(agent="opencode", count=2)])++ assert results["agents"]["opencode"][REJECTION_KEY] == "reason_not_tolerated"+ assert results["execution_status"] == "failed"+++ ("killed", "code"),+ [+ # The runner killed Harbor while every attempt still ran: nothing timed out.+ ({"case-001": "cancelled", "case-002": "cancelled"}, None),+ # One attempt timed out, then the kill cancelled the other.+ ({"case-001": "cancelled", "case-002": "timeout"}, "reason_not_tolerated"),+ # One attempt timed out, then the kill left the other without a result.+ ({"case-001": "no_result", "case-002": "timeout"}, "unaccounted_trial"),+ ],+)+def test_baseline_killed_by_the_runner_is_never_tolerated(+ tmp_path: Path, killed: dict[str, str], code: str | None+) -> None:+ jobs = tmp_path / "jobs"+ _arm(jobs, "opencode", "with", [(case, "scored") for case in CASES])+ job = jobs / f"{SKILL}-opencode-without"+ for index, (case, outcome) in enumerate(killed.items()):+ name = f"{case}__without{index}"+ if outcome == "no_result":+ (job / name / "agent").mkdir(parents=True)+ (job / name / "agent" / "opencode.txt").write_text(CLEAN_LOG, encoding="utf-8")+ else:+ exception_type = "CancelledError" if outcome == "cancelled" else "AgentTimeoutError"+ _failed_trial(job, name, case, exception_type=exception_type)+ _job_result(job, errored=sum(outcome != "no_result" for outcome in killed.values()))+ _arm(jobs, "codex", "with", [(case, "scored") for case in CASES])+ _arm(jobs, "codex", "without", [(case, "scored") for case in CASES])++ results = _collect(tmp_path, [ADC_LAUNCH_ERROR])++ opencode = results["agents"]["opencode"]+ assert results["execution_status"] == "failed"+ assert opencode["execution_status"] == "failed"+ assert RECORD_KEY not in opencode+ assert opencode.get(REJECTION_KEY) == code+ assert results[RUN_KEY]["explained_launch_errors"] == []+++def _multi_step_timeout_trial(job: Path, name: str, case: str) -> None:+ """Write a native multi-step trial as Harbor 0.24 records a step's agent timeout.++ ``MultiStepTrial._run_step_agent`` stores the exception on the step only,+ so the trial has no root exception and Harbor counts it as completed.+ """+ from harbor.models.trial.result import TrialResult++ trial = job / name+ finish = datetime(2026, 11, 1, 0, 20, tzinfo=UTC)+ result = TrialResult.model_validate(+ {+ "id": uuid4(),+ "task_name": case,+ "trial_name": name,+ "trial_uri": trial.as_uri(),+ "task_id": {"path": f"/tasks/{case}"},+ "task_checksum": "public-tolerance-example",+ "config": {"task": {"path": f"/tasks/{case}"}, "trial_name": name, "trials_dir": str(job)},+ "agent_info": {"name": "opencode", "version": "test", "model_info": {"name": "test-model"}},+ "started_at": finish - timedelta(minutes=20),+ "finished_at": finish,+ "exception_info": None,+ "step_results": [+ {+ "step_name": "build",+ "agent_result": {"n_output_tokens": 321},+ "exception_info": {+ "exception_type": "AgentTimeoutError",+ "exception_message": TIMEOUT,+ "exception_traceback": "in _run_agent_phase\nraise AgentTimeoutError(...)",+ "occurred_at": finish,+ },+ }+ ],+ }+ )+ trial.mkdir(parents=True)+ (trial / "result.json").write_text(result.model_dump_json(indent=2), encoding="utf-8")+ (trial / "steps" / "build" / "agent").mkdir(parents=True)+ (trial / "steps" / "build" / "agent" / "opencode.txt").write_text(CLEAN_LOG, encoding="utf-8")+++def test_native_multi_step_timeouts_are_refused_by_name(tmp_path: Path) -> None:+ pytest.importorskip("harbor")+ jobs = tmp_path / "jobs"+ _arm(jobs, "opencode", "with", [(case, "scored") for case in CASES])+ _arm(jobs, "opencode", "without", [("case-001", "scored")])+ job = jobs / f"{SKILL}-opencode-without"+ _multi_step_timeout_trial(job, "case-002__without1", "case-002")+ # Harbor counts the trial as completed, so the job reports no errored trial+ # and the runner no launch error.+ _job_result(job, errored=0)+ _arm(jobs, "codex", "with", [(case, "scored") for case in CASES])+ _arm(jobs, "codex", "without", [(case, "scored") for case in CASES])++ results = _collect(tmp_path, [])++ opencode = results["agents"]["opencode"]+ assert results["execution_status"] == "failed"+ assert opencode["execution_status"] == "failed"+ assert (+ f"Agent runtime failed in case-002__without1: AgentTimeoutError: {TIMEOUT}"+ in opencode["conditions"]["without_skill"]["execution_errors"]+ )+ assert RECORD_KEY not in opencode+ assert opencode[REJECTION_KEY] == "step_timeout_not_supported"+ assert results["warnings"] == [+ "opencode baseline timeouts were not tolerated: a baseline attempt timed out in a step of a native "+ "multi-step task, which the option does not cover (step_timeout_not_supported)."+ ]+++def test_trial_that_is_neither_scored_nor_timed_out_is_refused(tmp_path: Path) -> None:+ launch_errors = _two_agent_jobs(tmp_path / "jobs")+ (tmp_path / "jobs" / f"{SKILL}-opencode-without" / "case-002__stray" / "agent").mkdir(parents=True)++ results = _collect(tmp_path, launch_errors)++ assert results["agents"]["opencode"][REJECTION_KEY] == "unaccounted_trial"+ assert results["execution_status"] == "failed"+++def test_errored_count_without_matching_trials_is_refused(tmp_path: Path) -> None:+ _two_agent_jobs(tmp_path / "jobs")+ job = tmp_path / "jobs" / f"{SKILL}-opencode-without"+ # Harbor's statistics claim a second errored trial that no trial accounts for,+ # so the scored trial is not kept either and the arm holds an untyped trial.+ payload = json.loads((job / "result.json").read_text(encoding="utf-8"))+ payload["stats"]["n_errored_trials"] = 2+ (job / "result.json").write_text(json.dumps(payload), encoding="utf-8")++ results = _collect(tmp_path, [LAUNCH_ERROR.format(agent="opencode", count=2)])++ assert results["agents"]["opencode"][REJECTION_KEY] == "reason_not_tolerated"+ assert results["execution_status"] == "failed"+++def _evidence(job: Path, **overrides: Any) -> tuple[list[dict[str, Any]], str | None]:+ """Run the baseline evidence check on the arm-level fixture, with the summary inputs it receives."""+ from skillevaluator.tier3.harbor import collector++ rewards, _invalid = collector._partition_scoreable_rewards(+ collector._extract_rewards(job, {case: case for case in CASES})+ )+ kwargs: dict[str, Any] = {+ "job_dir": job,+ "rewards": rewards,+ "execution": {"expected_attempts": 2, "scored_attempts": 1},+ "slots": {+ "case-001": {"required": 1, "missing": 0, "missing_ordinals": None},+ "case-002": {"required": 1, "missing": 1, "missing_ordinals": None},+ },+ "residual_errors": ["Missing scored attempts for cases: case-002", "Scored attempt coverage is 1/2"],+ "job_failure": "Harbor job did not complete successfully: 1 errored",+ "runtime_failures": collector._extract_agent_runtime_failures(job),+ "trial_failures": collector._extract_trial_failures(job),+ "recovered": [],+ "expected_case_ids": CASES,+ "case_id_by_task_selector": {case: case for case in CASES},+ "arm_suffix": "",+ "task_entry_id_map": None,+ }+ kwargs.update(overrides)+ return collector._baseline_timeout_failures(**kwargs)+++def test_baseline_evidence_binds_every_error_to_the_timeouts(tmp_path: Path) -> None:+ _two_agent_jobs(tmp_path / "jobs")+ job = tmp_path / "jobs" / f"{SKILL}-opencode-without"++ failures, code = _evidence(job)+ assert code is None+ assert [(failure["trial"], failure["case_id"], failure["output_tokens"]) for failure in failures] == [+ ("case-002__without1", "case-002", 321)+ ]++ timed_out = {"trial": "case-002__without1", "reason": f"AgentTimeoutError: {TIMEOUT}"}+ other = {"trial": "case-001__without0", "reason": "Reward metrics are incomplete or non-finite"}+ assert _evidence(job, job_failure="Harbor job did not complete successfully: 1 running")[1] == "unbound_error"+ assert _evidence(job, residual_errors=["Unexpected scored cases: case-009"])[1] == "unbound_error"+ assert _evidence(job, trial_failures=[timed_out, other])[1] == "untyped_trial_failure"+ assert _evidence(job, trial_failures=[])[1] == "untyped_trial_failure"+ assert _evidence(job, runtime_failures=[{**timed_out, "reason": "rate limited"}])[1] == "agent_runtime_failure"+ assert _evidence(job, expected_case_ids=[])[1] == "no_case_identity"+ assert _evidence(job, case_id_by_task_selector={"case-001": "case-001"})[1] == "per_case_mismatch"+++def test_failed_peer_keeps_every_agent_failed(tmp_path: Path) -> None:+ launch_errors = _two_agent_jobs(tmp_path / "jobs", peer_with="timeout")++ results = _collect(tmp_path, launch_errors)++ assert results["execution_status"] == "failed"+ assert results["agents"]["opencode"]["execution_status"] == "failed"+ assert results["agents"]["opencode"][REJECTION_KEY] == "other_agent_failed"+ # codex's with-skill arm failed, so it was never a candidate.+ assert REJECTION_KEY not in results["agents"]["codex"]+++def test_single_agent_has_no_clean_peer(tmp_path: Path) -> None:+ _two_agent_jobs(tmp_path / "jobs")++ results = _collect(tmp_path, [LAUNCH_ERROR.format(agent="opencode", count=1)], agents=["opencode"])++ assert results["execution_status"] == "failed"+ assert results["agents"]["opencode"][REJECTION_KEY] == "no_clean_peer"+++ "extra",+ [+ "opencode with-skill Harbor run failed: harbor run exited 1",+ "Harbor job directory was not created: demo-opencode-with",+ ],+)+def test_other_launch_errors_keep_the_run_failed(tmp_path: Path, extra: str) -> None:+ launch_errors = [*_two_agent_jobs(tmp_path / "jobs"), extra]++ results = _collect(tmp_path, launch_errors)++ assert results["agents"]["opencode"]["execution_status"] == "failed"+ assert results["agents"]["opencode"][REJECTION_KEY] == "unbound_launch_error"+ assert results[RUN_KEY]["explained_launch_errors"] == []+++def _render_reports(tmp_path: Path, results: dict[str, Any]) -> tuple[dict[str, Any], str, str]:+ """Write ``result.json`` and render the canonical payload, ``tier3-benchmark.md`` and ``report.html``."""+ payload, benchmark, html, _message = _render_reports_and_message(tmp_path, results)+ return payload, benchmark, html+++def _render_reports_and_message(tmp_path: Path, results: dict[str, Any]) -> tuple[dict[str, Any], str, str, str]:+ """Like :func:`_render_reports`, and also return the Tier 3 result's ``agent_eval`` message."""+ from skillevaluator.evaluation.tier3_report import agent_eval_result_from_directory, render_agent_eval_html_report++ run_dir = tmp_path / "results"+ results.update(+ {+ "skill_name": SKILL,+ "run_dir": str(run_dir),+ "attempt_policy": {+ **results["attempt_policy"],+ "max_attempts": 1,+ "pass_threshold": 0.5,+ "stop_on_pass": False,+ },+ }+ )+ _write_json(run_dir / "result.json", results)+ skill = tmp_path / SKILL+ skill.mkdir()+ (skill / "SKILL.md").write_text("---\nname: demo\ndescription: demo skill\n---\nbody\n", encoding="utf-8")+ result = agent_eval_result_from_directory(+ skill, run_dir, env_mode="docker", engine_result=results, use_llm_judge=False+ )+ messages = [detail.message for detail in result.success_details if detail.check_name == "agent_eval"]+ report = render_agent_eval_html_report(+ skill, run_dir, env_mode="docker", engine_result=results, include_benchmark=True, use_llm_judge=False+ )+ benchmark = (run_dir / "tier3-benchmark.md").read_text(encoding="utf-8")+ return result.metadata["agent_eval"], benchmark, report.read_text(encoding="utf-8"), "\n".join(messages)+++def _tolerated_line(agent: str) -> str:+ return (+ f"Baseline incomplete for **{agent}** (1 of 2 attempts scored): kept by `--tolerate-baseline-timeouts`, "+ "so its baseline and uplift are not reported."+ )+++def test_reports_rank_tolerated_agents_below_their_complete_peer(tmp_path: Path) -> None:+ from skillevaluator.tier3.harbor.report import _pick_best_agent+ from skillevaluator.tier3.harbor.report_data import load_agent_data++ # Both tolerated agents score higher than their complete peer.+ low = {**dict.fromkeys(SCORES, 0.55), "security": 1.0}+ jobs = tmp_path / "jobs"+ for agent in ("opencode", "claude-code"):+ _arm(jobs, agent, "with", [(case, "scored") for case in CASES])+ _arm(jobs, agent, "without", [("case-001", "scored"), ("case-002", "timeout")])+ _arm(jobs, "codex", "with", [(case, "scored") for case in CASES], scores=low)+ _arm(jobs, "codex", "without", [(case, "scored") for case in CASES], scores=low)+ launch_errors = [LAUNCH_ERROR.format(agent=agent, count=1) for agent in ("opencode", "claude-code")]+ results = _collect(tmp_path, launch_errors, agents=["opencode", "claude-code", "codex"])+ assert results["execution_status"] == "succeeded"+ assert results[RUN_KEY]["tolerated_agents"] == ["claude-code", "opencode"]++ payload, benchmark, html = _render_reports(tmp_path, results)+ assert payload["execution_status"] == "succeeded"+ assert payload["best_agent"] == "codex"+ assert payload["overall_score"] == payload["agents"]["codex"]["with_skill"]+ assert payload["agents"]["opencode"]["with_skill"] > payload["overall_score"]+ assert payload["overall_lift"] == payload["agents"]["codex"]["lift"]+ # Findings follow the same agent.+ assert _pick_best_agent(load_agent_data(tmp_path / "results"), results["agents"]) == "codex"++ assert "> **Tier 3 completed-agent result: " in benchmark+ assert "Completed agent: **codex**; score **0.6400**" in benchmark+ assert "**Needs attention:** other execution failures remain." in benchmark+ assert f"{_tolerated_line('claude-code')}\n{_tolerated_line('opencode')}\n" in benchmark+ assert (+ "Completed-agent quality result; publication not assessed; other execution failures need attention" in benchmark+ )+ # Each HTML notice is its own block, never run together with the next one.+ assert ".t3-overview-lead .tolerated-baseline { display:block;" in html+ for agent in ("claude-code", "opencode"):+ assert f"Baseline incomplete for <strong>{agent}</strong> (1 of 2 attempts scored)" in html+ assert html.count("<code>--tolerate-baseline-timeouts</code>, so its baseline and uplift are not reported.") == 2+ assert "not reported.</span><span" not in html+++def test_reports_never_fall_back_to_a_tolerated_agent(tmp_path: Path) -> None:+ from skillevaluator.tier3.harbor.report import _pick_best_agent+ from skillevaluator.tier3.harbor.report_data import load_agent_data++ # codex completes both arms but never activates the skill; opencode+ # activates it and is tolerated.+ jobs = tmp_path / "jobs"+ _arm(jobs, "opencode", "with", [(case, "scored") for case in CASES], details=_activation(True))+ _arm(jobs, "opencode", "without", [("case-001", "scored"), ("case-002", "timeout")])+ _arm(jobs, "codex", "with", [(case, "scored") for case in CASES], details=_activation(False))+ _arm(jobs, "codex", "without", [(case, "scored") for case in CASES])+ results = _collect(tmp_path, [LAUNCH_ERROR.format(agent="opencode", count=1)])+ assert results["execution_status"] == "succeeded"++ payload, benchmark, html = _render_reports(tmp_path, results)+ # The canonical report ranks the complete agent first, then prefers activation.+ assert payload["best_agent"] == "codex"+ assert payload["agents"]["codex"]["skill_activation"]["status"] == "never_activated"+ assert payload["verdict"] == "inconclusive"+ # The findings panel has nothing to show for a never-activated best agent,+ # as on main, and never picks the tolerated agent instead.+ loaded = load_agent_data(tmp_path / "results")+ assert _pick_best_agent(results["agents"], loaded) == ""+ assert _pick_best_agent(loaded, results["agents"]) == ""+ # Both reports name the tolerated agent, also in the HTML's inconclusive overview.+ assert _tolerated_line("opencode") in benchmark+ assert "<strong>Inconclusive: skill never activated.</strong>" in html+ assert "Baseline incomplete for <strong>opencode</strong> (1 of 2 attempts scored)" in html+++ ("peer", "verdict", "lead"),+ [+ ("failing", "fail", "<strong>Completed-agent result: FAIL.</strong>"),+ ("never-activated", "inconclusive", "<strong>Inconclusive: skill never activated.</strong>"),+ ],+ ids=["failing-peer", "never-activated-peer"],+)+def test_verdict_comes_from_the_complete_peer_not_a_tolerated_agent(+ tmp_path: Path, peer: str, verdict: str, lead: str+) -> None:+ from skillevaluator.evaluation.tier3_report import _agent_quality_verdict++ # opencode activates the skill and passes every dimension and required+ # check (goal accuracy 1.0), but its baseline timed out. codex completes+ # both arms and fails its dimensions or never activates the skill.+ passing = {**SCORES, "goal_accuracy": 1.0}+ failing = {**dict.fromkeys(SCORES, 0.3), "security": 1.0}+ jobs = tmp_path / "jobs"+ _arm(jobs, "opencode", "with", [(case, "scored") for case in CASES], scores=passing, details=_activation(True))+ _arm(jobs, "opencode", "without", [("case-001", "scored"), ("case-002", "timeout")])+ peer_scores = failing if peer == "failing" else None+ peer_activation = _activation(peer != "never-activated")+ _arm(jobs, "codex", "with", [(case, "scored") for case in CASES], scores=peer_scores, details=peer_activation)+ _arm(jobs, "codex", "without", [(case, "scored") for case in CASES], scores=peer_scores)+ results = _collect(tmp_path, [LAUNCH_ERROR.format(agent="opencode", count=1)])+ assert results["execution_status"] == "succeeded"++ payload, benchmark, html, message = _render_reports_and_message(tmp_path, results)+ assert _agent_quality_verdict(payload["agents"]["opencode"]) == "pass"+ # The verdict comes from the same agent as the best agent and every headline.+ assert payload["best_agent"] == payload["summary"]["best_agent"] == "codex"+ assert payload["verdict"] == payload["summary"]["verdict"] == verdict+ assert message == f"Tier 3 evaluation complete: verdict {verdict.upper()}; best agent codex"+ assert f"> **Tier 3 completed-agent result: {verdict.upper()}**" in benchmark+ assert f"| Tier 3 | Live agent evaluation | **{verdict.upper()}** |" in benchmark+ assert lead in html+ if verdict == "inconclusive":+ # The tolerated agent did activate the skill, so Insights names whose trials never did.+ assert payload["conclusions"][0]["message"].startswith(+ "The skill was never activated in any positive with-skill trial of an agent with a complete baseline."+ )+++def test_verdict_counts_come_from_a_complete_agent_that_set_the_verdict(tmp_path: Path) -> None:+ # claude-code passes everything but its baseline timed out. opencode has the+ # top score but misses a goal (FAIL), so the best agent's own result is not+ # the run verdict; codex passes with a lower score and sets the PASS.+ passing = {**SCORES, "goal_accuracy": 1.0}+ lower_passing = {**dict.fromkeys(SCORES, 0.6), "goal_accuracy": 1.0, "security": 1.0}+ jobs = tmp_path / "jobs"+ _arm(jobs, "claude-code", "with", [(case, "scored") for case in CASES], scores=passing, details=_activation(True))+ _arm(jobs, "claude-code", "without", [("case-001", "scored"), ("case-002", "timeout")])+ for agent, scores in (("codex", lower_passing), ("opencode", None)):+ _arm(jobs, agent, "with", [(case, "scored") for case in CASES], scores=scores, details=_activation(True))+ _arm(jobs, agent, "without", [(case, "scored") for case in CASES], scores=scores)+ results = _collect(+ tmp_path, [LAUNCH_ERROR.format(agent="claude-code", count=1)], agents=["claude-code", "codex", "opencode"]+ )+ assert results[RUN_KEY]["tolerated_agents"] == ["claude-code"]++ payload, _benchmark, _html, _message = _render_reports_and_message(tmp_path, results)++ assert payload["best_agent"] == "opencode"+ assert payload["verdict"] == payload["summary"]["verdict"] == "pass"+ # The PASS counts are codex's, never those of the tolerated agent with no baseline.+ for field in ("correct_answers", "required_checks", "security_clean"):+ assert payload["summary"][field] == payload["agents"]["codex"][field]+ assert payload["agents"]["claude-code"]["correct_answers"] != payload["agents"]["codex"]["correct_answers"]+++ ("tolerated", "panel_agent"),+ [((), "opencode"), (("opencode",), None), (("opencode", "claude-code"), None)],+ ids=["none-tolerated", "one-tolerated", "two-tolerated"],+)+def test_terminal_findings_panel_never_shows_a_tolerated_agent(+ tmp_path: Path, capsys: pytest.CaptureFixture[str], tolerated: tuple[str, ...], panel_agent: str | None+) -> None:+ from skillevaluator.tier3.result_display import render_result++ # codex completes both arms but never activates the skill, so the terminal+ # summary leaves it out before it picks the agent for the findings panel.+ activated = list(dict.fromkeys(["opencode", *tolerated]))+ jobs = tmp_path / "jobs"+ for agent in activated:+ _arm(jobs, agent, "with", [(case, "scored") for case in CASES], details=_activation(True))+ outcome = "timeout" if agent in tolerated else "scored"+ _arm(jobs, agent, "without", [("case-001", "scored"), ("case-002", outcome)])+ _arm(jobs, "codex", "with", [(case, "scored") for case in CASES], details=_activation(False))+ _arm(jobs, "codex", "without", [(case, "scored") for case in CASES])+ launch_errors = [LAUNCH_ERROR.format(agent=agent, count=1) for agent in tolerated]+ results = _collect(tmp_path, launch_errors, agents=[*activated, "codex"])+ assert results["execution_status"] == "succeeded"+ assert results[RUN_KEY]["tolerated_agents"] == sorted(tolerated)+ results.update({"skill_name": SKILL, "run_dir": str(tmp_path / "results")})++ capsys.readouterr()+ render_result(results)+ printed = capsys.readouterr().out+ written = sorted(path.parent.name for path in (tmp_path / "results").glob("*/findings.json"))+ if panel_agent is None:+ # The canonical best agent is codex, which has no findings to show. No+ # tolerated agent stands in for it, however many are left.+ assert "Findings" not in printed+ assert written == []+ else:+ # Without tolerance the one activated agent keeps its panel, as on main.+ assert f"{SKILL} / {panel_agent} — Findings" in printed+ assert written == [panel_agent]++[email protected]("kwargs", [{"grading_mode": "custom_only"}, {"skip_baseline": True}])+def test_tolerance_needs_a_baseline_and_dimension_grading(tmp_path: Path, kwargs: dict[str, Any]) -> None:+ launch_errors = _two_agent_jobs(tmp_path / "jobs")++ results = _collect(tmp_path, launch_errors, **kwargs)++ assert RUN_KEY not in results+ assert all(RECORD_KEY not in agent and REJECTION_KEY not in agent for agent in results["agents"].values())+++def test_reused_baseline_leaves_the_option_inert(tmp_path: Path) -> None:+ # A run that completed both arms is the retained baseline (--reuse-baseline).+ source_jobs = tmp_path / "source-jobs"+ for agent in ("opencode", "codex"):+ for variant in ("with", "without"):+ _arm(source_jobs, agent, variant, [(case, "scored") for case in CASES])+ source = tmp_path / "source"+ collect_harbor_results(+ skill_name=SKILL,+ agents=["opencode", "codex"],+ output_dir=source / "results",+ jobs_dir=source_jobs,+ n_attempts=1,+ expected_cases=len(CASES),+ expected_case_ids=CASES,+ case_id_by_task_selector={case: case for case in CASES},+ expected_trials=len(CASES),+ )+ jobs = tmp_path / "jobs"+ for agent in ("opencode", "codex"):+ _arm(jobs, agent, "with", [(case, "scored") for case in CASES])++ results = _collect(tmp_path, [], reused_baseline_dir=source / "results")++ # The baseline did not run here, so there are no timeouts to judge.+ assert results["execution_status"] == "succeeded"+ assert all(agent["without_skill"] for agent in results["agents"].values())+ assert RUN_KEY not in results+ assert all(RECORD_KEY not in agent and REJECTION_KEY not in agent for agent in results["agents"].values())+++# -- stop-on-pass attempt jobs merged by the runner ---------------------------+++def _attempt_job(root: Path, agent: str, variant: str, case: str, attempt: int, outcome: str) -> Path:+ from harbor.models.job.result import JobResult, JobStats+ from harbor.models.trial.result import TrialResult++ job = root / "attempts" / f"{SKILL}-{agent}-{variant}-{case}-attempt{attempt:03d}"+ trial = job / f"{case}__{attempt:07d}"+ trial.mkdir(parents=True)+ start = datetime(2026, 11, 1, tzinfo=UTC) + timedelta(minutes=attempt)+ finish = start + timedelta(seconds=30)+ timed_out = outcome == "timeout"+ score = 1.0 if outcome == "pass" else 0.2+ result = TrialResult.model_validate(+ {+ "id": uuid4(),+ "task_name": case,+ "trial_name": trial.name,+ "trial_uri": trial.as_uri(),+ "task_id": {"path": str(root / "task" / case)},+ "task_checksum": "public-tolerance-example",+ "config": {"task": {"path": str(root / "task" / case)}, "trial_name": trial.name, "trials_dir": str(job)},+ "agent_info": {"name": agent, "version": "test", "model_info": {"name": "test-model"}},+ "agent_result": {"n_output_tokens": 77},+ "started_at": start,+ "finished_at": finish,+ "agent_execution": {"started_at": start, "finished_at": finish},+ "exception_info": {+ "exception_type": "AgentTimeoutError",+ "exception_message": TIMEOUT,+ "exception_traceback": "in _run_agent_phase\nraise AgentTimeoutError(...)",+ "occurred_at": finish,+ }+ if timed_out+ else None,+ "verifier_result": None if timed_out else {"rewards": dict.fromkeys(SCORES, score)},+ }+ )+ (trial / "result.json").write_text(result.model_dump_json(indent=2), encoding="utf-8")+ (trial / "agent").mkdir()+ (trial / "agent" / f"{agent}.txt").write_text(CLEAN_LOG, encoding="utf-8")+ job_result = JobResult(+ id=uuid4(),+ started_at=start,+ updated_at=finish,+ finished_at=finish,+ n_total_trials=1,+ stats=JobStats.from_trial_results([result], n_total_trials=1),+ trial_results=[result],+ )+ (job / "result.json").write_text(job_result.model_dump_json(indent=2), encoding="utf-8")+ return job+++def test_stop_on_pass_timeouts_are_matched_attempt_by_attempt(tmp_path: Path) -> None:+ pytest.importorskip("harbor")+ from skillevaluator.tier3.harbor.runner import _merge_attempt_jobs++ plan = {+ ("opencode", "with"): ["pass"],+ ("opencode", "without"): ["timeout", "timeout"],+ ("codex", "with"): ["pass"],+ ("codex", "without"): ["fail", "fail"],+ }+ for (agent, variant), outcomes in plan.items():+ jobs = [+ _attempt_job(tmp_path, agent, variant, "case-a", attempt, outcome)+ for attempt, outcome in enumerate(outcomes, start=1)+ ]+ _merge_attempt_jobs(jobs, tmp_path / "jobs" / f"{SKILL}-{agent}-{variant}")+ launch_errors = [+ f"opencode without-skill Harbor run failed: case-a attempt {attempt}: "+ "Harbor job did not complete successfully: 1 errored"+ for attempt in (1, 2)+ ]++ def collect(**kwargs: Any) -> dict[str, Any]:+ return collect_harbor_results(+ skill_name=SKILL,+ agents=["opencode", "codex"],+ output_dir=tmp_path / "results",+ jobs_dir=tmp_path / "jobs",+ n_attempts=2,+ stop_on_pass=True,+ expected_cases=1,+ expected_case_ids=["case-a"],+ case_id_by_task_selector={"case-a": "case-a"},+ **kwargs,+ )++ results = collect(launch_errors=launch_errors, tolerate_baseline_timeouts=True)++ opencode = results["agents"]["opencode"]+ assert results["execution_status"] == "succeeded", results.get("warnings")+ assert opencode["execution_status"] == "succeeded"+ record = opencode[RECORD_KEY]+ assert record["status"] == "unavailable"+ assert (record["scored_attempts"], record["expected_attempts"], record["failed_attempts"]) == (0, 2, 2)+ assert [failure["attempt"] for failure in record["failures"]] == [1, 2]+ assert results[RUN_KEY]["explained_launch_errors"] == launch_errors++ # One attempt's launch error the timeouts cannot explain keeps the run failed.+ wrong = [launch_errors[0], launch_errors[0].replace("attempt 1", "attempt 3")]+ refused = collect(launch_errors=wrong, tolerate_baseline_timeouts=True)+ assert refused["agents"]["opencode"][REJECTION_KEY] == "unbound_launch_error"+ assert refused["execution_status"] == "failed"+++def test_stop_on_pass_recovered_timeout_beside_unrecovered_ones(tmp_path: Path) -> None:+ pytest.importorskip("harbor")+ from skillevaluator.tier3.harbor.runner import _merge_attempt_jobs++ plan = {+ ("opencode", "with"): {"case-a": ["pass"], "case-b": ["pass"]},+ # case-a timed out once and then passed, so main's handling recovers it;+ # case-b timed out on both attempts.+ ("opencode", "without"): {"case-a": ["timeout", "pass"], "case-b": ["timeout", "timeout"]},+ ("codex", "with"): {"case-a": ["pass"], "case-b": ["pass"]},+ ("codex", "without"): {"case-a": ["fail", "fail"], "case-b": ["fail", "fail"]},+ }+ for (agent, variant), cases in plan.items():+ jobs = [+ _attempt_job(tmp_path, agent, variant, case, attempt, outcome)+ for case, outcomes in cases.items()+ for attempt, outcome in enumerate(outcomes, start=1)+ ]+ _merge_attempt_jobs(jobs, tmp_path / "jobs" / f"{SKILL}-{agent}-{variant}")+ # The runner already dropped the recovered attempt's launch error.+ launch_errors = [+ f"opencode without-skill Harbor run failed: case-b attempt {attempt}: "+ "Harbor job did not complete successfully: 1 errored"+ for attempt in (1, 2)+ ]++ results = collect_harbor_results(+ skill_name=SKILL,+ agents=["opencode", "codex"],+ output_dir=tmp_path / "results",+ jobs_dir=tmp_path / "jobs",+ n_attempts=2,+ stop_on_pass=True,+ expected_cases=2,+ expected_case_ids=["case-a", "case-b"],+ case_id_by_task_selector={"case-a": "case-a", "case-b": "case-b"},+ launch_errors=launch_errors,+ tolerate_baseline_timeouts=True,+ )++ opencode = results["agents"]["opencode"]+ # Harbor's errored count includes the recovered timeout.+ assert opencode["job_failures"]["without_skill"] == "Harbor job did not complete successfully: 3 errored"+ assert opencode["conditions"]["without_skill"]["recovered_attempts_total"] == 1+ assert results["execution_status"] == "succeeded", results.get("warnings")+ assert opencode["execution_status"] == "succeeded"+ record = opencode[RECORD_KEY]+ assert [(failure["case_id"], failure["attempt"]) for failure in record["failures"]] == [+ ("case-b", 1),+ ("case-b", 2),+ ]+ assert results[RUN_KEY]["explained_launch_errors"] == launch_errors+++def test_cost_limit_attempts_that_never_ran_are_not_missing_baseline_attempts(tmp_path: Path) -> None:+ pytest.importorskip("harbor")+ from skillevaluator.tier3.harbor.runner import _merge_attempt_jobs++ # A cost limit runs every attempt as its own job. It admitted no attempt+ # of case-b for opencode, so neither arm expects case-b; only the timed-out+ # second attempt of case-a is missing from the baseline.+ plan = {+ ("opencode", "with"): {"case-a": ["pass", "pass"]},+ ("opencode", "without"): {"case-a": ["pass", "timeout"]},+ ("codex", "with"): {"case-a": ["pass", "pass"], "case-b": ["pass", "pass"]},+ ("codex", "without"): {"case-a": ["fail", "fail"], "case-b": ["fail", "fail"]},+ }+ for (agent, variant), cases in plan.items():+ jobs = [+ _attempt_job(tmp_path, agent, variant, case, attempt, outcome)+ for case, outcomes in cases.items()+ for attempt, outcome in enumerate(outcomes, start=1)+ ]+ _merge_attempt_jobs(jobs, tmp_path / "jobs" / f"{SKILL}-{agent}-{variant}")+ not_run = [+ {"agent": "opencode", "arm": arm, "case_id": "case-b", "attempt": attempt, "status": "not_run"}+ for arm in ("with", "without")+ for attempt in (1, 2)+ ]+ launch_errors = [+ "opencode without-skill Harbor run failed: case-a attempt 2: Harbor job did not complete successfully: 1 errored"+ ]++ results = collect_harbor_results(+ skill_name=SKILL,+ agents=["opencode", "codex"],+ output_dir=tmp_path / "results",+ jobs_dir=tmp_path / "jobs",+ n_attempts=2,+ expected_cases=2,+ expected_case_ids=["case-a", "case-b"],+ case_id_by_task_selector={"case-a": "case-a", "case-b": "case-b"},+ expected_trials=4,+ launch_errors=launch_errors,+ tolerate_baseline_timeouts=True,+ budget_not_run=not_run,+ )++ opencode = results["agents"]["opencode"]+ assert results["execution_status"] == "succeeded", results.get("warnings")+ assert results["partial"] is True+ assert REJECTION_KEY not in opencode+ assert opencode["conditions"]["with_skill"]["expected_attempts"] == 2+ record = opencode[RECORD_KEY]+ assert (record["expected_attempts"], record["scored_attempts"], record["failed_attempts"]) == (2, 1, 1)+ assert [(failure["case_id"], failure["attempt"]) for failure in record["failures"]] == [("case-a", 2)]+ assert results[RUN_KEY]["explained_launch_errors"] == launch_errors+++# -- pure rules -----------------------------------------------------------------+++def _failure(case: str = "case-a", attempt: int | None = None, **fields: Any) -> dict[str, Any]:+ return {+ "trial": f"{case}__{attempt or 0}",+ "case_id": case,+ "task": case,+ "attempt": attempt,+ "exception_types": ["AgentTimeoutError"],+ "output_tokens": 10,+ **fields,+ }+++def _slots(**cases: tuple[int, list[int] | None]) -> dict[str, dict[str, Any]]:+ return {+ case.replace("_", "-"): {"required": 2, "missing": missing, "missing_ordinals": ordinals}+ for case, (missing, ordinals) in cases.items()+ }+++ ("expected", "scored", "slots", "failures", "code"),+ [+ (2, 1, _slots(case_a=(1, None)), [_failure()], None),+ (2, 0, _slots(case_a=(2, [1, 2])), [_failure(attempt=2), _failure(attempt=1)], None),+ (2, 2, _slots(case_a=(0, None)), [], "baseline_not_short"),+ (+ 2,+ 1,+ _slots(case_a=(1, None)),+ [_failure(exception_types=["AgentSetupTimeoutError"])],+ "reason_not_tolerated",+ ),+ (+ 2,+ 1,+ _slots(case_a=(1, None)),+ [_failure(exception_types=["AgentTimeoutError", "VerifierTimeoutError"])],+ "reason_not_tolerated",+ ),+ (2, 1, _slots(case_a=(1, None)), [_failure(exception_types=[])], "reason_not_tolerated"),+ (2, 0, _slots(case_a=(2, None)), [_failure()], "failures_do_not_account_for_missing"),+ (2, 1, _slots(case_a=(1, None)), [_failure(case="case-b")], "per_case_mismatch"),+ (2, 1, _slots(case_a=(1, [2])), [_failure(attempt=1)], "ordinal_mismatch"),+ (2, 1, _slots(case_a=(1, [2])), [_failure(attempt=None)], "ordinal_mismatch"),+ (2, 1, _slots(case_a=(1, None)), [_failure(output_tokens=0)], "no_progress_evidence"),+ (2, 1, _slots(case_a=(1, None)), [_failure(output_tokens=True)], "no_progress_evidence"),+ ],+)+def test_check_failures(expected, scored, slots, failures, code) -> None:+ assert check_failures(expected_attempts=expected, scored_attempts=scored, slots=slots, failures=failures) == code+++def _agent(status: str = "succeeded", baseline: str = "succeeded") -> dict[str, Any]:+ return {"execution_status": status, "conditions": {"without_skill": {"execution_status": baseline}}}+++def test_select_tolerated_is_all_or_nothing() -> None:+ agents = {"opencode": _agent("failed", "failed"), "codex": _agent(), "codex-cli": _agent()}+ candidates = {"opencode": [_failure(attempt=1)]}+ arm_level = LAUNCH_ERROR.format(agent="opencode", count=1)++ assert select_tolerated(agents, candidates, {}, [arm_level]) == (frozenset({"opencode"}), {}, [arm_level])+ # An agent whose name extends a candidate's never lends it a launch error.+ other = "codex-cli without-skill Harbor run failed: harbor run exited 1"+ tolerated, rejected, explained = select_tolerated(+ {**agents, "codex-cli": _agent("failed")}, candidates, {}, [arm_level, other]+ )+ assert (tolerated, explained) == (frozenset(), [])+ assert rejected == {"opencode": "other_agent_failed"}+ # A refused candidate fails the run, so no other candidate is tolerated either.+ agents["claude-code"] = _agent("failed", "failed")+ assert select_tolerated(agents, candidates, {"claude-code": "no_agent_log"}, [arm_level])[:2] == (+ frozenset(),+ {"claude-code": "no_agent_log", "opencode": "other_agent_failed"},+ )+++def test_select_tolerated_needs_a_peer_that_completed_both_arms() -> None:+ agents = {"opencode": _agent("failed", "failed"), "codex": _agent(baseline="skipped")}+ tolerated, rejected, _explained = select_tolerated(agents, {"opencode": [_failure()]}, {}, [])+ assert tolerated == frozenset()+ assert rejected == {"opencode": "no_clean_peer"}+++ "errors",+ [+ [LAUNCH_ERROR.format(agent="opencode", count=2)],+ [LAUNCH_ERROR.format(agent="opencode", count=1)] * 2,+ ["opencode runtime preflight failed: model unavailable"],+ ["Harbor execution failed before any agent ran"],+ [ADC_LAUNCH_ERROR],+ ],+)+def test_select_tolerated_refuses_launch_errors_it_cannot_bind(errors: list[str]) -> None:+ agents = {"opencode": _agent("failed", "failed"), "codex": _agent()}+ tolerated, rejected, explained = select_tolerated(agents, {"opencode": [_failure()]}, {}, errors)+ assert (tolerated, explained) == (frozenset(), [])+ assert rejected == {"opencode": "unbound_launch_error"}+++def test_settle_and_unexplained_launch_errors() -> None:+ record = build_record(+ expected_attempts=40,+ scored_attempts=0,+ failures=[_failure(attempt=n) for n in range(1, 41)],+ timeout_seconds=None,+ )+ assert record["failed_attempts"] == 40+ assert len(record["failures"]) == baseline_timeouts.FAILURES_PUBLISHED_MAX+ assert record["failures_truncated"] is True+ assert record["status"] == "unavailable"++ agent = {+ "execution_status": "failed",+ "execution_errors": ["Scored attempt coverage is 0/40"],+ "execution_error_details_total": 1,+ REJECTION_KEY: "stale",+ "conditions": {"without_skill": {"execution_status": "failed", "execution_errors": ["kept"]}},+ }+ settle(agent, record)+ assert agent["execution_status"] == "succeeded"+ assert agent["execution_errors"] == []+ assert agent["execution_error_details_total"] == 0+ assert REJECTION_KEY not in agent+ assert agent["conditions"]["without_skill"] == {"execution_status": "failed", "execution_errors": ["kept"]}+++def test_run_record_bounds_launch_errors_and_the_runner_drops_only_explained_ones() -> None:+ errors = [+ f"opencode without-skill Harbor run failed: case-{n:03d} attempt 1: "+ "Harbor job did not complete successfully: 1 errored"+ for n in range(40)+ ]+ record = run_record({"opencode"}, errors)+ assert record["tolerated_agents"] == ["opencode"]+ assert record["explained_launch_errors"] == errors[: baseline_timeouts.LAUNCH_ERRORS_PUBLISHED_MAX]+ assert record["explained_launch_errors_total"] == 40+ assert record["explained_launch_errors_truncated"] is True++ agents = {"opencode": {}, "opencode-cli": {}, "codex": {}}+ other = "opencode-cli with-skill Harbor run failed: harbor run exited 1"+ results = {"agents": agents, RUN_KEY: record}+ # Every tolerated agent's error is dropped, even past the published sample.+ assert unexplained_launch_errors(results, [*errors, other]) == [other]+ # A count that no longer matches the record, or no tolerated agent, keeps every error.+ assert unexplained_launch_errors(results, [*errors[:39], other]) == [*errors[:39], other]+ assert unexplained_launch_errors({"agents": agents, RUN_KEY: run_record((), [])}, errors[:1]) == errors[:1]+ assert unexplained_launch_errors({}, errors[:1]) == errors[:1]+++# -- engine and CLI plumbing ----------------------------------------------------+++def _provider():+ from skillevaluator.provider_config import ProviderConfig++ return ProviderConfig(+ provider="nv_build",+ model="test-model",+ api_key="provider-key",+ base_url="https://provider.example/v1",+ litellm_model="openai/test-model",+ )+++def _run_engine(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, config_yaml: str, **engine_kwargs: Any):+ """Run ``run_harbor_eval`` with Harbor faked and the real collector."""+ from skillevaluator.tier3.harbor import runner, runtime_preflight++ skill = tmp_path / SKILL+ (skill / "evals").mkdir(parents=True)+ (skill / "evals" / "config.yml").write_text(config_yaml, encoding="utf-8")+ captured: dict[str, Any] = {}++ monkeypatch.setattr(runner, "resolve_llm_provider", _provider)+ monkeypatch.setattr(runner, "find_evals_file", lambda _path: skill / "evals" / "evals.json")+ monkeypatch.setattr(runner, "_check_prerequisites", lambda **_kwargs: [])++ def emit(_skill: Path, target: Path, **_kwargs: Any) -> list[Path]:+ tasks = []+ for case_id in CASES:+ task = target / case_id+ (task / "tests").mkdir(parents=True)+ (task / "tests" / "entry.json").write_text(json.dumps({"id": case_id}), encoding="utf-8")+ tasks.append(task)+ return tasks++ def pair(**kwargs: Any) -> list[str]:+ agent, jobs_dir = kwargs["agent"], kwargs["jobs_dir"]+ _arm(jobs_dir, agent, "with", [(case, "scored") for case in CASES])+ if agent == "opencode":+ _arm(jobs_dir, agent, "without", [("case-001", "scored"), ("case-002", "timeout")])+ return [LAUNCH_ERROR.format(agent=agent, count=1)]+ _arm(jobs_dir, agent, "without", [(case, "scored") for case in CASES])+ return []++ def collect(**kwargs: Any) -> dict[str, Any]:+ captured["collect"] = kwargs+ return collect_harbor_results(**kwargs)++ monkeypatch.setattr(runner, "generate_harbor_tasks", emit)+ monkeypatch.setattr(runner, "_run_agent_pair", pair)+ monkeypatch.setattr(runner, "collect_harbor_results", collect)+ monkeypatch.setattr(runner, "render_agent_eval_html_report", lambda *_args, **_kwargs: tmp_path / "report.html")+ monkeypatch.setattr(+ runtime_preflight,+ "probe_model",+ lambda selected: runtime_preflight.ModelProbeResult(True, selected.provider, selected.model, "available"),+ )+ result = runner.run_harbor_eval(+ skill,+ ["opencode", "codex"],+ output_dir=tmp_path / "results",+ env_mode="docker",+ agent_runtime_preflight=False,+ keep_harbor_jobs=True,+ **engine_kwargs,+ )+ return result, captured+++CONFIG = "schema_version: 1\nharbor:\n task_source: evals_json\n"+++def test_engine_default_merges_the_baseline_launch_error(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ result, captured = _run_engine(monkeypatch, tmp_path, CONFIG)++ assert captured["collect"]["tolerate_baseline_timeouts"] is False+ assert result["execution_status"] == "failed"+ assert LAUNCH_ERROR.format(agent="opencode", count=1) in result["execution_errors"]+ assert "tolerate_baseline_timeouts" not in result["run_config"]["harbor"]+++def test_engine_config_key_tolerates_and_drops_the_explained_launch_error(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ result, captured = _run_engine(monkeypatch, tmp_path, CONFIG + " tolerate_baseline_timeouts: true\n")++ assert captured["collect"]["tolerate_baseline_timeouts"] is True+ assert result["execution_status"] == "succeeded", result.get("execution_errors")+ assert "error" not in result+ assert result["execution_errors"] == []+ assert result["agents"]["opencode"]["execution_status"] == "succeeded"+ assert result["run_config"]["harbor"]["tolerate_baseline_timeouts"] is True+ assert any(warning.startswith("opencode baseline incomplete") for warning in result["warnings"])+ persisted = json.loads(Path(result["result_path"]).read_text(encoding="utf-8"))+ assert persisted["agents"]["opencode"][RECORD_KEY]["failed_attempts"] == 1+++def test_option_is_not_part_of_the_comparison_identity(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ """The option changes no execution, so reuse and version comparison still pair runs across it."""+ from skillevaluator.tier3 import baseline_store++ result, _captured = _run_engine(monkeypatch, tmp_path, CONFIG + " tolerate_baseline_timeouts: true\n")+ run_dir = Path(result["run_dir"])+ config = json.loads((run_dir / "run_config.json").read_text(encoding="utf-8"))+ assert config["harbor"]["tolerate_baseline_timeouts"] is True+ source = json.loads(Path(result["result_path"]).read_text(encoding="utf-8"))["comparison_identity"]+ assert "tolerate_baseline_timeouts" not in source["config"]["harbor"]++ # The same run configured without the option.+ config["harbor"].pop("tolerate_baseline_timeouts")+ current = {**source, "config": baseline_store.comparison_identity(config, {})["config"]}+ assert baseline_store.comparison_mismatches(current, source) == []+ assert baseline_store.comparison_mismatches(source, current) == []+ # The complete peer's baseline is a --reuse-baseline source; the tolerated baseline is not.+ reasons, _result = baseline_store.baseline_eligibility(run_dir, ["codex"], current)+ assert reasons == []+ reasons, _result = baseline_store.baseline_eligibility(run_dir, ["opencode"], current)+ assert "opencode: without-skill condition did not succeed" in reasons+ # Both clean with-skill arms are a --compare-to prior.+ reasons, _result = baseline_store.condition_eligibility(run_dir, ["codex", "opencode"], current, "with_skill")+ assert reasons == []+++def test_engine_argument_overrides_the_config_key(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ result, captured = _run_engine(+ monkeypatch,+ tmp_path,+ CONFIG + " tolerate_baseline_timeouts: true\n",+ tolerate_baseline_timeouts=False,+ )++ assert captured["collect"]["tolerate_baseline_timeouts"] is False+ assert result["execution_status"] == "failed"+++def test_config_key_must_be_a_boolean(tmp_path: Path) -> None:+ from skillevaluator.tier3.evals_config import EvalsConfigError, load_evals_config++ (tmp_path / "evals").mkdir()+ (tmp_path / "evals" / "config.yml").write_text(+ "schema_version: 1\nharbor:\n tolerate_baseline_timeouts: sometimes\n", encoding="utf-8"+ )+ with pytest.raises(EvalsConfigError, match=r"harbor\.tolerate_baseline_timeouts"):+ load_evals_config(tmp_path)+++ ("flag", "expected"), [("--tolerate-baseline-timeouts", True), ("--no-tolerate-baseline-timeouts", False)]+)+def test_validate_forwards_the_flag(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, flag: str, expected: bool) -> None:+ from skillevaluator import cli as cli_module+ from skillevaluator.models.result import ValidationResult++ captured: dict[str, Any] = {}++ def tier3(*_args: Any, **kwargs: Any) -> ValidationResult:+ captured.update(kwargs)+ result = ValidationResult(validator_name="AGENT_EVAL")+ result.add_success("agent_eval", "ok")+ return result++ monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", tier3)+ fixture = Path(__file__).resolve().parents[1] / "fixtures" / "skills" / "simple"+ result = CliRunner().invoke(+ cli_module.cli,+ [+ "validate",+ "--no-autopilot",+ str(fixture),+ "--no-llm",+ "--no-tier2",+ "--tier3",+ flag,+ "--checks",+ "schema",+ "--output-dir",+ str(tmp_path / "reports"),+ ],+ )++ assert result.exit_code == 0, result.output+ assert captured["tolerate_baseline_timeouts"] is expected+++def test_evaluation_options_reach_the_engine() -> None:+ import inspect++ from skillevaluator.evaluation import EvaluationOptions+ from skillevaluator.tier3 import commands++ options = EvaluationOptions(skill_path=Path("demo"), tolerate_baseline_timeouts=True)+ assert options.engine_kwargs()["tolerate_baseline_timeouts"] is True+ assert "tolerate_baseline_timeouts" in inspect.signature(commands.evaluate).parameters