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 run budget limits with admission control and partial results (#404)
Christopher Kevine6d8c6112f37
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c6691c14..8b684208 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,8 @@ All notable changes to SkillEvaluator are documented in this file.- Tier 3 datasets can declare deterministic behavior checks for script invocation and success, workspace files, and final-response text.+- Tier 3 evaluations support token, judge-call, attempt, and priced-cost budgets.+- 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 negative@@ -25,7 +27,6 @@ All notable changes to SkillEvaluator are documented in this file.suggest removing cases or loosening expectations. The rules need no LLM; theTier 3 payload carries them as `next_steps`.-- Document per-agent Tier 3 `findings.json` artifacts and distinguish advisorymetric severity from dimension verdicts; include severity thresholds in theartifact and a muted CLI legend without changing scores or thresholds.diff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdxindex 4de3dc48..edf7d4e4 100644--- a/docs/cli-reference.mdx+++ b/docs/cli-reference.mdx@@ -294,6 +294,11 @@ The following flags are forwarded to the live-eval engine when Tier 3 is enabled| `--max-cases INTEGER RANGE` | unset | Run only the first N eval cases in staged order (minimum `1`); without a limit every case runs. A run that skips cases is recorded in `run_config.json` and is never publication evidence. || `--n-attempts INTEGER` | unset | Attempts per eval case (pass@k). || `--pass-threshold FLOAT` | unset | Score threshold (0.0–1.0) for a case to count as passed. |+| `--max-agent-tokens INTEGER` | unset | Maximum measured agent-model tokens. |+| `--max-judge-calls INTEGER` | unset | Maximum recorded non-salvage judge attempts; excludes transport retries and RAGAS-internal requests. |+| `--max-attempts-total INTEGER` | unset | Maximum logical Harbor attempts admitted across agents and arms, including private comparison arms. |+| `--max-cost-usd FLOAT` | unset | Maximum agent model spend; requires a price book and excludes judge spend, setup, and container time. |+| `--price-file FILE` | unset | JSON price book keyed by exact resolved model identifier; see [cost limits](tier3-live-evaluation.mdx#cost-limits). || `--stop-on-pass / --no-stop-on-pass` | unset | Stop a case's remaining attempts once one passes. || `--model TEXT` | unset | Global agent model override. || `--agent-model TEXT` | unset | Per-agent model override, `AGENT=MODEL` (repeatable). |@@ -499,6 +504,11 @@ Use `skillevaluator tier3 PATH` for the complete workflow with automatic missing| `--skip-with-skill` | off | Run only the without-skill baseline, for example to calibrate a task set or measure a model change before running the skill. The report is marked baseline-only: the overall score is the baseline score, with-skill and lift are unavailable (shown as `skipped` or N/A, never 0.0), and no skill verdict is given. Mutually exclusive with `--skip-baseline`. Not available on `validate`. || `--n-attempts INTEGER` | unset | Attempts per eval case (pass@k). || `--pass-threshold FLOAT` | unset | Score threshold (0.0–1.0) for a case to count as passed. |+| `--max-agent-tokens INTEGER` | unset | Maximum measured agent-model tokens. |+| `--max-judge-calls INTEGER` | unset | Maximum recorded non-salvage judge attempts; excludes transport retries and RAGAS-internal requests. |+| `--max-attempts-total INTEGER` | unset | Maximum logical Harbor attempts admitted across agents and arms, including private comparison arms. |+| `--max-cost-usd FLOAT` | unset | Maximum agent model spend; requires a price book and excludes judge spend, setup, and container time. |+| `--price-file FILE` | unset | JSON price book keyed by exact resolved model identifier; see [cost limits](tier3-live-evaluation.mdx#cost-limits). || `--stop-on-pass / --no-stop-on-pass` | unset | Stop a case's remaining attempts once one passes. || `--n-concurrent INTEGER` | unset | Concurrent eval cases per agent. || `--max-agents INTEGER` | unset | Maximum agents to run in parallel. |diff --git a/docs/eval-datasets.mdx b/docs/eval-datasets.mdxindex 5b55670b..d6d8a48a 100644--- a/docs/eval-datasets.mdx+++ b/docs/eval-datasets.mdx@@ -374,6 +374,11 @@ grading:| `harbor.n_concurrent` | integer ≥ 1 | Concurrent trials. || `harbor.max_agents` | integer ≥ 1 | Cap on agents evaluated in one run. || `harbor.max_cases` | integer ≥ 1 | Run only the first N cases in staged order (eval dataset order, or task-directory name order for native Harbor tasks). Unset runs every case. A run that skips cases is not publication evidence. The `--max-cases` CLI flag overrides this value. |+| `harbor.max_agent_tokens` | integer ≥ 0 | Maximum observed agent-model tokens across the run. |+| `harbor.max_judge_calls` | integer ≥ 0 | Maximum recorded non-salvage judge attempts; excludes transport retries and RAGAS-internal requests. |+| `harbor.max_attempts_total` | integer ≥ 0 | Maximum logical Harbor attempts admitted across agents and arms, including private comparison arms. |+| `harbor.max_cost_usd` | finite number ≥ 0 | Agent model spend ceiling; requires `harbor.price_file` and excludes judge spend, setup, and container time. |+| `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.agent_workdir` | string | Working directory for the agent inside the container. |diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdxindex 82a87a71..16bb04e2 100644--- a/docs/tier3-live-evaluation.mdx+++ b/docs/tier3-live-evaluation.mdx@@ -1176,6 +1176,25 @@ Artifacts record this contract ashistorical partial reports retain their recorded scoring semantics instead ofbeing silently reinterpreted.+## Cost limits++Runs can be bounded with `--max-agent-tokens`, `--max-judge-calls`,+`--max-attempts-total`, `--max-cost-usd`, and `--price-file`. The price file is+JSON keyed by model identifier; each model entry requires `input_per_mtok` and+`output_per_mtok`, and may set `cached_input_per_mtok` (defaulting to the+input rate). Cached prompt tokens use the cached rate and remaining prompt+tokens use the input rate. A model key must exactly match the resolved agent+model. Relative `harbor.price_file` paths resolve from the source skill+directory.++Token and cost limits measure agent model spend only; they exclude judge+spend, environment setup, and container time. `--max-judge-calls` counts+recorded judge attempts, excluding `salvage` entries, transport retries, and+requests made internally by RAGAS. Measured usage totals are retained even+when another attempt has no telemetry; that attempt is tracked as unmeasured.+Attempts that cannot start after a limit is reached are reported as `not_run`,+and the resulting run is partial.+### Which dimensions apply to each armSecurity is scored for every arm. Correctness uses `accuracy`, which is N/Adiff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.pyindex 768bf22b..f01a24d1 100644--- a/src/skillevaluator/cli.py+++ b/src/skillevaluator/cli.py@@ -895,6 +895,11 @@ def _run_agent_eval_or_skip(max_agents: int | None,max_cases: int | None = None,n_attempts: int | None = None,+ max_agent_tokens: int | None = None,+ max_judge_calls: int | None = None,+ max_attempts_total: int | None = None,+ max_cost_usd: float | None = None,+ price_file: Path | None = None,pass_threshold: float | None = None,stop_on_pass: bool | None = None,model: str | None = None,@@ -955,6 +960,11 @@ def _run_agent_eval_or_skip(max_agents=max_agents,max_cases=max_cases,n_attempts=n_attempts,+ max_agent_tokens=max_agent_tokens,+ max_judge_calls=max_judge_calls,+ max_attempts_total=max_attempts_total,+ max_cost_usd=max_cost_usd,+ price_file=price_file,pass_threshold=pass_threshold,stop_on_pass=stop_on_pass,model=model,@@ -1350,6 +1360,16 @@ def _catalog_child_argv_from_ctx(argv.extend(["--max-cases", str(params["max_cases"])])if params.get("n_attempts") is not None:argv.extend(["--n-attempts", str(params["n_attempts"])])+ if params.get("max_agent_tokens") is not None:+ argv.extend(["--max-agent-tokens", str(params["max_agent_tokens"])])+ if params.get("max_judge_calls") is not None:+ argv.extend(["--max-judge-calls", str(params["max_judge_calls"])])+ if params.get("max_attempts_total") is not None:+ argv.extend(["--max-attempts-total", str(params["max_attempts_total"])])+ if params.get("max_cost_usd") is not None:+ argv.extend(["--max-cost-usd", str(params["max_cost_usd"])])+ if params.get("price_file") is not None:+ argv.extend(["--price-file", str(Path(params["price_file"]).resolve())])if params.get("pass_threshold") is not None:argv.extend(["--pass-threshold", str(params["pass_threshold"])])stop_on_pass = params.get("stop_on_pass")@@ -2054,6 +2074,34 @@ def _print_run_banner(target_path: Path, content_type: str, profile: str | None)help_group=_TIER3_GROUP,help="Attempts per eval case (pass@k).",)[email protected]("--max-agent-tokens", type=click.IntRange(min=0), default=None, help="Maximum observed agent tokens.")+ "--max-judge-calls",+ type=click.IntRange(min=0),+ default=None,+ help=(+ "Maximum recorded non-salvage judge attempts; transport retries and RAGAS-internal requests are not counted "+ "separately."+ ),+)+ "--max-attempts-total",+ type=click.IntRange(min=0),+ default=None,+ help="Maximum logical Harbor attempts across agents and arms, including private comparison arms.",+)+ "--max-cost-usd",+ type=click.FloatRange(min=0),+ default=None,+ help="Maximum agent model spend; requires --price-file and excludes judge spend, setup, and container time.",+)+ "--price-file",+ type=click.Path(exists=True, dir_okay=False, path_type=Path),+ default=None,+ help="Model price JSON with input_per_mtok/output_per_mtok rates and optional cached_input_per_mtok.",+)@click.option("--pass-threshold",type=float,@@ -2191,6 +2239,11 @@ def validate(max_agents: int | None,max_cases: int | None,n_attempts: int | None,+ max_agent_tokens: int | None,+ max_judge_calls: int | None,+ max_attempts_total: int | None,+ max_cost_usd: float | None,+ price_file: Path | None,pass_threshold: float | None,stop_on_pass: bool | None,model: str | None,@@ -2536,6 +2589,11 @@ def validate(max_agents=max_agents,max_cases=max_cases,n_attempts=n_attempts,+ max_agent_tokens=max_agent_tokens,+ max_judge_calls=max_judge_calls,+ max_attempts_total=max_attempts_total,+ max_cost_usd=max_cost_usd,+ price_file=price_file,pass_threshold=pass_threshold,stop_on_pass=stop_on_pass,model=model,@@ -3188,6 +3246,39 @@ def _tier2_workflow(help="Skip the with-skill arm and run only the without-skill baseline (no lift analysis).",)@click.option("--n-attempts", type=int, default=None)+ "--max-agent-tokens",+ type=click.IntRange(min=0),+ default=None,+ help="Maximum measured agent-model tokens.",+)+ "--max-judge-calls",+ type=click.IntRange(min=0),+ default=None,+ help=(+ "Maximum recorded non-salvage judge attempts; transport retries and RAGAS-internal requests are not counted "+ "separately."+ ),+)+ "--max-attempts-total",+ type=click.IntRange(min=0),+ default=None,+ help="Maximum logical Harbor attempts across agents and arms, including private comparison arms.",+)+ "--max-cost-usd",+ type=click.FloatRange(min=0),+ default=None,+ help="Maximum agent model spend; requires --price-file and excludes judge spend, setup, and container time.",+)+ "--price-file",+ type=click.Path(exists=True, dir_okay=False, path_type=Path),+ default=None,+ help="Model price JSON with input_per_mtok/output_per_mtok rates and optional cached_input_per_mtok.",+)@click.option("--pass-threshold", type=float, default=None)@click.option("--stop-on-pass/--no-stop-on-pass",@@ -3266,6 +3357,11 @@ def evaluate(skip_baseline: bool,skip_with_skill: bool,n_attempts: int | None,+ max_agent_tokens: int | None,+ max_judge_calls: int | None,+ max_attempts_total: int | None,+ max_cost_usd: float | None,+ price_file: Path | None,pass_threshold: float | None,stop_on_pass: bool | None,n_concurrent: int | None,@@ -3299,6 +3395,17 @@ def evaluate(if skip_baseline and skip_with_skill:# Reject before --autopilot can spend a generation call on a run that cannot start.raise click.UsageError("--skip-baseline and --skip-with-skill are mutually exclusive (no arm would run)")+ from skillevaluator.tier3.evals_config import EvalsConfigError, load_evals_config++ try:+ merged_config, _ = load_evals_config(skill_path)+ except EvalsConfigError as exc:+ raise click.UsageError(str(exc)) from exc+ harbor_config = merged_config.get("harbor", {})+ effective_max_cost = max_cost_usd if max_cost_usd is not None else harbor_config.get("max_cost_usd")+ effective_price_file = price_file or harbor_config.get("price_file")+ if effective_max_cost is not None and effective_price_file is None:+ raise click.UsageError("--max-cost-usd requires --price-file")service = EvaluationService()# Resolved before the service is built so a non-canonical value is refused# at the boundary rather than after a long live run has already started.@@ -3332,6 +3439,11 @@ def evaluate(skip_baseline=skip_baseline,skip_with_skill=skip_with_skill,n_attempts=n_attempts,+ max_agent_tokens=max_agent_tokens,+ max_judge_calls=max_judge_calls,+ max_attempts_total=max_attempts_total,+ max_cost_usd=max_cost_usd,+ price_file=price_file,pass_threshold=pass_threshold,stop_on_pass=stop_on_pass,n_concurrent=n_concurrent,diff --git a/src/skillevaluator/evaluation/options.py b/src/skillevaluator/evaluation/options.pyindex 066b2a2c..904322c9 100644--- a/src/skillevaluator/evaluation/options.py+++ b/src/skillevaluator/evaluation/options.py@@ -57,6 +57,11 @@ class EvaluationOptions:environment_kwargs: dict[str, str] = field(default_factory=dict)# Appended so legacy positional construction keeps its field order.max_cases: int | None = None+ max_agent_tokens: int | None = None+ max_judge_calls: int | None = None+ max_attempts_total: int | None = None+ max_cost_usd: float | None = None+ price_file: Path | 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 1ff1b08a..8b2972e0 100644--- a/src/skillevaluator/evaluation/tier3_report.py+++ b/src/skillevaluator/evaluation/tier3_report.py@@ -1036,6 +1036,9 @@ def build_agent_eval_payload(best_evidence_links,)+ budget_metadata = (run_config or {}).get("budget")+ from skillevaluator.tier3.harbor.run_budget import budget_line+payload = {"schema_version": _SCHEMA_VERSION,"summary": summary,@@ -1094,6 +1097,8 @@ def build_agent_eval_payload("supported_metric_ids": list(AGENT_EVAL_EVALUATORS),"metric_labels": metric_labels,"attempt_policy": policy,+ "budget": budget_metadata,+ "budget_summary": budget_line(budget_metadata) if isinstance(budget_metadata, dict) else None,"dataset": public_dataset,"case_diagnostics": case_diagnostics,"provenance": _build_provenance(diff --git a/src/skillevaluator/reporting/templates/report.html.j2 b/src/skillevaluator/reporting/templates/report.html.j2index 8853a885..37cb7e27 100644--- a/src/skillevaluator/reporting/templates/report.html.j2+++ b/src/skillevaluator/reporting/templates/report.html.j2@@ -2178,6 +2178,7 @@{% set t3_max_attempts = (t3_attempt_policy.max_attempts or 1) | int %}{% set t3_dataset = tier3.dataset or [] %}{% set t3_provenance = tier3.provenance or {} %}+ {% set t3_budget = tier3.budget or {} %}{% set t3_source_errors = t3_provenance.get('source_validation') or [] %}{% set t3_harbor = tier3.get('harbor_viewer') or t3_summary.get('harbor_viewer') or {} %}{% set t3_harbor_job_url = t3_harbor.get('job_url') %}@@ -2185,6 +2186,9 @@{% set t3_evidence_links = t3_harbor.get('evidence_links') or [] %}{% set t3_agent_anchor_ids = {} %}{% set t3_agent_panel_ids = {} %}+ {% if t3_budget.status == 'exhausted' and tier3.budget_summary %}+ <p class="warning">{{ tier3.budget_summary }}</p>+ {% endif %}{% for name, _agent in t3_agents.items() %}{% set _ = t3_agent_anchor_ids.update({name: 'tier3-agent-anchor-' ~ loop.index0}) %}{% set _ = t3_agent_panel_ids.update({name: 'tier3-agent-panel-' ~ loop.index0}) %}diff --git a/src/skillevaluator/tier3/commands.py b/src/skillevaluator/tier3/commands.pyindex 02b6e283..a15f5b88 100644--- a/src/skillevaluator/tier3/commands.py+++ b/src/skillevaluator/tier3/commands.py@@ -669,6 +669,11 @@ def evaluate(skip_baseline: bool,skip_with_skill: bool = False,n_attempts: int | None,+ max_agent_tokens: int | None = None,+ max_judge_calls: int | None = None,+ max_attempts_total: int | None = None,+ max_cost_usd: float | None = None,+ price_file: Path | None = None,pass_threshold: float | None,stop_on_pass: bool | None = None,n_concurrent: int | None,@@ -756,6 +761,11 @@ def evaluate(skip_baseline=skip_baseline,skip_with_skill=skip_with_skill,n_attempts=n_attempts,+ max_agent_tokens=max_agent_tokens,+ max_judge_calls=max_judge_calls,+ max_attempts_total=max_attempts_total,+ max_cost_usd=max_cost_usd,+ price_file=price_file,pass_threshold=pass_threshold,stop_on_pass=stop_on_pass,n_concurrent=n_concurrent,diff --git a/src/skillevaluator/tier3/evals_config.py b/src/skillevaluator/tier3/evals_config.pyindex 29771a75..d60de99a 100644--- a/src/skillevaluator/tier3/evals_config.py+++ b/src/skillevaluator/tier3/evals_config.py@@ -53,6 +53,11 @@ _HARBOR_KEYS = {"passthrough_env","setup_commands","agents",+ "max_agent_tokens",+ "max_judge_calls",+ "max_attempts_total",+ "max_cost_usd",+ "price_file",}HARBOR_TASK_SOURCES = {"auto", "evals_json", "native_harbor"}# Harbor 0.22 multiplies its 600-second default verifier/build timeout by@@ -252,6 +257,17 @@ def _validate_config(raw: dict[str, Any], config_path: Path) -> dict[str, Any]:harbor["pre_agent_setup"] = _pre_agent_setup(pre_agent_setup_value, config_path)if "agents" in harbor_raw:harbor["agents"] = _agents(harbor_raw["agents"], config_path)+ for name in ("max_agent_tokens", "max_judge_calls", "max_attempts_total"):+ if name in harbor_raw:+ harbor[name] = _int_at_least(harbor_raw[name], 0, config_path, f"harbor.{name}")+ if "max_cost_usd" in harbor_raw:+ harbor["max_cost_usd"] = _float_between(+ harbor_raw["max_cost_usd"], 0.0, math.inf, config_path, "harbor.max_cost_usd"+ )+ if "price_file" in harbor_raw:+ harbor["price_file"] = _non_empty_string(harbor_raw["price_file"], config_path, "harbor.price_file")+ if "max_cost_usd" in harbor and "price_file" not in harbor:+ raise EvalsConfigError(f"{config_path}: harbor.max_cost_usd requires harbor.price_file")out["harbor"] = harbordiff --git a/src/skillevaluator/tier3/harbor/collector.py b/src/skillevaluator/tier3/harbor/collector.pyindex 6f990f70..32a46a7f 100644--- a/src/skillevaluator/tier3/harbor/collector.py+++ b/src/skillevaluator/tier3/harbor/collector.py@@ -4994,6 +4994,7 @@ def _pass_summary(stop_on_pass: bool = False,expected_cases: int | None,expected_case_ids: list[str] | None = None,+ expected_attempts_by_case: Mapping[str, int] | None = None,recovered_attempts: list[dict[str, Any]] | None = None,scorer: Callable[[dict[str, Any]], float | None] | None = None,shared_metrics_by_case: Mapping[str, set[str]] | None = None,@@ -5107,7 +5108,10 @@ def _pass_summary(if is_expected_case:attempts_used += len(attempts)recovered_count = sum(item["case_id"] == entry_id for item in (recovered_attempts or []))- unscored = max(0, n_attempts - len(attempts) - recovered_count)+ expected_attempt_count = (+ expected_attempts_by_case.get(entry_id, n_attempts) if expected_attempts_by_case is not None else n_attempts+ )+ unscored = max(0, expected_attempt_count - len(attempts) - recovered_count)skipped = unscored if stop_on_pass and case_passed else 0missing = 0 if skipped else unscored@@ -5148,6 +5152,9 @@ def _pass_summary(rate = round(passed_cases / total_cases, 4) if total_cases else 0.0rate_interval = _wilson_score_interval(passed_cases, total_cases)+ max_attempts_possible = (+ sum(expected_attempts_by_case.values()) if expected_attempts_by_case is not None else total_cases * n_attempts+ )return {"k": n_attempts,"pass_threshold": pass_threshold,@@ -5166,7 +5173,7 @@ def _pass_summary("rate": rate,"rate_interval": rate_interval,"attempts_used": attempts_used,- "max_attempts_possible": total_cases * n_attempts,+ "max_attempts_possible": max_attempts_possible,"avg_attempts_used": round(attempts_used / total_cases, 4) if total_cases else 0.0,"extra_case_count": len(extra_case_ids),"extra_cases": extra_case_ids[:PUBLISHED_CASE_ID_DIAGNOSTIC_SAMPLE_MAX],@@ -6740,6 +6747,7 @@ def _condition_execution_summary(skipped: bool = False,stop_on_pass: bool = False,pass_threshold: float = 0.50,+ expected_attempts_by_case: Mapping[str, int] | None = None,) -> dict[str, Any]:"""Describe whether a Harbor condition produced complete logical attempts.@@ -6860,7 +6868,9 @@ def _condition_execution_summary(if len(explicit + recovered_ordinals) != len(set(explicit + recovered_ordinals)):errors.append(f"Scored case {case_id!r} has duplicate attempt ordinals")- required = n_attempts+ required = (+ expected_attempts_by_case.get(case_id, n_attempts) if expected_attempts_by_case is not None else n_attempts+ )if stop_on_pass:first_pass = next(((index, item) for index, item in enumerate(attempts, start=1) if item["passed"]),@@ -6880,7 +6890,15 @@ def _condition_execution_summary(missing: list[str] = []excess: list[str] = []- expected_attempts = 0 if stop_on_pass else expected_count * n_attempts+ expected_attempts = (+ 0+ if stop_on_pass+ else (+ sum(expected_attempts_by_case.values())+ if expected_attempts_by_case is not None+ else expected_count * n_attempts+ )+ )case_ids = expected_ids or sorted(by_case)for case_id in case_ids:required, case_missing, case_excess = _case_attempt_coverage(case_id, by_case.get(case_id, []))@@ -7042,6 +7060,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,+ budget_not_run: list[dict[str, Any]] | None = None,) -> dict[str, Any]:"""Collect results from Harbor jobs into evals/results/<agent>/ structure.@@ -7063,6 +7082,36 @@ def collect_harbor_results(case_id_by_task_selector,expected_case_ids,)+ budget_not_run = budget_not_run or []++ def budget_expectations(+ agent: str,+ arm: str,+ ) -> tuple[int | None, list[str] | None, int | None, dict[str, int] | None]:+ matching = [+ item for item in budget_not_run if item.get("agent") == agent and item.get("arm") in {arm, f"{arm}_skill"}+ ]+ if not matching:+ return expected_trials, expected_case_ids, expected_cases, None+ attempts_by_case: dict[str, int] = {}+ for item in matching:+ selector = str(item.get("case_id") or "")+ case_id = (case_id_by_task_selector or {}).get(selector, selector)+ attempts_by_case[case_id] = attempts_by_case.get(case_id, 0) + 1+ active_ids = [case_id for case_id in (expected_case_ids or []) if attempts_by_case.get(case_id, 0) < n_attempts]+ if expected_case_ids:+ active_case_ids: list[str] | None = active_ids+ active_cases = len(active_ids)+ attempt_counts = {case_id: max(0, n_attempts - attempts_by_case.get(case_id, 0)) for case_id in active_ids}+ else:+ fully_not_run = sum(count >= n_attempts for count in attempts_by_case.values())+ active_case_ids = None+ active_cases = max(0, (expected_cases or 0) - fully_not_run)+ attempt_counts = {+ case_id: max(0, n_attempts - count) for case_id, count in attempts_by_case.items() if count < n_attempts+ }+ actual_trials = None if expected_trials is None else max(0, expected_trials - len(matching))+ return actual_trials, active_case_ids, active_cases, attempt_counts# Unscored conditions keep the requested grading policy instead of# falling back to the default metric set, which custom_only never grades.@@ -7087,6 +7136,20 @@ def collect_harbor_results(_prepare_generated_outputs(output_dir, agents)for agent in agents:+ with_expected_trials, with_expected_case_ids, with_expected_cases, with_expected_attempts = budget_expectations(+ agent, "with"+ )+ without_expected_trials, without_expected_case_ids, without_expected_cases, without_expected_attempts = (+ budget_expectations(agent, "without")+ )+ if skip_baseline:+ agent_expected_case_ids = with_expected_case_ids+ elif with_expected_case_ids is not None and without_expected_case_ids is not None:+ agent_expected_case_ids = [+ case_id for case_id in with_expected_case_ids if case_id in set(without_expected_case_ids)+ ]+ else:+ agent_expected_case_ids = expected_case_idsmodel_info = agent_models.get(agent, {}) if agent_models else {}agent_model = _bounded_reward_metadata_text(model_info.get("model"))agent_model_source = _bounded_reward_metadata_text(model_info.get("source"))@@ -7120,7 +7183,7 @@ def collect_harbor_results(if with_job_dir:with_job_ok, with_job_failure = validate_harbor_job_result(with_job_dir / "result.json",- expected_trials=expected_trials,+ expected_trials=with_expected_trials,)with_job_failure = _published_job_failure(with_job_failure)with_runtime_failures = _extract_agent_runtime_failures(with_job_dir)@@ -7170,14 +7233,15 @@ def collect_harbor_results(n_attempts=n_attempts,pass_threshold=pass_threshold,stop_on_pass=stop_on_pass,- expected_cases=expected_cases,- expected_case_ids=expected_case_ids,+ expected_cases=with_expected_cases,+ expected_case_ids=with_expected_case_ids,+ expected_attempts_by_case=with_expected_attempts,recovered_attempts=with_recovered,)with_execution = _condition_execution_summary(with_rewards,- expected_case_ids=expected_case_ids,- expected_cases=expected_cases,+ expected_case_ids=with_expected_case_ids,+ expected_cases=with_expected_cases,n_attempts=n_attempts,job_failure="" if with_job_recovered else with_job_failure,recovered_attempts=with_recovered,@@ -7185,6 +7249,7 @@ def collect_harbor_results(reward_failures=with_trial_failures,stop_on_pass=stop_on_pass,pass_threshold=pass_threshold,+ expected_attempts_by_case=with_expected_attempts,)if with_policy == "mixed-score-policies":_fail_execution_with_error(with_execution, "Conflicting score policies within the with-skill condition")@@ -7266,8 +7331,8 @@ def collect_harbor_results(if not with_execution:with_execution = _condition_execution_summary(with_rewards,- expected_case_ids=expected_case_ids,- expected_cases=expected_cases,+ expected_case_ids=with_expected_case_ids,+ expected_cases=with_expected_cases,n_attempts=n_attempts,job_failure=with_job_failure,runtime_failures=with_runtime_failures,@@ -7336,7 +7401,7 @@ def collect_harbor_results(if without_job_dir:without_job_ok, without_job_failure = validate_harbor_job_result(without_job_dir / "result.json",- expected_trials=expected_trials,+ expected_trials=without_expected_trials,)without_job_failure = _published_job_failure(without_job_failure)without_runtime_failures = _extract_agent_runtime_failures(without_job_dir)@@ -7399,14 +7464,15 @@ def collect_harbor_results(n_attempts=n_attempts,pass_threshold=pass_threshold,stop_on_pass=stop_on_pass,- expected_cases=expected_cases,- expected_case_ids=expected_case_ids,+ expected_cases=without_expected_cases,+ expected_case_ids=without_expected_case_ids,+ expected_attempts_by_case=without_expected_attempts,recovered_attempts=without_recovered,)without_execution = _condition_execution_summary(without_rewards,- expected_case_ids=expected_case_ids,- expected_cases=expected_cases,+ expected_case_ids=without_expected_case_ids,+ expected_cases=without_expected_cases,n_attempts=n_attempts,job_failure="" if without_job_recovered else without_job_failure,recovered_attempts=without_recovered,@@ -7414,6 +7480,7 @@ def collect_harbor_results(reward_failures=without_trial_failures,stop_on_pass=stop_on_pass,pass_threshold=pass_threshold,+ expected_attempts_by_case=without_expected_attempts,)if without_policy == "mixed-score-policies":_fail_execution_with_error(@@ -7498,14 +7565,15 @@ def collect_harbor_results(if not without_execution:without_execution = _condition_execution_summary(without_rewards,- expected_case_ids=expected_case_ids,- expected_cases=expected_cases,+ expected_case_ids=without_expected_case_ids,+ expected_cases=without_expected_cases,n_attempts=n_attempts,job_failure=without_job_failure,runtime_failures=without_runtime_failures,skipped=skip_baseline,stop_on_pass=stop_on_pass,pass_threshold=pass_threshold,+ expected_attempts_by_case=without_expected_attempts,)if not skip_baseline and without_job_dir is None:summary_dir = agent_dir / "without-skill"@@ -7601,7 +7669,7 @@ def collect_harbor_results(without_scores,with_logical_rewards,without_logical_rewards,- expected_case_ids,+ agent_expected_case_ids,score_policy=with_policy,with_not_applicable=with_not_applicable,without_not_applicable=without_not_applicable,@@ -7656,8 +7724,8 @@ def collect_harbor_results(n_attempts=n_attempts,pass_threshold=pass_threshold,stop_on_pass=stop_on_pass,- expected_cases=expected_cases,- expected_case_ids=expected_case_ids,+ expected_cases=with_expected_cases,+ expected_case_ids=agent_expected_case_ids,)_write_generated_root_json(agent_dir / "pass_at_k_lift.json", output_dir, pass_lift)@@ -7670,7 +7738,7 @@ def collect_harbor_results(with_rewards,without_rewards,baseline_run=not skip_baseline,- expected_case_ids=expected_case_ids,+ expected_case_ids=agent_expected_case_ids,)_write_generated_root_json(agent_dir / "security_attribution.json",@@ -7818,6 +7886,8 @@ def collect_harbor_results(if top_execution["execution_errors"]:all_results["error"] = list(top_execution["execution_errors"])+ if budget_not_run:+ all_results["partial"] = Truereturn all_resultsdiff --git a/src/skillevaluator/tier3/harbor/run_budget.py b/src/skillevaluator/tier3/harbor/run_budget.pynew file mode 100644index 00000000..516a14aa--- /dev/null+++ b/src/skillevaluator/tier3/harbor/run_budget.py@@ -0,0 +1,308 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Admission control and accounting for bounded Tier 3 runs."""++from __future__ import annotations++import json+import math+import threading+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any+++class BudgetConfigurationError(ValueError):+ """Raised when a run budget or price file is invalid."""+++@dataclass(frozen=True)+class Price:+ input_per_mtok: float+ output_per_mtok: float+ cached_input_per_mtok: float | None = None+++@dataclass(frozen=True)+class PriceBook:+ prices: dict[str, Price]++ @classmethod+ def load(cls, path: Path) -> PriceBook:+ try:+ raw = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as exc:+ raise BudgetConfigurationError(f"{path}: invalid price file: {exc}") from exc+ if not isinstance(raw, dict) or not raw:+ raise BudgetConfigurationError(f"{path}: price file must be a non-empty object")+ prices: dict[str, Price] = {}+ for model, value in raw.items():+ if not isinstance(model, str) or not isinstance(value, dict):+ raise BudgetConfigurationError(f"{path}: each model price must be an object")+ try:+ input_price = float(value["input_per_mtok"])+ output_price = float(value["output_per_mtok"])+ cached_input_price = float(value.get("cached_input_per_mtok", input_price))+ except (KeyError, TypeError, ValueError) as exc:+ raise BudgetConfigurationError(+ f"{path}: {model} must provide input_per_mtok and output_per_mtok, with optional cached_input_per_mtok"+ ) from exc+ if (+ not math.isfinite(input_price)+ or not math.isfinite(output_price)+ or not math.isfinite(cached_input_price)+ or input_price < 0+ or output_price < 0+ or cached_input_price < 0+ ):+ raise BudgetConfigurationError(f"{path}: {model} prices must be finite and non-negative")+ prices[model] = Price(input_price, output_price, cached_input_price)+ return cls(prices)++ def price_for(self, model: str) -> Price:+ try:+ return self.prices[model]+ except KeyError as exc:+ raise BudgetConfigurationError(f"No price is supplied for run model {model!r}") from exc+++def planned_attempts(+ cases: int,+ attempts: int,+ agents: int,+ *,+ arms: int = 2,+ stop_on_pass: bool = False,+) -> int:+ """Return the upper bound used for fail-fast admission checks."""+ if stop_on_pass:+ return cases * attempts * arms * agents+ return cases * attempts * arms * agents+++def _usage_number(usage: dict[str, Any] | None, *keys: str) -> int | float | None:+ if not isinstance(usage, dict):+ return None+ values = [usage[key] for key in keys if isinstance(usage.get(key), (int, float))]+ values = [value for value in values if not isinstance(value, bool) and math.isfinite(float(value)) and value >= 0]+ return max(values) if values else None+++@dataclass+class BudgetController:+ max_agent_tokens: int | None = None+ max_judge_calls: int | None = None+ max_attempts_total: int | None = None+ max_cost_usd: float | None = None+ price_book: PriceBook | None = None+ planned: int = 0+ used_agent_tokens: int | None = None+ used_judge_calls: int | None = None+ used_cost_usd: float | None = None+ exhausted_limit: str | None = None+ not_run: list[dict[str, Any]] = field(default_factory=list)+ _started: int = 0+ _finished: int = 0+ _agent_usage_seen: bool = False+ _judge_usage_seen: bool = False+ _cost_usage_seen: bool = False+ unmeasured_agent_attempts: int = 0+ unmeasured_judge_attempts: int = 0+ unmeasured_cost_attempts: int = 0+ _lock: threading.Lock = field(default_factory=threading.Lock, repr=False)++ def __post_init__(self) -> None:+ for name in ("max_agent_tokens", "max_judge_calls", "max_attempts_total"):+ value = getattr(self, name)+ if value is not None and (not isinstance(value, int) or isinstance(value, bool) or value < 0):+ raise BudgetConfigurationError(f"{name} must be a non-negative integer")+ if self.max_cost_usd is not None:+ if not math.isfinite(self.max_cost_usd) or self.max_cost_usd < 0:+ raise BudgetConfigurationError("max_cost_usd must be finite and non-negative")+ if self.price_book is None:+ raise BudgetConfigurationError("max_cost_usd requires a user-supplied price file")++ def admit(self, *, agent: str, arm: str, case_id: str, attempt: int) -> bool:+ return self.admit_many([{"agent": agent, "arm": arm, "case_id": case_id, "attempt": attempt}])++ def admit_many(self, attempts: list[dict[str, Any]]) -> bool:+ """Atomically admit a logical unit, or record every member as not run."""+ if not attempts:+ return True+ with self._lock:+ if self.exhausted_limit is not None:+ self.not_run.extend(+ self._not_run(item["agent"], item["arm"], item["case_id"], item["attempt"]) for item in attempts+ )+ return False+ if self.max_attempts_total is not None and self._started + len(attempts) > self.max_attempts_total:+ self.exhausted_limit = "attempts"+ self.not_run.extend(+ self._not_run(item["agent"], item["arm"], item["case_id"], item["attempt"]) for item in attempts+ )+ return False+ if self.max_agent_tokens == 0:+ self.exhausted_limit = "agent_tokens"+ elif self.max_judge_calls == 0:+ self.exhausted_limit = "judge_calls"+ elif self.max_cost_usd == 0:+ self.exhausted_limit = "cost"+ if self.exhausted_limit is not None:+ self.not_run.extend(+ self._not_run(item["agent"], item["arm"], item["case_id"], item["attempt"]) for item in attempts+ )+ return False+ if self._finished and self.max_agent_tokens is not None and self.unmeasured_agent_attempts:+ self.exhausted_limit = "agent_tokens"+ elif self._finished and self.max_judge_calls is not None and self.unmeasured_judge_attempts:+ self.exhausted_limit = "judge_calls"+ elif self._finished and self.max_cost_usd is not None and self.unmeasured_cost_attempts:+ self.exhausted_limit = "cost"+ if self.exhausted_limit is not None:+ self.not_run.extend(+ self._not_run(item["agent"], item["arm"], item["case_id"], item["attempt"]) for item in attempts+ )+ return False+ if (+ self.max_agent_tokens is not None+ and self.used_agent_tokens is not None+ and self.used_agent_tokens >= self.max_agent_tokens+ ):+ self.exhausted_limit = "agent_tokens"+ elif (+ self.max_judge_calls is not None+ and self.used_judge_calls is not None+ and self.used_judge_calls >= self.max_judge_calls+ ):+ self.exhausted_limit = "judge_calls"+ elif (+ self.max_cost_usd is not None+ and self.used_cost_usd is not None+ and self.used_cost_usd >= self.max_cost_usd+ ):+ self.exhausted_limit = "cost"+ if self.exhausted_limit is not None:+ self.not_run.extend(+ self._not_run(item["agent"], item["arm"], item["case_id"], item["attempt"]) for item in attempts+ )+ return False+ self._started += len(attempts)+ return True++ def record_usage(self, usage: dict[str, Any] | None, *, model: str | None = None) -> None:+ with self._lock:+ input_tokens = _usage_number(usage, "input_tokens", "prompt_tokens", "total_prompt_tokens")+ output_tokens = _usage_number(usage, "output_tokens", "completion_tokens", "total_completion_tokens")+ tokens = _usage_number(usage, "total_tokens")+ if tokens is None and input_tokens is not None and output_tokens is not None:+ tokens = input_tokens + output_tokens+ if tokens is None:+ self.unmeasured_agent_attempts += 1+ else:+ self.used_agent_tokens = (self.used_agent_tokens or 0) + int(tokens)+ self._agent_usage_seen = True+ judge_calls = _usage_number(usage, "judge_calls", "llm_call_count")+ if judge_calls is None:+ self.unmeasured_judge_attempts += 1+ else:+ self.used_judge_calls = (self.used_judge_calls or 0) + int(judge_calls)+ self._judge_usage_seen = True+ cost = None+ if self.price_book is not None and model and input_tokens is not None and output_tokens is not None:+ price = self.price_book.price_for(model)+ cached_tokens = _usage_number(usage, "cached_input_tokens", "total_cached_tokens", "cached_tokens") or 0+ cached_tokens = min(int(cached_tokens), int(input_tokens))+ cached_price = price.cached_input_per_mtok+ if cached_price is None:+ cached_price = price.input_per_mtok+ uncached_tokens = int(input_tokens) - cached_tokens+ cost = (+ uncached_tokens * price.input_per_mtok+ + cached_tokens * cached_price+ + output_tokens * price.output_per_mtok+ ) / 1_000_000+ if cost is None:+ cost = _usage_number(usage, "cost_usd", "total_cost_usd")+ if cost is None:+ self.unmeasured_cost_attempts += 1+ else:+ self.used_cost_usd = (self.used_cost_usd or 0.0) + float(cost)+ self._cost_usage_seen = True+ self._finished += 1++ def mark_remaining(self, attempts: list[dict[str, Any]]) -> None:+ with self._lock:+ for item in attempts:+ self.not_run.append(dict(item, status="not_run", reason="budget_exhausted"))++ def metadata(self) -> dict[str, Any]:+ with self._lock:+ return {+ "limits": {+ "max_agent_tokens": self.max_agent_tokens,+ "max_judge_calls": self.max_judge_calls,+ "max_attempts_total": self.max_attempts_total,+ "max_cost_usd": self.max_cost_usd,+ },+ "planned_attempts": self.planned,+ "started_attempts": self._started,+ "finished_attempts": self._finished,+ "unmeasured_attempts": {+ "agent_tokens": self.unmeasured_agent_attempts,+ "judge_calls": self.unmeasured_judge_attempts,+ "cost_usd": self.unmeasured_cost_attempts,+ },+ "used": {+ "agent_tokens": self.used_agent_tokens if self.used_agent_tokens is not None else "not measured",+ "judge_calls": self.used_judge_calls if self.used_judge_calls is not None else "not measured",+ "cost_usd": self.used_cost_usd if self.used_cost_usd is not None else "not measured",+ },+ "status": "exhausted" if self.exhausted_limit else "ok",+ "partial": bool(self.not_run),+ "exhausted_limit": self.exhausted_limit,+ "attempts_not_run": len(self.not_run),+ "not_run": list(self.not_run),+ }++ @staticmethod+ def _not_run(agent: str, arm: str, case_id: str, attempt: int) -> dict[str, Any]:+ return {+ "agent": agent,+ "arm": arm,+ "case_id": case_id,+ "attempt": attempt,+ "status": "not_run",+ "reason": "budget_exhausted",+ }+++def budget_line(metadata: dict[str, Any]) -> str:+ status = metadata.get("status")+ if status != "exhausted":+ return "Budget: within configured limits"+ used = metadata.get("used") or {}+ limit = metadata.get("exhausted_limit") or "budget"+ value = used.get({"agent_tokens": "agent_tokens", "judge_calls": "judge_calls", "cost": "cost_usd"}.get(limit, ""))+ cap = (metadata.get("limits") or {}).get(+ {"agent_tokens": "max_agent_tokens", "judge_calls": "max_judge_calls", "cost": "max_cost_usd"}.get(limit, "")+ )+ shown = (+ "not measured"+ if value is None or value == "not measured"+ else (f"${value:.2f}" if limit == "cost" else f"{value:,}")+ )+ cap_shown = "not configured" if cap is None else (f"${cap:.2f}" if limit == "cost" else f"{cap:,}")+ planned = metadata.get("planned_attempts")+ not_run = metadata.get("attempts_not_run", len(metadata.get("not_run") or []))+ if limit == "attempts":+ started = metadata.get("started_attempts", 0)+ cap = (metadata.get("limits") or {}).get("max_attempts_total", "not configured")+ return (+ f"Budget exhausted (attempts {started:,} of {cap:,}): "+ f"{not_run:,} of {planned:,} attempts not run; results are partial"+ )+ return (+ f"Budget exhausted ({limit.replace('_', ' ')} {shown} of {cap_shown}): "+ f"{not_run:,} of {planned:,} attempts not run; results are partial"+ )diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.pyindex b613976b..deb69a7c 100644--- a/src/skillevaluator/tier3/harbor/runner.py+++ b/src/skillevaluator/tier3/harbor/runner.py@@ -4647,6 +4647,214 @@ def _merge_attempt_jobs(job_dirs: list[Path], aggregate_dir: Path) -> None:)+def _budget_usage(job_dir: Path) -> dict[str, Any]:+ """Read attempt usage from Harbor's retained trajectory and judge artifacts."""+ usage: dict[str, Any] = {}+ for trajectory_path in job_dir.glob("**/trajectory.json"):+ try:+ payload = json.loads(trajectory_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ continue+ final_metrics = payload.get("final_metrics", {}) if isinstance(payload, dict) else {}+ if isinstance(final_metrics, dict):+ prompt = final_metrics.get("total_prompt_tokens")+ completion = final_metrics.get("total_completion_tokens")+ cached = final_metrics.get("total_cached_tokens")+ cost = final_metrics.get("total_cost_usd")+ if isinstance(prompt, int) and isinstance(completion, int):+ usage["input_tokens"] = usage.get("input_tokens", 0) + prompt+ usage["output_tokens"] = usage.get("output_tokens", 0) + completion+ if isinstance(cached, int) and not isinstance(cached, bool):+ usage["cached_input_tokens"] = usage.get("cached_input_tokens", 0) + cached+ if isinstance(cost, int | float) and not isinstance(cost, bool):+ usage["cost_usd"] = usage.get("cost_usd", 0.0) + float(cost)+ judge_calls = 0+ saw_judge_artifact = False+ for artifact_path in job_dir.glob("**/judge_attempts.json"):+ saw_judge_artifact = True+ try:+ payload = json.loads(artifact_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ continue+ attempts = payload.get("attempts") if isinstance(payload, dict) else payload+ if isinstance(attempts, list):+ judge_calls += sum(+ 1 for attempt in attempts if isinstance(attempt, dict) and attempt.get("method") != "salvage"+ )+ if saw_judge_artifact:+ usage["judge_calls"] = judge_calls+ return usage+++def _resolve_harbor_price_file(+ price_file: Path | None, harbor_config: Mapping[str, Any], source_skill_dir: Path+) -> Path | None:+ if price_file is not None:+ return Path(price_file).expanduser().resolve()+ configured = harbor_config.get("price_file")+ if not configured:+ return None+ path = Path(str(configured)).expanduser()+ return (path if path.is_absolute() else source_skill_dir / path).resolve()+++def _run_budgeted_variants(+ *,+ skill_name: str,+ agent: str,+ jobs: list[tuple[str, Path, str | None]],+ task_names: list[str],+ env_mode: str,+ model: str,+ jobs_dir: Path,+ run_env: dict[str, str],+ n_attempts: int,+ pass_threshold: float,+ stop_on_pass: bool,+ timeout_multiplier: float,+ override_cpus: int | None,+ override_memory_mb: int | None,+ override_storage_mb: int | None,+ budget: Any,+ n_concurrent: int,+ verifier_env: Mapping[str, str] | None = None,+ environment_kwargs: Mapping[str, Any] | None = None,+ cancellation: _HarborRunCancellation | None = None,+) -> dict[str, list[str]]:+ errors: dict[str, dict[tuple[int, int], str]] = {variant: {} for variant, _, _ in jobs}+ attempt_job_dirs: dict[str, dict[tuple[int, int], Path]] = {variant: {} for variant, _, _ in jobs}+ result_lock = threading.Lock()++ def run_unit(task_index: int, task_name: str, attempt: int) -> bool:+ if cancellation is not None:+ cancellation.raise_if_requested()+ admissions = [+ {"agent": agent, "arm": variant, "case_id": task_name, "attempt": attempt} for variant, _, _ in jobs+ ]+ if not budget.admit_many(admissions):+ return False+ passed = True+ for variant, dataset, job_import_path in jobs:+ if cancellation is not None:+ cancellation.raise_if_requested()+ job_name = f"{skill_name}-{agent}-{variant}-{task_name}-attempt{attempt:03d}"+ ok, detail = _run_harbor(+ dataset=dataset,+ agent=agent,+ job_name=job_name,+ env_mode=env_mode,+ model=model,+ jobs_dir=jobs_dir,+ run_env=run_env,+ n_attempts=1,+ n_concurrent=1,+ timeout_multiplier=timeout_multiplier,+ override_cpus=override_cpus,+ override_memory_mb=override_memory_mb,+ override_storage_mb=override_storage_mb,+ agent_import_path=job_import_path,+ verifier_env=verifier_env,+ environment_kwargs=environment_kwargs,+ expected_trials=1,+ include_task_names=[task_name],+ cancellation=cancellation,+ )+ job_dir = jobs_dir / job_name+ budget.record_usage(_budget_usage(job_dir), model=model)+ with result_lock:+ attempt_job_dirs[variant][(task_index, attempt)] = job_dir+ if ok:+ for key, error in list(errors[variant].items()):+ failed_dir = attempt_job_dirs[variant].get(key)+ if (+ key[0] == task_index+ and error.endswith(": Harbor job did not complete successfully: 1 errored")+ and failed_dir is not None+ and harbor_timeout_job_recovered(failed_dir, job_dir)+ ):+ errors[variant].pop(key)+ else:+ errors[variant][(task_index, attempt)] = (+ f"{agent} {variant}-skill Harbor run failed: {task_name} attempt {attempt}: {detail}"+ )+ passed = passed and ok and _job_passed(job_dir, pass_threshold)+ return passed++ def run_case(task_index: int, task_name: str) -> None:+ for attempt in range(1, n_attempts + 1):+ if run_unit(task_index, task_name, attempt) and stop_on_pass:+ break++ worker_count = max(1, min(n_concurrent, len(task_names) or 1))+ with ThreadPoolExecutor(max_workers=worker_count) as executor:+ if stop_on_pass:+ futures = [executor.submit(run_case, index, task_name) for index, task_name in enumerate(task_names)]+ else:+ futures = [+ executor.submit(run_unit, index, task_name, attempt)+ for index, task_name in enumerate(task_names)+ for attempt in range(1, n_attempts + 1)+ ]+ for future in as_completed(futures):+ future.result()+ for variant, _, _ in jobs:+ _merge_attempt_jobs(+ [attempt_job_dirs[variant][key] for key in sorted(attempt_job_dirs[variant])],+ jobs_dir / f"{skill_name}-{agent}-{variant}",+ )+ return {variant: [errors[variant][key] for key in sorted(errors[variant])] for variant, _, _ in jobs}+++def _run_budgeted_variant(+ *,+ skill_name: str,+ agent: str,+ variant: str,+ dataset: Path,+ task_names: list[str],+ env_mode: str,+ model: str,+ jobs_dir: Path,+ run_env: dict[str, str],+ n_attempts: int,+ pass_threshold: float,+ stop_on_pass: bool,+ timeout_multiplier: float,+ override_cpus: int | None,+ override_memory_mb: int | None,+ override_storage_mb: int | None,+ budget: Any,+ n_concurrent: int = 1,+ agent_import_path: str | None = None,+ verifier_env: Mapping[str, str] | None = None,+ environment_kwargs: Mapping[str, Any] | None = None,+ cancellation: _HarborRunCancellation | None = None,+) -> list[str]:+ errors = _run_budgeted_variants(+ skill_name=skill_name,+ agent=agent,+ jobs=[(variant, dataset, agent_import_path)],+ task_names=task_names,+ env_mode=env_mode,+ model=model,+ jobs_dir=jobs_dir,+ run_env=run_env,+ n_attempts=n_attempts,+ pass_threshold=pass_threshold,+ stop_on_pass=stop_on_pass,+ timeout_multiplier=timeout_multiplier,+ override_cpus=override_cpus,+ override_memory_mb=override_memory_mb,+ override_storage_mb=override_storage_mb,+ budget=budget,+ n_concurrent=n_concurrent,+ verifier_env=verifier_env,+ environment_kwargs=environment_kwargs,+ cancellation=cancellation,+ )+ return errors[variant]++def _run_stop_on_pass_variant(*,skill_name: str,@@ -4834,6 +5042,7 @@ def _run_agent_pair(cancellation: _HarborRunCancellation | None = None,additional_arms: Sequence[tuple[str, Path, str | None]] = (),additional_arm_errors: dict[str, str] | None = None,+ budget_controller: Any = None,) -> list[str]:"""Run ordinary and privately requested arms under one per-agent trial budget."""jobs = [] if with_skill is None else [("with", with_skill, with_agent_import_path or agent_import_path)]@@ -4853,6 +5062,34 @@ def _run_agent_pair(additional_arm_errors[variant] = _bounded_execution_error("; ".join(failures))return []+ if budget_controller is not None:+ budget_errors: list[str] = []+ failures_by_variant = _run_budgeted_variants(+ skill_name=skill_name,+ agent=agent,+ jobs=jobs,+ task_names=list(task_names or []),+ env_mode=env_mode,+ model=model,+ jobs_dir=jobs_dir,+ run_env=run_env,+ n_attempts=n_attempts,+ pass_threshold=pass_threshold,+ stop_on_pass=stop_on_pass,+ timeout_multiplier=timeout_multiplier,+ override_cpus=override_cpus,+ override_memory_mb=override_memory_mb,+ override_storage_mb=override_storage_mb,+ budget=budget_controller,+ n_concurrent=n_concurrent,+ verifier_env=verifier_env,+ environment_kwargs=environment_kwargs,+ cancellation=cancellation,+ )+ for variant, failures in failures_by_variant.items():+ budget_errors.extend(record_failure(variant, failures))+ return budget_errors+if stop_on_pass:# A case's later attempt is launched only after its previous one# scored. Up to n_concurrent cases run at once, and the conditions run@@ -5077,6 +5314,11 @@ def _run_harbor_eval_impl(skip_baseline: bool = False,skip_with_skill: bool = False,n_attempts: int | None = None,+ max_agent_tokens: int | None = None,+ max_judge_calls: int | None = None,+ max_attempts_total: int | None = None,+ max_cost_usd: float | None = None,+ price_file: Path | None = None,pass_threshold: float | None = None,stop_on_pass: bool | None = None,n_concurrent: int | None = None,@@ -5198,6 +5440,13 @@ def _run_harbor_eval_impl(n_concurrent = n_concurrent if n_concurrent is not None else harbor_config.get("n_concurrent", 4)max_agents = max_agents if max_agents is not None else harbor_config.get("max_agents", len(agents))max_cases = max_cases if max_cases is not None else harbor_config.get("max_cases")+ max_agent_tokens = max_agent_tokens if max_agent_tokens is not None else harbor_config.get("max_agent_tokens")+ max_judge_calls = max_judge_calls if max_judge_calls is not None else harbor_config.get("max_judge_calls")+ max_attempts_total = (+ max_attempts_total if max_attempts_total is not None else harbor_config.get("max_attempts_total")+ )+ max_cost_usd = max_cost_usd if max_cost_usd is not None else harbor_config.get("max_cost_usd")+ price_file = _resolve_harbor_price_file(price_file, harbor_config, evaluator_skill_path)timeout_multiplier = (timeout_multiplier if timeout_multiplier is not None else harbor_config.get("timeout_multiplier", 1.0))@@ -6001,6 +6250,56 @@ def _run_harbor_eval_impl(task_selectors = expected_task_selectors or []case_id_by_task_selector = expected_case_id_by_task_selector or {}case_ids = [case_id_by_task_selector[selector] for selector in task_selectors]+ from skillevaluator.tier3.harbor.run_budget import (+ BudgetConfigurationError,+ BudgetController,+ PriceBook,+ planned_attempts,+ )++ if max_cost_usd is not None and price_file is None:+ return _persist_pre_execution_failure(["--max-cost-usd requires --price-file"])+ try:+ price_book = PriceBook.load(price_file) if price_file is not None else None+ if price_book is not None:+ for agent in agents:+ price_book.price_for(model_resolution[agent]["model"])+ base_arms = 2 - int(skip_baseline) - int(skip_with_skill)+ planned_arm_count = sum(base_arms + len(additional_arms.get(agent, ())) for agent in agents)+ budget = BudgetController(+ max_agent_tokens=max_agent_tokens,+ max_judge_calls=max_judge_calls,+ max_attempts_total=max_attempts_total,+ max_cost_usd=max_cost_usd,+ price_book=price_book,+ planned=planned_attempts(+ len(case_ids),+ n_attempts,+ 1,+ arms=planned_arm_count,+ stop_on_pass=bool(stop_on_pass),+ ),+ )+ except BudgetConfigurationError as exc:+ return _persist_pre_execution_failure([str(exc)])+ active_budget = (+ budget+ if any(limit is not None for limit in (max_agent_tokens, max_judge_calls, max_attempts_total, max_cost_usd))+ else None+ )+ multiply_sign = "\u00d7"+ reporter.emit(+ ProgressEvent(+ stage="configuration",+ state="complete",+ detail=(+ f"Planned: {budget.planned} attempts "+ f"({len(case_ids)} cases {multiply_sign} {n_attempts} attempts {multiply_sign} "+ f"{planned_arm_count} agent arms total)"+ ),+ )+ )+ run_config["budget"] = budget.metadata()try:dataset_truth = _persist_dataset_truth(run_dir, fallback_task_ids=case_ids)except DatasetSnapshotContractError as exc:@@ -6143,6 +6442,7 @@ def _run_harbor_eval_impl(stop_on_pass=bool(stop_on_pass),pass_threshold=float(pass_threshold),task_names=task_selectors,+ budget_controller=active_budget,verifier_env=job_judge_verifier_env,environment_kwargs=effective_environment_kwargs,cancellation=cancellation,@@ -6275,6 +6575,7 @@ def _run_harbor_eval_impl(agent_models=model_resolution,launch_errors=errors,grading_mode=grading_mode,+ budget_not_run=active_budget.not_run if active_budget is not None else [],)except Exception:reporter.emit(ProgressEvent(stage="collection", state="failed", detail="result collection failed"))@@ -6297,10 +6598,13 @@ def _run_harbor_eval_impl("dataset_summary": dataset_truth["dataset_summary"],"dataset_digest": dataset_truth["dataset_digest"],"dataset_digest_algorithm": dataset_truth["dataset_digest_algorithm"],+ "budget": budget.metadata(),"dataset_provenance": dataset_provenance,"run_config": run_config,+ "partial": bool(budget.not_run),})+ run_config["budget"] = budget.metadata()from skillevaluator.evaluation.tier3_report import (_agent_score_policy,_build_agent,diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.pyindex eb4f3a98..c256aed4 100644--- a/src/skillevaluator/tier3/harbor/templates/eval.py+++ b/src/skillevaluator/tier3/harbor/templates/eval.py@@ -2913,6 +2913,10 @@ def _record_judge_attempt(if score is not None:entry["score"] = scoreattempts.append(entry)+ _write_judge_attempts(attempts)+++def _write_judge_attempts(attempts):try:path = _verifier_output_dir() / JUDGE_ATTEMPTS_FILE_NAMEpath.parent.mkdir(parents=True, exist_ok=True)@@ -4051,7 +4055,8 @@ def main():)# Every judge attempt below is saved to judge_attempts.json as it happens.- judge_evidence_token = _ACTIVE_JUDGE_EVIDENCE.set([])+ judge_attempts = []+ judge_evidence_token = _ACTIVE_JUDGE_EVIDENCE.set(judge_attempts)try:# ── Eval 4: accuracy (LLM judge) ─────────────────────────────────acc_result = _call_required_judge(@@ -4117,6 +4122,7 @@ def main():details["behavior_check"] = bc_resultfinally:_ACTIVE_JUDGE_EVIDENCE.reset(judge_evidence_token)+ _write_judge_attempts(judge_attempts)# persist refs + omission metadata onto the metric detailsattach_metric_evidence_refs(details, {m: bundles[m]["evidence_refs"] for m in bundles})diff --git a/src/skillevaluator/tier3/result_display.py b/src/skillevaluator/tier3/result_display.pyindex 708b1147..d82997a5 100644--- a/src/skillevaluator/tier3/result_display.py+++ b/src/skillevaluator/tier3/result_display.py@@ -997,6 +997,13 @@ def render_evaluation_result(duration = result.get("duration_seconds")if _finite_number(duration) is not None:console.print(f"Time: {float(duration):.1f}s")+ budget = result.get("budget")+ if isinstance(budget, Mapping) and (+ budget.get("status") == "exhausted" or any(value is not None for value in (budget.get("limits") or {}).values())+ ):+ from skillevaluator.tier3.harbor.run_budget import budget_line++ console.print(budget_line(dict(budget)))provenance_line, provenance_is_template = dataset_provenance_display(result.get("dataset_provenance"))if provenance_line:console.print(Text(provenance_line, style="yellow" if provenance_is_template else "dim"))diff --git a/src/skillevaluator/tier3/workflow.py b/src/skillevaluator/tier3/workflow.pyindex aa2884d2..c35bd8c6 100644--- a/src/skillevaluator/tier3/workflow.py+++ b/src/skillevaluator/tier3/workflow.py@@ -133,12 +133,17 @@ def _preflight_options(skill_path: Path, params: dict[str, Any]) -> dict[str, An"n_concurrent","max_agents","max_cases",+ "max_agent_tokens",+ "max_judge_calls",+ "max_attempts_total",+ "max_cost_usd",+ "price_file","timeout_multiplier","agent_runtime_preflight","custom_dockerfile_mode",):if params.get(name) is not None:- harbor[name] = params[name]+ harbor[name] = str(params[name]) if name == "price_file" else params[name]for resource in ("cpus", "memory_mb", "storage_mb"):if params.get(f"override_{resource}") is not None:harbor.setdefault("resources", {})[resource] = params[f"override_{resource}"]diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.jsonindex cda043c8..61bff829 100644--- a/tests/golden/cli_surface.json+++ b/tests/golden/cli_surface.json@@ -831,6 +831,46 @@"param_type": "option","type": "integer"},+ {+ "name": "max_agent_tokens",+ "opts": [+ "--max-agent-tokens"+ ],+ "param_type": "option",+ "type": "integer range"+ },+ {+ "name": "max_judge_calls",+ "opts": [+ "--max-judge-calls"+ ],+ "param_type": "option",+ "type": "integer range"+ },+ {+ "name": "max_attempts_total",+ "opts": [+ "--max-attempts-total"+ ],+ "param_type": "option",+ "type": "integer range"+ },+ {+ "name": "max_cost_usd",+ "opts": [+ "--max-cost-usd"+ ],+ "param_type": "option",+ "type": "float range"+ },+ {+ "name": "price_file",+ "opts": [+ "--price-file"+ ],+ "param_type": "option",+ "type": "file"+ },{"name": "pass_threshold","opts": [@@ -2885,6 +2925,46 @@"param_type": "option","type": "integer"},+ {+ "name": "max_agent_tokens",+ "opts": [+ "--max-agent-tokens"+ ],+ "param_type": "option",+ "type": "integer range"+ },+ {+ "name": "max_judge_calls",+ "opts": [+ "--max-judge-calls"+ ],+ "param_type": "option",+ "type": "integer range"+ },+ {+ "name": "max_attempts_total",+ "opts": [+ "--max-attempts-total"+ ],+ "param_type": "option",+ "type": "integer range"+ },+ {+ "name": "max_cost_usd",+ "opts": [+ "--max-cost-usd"+ ],+ "param_type": "option",+ "type": "float range"+ },+ {+ "name": "price_file",+ "opts": [+ "--price-file"+ ],+ "param_type": "option",+ "type": "file"+ },{"name": "pass_threshold","opts": [@@ -3567,6 +3647,46 @@"param_type": "option","type": "integer"},+ {+ "name": "max_agent_tokens",+ "opts": [+ "--max-agent-tokens"+ ],+ "param_type": "option",+ "type": "integer range"+ },+ {+ "name": "max_judge_calls",+ "opts": [+ "--max-judge-calls"+ ],+ "param_type": "option",+ "type": "integer range"+ },+ {+ "name": "max_attempts_total",+ "opts": [+ "--max-attempts-total"+ ],+ "param_type": "option",+ "type": "integer range"+ },+ {+ "name": "max_cost_usd",+ "opts": [+ "--max-cost-usd"+ ],+ "param_type": "option",+ "type": "float range"+ },+ {+ "name": "price_file",+ "opts": [+ "--price-file"+ ],+ "param_type": "option",+ "type": "file"+ },{"name": "pass_threshold","opts": [@@ -4158,6 +4278,46 @@"param_type": "option","type": "integer"},+ {+ "name": "max_agent_tokens",+ "opts": [+ "--max-agent-tokens"+ ],+ "param_type": "option",+ "type": "integer range"+ },+ {+ "name": "max_judge_calls",+ "opts": [+ "--max-judge-calls"+ ],+ "param_type": "option",+ "type": "integer range"+ },+ {+ "name": "max_attempts_total",+ "opts": [+ "--max-attempts-total"+ ],+ "param_type": "option",+ "type": "integer range"+ },+ {+ "name": "max_cost_usd",+ "opts": [+ "--max-cost-usd"+ ],+ "param_type": "option",+ "type": "float range"+ },+ {+ "name": "price_file",+ "opts": [+ "--price-file"+ ],+ "param_type": "option",+ "type": "file"+ },{"name": "pass_threshold","opts": [diff --git a/tests/test_commands.py b/tests/test_commands.pyindex bf18805a..bd51258f 100644--- a/tests/test_commands.py+++ b/tests/test_commands.py@@ -1851,6 +1851,43 @@ def test_catalog_child_argv_forwards_every_validate_option() -> None:assert sorted(dropped) == sorted(not_forwarded)+def test_catalog_child_argv_forwards_run_budget_options(tmp_path: Path) -> None:+ from skillevaluator.cli import _catalog_child_argv_from_ctx, validate++ skill_dir = tmp_path / "catalog" / "simple"+ skill_dir.mkdir(parents=True)+ price_file = tmp_path / "prices.json"+ price_file.write_text("{}", encoding="utf-8")+ ctx = validate.make_context(+ "validate",+ [+ str(skill_dir),+ "--max-agent-tokens",+ "120",+ "--max-judge-calls",+ "5",+ "--max-attempts-total",+ "9",+ "--max-cost-usd",+ "2.5",+ "--price-file",+ str(price_file),+ ],+ )++ argv = _catalog_child_argv_from_ctx(ctx, skill_dir, tmp_path / "out" / "simple")++ for option, value in (+ ("--max-agent-tokens", "120"),+ ("--max-judge-calls", "5"),+ ("--max-attempts-total", "9"),+ ("--max-cost-usd", "2.5"),+ ("--price-file", str(price_file.resolve())),+ ):+ assert option in argv+ assert argv[argv.index(option) + 1] == value++def test_validate_catalog_workers_records_the_evaluated_source_on_every_card() -> None:runner = CliRunner()with runner.isolated_filesystem():diff --git a/tests/test_evaluation_service.py b/tests/test_evaluation_service.pyindex f67be86a..30d4e446 100644--- a/tests/test_evaluation_service.py+++ b/tests/test_evaluation_service.py@@ -281,6 +281,49 @@ def test_validate_helper_routes_environment_kwargs_to_shared_service(monkeypatch)+def test_validate_helper_forwards_budget_options(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ from skillevaluator import cli as cli_module+ from skillevaluator.evaluation import tier3_report+ from skillevaluator.models.result import ValidationResult++ captured = {}+ expected = ValidationResult(validator_name="AGENT_EVAL")+ expected.add_success("agent_eval", "ok")+ monkeypatch.setattr(+ EvaluationService,+ "evaluate",+ lambda _self, options, **_kwargs: (+ captured.update(options=options) or {"execution_status": "succeeded", "execution_errors": []}+ ),+ raising=True,+ )+ monkeypatch.setattr(tier3_report, "agent_eval_result_from_run", lambda *_args, **_kwargs: expected)+ price_file = tmp_path / "prices.json"++ actual = cli_module._run_agent_eval_or_skip(+ FIXTURE,+ agents="codex",+ env_mode="docker",+ skip_baseline=True,+ n_concurrent=1,+ max_agents=1,+ max_agent_tokens=1000,+ max_judge_calls=4,+ max_attempts_total=8,+ max_cost_usd=0.5,+ price_file=price_file,+ validate_source=False,+ )++ assert actual is expected+ options = captured["options"]+ assert options.max_agent_tokens == 1000+ assert options.max_judge_calls == 4+ assert options.max_attempts_total == 8+ assert options.max_cost_usd == 0.5+ assert options.price_file == price_file++def _autopilot_skill(tmp_path: Path) -> Path:skill = tmp_path / "simple"shutil.copytree(FIXTURE, skill)@@ -296,6 +339,36 @@ def _write_one_case(skill: Path, marker: str = "generated") -> None:)+def test_cli_evaluate_validates_cost_price_pair_after_config_merge(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ from skillevaluator.tier3 import evals_config++ skill = tmp_path / "skill"+ skill.mkdir()+ (skill / "SKILL.md").write_text("---\nname: skill\ndescription: Test\n---\n", encoding="utf-8")+ service_calls = []+ config = {"harbor": {"max_cost_usd": 0.5}}+ monkeypatch.setattr(evals_config, "load_evals_config", lambda _path: (config, None))+ monkeypatch.setattr(+ EvaluationService,+ "evaluate",+ lambda *_args, **_kwargs: service_calls.append(True) or {"execution_status": "succeeded"},+ )++ missing_price = CliRunner().invoke(cli, ["evaluate", str(skill), "--progress", "off"])+ assert missing_price.exit_code == 2+ assert "--max-cost-usd requires --price-file" in missing_price.output+ assert not service_calls++ config["harbor"]["price_file"] = "evals/prices.json"+ configured_price = CliRunner().invoke(cli, ["evaluate", str(skill), "--progress", "off"])+ assert configured_price.exit_code == 0, configured_price.output+ assert service_calls+++@pytest.mark.parametrize("command", ["validate", "evaluate", "tier3 evaluate"])@pytest.mark.parametrize(("flags", "diagnostic"),diff --git a/tests/test_tier3_progress.py b/tests/test_tier3_progress.pyindex bbabaabc..5ed8377b 100644--- a/tests/test_tier3_progress.py+++ b/tests/test_tier3_progress.py@@ -3304,6 +3304,7 @@ def test_runner_emits_truthful_stages_plan_and_per_agent_state(("with-skill-tasks", "ready"),("baseline-tasks", "running"),("baseline-tasks", "ready"),+ ("configuration", "complete"),("docker-images", "delegated"),("agent-runtime-preflight", "running"),("agent-runtime-preflight", "complete"),diff --git a/tests/tier3/test_judge_contracts.py b/tests/tier3/test_judge_contracts.pyindex 972e8fe9..628bdfb6 100644--- a/tests/tier3/test_judge_contracts.py+++ b/tests/tier3/test_judge_contracts.py@@ -440,6 +440,19 @@ def test_scored_trial_records_judge_contract_and_every_attempt(tmp_path: Path) -assert "Complete the task" in attempts[0]["prompt"]+def test_trial_without_judge_references_writes_empty_attempt_artifact(tmp_path: Path) -> None:+ verifier = _stage_verifier(+ tmp_path,+ {"id": "case-1", "question": "Inspect the output.", "ground_truth": "", "expected_behavior": []},+ )+ verifier.call_public_llm = lambda *_args, **_kwargs: pytest.fail("no judge reference")+ verifier._call_public_llm_with_provenance = lambda *_args, **_kwargs: pytest.fail("no judge reference")++ verifier.main()++ assert _attempts(verifier.VERIFIER_DIR) == []++def test_failed_judge_keeps_its_rejected_attempts_without_a_score(tmp_path: Path) -> None:verifier = _stage_verifier(tmp_path)calls: list[str] = []diff --git a/tests/tier3/test_run_budget.py b/tests/tier3/test_run_budget.pynew file mode 100644index 00000000..6e9e5631--- /dev/null+++ b/tests/tier3/test_run_budget.py@@ -0,0 +1,517 @@+import json+import threading+from concurrent.futures import ThreadPoolExecutor++import pytest+from rich.console import Console++from skillevaluator.tier3.harbor import runner+from skillevaluator.tier3.harbor.run_budget import (+ BudgetConfigurationError,+ BudgetController,+ Price,+ PriceBook,+ budget_line,+ planned_attempts,+)+++def test_planned_attempts_and_attempt_cap():+ assert planned_attempts(3, 2, 2) == 24+ budget = BudgetController(max_attempts_total=1, planned=24)+ assert budget.admit(agent="a", arm="with_skill", case_id="c1", attempt=1)+ assert not budget.admit(agent="a", arm="with_skill", case_id="c2", attempt=1)+ assert budget.metadata()["not_run"][0]["reason"] == "budget_exhausted"+ assert "Budget exhausted (attempts 1 of 1)" in budget_line(budget.metadata())+++def test_token_and_cost_admission():+ prices = PriceBook({"model": Price(input_per_mtok=1.0, output_per_mtok=2.0)})+ budget = BudgetController(max_agent_tokens=10, max_cost_usd=1.0, price_book=prices, planned=2)+ assert budget.admit(agent="a", arm="with_skill", case_id="c1", attempt=1)+ budget.record_usage({"total_tokens": 10, "total_cost_usd": 1.0})+ assert not budget.admit(agent="a", arm="with_skill", case_id="c2", attempt=1)+ assert budget.metadata()["exhausted_limit"] == "agent_tokens"+ assert (+ budget_line(budget.metadata())+ == "Budget exhausted (agent tokens 10 of 10): 1 of 2 attempts not run; results are partial"+ )+++def test_judge_call_and_priced_cost_caps():+ prices = PriceBook({"model": Price(input_per_mtok=1.0, output_per_mtok=2.0)})+ judge_budget = BudgetController(max_judge_calls=1)+ assert judge_budget.admit(agent="a", arm="with_skill", case_id="c1", attempt=1)+ judge_budget.record_usage({"judge_calls": 1})+ assert not judge_budget.admit(agent="a", arm="with_skill", case_id="c2", attempt=1)++ cost_budget = BudgetController(max_cost_usd=0.001, price_book=prices)+ assert cost_budget.admit(agent="a", arm="with_skill", case_id="c1", attempt=1)+ cost_budget.record_usage({"input_tokens": 1000, "output_tokens": 0}, model="model")+ assert not cost_budget.admit(agent="a", arm="with_skill", case_id="c2", attempt=1)+++def test_price_file_requires_each_used_model(tmp_path):+ path = tmp_path / "prices.json"+ path.write_text(json.dumps({"model": {"input_per_mtok": 1, "output_per_mtok": 2}}))+ prices = PriceBook.load(path)+ assert prices.price_for("model").output_per_mtok == 2+ assert prices.price_for("model").cached_input_per_mtok == prices.price_for("model").input_per_mtok+ with pytest.raises(BudgetConfigurationError):+ prices.price_for("other")+++def test_relative_configured_price_file_uses_source_skill_directory(tmp_path):+ from skillevaluator.tier3.harbor.runner import _resolve_harbor_price_file++ skill = tmp_path / "skill"+ price_file = skill / "evals" / "prices.json"+ price_file.parent.mkdir(parents=True)+ price_file.write_text("{}")+ assert _resolve_harbor_price_file(None, {"price_file": "evals/prices.json"}, skill) == price_file.resolve()+++def test_unknown_usage_is_not_measured():+ budget = BudgetController(max_agent_tokens=10)+ assert budget.admit(agent="a", arm="with_skill", case_id="c1", attempt=1)+ budget.record_usage({})+ assert budget.metadata()["used"]["agent_tokens"] == "not measured"+ assert not budget.admit(agent="a", arm="with_skill", case_id="c2", attempt=1)+ assert budget.metadata()["unmeasured_attempts"]["agent_tokens"] == 1+++def test_measured_usage_is_preserved_across_unmeasured_attempt():+ budget = BudgetController(max_agent_tokens=10_000)+ budget.record_usage({"total_tokens": 900})+ budget.record_usage({})+ budget.record_usage({"total_tokens": 100})+ assert budget.metadata()["used"]["agent_tokens"] == 1000+ assert budget.metadata()["unmeasured_attempts"]["agent_tokens"] == 1+++def test_cached_input_pricing_overrides_reported_cost():+ prices = PriceBook({"model": Price(2.0, 4.0, 1.0)})+ budget = BudgetController(price_book=prices)+ budget.record_usage(+ {+ "input_tokens": 1000,+ "total_cached_tokens": 400,+ "output_tokens": 100,+ "cost_usd": 99,+ },+ model="model",+ )+ assert budget.metadata()["used"]["cost_usd"] == pytest.approx(0.002)+++def test_empty_judge_attempt_artifact_counts_zero_and_allows_more_runs(tmp_path):+ job_dir = tmp_path / "job"+ artifact = job_dir / "trial" / "verifier" / "judge_attempts.json"+ artifact.parent.mkdir(parents=True)+ artifact.write_text(json.dumps({"attempts": []}))+ budget = BudgetController(max_judge_calls=1)+ budget.record_usage(runner._budget_usage(job_dir))+ assert budget.metadata()["used"]["judge_calls"] == 0+ assert budget.admit(agent="a", arm="with", case_id="next", attempt=1)+++def test_budget_usage_reads_cached_tokens_and_excludes_salvage(tmp_path):+ trajectory_dir = tmp_path / "trial" / "agent"+ verifier_dir = tmp_path / "trial" / "verifier"+ trajectory_dir.mkdir(parents=True)+ verifier_dir.mkdir()+ (trajectory_dir / "trajectory.json").write_text(+ json.dumps(+ {+ "final_metrics": {+ "total_prompt_tokens": 1000,+ "total_cached_tokens": 250,+ "total_completion_tokens": 100,+ }+ }+ )+ )+ (verifier_dir / "judge_attempts.json").write_text(+ json.dumps({"attempts": [{"method": "llm"}, {"method": "salvage"}, {"method": "ragas"}]})+ )++ usage = runner._budget_usage(tmp_path)++ assert usage == {+ "input_tokens": 1000,+ "output_tokens": 100,+ "cached_input_tokens": 250,+ "judge_calls": 2,+ }+++def test_budgeted_attempts_use_real_cancellation_object(monkeypatch, tmp_path):+ cancellation = runner._HarborRunCancellation()+ cancellation.requested.set()+ monkeypatch.setattr(runner, "_run_harbor", lambda **_kwargs: pytest.fail("must not start"))+ budget = BudgetController()+ with pytest.raises(runner._HarborRunCancelledError):+ runner._run_budgeted_variant(+ skill_name="skill",+ agent="agent",+ variant="with",+ dataset=tmp_path / "dataset",+ task_names=["case"],+ env_mode="docker",+ model="model",+ jobs_dir=tmp_path / "jobs",+ run_env={},+ n_attempts=1,+ pass_threshold=0.5,+ stop_on_pass=False,+ timeout_multiplier=1,+ override_cpus=None,+ override_memory_mb=None,+ override_storage_mb=None,+ budget=budget,+ cancellation=cancellation,+ )+++def test_budgeted_attempts_run_concurrently_up_to_limit(monkeypatch, tmp_path):+ barrier = threading.Barrier(2)+ active = 0+ peak = 0+ lock = threading.Lock()++ def fake_harbor(*, job_name, jobs_dir, **_kwargs):+ nonlocal active, peak+ with lock:+ active += 1+ peak = max(peak, active)+ barrier.wait(timeout=5)+ (jobs_dir / job_name).mkdir(parents=True)+ with lock:+ active -= 1+ return True, ""++ monkeypatch.setattr(runner, "_run_harbor", fake_harbor)+ monkeypatch.setattr(runner, "_merge_attempt_jobs", lambda *_: None)+ runner._run_budgeted_variant(+ skill_name="skill",+ agent="agent",+ variant="with",+ dataset=tmp_path / "dataset",+ task_names=["one", "two"],+ env_mode="docker",+ model="model",+ jobs_dir=tmp_path / "jobs",+ run_env={},+ n_attempts=1,+ pass_threshold=0.5,+ stop_on_pass=False,+ timeout_multiplier=1,+ override_cpus=None,+ override_memory_mb=None,+ override_storage_mb=None,+ budget=BudgetController(),+ n_concurrent=2,+ )+ assert peak == 2+++def test_in_flight_agents_are_not_rejected_for_missing_usage(monkeypatch, tmp_path):+ barrier = threading.Barrier(2)+ starts = []+ lock = threading.Lock()++ def fake_harbor(*, job_name, jobs_dir, **_kwargs):+ with lock:+ starts.append(job_name)+ barrier.wait(timeout=5)+ (jobs_dir / job_name).mkdir(parents=True)+ return True, ""++ monkeypatch.setattr(runner, "_run_harbor", fake_harbor)+ monkeypatch.setattr(runner, "_merge_attempt_jobs", lambda *_: None)+ budget = BudgetController(max_agent_tokens=100_000)++ def run_agent(agent):+ return runner._run_budgeted_variant(+ skill_name="skill",+ agent=agent,+ variant="with",+ dataset=tmp_path / "dataset",+ task_names=["case"],+ env_mode="docker",+ model="model",+ jobs_dir=tmp_path / "jobs",+ run_env={},+ n_attempts=1,+ pass_threshold=0.5,+ stop_on_pass=False,+ timeout_multiplier=1,+ override_cpus=None,+ override_memory_mb=None,+ override_storage_mb=None,+ budget=budget,+ )++ with ThreadPoolExecutor(max_workers=2) as executor:+ list(executor.map(run_agent, ["first", "second"]))+ assert len(starts) == 2+ assert budget.metadata()["finished_attempts"] == 2+++def test_budget_admits_both_arms_as_one_case_attempt(monkeypatch, tmp_path):+ starts = []++ def fake_harbor(*, job_name, jobs_dir, **_kwargs):+ starts.append(job_name)+ trajectory = jobs_dir / job_name / "trial" / "agent"+ trajectory.mkdir(parents=True)+ (trajectory / "trajectory.json").write_text(+ json.dumps({"final_metrics": {"total_prompt_tokens": 1, "total_completion_tokens": 0}})+ )+ return True, ""++ monkeypatch.setattr(runner, "_run_harbor", fake_harbor)+ monkeypatch.setattr(runner, "_merge_attempt_jobs", lambda *_: None)+ budget = BudgetController(max_agent_tokens=2)+ runner._run_budgeted_variants(+ skill_name="skill",+ agent="agent",+ jobs=[("with", tmp_path / "with", None), ("without", tmp_path / "without", None)],+ task_names=["first", "second"],+ env_mode="docker",+ model="model",+ jobs_dir=tmp_path / "jobs",+ run_env={},+ n_attempts=1,+ pass_threshold=0.5,+ stop_on_pass=False,+ timeout_multiplier=1,+ override_cpus=None,+ override_memory_mb=None,+ override_storage_mb=None,+ budget=budget,+ n_concurrent=1,+ )+ assert len(starts) == 2+ assert any("-with-first-" in name for name in starts)+ assert any("-without-first-" in name for name in starts)+ assert budget.metadata()["attempts_not_run"] == 2+++def test_partial_budget_run_collects_real_harbor_results(monkeypatch, tmp_path):+ import shutil+ from datetime import UTC, datetime+ from uuid import UUID++ from harbor.models.job.result import JobResult, JobStats+ from harbor.models.trial.result import TrialResult++ from skillevaluator.tier3.harbor.collector import _extract_rewards, collect_harbor_results+ from skillevaluator.tier3.harbor.metrics import DEFAULT_METRIC_SET, DEFAULT_METRICS++ jobs_dir = tmp_path / "jobs"+ starts = []+ now = datetime(2026, 1, 1, tzinfo=UTC)++ def write_job_result(job_dir, task_selector, attempt, score):+ trial_name = f"{task_selector}__attempt-{attempt}"+ trial_dir = job_dir / trial_name+ verifier_dir = trial_dir / "verifier"+ verifier_dir.mkdir(parents=True)+ (trial_dir / "agent").mkdir()+ reward = {+ "entry_id": task_selector,+ "_attempt_ordinal": attempt,+ "metric_set": DEFAULT_METRIC_SET,+ **dict.fromkeys(DEFAULT_METRICS, score),+ }+ numeric_reward = dict.fromkeys(DEFAULT_METRICS, score)+ (verifier_dir / "reward.json").write_text(json.dumps(numeric_reward))+ (verifier_dir / "skill_evaluator_reward.json").write_text(json.dumps(reward))+ (trial_dir / "agent" / "trajectory.json").write_text(+ json.dumps({"final_metrics": {"total_prompt_tokens": 500, "total_completion_tokens": 0}})+ )+ trial = TrialResult.model_validate(+ {+ "id": UUID(int=len(starts) + 1),+ "task_name": task_selector,+ "trial_name": trial_name,+ "trial_uri": trial_dir.as_uri(),+ "task_id": {"path": task_selector},+ "task_checksum": "budget-fixture",+ "config": {"task": {"path": task_selector}, "trial_name": trial_name},+ "agent_info": {+ "name": "codex",+ "version": "fixture",+ "model_info": {"name": "fixture-model"},+ },+ "agent_result": {"n_input_tokens": 500, "n_output_tokens": 0},+ "verifier_result": {"rewards": numeric_reward},+ "started_at": now,+ "finished_at": now,+ "step_results": None,+ }+ )+ (trial_dir / "result.json").write_text(trial.model_dump_json())+ result = JobResult(+ id=UUID(int=len(starts) + 100),+ started_at=now,+ updated_at=now,+ finished_at=now,+ n_total_trials=1,+ stats=JobStats.from_trial_results([trial], n_total_trials=1),+ trial_results=[trial],+ )+ (job_dir / "result.json").write_text(result.model_dump_json())++ def fake_harbor(*, job_name, jobs_dir, **_kwargs):+ starts.append(job_name)+ variant = "with" if "-with-" in job_name else "without"+ task_selector = job_name.split(f"agent-{variant}-", 1)[1].rsplit("-attempt", 1)[0]+ attempt = int(job_name.rsplit("-attempt", 1)[1])+ write_job_result(jobs_dir / job_name, task_selector, attempt, 0.8 if variant == "with" else 0.6)+ return True, ""++ def merge_attempts(source_dirs, aggregate_dir):+ trials = []+ for source_dir in source_dirs:+ source = JobResult.model_validate_json((source_dir / "result.json").read_text())+ trials.extend(source.trial_results or [])+ aggregate_dir.mkdir(parents=True, exist_ok=True)+ for source_dir in source_dirs:+ for trial_dir in source_dir.iterdir():+ if trial_dir.is_dir():+ shutil.copytree(trial_dir, aggregate_dir / trial_dir.name, dirs_exist_ok=True)+ result = JobResult(+ id=UUID(int=999),+ started_at=now,+ updated_at=now,+ finished_at=now,+ n_total_trials=len(trials),+ stats=JobStats.from_trial_results(trials, n_total_trials=len(trials)),+ trial_results=trials,+ )+ (aggregate_dir / "result.json").write_text(result.model_dump_json())++ monkeypatch.setattr(runner, "_run_harbor", fake_harbor)+ monkeypatch.setattr(runner, "_merge_attempt_jobs", merge_attempts)+ budget = BudgetController(max_agent_tokens=2500, planned=12)+ errors = runner._run_budgeted_variants(+ skill_name="skill",+ agent="agent",+ jobs=[("with", tmp_path / "with", None), ("without", tmp_path / "without", None)],+ task_names=["case-1", "case-2", "case-3"],+ env_mode="docker",+ model="fixture-model",+ jobs_dir=jobs_dir,+ run_env={},+ n_attempts=2,+ pass_threshold=0.5,+ stop_on_pass=False,+ timeout_multiplier=1,+ override_cpus=None,+ override_memory_mb=None,+ override_storage_mb=None,+ budget=budget,+ n_concurrent=1,+ )+ assert not any(errors.values())+ collected = _extract_rewards(+ jobs_dir / "skill-agent-with",+ {case_id: case_id for case_id in ("case-1", "case-2", "case-3")},+ )+ assert len(collected) == 3, collected+ results = collect_harbor_results(+ "skill",+ ["agent"],+ tmp_path / "results",+ jobs_dir,+ n_attempts=2,+ expected_cases=3,+ expected_case_ids=["case-1", "case-2", "case-3"],+ case_id_by_task_selector={case_id: case_id for case_id in ("case-1", "case-2", "case-3")},+ expected_trials=6,+ budget_not_run=budget.not_run,+ )+ agent_result = results["agents"]["agent"]+ assert results["partial"] is True+ assert agent_result["execution_status"] == "succeeded", agent_result.get("execution_errors") or agent_result+ assert agent_result["num_trials_with"] == 3+ assert len(starts) == 6+++def test_fake_attempt_runner_stops_after_token_budget(monkeypatch, tmp_path):+ starts = []++ def fake_harbor(*, job_name, jobs_dir, **_kwargs):+ starts.append(job_name)+ job_dir = jobs_dir / job_name+ trajectory_dir = job_dir / "trial" / "agent"+ trajectory_dir.mkdir(parents=True)+ (trajectory_dir / "trajectory.json").write_text(+ json.dumps({"final_metrics": {"total_prompt_tokens": 8, "total_completion_tokens": 4}})+ )+ return True, ""++ monkeypatch.setattr(runner, "_run_harbor", fake_harbor)+ monkeypatch.setattr(runner, "_merge_attempt_jobs", lambda *_: None)+ budget = BudgetController(max_agent_tokens=10, planned=3)+ runner._run_budgeted_variant(+ skill_name="skill",+ agent="agent",+ variant="with",+ dataset=tmp_path / "dataset",+ task_names=["case"],+ env_mode="docker",+ model="model",+ jobs_dir=tmp_path / "jobs",+ run_env={},+ n_attempts=3,+ pass_threshold=0.5,+ stop_on_pass=False,+ timeout_multiplier=1,+ override_cpus=None,+ override_memory_mb=None,+ override_storage_mb=None,+ budget=budget,+ )+ assert len(starts) == 1+ assert budget.metadata()["attempts_not_run"] == 2+++def test_evaluate_summary_renders_budget_warning():+ from skillevaluator.tier3.result_display import render_evaluation_result++ output = Console(record=True, force_terminal=False, width=160)+ result = {+ "execution_status": "failed",+ "budget": {+ "limits": {"max_agent_tokens": 1000},+ "used": {"agent_tokens": 1000},+ "status": "exhausted",+ "exhausted_limit": "agent_tokens",+ "planned_attempts": 3,+ "attempts_not_run": 2,+ "not_run": [{}, {}],+ },+ }+ render_evaluation_result(result, console=output)+ assert (+ "Budget exhausted (agent tokens 1,000 of 1,000): 2 of 3 attempts not run; results are partial"+ in output.export_text()+ )+++def test_html_overview_renders_budget_warning():+ from skillevaluator.models.result import ValidationResult+ from skillevaluator.reporting import HTMLReporter++ result = ValidationResult(validator_name="AGENT_EVAL", validator_description="Live evaluation")+ result.metadata["agent_eval"] = {+ "execution_status": "failed",+ "budget": {"status": "exhausted", "not_run": [{}, {}]},+ "budget_summary": "Budget exhausted (agent tokens 1,000 of 1,000): 2 of 3 attempts not run; results are partial",+ }+ html = HTMLReporter(include_timestamp=False).render_all([result])+ assert "Budget exhausted (agent tokens 1,000 of 1,000): 2 of 3 attempts not run; results are partial" in html+ assert 'class="warning"' in htmldiff --git a/tests/tier3/test_workflow.py b/tests/tier3/test_workflow.pyindex df1e3e59..02ec15a4 100644--- a/tests/tier3/test_workflow.py+++ b/tests/tier3/test_workflow.py@@ -66,8 +66,10 @@ def configured(monkeypatch: pytest.MonkeyPatch) -> list:return captured-def test_direct_workflow_reuses_dataset_and_forwards_evaluation_options(skill, configured, monkeypatch):+def test_direct_workflow_reuses_dataset_and_forwards_evaluation_options(skill, configured, monkeypatch, tmp_path):dataset = _dataset(skill)+ price_file = skill / "evals" / "prices.json"+ price_file.write_text('{"nvidia/test-model": {"input_per_mtok": 1, "output_per_mtok": 2}}')original = dataset.read_bytes()monkeypatch.setattr(EvaluationService, "create_autopilot_dataset", lambda *_args, **_kwargs: pytest.fail("must reuse")@@ -81,6 +83,16 @@ def test_direct_workflow_reuses_dataset_and_forwards_evaluation_options(skill, c"--skip-baseline","--n-attempts","3",+ "--max-agent-tokens",+ "1000",+ "--max-judge-calls",+ "4",+ "--max-attempts-total",+ "12",+ "--max-cost-usd",+ "0.25",+ "--price-file",+ str(price_file),"--no-agent-runtime-preflight","--progress","off",@@ -95,6 +107,11 @@ def test_direct_workflow_reuses_dataset_and_forwards_evaluation_options(skill, cassert configured[0].skip_baseline is Trueassert configured[0].n_attempts == 3assert configured[0].agent_runtime_preflight is False+ assert configured[0].max_agent_tokens == 1000+ assert configured[0].max_judge_calls == 4+ assert configured[0].max_attempts_total == 12+ assert configured[0].max_cost_usd == 0.25+ assert configured[0].price_file == price_fileassert configured[0].agent_model == ("opencode=nvidia/nvidia/test-model",)assert configured[0].results_dir == skill.parent / "results"assert "reusing" in result.output.lower()@@ -669,11 +686,7 @@ def test_gke_workflow_resolves_env_vars_and_enforces_precedence_before_preflightfrom skillevaluator.tier3.harbor import runner_dataset(skill)- (skill / "evals" / "config.yml").write_text(- "schema_version: 1\n"- "harbor:\n"- " n_attempts: 1\n"- )+ (skill / "evals" / "config.yml").write_text("schema_version: 1\nharbor:\n n_attempts: 1\n")gke_env = {"SKILLEVALUATOR_GKE_CLUSTER": "env-cluster","SKILLEVALUATOR_GKE_REGION": "us-central1",