Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
feat(tier3): upgrade Harbor to 0.24.0 (#83)
Narendran Raghavancec2440d11fe
diff --git a/.gitleaks.toml b/.gitleaks.tomlindex 27cf54a0..81df4055 100644--- a/.gitleaks.toml+++ b/.gitleaks.toml@@ -23,3 +23,10 @@ condition = "AND"targetRules = ["generic-api-key"]regexes = ['''^main-(persistent|task|scoped)-secret-[0-9]{5}$''']paths = ['''^tests/test_harbor_secure_docker_environment\.py$''']++[[allowlists]]+description = "Synthetic cwsandbox API key used by Harbor environment contract tests"+condition = "AND"+targetRules = ["generic-api-key"]+regexes = ['''^cw-key-123456$''']+paths = ['''^tests/test_harbor_environment_contract\.py$''']diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 820423ab..44ee8417 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,9 +4,33 @@ All notable changes to SkillEvaluator are documented in this file.## Unreleased+### 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.22.0 and its compatible+- Upgraded the optional Tier 3 backend to Harbor 0.24.0 and its compatibleLiteLLM 1.92-1.93 window. Existing SkillEvaluator agent and environmentoptions now use Harbor's unified selectors; installed Codex adapters preservemerged user and MCP configuration; Docker and local execution stream redacted@@ -15,14 +39,52 @@ All notable changes to SkillEvaluator are documented in this file.limit; and Docker supports stdin plus isolated sidecar operations withoutexposing environment values on Compose argv. Generated schema 1.3 andunmodified native task schemas remain compatible, while collection accepts- Harbor 0.22 job, trial, reward, and ATIF v1.7 artifacts.-- Exposed Harbor 0.22's complete 26-backend environment set alongside local- mode. Non-secret backend constructor options can be supplied with repeatable,- operator-only `--environment-kwarg` / `--ek` flags; skill-owned configuration,+ 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 unresolvedpersisted identities fail closed instead of trusting grader-authored IDs.@@ -34,7 +96,8 @@ All notable changes to SkillEvaluator are documented in this file.nonzero exits, timeouts, output limits, and persisted launch errors.- Tier 3 local OpenCode runs routed through NVIDIA Build now retain the rendereduser instruction for ATIF conversion and fail on OpenCode error events, in- parity with Harbor 0.22's upstream agent lifecycle.+ 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 acondition mixes standard and custom rewards, including across separatetrials, and aggregate execution summaries preserve child-declared hidden@@ -52,19 +115,375 @@ All notable changes to SkillEvaluator are documented in this file.fallback models are forwarded only to standard verifier jobs, not agent or`custom_only` environments. Its Python payload now runs from a replacedevaluator-owned directory in isolated mode. `custom_only`- retains Harbor-native collect hooks and Harbor 0.22's shared/separate+ retains Harbor-native collect hooks and Harbor's shared/separatestep-test resolution, and fully authored native test paths are left untouchedinstead of replacing their unused `tests/skill_evaluator/` package.All native grading modes reject Windows agent or effective verifierenvironments until evaluator projection and verifier scripts are OS-aware.-- Tier 3 paired pass@k evidence now respects Python's active integer-string- conversion limit, preserves nonzero Wilson interval widths and paired-effect- directions at large case counts, and documents exact-rational omission- markers.- Tier 3 collection now fails closed on unsafe reward identities and malformedcustom-metric contracts, publishes exact truncation metadata for boundedcase and failure-detail samples, and keeps findings, attribution, andper-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.+- 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.+ Add `--max-entries` and `--max-scalar-comparisons` for explicit scan budgets;+ exceeded limits fail with actionable errors and never truncate the collection.+ Fresh pairwise scans reject excessive scalar work after the first validated+ embedding response, before requesting more embeddings or saving a catalog.+ Collection discovery has its own 20,000-path ceiling, allowing the supported+ 5,000-entry maximum for minimal collections while retaining the 4,096-path+ per-skill ceiling. Invalid Python command API budgets raise option-specific+ errors before provider initialization. Similarity comparisons validate and+ normalize each vector once instead of once per pair, making large pairwise+ scans more than an order of magnitude faster. Equal nonzero embeddings score+ exactly 1.0, so `--threshold 1` reports exact duplicates.+- Keep headings and comments inside fenced code examples in their enclosing Markdown+ section during Tier 2 content chunking, preserving original source line numbers.+- Run the public Docker image as an unprivileged user, with writable default report and home directories.+ Document UID/GID overrides for host-owned output mounts.+- Pin the HTML report Chart.js dependency and verify its integrity before browser execution.++- Preserve full Codex gateway model IDs in cloud environments, including E2B+ and Daytona, while retaining local runtime setup and native provider routing.+- Keep Tier 2 execution diagnostics visible alongside duplicate findings in+ CLI, HTML, and Markdown reports, without repeating the findings as errors.+- Use `nvidia/nemotron-3-super-120b-a12b` as the shared NVIDIA Build default for+ evaluator chat, agent execution, and judging, preserving explicit model overrides.+ Request nonstreaming chat responses explicitly to match the response parser.+- Tier 2 LLM failures now identify the selected provider and model, HTTP status,+ safe error metadata, and failed-cluster count without exposing response bodies.+- Replace the retired NVIDIA embedding default with `nvidia/nemotron-3-embed-1b`+ and send the required passage input type for NVIDIA document comparisons.+ Existing catalogs and caches must be rebuilt when switching embedding models.+- Report Tier 2 embedding and LLM service failures as incomplete checks, retaining+ a nonzero exit without inventing duplicate-content findings. Provider error+ messages include recovery guidance without echoing raw response bodies.+- Tier 3 script execution credit now requires evidence that the expected script+ was invoked. `check_script_execution` previously treated the script name as a+ substring of an execution command, so reading, printing or searching the+ script, or running a similarly named file, scored a full `Executed <script>`.+ Credit is now given only for a recognised invocation: the script run directly,+ an interpreter given it as its script argument, a `source`, or a `sh -c`+ payload that does one of those, with `cd` tracked and script identity compared+ exactly. Interpreter and wrapper options come from grammars derived by running+ each option against a script that records whether it executed, so `--help`,+ `perl -c` and `bash -n` run no script while `python -Wignore` and+ `env FOO=1` still resolve to theirs. A command the walk cannot resolve keeps+ the existing 0.75 partial credit rather than being scored either way: a path+ built at run time, an option outside a grammar, a name only in heredoc data,+ inline code or a module that names the script, and anything reaching a command+ through standard input, including `xargs` and `parallel`, whose behaviour the+ command text never determines. Partial credit is only ever given for a+ command that names the script: an unresolved command that never mentions it+ scores zero, as before. Redirections standing before the script+ (`python3 < /dev/null run.py`), a script's own arguments that look like shell+ options (`bash run.sh -c '...'`), invocations inside `if`, `while`, `until`+ and `for` bodies, and versioned interpreter names (`perl5.38.2`, `python3.13`)+ resolve as the shell runs them. A loop over an empty list keeps the earlier+ binding and its body is not read; a binding made inside `( ... )` stays+ there; the last command of a pipeline keeps its bindings where the shell+ does (zsh, ksh) and not where it forks it (bash, dash, mksh), with an+ option change that could move it (`shopt -s lastpipe`, `emulate sh`)+ read as unresolved; a quoted or escaped word that would read as syntax+ (`'done'`, `printf "("`, `';|'`) is the ordinary word it is; groups and+ compound pipeline stages nest in either order, each compound tested for its+ own pipe; `((` closed by `))` is an arithmetic command where the shell has+ one; the positional+ parameters are empty unless the text gives some, so `for f; do` at the top+ level runs nothing and keeps the variable's value; an interpreter fed its+ program by a pipe (`cat run.py | python3`) is unresolved like+ `python3 < run.py`; a variable bound by `export` or `readonly`, or by+ `declare` and `typeset` where the shell has them, holds the value it had+ when the builtin ran, `unset` empties it, `+x` and `export -n` unexport it+ however the builtin is reached, and one bound from data the text does not+ carry (`read`, `printf -v`, `local` outside a function, `declare -u`, a name+ `eval` may bind, including from a program held in a variable) is+ unresolved, as is a later assignment to a name given `-i`, `-u` or `-n`,+ while `-l` lowercases it and an array is never exported; what is done to a+ `-n` name (`nameref` in ksh and mksh) leaves the name it refers to+ unresolved; `let`, `$((...))` and `$[...]` assign as `((...))` does; an+ assignment the shell rejects (a value that is not a number for an `-i`+ name) and a special builtin given an option the shell rejects end the+ credit where the shell stops there; an assignment written before a command,+ `env NAME=value` included, is that command's environment only, reaching+ neither its own words nor the commands after it, except before a special+ builtin in the POSIX shells; a `-c` payload's shell sees the exported names,+ its command's own prefix and what `env` adds and removes, and a `$` quoted+ or escaped from the outer shell is expanded there (one left unquoted is+ expanded here, a name never bound to nothing), with the payload's own+ heredoc bodies kept as data; text that `eval`, inline+ code or a shell reading a heredoc may expand again is unresolved when a+ variable in it holds the script; every heredoc declared on a line takes its+ body after the line, in order, and past the number a shell accepts on one+ line (16 in bash) the line and the rest are data; a here-string, which dash+ and busybox ash reject before running anything, leaves nothing credited+ under those shells, and so does a compound's opening word written after an+ assignment (`A=1 for ...`, `A=1 if ...`, `A=1 ( ... )`), which every+ modelled shell rejects and which no longer raises; `(((` is a subshell+ around `((` in bash, zsh and mksh; and `ksh`, `mksh` and `ash` are+ recognised shells.+ Applied to both the host checker and the bundled Harbor verifier.++- Added `scripts/script_invocation_differential.py`, a differential harness that+ executes each command for real against fixtures that record whether they ran,+ and compares the result against both implementations. `--baseline REF` also+ scores every command with the checker at an earlier ref and lists each score+ that moved, so a change that lowers a command that ran, or raises one that+ did not, is seen before it is pushed.++### Added++- Interactive top-level help now opens with a green SkillEvaluator wordmark,+ installed version, and tier overview. Narrow terminals use a compact header;+ redirected output and subcommands keep their existing output format.++- OpenAI-compatible gateways now have chat, embedding, and separate Codex,+ Claude Code, and OpenCode model defaults. Set the provider, URL, and key;+ override model IDs when the gateway uses different catalog names. Claude+ Code inherits the gateway route unless an explicit Anthropic route is set.+ Run reports identify harness defaults separately from CLI/config overrides.++- Run individual tiers directly with `skillevaluator tier1 PATH`, `tier2 PATH`,+ and `tier3 PATH`, while retaining the expert subcommands. Tier 1 includes+ dependency checks and enables LLM checks when configured; Tier 2 reports+ whether a catalog comparison ran; Tier 3 creates a missing starter dataset+ and preserves existing evaluation sources.++### Changed++- Show elapsed waiting time during autopilot dataset generation and identify+ deterministic starter datasets used after a provider failure. Fully unscored+ Tier 3 runs show an `INCOMPLETE` summary with coverage, consolidated execution+ errors, and recovery steps; completed comparisons highlight overall Skill+ Lift ([#152](https://github.com/NVIDIA/SkillEvaluator/pull/152)).+- Harden documentation publishing with restricted token permissions, pinned+ checkout and Fern versions, and disabled persisted checkout credentials.+ Apply the checkout credential restriction to DCO checks+ ([#158](https://github.com/NVIDIA/SkillEvaluator/pull/158)).+- Add the methodology paper as the preferred citation and link research,+ developer-blog, and livestream resources from the README+ ([#146](https://github.com/NVIDIA/SkillEvaluator/pull/146),+ [#159](https://github.com/NVIDIA/SkillEvaluator/pull/159)).+- `validate PATH` now runs all three tiers for skills by default. Tier 3+ autopilot reuses an existing evaluation source or creates one starter case+ when none exists. `--full` remains compatible but is unnecessary;+ `--tiers`, `--no-tier3`, and `--no-autopilot` provide explicit scope controls.+ Keyless static CI gates should select `--tiers 1`.+- Tier 3 now selects a provider-native agent when `--agents` is omitted:+ OpenCode for NVIDIA Build, Codex for OpenAI, and Claude Code for Anthropic.+ NVIDIA Build agent runs default to Nemotron Super; explicit agent and model+ overrides remain unchanged.+- Tier 3's extra agent runtime preflight is now disabled by default because it+ executes the first real task prompt and incurs agent runtime and model cost.+ Enable it explicitly with `--agent-runtime-preflight` on either `tier3` or+ `validate`, or with `harbor.agent_runtime_preflight: true` in `evals/config.yml`.+- Missing-provider and API-key errors now show concise, copyable setup steps+ and a link to advanced configuration. Tier 1 also explains `--no-llm`.+- `tier1 validate` now runs only Tier 1, matching `tier1 PATH`. The top-level+ `validate` command retains its combined pipeline behavior.+- README and getting-started guides lead with provider-plus-key setup for+ NVIDIA Build and OpenAI, explain inherited model defaults, and separate+ credentials from scanner and agent runtime requirements.++## 0.3.0 - 2026-09-17++### Added++- Catalog validation now writes `catalog-summary.json` at the reports root with+ per-skill pass/fail status, optional severity rollups from child JSON reports,+ and paths to per-skill report directories.+- Catalog `validate` accepts `--workers N` to validate skills in parallel child+ processes (default 1 preserves the serial per-skill pipeline view).+- `SKILL_EVAL_MODEL_CATALOG_ALLOW_HTTP_HOSTS` names hosts whose model catalog may+ be read over plain HTTP. Catalog reads still require HTTPS for every other+ non-loopback host. Entries match one whole host as written, with no name+ resolution. A plain-HTTP request to an accepted host bypasses any inherited+ HTTP proxy so its bearer token is not offered to an intermediary. The+ transport rechecks authorization before dispatch and rejects hosts that+ are no longer allowed.+- Published benchmark cards record the evaluated source identity. `BENCHMARK.md`+ now carries `Evaluated source`, `Evaluated source revision` and+ `Evaluator container revision` as separate fields, so a reader can tell which+ source tree was evaluated apart from the evaluator build that evaluated it.+ Previously two skills evaluated from different repositories by the same+ evaluator container produced cards whose only recorded revision was the shared+ container tag. `validate` and `tier3 evaluate` take the identity as+ `--evaluated-source-repository`, `--evaluated-source-revision` and+ `--evaluator-container-revision`. `validate` records it on the card and in+ the top-level `evaluated_source` object of its JSON report and forwards it to+ every child of a parallel catalog run; both commands persist it into a Tier 3+ run's `run_config.json`. It can also arrive as the `evaluated_source`+ argument to `build_agent_eval_payload`, as an `evaluated_source` object in the+ run's `run_config.json`, or as `metadata["evaluated_source"]` on any+ validation result. It is never inferred from repository state while rendering,+ because the tree that renders a card is the evaluator checkout rather than the+ evaluated skill's source. Every populated carrier, including the payload of+ every Tier 3 result, is folded into one identity before any report is+ written, so carriers that disagree fail closed with nothing published instead+ of letting result ordering decide which source tree a card claims to describe.+ A revision is accepted only in an unambiguous shape: a full Git object id+ (40 or 64 hex characters), or a digest whose width matches the algorithm it+ names. A container revision is an image reference validated by component (a+ repository path of up to 255 characters, an optional tag of up to 128, and a+ digest at its algorithm's width), so a long repository name is no longer+ discarded. The 255 bound measures the path once the registry host is split+ off it. Path components are lower case, as the OCI grammar requires, while a+ registry host may use any case and is read as a host only when it is+ `localhost`, carries a dot, or carries a port.+ `check_public_benchmarks.py --require-source-provenance` requires the+ fields and fails any card publishing a `PASS` without them, including a+ `PASS` whose evaluator container is named by a mutable tag rather than+ pinned by digest. SkillEvaluator's own CI now runs the scan with that flag;+ it stays opt-in for trees whose cards predate the contract+ ([#72](https://github.com/NVIDIA/SkillEvaluator/issues/72)).+- SARIF 2.1.0 reporter (`-r sarif`) for GitHub Code Scanning and other SARIF+ consumers. Findings map to rule IDs, severity levels, and file locations from+ Tier 1 validation results.++### 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)).+- `--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+ instead of any path containing those substrings, so files like `latest.py`+ are scanned.+- Gitleaks CI now limits pull-request and push scans to history reachable from+ the checked-out commit, while audit events retain all-ref coverage,+ preventing unrelated refs from causing false failures+ ([#106](https://github.com/NVIDIA/SkillEvaluator/pull/106)).+- The Tier 3 agent runtime preflight now fails with an actionable diagnostic when+ the results directory is not visible to the Docker daemon. Previously the smoke+ run passed -- agent output travels over the Docker exec API rather than through+ the mounts -- and every scored trial then failed with `RewardFileNotFoundError`+ while the rewards sat inside the daemon's own filesystem.+- Dead-link validation now uses the shared CommonMark parser, covering+ reference-style and HTML links while preserving Markdown image checks and+ consistently normalizing local destinations. Root-absolute URLs are ignored+ instead of being treated as host paths; href-only diagnostics collapse+ repeated links to the same normalized target. Invalid destination bytes do+ not alias other files, relative URLs that normalize to absolute or+ drive-relative paths are reported without lookup, lookup failures remain+ per-link findings, and link diagnostics are bounded and escaped. Malformed+ frontmatter and repeated unclosed HTML comments no longer abort or stall+ supporting-document checks.+- Tier 3 accuracy and custom goal judges now retry one malformed (including+ empty) or schema-invalid response with a 4096-token output budget before+ failing closed, preventing a transient formatting error from making an otherwise+ successful trial and its full comparison arm unscoreable. Generated and+ injected Harbor verifier configs now reserve 600 seconds for six sequential+ direct provider attempts plus fail-closed artifact writes. Explicit native+ task timeouts remain owner-controlled and are not rewritten, and whole jobs+ defer to Harbor's task-configured phase controls instead of a hidden two-hour+ cap+ ([#70](https://github.com/NVIDIA/SkillEvaluator/issues/70)).+- PII scanning no longer treats Markdown ATX headings as code comments, so+ emails in headings such as `# Contact: ...` are flagged. Hash lines inside+ Python strings, YAML scalars, and shell heredocs are scanned too. Real+ comments stay skipped, including YAML frontmatter, fenced code, and+ `requirements.txt` ([#88](https://github.com/NVIDIA/SkillEvaluator/issues/88)).+- Tier 3 Harbor collection no longer scans an agent's unstructured transcript+ for runtime-error phrases when the recorded exception belongs to the+ verifier, health check, or task. Correct answers that discuss errors such as+ `401 Unauthorized` are no longer misreported as agent runtime failures.+- SkillSpector reports now use validated version-specific completeness+ contracts. Valid findings from coherent 2.10+ partial scans remain visible+ while the result stays incomplete, and fully covered 2.9.5/2.9.6 `--no-llm`+ reports remain compatible. Contradictory finding or component totals and+ duplicate component identities fail closed. Versioned findings require+ producer paths, and complete reports reconcile universal analyzer work with+ the component inventory. Reports scored before 2.10 finding compaction remain+ accepted. Shipped bytecode findings, source-scoped executable evidence, and+ version-specific finding identities remain authoritative without overstating+ compacted or hidden finding evidence. SkillSpector 2.11+ requires bundled+ execution-surface analyzer evidence; 2.11.1+ uses classification-aware+ finding IDs while rejecting conflicting reuse of an ID.+- Tier 3 paired pass@k evidence now respects Python's active integer-string+ conversion limit, preserves nonzero Wilson interval widths and paired-effect+ directions at large case counts, and documents exact-rational omission+ markers.+- Tier 3 now decodes bounded native Codex `exec` wrappers into their static+ tool calls. It preserves call order and outer-call provenance, maps an outer+ observation only when its rendered inner call is known, keeps ambiguous+ observations explicit, and reports unsupported or malformed JavaScript as+ untrusted instead of a clean security result.## 0.2.1 - 2026-08-24diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex fb517a00..4df5ff18 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -8,5 +8,5 @@ records the exact resolved dependency set used for this release.| --- | --- || Base | Click (BSD-3-Clause), IDNA (BSD-3-Clause), Jinja2 (BSD-3-Clause), Markdown-It-Py (MIT), Pydantic (MIT), PyYAML (MIT), Rich (MIT) || LLM | Anthropic (MIT), Boto3 (Apache-2.0), LiteLLM (MIT), OpenAI (Apache-2.0) |-| Tier 3 | Harbor (Apache-2.0), MCP (MIT), PyJWT (MIT) |+| Tier 3 | Harbor (Apache-2.0), MCP (MIT), PyJWT (MIT), python-dotenv (BSD-3-Clause) || Security | Bandit (Apache-2.0), pip-audit (Apache-2.0) |diff --git a/docs/agents-and-sandboxes.mdx b/docs/agents-and-sandboxes.mdxindex a825d07f..618d197c 100644--- a/docs/agents-and-sandboxes.mdx+++ b/docs/agents-and-sandboxes.mdx@@ -127,39 +127,36 @@ Anthropic evaluator with `opencode` also does not support local mode.## Where trials run-SkillEvaluator exposes 27 environment modes: 26 Harbor-native backends,+SkillEvaluator exposes 24 environment modes: 23 Harbor-native backends,including Docker, plus SkillEvaluator's own `local` host-execution mode.-Docker is the default. The `tier3` extra installs base `harbor==0.22.0`; install+Docker is the default. The `tier3` extra installs base `harbor==0.24.0`; installthe environment extra shown below when a managed backend needs one.| Mode | Type | Harbor extra or system prerequisite || --- | --- | --- || `docker` | Harbor-native | No additional Python extra. Requires Docker Engine and Docker Compose v2 — see [Docker mode](#docker-mode). |-| `daytona` | Harbor-native | `harbor[daytona]==0.22.0` |-| `e2b` | Harbor-native | `harbor[e2b]==0.22.0` |-| `modal` | Harbor-native | `harbor[modal]==0.22.0` |-| `runloop` | Harbor-native | `harbor[runloop]==0.22.0` |-| `langsmith` | Harbor-native | `harbor[langsmith]==0.22.0` |-| `ec2` | Harbor-native | `harbor[ec2]==0.22.0` |-| `gke` | Harbor-native | `harbor[gke]==0.22.0` |-| `ack` | Harbor-native | `harbor[gke]==0.22.0` |+| `daytona` | Harbor-native | `harbor[daytona]==0.24.0` |+| `e2b` | Harbor-native | `harbor[e2b]==0.24.0` |+| `modal` | Harbor-native | `harbor[modal]==0.24.0` |+| `runloop` | Harbor-native | `harbor[runloop]==0.24.0` |+| `langsmith` | Harbor-native | `harbor[langsmith]==0.24.0` |+| `ec2` | Harbor-native | `harbor[ec2]==0.24.0` |+| `gke` | Harbor-native | `harbor[gke]==0.24.0` |+| `ack` | Harbor-native | `harbor[gke]==0.24.0` || `openshift` | Harbor-native | No Harbor Python extra; install and authenticate the OpenShift `oc` CLI. |-| `novita` | Harbor-native | `harbor[novita]==0.22.0` |+| `novita` | Harbor-native | `harbor[novita]==0.24.0` || `apple-container` | Harbor-native | No Harbor Python extra; install the Apple `container` CLI. || `singularity` | Harbor-native | No Harbor Python extra; install the `singularity` CLI Harbor invokes. |-| `islo` | Harbor-native | `harbor[islo]==0.22.0` |-| `tensorlake` | Harbor-native | `harbor[tensorlake]==0.22.0` |-| `cwsandbox` | Harbor-native | `harbor[cwsandbox]==0.22.0` |-| `wandb` | Harbor-native | `harbor[wandb]==0.22.0` |-| `use-computer` | Harbor-native | `harbor[use-computer]==0.22.0` |-| `cua-cloud` | Harbor-native | `harbor[cua]==0.22.0` |-| `blaxel` | Harbor-native | `harbor[blaxel]==0.22.0` |-| `opensandbox` | Harbor-native | `harbor[opensandbox]==0.22.0` |-| `beam` | Harbor-native | `harbor[beam]==0.22.0` |-| `skypilot` | Harbor-native | `harbor[skypilot]==0.22.0` |-| `hf-sandbox` | Harbor-native | `harbor[hf-sandbox]==0.22.0` |-| `hyperbrowser` | Harbor-native | `harbor[hyperbrowser]==0.22.0` |-| `vercel` | Harbor-native | `harbor[vercel]==0.22.0` |+| `islo` | Harbor-native | `harbor[islo]==0.24.0` |+| `tensorlake` | Harbor-native | `harbor[tensorlake]==0.24.0` |+| `cwsandbox` | Harbor-native | `harbor[cwsandbox]==0.24.0` |+| `wandb` | Harbor-native | `harbor[cwsandbox]==0.24.0` |+| `use-computer` | Harbor-native | `harbor[use-computer]==0.24.0` |+| `blaxel` | Harbor-native | `harbor[blaxel]==0.24.0` |+| `beam` | Harbor-native | `harbor[beam]==0.24.0` |+| `skypilot` | Harbor-native | `harbor[skypilot]==0.24.0` |+| `hyperbrowser` | Harbor-native | `harbor[hyperbrowser]==0.24.0` |+| `vercel` | Harbor-native | `harbor[vercel]==0.24.0` || `local` | SkillEvaluator | Your machine, under an OS sandbox policy — see [Local mode](#local-mode). |<Tip>@@ -169,6 +166,20 @@ credentials that backend requires, and confirm readiness with`skillevaluator doctor --env-mode <mode>` before a full run.</Tip>+Harbor 0.24 merged its W&B sandbox into `cwsandbox`. SkillEvaluator keeps+`--env-mode wandb` and runs it as Harbor's `cwsandbox` backend with W&B+authentication (`auth=wandb`), using `WANDB_API_KEY` or the netrc file that+`wandb login` writes. Because SkillEvaluator sets `auth` itself, `--ek auth=...`+is rejected for both `cwsandbox` and `wandb`.++Harbor 0.24 also defines `cua-cloud`, `opensandbox`, `hf-sandbox`, `podman`,+`kata`, `runta`, `prime`, `mosaic`, and `smol`, but those backends are not+exposed until SkillEvaluator can project the complete task bundle — skill,+verifier, dependencies, and inputs — through a trusted image or+backend-native provisioning path, with credentials and constructor options+reviewed per backend. Selecting one of those names is rejected before a run+starts.+### Native backend constructor optionsEnvironment kwargs are operator-only and apply only to Harbor-native@@ -220,12 +231,6 @@ running SkillEvaluator; it is forwarded only to the EC2 backend process. Aprovided `ssh_key_path` must resolve to an existing regular file. Ephemeral EC2with `use_public_ip=false` also requires a non-empty `subnet_id`.-OpenSandbox requires either a non-empty `domain` constructor option or a-child-visible `OPENSANDBOX_DOMAIN`. An explicitly empty `domain` is invalid and-does not fall back to the host variable; `domain=null` uses the child-visible-variable. An API key remains optional because OpenSandbox also supports local-or otherwise unauthenticated deployments.-Managed-backend readiness is not a connectivity test. EC2 preflight checks thePython extra, the local `ssh` executable, and the constructor invariants above;it does not contact AWS or prove credentials, AMI/instance access, networking,@@ -240,7 +245,7 @@ in-cluster service account and performs a bounded, namespaced pod-list probebefore launching trials. `KUBERNETES_SERVICE_HOST` and`KUBERNETES_SERVICE_PORT` are forwarded only for this ACK client path.-Harbor 0.22 Modal preflight requires `~/.modal.toml` or `MODAL_TOKEN_ID` plus+Harbor 0.24 Modal preflight requires `~/.modal.toml` or `MODAL_TOKEN_ID` plus`MODAL_TOKEN_SECRET`. SkillEvaluator validates and forwards an explicitly set`MODAL_CONFIG_PATH`, but Harbor's child-process preflight does not recognize acustom config path by itself; configure one of Harbor's supported credentialdiff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdxindex b1141e0f..f86ae0a3 100644--- a/docs/cli-reference.mdx+++ b/docs/cli-reference.mdx@@ -382,8 +382,8 @@ Use `skillevaluator tier3 PATH` for the complete workflow with automatic missing| Flag | Default | Effect || --- | --- | --- |-| `-a, --agents TEXT` | `codex` | Comma-separated Harbor agents. Supported: `claude-code`, `codex`, `opencode`; the alias `claude` is accepted for `claude-code`. See [Agents & Sandboxes](agents-and-sandboxes.mdx). |-| `--env-mode` | `docker` | Where trials run. SkillEvaluator exposes 27 environment modes: 26 Harbor-native backends, including Docker, plus SkillEvaluator `local` mode. See the complete extras and prerequisites matrix in [Agents & Sandboxes](agents-and-sandboxes.mdx). |+| `-a, --agents TEXT` | provider-native | Comma-separated Harbor agents. Defaults: NVIDIA Build=`opencode`, OpenAI=`codex`, Anthropic=`claude-code`. Supported: `claude-code`, `codex`, `opencode`; the alias `claude` is accepted for `claude-code`. See [Agents & Sandboxes](agents-and-sandboxes.mdx). |+| `--env-mode` | `docker` | Where trials run. SkillEvaluator exposes 24 environment modes: 23 Harbor-native backends, including Docker, plus SkillEvaluator `local` mode. See the complete extras and prerequisites matrix in [Agents & Sandboxes](agents-and-sandboxes.mdx). || `--environment-kwarg`, `--ek` | none | Operator-only `KEY=VALUE` constructor option for Harbor-native non-Docker backends (repeatable). Values accept JSON-compatible types; skill-owned `evals/config.yml` cannot set them. Never pass secrets. Docker and local reject all kwargs, and Harbor runtime-policy fields for overrides, mounts, networks, extra Compose, lifecycle, and pod security are reserved. || `--autopilot` | off | Create one eval case when no dataset/task source exists, then evaluate. The case is LLM-generated with the configured provider, with a deterministic keyless template fallback; an existing source is never overwritten. || `--skip-baseline` | off | Skip the without-skill baseline (no lift analysis, faster). |@@ -515,8 +515,8 @@ skillevaluator doctor --env-mode docker| Flag | Default | Effect || --- | --- | --- |-| `-a, --agents TEXT` | `codex` | Comma-separated agents to check. |-| `--env-mode` | `docker` | Backend to check (same 27 modes as [tier3 evaluate](#tier3-evaluate)). |+| `-a, --agents TEXT` | provider-native | Comma-separated agents to check. Defaults: NVIDIA Build=`opencode`, OpenAI=`codex`, Anthropic=`claude-code`. |+| `--env-mode` | `docker` | Backend to check (same 24 modes as [tier3 evaluate](#tier3-evaluate)). || `--environment-kwarg`, `--ek` | none | `KEY=VALUE` non-secret constructor option for a Harbor-native non-Docker backend (repeatable). Pass the same values intended for evaluation. Docker and local reject all kwargs; policy-owned fields are rejected for every eligible backend. || `--agent-model TEXT` | unset | Per-agent model override, `AGENT=MODEL` (repeatable) — check readiness with the model each agent will actually run. || `--verify-models` | off | Live per-agent catalog probe. Prints pass for verified access, warn for an inconclusive or non-authoritative result (success or failure), and fail only for a definitive credential, model, or configuration rejection. |@@ -533,8 +533,8 @@ skillevaluator health-check| Flag | Default | Effect || --- | --- | --- |-| `-a, --agents TEXT` | `codex` | Comma-separated agents to check. |-| `--env-mode` | `docker` | Backend to check (same 27 modes as [tier3 evaluate](#tier3-evaluate)). |+| `-a, --agents TEXT` | provider-native | Comma-separated agents to check. Defaults: NVIDIA Build=`opencode`, OpenAI=`codex`, Anthropic=`claude-code`. |+| `--env-mode` | `docker` | Backend to check (same 24 modes as [tier3 evaluate](#tier3-evaluate)). || `--environment-kwarg`, `--ek` | none | `KEY=VALUE` non-secret constructor option for a Harbor-native non-Docker backend (repeatable). Pass the same values intended for evaluation. Docker and local reject all kwargs; policy-owned fields are rejected for every eligible backend. |## modelsdiff --git a/docs/custom-graders.mdx b/docs/custom-graders.mdxindex 3b42cc2c..d9d1e404 100644--- a/docs/custom-graders.mdx+++ b/docs/custom-graders.mdx@@ -191,6 +191,15 @@ Edit `instruction.md` for the agent-facing task, `environment/Dockerfile` forthe container, and `tests/grader.py` for the scoring — the same rewardcontract as BYOG applies.+A `custom_only` task that keeps its own Harbor test script instead of+`tests/grader.py` runs that script unchanged, so the script must follow+Harbor's reward contract. Harbor 0.24 requires every top-level value in its+`reward.json` to be a number, for example+`{"overall": 1.0, "native_quality": 1.0}`; SkillEvaluator reports each numeric+key other than `overall` as a custom metric. Nested objects such as+`custom_metrics` or `details` make Harbor reject the reward with+`VerifierOutputParseError`, so use `tests/grader.py` when you need them.+Two rules keep BYOT predictable:- **Case IDs must match dataset entries.** When the grading mode is `default`diff --git a/docs/eval-datasets.mdx b/docs/eval-datasets.mdxindex 478ab317..7bfdff38 100644--- a/docs/eval-datasets.mdx+++ b/docs/eval-datasets.mdx@@ -250,13 +250,12 @@ grading:| `harbor.n_concurrent` | integer ≥ 1 | Concurrent trials. || `harbor.max_agents` | integer ≥ 1 | Cap on agents evaluated in one run. || `harbor.timeout_multiplier` | finite number > 0 | Scales task timeouts. Values that would overflow Harbor's mandatory lifecycle timeouts are rejected before execution. |-| `harbor.agent_runtime_preflight` | boolean | Bounded one-task smoke run that checks agent runtime readiness before the full evaluation. Default: `true`. |+| `harbor.agent_runtime_preflight` | boolean | Opt-in extra agent-only execution of the first staged task before the measured evaluation. Default: `false`; the CLI flag overrides this value. || `harbor.agent_workdir` | string | Working directory for the agent inside the container. || `harbor.resources` | `cpus`, `memory_mb`, `storage_mb` | Per-container resource requests. || `harbor.runtime_env` | list or mapping | Non-credential task values passed into the container. Prefer a list of plain names — each expands to `${NAME}` from your shell; a mapping sets explicit templates. Entries that name or reference operator-owned credentials (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `NVIDIA_API_KEY`, base-URL variables, AWS credential variables) fail with a hard error. Alias: `passthrough_env`. || `harbor.pre_agent_setup` | string or list | Shell commands run in the container before the agent starts. This skill-owned code is allowed only for with-skill-only runs (`--skip-baseline`); paired runs reject it so setup cannot distinguish or alter the baseline arm. Alias: `setup_commands`. Both spellings normalize to the same policy. || `harbor.agents.<name>.model` | string | Per-agent model override; whitespace is trimmed. `claude` is accepted as an alias of `claude-code`, but configuring both spellings in one config is an error. |-| `skill_workspace.mode` | `isolated`, `group` | Whether sibling skills are visible — see [Agents & Sandboxes](agents-and-sandboxes.mdx). || `skill_workspace.include` | list of paths | Extra skills staged into a `group` workspace. || `grading.mode` | `default`, `default_plus_custom`, `custom_only` | Grading pipeline — see [Custom Graders & Tasks](custom-graders.mdx). Legacy spellings `aces_default` and `aces_plus_custom` are accepted and normalized to `default` and `default_plus_custom`. |diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdxindex 3538dc5b..434a98dc 100644--- a/docs/tier3-live-evaluation.mdx+++ b/docs/tier3-live-evaluation.mdx@@ -51,24 +51,31 @@ depth.| The agent and its credential | Same `doctor` run, with your agents; `tier3 evaluate` re-validates before any run | [Agents & Sandboxes](agents-and-sandboxes.mdx) || Docker running (the default environment) | `docker info` | [Agents & Sandboxes](agents-and-sandboxes.mdx) |-## Harbor 0.22 compatibility+## Harbor 0.24 compatibility-The `tier3` extra installs Harbor 0.22.0, the supported Tier 3 backend for this+The `tier3` extra installs Harbor 0.24.0, the supported Tier 3 backend for thisrelease. The `[all]` extra includes `tier3`. Existing SkillEvaluator commands donot change: the public `--agents` and `--env-mode` options map built-in names andinstalled adapters to Harbor's unified `--agent` and `--env` selectors.The exact Harbor pin is deliberate: its CLI, Python models, result artifacts,and environment/agent subclass interfaces form one compatibility surface. This-release targets stable Harbor 0.22.0 rather than unreleased `main`. Harbor stays+release targets stable Harbor 0.24.0 rather than unreleased `main`. Harbor staysbehind the operator-selected `tier3` extra, so static Tier 1 installs do not pullit in. The shared LLM client window (`litellm>=1.92.0,<1.94.0.dev0`) admitspatched 1.92 and 1.93 releases validated with this integration while excludingprerelease and as-yet unvalidated 1.94 behavior.The integration preserves SkillEvaluator's runtime and artifact contracts while-using Harbor 0.22:-+using Harbor 0.24:++- Every Harbor process starts in an empty, evaluator-owned working directory+ with `.env` loading and Harbor telemetry disabled. Harbor ignores `.env.local`+ and `.env` files around your project, so it sees only SkillEvaluator's+ allowlisted environment. Relative host paths such as `KUBECONFIG` keep their+ meaning.+- Codex runs with `reasoning_effort=high`, the effort Harbor 0.22 used by+ default, so results stay comparable across Harbor upgrades.- Installed Codex adapters merge existing user and MCP configuration before theselected runtime provider and endpoint take precedence over conflicting routekeys.@@ -92,12 +99,53 @@ using Harbor 0.22:and accepts regular files and directories only. Links, junctions, hardlinks,sparse files, special files, compressed streams, and unsafe or collidingWindows path spellings fail closed before publication.-- Generated tasks retain schema 1.3, which Harbor 0.22 accepts. User-owned native+- Generated tasks retain schema 1.3, which Harbor 0.24 accepts. User-owned nativetasks, including schema 1.4, are staged without a schema rewrite. Collection- accepts Harbor 0.22 job, trial, reward, and ATIF v1.7 artifacts, including- single-step `step_results: null` and authoritative multi-step results.+ accepts Harbor 0.24 job, trial, reward, and ATIF v1.8 artifacts, including+ single-step `step_results: null`, authoritative multi-step results, and+ multimodal tool output, which judges and reports see as text with+ `[image]`/`[audio]` markers.+- Native tasks follow Harbor 0.24's separate-verifier precedence: a verifier+ image, or a `Dockerfile` or `docker-compose.yaml` in the step or task `tests/`+ directory, defines a dedicated verifier that must ship its own test script.+ Otherwise the verifier is built from `environment/` and receives the uploaded+ tests. SkillEvaluator validates that Compose model against the verifier's+ environment allowlist, and rejects `docker-compose.yml` verifier definitions,+ which Harbor ignores.+- Harbor 0.24 rejects a `reward.json` whose top-level values are not all+ numbers. SkillEvaluator's verifier and wrapped custom graders already write+ numeric rewards; a native task's own test script must do the same. When+ Harbor records such a failure on a step, the failed job names that step's+ exception instead of reporting only a trial count.++## Start with one command++After the [provider setup](configuration.mdx) and runtime prerequisites above:++```bash title="Run Tier 3"+skillevaluator tier3 ./my-skill+```++The direct workflow uses Docker and selects an agent from the provider: OpenCode+for NVIDIA Build, Codex for OpenAI, or Claude Code for Anthropic. If no accepted+dataset or task source exists, it generates one starter case and proceeds to the+live with-skill and without-skill comparison. It reuses valid existing sources+unchanged; invalid sources produce an error rather than being replaced.+A generated starter case lets you try the pipeline, but does not establish+broad positive and negative coverage.++The same agent, model, environment, grading, and reporting options described for+`tier3 evaluate` apply to this direct workflow. For example:-## Run your first evaluation+```bash title="Choose the agent"+skillevaluator tier3 ./my-skill --agents opencode --env-mode docker+```++`tier3 evaluate` remains available for explicit execution; its missing-source+generation requires `--autopilot`. To prepare and review a fuller dataset before+running, follow the steps below.++## Prepare and review a fuller evaluation<Steps toc={true}>@@ -335,18 +383,23 @@ explicit models — see [Agents & Sandboxes](agents-and-sandboxes.mdx).## Where agents run-`--env-mode` selects one of 27 environment modes: 26 Harbor-native backends,+`--env-mode` selects one of 24 environment modes: 23 Harbor-native backends,including the default Docker backend, plus SkillEvaluator's **local mode**,which runs the agent CLI directly on the host under an OS-sandbox policy.Managed backends such as `daytona`, `e2b`, and `modal` require their mapped-Harbor 0.22 extra; OpenShift, Apple Container, and Singularity instead use+Harbor 0.24 extra; OpenShift, Apple Container, and Singularity instead usesystem CLIs and have no Harbor Python extra. These are selectable integrationmodes, not evidence that every managed backend was exercised end to end for-this release. Harbor 0.22 transport verification covers Docker and local;+this release. Harbor 0.24 transport verification covers Docker and local;validate any managed backend's extra, credentials, infrastructure, andconstructor settings with `doctor` and its Harbor preflight before relying onit.+Harbor's `cua-cloud`, `opensandbox`, `hf-sandbox`, `podman`, `kata`, `runta`,+`prime`, `mosaic`, and `smol` backends are not selectable because they cannot+yet receive SkillEvaluator's complete generated task bundle through a trusted+image or backend-native provisioning path.+Environment kwargs are only for Harbor-native non-Docker backends. Passnon-secret constructor settings with the repeatable, operator-only`--environment-kwarg KEY=VALUE` / `--ek KEY=VALUE` option. Skill-owneddiff --git a/pyproject.toml b/pyproject.tomlindex b7174051..db8eee76 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -61,11 +61,13 @@ tier2 = [# Tier 3 live agent evaluation through Harbor's native environments.tier3 = ["skillevaluator[llm]",- "harbor==0.22.0",+ "harbor==0.24.0",# CVE-2026-59950, CVE-2026-52870, and CVE-2026-52869 fixed floor."mcp>=1.28.1,<2",# CVE-2026-48522 through CVE-2026-48526 fixed floor."pyjwt[crypto]>=2.13.0",+ # PYTHON_DOTENV_DISABLED, which keeps Harbor from loading .env files, needs 1.2.0.+ "python-dotenv>=1.2.0",]# Static security scanners (floors raised to the established release baseline).security = [diff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.pyindex c4fd9176..2b571e3e 100644--- a/src/skillevaluator/cli.py+++ b/src/skillevaluator/cli.py@@ -921,6 +921,8 @@ def _catalog_child_argv_from_ctx(ctx: click.Context, skill_dir: Path, output_direnv_mode = params.get("env_mode", "docker")if env_mode != "docker":argv.extend(["--env-mode", str(env_mode)])+ for environment_kwarg in params.get("environment_kwarg") or ():+ argv.extend(["--environment-kwarg", str(environment_kwarg)])if params.get("skip_baseline"):argv.append("--skip-baseline")if params.get("n_concurrent") is not None:@@ -2773,7 +2775,7 @@ def models_command(limit: int, as_json: bool) -> None:help="Check resolved agent-model catalog reachability with a live credential-bearing request.",)def doctor(- agents: str,+ agents: str | None,env_mode: str,environment_kwarg: tuple[str, ...],agent_model: tuple[str, ...],@@ -2794,7 +2796,12 @@ def doctor(@cli.command("health-check")[email protected]("-a", "--agents", default="codex", show_default=True)+ "-a",+ "--agents",+ default=None,+ help="Agent list; default follows the configured provider.",+)@click.option("--env-mode", default="docker", show_default=True, type=ENV_MODE_CHOICE, metavar="MODE")@click.option("--environment-kwarg",@@ -2802,7 +2809,7 @@ def doctor(multiple=True,help="Harbor environment constructor kwarg, KEY=VALUE. Repeat for multiple values; never pass secrets.",)-def health_check(agents: str, env_mode: str, environment_kwarg: tuple[str, ...]) -> None:+def health_check(agents: str | None, env_mode: str, environment_kwarg: tuple[str, ...]) -> None:"""Quick readiness check for the CLI and selected live-eval backend."""from skillevaluator.tier3.commands import doctor as tier3_doctordiff --git a/src/skillevaluator/evaluation/options.py b/src/skillevaluator/evaluation/options.pyindex be396eca..1f091a7d 100644--- a/src/skillevaluator/evaluation/options.py+++ b/src/skillevaluator/evaluation/options.py@@ -26,7 +26,6 @@ class EvaluationOptions:skill_path: Pathagents: str | None = Noneenv_mode: str = "docker"- environment_kwarg: tuple[str, ...] = ()skip_baseline: bool = Falsen_attempts: int | None = Nonepass_threshold: float | None = None@@ -47,6 +46,7 @@ class EvaluationOptions:override_cpus: int | None = Noneoverride_memory_mb: int | None = Noneoverride_storage_mb: int | None = None+ environment_kwarg: tuple[str, ...] = ()# Supplied by the orchestration input, never inferred from repository state:# the tree that runs the evaluator is not the tree being evaluated.evaluated_source: dict[str, str] | None = Nonediff --git a/src/skillevaluator/evaluation/tier3_report.py b/src/skillevaluator/evaluation/tier3_report.pyindex d1e57f51..a213cf07 100644--- a/src/skillevaluator/evaluation/tier3_report.py+++ b/src/skillevaluator/evaluation/tier3_report.py@@ -2637,22 +2637,37 @@ def _overall_verdict_from_agents(agents: dict[str, dict[str, Any]]) -> str:return VERDICT_FAIL+def _canonical_agent_rank(agent: dict[str, Any]) -> tuple[float, float] | None:+ """Return the score/lift tuple used to rank one canonical agent payload."""+ if agent.get("execution_status") != "succeeded":+ return None+ score = _finite_float(agent.get("with_skill"))+ if score is None:+ return None+ return score, _as_float(agent.get("lift"))+++def _canonical_agent_rank_from_info(info: dict[str, Any]) -> tuple[float, float] | None:+ """Build and rank raw Harbor agent data exactly as the canonical report does."""+ from skillevaluator.tier3.harbor.report_data import metrics_for_condition++ agent = _build_agent(+ "",+ info,+ metrics_for_condition(info, "with_skill"),+ metrics_for_condition(info, "without_skill"),+ None,+ )+ return _canonical_agent_rank(agent)++def _pick_best_agent(agents: dict[str, dict[str, Any]]) -> str:- eligible = {- name: agent- for name, agent in agents.items()- if agent.get("execution_status") == "succeeded" and _finite_float(agent.get("with_skill")) is not None- }+ eligible = {name: rank for name, agent in agents.items() if (rank := _canonical_agent_rank(agent)) is not None}if not eligible:return ""if len(eligible) == 1:return next(iter(eligible))-- def _key(item: tuple[str, dict[str, Any]]) -> tuple[float, float]:- _name, agent = item- return (_as_float(agent.get("with_skill")), _as_float(agent.get("lift")))-- return max(eligible.items(), key=_key)[0]+ return max(eligible.items(), key=lambda item: item[1])[0]def _insights_from_dimensions(dimensions: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:diff --git a/src/skillevaluator/tier3/commands.py b/src/skillevaluator/tier3/commands.pyindex 88f10102..2be158c2 100644--- a/src/skillevaluator/tier3/commands.py+++ b/src/skillevaluator/tier3/commands.py@@ -48,6 +48,8 @@ from skillevaluator.tier3.harbor.progress import (from skillevaluator.tier3.harbor.runner import (_check_prerequisites,_harbor_bin,+ _harbor_launch_cwd,+ _harbor_launch_environment,_model_for_agent,_resolve_agent_runtime_plan,run_harbor_eval,@@ -1006,7 +1008,8 @@ def harbor_view(jobs_dir: Path) -> int:"""Open retained Harbor job artifacts with Harbor's trajectory browser."""cmd = [_harbor_bin(), "view", str(jobs_dir.resolve())]try:- return subprocess.call(cmd)+ with _harbor_launch_cwd() as launch_cwd:+ return subprocess.call(cmd, cwd=launch_cwd, env=_harbor_launch_environment(os.environ))except FileNotFoundError:console.print("[red]Error: harbor binary not found.[/red]")return 1diff --git a/src/skillevaluator/tier3/eval_core/atif_helpers.py b/src/skillevaluator/tier3/eval_core/atif_helpers.pyindex 29e391e3..6dbf126b 100644--- a/src/skillevaluator/tier3/eval_core/atif_helpers.py+++ b/src/skillevaluator/tier3/eval_core/atif_helpers.py@@ -17,6 +17,7 @@ import refrom typing import Anyfrom skillevaluator.evidence import evidence_ref_identity+from skillevaluator.tier3.eval_core.codex_tool_call_normalizer import atif_content_textfrom skillevaluator.tier3.eval_core.codex_tool_call_normalizer import (iter_normalized_tool_calls as iter_tool_calls,)@@ -148,7 +149,7 @@ def build_conversation_summary(traj: dict[str, Any], question: str) -> str:obs = step.get("observation") or {}for r in obs.get("results") or []:- content = str(r.get("content", ""))+ content = atif_content_text(r.get("content"))if content:parts.append(f"Tool returned: {content[:400]}")@@ -561,7 +562,7 @@ def _tool_observation_refs(traj: dict[str, Any]) -> list[dict[str, Any]]:for result_idx, result in enumerate((step.get("observation") or {}).get("results") or []):if len(refs) >= _METRIC_EVIDENCE_MAX_TOOL_REFS:return refs- content = str(result.get("content") or "")+ content = atif_content_text(result.get("content"))if not content.strip():continuecall_id = str(result.get("source_call_id") or f"result-{result_idx}")@@ -777,7 +778,7 @@ def _late_observation_excerpts(traj: dict[str, Any], limit: int) -> list[str]:if step.get("source") != "agent":continuefor result in reversed((step.get("observation") or {}).get("results") or []):- content = str(result.get("content") or "").strip()+ content = atif_content_text(result.get("content")).strip()if content:out.append(_clip(content, limit))return outdiff --git a/src/skillevaluator/tier3/eval_core/codex_tool_call_normalizer.py b/src/skillevaluator/tier3/eval_core/codex_tool_call_normalizer.pyindex 5b56f57e..e5d751b4 100644--- a/src/skillevaluator/tier3/eval_core/codex_tool_call_normalizer.py+++ b/src/skillevaluator/tier3/eval_core/codex_tool_call_normalizer.py@@ -20,6 +20,32 @@ _MAX_STATEMENTS = 256_MAX_TOOL_CALLS = 128+def atif_content_text(content: object) -> str:+ """Return the text of an ATIF message or observation content value.++ ATIF content is a string or a list of content parts. Text parts are joined;+ image and audio parts become ``[image]``/``[audio]`` markers so their+ agent-controlled source paths never reach judges or reports.+ """+ if content is None:+ return ""+ if isinstance(content, str):+ return content+ if isinstance(content, list):+ parts: list[str] = []+ for part in content:+ if isinstance(part, str):+ parts.append(part)+ elif isinstance(part, dict):+ kind = part.get("type")+ if kind == "text" and isinstance(part.get("text"), str):+ parts.append(part["text"])+ elif kind in ("image", "audio"):+ parts.append(f"[{kind}]")+ return "\n".join(parts)+ return str(content)++def iter_normalized_tool_calls(traj: dict[str, Any]):"""Yield each trajectory tool call after safe native-Codex normalization."""for step in traj.get("steps", []):@@ -33,7 +59,7 @@ def _outer_tool_call_observation() -> str:tool_call_id = tool_call.get("tool_call_id")return "".join(- str(result.get("content", ""))+ atif_content_text(result.get("content"))for result in (step.get("observation") or {}).get("results") or []if (tool_call_iddiff --git a/src/skillevaluator/tier3/generate_dataset.py b/src/skillevaluator/tier3/generate_dataset.pyindex 10992ec9..2ae3b41d 100644--- a/src/skillevaluator/tier3/generate_dataset.py+++ b/src/skillevaluator/tier3/generate_dataset.py@@ -55,6 +55,7 @@ import yamlfrom skillevaluator.constants import EXECUTABLE_SKILL_DIRSfrom skillevaluator.evaluation.results import DatasetGenerationError, DatasetGenerationResult+from skillevaluator.tier3.eval_core.codex_tool_call_normalizer import atif_content_textfrom skillevaluator.validators.frontmatter_parser import FRONTMATTER_PATTERN_INTERACTIVE_RE = re.compile(@@ -707,7 +708,7 @@ def _summarize_trajectory(trajectory: dict[str, Any], max_steps: int = 25) -> stargs_str = json.dumps(args, ensure_ascii=False)[:120]lines.append(f" {n}. [{fn}] {args_str}")- msg = (step.get("message") or "").strip()+ msg = atif_content_text(step.get("message")).strip()if msg and len(msg) > 30 and n < max_steps:n += 1truncated = msg[:250] + "..." if len(msg) > 250 else msg@@ -914,7 +915,7 @@ def _extract_agent_final_message(trajectory: dict[str, Any]) -> str:for step in reversed(trajectory.get("steps", [])):if step.get("source") != "agent":continue- msg = (step.get("message") or "").strip()+ msg = atif_content_text(step.get("message")).strip()if msg and len(msg) > 20 and not step.get("tool_calls"):return msgreturn ""diff --git a/src/skillevaluator/tier3/harbor/adapter.py b/src/skillevaluator/tier3/harbor/adapter.pyindex f1bded16..26a58575 100644--- a/src/skillevaluator/tier3/harbor/adapter.py+++ b/src/skillevaluator/tier3/harbor/adapter.py@@ -40,6 +40,7 @@ from skillevaluator.tier3.case_ids import (validate_case_ids,validate_output_directory_path,)+from skillevaluator.tier3.harbor import DEFAULT_LLM_VERIFIER_TIMEOUT_SECfrom skillevaluator.tier3.harbor.secure_copy import (copy_file_secure,copytree_secure,@@ -211,8 +212,30 @@ _COMPOSE_ALLOWED_VOLUME_KEYS = frozenset({"labels"})_VERIFIER_JUDGE_MODEL_ENV_VARS = frozenset({"LLM_JUDGE_MODEL", "SKILL_EVAL_JUDGE_MODEL"})_VERIFIER_JUDGE_FALLBACK_ENV_VARS = frozenset({"LLM_JUDGE_FALLBACK_MODELS"})_VERIFIER_JUDGE_CONTROL_ENV_VARS = _VERIFIER_JUDGE_MODEL_ENV_VARS | _VERIFIER_JUDGE_FALLBACK_ENV_VARS+_VERIFIER_BUDGET_ENV_VARS = frozenset(+ {+ "SKILL_EVAL_ACCURACY_BUDGET",+ "SKILL_EVAL_BEHAVIOR_CHECK_BUDGET",+ "SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT",+ "SKILL_EVAL_GOAL_ACCURACY_BUDGET",+ }+)+_VERIFIER_RETRY_ENV_VARS = frozenset(+ {+ "SKILL_EVAL_LLM_JUDGE_BUDGET_SEC",+ "SKILL_EVAL_LLM_MAX_RETRIES",+ "SKILL_EVAL_LLM_RETRY_BASE_DELAY",+ "SKILL_EVAL_LLM_RETRY_MAX_DELAY",+ }+)_VERIFIER_PROVIDER_ENV_VARS = frozenset({+ "SKILL_EVAL_LLM_PROVIDER",+ "SKILL_EVAL_LLM_MODEL",+ "SKILL_EVAL_LLM_API_KEY",+ "SKILL_EVAL_LLM_BASE_URL",+ "OPENAI_API_KEY",+ "OPENAI_BASE_URL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","NVIDIA_API_KEY",@@ -279,6 +302,8 @@ _VERIFIER_PROVIDER_ENV_VARS = frozenset("AWS_USE_FIPS_ENDPOINT","AWS_WEB_IDENTITY_TOKEN_FILE","BOTOCORE_TCP_KEEPALIVE",+ *_VERIFIER_BUDGET_ENV_VARS,+ *_VERIFIER_RETRY_ENV_VARS,})_RUNTIME_PROCESS_CONTROL_ENV_NAMES = frozenset(@@ -2116,16 +2141,17 @@ def _copy_verifier(task_dir: Path) -> None:tests_dir = task_dir / "tests"tests_dir.mkdir(parents=True, exist_ok=True)evaluator_dir = _replace_evaluator_tests_dir(task_dir)- src = TEMPLATES_DIR / "eval.py"- if src.exists():- shutil.copy2(src, evaluator_dir / "eval.py")- else:- logger.warning("Verifier template not found at %s", src)- lc = _EVAL_CORE_DIR / "log_converters.py"- if lc.exists():- shutil.copy2(lc, evaluator_dir / "log_converters.py")- else:- logger.warning("log_converters helper not found at %s", lc)+ sources = (+ (TEMPLATES_DIR / "eval.py", "Verifier template"),+ (_EVAL_CORE_DIR / "log_converters.py", "log_converters helper"),+ (_EVAL_CORE_DIR / "codex_tool_call_normalizer.py", "Codex tool-call normalizer"),+ (_EVAL_CORE_DIR.parent.parent / "evidence.py", "Evidence-reference helper"),+ )+ for src, label in sources:+ if src.exists():+ shutil.copy2(src, evaluator_dir / src.name)+ else:+ logger.warning("%s not found at %s", label, src)def _has_symlink_component(path: Path, root: Path) -> bool:@@ -4837,24 +4863,28 @@ def _validate_native_verifier_compose_boundaries() -> None:"""Keep separate-verifier Compose models inside the verifier env boundary."""from harbor.models.task.config import TaskConfig- from harbor.models.task.paths import TaskPaths- from harbor.models.task.verifier_mode import resolve_effective_verifier_env_configallowed_env = set(verifier_env if verifier_env is not None else runtime_env or {})allowed_env.update(_VERIFIER_JUDGE_CONTROL_ENV_VARS)config = TaskConfig.model_validate(data)- paths = TaskPaths(task_dir)+ paths, steps = _validated_native_task_steps(task_dir, config)contexts: list[Path] = []- if config.steps:- for step in config.steps:- if resolve_effective_verifier_env_config(config, step) is None:- continue- step_context = paths.step_tests_dir(step.name)- if not _path_is_canonically_contained(step_context, paths.steps_dir):- raise ValueError(f"Native Harbor task step verifier path escapes the task: {task_dir / 'task.toml'}")- contexts.append(step_context if step_context.exists() else paths.tests_dir)- elif resolve_effective_verifier_env_config(config, step_cfg=None) is not None:- contexts.append(paths.tests_dir)+ for verifier_pass in _native_verifier_passes(task_dir, config, paths, steps):+ definition = verifier_pass.definition+ if definition is None:+ continue+ # Harbor only recognizes docker-compose.yaml when choosing a verifier+ # definition; a .yml file would silently fall back to environment/.+ candidates = [paths.tests_dir]+ if verifier_pass.step is not None:+ candidates.insert(0, paths.step_tests_dir(verifier_pass.step.name))+ for candidate in candidates:+ if os.path.lexists(candidate / "docker-compose.yml"):+ raise ValueError(+ "Native Harbor verifier Compose files must be named docker-compose.yaml, which Harbor "+ f"recognizes for {verifier_pass.scope}: {candidate / 'docker-compose.yml'}"+ )+ contexts.append(definition.directory if definition.bundled_tests else paths.environment_dir)for context in dict.fromkeys(contexts):if _has_symlink_component(context, paths.task_dir):@@ -4907,11 +4937,31 @@ def _validated_native_task_steps(task_dir: Path, config: Any) -> tuple[Any, listreturn paths, steps-def _effective_native_verifiers(config: Any, steps: list[Any]) -> list[tuple[str, Any | None]]:- from harbor.models.task.verifier_mode import resolve_effective_verifier_env_config+@dataclass(frozen=True)+class _NativeVerifierPass:+ """One Harbor verify pass and the environment definition Harbor builds for it."""++ scope: str+ step: Any | None+ #: ``VerifierEnvironmentDefinition`` for a separate verifier, ``None`` when shared.+ definition: Any | None+++def _native_verifier_passes(task_dir: Path, config: Any, paths: Any, steps: list[Any]) -> list[_NativeVerifierPass]:+ """Resolve every verify pass with Harbor's own separate-verifier precedence."""+ from harbor.models.task.verifier_mode import resolve_verifier_environment_definitionscopes = [("task", None)] if not steps else [(f"step {step.name!r}", step) for step in steps]- return [(scope, resolve_effective_verifier_env_config(config, step)) for scope, step in scopes]+ passes: list[_NativeVerifierPass] = []+ for scope, step in scopes:+ try:+ definition = resolve_verifier_environment_definition(config, paths, step)+ except ValueError as exc:+ raise ValueError(+ f"Native Harbor verifier inputs for {scope} must stay inside the task: {task_dir / 'task.toml'}"+ ) from exc+ passes.append(_NativeVerifierPass(scope, step, definition))+ return passesdef _native_custom_only_tests_are_complete(task_dir: Path) -> bool:@@ -4921,28 +4971,41 @@ def _native_custom_only_tests_are_complete(task_dir: Path) -> bool:tomllib.loads((task_dir / "task.toml").read_text(encoding="utf-8")),)paths, steps = _validated_native_task_steps(task_dir, config)- if not steps:- return paths.discovered_test_path_for(config.environment.os) is not None-- from harbor.models.task.verifier_mode import resolve_effective_verifier_env_config-- for step in steps:- verifier_environment = resolve_effective_verifier_env_config(config, step)- task_os = verifier_environment.os if verifier_environment is not None else config.environment.os- step_test = paths.discovered_step_test_path_for(step.name, task_os)- if verifier_environment is not None and paths.step_tests_dir(step.name).exists():- if step_test is None:+ for verifier_pass in _native_verifier_passes(task_dir, config, paths, steps):+ definition = verifier_pass.definition+ task_os = definition.config.os if definition is not None else config.environment.os+ if definition is not None and definition.bundled_tests:+ # A dedicated verifier image runs its own /tests script and Harbor+ # uploads nothing, so only a script in its definition can count.+ bundled_test = definition.directory / paths.test_path_for(task_os).name+ if _path_is_link_or_reparse(bundled_test) or not bundled_test.is_file():return Falsecontinue- if step_test is None and paths.discovered_test_path_for(task_os) is None:+ if verifier_pass.step is not None and paths.discovered_step_test_path_for(verifier_pass.step.name, task_os):+ continue+ if paths.discovered_test_path_for(task_os) is None:return Falsereturn True+def _native_dedicated_verifier_scopes(task_dir: Path) -> list[str]:+ """Return verify passes whose dedicated image never receives uploaded tests."""+ config = _validated_native_task_model(+ task_dir,+ tomllib.loads((task_dir / "task.toml").read_text(encoding="utf-8")),+ )+ paths, steps = _validated_native_task_steps(task_dir, config)+ return [+ verifier_pass.scope+ for verifier_pass in _native_verifier_passes(task_dir, config, paths, steps)+ if verifier_pass.definition is not None and verifier_pass.definition.bundled_tests+ ]++def _reject_native_windows_execution(task_toml: Path,config: Any,- effective_verifiers: list[tuple[str, Any | None]],+ verifier_passes: list[_NativeVerifierPass],) -> None:from harbor.models.task.config import TaskOS@@ -4951,11 +5014,12 @@ def _reject_native_windows_execution("Native Harbor agent environments using Windows are unsupported until "f"SkillEvaluator's task projection and verifier scripts are OS-aware: {task_toml}")- for scope, verifier_environment in effective_verifiers:- if verifier_environment is not None and verifier_environment.os == TaskOS.WINDOWS:+ for verifier_pass in verifier_passes:+ definition = verifier_pass.definition+ if definition is not None and definition.config.os == TaskOS.WINDOWS:raise ValueError(- f"Native Harbor effective verifier for {scope} uses Windows, which is unsupported until "- f"SkillEvaluator's verifier projection is OS-aware: {task_toml}"+ f"Native Harbor effective verifier for {verifier_pass.scope} uses Windows, which is unsupported "+ f"until SkillEvaluator's verifier projection is OS-aware: {task_toml}")@@ -5015,7 +5079,7 @@ def _reject_native_standard_grading_overrides(config: Any,paths: Any,steps: list[Any],- effective_verifiers: list[tuple[str, Any | None]],+ verifier_passes: list[_NativeVerifierPass],allowed_verifier_env: set[str],) -> None:if grading_mode not in {"default", "default_plus_custom"}:@@ -5051,11 +5115,11 @@ def _reject_native_standard_grading_overrides("Native Harbor step tests overlay is incompatible with SkillEvaluator standard grading; "f"keep {step_tests} empty or use grading.mode=custom_only")- for scope, verifier_environment in effective_verifiers:- if verifier_environment is not None:+ for verifier_pass in verifier_passes:+ if verifier_pass.definition is not None:raise ValueError("Native Harbor separate verifier context is unsupported with SkillEvaluator standard grading; "- f"use a shared verifier for {scope} or grading.mode=custom_only: {task_toml}"+ f"use a shared verifier for {verifier_pass.scope} or grading.mode=custom_only: {task_toml}")@@ -5067,12 +5131,12 @@ def _validate_native_task_execution_compatibility(grading_mode: str,allowed_verifier_env: set[str],) -> None:- """Fail closed where Harbor 0.22 execution can bypass evaluator projections."""+ """Fail closed where Harbor execution can bypass evaluator projections."""task_toml = task_dir / "task.toml"config = _validated_native_task_model(task_dir, data)paths, steps = _validated_native_task_steps(task_dir, config)- effective_verifiers = _effective_native_verifiers(config, steps)- _reject_native_windows_execution(task_toml, config, effective_verifiers)+ verifier_passes = _native_verifier_passes(task_dir, config, paths, steps)+ _reject_native_windows_execution(task_toml, config, verifier_passes)if not with_skill:_reject_native_baseline_setup(task_toml, config, paths, steps)_reject_native_standard_grading_overrides(@@ -5081,7 +5145,7 @@ def _validate_native_task_execution_compatibility(config,paths,steps,- effective_verifiers,+ verifier_passes,allowed_verifier_env,)@@ -5183,46 +5247,6 @@ def _ensure_native_skills_dir(task_dir: Path) -> None:_mutate_native_task_toml(task_dir / "task.toml", update)-def _merge_toml_env_table_section(- lines: list[str],- header_idx: int,- rendered: dict[str, str],- *,- prepend_missing: bool = False,-) -> None:- """Replace colliding keys in-place inside a TOML env table section and add missing keys."""- idx = header_idx + 1- env_end = next(- (end_idx for end_idx in range(idx, len(lines)) if _toml_table_header(lines[end_idx]) is not None),- len(lines),- )- seen_keys: set[str] = set()- updated_section: list[str] = []- for line in lines[idx:env_end]:- stripped_line = line.strip()- assignment = (- line.split("=", 1)[0].strip() if stripped_line and not stripped_line.startswith("#") and "=" in line else ""- )- matching_key = next(- (key for key in rendered if assignment in {key, _toml_quote(key), f"'{key}'"}),- None,- )- if matching_key is not None:- if matching_key in seen_keys:- continue- updated_section.append(rendered[matching_key])- seen_keys.add(matching_key)- else:- updated_section.append(line)- missing_lines = [line for key, line in rendered.items() if key not in seen_keys]- if missing_lines:- if prepend_missing:- updated_section[0:0] = missing_lines- else:- updated_section.extend(missing_lines)- lines[idx:env_end] = updated_section--def _ensure_skill_evaluator_verifier_env(task_dir: Path, *, verifier_env: dict[str, str] | None) -> None:"""Ensure staged native tasks forward configured public provider variables."""env_names = _verifier_env_vars(verifier_env)@@ -5235,7 +5259,7 @@ def _ensure_skill_evaluator_verifier_env(task_dir: Path, *, verifier_env: dict[sif not isinstance(verifier, dict):raise TypeError("verifier is not a table")if verifier_missing:- verifier["timeout_sec"] = 180.0+ verifier["timeout_sec"] = DEFAULT_LLM_VERIFIER_TIMEOUT_SECenvironment = verifier.setdefault("env", {})if not isinstance(environment, dict):raise TypeError("verifier.env is not a table")@@ -5462,6 +5486,7 @@ def _stage_native_harbor_tasks_into(runtime_env=runtime_env,verifier_env=verifier_env,)+ validate_case_ids(_native_entry_id(path) for path in source_task_dirs)_ = task_resources_ = agent_workdir@@ -5492,6 +5517,7 @@ def _stage_native_harbor_tasks_into(baseline_aliases_prevalidated = Truefor task_dir in task_dirs:entry_id = _native_entry_id(task_dir)+ _append_native_task_name_suffix(task_dir, arm_suffix, entry_id=entry_id)native_agent_workdir = _native_task_workdir(task_dir,with_skill=with_skill,@@ -5547,6 +5573,12 @@ def _stage_native_harbor_tasks_into()_write_test_sh(task_dir, grading_mode=grading_mode, custom_grader=custom_grader)elif custom_grader:+ if dedicated_scopes := _native_dedicated_verifier_scopes(task_dir):+ raise ValueError(+ f"custom_only native Harbor task '{entry_id}' uses a dedicated verifier image for "+ f"{', '.join(dedicated_scopes)}, which never receives SkillEvaluator's grader payload; "+ "bundle the grader in that image or remove the verifier image definition"+ )_write_entry_json(task_dir,entry or {"id": entry_id},diff --git a/src/skillevaluator/tier3/harbor/collector.py b/src/skillevaluator/tier3/harbor/collector.pyindex c1e57976..149c3cc7 100644--- a/src/skillevaluator/tier3/harbor/collector.py+++ b/src/skillevaluator/tier3/harbor/collector.py@@ -20,16 +20,16 @@ import shutilimport statimport sysimport unicodedata+from collections.abc import Iterable, Mappingfrom dataclasses import dataclassfrom dataclasses import field as dataclass_fieldfrom fractions import Fractionfrom pathlib import Path, PurePosixPath, PureWindowsPathfrom typing import Any-from harbor.models.trajectories import Trajectory-from skillevaluator.tier3.eval_core.atif_helpers import extract_tool_calls_as_dicts, get_skill_tool_callsfrom skillevaluator.tier3.eval_core.checks import check_negative_case+from skillevaluator.tier3.eval_core.codex_tool_call_normalizer import atif_content_textfrom skillevaluator.tier3.harbor.metrics import (CUSTOM_ONLY_METRIC_SET,DEFAULT_METRIC_SET,@@ -53,6 +53,7 @@ from skillevaluator.tier3.harbor.metrics import (score_value,)from skillevaluator.tier3.output_provenance import write_output_file_atomically+from skillevaluator.tier3.toml_utils import extract_toml_metadata_entry_idfrom skillevaluator.utils.redaction import contains_credential_value, redact_sensitive_data, redact_sensitive_textfrom skillevaluator.utils.secure_fs import SecurePathError, SecureRoot, stat_is_link_or_reparse@@ -96,6 +97,14 @@ UNSAFE_CUSTOM_METRIC_UNION_REASON = (MISSING_MULTI_STEP_REWARD_REASON = ("Authoritative multi-step verifier reward is missing; it was not reconstructed or scored")+MAX_STAGED_TASK_TOMLS = 512+# Identity controls the collector derives itself; grader-authored rewards cannot set them.+_COLLECTOR_IDENTITY_KEYS = (+ "_arm_suffix",+ "_authoritative_entry_id",+ "_result_entry_id",+ "_trusted_case_identity_unresolved",+)TRIAL_DIAGNOSTIC_ARTIFACTS = ("result.json", "config.json", "exception.txt", "trial.log")AGENT_LOG_ARTIFACTS = ("trajectory.json",@@ -316,19 +325,47 @@ def _identity_text_is_publishable(value: object) -> bool:return len(encoded) <= REWARD_IDENTITY_TEXT_MAX_BYTES and not contains_credential_value(value)-def _published_trial_label(value: object, *, alias_ordinal: int | None = None) -> str:- """Return a bounded value-only label; unsafe identities never become keys or paths."""+def _direct_published_trial_label(value: object) -> str | None:+ """Return a safe trial label verbatim, or ``None`` when it needs an alias."""if isinstance(value, str) and value and value.isprintable() and not contains_credential_value(value):try:if len(value.encode("utf-8")) <= REWARD_IDENTITY_TEXT_MAX_BYTES:return valueexcept UnicodeError:pass+ return None+++def _published_trial_label(value: object, *, alias_ordinal: int | None = None) -> str:+ """Return a bounded value-only label; unsafe identities never become keys or paths."""+ if direct_label := _direct_published_trial_label(value):+ return direct_labelif alias_ordinal is not None:return f"redacted-or-invalid-trial-{alias_ordinal:06d}"return "redacted-or-invalid-trial"+def _published_trial_labels_by_root(trial_root_names: list[str]) -> dict[str, str]:+ """Assign one stable, distinct published identity to each physical trial root."""+ unique_roots = set(trial_root_names)+ labels = {+ trial_root_name: direct_label+ for trial_root_name in unique_roots+ if (direct_label := _direct_published_trial_label(trial_root_name)) is not None+ }+ used_labels = set(labels.values())+ alias_ordinal = 1+ for trial_root_name in sorted(unique_roots - labels.keys()):+ while True:+ alias = _published_trial_label(trial_root_name, alias_ordinal=alias_ordinal)+ alias_ordinal += 1+ if alias not in used_labels:+ break+ labels[trial_root_name] = alias+ used_labels.add(alias)+ return labels++def _validated_expected_case_ids(expected_case_ids: list[str] | None) -> list[str]:"""Validate caller-owned case identities before generated outputs are reset."""validated: list[str] = []@@ -629,7 +666,10 @@ def validate_harbor_job_result(rewarded_trial_names.update(metric_trial_names)if eval_trials != total:- return False, f"Harbor evaluation statistics account for {eval_trials}/{total} completed trials"+ detail = f"Harbor evaluation statistics account for {eval_trials}/{total} completed trials"+ if recorded := _first_recorded_trial_exception(result_path.parent):+ detail = f"{detail}; {recorded}"+ return False, detailif eval_errors != 0:return False, f"Harbor evaluation statistics contain {eval_errors} errored trials"if not rewarded_trial_names:@@ -694,7 +734,7 @@ def _trajectory_agent_runtime_failure_reason(trajectory: Any) -> str:for step in steps:if not isinstance(step, dict):continue- message = str(step.get("message") or "")+ message = atif_content_text(step.get("message"))reason = _text_contains_agent_runtime_failure(message)if reason and tokenless:return reason@@ -737,6 +777,31 @@ def _trial_step_exception_details(trial_dir: Path) -> list[tuple[str, str]]:]+def _first_recorded_trial_exception(job_dir: Path) -> str:+ """Name the first trial or step exception Harbor recorded under a failed job.++ Harbor 0.24 records a multi-step failure, such as a verifier ``reward.json``+ it cannot parse, on the failing step rather than on the trial, and still+ counts the trial as completed. Without this, a job reports only a trial count.+ """+ try:+ entries = sorted(job_dir.iterdir())+ except OSError:+ return ""+ for ordinal, trial_dir in enumerate(entries, start=1):+ kind, _unsafe_reason = _inspect_trial_directory(trial_dir)+ if kind != "directory":+ continue+ for _exception_type, reason in (+ _trial_exception_details(trial_dir),+ *_trial_step_exception_details(trial_dir),+ ):+ if reason:+ label = _published_trial_label(trial_dir.name, alias_ordinal=ordinal)+ return redact_sensitive_text(f"trial {label} recorded {reason}")[:600]+ return ""++def _agent_log_runtime_failure_reason(trial_dir: Path,*,@@ -783,7 +848,11 @@ def _agent_runtime_failure_reason(trial_dir: Path) -> str:]agent_reason = _agent_log_runtime_failure_reason(trial_dir,- include_text_logs=any(reason for _exception_type, reason in exception_details),+ include_text_logs=any(+ exception_type in _AGENT_RUNTIME_EXCEPTION_TYPES+ or exception_type in _UNCONDITIONAL_AGENT_RUNTIME_EXCEPTION_TYPES+ for exception_type, _exception_reason in exception_details+ ),)if agent_reason:return agent_reason@@ -1760,6 +1829,21 @@ def _validate_generated_json_value(raise ValueError("encoded JSON exceeds limit")+_ATIF_SCHEMA_VERSION_RE = re.compile(r"ATIF-v(?P<major>\d+)\.(?P<minor>\d+)")+# Merged trajectories emit v1.7 fields such as trajectory_id and subagent refs.+_MERGED_ATIF_SCHEMA_FLOOR = (1, 7)+++def _merged_atif_schema_version(*trajectories: Mapping[str, Any]) -> str:+ """Label a merged trajectory with the newest source ATIF version, never below v1.7."""+ newest = _MERGED_ATIF_SCHEMA_FLOOR+ for trajectory in trajectories:+ match = _ATIF_SCHEMA_VERSION_RE.fullmatch(str(trajectory.get("schema_version") or ""))+ if match:+ newest = max(newest, (int(match["major"]), int(match["minor"])))+ return f"ATIF-v{newest[0]}.{newest[1]}"++def _validated_trajectory_dict(data: Any) -> dict[str, Any]:try:# Bound traversal before deepcopy so hostile ATIF cannot amplify work@@ -1858,6 +1942,8 @@ def _validated_trajectory_dict(data: Any) -> dict[str, Any]:max_nodes=ATIF_JSON_MAX_NODES,max_bytes=GENERATED_JSON_MAX_BYTES,)+ from harbor.models.trajectories import Trajectory+validated = Trajectory.model_validate(candidate).to_json_dict()_validate_generated_json_value(validated,@@ -2190,7 +2276,7 @@ def _combine_continuation_trajectories(appended_steps = continuation_stepscombined = copy.deepcopy(scoped_base)- combined["schema_version"] = "ATIF-v1.7"+ combined["schema_version"] = _merged_atif_schema_version(base, continuation)combined["agent"] = copy.deepcopy(scoped_continuation["agent"])combined["steps"] = [copy.deepcopy(step) for step in (*base_steps, *appended_steps)]for index, step in enumerate(combined["steps"], start=1):@@ -2746,7 +2832,7 @@ def _merged_step_trajectory(trial_root: Path) -> dict[str, Any] | None:json.dumps(source_identity, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("utf-8")).hexdigest()[:20]merged: dict[str, Any] = {- "schema_version": "ATIF-v1.7",+ "schema_version": _merged_atif_schema_version(*(trajectory for _, trajectory in trajectories)),"session_id": f"skillevaluator-multistep-{digest}","trajectory_id": f"skillevaluator-multistep-{digest}","agent": copy.deepcopy(trajectories[-1][1]["agent"]),@@ -3256,9 +3342,84 @@ def _merge_constituent_default_reward_failure()+def _staged_task_entry_id_map(+ output_dir: Path | None,+ agent: str = "",+ variant: str = "",+ *,+ arm_suffix: str = "",+ max_tasks: int = MAX_STAGED_TASK_TOMLS,+) -> dict[str, str]:+ """Build an unambiguous mapping from staged task directory or task.name to [metadata].entry_id."""+ if output_dir is None:+ return {}+ tasks_root = output_dir / "_harbor-tasks"+ if not tasks_root.is_dir() or tasks_root.is_symlink():+ return {}++ search_roots: list[Path] = []+ if agent and variant:+ candidate = tasks_root / agent / variant+ if candidate.is_dir() and not candidate.is_symlink():+ search_roots.append(candidate)+ if not search_roots:+ search_roots.append(tasks_root)++ mapping: dict[str, str] = {}+ ambiguous: set[str] = set()++ def _bind(key: str, entry_id: str) -> None:+ if not key or key in ambiguous:+ return+ existing = mapping.get(key)+ if existing is not None and existing != entry_id:+ del mapping[key]+ ambiguous.add(key)+ else:+ mapping[key] = entry_id++ for root in search_roots:+ try:+ task_tomls = sorted(root.rglob("task.toml"))+ except OSError:+ continue+ for task_toml in task_tomls[:max_tasks]:+ if task_toml.is_symlink() or not task_toml.is_file():+ continue+ raw_toml = _read_bounded_text(task_toml)+ if raw_toml is None:+ continue+ try:+ import tomllib++ parsed = tomllib.loads(raw_toml)+ except Exception:+ continue+ if not isinstance(parsed, dict):+ continue+ raw_entry_id = extract_toml_metadata_entry_id(parsed)+ entry_id = str(raw_entry_id).strip() if raw_entry_id is not None else ""+ if not entry_id:+ entry_id = task_toml.parent.name+ _bind(task_toml.parent.name, entry_id)+ task_table = parsed.get("task")+ if isinstance(task_table, dict) and isinstance(task_table.get("name"), str):+ task_name = task_table["name"].strip()+ if task_name:+ _bind(task_name, entry_id)+ short_name = task_name.rsplit("/", 1)[-1]+ _bind(short_name, entry_id)+ if arm_suffix and short_name.endswith(arm_suffix):+ _bind(short_name.removesuffix(arm_suffix), entry_id)+ return mapping++def _extract_rewards(job_dir: Path,case_id_by_task_selector: dict[str, str] | None = None,+ *,+ arm_suffix: str = "",+ task_entry_id_map: Mapping[str, str] | None = None,) -> list[dict[str, Any]]:"""Extract reward.json from all trials in a job directory."""rewards: list[dict[str, Any]] = []@@ -3306,6 +3467,17 @@ def _extract_rewards(else:reward_data["_result_entry_id"] = entry_id+ def _assign_case_identity(data: dict[str, Any], result: dict[str, Any], trial_name: str) -> None:+ for key in _COLLECTOR_IDENTITY_KEYS:+ data.pop(key, None)+ if case_id_by_task_selector is None:+ # Direct callers and older artifacts have no runner-owned selector map;+ # resolve them from Harbor's persisted task path or the staged tasks.+ if arm_suffix:+ data["_arm_suffix"] = arm_suffix+ _populate_reward_entry_id(data, result or None, trial_name)+ _apply_harbor_result_case_identity(data, result, case_id_by_task_selector)+# Native multi-step Harbor tasks can persist an authoritative aggregate at# the trial root in addition to one reward file per step. Materialize that# single logical row first so both averages and pass@k use the same score.@@ -3328,7 +3500,7 @@ def _extract_rewards(data["_trial_name"] = trial_namedata["_trial_root_name"] = trial_dir.namedata["_started_at"] = result.get("started_at")- _apply_harbor_result_case_identity(data, result, case_id_by_task_selector)+ _assign_case_identity(data, result, trial_name)traj_file = _reward_trajectory_path(trial_dir, None)if traj_file.exists():data["_has_trajectory"] = True@@ -3358,8 +3530,6 @@ def _extract_rewards(continuedata["_trial_name"] = trial_namedata["_trial_root_name"] = trial_dir.name- if arm_suffix:- data["_arm_suffix"] = arm_suffixif step_name:data["_step_name"] = step_nameresult_file = trial_dir / "result.json"@@ -3370,7 +3540,7 @@ def _extract_rewards(result = loaded_result_merge_constituent_default_reward_failure(data, result, trial_dir)data["_started_at"] = result.get("started_at")- _apply_harbor_result_case_identity(data, result, case_id_by_task_selector)+ _assign_case_identity(data, result, trial_name)traj_file = _reward_trajectory_path(trial_dir, step_name)if traj_file.exists():data["_has_trajectory"] = True@@ -3417,7 +3587,7 @@ def _extract_rewards(data["_trial_root_name"] = trial_dir.namedata["_step_name"] = step_namedata["_started_at"] = result.get("started_at")- _apply_harbor_result_case_identity(data, result, case_id_by_task_selector)+ _assign_case_identity(data, result, trial_name)traj_file = _reward_trajectory_path(trial_dir, step_name)if traj_file.exists():data["_has_trajectory"] = True@@ -3432,7 +3602,7 @@ def _extract_rewards(data["_trial_name"] = trial_namedata["_trial_root_name"] = trial_dir.namedata["_started_at"] = result.get("started_at")- _apply_harbor_result_case_identity(data, result, case_id_by_task_selector)+ _assign_case_identity(data, result, trial_name)traj_file = _reward_trajectory_path(trial_dir, None)if traj_file.exists():data["_has_trajectory"] = True@@ -3741,28 +3911,52 @@ def _task_selector_from_harbor_result(result: dict[str, Any]) -> str:return Path(task_paths[0]).name-def _entry_id_from_harbor_result(+def _result_task_path_entry_id(task_path_value: Any) -> tuple[str, str]:+ """Return (metadata_entry_id, dir_name) from a Harbor task path when available."""+ if not isinstance(task_path_value, str) or not task_path_value.strip():+ return "", ""+ task_dir = Path(task_path_value.strip())+ task_toml = task_dir / "task.toml"+ if not task_toml.is_symlink() and task_toml.is_file():+ raw_toml = _read_bounded_text(task_toml)+ if raw_toml is not None:+ try:+ import tomllib++ parsed = tomllib.loads(raw_toml)+ raw_entry_id = extract_toml_metadata_entry_id(parsed)+ if raw_entry_id is not None:+ entry_id = str(raw_entry_id).strip()+ if entry_id:+ return entry_id, task_dir.name+ except Exception:+ pass+ return "", task_dir.name+++def _resolve_harbor_result_entry_id(result: dict[str, Any],- case_id_by_task_selector: dict[str, str] | None = None,-) -> str:- if case_id_by_task_selector is None:- # Preserve the legacy collector contract for direct callers and older- # artifacts: Harbor's task_name is the logical/display identity they- # supplied. New runner paths pass an explicit trusted selector map and- # never use this authored field as logical truth.- task_name = result.get("task_name")- if isinstance(task_name, str) and task_name.strip():- return task_name.strip().rsplit("/", 1)[-1]-- selector = _task_selector_from_harbor_result(result)- if selector:- return case_id_by_task_selector.get(selector, "") if case_id_by_task_selector is not None else selector-- # A trusted mapping deliberately keeps authored ``[task].name`` separate- # from logical identity. Harbor 0.22 normally persists ``task_id.path``;- # if it is absent, fail coverage instead of guessing from a display name.- if case_id_by_task_selector is not None:- return ""+ *,+ arm_suffix: str = "",+ task_entry_id_map: Mapping[str, str] | None = None,+) -> tuple[str, bool]:+ """Resolve (entry_id, is_authoritative) from a Harbor result.json payload."""+ fallback_dir_name = ""+ task_id = result.get("task_id")+ if isinstance(task_id, dict):+ meta_id, dir_name = _result_task_path_entry_id(task_id.get("path"))+ if meta_id:+ return meta_id, True+ fallback_dir_name = dir_name or fallback_dir_name++ config = result.get("config")+ if isinstance(config, dict):+ task = config.get("task")+ if isinstance(task, dict):+ meta_id, dir_name = _result_task_path_entry_id(task.get("path"))+ if meta_id:+ return meta_id, True+ fallback_dir_name = dir_name or fallback_dir_nameif fallback_dir_name and task_entry_id_map and fallback_dir_name in task_entry_id_map:return task_entry_id_map[fallback_dir_name], True@@ -3801,11 +3995,19 @@ def _entry_id_from_harbor_result(def _entry_id_from_harbor_result(result: dict[str, Any],+ case_id_by_task_selector: dict[str, str] | None = None,*,arm_suffix: str = "",task_entry_id_map: Mapping[str, str] | None = None,) -> str:- """Resolve the best-effort case ID from a Harbor trial result payload."""+ """Resolve a trial's case ID from Harbor's persisted result payload."""+ if case_id_by_task_selector is not None:+ # A trusted mapping deliberately keeps authored ``[task].name`` separate+ # from logical identity. Harbor normally persists ``task_id.path``; if it+ # is absent or inconsistent, fail coverage instead of guessing from a+ # display name.+ selector = _task_selector_from_harbor_result(result)+ return case_id_by_task_selector.get(selector, "") if selector else ""entry_id, is_authoritative = _resolve_harbor_result_entry_id(result,arm_suffix=arm_suffix,@@ -3881,6 +4083,7 @@ def _apply_harbor_result_case_identity(if case_id_by_task_selector is not None:if entry_id:data["entry_id"] = entry_id+ data["_authoritative_entry_id"] = Truedata.pop("_trusted_case_identity_unresolved", None)else:# A grader-authored identity is not authoritative. If Harbor's@@ -4120,7 +4323,26 @@ def _reward_identity_is_publishable(reward: dict[str, Any]) -> bool:return _identity_text_is_publishable(trial_name.split("__", 1)[0])-def _canonical_case_id(value: str, expected_case_ids: set[str] | None = None) -> str:+def _strip_arm_suffix(value: str) -> str:+ """Remove SkillEvaluator dual-arm suffixes (-with-skill, -without-skill) from an identifier."""+ return re.sub(r"-(?:with|without)-skill$", "", value)+++def _strip_arm_and_attempt_suffixes(value: str) -> str:+ """Remove at most one dual-arm suffix and one attempt suffix regardless of ordering."""+ attempt_stripped = _strip_attempt_suffix(value)+ if attempt_stripped != value:+ return _strip_arm_suffix(attempt_stripped)+ return _strip_attempt_suffix(_strip_arm_suffix(value))+++def _canonical_case_id(+ value: str,+ expected_case_ids: set[str] | None = None,+ *,+ strip_arm: bool = True,+) -> str:+ """Normalize a task, trial, or entry identifier to its canonical case ID."""if not _identity_text_is_publishable(value):return ""if expected_case_ids and value in expected_case_ids:@@ -4163,11 +4385,29 @@ def _normalize_expected_case_id_set(def _entry_id(reward: dict[str, Any], expected_case_ids: set[str] | None = None) -> str:+ """Resolve the canonical case ID for a collected reward dictionary."""if reward.get("_trusted_case_identity_unresolved") is True:return "unknown"- if isinstance(reward.get("entry_id"), str) and reward["entry_id"]:- return _canonical_case_id(reward["entry_id"], expected_case_ids)- trial_name = reward.get("_trial_name")+ entry_id = reward.get("entry_id")+ if isinstance(entry_id, str) and entry_id:+ raw_entry_id = entry_id.strip()+ if reward.get("_authoritative_entry_id"):+ return raw_entry_id+ if not reward.get("_result_entry_id"):+ if expected_case_ids:+ if raw_entry_id in expected_case_ids:+ return raw_entry_id+ stripped_attempt = _strip_attempt_suffix(raw_entry_id)+ if stripped_attempt in expected_case_ids:+ return stripped_attempt+ else:+ return _strip_attempt_suffix(raw_entry_id)+ return _canonical_case_id(+ raw_entry_id,+ expected_case_ids,+ strip_arm=not bool(reward.get("_arm_suffix")),+ )+ trial_name = str(reward.get("_trial_name") or "")if trial_name:trial_prefix = trial_name.split("__", 1)[0]arm_suffix = str(reward.get("_arm_suffix") or "")@@ -4249,6 +4489,9 @@ def _logical_attempt_rewards(rewards: list[dict[str, Any]]) -> list[dict[str, An}if first.get("_trusted_task_selector") is not None:logical_reward["_trusted_task_selector"] = first["_trusted_task_selector"]+ for key in _COLLECTOR_IDENTITY_KEYS:+ if key in first:+ logical_reward[key] = first[key]if (attempt_ordinal := _attempt_ordinal(first)) is not None:logical_reward["_attempt_ordinal"] = attempt_ordinalif metric_set:@@ -5433,8 +5676,12 @@ def _save_trials(agent = _bounded_reward_metadata_text(agent) or "unknown"agent_model = _bounded_reward_metadata_text(agent_model)agent_model_source = _bounded_reward_metadata_text(agent_model_source)+ expected_id_set = _normalize_expected_case_id_set(expected_case_ids)trials_dir.mkdir(parents=True, exist_ok=True)persisted_names, unscored_names = _persisted_trial_layout(rewards, job_dir)+ published_trial_ids = _published_trial_labels_by_root(+ [trial_root_name for _trial_name, trial_root_name in persisted_names]+ )for reward, (trial_name, trial_root_name) in zip(rewards, persisted_names, strict=True):trial_out = trials_dir / trial_nametrial_out.mkdir(parents=True, exist_ok=True)@@ -5480,9 +5727,9 @@ def _save_trials(# fallback multi-step rows for diagnostics without weighting a logical# Harbor trial once per step. This also populates the canonical report's# existing trial_id field instead of inventing a second report schema.- clean_reward["trial_id"] = _published_trial_label(trial_root_name)- if not clean_reward.get("entry_id"):- clean_reward["entry_id"] = _entry_id(reward)+ clean_reward["trial_id"] = published_trial_ids[trial_root_name]+ if not clean_reward.get("entry_id") or reward.get("_result_entry_id"):+ clean_reward["entry_id"] = _entry_id(reward, expected_id_set)clean_reward["agent"] = agentif agent_model:clean_reward["model"] = agent_model@@ -5897,8 +6144,22 @@ def collect_harbor_results(with_runtime_failures = _extract_agent_runtime_failures(with_job_dir)with_trial_failures = _extract_trial_failures(with_job_dir)preserve_partial = _can_preserve_partial_rewards(with_job_dir, with_trial_failures)+ # Runner-owned selector maps are authoritative; staged task files only+ # resolve identities for direct callers that do not supply one.+ with_task_entry_ids = (+ _staged_task_entry_id_map(output_dir, agent, "with", arm_suffix=with_arm_suffix)+ if case_id_by_task_selector is None+ else None+ )with_collected_rewards = (- _extract_rewards(with_job_dir, case_id_by_task_selector) if with_job_ok or preserve_partial else []+ _extract_rewards(+ with_job_dir,+ case_id_by_task_selector,+ arm_suffix=with_arm_suffix,+ task_entry_id_map=with_task_entry_ids,+ )+ if with_job_ok or preserve_partial+ else [])with_rewards, invalid_score_failures = _partition_scoreable_rewards(with_collected_rewards)with_logical_rewards = _logical_attempt_rewards(with_rewards)@@ -6069,14 +6330,18 @@ def collect_harbor_results(without_runtime_failures = _extract_agent_runtime_failures(without_job_dir)without_trial_failures = _extract_trial_failures(without_job_dir)preserve_partial = _can_preserve_partial_rewards(without_job_dir, without_trial_failures)- without_task_entry_ids = _staged_task_entry_id_map(- output_dir,- agent,- "without",- arm_suffix="-without-skill",+ without_task_entry_ids = (+ _staged_task_entry_id_map(output_dir, agent, "without", arm_suffix="-without-skill")+ if case_id_by_task_selector is None+ else None)without_collected_rewards = (- _extract_rewards(without_job_dir, case_id_by_task_selector)+ _extract_rewards(+ without_job_dir,+ case_id_by_task_selector,+ arm_suffix="-without-skill",+ task_entry_id_map=without_task_entry_ids,+ )if without_job_ok or preserve_partialelse [])diff --git a/src/skillevaluator/tier3/harbor/local_agents.py b/src/skillevaluator/tier3/harbor/local_agents.pyindex a4b9ba24..65a1796a 100644--- a/src/skillevaluator/tier3/harbor/local_agents.py+++ b/src/skillevaluator/tier3/harbor/local_agents.py@@ -276,7 +276,8 @@ class SkillEvaluatorLocalOpenCode(OpenCode):cmd_list = [server.command, *server.args] if server.command else []mcp[server.name] = {"type": "local", "command": cmd_list}else:- mcp[server.name] = {"type": "remote", "url": server.url}+ # Match Harbor's OpenCode config: headless trials cannot complete OAuth.+ mcp[server.name] = {"type": "remote", "url": server.url, "oauth": False}config["mcp"] = mcpconfig["provider"] = {diff --git a/src/skillevaluator/tier3/harbor/progress.py b/src/skillevaluator/tier3/harbor/progress.pyindex 95e3fcc0..8597126a 100644--- a/src/skillevaluator/tier3/harbor/progress.py+++ b/src/skillevaluator/tier3/harbor/progress.py@@ -21,6 +21,7 @@ from typing import Literal, Protocol, TextIO, runtime_checkablefrom skillevaluator.tier3.harbor.secret_redaction import redact_secrets_in_log_linefrom skillevaluator.utils.redaction import credential_uri_secret_values+from skillevaluator.utils.rich_markup import strip_terminal_controlsProgressMode = Literal["auto", "rich", "plain", "off"]logger = logging.getLogger(__name__)@@ -33,10 +34,10 @@ _SECRET_ASSIGNMENT_RE = re.compile(r"(?:\"[^\"]*\"|'[^']*'|[^\s,;]+)")_SECRET_ENV_NAME_RE = re.compile(r"(?i)(?:api[_-]?key|access[_-]?key|auth|credential|password|secret|token)")+# Whole environment values shorter than this are never treated as exact secrets;+# shorter credential fragments come only from URI userinfo.+MIN_EXACT_SECRET_CHARS = 4_CREDENTIAL_URI_USERINFO_RE = re.compile(r"(?i)(?P<scheme>[a-z][a-z0-9+.-]{0,31}://)(?P<userinfo>[^\s/?#]+@)")-_ANSI_ESCAPE_RE = re.compile(r"\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")-_OSC_ESCAPE_RE = re.compile(r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)")-_TERMINAL_CONTROL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]")@dataclass(frozen=True, slots=True)@@ -101,14 +102,11 @@ class ProgressReporter(Protocol):def redact_progress_detail(detail: object, *, secret_values: set[str] | None = None) -> str:"""Return a single-line diagnostic safe enough for a progress surface."""- text = _OSC_ESCAPE_RE.sub("", str(detail))- text = _ANSI_ESCAPE_RE.sub("", text)- text = _TERMINAL_CONTROL_RE.sub("", text)- text = " ".join(text.split())+ text = " ".join(strip_terminal_controls(str(detail)).split())if "://" in text:text = _CREDENTIAL_URI_USERINFO_RE.sub(r"\g<scheme><redacted>@", text)for secret in sorted(secret_values or (), key=len, reverse=True):- if len(secret) >= 4:+ if len(secret) >= MIN_EXACT_SECRET_CHARS:text = text.replace(secret, "<redacted>")elif secret:# Exact credential-derived fragments can legitimately be short@@ -130,7 +128,9 @@ def secret_values_from_environment(environment: Mapping[str, str]) -> set[str]:if not value:continuerendered = str(value)- if _SECRET_ENV_NAME_RE.search(name):+ # Short values of credential-named variables are flags such as "1" or+ # "true", not credentials; redacting them would erase counts in prose.+ if _SECRET_ENV_NAME_RE.search(name) and len(rendered) >= MIN_EXACT_SECRET_CHARS:protected.add(rendered)if name.upper().endswith("_PROXY") or "://" in rendered:protected.update(diff --git a/src/skillevaluator/tier3/harbor/report.py b/src/skillevaluator/tier3/harbor/report.pyindex 29fe2ed5..fdd30100 100644--- a/src/skillevaluator/tier3/harbor/report.py+++ b/src/skillevaluator/tier3/harbor/report.py@@ -28,10 +28,9 @@ from skillevaluator.tier3.harbor.metrics import (extract_custom_metrics,metric_set_for_reward,metric_value,- score_value,)from skillevaluator.tier3.output_provenance import write_output_file_atomically-from skillevaluator.utils.redaction import redact_sensitive_data+from skillevaluator.utils.redaction import redact_sensitive_data, redact_sensitive_textlogger = logging.getLogger(__name__)@@ -44,6 +43,7 @@ _MAX_FINDING_TEXT_CHARS = 2048_EVIDENCE_REF_TEXT_LIMITS = {"source": 256,"json_pointer": 512,+ "evidence_id": 512,"kind": 64,"path": 512,"label": 256,@@ -69,6 +69,8 @@ def _bounded_json_text(value: Any, *, max_encoded_bytes: int) -> str:return text[:low] + suffix if low else suffix[:max_encoded_bytes]+_REPORT_REASON_LIMIT = 512+_METRIC_LABELS = {"security": "SECURITY (unsafe operations, secret leakage, unauthorized access)","skill_execution": "SKILL EXECUTION (activation, script run, workflow order, error recovery)",@@ -121,29 +123,29 @@ def _pick_best_agent(agents_data: dict[str, dict[str, Any]],persisted_agents: dict[str, dict[str, Any]] | None = None,) -> str:- """Select the agent with the highest overall with-skill score."""+ """Select the same best agent identity as the canonical Tier 3 report."""+ from skillevaluator.evaluation.tier3_report import _canonical_agent_rank_from_info+best_agent = ""- best_score = -1.0- for agent, data in agents_data.items():+ best_rank: tuple[float, float] | None = None+ for agent in sorted(agents_data):+ data = agents_data[agent]if not _findings_eligible(data):continuepersisted = persisted_agents.get(agent) if isinstance(persisted_agents, dict) else None- overall = score_value(persisted.get("overall_with_skill")) if isinstance(persisted, dict) else None- if overall is not None:- if overall > best_score:- best_score = overall- best_agent = agent- continue- with_scores = data.get("with_skill", {})- if not isinstance(with_scores, dict) or not with_scores:+ ranking_data = persisted if isinstance(persisted, dict) else data+ standard_metrics = report_data.metrics_for_condition(ranking_data, "with_skill")+ with_scores = ranking_data.get("with_skill")+ if standard_metrics and (+ not isinstance(with_scores, dict)+ or any(metric_value(with_scores, metric) is None for metric in standard_metrics)+ ):continue- metrics = [m for m in DISPLAY_METRICS if m in with_scores] or list(DISPLAY_METRICS)- metric_scores = [score for metric in metrics if (score := metric_value(with_scores, metric)) is not None]- if len(metric_scores) != len(metrics):+ rank = _canonical_agent_rank_from_info(ranking_data)+ if rank is None:continue- overall = sum(metric_scores) / len(metric_scores)- if overall > best_score:- best_score = overall+ if best_rank is None or rank > best_rank:+ best_rank = rankbest_agent = agentreturn best_agent@@ -292,7 +294,7 @@ def _extract_findings(if not isinstance(raw_ref, dict | str):continuer = _resolve_evidence_ref(raw_ref, {})- k = tuple(str(r.get(field) or "") for field in ("source", "json_pointer", "kind", "path"))+ k = (r.get("source"), evidence_ref_identity(r), r.get("kind"))if k not in _seen:_seen.add(k)_refs.append(r)@@ -365,6 +367,8 @@ def _render_findings_body(findings: list[dict[str, Any]]) -> Any:def _bounded_report_reason(value: Any) -> str:"""Coerce legacy/custom artifact values into bounded display text."""+ if value is None:+ return ""if isinstance(value, str):text = value.strip()else:@@ -544,19 +548,15 @@ def _compact_evidence_ref(ref: dict[str, Any]) -> str:def _bounded_reason_text(value: Any, *, max_len: int = 512) -> str:- """Normalize scalar evaluator explanations without expanding malformed containers."""- if isinstance(value, str):- return value[:max_len]- if isinstance(value, int | float | bool):- return str(value)[:max_len]- return ""+ """Normalize, redact, and bound evaluator explanations."""+ return _bounded_report_reason(value)[:max_len]def _build_evidence_ref_lookup(rewards: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:"""Build a lookup from each stable compact evidence key to its full dict ref.- Iterates over all metrics in every reward's ``details`` dict, collecting- ``evidence_refs`` entries. The resulting mapping lets+ Iterates over every publishable metric and resolves its detail through the+ same standard/custom precedence used by findings. The resulting mapping lets``_generate_suggestions_structured`` resolve the compact string refs thatthe LLM returns into the richer dict form consumed by SkillEvaluator reporttemplates (which read ``ref.kind``, ``ref.json_pointer``, ``ref.path``,@@ -564,10 +564,8 @@ def _build_evidence_ref_lookup(rewards: list[dict[str, Any]]) -> dict[str, dict["""lookup: dict[str, dict[str, Any]] = {}for reward in rewards:- details = reward.get("details") or {}- if not isinstance(details, dict):- continue- for metric_detail in details.values():+ for metric in _finding_metric_names([reward]):+ metric_detail = _detail_for_finding(reward, metric)if not isinstance(metric_detail, dict):continuefor ref in metric_detail.get("evidence_refs") or []:diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.pyindex 0c40b544..c46d0f16 100644--- a/src/skillevaluator/tier3/harbor/runner.py+++ b/src/skillevaluator/tier3/harbor/runner.py@@ -25,7 +25,7 @@ import timeimport tomllibfrom collections.abc import Iterator, Mappingfrom concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, as_completed, wait-from contextlib import ExitStack, suppress+from contextlib import ExitStack, contextmanager, suppressfrom dataclasses import dataclass, fieldfrom datetime import UTC, datetimefrom functools import wraps@@ -46,6 +46,7 @@ from skillevaluator.provider_config import (_normalize_anthropic_base_url,resolve_llm_provider,)+from skillevaluator.source_identity import normalized_evaluated_sourcefrom skillevaluator.tier3.case_ids import validate_case_idsfrom skillevaluator.tier3.evals_config import (MAX_HARBOR_TIMEOUT_MULTIPLIER,@@ -57,8 +58,10 @@ from skillevaluator.tier3.evals_config import (from skillevaluator.tier3.harbor.adapter import (_RUNTIME_PROCESS_CONTROL_ENV_NAMES,_RUNTIME_PROCESS_CONTROL_ENV_PREFIXES,+ _VERIFIER_BUDGET_ENV_VARS,_VERIFIER_JUDGE_CONTROL_ENV_VARS,_VERIFIER_JUDGE_MODEL_ENV_VARS,+ _VERIFIER_RETRY_ENV_VARS,_native_entry_id,_prevalidate_baseline_skill_candidates,build_eval_base_image,@@ -78,6 +81,7 @@ from skillevaluator.tier3.harbor.collector import ()from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS, score_definitionfrom skillevaluator.tier3.harbor.progress import (+ MIN_EXACT_SECRET_CHARS,NullProgressReporter,ProgressEvent,ProgressReporter,@@ -118,8 +122,11 @@ from skillevaluator.tier3_environments import (DEFAULT_ENV_MODE,ENV_MODE_LOCAL,HARBOR_ENV_MODES,+ HARBOR_ENVIRONMENT_ALIAS_KWARGS,HARBOR_ENVIRONMENT_EXTRAS,- HARBOR_V022_ENVIRONMENT_KWARGS,+ HARBOR_ENVIRONMENT_KWARGS,+ HARBOR_VERSION,+ harbor_environment_type,)from skillevaluator.utils.redaction import is_sensitive_key, redact_sensitive_textfrom skillevaluator.utils.secure_fs import SecurePathError, SecureRoot@@ -576,8 +583,11 @@ def _persist_dataset_truth(run_dir: Path, *, fallback_task_ids: list[str]) -> di_NVIDIA_BUILD_FILE_SENTINEL = "skillevaluator-file-backed-nvidia-key"_NVIDIA_BUILD_KEY_FILE_ENV = "SKILLEVALUATOR_NVIDIA_API_KEY_FILE"-_NVIDIA_BUILD_BRIDGED_AGENT_DEFAULT_MODEL = "nvidia/nemotron-3-super-120b-a12b"-_HARBOR_RUN_TIMEOUT_SECONDS = 7200.0+_NVIDIA_BUILD_AGENT_DEFAULT_MODEL = CHAT_DEFAULT_NVIDIA+_GATEWAY_CODEX_IMPORT_PATH = "skillevaluator.tier3.harbor.local_agents:SkillEvaluatorGatewayCodex"+# The OpenAI-compatible gateway Codex wrapper only routes the stock agent to the+# operator's gateway, so it is the one custom agent allowed on Harbor-native backends.+_NATIVE_BACKEND_AGENT_IMPORT_PATHS = frozenset({_GATEWAY_CODEX_IMPORT_PATH})_HARBOR_RUN_OUTPUT_MAX_BYTES = MAX_COMMAND_OUTPUT_BYTES_HARBOR_RUN_DIAGNOSTIC_TAIL_CHARS = 16 * 1024_HARBOR_RUN_OUTPUT_READ_BYTES = 64 * 1024@@ -845,16 +855,6 @@ _HARBOR_ENV_MODE_VARS = {"use-computer": frozenset({"USE_COMPUTER_API_KEY", "USE_COMPUTER_HOST", "USE_COMPUTER_SNAPSHOT", "USE_COMPUTER_VERSION"}),- "cua-cloud": frozenset(- {- "CUA_BASE_URL",- "CUA_CLIENT_ID",- "CUA_CLIENT_SECRET",- "CUA_CLOUD_NAMESPACE",- "CUA_CLOUD_STARTUP_COMMAND",- "CUA_TOKEN_URL",- }- ),"blaxel": frozenset({"BL_API_KEY",@@ -865,7 +865,6 @@ _HARBOR_ENV_MODE_VARS = {"BL_WORKSPACE",}),- "opensandbox": frozenset({"OPENSANDBOX_API_KEY", "OPENSANDBOX_DOMAIN"}),"beam": frozenset({"API_HOST",@@ -888,7 +887,6 @@ _HARBOR_ENV_MODE_VARS = {"SKYPILOT_SERVICE_ACCOUNT_TOKEN",}),- "hf-sandbox": frozenset({"HF_ENDPOINT", "HF_HOME", "HF_TOKEN", "HF_TOKEN_PATH", "HUGGING_FACE_HUB_TOKEN"}),"hyperbrowser": _DOCKER_HOST_ENV_VARS | frozenset({"HYPERBROWSER_API_KEY", "HYPERBROWSER_BASE_URL"}),"vercel": frozenset({"VERCEL_OIDC_TOKEN", "VERCEL_PROJECT_ID", "VERCEL_TEAM_ID", "VERCEL_TOKEN"}),}@@ -900,10 +898,7 @@ _BEDROCK_HOST_ENV_VARS = _AWS_HOST_ENV_VARS | {"AWS_ENDPOINT_URL_BEDROCK_RUNTIME",}_RUNTIME_ENV_HOST_CONTROL_NAMES = (- _RUNTIME_PROCESS_CONTROL_ENV_NAMES- | _BEDROCK_HOST_ENV_VARS- | _VERIFIER_JUDGE_CONTROL_ENV_VARS- | frozenset().union(*_HARBOR_ENV_MODE_VARS.values())+ _RUNTIME_PROCESS_CONTROL_ENV_NAMES | _BEDROCK_HOST_ENV_VARS | _VERIFIER_JUDGE_CONTROL_ENV_VARS)_RUNTIME_ENV_HOST_CONTROL_PREFIXES = _RUNTIME_PROCESS_CONTROL_ENV_PREFIXES_OPERATOR_OWNED_AGENT_ENV = frozenset(@@ -935,6 +930,95 @@ def _harbor_bin() -> str:return str(candidate) if candidate.exists() else (shutil.which("harbor") or "harbor")+# Harbor loads ``.env.local`` from its working directory, and Harbor and LiteLLM+# call ``load_dotenv()`` on import. Every Harbor process therefore starts in an+# empty evaluator-owned directory with dotenv loading and telemetry disabled, so+# no file outside the allowlisted environment can add credentials or settings.+# These controls are applied at launch, outside the secret-tracked environment.+_HARBOR_LAUNCH_ENV = MappingProxyType({"HARBOR_TELEMETRY": "0", "PYTHON_DOTENV_DISABLED": "1"})+# Harbor 0.22's Codex agent ran with ``model_reasoning_effort=high``; later+# releases defer to Codex's own default. Pin the effort SkillEvaluator was+# validated with so scores and cost stay comparable across Harbor upgrades.+_HARBOR_AGENT_KWARGS: Mapping[str, Mapping[str, str]] = MappingProxyType(+ {"codex": MappingProxyType({"reasoning_effort": "high"})}+)+# Allowlisted host variables that name a file or directory. A relative value keeps+# its meaning by being anchored to the operator's working directory.+_HARBOR_HOST_PATH_ENV_VARS = frozenset(+ {+ "APPTAINER_AUTHFILE",+ "APPTAINER_CONFIGDIR",+ "AWS_CA_BUNDLE",+ "AWS_CONFIG_FILE",+ "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE",+ "AWS_CREDENTIAL_FILE",+ "AWS_LOGIN_CACHE_DIRECTORY",+ "AWS_SHARED_CREDENTIALS_FILE",+ "AWS_WEB_IDENTITY_TOKEN_FILE",+ "CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE",+ "CLOUDSDK_CONFIG",+ "DOCKER_CERT_PATH",+ "DOCKER_CONFIG",+ "GOOGLE_APPLICATION_CREDENTIALS",+ "LANGSMITH_CONFIG_FILE",+ "MODAL_CONFIG_PATH",+ "NETRC",+ "REQUESTS_CA_BUNDLE",+ "SINGULARITY_AUTHFILE",+ "SINGULARITY_CONFIGDIR",+ "SKYPILOT_GLOBAL_CONFIG",+ "SKYPILOT_PROJECT_CONFIG",+ "SSL_CERT_FILE",+ "TEMP",+ "TMP",+ "TMPDIR",+ }+)+_HARBOR_HOST_PATH_LIST_ENV_VARS = frozenset({"AWS_DATA_PATH", "KUBECONFIG", "SSL_CERT_DIR"})+_HOST_PATH_ENVIRONMENT_KWARGS: Mapping[str, frozenset[str]] = MappingProxyType(+ {+ "ack": frozenset({"kubeconfig"}),+ "ec2": frozenset({"ssh_key_path", "ssh_known_hosts_path"}),+ "singularity": frozenset({"singularity_image_cache_dir"}),+ }+)+++def _absolute_host_path(value: str) -> str:+ """Anchor a relative host path to the operator's working directory."""+ if not value or value.startswith("~"):+ return value+ path = Path(value)+ return value if path.is_absolute() else str(path.absolute())+++def _harbor_launch_environment(env: Mapping[str, str]) -> dict[str, str]:+ """Return a Harbor child environment that no longer depends on the caller's directory."""+ launch_env = dict(env)+ for name in _HARBOR_HOST_PATH_ENV_VARS & launch_env.keys():+ launch_env[name] = _absolute_host_path(launch_env[name])+ for name in _HARBOR_HOST_PATH_LIST_ENV_VARS & launch_env.keys():+ launch_env[name] = os.pathsep.join(_absolute_host_path(entry) for entry in launch_env[name].split(os.pathsep))+ launch_env.update(_HARBOR_LAUNCH_ENV)+ return launch_env+++def _absolute_host_path_kwargs(env_mode: str, environment_kwargs: Mapping[str, Any]) -> dict[str, Any]:+ """Anchor relative host-path constructor kwargs before Harbor changes directory."""+ anchored = dict(environment_kwargs)+ for name in _HOST_PATH_ENVIRONMENT_KWARGS.get(env_mode, frozenset()) & anchored.keys():+ if isinstance(anchored[name], str):+ anchored[name] = _absolute_host_path(anchored[name])+ return anchored+++@contextmanager+def _harbor_launch_cwd() -> Iterator[Path]:+ """Yield a private, empty working directory for one Harbor process."""+ with tempfile.TemporaryDirectory(prefix="skillevaluator-harbor-", ignore_cleanup_errors=True) as directory:+ yield Path(directory)++def _harbor_supports_yes() -> bool:"""The supported Harbor CLI accepts ``--yes`` for non-interactive runs."""return True@@ -982,6 +1066,7 @@ _HARBOR_RUNTIME_POLICY_KWARGS = frozenset("context_id","cpu_enforcement_policy","delete",+ "enable_environment_dir_upload","environment_dir","environment_name","extra_allowed_hosts",@@ -1007,6 +1092,7 @@ _HARBOR_RUNTIME_POLICY_KWARGS = frozenset("pod_run_as_user","phase_network_policies","session_id",+ "stream","suppress_override_warnings","extra_env","extra_volume_mounts",@@ -1032,16 +1118,17 @@ _HARBOR_ENVIRONMENT_RUNTIME_POLICY_KWARGS: dict[str, frozenset[str]] = {}),"blaxel": frozenset({"dind_extra_args"}),- "cua-cloud": frozenset({"claim_spec"}),+ # Credential strategy selection; SkillEvaluator sets it only for the wandb alias.+ "cwsandbox": frozenset({"auth"}),"daytona": frozenset({"network_block_all"}),"ec2": frozenset({"iam_instance_profile", "strict_host_key_checking"}),"gke": frozenset({"memory_limit_multiplier"}),"modal": frozenset({"volumes"}),- "opensandbox": frozenset({"volumes"}),"openshift": frozenset({"service_account_name"}),"singularity": frozenset({"singularity_no_mount"}),"use-computer": frozenset({"resources"}),"vercel": frozenset({"ports"}),+ "wandb": frozenset({"auth"}),}@@ -1055,8 +1142,10 @@ def _environment_kwarg_policy_error(env_mode: str, environment_kwargs: Mapping[sreserved = _HARBOR_RUNTIME_POLICY_KWARGS | _HARBOR_ENVIRONMENT_RUNTIME_POLICY_KWARGS.get(env_mode, frozenset())if collisions := sorted(reserved & environment_kwargs.keys()):return "Environment kwarg(s) reserved for Harbor runtime policy: " + ", ".join(collisions)- if unknown := sorted(environment_kwargs.keys() - HARBOR_V022_ENVIRONMENT_KWARGS[env_mode]):- return f"Harbor 0.22.0 environment '{env_mode}' does not accept environment kwarg(s): " + ", ".join(unknown)+ if unknown := sorted(environment_kwargs.keys() - HARBOR_ENVIRONMENT_KWARGS[env_mode]):+ return f"Harbor {HARBOR_VERSION} environment '{env_mode}' does not accept environment kwarg(s): " + ", ".join(+ unknown+ )return None@@ -1112,7 +1201,11 @@ def build_harbor_run_command(if env_mode not in HARBOR_ENV_MODES:raise ValueError(f"env_mode must be one of: {', '.join(sorted(HARBOR_ENV_MODES))}")timeout_multiplier = _validated_timeout_multiplier(timeout_multiplier)- if agent_import_path and env_mode not in {"docker", ENV_MODE_LOCAL}:+ if (+ agent_import_path+ and env_mode not in {"docker", ENV_MODE_LOCAL}+ and agent_import_path not in _NATIVE_BACKEND_AGENT_IMPORT_PATHS+ ):raise ValueError("agent_import_path is supported only with --env docker or local")validated_environment_kwargs = validate_environment_kwargs(dict(environment_kwargs or {}),@@ -1120,6 +1213,7 @@ def build_harbor_run_command()if policy_error := _environment_kwarg_policy_error(env_mode, validated_environment_kwargs):raise ValueError(policy_error)+ validated_environment_kwargs = _absolute_host_path_kwargs(env_mode, validated_environment_kwargs)command = [_harbor_bin(),@@ -1131,7 +1225,7 @@ def build_harbor_run_command("--n-concurrent",str(n_concurrent),"-p",- str(dataset_path),+ str(Path(dataset_path).absolute()),]if env_mode == ENV_MODE_LOCAL:# Local mode is a custom SkillEvaluator environment + agent wrappers,@@ -1175,11 +1269,16 @@ def build_harbor_run_command(command.extend(["--agent", agent])command.extend(["--env", SECURE_DOCKER_ENV_IMPORT_PATH])else:- command.extend(["--agent", agent, "--env", env_mode])+ command.extend(["--agent", agent_import_path or agent, "--env", harbor_environment_type(env_mode)])+ for name, value in sorted(_HARBOR_AGENT_KWARGS.get(agent, {}).items()):+ command.extend(["--ak", encode_environment_kwarg(name, value)])for name, value in sorted(validated_environment_kwargs.items()):command.extend(["--ek", encode_environment_kwarg(name, value)])+ # Alias kwargs come after operator kwargs, which may never set them.+ for name, value in sorted(HARBOR_ENVIRONMENT_ALIAS_KWARGS.get(env_mode, {}).items()):+ command.extend(["--ek", encode_environment_kwarg(name, value)])if jobs_dir is not None:- command.extend(["--jobs-dir", str(jobs_dir)])+ command.extend(["--jobs-dir", str(Path(jobs_dir).absolute())])if disable_verification:command.append("--disable-verification")for task_name in include_task_names or []:@@ -1208,7 +1307,11 @@ def _provider_environment(config: ProviderConfig) -> dict[str, str]:"SKILL_EVAL_LLM_MODEL": config.model,}environment.update(- {name: value for name in _VERIFIER_JUDGE_CONTROL_ENV_VARS if (value := os.environ.get(name, "").strip())}+ {+ name: value+ for name in (_VERIFIER_JUDGE_CONTROL_ENV_VARS | _VERIFIER_BUDGET_ENV_VARS | _VERIFIER_RETRY_ENV_VARS)+ if (value := os.environ.get(name, "").strip())+ })if config.provider == "anthropic":environment["ANTHROPIC_API_KEY"] = config.api_key or ""@@ -1439,8 +1542,6 @@ def _environment_kwarg_prerequisite_errors(invalid := invalid_strings(*(name for name in ("context", "kubeconfig") if name in kwargs))):return ["Harbor environment 'ack' requires non-empty string --environment-kwarg for: " + ", ".join(invalid)]- if env_mode == "opensandbox" and kwargs.get("domain") is not None and invalid_strings("domain"):- return ["Harbor environment 'opensandbox' requires domain to be a non-empty string when provided"]if env_mode == "ec2":launch_mode_value = kwargs.get("launch_mode", "ephemeral")if not isinstance(launch_mode_value, str):@@ -1465,10 +1566,31 @@ def _environment_kwarg_prerequisite_errors(return []+def _cwsandbox_prerequisite_errors(env_mode: str) -> list[str]:+ """Check what Harbor's cwsandbox backend needs; Harbor 0.24 no longer checks it."""+ if harbor_environment_type(env_mode) != "cwsandbox":+ return []+ required_modules = ("cwsandbox", "wandb") if env_mode == "wandb" else ("cwsandbox",)+ if missing := [name for name in required_modules if importlib.util.find_spec(name) is None]:+ return [+ f"Harbor environment '{env_mode}' needs optional dependencies: {', '.join(missing)}. "+ f"{_environment_extra_install_hint(env_mode)}"+ ]+ if env_mode == "wandb":+ netrc_paths = [os.environ.get("NETRC", ""), str(Path.home() / ".netrc"), str(Path.home() / "_netrc")]+ if not os.environ.get("WANDB_API_KEY", "").strip() and not any(+ path and Path(path).expanduser().is_file() for path in netrc_paths+ ):+ return ["Harbor environment 'wandb' requires WANDB_API_KEY or a netrc file from `wandb login`."]+ elif not os.environ.get("CWSANDBOX_API_KEY", "").strip():+ return ["Harbor environment 'cwsandbox' requires CWSANDBOX_API_KEY."]+ return []++def _environment_extra_install_hint(env_mode: str) -> str:extra = HARBOR_ENVIRONMENT_EXTRAS.get(env_mode)if extra is not None:- return f"Install 'harbor[{extra}]==0.22.0'."+ return f"Install 'harbor[{extra}]=={HARBOR_VERSION}'."system_hints = {"apple-container": "Install the Apple container CLI; Harbor has no Python extra for this backend.","openshift": "Install the OpenShift oc CLI; Harbor has no Python extra for this backend.",@@ -1543,6 +1665,7 @@ def _check_ack_cluster_readiness_subprocess(validated = validate_environment_kwargs(dict(environment_kwargs), env_mode="ack")if policy_error := _environment_kwarg_policy_error("ack", validated):raise ValueError(policy_error)+ validated = _absolute_host_path_kwargs("ack", validated)payload = {name: validated[name] for name in ("namespace", "context", "kubeconfig") if name in validated}encoded = json.dumps(payload, ensure_ascii=True, separators=(",", ":"), allow_nan=False)child_env = dict(subprocess_env)@@ -1550,19 +1673,22 @@ def _check_ack_cluster_readiness_subprocess(redacted_values.update(str(value) for value in payload.values() if isinstance(value, str) and value)process: subprocess.Popen[str] | None = Nonetry:- process = subprocess.Popen(- [sys.executable, "-c", _ACK_CLUSTER_READINESS_PROBE_CODE],- stdin=subprocess.PIPE,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- text=True,- env=child_env,- start_new_session=os.name == "posix",- )- stdout, stderr = process.communicate(- encoded,- timeout=_ACK_CLUSTER_READINESS_SUBPROCESS_TIMEOUT_SECONDS,- )+ with _harbor_launch_cwd() as launch_cwd:+ # ``-P`` keeps the probe's working directory off ``sys.path``.+ process = subprocess.Popen(+ [sys.executable, "-P", "-c", _ACK_CLUSTER_READINESS_PROBE_CODE],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ cwd=str(launch_cwd),+ env=_harbor_launch_environment(child_env),+ start_new_session=os.name == "posix",+ )+ stdout, stderr = process.communicate(+ encoded,+ timeout=_ACK_CLUSTER_READINESS_SUBPROCESS_TIMEOUT_SECONDS,+ )except subprocess.TimeoutExpired:assert process is not None_terminate_ack_readiness_process(process)@@ -1597,6 +1723,23 @@ def _modal_custom_config_status() -> tuple[bool, str | None]:return True, None+def _python_dotenv_prerequisite_error() -> str | None:+ """Require the python-dotenv release that honors ``PYTHON_DOTENV_DISABLED``."""+ from importlib.metadata import PackageNotFoundError, version++ try:+ installed = version("python-dotenv")+ except PackageNotFoundError:+ return None+ release = re.match(r"(\d+)\.(\d+)", installed)+ if release is None or (int(release[1]), int(release[2])) >= (1, 2):+ return None+ return (+ f"python-dotenv {installed} cannot disable Harbor's .env loading; "+ "install skillevaluator[tier3] to upgrade it to 1.2.0 or newer."+ )++def _check_prerequisites(env_mode: str = DEFAULT_ENV_MODE,agents: list[str] | None = None,@@ -1606,6 +1749,8 @@ def _check_prerequisites("""Check Harbor and the selected environment (built-in or local mode)."""if env_mode not in HARBOR_ENV_MODES:return [f"Unsupported Harbor environment '{env_mode}'. Choose one of: {', '.join(sorted(HARBOR_ENV_MODES))}"]+ if dotenv_error := _python_dotenv_prerequisite_error():+ return [dotenv_error]if kwarg_errors := _environment_kwarg_prerequisite_errors(env_mode, environment_kwargs):return kwarg_errorsif env_mode == ENV_MODE_LOCAL:@@ -1626,21 +1771,6 @@ def _check_prerequisites(return ["Harbor environment 'singularity' requires the singularity CLI on PATH."]if env_mode == "islo" and not os.environ.get("ISLO_API_KEY", "").strip():return ["Harbor environment 'islo' requires a non-empty ISLO_API_KEY in the host environment."]- if env_mode == "opensandbox" and (environment_kwargs or {}).get("domain") is None:- opensandbox_env = (- subprocess_env- if subprocess_env is not None- else _selected_host_environment(- _HARBOR_BASE_ENV_VARS | _HARBOR_ENV_MODE_VARS["opensandbox"],- os.environ,- )- )- if not opensandbox_env.get("OPENSANDBOX_DOMAIN", "").strip():- return [- "Harbor environment 'opensandbox' requires a non-empty domain --environment-kwarg "- "or child-visible OPENSANDBOX_DOMAIN."- ]-if env_mode == "modal":_, modal_config_error = _modal_custom_config_status()if modal_config_error:@@ -1706,7 +1836,9 @@ def _check_prerequisites(from harbor.environments.factory import EnvironmentFactoryfrom harbor.models.environment_type import EnvironmentType- EnvironmentFactory.run_preflight(EnvironmentType(env_mode))+ if cwsandbox_errors := _cwsandbox_prerequisite_errors(env_mode):+ return cwsandbox_errors+ EnvironmentFactory.run_preflight(EnvironmentType(harbor_environment_type(env_mode)))if env_mode == "ack":ack_subprocess_env = (dict(subprocess_env)@@ -1747,21 +1879,26 @@ def _check_prerequisites(return []-def _is_operator_owned_runtime_name(name: str) -> bool:+def _is_operator_owned_runtime_name(name: str, *, env_mode: str) -> bool:normalized = name.upper()return (is_sensitive_key(name)or normalized in _RUNTIME_ENV_HOST_CONTROL_NAMES+ or normalized in _HARBOR_ENV_MODE_VARS.get(env_mode, frozenset())or normalized in _OPERATOR_OWNED_AGENT_ENVor normalized.startswith(_RUNTIME_ENV_HOST_CONTROL_PREFIXES))-def _resolve_runtime_env(templates: dict[str, str] | None) -> tuple[dict[str, str], list[str]]:+def _resolve_runtime_env(+ templates: dict[str, str] | None,+ *,+ env_mode: str,+) -> tuple[dict[str, str], list[str]]:resolved: dict[str, str] = {}errors: list[str] = []for name, template in (templates or {}).items():- if _is_operator_owned_runtime_name(name):+ if _is_operator_owned_runtime_name(name, env_mode=env_mode):errors.append(f"harbor.runtime_env.{name} controls the host process and is not allowed")continuetemplate_value = str(template)@@ -1774,7 +1911,9 @@ def _resolve_runtime_env(templates: dict[str, str] | None) -> tuple[dict[str, st}percent_references = set(re.findall(r"%([A-Za-z_][A-Za-z0-9_]*)%", template_value))references = dollar_references | percent_references- owned_references = sorted(reference for reference in references if _is_operator_owned_runtime_name(reference))+ owned_references = sorted(+ reference for reference in references if _is_operator_owned_runtime_name(reference, env_mode=env_mode)+ )if owned_references:errors.append(f"harbor.runtime_env.{name} references operator-owned credential(s): " + ", ".join(owned_references)@@ -2305,7 +2444,7 @@ def _model_for_agent(def _agent_import_path(provider: ProviderConfig, agent: str, env_mode: str) -> str | None:"""Select only the provider-specific wrappers required for this environment."""if provider.provider == "openai-compatible" and agent == "codex" and env_mode != ENV_MODE_LOCAL:- return "skillevaluator.tier3.harbor.local_agents:SkillEvaluatorGatewayCodex"+ return _GATEWAY_CODEX_IMPORT_PATHif provider.provider == "openai-compatible" and agent == "opencode" and env_mode == "docker":return "skillevaluator.tier3.harbor.local_agents:SkillEvaluatorGatewayOpenCode"return _nvidia_build_agent_import_path(provider, agent, env_mode)@@ -2455,14 +2594,15 @@ def _run_bounded_harbor_process(command: list[str],*,env: Mapping[str, str],+ cwd: Path,stdin_text: str | None,- timeout_seconds: float,+ timeout_seconds: float | None,max_output_bytes: int,diagnostic_tail_chars: int,secret_values: set[str],) -> _BoundedHarborProcessResult:- """Run Harbor with bounded merged output and platform cleanup ownership."""- if timeout_seconds <= 0:+ """Run Harbor with bounded merged output and optional cleanup deadline."""+ if timeout_seconds is not None and timeout_seconds <= 0:raise ValueError("Harbor run timeout must be positive")if max_output_bytes <= 0:raise ValueError("Harbor output byte limit must be positive")@@ -2475,7 +2615,8 @@ def _run_bounded_harbor_process(stdin=subprocess.PIPE if stdin_text is not None else subprocess.DEVNULL,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,- env=dict(env),+ cwd=str(cwd),+ env=_harbor_launch_environment(env),start_new_session=os.name == "posix",creationflags=creation_flags,)@@ -2488,7 +2629,7 @@ def _run_bounded_harbor_process(reader_error: list[BaseException] = []stdin_error: list[BaseException] = []output_tail = ""- deadline = time.monotonic() + timeout_seconds+ deadline = time.monotonic() + timeout_seconds if timeout_seconds is not None else Nonedef append_tail(text: str) -> None:nonlocal output_tail@@ -2567,6 +2708,9 @@ def _run_bounded_harbor_process(breakif reader_done.is_set() and process.poll() is not None:break+ if deadline is None:+ reader_done.wait(_HARBOR_RUN_POLL_SECONDS)+ continueremaining = deadline - time.monotonic()if remaining <= 0:timed_out = True@@ -2588,6 +2732,7 @@ def _run_bounded_harbor_process(if stdin_error:raise RuntimeError("Harbor stdin delivery failed") from stdin_error[0]if timed_out:+ assert timeout_seconds is not Nonedetail = f"Harbor run timed out after {timeout_seconds:g} seconds"safe_tail = redact_progress_detail(output_tail, secret_values=secret_values)if safe_tail:@@ -2646,7 +2791,7 @@ def _run_harbor(# Preserve the historical exact-value protection for every selected child# value, and additionally protect detached credential URI/proxy userinfo# (including percent-decoded and schemeless proxy components).- secret_values = set(run_env.values())+ secret_values = {value for value in run_env.values() if len(value) >= MIN_EXACT_SECRET_CHARS}secret_values.update(secret_values_from_environment(run_env))command = build_harbor_run_command(dataset_path=dataset,@@ -2668,15 +2813,20 @@ def _run_harbor()try:handoff = _nvidia_build_key_handoff(run_env, env_mode=env_mode)- result = _run_bounded_harbor_process(- command,- env=handoff.subprocess_env,- stdin_text=handoff.stdin_text,- timeout_seconds=_HARBOR_RUN_TIMEOUT_SECONDS,- max_output_bytes=_HARBOR_RUN_OUTPUT_MAX_BYTES,- diagnostic_tail_chars=_HARBOR_RUN_DIAGNOSTIC_TAIL_CHARS,- secret_values=secret_values,- )+ # Harbor owns its phase deadlines, and native tasks may intentionally+ # leave the agent unbounded. Keep bounded streaming and process-tree+ # cleanup without imposing an outer orchestration deadline.+ with _harbor_launch_cwd() as launch_cwd:+ result = _run_bounded_harbor_process(+ command,+ env=handoff.subprocess_env,+ cwd=launch_cwd,+ stdin_text=handoff.stdin_text,+ timeout_seconds=None,+ max_output_bytes=_HARBOR_RUN_OUTPUT_MAX_BYTES,+ diagnostic_tail_chars=_HARBOR_RUN_DIAGNOSTIC_TAIL_CHARS,+ secret_values=secret_values,+ )except (OSError, RuntimeError, UnicodeError) as exc:detail = _redact_harbor_diagnostic(exc, secret_values=secret_values)if not detail:@@ -3563,7 +3713,10 @@ def _run_harbor_eval_impl(model_resolution[agent] = {"agent": agent, "model": selected, "source": source}provider_env = _provider_environment(provider)- configured_runtime_env, runtime_errors = _resolve_runtime_env(harbor_config.get("runtime_env"))+ configured_runtime_env, runtime_errors = _resolve_runtime_env(+ harbor_config.get("runtime_env"),+ env_mode=env_mode,+ )reporter.set_secret_values(secret_values_from_environment(provider_env) | set(configured_runtime_env.values()))reporter.emit(ProgressEvent(stage="model-resolution", state="complete", detail="agent models resolved"))reporter.start(@@ -3582,7 +3735,7 @@ def _run_harbor_eval_impl()prerequisite_subprocess_env: dict[str, str] | None = None- if env_mode in {"ack", "opensandbox"} and agents:+ if env_mode == "ack" and agents:preflight_agent = agents[0]runtime_provider_env = {name: value for name, value in provider_env.items() if name not in _VERIFIER_JUDGE_CONTROL_ENV_VARS@@ -4149,7 +4302,7 @@ def _run_harbor_eval_impl(override_cpus=override_cpus,override_memory_mb=override_memory_mb,override_storage_mb=override_storage_mb,- agent_import_path=nvidia_build_agent_import_paths.get(agent),+ agent_import_path=agent_import_paths.get(agent),environment_kwargs=effective_environment_kwargs,)if not preflight.ok:diff --git a/src/skillevaluator/tier3/harbor/runtime_preflight.py b/src/skillevaluator/tier3/harbor/runtime_preflight.pyindex 1aa0d435..b402091e 100644--- a/src/skillevaluator/tier3/harbor/runtime_preflight.py+++ b/src/skillevaluator/tier3/harbor/runtime_preflight.py@@ -73,7 +73,12 @@ from skillevaluator.model_catalog import (fetch_model_records,)from skillevaluator.tier3.harbor.progress import redact_progress_detail-from skillevaluator.tier3.harbor.runner import _nvidia_build_key_handoff, build_harbor_run_command+from skillevaluator.tier3.harbor.runner import (+ _harbor_launch_cwd,+ _harbor_launch_environment,+ _nvidia_build_key_handoff,+ build_harbor_run_command,+)if TYPE_CHECKING:from skillevaluator.provider_config import ProviderConfig@@ -1500,15 +1505,17 @@ def run_agent_runtime_preflight()try:handoff = _nvidia_build_key_handoff(run_env, env_mode=env_mode)- completed = subprocess.run(- command,- capture_output=True,- text=True,- input=handoff.stdin_text,- env=handoff.subprocess_env,- timeout=timeout_seconds,- check=False,- )+ with _harbor_launch_cwd() as launch_cwd:+ completed = subprocess.run(+ command,+ capture_output=True,+ text=True,+ input=handoff.stdin_text,+ cwd=launch_cwd,+ env=_harbor_launch_environment(handoff.subprocess_env),+ timeout=timeout_seconds,+ check=False,+ )except subprocess.TimeoutExpired:return PreflightResult(False,diff --git a/src/skillevaluator/tier3/harbor/secure_docker_environment.py b/src/skillevaluator/tier3/harbor/secure_docker_environment.pyindex c010eb16..f34bc03b 100644--- a/src/skillevaluator/tier3/harbor/secure_docker_environment.py+++ b/src/skillevaluator/tier3/harbor/secure_docker_environment.py@@ -32,7 +32,7 @@ from collections import dequefrom collections.abc import AsyncIterator, Iterable, Iterator, Mappingfrom dataclasses import dataclassfrom pathlib import Path, PurePosixPath-from typing import Any, BinaryIO+from typing import TYPE_CHECKING, Any, BinaryIOimport yamlfrom harbor.environments.base import (@@ -43,6 +43,7 @@ from harbor.environments.base import (ServiceOperationsUnsupportedError,)from harbor.environments.docker.docker import DockerEnvironment, _sanitize_docker_compose_project_name+from harbor.environments.docker.runtime import DOCKER_RUNTIME, ContainerRuntimefrom skillevaluator.tier3.harbor.progress import secret_values_from_environmentfrom skillevaluator.tier3.harbor.secure_copy import (@@ -58,6 +59,9 @@ from skillevaluator.tier3.harbor.sensitive_stdin import (from skillevaluator.tier3.harbor.stream_redaction import CommandOutputByteBudgetfrom skillevaluator.utils.secure_fs import stat_is_link_or_reparse+if TYPE_CHECKING:+ from harbor.environments.capabilities import EnvironmentCapabilities+SECURE_DOCKER_ENV_IMPORT_PATH = ("skillevaluator.tier3.harbor.secure_docker_environment:SkillEvaluatorSecureDockerEnvironment")@@ -201,6 +205,23 @@ for _compose_override_tag in ("!reset", "!override"):)+def _validate_compose_model_parse_budget(content: str) -> None:+ """Reject oversized YAML graphs before PyYAML constructs them."""+ node_count = 0+ depth = 0+ for event in yaml.parse(content, Loader=_ComposeModelLoader):+ if isinstance(event, yaml.events.NodeEvent):+ node_count += 1+ if node_count > _MAX_COMPOSE_MODEL_NODES:+ raise RuntimeError("could not inspect Docker Compose interpolation inputs")+ if isinstance(event, yaml.events.CollectionStartEvent):+ depth += 1+ if depth > _MAX_COMPOSE_MODEL_DEPTH:+ raise RuntimeError("could not inspect Docker Compose interpolation inputs")+ elif isinstance(event, yaml.events.CollectionEndEvent):+ depth -= 1++class _SecretTrieNode:__slots__ = ("children", "failure", "max_terminal_length", "terminal_length")@@ -1277,6 +1298,24 @@ class SkillEvaluatorDockerEnvironment(DockerEnvironment):self._compose_model_metadata()await super().start(force_build)+ @classmethod+ def runtime(cls) -> ContainerRuntime:+ """Stay on Docker: the hardened Compose runner and containment use the Docker CLI."""+ return DOCKER_RUNTIME++ @property+ def capabilities(self) -> EnvironmentCapabilities:+ """Disable SSH streaming and GPU device reservations, which bypass the hardened runner."""+ return super().capabilities.model_copy(update={"stream": False, "gpus": False})++ async def download_file(self, source_path: str, target_path: Path | str) -> None:+ """Download from the main container without Harbor's raw ``docker cp`` fallback."""+ await self.service_download_file(source_path, target_path, service=None)++ async def download_dir(self, source_dir: str, target_dir: Path | str) -> None:+ """Download from the main container without Harbor's raw ``docker cp`` fallback."""+ await self.service_download_dir(source_dir, target_dir, service=None)+@staticmethodasync def _collect_streamed_output(process: asyncio.subprocess.Process,@@ -1890,7 +1929,7 @@ class SkillEvaluatorDockerEnvironment(DockerEnvironment):user: str | int | None = None,) -> ExecResult:user = self._resolve_user(user)- merged_environment = self._merge_env(env)+ merged_environment = self._merge_env(env) or {}environment_args, subprocess_environment = _secure_exec_arguments(merged_environment)exact_secret_values = _sensitive_environment_values(merged_environment)exact_secret_values.update(_credential_uri_environment_values(merged_environment))@@ -2042,12 +2081,16 @@ class SkillEvaluatorDockerEnvironment(DockerEnvironment):if len(content) > remaining_bytes:raise RuntimeError("could not inspect Docker Compose interpolation inputs")total_bytes += len(content)+ decoded_content = content.decode("utf-8")+ # Scan PyYAML's incremental event stream before composing the object+ # graph. This keeps compact, deeply nested, or high-node YAML from+ # exhausting memory or recursion before the post-load metadata walk.+ _validate_compose_model_parse_budget(decoded_content)# _ComposeModelLoader subclasses yaml.SafeLoader and registers only# scalar, sequence, and mapping constructors for Compose's !reset and# !override tags, so arbitrary Python-object construction stays disabled.- # Depth and node-count bounds are enforced separately after parsing.model = yaml.load( # nosec B506- content.decode("utf-8"),+ decoded_content,Loader=_ComposeModelLoader,)except (OSError, RecursionError, UnicodeDecodeError, yaml.YAMLError) as exc:diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.pyindex 30d886e7..63f4ab74 100644--- a/src/skillevaluator/tier3/harbor/templates/eval.py+++ b/src/skillevaluator/tier3/harbor/templates/eval.py@@ -74,6 +74,7 @@ try:AMBIGUOUS_OUTER_EXEC_OBSERVATION,UNOBSERVED_INNER_CALL,UNSUPPORTED_NATIVE_CODEX_EXEC,+ atif_content_text,iter_normalized_tool_calls,normalized_tool_call_observation,normalized_tool_call_wrapper_observation,@@ -83,6 +84,7 @@ except ImportError: # pragma: no cover -- source-tree import onlyAMBIGUOUS_OUTER_EXEC_OBSERVATION,UNOBSERVED_INNER_CALL,UNSUPPORTED_NATIVE_CODEX_EXEC,+ atif_content_text,iter_normalized_tool_calls,normalized_tool_call_observation,normalized_tool_call_wrapper_observation,@@ -467,7 +469,7 @@ def build_conversation_summary(traj, question):parts.append(f"Agent called: {fn}({json.dumps(args)[:200]})")obs = step.get("observation") or {}for r in obs.get("results") or []:- content = str(r.get("content", ""))+ content = atif_content_text(r.get("content"))if content:parts.append(f"Tool returned: {content[:400]}")msg = step.get("message") or ""@@ -855,7 +857,7 @@ def _tool_observation_refs(traj):for result_idx, result in enumerate((step.get("observation") or {}).get("results") or []):if len(refs) >= _METRIC_EVIDENCE_MAX_TOOL_REFS:return refs- content = str(result.get("content") or "")+ content = atif_content_text(result.get("content"))if not content.strip():continuecall_id = str(result.get("source_call_id") or f"result-{result_idx}")@@ -1051,7 +1053,7 @@ def _late_observation_excerpts(traj, limit):if step.get("source") != "agent":continuefor result in reversed((step.get("observation") or {}).get("results") or []):- content = str(result.get("content") or "").strip()+ content = atif_content_text(result.get("content")).strip()if content:out.append(_clip(content, limit))return out@@ -4201,7 +4203,7 @@ def check_security(traj, tool_calls, expected_skill=None, acceptable_skills=Nonefindings = []agent_text = get_agent_text(traj)user_text = "\n".join(- str(step.get("message") or "") for step in traj.get("steps", []) if step.get("source") == "user"+ atif_content_text(step.get("message")) for step in traj.get("steps", []) if step.get("source") == "user")if user_text and any(pattern.search(user_text) for pattern in _PROMPT_INJECTION_PATTERNS):diff --git a/src/skillevaluator/tier3/workflow.py b/src/skillevaluator/tier3/workflow.pyindex bc3dbf51..f0af6458 100644--- a/src/skillevaluator/tier3/workflow.py+++ b/src/skillevaluator/tier3/workflow.py@@ -94,7 +94,11 @@ def _preflight_options(skill_path: Path, params: dict[str, Any]) -> None:from skillevaluator.cli import _evaluated_source_from_optionsfrom skillevaluator.provider_config import resolve_llm_providerfrom skillevaluator.tier3.commands import parse_agent_model_overrides, resolve_agents, validate_agents- from skillevaluator.tier3.evals_config import _validate_config, load_evals_config+ from skillevaluator.tier3.evals_config import (+ _validate_config,+ load_evals_config,+ parse_environment_kwarg_overrides,+ )from skillevaluator.tier3.harbor.runner import (_model_for_agent,_resolve_agent_runtime_plan,@@ -126,6 +130,7 @@ def _preflight_options(skill_path: Path, params: dict[str, Any]) -> None:if params.get(cli_name) is not None:effective.setdefault(group, {})["mode"] = params[cli_name]_validate_config(effective, config_path or skill_path / "evals" / "config.yml")+ parse_environment_kwarg_overrides(params.get("environment_kwarg") or (), env_mode=params["env_mode"])if harbor.get("stop_on_pass", False) and harbor.get("n_attempts", 1) == 1:raise ValueError("stop_on_pass requires n_attempts > 1")@@ -160,7 +165,7 @@ def _preflight_options(skill_path: Path, params: dict[str, Any]) -> None:)for agent in agents}- runtime_env, errors = _resolve_runtime_env(harbor.get("runtime_env"))+ runtime_env, errors = _resolve_runtime_env(harbor.get("runtime_env"), env_mode=params["env_mode"])if errors:raise ValueError("; ".join(errors))_resolve_agent_runtime_plan(@@ -181,13 +186,22 @@ def _preflight_options(skill_path: Path, params: dict[str, Any]) -> None:def _preflight_environment(params: dict[str, Any]) -> None:"""Check installed runtimes and backend configuration without an agent run."""from skillevaluator.tier3.commands import parse_agents+ from skillevaluator.tier3.evals_config import parse_environment_kwarg_overridesfrom skillevaluator.tier3.harbor.runner import _check_prerequisites- # These Harbor preflights perform remote authentication RPCs. Leave those+ # These preflights contact a remote control plane or cluster. Leave those# probes in the execution engine instead of running them before generation.- if params["env_mode"] in {"cwsandbox", "wandb", "langsmith"}:+ if params["env_mode"] in {"ack", "cwsandbox", "langsmith", "openshift", "wandb"}:return- errors = _check_prerequisites(env_mode=params["env_mode"], agents=parse_agents(params["agents"]))+ environment_kwargs = parse_environment_kwarg_overrides(+ params.get("environment_kwarg") or (),+ env_mode=params["env_mode"],+ )+ errors = _check_prerequisites(+ env_mode=params["env_mode"],+ agents=parse_agents(params["agents"]),+ environment_kwargs=environment_kwargs,+ )if errors:raise ValueError("; ".join(errors))diff --git a/src/skillevaluator/tier3_environments.py b/src/skillevaluator/tier3_environments.pyindex dc77bf9c..60f1a300 100644--- a/src/skillevaluator/tier3_environments.py+++ b/src/skillevaluator/tier3_environments.py@@ -9,6 +9,10 @@ show its command help without importing Harbor or any optional dependencies.from __future__ import annotations+#: The exact Harbor release whose CLI, models, and environment interfaces this+#: SkillEvaluator release targets; the ``tier3`` extra pins it.+HARBOR_VERSION = "0.24.0"+HARBOR_ENVIRONMENTS = ("docker","daytona",@@ -28,12 +32,9 @@ HARBOR_ENVIRONMENTS = ("cwsandbox","wandb","use-computer",- "cua-cloud","blaxel",- "opensandbox","beam","skypilot",- "hf-sandbox","hyperbrowser","vercel",# Not a Harbor-native backend: SkillEvaluator's host execution mode, run@@ -42,11 +43,24 @@ HARBOR_ENVIRONMENTS = ("local",)HARBOR_ENV_MODES = frozenset(HARBOR_ENVIRONMENTS)-#: env modes that Harbor accepts natively via ``--env`` (everything except ``local``).+#: Public env modes that Harbor accepts natively via ``--env`` (everything except ``local``).HARBOR_NATIVE_ENV_MODES = frozenset(m for m in HARBOR_ENVIRONMENTS if m != "local")-# Exact Harbor 0.22 ``Provides-Extra`` names. ``ack`` reuses the Kubernetes-# dependencies supplied by ``gke``. Of the four ``None`` entries, Docker needs-# no additional Python extra and the other three are system-CLI backends.+#: SkillEvaluator modes that run as a different Harbor environment type. Harbor+#: 0.24 merged its W&B sandbox into ``cwsandbox``, selected with ``auth=wandb``.+HARBOR_ENVIRONMENT_TYPE_ALIASES: dict[str, str] = {"wandb": "cwsandbox"}+#: Constructor kwargs SkillEvaluator supplies for an alias; operators cannot set them.+HARBOR_ENVIRONMENT_ALIAS_KWARGS: dict[str, dict[str, str]] = {"wandb": {"auth": "wandb"}}+++def harbor_environment_type(env_mode: str) -> str:+ """Return the Harbor ``--env`` type that implements a SkillEvaluator mode."""+ return HARBOR_ENVIRONMENT_TYPE_ALIASES.get(env_mode, env_mode)+++# Exact Harbor ``Provides-Extra`` names. ``ack`` reuses the Kubernetes+# dependencies supplied by ``gke``, and ``wandb`` the W&B-capable ``cwsandbox``+# extra. Of the four ``None`` entries, Docker needs no additional Python extra+# and the other three are system-CLI backends.HARBOR_ENVIRONMENT_EXTRAS: dict[str, str | None] = {"docker": None,"daytona": "daytona",@@ -64,25 +78,25 @@ HARBOR_ENVIRONMENT_EXTRAS: dict[str, str | None] = {"islo": "islo","tensorlake": "tensorlake","cwsandbox": "cwsandbox",- "wandb": "wandb",+ "wandb": "cwsandbox","use-computer": "use-computer",- "cua-cloud": "cua","blaxel": "blaxel",- "opensandbox": "opensandbox","beam": "beam","skypilot": "skypilot",- "hf-sandbox": "hf-sandbox","hyperbrowser": "hyperbrowser","vercel": "vercel",}-# Constructor kwargs consumed by Harbor 0.22.0. Keep this static so importing-# the base SkillEvaluator CLI never imports Harbor or optional provider SDKs.-# The packaging parity test AST-reads the pinned Harbor sources and catches+# Constructor kwargs consumed by the pinned Harbor release. Keep this static so+# importing the base SkillEvaluator CLI never imports Harbor or optional provider+# SDKs. The packaging parity test AST-reads the pinned Harbor sources and catches# additions, removals, and provider kwargs that are consumed through **kwargs.-_HARBOR_V022_BASE_ENVIRONMENT_KWARGS = frozenset(+# Registry-only entries (cua-cloud, opensandbox, hf-sandbox, podman, kata, runta,+# prime, mosaic, smol) keep that parity exact; those modes are not exposed.+_HARBOR_BASE_ENVIRONMENT_KWARGS = frozenset({"cpu_enforcement_policy",+ "enable_environment_dir_upload","environment_dir","environment_name","extra_docker_compose",@@ -98,13 +112,14 @@ _HARBOR_V022_BASE_ENVIRONMENT_KWARGS = frozenset("persistent_env","phase_network_policies","session_id",+ "stream","suppress_override_warnings","task_env_config","trial_paths",})-_HARBOR_V022_BACKEND_ENVIRONMENT_KWARGS = {+_HARBOR_BACKEND_ENVIRONMENT_KWARGS = {"docker": "keep_containers","daytona": ("assume_global_snapshot auto_delete_interval_mins auto_labels auto_snapshot auto_stop_interval_mins "@@ -113,7 +128,7 @@ _HARBOR_V022_BACKEND_ENVIRONMENT_KWARGS = {),"e2b": "","modal": (- "app_name auto_labels dind_image keepalive labels modal_sandbox_v2 modal_vm_runtime region registry_secret "+ "app_name auto_labels dind_image keepalive labels modal_vm_runtime region registry_secret ""sandbox_idle_timeout_secs sandbox_timeout_secs secrets volumes"),"runloop": "",@@ -144,12 +159,10 @@ _HARBOR_V022_BACKEND_ENVIRONMENT_KWARGS = {"apple-container": "keep_containers","singularity": "singularity_force_pull singularity_image_cache_dir singularity_no_mount","islo": "delete_after_seconds gateway gateway_profile",- "tensorlake": "is_public preinstall_packages snapshot_id timeout_secs use_oci_image_build",+ "tensorlake": "dind_image is_public preinstall_packages snapshot_id timeout_secs use_oci_image_build","cwsandbox": (- "base_url docker_image max_lifetime_seconds max_timeout_seconds mounts_json request_timeout_seconds secrets tags"- ),- "wandb": (- "base_url docker_image max_lifetime_seconds max_timeout_seconds mounts_json request_timeout_seconds secrets tags"+ "auth base_url docker_image max_lifetime_seconds max_timeout_seconds mounts_json request_timeout_seconds "+ "secrets tags"),"use-computer": ("api_key base_url device_type family gateway_url host keepalive_interval mode override_exec_timeout platform "@@ -168,16 +181,30 @@ _HARBOR_V022_BACKEND_ENVIRONMENT_KWARGS = {"beam": "keep_warm_seconds","skypilot": "context_name namespace platform pool registry secrets","hf-sandbox": "flavor forward_hf_token job_timeout",- "hyperbrowser": "image_id image_name region timeout_minutes",+ "hyperbrowser": "builder_cpus builder_memory_mib builder_scratch_mib image_id image_name region timeout_minutes","vercel": ("builder_image create_timeout_sec credential_injection destroy_timeout_sec host_bootstrap host_image image ""ports post_cancel_command_timeout_sec process_cancel_grace_sec process_wait_retry_delay_sec project_name ""sandbox_lifetime_seconds task_bootstrap task_image transfer_timeout_sec"),+ "podman": "keep_containers",+ "kata": "kata_dns kata_runtime keep_containers",+ "runta": "endpoint mode request_timeout_sec startup_timeout_sec token",+ "prime": "api_key compose_host_image gpu_type region team_id timeout_minutes",+ "mosaic": "build_args build_target enable_ssh metadata persist replicas secrets ttl_seconds volume",+ "smol": (+ "api_key auto_checkpoint base_url checkpoints fork_batch_size fork_batch_window_ms gpu_mode ready_timeout_sec "+ "target"+ ),}-HARBOR_V022_ENVIRONMENT_KWARGS: dict[str, frozenset[str]] = {- mode: _HARBOR_V022_BASE_ENVIRONMENT_KWARGS | frozenset(names.split())- for mode, names in _HARBOR_V022_BACKEND_ENVIRONMENT_KWARGS.items()+HARBOR_ENVIRONMENT_KWARGS: dict[str, frozenset[str]] = {+ mode: _HARBOR_BASE_ENVIRONMENT_KWARGS | frozenset(names.split())+ for mode, names in _HARBOR_BACKEND_ENVIRONMENT_KWARGS.items()}+# An alias accepts its Harbor type's kwargs except the ones SkillEvaluator sets.+for _alias, _harbor_type in HARBOR_ENVIRONMENT_TYPE_ALIASES.items():+ HARBOR_ENVIRONMENT_KWARGS[_alias] = (+ HARBOR_ENVIRONMENT_KWARGS[_harbor_type] - HARBOR_ENVIRONMENT_ALIAS_KWARGS[_alias].keys()+ )ENV_MODE_LOCAL = "local"DEFAULT_ENV_MODE = "docker"diff --git a/src/skillevaluator/utils/redaction.py b/src/skillevaluator/utils/redaction.pyindex e4b19d73..c02b2a8f 100644--- a/src/skillevaluator/utils/redaction.py+++ b/src/skillevaluator/utils/redaction.py@@ -227,6 +227,21 @@ def credential_uri_secret_values(value: str, *, allow_schemeless: bool = False)return {item for item in protected if item}+def _redact_unterminated_private_key(text: str) -> str:+ """Redact from the first private-key header with no later ``-----END `` to the end of the text."""+ # Same result as substituting ``HEADER(?![\s\S]*-----END )[\s\S]*\Z``, whose+ # lookahead rescanned the rest of the text from every header. A header qualifies+ # when the last "-----END " in the text starts before the header ends.+ last_end = text.rfind("-----END ")+ match = _PRIVATE_KEY_HEADER_RE.search(text)+ while match is not None:+ if match.end() > last_end:+ return f"{text[: match.start()]}private-key-<redacted>"+ # Headers can overlap ("...PRIVATE KEY-----BEGIN ..."), so resume inside this one.+ match = _PRIVATE_KEY_HEADER_RE.search(text, match.start() + 1)+ return text++def redact_sensitive_text(value: str, *, max_len: int | None = None) -> str:"""Best-effort masking for credentials before writing logs or artifacts."""out = value@@ -234,6 +249,7 @@ def redact_sensitive_text(value: str, *, max_len: int | None = None) -> str:# or header rule can consume only its BEGIN delimiter and orphan the body.for pattern, replacement in _PEM_REDACTIONS:out = pattern.sub(replacement, out)+ out = _redact_unterminated_private_key(out)if "://" in out:out = _CREDENTIAL_URI_USERINFO_RE.sub(r"\g<scheme><redacted>@", out)out = _AUTH_HEADER_RE.sub(_redact_auth_header, out)diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.jsonindex bcc42942..d51f092a 100644--- a/tests/golden/cli_surface.json+++ b/tests/golden/cli_surface.json@@ -269,12 +269,9 @@"cwsandbox","wandb","use-computer",- "cua-cloud","blaxel",- "opensandbox","beam","skypilot",- "hf-sandbox","hyperbrowser","vercel","local"@@ -357,12 +354,9 @@"cwsandbox","wandb","use-computer",- "cua-cloud","blaxel",- "opensandbox","beam","skypilot",- "hf-sandbox","hyperbrowser","vercel","local"@@ -664,12 +658,9 @@"cwsandbox","wandb","use-computer",- "cua-cloud","blaxel",- "opensandbox","beam","skypilot",- "hf-sandbox","hyperbrowser","vercel","local"@@ -1531,332 +1522,6 @@"param_type": "option","type": "text"},- {- "default": "False",- "is_flag": true,- "name": "fail_fast",- "opts": [- "--fail-fast"- ],- "param_type": "option",- "type": "boolean"- },- {- "default": "False",- "is_flag": true,- "name": "continue_on_failure",- "opts": [- "--continue-on-failure",- "-c"- ],- "param_type": "option",- "type": "boolean"- },- {- "default": "False",- "is_flag": true,- "name": "llm",- "opts": [- "--llm",- "--tier1-llm"- ],- "param_type": "option",- "secondary_opts": [- "--no-llm",- "--no-tier1-llm"- ],- "type": "boolean"- },- {- "default": "False",- "is_flag": true,- "name": "llm_verify",- "opts": [- "--llm-verify"- ],- "param_type": "option",- "type": "boolean"- },- {- "default": "70",- "name": "min_score",- "opts": [- "--min-score"- ],- "param_type": "option",- "type": "integer"- },- {- "name": "profile",- "opts": [- "--profile"- ],- "param_type": "option",- "type": "text"- },- {- "default": "False",- "is_flag": true,- "name": "external",- "opts": [- "--external"- ],- "param_type": "option",- "type": "boolean"- },- {- "name": "policy_path",- "opts": [- "--policy"- ],- "param_type": "option",- "type": "file"- },- {- "default": "True",- "is_flag": true,- "name": "dedup",- "opts": [- "--dedup",- "--tier2"- ],- "param_type": "option",- "secondary_opts": [- "--no-dedup",- "--no-tier2"- ],- "type": "boolean"- },- {- "is_flag": true,- "name": "block_on_dedup",- "opts": [- "--block-on-dedup"- ],- "param_type": "option",- "secondary_opts": [- "--no-block-on-dedup"- ],- "type": "boolean"- },- {- "default": "False",- "is_flag": true,- "name": "agent_eval",- "opts": [- "--agent-eval",- "--tier3"- ],- "param_type": "option",- "type": "boolean"- },- {- "is_flag": true,- "name": "block_on_agent_eval",- "opts": [- "--block-on-agent-eval"- ],- "param_type": "option",- "secondary_opts": [- "--no-block-on-agent-eval"- ],- "type": "boolean"- },- {- "default": "False",- "is_flag": true,- "name": "autopilot",- "opts": [- "--autopilot"- ],- "param_type": "option",- "type": "boolean"- },- {- "default": "codex",- "name": "agents",- "opts": [- "--agents",- "-a"- ],- "param_type": "option",- "type": "text"- },- {- "choices": [- "docker",- "daytona",- "e2b",- "modal",- "runloop",- "langsmith",- "ec2",- "gke",- "ack",- "openshift",- "novita",- "apple-container",- "singularity",- "islo",- "tensorlake",- "cwsandbox",- "wandb",- "use-computer",- "cua-cloud",- "blaxel",- "opensandbox",- "beam",- "skypilot",- "hf-sandbox",- "hyperbrowser",- "vercel",- "local"- ],- "default": "docker",- "name": "env_mode",- "opts": [- "--env-mode"- ],- "param_type": "option"- },- {- "multiple": true,- "name": "environment_kwarg",- "opts": [- "--ek",- "--environment-kwarg"- ],- "param_type": "option",- "type": "text"- },- {- "default": "False",- "is_flag": true,- "name": "skip_baseline",- "opts": [- "--skip-baseline"- ],- "param_type": "option",- "type": "boolean"- },- {- "name": "n_concurrent",- "opts": [- "--n-concurrent"- ],- "param_type": "option",- "type": "integer"- },- {- "name": "max_agents",- "opts": [- "--max-agents"- ],- "param_type": "option",- "type": "integer"- },- {- "name": "n_attempts",- "opts": [- "--n-attempts"- ],- "param_type": "option",- "type": "integer"- },- {- "name": "pass_threshold",- "opts": [- "--pass-threshold"- ],- "param_type": "option",- "type": "float"- },- {- "is_flag": true,- "name": "stop_on_pass",- "opts": [- "--stop-on-pass"- ],- "param_type": "option",- "secondary_opts": [- "--no-stop-on-pass"- ],- "type": "boolean"- },- {- "name": "model",- "opts": [- "--model"- ],- "param_type": "option",- "type": "text"- },- {- "multiple": true,- "name": "agent_model",- "opts": [- "--agent-model"- ],- "param_type": "option",- "type": "text"- },- {- "choices": [- "default",- "default_plus_custom",- "custom_only"- ],- "name": "grading_mode",- "opts": [- "--grading-mode"- ],- "param_type": "option"- },- {- "name": "results_dir",- "opts": [- "--results-dir"- ],- "param_type": "option",- "type": "directory"- },- {- "multiple": true,- "name": "include_skills",- "opts": [- "--include-skills"- ],- "param_type": "option",- "type": "path"- },- {- "default": "False",- "is_flag": true,- "name": "copy_repo",- "opts": [- "--copy-repo"- ],- "param_type": "option",- "type": "boolean"- },- {- "name": "timeout_multiplier",- "opts": [- "--timeout-multiplier"- ],- "param_type": "option",- "type": "float"- },- {- "default": "False",- "is_flag": true,- "name": "harbor_keep_jobs",- "opts": [- "--harbor-keep-jobs"- ],- "param_type": "option",- "type": "boolean"- },{"choices": ["cli",@@ -2457,12 +2122,9 @@"cwsandbox","wandb","use-computer",- "cua-cloud","blaxel",- "opensandbox","beam","skypilot",- "hf-sandbox","hyperbrowser","vercel","local"@@ -2545,12 +2207,9 @@"cwsandbox","wandb","use-computer",- "cua-cloud","blaxel",- "opensandbox","beam","skypilot",- "hf-sandbox","hyperbrowser","vercel","local"@@ -3039,7 +2698,10 @@"modal","runloop","langsmith",+ "ec2","gke",+ "ack",+ "openshift","novita","apple-container","singularity",@@ -3048,6 +2710,11 @@"cwsandbox","wandb","use-computer",+ "blaxel",+ "beam",+ "skypilot",+ "hyperbrowser",+ "vercel","local"],"default": "docker",@@ -3057,6 +2724,16 @@],"param_type": "option"},+ {+ "multiple": true,+ "name": "environment_kwarg",+ "opts": [+ "--ek",+ "--environment-kwarg"+ ],+ "param_type": "option",+ "type": "text"+ },{"default": "False","is_flag": true,@@ -3549,12 +3226,9 @@"cwsandbox","wandb","use-computer",- "cua-cloud","blaxel",- "opensandbox","beam","skypilot",- "hf-sandbox","hyperbrowser","vercel","local"diff --git a/tests/test_ci_workflows.py b/tests/test_ci_workflows.pyindex ec7d115e..24baa4c7 100644--- a/tests/test_ci_workflows.py+++ b/tests/test_ci_workflows.py@@ -194,6 +194,10 @@ def test_gitleaks_synthetic_harbor_allowlists_are_exactly_scoped() -> None:r"^main-(persistent|task|scoped)-secret-[0-9]{5}$",r"^tests/test_harbor_secure_docker_environment\.py$",),+ "Synthetic cwsandbox API key used by Harbor environment contract tests": (+ "^cw-key-123456$",+ r"^tests/test_harbor_environment_contract\.py$",+ ),}for description, (regex, path) in expected.items():entry = allowlists[description]@@ -206,6 +210,37 @@ def test_gitleaks_synthetic_harbor_allowlists_are_exactly_scoped() -> None:}+def test_gitleaks_uses_event_specific_full_history_scopes() -> None:+ job = _load("security.yml")["jobs"]["gitleaks"]+ checkout = next(+ step for step in job["steps"] if step.get("uses", "").startswith("actions/checkout@")+ )+ verify = next(step for step in job["steps"] if step.get("name") == "Verify full Git checkout")+ scan = next(step for step in job["steps"] if step.get("name") == "Scan Git history")++ assert str(checkout["with"]["fetch-depth"]) == "0"+ assert 'test "$(git rev-parse --is-shallow-repository)" = "false"' in verify["run"]+ assert 'git rev-parse --verify "HEAD^{commit}"' in verify["run"]+ assert (+ "gitleaks:v8.30.0@sha256:691af3c7c5a48b16f187ce3446d5f194838f91238f27270ed36eef6359a574d9"+ in scan["run"]+ )+ scan_run = scan["run"]+ head_opts = "--full-history --diff-filter=tuxdb HEAD --"+ audit_opts = "--full-history --all --diff-filter=tuxdb --"+ assignments = re.findall(r'log_opts="([^"]+)"', scan_run)++ assert assignments == [head_opts, audit_opts]+ assert scan["shell"] == "bash"+ assert "set -euo pipefail" in scan_run+ assert 'case "$GITHUB_EVENT_NAME" in' in scan_run+ assert re.search(+ rf'pull_request\|push\)\s+log_opts="{re.escape(head_opts)}"\s+;;', scan_run+ )+ assert re.search(rf'\*\)\s+log_opts="{re.escape(audit_opts)}"\s+;;', scan_run)+ assert '--log-opts="$log_opts"' in scan_run++def test_dco_stays_unconditional_and_has_no_path_filter() -> None:dco = _load("dco.yml")@@ -231,8 +266,8 @@ def test_all_workflows_pin_every_action_to_a_commit() -> None:assert re.fullmatch(r"[^@]+@[0-9a-f]{40}", uses), uses-def test_changed_workflows_do_not_persist_checkout_credentials() -> None:- for workflow_name in ("ci.yml", "security.yml"):+def test_all_workflows_do_not_persist_checkout_credentials() -> None:+ for workflow_name in _workflow_names():checkout_steps = [step for step in _all_steps(_load(workflow_name)) if step.get("uses", "").startswith("actions/checkout@")]diff --git a/tests/test_evaluation_service.py b/tests/test_evaluation_service.pyindex 8f1f90e9..c2bb456c 100644--- a/tests/test_evaluation_service.py+++ b/tests/test_evaluation_service.py@@ -109,6 +109,13 @@ def test_engine_kwargs_excludes_skill_path() -> None:assert kwargs["env_mode"] == "docker"+def test_evaluation_options_preserves_legacy_positional_skip_baseline() -> None:+ options = EvaluationOptions(Path("/tmp/x"), "codex", "docker", True)++ assert options.skip_baseline is True+ assert options.environment_kwarg == ()++def test_evaluation_options_leave_agent_selection_to_the_provider() -> None:assert EvaluationOptions(skill_path=Path("/tmp/x")).agents is None@@ -211,6 +218,7 @@ def test_cli_validate_forwards_environment_kwargs_to_tier3(monkeypatch: pytest.Mcli,["validate",+ "--no-autopilot",str(FIXTURE),"--no-llm","--no-tier2",diff --git a/tests/test_harbor_collector_multistep_trajectory.py b/tests/test_harbor_collector_multistep_trajectory.pyindex fac85b15..ca9509f3 100644--- a/tests/test_harbor_collector_multistep_trajectory.py+++ b/tests/test_harbor_collector_multistep_trajectory.py@@ -2274,3 +2274,17 @@ def test_trajectory_redaction_masks_plural_and_nonnumeric_token_fields(tmp_path:}assert persisted["final_metrics"]["total_prompt_tokens"] == 10Trajectory.model_validate(persisted)+++ ("versions", "expected"),+ [+ (("ATIF-v1.2", "ATIF-v1.6"), "ATIF-v1.7"),+ (("ATIF-v1.7", "ATIF-v1.8"), "ATIF-v1.8"),+ (("ATIF-v1.8", None, "unexpected"), "ATIF-v1.8"),+ ],+)+def test_merged_trajectories_keep_the_newest_source_schema(versions: tuple, expected: str) -> None:+ from skillevaluator.tier3.harbor.collector import _merged_atif_schema_version++ assert _merged_atif_schema_version(*({"schema_version": version} for version in versions)) == expecteddiff --git a/tests/test_harbor_collector_runtime_failures.py b/tests/test_harbor_collector_runtime_failures.pyindex 59875daa..c590b31d 100644--- a/tests/test_harbor_collector_runtime_failures.py+++ b/tests/test_harbor_collector_runtime_failures.py@@ -16,7 +16,10 @@ import pytestfrom skillevaluator.evaluation.tier3_report import render_agent_eval_html_reportfrom skillevaluator.tier3.harbor import collector as collector_modulefrom skillevaluator.tier3.harbor import report_data-from skillevaluator.tier3.harbor.collector import collect_harbor_results+from skillevaluator.tier3.harbor.collector import (+ _agent_runtime_failure_reason,+ collect_harbor_results,+)from skillevaluator.tier3.harbor.metrics import DEFAULT_METRIC_SET, DEFAULT_METRICS_HARBOR_022_AGENT_RUNTIME_EXCEPTION_TYPES = (@@ -656,6 +659,34 @@ def test_verifier_exception_does_not_scan_plain_agent_transcript(tmp_path: Path)assert _agent_runtime_failure_reason(trial_dir) == ""+def test_step_verifier_exception_does_not_scan_plain_agent_transcript(tmp_path: Path) -> None:+ """Correct agent prose must not turn a step verifier failure into an agent failure."""+ trial_dir = tmp_path / "case-001__attempt"+ agent_dir = trial_dir / "agent"+ agent_dir.mkdir(parents=True)+ (trial_dir / "result.json").write_text(+ json.dumps(+ {+ "step_results": [+ {+ "exception_info": {+ "exception_type": "VerifierError",+ "exception_message": "step verifier exited nonzero",+ }+ }+ ]+ }+ ),+ encoding="utf-8",+ )+ (agent_dir / "opencode.txt").write_text(+ "Troubleshooting: an invalid credential can produce 401 Unauthorized.\n",+ encoding="utf-8",+ )++ assert _agent_runtime_failure_reason(trial_dir) == ""++def test_errored_job_stats_suppress_rewards_without_trial_exception(tmp_path: Path) -> None:"""Aggregate Harbor failure state wins even when a trial reward looks valid."""jobs_dir = tmp_path / "jobs"@@ -1081,6 +1112,37 @@ def test_harbor_022_multistep_result_without_root_aggregate_is_not_reconstructedassert "statistics account for 0/1 completed trials" in " ".join(condition["execution_errors"])+def test_job_statistics_failure_names_the_recorded_step_exception(tmp_path: Path) -> None:+ jobs_dir = tmp_path / "jobs"+ job_dir = jobs_dir / "demo-opencode-with"+ trial_name = _write_actual_harbor_022_result(+ job_dir,+ verifier_mode="missing",+ step_rewards=(1.0,),+ step_exception_type="VerifierOutputParseError",+ )++ results = collect_harbor_results(+ skill_name="demo",+ agents=["opencode"],+ output_dir=tmp_path / "results",+ jobs_dir=jobs_dir,+ skip_baseline=True,+ expected_cases=1,+ expected_case_ids=["case-001"],+ expected_trials=1,+ )++ condition = results["agents"]["opencode"]["conditions"]["with_skill"]+ errors = " ".join(condition["execution_errors"])+ assert results["execution_status"] == "failed"+ assert condition["scored_attempts"] == 0+ assert (+ "statistics account for 0/1 completed trials; "+ f"trial {trial_name} recorded VerifierOutputParseError: provider step operation failed"+ ) in errors++def test_harbor_022_complete_envelope_accepts_final_reward_strategy(tmp_path: Path) -> None:jobs_dir = tmp_path / "jobs"job_dir = jobs_dir / "demo-opencode-with"@@ -1682,16 +1744,35 @@ def test_result_derived_case_ids_exercise_partial_pairing_through_collector(tmp_assert "mcnemar_exact" not in paired-def test_legacy_result_identity_prefers_task_name_without_trusted_selector_mapping() -> None:+def test_legacy_result_identity_prefers_task_path_without_trusted_selector_mapping() -> None:result = {"task_name": "publisher/logical-native-id","task_id": {"path": "/trusted/staging/native-selector"},"config": {"task": {"path": "/trusted/staging/native-selector"}},}+ # Without a runner-owned selector map, Harbor's persisted task directory is the+ # canonical identity; repository-prefixed task names are only a fallback.+ assert collector_module._entry_id_from_harbor_result(result) == "native-selector"+++def test_legacy_result_identity_falls_back_to_task_name_without_task_path() -> None:+ result = {"task_name": "publisher/logical-native-id"}+assert collector_module._entry_id_from_harbor_result(result) == "logical-native-id"+def test_trusted_selector_mapping_ignores_task_name_and_unmapped_paths() -> None:+ result = {+ "task_name": "publisher/victim-case",+ "task_id": {"path": "/trusted/staging/native-selector"},+ "config": {"task": {"path": "/trusted/staging/native-selector"}},+ }++ assert collector_module._entry_id_from_harbor_result(result, {"native-selector": "logical-id"}) == "logical-id"+ assert collector_module._entry_id_from_harbor_result(result, {"other-selector": "other-id"}) == ""++@pytest.mark.parametrize("separator", ["-", "_"])def test_attempt_like_legacy_identities_are_not_generated_attempt_suffixes(separator: str) -> None:reward = {@@ -2284,3 +2365,87 @@ def test_credential_shaped_trial_name_uses_collision_safe_output_alias(tmp_path:assert credential_trial not in generated_jsonassert credential_trial not in trial_dirsassert trial_dirs == ["skillevaluator-trial-collision-000001"]++[email protected]("trusted_map", [None, {"native-selector": "logical-case"}])+def test_grader_authored_reward_cannot_set_collector_identity_controls(+ tmp_path: Path,+ trusted_map: dict[str, str] | None,+) -> None:+ trial = tmp_path / "job" / "native-selector__abc1234"+ verifier_dir = trial / "verifier"+ verifier_dir.mkdir(parents=True)+ (verifier_dir / "reward.json").write_text(+ json.dumps(+ {+ "overall": 1.0,+ "entry_id": "victim-case-attempt3",+ "_authoritative_entry_id": True,+ "_result_entry_id": "victim-case",+ "_arm_suffix": "-attempt3",+ "_trusted_case_identity_unresolved": False,+ }+ ),+ encoding="utf-8",+ )+ (trial / "result.json").write_text(+ json.dumps(+ {+ "trial_name": trial.name,+ "task_id": {"path": "/trusted/staging/native-selector"},+ "config": {"task": {"path": "/trusted/staging/native-selector"}},+ }+ ),+ encoding="utf-8",+ )++ [reward] = collector_module._extract_rewards(tmp_path / "job", trusted_map)++ assert "_result_entry_id" not in reward+ assert "_arm_suffix" not in reward+ if trusted_map is None:+ # Legacy callers keep a grader-authored entry_id, but only as a+ # non-authoritative value that is canonicalized like any other.+ assert "_authoritative_entry_id" not in reward+ assert collector_module._entry_id(reward) == "victim-case"+ else:+ assert reward["entry_id"] == "logical-case"+ assert reward["_authoritative_entry_id"] is True+ assert collector_module._entry_id(reward) == "logical-case"+++ "exception_type",+ ["VerifierTimeoutError", "EnvironmentStartTimeoutError", "VerifierOutputParseError", "RewardFileNotFoundError"],+)[email protected]("multistep", [False, True])+def test_harbor_verifier_and_environment_failures_are_unscored_not_agent_failures(+ tmp_path: Path,+ exception_type: str,+ multistep: bool,+) -> None:+ jobs_dir = tmp_path / "jobs"+ job_dir = jobs_dir / "demo-opencode-with"+ _write_actual_harbor_022_result(+ job_dir,+ reward=1.0,+ exception_type=None if multistep else exception_type,+ step_rewards=(1.0, 1.0) if multistep else None,+ step_exception_type=exception_type if multistep else None,+ )++ results = collect_harbor_results(+ skill_name="demo",+ agents=["opencode"],+ output_dir=tmp_path / "results",+ jobs_dir=jobs_dir,+ skip_baseline=True,+ expected_cases=1,+ expected_case_ids=["case-001"],+ expected_trials=1,+ )++ opencode = results["agents"]["opencode"]+ assert opencode["num_trials_with"] == 0+ assert opencode["agent_runtime_failures"]["with_skill"] == []+ assert results["execution_status"] == "failed"diff --git a/tests/test_harbor_dotenv_isolation.py b/tests/test_harbor_dotenv_isolation.pynew file mode 100644index 00000000..d7a60611--- /dev/null+++ b/tests/test_harbor_dotenv_isolation.py@@ -0,0 +1,181 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Harbor processes must not read operator dotenv files or depend on the caller's directory."""++from __future__ import annotations++import json+import os+import sys+from pathlib import Path++import pytest++from skillevaluator.tier3.harbor import runner++# Replays the loaders Harbor runs: the jobs CLI loads ``<cwd>/.env.local``, while+# Harbor's registry client and LiteLLM call ``load_dotenv()`` on import.+_PROBE = """+import json+import os+import sys+from pathlib import Path++from dotenv import find_dotenv, load_dotenv++if (Path.cwd() / ".env.local").exists():+ load_dotenv(Path.cwd() / ".env.local", override=False)+load_dotenv()+load_dotenv(find_dotenv(usecwd=True))+Path(sys.argv[1]).write_text(+ json.dumps(+ {+ "cwd": str(Path.cwd()),+ "cwd_entries": sorted(path.name for path in Path.cwd().iterdir()),+ "sentinel": os.environ.get("SE_DOTENV_SENTINEL"),+ "docker_host": os.environ.get("DOCKER_HOST"),+ "dotenv_disabled": os.environ.get("PYTHON_DOTENV_DISABLED"),+ "telemetry": os.environ.get("HARBOR_TELEMETRY"),+ }+ ),+ encoding="utf-8",+)+print("Harbor job did not complete successfully: 1 errored")+sys.exit(3)+"""+++def _operator_directory(tmp_path: Path) -> Path:+ operator_dir = tmp_path / "operator"+ operator_dir.mkdir()+ for name in (".env.local", ".env"):+ (operator_dir / name).write_text(+ "SE_DOTENV_SENTINEL=leaked\nDOCKER_HOST=tcp://attacker.invalid:2375\n",+ encoding="utf-8",+ )+ return operator_dir+++def test_harbor_run_ignores_operator_dotenv_files(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ operator_dir = _operator_directory(tmp_path)+ monkeypatch.chdir(operator_dir)+ probe = tmp_path / "probe.py"+ probe.write_text(_PROBE, encoding="utf-8")+ observed = tmp_path / "observed.json"+ monkeypatch.setattr(+ runner, "build_harbor_run_command", lambda **_kwargs: [sys.executable, str(probe), str(observed)]+ )++ ok, detail = runner._run_harbor(+ dataset=tmp_path / "dataset",+ agent="codex",+ job_name="dotenv-isolation",+ env_mode="docker",+ model="model",+ jobs_dir=tmp_path / "jobs",+ run_env={+ "DOCKER_HOST": "unix:///operator/docker.sock",+ "FEATURE_FLAG": "1",+ "HARBOR_TELEMETRY": "1",+ "PYTHON_DOTENV_DISABLED": "0",+ },+ n_attempts=1,+ n_concurrent=1,+ timeout_multiplier=1.0,+ override_cpus=None,+ override_memory_mb=None,+ override_storage_mb=None,+ )++ assert ok is False+ # Short child values are not exact secrets, so counts survive redaction.+ assert "1 errored" in detail+ child = json.loads(observed.read_text(encoding="utf-8"))+ assert child["sentinel"] is None+ assert child["docker_host"] == "unix:///operator/docker.sock"+ assert child["dotenv_disabled"] == "1"+ assert child["telemetry"] == "0"+ assert Path(child["cwd"]) != operator_dir+ assert child["cwd_entries"] == []+ assert not Path(child["cwd"]).exists()+++def test_disabled_dotenv_blocks_files_even_in_the_operator_directory(tmp_path: Path) -> None:+ operator_dir = _operator_directory(tmp_path)+ probe = tmp_path / "probe.py"+ probe.write_text(_PROBE, encoding="utf-8")+ observed = tmp_path / "observed.json"++ result = runner._run_bounded_harbor_process(+ [sys.executable, str(probe), str(observed)],+ env={"PATH": os.environ.get("PATH", "")},+ cwd=operator_dir,+ stdin_text=None,+ timeout_seconds=60,+ max_output_bytes=64 * 1024,+ diagnostic_tail_chars=4096,+ secret_values=set(),+ )++ assert result.returncode == 3+ child = json.loads(observed.read_text(encoding="utf-8"))+ assert child["sentinel"] is None+ assert child["docker_host"] is None+++def test_harbor_command_and_environment_anchor_relative_host_paths(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ monkeypatch.chdir(tmp_path)+ command = runner.build_harbor_run_command(+ dataset_path="relative/dataset",+ agent="codex",+ job_name="paths",+ env_mode="ec2",+ jobs_dir=Path("relative/jobs"),+ environment_kwargs={+ "region": "us-west-2",+ "ssh_key_path": "keys/id_ed25519",+ "ssh_known_hosts_path": "~/.ssh/known_hosts",+ },+ )++ assert command[command.index("-p") + 1] == str(tmp_path / "relative" / "dataset")+ assert command[command.index("--jobs-dir") + 1] == str(tmp_path / "relative" / "jobs")+ encoded = [command[index + 1] for index, value in enumerate(command) if value == "--ek"]+ assert f"ssh_key_path={json.dumps(str(tmp_path / 'keys' / 'id_ed25519'))}" in encoded+ assert 'ssh_known_hosts_path="~/.ssh/known_hosts"' in encoded++ launch_env = runner._harbor_launch_environment(+ {+ "KUBECONFIG": os.pathsep.join(["kube/config", "~/.kube/config", "/etc/kube/config"]),+ "TMPDIR": "scratch",+ "DOCKER_HOST": "unix:///var/run/docker.sock",+ }+ )+ assert launch_env["KUBECONFIG"].split(os.pathsep) == [+ str(tmp_path / "kube" / "config"),+ "~/.kube/config",+ "/etc/kube/config",+ ]+ assert launch_env["TMPDIR"] == str(tmp_path / "scratch")+ assert launch_env["DOCKER_HOST"] == "unix:///var/run/docker.sock"++[email protected](("installed", "rejected"), [("1.1.1", True), ("1.2.0", False), ("1.2.2", False)])+def test_prerequisites_require_dotenv_disable_support(+ monkeypatch: pytest.MonkeyPatch,+ installed: str,+ rejected: bool,+) -> None:+ import importlib.metadata++ monkeypatch.setattr(importlib.metadata, "version", lambda _name: installed)++ error = runner._python_dotenv_prerequisite_error()++ assert (error is not None) is rejected+ if rejected:+ assert "1.2.0" in errordiff --git a/tests/test_harbor_environment_contract.py b/tests/test_harbor_environment_contract.pynew file mode 100644index 00000000..c85293cb--- /dev/null+++ b/tests/test_harbor_environment_contract.py@@ -0,0 +1,137 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""SkillEvaluator's environment surface over the pinned Harbor release."""++from __future__ import annotations++import inspect+import json+from pathlib import Path++import pytest++from skillevaluator.tier3.harbor import runner+from skillevaluator.tier3.harbor.runner import build_harbor_run_command+++def _environment_kwargs(command: list[str]) -> list[str]:+ return [command[index + 1] for index, value in enumerate(command) if value == "--ek"]+++def test_wandb_runs_as_harbor_cwsandbox_with_wandb_auth() -> None:+ command = build_harbor_run_command(+ dataset_path="/tmp/dataset",+ agent="opencode",+ job_name="wandb",+ env_mode="wandb",+ environment_kwargs={"max_lifetime_seconds": 600},+ )++ assert command[command.index("--env") + 1] == "cwsandbox"+ # SkillEvaluator's alias kwarg comes after every operator kwarg.+ assert _environment_kwargs(command) == ["max_lifetime_seconds=600", f"auth={json.dumps('wandb')}"]++[email protected]("env_mode", ["cwsandbox", "wandb"])+def test_operators_cannot_choose_cwsandbox_auth(env_mode: str) -> None:+ with pytest.raises(ValueError, match="auth"):+ build_harbor_run_command(+ dataset_path="/tmp/dataset",+ agent="opencode",+ job_name="auth",+ env_mode=env_mode,+ environment_kwargs={"auth": "wandb"},+ )++[email protected]("env_mode", ["daytona", "modal", "tensorlake", "beam"])[email protected]("name", ["stream", "enable_environment_dir_upload"])+def test_harbor_stream_and_upload_controls_are_reserved(env_mode: str, name: str) -> None:+ with pytest.raises(ValueError, match="reserved for Harbor runtime policy"):+ build_harbor_run_command(+ dataset_path="/tmp/dataset",+ agent="opencode",+ job_name="reserved",+ env_mode=env_mode,+ environment_kwargs={name: False},+ )+++def test_backend_kwargs_track_the_pinned_harbor_release() -> None:+ with pytest.raises(ValueError, match=r"Harbor 0\.24\.0 environment 'modal'.*modal_sandbox_v2"):+ build_harbor_run_command(+ dataset_path="/tmp/dataset",+ agent="opencode",+ job_name="modal",+ env_mode="modal",+ environment_kwargs={"modal_sandbox_v2": True},+ )+ hyperbrowser = build_harbor_run_command(+ dataset_path="/tmp/dataset",+ agent="opencode",+ job_name="hyperbrowser",+ env_mode="hyperbrowser",+ environment_kwargs={"builder_cpus": 4},+ )+ assert "builder_cpus=4" in _environment_kwargs(hyperbrowser)+ tensorlake = build_harbor_run_command(+ dataset_path="/tmp/dataset",+ agent="opencode",+ job_name="tensorlake",+ env_mode="tensorlake",+ environment_kwargs={"dind_image": "docker:dind"},+ )+ assert f"dind_image={json.dumps('docker:dind')}" in _environment_kwargs(tensorlake)+++def test_cwsandbox_prerequisites_require_sdk_and_api_key(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(runner.importlib.util, "find_spec", lambda name: None if name == "cwsandbox" else object())+ assert "harbor[cwsandbox]==0.24.0" in runner._cwsandbox_prerequisite_errors("cwsandbox")[0]++ monkeypatch.setattr(runner.importlib.util, "find_spec", lambda _name: object())+ monkeypatch.delenv("CWSANDBOX_API_KEY", raising=False)+ assert runner._cwsandbox_prerequisite_errors("cwsandbox") == [+ "Harbor environment 'cwsandbox' requires CWSANDBOX_API_KEY."+ ]+ monkeypatch.setenv("CWSANDBOX_API_KEY", "cw-key-123456")+ assert runner._cwsandbox_prerequisite_errors("cwsandbox") == []+ assert runner._cwsandbox_prerequisite_errors("daytona") == []+++def test_wandb_prerequisites_accept_api_key_or_netrc(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ monkeypatch.setattr(runner.importlib.util, "find_spec", lambda name: None if name == "wandb" else object())+ assert "wandb" in runner._cwsandbox_prerequisite_errors("wandb")[0]++ monkeypatch.setattr(runner.importlib.util, "find_spec", lambda _name: object())+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))+ monkeypatch.delenv("WANDB_API_KEY", raising=False)+ monkeypatch.delenv("NETRC", raising=False)+ assert "WANDB_API_KEY" in runner._cwsandbox_prerequisite_errors("wandb")[0]+ (tmp_path / ".netrc").write_text("machine api.wandb.ai\n", encoding="utf-8")+ assert runner._cwsandbox_prerequisite_errors("wandb") == []+++def test_wandb_preflight_uses_the_cwsandbox_environment_type(monkeypatch: pytest.MonkeyPatch) -> None:+ from harbor.environments.factory import EnvironmentFactory+ from harbor.models.environment_type import EnvironmentType++ preflights: list[object] = []+ monkeypatch.setattr(runner, "_cwsandbox_prerequisite_errors", lambda _env_mode: [])+ monkeypatch.setattr(+ EnvironmentFactory, "run_preflight", lambda environment_type, **_kwargs: preflights.append(environment_type)+ )++ assert runner._check_prerequisites(env_mode="wandb", agents=["opencode"]) == []+ assert preflights == [EnvironmentType.CWSANDBOX]+++def test_pinned_harbor_loads_env_local_from_its_working_directory() -> None:+ """Document why every Harbor launch uses an evaluator-owned working directory."""+ from importlib.metadata import version++ from harbor.cli import jobs++ assert ".env.local" in inspect.getsource(jobs)+ major, minor = (int(part) for part in version("python-dotenv").split(".")[:2])+ assert (major, minor) >= (1, 2)diff --git a/tests/test_harbor_local_mode.py b/tests/test_harbor_local_mode.pyindex ce556c0e..d6e94b9f 100644--- a/tests/test_harbor_local_mode.py+++ b/tests/test_harbor_local_mode.py@@ -447,10 +447,29 @@ def test_local_is_a_registered_env_mode() -> None:assert "local" in HARBOR_ENV_MODES-def test_registered_native_env_modes_match_pinned_harbor_release() -> None:+def test_registered_native_env_modes_are_supported_subset_of_pinned_harbor_release() -> None:from harbor.models.environment_type import EnvironmentType- assert frozenset(environment.value for environment in EnvironmentType) == HARBOR_NATIVE_ENV_MODES+ from skillevaluator.tier3_environments import harbor_environment_type++ harbor_modes = frozenset(environment.value for environment in EnvironmentType)+ harbor_types = frozenset(harbor_environment_type(mode) for mode in HARBOR_NATIVE_ENV_MODES)++ assert harbor_modes > harbor_types+ # Each SkillEvaluator mode maps to a pinned Harbor type; only aliases are not types themselves.+ assert HARBOR_NATIVE_ENV_MODES - harbor_modes == {"wandb"}+ # Harbor backends SkillEvaluator does not expose until it can project task bundles safely.+ assert harbor_modes - harbor_types == {+ "cua-cloud",+ "opensandbox",+ "hf-sandbox",+ "podman",+ "kata",+ "runta",+ "prime",+ "mosaic",+ "smol",+ }def test_build_command_uses_unified_flags_for_local_imports() -> None:@@ -3991,6 +4010,15 @@ def test_output_redaction_balances_component_names_and_legacy_fallback(assert callback_output == value[email protected]("name", ["BASH_ENV", "ENV", "LD_PRELOAD", "PYTHONPATH"])+def test_empty_runtime_injection_env_is_dropped(name: str) -> None:+ assert SkillEvaluatorLocalEnvironment._filter_command_env({name: ""}, protected=set()) == {}+++def test_unblocked_empty_runtime_env_is_preserved() -> None:+ assert SkillEvaluatorLocalEnvironment._filter_command_env({"EXAMPLE": ""}, protected=set()) == {"EXAMPLE": ""}++@pytest.mark.skipif(os.name == "nt", reason=_NATIVE_WINDOWS_LOCAL_REASON)def test_persistent_runtime_injection_env_is_blocked_before_launcher(tmp_path: Path) -> None:environment = _local_environment(tmp_path, persistent_env={"NODE_OPTIONS": "--require=/tmp/attack.js"})@@ -5725,8 +5753,9 @@ def test_ack_subprocess_probe_uses_exact_harbor_environment_and_stdin(subprocess_env=child_env,)- assert captured["env"] == child_env+ assert captured["env"] == {**child_env, "HARBOR_TELEMETRY": "0", "PYTHON_DOTENV_DISABLED": "1"}assert "ALIBABA_CLOUD_ACCESS_KEY_ID" not in captured["env"]+ assert Path(str(captured["cwd"])) != Path.cwd()assert json.loads(str(captured["input"])) == {"namespace": "skill-evals","context": "production",@@ -5740,7 +5769,7 @@ def test_ack_subprocess_probe_uses_exact_harbor_environment_and_stdin(assert captured["start_new_session"] is (os.name == "posix")command = captured["command"]assert isinstance(command, list)- assert command[:2] == [sys.executable, "-c"]+ assert command[:3] == [sys.executable, "-P", "-c"]assert "production" not in " ".join(command)assert "/config/ack" not in " ".join(command)@@ -5909,3 +5938,22 @@ def test_docker_prerequisite_accepts_compose_v2(monkeypatch: pytest.MonkeyPatch))assert _check_prerequisites(env_mode="docker", agents=[]) == []+++def test_local_nvidia_opencode_config_disables_oauth_for_remote_mcp(monkeypatch: pytest.MonkeyPatch) -> None:+ from types import SimpleNamespace++ agent = object.__new__(SkillEvaluatorLocalOpenCode)+ agent.mcp_servers = [+ SimpleNamespace(name="remote-tools", transport="streamable-http", url="https://tools.example/mcp"),+ SimpleNamespace(name="local-tools", transport="stdio", command="tool-server", args=["--stdio"]),+ ]+ agent._opencode_config = {}+ monkeypatch.setenv("OPENAI_BASE_URL", "https://integrate.api.nvidia.com/v1")++ command = agent._nvidia_provider_config_command("nvidia/model")++ payload = shlex.split(command.split("&&", 1)[1])[1]+ config = json.loads(payload)+ assert config["mcp"]["remote-tools"] == {"type": "remote", "url": "https://tools.example/mcp", "oauth": False}+ assert config["mcp"]["local-tools"] == {"type": "local", "command": ["tool-server", "--stdio"]}diff --git a/tests/test_harbor_runner_environment.py b/tests/test_harbor_runner_environment.pyindex b2989891..3a3a4b5c 100644--- a/tests/test_harbor_runner_environment.py+++ b/tests/test_harbor_runner_environment.py@@ -183,7 +183,10 @@ def test_skill_config_cannot_alias_operator_owned_credentials() -> None:monkeypatch.setenv(source_name, "operator-secret")- resolved, errors = runner._resolve_runtime_env({"INNOCENT_NAME": f"${{{source_name}}}"})+ resolved, errors = runner._resolve_runtime_env(+ {"INNOCENT_NAME": f"${{{source_name}}}"},+ env_mode="docker",+ )assert resolved == {}assert errors and "operator-owned" in errors[0]@@ -206,7 +209,7 @@ def test_skill_config_cannot_stage_conventional_unlisted_secret_names(source_name = value.removeprefix("${").removesuffix("}")monkeypatch.setenv(source_name, "synthetic-secret")- resolved, errors = runner._resolve_runtime_env(runtime_env)+ resolved, errors = runner._resolve_runtime_env(runtime_env, env_mode="docker")assert resolved == {}assert errors@@ -221,7 +224,10 @@ def test_skill_config_cannot_alias_judge_model_with_default_expansion() -> None:monkeypatch.setenv(source_name, "operator-model")- resolved, errors = runner._resolve_runtime_env({"INNOCENT_NAME": f"${{{source_name}:-skill-fallback}}"})+ resolved, errors = runner._resolve_runtime_env(+ {"INNOCENT_NAME": f"${{{source_name}:-skill-fallback}}"},+ env_mode="docker",+ )assert resolved == {}assert errors and "operator-owned" in errors[0]@@ -239,7 +245,10 @@ def test_skill_config_cannot_alias_judge_model_with_default_expansion(],)def test_skill_config_cannot_control_evaluator_or_judge_routing(name: str) -> None:- resolved, errors = runner._resolve_runtime_env({name: "https://attacker.example/v1"})+ resolved, errors = runner._resolve_runtime_env(+ {name: "https://attacker.example/v1"},+ env_mode="docker",+ )assert resolved == {}assert errors and "host process" in errors[0]@@ -343,7 +352,10 @@ def test_runtime_env_rejects_operator_owned_windows_style_variable_references() -> None:monkeypatch.setenv(source_name, "host-value")- resolved, errors = runner._resolve_runtime_env({"SAFE_ALIAS": f"%{source_name}%"})+ resolved, errors = runner._resolve_runtime_env(+ {"SAFE_ALIAS": f"%{source_name}%"},+ env_mode="docker",+ )assert resolved == {}assert errors and source_name in errors[0]@@ -361,13 +373,36 @@ def test_runtime_env_preserves_platform_expansion_for_non_owned_percent_referencmonkeypatch.setattr(runner.os.path, "expandvars", expandvars)- resolved, errors = runner._resolve_runtime_env({"SAFE_ALIAS": "%HOST_AGENT_LABEL%"})+ resolved, errors = runner._resolve_runtime_env(+ {"SAFE_ALIAS": "%HOST_AGENT_LABEL%"},+ env_mode="docker",+ )assert errors == []assert resolved == {"SAFE_ALIAS": "host-value"}assert expanded == ["%HOST_AGENT_LABEL%"]+def test_runtime_env_allows_mode_unrelated_backend_name() -> None:+ resolved, errors = runner._resolve_runtime_env(+ {"API_HOST": "ordinary-task-value"},+ env_mode="docker",+ )++ assert errors == []+ assert resolved == {"API_HOST": "ordinary-task-value"}+++def test_runtime_env_rejects_selected_backend_control_name() -> None:+ resolved, errors = runner._resolve_runtime_env(+ {"API_HOST": "attacker-controlled"},+ env_mode="beam",+ )++ assert resolved == {}+ assert errors == ["harbor.runtime_env.API_HOST controls the host process and is not allowed"]++def test_custom_only_does_not_force_the_standard_judge_model_into_custom_verifiers() -> None:provider_env = {"LLM_JUDGE_MODEL": "legacy-judge-model",@@ -1741,14 +1776,6 @@ def test_harbor_backend_environment_allowlist_covers_every_native_022_mode() ->"USE_COMPUTER_SNAPSHOT","USE_COMPUTER_VERSION",},- "cua-cloud": {- "CUA_BASE_URL",- "CUA_CLIENT_ID",- "CUA_CLIENT_SECRET",- "CUA_CLOUD_NAMESPACE",- "CUA_CLOUD_STARTUP_COMMAND",- "CUA_TOKEN_URL",- },"blaxel": {"BL_API_KEY","BL_API_VERSION",@@ -1757,7 +1784,6 @@ def test_harbor_backend_environment_allowlist_covers_every_native_022_mode() ->"BL_REGION","BL_WORKSPACE",},- "opensandbox": {"OPENSANDBOX_API_KEY", "OPENSANDBOX_DOMAIN"},"beam": {"API_HOST","API_PORT",@@ -1792,7 +1818,6 @@ def test_harbor_backend_environment_allowlist_covers_every_native_022_mode() ->"SKYPILOT_SERVICE_ACCOUNT_TOKEN","SSH_AUTH_SOCK",},- "hf-sandbox": {"HF_ENDPOINT", "HF_HOME", "HF_TOKEN", "HF_TOKEN_PATH", "HUGGING_FACE_HUB_TOKEN"},"hyperbrowser": {"COMPOSE_ANSI","COMPOSE_HTTP_TIMEOUT",@@ -2014,14 +2039,11 @@ def test_skip_baseline_keeps_normalized_skill_owned_setup_enabled(("novita", "NOVITA_SANDBOX_URL"),("singularity", "APPTAINER_AUTHFILE"),("tensorlake", "TENSORLAKE_ORGANIZATION_ID"),- ("cua-cloud", "CUA_CLIENT_SECRET"),("blaxel", "BL_API_KEY"),- ("opensandbox", "OPENSANDBOX_DOMAIN"),("beam", "BEAM_TOKEN"),("beam", "API_HOST"),("skypilot", "SKYPILOT_API_SERVER_ENDPOINT"),("skypilot", "DOCKER_CONFIG"),- ("hf-sandbox", "HF_TOKEN_PATH"),("hyperbrowser", "HYPERBROWSER_API_KEY"),("hyperbrowser", "DOCKER_HOST"),("wandb", "NETRC"),@@ -2087,7 +2109,10 @@ def test_config_declared_substitution_is_resolved_without_leaking_source_variabl"environ",{"PATH": "/usr/bin", "HOME": "/home/test", "HOST_AGENT_LABEL": "runtime-value", "UNRELATED_SECRET": "no"},)- configured_runtime_env, errors = runner._resolve_runtime_env({"AGENT_LABEL": "${HOST_AGENT_LABEL}"})+ configured_runtime_env, errors = runner._resolve_runtime_env(+ {"AGENT_LABEL": "${HOST_AGENT_LABEL}"},+ env_mode="docker",+ )provider = _provider()environment = runner._harbor_subprocess_environment(@@ -2134,7 +2159,10 @@ def test_runtime_env_rejects_host_process_control_names() -> None:)for name in unsafe_names:- resolved, errors = runner._resolve_runtime_env({name: "attacker-controlled"})+ resolved, errors = runner._resolve_runtime_env(+ {name: "attacker-controlled"},+ env_mode="docker",+ )assert name not in resolvedassert any(name in error and "host process" in error for error in errors)diff --git a/tests/test_harbor_runner_status.py b/tests/test_harbor_runner_status.pyindex d37d1323..2ef941df 100644--- a/tests/test_harbor_runner_status.py+++ b/tests/test_harbor_runner_status.py@@ -126,6 +126,7 @@ def test_bounded_harbor_process_preserves_exit_and_combined_diagnostic_tail(result = runner._run_bounded_harbor_process([sys.executable, "-c", script],env=dict(os.environ),+ cwd=Path.cwd(),stdin_text=None,timeout_seconds=5,max_output_bytes=4096,@@ -146,6 +147,7 @@ def test_bounded_harbor_process_redacts_before_retaining_diagnostic_tail() -> Noresult = runner._run_bounded_harbor_process([sys.executable, "-c", script],env=dict(os.environ),+ cwd=Path.cwd(),stdin_text=None,timeout_seconds=5,max_output_bytes=4096,@@ -169,6 +171,7 @@ def test_bounded_harbor_process_drops_partial_secret_at_output_limit() -> None:result = runner._run_bounded_harbor_process([sys.executable, "-c", script],env=dict(os.environ),+ cwd=Path.cwd(),stdin_text=None,timeout_seconds=5,max_output_bytes=len((prefix + accepted_secret_prefix).encode()),@@ -188,6 +191,7 @@ def test_bounded_harbor_process_timeout_includes_blocked_stdin_delivery() -> Nonrunner._run_bounded_harbor_process([sys.executable, "-c", "import time; time.sleep(30)"],env=dict(os.environ),+ cwd=Path.cwd(),stdin_text="x" * (1024 * 1024),timeout_seconds=0.1,max_output_bytes=4096,@@ -205,6 +209,7 @@ def test_bounded_harbor_process_contains_tree_after_stdin_delivery_error() -> Norunner._run_bounded_harbor_process([sys.executable, "-c", "import time; time.sleep(30)"],env=dict(os.environ),+ cwd=Path.cwd(),stdin_text="\udcff",timeout_seconds=5,max_output_bytes=4096,@@ -223,6 +228,7 @@ def test_bounded_harbor_process_timeout_preserves_redacted_diagnostic_tail() ->runner._run_bounded_harbor_process([sys.executable, "-c", script],env=dict(os.environ),+ cwd=Path.cwd(),stdin_text=None,timeout_seconds=0.1,max_output_bytes=4096,@@ -243,6 +249,7 @@ def test_bounded_harbor_process_redacts_secret_created_by_timeout_message() -> Nrunner._run_bounded_harbor_process([sys.executable, "-c", "import time; time.sleep(30)"],env=dict(os.environ),+ cwd=Path.cwd(),stdin_text=None,timeout_seconds=0.1,max_output_bytes=4096,@@ -289,6 +296,7 @@ def test_bounded_harbor_process_owns_cleanup_during_thread_start(runner._run_bounded_harbor_process([sys.executable, "-c", "import time; time.sleep(30)"],env=dict(os.environ),+ cwd=Path.cwd(),stdin_text="payload",timeout_seconds=5,max_output_bytes=4096,@@ -341,6 +349,7 @@ def test_bounded_harbor_process_failure_reaps_descendants(runner._run_bounded_harbor_process([sys.executable, "-c", parent_script],env=dict(os.environ),+ cwd=Path.cwd(),stdin_text=None,timeout_seconds=1,max_output_bytes=4096,@@ -351,6 +360,7 @@ def test_bounded_harbor_process_failure_reaps_descendants(result = runner._run_bounded_harbor_process([sys.executable, "-c", parent_script],env=dict(os.environ),+ cwd=Path.cwd(),stdin_text=None,timeout_seconds=5,max_output_bytes=4096,@@ -407,6 +417,7 @@ def test_bounded_harbor_process_failure_reaps_windows_descendants(runner._run_bounded_harbor_process([sys.executable, "-c", parent_script],env=dict(os.environ),+ cwd=Path.cwd(),stdin_text=None,timeout_seconds=1,max_output_bytes=4096,@@ -417,6 +428,7 @@ def test_bounded_harbor_process_failure_reaps_windows_descendants(result = runner._run_bounded_harbor_process([sys.executable, "-c", parent_script],env=dict(os.environ),+ cwd=Path.cwd(),stdin_text=None,timeout_seconds=5,max_output_bytes=4096,@@ -1562,11 +1574,16 @@ def test_run_harbor_defers_to_harbor_phase_timeouts_without_outer_deadline(captured: dict[str, object] = {}monkeypatch.setattr(runner, "build_harbor_run_command", lambda **_kwargs: ["harbor", "run"])- def completed_run(command: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:+ def completed_run(command: list[str], **kwargs: object) -> runner._BoundedHarborProcessResult:+ del commandcaptured.update(kwargs)- return subprocess.CompletedProcess(command, 1, stdout="", stderr="expected test stop")+ return runner._BoundedHarborProcessResult(+ returncode=1,+ output_tail="expected test stop",+ output_exceeded=False,+ )- monkeypatch.setattr(runner.subprocess, "run", completed_run)+ monkeypatch.setattr(runner, "_run_bounded_harbor_process", completed_run)ok, _detail = runner._run_harbor(dataset=dataset,@@ -1586,7 +1603,7 @@ def test_run_harbor_defers_to_harbor_phase_timeouts_without_outer_deadline()assert ok is False- assert "timeout" not in captured+ assert captured["timeout_seconds"] is Nonedef _run(diff --git a/tests/test_harbor_runtime_preflight.py b/tests/test_harbor_runtime_preflight.pyindex 1dd0de31..2326c957 100644--- a/tests/test_harbor_runtime_preflight.py+++ b/tests/test_harbor_runtime_preflight.py@@ -151,6 +151,7 @@ def test_runtime_preflight_runs_one_case_once_without_verification(monkeypatch,def run(command, **kwargs):captured["command"] = commandcaptured["run_kwargs"] = kwargs+ captured["cwd_entries"] = sorted(path.name for path in Path(kwargs["cwd"]).iterdir())return subprocess.CompletedProcess(command, 0, "", "")monkeypatch.setattr(runtime_preflight, "build_harbor_run_command", build)@@ -160,6 +161,10 @@ def test_runtime_preflight_runs_one_case_once_without_verification(monkeypatch,"validate_harbor_agent_only_job_result",lambda *_args, **_kwargs: (True, "ok"),)+ operator_dir = tmp_path / "operator"+ operator_dir.mkdir()+ (operator_dir / ".env.local").write_text("SE_DOTENV_SENTINEL=leaked\n", encoding="utf-8")+ monkeypatch.chdir(operator_dir)result = runtime_preflight.run_agent_runtime_preflight(dataset=_dataset(tmp_path),@@ -181,7 +186,11 @@ def test_runtime_preflight_runs_one_case_once_without_verification(monkeypatch,run_kwargs = captured["run_kwargs"]assert isinstance(run_kwargs, dict)assert run_kwargs["timeout"] == 321- assert run_kwargs["env"] == {"NVIDIA_API_KEY": "secret"}+ assert run_kwargs["env"] == {"NVIDIA_API_KEY": "secret", "HARBOR_TELEMETRY": "0", "PYTHON_DOTENV_DISABLED": "1"}+ # Harbor starts in an empty evaluator-owned directory, never the operator's.+ assert Path(run_kwargs["cwd"]) != operator_dir+ assert captured["cwd_entries"] == []+ assert not Path(run_kwargs["cwd"]).exists()def test_runtime_preflight_hands_nvidia_build_key_only_over_stdin(monkeypatch, tmp_path: Path) -> None:diff --git a/tests/test_harbor_runtime_skill_isolation.py b/tests/test_harbor_runtime_skill_isolation.pyindex 589014b9..5322bec1 100644--- a/tests/test_harbor_runtime_skill_isolation.py+++ b/tests/test_harbor_runtime_skill_isolation.py@@ -20,10 +20,12 @@ import pytestfrom harbor.models.task.config import TaskConfig, TaskOSfrom harbor.models.task.paths import TaskPathsfrom harbor.models.task.task import Task-from harbor.models.task.verifier_mode import resolve_effective_verifier_env_config+from harbor.models.task.verifier_mode import (+ resolve_effective_verifier_env_config,+ resolve_verifier_environment_definition,+)from harbor.models.trajectories import Trajectoryfrom harbor.models.trial.paths import TrialPaths-from harbor.trial.trial import Trialfrom harbor.verifier.verifier import Verifierimport skillevaluator.tier3.harbor.adapter as adapter_module@@ -261,6 +263,7 @@ def test_native_custom_only_preserves_authored_judge_controls_in_verifier_env(task_config = tomllib.loads((task / "task.toml").read_text(encoding="utf-8"))assert task_config["verifier"]["env"] == {name: "skill-model"}+ assert task_config["verifier"]["timeout_sec"] == 180.0@pytest.mark.parametrize("grading_mode", ["default", "default_plus_custom"])@@ -618,11 +621,9 @@ def test_native_tasks_allow_staged_verifier_env_interpolation_in_separate_verifi' ports: ["18080:80"]\n')(verifier_context / "docker-compose.yaml").write_text(compose_text, encoding="utf-8")- if verifier_scope == "step":- # Harbor 0.22 resolves an existing separate step verifier context as a- # complete overlay, so it must provide its own test script instead of- # falling back to the task-level tests/test.sh.- (verifier_context / "test.sh").write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")+ # A Compose definition makes the verifier a dedicated image that bundles its+ # own tests; Harbor uploads no tests to it, so it must ship its test script.+ (verifier_context / "test.sh").write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")staged_task = stage_native_harbor_tasks(target,@@ -637,6 +638,21 @@ def test_native_tasks_allow_staged_verifier_env_interpolation_in_separate_verifiassert "ports:" not in staged_compose+def test_native_task_injected_verifier_timeout_covers_all_structured_judge_attempts(tmp_path: Path) -> None:+ _, target, _, _ = _write_projection_fixture(tmp_path)+ _write_minimal_native_task(target)++ task = stage_native_harbor_tasks(+ target,+ tmp_path / "native-injected-verifier-timeout",+ grading_mode="default",+ verifier_env={"SKILL_EVAL_LLM_PROVIDER": "${SKILL_EVAL_LLM_PROVIDER}"},+ )[0]+ task_config = tomllib.loads((task / "task.toml").read_text(encoding="utf-8"))++ assert task_config["verifier"]["timeout_sec"] >= (3 * 2 * 90) + 60++def test_native_task_reuses_existing_exact_provider_placeholder_when_injecting(tmp_path: Path) -> None:_, target, _, _ = _write_projection_fixture(tmp_path)_write_minimal_native_task(target)@@ -2691,15 +2707,22 @@ def test_native_custom_only_rejects_top_level_fallback_hidden_by_existing_separaharbor_task = Task(native_task, disable_verification=True)assert harbor_task.config.steps is not None- build_context = Trial._verifier_env_build_context(- SimpleNamespace(task=harbor_task),+ definition = resolve_verifier_environment_definition(+ harbor_task.config,+ harbor_task.paths,harbor_task.config.steps[0],)- assert build_context.resolve() == step_tests.resolve()- assert not (build_context / "test.sh").exists()+ # The step's Dockerfile makes a dedicated verifier image that bundles its+ # own tests, so Harbor never uploads the top-level tests/test.sh.+ assert definition is not None+ assert definition.directory.resolve() == step_tests.resolve()+ assert definition.bundled_tests is True+ assert not (definition.directory / "test.sh").exists()output_dir = tmp_path / "native-custom-only-testless-separate-step-context"- with pytest.raises(FileNotFoundError, match=r"Harbor-resolvable test script for every verifier pass"):+ # The fixture's evals/grader.py would be injected into tests/, which Harbor+ # never uploads to the step's dedicated verifier image.+ with pytest.raises(ValueError, match=r"dedicated verifier image for step 'step-one'"):stage_native_harbor_tasks(target,output_dir,@@ -2731,12 +2754,16 @@ def test_native_custom_only_accepts_top_level_fallback_for_separate_step_withoutharbor_task = Task(native_task, disable_verification=True)assert harbor_task.config.steps is not None- build_context = Trial._verifier_env_build_context(- SimpleNamespace(task=harbor_task),+ definition = resolve_verifier_environment_definition(+ harbor_task.config,+ harbor_task.paths,harbor_task.config.steps[0],)- assert build_context.resolve() == tests_dir.resolve()- assert (build_context / "test.sh").is_file()+ # Without a verifier image or build definition, Harbor builds the verifier+ # from environment/ and uploads the shared tests/test.sh at verify time.+ assert definition is not None+ assert definition.directory.resolve() == (native_task / "environment").resolve()+ assert definition.bundled_tests is False[staged] = stage_native_harbor_tasks(target,@@ -4590,3 +4617,95 @@ def test_link_or_reparse_check_accepts_missing_windows_file_attributes(tmp_path:)assert not adapter_module._path_is_link_or_reparse(path, partial_metadata)+++def _write_separate_verifier_task(target: Path, *, step: bool) -> Path:+ _write_minimal_native_task(target)+ native_task = target / "evals" / "harbor" / "case-001"+ task_toml = native_task / "task.toml"+ if step:+ authored = '\n[[steps]]\nname = "step-one"\n\n[steps.verifier]\nenvironment_mode = "separate"\n'+ step_dir = native_task / "steps" / "step-one"+ step_dir.mkdir(parents=True)+ (step_dir / "instruction.md").write_text("Run step one.\n", encoding="utf-8")+ else:+ authored = '\n[verifier]\nenvironment_mode = "separate"\n'+ task_toml.write_text(task_toml.read_text(encoding="utf-8") + authored, encoding="utf-8")+ tests_dir = native_task / "tests"+ tests_dir.mkdir()+ (tests_dir / "test.sh").write_text("#!/bin/sh\nprintf 1 > /logs/verifier/reward.txt\n", encoding="utf-8")+ return native_task+++def test_native_fallback_verifier_compose_uses_the_verifier_allowlist(tmp_path: Path) -> None:+ _, target, _, _ = _write_projection_fixture(tmp_path)+ native_task = _write_separate_verifier_task(target, step=False)+ (target / "evals" / "grader.py").unlink()+ environment_dir = native_task / "environment"+ environment_dir.mkdir()+ (environment_dir / "Dockerfile").write_text("FROM python:3.12-slim\n", encoding="utf-8")+ (environment_dir / "docker-compose.yaml").write_text(+ "services:\n main:\n depends_on: [helper]\n helper:\n image: busybox:${AGENT_ONLY}\n",+ encoding="utf-8",+ )+ task = TaskConfig.model_validate_toml((native_task / "task.toml").read_text(encoding="utf-8"))+ definition = resolve_verifier_environment_definition(task, TaskPaths(native_task))+ assert definition is not None+ assert definition.directory == native_task / "environment"+ assert definition.bundled_tests is False++ # Harbor builds this verifier from environment/, so a value staged only+ # for the agent must not reach the verifier's Compose model.+ with pytest.raises(ValueError, match="undeclared interpolation variables"):+ stage_native_harbor_tasks(+ target,+ tmp_path / "native-fallback-verifier-compose",+ grading_mode="custom_only",+ runtime_env={"AGENT_ONLY": "${AGENT_ONLY}"},+ verifier_env={},+ )++[email protected]("step", [False, True])+def test_native_separate_verifier_rejects_compose_yml_harbor_ignores(tmp_path: Path, step: bool) -> None:+ _, target, _, _ = _write_projection_fixture(tmp_path)+ native_task = _write_separate_verifier_task(target, step=step)+ context = native_task / "steps" / "step-one" / "tests" if step else native_task / "tests"+ context.mkdir(parents=True, exist_ok=True)+ (context / "docker-compose.yml").write_text("services:\n main: {}\n", encoding="utf-8")++ with pytest.raises(ValueError, match=r"must be named docker-compose\.yaml"):+ stage_native_harbor_tasks(+ target,+ tmp_path / f"native-yml-verifier-{step}",+ grading_mode="custom_only",+ )+++def test_native_dedicated_verifier_image_without_bundled_test_is_incomplete(tmp_path: Path) -> None:+ from skillevaluator.tier3.harbor.adapter import _native_custom_only_tests_are_complete++ _, target, _, _ = _write_projection_fixture(tmp_path)+ native_task = _write_separate_verifier_task(target, step=False)+ task_toml = native_task / "task.toml"+ task_toml.write_text(+ task_toml.read_text(encoding="utf-8") + '\n[verifier.environment]\ndocker_image = "verifier:latest"\n',+ encoding="utf-8",+ )+ (native_task / "tests" / "test.sh").unlink()++ assert _native_custom_only_tests_are_complete(native_task) is False+ (native_task / "tests" / "test.sh").write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")+ assert _native_custom_only_tests_are_complete(native_task) is True+++def test_native_standard_grading_rejects_fallback_separate_verifier(tmp_path: Path) -> None:+ _, target, _, _ = _write_projection_fixture(tmp_path)+ _write_separate_verifier_task(target, step=False)++ with pytest.raises(ValueError, match="separate verifier context is unsupported with SkillEvaluator standard"):+ stage_native_harbor_tasks(+ target,+ tmp_path / "native-standard-fallback-verifier",+ grading_mode="default",+ )diff --git a/tests/test_harbor_secure_docker_environment.py b/tests/test_harbor_secure_docker_environment.pyindex 6fb90719..87d588a1 100644--- a/tests/test_harbor_secure_docker_environment.py+++ b/tests/test_harbor_secure_docker_environment.py@@ -2785,8 +2785,43 @@ def test_compose_model_parser_bounds_recursive_aliases_and_node_expansion(assert "HELPER_IMAGE" in environment._compose_model_interpolation_names()monkeypatch.setattr(secure_docker_environment, "_MAX_COMPOSE_MODEL_NODES", 1)+ construction_attempted = False++ def reject_construction(*_args: object, **_kwargs: object) -> object:+ nonlocal construction_attempted+ construction_attempted = True+ raise AssertionError("bounded Compose YAML reached object construction")++ monkeypatch.setattr(secure_docker_environment.yaml, "load", reject_construction)with pytest.raises(RuntimeError, match="could not inspect Docker Compose"):environment._compose_model_interpolation_names()+ assert construction_attempted is False+++def test_compose_model_parser_bounds_depth_before_object_construction(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from skillevaluator.tier3.harbor import secure_docker_environment++ environment = _initialized_secure_docker_environment(tmp_path)+ (environment.environment_dir / "docker-compose.yaml").write_text(+ "services:\n helper:\n labels:\n nested:\n value: fixed\n",+ encoding="utf-8",+ )+ construction_attempted = False++ def reject_construction(*_args: object, **_kwargs: object) -> object:+ nonlocal construction_attempted+ construction_attempted = True+ raise AssertionError("bounded Compose YAML reached object construction")++ monkeypatch.setattr(secure_docker_environment, "_MAX_COMPOSE_MODEL_DEPTH", 2)+ monkeypatch.setattr(secure_docker_environment.yaml, "load", reject_construction)++ with pytest.raises(RuntimeError, match="could not inspect Docker Compose"):+ environment._compose_model_interpolation_names()+ assert construction_attempted is Falsedef test_compose_model_parser_rejects_non_regular_include_without_blocking(@@ -6913,6 +6948,28 @@ def test_exec_uses_name_only_argv_and_subprocess_override(tmp_path: Path) -> Nonassert captured["stop_main_on_interrupt"] is True+def test_compatibility_exec_without_environment_uses_empty_process_override(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ environment = _initialized_docker_environment(tmp_path)+ captured: dict[str, object] = {}++ async def capture(command: list[str], **kwargs: object) -> ExecResult:+ captured["command"] = command+ captured.update(kwargs)+ return ExecResult(stdout="ok", stderr=None, return_code=0)++ monkeypatch.setattr(environment, "_run_docker_compose_command", capture)++ result = asyncio.run(environment.exec("true"))++ assert result.return_code == 0+ assert captured["command"] == ["exec", "main", *environment._platform.exec_shell_args("true")]+ assert captured["env_overrides"] == {}+ assert captured["stop_main_on_interrupt"] is True++def test_all_values_use_subprocess_env_including_empty_and_special_values() -> None:special = "spaces = quotes ' \" and $shell"arguments, child_environment = _secure_exec_arguments({"DATABASE_URL": _SENTINEL, "EMPTY": "", "SPECIAL": special})@@ -6993,6 +7050,7 @@ def test_compose_stdin_handoff_redacts_secret_without_argv_or_environment(environment._resources_compose_path = Noneenvironment._env_compose_path = Noneenvironment._mounts_compose_path = None+ environment._stream_compose_path = Noneenvironment._use_prebuilt = Trueenvironment._is_windows_container = Falseenvironment.extra_docker_compose_paths = []@@ -8412,3 +8470,66 @@ def test_invalid_exec_environment_fails_without_serializing_value(assert message in str(caught.value)assert _SENTINEL not in str(caught.value)+++def test_secure_docker_stays_on_the_docker_runtime(monkeypatch: pytest.MonkeyPatch) -> None:+ from harbor.environments.docker.runtime import DOCKER_RUNTIME+ from harbor.environments.podman import PodmanEnvironment++ podman_runtime = PodmanEnvironment.runtime()+ assert podman_runtime is not DOCKER_RUNTIME+ monkeypatch.setattr(DockerEnvironment, "runtime", classmethod(lambda _cls: podman_runtime))++ assert SkillEvaluatorDockerEnvironment.runtime() is DOCKER_RUNTIME+ assert SkillEvaluatorSecureDockerEnvironment.runtime() is DOCKER_RUNTIME+++def test_secure_docker_disables_ssh_streaming_and_gpu_reservations(tmp_path: Path) -> None:+ environment = _initialized_secure_docker_environment(tmp_path)++ assert environment.capabilities.stream is False+ assert environment.capabilities.gpus is False+ assert environment.capabilities.docker_compose is True+ with pytest.raises(ValueError):+ SkillEvaluatorSecureDockerEnvironment(+ environment_dir=environment.environment_dir,+ environment_name="secure-stream-test",+ session_id="secure-stream-test",+ trial_paths=TrialPaths(tmp_path / "stream-trial"),+ task_env_config=EnvironmentConfig(),+ stream=True,+ )++[email protected]("kind", ["file", "dir"])+def test_secure_docker_main_downloads_use_compose_copy_only(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ kind: str,+) -> None:+ from harbor.environments.docker.docker_unix import UnixOps++ environment = _initialized_secure_docker_environment(tmp_path)+ commands: list[tuple[str, ...]] = []++ async def create_subprocess(*args: object, **_kwargs: object) -> _BufferedComposeProcess:+ commands.append(tuple(str(argument) for argument in args))+ return _BufferedComposeProcess(stdout=b"")++ async def raw_engine_copy(*_args: object, **_kwargs: object) -> None:+ raise AssertionError("main-container downloads must not fall back to raw docker cp")++ monkeypatch.setattr(asyncio, "create_subprocess_exec", create_subprocess)+ monkeypatch.setattr(UnixOps, "_download_via_engine_cp", raw_engine_copy, raising=False)++ if kind == "file":+ asyncio.run(environment.download_file("/app/result.txt", tmp_path / "result.txt"))+ else:+ asyncio.run(environment.download_dir("/app/output", tmp_path / "output"))++ copy_commands = [command for command in commands if "cp" in command]+ assert len(copy_commands) == 1+ assert Path(copy_commands[0][0]).name == "docker"+ assert copy_commands[0][1] == "compose"+ assert copy_commands[0][copy_commands[0].index("cp") + 2].startswith(f"{MAIN_SERVICE_NAME}:")+ assert not any(Path(command[0]).name == "docker" and command[1] in {"cp", "ps"} for command in commands)diff --git a/tests/test_harbor_task_toml_retry_env.py b/tests/test_harbor_task_toml_retry_env.pyindex 1c8ebb4a..b9ada7d1 100644--- a/tests/test_harbor_task_toml_retry_env.py+++ b/tests/test_harbor_task_toml_retry_env.py@@ -195,8 +195,19 @@ def test_runner_forwards_host_retry_settings_to_staged_task_and_verifier_runtimeassert _resolve_verifier_retry_tuple(monkeypatch, tmp_path, verifier_toml_env, run_env) == (0, 0.1, 0.5)-def _create_native_skill_with_authored_retry_env(skill_dir: Path, grading_mode: str) -> None:- """Create a native Harbor skill fixture whose task.toml defines all three retry variables."""+_AUTHORED_RETRY_ENV_LINES = (+ 'SKILL_EVAL_LLM_MAX_RETRIES = "2"\n'+ 'SKILL_EVAL_LLM_RETRY_BASE_DELAY = "0.5"\n'+ 'SKILL_EVAL_LLM_RETRY_MAX_DELAY = "10.0"\n'+)+++def _create_native_skill_with_authored_retry_env(+ skill_dir: Path,+ grading_mode: str,+ verifier_env_lines: str = _AUTHORED_RETRY_ENV_LINES,+) -> None:+ """Create a native Harbor skill fixture whose task.toml authors [verifier.env] retry variables."""evals = skill_dir / "evals"native_task = evals / "harbor" / "case-001"(native_task / "environment").mkdir(parents=True)@@ -222,56 +233,50 @@ def _create_native_skill_with_authored_retry_env(skill_dir: Path, grading_mode:'[metadata]\nentry_id = "case-001"\n\n'"[verifier]\ntimeout_sec = 180.0\n\n""[verifier.env]\n"- 'SKILL_EVAL_LLM_MAX_RETRIES = "2"\n'- 'SKILL_EVAL_LLM_RETRY_BASE_DELAY = "0.5"\n'- 'SKILL_EVAL_LLM_RETRY_MAX_DELAY = "10.0"\n\n'+ f"{verifier_env_lines}\n""[environment]\n",encoding="utf-8",)@pytest.mark.parametrize("grading_mode", ["default", "default_plus_custom"])-def test_native_task_preserves_authored_retry_settings_without_host_override(+def test_native_standard_grading_rejects_authored_retry_settings(tmp_path: Path,grading_mode: str,) -> None:- """Verify native task staging keeps authored [verifier.env] retry values when host does not override them."""- skill = tmp_path / f"native-no-override-{grading_mode}"+ """Verify a native task cannot pin judge retry budgets for SkillEvaluator's standard grader."""+ skill = tmp_path / f"native-authored-{grading_mode}"_create_native_skill_with_authored_retry_env(skill, grading_mode)- staged = stage_native_harbor_tasks(- skill,- tmp_path / f"staged-no-override-{grading_mode}",- grading_mode=grading_mode,- verifier_env={"SKILL_EVAL_LLM_PROVIDER": "openai", "SKILL_EVAL_LLM_MODEL": "gpt-4o-mini"},- )[0]+ with pytest.raises(ValueError, match="rejects task-controlled environment control") as exc_info:+ stage_native_harbor_tasks(+ skill,+ tmp_path / f"staged-authored-{grading_mode}",+ grading_mode=grading_mode,+ verifier_env={"SKILL_EVAL_LLM_PROVIDER": "openai", "SKILL_EVAL_LLM_MODEL": "gpt-4o-mini"},+ )- staged_task = tomllib.loads((staged / "task.toml").read_text(encoding="utf-8"))- verifier_env = staged_task["verifier"]["env"]- assert verifier_env["SKILL_EVAL_LLM_MAX_RETRIES"] == "2"- assert verifier_env["SKILL_EVAL_LLM_RETRY_BASE_DELAY"] == "0.5"- assert verifier_env["SKILL_EVAL_LLM_RETRY_MAX_DELAY"] == "10.0"- assert verifier_env["SKILL_EVAL_LLM_PROVIDER"] == "${SKILL_EVAL_LLM_PROVIDER}"+ for name in sorted(_VERIFIER_RETRY_ENV_VARS - {"SKILL_EVAL_LLM_JUDGE_BUDGET_SEC"}):+ assert name in str(exc_info.value)@pytest.mark.parametrize("grading_mode", ["default", "default_plus_custom"])@pytest.mark.parametrize(- ("retry_var", "host_val", "expected_tuple"),+ ("retry_var", "host_val"),[- ("SKILL_EVAL_LLM_MAX_RETRIES", "0", (0, 0.5, 10.0)),- ("SKILL_EVAL_LLM_RETRY_BASE_DELAY", "0.1", (2, 0.1, 10.0)),- ("SKILL_EVAL_LLM_RETRY_MAX_DELAY", "0.5", (2, 0.5, 0.5)),+ ("SKILL_EVAL_LLM_MAX_RETRIES", "0"),+ ("SKILL_EVAL_LLM_RETRY_BASE_DELAY", "0.1"),+ ("SKILL_EVAL_LLM_RETRY_MAX_DELAY", "0.5"),],)-def test_native_task_host_override_replaces_authored_retry_key_without_duplicate_toml_keys(+def test_native_host_override_does_not_launder_authored_retry_settings(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,grading_mode: str,retry_var: str,host_val: str,- expected_tuple: tuple[int, float, float],) -> None:- """Verify each host retry override replaces its colliding authored [verifier.env] key and produces valid TOML."""+ """Verify an operator override cannot make authored retry literals acceptable for standard grading."""skill = tmp_path / f"native-override-{grading_mode}-{retry_var.lower()}"_create_native_skill_with_authored_retry_env(skill, grading_mode)@@ -298,60 +303,103 @@ def test_native_task_host_override_replaces_authored_retry_key_without_duplicateagent_runtime_preflight=False,)+ assert result["execution_status"] == "failed"+ assert any(retry_var in str(error) for error in result["execution_errors"])+ assert "with_skill" not in captured_launch++[email protected]("grading_mode", ["default", "default_plus_custom"])+ ("retry_var", "host_val"),+ [+ ("SKILL_EVAL_LLM_MAX_RETRIES", "0"),+ ("SKILL_EVAL_LLM_RETRY_BASE_DELAY", "0.1"),+ ("SKILL_EVAL_LLM_RETRY_MAX_DELAY", "0.5"),+ ],+)+def test_native_task_accepts_operator_staged_retry_placeholders(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ grading_mode: str,+ retry_var: str,+ host_val: str,+) -> None:+ """Verify exact ${NAME} placeholders still carry the operator's retry settings to the verifier."""+ skill = tmp_path / f"native-placeholder-{grading_mode}-{retry_var.lower()}"+ _create_native_skill_with_authored_retry_env(+ skill,+ grading_mode,+ verifier_env_lines=f'{retry_var} = "${{{retry_var}}}"\nCUSTOM_VERIFIER_FLAG = "keep-me"\n',+ )++ for var in _VERIFIER_RETRY_ENV_VARS:+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setenv(retry_var, host_val)++ captured_launch = _stub_harbor_runner(+ monkeypatch,+ tmp_path,+ task_source="native_harbor",+ grading_mode=grading_mode,+ )++ result = runner.run_harbor_eval(+ skill,+ ["codex"],+ agent_models={"codex": "gpt-4o-mini"},+ output_dir=tmp_path / f"results-placeholder-{grading_mode}-{retry_var.lower()}",+ env_mode="docker",+ grading_mode=grading_mode,+ skip_baseline=True,+ keep_harbor_jobs=True,+ agent_runtime_preflight=False,+ )+assert "error" not in resulttask_toml_path = captured_launch["with_skill"] / "case-001" / "task.toml"staged_task = tomllib.loads(task_toml_path.read_text(encoding="utf-8"))verifier_toml_env = staged_task["verifier"]["env"]assert verifier_toml_env[retry_var] == f"${{{retry_var}}}"-+ assert verifier_toml_env["CUSTOM_VERIFIER_FLAG"] == "keep-me"run_env = captured_launch["run_env"]assert run_env[retry_var] == host_val- assert _resolve_verifier_retry_tuple(monkeypatch, tmp_path, verifier_toml_env, run_env) == expected_tuple+ # The placeholder must resolve exactly as if the operator set the value for the verifier.+ expected = _resolve_verifier_retry_tuple(monkeypatch, tmp_path, {retry_var: host_val}, {})+ assert _resolve_verifier_retry_tuple(monkeypatch, tmp_path, verifier_toml_env, run_env) == expected+ assert expected != _resolve_verifier_retry_tuple(monkeypatch, tmp_path, {}, {})@pytest.mark.parametrize("grading_mode", ["default", "default_plus_custom"])-def test_native_task_simultaneous_host_overrides_and_quoted_keys(+def test_native_standard_grading_rejects_quoted_authored_retry_keys(tmp_path: Path,grading_mode: str,) -> None:- """Verify simultaneous host overrides replace all three authored retry keys including quoted TOML keys."""- skill = tmp_path / f"native-all-three-{grading_mode}"- _create_native_skill_with_authored_retry_env(skill, grading_mode)- task_toml = skill / "evals" / "harbor" / "case-001" / "task.toml"- task_toml.write_text(- task_toml.read_text(encoding="utf-8").replace(- 'SKILL_EVAL_LLM_MAX_RETRIES = "2"\n',- '"SKILL_EVAL_LLM_MAX_RETRIES" = "2"\nCUSTOM_VERIFIER_FLAG = "keep-me"\n',- ),- encoding="utf-8",- )-- staged = stage_native_harbor_tasks(+ """Verify quoting a TOML key cannot smuggle an authored retry budget past standard grading."""+ skill = tmp_path / f"native-quoted-{grading_mode}"+ _create_native_skill_with_authored_retry_env(skill,- tmp_path / f"staged-all-three-{grading_mode}",- grading_mode=grading_mode,- verifier_env={- "SKILL_EVAL_LLM_PROVIDER": "openai",- "SKILL_EVAL_LLM_MODEL": "gpt-4o-mini",- "SKILL_EVAL_LLM_MAX_RETRIES": "0",- "SKILL_EVAL_LLM_RETRY_BASE_DELAY": "0.1",- "SKILL_EVAL_LLM_RETRY_MAX_DELAY": "0.5",- },- )[0]+ grading_mode,+ verifier_env_lines='"SKILL_EVAL_LLM_MAX_RETRIES" = "2"\nCUSTOM_VERIFIER_FLAG = "keep-me"\n',+ )- staged_task = tomllib.loads((staged / "task.toml").read_text(encoding="utf-8"))- verifier_env = staged_task["verifier"]["env"]- assert verifier_env["SKILL_EVAL_LLM_MAX_RETRIES"] == "${SKILL_EVAL_LLM_MAX_RETRIES}"- assert verifier_env["SKILL_EVAL_LLM_RETRY_BASE_DELAY"] == "${SKILL_EVAL_LLM_RETRY_BASE_DELAY}"- assert verifier_env["SKILL_EVAL_LLM_RETRY_MAX_DELAY"] == "${SKILL_EVAL_LLM_RETRY_MAX_DELAY}"- assert verifier_env["CUSTOM_VERIFIER_FLAG"] == "keep-me"+ with pytest.raises(ValueError, match="SKILL_EVAL_LLM_MAX_RETRIES"):+ stage_native_harbor_tasks(+ skill,+ tmp_path / f"staged-quoted-{grading_mode}",+ grading_mode=grading_mode,+ verifier_env={+ "SKILL_EVAL_LLM_PROVIDER": "openai",+ "SKILL_EVAL_LLM_MODEL": "gpt-4o-mini",+ "SKILL_EVAL_LLM_MAX_RETRIES": "0",+ },+ )-def test_native_task_verifier_env_with_header_comments_and_cross_section_keys(+def test_native_task_verifier_env_with_header_comments_keeps_single_tables(tmp_path: Path,) -> None:- """Verify [verifier.env] and next-table headers with inline comments or whitespace do not duplicate tables or keys."""+ """Verify commented [verifier] headers and operator placeholders stage without duplicate tables or keys."""skill = tmp_path / "native-header-comments"_create_native_skill_with_authored_retry_env(skill, "default")task_toml = skill / "evals" / "harbor" / "case-001" / "task.toml"@@ -362,10 +410,7 @@ def test_native_task_verifier_env_with_header_comments_and_cross_section_keys(" [verifier] # verifier config\n""timeout_sec = 180.0\n\n"" [verifier.env] # verifier env overrides\n"- 'SKILL_EVAL_LLM_MAX_RETRIES = "2" # authored retry budget\n\n'- '[[steps]] # step list\nname = "step-one"\n\n'- "[steps.verifier.env]\n"- 'SKILL_EVAL_LLM_RETRY_BASE_DELAY = "${SKILL_EVAL_LLM_RETRY_BASE_DELAY}"\n\n'+ 'SKILL_EVAL_LLM_MAX_RETRIES = "${SKILL_EVAL_LLM_MAX_RETRIES}" # operator retry budget\n\n'"[environment] # agent environment\n",encoding="utf-8",)@@ -381,8 +426,10 @@ def test_native_task_verifier_env_with_header_comments_and_cross_section_keys(},)[0]- staged_task = tomllib.loads((staged / "task.toml").read_text(encoding="utf-8"))+ staged_text = (staged / "task.toml").read_text(encoding="utf-8")+ staged_task = tomllib.loads(staged_text)verifier_env = staged_task["verifier"]["env"]assert verifier_env["SKILL_EVAL_LLM_MAX_RETRIES"] == "${SKILL_EVAL_LLM_MAX_RETRIES}"assert verifier_env["SKILL_EVAL_LLM_RETRY_BASE_DELAY"] == "${SKILL_EVAL_LLM_RETRY_BASE_DELAY}"assert verifier_env["SKILL_EVAL_LLM_PROVIDER"] == "${SKILL_EVAL_LLM_PROVIDER}"+ assert staged_task["verifier"]["timeout_sec"] == 180.0diff --git a/tests/test_issue55_collector_truth.py b/tests/test_issue55_collector_truth.pyindex 82c2fb02..40915dac 100644--- a/tests/test_issue55_collector_truth.py+++ b/tests/test_issue55_collector_truth.py@@ -2403,6 +2403,72 @@ def test_persisted_trial_alias_keeps_exact_source_identity_with_trailing_space(t}+def test_distinct_unsafe_trial_roots_receive_distinct_published_identities(tmp_path: Path) -> None:+ job_dir = tmp_path / "jobs"+ trial_root_names = ("ghp_" + ("a" * 36), "ghp_" + ("b" * 36))+ rewards: list[dict[str, object]] = []+ for index, trial_root_name in enumerate(trial_root_names, start=1):+ (job_dir / trial_root_name).mkdir(parents=True)+ rewards.append(+ {+ **_default_reward(f"case-{index}", 1.0),+ "_trial_name": trial_root_name,+ "_trial_root_name": trial_root_name,+ }+ )++ trials_dir = tmp_path / "results" / "trials"+ collector_module._save_trials(+ rewards,+ trials_dir,+ job_dir,+ skill_name="demo",+ agent="opencode",+ variant="with_skill",+ )++ persisted_rewards = [+ json.loads(path.read_text(encoding="utf-8")) for path in sorted(trials_dir.glob("*/reward.json"))+ ]+ published_ids = {reward["trial_id"] for reward in persisted_rewards}+ assert len(published_ids) == 2+ assert all(str(trial_id).startswith("redacted-or-invalid-trial-") for trial_id in published_ids)+ assert published_ids.isdisjoint(trial_root_names)+ assert sorted(len(group) for group in report_data.logical_trial_reward_groups(persisted_rewards)) == [1, 1]+++def test_unsafe_multistep_trial_rows_share_one_published_identity(tmp_path: Path) -> None:+ job_dir = tmp_path / "jobs"+ trial_root_name = "ghp_" + ("c" * 36)+ (job_dir / trial_root_name).mkdir(parents=True)+ rewards = [+ {+ **_default_reward("case-1", score),+ "_trial_name": trial_root_name,+ "_trial_root_name": trial_root_name,+ "_step_name": step_name,+ }+ for step_name, score in (("prepare", 0.5), ("finish", 1.0))+ ]++ trials_dir = tmp_path / "results" / "trials"+ collector_module._save_trials(+ rewards,+ trials_dir,+ job_dir,+ skill_name="demo",+ agent="opencode",+ variant="with_skill",+ )++ persisted_rewards = [+ json.loads(path.read_text(encoding="utf-8")) for path in sorted(trials_dir.glob("*/reward.json"))+ ]+ assert len(persisted_rewards) == 2+ assert {reward["trial_id"] for reward in persisted_rewards} == {"redacted-or-invalid-trial-000001"}+ assert [len(group) for group in report_data.logical_trial_reward_groups(persisted_rewards)] == [2]++def test_scored_and_unscored_portable_name_collision_persists_distinct_trials(tmp_path: Path) -> None:job_dir = tmp_path / "jobs"scored_source = job_dir / "foo "diff --git a/tests/test_oss_packaging.py b/tests/test_oss_packaging.pyindex 5352f899..ef0f214e 100644--- a/tests/test_oss_packaging.py+++ b/tests/test_oss_packaging.py@@ -23,9 +23,12 @@ from packaging.version import Versionfrom skillevaluator.cli import clifrom skillevaluator.tier3_environments import (+ HARBOR_ENVIRONMENT_ALIAS_KWARGS,HARBOR_ENVIRONMENT_EXTRAS,+ HARBOR_ENVIRONMENT_TYPE_ALIASES,HARBOR_ENVIRONMENTS,HARBOR_NATIVE_ENV_MODES,+ HARBOR_VERSION,)REPO_ROOT = Path(__file__).resolve().parents[1]@@ -127,7 +130,7 @@ def test_public_extras_use_public_dependency_sources() -> None:)-def test_harbor_022_dependency_contract_keeps_base_install_isolated() -> None:+def test_harbor_dependency_contract_keeps_base_install_isolated() -> None:project = _project()extras = project["project"]["optional-dependencies"]base_requirements = [Requirement(raw) for raw in project["project"]["dependencies"]]@@ -145,7 +148,8 @@ def test_harbor_022_dependency_contract_keeps_base_install_isolated() -> None:assert base_names.isdisjoint({"harbor", "litellm"})assert len(harbor_requirements) == 1assert not harbor_requirements[0].extras- assert str(harbor_requirements[0].specifier) == "==0.22.0"+ assert HARBOR_VERSION == "0.24.0"+ assert str(harbor_requirements[0].specifier) == f"=={HARBOR_VERSION}"assert len(litellm_requirements) == 1litellm_specifier = litellm_requirements[0].specifierassert litellm_specifier.contains(Version("1.92.0"), prereleases=True)@@ -161,7 +165,7 @@ def test_harbor_022_dependency_contract_keeps_base_install_isolated() -> None:name: [Version(package["version"]) for package in lock["package"] if package["name"] == name]for name in ("harbor", "litellm")}- assert locked_versions["harbor"] == [Version("0.22.0")]+ assert locked_versions["harbor"] == [Version(HARBOR_VERSION)]assert len(locked_versions["litellm"]) == 1assert litellm_specifier.contains(locked_versions["litellm"][0], prereleases=True)@@ -169,7 +173,7 @@ def test_harbor_022_dependency_contract_keeps_base_install_isolated() -> None:locked_requirements = root_lock["metadata"]["requires-dist"]locked_harbor = [requirement for requirement in locked_requirements if requirement["name"] == "harbor"]locked_litellm = [requirement for requirement in locked_requirements if requirement["name"] == "litellm"]- assert [requirement["specifier"] for requirement in locked_harbor] == ["==0.22.0"]+ assert [requirement["specifier"] for requirement in locked_harbor] == [f"=={HARBOR_VERSION}"]assert [requirement["specifier"] for requirement in locked_litellm] == [">=1.92.0,<1.94.0.dev0"]@@ -177,21 +181,22 @@ def test_harbor_environment_extra_mapping_matches_installed_metadata() -> None:provided_extras = set(metadata("harbor").get_all("Provides-Extra") or ())system_or_base_backends = {"docker", "openshift", "apple-container", "singularity"}- assert len(HARBOR_ENVIRONMENTS) == 27- assert len(HARBOR_NATIVE_ENV_MODES) == 26+ assert len(HARBOR_ENVIRONMENTS) == 24+ assert len(HARBOR_NATIVE_ENV_MODES) == 23assert frozenset(HARBOR_ENVIRONMENTS) - {"local"} == HARBOR_NATIVE_ENV_MODESassert set(HARBOR_ENVIRONMENT_EXTRAS) == HARBOR_NATIVE_ENV_MODESassert {mode for mode, extra in HARBOR_ENVIRONMENT_EXTRAS.items() if extra is None} == system_or_base_backendsassert {extra for extra in HARBOR_ENVIRONMENT_EXTRAS.values() if extra is not None} <= provided_extrasassert {mode: extra for mode, extra in HARBOR_ENVIRONMENT_EXTRAS.items() if extra is not None and extra != mode- } == {"ack": "gke", "cua-cloud": "cua"}+ } == {"ack": "gke", "wandb": "cwsandbox"}assert HARBOR_ENVIRONMENT_EXTRAS["ack"] == "gke"- assert "cloud" in provided_extras- assert HARBOR_ENVIRONMENT_EXTRAS["cua-cloud"] == "cua"+ # Harbor 0.24 merged its W&B sandbox into the cwsandbox extra.+ assert "wandb" not in provided_extras+ assert HARBOR_ENVIRONMENT_TYPE_ALIASES == {"wandb": "cwsandbox"}-def _harbor_022_environment_kwargs_from_installed_source() -> dict[str, frozenset[str]]:+def _harbor_environment_kwargs_from_installed_source() -> dict[str, frozenset[str]]:"""Read the pinned Harbor sources without importing optional backend SDKs."""harbor_spec = importlib.util.find_spec("harbor")assert harbor_spec is not None and harbor_spec.origin is not None@@ -284,13 +289,22 @@ def _harbor_022_environment_kwargs_from_installed_source() -> dict[str, frozensereturn contract-def test_harbor_022_environment_kwarg_contract_matches_installed_source() -> None:+def test_harbor_environment_kwarg_contract_matches_installed_source() -> None:from skillevaluator import tier3_environments- contract = getattr(tier3_environments, "HARBOR_V022_ENVIRONMENT_KWARGS", None)+ contract = getattr(tier3_environments, "HARBOR_ENVIRONMENT_KWARGS", None)+ registry = _harbor_environment_kwargs_from_installed_source()assert contract is not None- assert contract == _harbor_022_environment_kwargs_from_installed_source()+ # Aliases are SkillEvaluator modes, not Harbor registry types.+ assert HARBOR_ENVIRONMENT_TYPE_ALIASES.keys().isdisjoint(registry)+ assert {+ mode: kwargs for mode, kwargs in contract.items() if mode not in HARBOR_ENVIRONMENT_TYPE_ALIASES+ } == registry+ for alias, harbor_type in HARBOR_ENVIRONMENT_TYPE_ALIASES.items():+ alias_kwargs = HARBOR_ENVIRONMENT_ALIAS_KWARGS[alias]+ assert alias_kwargs.keys() <= registry[harbor_type]+ assert contract[alias] == registry[harbor_type] - alias_kwargs.keys()def test_public_docs_match_harbor_environment_and_kwarg_contract() -> None:@@ -302,17 +316,17 @@ def test_public_docs_match_harbor_environment_and_kwarg_contract() -> None:public_docs = f"{agents}\n{cli_reference}\n{configuration}\n{tier3}\n{eval_config}"normalized_docs = " ".join(public_docs.split())- assert "27 environment modes" in public_docs- assert "26 Harbor-native backends" in public_docs+ assert "24 environment modes" in public_docs+ assert "23 Harbor-native backends" in public_docsassert "All 16 values" not in public_docsassert "same 16 values" not in public_docsassert "14 additional Harbor-native backends" not in public_docsassert all(f"`{mode}`" in agents for mode in HARBOR_ENVIRONMENTS)for mode, extra in HARBOR_ENVIRONMENT_EXTRAS.items():if extra is not None:- assert f"| `{mode}` | Harbor-native | `harbor[{extra}]==0.22.0`" in agents- assert "`harbor[cloud]==0.22.0`" not in public_docs- assert "OpenSandbox requires either a non-empty `domain`" in normalized_docs+ assert f"| `{mode}` | Harbor-native | `harbor[{extra}]=={HARBOR_VERSION}`" in agents+ assert f"`harbor[cloud]=={HARBOR_VERSION}`" not in public_docs+ assert "not exposed until SkillEvaluator can project the complete task bundle" in normalized_docsassert "does not contact AWS" in normalized_docsassert "does not contact the GKE cluster" in normalized_docsassert "no harbor python extra" in agents.lower()@@ -427,6 +441,7 @@ def test_tier3_direct_dependencies_have_complete_license_notices() -> None:"harbor": "Harbor (Apache-2.0)","mcp": "MCP (MIT)","pyjwt": "PyJWT (MIT)",+ "python-dotenv": "python-dotenv (BSD-3-Clause)",}notices = (REPO_ROOT / "THIRD_PARTY_NOTICES.md").read_text(encoding="utf-8")@@ -847,12 +862,13 @@ def test_tier3_docs_name_the_supported_harbor_backend_version() -> None:tier3 = (REPO_ROOT / "docs" / "tier3-live-evaluation.mdx").read_text(encoding="utf-8")normalized = " ".join(tier3.split())- assert "The `tier3` extra installs Harbor 0.22.0" in normalized+ assert f"The `tier3` extra installs Harbor {HARBOR_VERSION}" in normalizedassert "The exact Harbor pin is deliberate" in normalized- assert "stable Harbor 0.22.0 rather than unreleased `main`" in normalized+ assert f"stable Harbor {HARBOR_VERSION} rather than unreleased `main`" in normalizedassert "litellm>=1.92.0,<1.94.0.dev0" in normalizedassert "static Tier 1 installs do not pull it in" in normalizedassert "0.13.2" not in normalized+ assert "0.22.0" not in normalizeddef test_tier3_docs_describe_the_current_nvidia_build_docker_handoff() -> None:diff --git a/tests/test_secure_docker_environment.py b/tests/test_secure_docker_environment.pyindex 86af5345..5b029f19 100644--- a/tests/test_secure_docker_environment.py+++ b/tests/test_secure_docker_environment.py@@ -6,6 +6,7 @@from __future__ import annotationsimport asyncio+import contextlibimport contextvarsimport hashlibimport importlib@@ -110,6 +111,7 @@ def test_secure_docker_exec_redacts_persistent_and_per_call_credentials_from_allenvironment._resources_compose_path = Noneenvironment._env_compose_path = Noneenvironment._mounts_compose_path = None+ environment._stream_compose_path = Noneenvironment._use_prebuilt = Trueenvironment._is_windows_container = Falseenvironment.extra_docker_compose_paths = []@@ -352,9 +354,22 @@ def test_harbor_subprocess_receives_nvidia_key_only_over_stdin(monkeypatch, tmp_raise AssertionError("NVIDIA key handoff must not create a temporary directory")monkeypatch.setattr(runner.tempfile, "TemporaryDirectory", reject_temporary_directory)+ launch_dirs: list[Path] = []++ @contextlib.contextmanager+ def recording_launch_cwd():+ # The evaluator-owned launch directory is allowed, but must stay empty.+ launch_dir = tmp_path / f"launch-{len(launch_dirs)}"+ launch_dir.mkdir()+ launch_dirs.append(launch_dir)+ yield launch_dir++ monkeypatch.setattr(runner, "_harbor_launch_cwd", recording_launch_cwd)def fake_run(command, **kwargs):environment = kwargs["env"]+ assert kwargs["cwd"] in launch_dirs+ assert not any(Path(kwargs["cwd"]).iterdir())assert secret not in commandassert secret not in environment.values()assert environment["NVIDIA_API_KEY"] == runner._NVIDIA_BUILD_STDIN_SENTINEL@@ -386,6 +401,8 @@ def test_harbor_subprocess_receives_nvidia_key_only_over_stdin(monkeypatch, tmp_)assert (ok, detail) == (True, "")+ assert launch_dirs+ assert all(not any(launch_dir.iterdir()) for launch_dir in launch_dirs)handoff = runner._nvidia_build_key_handoff({"SKILL_EVAL_LLM_PROVIDER": "nv_build", "NVIDIA_API_KEY": secret},env_mode="docker",diff --git a/tests/test_tier3_progress.py b/tests/test_tier3_progress.pyindex df24e3f6..38d40b2c 100644--- a/tests/test_tier3_progress.py+++ b/tests/test_tier3_progress.py@@ -775,7 +775,7 @@ def _stub_runner(monkeypatch.setattr(runner, "find_evals_file", lambda _path: evals_file)monkeypatch.setattr(runner, "generate_harbor_tasks", task_emitter or emit_tasks)monkeypatch.setattr(runner, "_provider_environment", lambda _provider: {"OPENAI_API_KEY": provider.api_key})- monkeypatch.setattr(runner, "_resolve_runtime_env", lambda _templates: ({}, []))+ monkeypatch.setattr(runner, "_resolve_runtime_env", lambda _templates, **_kwargs: ({}, []))monkeypatch.setattr(runner,"_validate_agent_provider_credentials",@@ -938,7 +938,11 @@ def test_ack_eval_preflight_uses_the_exact_prospective_bedrock_child_environmentmonkeypatch.setattr(runner, "resolve_llm_provider", lambda: provider)monkeypatch.setattr(runner, "_provider_environment", real_provider_environment)monkeypatch.setattr(runner, "_harbor_subprocess_environment", real_harbor_subprocess_environment)- monkeypatch.setattr(runner, "_resolve_runtime_env", lambda _templates: ({"SAFE_RUNTIME_FLAG": "enabled"}, []))+ monkeypatch.setattr(+ runner,+ "_resolve_runtime_env",+ lambda _templates, **_kwargs: ({"SAFE_RUNTIME_FLAG": "enabled"}, []),+ )result = runner.run_harbor_eval(skill,@@ -2314,7 +2318,7 @@ def test_runner_emits_truthful_stages_plan_and_per_agent_state(monkeypatch.setattr(runner, "find_evals_file", lambda _path: evals_file)monkeypatch.setattr(runner, "generate_harbor_tasks", _emit_tasks)monkeypatch.setattr(runner, "_provider_environment", lambda _provider: {"OPENAI_API_KEY": "sk-test-secret"})- monkeypatch.setattr(runner, "_resolve_runtime_env", lambda _templates: ({}, []))+ monkeypatch.setattr(runner, "_resolve_runtime_env", lambda _templates, **_kwargs: ({}, []))monkeypatch.setattr(runner, "_validate_agent_provider_credentials", lambda *_args, **_kwargs: [])monkeypatch.setattr(runner, "_harbor_subprocess_environment", lambda **_kwargs: {})from skillevaluator.tier3.harbor import runtime_preflight@@ -2808,7 +2812,11 @@ def test_runner_registers_exact_secrets_before_skill_and_model_render(skill_name=secret,provider_model=secret,)- monkeypatch.setattr(runner, "_resolve_runtime_env", lambda _templates: ({"CUSTOM_VALUE": secret}, []))+ monkeypatch.setattr(+ runner,+ "_resolve_runtime_env",+ lambda _templates, **_kwargs: ({"CUSTOM_VALUE": secret}, []),+ )output = io.StringIO()reporter = _progress_module().PlainProgressReporter(stream=output, refresh_interval=60)@@ -3127,3 +3135,29 @@ def test_command_runner_terminalizes_inherited_configuration_stage(("run-finished", "failed"),]assert transitions.count(("run-finished", "failed")) == 1+++def test_short_credential_named_flags_do_not_redact_counts() -> None:+ from skillevaluator.tier3.harbor.progress import redact_progress_detail, secret_values_from_environment++ secrets = secret_values_from_environment(+ {+ "SDK_HAS_HOST_AUTH_REFRESH": "1",+ "FEATURE_TOKEN_ENABLED": "yes",+ "SERVICE_API_KEY": "service-key-123456",+ "HTTPS_PROXY": "http://u:[email protected]:8080",+ }+ )++ assert "1" not in secrets+ assert "yes" not in secrets+ assert "service-key-123456" in secrets+ detail = redact_progress_detail(+ "Harbor job did not complete successfully: 1 errored; codex with-skill (0/1 scored) "+ "via http://u:[email protected]:8080 using service-key-123456",+ secret_values=secrets,+ )+ assert "1 errored" in detail+ assert "(0/1 scored)" in detail+ assert "service-key-123456" not in detail+ assert "u:p@" not in detaildiff --git a/tests/test_tier3_public_runtime.py b/tests/test_tier3_public_runtime.pyindex 1db3235d..4bf440da 100644--- a/tests/test_tier3_public_runtime.py+++ b/tests/test_tier3_public_runtime.py@@ -43,7 +43,7 @@ from skillevaluator.tier3.harbor.runner import (build_harbor_run_command,)from skillevaluator.tier3.harbor.runtime_preflight import ModelProbeResult-from skillevaluator.tier3_environments import HARBOR_NATIVE_ENV_MODES+from skillevaluator.tier3_environments import HARBOR_ENV_MODES, HARBOR_NATIVE_ENV_MODESdef _load_verifier_template():@@ -191,7 +191,7 @@ def test_native_environment_kwargs_round_trip_through_real_harbor_parser() -> No@pytest.mark.parametrize("env_mode", sorted(HARBOR_NATIVE_ENV_MODES - {"docker"}))def test_native_environment_kwargs_reject_unknown_harbor_022_names(env_mode: str) -> None:- with pytest.raises(ValueError, match=rf"Harbor 0\.22\.0 environment '{env_mode}'.*totally_ignored"):+ with pytest.raises(ValueError, match=rf"Harbor 0\.24\.0 environment '{env_mode}'.*totally_ignored"):build_harbor_run_command(dataset_path="/tmp/dataset",agent="codex",@@ -331,13 +331,11 @@ def test_environment_kwargs_cannot_override_sandbox_or_runtime_policy(("ack", "service_account", "cluster-admin"),("ack", "use_buildkit", True),("blaxel", "dind_extra_args", {"host": "tcp://0.0.0.0:2375"}),- ("cua-cloud", "claim_spec", {"serviceAccountName": "cluster-admin"}),("daytona", "network_block_all", False),("ec2", "iam_instance_profile", "administrator"),("ec2", "strict_host_key_checking", "no"),("gke", "memory_limit_multiplier", 0),("modal", "volumes", {"/workspace": "shared"}),- ("opensandbox", "volumes", [{"host_path": "/"}]),("openshift", "service_account_name", "cluster-admin"),("singularity", "singularity_no_mount", ""),("use-computer", "resources", {"cpu": 128, "memory": 1048576}),@@ -397,14 +395,6 @@ def test_backend_aliases_cannot_bypass_sandbox_runtime_policy("cloud_build_disk_size_gb": 500,},),- (- "opensandbox",- {- "entrypoint": ["/bin/sh", "-lc", "sleep infinity"],- "extensions": {"provider.example/feature": "enabled"},- "sandbox_timeout_sec": 7200,- },- ),],)def test_backend_operator_functionality_outside_policy_boundary_remains_usable(@@ -561,39 +551,19 @@ def test_ec2_private_ephemeral_environment_accepts_nonempty_subnet() -> None:)- ("environment_kwargs", "subprocess_env", "ready"),- [- ({}, {}, False),- ({}, {"OPENSANDBOX_DOMAIN": "sandbox.example.test"}, True),- ({"domain": "sandbox.example.test"}, {}, True),- ({"domain": None}, {}, False),- ({"domain": None}, {"OPENSANDBOX_DOMAIN": "sandbox.example.test"}, True),- ({"domain": ""}, {"OPENSANDBOX_DOMAIN": "sandbox.example.test"}, False),- ({"domain": " "}, {"OPENSANDBOX_DOMAIN": "sandbox.example.test"}, False),- ],-)-def test_opensandbox_domain_preflight_uses_effective_child_configuration(- monkeypatch: pytest.MonkeyPatch,- environment_kwargs: dict[str, object],- subprocess_env: dict[str, str],- ready: bool,-) -> None:- from harbor.environments.factory import EnvironmentFactory-- monkeypatch.setattr(EnvironmentFactory, "run_preflight", lambda *_args, **_kwargs: None)-- errors = _check_prerequisites(- env_mode="opensandbox",- agents=[],- environment_kwargs=environment_kwargs,- subprocess_env=subprocess_env,- )[email protected]("env_mode", ["cua-cloud", "opensandbox", "hf-sandbox"])+def test_unprovisionable_harbor_backends_are_not_publicly_supported(env_mode: str) -> None:+ with pytest.raises(ValueError, match="env_mode must be one of"):+ build_harbor_run_command(+ dataset_path="/tmp/dataset",+ agent="codex",+ job_name="unsupported-backend",+ env_mode=env_mode,+ )- assert (errors == []) is ready- if not ready:- assert len(errors) == 1- assert "domain" in errors[0]+ assert _check_prerequisites(env_mode=env_mode, agents=[]) == [+ f"Unsupported Harbor environment '{env_mode}'. Choose one of: " + ", ".join(sorted(HARBOR_ENV_MODES))+ ]def test_native_environment_required_kwargs_reject_whitespace_padded_ec2_launch_mode() -> None:@@ -606,9 +576,9 @@ def test_native_environment_required_kwargs_reject_whitespace_padded_ec2_launch_def test_native_environment_install_hints_use_real_harbor_022_extra_names() -> None:- assert "harbor[gke]==0.22.0" in _environment_extra_install_hint("ack")- assert "harbor[cloud]==0.22.0" not in _environment_extra_install_hint("ack")- assert "harbor[cua]==0.22.0" in _environment_extra_install_hint("cua-cloud")+ assert "harbor[gke]==0.24.0" in _environment_extra_install_hint("ack")+ assert "harbor[cloud]==0.24.0" not in _environment_extra_install_hint("ack")+ assert "harbor[cwsandbox]==0.24.0" in _environment_extra_install_hint("wandb")assert "no Python extra" in _environment_extra_install_hint("openshift")@@ -710,13 +680,25 @@ def test_custom_agent_import_path_preserves_native_cloud_environment(env_mode: smodel=model,)- assert command[command.index("--agent-import-path") + 1] == import_path+ assert command[command.index("--agent") + 1] == import_pathassert command[command.index("--env") + 1] == env_modeassert command[command.index("--model") + 1] == modelassert "-a" not in command+ assert "--agent-import-path" not in commandassert "--environment-import-path" not in command+def test_custom_agent_import_path_is_rejected_for_native_cloud() -> None:+ with pytest.raises(ValueError, match="agent_import_path is supported only with --env docker or local"):+ build_harbor_run_command(+ dataset_path="/tmp/dataset",+ agent="codex",+ job_name="bridge-test",+ env_mode="e2b",+ agent_import_path="example:Agent",+ )++def test_evaluate_forwards_native_environment_without_legacy_sandbox_configuration(monkeypatch, tmp_path) -> None:skill = tmp_path / "skill"skill.mkdir()@@ -2463,49 +2445,58 @@ def test_native_harbor_metadata_entry_id_seam_across_runner_collector_and_dataseagent_import_path: str | None = None,verifier_env: object = None,include_task_names: list[str] | None = None,+ environment_kwargs: object = None,) -> tuple[bool, str]:+ from datetime import UTC, datetime+ from uuid import uuid4++ from harbor.models.job.result import JobResult, JobStats+ from harbor.models.trial.result import TrialResult+seen_include_task_names.append(include_task_names)job_dir = jobs_dir / job_nameis_with = "-with-" in job_name or job_name.endswith("-with")arm_suffix = "-with-skill" if is_with else "-without-skill"selected_folders = include_task_names or ["physical-case", "zero-case"]- trial_names: list[str] = []+ now = datetime(2026, 9, 12, tzinfo=UTC)+ trial_results: list[TrialResult] = []for idx, folder in enumerate(selected_folders, start=1):trial_name = f"trial-{idx}-{folder}__attempt1"- trial_names.append(trial_name)trial_dir = job_dir / trial_nametrial_dir.mkdir(parents=True, exist_ok=True)- # Notice result.json only has task_name derived from the staged [task].name (physical-case),- # not [metadata].entry_id, exercising collector's staged task.toml entry_id lookup!- (trial_dir / "result.json").write_text(- json.dumps(- {- "trial_name": trial_name,- "task_name": f"nvidia/{folder}{arm_suffix}_attempt1",- "verifier_result": {"rewards": {"reward": 1.0 if is_with else 0.25}},- }- ),- encoding="utf-8",- )- (job_dir / "result.json").write_text(- json.dumps(+ # Harbor persists the staged task path, while task_name carries the+ # suffixed display name; only the runner's selector map may turn the+ # staged directory into the authored [metadata].entry_id.+ task_path = str(dataset / folder)+ trial_result = TrialResult.model_validate({- "n_total_trials": len(trial_names),- "stats": {- "n_trials": len(trial_names),- "n_errors": 0,- "evals": {- agent: {- "n_trials": len(trial_names),- "n_errors": 0,- "reward_stats": {"reward": {"1.0": trial_names}},- }- },- },+ "id": uuid4(),+ "task_name": f"nvidia/{folder}{arm_suffix}_attempt1",+ "trial_name": trial_name,+ "trial_uri": trial_dir.as_uri(),+ "task_id": {"path": task_path},+ "task_checksum": "native-entry-id-seam-fixture",+ "config": {"task": {"path": task_path}, "trial_name": trial_name, "trials_dir": str(job_dir)},+ "agent_info": {"name": agent, "version": "test", "model_info": {"name": "test-model"}},+ "agent_result": {},+ "verifier_result": {"rewards": {"reward": 1.0 if is_with else 0.25}},+ "started_at": now,+ "finished_at": now,}- ),- encoding="utf-8",+ )+ (trial_dir / "result.json").write_text(trial_result.model_dump_json(indent=2), encoding="utf-8")+ (trial_dir / "config.json").write_text(trial_result.config.model_dump_json(indent=2), encoding="utf-8")+ trial_results.append(trial_result)+ job_result = JobResult(+ id=uuid4(),+ started_at=now,+ updated_at=now,+ finished_at=now,+ n_total_trials=len(trial_results),+ stats=JobStats.from_trial_results(trial_results, n_total_trials=len(trial_results)),+ trial_results=[],)+ (job_dir / "result.json").write_text(job_result.model_dump_json(indent=2), encoding="utf-8")return True, ""monkeypatch.setattr(runner, "_run_harbor", fake_run_harbor)@@ -2611,3 +2602,50 @@ def test_write_task_toml_forwards_retry_env(tmp_path: Path) -> None:assert verifier_env["SKILL_EVAL_LLM_RETRY_BASE_DELAY"] == "${SKILL_EVAL_LLM_RETRY_BASE_DELAY}"assert verifier_env["SKILL_EVAL_LLM_RETRY_MAX_DELAY"] == "${SKILL_EVAL_LLM_RETRY_MAX_DELAY}"assert "UNRELATED_CUSTOM_VAR" not in verifier_env+++ ("env_mode", "agent_import_path"),+ [+ ("docker", None),+ ("docker", "skillevaluator.tier3.harbor.local_agents:SkillEvaluatorNvidiaBuildCodex"),+ ("local", None),+ ("e2b", None),+ ("daytona", "skillevaluator.tier3.harbor.local_agents:SkillEvaluatorGatewayCodex"),+ ],+)+def test_codex_runs_pin_harbor_022_reasoning_effort(env_mode: str, agent_import_path: str | None) -> None:+ from harbor.cli.utils import parse_kwargs++ command = build_harbor_run_command(+ dataset_path="/tmp/dataset",+ agent="codex",+ job_name="effort",+ env_mode=env_mode,+ agent_import_path=agent_import_path,+ )++ agent_kwargs = [command[index + 1] for index, value in enumerate(command) if value == "--ak"]+ assert parse_kwargs(agent_kwargs) == {"reasoning_effort": "high"}++[email protected]("agent", ["claude-code", "opencode"])+def test_non_codex_runs_pass_no_agent_kwargs(agent: str) -> None:+ command = build_harbor_run_command(dataset_path="/tmp/dataset", agent=agent, job_name="effort", env_mode="docker")++ assert "--ak" not in command+++def test_codex_agents_render_the_pinned_reasoning_effort(tmp_path: Path) -> None:+ from harbor.agents.installed.codex import Codex++ from skillevaluator.tier3.harbor import local_agents++ for agent_class in (+ Codex,+ local_agents.SkillEvaluatorGatewayCodex,+ local_agents.SkillEvaluatorLocalCodex,+ local_agents.SkillEvaluatorNvidiaBuildCodex,+ ):+ agent = agent_class(logs_dir=tmp_path, model_name="openai/gpt-5", reasoning_effort="high")+ assert "-c model_reasoning_effort=high" in agent.build_cli_flags(), agent_class.__name__diff --git a/tests/tier3/test_codex_tool_call_normalization.py b/tests/tier3/test_codex_tool_call_normalization.pyindex 27d99710..036a775c 100644--- a/tests/tier3/test_codex_tool_call_normalization.py+++ b/tests/tier3/test_codex_tool_call_normalization.py@@ -983,7 +983,7 @@ def test_native_codex_exec_evidence_refs_resolve_to_the_outer_call():def test_copied_verifier_imports_its_sibling_codex_normalizer(tmp_path):adapter._copy_verifier(tmp_path)- tests_dir = tmp_path / "tests"+ tests_dir = tmp_path / "tests" / adapter._EVALUATOR_TESTS_SUBDIRnormalizer = tests_dir / "codex_tool_call_normalizer.py"evidence = tests_dir / "evidence.py"assert normalizer.is_file()@@ -1003,3 +1003,58 @@ def test_copied_verifier_imports_its_sibling_codex_normalizer(tmp_path):]== "exec_command")+++def _multimodal_trajectory() -> dict:+ return {+ "steps": [+ {+ "source": "agent",+ "tool_calls": [{"tool_call_id": "call-1", "function_name": "view_image", "arguments": {}}],+ "observation": {+ "results": [+ {+ "source_call_id": "call-1",+ "content": [+ {"type": "text", "text": "rendered chart"},+ {"type": "image", "source": {"media_type": "image/png", "path": "/secret/a.png"}},+ {"type": "audio", "source": {"media_type": "audio/wav", "path": "/secret/a.wav"}},+ {"type": "video"},+ ],+ }+ ]+ },+ }+ ]+ }+++def test_atif_content_text_flattens_parts_without_source_paths() -> None:+ content = _multimodal_trajectory()["steps"][0]["observation"]["results"][0]["content"]++ assert codex_tool_call_normalizer.atif_content_text(None) == ""+ assert codex_tool_call_normalizer.atif_content_text("plain") == "plain"+ assert codex_tool_call_normalizer.atif_content_text(content) == "rendered chart\n[image]\n[audio]"+ assert "/secret" not in codex_tool_call_normalizer.atif_content_text(content)++[email protected]("extract", _EXTRACTORS)+def test_list_observation_content_is_text_not_repr(extract) -> None:+ [call] = extract(_multimodal_trajectory())++ assert call["observation"] == "rendered chart\n[image]\n[audio]"+++def test_host_and_template_summaries_agree_on_list_observations() -> None:+ from skillevaluator.tier3.eval_core import atif_helpers++ trajectory = _multimodal_trajectory()++ host = atif_helpers.build_conversation_summary(trajectory, "question")+ template = _TEMPLATE_MODULE.build_conversation_summary(trajectory, "question")+ assert host == template+ assert "Tool returned: rendered chart\n[image]\n[audio]" in host+ assert "/secret" not in host+ assert atif_helpers._late_observation_excerpts(trajectory, 200) == _TEMPLATE_MODULE._late_observation_excerpts(+ trajectory, 200+ )diff --git a/tests/tier3/test_gateway_codex.py b/tests/tier3/test_gateway_codex.pyindex 05ad7823..0283653c 100644--- a/tests/tier3/test_gateway_codex.py+++ b/tests/tier3/test_gateway_codex.py@@ -3,8 +3,10 @@import asyncioimport shlex+from pathlib import Pathimport pytest+import tomlfrom harbor.agents.factory import AgentFactoryfrom harbor.environments.base import ExecResultfrom harbor.models.agent.context import AgentContext@@ -86,27 +88,45 @@ def test_selected_codex_launcher_preserves_provider_model_contract(if mode in {"e2b", "daytona"}:assert option_value("--env") == modeassert "--environment-import-path" not in command+ # Harbor's unified --agent selector carries either a built-in name or an import path.+ selected_agent = option_value("--agent")+ assert selected_agent is not None+ assert "-a" not in command+ assert "--agent-import-path" not in commandagent = AgentFactory.create_agent_from_config(AgentConfig(- name=option_value("-a"),- import_path=option_value("--agent-import-path"),+ name=None if ":" in selected_agent else selected_agent,+ import_path=selected_agent if ":" in selected_agent else None,model_name=option_value("--model"),),logs_dir=tmp_path / "logs",)class RecordingEnvironment:+ default_user = None+def __init__(self):self.commands = []+ self.uploads = {}async def exec(self, command, **kwargs):self.commands.append((command, kwargs.get("env") or {}))return ExecResult(return_code=0, stdout="", stderr="")+ async def upload_file(self, source_path, target_path):+ self.uploads[str(target_path)] = Path(source_path).read_text(encoding="utf-8")+environment = RecordingEnvironment()instruction = "quote --model gpt-5.6-sol and /tmp/codex-secrets literally"asyncio.run(agent.run(instruction, environment=environment, context=AgentContext()))+ # Harbor uploads the effective Codex config; gateway routing must survive it.+ configs = [toml.loads(text) for path, text in environment.uploads.items() if path.endswith("config.toml")]+ if base_url:+ assert len(configs) == 1+ assert configs[0]["model_provider"] == "openai_compatible"+ assert configs[0]["model_providers"]["openai_compatible"]["base_url"] == base_url+launchers = [(text, env) for text, env in environment.commands if "codex exec " in text]assert len(launchers) == 1launcher, launch_env = launchers[0]diff --git a/tests/tier3/test_generate_dataset_results.py b/tests/tier3/test_generate_dataset_results.pyindex 2e21d77b..cd74f4be 100644--- a/tests/tier3/test_generate_dataset_results.py+++ b/tests/tier3/test_generate_dataset_results.py@@ -622,3 +622,46 @@ def test_parse_skill_includes_tools_dir_scripts(tmp_path):(tools / "run.py").write_text("print('hello')\n", encoding="utf-8")parsed = generate_dataset._parse_skill(skill)assert parsed["scripts"] == ["run.py"]+++_BLOCK_HARBOR_AND_RESOLVE_CASE = """+import importlib.abc+import json+import sys+from pathlib import Path+++class _BlockHarbor(importlib.abc.MetaPathFinder):+ def find_spec(self, name, path=None, target=None):+ if name == "harbor" or name.startswith("harbor."):+ raise ImportError(name)+ return None+++sys.meta_path.insert(0, _BlockHarbor())+from skillevaluator.tier3 import generate_dataset++case_id = generate_dataset._case_id_from_trial_dir(Path(sys.argv[1]))+print(json.dumps({"case_id": case_id, "harbor_loaded": "harbor" in sys.modules}))+"""+++def test_refine_resolves_result_case_ids_without_the_tier3_extra(tmp_path: Path) -> None:+ import subprocess++ trial = tmp_path / "case-007__abc1234"+ trial.mkdir()+ (trial / "result.json").write_text(+ json.dumps({"task_id": {"path": str(tmp_path / "tasks" / "case-007")}}),+ encoding="utf-8",+ )++ completed = subprocess.run(+ [sys.executable, "-c", _BLOCK_HARBOR_AND_RESOLVE_CASE, str(trial)],+ capture_output=True,+ text=True,+ check=False,+ )++ assert completed.returncode == 0, completed.stderr+ assert json.loads(completed.stdout) == {"case_id": "case-007", "harbor_loaded": False}diff --git a/tests/tier3/test_harbor_security_attribution.py b/tests/tier3/test_harbor_security_attribution.pyindex be9b5046..82063858 100644--- a/tests/tier3/test_harbor_security_attribution.py+++ b/tests/tier3/test_harbor_security_attribution.py@@ -165,3 +165,25 @@ def test_security_attribution_bounds_case_details_with_exact_metadata():assert summary["case_details_shown"] == 256assert summary["case_details_truncated"] is Trueassert len(summary["cases"]) == 256+++def test_security_attribution_preserves_distinct_authored_ids_without_expected_set():+ """Verify authored IDs like case-1-with-skill and skillevaluator-case-1 do not collapse onto case-1."""+ with_rewards = [+ _reward("case-1", []),+ _reward("case-1-with-skill", [_finding(target_skill_used_before=True)]),+ _reward("skillevaluator-case-1", [_finding(target_skill_used_before=True)]),+ ]+ without_rewards = [+ _reward("case-1", [_finding()]),+ _reward("case-1-with-skill", []),+ _reward("skillevaluator-case-1", []),+ ]++ summary = _annotate_security_attribution(with_rewards, without_rewards)++ assert with_rewards[1]["details"]["security"]["findings"][0]["attribution"] == "likely_skill_related"+ assert with_rewards[2]["details"]["security"]["findings"][0]["attribution"] == "likely_skill_related"+ assert summary["likely_skill_related"] == 2+ assert summary["likely_baseline_prompt_or_environment"] == 0+ assert set(summary["cases"]) == {"case-1", "case-1-with-skill", "skillevaluator-case-1"}diff --git a/tests/tier3/test_judge_failure_artifacts.py b/tests/tier3/test_judge_failure_artifacts.pyindex 756a6c41..38e2317e 100644--- a/tests/tier3/test_judge_failure_artifacts.py+++ b/tests/tier3/test_judge_failure_artifacts.py@@ -21,6 +21,7 @@ from types import ModuleType, SimpleNamespaceimport pytest+from skillevaluator.tier3.harbor import collector, reportfrom skillevaluator.tier3.harbor.adapter import _EVALUATOR_TESTS_SUBDIR, _write_test_shfrom skillevaluator.tier3.harbor.metrics import (DEFAULT_METRIC_SET,diff --git a/tests/tier3/test_suggestion_grounding.py b/tests/tier3/test_suggestion_grounding.pyindex 9f82205d..e9650342 100644--- a/tests/tier3/test_suggestion_grounding.py+++ b/tests/tier3/test_suggestion_grounding.py@@ -6,6 +6,7 @@ import jsonimport pytestfrom skillevaluator.tier3.harbor import report+from skillevaluator.tier3.harbor.metrics import CUSTOM_ONLY_METRIC_SET, DEFAULT_METRIC_SET, DEFAULT_METRICSdef _reward(metric_score=0.1):@@ -204,6 +205,94 @@ def test_findings_best_agent_ignores_invalid_legacy_summary_numbers(invalid: floassert report._pick_best_agent(agents) == "valid"+def test_findings_best_agent_matches_canonical_dimension_ranking_and_suggestion_identity(tmp_path, monkeypatch):+ from skillevaluator.evaluation.tier3_report import build_agent_eval_payload++ standard_scores = dict(zip(DEFAULT_METRICS, (1.0, 1.0, 1.0, 1.0, 0.0, 0.0), strict=True))+ standard_reward = _reward(0.0)+ standard_reward.update(+ {+ "entry_id": "standard-case",+ "metric_set": DEFAULT_METRIC_SET,+ "behavior_check": 0.0,+ }+ )+ custom_reward = {+ "entry_id": "custom-case",+ "metric_set": CUSTOM_ONLY_METRIC_SET,+ "overall": 0.75,+ "custom_metrics": {"domain_quality": 0.75},+ "custom_details": {"domain_quality": {"reason": "custom evidence"}},+ }+ specs = {+ "standard-agent": (standard_scores, {}, list(DEFAULT_METRICS), 4 / 6, standard_reward),+ "custom-agent": ({}, {"domain_quality": 0.75}, [], 0.75, custom_reward),+ }+ live_agents = {}+ for agent, (scores, custom_scores, metrics, overall, reward) in specs.items():+ condition_dir = tmp_path / agent / "with-skill"+ trial_dir = condition_dir / "trials" / f"{reward['entry_id']}__attempt"+ trial_dir.mkdir(parents=True)+ (condition_dir / "summary.json").write_text(+ json.dumps(+ {+ "agent": agent,+ "scores": scores,+ "custom_scores": custom_scores,+ "overall_score": overall,+ "metrics": metrics,+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 1,+ "scored_attempts": 1,+ "num_trials": 1,+ "num_reward_rows": 1,+ }+ ),+ encoding="utf-8",+ )+ (trial_dir / "reward.json").write_text(json.dumps(reward), encoding="utf-8")+ live_agents[agent] = {+ "execution_status": "succeeded",+ "with_skill": scores,+ "custom_with_skill": custom_scores,+ "conditions": {"with_skill": {"execution_status": "succeeded"}},+ }++ loaded_agents = report.report_data.load_agent_data(tmp_path)+ canonical = build_agent_eval_payload(+ "demo",+ loaded_agents,+ use_llm_judge=False,+ )+ assert canonical is not None+ assert canonical["agents"]["standard-agent"]["with_skill"] == 0.8+ assert canonical["agents"]["custom-agent"]["with_skill"] == 0.75+ assert canonical["best_agent"] == "standard-agent"+ assert report._pick_best_agent(live_agents, loaded_agents) == canonical["best_agent"]++ selected_reward_ids = []++ def fake_suggestions(_skill, _findings, rewards):+ selected_reward_ids.extend(reward["entry_id"] for reward in rewards)+ return [{"suggestion": "Fix the standard case.", "dimension": "effectiveness", "evidence_refs": []}]++ monkeypatch.setattr(report, "_generate_suggestions_structured", fake_suggestions)+ report.display_findings_report(+ {"agents": live_agents},+ "demo",+ ["custom-agent", "standard-agent"],+ tmp_path,+ )++ assert selected_reward_ids == ["standard-case"]+ standard_artifact = json.loads((tmp_path / "standard-agent" / "findings.json").read_text(encoding="utf-8"))+ custom_artifact = json.loads((tmp_path / "custom-agent" / "findings.json").read_text(encoding="utf-8"))+ assert standard_artifact["suggestions_v2"][0]["suggestion"] == "Fix the standard case."+ assert custom_artifact["suggestions_v2"] == []+ assert custom_artifact["suggestion_mode"] == "not_generated"++def test_passing_suggestions_count_mixed_current_and_legacy_logical_trials():suggestions = report._passing_skill_suggestions([],@@ -377,6 +466,68 @@ def test_suggestions_evidence_refs_lookup_uses_all_metrics(monkeypatch):assert refs[0]["kind"] == "tool_call"[email protected]("metric_set", [DEFAULT_METRIC_SET, CUSTOM_ONLY_METRIC_SET])+def test_suggestions_evidence_lookup_prefers_custom_detail_for_custom_metric_collision(monkeypatch, metric_set):+ compact_ref = "trajectory.json#/steps/8"+ reward = {+ "entry_id": "custom-case",+ "metric_set": metric_set,+ "overall": 0.2,+ "custom_metrics": {"domain_quality": 0.2},+ "details": {+ "domain_quality": {+ "reason": "stale ordinary detail",+ "evidence_refs": [+ {+ "source": "trajectory.json",+ "json_pointer": "/steps/8",+ "kind": "stale",+ "excerpt": "stale evidence",+ }+ ],+ }+ },+ "custom_details": {+ "domain_quality": {+ "reason": "authoritative custom detail",+ "evidence_refs": [+ {+ "source": "trajectory.json",+ "json_pointer": "/steps/8",+ "kind": "custom_evidence",+ "excerpt": "authoritative evidence",+ }+ ],+ }+ },+ }+ if metric_set == DEFAULT_METRIC_SET:+ reward.update(dict.fromkeys(DEFAULT_METRICS, 1.0))+ monkeypatch.setattr(+ "skillevaluator.tier3.eval_core.llm_judge.call_public_llm",+ lambda _prompt, **_kw: (+ '[{"suggestion": "Fix custom scoring", "dimension": "domain_quality", '+ f'"evidence_refs": ["{compact_ref}"]}}]',+ None,+ ),+ )++ findings = report._extract_findings([reward])+ suggestion = report._generate_suggestions_structured("demo", findings, [reward])[0]++ assert next(item for item in findings if item["metric"] == "domain_quality")["reasons"] == [+ "authoritative custom detail"+ ]+ assert suggestion["evidence_refs"] == [+ {+ "source": "trajectory.json",+ "json_pointer": "/steps/8",+ "kind": "custom_evidence",+ "excerpt": "authoritative evidence",+ }+ ]++def test_normalized_tool_evidence_refs_remain_distinct_and_resolve_by_compact_identity(monkeypatch):compact_ref = "trajectory.json#/steps/0/tool_calls/0/normalized/1"captured = {}diff --git a/uv.lock b/uv.lockindex 0766d8ce..7b242466 100644--- a/uv.lock+++ b/uv.lock@@ -658,7 +658,7 @@ wheels = [[[package]]name = "harbor"-version = "0.22.0"+version = "0.24.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "dirhash" },@@ -666,6 +666,7 @@ dependencies = [{ name = "filelock" },{ name = "httpx" },{ name = "jinja2" },+ { name = "jsonschema" },{ name = "litellm" },{ name = "packaging" },{ name = "pathspec" },@@ -676,6 +677,7 @@ dependencies = [{ name = "pyyaml" },{ name = "requests" },{ name = "rich" },+ { name = "semver" },{ name = "shortuuid" },{ name = "supabase" },{ name = "tenacity" },@@ -683,9 +685,9 @@ dependencies = [{ name = "typer" },{ name = "uvicorn" },]-sdist = { url = "https://files.pythonhosted.org/packages/12/a0/a37532fb647b93ef709b63a7fbdf613a84837a569fdd88f69dd7105bf093/harbor-0.22.0.tar.gz", hash = "sha256:becf0ce354026cc37899855e0a0d2687cd5188034a43635849245069aad0938b", size = 1832554, upload-time = "2026-08-22T03:22:39.798Z" }+sdist = { url = "https://files.pythonhosted.org/packages/82/7d/16e21cfd52938260dce71ff77ec1ed156bd8c327642760fe66163b0cd3ce/harbor-0.24.0.tar.gz", hash = "sha256:6c5185e6a76abc677ed3f95e688dc0dbf8597e4fa50847cb9a37a4448c91b1e5", size = 2090577, upload-time = "2026-10-05T05:04:46.252Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/ce/12/d517f1ca18738f7be78a210b13264c64bace531fdf644632128966aca530/harbor-0.22.0-py3-none-any.whl", hash = "sha256:4c4c6571b3d160ed0cb45b82918136751fb08e7b8596412723ac00dde12eeabb", size = 2058718, upload-time = "2026-08-22T03:22:38.071Z" },+ { url = "https://files.pythonhosted.org/packages/9e/63/0e3d788e8d1ed116125507c6a01e3fb95cf82be71f2ea7040a1458709d21/harbor-0.24.0-py3-none-any.whl", hash = "sha256:23b7ba616a3aae4eff561ced5e2c51c7186f2981e53a770dea9c689d3969877c", size = 2331740, upload-time = "2026-10-05T05:04:42.088Z" },][[package]]@@ -1783,6 +1785,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/93/ce/828467ddfa0d2fe473673026442d2032d552a168e42cfbf25fd0e5264e0c/scantree-0.0.4-py3-none-any.whl", hash = "sha256:7616ab65aa6b7f16fcf8e6fa1d9afaa99a27ab72bba05c61b691853b96763174", size = 20690, upload-time = "2024-08-03T20:08:58.137Z" },]+[[package]]+name = "semver"+version = "3.1.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/92/f5/e1dfe8e1d91c54ce212fd93916eb01fd1c590f413be0a0978c39a97aa1bb/semver-3.1.0.tar.gz", hash = "sha256:14bc073439513d7773662a338f4db9829cf16c12b74b9568e2d2689975fbd7fc", size = 304162, upload-time = "2026-09-12T18:38:14.045Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/be/02/bce7a1d70e9d0f6ea8623c16386138c251b5855af6cd3a11433d3fba4e66/semver-3.1.0-py3-none-any.whl", hash = "sha256:6e4998f8b4762acdfea85f9bfd5b4032e0bb50038dc04bf82011b42d5d1145c5", size = 18783, upload-time = "2026-09-12T18:38:12.457Z" },+]+[[package]]name = "shellingham"version = "1.5.4"@@ -1835,6 +1846,7 @@ all = [{ name = "openai" },{ name = "pip-audit" },{ name = "pyjwt", extra = ["crypto"] },+ { name = "python-dotenv" },]dev = [{ name = "build" },@@ -1868,6 +1880,7 @@ tier3 = [{ name = "mcp" },{ name = "openai" },{ name = "pyjwt", extra = ["crypto"] },+ { name = "python-dotenv" },][package.metadata]@@ -1877,7 +1890,7 @@ requires-dist = [{ name = "boto3", marker = "extra == 'llm'", specifier = ">=1.34.0" },{ name = "build", marker = "extra == 'dev'", specifier = ">=1.2" },{ name = "click", specifier = ">=8.3.3,<9" },- { name = "harbor", marker = "extra == 'tier3'", specifier = "==0.22.0" },+ { name = "harbor", marker = "extra == 'tier3'", specifier = "==0.24.0" },{ name = "httpx", marker = "extra == 'dev'", specifier = ">=0.27" },{ name = "idna", specifier = ">=3.10,<4" },{ name = "jinja2", specifier = ">=3.1" },@@ -1891,6 +1904,7 @@ requires-dist = [{ name = "pytest", marker = "extra == 'dev'", specifier = ">=8.4.0" },{ name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=6.2.0" },{ name = "pytest-xdist", marker = "extra == 'dev'", specifier = ">=3.6.0" },+ { name = "python-dotenv", marker = "extra == 'tier3'", specifier = ">=1.2.0" },{ name = "pyyaml", specifier = ">=6.0" },{ name = "rich", specifier = ">=13.5.0" },{ name = "ruff", marker = "extra == 'dev'", specifier = ">=0.15.4,<0.16" },