Skip to content

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.

fix(tier3): use one overall-score formula (#124)

Saibernard Yogendran340e84901ef0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 76cd4b5b..db55af5f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -112,252 +112,16 @@ All notable changes to SkillEvaluator are documented in this file.
### Fixed
-- Preserve explicit Claude and OpenCode read failure metadata in reconstructed
- ATIF trajectories. Failed isolated SKILL.md reads and failed native Skill
- calls lose credit; compound shell failures and shell reads whose path may
- expand to several files (braces, globs, `$` or backticks) remain ambiguous
- and retain prior credit in host and verifier grading. Unattributed errors do
- not cancel successful reads, and shell reads count dash-prefixed filenames
- after `--`.
-- Tier 1 pyproject dependency audits now inspect static target declarations
- rather than the evaluator environment. Exact direct pins (including optional
- groups) are queried without installation or build-script execution;
- unresolved declarations and invalid scanner evidence are incomplete.
-- Tier 1 PII scanning now includes `.mdc` rules and workflows.
-- Tier 3 negative-case accuracy excludes inapplicable skill identification and
- records its scoring policy. Reports separately expose measured token and
- agent execution-time differences with complete matching-arm coverage, while
- efficiency continues to measure routing and productive tool use.
-- Derive accuracy scores from complete criterion verdicts in both judge
- runtimes (passing applicable criteria divided by applicable criteria), so an
- inconsistent model-supplied total cannot distort Skill Lift. Correct the
- Harbor prompt example to score five passing criteria as 1.0.
-- Include schema-valid ATIF message content parts in final answers, conversation
- summaries, and judge evidence references in the host and Harbor verifier.
- Image and audio parts use markers without exposing their source paths.
-- Preserve scored Harbor trials when agent answers mention authentication errors
- and per-step token usage is present but aggregate ATIF token metrics are absent
- or zero. Explicit runtime exceptions and error events still invalidate trials.
-- Safety-classifier refusals, content filters and output-token truncation are
- detected instead of being read as empty or malformed output. `--llm-verify`
- and rubric evaluation report the cause, and `--llm-verify` keeps the
- complete verdicts of a truncated reply. Claude 5.5 or later requests to the
- native Claude API use server-side fallback to Claude Opus 4.8. In the Harbor
- verifier, Bedrock retries a filtered Claude 5.5 reply on Claude Opus 4.8, and
- a refusal or empty judge reply moves on to the next
- `LLM_JUDGE_FALLBACK_MODELS` entry.
-- The Harbor verifier's last-resort judge model follows the selected provider.
- With no judge or chat model configured, it used to request an OpenAI model
- from Anthropic, Bedrock, NVIDIA Build and gateways. The unused host-side
- `llm_judge.DEFAULT_JUDGE_MODEL` constant is removed.
-- Fixed Docker Codex and Claude Code setup wasting its timeout installing
- distribution Node/npm before Harbor's own installers. Native, gateway Codex,
- and NVIDIA Build agents now provision Node/npm only on the installer branches
- that need them, while preserving installed-agent and version-pin checks.
-- Preserved multiline skill descriptions when saving and loading Tier 2
- embedding catalogs. Descriptions can contain line breaks and tabs, while
- catalog identifiers and other control characters remain strictly validated.
-- Brought the published documentation in line with 0.5.0. It now covers how
- standard grading builds judge evidence and rebuilds trajectories from
- OpenCode and Codex logs, structured judge output and retries, the evidence
- budget and judge time-budget variables, and the Harbor process environment.
- The CLI reference adds `validate --workers`, the full `--env-mode` list, and
- the exit codes the CLI actually returns (`0`, `1`, `2`).
-- `BENCHMARK.md` publication verdicts now require completed Tier 1 and Tier 2
- execution evidence by default (Tier 1 must cover every default check that
- applies to the content type, so a run narrowed with `--checks` cannot
- certify publication), conservatively resolve conflicting peer
- policy and Tier 3 result metadata, bind every tier and policy claim to one
- versioned source-tree digest, preserve the Tier 3 run ID, persist an explicit
- publication status in JSON and HTML, and reject
- publication `PASS` cards whose decision evidence is missing, incomplete,
- linked, or hidden in raw HTML. Tier 3 evidence now cross-checks complete
- per-condition attempt and error records, and the public-card gate rejects
- ambiguous structural headings, browser-rendered decision-text aliases, and
- literal or entity-encoded Unicode control/format characters. The source
- identity is read without following links before and after each producer,
- follows the host filesystem's case aliases, and records a bounded
- source-change marker. Tier 3 runs that stage repository context, external
- reference or workspace skills, or task inputs with `.git`, `.venv`,
- `__pycache__`, or `node_modules` entries remain runnable but cannot certify
- publication, and neither can a target whose authored paths below the root
- use names that Tier 1 skips (such as `references/results/`).
-- Clean and not-applicable License, Code Risk, Secrets, and Dependency Audit
- runs now record structured execution evidence, so legitimate built-in Tier 1
- results can satisfy publication without relying on findings or errors.
-- Skip reasons are bounded, control-free, and escaped in reports and in the
- terminal, so oversized metadata, Rich markup, or terminal escape sequences
- cannot corrupt them. Reports show one line; the pipeline view keeps the
- reason's line breaks.
-- SkillSpector issue paths with NUL bytes or lone surrogates now make the
- security scan incomplete instead of being accepted.
-- The public benchmark gate rejects `PASS` cards with placeholder identities,
- malformed or future evaluation dates, a missing Tier 3 run ID, hostile
- benchmark-policy metadata, or environment-label substitutions in required
- proof fields.
-- Hardened Tier 3 HTML and Markdown reporting against recursive or malformed
- display metadata, Markdown structure injection, and inline-JavaScript
- injection through untrusted agent or skill names.
-
-## 0.5.0 - 2026-10-06
-
-### Added
-
-- Transparent HTTP 429 (rate-limiting), transient 5xx, and timeout recovery for
- LLM judges in both the Harbor container verifier (`eval.py`) and host runtime
- (`LLMClient`). Features zero-dependency full jitter exponential backoff,
- RFC-7231 `Retry-After` header parsing, finite-value environment overrides
- (`SKILL_EVAL_LLM_MAX_RETRIES`, `SKILL_EVAL_LLM_RETRY_BASE_DELAY`, and
- `SKILL_EVAL_LLM_RETRY_MAX_DELAY`), and
- automatic container forwarding via Harbor `task.toml`, and a per-judge
- verifier time budget that leaves room for failure artifacts, without altering
- benchmark metrics or scoring formulas.
-- Provider-aware structured JSON schema enforcement (`response_format` for
- OpenAI-compatible / Gemini Vertex / NVIDIA NIM endpoints and `output_config`
- for Anthropic `/v1/messages`) across the custom `judge_accuracy`,
- `judge_goal_accuracy`, and `judge_behavior_check` paths, with automatic
- schema-specific `HTTP 400`/`422` downgrade and per-target memoization
- (`_SCHEMA_UNSUPPORTED_TARGETS`), boolean prompt alignment, and a guard for
- missing `message` fields on reasoning token exhaustion. The canonical OpenAI
- RAGAS goal scorer retains its separate scoring path.
-- Configurable evidence bundle budgets (`SKILL_EVAL_ACCURACY_BUDGET`, `SKILL_EVAL_GOAL_ACCURACY_BUDGET`, `SKILL_EVAL_BEHAVIOR_CHECK_BUDGET`) and final response limit (`SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT`).
-- Tier 3 log converters now rebuild ATIF trajectories from OpenCode JSON streams
- (`opencode.txt`) and structured Codex tee logs (`codex.txt`) when
- `trajectory.json` is missing or empty.
-
-### Changed
-
-- Upgraded the optional Tier 3 backend to Harbor 0.24.0 and its compatible
- LiteLLM 1.92-1.93 window. Existing SkillEvaluator agent and environment
- options now use Harbor's unified selectors; installed Codex adapters preserve
- merged user and MCP configuration; Docker and local execution stream redacted
- callbacks under a shared 16 MiB per-command output limit, while the parent
- Harbor orchestration process has a separate 16 MiB combined stdout/stderr
- limit; and Docker supports stdin plus isolated sidecar operations without
- exposing environment values on Compose argv. Generated schema 1.3 and
- unmodified native task schemas remain compatible, while collection accepts
- Harbor 0.24 job, trial, reward, and ATIF v1.8 artifacts. Multimodal tool
- output reaches judges and reports as text with `[image]`/`[audio]` markers.
- Native tasks' own test scripts must write numeric `reward.json` values, which
- Harbor 0.24 enforces; a failed job now names the trial or step exception that
- Harbor recorded.
-- Exposed 23 Harbor 0.24 backends alongside local mode. `cua-cloud`,
- `opensandbox`, `hf-sandbox`, `podman`, `kata`, `runta`, `prime`, `mosaic`,
- and `smol` remain disabled until generated tasks can be projected through a
- trusted image or backend-native provisioning path. Non-secret backend
- constructor options can be supplied with repeatable, operator-only
- `--environment-kwarg` / `--ek` flags; skill-owned configuration,
- credentials, and sandbox-policy overrides remain outside that surface.
- Harbor's `stream` and `enable_environment_dir_upload` options are reserved,
- and Modal's `modal_sandbox_v2` option no longer exists.
-- `--env-mode wandb` now runs Harbor's `cwsandbox` backend with W&B
- authentication, because Harbor 0.24 merged the two. Install
- `harbor[cwsandbox]==0.24.0` instead of the removed `harbor[wandb]` extra.
-- Harbor now always starts in an empty, evaluator-owned working directory with
- `.env` loading and Harbor telemetry disabled. A `.env.local` or `.env` file
- near the operator's project can no longer add credentials or settings that
- SkillEvaluator's allowlisted environment removed. The `tier3` extra requires
- python-dotenv 1.2.0.
-- Codex runs with `reasoning_effort=high`, the default under Harbor 0.22, so
- scores and cost stay comparable after Harbor stopped pinning it.
-- Native tasks follow Harbor 0.24's separate-verifier precedence. A dedicated
- verifier image or build definition must ship its own test script and never
- receives SkillEvaluator's grader. Otherwise the verifier is built from
- `environment/`, whose Compose model must stay within the verifier's
- environment allowlist. `docker-compose.yml` verifier definitions, which
- Harbor ignores, are rejected.
-
-### Fixed
-
-- Report non-string YAML keys as validation errors in skills, rules, workflows,
- and plugin manifests instead of raising a `TypeError`, including frontmatter
- `metadata` keys. Show boolean, null, and date keys in a readable YAML form.
-- Harbor ``result.json`` case ids now prefer canonical ``task_id.path`` metadata
- over repository-prefixed ``task_name`` values when resolving eval entries.
-- Codex log synthesis maps ``web_search`` action payloads and ``collab_tool_call``
- thread items into ATIF, and error-recovery checks recognize ``status=failed`` /
- ``exit_code=`` terminal evidence emitted by Codex converters.
-- Tier 3 Harbor dual-arm evaluation propagates arm suffixes (`-with-skill`,
- `-without-skill`) to `[task] name` in staged native `task.toml` files,
- normalizes external repository and namespace prefixes, and commutatively
- resolves canonical case IDs across attempt and arm suffix combinations
- while preserving expected case IDs.
-- Tier 3 native-task collection now keeps Harbor's staged directory selector,
- logical dataset ID, and display name separate; ambiguous or unresolved
- persisted identities fail closed instead of trusting grader-authored IDs.
- Runner-owned attempt ordinals are carried structurally, so `attempt`-like
- text in authored selectors, logical IDs, or display names cannot corrupt
- pass@k or `stop_on_pass` accounting, including truncated aggregate names.
-- Tier 3 Harbor subprocess, Docker, and local diagnostics now redact raw and
- percent-decoded URI/proxy userinfo components across streamed callbacks,
- nonzero exits, timeouts, output limits, and persisted launch errors.
-- Tier 3 local OpenCode runs routed through NVIDIA Build now retain the rendered
- user instruction for ATIF conversion and fail on OpenCode error events, in
- parity with Harbor's upstream agent lifecycle. Remote MCP servers in that
- configuration disable OAuth, as Harbor's own OpenCode configuration does.
-- Tier 3 reports now use the collector's logical attempt overall whenever a
- condition mixes standard and custom rewards, including across separate
- trials, and aggregate execution summaries preserve child-declared hidden
- error counts and truncation through launch-error overlays.
-- Tier 3 now rejects non-finite, overflowing, and finite-but-unscalable timeout
- multipliers at YAML, programmatic, and Harbor command boundaries.
-- Tier 3 now preserves paired baseline isolation by rejecting skill-owned
- pre-agent setup, native task/step healthchecks, native step workdir overlays,
- and Harbor task-shipped prior trajectories whenever the baseline arm is
- enabled. Native standard grading also fails closed on step test overlays,
- separate verifier contexts, post-agent collect hooks, and task-controlled
- verifier executable-path, shell, loader, proxy/TLS, provider, and judge
- environment controls; exact operator-staged provider/judge placeholders and
- unrelated verifier variables remain compatible. Operator-configured judge
- fallback models are forwarded only to standard verifier jobs, not agent or
- `custom_only` environments. Its Python payload now runs from a replaced
- evaluator-owned directory in isolated mode. `custom_only`
- retains Harbor-native collect hooks and Harbor's shared/separate
- step-test resolution, and fully authored native test paths are left untouched
- instead of replacing their unused `tests/skill_evaluator/` package.
- All native grading modes reject Windows agent or effective verifier
- environments until evaluator projection and verifier scripts are OS-aware.
-- Tier 3 collection now fails closed on unsafe reward identities and malformed
- custom-metric contracts, publishes exact truncation metadata for bounded
- case and failure-detail samples, and keeps findings, attribution, and
- per-trial JSON inside the report loader's artifact envelope.
-- Tier 3 progress output, diagnostics, and result summaries no longer redact
- counts such as `0/1 scored` or `1 errored` when a credential-named
- environment variable holds a short flag value such as `1`. Short credential
- fragments in proxy URLs are still redacted.
-- `create-eval-dataset --refine` no longer requires the `tier3` extra to read
- case IDs from Harbor result files, and no longer fails on multimodal
- trajectory messages.
-
-## 0.4.0 - 2026-09-30
-
-### Fixed
-
-- Render untrusted skill content, paths, tool messages, and LLM output literally
- in CLI reports and logs. Escape Rich markup and strip terminal control
- sequences to prevent rendering failures and misleading output, including
- catalog summaries and the compact validation view. Preserve Windows paths
- and literal emoji codes
- ([#173](https://github.com/NVIDIA/SkillEvaluator/pull/173),
- [#175](https://github.com/NVIDIA/SkillEvaluator/pull/175)).
-- Make sensitive-assignment, JWT, and private-key redaction linear-time,
- preventing long adversarial text from stalling logs and reports. Apply the
- JWT fix to Tier 3 command output and the bundled Harbor verifier
- ([#172](https://github.com/NVIDIA/SkillEvaluator/pull/172),
- [#176](https://github.com/NVIDIA/SkillEvaluator/pull/176)).
-- `--no-llm` full datasets include a negative bucket only when eval guidance
- supplies an off-skill prompt; template mode no longer guesses canned
- negatives from a fixed question list. CLI and docs now describe `--full` as
- up to four cases instead of always four.
-- Treat `apply_patch` file headers (`*** Add File:`, `*** Update File:`, `*** Delete File:`,
- `*** Move to:`) as write targets in the Tier 3 security check. A patch that targets a shell
- profile, SSH, credential, or privileged config path, sent as an `apply_patch` tool call or a
- shell heredoc, is now a critical `sensitive_file_write` finding whose evidence names the
- protected path, not the patch. Every header in the patch is checked.
-- Mask GitHub tokens (`ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_`, and `github_pat_`) in Tier 3
- evidence excerpts and Harbor verifier log output.
-- Stop the PII scan reporting User-Agent product versions such as `Chrome/140.0.0.0`
- as public IP addresses. Chromium's reduced User-Agent gives every version this shape.
+- Tier 3 now uses one versioned, equal-weight five-dimension overall-score
+ policy across Harbor rewards, pass@k, Skill Lift, reports, comparisons, and
+ best-agent selection. Previously, some paths averaged all six evaluators
+ directly while reports averaged five dimensions, which gave Effectiveness
+ two votes and could reverse the reported lift direction. Current artifacts
+ persist `skill-evaluator-dimension-mean-v1`; legacy and partial artifacts
+ retain their historical semantics. Conditions keep their own recorded metric
+ sets; overall lift and best-agent rankings are omitted across incomparable
+ metric sets while individual scores are preserved
+ (Relates to [#61](https://github.com/NVIDIA/SkillEvaluator/issues/61)).
- Separate Tier 2 collection limits from the 256-file per-skill limit. Fresh
similarity scans now allow 1,024 selected manifests and 128 million scalar
comparisons by default, covering 343 skills with 2,048-dimensional embeddings.
@@ -577,46 +341,14 @@ All notable changes to SkillEvaluator are documented in this file.
### Fixed
-- Fully covered documentation-only skills no longer fail security validation
- solely because non-applicable SkillSpector analyzers report a partial status
- ([#137](https://github.com/NVIDIA/SkillEvaluator/issues/137)).
-- Embedding chunking now rejects zero-sized or non-progressing windows before
- entering the splitter or contacting the embedding provider
- ([#139](https://github.com/NVIDIA/SkillEvaluator/issues/139)).
-- Scoped network exfiltration command flag patterns in security checks, enforcing command-position anchoring, quote-aware argument segmentation, explicit HTTP method flags, and case-sensitive `-F`/`-d`/`-T` flags to prevent false-positive flags on safe URLs, packages, or download scripts while reliably detecting quoted secrets and subshell wrappers.
-- Malformed, non-UTF-8, or unreadable bundled and custom policy files now
- produce path-specific CLI errors instead of leaking raw parser or I/O errors
- ([#128](https://github.com/NVIDIA/SkillEvaluator/issues/128)).
-- `create-eval-dataset --refine` resolves Harbor trial case ids from persisted
- `reward.json` `entry_id` metadata, using folder-name parsing only as an
- unambiguous legacy fallback.
-- Tier 3 local mode now drops evaluator-managed empty process-loader resets
- while continuing to reject non-empty loader overrides, allowing generated
- tasks to reach agent execution
- ([#132](https://github.com/NVIDIA/SkillEvaluator/issues/132)).
-- Unpinned-dependency warnings are no longer suppressed by comparison
- operators inside PEP 508 environment markers; requirements such as
- `pkg; python_version < "3.13"` are now correctly reported, while direct
- references are treated as pinned independently of marker contents.
-- Schema, frontmatter, quality parsing, and security PII scanning accept a leading
- UTF-8 BOM, matching the unicode scanner's "benign BOM" note
- ([#91](https://github.com/NVIDIA/SkillEvaluator/issues/91)).
-- SPDX headers keep the full license expression, so `MIT OR GPL-3.0` is
- no longer truncated to MIT and allowed. Closing comment markers such as
- `*/` and `-->` are not treated as part of the expression
- ([#86](https://github.com/NVIDIA/SkillEvaluator/issues/86)).
-- Windows personal-path PII now flags `C:\Users\...` usernames that start with
- `s` (for example `steve`), matching the intended whitespace class rather than
- excluding the letter `s` ([#87](https://github.com/NVIDIA/SkillEvaluator/issues/87)).
-- Quality scoring, script lint, and `create-eval-dataset` now treat `tools/`
- the same as `scripts/` for executable helpers.
-- License detection no longer treats a frontmatter `license` identifier as
- authoritative when a LICENSE file declares a different license. Claiming
- MIT while shipping GPL-3.0 now fails closed. Every LICENSE/COPYING file is
- reconciled, NOTICE files stay informational, an unidentified license file is
- not treated as absent, and a blocking conflict no longer publishes
- `license_status=allowed`
- ([#85](https://github.com/NVIDIA/SkillEvaluator/issues/85)).
+- Tier 3 now uses one versioned, equal-weight five-dimension overall-score
+ policy across Harbor rewards, pass@k, Skill Lift, reports, comparisons, and
+ best-agent selection. Previously, some paths averaged all six evaluators
+ directly while reports averaged five dimensions, which gave Effectiveness
+ two votes and could reverse the reported lift direction. Current artifacts
+ persist `skill-evaluator-dimension-mean-v1`; legacy and partial artifacts
+ retain their historical semantics
+ (Relates to [#61](https://github.com/NVIDIA/SkillEvaluator/issues/61)).
- `--llm-verify` now refuses to send file context from paths outside the
skill root, including `..`, absolute paths, and outbound file symlinks.
- Gitleaks path allowlist now skips test/example/fixture/mock directories
diff --git a/docs/reports.mdx b/docs/reports.mdx
index 3a8a929a..c6e8393a 100644
--- a/docs/reports.mdx
+++ b/docs/reports.mdx
@@ -362,25 +362,57 @@ command.
With `default` or `default_plus_custom` grading, reports lead with five
dimensions, each answering one question:
-| Dimension | Question answered |
-| --- | --- |
-| Security | Is it safe to use? |
-| Correctness | Is the answer correct? |
-| Discoverability | Was the right skill loaded when needed? |
-| Effectiveness | Did the skill help complete the task? |
-| Efficiency | Did it avoid wasted tool or skill usage? |
-
-Dimension scores are 0.0–1.0 rollups of the underlying evaluation signals. The
-verdict bands are fixed: a dimension **passes** at 0.50 or above, is
-**neutral** from 0.40 to below 0.50, and **fails** below 0.40. The judge runs on
-the configured provider model; override it per run as described in
-[Tier 3: Live Evaluation](tier3-live-evaluation.mdx).
+| Dimension | Question answered | Signals and source |
+| --- | --- | --- |
+| Security | Is it safe to use? | `security`, from deterministic trace checks |
+| Correctness | Is the answer correct? | `accuracy`, from the `judge_accuracy` LLM judge |
+| Discoverability | Was the right skill loaded when needed? | `skill_execution`, from deterministic trajectory checks |
+| Effectiveness | Did the skill help complete the task? | `goal_accuracy` and `behavior_check`, from LLM judges |
+| Efficiency | Did it avoid wasted tool or skill usage? | `skill_efficiency`, from deterministic trajectory checks |
+
+Every evaluator and dimension score is on a 0.0 to 1.0 scale. The generated
+standard grader rejects non-finite values and clamps numeric scores with
+`max(0.0, min(1.0, score))`. A failed required judge produces no score instead
+of a numeric zero. The fixed dimension bands are **pass** at 0.50 or above,
+**neutral** from 0.40 to below 0.50, and **fail** below 0.40.
+
+`run_config.json` records the configured judge provider, model, source, and
+catalog-verification status separately from the agent model. `result.json`
+embeds that run configuration alongside the scores. This provenance makes the
+LLM-judged values traceable, but it is not evidence that the judges are
+validated. The repository does not publish inter-rater agreement, calibration
+results, or a comparison against human-labeled ground truth.
+
+The **Quality Score** displayed out of 100 in the HTML report is the Tier 1
+static-analysis score. It is not an input to the Tier 3 dimensions, overall
+score, or Skill Lift.
+
+The standard overall score gives each dimension one equal vote:
+
+```text
+overall = (Security + Correctness + Discoverability + Effectiveness + Efficiency) / 5
+Effectiveness = (goal_accuracy + behavior_check) / 2
+```
+
+This formula is shared by the report, per-attempt pass@k thresholding, Skill
+Lift, comparisons, and best-agent selection. Standard artifacts identify it as
+`skill-evaluator-dimension-mean-v1` in `score_policy` and in the persisted
+attempt policy. Older metric sets and partial historical artifacts keep their
+legacy policy rather than being rescored as current data.
+
+Overall comparisons require both the same scoring policy and the same metric
+set. A shared policy name alone does not make five-metric and six-metric means
+comparable. When two conditions use different metric sets under the same
+policy, their individual scores and shared per-metric deltas remain available,
+but overall Skill Lift and the pass@k comparison are omitted. Reports containing
+agents scored on different metric sets retain their individual scores and mark
+the overall comparison as incomplete, without selecting a best agent.
### Skill Lift
-Skill Lift is the with-skill score minus the without-skill baseline — the
-direct measurement of what your skill contributes. Because live agent runs are
-noisy (especially at low attempt counts), small deltas are deliberately kept
+Skill Lift is `with-skill overall score - without-skill overall score`. It uses
+the same score units as both arms and ranges from -1.0 to +1.0. Because live
+agent runs are noisy, especially at low attempt counts, small deltas are kept
neutral. The verdict bands:
| Lift | Verdict | Read it as |
@@ -416,7 +448,8 @@ they do not measure evaluator tokens, setup time, price, or statistical savings.
pass@k is the reliability signal, reported separately from the dimension
scores. With `--n-attempts k`, each eval case runs k times per arm, and a case
counts as passed when at least one attempt clears the `--pass-threshold`
-score. Comparing pass@k across arms (in `pass_at_k_lift.json`) tells you
+score using the same overall formula above. Comparing pass@k across arms (in
+`pass_at_k_lift.json`) tells you
whether the skill makes success more *repeatable*, not just whether the average
score moved. Each arm also records a case-level 95% Wilson score interval for
its pass rate. When both arms contain the same identified cases,
diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdx
index 00e3d08d..5948ab25 100644
--- a/docs/tier3-live-evaluation.mdx
+++ b/docs/tier3-live-evaluation.mdx
@@ -699,13 +699,48 @@ rollups, followed by a compact Artifacts panel pointing at the report and
output directory. A failed run renders the same structured display instead of
a bare exception.
-| Dimension | Key question | Maps to | Weights |
-| --- | --- | --- | --- |
-| Security | Is it safe to use? | `security` | 1.0 |
-| Correctness | Is the answer correct? | `accuracy` | 1.0 |
-| Discoverability | Was the right skill loaded when needed? | `skill_execution` | 1.0 |
-| Effectiveness | Did the skill help complete the task? | `goal_accuracy` + `behavior_check` | 0.5 + 0.5 |
-| Efficiency | Did it avoid wasted tool or skill usage? | `skill_efficiency` | 1.0 |
+Every evaluator score and dimension score is on a 0.0 to 1.0 scale. The
+generated standard grader rejects non-finite values and clamps numeric scores
+with `max(0.0, min(1.0, score))`. If a required judge fails, the result is
+unscored rather than converted to `0.0`.
+
+| Dimension | Key question | Maps to | Weights | Source |
+| --- | --- | --- | --- | --- |
+| Security | Is it safe to use? | `security` | 1.0 | Deterministic checks of the trace and agent actions |
+| Correctness | Is the answer correct? | `accuracy` | 1.0 | LLM judge (`judge_accuracy`) |
+| Discoverability | Was the right skill loaded when needed? | `skill_execution` | 1.0 | Deterministic checks of the trajectory and tool calls |
+| Effectiveness | Did the skill help complete the task? | `goal_accuracy` + `behavior_check` | 0.5 + 0.5 | LLM judges (`judge_goal_accuracy`, `judge_behavior_check`) |
+| Efficiency | Did it avoid wasted tool or skill usage? | `skill_efficiency` | 1.0 | Deterministic checks of the trajectory and tool calls |
+
+The run's configured judge provider and model are stored under `judge` in
+`run_config.json`, separately from the agent's provider and model. The same run
+configuration is embedded in `result.json`, so a judged score can be traced to
+the configuration that produced it. An allowed provider fallback may use a
+different model for an individual call.
+
+This provenance does not establish that the LLM judgments are correct. The
+repository does not publish inter-rater agreement, calibration results, or a
+comparison against human-labeled ground truth for these judges.
+
+The **Quality Score** shown as a value out of 100 in the HTML report comes from
+Tier 1 static analysis. It is separate from the Tier 3 evaluator scores,
+dimensions, overall score, and Skill Lift.
+
+For standard grading, the overall score is the equal-weight mean of these five
+dimensions:
+
+```text
+overall = (Security + Correctness + Discoverability + Effectiveness + Efficiency) / 5
+Effectiveness = (goal_accuracy + behavior_check) / 2
+```
+
+Effectiveness therefore enters the overall score once; its two source
+evaluators do not receive an extra combined vote. The same aggregate drives
+per-attempt pass@k, Skill Lift, comparison output, and best-agent selection.
+Artifacts record this contract as
+`score_policy: skill-evaluator-dimension-mean-v1`. Legacy metric sets and
+historical partial reports retain their recorded scoring semantics instead of
+being silently reinterpreted.
`token_efficiency` is a standalone report signal, not a dimension source. It
never changes a dimension score or the overall verdict.
@@ -730,8 +765,9 @@ agent passes only when every dimension passes. The top-level Tier 3 verdict is:
| Neutral | No agent passes, but at least one has no dimension below 0.40 |
| Fail | Every successful agent has a dimension below 0.40 |
-Skill Lift is the signed difference between the with-skill result and the
-without-skill baseline. Its independent band is **PASS** at +0.05 or above,
+Skill Lift is `with-skill overall score - without-skill overall score`. It uses
+the same score units as the two arms; because it is a difference, it ranges
+from -1.0 to +1.0. Its independent band is **PASS** at +0.05 or above,
**NEUTRAL** between -0.10 and +0.05, and **FAIL** at -0.10 or below. Lift is
diagnostic evidence and does not override the every-dimension gate.
@@ -750,7 +786,7 @@ The canonical Tier 3 payload embedded by both standalone `evaluate` and
`validate --agent-eval` reports uses schema version 2.0. A completed
standard-grading payload includes the summary, five dimensions, per-agent
results, trials, pass@k, attempt policy, run-owned dataset summary and digest,
-evaluation timestamp, evaluator version, and verdict policy; advisory or
+evaluation timestamp, evaluator version, score policy, and verdict policy; advisory or
skipped payloads may leave live-evidence sections empty.
Generated `BENCHMARK.md` cards put the verdict first, label each result column
diff --git a/src/skillevaluator/constants.py b/src/skillevaluator/constants.py
index c6eb814d..c2b1705f 100644
--- a/src/skillevaluator/constants.py
+++ b/src/skillevaluator/constants.py
@@ -511,6 +511,7 @@ AGENT_EVAL_SCORE_DEFINITION = (
"overall = mean(Security, Correctness, Discoverability, Effectiveness, Efficiency) "
"dimensions; Security maps to security evaluator (fallback: behavior_check)"
)
+DEFAULT_SCORE_POLICY = "skill-evaluator-dimension-mean-v1"
AGENT_EVAL_VERDICT_PASS = "pass"
AGENT_EVAL_VERDICT_NEUTRAL = "neutral"
diff --git a/src/skillevaluator/evaluation/tier3_report.py b/src/skillevaluator/evaluation/tier3_report.py
index feb3b64a..18a39a50 100644
--- a/src/skillevaluator/evaluation/tier3_report.py
+++ b/src/skillevaluator/evaluation/tier3_report.py
@@ -30,6 +30,7 @@ from skillevaluator import __version__
from skillevaluator.constants import (
AGENT_EVAL_EVALUATORS,
AGENT_EVAL_SCORE_DEFINITION,
+ DEFAULT_SCORE_POLICY,
DIMENSION_HINTS,
DIMENSION_MAPPING,
DIMENSION_VERDICT_NEUTRAL_THRESHOLD,
@@ -90,13 +91,16 @@ def _finite_float(value: object) -> float | None:
return numeric if math.isfinite(numeric) else None
-def _token_counter(value: object) -> int | None:
- """Return one browser-safe token count, preserving unavailable as null."""
- return (
- value
- if isinstance(value, int) and not isinstance(value, bool) and 0 <= value <= _MAX_JSON_SAFE_INTEGER
- else None
- )
+def _unit_interval_score(value: object) -> float | None:
+ """Return a finite score in the documented 0.0 to 1.0 range."""
+ numeric = _finite_float(value)
+ return numeric if numeric is not None and 0.0 <= numeric <= 1.0 else None
+
+
+def _skill_lift_value(value: object) -> float | None:
+ """Return a finite Skill Lift value in its documented -1.0 to 1.0 range."""
+ numeric = _finite_float(value)
+ return numeric if numeric is not None and -1.0 <= numeric <= 1.0 else None
def _sanitize_json_numbers(value: Any) -> Any:
@@ -241,7 +245,7 @@ def _advisory_agent_eval_payload(
"dataset_summary": dataset_summary,
"dataset_digest": None,
"dataset_digest_algorithm": None,
- "evaluated_source": None,
+ "score_policy": attempt_policy["score_policy"],
"verdict_policy": verdict_policy,
"execution_status": "skipped",
"execution_errors": [message],
@@ -281,7 +285,7 @@ def _advisory_agent_eval_payload(
"dataset_summary": dataset_summary,
"dataset_digest": None,
"dataset_digest_algorithm": None,
- "evaluated_source": None,
+ "score_policy": attempt_policy["score_policy"],
"verdict_policy": verdict_policy,
"provenance": {
"source": "advisory",
@@ -467,16 +471,13 @@ def agent_eval_result_from_directory(
run_truth = _run_truth_metadata(run_dir, engine_result, load_dataset_snapshot(run_dir))
dataset = run_truth.get("dataset") or load_staged_harbor_dataset(run_dir)
- publication_target = run_truth.get("publication_target")
- persisted_skill_name = publication_target.get("skill_name") if isinstance(publication_target, dict) else None
- skill_name = (
- persisted_skill_name if isinstance(persisted_skill_name, str) and persisted_skill_name else skill_path.name
- )
+ attempt_policy = _read_attempt_policy(run_dir)
payload = build_agent_eval_payload(
skill_name,
agents,
dataset=dataset,
- attempt_policy=_read_attempt_policy(run_dir),
+ attempt_policy=attempt_policy,
+ historical_missing_score_policy="score_policy" not in attempt_policy,
run_config=_read_run_config(run_dir),
env_mode=env_mode,
runtime_seconds=_runtime_seconds(engine_result),
@@ -598,10 +599,7 @@ def build_agent_eval_payload(
persisted_dataset_summary: dict[str, Any] | None = None,
dataset_digest: str | None = None,
dataset_digest_algorithm: str | None = None,
- run_id: str | None = None,
- publication_target: dict[str, str] | None = None,
- publication_target_conflict: str | None = None,
- evaluated_source: dict[str, Any] | None = None,
+ historical_missing_score_policy: bool = False,
use_llm_judge: bool = True,
) -> dict[str, Any] | None:
"""Assemble the canonical Tier 3 ``agent_eval`` payload from loaded agent data.
@@ -623,23 +621,54 @@ def build_agent_eval_payload(
metrics_for_condition,
)
+ metrics = metrics_for_agents(agents)
+ policy_metrics = _policy_metrics_from_agents(agents, metrics)
+
+ from skillevaluator.tier3.harbor.metrics import (
+ DEFAULT_METRICS,
+ LEGACY_SCORE_POLICY,
+ score_policy_for_metrics,
+ )
+
+ policy = dict(attempt_policy) if attempt_policy else _default_attempt_policy()
+ if not attempt_policy:
+ policy.pop("score_definition", None)
+ policy.pop("score_policy", None)
+ stored_policy = policy.get("score_policy")
+ if isinstance(stored_policy, str) and stored_policy.strip():
+ policy["score_policy"] = stored_policy.strip()
+ else:
+ recorded_policy = _recorded_score_policy(agents)
+ if recorded_policy is not None:
+ policy["score_policy"] = recorded_policy
+ elif historical_missing_score_policy and policy_metrics == DEFAULT_METRICS:
+ policy["score_policy"] = LEGACY_SCORE_POLICY
+ else:
+ policy["score_policy"] = score_policy_for_metrics(policy_metrics)
+ policy.setdefault(
+ "score_definition",
+ _score_definition_for_policy(policy_metrics, policy["score_policy"]),
+ )
+
report_budget = _ReportBudget(artifact_loading=_artifact_loading_reasons(agents, dataset))
agent_payloads: dict[str, dict[str, Any]] = {}
for name in sorted(agents):
info = agents[name]
model = _agent_model(name, info, run_config)
- agent_payloads[name] = _build_agent(
- name,
- info,
- metrics_for_condition(info, "with_skill"),
- metrics_for_condition(info, "without_skill"),
- model,
- )
+ agent_payloads[name] = _build_agent(name, info, metrics, model, policy["score_policy"])
if not agent_payloads:
return None
- best_agent = _pick_best_agent(agent_payloads)
+ scored_metric_sets = {
+ frozenset(agent["metrics_with_skill"])
+ for agent in agent_payloads.values()
+ if agent["execution_status"] == "succeeded" and agent["with_skill"] is not None
+ }
+ conflicting_metric_sets = len(scored_metric_sets) > 1
+ if conflicting_metric_sets and not conflicting_policies:
+ policy["score_definition"] = "overall unavailable: incomparable metric sets across agents"
+ best_agent = "" if conflicting_policies or conflicting_metric_sets else _pick_best_agent(agent_payloads)
detail_priority = ([best_agent] if best_agent else []) + [name for name in agent_payloads if name != best_agent]
for name in detail_priority:
_attach_agent_report_details(
@@ -664,6 +693,20 @@ def build_agent_eval_payload(
execution_status = "unknown"
else:
execution_status = "skipped"
+ if conflicting_policies:
+ execution_status = "failed"
+ execution_errors.append(
+ "Conflicting score policies across scored conditions: " + ", ".join(sorted(recorded_policies))
+ )
+ elif conflicting_metric_sets:
+ execution_status = "failed"
+ execution_errors.append("Incomparable metric sets across scored agents; overall ranking is unavailable")
+ elif policy["score_policy"] not in SUPPORTED_SCORE_POLICIES and any(
+ agent.get("execution_status") == "succeeded" and agent.get("with_skill") is None
+ for agent in agent_payloads.values()
+ ):
+ execution_status = "failed"
+ execution_errors.append("Unsupported score policy has no persisted overall score")
raw_overall_score = best.get("with_skill")
overall_score = _finite_float(raw_overall_score) if execution_status == "succeeded" else None
@@ -672,8 +715,6 @@ def build_agent_eval_payload(
metric_ids = list(best.get("evaluators", {}).keys())
metric_labels = _metric_labels(metric_ids)
-
- policy = attempt_policy or _default_attempt_policy()
canonical_trials = _flatten_trials(agent_payloads)
public_dataset = deduplicate_dataset_entries([entry for entry in (dataset or []) if isinstance(entry, dict)])
computed_dataset_truth = (
@@ -714,9 +755,7 @@ def build_agent_eval_payload(
"dataset_summary": dataset_summary,
"dataset_digest": effective_dataset_digest,
"dataset_digest_algorithm": effective_dataset_digest_algorithm,
- "run_id": run_id,
- "publication_target": dict(publication_target) if isinstance(publication_target, dict) else None,
- "evaluated_source": effective_evaluated_source,
+ "score_policy": policy["score_policy"],
"verdict_policy": verdict_policy,
"execution_status": execution_status,
"execution_errors": execution_errors,
@@ -780,9 +819,7 @@ def build_agent_eval_payload(
"dataset_summary": dataset_summary,
"dataset_digest": effective_dataset_digest,
"dataset_digest_algorithm": effective_dataset_digest_algorithm,
- "run_id": run_id,
- "publication_target": dict(publication_target) if isinstance(publication_target, dict) else None,
- "evaluated_source": effective_evaluated_source,
+ "score_policy": policy["score_policy"],
"verdict_policy": verdict_policy,
"agents": agent_payloads,
"dimensions": best_dimensions,
@@ -1209,6 +1246,14 @@ def _serialized_payload_size(payload: dict[str, Any]) -> int:
def _replace_with_minimal_payload(payload: dict[str, Any], report_budget: _ReportBudget) -> None:
"""Last-resort bounded shape for pathological single-field payloads."""
summary = payload.get("summary") if isinstance(payload.get("summary"), dict) else {}
+ attempt_policy = payload.get("attempt_policy") if isinstance(payload.get("attempt_policy"), dict) else {}
+ compact_attempt_policy = {
+ key: attempt_policy[key] for key in ("max_attempts", "pass_threshold", "stop_on_pass") if key in attempt_policy
+ }
+ for key, limit in (("score_definition", 1024), ("score_policy", 256)):
+ value = attempt_policy.get(key)
+ if isinstance(value, str):
+ compact_attempt_policy[key] = value[:limit]
compact_summary = {
key: value
for key, value in summary.items()
@@ -1220,6 +1265,7 @@ def _replace_with_minimal_payload(payload: dict[str, Any], report_budget: _Repor
"overall_lift",
"environment",
"runtime_seconds",
+ "score_policy",
"execution_status",
"execution_error_details_total",
"execution_error_details_shown",
@@ -1230,6 +1276,8 @@ def _replace_with_minimal_payload(payload: dict[str, Any], report_budget: _Repor
}
compact_summary["skill_name"] = str(summary.get("skill_name") or payload.get("skill_name") or "")[:256]
compact_summary["best_agent"] = str(summary.get("best_agent") or payload.get("best_agent") or "")[:256]
+ raw_score_policy = payload.get("score_policy", summary.get("score_policy"))
+ compact_summary["score_policy"] = raw_score_policy[:256] if isinstance(raw_score_policy, str) else None
compact_summary["agents_run"] = [str(name)[:256] for name in (summary.get("agents_run") or [])[:64]]
compact_summary["execution_errors"] = [str(error)[:1024] for error in (summary.get("execution_errors") or [])[:16]]
compact_summary.update(
@@ -1259,6 +1307,8 @@ def _replace_with_minimal_payload(payload: dict[str, Any], report_budget: _Repor
"expected_attempts": payload.get("expected_attempts", 0),
"scored_attempts": payload.get("scored_attempts", 0),
"runtime_seconds": payload.get("runtime_seconds", 0.0),
+ "score_policy": compact_summary["score_policy"],
+ "attempt_policy": compact_attempt_policy,
"agents": {},
"dimensions": [],
"evaluators": {},
@@ -1291,6 +1341,58 @@ def _replace_with_minimal_payload(payload: dict[str, Any], report_budget: _Repor
# ---------------------------------------------------------------------------
+def _policy_metrics_from_agents(
+ agents: dict[str, dict[str, Any]],
+ metrics: list[str],
+) -> tuple[str, ...]:
+ available = tuple(
+ metric
+ for metric in metrics
+ if any(
+ _finite_float(scores.get(metric)) is not None
+ for info in agents.values()
+ for scores in (info.get("with_skill"), info.get("without_skill"))
+ if isinstance(scores, dict)
+ )
+ )
+ return available or tuple(metrics)
+
+
+def _recorded_score_policy(agents: dict[str, dict[str, Any]]) -> str | None:
+ recorded: set[str] = set()
+ for info in agents.values():
+ for condition, scores_key, policy_key in (
+ ("with_skill", "with_skill", "score_policy_with_skill"),
+ ("without_skill", "without_skill", "score_policy_without_skill"),
+ ):
+ scores = info.get(scores_key)
+ policy = info.get(policy_key)
+ if (
+ _condition_quality_available(info, condition)
+ and isinstance(scores, dict)
+ and scores
+ and isinstance(policy, str)
+ and policy.strip()
+ ):
+ recorded.add(policy.strip())
+ return next(iter(recorded)) if len(recorded) == 1 else None
+
+
+def _score_definition_for_policy(metrics: tuple[str, ...], score_policy: str) -> str:
+ from skillevaluator.tier3.harbor.metrics import LEGACY_SCORE_POLICY, score_definition
+
+ if score_policy == LEGACY_SCORE_POLICY and metrics:
+ return f"overall = mean({', '.join(metrics)}) [{LEGACY_SCORE_POLICY}]"
+ return score_definition(metrics)
+
+
+def _complete_metric_mean(scores: dict[str, Any], metrics: list[str]) -> float | None:
+ values = tuple(_finite_float(scores.get(metric)) for metric in metrics)
+ if not values or any(value is None for value in values):
+ return None
+ return round(sum(value for value in values if value is not None) / len(values), 4)
+
+
def _condition_quality_available(info: dict[str, Any], condition: str) -> bool:
"""Return whether a condition may contribute score-bearing report fields."""
conditions = info.get("conditions")
@@ -1307,9 +1409,25 @@ def _build_agent(
with_metrics: list[str],
baseline_metrics: list[str],
model: str | None,
+ score_policy: str,
) -> dict[str, Any]:
+ from skillevaluator.tier3.harbor.metrics import (
+ LEGACY_METRICS,
+ LEGACY_SCORE_POLICY,
+ canonical_dimension_mean,
+ overall_score_from_metrics,
+ )
+ from skillevaluator.tier3.harbor.report_data import metrics_for_condition
+
with_scores = info.get("with_skill") or {}
without_scores = info.get("without_skill") or {}
+ with_metrics = metrics_for_condition(info, "with_skill")
+ without_metrics = metrics_for_condition(info, "without_skill")
+ condition_policies = {
+ value.strip() if isinstance(value, str) and value.strip() else score_policy
+ for value in (info.get("score_policy_with_skill"), info.get("score_policy_without_skill"))
+ }
+ comparable_scores = set(with_metrics) == set(without_metrics) and len(condition_policies) == 1
lift_data = info.get("lift") or {}
with_quality_available = _condition_quality_available(info, "with_skill")
baseline_quality_available = _condition_quality_available(info, "without_skill")
@@ -1325,50 +1443,81 @@ def _build_agent(
info.get("dimensions_with_skill") or {},
info.get("dimensions_without_skill") or {},
)
- overall_ws = _mean([d["with_skill"] for d in dimensions])
- overall_bl = _mean([d["baseline"] for d in dimensions])
- with_mixed_contract = with_quality_available and _condition_has_mixed_metric_contracts(
- info,
- flag="mixed_metric_contracts_with_skill",
- rewards="rewards",
- )
- baseline_mixed_contract = baseline_quality_available and _condition_has_mixed_metric_contracts(
- info,
- flag="mixed_metric_contracts_without_skill",
- rewards="rewards_baseline",
- )
- if with_mixed_contract or (overall_ws is None and not with_metrics and with_quality_available):
- # Custom-only runs have no dimension mean. For mixed condition
- # contracts, the dimension mean covers only standard rows and can
- # overstate Harbor's logical attempt score used by pass@k. In both
- # cases, prefer the collector-owned logical overall.
- overall_ws = _finite_float(info.get("overall_with_skill"))
+ with_dimension_values = [d["with_skill"] for d in dimensions]
+ baseline_dimension_values = [d["baseline"] for d in dimensions]
+ overall_ws = None
+ overall_bl = None
+ if score_policy == LEGACY_SCORE_POLICY:
+ overall_ws = _complete_metric_mean(with_scores, with_metrics) if with_quality_available else None
+ overall_bl = _complete_metric_mean(without_scores, without_metrics) if baseline_quality_available else None
+ if overall_ws is None and not with_scores and with_quality_available:
+ overall_ws = _unit_interval_score(info.get("overall_with_skill"))
+ if overall_bl is None and not without_scores and baseline_quality_available:
+ overall_bl = _unit_interval_score(info.get("overall_without_skill"))
+ elif score_policy == DEFAULT_SCORE_POLICY:
+ overall_ws = overall_score_from_metrics(with_scores, DEFAULT_METRICS) if with_quality_available else None
+ overall_bl = overall_score_from_metrics(without_scores, DEFAULT_METRICS) if baseline_quality_available else None
+ elif score_policy == PARTIAL_SCORE_POLICY:
+ overall_ws = overall_score_from_metrics(with_scores, tuple(with_metrics)) if with_quality_available else None
+ overall_bl = (
+ overall_score_from_metrics(without_scores, tuple(without_metrics)) if baseline_quality_available else None
+ )
+ if overall_ws is None:
+ overall_ws = _mean(with_dimension_values)
+ if overall_bl is None:
+ overall_bl = _mean(baseline_dimension_values)
+ elif score_policy == CUSTOM_SCORE_POLICY or score_policy not in {
+ DEFAULT_SCORE_POLICY,
+ LEGACY_SCORE_POLICY,
+ PARTIAL_SCORE_POLICY,
+ }:
+ overall_ws = _unit_interval_score(info.get("overall_with_skill")) if with_quality_available else None
+ overall_bl = _unit_interval_score(info.get("overall_without_skill")) if baseline_quality_available else None
+ if overall_ws is None:
+ overall_ws = _complete_metric_mean(with_scores, metrics)
+ if overall_bl is None:
+ overall_bl = _complete_metric_mean(without_scores, metrics)
+ elif tuple(metrics) == LEGACY_METRICS:
+ if overall_ws is None:
+ overall_ws = overall_score_from_metrics(with_scores, LEGACY_METRICS)
+ if overall_bl is None:
+ overall_bl = overall_score_from_metrics(without_scores, LEGACY_METRICS)
+ else:
+ if overall_ws is None:
+ overall_ws = canonical_dimension_mean(with_dimension_values)
+ if overall_bl is None:
+ overall_bl = canonical_dimension_mean(baseline_dimension_values)
+ if overall_ws is None:
+ overall_ws = _mean(with_dimension_values)
+ if overall_bl is None:
+ overall_bl = _mean(baseline_dimension_values)
+ if overall_ws is None and not metrics and with_quality_available:
+ overall_ws = _unit_interval_score(info.get("overall_with_skill"))
if overall_ws is None and info.get("rewards_complete") is not False:
overall_ws = _logical_reward_mean(info.get("rewards"), "overall")
- if baseline_mixed_contract or (overall_bl is None and not baseline_metrics and baseline_quality_available):
- overall_bl = _finite_float(info.get("overall_without_skill"))
+ if overall_bl is None and not metrics and baseline_quality_available:
+ overall_bl = _unit_interval_score(info.get("overall_without_skill"))
if overall_bl is None and info.get("rewards_baseline_complete") is not False:
overall_bl = _logical_reward_mean(info.get("rewards_baseline"), "overall")
- overall_lift = round(overall_ws - overall_bl, 4) if overall_ws is not None and overall_bl is not None else None
-
- trials = _normalize_trials(info.get("rewards") or [], with_metrics)
- baseline_trials = _normalize_trials(info.get("rewards_baseline") or [], baseline_metrics)
- _attach_baseline_pairs(trials, baseline_trials, with_metrics)
- from skillevaluator.tier3.harbor.resource_usage import resource_comparison
-
- resources = resource_comparison(
- trials,
- baseline_trials,
- with_complete=with_quality_available and info.get("rewards_complete") is True,
- baseline_complete=baseline_quality_available and info.get("rewards_baseline_complete") is True,
+ overall_lift = (
+ round(overall_ws - overall_bl, 4)
+ if comparable_scores and overall_ws is not None and overall_bl is not None
+ else None
)
+ if score_policy == LEGACY_SCORE_POLICY and overall_lift is not None and with_metrics:
+ with_values = tuple(_unit_interval_score(with_scores.get(metric)) for metric in with_metrics)
+ baseline_values = tuple(_unit_interval_score(without_scores.get(metric)) for metric in with_metrics)
+ if all(value is not None for value in (*with_values, *baseline_values)):
+ # Historical lift subtracted the unrounded metric means. Recompute
+ # that value from trusted metrics instead of a mutable lift artifact.
+ overall_lift = round(
+ sum(w - b for w, b in zip(with_values, baseline_values, strict=True)) / len(with_metrics),
+ 4,
+ )
- execution_errors = (
- [str(error) for error in info.get("execution_errors", [])]
- if isinstance(info.get("execution_errors"), list)
- else []
- )
- execution_error_details = _aggregate_execution_error_details({name: info}, len(execution_errors))
+ trials = _normalize_trials(info.get("rewards") or [], metrics)
+ baseline_trials = _normalize_trials(info.get("rewards_baseline") or [], metrics)
+ _attach_baseline_pairs(trials, baseline_trials, metrics, comparable_overall=comparable_scores)
return {
"name": name,
@@ -1389,6 +1538,8 @@ def _build_agent(
"with_skill": overall_ws,
"baseline": overall_bl,
"lift": overall_lift,
+ "metrics_with_skill": with_metrics,
+ "metrics_without_skill": without_metrics,
"num_trials": int(info.get("num_trials", 0) or 0),
"num_trials_baseline": int(info.get("num_trials_baseline", len(baseline_trials)) or 0),
"trials": trials,
@@ -1397,7 +1548,7 @@ def _build_agent(
"pass_at_k": {
"with_skill": info.get("pass_with_skill") or {},
"without_skill": info.get("pass_without_skill") or {},
- "lift": info.get("pass_lift") or {},
+ "lift": (info.get("pass_lift") or {}) if comparable_scores else {},
},
"cases": _cases(info),
}
@@ -2068,6 +2219,8 @@ def _attach_baseline_pairs(
trials: list[dict[str, Any]],
baseline_trials: list[dict[str, Any]],
metrics: list[str],
+ *,
+ comparable_overall: bool = True,
) -> None:
"""Pair with-skill trials to their baseline counterparts by ``entry_id``.
@@ -2089,7 +2242,8 @@ def _attach_baseline_pairs(
if not matches:
continue
baseline = matches.pop(0)
- trial["baseline_overall"] = baseline.get("overall")
+ if comparable_overall:
+ trial["baseline_overall"] = baseline.get("overall")
trial["baseline_scores"] = baseline.get("scores") or {}
lift_scores: dict[str, float] = {}
scores = trial.get("scores") or {}
@@ -2813,6 +2967,11 @@ def _read_attempt_policy(run_dir: Path) -> dict[str, Any]:
loaded = json.loads(policy_file.read_text(encoding="utf-8"))
if isinstance(loaded, dict):
policy.update(loaded)
+ if "score_policy" not in loaded:
+ policy.pop("score_policy", None)
+ return policy
+ policy.pop("score_definition", None)
+ policy.pop("score_policy", None)
return policy
@@ -2959,6 +3118,7 @@ def _default_attempt_policy() -> dict[str, Any]:
"pass_threshold": 0.50,
"stop_on_pass": False,
"score_definition": AGENT_EVAL_SCORE_DEFINITION,
+ "score_policy": DEFAULT_SCORE_POLICY,
}
diff --git a/src/skillevaluator/tier3/commands.py b/src/skillevaluator/tier3/commands.py
index 312aa212..846f72cb 100644
--- a/src/skillevaluator/tier3/commands.py
+++ b/src/skillevaluator/tier3/commands.py
@@ -6,6 +6,7 @@
from __future__ import annotations
import json
+import math
import os
import shutil
import subprocess
@@ -36,7 +37,13 @@ from skillevaluator.tier3.harbor import (
HARBOR_AGENTS_SUPPORTED,
canonical_agent_name,
)
-from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS, LEGACY_METRICS
+from skillevaluator.tier3.harbor.metrics import (
+ DEFAULT_METRICS,
+ DEFAULT_SCORE_POLICY,
+ LEGACY_METRICS,
+ LEGACY_SCORE_POLICY,
+ overall_score_from_metrics,
+)
from skillevaluator.tier3.harbor.progress import (
NullProgressReporter,
ProgressEvent,
@@ -1066,16 +1073,25 @@ def compare_results(skill_path: Path, *, results_dir: Path | None = None) -> int
"timestamp": ts_dir.name,
"path": str(agent_dir),
"num_trials": data.get("num_trials", "?"),
+ "overall_with_skill": _summary_overall(data),
+ "score_policy_with_skill": _summary_score_policy(data),
}
wo_summary = agent_dir / "without-skill" / "summary.json"
if wo_summary.exists():
try:
+ wo_data = json.loads(wo_summary.read_text(encoding="utf-8"))
wo_scores = _summary_scores(
- json.loads(wo_summary.read_text(encoding="utf-8")),
+ wo_data,
allow_missing_status=allow_missing_status,
)
if wo_scores:
root_without[agent_name] = wo_scores
+ root_meta[agent_name].update(
+ {
+ "overall_without_skill": _summary_overall(wo_data),
+ "score_policy_without_skill": _summary_score_policy(wo_data),
+ }
+ )
except (ValueError, OSError):
pass
if root_with:
@@ -1115,11 +1131,20 @@ def compare_results(skill_path: Path, *, results_dir: Path | None = None) -> int
table.add_row(*[""] * (1 + sum(2 if agent in agent_without else 1 for agent in agents)))
overall_row: list[str | Text] = [Text("Overall", style="bold")]
for agent in agents:
- with_avg = sum(_safe_score(agent_with[agent], metric) for metric in overall_metrics) / len(overall_metrics)
+ meta = agent_meta[agent]
+ with_avg = _overall_score_for_display(
+ agent_with[agent],
+ overall_metrics,
+ persisted_overall=meta.get("overall_with_skill"),
+ score_policy=meta.get("score_policy_with_skill"),
+ )
overall_row.append(Text(f"{with_avg:.2f}", style=f"bold {_score_style(with_avg)}"))
if agent in agent_without:
- without_avg = sum(_safe_score(agent_without[agent], metric) for metric in overall_metrics) / len(
- overall_metrics
+ without_avg = _overall_score_for_display(
+ agent_without[agent],
+ overall_metrics,
+ persisted_overall=meta.get("overall_without_skill"),
+ score_policy=meta.get("score_policy_without_skill"),
)
delta = with_avg - without_avg
delta_text = f"+{delta:.2f}" if delta > 0 else f"{delta:.2f}"
@@ -1166,6 +1191,15 @@ def _summary_scores(data: dict[str, Any], *, allow_missing_status: bool = False)
return scores
+def _summary_overall(data: dict[str, Any]) -> float | None:
+ return _unit_interval_score(data.get("overall_score"))
+
+
+def _summary_score_policy(data: dict[str, Any]) -> str | None:
+ value = data.get("score_policy")
+ return value.strip() if isinstance(value, str) and value.strip() else None
+
+
def _display_metrics(agent_with: dict[str, dict[str, float]]) -> tuple[tuple[str, ...], tuple[str, ...]]:
has_default_scores = any(any(metric in scores for metric in DEFAULT_METRICS) for scores in agent_with.values())
if has_default_scores:
@@ -1185,6 +1219,48 @@ def _safe_score(scores: dict[str, float], metric: str) -> float:
return float(value) if isinstance(value, int | float) else 0.0
+def _unit_interval_score(value: object) -> float | None:
+ """Return a finite score in the documented 0.0 to 1.0 range."""
+ if not isinstance(value, int | float) or isinstance(value, bool):
+ return None
+ try:
+ numeric = float(value)
+ except OverflowError:
+ return None
+ return numeric if math.isfinite(numeric) and 0.0 <= numeric <= 1.0 else None
+
+
+def _overall_score_for_display(
+ scores: dict[str, float],
+ metrics: tuple[str, ...],
+ *,
+ persisted_overall: object = None,
+ score_policy: object = DEFAULT_SCORE_POLICY,
+) -> float:
+ """Honor persisted score truth before inferring a policy from metric names."""
+ recorded_overall = _unit_interval_score(persisted_overall)
+
+ if score_policy == DEFAULT_SCORE_POLICY:
+ score = overall_score_from_metrics(scores, metrics)
+ if score is not None:
+ return score
+
+ if recorded_overall is not None:
+ return recorded_overall
+
+ if score_policy == LEGACY_SCORE_POLICY or (score_policy is None and metrics == DEFAULT_METRICS):
+ values = tuple(scores.get(metric) for metric in metrics)
+ if values and all(
+ isinstance(value, int | float) and not isinstance(value, bool) and math.isfinite(value) for value in values
+ ):
+ return round(sum(float(value) for value in values) / len(values), 4)
+
+ score = overall_score_from_metrics(scores, metrics)
+ if score is not None:
+ return score
+ return sum(_safe_score(scores, metric) for metric in metrics) / len(metrics)
+
+
def _score_style(score: float) -> str:
if score >= 0.8:
return "green"
diff --git a/src/skillevaluator/tier3/harbor/collector.py b/src/skillevaluator/tier3/harbor/collector.py
index 36c637d3..f696f90f 100644
--- a/src/skillevaluator/tier3/harbor/collector.py
+++ b/src/skillevaluator/tier3/harbor/collector.py
@@ -34,6 +34,7 @@ from skillevaluator.tier3.harbor.metrics import (
CUSTOM_ONLY_METRIC_SET,
DEFAULT_METRIC_SET,
DEFAULT_METRICS,
+ DEFAULT_SCORE_POLICY,
LEGACY_METRIC_SET,
LEGACY_METRICS,
MAX_CUSTOM_METRICS,
@@ -48,9 +49,9 @@ from skillevaluator.tier3.harbor.metrics import (
metric_set_for_reward,
metric_value,
overall_score,
- rewards_have_mixed_metric_contracts,
+ overall_score_from_metrics,
score_definition,
- score_value,
+ score_policy_for_metrics,
)
from skillevaluator.tier3.output_provenance import write_output_file_atomically
from skillevaluator.tier3.toml_utils import extract_toml_metadata_entry_id
@@ -5016,8 +5017,12 @@ def _compute_lift(
}
metrics = tuple(paired_scores)
if metrics in {DISPLAY_METRICS, LEGACY_METRICS}:
- overall_with = sum(paired_scores[m][0] for m in metrics) / len(metrics)
- overall_without = sum(paired_scores[m][1] for m in metrics) / len(metrics)
+ overall_with = overall_score_from_metrics(with_scores, metrics)
+ overall_without = overall_score_from_metrics(without_scores, metrics)
+ else:
+ overall_with = None
+ overall_without = None
+ if overall_with is not None and overall_without is not None:
lift["overall"] = {
"with_skill": round(overall_with, 4),
"without_skill": round(overall_without, 4),
@@ -5036,6 +5041,18 @@ def _average_overall(rewards: list[dict[str, Any]]) -> float | None:
return round(sum(value for value in values if value is not None) / len(values), 4)
+def _aggregate_condition_overall(
+ scores: dict[str, float],
+ metrics: tuple[str, ...],
+ rewards: list[dict[str, Any]],
+) -> float | None:
+ """Aggregate a condition consistently with lift and canonical reports."""
+ if not metrics:
+ return _average_overall(rewards)
+ score = overall_score_from_metrics(scores, metrics)
+ return round(score, 4) if score is not None else None
+
+
def _compute_custom_lift(
with_custom_scores: dict[str, float],
without_custom_scores: dict[str, float],
@@ -6188,11 +6205,13 @@ def collect_harbor_results(
"agents": {},
"metric_set": DEFAULT_METRIC_SET,
"metrics": list(DISPLAY_METRICS),
+ "score_policy": DEFAULT_SCORE_POLICY,
"attempt_policy": {
"max_attempts": n_attempts,
"pass_threshold": pass_threshold,
"stop_on_pass": stop_on_pass,
"score_definition": score_definition(DISPLAY_METRICS),
+ "score_policy": DEFAULT_SCORE_POLICY,
},
}
@@ -6218,6 +6237,10 @@ def collect_harbor_results(
with_trial_failures: list[dict[str, str]] = []
with_job_failure = ""
with_execution: dict[str, Any] = {}
+ with_overall_score: float | None = None
+ with_policy = DEFAULT_SCORE_POLICY
+ with_policy_ambiguous = False
+ with_metrics: tuple[str, ...] = ()
with_arm_suffix = "-with-skill" if not skip_baseline else ""
if with_job_dir:
@@ -6254,6 +6277,8 @@ def collect_harbor_results(
all_results["metric_set"] = with_metric_set
all_results["metrics"] = list(with_metrics)
all_results["attempt_policy"]["score_definition"] = score_definition(with_metrics)
+ all_results["score_policy"] = score_policy_for_metrics(with_metrics)
+ all_results["attempt_policy"]["score_policy"] = score_policy_for_metrics(with_metrics)
with_custom_scores = average_custom_metrics(with_logical_rewards)
with_pass = _pass_summary(
with_logical_rewards,
@@ -6279,7 +6304,9 @@ def collect_harbor_results(
with_custom_scores = {}
with_pass = {}
with_overall_score = (
- _average_overall(with_logical_rewards) if with_execution["execution_status"] == "succeeded" else None
+ _aggregate_condition_overall(with_scores, with_metrics, with_logical_rewards)
+ if with_execution["execution_status"] == "succeeded"
+ else None
)
_save_trials(
with_collected_rewards,
@@ -6292,34 +6319,28 @@ def collect_harbor_results(
agent_model_source=agent_model_source,
expected_case_ids=expected_case_ids,
)
- _write_generated_root_json(
- agent_dir / "with-skill" / "summary.json",
- output_dir,
- {
- "agent": agent,
- "model": agent_model,
- "model_source": agent_model_source,
- "scores": with_scores,
- "custom_scores": with_custom_scores,
- "overall_score": with_overall_score,
- "metric_set": with_metric_set,
- "metrics": list(with_metrics),
- "dimensions": dimension_scores(with_scores),
- "num_trials": len(with_logical_rewards),
- "num_reward_rows": len(with_collected_rewards),
- "mixed_metric_contracts": with_mixed_metric_contracts,
- "pass_at_k": _public_pass_summary(with_pass),
- **with_execution,
- "job_failure": with_job_failure,
- "trial_failures": _public_failure_list(with_trial_failures),
- **_failure_list_metadata("trial_failure_details", with_trial_failures),
- },
- )
- logger.debug(
- "Agent %s with-skill: %d trials, scores=%s",
- agent,
- len(with_logical_rewards),
- with_scores,
+ (agent_dir / "with-skill" / "summary.json").write_text(
+ json.dumps(
+ {
+ "agent": agent,
+ "model": agent_model,
+ "model_source": agent_model_source,
+ "scores": with_scores,
+ "custom_scores": with_custom_scores,
+ "overall_score": with_overall_score,
+ "metric_set": with_metric_set,
+ "metrics": list(with_metrics),
+ "score_policy": score_policy_for_metrics(with_metrics),
+ "dimensions": dimension_scores(with_scores),
+ "num_trials": len(with_rewards),
+ "pass_at_k": with_pass,
+ **with_execution,
+ "job_failure": with_job_failure,
+ "trial_failures": with_trial_failures,
+ },
+ indent=2,
+ ),
+ encoding="utf-8",
)
else:
with_job_failure = f"No Harbor job found for {with_job_name}"
@@ -6401,6 +6422,10 @@ def collect_harbor_results(
without_trial_failures: list[dict[str, str]] = []
without_job_failure = ""
without_execution: dict[str, Any] = {}
+ without_overall_score: float | None = None
+ without_policy = DEFAULT_SCORE_POLICY
+ without_policy_ambiguous = False
+ without_metrics: tuple[str, ...] = ()
without_job_dir: Path | None = None
if not skip_baseline:
without_job_name = f"{skill_name}-{agent}-without"
@@ -6460,7 +6485,7 @@ def collect_harbor_results(
without_custom_scores = {}
without_pass = {}
without_overall_score = (
- _average_overall(without_logical_rewards)
+ _aggregate_condition_overall(without_scores, without_metrics, without_logical_rewards)
if without_execution["execution_status"] == "succeeded"
else None
)
@@ -6475,28 +6500,28 @@ def collect_harbor_results(
agent_model_source=agent_model_source,
expected_case_ids=expected_case_ids,
)
- _write_generated_root_json(
- agent_dir / "without-skill" / "summary.json",
- output_dir,
- {
- "agent": agent,
- "model": agent_model,
- "model_source": agent_model_source,
- "scores": without_scores,
- "custom_scores": without_custom_scores,
- "overall_score": without_overall_score,
- "metric_set": without_metric_set,
- "metrics": list(without_metrics),
- "dimensions": dimension_scores(without_scores),
- "num_trials": len(without_logical_rewards),
- "num_reward_rows": len(without_collected_rewards),
- "mixed_metric_contracts": without_mixed_metric_contracts,
- "pass_at_k": _public_pass_summary(without_pass),
- **without_execution,
- "job_failure": without_job_failure,
- "trial_failures": _public_failure_list(without_trial_failures),
- **_failure_list_metadata("trial_failure_details", without_trial_failures),
- },
+ (agent_dir / "without-skill" / "summary.json").write_text(
+ json.dumps(
+ {
+ "agent": agent,
+ "model": agent_model,
+ "model_source": agent_model_source,
+ "scores": without_scores,
+ "custom_scores": without_custom_scores,
+ "overall_score": without_overall_score,
+ "metric_set": without_metric_set,
+ "metrics": list(without_metrics),
+ "score_policy": score_policy_for_metrics(without_metrics),
+ "dimensions": dimension_scores(without_scores),
+ "num_trials": len(without_rewards),
+ "pass_at_k": without_pass,
+ **without_execution,
+ "job_failure": without_job_failure,
+ "trial_failures": without_trial_failures,
+ },
+ indent=2,
+ ),
+ encoding="utf-8",
)
logger.debug(
"Agent %s without-skill: %d trials, scores=%s",
@@ -6515,26 +6540,27 @@ def collect_harbor_results(
without_job_failure = _published_job_failure(without_job_failure)
summary_dir = agent_dir / "without-skill"
summary_dir.mkdir(parents=True, exist_ok=True)
- _write_generated_root_json(
- summary_dir / "summary.json",
- output_dir,
- {
- "agent": agent,
- "model": agent_model,
- "model_source": agent_model_source,
- "scores": {},
- "custom_scores": {},
- "overall_score": None,
- "metric_set": DEFAULT_METRIC_SET,
- "metrics": list(DISPLAY_METRICS),
- "dimensions": {},
- "num_trials": 0,
- "num_reward_rows": 0,
- "mixed_metric_contracts": False,
- "pass_at_k": {},
- "job_failure": without_job_failure,
- "trial_failures": [],
- },
+ (summary_dir / "summary.json").write_text(
+ json.dumps(
+ {
+ "agent": agent,
+ "model": agent_model,
+ "model_source": agent_model_source,
+ "scores": {},
+ "custom_scores": {},
+ "overall_score": None,
+ "metric_set": DEFAULT_METRIC_SET,
+ "metrics": list(DISPLAY_METRICS),
+ "score_policy": DEFAULT_SCORE_POLICY,
+ "dimensions": {},
+ "num_trials": 0,
+ "pass_at_k": {},
+ "job_failure": without_job_failure,
+ "trial_failures": [],
+ },
+ indent=2,
+ ),
+ encoding="utf-8",
)
if not without_execution:
@@ -6552,42 +6578,98 @@ def collect_harbor_results(
if not skip_baseline and without_job_dir is None:
summary_dir = agent_dir / "without-skill"
summary_dir.mkdir(parents=True, exist_ok=True)
- _write_generated_root_json(
- summary_dir / "summary.json",
- output_dir,
- {
- "agent": agent,
- "model": agent_model,
- "model_source": agent_model_source,
- "scores": {},
- "custom_scores": {},
- "overall_score": None,
- "metrics": [],
- "dimensions": {},
- "num_trials": 0,
- "num_reward_rows": 0,
- "mixed_metric_contracts": False,
- "pass_at_k": {},
- **without_execution,
- "job_failure": without_job_failure,
- "trial_failures": [],
- },
+ (summary_dir / "summary.json").write_text(
+ json.dumps(
+ {
+ "agent": agent,
+ "model": agent_model,
+ "model_source": agent_model_source,
+ "scores": {},
+ "custom_scores": {},
+ "overall_score": None,
+ "metrics": [],
+ "score_policy": DEFAULT_SCORE_POLICY,
+ "dimensions": {},
+ "num_trials": 0,
+ "pass_at_k": {},
+ **without_execution,
+ "job_failure": without_job_failure,
+ "trial_failures": [],
+ },
+ indent=2,
+ ),
+ encoding="utf-8",
)
+ if (
+ not skip_baseline
+ and with_execution.get("execution_status") == "succeeded"
+ and without_execution.get("execution_status") == "succeeded"
+ and with_policy != without_policy
+ and set(with_metrics) == set(without_metrics)
+ ):
+ if with_policy_ambiguous and not without_policy_ambiguous:
+ with_policy = without_policy
+ summary_path = agent_dir / "with-skill" / "summary.json"
+ summary = json.loads(summary_path.read_text(encoding="utf-8"))
+ summary["score_policy"] = with_policy
+ summary_path.write_text(json.dumps(summary, indent=2), encoding="utf-8")
+ elif without_policy_ambiguous and not with_policy_ambiguous:
+ without_policy = with_policy
+ summary_path = agent_dir / "without-skill" / "summary.json"
+ summary = json.loads(summary_path.read_text(encoding="utf-8"))
+ summary["score_policy"] = without_policy
+ summary_path.write_text(json.dumps(summary, indent=2), encoding="utf-8")
+ all_results["score_policy"] = with_policy
+ all_results["attempt_policy"]["score_policy"] = with_policy
+ if with_job_dir:
+ all_results["attempt_policy"]["score_definition"] = _score_definition_for_policy(with_metrics, with_policy)
+ policy_conflict = (
+ not skip_baseline
+ and with_execution.get("execution_status") == "succeeded"
+ and without_execution.get("execution_status") == "succeeded"
+ and with_policy != without_policy
+ )
+ if policy_conflict:
+ reason = f"Conflicting score policies across conditions: {with_policy}, {without_policy}"
+ for condition, execution in (("with-skill", with_execution), ("without-skill", without_execution)):
+ execution["execution_status"] = "failed"
+ execution.setdefault("execution_errors", []).append(reason)
+ summary_path = agent_dir / condition / "summary.json"
+ summary = json.loads(summary_path.read_text(encoding="utf-8"))
+ summary.update(execution)
+ summary.update({"scores": {}, "custom_scores": {}, "overall_score": None, "pass_at_k": {}})
+ summary_path.write_text(json.dumps(summary, indent=2), encoding="utf-8")
+ with_scores = {}
+ without_scores = {}
+ with_custom_scores = {}
+ without_custom_scores = {}
+ with_pass = {}
+ without_pass = {}
+ with_overall_score = None
+ without_overall_score = None
+
lift: dict[str, Any] = {}
paired_execution_succeeded = (
with_execution.get("execution_status") == "succeeded"
and without_execution.get("execution_status") == "succeeded"
)
if paired_execution_succeeded and with_scores and without_scores:
- lift = _compute_lift(
- with_scores,
- without_scores,
- with_logical_rewards,
- without_logical_rewards,
- expected_case_ids,
- )
- _write_generated_root_json(agent_dir / "lift.json", output_dir, lift)
+ lift = _compute_lift(with_scores, without_scores)
+ # The policy and scored metric set must match before comparing
+ # overall scores; shared per-metric deltas remain useful separately.
+ lift.pop("overall", None)
+ if (
+ set(with_metrics) == set(without_metrics)
+ and with_overall_score is not None
+ and without_overall_score is not None
+ ):
+ lift["overall"] = {
+ "with_skill": with_overall_score,
+ "without_skill": without_overall_score,
+ "delta": round(with_overall_score - without_overall_score, 4),
+ }
+ (agent_dir / "lift.json").write_text(json.dumps(lift, indent=2), encoding="utf-8")
custom_lift: dict[str, Any] = {}
if (
@@ -6607,7 +6689,7 @@ def collect_harbor_results(
_write_generated_root_json(agent_dir / "custom_lift.json", output_dir, custom_lift)
pass_lift: dict[str, Any] = {}
- if paired_execution_succeeded and with_pass and without_pass:
+ if paired_execution_succeeded and set(with_metrics) == set(without_metrics) and with_pass and without_pass:
pass_lift = {
"with_skill": with_pass.get("rate", 0.0),
"without_skill": without_pass.get("rate", 0.0),
@@ -6657,6 +6739,12 @@ def collect_harbor_results(
},
"with_skill": with_scores,
"without_skill": without_scores,
+ "overall_with_skill": with_overall_score,
+ "overall_without_skill": without_overall_score,
+ "metrics_with_skill": list(with_metrics),
+ "metrics_without_skill": list(without_metrics),
+ "score_policy_with_skill": with_policy,
+ "score_policy_without_skill": without_policy if not skip_baseline else None,
"custom_with_skill": with_custom_scores,
"custom_without_skill": without_custom_scores,
"dimensions_with_skill": dimension_scores(with_scores),
diff --git a/src/skillevaluator/tier3/harbor/metrics.py b/src/skillevaluator/tier3/harbor/metrics.py
index 7577a581..5d63cd07 100644
--- a/src/skillevaluator/tier3/harbor/metrics.py
+++ b/src/skillevaluator/tier3/harbor/metrics.py
@@ -6,16 +6,19 @@
from __future__ import annotations
import math
-import re
+from collections.abc import Iterable, Mapping
from typing import Any
-from skillevaluator.constants import DIMENSION_MAPPING
-from skillevaluator.utils.redaction import contains_credential_value, is_sensitive_key
+from skillevaluator.constants import DEFAULT_SCORE_POLICY, DIMENSION_MAPPING
DEFAULT_METRIC_SET = "skill-evaluator-default-v2"
LEGACY_METRIC_SET = "skill-evaluator-default-v1"
CUSTOM_ONLY_METRIC_SET = "custom-only"
+LEGACY_SCORE_POLICY = "skill-evaluator-metric-mean-v1"
+CUSTOM_SCORE_POLICY = "custom-overall-v1"
+PARTIAL_SCORE_POLICY = "legacy-partial-dimension-mean-v1"
+
DEFAULT_METRICS = (
"security",
"skill_execution",
@@ -333,19 +336,59 @@ def average_metrics(rewards: list[dict[str, Any]]) -> tuple[dict[str, float], st
return averages, metric_set, metrics
+def score_policy_for_metrics(metrics: tuple[str, ...]) -> str:
+ """Return the versioned overall-score policy for one metric set."""
+ if metrics == DEFAULT_METRICS:
+ return DEFAULT_SCORE_POLICY
+ if metrics == LEGACY_METRICS:
+ return LEGACY_SCORE_POLICY
+ if not metrics:
+ return CUSTOM_SCORE_POLICY
+ return PARTIAL_SCORE_POLICY
+
+
+def canonical_dimension_mean(values: Iterable[object]) -> float | None:
+ """Average one complete canonical dimension set, failing closed on gaps."""
+ raw_values = tuple(values)
+ if len(raw_values) != len(DIMENSION_DEFINITIONS):
+ return None
+ numeric = tuple(_finite_number(value) for value in raw_values)
+ if any(value is None for value in numeric):
+ return None
+ return sum(value for value in numeric if value is not None) / len(numeric)
+
+
+def overall_score_from_metrics(
+ scores: Mapping[str, object],
+ metrics: tuple[str, ...] = DEFAULT_METRICS,
+) -> float | None:
+ """Aggregate one metric set using its versioned score policy."""
+ values = tuple(_finite_number(scores.get(metric)) for metric in metrics)
+ if not values or any(value is None for value in values):
+ return None
+
+ if metrics != LEGACY_METRICS and all(metric in DEFAULT_METRICS for metric in metrics):
+ dimensions = dimension_scores(dict(zip(metrics, values, strict=True)))
+ dimension_values = tuple(
+ dimensions[dimension]["score"] for dimension in DIMENSION_DEFINITIONS if dimension in dimensions
+ )
+ if metrics == DEFAULT_METRICS:
+ return canonical_dimension_mean(dimension_values)
+ return sum(dimension_values) / len(dimension_values) if dimension_values else None
+
+ return sum(value for value in values if value is not None) / len(values)
+
+
def overall_score(reward: dict[str, Any]) -> float | None:
"""Compute pass@k/lift overall score for a reward payload.
- SkillEvaluator default rewards use the mean of their active SkillEvaluator metric set. Custom
- rewards without SkillEvaluator metrics can still pass through by emitting numeric
- ``overall``.
+ Default rewards use the equal-weight mean of the five canonical dimensions.
+ Legacy metric sets retain their historical metric mean. Custom rewards without
+ SkillEvaluator metrics can still pass through by emitting numeric ``overall``.
"""
_, metrics = metric_set_for_reward(reward)
- values = [metric_value(reward, m) for m in metrics]
if metrics:
- if not values or any(value is None for value in values):
- return None
- return sum(value for value in values if value is not None) / len(values)
+ return overall_score_from_metrics({metric: metric_value(reward, metric) for metric in metrics}, metrics)
return score_value(reward.get("overall"))
@@ -353,8 +396,15 @@ def overall_score(reward: dict[str, Any]) -> float | None:
def score_definition(metrics: tuple[str, ...] = DEFAULT_METRICS) -> str:
"""Human-readable definition for the SkillEvaluator overall score."""
if not metrics:
- return "overall = user-provided reward overall"
- return "overall = mean(" + ", ".join(metrics) + ")"
+ return f"overall = user-provided reward overall [{CUSTOM_SCORE_POLICY}]"
+ if metrics == DEFAULT_METRICS:
+ return (
+ "overall = mean(Security, Correctness, Discoverability, Effectiveness, Efficiency) "
+ f"[{DEFAULT_SCORE_POLICY}]"
+ )
+ if metrics == LEGACY_METRICS:
+ return "overall = mean(" + ", ".join(metrics) + f") [{LEGACY_SCORE_POLICY}]"
+ return f"overall = mean(available canonical dimensions) [{PARTIAL_SCORE_POLICY}]"
def dimension_scores(scores: dict[str, float]) -> dict[str, dict[str, Any]]:
diff --git a/src/skillevaluator/tier3/harbor/report.py b/src/skillevaluator/tier3/harbor/report.py
index 64be5bc9..346e2ac3 100644
--- a/src/skillevaluator/tier3/harbor/report.py
+++ b/src/skillevaluator/tier3/harbor/report.py
@@ -26,8 +26,7 @@ from skillevaluator.tier3.harbor.metrics import (
METRIC_DISPLAY,
METRIC_QUESTIONS,
extract_custom_metrics,
- metric_set_for_reward,
- metric_value,
+ overall_score_from_metrics,
)
from skillevaluator.tier3.output_provenance import write_output_file_atomically
from skillevaluator.utils.redaction import redact_sensitive_data, redact_sensitive_text
@@ -127,9 +126,9 @@ def _pick_best_agent(
from skillevaluator.evaluation.tier3_report import _canonical_agent_rank_from_info
best_agent = ""
- best_rank: tuple[float, float] | None = None
- for agent in sorted(agents_data):
- data = agents_data[agent]
+ best_score = -1.0
+ scored_metric_sets: set[frozenset[str]] = set()
+ for agent, data in agents_data.items():
if not _findings_eligible(data):
continue
persisted = persisted_agents.get(agent) if isinstance(persisted_agents, dict) else None
@@ -141,11 +140,24 @@ def _pick_best_agent(
or any(metric_value(with_scores, metric) is None for metric in standard_metrics)
):
continue
- rank = _canonical_agent_rank_from_info(ranking_data)
- if rank is None:
+ metrics = tuple(report_data.metrics_for_condition(data, "with_skill"))
+ if data.get("score_policy_with_skill") == LEGACY_SCORE_POLICY:
+ overall = overall_score(
+ {
+ "metric_set": DEFAULT_METRIC_SET if "security" in metrics else LEGACY_METRIC_SET,
+ "score_policy": LEGACY_SCORE_POLICY,
+ **with_scores,
+ }
+ )
+ else:
+ overall = overall_score_from_metrics(with_scores, metrics)
+ if overall is None:
continue
- if best_rank is None or rank > best_rank:
- best_rank = rank
+ scored_metric_sets.add(frozenset(metrics))
+ if len(scored_metric_sets) > 1:
+ return ""
+ if overall > best_score:
+ best_score = overall
best_agent = agent
return best_agent
diff --git a/src/skillevaluator/tier3/harbor/report_data.py b/src/skillevaluator/tier3/harbor/report_data.py
index 01e34999..36ced7a9 100644
--- a/src/skillevaluator/tier3/harbor/report_data.py
+++ b/src/skillevaluator/tier3/harbor/report_data.py
@@ -21,8 +21,13 @@ from itertools import islice
from pathlib import Path
from typing import Any
-from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS, LEGACY_METRICS, metric_set_for_reward
-from skillevaluator.tier3.harbor.resource_usage import agent_execution_seconds
+from skillevaluator.tier3.harbor.metrics import (
+ CUSTOM_ONLY_METRIC_SET,
+ DEFAULT_METRIC_SET,
+ DEFAULT_METRICS,
+ LEGACY_METRIC_SET,
+ LEGACY_METRICS,
+)
logger = logging.getLogger(__name__)
@@ -501,21 +506,21 @@ def _metrics_for_rewards(rewards: list[dict[str, Any]]) -> list[str]:
def metrics_for_condition(agent_info: dict[str, Any], condition: str) -> list[str]:
- """Return the standard metric contract declared by one agent condition."""
- if condition == "with_skill":
- metrics_key, scores_key, rewards_key = "metrics_with_skill", "with_skill", "rewards"
- elif condition == "without_skill":
- metrics_key, scores_key, rewards_key = "metrics_without_skill", "without_skill", "rewards_baseline"
- else:
- return []
-
- configured = agent_info.get(metrics_key)
+ """Use one condition's recorded metrics, inferring only for older artifacts."""
+ configured = agent_info.get(f"metrics_{condition}")
if isinstance(configured, list):
- return [str(metric) for metric in configured]
- scores = agent_info.get(scores_key, {})
- if isinstance(scores, dict) and "security" in scores:
+ return list(dict.fromkeys(str(metric) for metric in configured))
+ recorded_set = agent_info.get(f"metric_set_{condition}")
+ if recorded_set == DEFAULT_METRIC_SET:
return list(DEFAULT_METRICS)
- rewards = agent_info.get(rewards_key, [])
+ if recorded_set == LEGACY_METRIC_SET:
+ return list(LEGACY_METRICS)
+ if recorded_set == CUSTOM_ONLY_METRIC_SET:
+ return []
+ scores = agent_info.get(condition, {})
+ if isinstance(scores, dict) and scores:
+ return [metric for metric in DEFAULT_METRICS if metric in scores]
+ rewards = agent_info.get("rewards" if condition == "with_skill" else "rewards_baseline", [])
return _metrics_for_rewards(rewards) if isinstance(rewards, list) else []
@@ -666,7 +671,10 @@ def load_agent_data(
key = "with_skill" if variant == "with-skill" else "without_skill"
agent_info[key] = scores
metric_key = "metrics_with_skill" if variant == "with-skill" else "metrics_without_skill"
- agent_info[metric_key] = data.get("metrics", [])
+ if isinstance(data.get("metrics"), list):
+ agent_info[metric_key] = data["metrics"]
+ if isinstance(data.get("metric_set"), str):
+ agent_info[f"metric_set_{key}"] = data["metric_set"]
custom_key = "custom_with_skill" if variant == "with-skill" else "custom_without_skill"
if "custom_scores" in data:
custom_scores = data.get("custom_scores")
@@ -674,13 +682,11 @@ def load_agent_data(
overall_key = "overall_with_skill" if variant == "with-skill" else "overall_without_skill"
if "overall_score" in data:
agent_info[overall_key] = data.get("overall_score")
- mixed_contract_key = (
- "mixed_metric_contracts_with_skill"
- if variant == "with-skill"
- else "mixed_metric_contracts_without_skill"
+ score_policy_key = (
+ "score_policy_with_skill" if variant == "with-skill" else "score_policy_without_skill"
)
- if isinstance(data.get("mixed_metric_contracts"), bool):
- agent_info[mixed_contract_key] = data["mixed_metric_contracts"]
+ if isinstance(data.get("score_policy"), str) and data["score_policy"].strip():
+ agent_info[score_policy_key] = data["score_policy"].strip()
dimension_key = "dimensions_with_skill" if variant == "with-skill" else "dimensions_without_skill"
if "dimensions" in data:
agent_info[dimension_key] = data.get("dimensions", {})
diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.py
index 24e9a5fb..ad19318e 100644
--- a/src/skillevaluator/tier3/harbor/runner.py
+++ b/src/skillevaluator/tier3/harbor/runner.py
@@ -91,7 +91,7 @@ from skillevaluator.tier3.harbor.collector import (
harbor_job_passed,
validate_harbor_job_result,
)
-from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS, score_definition
+from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS, score_definition, score_policy_for_metrics
from skillevaluator.tier3.harbor.progress import (
MIN_EXACT_SECRET_CHARS,
NullProgressReporter,
@@ -4775,6 +4775,7 @@ def _run_harbor_eval_impl(
"pass_threshold": float(pass_threshold),
"stop_on_pass": bool(stop_on_pass),
"score_definition": score_definition(tuple(results.get("metrics", DEFAULT_METRICS))),
+ "score_policy": score_policy_for_metrics(tuple(results.get("metrics", DEFAULT_METRICS))),
},
}
)
diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.py
index c7538b7c..7b32e59c 100644
--- a/src/skillevaluator/tier3/harbor/templates/eval.py
+++ b/src/skillevaluator/tier3/harbor/templates/eval.py
@@ -8909,8 +8909,14 @@ def main():
logger.error("Required LLM judging failed for: %s", ", ".join(sorted(judge_errors)))
raise SystemExit(1)
- scores = [float(result[metric]) for metric in DISPLAY_METRICS]
- overall = round(sum(scores) / len(scores), 4)
+ dimensions = (
+ security_score,
+ acc_score,
+ se_score,
+ round((ga_score + bc_score) / 2, 4),
+ sef_score,
+ )
+ overall = round(sum(dimensions) / len(dimensions), 4)
write_reward_outputs(result, overall)
diff --git a/src/skillevaluator/tier3/harbor/templates/metric.py b/src/skillevaluator/tier3/harbor/templates/metric.py
index 5cb35c11..91cce43e 100644
--- a/src/skillevaluator/tier3/harbor/templates/metric.py
+++ b/src/skillevaluator/tier3/harbor/templates/metric.py
@@ -9,7 +9,7 @@ Harbor calls this with:
python metric.py -i rewards.jsonl -o metrics.json
Input: JSONL where each line is one task's reward.json content.
-Output: JSON with averaged 5-eval scores.
+Output: JSON with six averaged evaluator scores and their five-dimension overall.
"""
import argparse
@@ -72,7 +72,17 @@ def main(input_path: Path, output_path: Path) -> None:
c = counts[metric]
result[metric] = round(sums[metric] / c, 4) if c > 0 else 0.0
- result["overall"] = round(sum(result.values()) / len(result), 4) if result else 0.0
+ if metrics == DEFAULT_METRICS:
+ dimensions = (
+ result["security"],
+ result["accuracy"],
+ result["skill_execution"],
+ round((result["goal_accuracy"] + result["behavior_check"]) / 2, 4),
+ result["skill_efficiency"],
+ )
+ result["overall"] = round(sum(dimensions) / len(dimensions), 4)
+ else:
+ result["overall"] = round(sum(result.values()) / len(result), 4) if result else 0.0
result["metric_set"] = "skill-evaluator-default-v2" if "security" in metrics else "skill-evaluator-default-v1"
output_path.write_text(json.dumps(result, indent=2))
diff --git a/src/skillevaluator/tier3/result_display.py b/src/skillevaluator/tier3/result_display.py
index 46f75dc6..8f20b8c1 100644
--- a/src/skillevaluator/tier3/result_display.py
+++ b/src/skillevaluator/tier3/result_display.py
@@ -26,6 +26,7 @@ from skillevaluator.tier3.harbor.metrics import (
DEFAULT_METRICS,
DIMENSION_DISPLAY,
METRIC_DISPLAY,
+ overall_score_from_metrics,
)
from skillevaluator.tier3.harbor.progress import redact_progress_detail, secret_values_from_environment
from skillevaluator.tier3.harbor.runner import format_harbor_view_command
@@ -98,13 +99,8 @@ def _default_with_skill_overall(data: Mapping[str, Any]) -> float | None:
scores = data.get("with_skill")
if not isinstance(scores, Mapping):
return None
- values: list[float] = []
- for metric in DEFAULT_METRICS:
- value = _finite_number(scores.get(metric))
- if value is None:
- return None
- values.append(value)
- return round(sum(values) / len(values), 4)
+ score = overall_score_from_metrics(scores, DEFAULT_METRICS)
+ return round(score, 4) if score is not None else None
def _custom_only_with_skill_overall(data: Mapping[str, Any]) -> float | None:
diff --git a/src/skillevaluator/tier3/results_location.py b/src/skillevaluator/tier3/results_location.py
index a131cb08..11a5aad5 100644
--- a/src/skillevaluator/tier3/results_location.py
+++ b/src/skillevaluator/tier3/results_location.py
@@ -379,6 +379,18 @@ def _current_result_identity_is_valid(candidate: Path, run_config: dict[object,
or not isinstance(attempt_policy.get("stop_on_pass"), bool)
or not isinstance(attempt_policy.get("score_definition"), str)
or not attempt_policy["score_definition"]
+ or (
+ "score_policy" in attempt_policy
+ and (not isinstance(attempt_policy["score_policy"], str) or not attempt_policy["score_policy"])
+ )
+ ):
+ return False
+ result_score_policy = result.get("score_policy")
+ attempt_score_policy = attempt_policy.get("score_policy")
+ if "score_policy" in result and (
+ not isinstance(result_score_policy, str)
+ or not result_score_policy
+ or (isinstance(attempt_score_policy, str) and result_score_policy != attempt_score_policy)
):
return False
return _recorded_path_matches(result.get("run_dir"), candidate) and _recorded_path_matches(
diff --git a/tests/evaluation/test_tier3_benchmark_contract.py b/tests/evaluation/test_tier3_benchmark_contract.py
index dcba337f..64d4c582 100644
--- a/tests/evaluation/test_tier3_benchmark_contract.py
+++ b/tests/evaluation/test_tier3_benchmark_contract.py
@@ -10,6 +10,7 @@ from pathlib import Path
from skillevaluator import __version__
from skillevaluator.constants import (
+ DEFAULT_SCORE_POLICY,
DIMENSION_VERDICT_NEUTRAL_THRESHOLD,
DIMENSION_VERDICT_PASS_THRESHOLD,
TIER3_LIFT_FAIL_THRESHOLD,
@@ -24,6 +25,7 @@ from skillevaluator.evaluation.tier3_report import (
agent_eval_result_from_run,
build_agent_eval_payload,
)
+from skillevaluator.tier3.harbor.metrics import LEGACY_METRICS, LEGACY_SCORE_POLICY
from skillevaluator.tier3.harbor.report_data import build_dataset_snapshot, load_dataset_snapshot
@@ -81,6 +83,8 @@ def test_payload_exposes_report_truth_metadata() -> None:
assert payload["evaluator_version"] == __version__
assert payload["dataset_digest"].startswith("sha256:")
assert payload["dataset_digest_algorithm"] == "skill-evaluator-dataset-snapshot/1"
+ assert payload["score_policy"] == DEFAULT_SCORE_POLICY
+ assert payload["attempt_policy"]["score_policy"] == DEFAULT_SCORE_POLICY
assert payload["dataset_summary"] == {
"total_tasks": 3,
"positive_tasks": 1,
@@ -97,9 +101,36 @@ def test_payload_exposes_report_truth_metadata() -> None:
"overall_pass_rule": "one_supported_agent_all_dimensions_pass",
}
assert payload["summary"]["dataset_summary"] == payload["dataset_summary"]
+ assert payload["summary"]["score_policy"] == payload["score_policy"]
assert payload["summary"]["verdict_policy"] == payload["verdict_policy"]
+def test_legacy_payload_preserves_the_versioned_metric_mean() -> None:
+ scores = {
+ "skill_execution": 0.2,
+ "skill_efficiency": 0.4,
+ "accuracy": 0.6,
+ "goal_accuracy": 0.8,
+ "behavior_check": 1.0,
+ }
+
+ payload = build_agent_eval_payload(
+ "legacy-demo",
+ {
+ "opencode": {
+ "execution_status": "succeeded",
+ "metrics_with_skill": list(LEGACY_METRICS),
+ "with_skill": scores,
+ }
+ },
+ use_llm_judge=False,
+ )
+
+ assert payload is not None
+ assert payload["overall_score"] == 0.6
+ assert payload["score_policy"] == LEGACY_SCORE_POLICY
+
+
def test_advisory_payload_exposes_same_report_truth_metadata() -> None:
payload = _advisory_agent_eval_payload(
"Tier 3 was skipped",
@@ -110,6 +141,7 @@ def test_advisory_payload_exposes_same_report_truth_metadata() -> None:
assert payload["evaluated_at"] is None
assert payload["evaluator_version"] == __version__
+ assert payload["score_policy"] == DEFAULT_SCORE_POLICY
assert payload["dataset_summary"] == {
"total_tasks": 0,
"positive_tasks": 0,
diff --git a/tests/golden/test_tier3_schema.py b/tests/golden/test_tier3_schema.py
index daa58853..9e214a16 100644
--- a/tests/golden/test_tier3_schema.py
+++ b/tests/golden/test_tier3_schema.py
@@ -15,8 +15,10 @@ from __future__ import annotations
from skillevaluator.tier3.harbor.metrics import (
DEFAULT_METRIC_SET,
DEFAULT_METRICS,
+ DEFAULT_SCORE_POLICY,
metric_set_for_reward,
score_definition,
+ score_policy_for_metrics,
)
@@ -47,7 +49,9 @@ def test_metric_set_for_reward_defaults_to_skill_evaluator() -> None:
assert metrics == DEFAULT_METRICS
-def test_score_definition_mentions_metrics() -> None:
+def test_score_definition_identifies_the_versioned_dimension_policy() -> None:
definition = score_definition(DEFAULT_METRICS)
assert isinstance(definition, str)
- assert "security" in definition
+ assert "Security" in definition
+ assert DEFAULT_SCORE_POLICY in definition
+ assert score_policy_for_metrics(DEFAULT_METRICS) == DEFAULT_SCORE_POLICY
diff --git a/tests/reporting/test_unified_tier3_report.py b/tests/reporting/test_unified_tier3_report.py
index 009ace82..284e46e1 100644
--- a/tests/reporting/test_unified_tier3_report.py
+++ b/tests/reporting/test_unified_tier3_report.py
@@ -20,6 +20,7 @@ from skillevaluator.evaluation.tier3_report import (
_metric_evidence,
_normalize_trials,
_raw_trial_rewards,
+ _replace_with_minimal_payload,
_ReportBudget,
agent_eval_result_from_directory,
build_agent_eval_payload,
@@ -31,9 +32,14 @@ from skillevaluator.reporting import html as html_module
from skillevaluator.reporting.base import agent_eval_publication_evidence_complete
from skillevaluator.reporting.html import PackageLoader, _compact_json
from skillevaluator.tier3.harbor.collector import _paired_pass_comparison, _wilson_score_interval
-from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS, MAX_CUSTOM_METRIC_NAME_BYTES
-from skillevaluator.tier3.harbor.report import _extract_findings
-from skillevaluator.tier3.harbor.report_data import build_dataset_snapshot, metrics_for_agents
+from skillevaluator.tier3.harbor.metrics import (
+ DEFAULT_METRICS,
+ DEFAULT_SCORE_POLICY,
+ LEGACY_METRICS,
+ LEGACY_SCORE_POLICY,
+ PARTIAL_SCORE_POLICY,
+)
+from skillevaluator.tier3.harbor.report_data import build_dataset_snapshot
def _write_summary(
@@ -796,9 +802,450 @@ def test_authenticated_pre_status_rerender_preserves_historical_scores(tmp_path:
payload = tier3.metadata["agent_eval"]
assert payload["execution_status"] == "succeeded"
assert payload["overall_score"] is not None
+ assert payload["score_policy"] == PARTIAL_SCORE_POLICY
assert payload["agents"]["opencode"]["evaluators"]["security"]["with_skill"] == 0.8
+ ("stored_overall", "recorded_policy", "expected_policy", "expected_score"),
+ [
+ pytest.param(0.5583, None, LEGACY_SCORE_POLICY, 0.5583, id="stored-historical-overall"),
+ pytest.param(None, None, LEGACY_SCORE_POLICY, 0.5583, id="recomputed-historical-overall"),
+ pytest.param(2.0, None, LEGACY_SCORE_POLICY, 0.5583, id="out-of-range-overall"),
+ pytest.param(10**4000, None, LEGACY_SCORE_POLICY, 0.5583, id="overflowing-overall"),
+ pytest.param(None, DEFAULT_SCORE_POLICY, DEFAULT_SCORE_POLICY, 0.49, id="current-policy"),
+ ],
+)
+def test_default_v2_rerender_respects_recorded_or_historical_policy(
+ tmp_path: Path,
+ stored_overall: object,
+ recorded_policy: str | None,
+ expected_policy: str,
+ expected_score: float,
+) -> None:
+ skill = tmp_path / "demo"
+ skill.mkdir()
+ run_dir = tmp_path / "results" / "20260709_120009"
+ summary = run_dir / "opencode" / "with-skill" / "summary.json"
+ summary.parent.mkdir(parents=True)
+ scores = {
+ "security": 0.3875,
+ "skill_execution": 0.3875,
+ "skill_efficiency": 0.3875,
+ "accuracy": 0.3875,
+ "goal_accuracy": 0.9,
+ "behavior_check": 0.9,
+ }
+ summary_payload = {
+ "execution_status": "succeeded",
+ "execution_errors": [],
+ "expected_attempts": 1,
+ "scored_attempts": 1,
+ "scores": scores,
+ "metric_set": "skill-evaluator-default-v2",
+ "metrics": list(DEFAULT_METRICS),
+ "num_trials": 0,
+ }
+ if stored_overall is not None:
+ summary_payload["overall_score"] = stored_overall
+ if recorded_policy is not None:
+ summary_payload["score_policy"] = recorded_policy
+ summary.write_text(json.dumps(summary_payload), encoding="utf-8")
+ if recorded_policy is None:
+ comparison_summary = run_dir / "codex" / "with-skill" / "summary.json"
+ comparison_summary.parent.mkdir(parents=True)
+ comparison_summary.write_text(
+ json.dumps(
+ {
+ **summary_payload,
+ "scores": dict.fromkeys(DEFAULT_METRICS, 0.55),
+ "overall_score": 0.55,
+ }
+ ),
+ encoding="utf-8",
+ )
+ (run_dir / "attempt_policy.json").write_text(
+ json.dumps(
+ {
+ "max_attempts": 1,
+ "pass_threshold": 0.5,
+ "stop_on_pass": False,
+ "score_definition": "overall = mean(security, skill_execution, skill_efficiency, accuracy, goal_accuracy, behavior_check)",
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ tier3 = agent_eval_result_from_directory(skill, run_dir, use_llm_judge=False)
+
+ assert tier3 is not None
+ payload = tier3.metadata["agent_eval"]
+ assert payload["overall_score"] == pytest.approx(expected_score)
+ assert payload["agents"]["opencode"]["with_skill"] == pytest.approx(expected_score)
+ assert payload["score_policy"] == expected_policy
+ assert payload["attempt_policy"]["score_policy"] == expected_policy
+ if expected_policy == LEGACY_SCORE_POLICY:
+ assert payload["best_agent"] == "opencode"
+ definition = payload["attempt_policy"]["score_definition"]
+ if expected_policy == LEGACY_SCORE_POLICY:
+ assert definition.startswith("overall = mean(security,")
+ else:
+ assert "mean(Security, Correctness, Discoverability, Effectiveness, Efficiency)" in definition
+
+
+def test_canonical_report_fails_closed_on_mixed_recorded_score_policies() -> None:
+ scores = dict.fromkeys(DEFAULT_METRICS, 0.5)
+ payload = build_agent_eval_payload(
+ "mixed-policy-demo",
+ {
+ "codex": {
+ "execution_status": "succeeded",
+ "execution_errors": [],
+ "expected_attempts": 1,
+ "scored_attempts": 1,
+ "with_skill": scores,
+ "overall_with_skill": 0.5,
+ "score_policy_with_skill": DEFAULT_SCORE_POLICY,
+ },
+ "opencode": {
+ "execution_status": "succeeded",
+ "execution_errors": [],
+ "expected_attempts": 1,
+ "scored_attempts": 1,
+ "with_skill": scores,
+ "overall_with_skill": 0.5,
+ "score_policy_with_skill": LEGACY_SCORE_POLICY,
+ },
+ },
+ use_llm_judge=False,
+ )
+
+ assert payload is not None
+ assert payload["execution_status"] == "failed"
+ assert payload["overall_score"] is None
+ assert payload["best_agent"] == ""
+ assert any("conflicting score policies" in error.lower() for error in payload["execution_errors"])
+
+
+def test_canonical_report_fails_closed_on_different_condition_policies() -> None:
+ payload = build_agent_eval_payload(
+ "mixed-condition-demo",
+ {
+ "opencode": {
+ "execution_status": "succeeded",
+ "execution_errors": [],
+ "expected_attempts": 2,
+ "scored_attempts": 2,
+ "with_skill": dict.fromkeys(DEFAULT_METRICS, 0.5),
+ "without_skill": dict.fromkeys(DEFAULT_METRICS, 0.2),
+ "overall_with_skill": 0.5,
+ "overall_without_skill": 0.2,
+ "score_policy_with_skill": DEFAULT_SCORE_POLICY,
+ "score_policy_without_skill": LEGACY_SCORE_POLICY,
+ }
+ },
+ attempt_policy={"score_policy": DEFAULT_SCORE_POLICY},
+ use_llm_judge=False,
+ )
+
+ assert payload is not None
+ assert payload["execution_status"] == "failed"
+ assert payload["overall_score"] is None
+ assert payload["overall_lift"] is None
+ assert payload["agents"]["opencode"]["lift"] is None
+ assert any("conflicting score policies" in error.lower() for error in payload["execution_errors"])
+
+
+def test_current_policy_overall_uses_raw_evaluators_not_cached_dimensions() -> None:
+ payload = build_agent_eval_payload(
+ "stale-dimensions-demo",
+ {
+ "opencode": {
+ "execution_status": "succeeded",
+ "execution_errors": [],
+ "expected_attempts": 1,
+ "scored_attempts": 1,
+ "with_skill": dict.fromkeys(DEFAULT_METRICS, 0.5),
+ "dimensions_with_skill": {
+ dimension: {"score": 1.0}
+ for dimension in ("security", "correctness", "discoverability", "effectiveness", "efficiency")
+ },
+ "score_policy_with_skill": DEFAULT_SCORE_POLICY,
+ }
+ },
+ use_llm_judge=False,
+ )
+
+ assert payload is not None
+ assert payload["overall_score"] == 0.5
+ assert payload["agents"]["opencode"]["with_skill"] == 0.5
+
+
+def test_known_legacy_policy_overall_uses_raw_metrics_when_stored_value_disagrees() -> None:
+ payload = build_agent_eval_payload(
+ "legacy-integrity-demo",
+ {
+ "opencode": {
+ "execution_status": "succeeded",
+ "execution_errors": [],
+ "expected_attempts": 1,
+ "scored_attempts": 1,
+ "with_skill": dict.fromkeys(DEFAULT_METRICS, 0.2),
+ "overall_with_skill": 0.9,
+ "score_policy_with_skill": LEGACY_SCORE_POLICY,
+ }
+ },
+ use_llm_judge=False,
+ )
+
+ assert payload is not None
+ assert payload["score_policy"] == LEGACY_SCORE_POLICY
+ assert payload["overall_score"] == 0.2
+
+
+def test_known_legacy_policy_lift_uses_condition_scores_not_stale_lift_artifact() -> None:
+ payload = build_agent_eval_payload(
+ "legacy-lift-integrity-demo",
+ {
+ "opencode": {
+ "execution_status": "succeeded",
+ "execution_errors": [],
+ "expected_attempts": 1,
+ "scored_attempts": 1,
+ "with_skill": dict.fromkeys(DEFAULT_METRICS, 0.6),
+ "without_skill": dict.fromkeys(DEFAULT_METRICS, 0.4),
+ "lift": {"overall": {"delta": -0.5}},
+ "score_policy_with_skill": LEGACY_SCORE_POLICY,
+ "score_policy_without_skill": LEGACY_SCORE_POLICY,
+ }
+ },
+ use_llm_judge=False,
+ )
+
+ assert payload is not None
+ assert payload["overall_score"] == 0.6
+ assert payload["overall_lift"] == 0.2
+ assert payload["agents"]["opencode"]["lift"] == 0.2
+
+
+def test_legacy_report_honors_recorded_metric_membership_and_ignores_order() -> None:
+ payload = build_agent_eval_payload(
+ "recorded-metrics-demo",
+ {
+ "opencode": {
+ "execution_status": "succeeded",
+ "with_skill": {**dict.fromkeys(LEGACY_METRICS, 0.8), "security": 0.0},
+ "without_skill": dict.fromkeys(LEGACY_METRICS, 0.6),
+ "metrics_with_skill": list(LEGACY_METRICS),
+ "metrics_without_skill": list(reversed(LEGACY_METRICS)),
+ "score_policy_with_skill": LEGACY_SCORE_POLICY,
+ "score_policy_without_skill": LEGACY_SCORE_POLICY,
+ }
+ },
+ use_llm_judge=False,
+ )
+ assert payload is not None
+ assert payload["overall_score"] == 0.8
+ assert payload["agents"]["opencode"]["baseline"] == 0.6
+ assert payload["overall_lift"] == 0.2
+
+
+def test_partial_reports_do_not_rank_agents_scored_on_different_metrics() -> None:
+ payload = build_agent_eval_payload(
+ "partial-metrics-demo",
+ {
+ "codex": {
+ "execution_status": "succeeded",
+ "with_skill": {"security": 0.8},
+ "score_policy_with_skill": PARTIAL_SCORE_POLICY,
+ },
+ "opencode": {
+ "execution_status": "succeeded",
+ "with_skill": {"security": 0.4, "accuracy": 0.6},
+ "score_policy_with_skill": PARTIAL_SCORE_POLICY,
+ },
+ },
+ use_llm_judge=False,
+ )
+ assert payload is not None
+ assert payload["agents"]["codex"]["with_skill"] == 0.8
+ assert payload["agents"]["opencode"]["with_skill"] == 0.5
+ assert payload["best_agent"] == ""
+ assert payload["overall_score"] is None
+ assert payload["execution_status"] == "failed"
+
+
[email protected]("missing_metric", [False, True])
+def test_legacy_report_keeps_declared_metric_set_when_metric_names_are_absent(
+ tmp_path: Path, missing_metric: bool
+) -> None:
+ skill = tmp_path / "demo"
+ skill.mkdir()
+ run_dir = tmp_path / "results"
+ _write_summary(run_dir, score=0.6)
+ summary_path = run_dir / "opencode/with-skill/summary.json"
+ summary = json.loads(summary_path.read_text(encoding="utf-8"))
+ summary.pop("metrics")
+ summary["metric_set"] = "skill-evaluator-default-v2"
+ summary["score_policy"] = LEGACY_SCORE_POLICY
+ if missing_metric:
+ summary["scores"].pop("security")
+ summary_path.write_text(json.dumps(summary), encoding="utf-8")
+
+ result = agent_eval_result_from_directory(skill, run_dir, use_llm_judge=False)
+ assert result is not None
+ payload = result.metadata["agent_eval"]
+ assert payload["agents"]["opencode"]["metrics_with_skill"] == list(DEFAULT_METRICS)
+ assert payload["agents"]["opencode"]["with_skill"] == (None if missing_metric else 0.6)
+
+
+def test_unknown_report_policy_without_a_persisted_score_is_incomplete() -> None:
+ payload = build_agent_eval_payload(
+ "unknown-policy-demo",
+ {
+ "opencode": {
+ "execution_status": "succeeded",
+ "execution_errors": [],
+ "expected_attempts": 1,
+ "scored_attempts": 1,
+ "with_skill": dict.fromkeys(DEFAULT_METRICS, 0.5),
+ "score_policy_with_skill": "future-weighted-policy-v2",
+ }
+ },
+ use_llm_judge=False,
+ )
+
+ assert payload is not None
+ assert payload["execution_status"] == "failed"
+ assert payload["overall_score"] is None
+ assert any("persisted" in error.lower() for error in payload["execution_errors"])
+
+
+def test_report_replaces_stale_formula_when_recorded_policy_is_unknown() -> None:
+ payload = build_agent_eval_payload(
+ "unknown-policy-definition-demo",
+ {
+ "opencode": {
+ "execution_status": "succeeded",
+ "execution_errors": [],
+ "expected_attempts": 1,
+ "scored_attempts": 1,
+ "with_skill": dict.fromkeys(DEFAULT_METRICS, 0.5),
+ "overall_with_skill": 0.8,
+ "score_policy_with_skill": "future-weighted-policy-v2",
+ }
+ },
+ attempt_policy={
+ "score_policy": "future-weighted-policy-v2",
+ "score_definition": "overall = mean(Security, Correctness, Discoverability, Effectiveness, Efficiency)",
+ },
+ use_llm_judge=False,
+ )
+
+ assert payload is not None
+ definition = payload["attempt_policy"]["score_definition"]
+ assert "future-weighted-policy-v2" in definition
+ assert "formula unavailable" in definition
+ assert "mean(Security" not in definition
+
+
+def test_policy_only_attempt_artifact_gets_its_matching_definition(tmp_path: Path) -> None:
+ skill = tmp_path / "demo"
+ skill.mkdir()
+ run_dir = tmp_path / "results" / "20260709_120099"
+ _write_summary(run_dir, score=0.5)
+ (run_dir / "attempt_policy.json").write_text(json.dumps({"score_policy": LEGACY_SCORE_POLICY}), encoding="utf-8")
+
+ tier3 = agent_eval_result_from_directory(skill, run_dir, use_llm_judge=False)
+
+ assert tier3 is not None
+ definition = tier3.metadata["agent_eval"]["attempt_policy"]["score_definition"]
+ assert LEGACY_SCORE_POLICY in definition
+ assert DEFAULT_SCORE_POLICY not in definition
+
+
+def test_default_v2_rerender_preserves_historical_baseline_lift_and_pass_at_k(tmp_path: Path) -> None:
+ skill = tmp_path / "demo"
+ skill.mkdir()
+ run_dir = tmp_path / "results" / "20260709_120010"
+ agent_dir = run_dir / "opencode"
+ with_scores = {
+ "security": 0.5,
+ "skill_execution": 0.5,
+ "skill_efficiency": 0.5,
+ "accuracy": 0.5,
+ "goal_accuracy": 1.0,
+ "behavior_check": 1.0,
+ }
+ without_scores = {
+ "security": 0.75,
+ "skill_execution": 0.75,
+ "skill_efficiency": 0.75,
+ "accuracy": 0.75,
+ "goal_accuracy": 0.25,
+ "behavior_check": 0.25,
+ }
+ with_pass = {"rate": 0.75, "passed_cases": 3, "total_cases": 4}
+ without_pass = {"rate": 0.25, "passed_cases": 1, "total_cases": 4}
+
+ for condition, scores, overall, pass_at_k in (
+ ("with-skill", with_scores, 0.6667, with_pass),
+ ("without-skill", without_scores, 0.5833, without_pass),
+ ):
+ summary = agent_dir / condition / "summary.json"
+ summary.parent.mkdir(parents=True)
+ summary.write_text(
+ json.dumps(
+ {
+ "execution_status": "succeeded",
+ "execution_errors": [],
+ "expected_attempts": 1,
+ "scored_attempts": 1,
+ "scores": scores,
+ "overall_score": overall,
+ "metric_set": "skill-evaluator-default-v2",
+ "metrics": list(DEFAULT_METRICS),
+ "num_trials": 0,
+ "pass_at_k": pass_at_k,
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ (agent_dir / "lift.json").write_text(
+ json.dumps({"overall": {"with_skill": 0.6667, "without_skill": 0.5833, "delta": 0.0833}}),
+ encoding="utf-8",
+ )
+ pass_lift = {"with_skill": 0.75, "without_skill": 0.25, "delta": 0.5}
+ (agent_dir / "pass_at_k_lift.json").write_text(json.dumps(pass_lift), encoding="utf-8")
+ (run_dir / "attempt_policy.json").write_text(
+ json.dumps(
+ {
+ "max_attempts": 1,
+ "pass_threshold": 0.5,
+ "stop_on_pass": False,
+ "score_definition": "overall = mean(security, skill_execution, skill_efficiency, accuracy, goal_accuracy, behavior_check)",
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ tier3 = agent_eval_result_from_directory(skill, run_dir, use_llm_judge=False)
+
+ assert tier3 is not None
+ payload = tier3.metadata["agent_eval"]
+ agent = payload["agents"]["opencode"]
+ assert payload["score_policy"] == LEGACY_SCORE_POLICY
+ assert agent["with_skill"] == pytest.approx(0.6667)
+ assert agent["baseline"] == pytest.approx(0.5833)
+ assert agent["lift"] == pytest.approx(0.0833)
+ assert agent["pass_at_k"] == {
+ "with_skill": with_pass,
+ "without_skill": without_pass,
+ "lift": pass_lift,
+ }
+
+
def test_canonical_report_prefers_agentskills_dataset_fields() -> None:
payload = build_agent_eval_payload(
"hld-documents",
@@ -1510,6 +1957,7 @@ def test_global_report_budget_prioritizes_best_agent_details() -> None:
{
"entry_id": f"low-{index:03d}",
"security": 0.1,
+ "goal_accuracy": 0.1,
"custom_metrics": custom_scores,
}
for index in range(256)
@@ -1522,7 +1970,7 @@ def test_global_report_budget_prioritizes_best_agent_details() -> None:
"execution_errors": [],
"expected_attempts": len(low_agent_rewards),
"scored_attempts": len(low_agent_rewards),
- "with_skill": {"security": 0.1},
+ "with_skill": {"security": 0.1, "goal_accuracy": 0.1},
"custom_with_skill": custom_scores,
"rewards": low_agent_rewards,
},
@@ -1563,9 +2011,9 @@ def test_payload_prunes_oversized_non_best_conditions_before_best_evidence() ->
"execution_errors": [],
"expected_attempts": 1,
"scored_attempts": 1,
- "with_skill": {"security": 0.1},
+ "with_skill": {"security": 0.1, "goal_accuracy": 0.1},
"conditions": {"with_skill": {"diagnostic": "x" * (3 * 1024 * 1024)}},
- "rewards": [{"entry_id": "low-case", "security": 0.1}],
+ "rewards": [{"entry_id": "low-case", "security": 0.1, "goal_accuracy": 0.1}],
},
"zzz": {
"execution_status": "succeeded",
@@ -1929,6 +2377,24 @@ def test_canonical_payload_enforces_total_serialized_budget() -> None:
assert len(encoded) <= truncation["payload_budget_bytes"]
+def test_minimal_payload_preserves_score_policy() -> None:
+ payload = {
+ "summary": {"score_policy": DEFAULT_SCORE_POLICY},
+ "score_policy": DEFAULT_SCORE_POLICY,
+ "attempt_policy": {
+ "score_definition": "x" * (3 * 1024 * 1024),
+ "score_policy": DEFAULT_SCORE_POLICY,
+ },
+ }
+
+ _replace_with_minimal_payload(payload, _ReportBudget())
+
+ assert payload["summary"]["score_policy"] == DEFAULT_SCORE_POLICY
+ assert payload["score_policy"] == DEFAULT_SCORE_POLICY
+ assert payload["attempt_policy"]["score_policy"] == DEFAULT_SCORE_POLICY
+ assert len(payload["attempt_policy"]["score_definition"]) == 1024
+
+
def test_unpaired_id_artifact_survives_loader_report_budget_and_html(tmp_path: Path) -> None:
skill = tmp_path / "demo"
skill.mkdir()
diff --git a/tests/test_harbor_metrics_truth.py b/tests/test_harbor_metrics_truth.py
index 11488113..b7182064 100644
--- a/tests/test_harbor_metrics_truth.py
+++ b/tests/test_harbor_metrics_truth.py
@@ -10,6 +10,8 @@ import subprocess
import sys
import time
from fractions import Fraction
+from itertools import product
+from pathlib import Path
import pytest
@@ -34,20 +36,20 @@ from skillevaluator.tier3.harbor.metrics import (
CUSTOM_ONLY_METRIC_SET,
DEFAULT_METRIC_SET,
DEFAULT_METRICS,
+ DEFAULT_SCORE_POLICY,
LEGACY_METRIC_SET,
LEGACY_METRICS,
- MAX_CUSTOM_METRIC_NAME_BYTES,
- MAX_CUSTOM_METRICS,
- CustomMetricContractError,
- average_custom_metrics,
average_metrics,
- custom_metric_contract_error,
+ canonical_dimension_mean,
extract_custom_metrics,
metric_set_for_reward,
metric_value,
overall_score,
- rewards_have_mixed_metric_contracts,
+ overall_score_from_metrics,
+ score_definition,
+ score_policy_for_metrics,
)
+from skillevaluator.tier3.harbor.report import _pick_best_agent
def test_custom_metric_names_filter_credentials_but_keep_explicit_metric_terms() -> None:
@@ -243,6 +245,173 @@ def test_overall_score_requires_a_complete_finite_metric_set() -> None:
assert overall_score({"metric_set": CUSTOM_ONLY_METRIC_SET, "overall": float("nan")}) is None
+def test_default_overall_score_uses_the_canonical_dimension_mean() -> None:
+ reward = {
+ "metric_set": DEFAULT_METRIC_SET,
+ "security": 0.3875,
+ "skill_execution": 0.3875,
+ "skill_efficiency": 0.3875,
+ "accuracy": 0.3875,
+ "goal_accuracy": 0.9,
+ "behavior_check": 0.9,
+ }
+
+ # Effectiveness owns goal_accuracy + behavior_check as one of five
+ # dimensions. Averaging all six evaluators would incorrectly return 0.5583.
+ assert overall_score(reward) == pytest.approx(0.49)
+ assert score_policy_for_metrics(DEFAULT_METRICS) == DEFAULT_SCORE_POLICY
+ assert "mean(Security, Correctness, Discoverability, Effectiveness, Efficiency)" in score_definition(
+ DEFAULT_METRICS
+ )
+
+
+def test_best_agent_selection_uses_the_canonical_dimension_mean() -> None:
+ direction_reversing = {
+ "security": 0.3875,
+ "skill_execution": 0.3875,
+ "skill_efficiency": 0.3875,
+ "accuracy": 0.3875,
+ "goal_accuracy": 0.9,
+ "behavior_check": 0.9,
+ }
+ agents = {
+ "metric-mean-winner": {"execution_status": "succeeded", "with_skill": direction_reversing},
+ "dimension-mean-winner": {
+ "execution_status": "succeeded",
+ "with_skill": dict.fromkeys(DEFAULT_METRICS, 0.5),
+ },
+ }
+
+ assert sum(direction_reversing.values()) / len(direction_reversing) > 0.5
+ assert _pick_best_agent(agents) == "dimension-mean-winner"
+
+
+def test_standalone_harbor_metric_aggregation_uses_the_canonical_dimension_mean(tmp_path: Path) -> None:
+ reward = {
+ "metric_set": DEFAULT_METRIC_SET,
+ "security": 0.3875,
+ "skill_execution": 0.3875,
+ "skill_efficiency": 0.3875,
+ "accuracy": 0.3875,
+ "goal_accuracy": 0.9,
+ "behavior_check": 0.9,
+ }
+ input_path = tmp_path / "rewards.jsonl"
+ output_path = tmp_path / "metrics.json"
+ input_path.write_text(json.dumps(reward) + "\n", encoding="utf-8")
+ metric_script = Path(__file__).parents[1] / "src/skillevaluator/tier3/harbor/templates/metric.py"
+
+ completed = subprocess.run(
+ [sys.executable, str(metric_script), "-i", str(input_path), "-o", str(output_path)],
+ check=False,
+ capture_output=True,
+ text=True,
+ )
+
+ assert completed.returncode == 0, completed.stderr
+ assert json.loads(output_path.read_text(encoding="utf-8"))["overall"] == 0.49
+
+ precision_reward = {
+ "metric_set": DEFAULT_METRIC_SET,
+ "security": 0.0001,
+ "skill_execution": 0.0001,
+ "skill_efficiency": 0.0001,
+ "accuracy": 0.0001,
+ "goal_accuracy": 0.0,
+ "behavior_check": 0.0007,
+ }
+ input_path.write_text(json.dumps(precision_reward) + "\n", encoding="utf-8")
+ completed = subprocess.run(
+ [sys.executable, str(metric_script), "-i", str(input_path), "-o", str(output_path)],
+ check=False,
+ capture_output=True,
+ text=True,
+ )
+
+ assert completed.returncode == 0, completed.stderr
+ assert json.loads(output_path.read_text(encoding="utf-8"))["overall"] == 0.0001
+
+
+def test_legacy_overall_score_preserves_the_historical_metric_mean() -> None:
+ reward = {
+ "metric_set": LEGACY_METRIC_SET,
+ "skill_execution": 0.2,
+ "skill_efficiency": 0.4,
+ "accuracy": 0.6,
+ "goal_accuracy": 0.8,
+ "behavior_check": 1.0,
+ }
+
+ assert overall_score(reward) == pytest.approx(0.6)
+ assert "mean(skill_execution, skill_efficiency, accuracy, goal_accuracy, behavior_check)" in score_definition(
+ LEGACY_METRICS
+ )
+
+
+def test_partial_score_averages_available_dimensions_instead_of_evaluators() -> None:
+ scores = {"accuracy": 0.0, "goal_accuracy": 1.0, "behavior_check": 1.0}
+ metrics = ("accuracy", "goal_accuracy", "behavior_check")
+
+ assert overall_score_from_metrics(scores, metrics) == pytest.approx(0.5)
+
+
+def test_lift_and_pass_at_k_share_the_canonical_default_score() -> None:
+ baseline = dict.fromkeys(DEFAULT_METRICS, 0.5)
+ with_skill = {
+ "security": 0.3875,
+ "skill_execution": 0.3875,
+ "skill_efficiency": 0.3875,
+ "accuracy": 0.3875,
+ "goal_accuracy": 0.9,
+ "behavior_check": 0.9,
+ }
+
+ lift = _compute_lift(with_skill, baseline)
+ summary = _pass_summary(
+ [{"entry_id": "case-001", "_trial_name": "case-001__attempt1", **with_skill}],
+ n_attempts=1,
+ pass_threshold=0.5,
+ expected_cases=1,
+ expected_case_ids=["case-001"],
+ )
+
+ assert lift["overall"] == {
+ "with_skill": 0.49,
+ "without_skill": 0.5,
+ "delta": -0.01,
+ }
+ assert summary["cases"]["case-001"]["attempts"] == [
+ {
+ "attempt": 1,
+ "trial": "case-001__attempt1",
+ "score": 0.49,
+ "passed": False,
+ }
+ ]
+
+
+def test_default_score_policy_matches_the_five_dimension_contract_exhaustively() -> None:
+ for values in product((0.0, 0.5, 1.0), repeat=len(DEFAULT_METRICS)):
+ scores = dict(zip(DEFAULT_METRICS, values, strict=True))
+ expected = (
+ scores["security"]
+ + scores["accuracy"]
+ + scores["skill_execution"]
+ + (scores["goal_accuracy"] + scores["behavior_check"]) / 2
+ + scores["skill_efficiency"]
+ ) / 5
+
+ assert overall_score_from_metrics(scores) == pytest.approx(expected)
+
+
+ "values",
+ [[], [0.5] * 4, [0.5] * 6, [0.5, 0.5, 0.5, 0.5, float("nan")]],
+)
+def test_canonical_dimension_mean_rejects_partial_or_invalid_dimension_sets(values: list[float]) -> None:
+ assert canonical_dimension_mean(values) is None
+
+
def test_lift_omits_unpaired_metrics_and_incomplete_overall() -> None:
lift = _compute_lift(
{"security": 1.0, "accuracy": 0.8},
diff --git a/tests/test_issue55_collector_truth.py b/tests/test_issue55_collector_truth.py
index 40915dac..ed12143f 100644
--- a/tests/test_issue55_collector_truth.py
+++ b/tests/test_issue55_collector_truth.py
@@ -14,10 +14,7 @@ from pathlib import Path
import pytest
-from skillevaluator.evaluation.tier3_report import (
- agent_eval_result_from_directory,
- render_agent_eval_html_report,
-)
+from skillevaluator.evaluation.tier3_report import build_agent_eval_payload, render_agent_eval_html_report
from skillevaluator.tier3.harbor import collector as collector_module
from skillevaluator.tier3.harbor import report, report_data
from skillevaluator.tier3.harbor.collector import (
@@ -30,6 +27,7 @@ from skillevaluator.tier3.harbor.metrics import (
CUSTOM_ONLY_METRIC_SET,
DEFAULT_METRIC_SET,
DEFAULT_METRICS,
+ DEFAULT_SCORE_POLICY,
LEGACY_METRIC_SET,
LEGACY_METRICS,
MAX_CUSTOM_METRIC_NAME_BYTES,
@@ -173,6 +171,367 @@ def _collect(
)
+def test_collection_and_canonical_report_share_one_versioned_overall_score_policy(tmp_path: Path) -> None:
+ skill_path = tmp_path / "demo"
+ skill_path.mkdir()
+ baseline = {"entry_id": "case-001", "metric_set": DEFAULT_METRIC_SET, **dict.fromkeys(DEFAULT_METRICS, 0.5)}
+ with_skill = {
+ "entry_id": "case-001",
+ "metric_set": DEFAULT_METRIC_SET,
+ "security": 0.3875,
+ "skill_execution": 0.3875,
+ "skill_efficiency": 0.3875,
+ "accuracy": 0.3875,
+ "goal_accuracy": 0.9,
+ "behavior_check": 0.9,
+ }
+ for variant, reward in (("with", with_skill), ("without", baseline)):
+ job_dir = tmp_path / "jobs" / f"demo-opencode-{variant}"
+ _write_reward(job_dir, "case-001__attempt", reward)
+ _write_complete_job_result(job_dir, ["case-001__attempt"])
+
+ result = _collect(tmp_path, skip_baseline=False, case_ids=["case-001"])
+ agent = result["agents"]["opencode"]
+ payload = build_agent_eval_payload(
+ "demo",
+ result["agents"],
+ attempt_policy=result["attempt_policy"],
+ use_llm_judge=False,
+ )
+
+ assert result["score_policy"] == DEFAULT_SCORE_POLICY
+ assert result["attempt_policy"]["score_policy"] == DEFAULT_SCORE_POLICY
+ assert agent["lift"]["overall"] == {"with_skill": 0.49, "without_skill": 0.5, "delta": -0.01}
+ assert agent["pass_at_k"]["with_skill"]["cases"]["case-001"]["best_score"] == 0.49
+ with_summary = json.loads(
+ (tmp_path / "results" / "opencode" / "with-skill" / "summary.json").read_text(encoding="utf-8")
+ )
+ assert with_summary["overall_score"] == 0.49
+ assert with_summary["score_policy"] == DEFAULT_SCORE_POLICY
+ assert payload is not None
+ assert payload["score_policy"] == DEFAULT_SCORE_POLICY
+ assert payload["summary"]["score_policy"] == DEFAULT_SCORE_POLICY
+ assert payload["overall_score"] == 0.49
+ assert payload["overall_lift"] == -0.01
+
+ report_path = render_agent_eval_html_report(skill_path, tmp_path / "results", use_llm_judge=False)
+ report_html = report_path.read_text(encoding="utf-8")
+ assert DEFAULT_SCORE_POLICY in report_html
+ assert "-0.01" in report_html
+
+ persisted_policy = json.loads((tmp_path / "results" / "attempt_policy.json").read_text(encoding="utf-8"))
+ assert persisted_policy["score_policy"] == DEFAULT_SCORE_POLICY
+ assert DEFAULT_SCORE_POLICY in persisted_policy["score_definition"]
+
+
+def test_recollecting_historical_rewards_keeps_pass_summary_and_report_consistent(tmp_path: Path) -> None:
+ skill_path = tmp_path / "demo"
+ skill_path.mkdir()
+ with_skill = {
+ "entry_id": "case-001",
+ "metric_set": DEFAULT_METRIC_SET,
+ "security": 0.3875,
+ "skill_execution": 0.3875,
+ "skill_efficiency": 0.3875,
+ "accuracy": 0.3875,
+ "goal_accuracy": 0.9,
+ "behavior_check": 0.9,
+ "overall": 0.5583,
+ }
+ baseline = {
+ "entry_id": "case-001",
+ "metric_set": DEFAULT_METRIC_SET,
+ **dict.fromkeys(DEFAULT_METRICS, 0.5),
+ "overall": 0.5,
+ }
+ for variant, reward in (("with", with_skill), ("without", baseline)):
+ job_dir = tmp_path / "jobs" / f"demo-opencode-{variant}"
+ _write_reward(job_dir, "case-001__attempt", reward)
+ _write_complete_job_result(job_dir, ["case-001__attempt"])
+
+ result = _collect(tmp_path, skip_baseline=False, case_ids=["case-001"])
+ with_summary = json.loads(
+ (tmp_path / "results" / "opencode" / "with-skill" / "summary.json").read_text(encoding="utf-8")
+ )
+ report = build_agent_eval_payload(
+ "demo", result["agents"], attempt_policy=result["attempt_policy"], use_llm_judge=False
+ )
+
+ assert result["score_policy"] == LEGACY_SCORE_POLICY
+ assert with_summary["score_policy"] == LEGACY_SCORE_POLICY
+ assert with_summary["overall_score"] == 0.5583
+ assert result["agents"]["opencode"]["pass_at_k"]["with_skill"]["cases"]["case-001"]["best_score"] == 0.5583
+ assert result["agents"]["opencode"]["lift"]["overall"]["delta"] == 0.0583
+ assert report is not None
+ assert report["overall_score"] == 0.5583
+
+
+def test_historical_condition_accepts_cases_where_both_formulas_agree(tmp_path: Path) -> None:
+ historical = {
+ "entry_id": "case-001",
+ "metric_set": DEFAULT_METRIC_SET,
+ "security": 0.3875,
+ "skill_execution": 0.3875,
+ "skill_efficiency": 0.3875,
+ "accuracy": 0.3875,
+ "goal_accuracy": 0.9,
+ "behavior_check": 0.9,
+ "overall": 0.5583,
+ }
+ equal_formulas = {
+ "entry_id": "case-002",
+ "metric_set": DEFAULT_METRIC_SET,
+ **dict.fromkeys(DEFAULT_METRICS, 0.5),
+ "overall": 0.5,
+ }
+ for variant, rewards in (
+ ("with", [historical, equal_formulas]),
+ ("without", [dict(equal_formulas, entry_id="case-001"), equal_formulas]),
+ ):
+ job_dir = tmp_path / "jobs" / f"demo-opencode-{variant}"
+ for index, reward in enumerate(rewards, start=1):
+ _write_reward(job_dir, f"case-{index:03d}__attempt", reward)
+ _write_complete_job_result(job_dir, ["case-001__attempt", "case-002__attempt"])
+
+ result = _collect(tmp_path, skip_baseline=False, case_ids=["case-001", "case-002"])
+
+ assert result["execution_status"] == "succeeded"
+ assert result["score_policy"] == LEGACY_SCORE_POLICY
+ assert result["agents"]["opencode"]["lift"]["overall"]["delta"] == 0.0292
+
+
+def test_mixed_explicit_reward_policies_fail_the_condition(tmp_path: Path) -> None:
+ job_dir = tmp_path / "jobs" / "demo-opencode-with"
+ for index, policy in enumerate((DEFAULT_SCORE_POLICY, LEGACY_SCORE_POLICY), start=1):
+ _write_reward(
+ job_dir,
+ f"case-{index:03d}__attempt",
+ {
+ "entry_id": f"case-{index:03d}",
+ "metric_set": DEFAULT_METRIC_SET,
+ "score_policy": policy,
+ **dict.fromkeys(DEFAULT_METRICS, 0.5),
+ "overall": 0.5,
+ },
+ )
+ _write_complete_job_result(job_dir, ["case-001__attempt", "case-002__attempt"])
+
+ result = _collect(tmp_path, skip_baseline=True, case_ids=["case-001", "case-002"])
+ summary = json.loads(
+ (tmp_path / "results" / "opencode" / "with-skill" / "summary.json").read_text(encoding="utf-8")
+ )
+
+ assert result["execution_status"] == "failed"
+ assert summary["execution_status"] == "failed"
+ assert summary["overall_score"] is None
+ assert any("score policies" in error.lower() for error in result["execution_errors"])
+
+
+def test_paired_conditions_with_different_policies_have_no_publishable_scores(tmp_path: Path) -> None:
+ for variant, policy, score in (
+ ("with", DEFAULT_SCORE_POLICY, 0.8),
+ ("without", LEGACY_SCORE_POLICY, 0.2),
+ ):
+ job_dir = tmp_path / "jobs" / f"demo-opencode-{variant}"
+ _write_reward(
+ job_dir,
+ "case-001__attempt",
+ {
+ "entry_id": "case-001",
+ "metric_set": DEFAULT_METRIC_SET,
+ "score_policy": policy,
+ **dict.fromkeys(DEFAULT_METRICS, score),
+ "overall": score,
+ },
+ )
+ _write_complete_job_result(job_dir, ["case-001__attempt"])
+
+ result = _collect(tmp_path, skip_baseline=False, case_ids=["case-001"])
+ agent = result["agents"]["opencode"]
+ with_summary = json.loads(
+ (tmp_path / "results" / "opencode" / "with-skill" / "summary.json").read_text(encoding="utf-8")
+ )
+ without_summary = json.loads(
+ (tmp_path / "results" / "opencode" / "without-skill" / "summary.json").read_text(encoding="utf-8")
+ )
+
+ assert result["execution_status"] == "failed"
+ assert agent["lift"] == {}
+ assert with_summary["execution_status"] == "failed"
+ assert without_summary["execution_status"] == "failed"
+ assert with_summary["scores"] == without_summary["scores"] == {}
+
+
+def test_multi_agent_collection_rejects_incomparable_score_policies(tmp_path: Path) -> None:
+ for agent, policy in (("opencode", DEFAULT_SCORE_POLICY), ("codex", LEGACY_SCORE_POLICY)):
+ job_dir = tmp_path / "jobs" / f"demo-{agent}-with"
+ _write_reward(
+ job_dir,
+ "case-001__attempt",
+ {
+ "entry_id": "case-001",
+ "metric_set": DEFAULT_METRIC_SET,
+ "score_policy": policy,
+ **dict.fromkeys(DEFAULT_METRICS, 0.5),
+ "overall": 0.5,
+ },
+ )
+ _write_complete_job_result(job_dir, ["case-001__attempt"])
+
+ result = collect_harbor_results(
+ skill_name="demo",
+ agents=["opencode", "codex"],
+ output_dir=tmp_path / "results",
+ jobs_dir=tmp_path / "jobs",
+ skip_baseline=True,
+ expected_cases=1,
+ expected_case_ids=["case-001"],
+ expected_trials=1,
+ )
+
+ assert result["execution_status"] == "failed"
+ assert result["score_policy"] == "mixed-score-policies"
+ assert "comparison" not in result
+ assert any("score policies" in error.lower() for error in result["execution_errors"])
+
+
+def test_failed_later_agent_does_not_relabel_a_successful_legacy_agent(tmp_path: Path) -> None:
+ job_dir = tmp_path / "jobs" / "demo-opencode-with"
+ _write_reward(
+ job_dir,
+ "case-001__attempt",
+ {
+ "entry_id": "case-001",
+ "metric_set": DEFAULT_METRIC_SET,
+ "score_policy": LEGACY_SCORE_POLICY,
+ **dict.fromkeys(DEFAULT_METRICS, 0.5),
+ "overall": 0.5,
+ },
+ )
+ _write_complete_job_result(job_dir, ["case-001__attempt"])
+
+ result = collect_harbor_results(
+ skill_name="demo",
+ agents=["opencode", "codex"],
+ output_dir=tmp_path / "results",
+ jobs_dir=tmp_path / "jobs",
+ skip_baseline=True,
+ expected_cases=1,
+ expected_case_ids=["case-001"],
+ expected_trials=1,
+ )
+
+ assert result["execution_status"] == "failed"
+ assert result["score_policy"] == LEGACY_SCORE_POLICY
+ assert LEGACY_SCORE_POLICY in result["attempt_policy"]["score_definition"]
+
+
[email protected]("reverse_conditions", [False, True])
+def test_different_condition_metric_sets_preserve_scores_without_overall_lift(
+ tmp_path: Path, reverse_conditions: bool
+) -> None:
+ legacy = {
+ "entry_id": "case-001",
+ "metric_set": LEGACY_METRIC_SET,
+ "score_policy": LEGACY_SCORE_POLICY,
+ **dict.fromkeys(LEGACY_METRICS, 0.8),
+ "overall": 0.8,
+ }
+ historical = {**legacy, "metric_set": DEFAULT_METRIC_SET, "security": 0.0, "overall": 0.6667}
+ conditions = [legacy, historical]
+ if reverse_conditions:
+ conditions.reverse()
+ for variant, reward in zip(("with", "without"), conditions, strict=True):
+ job_dir = tmp_path / "jobs" / f"demo-opencode-{variant}"
+ _write_reward(job_dir, "case-001__attempt", reward)
+ _write_complete_job_result(job_dir, ["case-001__attempt"])
+
+ result = _collect(tmp_path, skip_baseline=False, case_ids=["case-001"])
+ agent = result["agents"]["opencode"]
+ assert result["execution_status"] == "succeeded"
+ assert agent["overall_with_skill"] == conditions[0]["overall"]
+ assert agent["overall_without_skill"] == conditions[1]["overall"]
+ assert "overall" not in agent["lift"]
+ assert all(agent["lift"][metric]["delta"] == 0.0 for metric in LEGACY_METRICS)
+ assert agent["pass_at_k"]["lift"] == {}
+ persisted_lift = json.loads((tmp_path / "results/opencode/lift.json").read_text(encoding="utf-8"))
+ assert "overall" not in persisted_lift
+ assert not (tmp_path / "results/opencode/pass_at_k_lift.json").exists()
+
+ # Rendering older artifacts must not revive the invalid comparisons either.
+ persisted_lift["overall"] = {"with_skill": 0.8, "without_skill": 0.6667, "delta": 0.1333}
+ (tmp_path / "results/opencode/lift.json").write_text(json.dumps(persisted_lift), encoding="utf-8")
+ (tmp_path / "results/opencode/pass_at_k_lift.json").write_text(
+ json.dumps({"with_skill": 1.0, "without_skill": 0.0, "delta": 1.0}), encoding="utf-8"
+ )
+ for agents in (result["agents"], report_data.load_agent_data(tmp_path / "results")):
+ payload = build_agent_eval_payload(
+ "demo", agents, attempt_policy=result["attempt_policy"], use_llm_judge=False
+ )
+ assert payload is not None
+ assert payload["overall_score"] == conditions[0]["overall"]
+ assert payload["agents"]["opencode"]["baseline"] == conditions[1]["overall"]
+ assert payload["agents"]["opencode"]["lift"] is None
+ assert payload["overall_lift"] is None
+ assert payload["pass_at_k"]["lift"] == {}
+ assert all("baseline_overall" not in trial for trial in payload["trials"])
+
+
[email protected]("reverse_agents", [False, True])
[email protected]("same_metric_set", [False, True])
+def test_multi_agent_legacy_reports_preserve_each_agents_metric_set(
+ tmp_path: Path, reverse_agents: bool, same_metric_set: bool
+) -> None:
+ agents = ["opencode", "codex"]
+ for agent, score in zip(agents, (0.9, 0.7), strict=True):
+ use_legacy = agent == "opencode" or same_metric_set
+ metrics = LEGACY_METRICS if use_legacy else DEFAULT_METRICS
+ job_dir = tmp_path / "jobs" / f"demo-{agent}-with"
+ _write_reward(
+ job_dir,
+ "case-001__attempt",
+ {
+ "entry_id": "case-001",
+ "metric_set": LEGACY_METRIC_SET if use_legacy else DEFAULT_METRIC_SET,
+ "score_policy": LEGACY_SCORE_POLICY,
+ **dict.fromkeys(metrics, score),
+ "overall": score,
+ },
+ )
+ _write_complete_job_result(job_dir, ["case-001__attempt"])
+ if reverse_agents:
+ agents.reverse()
+ result = collect_harbor_results(
+ skill_name="demo",
+ agents=agents,
+ output_dir=tmp_path / "results",
+ jobs_dir=tmp_path / "jobs",
+ skip_baseline=True,
+ expected_cases=1,
+ expected_case_ids=["case-001"],
+ expected_trials=1,
+ )
+
+ for data in (result["agents"], report_data.load_agent_data(tmp_path / "results")):
+ payload = build_agent_eval_payload(
+ "demo", data, attempt_policy=result["attempt_policy"], use_llm_judge=False
+ )
+ assert payload is not None
+ assert payload["agents"]["opencode"]["with_skill"] == 0.9
+ assert payload["agents"]["codex"]["with_skill"] == 0.7
+ if same_metric_set:
+ assert payload["execution_status"] == "succeeded"
+ assert payload["best_agent"] == "opencode"
+ assert payload["overall_score"] == 0.9
+ assert report._pick_best_agent(data) == "opencode"
+ else:
+ assert payload["best_agent"] == ""
+ assert payload["overall_score"] is None
+ assert payload["execution_status"] == "failed"
+ assert any("metric sets" in error.lower() for error in payload["execution_errors"])
+ assert report._pick_best_agent(data) == ""
+
+
def test_failed_judge_sidecar_is_merged_but_never_scored_and_reason_is_safe(tmp_path: Path) -> None:
job_dir = tmp_path / "jobs" / "demo-opencode-with"
trial_name = "case-001__attempt"
diff --git a/tests/test_results_location.py b/tests/test_results_location.py
index 758b6287..26acbebe 100644
--- a/tests/test_results_location.py
+++ b/tests/test_results_location.py
@@ -13,6 +13,7 @@ from pathlib import Path
import pytest
+from skillevaluator.constants import DEFAULT_SCORE_POLICY
from skillevaluator.tier3 import results_location
from skillevaluator.tier3.output_provenance import mark_generated_output_root
from skillevaluator.tier3.results_location import external_results_root, resolve_latest_results
@@ -99,11 +100,13 @@ def _write_authenticated_current_run(
"result_path": recorded_result_path or str((run_dir / "result.json").resolve()),
"run_config": run_config,
"agents": {"opencode": agent_result},
+ "score_policy": DEFAULT_SCORE_POLICY,
"attempt_policy": {
"max_attempts": 1,
"pass_threshold": 0.5,
"stop_on_pass": False,
"score_definition": "test",
+ "score_policy": DEFAULT_SCORE_POLICY,
},
"execution_status": "succeeded",
"execution_errors": [],
@@ -267,6 +270,68 @@ def test_latest_results_rejects_authenticated_current_run_with_malformed_result_
assert resolve_latest_results(skill_path, cli_results_dir, environ={}) == historical
[email protected]("invalid_score_policy", ["", 1, None])
+def test_latest_results_rejects_invalid_recorded_score_policy(tmp_path: Path, invalid_score_policy: object) -> None:
+ skill_path = tmp_path / "demo"
+ skill_path.mkdir()
+ cli_results_dir = tmp_path / "results"
+ root = external_results_root(cli_results_dir, skill_path)
+ historical = _write_completed_run(root, "20260705_120000")
+ current = _write_authenticated_current_run(root, "20260705_130000_222_bbbbbbbbbbbb")
+ result_path = current / "result.json"
+ result = json.loads(result_path.read_text(encoding="utf-8"))
+ result["attempt_policy"]["score_policy"] = invalid_score_policy
+ result_path.write_text(json.dumps(result), encoding="utf-8")
+
+ assert resolve_latest_results(skill_path, cli_results_dir, environ={}) == historical
+
+
[email protected]("invalid_score_policy", ["", 1, None])
+def test_latest_results_rejects_invalid_top_level_score_policy(tmp_path: Path, invalid_score_policy: object) -> None:
+ skill_path = tmp_path / "demo"
+ skill_path.mkdir()
+ cli_results_dir = tmp_path / "results"
+ root = external_results_root(cli_results_dir, skill_path)
+ historical = _write_completed_run(root, "20260705_120000")
+ current = _write_authenticated_current_run(root, "20260705_130000_222_bbbbbbbbbbbb")
+ result_path = current / "result.json"
+ result = json.loads(result_path.read_text(encoding="utf-8"))
+ result["score_policy"] = invalid_score_policy
+ result_path.write_text(json.dumps(result), encoding="utf-8")
+
+ assert resolve_latest_results(skill_path, cli_results_dir, environ={}) == historical
+
+
+def test_latest_results_rejects_mismatched_score_policies(tmp_path: Path) -> None:
+ skill_path = tmp_path / "demo"
+ skill_path.mkdir()
+ cli_results_dir = tmp_path / "results"
+ root = external_results_root(cli_results_dir, skill_path)
+ historical = _write_completed_run(root, "20260705_120000")
+ current = _write_authenticated_current_run(root, "20260705_130000_222_bbbbbbbbbbbb")
+ result_path = current / "result.json"
+ result = json.loads(result_path.read_text(encoding="utf-8"))
+ result["score_policy"] = "different-policy-v1"
+ result_path.write_text(json.dumps(result), encoding="utf-8")
+
+ assert resolve_latest_results(skill_path, cli_results_dir, environ={}) == historical
+
+
+def test_latest_results_accepts_authenticated_current_run_without_historical_score_policy(tmp_path: Path) -> None:
+ skill_path = tmp_path / "demo"
+ skill_path.mkdir()
+ cli_results_dir = tmp_path / "results"
+ root = external_results_root(cli_results_dir, skill_path)
+ current = _write_authenticated_current_run(root, "20260705_130000_222_bbbbbbbbbbbb")
+ result_path = current / "result.json"
+ result = json.loads(result_path.read_text(encoding="utf-8"))
+ result["attempt_policy"].pop("score_policy")
+ result.pop("score_policy")
+ result_path.write_text(json.dumps(result), encoding="utf-8")
+
+ assert resolve_latest_results(skill_path, cli_results_dir, environ={}) == current
+
+
def test_latest_results_accepts_authenticated_current_run_with_relative_recorded_path_after_cwd_change(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/test_tier3_compare.py b/tests/test_tier3_compare.py
index 3298fc39..67845232 100644
--- a/tests/test_tier3_compare.py
+++ b/tests/test_tier3_compare.py
@@ -11,7 +11,8 @@ from pathlib import Path
import pytest
-from skillevaluator.tier3.commands import compare_results
+from skillevaluator.tier3.commands import _overall_score_for_display, _summary_overall, compare_results
+from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS, DEFAULT_SCORE_POLICY
from skillevaluator.tier3.output_provenance import mark_generated_output_root
@@ -23,6 +24,117 @@ def _complete_current_run(run_dir: Path) -> None:
)
+def test_compare_overall_uses_the_canonical_dimension_mean() -> None:
+ scores = {
+ "security": 0.3875,
+ "skill_execution": 0.3875,
+ "skill_efficiency": 0.3875,
+ "accuracy": 0.3875,
+ "goal_accuracy": 0.9,
+ "behavior_check": 0.9,
+ }
+
+ assert _overall_score_for_display(scores, DEFAULT_METRICS) == pytest.approx(0.49)
+
+
+def test_overall_display_preserves_pre_policy_default_v2_semantics() -> None:
+ scores = {
+ "security": 0.3875,
+ "skill_execution": 0.3875,
+ "skill_efficiency": 0.3875,
+ "accuracy": 0.3875,
+ "goal_accuracy": 0.9,
+ "behavior_check": 0.9,
+ }
+
+ assert _overall_score_for_display(scores, DEFAULT_METRICS, score_policy=None) == pytest.approx(0.5583)
+ assert _overall_score_for_display(
+ scores,
+ DEFAULT_METRICS,
+ persisted_overall=0.5583,
+ score_policy=None,
+ ) == pytest.approx(0.5583)
+ assert _overall_score_for_display(
+ scores,
+ DEFAULT_METRICS,
+ persisted_overall=0.5583,
+ score_policy=DEFAULT_SCORE_POLICY,
+ ) == pytest.approx(0.49)
+
+
[email protected]("invalid_overall", [2.0, -0.1, float("inf"), 10**4000, True])
+def test_historical_overall_rejects_invalid_persisted_scores(invalid_overall: object) -> None:
+ scores = {
+ "security": 0.3875,
+ "skill_execution": 0.3875,
+ "skill_efficiency": 0.3875,
+ "accuracy": 0.3875,
+ "goal_accuracy": 0.9,
+ "behavior_check": 0.9,
+ }
+
+ assert _summary_overall({"overall_score": invalid_overall}) is None
+ assert _overall_score_for_display(
+ scores,
+ DEFAULT_METRICS,
+ persisted_overall=invalid_overall,
+ score_policy=None,
+ ) == pytest.approx(0.5583)
+
+
+def test_compare_carries_persisted_historical_overall(
+ tmp_path: Path,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ skill_path = tmp_path / "demo"
+ skill_path.mkdir()
+ run_dir = tmp_path / "results" / "demo" / "20260709_010000"
+ summary = run_dir / "opencode" / "with-skill" / "summary.json"
+ summary.parent.mkdir(parents=True)
+ summary.write_text(
+ json.dumps(
+ {
+ "execution_status": "succeeded",
+ "scores": {
+ "security": 0.3875,
+ "skill_execution": 0.3875,
+ "skill_efficiency": 0.3875,
+ "accuracy": 0.3875,
+ "goal_accuracy": 0.9,
+ "behavior_check": 0.9,
+ },
+ "overall_score": 0.5583,
+ "metric_set": "skill-evaluator-default-v2",
+ "metrics": list(DEFAULT_METRICS),
+ "num_trials": 1,
+ }
+ ),
+ encoding="utf-8",
+ )
+ baseline_summary = run_dir / "opencode" / "without-skill" / "summary.json"
+ baseline_summary.parent.mkdir(parents=True)
+ baseline_summary.write_text(
+ json.dumps(
+ {
+ "execution_status": "succeeded",
+ "scores": dict.fromkeys(DEFAULT_METRICS, 0.5),
+ "overall_score": 0.5,
+ "metric_set": "skill-evaluator-default-v2",
+ "metrics": list(DEFAULT_METRICS),
+ "num_trials": 1,
+ }
+ ),
+ encoding="utf-8",
+ )
+ _complete_current_run(run_dir)
+
+ assert compare_results(skill_path, results_dir=tmp_path / "results") == 0
+ output = capsys.readouterr().out
+ assert "0.56" in output
+ assert "0.49" not in output
+ assert "+0.06" in output
+
+
def _write_authentic_pre_status_run(root: Path, run_id: str, *, score: float = 0.8) -> Path:
run_dir = root / run_id
summary_dir = run_dir / "opencode" / "with-skill"
diff --git a/tests/test_tier3_result_display.py b/tests/test_tier3_result_display.py
index 968027f0..d03441a0 100644
--- a/tests/test_tier3_result_display.py
+++ b/tests/test_tier3_result_display.py
@@ -189,6 +189,21 @@ def test_skip_baseline_success_uses_canonical_default_metric_aggregate() -> None
assert "skipped" in output
+def test_skip_baseline_default_overall_uses_the_dimension_score_policy() -> None:
+ agent = _skip_baseline_agent(
+ {
+ "security": 0.3875,
+ "skill_execution": 0.3875,
+ "skill_efficiency": 0.3875,
+ "accuracy": 0.3875,
+ "goal_accuracy": 0.9,
+ "behavior_check": 0.9,
+ }
+ )
+
+ assert _with_skill_overall(agent, DEFAULT_METRIC_SET) == pytest.approx(0.49)
+
+
def test_skip_baseline_custom_only_uses_persisted_attempt_scores() -> None:
agent = _skip_baseline_agent({}, pass_rate=0.5)
agent["pass_at_k"] = {
diff --git a/tests/tier3/test_judge_failure_artifacts.py b/tests/tier3/test_judge_failure_artifacts.py
index c9edcb20..c52ddd22 100644
--- a/tests/tier3/test_judge_failure_artifacts.py
+++ b/tests/tier3/test_judge_failure_artifacts.py
@@ -369,8 +369,8 @@ def test_verifier_main_keeps_genuine_zero_judge_verdicts_scoreable(
"goal_accuracy": 0.0,
"behavior_check": 0.0,
}
- assert numeric["overall"] == 0.5
- assert overall_score(numeric) == 0.5
+ assert numeric["overall"] == 0.6
+ assert overall_score(numeric) == 0.6
def test_verifier_main_recovers_malformed_accuracy_and_goal_judges(
diff --git a/tests/tier3/test_negative_control_invocation_evidence.py b/tests/tier3/test_negative_control_invocation_evidence.py
index a6536483..4ffbb68f 100644
--- a/tests/tier3/test_negative_control_invocation_evidence.py
+++ b/tests/tier3/test_negative_control_invocation_evidence.py
@@ -13,6 +13,7 @@ from pathlib import Path
import pytest
from skillevaluator.tier3.eval_core import checks as shared_checks
+from skillevaluator.tier3.harbor.metrics import overall_score
def _load_template():
@@ -498,11 +499,7 @@ def test_template_main_scores_standard_negative_fail_closed(tmp_path, monkeypatc
result = json.loads(rich_reward_json.read_text(encoding="utf-8"))
harbor_reward = json.loads(reward_json.read_text(encoding="utf-8"))
expected_reward_keys = {*TEMPLATE.DISPLAY_METRICS, "overall"}
- expected_overall = round(
- sum(float(result.get(metric, 0.0) or 0.0) for metric in TEMPLATE.DISPLAY_METRICS)
- / len(TEMPLATE.DISPLAY_METRICS),
- 4,
- )
+ expected_overall = overall_score(result)
assert result["skill_execution"] == 0.0
if include_trusted_identity: