Skip to content

Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.

feat(tier3): add selectable NeMo Gym execution backend (#225)

Christopher Kevina2da2440a65f
diff --git a/.gitleaks.toml b/.gitleaks.toml
index 7c8207fd..7b3b3660 100644
--- a/.gitleaks.toml
+++ b/.gitleaks.toml
@@ -10,6 +10,13 @@ targetRules = ["generic-api-key"]
regexes = ['''^sk-AbCdEf1234567890$''']
paths = ['''^tests/test_tier3_(progress|result_display)\.py$''']
+[[allowlists]]
+description = "Synthetic policy key used by NeMo Gym rollout redaction tests"
+condition = "AND"
+targetRules = ["generic-api-key"]
+regexes = ['''^gw-policy-0a1b2c3d4e5f6789$''']
+paths = ['''^tests/test_nemo_gym_backend\.py$''']
+
[[allowlists]]
description = "Synthetic curl basic-auth credential used by judge evidence redaction tests"
condition = "AND"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 024a66dc..8c207c41 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,47 @@ All notable changes to SkillEvaluator are documented in this file.
## Unreleased
+### Added
+
+- Experimental `tier3 evaluate --backend nemo-gym` targets a native Gym task-folder
+ interface. Public `nemo-gym==0.7.0` is incompatible; public source candidate
+ `NVIDIA-NeMo/Gym@792fa142f58277aecff05d402061d647e9a92acf` exposes the required
+ `TARGET` help interface but still needs independent native runtime qualification.
+ CLI compatibility is checked before dataset generation or task staging, with bounded combined help output and process-group cleanup on timeout,
+ interruption or overflow. Doctor no longer treats an installed version as runtime readiness.
+ Live Codex, Claude Code and OpenCode support remains unverified. The adapter's
+ intended contract runs the Tier 3 cases on NeMo Gym instead
+ of Harbor (`--backend harbor`, the default, is unchanged). The same
+ `evals.json` cases are generated as task folders, and NeMo Gym's own
+ orchestrator, agent harness (Codex, Claude Code, OpenCode) and Docker sandbox
+ run them with the SkillEvaluator verifier. Its rollouts are written back as
+ the usual trial results, so scores, lift, reports and `result.json` are
+ shared; `result.json` records `execution_backend` with the NeMo Gym version.
+ Gym runs as a separate pinned process (`SKILL_EVAL_NEMO_GYM_BIN`) because it
+ needs Python 3.13.14 or later. Options the backend cannot honor (other
+ environment modes, `--harbor-keep-jobs`, `--stop-on-pass`, ...)
+ are rejected before anything runs, with no fallback to Harbor.
+ `--timeout-multiplier`, `--copy-repo`, `harbor.agent_workdir` and
+ `harbor.pre_agent_setup`, `skill_workspace.decoy_manifest` and
+ `--custom-dockerfile-mode preserve`, `harbor.base_image_mode` and native
+ `evals/harbor/` tasks work as on Harbor, and
+ `tier3 doctor --backend nemo-gym` checks Gym readiness. When a Gym process group
+ cannot be confirmed stopped after a timeout or interruption, no further arm starts
+ beside it and the failure is reported. After a timeout, the failed run still keeps
+ the scores of the arms that finished.
+
+### Fixed
+
+- A failed Tier 3 execution (for example a backend launch failure) now marks the
+ report payload, its summary and the affected agents as failed with their
+ errors, instead of only the top-level `result.json`. A report re-rendered by
+ `tier3 view` reads the status from the run's `result.json`. Scores from the
+ completed trials are kept.
+- Skill activation now credits a SKILL.md read wrapped in a shell, such as
+ `/bin/bash -lc 'cat skills/x/SKILL.md'`, which some agent harnesses record
+ instead of the bare command. Searches inside a wrapper (`bash -c 'grep SKILL
+ config.json'`) are still not counted.
+
## 0.9.0 - 2026-11-13
### Fixed
diff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdx
index 9e1774bd..1bc9142d 100644
--- a/docs/cli-reference.mdx
+++ b/docs/cli-reference.mdx
@@ -591,6 +591,7 @@ Use `skillevaluator tier3 PATH` for the complete workflow with automatic missing
| --- | --- | --- |
| `-a, --agents TEXT` | provider-native | Comma-separated Harbor agents. Defaults: NVIDIA Build=`opencode`, OpenAI=`codex`, Anthropic=`claude-code`. Supported: `claude-code`, `codex`, `opencode`; Experimental: `hermes` (Docker with NVIDIA Build only; see [Experimental Hermes](/skills/skillevaluator/agents-and-sandboxes#experimental-hermes)). The alias `claude` is accepted for `claude-code`. See [Agents & Sandboxes](/skills/skillevaluator/agents-and-sandboxes). |
| `--env-mode` | `docker` | Where trials run. SkillEvaluator exposes 27 environment modes: 26 Harbor-native modes — `docker`, `daytona`, `e2b`, `modal`, `runloop`, `langsmith`, `ec2`, `gke`, `ack`, `openshift`, `novita`, `apple-container`, `singularity`, `islo`, `tensorlake`, `cwsandbox`, `wandb`, `use-computer`, `blaxel`, `beam`, `skypilot`, `hyperbrowser`, `vercel`, `kata`, `runta`, `mosaic` — plus SkillEvaluator `local` mode. `wandb` runs Harbor's `cwsandbox` backend with W&B authentication, so it needs the `harbor[cwsandbox]==0.25.0` extra; Harbor 0.25 has no `wandb` extra. Harbor's `cua-cloud`, `opensandbox`, `hf-sandbox`, `podman`, `prime`, `smol`, `sbx`, `sail`, and `kernel` backends are not selectable. See the complete extras and prerequisites matrix in [Agents & Sandboxes](/skills/skillevaluator/agents-and-sandboxes#where-trials-run). Installed packages can add more modes; see [Custom execution backends](/skills/skillevaluator/agents-and-sandboxes#custom-execution-backends). |
+| `--backend` | `harbor` | Execution backend: `harbor`, or the experimental `nemo-gym` task-folder adapter. Public Gym 0.7.0 is incompatible; see [Execution backends](/skills/skillevaluator/tier3-live-evaluation#execution-backends). |
| `--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, Kata accepts only `kata_runtime` and `kata_dns`, and Harbor runtime-policy fields for overrides, mounts, networks, extra Compose, lifecycle, and pod security are reserved, as are `stream`, `enable_environment_dir_upload`, `auto_mounts`, `auto_mounting`, and `auth`/`forward_compose_env` for `cwsandbox`/`wandb`. Names the selected backend does not accept in Harbor 0.25.0 are rejected. See [Native backend constructor options](/skills/skillevaluator/agents-and-sandboxes#native-backend-constructor-options). |
| `--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). |
@@ -962,11 +963,12 @@ An option for a tier that is not selected exits with a usage error before any ch
| `--timeout FLOAT` | `60` | Tier 1, and Tier 2 with `--verify-models`. Seconds allowed for each scanner version probe and each Tier 2 live request, including a Bedrock chat request; must be finite, greater than 0 and at most 3600. |
| `-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 27 modes as [tier3 evaluate](#tier3-evaluate)). |
+| `--backend [harbor\|nemo-gym]` | `harbor` | Execution backend to check, as in [tier3 evaluate](#tier3-evaluate). `nemo-gym` checks the Gym CLI, the Docker daemon, the `SKILL_EVAL_NEMO_GYM_*` settings and each agent's policy endpoint. |
| `--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, and Kata accepts only `kata_runtime` and `kata_dns`; 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 | Tier 3: 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. Tier 2: one embedding and one chat request. |
-`-a`, `--env-mode`, `--environment-kwarg` and `--agent-model` apply to Tier 3 only. `skillevaluator tier3 doctor` checks only Tier 3. It takes the Tier 3 flags, including `--agent-model` and `--verify-models`, and has no `--tier`, `--checks` or `--timeout`.
+`-a`, `--env-mode`, `--backend`, `--environment-kwarg` and `--agent-model` apply to Tier 3 only. `skillevaluator tier3 doctor` checks only Tier 3. It takes the Tier 3 flags, including `--agent-model` and `--verify-models`, and has no `--tier`, `--checks` or `--timeout`.
## health-check
diff --git a/docs/environment-variables.mdx b/docs/environment-variables.mdx
index 6557b275..f8078965 100644
--- a/docs/environment-variables.mdx
+++ b/docs/environment-variables.mdx
@@ -156,6 +156,12 @@ execution environments are covered in
| `SKILLEVALUATOR_RESULTS_DIR` | `<skill>/evals/results` | External root for run results. Precedence for writes: the `--results-dir` flag, then this variable, then the canonical in-skill location. Configured roots must remain outside the skill; `evals/results` is the only supported in-skill results root so generated output cannot change the skill's publication identity. Read commands (`view`, `compare`) honor the same order and also fall back to the legacy location so older runs stay visible. |
| `SKILLEVALUATOR_OUTPUT_PROVENANCE_KEY_FILE` | macOS: `~/Library/Application Support/skillevaluator/output-provenance.key`; Linux: `$XDG_STATE_HOME/skillevaluator/output-provenance.key` (`~/.local/state` when `XDG_STATE_HOME` is unset); Windows: `%LOCALAPPDATA%\skillevaluator\output-provenance.key` | Local key that authenticates the markers SkillEvaluator writes into its generated output directories; a directory is replaced only when its marker verifies for that path. The key is created on first use. It must be outside every evaluated skill and generated output tree. On macOS and Linux, the file and its directory must be owned by the current user and not accessible to group or other users. |
| `SKILLEVALUATOR_LOCAL_SANDBOX` | `require` | Local-mode sandbox policy. `require` fails closed when no OS sandbox backend (Bubblewrap on Linux, Seatbelt on macOS) is usable; `prefer` degrades to advisory-only guardrails with a loud warning; `off` skips sandbox probing entirely — for skills you fully trust. Any other value is rejected. No value enables native Windows: local mode fails closed there before anything runs — use WSL2 or `--env-mode docker`. |
+| `SKILL_EVAL_NEMO_GYM_BIN` | `gym` on `PATH` | Path to the experimental task-folder adapter's pinned Gym executable. Public `nemo-gym==0.7.0` is incompatible; the public source candidate still needs native runtime qualification. See [Execution backends](/skills/skillevaluator/tier3-live-evaluation#execution-backends). |
+| `SKILL_EVAL_NEMO_GYM_MODEL_URL` | provider base URL | OpenAI-compatible base URL (ending in `/v1`) of the policy model for `--backend nemo-gym`. |
+| `SKILL_EVAL_NEMO_GYM_MODEL_API_KEY` | provider key, only when the URL is also the provider's | API key for that policy model. Required when `SKILL_EVAL_NEMO_GYM_MODEL_URL` is set; use `EMPTY` for a keyless server. Passed to Gym through the environment, never on the command line. |
+| `SKILL_EVAL_NEMO_GYM_HOST` | — | Address of this host that the Gym sandbox can reach (for example the Docker bridge gateway). Needed when the host name resolves to a loopback address. |
+| `SKILL_EVAL_NEMO_GYM_SANDBOX` | `docker` | NeMo Gym sandbox provider for `--backend nemo-gym`. |
+| `SKILL_EVAL_NEMO_GYM_TIMEOUT_S` | `21600` | Wall-clock limit, in seconds, for one `gym eval run` (one agent and arm); must be a finite number greater than 0. With Vertex AI ADC credentials it is also capped to the token's lifetime. On timeout, Ctrl-C, SIGTERM or SIGHUP, Gym's process group gets SIGTERM and 30 seconds to clean up its servers and sandboxes, then SIGKILL; a second Ctrl-C skips the wait. If the group still cannot be confirmed stopped after one last SIGKILL, no further arm starts. After a timeout, the run then finishes as failed with that error and keeps the scores of the arms that finished; after an interruption, the progress output reports it. |
| `SKILLEVALUATOR_LOCAL_ALLOW_NET` | `true` | Network egress for local-mode trials. Set to `0` to airgap a skill that must not reach the network. Incompatible with the `nv_build` provider — NVIDIA Build local agents require network access, so airgapped runs are rejected up front. |
| `SKILLEVALUATOR_LOCAL_STRICT_READS` | `false` | Tightens the sandbox's read-only view of the host system to a stricter path set. |
| `SKILLEVALUATOR_LOCAL_INHERIT_AGENT_KEYS` | `false` | When true, local-mode trials inherit the host's agent credential variables into their ambient environment. Off by default so a hostile skill command cannot read credentials — agents and verifiers receive credentials per-exec instead. |
diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdx
index fccd2fc3..2032e6c8 100644
--- a/docs/tier3-live-evaluation.mdx
+++ b/docs/tier3-live-evaluation.mdx
@@ -687,6 +687,118 @@ unavailable: `opencode` still works with `NVIDIA_API_KEY` directly, but
`codex` and `claude-code` fall back to their own native credentials and
explicit models — see [Agents & Sandboxes](/skills/skillevaluator/agents-and-sandboxes).
+## Execution backends
+
+`--backend` chooses what executes the cases. The default is Harbor. The experimental
+NeMo Gym adapter stages the same task folders and uses the shared verifier and result
+collector, but requires a Gym interface that is not available in the checked public
+`nemo-gym==0.7.0` release.
+
+| Backend | What runs the cases |
+| --- | --- |
+| `harbor` (default) | Harbor orchestrates the trials, runs the agent and the sandbox. Every `--env-mode` is available. |
+| `nemo-gym` | Experimental native Gym task-folder adapter, restricted to `--env-mode docker`. Public Gym 0.7.0 is incompatible and fails preflight. A public source candidate exposes the interface; independent live validation is still required. |
+
+**Compatibility status:** installing `nemo-gym==0.7.0` does not enable this backend.
+That release's `gym eval run` takes JSONL inputs and configured environments; it has
+neither the positional task-directory argument nor `--sandbox` used by this adapter.
+Removing that flag alone does not provide the required execution or verifier contract.
+The immutable public source candidate
+[`NVIDIA-NeMo/Gym@792fa142f58277aecff05d402061d647e9a92acf`](https://github.com/NVIDIA-NeMo/Gym/blob/792fa142f58277aecff05d402061d647e9a92acf/nemo_gym/cli/main.py)
+declares the `TARGET` task-folder argument and the seven required flags. This source
+inspection establishes an interface candidate, not a supported runtime installation.
+Native agent execution, verifier artifacts, paired small/custom-Dockerfile runs and
+input-file handling still need independent qualification. Codex, Claude Code and
+OpenCode mappings remain experimental and do not establish end-to-end agent support.
+
+```bash
+# Requires a separately verified, pinned Gym task-folder implementation.
+export SKILL_EVAL_NEMO_GYM_BIN=/opt/nemo-gym/.venv/bin/gym
+export SKILL_EVAL_NEMO_GYM_MODEL_URL=https://integrate.api.nvidia.com/v1
+export SKILL_EVAL_NEMO_GYM_MODEL_API_KEY="$NVIDIA_API_KEY"
+skillevaluator tier3 doctor --backend nemo-gym --agents codex
+skillevaluator tier3 evaluate ./my-skill --backend nemo-gym --agents codex --model <model>
+```
+
+`tier3 doctor --backend nemo-gym` checks the Gym CLI interface and its version, that the Docker
+daemon answers, the `SKILL_EVAL_NEMO_GYM_*` settings, each selected agent's policy model
+endpoint, and the selected agents and `--env-mode`. The CLI check runs
+`gym eval run --help` with a 15-second timeout and a combined stdout/stderr limit of
+256 KiB, without policy credentials or server startup. Timeout, interruption, or output
+overflow stops its isolated process group with bounded TERM/KILL cleanup. It rejects
+missing task-folder arguments and required flags before dataset
+generation or task staging. Passing this necessary check does not certify live runtime
+compatibility. A Gym run reports
+configuration, Docker image, per-agent and collection progress.
+
+Public Gym 0.7.0 requires Python 3.13.14 or later. Gym runs as its own pinned install
+rather than a SkillEvaluator dependency. Point `SKILL_EVAL_NEMO_GYM_BIN` at that
+install's `gym` executable. The run records `execution_backend` (name, Gym version,
+sandbox) in `result.json`; keep Harbor and NeMo Gym scores apart unless the model,
+harness and judge match.
+
+The adapter's required Gym contract is `gym eval run TASKS --sandbox docker`, with
+`--agent`, `--model-type openai_model`, `--model`, `--model-url`, `--output`, and
+`--concurrency`, plus Hydra overrides for repeats, credentials and cache disabling.
+Its help must describe a standalone positional `TARGET`, `tasks`, `task_dir`,
+`tasks_dir` or `task_folder` argument. Each rollout must identify its task and provide
+`verifier_return_code` and `verifier_logs_dir`, where the SkillEvaluator verifier's rewards and trajectory can
+be collected. The Gym implementation must execute inside Docker and resolve task
+environment templates; a host-only agent harness does not meet this contract.
+
+Subject to that unverified runtime contract, the adapter maps `codex`, `claude-code`
+and `opencode` and accepts `default`, `default_plus_custom` and `custom_only` grading
+modes. These are adapter capabilities, not independently validated live combinations.
+Every other `--env-mode` (including `local`, `daytona`, `e2b` and `singularity`) is
+not supported on the NeMo Gym path and is rejected before the run starts; use
+`--backend harbor` for those modes. Unset flags fall back to these `evals/config.yml` keys, as on Harbor:
+`harbor.n_attempts`, `pass_threshold`, `n_concurrent`, `max_cases`, `agents.<agent>.model`,
+`resources` (`cpus`, `memory_mb`), `runtime_env`, `grading.mode`, and
+`skill_workspace.mode`/`include`. `--skip-baseline`, `--skip-with-skill`, `--max-cases` and
+`--agent-model` (one model per agent) apply the same way. `--timeout-multiplier` (or
+`harbor.timeout_multiplier`) scales each task's agent, verifier, and environment-build timeouts
+as on Harbor, and Gym enforces them. `harbor.agent_workdir` and `harbor.pre_agent_setup`
+(alias `setup_commands`, with-skill-only runs) work as on Harbor: Gym starts the agent in
+that working directory and runs the setup commands as the task's environment healthcheck
+before the agent. `--copy-repo` stages the whole repository under
+`/workspace/repo/` as on Harbor, and a `skill_workspace.decoy_manifest` stages the same
+verified decoy snapshot into every arm. Native `evals/harbor/` tasks (`task_source: native_harbor`, or
+`auto` without `evals/evals.json`) are staged with Harbor's own native staging and run on Gym; their verifiers may write
+`reward.json` or a numeric `reward.txt`, and `--override-cpus`/`--override-memory-mb` apply to them, as on Harbor. `harbor.base_image_mode`
+(reuse/rebuild) builds Harbor's shared eval base image that the task images start from. `--custom-dockerfile-mode` rebase and preserve
+behave as on Harbor. `--environment-kwarg` is rejected, as Harbor rejects it in
+Docker mode. It rejects `--stop-on-pass`,
+`--harbor-keep-jobs`, `--agent-runtime-preflight`, `--override-storage-mb`,
+`--reuse-baseline`, `--compare-to`, `--max-agent-tokens`, `--max-judge-calls`,
+`--max-attempts-total`, `--max-cost-usd`, `--price-file`, `--tolerate-baseline-timeouts`,
+and the config keys
+`resources.storage_mb`, `max_agent_tokens`, `max_judge_calls`, `max_attempts_total`,
+`max_cost_usd`, `price_file` and `tolerate_baseline_timeouts: true` under `harbor`, MCP
+servers in `evals/environment/mcp_servers.toml` or a native task's `[[environment.mcp_servers]]`, a model URL with embedded credentials, and Windows hosts,
+whether set by flag or config (a flag overrides its config key), before anything
+starts (`tier3 PATH --autopilot` checks these before it writes a dataset); it never
+falls back to Harbor. `runtime_env` (alias `passthrough_env`) entries reach the agent's sandbox as `${NAME}`
+references resolved from Gym's environment. Gym receives only the variables Harbor's
+Docker backend allows (including `DOCKER_HOST`, `DOCKER_CONTEXT` and TLS settings),
+Gym's `UV_*` package-index settings and credentials, `NETRC`, and the policy and judge
+credentials; relative Docker and TLS paths are made absolute first. Judge overrides
+(`LLM_JUDGE_MODEL`, `SKILL_EVAL_JUDGE_*`) reach Gym's verifier as on Harbor, and Vertex
+AI ADC tokens are refreshed before every `gym eval run`. Every agent and arm is staged
+from one skill snapshot before the first launch. A missing or failed attempt counts as a
+failed trial, and the arm keeps its other scored trials. Excess rollouts are reported
+as execution errors and scoring remains bounded by the planned attempts. Any launch
+or rollout-count failure marks the
+run, the agent's progress row and the report as failed. If Gym's process group cannot be
+confirmed stopped after a timeout or interruption, no further arm starts beside it. After a
+timeout, the run records that as an execution error, finishes as failed and keeps the scores
+of the arms that finished. After an interruption, the progress output reports it and the run
+ends. Either way, check for leftover Gym servers and Docker sandboxes before you run again.
+A finished run updates `latest`
+and records the same dataset snapshot and publication target as a Harbor run. As on
+Harbor without `--harbor-keep-jobs`, the staged tasks and per-trial files are removed at
+the end; Gym's own redacted `gym.log` and its `rollouts.jsonl` stay under `_nemo-gym/`
+in the run folder, and the rollouts hold the raw agent responses.
+
## Where agents run
`--env-mode` selects one of 27 environment modes: 26 Harbor-native backends,
diff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.py
index cdd615a4..eaf804b5 100644
--- a/src/skillevaluator/cli.py
+++ b/src/skillevaluator/cli.py
@@ -1187,12 +1187,21 @@ def _ensure_autopilot_dataset(
provider = resolve_llm_provider()
except ProviderConfigurationError:
no_llm = True
+ if evaluation_params is not None and evaluation_params.get("backend") == "nemo-gym":
+ from skillevaluator.tier3.workflow import _source_snapshot, nemo_gym_preflight_errors
+
+ params = {**evaluation_params, "skill_path": skill_path}
+ with _source_snapshot(skill_path) as source_path:
+ errors = nemo_gym_preflight_errors(source_path, params)
+ if errors:
+ raise click.UsageError("; ".join(errors)) from None
echo("Autopilot: no public provider key is configured; generating one deterministic case.")
else:
no_llm = False
if evaluation_params is not None:
from skillevaluator.tier3.workflow import (
_preflight_environment,
+ _preflight_nemo_gym,
_preflight_options,
_source_snapshot,
)
@@ -1202,10 +1211,14 @@ def _ensure_autopilot_dataset(
# leave existing authored sources untouched above.
params = {**evaluation_params, "skill_path": skill_path}
with _source_snapshot(skill_path) as source_path:
- environment_kwargs = _preflight_options(source_path, params)
- if prepare_environment is not None:
- prepare_environment()
- _preflight_environment(params, environment_kwargs=environment_kwargs)
+ if params.get("backend") == "nemo-gym":
+ _preflight_nemo_gym(source_path, params)
+ else:
+ environment_kwargs = _preflight_options(source_path, params)
+ if params.get("backend") != "nemo-gym":
+ if prepare_environment is not None:
+ prepare_environment()
+ _preflight_environment(params, environment_kwargs=environment_kwargs)
provider_name, model_name = safe_llm_labels(provider.provider, provider.model)
echo(f"Autopilot: generating one case with {provider_name} / {model_name}.")
@@ -3338,6 +3351,13 @@ def _tier2_workflow(
),
)
@click.option("--env-mode", default="docker", show_default=True, type=ENV_MODE_CHOICE)
+ "--backend",
+ default="harbor",
+ show_default=True,
+ type=click.Choice(["harbor", "nemo-gym"]),
+ help="Tier 3 execution backend: Harbor, or NeMo Gym's orchestrator, agent harness and sandbox.",
+)
@click.option(
"--environment-kwarg",
"--ek",
@@ -3479,6 +3499,7 @@ def evaluate(
skill_path: Path,
agents: str | None,
env_mode: str,
+ backend: str,
environment_kwarg: tuple[str, ...],
autopilot: bool,
skip_baseline: bool,
@@ -3560,7 +3581,7 @@ def evaluate(
skill_path,
progress=progress,
evaluation_params=click.get_current_context().params,
- prepare_environment=prepare_local_runtime if env_mode == "local" else None,
+ prepare_environment=prepare_local_runtime if backend == "harbor" and env_mode == "local" else None,
)
parsed_environment_kwargs = _parse_environment_kwargs_cli(environment_kwarg, env_mode=env_mode)
@@ -3569,6 +3590,7 @@ def evaluate(
skill_path=skill_path,
agents=agents,
env_mode=env_mode,
+ backend=backend,
environment_kwarg=environment_kwarg,
skip_baseline=skip_baseline,
skip_with_skill=skip_with_skill,
@@ -3604,7 +3626,7 @@ def evaluate(
environment_kwargs=parsed_environment_kwargs,
)
try:
- if env_mode == "local":
+ if backend == "harbor" and env_mode == "local":
if not local_runtime_offered:
prepare_local_runtime()
from rich.panel import Panel
@@ -3622,7 +3644,7 @@ def evaluate(
padding=(0, 1),
)
)
- elif env_mode == "gke":
+ elif backend == "harbor" and env_mode == "gke":
from skillevaluator.tier3.commands import parse_agents
from skillevaluator.tier3.harbor.runner import (
is_gke_vertex_workload_identity_active,
@@ -3864,6 +3886,7 @@ _DOCTOR_OPTION_TIERS = {
"env_mode": frozenset({"3"}),
"environment_kwarg": frozenset({"3"}),
"agent_model": frozenset({"3"}),
+ "backend": frozenset({"3"}),
}
@@ -3896,6 +3919,13 @@ def _doctor_tier_options(*, timeout_help: str):
def _tier3_doctor_options(func):
"""Add the Tier 3 options shared by doctor and tier3 doctor."""
+ func = click.option(
+ "--backend",
+ default="harbor",
+ show_default=True,
+ type=click.Choice(["harbor", "nemo-gym"]),
+ help="Tier 3 execution backend to check: Harbor, or NeMo Gym.",
+ )(func)
func = click.option("--agent-model", multiple=True, help="Per-agent model override, AGENT=MODEL.")(func)
func = click.option(
"--environment-kwarg",
@@ -3926,6 +3956,7 @@ def _run_doctor(
timeout: float = DEFAULT_PROBE_TIMEOUT_SEC,
agent_model: tuple[str, ...] = (),
verify_models: bool = False,
+ backend: str = "harbor",
) -> int:
"""Validate every option before any probe, then check each selected tier in order."""
selected_tiers = ("1", "2", "3") if tier == "all" else (tier,)
@@ -3963,6 +3994,7 @@ def _run_doctor(
verify_models=verify_models,
agent_model=agent_model,
environment_kwargs=parsed_environment_kwargs,
+ backend=backend,
)
)
else:
diff --git a/src/skillevaluator/evaluation/options.py b/src/skillevaluator/evaluation/options.py
index e152380b..a7b3faca 100644
--- a/src/skillevaluator/evaluation/options.py
+++ b/src/skillevaluator/evaluation/options.py
@@ -65,6 +65,8 @@ class EvaluationOptions:
max_cost_usd: float | None = None
price_file: Path | None = None
tolerate_baseline_timeouts: bool | None = None
+ # Tier 3 execution backend ("harbor" or "nemo-gym"); appended to keep positional order stable.
+ backend: str = "harbor"
def engine_kwargs(self) -> dict[str, Any]:
"""Return keyword arguments (excluding ``skill_path``) for the engine."""
diff --git a/src/skillevaluator/evaluation/tier3_report.py b/src/skillevaluator/evaluation/tier3_report.py
index 29644819..bcd0b0b1 100644
--- a/src/skillevaluator/evaluation/tier3_report.py
+++ b/src/skillevaluator/evaluation/tier3_report.py
@@ -561,6 +561,7 @@ def agent_eval_result_from_directory(
use_llm_judge=use_llm_judge,
enforce_embedded_size=enforce_embedded_size,
)
+ _apply_engine_failure(payload, engine_result if isinstance(engine_result, dict) else _persisted_run_result(run_dir))
with contextlib.suppress(Exception):
source = json.loads((run_dir / "result.json").read_text(encoding="utf-8"))
if isinstance(source, dict) and isinstance(source.get("agents"), dict):
@@ -571,6 +572,51 @@ def agent_eval_result_from_directory(
return _validation_result_from_payload(payload)
+def _persisted_run_result(run_dir: Path) -> dict[str, Any] | None:
+ """Read the run's own ``result.json`` so re-rendered reports keep the engine status."""
+ try:
+ persisted = json.loads((run_dir / "result.json").read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ return persisted if isinstance(persisted, dict) else None
+
+
+def _apply_engine_failure(payload: dict[str, Any] | None, engine_result: dict[str, Any] | None) -> None:
+ """Carry a failed engine status (for example a backend launch failure) into the report payload.
+
+ Scores from the trials that did complete are kept; only the status and errors change.
+ """
+ if not isinstance(payload, dict) or not isinstance(engine_result, dict):
+ return
+ if engine_result.get("execution_status") != "failed":
+ return
+ raw_errors = engine_result.get("execution_errors") or []
+ engine_errors = [str(error) for error in (raw_errors if isinstance(raw_errors, list) else [raw_errors]) if error]
+ agents = payload.get("agents")
+ agent_payloads = (
+ {name: agent for name, agent in agents.items() if isinstance(agent, dict)} if isinstance(agents, dict) else {}
+ )
+ attributed = {
+ name: [error for error in engine_errors if error.startswith((f"{name} ", f"{name}:"))]
+ for name in agent_payloads
+ }
+ # Only agents an error names are marked; the root and summary carry unattributed failures.
+ for name, errors in attributed.items():
+ if errors:
+ _mark_failed(agent_payloads[name], errors)
+ summary = payload.get("summary")
+ for target in (payload, summary) if isinstance(summary, dict) else (payload,):
+ _mark_failed(target, engine_errors)
+
+
+def _mark_failed(target: dict[str, Any], errors: list[str]) -> None:
+ target["execution_status"] = "failed"
+ existing = [str(error) for error in target.get("execution_errors") or [] if error]
+ target["execution_errors"] = list(dict.fromkeys([*existing, *errors])) or [
+ "Tier 3 execution backend reported a failed run"
+ ]
+
+
def _validation_result_from_payload(payload: dict[str, Any] | None) -> ValidationResult | None:
"""Wrap a canonical Tier 3 payload in the shared validation-result model."""
if payload is None:
diff --git a/src/skillevaluator/tier3/case_summary.py b/src/skillevaluator/tier3/case_summary.py
index bb5f1419..033be3d4 100644
--- a/src/skillevaluator/tier3/case_summary.py
+++ b/src/skillevaluator/tier3/case_summary.py
@@ -1309,10 +1309,52 @@ def _live_mark(trial: Path, run_dir: Path, pass_threshold: float) -> str | None:
return ERROR
+def _add_gym_live_marks(
+ run_dir: Path, agents: list[str], marks: dict[str, dict[str, dict[str, list[str]]]], pass_threshold: float
+) -> bool:
+ """Add the attempts a running NeMo Gym arm has appended to its ``rollouts.jsonl``; False for a non-Gym run.
+
+ Each attempt is scored from its verifier logs with the same rules the Gym result normalizer uses.
+ """
+ from skillevaluator.tier3.nemo_gym.results import (
+ read_rollouts,
+ read_verifier_rewards,
+ rollout_failure_text,
+ rollout_task_name,
+ )
+
+ gym_root = run_dir / "_nemo-gym"
+ if not gym_root.is_dir() or gym_root.is_symlink():
+ return False
+ for agent in agents:
+ for variant, key in _LIVE_VARIANTS.items():
+ arm = gym_root / f"{agent}-{variant}"
+ rollouts = arm / "rollouts.jsonl"
+ if arm.is_symlink() or rollouts.is_symlink() or not rollouts.is_file():
+ continue
+ for row in read_rollouts(rollouts):
+ case_id = rollout_task_name(row)
+ if case_id is None or not _SAFE_TRIAL.match(case_id):
+ continue
+ logs_dir = row.get("verifier_logs_dir")
+ rewards = (
+ read_verifier_rewards(Path(logs_dir))
+ if not rollout_failure_text(row) and isinstance(logs_dir, str) and logs_dir
+ else None
+ )
+ score = rewards.get("overall", rewards.get("reward")) if rewards else None
+ if not isinstance(score, int | float) or isinstance(score, bool):
+ mark = ERROR
+ else:
+ mark = PASS if score >= pass_threshold else FAIL
+ marks.setdefault(agent, {}).setdefault(key, {}).setdefault(case_id, []).append(mark)
+ return True
+
+
def live_case_marks(
run_dir: Path, agents: list[str], *, pass_threshold: float = 0.5
) -> tuple[dict[str, dict[str, dict[str, list[str]]]], set[tuple[str, str, str]]]:
- """Attempt marks of an in-flight run, read from its Harbor job directories.
+ """Attempt marks of an in-flight run, read from its Harbor job directories or Gym rollouts.
Returns ``(marks, running)``: every staged case appears (with no marks
until an attempt finishes), and ``running`` holds the
@@ -1328,8 +1370,10 @@ def live_case_marks(
for task in sorted(staged.iterdir()):
if task.is_dir() and not task.is_symlink() and _SAFE_TRIAL.match(task.name):
cases.setdefault(task.name, [])
+ # A Gym run's _harbor-jobs holds only finished, normalized trials; its rollouts are the live record.
+ is_gym_run = _add_gym_live_marks(run_dir, agents, marks, pass_threshold)
jobs = run_dir / "_harbor-jobs"
- if not jobs.is_dir() or jobs.is_symlink():
+ if is_gym_run or not jobs.is_dir() or jobs.is_symlink():
return marks, running
seen: set[tuple[str, str, str]] = set()
for job in islice(sorted(jobs.iterdir()), _MAX_TRIAL_PATHS_SCANNED):
diff --git a/src/skillevaluator/tier3/commands.py b/src/skillevaluator/tier3/commands.py
index 189a9def..c94b8a88 100644
--- a/src/skillevaluator/tier3/commands.py
+++ b/src/skillevaluator/tier3/commands.py
@@ -668,6 +668,7 @@ def evaluate(
*,
agents: str | None,
env_mode: str,
+ backend: str = "harbor",
environment_kwarg: tuple[str, ...] = (),
skip_baseline: bool,
skip_with_skill: bool = False,
@@ -704,8 +705,11 @@ def evaluate(
progress_reporter: ProgressReporter | None = None,
environment_kwargs: Mapping[str, str] | None = None,
) -> dict[str, Any]:
- """Run Harbor live-agent evaluation for a skill."""
+ """Run a live-agent evaluation for a skill on the selected execution backend."""
+ from skillevaluator.tier3.nemo_gym.backend import NEMO_GYM_BACKEND, nemo_gym_capability_errors, normalize_backend
+
env_mode = _engine_env_mode(env_mode)
+ execution_backend = normalize_backend(backend)
if agents is None:
try:
@@ -764,6 +768,69 @@ def evaluate(
)
output_dir = resolve_results_root(skill_path, results_dir)
+ if execution_backend == NEMO_GYM_BACKEND:
+ from skillevaluator.tier3.nemo_gym.runner import run_nemo_gym_eval
+
+ capability_errors = nemo_gym_capability_errors(
+ agents=agent_list,
+ env_mode=env_mode,
+ grading_mode=grading_mode,
+ harbor_keep_jobs=harbor_keep_jobs,
+ stop_on_pass=bool(stop_on_pass),
+ custom_dockerfile_mode=custom_dockerfile_mode,
+ copy_repo=copy_repo,
+ environment_kwargs=merged_environment_kwargs,
+ override_storage_mb=override_storage_mb,
+ agent_runtime_preflight=bool(agent_runtime_preflight),
+ run_options={
+ "reuse_baseline": reuse_baseline,
+ "compare_to": compare_to,
+ "max_agent_tokens": max_agent_tokens,
+ "max_judge_calls": max_judge_calls,
+ "max_attempts_total": max_attempts_total,
+ "max_cost_usd": max_cost_usd,
+ "price_file": price_file,
+ "tolerate_baseline_timeouts": tolerate_baseline_timeouts,
+ },
+ )
+ multi_model_agents = sorted(agent for agent, models in agent_models.items() if len(models) != 1)
+ if multi_model_agents:
+ capability_errors.append(
+ "--backend nemo-gym runs one --agent-model per agent; got several for "
+ + ", ".join(multi_model_agents)
+ )
+ if capability_errors:
+ raise ValueError("; ".join(capability_errors))
+ engine_started = True
+ return run_nemo_gym_eval(
+ skill_path=skill_path.resolve(),
+ agents=agent_list,
+ skip_baseline=skip_baseline,
+ skip_with_skill=skip_with_skill,
+ n_attempts=n_attempts,
+ pass_threshold=pass_threshold,
+ stop_on_pass=stop_on_pass,
+ n_concurrent=n_concurrent,
+ max_cases=max_cases,
+ max_agents=max_agents,
+ model=model,
+ agent_models={agent: models[0] for agent, models in agent_models.items()} or None,
+ custom_dockerfile_mode=custom_dockerfile_mode,
+ agent_runtime_preflight=agent_runtime_preflight,
+ skill_workspace_mode=skill_workspace_mode,
+ include_skills=[p.resolve() for p in include_skills] or None,
+ grading_mode=grading_mode,
+ output_dir=output_dir,
+ env_mode=env_mode,
+ timeout_multiplier=timeout_multiplier,
+ evaluated_source=evaluated_source,
+ override_cpus=override_cpus,
+ override_memory_mb=override_memory_mb,
+ repo_context_exclude_paths=repo_context_exclude_paths,
+ copy_repo=copy_repo,
+ tolerate_baseline_timeouts=tolerate_baseline_timeouts,
+ progress_reporter=reporter,
+ )
engine_started = True
return run_harbor_eval(
skill_path=skill_path.resolve(),
@@ -821,9 +888,13 @@ def doctor(
verify_models: bool = False,
agent_model: tuple[str, ...] = (),
environment_kwargs: Mapping[str, Any] | None = None,
+ backend: str | None = None,
) -> int:
"""Check whether live evaluation dependencies are available."""
from skillevaluator.tier3.evals_config import parse_environment_kwarg_overrides
+ from skillevaluator.tier3.nemo_gym.backend import NEMO_GYM_BACKEND, normalize_backend
+
+ gym_backend = normalize_backend(backend) == NEMO_GYM_BACKEND
env_mode = _engine_env_mode(env_mode)
agent_list = parse_agents(agents) if agents is not None else []
@@ -878,7 +949,7 @@ def doctor(
for agent in agent_list
}
plan_error: str | None = None
- if not unknown_model_agents and not validate_agents(agent_list):
+ if not gym_backend and not unknown_model_agents and not validate_agents(agent_list):
try:
runtime_plans = _resolve_agent_runtime_plan(
provider=provider,
@@ -917,6 +988,9 @@ def doctor(
if kwarg_parse_error is not None:
prereq_errors = [kwarg_parse_error]
+ elif gym_backend:
+ rows.extend(_nemo_gym_doctor_rows(agent_list, env_mode, merged_cli_kwargs, agent_model=agent_model))
+ prereq_errors = None
else:
prerequisite_subprocess_env = dict(next(iter(runtime_plans.values())).subprocess_env) if runtime_plans else None
prereq_errors = _check_prerequisites(
@@ -929,10 +1003,12 @@ def doctor(
if prereq_errors:
for error in prereq_errors:
rows.append((f"{env_mode} prerequisite", "fail", error))
- else:
+ elif prereq_errors is not None:
rows.append((f"{env_mode} prerequisite", "pass", "ready"))
- if verify_models:
+ if verify_models and gym_backend:
+ rows.append(("provider model", "warn", "--verify-models is not checked for --backend nemo-gym yet"))
+ elif verify_models:
if provider is None or not runtime_plans:
rows.append(("provider model", "fail", "provider model resolution was unavailable"))
else:
@@ -978,6 +1054,102 @@ def doctor(
return 1 if any(row[1] == "fail" for row in rows) else 0
+def _docker_daemon_error(env: Mapping[str, str]) -> str | None:
+ """Return why the Docker daemon Gym would use is unreachable, or None when it answers."""
+ docker = shutil.which("docker")
+ if docker is None:
+ return "NeMo Gym's docker sandbox needs the docker CLI on PATH"
+ try:
+ probe = subprocess.run(
+ [docker, "info", "--format", "{{.ServerVersion}}"],
+ env=dict(env),
+ stdin=subprocess.DEVNULL,
+ capture_output=True,
+ text=True,
+ timeout=_DOCKER_PROBE_TIMEOUT_S,
+ check=False,
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ return f"NeMo Gym's docker sandbox could not reach the Docker daemon: {type(exc).__name__}"
+ if probe.returncode != 0:
+ reason = (probe.stderr or probe.stdout).strip().splitlines()
+ detail = reason[-1][:200] if reason else f"docker info exited {probe.returncode}"
+ return f"NeMo Gym's docker sandbox could not reach the Docker daemon: {detail}"
+ return None
+
+
+_DOCKER_PROBE_TIMEOUT_S = 15.0
+
+
+def _nemo_gym_doctor_rows(
+ agents: list[str],
+ env_mode: str,
+ environment_kwargs: Mapping[str, Any],
+ *,
+ agent_model: tuple[str, ...] = (),
+) -> list[tuple[str, str, str]]:
+ """Readiness rows for ``--backend nemo-gym``: the Gym CLI, its sandbox, the policy endpoint and options."""
+ from skillevaluator.provider_config import ProviderConfigurationError
+ from skillevaluator.tier3.nemo_gym.backend import (
+ MODEL_URL_ENV,
+ NEMO_GYM_BIN_ENV,
+ model_url_credential_error,
+ nemo_gym_bin,
+ nemo_gym_capability_errors,
+ nemo_gym_cli_error,
+ nemo_gym_settings_errors,
+ nemo_gym_version,
+ )
+ from skillevaluator.tier3.nemo_gym.runner import _model_endpoint, gym_launch_environment
+
+ rows: list[tuple[str, str, str]] = []
+ gym = nemo_gym_bin()
+ if gym is None:
+ rows.append(
+ (
+ "NeMo Gym CLI",
+ "fail",
+ f"not found: set {NEMO_GYM_BIN_ENV} to a verified, pinned Gym task-folder CLI; "
+ "public nemo-gym 0.7.0 is incompatible and the candidate source still needs runtime qualification",
+ )
+ )
+ elif cli_error := nemo_gym_cli_error(gym):
+ rows.append(("NeMo Gym CLI", "fail", cli_error))
+ elif version := nemo_gym_version(gym):
+ rows.append(("NeMo Gym CLI", "pass", f"{gym} (nemo-gym {version})"))
+ else:
+ rows.append(("NeMo Gym CLI", "warn", f"{gym} (could not read the nemo-gym version)"))
+ errors = nemo_gym_capability_errors(
+ agents=agents, env_mode=env_mode, grading_mode=None, environment_kwargs=dict(environment_kwargs)
+ )
+ errors += nemo_gym_settings_errors()
+ if gym is None or rows[0][1] == "fail":
+ errors.append("NeMo Gym execution is unavailable until its CLI compatibility check passes")
+ url = os.environ.get(MODEL_URL_ENV, "").strip()
+ if url and (url_error := model_url_credential_error(url)):
+ errors.append(url_error)
+ if not errors:
+ # The same policy endpoint resolution the run uses, per agent and its --agent-model.
+ try:
+ overrides = parse_agent_model_overrides(agent_model)
+ except ValueError:
+ overrides = {}
+ for agent in agents:
+ try:
+ _model, endpoint_url, _key = _model_endpoint((overrides.get(agent) or [None])[0])
+ except (ValueError, ProviderConfigurationError) as exc:
+ errors.append(f"{agent}: {exc}")
+ continue
+ if (url_error := model_url_credential_error(endpoint_url)) and url_error not in errors:
+ errors.append(url_error)
+ if env_mode == "docker" and (docker_error := _docker_daemon_error(gym_launch_environment({}))):
+ errors.append(docker_error)
+ rows += [("NeMo Gym backend", "fail", error) for error in errors] or [
+ ("NeMo Gym backend", "pass", f"{env_mode} sandbox ready")
+ ]
+ return rows
+
+
def validate_evals(skill_path: Path, *, as_json: bool, strict: bool, harbor_contract: bool) -> int:
"""Validate the Tier 3 evals/ directory and optional Harbor contract."""
results = validate_skillevaluators(skill_path)
diff --git a/src/skillevaluator/tier3/decoy_commands.py b/src/skillevaluator/tier3/decoy_commands.py
index ee1961ab..8f3a7e37 100644
--- a/src/skillevaluator/tier3/decoy_commands.py
+++ b/src/skillevaluator/tier3/decoy_commands.py
@@ -130,7 +130,9 @@ def _validate_existing_output(output: Path) -> None:
return
try:
data = _object(
- json.loads(_read_catalog_text(output), object_pairs_hook=_catalog_object, parse_constant=_reject_json_constant),
+ json.loads(
+ _read_catalog_text(output), object_pairs_hook=_catalog_object, parse_constant=_reject_json_constant
+ ),
_MANIFEST_FIELDS,
"root",
)
diff --git a/src/skillevaluator/tier3/decoys.py b/src/skillevaluator/tier3/decoys.py
index aa788ec9..fed9c326 100644
--- a/src/skillevaluator/tier3/decoys.py
+++ b/src/skillevaluator/tier3/decoys.py
@@ -212,7 +212,11 @@ def select_decoys(
if stored.content_type != CONTENT_TYPE_SKILL or stored.path in exclusions:
continue
candidate = _selected_path(root, stored.path)
- if _is_target_path(candidate, target) or _identity(candidate.name) in names or _identity(stored.name) in skill_names:
+ if (
+ _is_target_path(candidate, target)
+ or _identity(candidate.name) in names
+ or _identity(stored.name) in skill_names
+ ):
continue
entry = _skill(candidate)
if _sha256(entry.embedding_text) != stored.content_fingerprint:
diff --git a/src/skillevaluator/tier3/eval_core/checks.py b/src/skillevaluator/tier3/eval_core/checks.py
index 81425e9d..6e924093 100644
--- a/src/skillevaluator/tier3/eval_core/checks.py
+++ b/src/skillevaluator/tier3/eval_core/checks.py
@@ -1433,10 +1433,18 @@ def _failed_single_skill_read(call):
"""
if call.get("is_error") is not True:
return False
- tokens = _shell_tokens(_command_text(call))
+ return _isolated_skill_read(_command_text(call))
+
+
+def _isolated_skill_read(cmd, _depth: int = 0) -> bool:
+ """True if ``cmd`` is one plain read of one SKILL.md, also inside ``bash -c '...'`` wrappers."""
+ tokens = _shell_tokens(cmd)
if not tokens or any(token in _SHELL_SEPARATORS for token in tokens):
return False
command = tokens[0].rsplit("/", 1)[-1].lower()
+ if command in _SHELL_COMMAND_INTERPRETERS and _depth < _MAX_SHELL_WRAPPERS:
+ payload = _shell_c_payload(tokens, 0, {})
+ return bool(payload) and _isolated_skill_read(payload, _depth + 1)
if command not in {"cat", "nl", "bat", "less", "more"}:
return False
files = []
@@ -1450,7 +1458,7 @@ def _failed_single_skill_read(call):
return len(files) == 1 and not _SHELL_EXPANSION_CHARS.intersection(files[0]) and _skill_md_arg(files[0], {})
-def _cmd_reads_skill_md(cmd) -> bool:
+def _cmd_reads_skill_md(cmd, _depth: int = 0) -> bool:
"""True if a shell command reads a SKILL.md via a file-view utility.
Requires both a read verb (cat/sed/head/...) AND a ``SKILL.md`` filename
@@ -1483,6 +1491,11 @@ def _cmd_reads_skill_md(cmd) -> bool:
executable = command[cmd_idx].rsplit("/", 1)[-1].lower()
if executable in _FILE_READ_VERBS and _command_reads_skill_md_arg(command, cmd_idx, assignments):
return True
+ # ``bash -lc 'cat .../SKILL.md'``: harnesses such as NeMo Gym's Codex agent record the wrapper.
+ if executable in _SHELL_COMMAND_INTERPRETERS and _depth < _MAX_SHELL_WRAPPERS:
+ payload = _shell_c_payload(command, cmd_idx, assignments)
+ if payload and _cmd_reads_skill_md(payload, _depth + 1):
+ return True
idx = end + 1
return False
diff --git a/src/skillevaluator/tier3/eval_core/codex_tool_call_normalizer.py b/src/skillevaluator/tier3/eval_core/codex_tool_call_normalizer.py
index 634012b6..77dadf7b 100644
--- a/src/skillevaluator/tier3/eval_core/codex_tool_call_normalizer.py
+++ b/src/skillevaluator/tier3/eval_core/codex_tool_call_normalizer.py
@@ -82,11 +82,7 @@ def _outer_tool_call_observation(
return "".join(
atif_content_text(result.get("content"))
for result in (step.get("observation") or {}).get("results") or []
- if (
- tool_call_id
- and result.get("source_call_id")
- and result.get("source_call_id") == tool_call_id
- )
+ if (tool_call_id and result.get("source_call_id") and result.get("source_call_id") == tool_call_id)
or (include_unscoped and not result.get("source_call_id"))
)
@@ -134,10 +130,14 @@ def normalized_tool_call_is_error(step: dict[str, Any], tool_call: dict[str, Any
def normalized_tool_call_wrapper_observation(step: dict[str, Any], tool_call: dict[str, Any]) -> str:
"""Return an unattributed wrapper observation once for security scanning."""
- if tool_call.get("_atif_observation_status") not in (
- AMBIGUOUS_OUTER_EXEC_OBSERVATION,
- UNOBSERVED_INNER_CALL,
- ) or tool_call.get("_atif_inner_tool_index") != 0:
+ if (
+ tool_call.get("_atif_observation_status")
+ not in (
+ AMBIGUOUS_OUTER_EXEC_OBSERVATION,
+ UNOBSERVED_INNER_CALL,
+ )
+ or tool_call.get("_atif_inner_tool_index") != 0
+ ):
return ""
observation_owner = tool_call.get("_atif_outer_observation_owner")
if isinstance(observation_owner, int) and observation_owner >= 0:
@@ -476,20 +476,24 @@ def _js_code_tokens(source: str) -> list[tuple[str, str]]:
if previous == "newline":
previous_significant_index -= 1
previous_significant = tokens[previous_significant_index][1] if previous_significant_index >= 0 else ""
- regex_context = previous_significant in (
- _JS_EXPRESSION_OPERATORS
- | {
- "",
- "(",
- "[",
- "{",
- "=",
- ":",
- ",",
- ";",
- "=>",
- }
- ) or previous_significant in _JS_EXPRESSION_KEYWORDS
+ regex_context = (
+ previous_significant
+ in (
+ _JS_EXPRESSION_OPERATORS
+ | {
+ "",
+ "(",
+ "[",
+ "{",
+ "=",
+ ":",
+ ",",
+ ";",
+ "=>",
+ }
+ )
+ or previous_significant in _JS_EXPRESSION_KEYWORDS
+ )
if previous_significant == ")":
regex_context = previous_significant_index in control_condition_closes
elif previous_significant == "}":
@@ -550,9 +554,7 @@ def _js_code_tokens(source: str) -> list[tuple[str, str]]:
previous_significant_index = len(tokens) - 1
if previous_significant_index >= 0 and tokens[previous_significant_index][1] == "newline":
previous_significant_index -= 1
- previous_significant = (
- tokens[previous_significant_index][1] if previous_significant_index >= 0 else ""
- )
+ previous_significant = tokens[previous_significant_index][1] if previous_significant_index >= 0 else ""
if operator == "(":
control_parentheses.append(previous_significant in {"if", "for", "while", "switch", "with"})
elif operator == ")" and control_parentheses and control_parentheses.pop():
@@ -561,10 +563,7 @@ def _js_code_tokens(source: str) -> list[tuple[str, str]]:
block_braces.append(
previous_significant in {"", ";", "newline", "{", "}", "do", "else", "finally", "try"}
or previous_significant == "=>"
- or (
- previous_significant == ")"
- and previous_significant_index in control_condition_closes
- )
+ or (previous_significant == ")" and previous_significant_index in control_condition_closes)
)
elif operator == "}" and block_braces and block_braces.pop():
block_closes.add(len(tokens))
@@ -630,9 +629,7 @@ def _skip_balanced_member(tokens: list[tuple[str, str]], start: int, ends: dict[
return len(tokens) if end is None else end + 1
-def _tools_reference_is_called(
- tokens: list[tuple[str, str]], end: int, bracket_ends: dict[int, int]
-) -> bool:
+def _tools_reference_is_called(tokens: list[tuple[str, str]], end: int, bracket_ends: dict[int, int]) -> bool:
cursor = end
saw_member = False
while cursor < len(tokens):
@@ -672,9 +669,7 @@ def _matching_delimiters(tokens: list[tuple[str, str]], opening: str, closing: s
return matches
-def _reference_contexts(
- tokens: list[tuple[str, str]], references: list[tuple[int, int]]
-) -> list[bool]:
+def _reference_contexts(tokens: list[tuple[str, str]], references: list[tuple[int, int]]) -> list[bool]:
results: list[bool] = []
reference_index = 0
strong_context = False
@@ -688,11 +683,7 @@ def _reference_contexts(
_, end = references[reference_index]
called = _tools_reference_is_called(tokens, end, bracket_ends)
immediate_expression_context = called and previous in call_prefixes
- results.append(
- strong_context
- or immediate_expression_context
- or last_identifier in _JS_EXPRESSION_KEYWORDS
- )
+ results.append(strong_context or immediate_expression_context or last_identifier in _JS_EXPRESSION_KEYWORDS)
reference_index += 1
if index == len(tokens):
break
diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.py
index 54440de8..d37dc594 100644
--- a/src/skillevaluator/tier3/harbor/runner.py
+++ b/src/skillevaluator/tier3/harbor/runner.py
@@ -349,6 +349,11 @@ _FINAL_RESULT_PROJECTION_SCHEMA_VERSION = "1.0"
_FINAL_RESULT_CONTRACT_ERROR = (
"Final Tier 3 result exceeds the 2 MiB, depth-64, or 50,000-node publication limit after artifact projection"
)
+# Shared with the NeMo Gym backend, so both give the same advice for a skill without a dataset.
+_MISSING_EVALS_DATASET_ERROR = (
+ "No evals/evals.json found. Add task guidance in evals/EVAL.md or pass --prompt to "
+ "create-eval-dataset; add --grounding skill for an explicit skill-only starter, or author a dataset."
+)
class _FinalResultContractError(ValueError):
@@ -5669,12 +5674,7 @@ def _run_harbor_eval_impl(
task_source = "evals_json" if evals_exists else "native_harbor" if native_exists else ""
if task_source == "evals_json" and not evals_exists:
reporter.emit(ProgressEvent(stage="with-skill-tasks", state="failed", detail="evaluation dataset missing"))
- return {
- "error": [
- "No evals/evals.json found. Add task guidance in evals/EVAL.md or pass --prompt to "
- "create-eval-dataset; add --grounding skill for an explicit skill-only starter, or author a dataset."
- ]
- }
+ return {"error": [_MISSING_EVALS_DATASET_ERROR]}
if task_source == "native_harbor" and not native_exists:
reporter.emit(ProgressEvent(stage="with-skill-tasks", state="failed", detail="native Harbor tasks missing"))
return {"error": ["No native Harbor task source found at evals/harbor."]}
diff --git a/src/skillevaluator/tier3/nemo_gym/__init__.py b/src/skillevaluator/tier3/nemo_gym/__init__.py
new file mode 100644
index 00000000..daa758fb
--- /dev/null
+++ b/src/skillevaluator/tier3/nemo_gym/__init__.py
@@ -0,0 +1,3 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+"""NeMo Gym execution backend for Tier 3 live-agent evaluation."""
diff --git a/src/skillevaluator/tier3/nemo_gym/backend.py b/src/skillevaluator/tier3/nemo_gym/backend.py
new file mode 100644
index 00000000..f8b4a753
--- /dev/null
+++ b/src/skillevaluator/tier3/nemo_gym/backend.py
@@ -0,0 +1,388 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+"""Tier 3 execution backend selection and NeMo Gym capability checks."""
+
+from __future__ import annotations
+
+import math
+import os
+import re
+import shutil
+import subprocess
+from collections.abc import Mapping
+from pathlib import Path
+from typing import Any
+from urllib.parse import urlsplit
+
+HARBOR_BACKEND = "harbor"
+NEMO_GYM_BACKEND = "nemo-gym"
+EXECUTION_BACKENDS = (HARBOR_BACKEND, NEMO_GYM_BACKEND)
+DEFAULT_EXECUTION_BACKEND = HARBOR_BACKEND
+
+NEMO_GYM_BIN_ENV = "SKILL_EVAL_NEMO_GYM_BIN"
+MODEL_API_KEY_ENV = "SKILL_EVAL_NEMO_GYM_MODEL_API_KEY"
+MODEL_URL_ENV = "SKILL_EVAL_NEMO_GYM_MODEL_URL"
+RUN_TIMEOUT_ENV = "SKILL_EVAL_NEMO_GYM_TIMEOUT_S"
+DEFAULT_RUN_TIMEOUT_S = 21600.0
+_GYM_HELP_TIMEOUT_S = 15.0
+_GYM_HELP_MAX_OUTPUT_BYTES = 256 * 1024
+NEMO_GYM_AGENTS = {
+ "codex": "codex_agent",
+ "claude-code": "claude_code_agent",
+ "opencode": "opencode_agent",
+}
+NEMO_GYM_ENV_MODES = frozenset({"docker"})
+NEMO_GYM_GRADING_MODES = frozenset({"default", "default_plus_custom", "custom_only"})
+
+_ALIASES = {
+ "harbor": HARBOR_BACKEND,
+ "nemo-gym": NEMO_GYM_BACKEND,
+ "nemo_gym": NEMO_GYM_BACKEND,
+ "nemogym": NEMO_GYM_BACKEND,
+ "gym": NEMO_GYM_BACKEND,
+}
+
+
+def normalize_backend(value: str | None) -> str:
+ """Return the canonical backend name or raise ``ValueError``."""
+ if value is None or not str(value).strip():
+ return DEFAULT_EXECUTION_BACKEND
+ key = str(value).strip().casefold()
+ if key not in _ALIASES:
+ choices = ", ".join(EXECUTION_BACKENDS)
+ raise ValueError(f"Unknown Tier 3 execution backend {value!r}; choose one of: {choices}")
+ return _ALIASES[key]
+
+
+def nemo_gym_bin() -> str | None:
+ """Locate the ``gym`` CLI, preferring the pinned worker named by ``SKILL_EVAL_NEMO_GYM_BIN``."""
+ configured = os.environ.get(NEMO_GYM_BIN_ENV, "").strip()
+ if configured:
+ path = Path(configured).expanduser()
+ return str(path.absolute()) if path.is_file() and os.access(path, os.X_OK) else None
+ found = shutil.which("gym")
+ return str(Path(found).absolute()) if found else None
+
+
+def _gym_interpreters(gym_bin: str) -> list[Path]:
+ """Return candidate interpreters for the Gym install: the script's shebang, then its sibling Python."""
+ script = Path(gym_bin).resolve()
+ candidates: list[Path] = []
+ try:
+ with script.open("rb") as handle:
+ first_line = handle.read(512).split(b"\n", 1)[0].decode("utf-8", "replace")
+ except OSError:
+ first_line = ""
+ if first_line.startswith("#!"):
+ parts = first_line[2:].strip().split()
+ if parts and Path(parts[0]).name.startswith("python"):
+ candidates.append(Path(parts[0]))
+ candidates += [script.with_name("python"), script.with_name("python.exe")]
+ return [candidate for candidate in candidates if candidate.is_file()]
+
+
+def nemo_gym_version(gym_bin: str) -> str | None:
+ """Return the installed NeMo Gym version from the worker's own interpreter.
+
+ ``-P`` keeps the caller's directory off ``sys.path``, so a ``nemo_gym`` module in the
+ skill under evaluation is never imported, and the probe gets only Gym's launch environment.
+ """
+ from skillevaluator.tier3.nemo_gym.runner import gym_launch_environment
+
+ for python in _gym_interpreters(gym_bin):
+ try:
+ completed = subprocess.run(
+ [str(python), "-P", "-c", "import nemo_gym; print(nemo_gym.__version__)"],
+ cwd=python.parent,
+ env=gym_launch_environment({}),
+ capture_output=True,
+ text=True,
+ timeout=60,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError):
+ continue
+ version = completed.stdout.strip().splitlines()
+ if completed.returncode == 0 and version:
+ return version[-1]
+ return None
+
+
+# Candidate public source interface; native runtime qualification remains required.
+NEMO_GYM_SOURCE = "git+https://github.com/NVIDIA-NeMo/Gym@792fa142f58277aecff05d402061d647e9a92acf"
+
+
+def nemo_gym_cli_error(gym_bin: str) -> str | None:
+ """Check the task-folder CLI contract without starting servers or passing policy credentials.
+
+ A version string alone does not identify this interface: public Gym 0.7.0 uses
+ JSONL inputs and lacks the task-folder / sandbox command this adapter requires.
+ This necessary interface check does not certify an installation's runtime support.
+ """
+ from skillevaluator.tier3.harbor.runner import _HarborRunTimeoutError, _run_bounded_harbor_process
+ from skillevaluator.tier3.nemo_gym.runner import _signals_raise_keyboard_interrupt, gym_launch_environment
+
+ try:
+ # Reuse bounded streaming and isolated process-group cleanup, not Harbor execution.
+ # Both output streams share one raw byte budget; no subprocess output enters errors.
+ with _signals_raise_keyboard_interrupt():
+ completed = _run_bounded_harbor_process(
+ [gym_bin, "eval", "run", "--help"],
+ cwd=Path(gym_bin).resolve().parent,
+ env=gym_launch_environment({}),
+ stdin_text=None,
+ timeout_seconds=_GYM_HELP_TIMEOUT_S,
+ max_output_bytes=_GYM_HELP_MAX_OUTPUT_BYTES,
+ diagnostic_tail_chars=_GYM_HELP_MAX_OUTPUT_BYTES,
+ secret_values=set(),
+ )
+ except _HarborRunTimeoutError:
+ return (
+ f"NeMo Gym CLI compatibility check failed: `gym eval run --help` timed out after {_GYM_HELP_TIMEOUT_S:g}s"
+ )
+ except (OSError, subprocess.SubprocessError, RuntimeError):
+ return "NeMo Gym CLI compatibility check failed: `gym eval run --help` could not complete safely"
+ if completed.output_exceeded:
+ return "NeMo Gym CLI compatibility check failed: `gym eval run --help` exceeded its combined output limit"
+ if completed.returncode:
+ return f"NeMo Gym CLI compatibility check failed: `gym eval run --help` exited {completed.returncode}"
+ help_text = completed.output_tail
+ flags = ("--sandbox", "--agent", "--model-type", "--model", "--model-url", "--output", "--concurrency")
+ missing = [flag for flag in flags if not re.search(rf"(?<![\w-]){re.escape(flag)}(?=[\s,=]|$)", help_text)]
+ if not _declares_task_positional(help_text):
+ missing.append("positional tasks directory")
+ if missing:
+ return (
+ f"NeMo Gym CLI is incompatible with this experimental task-folder adapter; missing: {', '.join(missing)}. "
+ f"Public nemo-gym 0.7.0 is incompatible; candidate source {NEMO_GYM_SOURCE} still needs runtime qualification. "
+ "No Harbor fallback was started."
+ )
+ return None
+
+
+def _declares_task_positional(help_text: str) -> bool:
+ """Whether argparse help lists a task-folder positional under ``positional arguments:``.
+
+ Only entries at argparse's two-space item indent count, so wrapped option prose that happens
+ to start with ``tasks`` (as ``--only-tasks`` does at 80 columns) is not mistaken for one.
+ """
+ section = re.search(r"(?ms)^positional arguments:\n(.*?)(?=^\S|\Z)", help_text)
+ return bool(
+ section and re.search(r"(?m)^ {2}(?:tasks|task_dir|tasks_dir|task_folder|TARGET)(?:\s|$)", section.group(1))
+ )
+
+
+_UNSUPPORTED_RUN_OPTIONS = (
+ ("reuse_baseline", "--reuse-baseline"),
+ ("compare_to", "--compare-to"),
+ ("max_agent_tokens", "--max-agent-tokens"),
+ ("max_judge_calls", "--max-judge-calls"),
+ ("max_attempts_total", "--max-attempts-total"),
+ ("max_cost_usd", "--max-cost-usd"),
+ ("price_file", "--price-file"),
+)
+_UNSUPPORTED_BUDGET_CONFIG = ("max_agent_tokens", "max_judge_calls", "max_attempts_total", "max_cost_usd", "price_file")
+# Off is Gym's own behavior, so only an enabled option is rejected.
+_UNSUPPORTED_ENABLED_OPTIONS = (("tolerate_baseline_timeouts", "--tolerate-baseline-timeouts"),)
+
+
+def nemo_gym_capability_errors(
+ *,
+ agents: list[str],
+ env_mode: str,
+ grading_mode: str | None,
+ harbor_keep_jobs: bool = False,
+ stop_on_pass: bool = False,
+ custom_dockerfile_mode: str | None = None,
+ copy_repo: bool = False,
+ environment_kwargs: dict[str, str] | None = None,
+ override_storage_mb: int | None = None,
+ agent_runtime_preflight: bool = False,
+ timeout_multiplier: float | None = None,
+ run_options: dict[str, Any] | None = None,
+) -> list[str]:
+ """Reject configurations the NeMo Gym backend cannot run equivalently, before anything starts."""
+ errors = nemo_gym_harbor_only_option_errors(run_options or {})
+ if os.name != "posix":
+ errors.append("--backend nemo-gym needs a POSIX host (Linux or macOS); NeMo Gym does not run on Windows")
+ unsupported = [agent for agent in agents if agent not in NEMO_GYM_AGENTS]
+ if unsupported:
+ supported = ", ".join(sorted(NEMO_GYM_AGENTS))
+ errors.append(f"--backend nemo-gym supports agents {supported}; not supported: {', '.join(unsupported)}")
+ if env_mode not in NEMO_GYM_ENV_MODES:
+ errors.append(f"--backend nemo-gym supports --env-mode docker only; got {env_mode!r}")
+ if grading_mode and grading_mode not in NEMO_GYM_GRADING_MODES:
+ errors.append(f"--backend nemo-gym does not support grading mode {grading_mode!r}")
+ if harbor_keep_jobs:
+ errors.append("--harbor-keep-jobs applies to the Harbor backend only")
+ if stop_on_pass:
+ errors.append("--stop-on-pass is not supported with --backend nemo-gym yet")
+ if custom_dockerfile_mode not in (None, "rebase", "preserve"):
+ errors.append(f"unsupported --custom-dockerfile-mode {custom_dockerfile_mode!r}")
+ if environment_kwargs:
+ errors.append("--environment-kwarg applies to the Harbor environment providers only")
+ if override_storage_mb is not None:
+ errors.append("--override-storage-mb is not supported with --backend nemo-gym")
+ if agent_runtime_preflight:
+ errors.append("--agent-runtime-preflight applies to the Harbor backend only")
+ if timeout_multiplier is not None:
+ from skillevaluator.tier3.harbor.runner import _validated_timeout_multiplier
+
+ try:
+ _validated_timeout_multiplier(timeout_multiplier)
+ except ValueError as exc:
+ errors.append(str(exc))
+ return errors
+
+
+def nemo_gym_harbor_only_option_errors(options: Mapping[str, object], *, from_config: bool = False) -> list[str]:
+ """Reject baseline reuse, version comparison, budgets and baseline-timeout tolerance until Gym can honor them."""
+ errors: list[str] = []
+ for name, flag in _UNSUPPORTED_RUN_OPTIONS:
+ # Zero is an explicit limit, not an unset option.
+ if options.get(name) is not None:
+ label = f"harbor.{name}" if from_config else flag
+ errors.append(f"{label} is not supported with --backend nemo-gym yet")
+ for name, flag in _UNSUPPORTED_ENABLED_OPTIONS:
+ if options.get(name):
+ label = f"harbor.{name}" if from_config else flag
+ errors.append(f"{label} is not supported with --backend nemo-gym yet")
+ return errors
+
+
+def nemo_gym_timeout_s() -> float:
+ """Return ``SKILL_EVAL_NEMO_GYM_TIMEOUT_S`` in seconds, or raise ``ValueError``."""
+ raw = os.environ.get(RUN_TIMEOUT_ENV, "").strip()
+ try:
+ timeout_s = float(raw) if raw else DEFAULT_RUN_TIMEOUT_S
+ except ValueError:
+ timeout_s = math.nan
+ if not math.isfinite(timeout_s) or timeout_s <= 0:
+ raise ValueError(f"{RUN_TIMEOUT_ENV} must be a finite number of seconds greater than 0")
+ return timeout_s
+
+
+def nemo_gym_sandbox_error() -> str | None:
+ """Return an error when ``SKILL_EVAL_NEMO_GYM_SANDBOX`` names a sandbox the backend does not support."""
+ sandbox = os.environ.get("SKILL_EVAL_NEMO_GYM_SANDBOX", "").strip()
+ if sandbox and sandbox not in NEMO_GYM_ENV_MODES:
+ return f"SKILL_EVAL_NEMO_GYM_SANDBOX={sandbox} is not supported; NeMo Gym runs Tier 3 cases in docker only"
+ return None
+
+
+def nemo_gym_settings_errors() -> list[str]:
+ """Reject invalid ``SKILL_EVAL_NEMO_GYM_*`` settings, before any dataset work."""
+ errors: list[str] = []
+ if sandbox_error := nemo_gym_sandbox_error():
+ errors.append(sandbox_error)
+ try:
+ nemo_gym_timeout_s()
+ except ValueError as exc:
+ errors.append(str(exc))
+ url = os.environ.get(MODEL_URL_ENV, "").strip()
+ if url and not os.environ.get(MODEL_API_KEY_ENV, "").strip():
+ errors.append(f"{MODEL_URL_ENV} is set, so also set {MODEL_API_KEY_ENV} (use EMPTY for a keyless server)")
+ return errors
+
+
+def model_url_credential_error(url: str) -> str | None:
+ """Return an error when a policy URL carries userinfo, which would land on Gym's command line."""
+ try:
+ parts = urlsplit(url)
+ except ValueError:
+ return None
+ if parts.username or parts.password:
+ return (
+ "the NeMo Gym policy model URL must not embed a username or password; "
+ f"put the credential in {MODEL_API_KEY_ENV} instead"
+ )
+ return None
+
+
+def uses_native_harbor_tasks(skill_path: Path, task_source: object) -> bool:
+ """Return True when the Tier 3 source resolves to native ``evals/harbor/`` tasks, as on Harbor."""
+ if task_source == "native_harbor":
+ return True
+ if task_source not in (None, "auto"):
+ return False
+ from skillevaluator.tier3.harbor.adapter import find_evals_file
+
+ try:
+ has_evals_file = find_evals_file(skill_path) is not None
+ except (OSError, ValueError):
+ return False
+ return not has_evals_file and (skill_path / "evals" / "harbor").is_dir()
+
+
+def mcp_servers_declared(skill_path: Path) -> bool:
+ """Return True when ``evals/environment/mcp_servers.toml`` declares any MCP server."""
+ from skillevaluator.tier3.harbor.adapter import _load_mcp_servers
+
+ if not (skill_path / "evals" / "environment" / "mcp_servers.toml").is_file():
+ return False
+ try:
+ return bool(_load_mcp_servers(skill_path))
+ except Exception:
+ return True
+
+
+MCP_SERVERS_ERROR = "evals/environment/mcp_servers.toml is not supported with --backend nemo-gym yet"
+NATIVE_MCP_SERVERS_ERROR = (
+ "[[environment.mcp_servers]] in a native task.toml is not supported with --backend nemo-gym yet"
+)
+
+
+def native_mcp_servers_declared(skill_path: Path) -> bool:
+ """Return True when a native ``evals/harbor/*/task.toml`` declares ``[[environment.mcp_servers]]``."""
+ import tomllib
+
+ for task_toml in sorted((skill_path / "evals" / "harbor").glob("*/task.toml")):
+ try:
+ environment = tomllib.loads(task_toml.read_text(encoding="utf-8")).get("environment") or {}
+ except (OSError, ValueError):
+ continue
+ if isinstance(environment, dict) and environment.get("mcp_servers"):
+ return True
+ return False
+
+
+def nemo_gym_config_errors(
+ skill_path: Path,
+ *,
+ stop_on_pass: bool | None = None,
+ timeout_multiplier: float | None = None,
+ agent_runtime_preflight: bool | None = None,
+ custom_dockerfile_mode: str | None = None,
+ run_options: dict[str, Any] | None = None,
+) -> list[str]:
+ """Reject ``evals/config.yml`` settings the NeMo Gym backend cannot honor, before any dataset work.
+
+ A setting also given on the command line is skipped here: the CLI value wins, and
+ ``nemo_gym_capability_errors`` already rejects an unsupported CLI value.
+ """
+ from skillevaluator.tier3.evals_config import EvalsConfigError, load_evals_config
+
+ try:
+ config, _config_path = load_evals_config(skill_path)
+ except EvalsConfigError as exc:
+ return [str(exc)]
+ harbor = config.get("harbor") or {}
+ unsupported_config = {
+ name: harbor.get(name)
+ for name in (*_UNSUPPORTED_BUDGET_CONFIG, *(name for name, _flag in _UNSUPPORTED_ENABLED_OPTIONS))
+ if (run_options or {}).get(name) is None
+ }
+ errors = nemo_gym_harbor_only_option_errors(unsupported_config, from_config=True)
+ if stop_on_pass is None and harbor.get("stop_on_pass"):
+ errors.append("harbor.stop_on_pass is not supported with --backend nemo-gym yet")
+ if agent_runtime_preflight is None and harbor.get("agent_runtime_preflight"):
+ errors.append("harbor.agent_runtime_preflight applies to the Harbor backend only")
+ if mcp_servers_declared(skill_path):
+ errors.append(MCP_SERVERS_ERROR)
+ if uses_native_harbor_tasks(skill_path, harbor.get("task_source", "auto")) and native_mcp_servers_declared(
+ skill_path
+ ):
+ errors.append(NATIVE_MCP_SERVERS_ERROR)
+ if "storage_mb" in (harbor.get("resources") or {}):
+ errors.append("harbor.resources.storage_mb is not supported with --backend nemo-gym")
+ return errors
diff --git a/src/skillevaluator/tier3/nemo_gym/results.py b/src/skillevaluator/tier3/nemo_gym/results.py
new file mode 100644
index 00000000..b14b8c85
--- /dev/null
+++ b/src/skillevaluator/tier3/nemo_gym/results.py
@@ -0,0 +1,245 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+"""Normalize NeMo Gym Harbor-environment rollouts into SkillEvaluator trial evidence.
+
+The shared collector reads one job directory per agent and arm. Each Gym rollout
+becomes one trial holding the verifier files Gym downloaded from ``/logs/verifier``
+and the ATIF trajectory Gym wrote for the verifier, so scoring, lift, pass@k and
+reports stay backend-neutral.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import json
+import math
+import re
+import shutil
+from collections import defaultdict
+from pathlib import Path
+from typing import Any
+
+_UNSAFE = re.compile(r"[^A-Za-z0-9._-]+")
+_VERIFIER_FILES = ("reward.json", "reward.txt", "skill_evaluator_reward.json", "test-stdout.txt")
+
+
+def _safe(value: str) -> str:
+ return _UNSAFE.sub("-", value).strip("-") or "task"
+
+
+def read_rollouts(path: Path, errors: list[str] | None = None) -> list[dict[str, Any]]:
+ """Read a Gym rollouts JSONL file, skipping blank lines.
+
+ A line Gym was still writing when it was stopped (timeout, OOM, full disk) is
+ skipped and reported through ``errors``, so it becomes a missing trial.
+ """
+ if not path.is_file():
+ return []
+ rows: list[dict[str, Any]] = []
+ skipped = 0
+ # Gym ends each row with "\n"; str.splitlines() would also split on raw U+2028/U+0085 inside strings.
+ for line in path.read_text(encoding="utf-8", errors="replace").split("\n"):
+ if not line.strip():
+ continue
+ try:
+ row = json.loads(line)
+ except ValueError:
+ skipped += 1
+ continue
+ if isinstance(row, dict):
+ rows.append(row)
+ if skipped and errors is not None:
+ lost = (
+ "those failure reasons were lost"
+ if path.name.endswith("_failures.jsonl")
+ else "those rollouts were not collected"
+ )
+ errors.append(f"NeMo Gym wrote {skipped} unreadable line(s) to {path.name}; {lost}")
+ return rows
+
+
+_MISSING_ROLLOUT = "_skillevaluator_missing_rollout"
+
+
+def read_rollout_failures(rollouts_path: Path, errors: list[str] | None = None) -> dict[str, list[str]]:
+ """Map each task folder name to the failure messages Gym recorded in ``<stem>_failures.jsonl``."""
+ failures: dict[str, list[str]] = defaultdict(list)
+ for row in read_rollouts(rollouts_path.with_name(f"{rollouts_path.stem}_failures.jsonl"), errors):
+ task_id = row.get("_ng_task_id")
+ if isinstance(task_id, str):
+ with contextlib.suppress(ValueError):
+ task_id = json.loads(task_id)
+ task_name = rollout_task_name({"task_id": task_id})
+ message = row.get("error") or row.get("_ng_failure_message") or row.get("_ng_failure_class")
+ if task_name and message:
+ failures[task_name].append(str(message))
+ return dict(failures)
+
+
+def rollout_task_name(row: dict[str, Any]) -> str | None:
+ """Return the task folder name a Gym Harbor rollout ran."""
+ task_id = row.get("_ng_task_id", row.get("task_id"))
+ if isinstance(task_id, str) and task_id.startswith("{"):
+ with contextlib.suppress(ValueError):
+ task_id = json.loads(task_id)
+ if isinstance(task_id, dict):
+ task_id = task_id.get("task_id")
+ return task_id if isinstance(task_id, str) and task_id else None
+
+
+def read_verifier_rewards(verifier_dir: Path) -> dict[str, Any] | None:
+ """Return a trial's rewards from ``reward.json``, else a numeric ``reward.txt``, as Harbor reads them."""
+ reward_json = verifier_dir / "reward.json"
+ if reward_json.is_file() and not reward_json.is_symlink():
+ try:
+ loaded = json.loads(reward_json.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ return loaded if isinstance(loaded, dict) else None
+ reward_txt = verifier_dir / "reward.txt"
+ if reward_txt.is_file() and not reward_txt.is_symlink():
+ try:
+ value = float(reward_txt.read_text(encoding="utf-8").strip())
+ except (OSError, ValueError):
+ return None
+ return {"reward": value} if math.isfinite(value) else None
+ return None
+
+
+def rollout_failure_text(row: dict[str, Any]) -> str:
+ """Return why a Gym rollout failed, or an empty string when its verifier ran."""
+ return _failure_text(row)
+
+
+def _failure_text(row: dict[str, Any]) -> str:
+ failure = row.get("failure") or row.get("failure_reason") or row.get("failure_kind")
+ if isinstance(failure, dict):
+ return str(failure.get("message") or failure.get("failure_kind") or "NeMo Gym episode failed")
+ if failure:
+ return str(failure)
+ if row.get("mask_sample"):
+ return "NeMo Gym masked the sample (Gym-side failure)"
+ if row.get("verifier_return_code") is None:
+ return "SkillEvaluator verifier did not run in the NeMo Gym sandbox"
+ return ""
+
+
+def _copy_verifier_logs(logs_dir: Path, trial_dir: Path) -> None:
+ verifier_dir = trial_dir / "verifier"
+ verifier_dir.mkdir(parents=True, exist_ok=True)
+ for name in _VERIFIER_FILES:
+ source = logs_dir / name
+ if source.is_file() and not source.is_symlink():
+ shutil.copyfile(source, verifier_dir / name)
+ trajectory = logs_dir / "trajectory.json"
+ if trajectory.is_file() and not trajectory.is_symlink():
+ (trial_dir / "agent").mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(trajectory, trial_dir / "agent" / "trajectory.json")
+
+
+def write_job_from_rollouts(
+ rows: list[dict[str, Any]],
+ job_dir: Path,
+ *,
+ eval_name: str,
+ task_case_ids: dict[str, str],
+ n_attempts: int,
+ failures: dict[str, list[str]] | None = None,
+) -> list[str]:
+ """Write one collector job directory from Gym rollouts and return the run errors.
+
+ ``task_case_ids`` maps each staged task folder name to its evals.json case id.
+ """
+ job_dir.mkdir(parents=True, exist_ok=True)
+ errors: list[str] = []
+ by_task: dict[str, list[dict[str, Any]]] = defaultdict(list)
+ for row in rows:
+ task_name = rollout_task_name(row)
+ if task_name not in task_case_ids:
+ errors.append(f"NeMo Gym returned a rollout for an unknown task: {task_name!r}")
+ continue
+ by_task[task_name].append(row)
+
+ rewarded: dict[str, list[str]] = defaultdict(list)
+ n_scored = 0
+ n_written = 0
+ n_errors = 0
+ for task_name, case_id in task_case_ids.items():
+ task_rows = by_task.get(task_name, [])
+ if len(task_rows) < n_attempts:
+ reasons = sorted(set((failures or {}).get(task_name, [])))
+ detail = f": {'; '.join(reasons)}" if reasons else ""
+ errors.append(f"NeMo Gym returned {len(task_rows)}/{n_attempts} rollouts for case {case_id}{detail}")
+ # Every expected attempt gets a failed trial, so the collector keeps the arm's scored trials.
+ missing = {"failure": f"NeMo Gym returned no rollout{detail}", _MISSING_ROLLOUT: True}
+ task_rows = [*task_rows, *([missing] * (n_attempts - len(task_rows)))]
+ elif len(task_rows) > n_attempts:
+ # Only the planned attempts become trials; the excess is reported so the run is not shown as matching.
+ errors.append(
+ f"NeMo Gym returned {len(task_rows)}/{n_attempts} rollouts for case {case_id}; "
+ f"the {len(task_rows) - n_attempts} extra rollout(s) were not collected"
+ )
+ for attempt, row in enumerate(task_rows[:n_attempts], start=1):
+ trial_name = f"{_safe(task_name)}__gym{attempt:03d}"
+ trial_dir = job_dir / trial_name
+ trial_dir.mkdir(parents=True, exist_ok=True)
+ logs_dir = row.get("verifier_logs_dir")
+ if isinstance(logs_dir, str) and Path(logs_dir).is_dir():
+ _copy_verifier_logs(Path(logs_dir), trial_dir)
+ reward_path = trial_dir / "verifier" / "reward.json"
+ failure = _failure_text(row)
+ rewards: dict[str, Any] | None = None
+ loaded = None if failure else read_verifier_rewards(trial_dir / "verifier")
+ if loaded is not None:
+ rewards = {"entry_id": case_id, **loaded}
+ if reward_path.is_file():
+ reward_path.write_text(json.dumps(rewards, indent=2), encoding="utf-8")
+ if rewards is None:
+ failure = failure or "the task verifier wrote no reward.json or numeric reward.txt"
+ n_errors += 1
+ if not row.get(_MISSING_ROLLOUT):
+ errors.append(f"case {case_id} attempt {attempt}: {failure}")
+ else:
+ n_scored += 1
+ score = rewards.get("overall", rewards.get("reward", row.get("reward", 0.0)))
+ rewarded[str(score)].append(trial_name)
+ (trial_dir / "result.json").write_text(
+ json.dumps(
+ {
+ "trial_name": trial_name,
+ "task_name": task_name,
+ "execution_backend": "nemo-gym",
+ "episode_id": row.get("episode_id"),
+ "verifier_result": {"rewards": rewards} if rewards else None,
+ "exception_info": None
+ if rewards
+ else {"exception_type": "NeMoGymEpisodeFailure", "exception_message": failure},
+ },
+ indent=2,
+ ),
+ encoding="utf-8",
+ )
+ n_written += 1
+
+ (job_dir / "result.json").write_text(
+ json.dumps(
+ {
+ "execution_backend": "nemo-gym",
+ "n_total_trials": len(task_case_ids) * n_attempts,
+ "stats": {
+ "n_trials": n_written,
+ "n_errors": n_errors,
+ "evals": {
+ eval_name: {
+ "n_trials": n_scored,
+ "n_errors": n_errors,
+ "reward_stats": {"reward": dict(rewarded)},
+ }
+ },
+ },
+ },
+ indent=2,
+ ),
+ encoding="utf-8",
+ )
+ return errors
diff --git a/src/skillevaluator/tier3/nemo_gym/runner.py b/src/skillevaluator/tier3/nemo_gym/runner.py
new file mode 100644
index 00000000..53ae72c6
--- /dev/null
+++ b/src/skillevaluator/tier3/nemo_gym/runner.py
@@ -0,0 +1,1292 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+"""Run Tier 3 cases on NeMo Gym instead of Harbor.
+
+SkillEvaluator still turns ``evals.json`` into task folders with its own verifier
+(``tests/test.sh``). NeMo Gym then owns execution: ``gym eval run <tasks>`` starts its
+Harbor-format environment server, model server and agent harness, runs each case in a
+Gym sandbox and grades it with that verifier. The rollouts are normalized back into the
+trial layout the shared collector reads, so scores, lift and reports are unchanged.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+import re
+import signal
+import subprocess
+import time
+import tomllib
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+from skillevaluator.tier3.harbor.progress import (
+ MIN_EXACT_SECRET_CHARS,
+ NullProgressReporter,
+ ProgressEvent,
+ ProgressReporter,
+ redact_progress_detail,
+ secret_values_from_environment,
+)
+from skillevaluator.tier3.nemo_gym.backend import (
+ DEFAULT_RUN_TIMEOUT_S,
+ MCP_SERVERS_ERROR,
+ MODEL_API_KEY_ENV,
+ MODEL_URL_ENV,
+ NATIVE_MCP_SERVERS_ERROR,
+ NEMO_GYM_AGENTS,
+ NEMO_GYM_BACKEND,
+ NEMO_GYM_BIN_ENV,
+ RUN_TIMEOUT_ENV,
+ mcp_servers_declared,
+ model_url_credential_error,
+ native_mcp_servers_declared,
+ nemo_gym_bin,
+ nemo_gym_capability_errors,
+ nemo_gym_cli_error,
+ nemo_gym_harbor_only_option_errors,
+ nemo_gym_sandbox_error,
+ nemo_gym_timeout_s,
+ nemo_gym_version,
+ uses_native_harbor_tasks,
+)
+from skillevaluator.tier3.nemo_gym.results import read_rollout_failures, read_rollouts, write_job_from_rollouts
+
+__all__ = ["MODEL_API_KEY_ENV", "MODEL_URL_ENV", "RUN_TIMEOUT_ENV"]
+
+SANDBOX_ENV = "SKILL_EVAL_NEMO_GYM_SANDBOX"
+HOST_ENV = "SKILL_EVAL_NEMO_GYM_HOST"
+
+
+_SKILLS_DIR_LINE = re.compile(r"^skills_dir\s*=.*\n?", re.MULTILINE)
+
+
+def stage_for_gym(
+ arm_dir: Path,
+ verifier_env: dict[str, str] | None = None,
+ *,
+ timeout_multiplier: float = 1.0,
+ resource_overrides: dict[str, int] | None = None,
+) -> None:
+ """Adapt Harbor-format tasks for Gym's agents and verifier.
+
+ Drops Harbor's ``skills_dir`` task hook, which Gym's CLI agents reject. The task image
+ already carries the skills at each agent's native location (``/root/.agents/skills``,
+ ``/root/.claude/skills``, ...), so the with-skill arm is unchanged and the baseline image
+ still has none. Adds ``verifier_env`` (``${NAME}`` templates) to ``[verifier.env]``: Harbor
+ passes the judge overrides at job level, and Gym has no job-level verifier env. Scales the
+ agent, verifier and environment-build timeouts by ``timeout_multiplier``, as Harbor's
+ ``--timeout-multiplier`` does, because Gym enforces the task's own timeouts. Writes the
+ ``--override-cpus``/``--override-memory-mb`` values into ``[environment]``, which Harbor
+ applies at job level. Raises ``ValueError`` for a task that declares MCP servers.
+ """
+ for task_toml in arm_dir.glob("*/task.toml"):
+ text = task_toml.read_text(encoding="utf-8")
+ if (tomllib.loads(text).get("environment") or {}).get("mcp_servers"):
+ raise ValueError(f"{task_toml.parent.name}: {NATIVE_MCP_SERVERS_ERROR}")
+ staged = _SKILLS_DIR_LINE.sub("", text)
+ existing = set((tomllib.loads(staged).get("verifier") or {}).get("env") or {})
+ lines = "".join(
+ f"{json.dumps(name)} = {json.dumps(value)}\n"
+ for name, value in sorted((verifier_env or {}).items())
+ if name not in existing
+ )
+ if lines:
+ header = re.search(r"^\[verifier\.env\][ \t]*\n", staged, re.MULTILINE)
+ if header:
+ staged = staged[: header.end()] + lines + staged[header.end() :]
+ else:
+ staged = staged.rstrip("\n") + "\n\n[verifier.env]\n" + lines
+ if timeout_multiplier != 1.0:
+ staged = _scaled_task_timeouts(staged, timeout_multiplier, task_file=task_toml)
+ # Harbor's multiplier also scales the verifier's 600 s default.
+ staged = _set_table_numbers(
+ staged,
+ "verifier",
+ {"timeout_sec": _DEFAULT_VERIFIER_TIMEOUT_SEC * timeout_multiplier},
+ only_missing=True,
+ task_file=task_toml,
+ )
+ if resource_overrides:
+ if "memory_mb" in resource_overrides:
+ # Harbor's deprecated `memory = "4G"` would conflict with the overriding memory_mb.
+ staged = _drop_table_key(staged, "environment", "memory", task_file=task_toml)
+ staged = _set_table_numbers(staged, "environment", resource_overrides, task_file=task_toml)
+ if staged != text:
+ task_toml.write_text(staged, encoding="utf-8")
+
+
+_TIMEOUT_FIELDS = {
+ "agent": "timeout_sec",
+ "verifier": "timeout_sec",
+ "environment": "build_timeout_sec",
+ "steps.agent": "timeout_sec",
+ "steps.verifier": "timeout_sec",
+}
+# Harbor's default environment build timeout, which its multiplier also scales when a task names none.
+_DEFAULT_BUILD_TIMEOUT_SEC = 600.0
+# Harbor's VerifierConfig.timeout_sec default.
+_DEFAULT_VERIFIER_TIMEOUT_SEC = 600.0
+_TRIPLE_QUOTES = ('"' * 3, "'" * 3)
+_TABLE_RE = re.compile(r"^[ \t]*\[{1,2}[ \t]*([A-Za-z0-9_.-]+)[ \t]*\]{1,2}[ \t]*(?:#.*)?$")
+_NUMBER_RE = re.compile(r"^([ \t]*)([A-Za-z_]+)([ \t]*=[ \t]*)([0-9][0-9_.eE+-]*)([ \t]*(?:#.*)?)$")
+
+
+def _scaled_task_timeouts(text: str, multiplier: float, *, task_file: Path) -> str:
+ """Scale a staged task.toml's timeouts by Harbor's multiplier, checking nothing else changed."""
+ from skillevaluator.tier3.harbor.runner import _scaled_harbor_timeout
+
+ lines = text.split("\n")
+ table = ""
+ open_string: str | None = None
+ build_timeout_seen = False
+ environment_end: int | None = None
+ for index, line in enumerate(lines):
+ if open_string is not None:
+ if line.count(open_string) % 2:
+ open_string = None
+ continue
+ header = _TABLE_RE.match(line)
+ if header:
+ if table == "environment" and environment_end is None:
+ environment_end = index
+ table = header.group(1)
+ continue
+ number = _NUMBER_RE.match(line)
+ if number and _TIMEOUT_FIELDS.get(table) == number.group(2):
+ field = f"{table}.{number.group(2)}"
+ scaled = _scaled_harbor_timeout(number.group(4), multiplier, task_file=task_file, field=field)
+ build_timeout_seen = build_timeout_seen or table == "environment"
+ lines[index] = f"{number.group(1)}{number.group(2)}{number.group(3)}{scaled!r}{number.group(5)}"
+ continue
+ open_string = next((quote for quote in ('"""', "'''") if line.count(quote) % 2), None)
+ if table == "environment" and environment_end is None:
+ environment_end = len(lines)
+ expected = tomllib.loads(text)
+ _scale_timeout_values(expected, multiplier)
+ if not build_timeout_seen and environment_end is not None:
+ while environment_end > 0 and not lines[environment_end - 1].strip():
+ environment_end -= 1
+ lines.insert(environment_end, f"build_timeout_sec = {_DEFAULT_BUILD_TIMEOUT_SEC * multiplier!r}")
+ expected["environment"]["build_timeout_sec"] = _DEFAULT_BUILD_TIMEOUT_SEC * multiplier
+ staged = "\n".join(lines)
+ if tomllib.loads(staged) != expected:
+ raise ValueError(f"{task_file}: could not apply --timeout-multiplier to the task timeouts")
+ return staged
+
+
+_KEY_RE = re.compile(r"^[ \t]*([A-Za-z0-9_-]+)[ \t]*=")
+
+
+def _drop_table_key(text: str, table_name: str, key: str, *, task_file: Path) -> str:
+ """Remove a single-line ``key = value`` from one top-level task.toml table, checking nothing else changed."""
+ expected = tomllib.loads(text)
+ table_data = expected.get(table_name)
+ if not isinstance(table_data, dict) or key not in table_data:
+ return text
+ del table_data[key]
+ lines = text.split("\n")
+ table = ""
+ for index, line in enumerate(lines):
+ header = _TABLE_RE.match(line)
+ if header:
+ table = header.group(1)
+ continue
+ match = _KEY_RE.match(line)
+ if table == table_name and match and match.group(1) == key:
+ del lines[index]
+ break
+ staged = "\n".join(lines)
+ if tomllib.loads(staged) != expected:
+ raise ValueError(f"{task_file}: could not replace [{table_name}] {key} with the override")
+ return staged
+
+
+def _set_table_numbers(
+ text: str, table_name: str, values: dict[str, Any], *, only_missing: bool = False, task_file: Path
+) -> str:
+ """Set numeric keys of one top-level task.toml table, adding the keys or the table when absent."""
+ lines = text.split("\n")
+ table = ""
+ open_string: str | None = None
+ seen: set[str] = set()
+ table_end: int | None = None
+ for index, line in enumerate(lines):
+ if open_string is not None:
+ if line.count(open_string) % 2:
+ open_string = None
+ continue
+ header = _TABLE_RE.match(line)
+ if header:
+ if table == table_name and table_end is None:
+ table_end = index
+ table = header.group(1)
+ continue
+ number = _NUMBER_RE.match(line)
+ if table == table_name and number and number.group(2) in values:
+ seen.add(number.group(2))
+ if not only_missing:
+ value = values[number.group(2)]
+ lines[index] = f"{number.group(1)}{number.group(2)}{number.group(3)}{value!r}{number.group(5)}"
+ continue
+ open_string = next((quote for quote in _TRIPLE_QUOTES if line.count(quote) % 2), None)
+ if table == table_name and table_end is None:
+ table_end = len(lines)
+ expected = tomllib.loads(text)
+ current = expected.setdefault(table_name, {})
+ if not isinstance(current, dict):
+ raise ValueError(f"{task_file}: [{table_name}] is not a table")
+ missing = {key: value for key, value in values.items() if key not in current and key not in seen}
+ for key, value in values.items():
+ if key in missing or not only_missing:
+ current[key] = value
+ added = [f"{key} = {value!r}" for key, value in missing.items()]
+ if added:
+ if table_end is None:
+ body = lines[:-1] if lines and lines[-1] == "" else lines
+ lines = [*body, "", f"[{table_name}]", *added, ""]
+ else:
+ while table_end > 0 and not lines[table_end - 1].strip():
+ table_end -= 1
+ lines[table_end:table_end] = added
+ staged = "\n".join(lines)
+ if tomllib.loads(staged) != expected:
+ raise ValueError(f"{task_file}: could not set [{table_name}] {', '.join(values)} in the task")
+ return staged
+
+
+def _scale_timeout_values(data: dict[str, Any], multiplier: float) -> None:
+ tables = [(data, section) for section in ("agent", "verifier", "environment")]
+ tables += [
+ (step, section)
+ for step in data.get("steps") or []
+ if isinstance(step, dict)
+ for section in ("agent", "verifier")
+ ]
+ for parent, section in tables:
+ key = "steps." + section if parent is not data else section
+ table = parent.get(section)
+ if isinstance(table, dict) and _TIMEOUT_FIELDS[key] in table:
+ table[_TIMEOUT_FIELDS[key]] = float(table[_TIMEOUT_FIELDS[key]]) * multiplier
+
+
+def _task_case_ids(arm_dir: Path) -> dict[str, str]:
+ mapping: dict[str, str] = {}
+ for task_dir in sorted(p for p in arm_dir.iterdir() if (p / "task.toml").is_file()):
+ metadata = tomllib.loads((task_dir / "task.toml").read_text(encoding="utf-8")).get("metadata") or {}
+ entry_id = metadata.get("entry_id")
+ mapping[task_dir.name] = entry_id if isinstance(entry_id, str) and entry_id else task_dir.name
+ return mapping
+
+
+def _model_endpoint(model: str | None) -> tuple[str, str, str]:
+ """Return ``(model, base_url, api_key)`` for Gym's OpenAI-compatible policy model server."""
+ from skillevaluator.provider_config import resolve_llm_provider
+
+ url = os.environ.get(MODEL_URL_ENV, "").strip()
+ key = os.environ.get(MODEL_API_KEY_ENV, "").strip()
+ if url and not key:
+ # Never send the evaluator's provider key to a policy server it was not issued for.
+ raise ValueError(f"{MODEL_URL_ENV} is set, so also set {MODEL_API_KEY_ENV} (use EMPTY for a keyless server)")
+ resolved_model = model
+ if not url or not key or not resolved_model:
+ provider = resolve_llm_provider()
+ url = url or (provider.base_url or "")
+ key = key or (provider.api_key or "")
+ resolved_model = resolved_model or provider.model
+ if not url or not key or not resolved_model:
+ raise ValueError(
+ f"--backend nemo-gym needs a model, an OpenAI-compatible base URL and an API key "
+ f"(--model, {MODEL_URL_ENV}, {MODEL_API_KEY_ENV}, or the SkillEvaluator LLM provider settings)"
+ )
+ return resolved_model, url, key
+
+
+def verifier_judge_env(skill_path: Path, grading_mode: str, env_mode: str) -> tuple[dict[str, str], dict[str, str]]:
+ """Return ``(task verifier env templates, Gym process env)`` carrying the judge settings.
+
+ Mirrors the Harbor runner's staging. Gym has no job-level env layer, so the job-level
+ judge overrides are folded into the task templates, which the Gym environment server
+ resolves from its own environment; the values never enter a task folder or row.
+ """
+ from skillevaluator.provider_config import ProviderConfigurationError, resolve_llm_provider
+ from skillevaluator.tier3.evals_config import EvalsConfigError, load_evals_config
+ from skillevaluator.tier3.harbor.runner import (
+ _VERIFIER_JUDGE_CONTROL_ENV_VARS,
+ _VERIFIER_JUDGE_MODEL_ENV_VARS,
+ _job_judge_subprocess_env,
+ _job_judge_verifier_env,
+ _provider_environment,
+ _resolve_runtime_env,
+ )
+
+ try:
+ provider = resolve_llm_provider()
+ config, _config_path = load_evals_config(skill_path)
+ except (ProviderConfigurationError, EvalsConfigError) as exc:
+ raise ValueError(str(exc)) from exc
+ runtime_env, runtime_errors = _resolve_runtime_env(
+ (config.get("harbor") or {}).get("runtime_env"), env_mode=env_mode
+ )
+ if runtime_errors:
+ raise ValueError("; ".join(runtime_errors))
+ provider_env = _provider_environment(provider)
+ values = {**runtime_env, **provider_env}
+ templates = {
+ name: f"${{{name}}}"
+ for name in values
+ if name not in _VERIFIER_JUDGE_MODEL_ENV_VARS
+ and not (grading_mode == "custom_only" and name in _VERIFIER_JUDGE_CONTROL_ENV_VARS)
+ }
+ templates.update(_job_judge_verifier_env(provider_env, grading_mode))
+ return templates, {**values, **_job_judge_subprocess_env(provider_env, grading_mode)}
+
+
+def gym_eval_command(
+ gym: str,
+ arm_dir: Path,
+ *,
+ agent: str,
+ model: str,
+ model_url: str,
+ rollouts_path: Path,
+ n_attempts: int,
+ n_concurrent: int | None,
+ sandbox: str,
+ inherit_sandbox_environment: bool = False,
+) -> list[str]:
+ """Build the ``gym eval run`` command for one agent and arm; the API key is read from the environment."""
+ command = [
+ gym,
+ "eval",
+ "run",
+ str(arm_dir),
+ "--agent",
+ NEMO_GYM_AGENTS[agent],
+ "--sandbox",
+ sandbox,
+ "--model-type",
+ "openai_model",
+ "--model",
+ model,
+ "--model-url",
+ model_url,
+ "--output",
+ str(rollouts_path),
+ f"+policy_api_key=${{oc.env:{MODEL_API_KEY_ENV}}}",
+ f"+num_repeats={n_attempts}",
+ "+resume_from_cache=false",
+ ]
+ if n_concurrent:
+ command += ["--concurrency", str(n_concurrent)]
+ if inherit_sandbox_environment:
+ # Gym's Codex agent starts Codex with only its own variables unless told to keep the sandbox's.
+ gym_agent = NEMO_GYM_AGENTS[agent]
+ command.append(f"++{gym_agent}.responses_api_agents.{gym_agent}.inherit_sandbox_environment=true")
+ host = os.environ.get(HOST_ENV, "").strip()
+ if host:
+ command.append(f"+default_host={host}")
+ return command
+
+
+# Package-index settings, and the credentials for them, that Gym's own ``uv sync`` of its servers reads.
+_GYM_HOST_ENV_VARS = frozenset(
+ {"NETRC", "UV_DEFAULT_INDEX", "UV_EXTRA_INDEX_URL", "UV_INDEX", "UV_INDEX_URL", "UV_KEYRING_PROVIDER"}
+)
+_UV_INDEX_CREDENTIAL_ENV = re.compile(r"UV_INDEX_[A-Z0-9_]+_(?:USERNAME|PASSWORD)")
+_GYM_SHUTDOWN_GRACE_SECONDS = 30.0
+_GYM_LOG_DRAIN_SECONDS = 5.0
+
+
+class GymLaunchError(OSError):
+ """``gym eval run`` could not be started."""
+
+
+class GymCleanupError(RuntimeError):
+ """``gym eval run`` could not be confirmed stopped, so its servers or sandboxes may still be running."""
+
+
+_GYM_EARLIER_RUN_NOT_STOPPED = "an earlier NeMo Gym run could not be confirmed stopped"
+
+
+def _signals_raise_keyboard_interrupt() -> Any:
+ """While Gym runs, turn SIGTERM/SIGHUP into one KeyboardInterrupt so Gym's cleanup still runs."""
+ import threading
+
+ names = [name for name in ("SIGTERM", "SIGHUP") if hasattr(signal, name)]
+ if threading.current_thread() is not threading.main_thread() or not names:
+ yield
+ return
+ raised = False
+
+ def _handler(_signum: int, _frame: object) -> None:
+ nonlocal raised
+ if not raised:
+ raised = True
+ raise KeyboardInterrupt
+
+ previous = {name: signal.signal(getattr(signal, name), _handler) for name in names}
+ try:
+ yield
+ finally:
+ for name, handler in previous.items():
+ signal.signal(getattr(signal, name), handler)
+
+
+def _run_gym(
+ command: list[str],
+ *,
+ cwd: Path,
+ env: dict[str, str],
+ log: Any,
+ timeout_s: float,
+ secret_values: set[str] | None = None,
+ reporter: ProgressReporter | None = None,
+) -> int | None:
+ """Run ``gym eval run`` in its own process group; return its exit code, or None on timeout.
+
+ Gym's output reaches ``log`` through the secret redactor. On timeout, Ctrl-C, SIGTERM or
+ SIGHUP the group gets SIGTERM and a grace period, so Gym's own shutdown stops its servers
+ and removes its sandboxes, then always SIGKILL. A second Ctrl-C skips the rest of the grace.
+ If that stop fails, one last bounded SIGKILL and reap follows; a group still not confirmed
+ stopped raises ``GymCleanupError``, so the caller never starts another launch beside it.
+ """
+ import codecs
+ import threading
+
+ from skillevaluator.tier3.harbor.runner import (
+ _HARBOR_RUN_CANCEL_POLL_SECONDS,
+ _HARBOR_RUN_REAP_SECONDS,
+ _terminate_harbor_process_tree,
+ )
+ from skillevaluator.tier3.harbor.stream_redaction import StreamingLogRedactor
+
+ try:
+ process = subprocess.Popen(
+ command,
+ cwd=cwd,
+ env=env,
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ except OSError as exc:
+ raise GymLaunchError(str(exc)) from exc
+ redactor = StreamingLogRedactor(secret_values or set())
+
+ def _pump() -> None:
+ decoder = codecs.getincrementaldecoder("utf-8")("replace")
+ stream = process.stdout
+ if stream is None:
+ return
+ with contextlib.suppress(OSError, ValueError):
+ for chunk in iter(lambda: stream.read1(65536), b""):
+ log.write(redactor.feed(decoder.decode(chunk)))
+ log.flush()
+ log.write(redactor.feed(decoder.decode(b"", final=True)) + redactor.finish())
+ log.flush()
+
+ reader = threading.Thread(target=_pump, name="nemo-gym-log", daemon=True)
+ reader.start()
+
+ def _kill_group() -> None:
+ with contextlib.suppress(ProcessLookupError, PermissionError):
+ os.killpg(process.pid, signal.SIGKILL)
+
+ def _group_is_gone() -> bool:
+ # Signal 0 finds no member once the group is empty; killed members get a moment to be reaped.
+ deadline = time.monotonic() + _HARBOR_RUN_REAP_SECONDS
+ while True:
+ # As PID 1 or a subreaper we adopt Gym's orphans, and on Linux signal 0 still finds a zombie,
+ # so reap our own dead members first. The leader is already reaped, so Popen keeps its status.
+ with contextlib.suppress(ChildProcessError):
+ while os.waitpid(-process.pid, os.WNOHANG)[0]:
+ pass
+ try:
+ os.killpg(process.pid, 0)
+ except ProcessLookupError:
+ return True
+ except PermissionError:
+ pass
+ if time.monotonic() >= deadline:
+ return False
+ time.sleep(_HARBOR_RUN_CANCEL_POLL_SECONDS)
+
+ def _confirm_stopped(cause: Exception) -> None:
+ # The normal stop failed: one last bounded SIGKILL and reap before giving up on the group.
+ _kill_group()
+ with contextlib.suppress(subprocess.TimeoutExpired):
+ process.wait(timeout=_HARBOR_RUN_REAP_SECONDS)
+ if process.poll() is None or not _group_is_gone():
+ raise GymCleanupError(
+ f"NeMo Gym (process group {process.pid}) could not be confirmed stopped: {cause}. "
+ "Its servers or sandboxes may still be running; stop them before another run."
+ ) from cause
+
+ def _stop() -> None:
+ # A second interrupt anywhere in here still SIGKILLs the group before it propagates.
+ try:
+ if reporter is not None:
+ reporter.emit(
+ ProgressEvent(
+ stage="cleanup",
+ state="running",
+ detail="Stopping NeMo Gym; press Ctrl+C again to skip up to 30s of sandbox cleanup",
+ )
+ )
+ # Let a leader that is already exiting be reaped, so macOS reports ESRCH rather than EPERM.
+ with contextlib.suppress(subprocess.TimeoutExpired):
+ process.wait(timeout=_HARBOR_RUN_CANCEL_POLL_SECONDS)
+ try:
+ try:
+ _terminate_harbor_process_tree(process, grace_seconds=_GYM_SHUTDOWN_GRACE_SECONDS)
+ except PermissionError:
+ # macOS EPERM race: the leader was exiting while its group was signalled.
+ with contextlib.suppress(subprocess.TimeoutExpired):
+ process.wait(timeout=_HARBOR_RUN_CANCEL_POLL_SECONDS)
+ if process.poll() is None:
+ raise
+ _kill_group()
+ except (OSError, RuntimeError) as exc:
+ _confirm_stopped(exc)
+ except KeyboardInterrupt:
+ _kill_group()
+ process.wait()
+ raise
+
+ try:
+ with _signals_raise_keyboard_interrupt():
+ try:
+ return process.wait(timeout=timeout_s)
+ except subprocess.TimeoutExpired:
+ _stop()
+ return None
+ except BaseException as interrupt:
+ # A failed stop during Ctrl-C/SIGTERM must not replace the interrupt and let the next arm launch.
+ try:
+ _stop()
+ except Exception as stop_error:
+ if isinstance(stop_error, GymCleanupError) and reporter is not None:
+ # The interrupt still ends the run; the progress output says Gym may be running.
+ with contextlib.suppress(Exception):
+ reporter.emit(ProgressEvent(stage="cleanup", state="failed", detail=str(stop_error)))
+ raise interrupt from stop_error
+ raise
+ finally:
+ reader.join(timeout=_GYM_LOG_DRAIN_SECONDS)
+
+
+def _redacted_row(row: dict[str, Any], secrets: set[str]) -> dict[str, Any]:
+ """Redact the failure text a rollout row carries before it reaches trial and result files."""
+ redacted = dict(row)
+ for name in ("failure", "failure_reason", "failure_kind"):
+ value = redacted.get(name)
+ if isinstance(value, dict):
+ redacted[name] = {
+ key: redact_progress_detail(item, secret_values=secrets) if isinstance(item, str) else item
+ for key, item in value.items()
+ }
+ elif isinstance(value, str):
+ redacted[name] = redact_progress_detail(value, secret_values=secrets)
+ return redacted
+
+
+def gym_launch_environment(credentials: dict[str, str]) -> dict[str, str]:
+ """Return Gym's process environment: the host variables a Harbor backend may receive, plus its credentials.
+
+ Relative host paths (Docker TLS, CA bundles, ...) are anchored to the caller's directory,
+ because Gym runs in the run directory.
+ """
+ from skillevaluator.tier3.harbor.runner import (
+ _HARBOR_BASE_ENV_VARS,
+ _HARBOR_ENV_MODE_VARS,
+ _HARBOR_HOST_PATH_ENV_VARS,
+ _HARBOR_HOST_PATH_LIST_ENV_VARS,
+ _absolute_host_path,
+ )
+
+ allowed = _HARBOR_BASE_ENV_VARS | _HARBOR_ENV_MODE_VARS["docker"] | _GYM_HOST_ENV_VARS
+ host_env = {
+ name: value for name, value in os.environ.items() if name in allowed or _UV_INDEX_CREDENTIAL_ENV.fullmatch(name)
+ }
+ for name in _HARBOR_HOST_PATH_ENV_VARS & host_env.keys():
+ host_env[name] = _absolute_host_path(host_env[name])
+ for name in _HARBOR_HOST_PATH_LIST_ENV_VARS & host_env.keys():
+ host_env[name] = os.pathsep.join(_absolute_host_path(entry) for entry in host_env[name].split(os.pathsep))
+ return {**host_env, **credentials}
+
+
+def _refresh_adc_credentials(
+ credentials: dict[str, str], *, policy_uses_provider_key: bool, timeout_s: float
+) -> tuple[dict[str, str], float]:
+ """Mint a fresh Vertex ADC token for one Gym launch and cap the launch to its lifetime.
+
+ Mirrors the Harbor runner: the token is refreshed before every launch, reused as the
+ policy key when the policy has no key of its own, and the launch timeout is
+ capped by ``compute_adc_job_timeout``. Raises ``RuntimeError``/``ValueError`` on failure.
+ """
+ from skillevaluator.provider_config import (
+ CREDENTIAL_EXPIRY_ENV,
+ CREDENTIAL_SOURCE_ADC,
+ CREDENTIAL_SOURCE_ENV,
+ _get_google_access_token,
+ _is_vertex_openapi_endpoint,
+ _normalize_expiry_epoch,
+ compute_adc_job_timeout,
+ get_adc_token_expiry,
+ refresh_host_vertex_adc_environment,
+ )
+ from skillevaluator.tier3.harbor.runner import VERTEX_ADC_JOB_TIMEOUT_ENV
+
+ refreshed = dict(credentials)
+ fresh = refresh_host_vertex_adc_environment(
+ refreshed, fallback_env=os.environ, fail_on_expired=True, token_getter=_get_google_access_token
+ )
+ if fresh:
+ refreshed["OPENAI_API_KEY"] = fresh
+ if policy_uses_provider_key:
+ refreshed[MODEL_API_KEY_ENV] = fresh
+ source = refreshed.get(CREDENTIAL_SOURCE_ENV) or os.environ.get(CREDENTIAL_SOURCE_ENV)
+ base_url = refreshed.get("OPENAI_BASE_URL") or os.environ.get("OPENAI_BASE_URL")
+ if source == CREDENTIAL_SOURCE_ADC and _is_vertex_openapi_endpoint(base_url):
+ expiry = get_adc_token_expiry(refreshed.get("OPENAI_API_KEY")) or _normalize_expiry_epoch(
+ refreshed.get(CREDENTIAL_EXPIRY_ENV) or os.environ.get(CREDENTIAL_EXPIRY_ENV)
+ )
+ raw_timeout = os.environ.get(VERTEX_ADC_JOB_TIMEOUT_ENV, "").strip()
+ timeout_s = min(
+ timeout_s, compute_adc_job_timeout(expiry_epoch=expiry, configured_timeout_sec=raw_timeout or None)
+ )
+ return refreshed, timeout_s
+
+
+def _is_positive_int(value: object) -> bool:
+ return isinstance(value, int) and not isinstance(value, bool) and value >= 1
+
+
+def run_nemo_gym_eval(
+ *,
+ skill_path: Path,
+ agents: list[str],
+ skip_baseline: bool,
+ n_attempts: int | None,
+ pass_threshold: float | None,
+ n_concurrent: int | None,
+ model: str | None,
+ agent_models: dict[str, str] | None,
+ skill_workspace_mode: str | None,
+ include_skills: list[Path] | None,
+ grading_mode: str | None,
+ output_dir: Path,
+ env_mode: str,
+ timeout_multiplier: float | None,
+ evaluated_source: dict[str, str] | None,
+ override_cpus: int | None,
+ override_memory_mb: int | None,
+ repo_context_exclude_paths: tuple[Path, ...] = (),
+ progress_reporter: ProgressReporter | None = None,
+ skip_with_skill: bool = False,
+ max_cases: int | None = None,
+ max_agents: int | None = None,
+ stop_on_pass: bool | None = None,
+ agent_runtime_preflight: bool | None = None,
+ custom_dockerfile_mode: str | None = None,
+ copy_repo: bool = False,
+ tolerate_baseline_timeouts: bool | None = None,
+) -> dict[str, Any]:
+ """Run the selected arms on NeMo Gym and return the shared results mapping."""
+ from skillevaluator.evaluation.tier3_report import render_agent_eval_html_report
+ from skillevaluator.provider_config import ProviderConfigurationError, resolve_llm_provider
+ from skillevaluator.publication_identity import publication_target_from_path
+ from skillevaluator.source_identity import normalized_evaluated_source
+ from skillevaluator.tier3.case_ids import validate_case_ids
+ from skillevaluator.tier3.evals_config import EvalsConfigError, load_evals_config
+ from skillevaluator.tier3.harbor.adapter import (
+ build_eval_base_image,
+ find_evals_file,
+ generate_harbor_tasks,
+ stage_native_harbor_tasks,
+ )
+ from skillevaluator.tier3.harbor.artifact_retention import HarborArtifactLifecycle
+ from skillevaluator.tier3.harbor.collector import _score_definition_for_policy, collect_harbor_results
+ from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS, score_policy_for_metrics
+ from skillevaluator.tier3.harbor.progress import Tier3RunPlan
+ from skillevaluator.tier3.harbor.report_data import dataset_snapshot_manifest
+ from skillevaluator.tier3.harbor.runner import (
+ _MISSING_EVALS_DATASET_ERROR,
+ _VERIFIER_JUDGE_CONTROL_ENV_VARS,
+ _VERIFIER_JUDGE_MODEL_ENV_VARS,
+ _apply_retention_outcome,
+ _decoy_workspace_skills,
+ _judge_model_config,
+ _limit_staged_cases,
+ _merge_launch_execution_errors,
+ _native_entry_id,
+ _persist_dataset_truth,
+ _private_decoy_workspace_snapshot,
+ _provider_environment,
+ _reserve_run_dir,
+ _resolve_runtime_env,
+ _runtime_context_is_bound_to_publication_target,
+ _validated_pass_threshold,
+ _workspace_skills,
+ _write_final_result,
+ )
+ from skillevaluator.tier3.results_location import publish_latest_results
+
+ started_at = time.monotonic()
+ publication_target = publication_target_from_path(skill_path)
+ reporter = progress_reporter or NullProgressReporter()
+
+ def _config_failure(detail: str) -> dict[str, Any]:
+ reporter.emit(ProgressEvent(stage="configuration", state="failed", detail=detail))
+ return {"error": [detail]}
+
+ gym = nemo_gym_bin()
+ if gym is None:
+ raise ValueError(
+ f"--backend nemo-gym needs a verified, pinned Gym task-folder CLI: set {NEMO_GYM_BIN_ENV} "
+ "to its `gym` executable; public nemo-gym 0.7.0 is incompatible and the candidate source still needs runtime qualification"
+ )
+ if skip_baseline and skip_with_skill:
+ return _config_failure("skip_baseline and skip_with_skill are mutually exclusive (no arm would run)")
+ if cli_error := nemo_gym_cli_error(gym):
+ return _config_failure(cli_error)
+ try:
+ provider = resolve_llm_provider()
+ config, config_path = load_evals_config(skill_path)
+ except (ProviderConfigurationError, EvalsConfigError) as exc:
+ return _config_failure(str(exc))
+
+ # Unset options resolve from evals/config.yml exactly as on Harbor; anything Gym cannot honor is rejected.
+ harbor_config = config.get("harbor") or {}
+ grading_config = config.get("grading") or {}
+ workspace_config = config.get("skill_workspace") or {}
+ attempts = n_attempts if n_attempts is not None else harbor_config.get("n_attempts", 1)
+ concurrency = n_concurrent if n_concurrent is not None else harbor_config.get("n_concurrent", 4)
+ max_cases = max_cases if max_cases is not None else harbor_config.get("max_cases")
+ effective_grading = grading_mode or grading_config.get("mode", "default")
+ workspace_mode = skill_workspace_mode or workspace_config.get("mode", "isolated")
+ effective_timeout = (
+ timeout_multiplier if timeout_multiplier is not None else harbor_config.get("timeout_multiplier", 1.0)
+ )
+ errors = nemo_gym_capability_errors(
+ agents=agents,
+ env_mode=env_mode,
+ grading_mode=effective_grading,
+ stop_on_pass=bool(stop_on_pass if stop_on_pass is not None else harbor_config.get("stop_on_pass", False)),
+ custom_dockerfile_mode=custom_dockerfile_mode or harbor_config.get("custom_dockerfile_mode"),
+ agent_runtime_preflight=bool(
+ agent_runtime_preflight
+ if agent_runtime_preflight is not None
+ else harbor_config.get("agent_runtime_preflight", False)
+ ),
+ )
+ # A flag overrides its config key, as on Harbor.
+ config_options = dict(harbor_config)
+ if tolerate_baseline_timeouts is not None:
+ config_options.pop("tolerate_baseline_timeouts", None)
+ errors += nemo_gym_harbor_only_option_errors(config_options, from_config=True)
+ errors += nemo_gym_harbor_only_option_errors({"tolerate_baseline_timeouts": tolerate_baseline_timeouts})
+ # Gym runs agents one at a time, so the cap always holds; it is still validated as on Harbor.
+ effective_max_agents = max_agents if max_agents is not None else harbor_config.get("max_agents", 1)
+ if isinstance(effective_max_agents, bool) or not isinstance(effective_max_agents, int) or effective_max_agents < 1:
+ errors.append("max_agents must be >= 1")
+ from skillevaluator.tier3.harbor.runner import _validated_timeout_multiplier
+
+ try:
+ effective_timeout = _validated_timeout_multiplier(effective_timeout)
+ except ValueError as exc:
+ errors.append(str(exc))
+ if not _is_positive_int(attempts):
+ errors.append("n_attempts must be >= 1")
+ if not _is_positive_int(concurrency):
+ errors.append("n_concurrent must be >= 1")
+ if max_cases is not None and not _is_positive_int(max_cases):
+ errors.append("max_cases must be >= 1")
+ configured_task_source = harbor_config.get("task_source", "auto")
+ if configured_task_source not in ("auto", "evals_json", "native_harbor"):
+ errors.append("harbor.task_source must be auto, evals_json, or native_harbor")
+ task_source = "native_harbor" if uses_native_harbor_tasks(skill_path, configured_task_source) else "evals_json"
+ if task_source == "native_harbor" and not (skill_path / "evals" / "harbor").is_dir():
+ errors.append("No native Harbor task source found at evals/harbor.")
+ if task_source == "evals_json" and find_evals_file(skill_path) is None:
+ errors.append(_MISSING_EVALS_DATASET_ERROR)
+ if mcp_servers_declared(skill_path):
+ errors.append(MCP_SERVERS_ERROR)
+ if task_source == "native_harbor" and native_mcp_servers_declared(skill_path):
+ errors.append(NATIVE_MCP_SERVERS_ERROR)
+ pre_agent_setup = list(harbor_config.get("pre_agent_setup") or [])
+ if pre_agent_setup and not skip_baseline:
+ if skip_with_skill:
+ errors.append(
+ "harbor.pre_agent_setup/setup_commands cannot run in a baseline-only run (--skip-with-skill); "
+ "the baseline arm must stay isolated from skill-owned setup commands"
+ )
+ else:
+ errors.append(
+ "harbor.pre_agent_setup/setup_commands cannot run in a paired evaluation; "
+ "use --skip-baseline for a with-skill-only run"
+ )
+ agent_workdir = harbor_config.get("agent_workdir")
+ if agent_workdir is not None:
+ from skillevaluator.tier3.harbor.adapter import _validated_agent_workdir
+
+ try:
+ agent_workdir = _validated_agent_workdir(agent_workdir)
+ except ValueError as exc:
+ errors.append(f"harbor.{exc}")
+ resource_config = dict(harbor_config.get("resources") or {})
+ if "storage_mb" in resource_config:
+ errors.append("harbor.resources.storage_mb is not supported with --backend nemo-gym")
+ include_values = [*workspace_config.get("include", []), *(include_skills or [])]
+ if include_values and workspace_mode != "group":
+ errors.append("include_skills requires skill_workspace.mode=group")
+ for name, value in (("cpus", override_cpus), ("memory_mb", override_memory_mb)):
+ if value is not None and value <= 0:
+ errors.append(f"--override-{name.replace('_', '-')} must be greater than 0")
+ timeout_s = DEFAULT_RUN_TIMEOUT_S
+ try:
+ timeout_s = nemo_gym_timeout_s()
+ except ValueError as exc:
+ errors.append(str(exc))
+ if sandbox_error := nemo_gym_sandbox_error():
+ errors.append(sandbox_error)
+ if errors:
+ return _config_failure("; ".join(errors))
+ try:
+ threshold = _validated_pass_threshold(
+ pass_threshold if pass_threshold is not None else harbor_config.get("pass_threshold", 0.5)
+ )
+ decoy_manifest: dict[str, Any] | None = None
+ selected_decoys: list[Path] = []
+ if "decoy_manifest" in workspace_config:
+ workspace_skills, selected_decoys, decoy_manifest = _decoy_workspace_skills(
+ skill_path, workspace_config, workspace_mode, include_skills
+ )
+ else:
+ workspace_skills = _workspace_skills(skill_path, include_values if workspace_mode == "group" else [])
+ workspace_source_paths = [*workspace_skills, *selected_decoys]
+ except ValueError as exc:
+ return _config_failure(str(exc))
+
+ gym_version = nemo_gym_version(gym)
+ sandbox = os.environ.get(SANDBOX_ENV, "docker").strip() or "docker"
+ execution_backend = {"name": NEMO_GYM_BACKEND, "version": gym_version, "sandbox": sandbox}
+ resolved_models: dict[str, dict[str, str]] = {}
+ endpoints: dict[str, tuple[str, str, str]] = {}
+ # _model_endpoint falls back to the provider key exactly when the policy has none of its own.
+ policy_uses_provider_key = not os.environ.get(MODEL_API_KEY_ENV, "").strip()
+ config_agents = harbor_config.get("agents") or {}
+ for agent in agents:
+ cli_model = (agent_models or {}).get(agent) or model
+ config_model = (config_agents.get(agent) or {}).get("model")
+ endpoints[agent] = _model_endpoint(cli_model or config_model)
+ source = "CLI" if cli_model else "evals/config.yml" if config_model else "public provider default"
+ resolved_models[agent] = {"agent": agent, "model": endpoints[agent][0], "source": source}
+ if url_error := model_url_credential_error(endpoints[agent][1]):
+ return _config_failure(url_error)
+
+ # Judge credentials reach only the verifier: tasks carry ${NAME} templates that the
+ # Gym environment server resolves from its own process environment. Resolved before the
+ # run folder is reserved, so a bad harbor.runtime_env leaves nothing behind, as on Harbor.
+ try:
+ judge_verifier_env, judge_process_env = verifier_judge_env(skill_path, effective_grading, env_mode)
+ except ValueError as exc:
+ return _config_failure(str(exc))
+ reporter.set_secret_values(set(judge_process_env.values()))
+ # harbor.runtime_env reaches the agent as ${NAME} templates, resolved from Gym's environment.
+ runtime_values, _runtime_errors = _resolve_runtime_env(harbor_config.get("runtime_env"), env_mode=env_mode)
+ agent_runtime_env = {name: f"${{{name}}}" for name in runtime_values}
+
+ run_dir = _reserve_run_dir(output_dir, datetime.now(UTC).strftime("%Y%m%d_%H%M%S"))
+ # As on Harbor, the results root never enters a --copy-repo or base-image build context.
+ repo_context_exclude_paths = (Path(output_dir), *(Path(path) for path in repo_context_exclude_paths))
+ tasks_root = run_dir / "_harbor-tasks"
+ jobs_dir = run_dir / "_harbor-jobs"
+ gym_root = run_dir / "_nemo-gym"
+ # Staged tasks and raw trial files can hold trajectories with secrets: removed as on Harbor
+ # without --harbor-keep-jobs. Gym's own launch logs and rollouts stay in _nemo-gym/.
+ with HarborArtifactLifecycle([jobs_dir, tasks_root], keep_requested=False) as lifecycle:
+ gym_root.mkdir(parents=True, exist_ok=True)
+ arms = [
+ (arm, with_skill)
+ for arm, with_skill, skipped in (("with", True, skip_with_skill), ("without", False, skip_baseline))
+ if not skipped
+ ]
+ task_resources = {
+ **resource_config,
+ **{
+ key: value
+ for key, value in (("cpus", override_cpus), ("memory_mb", override_memory_mb))
+ if value is not None
+ },
+ }
+ reporter.emit(ProgressEvent(stage="configuration", state="ready", detail="evaluation config validated"))
+ judge_job_env = {
+ name: value
+ for name, value in judge_verifier_env.items()
+ if name in _VERIFIER_JUDGE_CONTROL_ENV_VARS | _VERIFIER_JUDGE_MODEL_ENV_VARS
+ }
+ launch_errors: list[str] = []
+ case_ids: list[str] = []
+ case_selection: dict[str, Any] | None = None
+ # Stage every agent and arm before the first launch, so all arms see the same skill inputs.
+ planned: list[tuple[str, str, Path, dict[str, str]]] = []
+ staged_task_paths: list[Path] = []
+ base_image_mode = harbor_config.get("base_image_mode", "disabled")
+ base_image = ""
+ if base_image_mode != "disabled":
+ reporter.emit(
+ ProgressEvent(
+ stage="docker-images",
+ state="running",
+ detail=f"preparing shared eval base image ({base_image_mode})",
+ )
+ )
+ base_image = build_eval_base_image(
+ skill_path.resolve(),
+ None,
+ workspace_skill_paths=workspace_source_paths,
+ excluded_roots=repo_context_exclude_paths,
+ force_rebuild=base_image_mode == "rebuild",
+ )
+ reporter.emit(
+ ProgressEvent(stage="docker-images", state="complete", detail=f"eval base image ready: {base_image}")
+ if base_image
+ else ProgressEvent(
+ stage="docker-images",
+ state="degraded",
+ detail="base image build failed; falling back to per-task Dockerfiles",
+ )
+ )
+ # Every arm stages the same verified decoy bytes, as on Harbor.
+ with (
+ _private_decoy_workspace_snapshot(selected_decoys, decoy_manifest)
+ if decoy_manifest is not None
+ else contextlib.nullcontext([])
+ ) as frozen_decoys:
+ staged_workspace_skills = [*workspace_skills, *frozen_decoys]
+ for agent in agents:
+ for arm, with_skill in arms:
+ arm_dir = tasks_root / agent / arm
+ emit_tasks = stage_native_harbor_tasks if task_source == "native_harbor" else generate_harbor_tasks
+ task_paths = emit_tasks(
+ skill_path,
+ arm_dir,
+ with_skill=with_skill,
+ workspace_skill_paths=staged_workspace_skills,
+ workspace_mode=workspace_mode,
+ grading_mode=effective_grading,
+ verifier_env=judge_verifier_env or None,
+ repo_context_exclude_paths=repo_context_exclude_paths,
+ task_resources=task_resources or None,
+ runtime_env=agent_runtime_env or None,
+ arm_suffix=f"-{arm}-skill" if len(arms) == 2 else "",
+ pre_agent_setup=pre_agent_setup or None,
+ agent_workdir=agent_workdir,
+ copy_repo=copy_repo,
+ base_image=base_image,
+ custom_dockerfile_mode=custom_dockerfile_mode
+ or harbor_config.get("custom_dockerfile_mode", "rebase"),
+ )
+ if max_cases is not None:
+ selectors = validate_case_ids(task.name for task in task_paths)
+ selector_case_ids = validate_case_ids(_native_entry_id(task) for task in task_paths)
+ case_selection = _limit_staged_cases(
+ selectors,
+ dict(zip(selectors, selector_case_ids, strict=True)),
+ task_paths,
+ max_cases=max_cases,
+ )
+ stage_for_gym(
+ arm_dir,
+ judge_job_env,
+ timeout_multiplier=effective_timeout,
+ # Generated tasks already carry them; native tasks get Harbor's job-level override.
+ resource_overrides={
+ key: value
+ for key, value in (("cpus", override_cpus), ("memory_mb", override_memory_mb))
+ if value is not None and task_source == "native_harbor"
+ },
+ )
+ task_case_ids = _task_case_ids(arm_dir)
+ case_ids = case_ids or sorted(set(task_case_ids.values()))
+ staged_task_paths += [task for task in task_paths if task.is_dir()]
+ planned.append((agent, arm, arm_dir, task_case_ids))
+ # The same plan a Harbor run starts its reporter with; output_dir lets a case view poll the rollouts.
+ reporter.start(
+ Tier3RunPlan(
+ skill_name=skill_path.name,
+ environment=env_mode,
+ agents=tuple(agents),
+ agent_models=tuple((agent, endpoints[agent][0]) for agent in agents),
+ provider=provider.provider,
+ case_count=len(case_ids),
+ attempts=attempts,
+ baseline=not skip_baseline,
+ with_skill=not skip_with_skill,
+ concurrency=concurrency,
+ timeout_multiplier=float(effective_timeout),
+ matrix_trials=len(case_ids) * attempts * len(planned),
+ output_dir=str(run_dir),
+ )
+ )
+ runtime_context_bound = _runtime_context_is_bound_to_publication_target(
+ skill_path,
+ staged_task_paths,
+ reference_skills_dir=None,
+ workspace_skill_paths=workspace_source_paths,
+ )
+ # The same immutable dataset identity a Harbor run records, taken before any agent runs.
+ dataset_warning: str | None = None
+ try:
+ dataset_truth = _persist_dataset_truth(run_dir, fallback_task_ids=case_ids)
+ except Exception as exc:
+ dataset_truth = None
+ dataset_warning = f"Dataset snapshot was not recorded: {type(exc).__name__}"
+
+ # Set once a Gym group cannot be confirmed stopped. Nothing else is launched beside it, but the
+ # arms that finished are still collected, so the failed run keeps their scores.
+ cleanup_error: GymCleanupError | None = None
+ for agent in agents:
+ reporter.emit(ProgressEvent(stage=f"agent:{agent}", state="running", detail="NeMo Gym"))
+ agent_model, model_url, api_key = endpoints[agent]
+ errors_before = len(launch_errors)
+ blocked_before_agent = cleanup_error is not None
+ for planned_agent, arm, arm_dir, task_case_ids in planned:
+ if planned_agent != agent:
+ continue
+ arm_errors: list[str] = []
+ secrets = {value for value in judge_process_env.values() if len(value) >= MIN_EXACT_SECRET_CHARS}
+ rollouts_path = gym_root / f"{agent}-{arm}" / "rollouts.jsonl"
+ log_path = rollouts_path.with_name("gym.log")
+ if cleanup_error is not None:
+ arm_errors.append(f"gym eval run was not started: {_GYM_EARLIER_RUN_NOT_STOPPED}")
+ else:
+ rollouts_path.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ credentials, arm_timeout = _refresh_adc_credentials(
+ {**judge_process_env, MODEL_API_KEY_ENV: api_key},
+ policy_uses_provider_key=policy_uses_provider_key,
+ timeout_s=timeout_s,
+ )
+ except (RuntimeError, ValueError) as exc:
+ arm_errors.append(f"Vertex AI ADC credentials could not be refreshed: {exc}")
+ else:
+ launch_env = gym_launch_environment(credentials)
+ secrets |= {
+ value
+ for value in credentials.values()
+ if len(value) >= MIN_EXACT_SECRET_CHARS and value != "EMPTY"
+ }
+ secrets |= secret_values_from_environment(launch_env)
+ reporter.set_secret_values(secrets)
+ command = gym_eval_command(
+ gym,
+ arm_dir,
+ agent=agent,
+ model=agent_model,
+ model_url=model_url,
+ rollouts_path=rollouts_path,
+ n_attempts=attempts,
+ n_concurrent=concurrency,
+ sandbox=sandbox,
+ inherit_sandbox_environment=agent == "codex" and sandbox == "docker",
+ )
+ reporter.emit(
+ ProgressEvent(stage=f"agent:{agent}", state="running", detail=f"NeMo Gym {arm}-skill arm")
+ )
+ with log_path.open("w", encoding="utf-8") as log:
+ try:
+ returncode = _run_gym(
+ command,
+ cwd=rollouts_path.parent,
+ env=launch_env,
+ log=log,
+ timeout_s=arm_timeout,
+ secret_values=secrets,
+ reporter=reporter,
+ )
+ except GymLaunchError as exc:
+ arm_errors.append(f"gym eval run could not start: {exc}")
+ except GymCleanupError as exc:
+ # Only the timeout path raises it; an interrupt re-raises KeyboardInterrupt.
+ cleanup_error = exc
+ arm_errors += [f"gym eval run timed out after {arm_timeout:.0f}s", str(exc)]
+ else:
+ if returncode is None:
+ arm_errors.append(f"gym eval run timed out after {arm_timeout:.0f}s")
+ elif returncode != 0:
+ arm_errors.append(f"gym eval run exited {returncode}; see {log_path}")
+ rows = [_redacted_row(row, secrets) for row in read_rollouts(rollouts_path, arm_errors)]
+ failures = {
+ task: [redact_progress_detail(reason, secret_values=secrets) for reason in reasons]
+ for task, reasons in read_rollout_failures(rollouts_path, arm_errors).items()
+ }
+ arm_errors += write_job_from_rollouts(
+ rows,
+ jobs_dir / f"{skill_path.name}-{agent}-{arm}",
+ eval_name=f"{agent}__{agent_model}",
+ task_case_ids=task_case_ids,
+ n_attempts=attempts,
+ failures=failures,
+ )
+ launch_errors += [
+ f"{agent} {arm}-skill: {redact_progress_detail(error, secret_values=secrets)}"
+ for error in arm_errors
+ ]
+ if cleanup_error is not None:
+ # The row says that Gym may still be running, or why this agent never started.
+ detail = f"not started: {_GYM_EARLIER_RUN_NOT_STOPPED}" if blocked_before_agent else str(cleanup_error)
+ reporter.emit(ProgressEvent(stage=f"agent:{agent}", state="failed", detail=detail))
+ else:
+ reporter.emit(
+ ProgressEvent(
+ stage=f"agent:{agent}",
+ state="failed",
+ detail=f"one or more NeMo Gym runs failed; see {gym_root}/{agent}-*/gym.log",
+ )
+ if len(launch_errors) > errors_before
+ else ProgressEvent(stage=f"agent:{agent}", state="complete")
+ )
+
+ reporter.emit(ProgressEvent(stage="collection", state="running"))
+ results = collect_harbor_results(
+ skill_name=skill_path.name,
+ agents=agents,
+ output_dir=run_dir,
+ jobs_dir=jobs_dir,
+ skip_baseline=skip_baseline,
+ skip_with_skill=skip_with_skill,
+ n_attempts=attempts,
+ pass_threshold=threshold,
+ expected_cases=len(case_ids),
+ expected_case_ids=case_ids,
+ expected_trials=len(case_ids) * attempts,
+ env_mode=env_mode,
+ agent_models=resolved_models,
+ launch_errors=launch_errors,
+ grading_mode=effective_grading,
+ )
+ if launch_errors:
+ _merge_launch_execution_errors(results, launch_errors)
+ if cleanup_error is not None:
+ # Also a warning: the summary shows warnings even when it folds failure details behind --verbose.
+ results.setdefault("warnings", []).append(str(cleanup_error))
+ reporter.emit(ProgressEvent(stage="collection", state="complete", detail="NeMo Gym results collected"))
+
+ # The same completion contract as a Harbor run, so result discovery (`view`, compare) finds Gym runs.
+ try:
+ config_file = str(config_path.relative_to(skill_path)) if config_path else "none"
+ except ValueError:
+ config_file = config_path.name if config_path else "none"
+ run_config: dict[str, Any] = {
+ "config_file": config_file,
+ "harbor": {
+ "environment": {"value": env_mode, "source": "CLI"},
+ "environment_kwargs": {"keys": [], "sources": {}},
+ "n_attempts": attempts,
+ "stop_on_pass": False,
+ "n_concurrent": concurrency,
+ "timeout_multiplier": effective_timeout,
+ "base_image_mode": base_image_mode,
+ "custom_dockerfile_mode": custom_dockerfile_mode
+ or harbor_config.get("custom_dockerfile_mode", "rebase"),
+ "jobs_retained": False,
+ },
+ "provider": {"name": provider.provider, "model": provider.model},
+ "judge": _judge_model_config(provider, _provider_environment(provider), effective_grading),
+ "task_source": task_source,
+ "grading": {"mode": effective_grading},
+ "agents": resolved_models,
+ "evaluated_source": normalized_evaluated_source(evaluated_source),
+ "execution_backend": execution_backend,
+ }
+ if max_cases is not None:
+ run_config["harbor"]["max_cases"] = max_cases
+ if case_selection is not None:
+ run_config["case_selection"] = case_selection
+ if decoy_manifest is not None:
+ run_config["skill_workspace"] = {"mode": workspace_mode, "decoy_manifest": decoy_manifest}
+ selected_metrics = tuple(results.get("metrics", DEFAULT_METRICS))
+ attempt_policy = dict(results.get("attempt_policy") or {})
+ score_policy = results.get("score_policy") or attempt_policy.get("score_policy")
+ if not isinstance(score_policy, str) or not score_policy.strip():
+ score_policy = score_policy_for_metrics(selected_metrics)
+ attempt_policy.update(
+ {
+ "max_attempts": attempts,
+ "pass_threshold": float(threshold),
+ "stop_on_pass": False,
+ "score_policy": score_policy,
+ "score_definition": attempt_policy.get("score_definition")
+ or _score_definition_for_policy(selected_metrics, score_policy),
+ }
+ )
+ if dataset_warning:
+ results.setdefault("warnings", []).append(dataset_warning)
+ if dataset_truth is not None:
+ results.update(
+ {
+ "evaluated_at": datetime.now(UTC).isoformat(),
+ "evaluator_version": dataset_truth["evaluator_version"],
+ "dataset_snapshot": dataset_snapshot_manifest(dataset_truth),
+ "dataset_snapshot_path": str(run_dir / "dataset_snapshot.json"),
+ "dataset_summary": dataset_truth["dataset_summary"],
+ "dataset_digest": dataset_truth["dataset_digest"],
+ "dataset_digest_algorithm": dataset_truth["dataset_digest_algorithm"],
+ }
+ )
+ run_end_target = publication_target_from_path(skill_path) if runtime_context_bound else None
+ if not runtime_context_bound:
+ # Included skills or repo context the digest does not cover were staged into the tasks.
+ results["publication_target"] = None
+ results["publication_target_conflict"] = {
+ "run_start": dict(publication_target) if publication_target is not None else None,
+ "run_end": None,
+ "reason_code": "runtime_context_outside_publication_target",
+ }
+ elif run_end_target == publication_target:
+ results["publication_target"] = dict(publication_target) if publication_target is not None else None
+ else:
+ results["publication_target"] = None
+ results["publication_target_conflict"] = {
+ "run_start": dict(publication_target) if publication_target is not None else None,
+ "run_end": dict(run_end_target) if run_end_target is not None else None,
+ }
+ result_path = run_dir / "result.json"
+ results.update(
+ {
+ "skill_name": skill_path.name,
+ "run_id": run_dir.name,
+ "run_dir": str(run_dir),
+ "result_path": str(result_path),
+ "execution_backend": execution_backend,
+ "nemo_gym_dir": str(gym_root),
+ "attempt_policy": attempt_policy,
+ "run_config": run_config,
+ }
+ )
+ if evaluated_source:
+ results["evaluated_source"] = dict(evaluated_source)
+ (run_dir / "run_config.json").write_text(json.dumps(run_config, indent=2), encoding="utf-8")
+ try:
+ results["report_path"] = str(
+ render_agent_eval_html_report(skill_path, run_dir, env_mode=env_mode, engine_result=results)
+ )
+ results["report_status"] = "complete"
+ except Exception as exc:
+ results.setdefault("warnings", []).append(f"HTML report was not generated: {type(exc).__name__}")
+ results["report_status"] = "degraded"
+ outcome = lifecycle.finalize()
+ _apply_retention_outcome(results, outcome=outcome, jobs_dir=jobs_dir)
+ (run_dir / "run_config.json").write_text(json.dumps(run_config, indent=2), encoding="utf-8")
+ results["duration_seconds"] = round(time.monotonic() - started_at, 3)
+ final = _write_final_result(result_path, results)
+ publish_latest_results(output_dir, run_dir.name)
+ return final
diff --git a/src/skillevaluator/tier3/reference_skills/api-caller/scripts/call_api.py b/src/skillevaluator/tier3/reference_skills/api-caller/scripts/call_api.py
index b65cef54..a670923b 100644
--- a/src/skillevaluator/tier3/reference_skills/api-caller/scripts/call_api.py
+++ b/src/skillevaluator/tier3/reference_skills/api-caller/scripts/call_api.py
@@ -217,9 +217,7 @@ def main():
if args.spec and args.operation:
spec = fetch_openapi_spec(args.spec)
if not spec:
- _print_json(
- {"success": False, "error": f"Failed to fetch OpenAPI spec from {args.spec}"}, file=sys.stderr
- )
+ _print_json({"success": False, "error": f"Failed to fetch OpenAPI spec from {args.spec}"}, file=sys.stderr)
sys.exit(1)
path, spec_method, _operation = find_operation(spec, args.operation)
diff --git a/src/skillevaluator/tier3/workflow.py b/src/skillevaluator/tier3/workflow.py
index b8cffd80..19086720 100644
--- a/src/skillevaluator/tier3/workflow.py
+++ b/src/skillevaluator/tier3/workflow.py
@@ -5,6 +5,7 @@
from __future__ import annotations
+import os
import stat
from collections.abc import Iterator
from contextlib import contextmanager
@@ -102,8 +103,12 @@ def _resolve_workflow_environment_kwargs(params: dict[str, Any]) -> dict[str, An
)
-def _preflight_options(skill_path: Path, params: dict[str, Any]) -> dict[str, Any]:
- """Reject known configuration errors before generating a paid dataset."""
+def _preflight_options(skill_path: Path, params: dict[str, Any], *, harbor_runtime: bool = True) -> dict[str, Any]:
+ """Reject known configuration errors before generating a paid dataset.
+
+ ``harbor_runtime=False`` keeps the backend-neutral checks but skips the Harbor agent
+ runtime and credential plan, for backends that run their own agent harness.
+ """
from skillevaluator.cli import _evaluated_source_from_options
from skillevaluator.provider_config import resolve_llm_provider
from skillevaluator.tier3.commands import parse_agent_model_overrides, resolve_agents, validate_agents
@@ -210,15 +215,16 @@ def _preflight_options(skill_path: Path, params: dict[str, Any]) -> dict[str, An
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(
- provider=provider,
- agents=agents,
- models={agent: value[0] for agent, value in resolution.items()},
- configured_runtime_env=runtime_env,
- env_mode=params["env_mode"],
- model_sources={agent: value[1] for agent, value in resolution.items()},
- environment_kwargs=resolved_environment_kwargs,
- )
+ if harbor_runtime:
+ _resolve_agent_runtime_plan(
+ provider=provider,
+ agents=agents,
+ models={agent: value[0] for agent, value in resolution.items()},
+ configured_runtime_env=runtime_env,
+ env_mode=params["env_mode"],
+ model_sources={agent: value[1] for agent, value in resolution.items()},
+ environment_kwargs=resolved_environment_kwargs,
+ )
_evaluated_source_from_options(
params["evaluated_source_repository"],
params["evaluated_source_revision"],
@@ -252,6 +258,68 @@ def _preflight_environment(
raise ValueError("; ".join(errors))
+def nemo_gym_preflight_errors(skill_path: Path, params: dict[str, Any]) -> list[str]:
+ """Return every option, config and setting error the NeMo Gym backend would reject, before any dataset work."""
+ from skillevaluator.tier3.commands import parse_agents
+ from skillevaluator.tier3.nemo_gym.backend import (
+ MODEL_URL_ENV,
+ model_url_credential_error,
+ nemo_gym_bin,
+ nemo_gym_capability_errors,
+ nemo_gym_cli_error,
+ nemo_gym_config_errors,
+ nemo_gym_settings_errors,
+ )
+
+ errors = nemo_gym_capability_errors(
+ agents=parse_agents(params["agents"]) if params.get("agents") else [],
+ env_mode=params["env_mode"],
+ grading_mode=params.get("grading_mode"),
+ harbor_keep_jobs=bool(params.get("harbor_keep_jobs")),
+ stop_on_pass=bool(params.get("stop_on_pass")),
+ custom_dockerfile_mode=params.get("custom_dockerfile_mode"),
+ copy_repo=bool(params.get("copy_repo")),
+ environment_kwargs=dict.fromkeys(params.get("environment_kwarg") or (), ""),
+ override_storage_mb=params.get("override_storage_mb"),
+ agent_runtime_preflight=bool(params.get("agent_runtime_preflight")),
+ timeout_multiplier=params.get("timeout_multiplier"),
+ run_options=params,
+ ) + nemo_gym_config_errors(
+ skill_path,
+ stop_on_pass=params.get("stop_on_pass"),
+ timeout_multiplier=params.get("timeout_multiplier"),
+ agent_runtime_preflight=params.get("agent_runtime_preflight"),
+ custom_dockerfile_mode=params.get("custom_dockerfile_mode"),
+ run_options=params,
+ )
+ errors += nemo_gym_settings_errors()
+ for url in (os.environ.get(MODEL_URL_ENV, "").strip(), str(params.get("model") or "")):
+ if url and (url_error := model_url_credential_error(url)) and url_error not in errors:
+ errors.append(url_error)
+ for name in ("override_cpus", "override_memory_mb"):
+ value = params.get(name)
+ if value is not None and value <= 0:
+ errors.append(f"--{name.replace('_', '-')} must be greater than 0")
+ gym = nemo_gym_bin()
+ if gym is None:
+ errors.append("--backend nemo-gym needs the NeMo Gym CLI: set SKILL_EVAL_NEMO_GYM_BIN to its `gym` executable")
+ elif not errors and (cli_error := nemo_gym_cli_error(gym)):
+ errors.append(cli_error)
+ return errors
+
+
+def _preflight_nemo_gym(skill_path: Path, params: dict[str, Any]) -> None:
+ """Reject options and config the NeMo Gym backend cannot honor, before the dataset step."""
+ errors = nemo_gym_preflight_errors(skill_path, params)
+ if errors:
+ raise click.UsageError("; ".join(errors))
+ # The same backend-neutral checks Harbor runs, without Harbor's own agent runtime plan.
+ try:
+ _preflight_options(skill_path, params, harbor_runtime=False)
+ except ValueError as exc:
+ raise click.UsageError(str(exc)) from exc
+
+
def _prepare_dataset(skill_path: Path, *, source_path: Path, progress: str = "auto") -> None:
"""Reuse valid authored sources; create one starter case only when absent."""
from skillevaluator.cli import _ensure_autopilot_dataset
@@ -309,8 +377,12 @@ def build_tier3_workflow(evaluate_command: click.Command) -> click.Command:
_validate_skill_root(params["skill_path"])
params["skill_path"] = params["skill_path"].resolve()
with _source_snapshot(params["skill_path"]) as source_path:
- resolved_environment_kwargs = _preflight_options(source_path, params)
- _preflight_environment(params, environment_kwargs=resolved_environment_kwargs)
+ if params.get("backend") == "nemo-gym":
+ # Gym agents use the NeMo Gym model endpoint, not Harbor's runtime credentials.
+ _preflight_nemo_gym(source_path, params)
+ else:
+ resolved_environment_kwargs = _preflight_options(source_path, params)
+ _preflight_environment(params, environment_kwargs=resolved_environment_kwargs)
_prepare_dataset(params["skill_path"], source_path=source_path, progress=params["progress"])
except ImportError as exc:
raise click.ClickException(
diff --git a/tests/cli/test_nemo_gym_autopilot_preflight.py b/tests/cli/test_nemo_gym_autopilot_preflight.py
new file mode 100644
index 00000000..c1b54bf6
--- /dev/null
+++ b/tests/cli/test_nemo_gym_autopilot_preflight.py
@@ -0,0 +1,107 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Gym dataset preparation must use its own compatibility and runtime checks."""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from skillevaluator.cli import cli
+from skillevaluator.evaluation import EvaluationService
+
+
[email protected]("command", [["evaluate", "--autopilot"], ["tier3"]])
+def test_keyed_gym_generates_with_its_endpoint_and_one_compatibility_probe(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, command: list[str]
+) -> None:
+ """Harbor credential or Docker checks must not block a compatible Gym worker."""
+ from skillevaluator.tier3.harbor import runner
+
+ for name in os.environ:
+ if name.startswith("SKILL_EVAL_") or name in {"OPENAI_API_KEY", "ANTHROPIC_API_KEY", "LLM_JUDGE_MODEL"}:
+ monkeypatch.delenv(name)
+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "openai")
+ monkeypatch.setenv("OPENAI_API_KEY", "test-generation-key")
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_MODEL_URL", "http://127.0.0.1:9/v1")
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_MODEL_API_KEY", "EMPTY")
+ skill = tmp_path / "sample"
+ skill.mkdir()
+ (skill / "SKILL.md").write_text("---\nname: sample\ndescription: Add numbers.\n---\n# Add\n")
+ # A config without a dataset takes the real private source snapshot path.
+ (skill / "evals").mkdir()
+ (skill / "evals" / "config.yml").write_text("schema_version: 1\nharbor:\n n_attempts: 1\n")
+ probe_log = tmp_path / "probe-count"
+ gym = tmp_path / "gym"
+ gym.write_text(
+ f"#!{sys.executable}\n"
+ "import pathlib, sys\n"
+ "assert sys.argv[1:] == ['eval', 'run', '--help']\n"
+ f"with pathlib.Path({str(probe_log)!r}).open('a') as log: log.write('probe\\n')\n"
+ "print('usage: gym eval run TARGET --sandbox --agent --model-type --model --model-url --output --concurrency')\n"
+ "print('\\npositional arguments:')\n"
+ "print(' TARGET Harbor task folder')\n"
+ )
+ gym.chmod(0o755)
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_BIN", str(gym))
+ monkeypatch.setattr(
+ runner, "_check_prerequisites", lambda **_kwargs: pytest.fail("Gym must not check Harbor prerequisites")
+ )
+
+ def generate(_self, path, *, use_llm):
+ assert use_llm is True
+ (path / "evals" / "evals.json").write_text(
+ json.dumps(
+ {
+ "skill_name": "sample",
+ "evals": [{"id": "sum", "prompt": "Add 2 and 3.", "expected_output": "5"}],
+ }
+ )
+ )
+
+ monkeypatch.setattr(EvaluationService, "create_autopilot_dataset", generate)
+ evaluated = []
+ monkeypatch.setattr(
+ EvaluationService,
+ "evaluate",
+ lambda _self, options, **_kwargs: evaluated.append(options) or {"execution_status": "succeeded"},
+ )
+
+ result = CliRunner().invoke(
+ cli, [*command, str(skill), "--backend", "nemo-gym", "--agents", "claude-code", "--progress", "off"]
+ )
+
+ assert result.exit_code == 0, result.output
+ assert (skill / "evals" / "evals.json").is_file()
+ assert len(evaluated) == 1
+ assert evaluated[0].backend == "nemo-gym"
+ assert probe_log.read_text().splitlines() == ["probe"]
+
+
+def test_keyed_incompatible_gym_does_not_generate_a_dataset(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "nv_build")
+ monkeypatch.setenv("NVIDIA_API_KEY", "test-generation-key")
+ skill = tmp_path / "sample"
+ skill.mkdir()
+ (skill / "SKILL.md").write_text("---\nname: sample\ndescription: Add numbers.\n---\n# Add\n")
+ gym = tmp_path / "gym"
+ gym.write_text("#!/bin/sh\necho 'usage: gym eval run --input INPUT'\n")
+ gym.chmod(0o755)
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_BIN", str(gym))
+ monkeypatch.setattr(
+ EvaluationService, "create_autopilot_dataset", lambda *_args, **_kwargs: pytest.fail("must not generate")
+ )
+
+ result = CliRunner().invoke(
+ cli, ["evaluate", str(skill), "--backend", "nemo-gym", "--autopilot", "--progress", "off"]
+ )
+
+ assert result.exit_code == 2, result.output
+ assert "incompatible" in result.output
+ assert not (skill / "evals").exists()
diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.json
index 548e2c2a..8d5ce850 100644
--- a/tests/golden/cli_surface.json
+++ b/tests/golden/cli_surface.json
@@ -825,6 +825,18 @@
"param_type": "option",
"type": "text"
},
+ {
+ "choices": [
+ "harbor",
+ "nemo-gym"
+ ],
+ "default": "harbor",
+ "name": "backend",
+ "opts": [
+ "--backend"
+ ],
+ "param_type": "option"
+ },
{
"default": "False",
"is_flag": true,
@@ -894,6 +906,18 @@
],
"param_type": "option"
},
+ {
+ "choices": [
+ "harbor",
+ "nemo-gym"
+ ],
+ "default": "harbor",
+ "name": "backend",
+ "opts": [
+ "--backend"
+ ],
+ "param_type": "option"
+ },
{
"multiple": true,
"name": "environment_kwarg",
@@ -3055,6 +3079,18 @@
"param_type": "option",
"type": "text"
},
+ {
+ "choices": [
+ "harbor",
+ "nemo-gym"
+ ],
+ "default": "harbor",
+ "name": "backend",
+ "opts": [
+ "--backend"
+ ],
+ "param_type": "option"
+ },
{
"default": "False",
"is_flag": true,
@@ -3124,6 +3160,18 @@
],
"param_type": "option"
},
+ {
+ "choices": [
+ "harbor",
+ "nemo-gym"
+ ],
+ "default": "harbor",
+ "name": "backend",
+ "opts": [
+ "--backend"
+ ],
+ "param_type": "option"
+ },
{
"multiple": true,
"name": "environment_kwarg",
@@ -4239,6 +4287,18 @@
],
"param_type": "option"
},
+ {
+ "choices": [
+ "harbor",
+ "nemo-gym"
+ ],
+ "default": "harbor",
+ "name": "backend",
+ "opts": [
+ "--backend"
+ ],
+ "param_type": "option"
+ },
{
"multiple": true,
"name": "environment_kwarg",
diff --git a/tests/reporting/test_tier3_validate_cases.py b/tests/reporting/test_tier3_validate_cases.py
index 59e8a793..a09db3f2 100644
--- a/tests/reporting/test_tier3_validate_cases.py
+++ b/tests/reporting/test_tier3_validate_cases.py
@@ -245,3 +245,29 @@ def test_setup_fix_names_failed_skillspector_setup():
"or install it yourself: uv tool install skillspector.whl",
"or skip it: --skip security",
]
+
+
+def test_live_case_marks_reads_nemo_gym_rollouts(tmp_path):
+ from skillevaluator.tier3.case_summary import ERROR, FAIL, PASS
+
+ for case in ("case-1", "case-2"):
+ (tmp_path / "_harbor-tasks" / "codex" / "with" / case).mkdir(parents=True)
+ arm = tmp_path / "_nemo-gym" / "codex-with"
+ arm.mkdir(parents=True)
+ task = {"taskset": "with", "task_id": "case-1"}
+ # Scored from the verifier logs, with the same rules as the final Gym result normalizer.
+ logs = []
+ for index, overall in enumerate((0.9, 0.1)):
+ log_dir = tmp_path / "gym-logs" / str(index)
+ log_dir.mkdir(parents=True)
+ (log_dir / "reward.json").write_text(json.dumps({"overall": overall}))
+ logs.append(str(log_dir))
+ rows = [
+ {"_ng_task_id": task, "verifier_return_code": 0, "verifier_logs_dir": logs[0]},
+ {"_ng_task_id": task, "verifier_return_code": 0, "verifier_logs_dir": logs[1]},
+ {"_ng_task_id": task, "failure_reason": "sandbox died", "verifier_return_code": None},
+ ]
+ (arm / "rollouts.jsonl").write_text("\n".join(json.dumps(row) for row in rows) + '\n{"_ng_task_id": {"ta')
+ marks, running = live_case_marks(tmp_path, ["codex"], pass_threshold=0.5)
+ assert marks == {"codex": {"with_skill": {"case-1": [PASS, FAIL, ERROR], "case-2": []}}}
+ assert running == set()
diff --git a/tests/test_checks_routing.py b/tests/test_checks_routing.py
index 73fdc027..bac2c1d4 100644
--- a/tests/test_checks_routing.py
+++ b/tests/test_checks_routing.py
@@ -29,6 +29,8 @@ from skillevaluator.tier3.eval_core.checks import (
"less skills/x/SKILL.md",
"F=skills/x/SKILL.md; cat $F",
"cat ./SKILL.md && echo done",
+ "/bin/bash -lc 'cat /root/.agents/skills/x/SKILL.md'", # NeMo Gym Codex records the shell wrapper
+ "bash -c 'head -5 skills/x/SKILL.md'",
],
)
def test_recognizes_shell_reads_of_skill_md(cmd: str):
@@ -44,6 +46,7 @@ def test_recognizes_shell_reads_of_skill_md(cmd: str):
"cat config.json", # reads a non-SKILL file
"echo SKILL.md > out.txt", # output redirect, not a read
"rg SKILL .",
+ "bash -lc 'grep SKILL config.json'",
],
)
def test_ignores_non_reads_and_searches(cmd: str):
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 53b8a5da..cdf1902b 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -641,6 +641,7 @@ def test_doctor_without_tier_keeps_checking_only_live_evaluation(doctor_calls, c
"verify_models": False,
"agent_model": (),
"environment_kwargs": {},
+ "backend": "harbor",
}
]
diff --git a/tests/test_nemo_gym_backend.py b/tests/test_nemo_gym_backend.py
new file mode 100644
index 00000000..9d3f8cbf
--- /dev/null
+++ b/tests/test_nemo_gym_backend.py
@@ -0,0 +1,2182 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for the selectable Tier 3 execution backend and the NeMo Gym adapter."""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import sys
+from pathlib import Path
+
+import click
+import pytest
+
+from skillevaluator.evaluation.options import EvaluationOptions
+from skillevaluator.tier3.harbor.collector import collect_harbor_results
+from skillevaluator.tier3.nemo_gym.backend import (
+ DEFAULT_EXECUTION_BACKEND,
+ nemo_gym_bin,
+ nemo_gym_capability_errors,
+ normalize_backend,
+)
+from skillevaluator.tier3.nemo_gym.results import rollout_task_name, write_job_from_rollouts
+from skillevaluator.tier3.nemo_gym.runner import MODEL_API_KEY_ENV, gym_eval_command, stage_for_gym
+
+
+def keep_staged_tasks(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Keep the staged task folders, which a Gym run removes at the end, for inspection."""
+ from skillevaluator.tier3.harbor import artifact_retention
+
+ class _Keep(artifact_retention.HarborArtifactLifecycle):
+ def __init__(self, paths: list[Path], *, keep_requested: bool) -> None:
+ del keep_requested
+ super().__init__(paths, keep_requested=True)
+
+ monkeypatch.setattr(artifact_retention, "HarborArtifactLifecycle", _Keep)
+
+
+def test_backend_defaults_to_harbor_and_is_forwarded() -> None:
+ assert DEFAULT_EXECUTION_BACKEND == "harbor"
+ assert normalize_backend(None) == "harbor"
+ assert normalize_backend("NeMo-Gym") == "nemo-gym"
+ assert EvaluationOptions(skill_path=Path("s")).engine_kwargs()["backend"] == "harbor"
+
+
+def test_unknown_backend_is_rejected() -> None:
+ with pytest.raises(ValueError, match="Unknown Tier 3 execution backend"):
+ normalize_backend("modal")
+
+
+def test_capability_errors_reject_unsupported_combinations() -> None:
+ assert nemo_gym_capability_errors(agents=["codex"], env_mode="docker", grading_mode=None) == []
+ errors = nemo_gym_capability_errors(
+ agents=["codex", "gemini-cli"],
+ env_mode="modal",
+ grading_mode=None,
+ harbor_keep_jobs=True,
+ stop_on_pass=True,
+ )
+ joined = " | ".join(errors)
+ for fragment in ("gemini-cli", "--env-mode docker", "--harbor-keep-jobs", "--stop-on-pass"):
+ assert fragment in joined
+
+
+def test_gym_bin_uses_configured_worker(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ gym = tmp_path / "gym"
+ gym.write_text("#!/bin/sh\n")
+ gym.chmod(0o755)
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_BIN", str(gym))
+ assert nemo_gym_bin() == str(gym)
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_BIN", str(tmp_path / "missing"))
+ assert nemo_gym_bin() is None
+
+
+def test_gym_command_keeps_api_key_out_of_argv(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_HOST", "172.17.0.1")
+ command = gym_eval_command(
+ "gym",
+ tmp_path / "tasks",
+ agent="codex",
+ model="m",
+ model_url="http://127.0.0.1:9/v1",
+ rollouts_path=tmp_path / "r.jsonl",
+ n_attempts=2,
+ n_concurrent=3,
+ sandbox="docker",
+ )
+ assert command[:4] == ["gym", "eval", "run", str(tmp_path / "tasks")]
+ assert command[command.index("--agent") + 1] == "codex_agent"
+ assert f"+policy_api_key=${{oc.env:{MODEL_API_KEY_ENV}}}" in command
+ assert "+num_repeats=2" in command
+ assert command[command.index("--concurrency") + 1] == "3"
+ assert "+default_host=172.17.0.1" in command
+
+
+def _rollout(tmp_path: Path, task: str, attempt: int, overall: float | None) -> dict:
+ logs = tmp_path / "gym-logs" / f"{task}-{attempt}"
+ logs.mkdir(parents=True)
+ if overall is not None:
+ (logs / "reward.json").write_text(json.dumps({"overall": overall, "correctness": overall}))
+ (logs / "skill_evaluator_reward.json").write_text(json.dumps({"overall": overall}))
+ (logs / "trajectory.json").write_text(json.dumps({"schema_version": "ATIF-v1.7", "steps": []}))
+ return {
+ "_ng_task_id": {"taskset": "t", "task_id": task},
+ "episode_id": {"rollout_id": f"r{attempt}", "attempt": 0},
+ "reward": 99.0,
+ "verifier_return_code": 0 if overall is not None else None,
+ "verifier_logs_dir": str(logs),
+ }
+
+
+def test_rollouts_normalize_into_collector_trials(tmp_path: Path) -> None:
+ job_dir = tmp_path / "jobs" / "calc-codex-with"
+ rows = [_rollout(tmp_path, "calc-001", 1, 0.8), _rollout(tmp_path, "calc-002", 1, None)]
+ assert rollout_task_name(rows[0]) == "calc-001"
+ errors = write_job_from_rollouts(
+ rows,
+ job_dir,
+ eval_name="codex__m",
+ task_case_ids={"calc-001": "calc-001", "calc-002": "calc-002"},
+ n_attempts=1,
+ )
+ assert len(errors) == 1 and "calc-002" in errors[0]
+ trial = job_dir / "calc-001__gym001"
+ reward = json.loads((trial / "verifier" / "reward.json").read_text())
+ assert reward["entry_id"] == "calc-001" and reward["overall"] == 0.8
+ assert (trial / "agent" / "trajectory.json").is_file()
+ assert (trial / "verifier" / "skill_evaluator_reward.json").is_file()
+ job = json.loads((job_dir / "result.json").read_text())
+ assert job["n_total_trials"] == 2
+ assert job["stats"]["n_errors"] == 1
+ assert job["stats"]["evals"]["codex__m"]["reward_stats"]["reward"] == {"0.8": ["calc-001__gym001"]}
+
+
+def test_normalized_gym_jobs_are_read_by_shared_collector(tmp_path: Path) -> None:
+ jobs = tmp_path / "jobs"
+ for arm, value in (("with", 0.9), ("without", 0.4)):
+ write_job_from_rollouts(
+ [_rollout(tmp_path / arm, "calc-001", 1, value)],
+ jobs / f"calc-codex-{arm}",
+ eval_name="codex__m",
+ task_case_ids={"calc-001": "calc-001"},
+ n_attempts=1,
+ )
+ results = collect_harbor_results(
+ "calc",
+ ["codex"],
+ tmp_path / "out",
+ jobs,
+ expected_cases=1,
+ expected_case_ids=["calc-001"],
+ expected_trials=1,
+ )
+ agent = results["agents"]["codex"]
+ assert agent["overall_with_skill"] == pytest.approx(0.9)
+ assert agent["overall_without_skill"] == pytest.approx(0.4)
+ assert agent["scored_attempts"]
+
+
+def _evaluate(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, **overrides):
+ from skillevaluator.provider_config import ProviderConfig
+ from skillevaluator.tier3 import commands as tier3_commands
+ from skillevaluator.tier3.nemo_gym import runner as gym_runner
+
+ skill = tmp_path / "skill"
+ skill.mkdir(exist_ok=True)
+ provider = ProviderConfig(
+ provider="openai",
+ model="gpt-4.1-mini",
+ api_key="test-key",
+ base_url="https://api.openai.com/v1",
+ litellm_model="openai/gpt-4.1-mini",
+ )
+ calls: dict[str, dict] = {}
+ monkeypatch.setattr(tier3_commands, "resolve_llm_provider", lambda: provider)
+ monkeypatch.setattr(tier3_commands, "resolve_results_root", lambda *_args: tmp_path / "results")
+ monkeypatch.setattr(tier3_commands, "run_harbor_eval", lambda **kw: calls.setdefault("harbor", kw) and {})
+ monkeypatch.setattr(gym_runner, "run_nemo_gym_eval", lambda **kw: calls.setdefault("nemo-gym", kw) and {})
+ kwargs = {
+ "agents": "codex",
+ "env_mode": "docker",
+ "skip_baseline": False,
+ "n_attempts": None,
+ "pass_threshold": None,
+ "n_concurrent": None,
+ "max_agents": None,
+ "model": None,
+ "agent_model": (),
+ "custom_dockerfile_mode": None,
+ "skill_workspace_mode": None,
+ "include_skills": (),
+ "copy_repo": False,
+ "grading_mode": None,
+ "results_dir": None,
+ "harbor_keep_jobs": False,
+ "timeout_multiplier": None,
+ "override_cpus": None,
+ "override_memory_mb": None,
+ "override_storage_mb": None,
+ }
+ kwargs.update(overrides)
+ tier3_commands.evaluate(skill, **kwargs)
+ return calls
+
+
+def test_default_backend_dispatches_to_harbor_only(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ calls = _evaluate(monkeypatch, tmp_path)
+ assert set(calls) == {"harbor"}
+
+
+def test_nemo_gym_backend_dispatches_to_gym_runner(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ calls = _evaluate(monkeypatch, tmp_path, backend="nemo-gym", n_attempts=2)
+ assert set(calls) == {"nemo-gym"}
+ assert calls["nemo-gym"]["agents"] == ["codex"] and calls["nemo-gym"]["n_attempts"] == 2
+
+
+def test_nemo_gym_backend_forwards_copy_repo(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ calls = _evaluate(monkeypatch, tmp_path, backend="nemo-gym", copy_repo=True)
+ assert calls["nemo-gym"]["copy_repo"] is True
+
+
+def test_nemo_gym_rejects_unsupported_env_before_execution(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ with pytest.raises(ValueError, match="docker"):
+ _evaluate(monkeypatch, tmp_path, backend="nemo-gym", env_mode="e2b")
+
+
+def test_stage_for_gym_drops_only_the_skills_dir_hook(tmp_path: Path) -> None:
+ task = tmp_path / "calc-001"
+ task.mkdir()
+ (task / "task.toml").write_text(
+ '[environment]\ncpus = 2\nskills_dir = "/workspace/skills"\n\n[environment.env]\nA = "1"\n'
+ )
+ stage_for_gym(tmp_path)
+ text = (task / "task.toml").read_text()
+ assert "skills_dir" not in text
+ assert "cpus = 2" in text and 'A = "1"' in text
+
+
+def test_verifier_judge_env_stages_templates_not_values(tmp_path: Path, monkeypatch) -> None:
+ from skillevaluator.tier3.nemo_gym.runner import verifier_judge_env
+
+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "openai")
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test-secret")
+ (tmp_path / "SKILL.md").write_text("---\nname: s\ndescription: d\n---\n")
+ templates, process_env = verifier_judge_env(tmp_path, "default", "docker")
+ assert templates["OPENAI_API_KEY"] == "${OPENAI_API_KEY}"
+ assert "sk-test-secret" not in templates.values()
+ assert process_env["OPENAI_API_KEY"] == "sk-test-secret"
+
+
+def test_nemo_gym_forwards_arm_case_and_model_selection(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ calls = _evaluate(
+ monkeypatch,
+ tmp_path,
+ backend="nemo-gym",
+ skip_baseline=False,
+ skip_with_skill=True,
+ max_cases=1,
+ agent_model=("codex=gpt-custom",),
+ )
+ gym_call = calls["nemo-gym"]
+ assert gym_call["skip_with_skill"] is True and gym_call["max_cases"] == 1
+ assert gym_call["agent_models"] == {"codex": "gpt-custom"}
+
+
+def test_nemo_gym_rejects_agent_runtime_preflight(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ with pytest.raises(ValueError, match="agent-runtime-preflight"):
+ _evaluate(monkeypatch, tmp_path, backend="nemo-gym", agent_runtime_preflight=True)
+
+
+_FAKE_GYM = """#!{python}
+import json, os, sys
+from pathlib import Path
+
+args = sys.argv[1:]
+if args == ["eval", "run", "--help"]:
+ print("usage: gym eval run tasks --sandbox docker --agent AGENT --model-type TYPE --model MODEL --model-url URL --output OUTPUT --concurrency N\\n\\npositional arguments:\\n tasks Harbor task directory")
+ sys.exit(0)
+tasks = Path(args[2])
+output = Path(args[args.index("--output") + 1])
+repeats = int(next(a for a in args if a.startswith("+num_repeats=")).split("=", 1)[1])
+Path(os.environ["FAKE_GYM_ENV_LOG"]).open("a").write(json.dumps({{"arm": tasks.name, "repeats": repeats, "env": sorted(os.environ), "argv": args}}) + "\\n")
+with output.open("w") as rows:
+ for task in sorted(p for p in tasks.iterdir() if (p / "task.toml").is_file()):
+ for attempt in range(repeats + int(bool(os.environ.get("FAKE_GYM_EXTRA_ROLLOUT")))):
+ logs = output.parent / "logs" / f"{{task.name}}-{{attempt}}"
+ logs.mkdir(parents=True)
+ if os.environ.get("FAKE_GYM_REWARD_TXT"):
+ (logs / "reward.txt").write_text("1\\n")
+ else:
+ (logs / "reward.json").write_text(json.dumps({{"overall": 0.75}}))
+ (logs / "skill_evaluator_reward.json").write_text(json.dumps({{"overall": 0.75}}))
+ row = {{"_ng_task_id": {{"taskset": tasks.name, "task_id": task.name}}, "verifier_return_code": 0,
+ "verifier_logs_dir": str(logs), "episode_id": {{"rollout_id": f"r{{attempt}}", "attempt": 0}}}}
+ if os.environ.get("FAKE_GYM_FAILURE"):
+ row["failure"] = os.environ["FAKE_GYM_FAILURE"]
+ rows.write(json.dumps(row) + "\\n")
+"""
+
+
+def _fake_gym_skill(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, config: str = "") -> tuple[Path, Path]:
+ import sys
+
+ from skillevaluator import provider_config
+ from skillevaluator.evaluation.insights_judge import InsightsJudge
+ from skillevaluator.provider_config import ProviderConfig
+ from skillevaluator.tier3.eval_core import llm_judge
+
+ # Keep report parsing/rendering real while replacing unrelated remote advice requests.
+ monkeypatch.setattr(llm_judge, "call_public_llm", lambda *_args, **_kwargs: ("[]", None))
+ monkeypatch.setattr(
+ InsightsJudge, "completions", lambda *_args, **_kwargs: '{"conclusions": [], "recommendations": []}'
+ )
+
+ skill = tmp_path / "calc"
+ (skill / "evals").mkdir(parents=True)
+ (skill / "SKILL.md").write_text("---\nname: calc\ndescription: Adds numbers.\n---\n# Calc\n")
+ cases = [
+ {"id": f"calc-00{i}", "prompt": f"Add {i}+{i}", "expected_output": str(2 * i), "assertions": ["adds"]}
+ for i in (1, 2)
+ ]
+ (skill / "evals" / "evals.json").write_text(json.dumps({"skill_name": "calc", "evals": cases}))
+ if config:
+ (skill / "evals" / "config.yml").write_text(config)
+ gym = tmp_path / "gym-venv" / "gym"
+ gym.parent.mkdir()
+ gym.write_text(_FAKE_GYM.format(python=sys.executable))
+ gym.chmod(0o755)
+ env_log = tmp_path / "gym-env.jsonl"
+ provider = ProviderConfig(
+ provider="openai",
+ model="gpt-4.1-mini",
+ api_key="judge-key",
+ base_url="https://api.openai.com/v1",
+ litellm_model="openai/gpt-4.1-mini",
+ )
+ monkeypatch.setattr(provider_config, "resolve_llm_provider", lambda: provider)
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_BIN", str(gym))
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_MODEL_URL", "http://127.0.0.1:9/v1")
+ monkeypatch.setenv(MODEL_API_KEY_ENV, "policy-key")
+ monkeypatch.setenv("FAKE_GYM_ENV_LOG", str(env_log))
+ from skillevaluator.tier3.nemo_gym import runner as gym_runner
+
+ monkeypatch.setattr(
+ gym_runner,
+ "_GYM_HOST_ENV_VARS",
+ gym_runner._GYM_HOST_ENV_VARS
+ | {"FAKE_GYM_ENV_LOG", "FAKE_GYM_REWARD_TXT", "FAKE_GYM_FAILURE", "FAKE_GYM_EXTRA_ROLLOUT"},
+ )
+ monkeypatch.setenv("GITHUB_TOKEN", "host-only-token")
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "host-only-key")
+ return skill, env_log
+
+
+def _run_fake_gym(skill: Path, tmp_path: Path, **overrides) -> dict:
+ from skillevaluator.tier3.nemo_gym.runner import run_nemo_gym_eval
+
+ kwargs = {
+ "skill_path": skill,
+ "agents": ["codex"],
+ "skip_baseline": False,
+ "n_attempts": None,
+ "pass_threshold": None,
+ "n_concurrent": 1,
+ "model": "policy-model",
+ "agent_models": None,
+ "skill_workspace_mode": None,
+ "include_skills": None,
+ "grading_mode": None,
+ "output_dir": tmp_path / "results",
+ "env_mode": "docker",
+ "timeout_multiplier": None,
+ "evaluated_source": None,
+ "override_cpus": None,
+ "override_memory_mb": None,
+ }
+ kwargs.update(overrides)
+ return run_nemo_gym_eval(**kwargs)
+
+
+def incompatible_gym(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ gym = tmp_path / "released-gym"
+ gym.write_text("#!/bin/sh\necho 'usage: gym eval run [--input INPUT] [--agent AGENT] [--output OUTPUT]'\n")
+ gym.chmod(0o755)
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_BIN", str(gym))
+ return gym
+
+
+def test_incompatible_gym_is_rejected_before_dataset_generation(incompatible_gym: Path, tmp_path: Path) -> None:
+ from skillevaluator.tier3.workflow import nemo_gym_preflight_errors
+
+ errors = nemo_gym_preflight_errors(tmp_path, {"agents": "codex", "env_mode": "docker"})
+ assert any("incompatible" in error and "--sandbox" in error for error in errors)
+ assert not (tmp_path / "evals").exists()
+
+
[email protected]("command", [["evaluate", "--autopilot"], ["tier3"]])
+def test_cli_rejects_incompatible_gym_before_generating_a_dataset(
+ incompatible_gym: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, command: list[str]
+) -> None:
+ from click.testing import CliRunner
+
+ from skillevaluator.cli import cli
+ from skillevaluator.evaluation import EvaluationService
+ from skillevaluator.tier3 import workflow
+
+ skill = tmp_path / "skill"
+ skill.mkdir()
+ (skill / "SKILL.md").write_text("---\nname: calc\ndescription: Adds numbers.\n---\n# Calc\n")
+ monkeypatch.setattr(
+ EvaluationService, "create_autopilot_dataset", lambda *_args, **_kwargs: pytest.fail("must not generate")
+ )
+ monkeypatch.setattr(workflow, "_prepare_dataset", lambda *_args, **_kwargs: pytest.fail("must not generate"))
+ result = CliRunner().invoke(cli, [*command, str(skill), "--backend", "nemo-gym", "--agents", "codex"])
+ assert result.exit_code == 2, result.output
+ assert "incompatible" in result.output
+ assert not (skill / "evals").exists()
+
+
+def test_direct_run_rejects_incompatible_gym_before_staging(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch)
+ gym = Path(os.environ["SKILL_EVAL_NEMO_GYM_BIN"])
+ gym.write_text("#!/bin/sh\necho 'usage: gym eval run [--input INPUT]'\n")
+ result = _run_fake_gym(skill, tmp_path)
+ assert any("incompatible" in error for error in result.get("error", []))
+ assert not (tmp_path / "results").exists()
+
+
+def test_doctor_rejects_incompatible_gym_despite_readable_version(
+ incompatible_gym: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from skillevaluator.tier3 import commands
+ from skillevaluator.tier3.nemo_gym import backend
+
+ monkeypatch.setattr(backend, "nemo_gym_version", lambda _gym: "0.7.0")
+ monkeypatch.setattr(commands, "_docker_daemon_error", lambda _env: None)
+ rows = commands._nemo_gym_doctor_rows(["codex"], "docker", {})
+ assert rows[0][0:2] == ("NeMo Gym CLI", "fail")
+ assert "incompatible" in rows[0][2]
+ assert not any(status == "pass" for _name, status, _detail in rows)
+
+
+ ("positional", "omitted_flag", "missing"),
+ [
+ ("TARGET", None, None),
+ ("tasks", None, None),
+ ("task_dir", None, None),
+ ("tasks_dir", None, None),
+ ("task_folder", None, None),
+ ("TARGETED", None, "positional tasks directory"),
+ ("TARGET", "--sandbox", "--sandbox"),
+ ("TARGET", "--agent", "--agent"),
+ ("TARGET", "--model-type", "--model-type"),
+ ("TARGET", "--model", "--model"),
+ ("TARGET", "--model-url", "--model-url"),
+ ("TARGET", "--output", "--output"),
+ ("TARGET", "--concurrency", "--concurrency"),
+ ],
+)
+def test_gym_cli_probe_accepts_source_shaped_argparse_help_and_requires_all_flags(
+ tmp_path: Path, positional: str, omitted_flag: str | None, missing: str | None
+) -> None:
+ import sys
+
+ from skillevaluator.tier3.nemo_gym.backend import nemo_gym_cli_error
+
+ # NVIDIA-NeMo/Gym@792fa142f58277aecff05d402061d647e9a92acf,
+ # nemo_gym/cli/main.py:846-857 declares target with nargs="?", metavar="TARGET".
+ # Exercise argparse's actual help layout through the executable boundary.
+ gym = tmp_path / "gym"
+ gym.write_text(
+ f"#!{sys.executable}\n"
+ "import argparse, sys\n"
+ "assert sys.argv[1:] == ['eval', 'run', '--help']\n"
+ "parser = argparse.ArgumentParser(prog='gym eval run')\n"
+ f"parser.add_argument('target', nargs='?', metavar={positional!r}, "
+ "help='Harbor task folder, folder of task folders')\n"
+ "for flag in ['--sandbox', '--agent', '--model-type', '--model', '--model-url', '--output', '--concurrency']:\n"
+ f" if flag != {omitted_flag!r}: parser.add_argument(flag)\n"
+ "parser.print_help()\n"
+ )
+ gym.chmod(0o755)
+ error = nemo_gym_cli_error(str(gym))
+ if missing is None:
+ assert error is None
+ else:
+ assert error is not None
+ assert f"missing: {missing}." in error
+
+
+def test_gym_cli_probe_handles_unreadable_help(tmp_path: Path) -> None:
+ from skillevaluator.tier3.nemo_gym.backend import nemo_gym_cli_error
+
+ gym = tmp_path / "gym"
+ gym.write_bytes(b"#!/bin/sh\nprintf '\\377'\n")
+ gym.chmod(0o755)
+ assert "incompatible" in (nemo_gym_cli_error(str(gym)) or "")
+
+
[email protected]("descriptor", [1, 2])
+def test_gym_cli_probe_bounds_stdout_and_stderr(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, descriptor: int
+) -> None:
+ import sys
+
+ from skillevaluator.tier3.nemo_gym import backend
+
+ gym = tmp_path / "gym"
+ gym.write_text(f"#!{sys.executable}\nimport os\nos.write({descriptor}, b'policy-secret' * 100000)\n")
+ gym.chmod(0o755)
+ monkeypatch.setattr(backend, "_GYM_HELP_MAX_OUTPUT_BYTES", 4096)
+ error = backend.nemo_gym_cli_error(str(gym))
+ assert error is not None and "output limit" in error
+ assert "policy-secret" not in error
+
+
[email protected](os.name != "posix", reason="requires POSIX process groups and signals")
[email protected]("failure_mode", ["timeout", "overflow", "interrupt"])
+def test_gym_cli_probe_failure_contains_descendants(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failure_mode: str
+) -> None:
+ import contextlib
+ import signal
+ import sys
+ import threading
+ import time
+
+ from skillevaluator.tier3.nemo_gym import backend
+
+ child_ready = tmp_path / "child-ready"
+ pid_file = tmp_path / "pids.json"
+ child_code = (
+ "import pathlib, signal, time\n"
+ "signal.signal(signal.SIGTERM, signal.SIG_IGN)\n"
+ f"pathlib.Path({str(child_ready)!r}).touch()\n"
+ "time.sleep(30)\n"
+ )
+ gym = tmp_path / "gym"
+ gym.write_text(
+ f"#!{sys.executable}\nimport json, os, pathlib, subprocess, sys, time\n"
+ f"child = subprocess.Popen([sys.executable, '-c', {child_code!r}])\n"
+ f"while not pathlib.Path({str(child_ready)!r}).exists(): time.sleep(0.005)\n"
+ f"pathlib.Path({str(pid_file)!r}).write_text(json.dumps([os.getpid(), child.pid]))\n"
+ "print('policy-secret', flush=True)\n"
+ + ("os.write(1, b'a' * 3000); os.write(2, b'b' * 3000)\n" if failure_mode == "overflow" else "")
+ + "time.sleep(30)\n"
+ )
+ gym.chmod(0o755)
+ monkeypatch.setattr(backend, "_GYM_HELP_TIMEOUT_S", 2.0)
+ monkeypatch.setattr(backend, "_GYM_HELP_MAX_OUTPUT_BYTES", 4096)
+ stop_interrupter = threading.Event()
+
+ def interrupt_once_ready() -> None:
+ deadline = time.monotonic() + 4
+ while not pid_file.exists() and time.monotonic() < deadline:
+ if stop_interrupter.wait(0.005):
+ return
+ if pid_file.exists() and not stop_interrupter.is_set():
+ os.kill(os.getpid(), signal.SIGINT)
+
+ interrupter = None
+ if failure_mode == "interrupt":
+ interrupter = threading.Thread(target=interrupt_once_ready, daemon=True)
+ interrupter.start()
+ started = time.monotonic()
+ try:
+ if failure_mode == "interrupt":
+ with pytest.raises(KeyboardInterrupt):
+ backend.nemo_gym_cli_error(str(gym))
+ else:
+ error = backend.nemo_gym_cli_error(str(gym))
+ assert error is not None and ("timed out" if failure_mode == "timeout" else "output limit") in error
+ assert "policy-secret" not in error
+ assert time.monotonic() - started < 4
+ pids = json.loads(pid_file.read_text())
+ for pid in pids:
+ deadline = time.monotonic() + 2
+ while time.monotonic() < deadline:
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ break
+ time.sleep(0.01)
+ else:
+ pytest.fail(f"Gym help {failure_mode} left process {pid} alive")
+ finally:
+ stop_interrupter.set()
+ if interrupter is not None:
+ interrupter.join(timeout=3)
+ if pid_file.exists():
+ for pid in json.loads(pid_file.read_text()):
+ with contextlib.suppress(ProcessLookupError):
+ os.kill(pid, signal.SIGKILL)
+
+
+def test_gym_cli_probe_omits_policy_credentials_and_ignores_raw_error_output(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import sys
+
+ from skillevaluator.tier3.nemo_gym.backend import nemo_gym_cli_error
+
+ gym = tmp_path / "gym"
+ gym.write_text(
+ f"#!{sys.executable}\nimport os, sys\n"
+ "assert 'SKILL_EVAL_NEMO_GYM_MODEL_API_KEY' not in os.environ\n"
+ "assert 'OPENAI_API_KEY' not in os.environ\n"
+ "assert sys.argv[1:] == ['eval', 'run', '--help']\n"
+ "print('policy-secret', file=sys.stderr)\nsys.exit(7)\n"
+ )
+ gym.chmod(0o755)
+ monkeypatch.setenv(MODEL_API_KEY_ENV, "policy-secret")
+ monkeypatch.setenv("OPENAI_API_KEY", "judge-secret")
+ error = nemo_gym_cli_error(str(gym))
+ assert error is not None and "exited 7" in error
+ assert "policy-secret" not in error
+
+
+def test_fake_gym_run_honors_arm_case_limit_config_and_is_discoverable(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, keep_staged_tasks: None
+) -> None:
+ from skillevaluator.tier3.results_location import ordered_run_directories
+
+ skill, env_log = _fake_gym_skill(tmp_path, monkeypatch, config="schema_version: 1\nharbor:\n n_attempts: 2\n")
+ result = _run_fake_gym(skill, tmp_path, skip_with_skill=True, max_cases=1)
+
+ run_dir = Path(result["run_dir"])
+ assert sorted(p.name for p in (run_dir / "_harbor-tasks" / "codex").iterdir()) == ["without"]
+ assert len(list((run_dir / "_harbor-tasks" / "codex" / "without").glob("*/task.toml"))) == 1
+ launches = [json.loads(line) for line in env_log.read_text().splitlines()]
+ assert [(launch["arm"], launch["repeats"]) for launch in launches] == [("without", 2)]
+ assert MODEL_API_KEY_ENV in launches[0]["env"]
+ assert "GITHUB_TOKEN" not in launches[0]["env"] and "ANTHROPIC_API_KEY" not in launches[0]["env"]
+ assert result["run_config"]["case_selection"]["selected_ids"] == ["calc-001"]
+ assert result["attempt_policy"]["max_attempts"] == 2
+ assert result["agents"]["codex"]["num_trials_with"] == 0
+ assert ordered_run_directories(tmp_path / "results", completed_only=True) == [run_dir]
+ assert json.loads((run_dir / "run_config.json").read_text()) == result["run_config"]
+
+
+def test_excess_rollouts_fail_the_run_and_rerendered_report(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skillevaluator.evaluation.tier3_report import agent_eval_result_from_directory
+
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch)
+ monkeypatch.setenv("FAKE_GYM_EXTRA_ROLLOUT", "1")
+ result = _run_fake_gym(skill, tmp_path, n_attempts=1, max_cases=1)
+ assert result["execution_status"] == "failed"
+ assert result["agents"]["codex"]["num_trials_with"] == 1
+ assert result["agents"]["codex"]["num_trials_without"] == 1
+ assert any("2/1 rollouts" in error for error in result["execution_errors"])
+ validation = agent_eval_result_from_directory(skill, Path(result["run_dir"]))
+ assert validation is not None and not validation.passed
+ assert validation.metadata["agent_eval"]["summary"]["execution_status"] == "failed"
+
+
+def test_fake_gym_run_rejects_config_options_gym_cannot_honor(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ skill, env_log = _fake_gym_skill(
+ tmp_path, monkeypatch, config="schema_version: 1\nharbor:\n n_attempts: 2\n stop_on_pass: true\n"
+ )
+ result = _run_fake_gym(skill, tmp_path)
+ assert "stop-on-pass" in result["error"][0]
+ assert not env_log.exists()
+
+
+def test_cli_rejects_unsupported_gym_flags_before_autopilot_writes_a_dataset(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ from click.testing import CliRunner
+
+ from skillevaluator.cli import cli
+ from skillevaluator.evaluation import EvaluationService
+
+ skill = tmp_path / "calc"
+ skill.mkdir()
+ (skill / "SKILL.md").write_text("---\nname: calc\ndescription: Adds numbers.\n---\n# Calc\n")
+ monkeypatch.setattr(
+ EvaluationService, "create_autopilot_dataset", lambda *_args, **_kwargs: pytest.fail("must not generate")
+ )
+ result = CliRunner().invoke(
+ cli,
+ ["evaluate", str(skill), "--backend", "nemo-gym", "--autopilot", "--harbor-keep-jobs", "--progress", "off"],
+ )
+ assert result.exit_code == 2, result.output
+ assert "--harbor-keep-jobs" in result.output
+ assert not (skill / "evals" / "evals.json").exists()
+
+
+def test_fake_gym_run_uses_config_agent_model_and_resources(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, keep_staged_tasks: None
+) -> None:
+ config = "schema_version: 1\nharbor:\n agents:\n codex:\n model: cfg-model\n resources:\n cpus: 3\n"
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch, config=config)
+ result = _run_fake_gym(skill, tmp_path, model=None, skip_baseline=True)
+
+ assert result["run_config"]["agents"]["codex"] == {
+ "agent": "codex",
+ "model": "cfg-model",
+ "source": "evals/config.yml",
+ }
+ task_tomls = list((Path(result["run_dir"]) / "_harbor-tasks" / "codex" / "with").glob("*/task.toml"))
+ assert task_tomls and all("cpus = 3" in path.read_text() for path in task_tomls)
+
+
+ "harbor_config",
+ [" resources:\n storage_mb: 4096\n"],
+)
+def test_fake_gym_run_rejects_harbor_only_config_keys(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, harbor_config: str
+) -> None:
+ skill, env_log = _fake_gym_skill(tmp_path, monkeypatch, config=f"schema_version: 1\nharbor:\n{harbor_config}")
+ result = _run_fake_gym(skill, tmp_path)
+ assert "not supported with --backend nemo-gym" in result["error"][0]
+ assert not env_log.exists()
+
+
+def test_fake_gym_run_rejects_pre_agent_setup_with_a_baseline_arm(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ skill, env_log = _fake_gym_skill(
+ tmp_path, monkeypatch, config="schema_version: 1\nharbor:\n pre_agent_setup:\n - echo hi\n"
+ )
+ result = _run_fake_gym(skill, tmp_path)
+ assert "cannot run in a paired evaluation" in result["error"][0]
+ assert not env_log.exists()
+
+
+def test_fake_gym_run_stages_agent_workdir_and_pre_agent_setup(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ config = "schema_version: 1\nharbor:\n agent_workdir: /work\n setup_commands:\n - touch /tmp/ready\n"
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch, config=config)
+ from skillevaluator.tier3.nemo_gym import runner as gym_runner
+
+ staged: list[str] = []
+ original_stage = gym_runner.stage_for_gym
+
+ def recording_stage(arm_dir: Path, *args, **kwargs) -> None:
+ original_stage(arm_dir, *args, **kwargs)
+ staged.extend(path.read_text() for path in sorted(arm_dir.glob("*/task.toml")))
+
+ monkeypatch.setattr(gym_runner, "stage_for_gym", recording_stage)
+ result = _run_fake_gym(skill, tmp_path, skip_baseline=True)
+ assert result.get("execution_status") == "succeeded", result
+ assert staged
+ for text in staged:
+ assert 'workdir = "/work"' in text
+ assert "[environment.healthcheck]" in text
+ assert "touch /tmp/ready" in text
+
+
+def test_fake_gym_run_rejects_an_invalid_agent_workdir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ skill, env_log = _fake_gym_skill(
+ tmp_path, monkeypatch, config="schema_version: 1\nharbor:\n agent_workdir: relative/dir\n"
+ )
+ result = _run_fake_gym(skill, tmp_path)
+ assert any("agent_workdir" in error for error in result["error"])
+ assert not env_log.exists()
+
+
+def test_truncated_rollout_line_is_skipped_and_reported(tmp_path: Path) -> None:
+ from skillevaluator.tier3.nemo_gym.results import read_rollouts
+
+ rollouts = tmp_path / "rollouts.jsonl"
+ rollouts.write_bytes(b'{"task_id": "a"}\n{"task_id": "b", "reward\xff')
+ errors: list[str] = []
+ assert read_rollouts(rollouts, errors) == [{"task_id": "a"}]
+ assert "1 unreadable line" in errors[0]
+
+
+def test_custom_model_url_requires_its_own_key(monkeypatch: pytest.MonkeyPatch) -> None:
+ from skillevaluator.tier3.nemo_gym.runner import _model_endpoint
+
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_MODEL_URL", "http://policy.example/v1")
+ monkeypatch.delenv(MODEL_API_KEY_ENV, raising=False)
+ with pytest.raises(ValueError, match=MODEL_API_KEY_ENV):
+ _model_endpoint("policy-model")
+ monkeypatch.setenv(MODEL_API_KEY_ENV, "EMPTY")
+ assert _model_endpoint("policy-model") == ("policy-model", "http://policy.example/v1", "EMPTY")
+
+
[email protected]("value", ["abc", "0", "-5", "nan", "inf"])
+def test_invalid_gym_timeout_is_rejected_before_launch(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, value: str
+) -> None:
+ skill, env_log = _fake_gym_skill(tmp_path, monkeypatch)
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_TIMEOUT_S", value)
+ result = _run_fake_gym(skill, tmp_path)
+ assert "SKILL_EVAL_NEMO_GYM_TIMEOUT_S" in result["error"][0]
+ assert not env_log.exists()
+
+
+def test_gym_bin_is_absolute_and_version_follows_symlinks(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ import sys
+
+ from skillevaluator.tier3.nemo_gym.backend import _gym_interpreters, nemo_gym_bin
+
+ real = tmp_path / "tools" / "gym"
+ real.parent.mkdir()
+ real.write_text(f"#!{sys.executable}\nprint('gym')\n")
+ real.chmod(0o755)
+ (tmp_path / "bin").mkdir()
+ (tmp_path / "bin" / "gym").symlink_to(real)
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_BIN", "bin/gym")
+ found = nemo_gym_bin()
+ assert found is not None and Path(found).is_absolute()
+ assert _gym_interpreters(found)[0] == Path(sys.executable)
+
+
+def test_failed_gym_launch_is_reported_not_succeeded(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch)
+ gym = Path(os.environ["SKILL_EVAL_NEMO_GYM_BIN"])
+ failing = tmp_path / "failing-gym"
+ failing.write_text(f'#!/bin/sh\ncase "$*" in *--help*) exec "{gym}" "$@";; esac\nexit 3\n')
+ failing.chmod(0o755)
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_BIN", str(failing))
+ result = _run_fake_gym(skill, tmp_path)
+ assert result["execution_status"] == "failed"
+ assert Path(result["run_dir"]).is_dir()
+ assert "exited 3" in json.dumps(result)
+
+
+def test_rerendered_report_keeps_a_failed_gym_launch(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skillevaluator.evaluation.tier3_report import agent_eval_result_from_directory, render_agent_eval_html_report
+
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch)
+ gym = Path(os.environ["SKILL_EVAL_NEMO_GYM_BIN"])
+ wrapper = tmp_path / "gym-then-exit-3"
+ wrapper.write_text(f'#!/bin/sh\n"{gym}" "$@"\ncase "$*" in *--help*) exit 0;; esac\nexit 3\n')
+ wrapper.chmod(0o755)
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_BIN", str(wrapper))
+ result = _run_fake_gym(skill, tmp_path)
+ run_dir = Path(result["run_dir"])
+ assert result["execution_status"] == "failed"
+ (run_dir / "report.html").unlink(missing_ok=True)
+
+ report = render_agent_eval_html_report(skill, run_dir)
+ assert "exited 3" in report.read_text(encoding="utf-8")
+ validation = agent_eval_result_from_directory(skill, run_dir)
+ assert validation is not None and not validation.passed
+ payload = validation.metadata["agent_eval"]
+ assert payload["summary"]["execution_status"] == "failed"
+ assert any("exited 3" in error for error in payload["summary"]["execution_errors"])
+ assert payload["agents"]["codex"]["execution_status"] == "failed"
+
+
+def test_gym_run_publishes_latest_stages_runtime_env_and_records_dataset(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, keep_staged_tasks: None
+) -> None:
+ from skillevaluator.tier3.results_location import publish_latest_results
+
+ skill, _env_log = _fake_gym_skill(
+ tmp_path, monkeypatch, config='schema_version: 1\nharbor:\n runtime_env:\n GYM_TEST_FLAG: "on"\n'
+ )
+ earlier = tmp_path / "results" / "20200101_000000_1_harbor"
+ earlier.mkdir(parents=True)
+ publish_latest_results(tmp_path / "results", earlier.name)
+ result = _run_fake_gym(skill, tmp_path, skip_with_skill=True, max_cases=1)
+ run_dir = Path(result["run_dir"])
+ assert (tmp_path / "results" / "latest").resolve() == run_dir.resolve()
+ task_toml = next((run_dir / "_harbor-tasks" / "codex" / "without").glob("*/task.toml")).read_text()
+ assert '"GYM_TEST_FLAG" = "${GYM_TEST_FLAG}"' in task_toml
+ assert "on" not in task_toml.split("GYM_TEST_FLAG", 1)[1].splitlines()[0]
+ assert result["dataset_digest"] and (run_dir / "dataset_snapshot.json").is_file()
+ assert "publication_target" in result
+
+
+def test_config_errors_accept_decoys_and_timeout_multiplier(tmp_path: Path) -> None:
+ from skillevaluator.tier3.nemo_gym.backend import nemo_gym_config_errors
+
+ (tmp_path / "evals").mkdir()
+ (tmp_path / "evals" / "config.yml").write_text(
+ "schema_version: 1\nharbor:\n timeout_multiplier: 2\n"
+ "skill_workspace:\n mode: group\n decoy_manifest: decoys.json\n"
+ )
+ assert nemo_gym_config_errors(tmp_path) == []
+
+
+def test_fake_gym_run_stages_frozen_decoys_in_every_arm(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skillevaluator.tier3 import decoys
+ from skillevaluator.tier3.decoy_identity import decoy_source_digest
+ from skillevaluator.tier3.nemo_gym import runner as gym_runner
+
+ config = "schema_version: 1\nskill_workspace:\n mode: group\n decoy_manifest: frozen.json\n"
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch, config=config)
+ decoy = tmp_path / "catalog" / "decoy"
+ decoy.mkdir(parents=True)
+ (decoy / "SKILL.md").write_text("---\nname: decoy\ndescription: Use this decoy workflow.\n---\n# decoy\n")
+ manifest = {"selected": [{"path": "decoy", "skill_name": "decoy", "source_digest": decoy_source_digest(decoy)}]}
+ monkeypatch.setattr(decoys, "load_decoy_manifest", lambda *_: ([decoy], manifest))
+ staged_arms: list[str] = []
+ original_stage = gym_runner.stage_for_gym
+
+ def recording_stage(arm_dir: Path, *args, **kwargs) -> None:
+ original_stage(arm_dir, *args, **kwargs)
+ if any(path.parent.name == "decoy" for path in arm_dir.rglob("SKILL.md")):
+ staged_arms.append(arm_dir.name)
+
+ monkeypatch.setattr(gym_runner, "stage_for_gym", recording_stage)
+ result = _run_fake_gym(skill, tmp_path)
+ assert result.get("execution_status") == "succeeded", result
+ assert "with" in staged_arms
+ run_config = json.loads((Path(result["run_dir"]) / "run_config.json").read_text())
+ assert run_config["skill_workspace"] == {"mode": "group", "decoy_manifest": manifest}
+
+
+def test_timeout_multiplier_scales_staged_task_timeouts(tmp_path: Path) -> None:
+ import tomllib
+
+ from skillevaluator.tier3.nemo_gym.runner import stage_for_gym
+
+ task = tmp_path / "case-1"
+ task.mkdir()
+ (task / "task.toml").write_text(
+ 'instruction = """\n[agent]\ntimeout_sec = 1\n"""\n\n[agent]\ntimeout_sec = 300.0\n\n'
+ '[verifier]\ntimeout_sec = 600 # judges\n\n[verifier.env]\nA = "1"\n\n[environment]\ncpus = 1\n'
+ )
+ stage_for_gym(tmp_path, timeout_multiplier=2.5)
+ data = tomllib.loads((task / "task.toml").read_text())
+ assert data["agent"]["timeout_sec"] == 750.0
+ assert data["verifier"]["timeout_sec"] == 1500.0
+ assert data["environment"]["build_timeout_sec"] == 1500.0
+ assert data["environment"]["cpus"] == 1
+ assert "timeout_sec = 1\n" in data["instruction"]
+
+
+def test_timeout_multiplier_is_validated_and_recorded(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, keep_staged_tasks: None
+) -> None:
+ import tomllib
+
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch)
+ bad = _run_fake_gym(skill, tmp_path, timeout_multiplier=0.0)
+ assert any("timeout_multiplier" in error for error in bad["error"])
+
+ result = _run_fake_gym(skill, tmp_path, timeout_multiplier=2.0, skip_baseline=True, max_cases=1)
+ run_dir = Path(result["run_dir"])
+ task_toml = next((run_dir / "_harbor-tasks" / "codex" / "with").glob("*/task.toml")).read_text()
+ assert tomllib.loads(task_toml)["agent"]["timeout_sec"] == 600.0
+ run_config = json.loads((run_dir / "run_config.json").read_text())
+ assert run_config["harbor"]["timeout_multiplier"] == 2.0
+
+
+def test_passthrough_env_alias_reaches_the_gym_agent(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, keep_staged_tasks: None
+) -> None:
+ skill, _env_log = _fake_gym_skill(
+ tmp_path, monkeypatch, config="schema_version: 1\nharbor:\n passthrough_env:\n - GYM_ALIAS_FLAG\n"
+ )
+ monkeypatch.setenv("GYM_ALIAS_FLAG", "on")
+ result = _run_fake_gym(skill, tmp_path, skip_with_skill=True, max_cases=1)
+ task_toml = next((Path(result["run_dir"]) / "_harbor-tasks" / "codex" / "without").glob("*/task.toml")).read_text()
+ assert '"GYM_ALIAS_FLAG" = "${GYM_ALIAS_FLAG}"' in task_toml
+
+
+def test_config_errors_let_cli_overrides_win(tmp_path: Path) -> None:
+ from skillevaluator.tier3.nemo_gym.backend import nemo_gym_config_errors
+
+ (tmp_path / "evals").mkdir()
+ (tmp_path / "evals" / "config.yml").write_text(
+ "schema_version: 1\nharbor:\n stop_on_pass: true\n timeout_multiplier: 2\n"
+ " agent_runtime_preflight: true\n custom_dockerfile_mode: preserve\n"
+ )
+ assert len(nemo_gym_config_errors(tmp_path)) == 2
+ assert (
+ nemo_gym_config_errors(
+ tmp_path,
+ stop_on_pass=False,
+ timeout_multiplier=1.0,
+ agent_runtime_preflight=False,
+ custom_dockerfile_mode="rebase",
+ )
+ == []
+ )
+
+
+def test_workflow_preflight_rejects_environment_kwarg(tmp_path: Path) -> None:
+ import click
+
+ from skillevaluator.tier3.workflow import _preflight_nemo_gym
+
+ with pytest.raises(click.UsageError, match="--environment-kwarg"):
+ _preflight_nemo_gym(tmp_path, {"agents": "codex", "env_mode": "docker", "environment_kwarg": ("cpus=2",)})
+
+
+def test_version_probe_ignores_the_callers_directory_and_environment(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import subprocess
+
+ from skillevaluator.tier3.nemo_gym import backend
+
+ python = tmp_path / "venv" / "python"
+ python.parent.mkdir()
+ python.write_text("")
+ calls: list[dict] = []
+
+ def _run(args, **kwargs):
+ calls.append({"args": args, **kwargs})
+ return subprocess.CompletedProcess(args, 0, stdout="0.7.0\n", stderr="")
+
+ monkeypatch.setattr(backend, "_gym_interpreters", lambda _gym: [python])
+ monkeypatch.setattr(backend.subprocess, "run", _run)
+ monkeypatch.setenv("GITHUB_TOKEN", "host-only-token")
+ assert backend.nemo_gym_version("gym") == "0.7.0"
+ assert calls[0]["args"][1] == "-P"
+ assert calls[0]["cwd"] == python.parent
+ assert "GITHUB_TOKEN" not in calls[0]["env"]
+
+
+def test_stage_for_gym_adds_job_level_judge_env(tmp_path: Path) -> None:
+ import tomllib
+
+ task = tmp_path / "arm" / "calc-001"
+ task.mkdir(parents=True)
+ (task / "task.toml").write_text(
+ 'skills_dir = "/skills"\n[verifier]\ntimeout_sec = 1.0\n\n[verifier.env]\nOPENAI_API_KEY = "${OPENAI_API_KEY}"\n'
+ )
+ stage_for_gym(
+ tmp_path / "arm",
+ {"LLM_JUDGE_MODEL": "${LLM_JUDGE_MODEL}", "OPENAI_API_KEY": "${OTHER}"},
+ )
+ staged = tomllib.loads((task / "task.toml").read_text())
+ assert "skills_dir" not in staged
+ assert staged["verifier"]["env"] == {"OPENAI_API_KEY": "${OPENAI_API_KEY}", "LLM_JUDGE_MODEL": "${LLM_JUDGE_MODEL}"}
+
+
+def test_missing_attempts_become_failed_trials_and_keep_scored_ones(tmp_path: Path) -> None:
+ job_dir = tmp_path / "job"
+ errors = write_job_from_rollouts(
+ [_rollout(tmp_path / "with", "calc-001", 1, 0.9)],
+ job_dir,
+ eval_name="codex__m",
+ task_case_ids={"calc-001": "calc-001"},
+ n_attempts=2,
+ )
+ assert len(errors) == 1 and "1/2" in errors[0]
+ assert len([path for path in job_dir.iterdir() if path.is_dir()]) == 2
+ stats = json.loads((job_dir / "result.json").read_text())["stats"]
+ assert stats["n_trials"] == 2 and stats["n_errors"] == 1
+ assert stats["evals"]["codex__m"]["n_trials"] == 1
+
+
+def test_rollout_reader_splits_only_on_newlines(tmp_path: Path) -> None:
+ from skillevaluator.tier3.nemo_gym.results import read_rollouts
+
+ path = tmp_path / "rollouts.jsonl"
+ path.write_text(json.dumps({"text": "a\u2028b\u0085c"}, ensure_ascii=False) + "\n", encoding="utf-8")
+ errors: list[str] = []
+ assert read_rollouts(path, errors) == [{"text": "a\u2028b\u0085c"}] and errors == []
+
+
+def test_codex_inherits_the_sandbox_environment_when_runtime_env_is_set(tmp_path: Path) -> None:
+ kwargs = {
+ "agent": "codex",
+ "model": "m",
+ "model_url": "http://127.0.0.1:9/v1",
+ "rollouts_path": tmp_path / "r.jsonl",
+ "n_attempts": 1,
+ "n_concurrent": 1,
+ "sandbox": "docker",
+ }
+ override = "++codex_agent.responses_api_agents.codex_agent.inherit_sandbox_environment=true"
+ assert override in gym_eval_command("gym", tmp_path, inherit_sandbox_environment=True, **kwargs)
+ assert override not in gym_eval_command("gym", tmp_path, **kwargs)
+
+
+def test_model_url_with_userinfo_is_rejected() -> None:
+ from skillevaluator.tier3.nemo_gym.backend import model_url_credential_error
+
+ assert model_url_credential_error("https://user:[email protected]/v1")
+ assert model_url_credential_error("https://models.example/v1") is None
+
+
+def test_gym_environment_keeps_uv_credentials_and_anchors_paths(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from skillevaluator.tier3.nemo_gym.runner import gym_launch_environment
+
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setenv("UV_INDEX_INTERNAL_PASSWORD", "index-secret")
+ monkeypatch.setenv("NETRC", "netrc")
+ monkeypatch.setenv("SSL_CERT_FILE", "certs/ca.pem")
+ env = gym_launch_environment({})
+ assert env["UV_INDEX_INTERNAL_PASSWORD"] == "index-secret"
+ assert env["NETRC"] == "netrc" or env["NETRC"] == str(tmp_path / "netrc")
+ assert env["SSL_CERT_FILE"] == str(tmp_path / "certs" / "ca.pem")
+
+
+def test_native_harbor_task_source_resolves_like_harbor(tmp_path: Path) -> None:
+ from skillevaluator.tier3.nemo_gym.backend import uses_native_harbor_tasks
+
+ skill = tmp_path / "skill"
+ (skill / "evals" / "harbor" / "task-1").mkdir(parents=True)
+ assert uses_native_harbor_tasks(skill, "auto")
+ (skill / "evals" / "evals.json").write_text("{}")
+ assert not uses_native_harbor_tasks(skill, "auto")
+ assert uses_native_harbor_tasks(skill, "native_harbor")
+
+
+def test_gym_log_is_redacted(tmp_path: Path) -> None:
+ import sys
+
+ from skillevaluator.tier3.nemo_gym.runner import _run_gym
+
+ log_path = tmp_path / "gym.log"
+ with log_path.open("w", encoding="utf-8") as log:
+ code = _run_gym(
+ [sys.executable, "-c", "print('key=super-secret-value done')"],
+ cwd=tmp_path,
+ env={"PATH": "/usr/bin:/bin"},
+ log=log,
+ timeout_s=30,
+ secret_values={"super-secret-value"},
+ )
+ assert code == 0
+ text = log_path.read_text()
+ assert "super-secret-value" not in text and "done" in text
+
+
+def test_gym_timeout_kills_the_whole_process_group(tmp_path: Path) -> None:
+ import os
+ import sys
+
+ from skillevaluator.tier3.nemo_gym import runner as gym_runner
+
+ pid_file = tmp_path / "child.pid"
+ script = (
+ "import os, signal, subprocess, sys, time\n"
+ "signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))\n"
+ f"child = subprocess.Popen([sys.executable, '-c', 'import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(60)'])\n"
+ f"open({str(pid_file)!r}, 'w').write(str(child.pid))\n"
+ "time.sleep(60)\n"
+ )
+ with (tmp_path / "gym.log").open("w") as log:
+ code = gym_runner._run_gym(
+ [sys.executable, "-c", script], cwd=tmp_path, env=dict(os.environ), log=log, timeout_s=2
+ )
+ assert code is None
+ child = int(pid_file.read_text())
+ import time
+
+ for _ in range(50):
+ try:
+ os.kill(child, 0)
+ except ProcessLookupError:
+ break
+ time.sleep(0.1)
+ else:
+ pytest.fail("child of the Gym leader survived")
+
+
+def test_gym_judge_override_reaches_the_staged_verifier(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, keep_staged_tasks: None
+) -> None:
+ import tomllib
+
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch)
+ monkeypatch.setenv("LLM_JUDGE_MODEL", "judge-override-model")
+ result = _run_fake_gym(skill, tmp_path)
+ task_toml = next((Path(result["run_dir"]) / "_harbor-tasks" / "codex" / "with").glob("*/task.toml"))
+ verifier_env = tomllib.loads(task_toml.read_text())["verifier"]["env"]
+ assert verifier_env["LLM_JUDGE_MODEL"] == "${LLM_JUDGE_MODEL}"
+ assert result["run_config"]["judge"]["model"] == "judge-override-model"
+
+
+def test_gym_run_removes_staged_tasks_and_jobs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch)
+ result = _run_fake_gym(skill, tmp_path)
+ run_dir = Path(result["run_dir"])
+ assert not (run_dir / "_harbor-tasks").exists() and not (run_dir / "_harbor-jobs").exists()
+ assert (run_dir / "_nemo-gym").is_dir()
+ assert result["run_config"]["harbor"]["jobs_retained"] is False
+ assert json.loads((run_dir / "run_config.json").read_text())["harbor"]["jobs_retained"] is False
+
+
+def test_doctor_reports_nemo_gym_readiness(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skillevaluator.tier3 import commands
+ from skillevaluator.tier3.nemo_gym import backend
+ from skillevaluator.tier3.nemo_gym import runner as gym_runner
+
+ gym = tmp_path / "gym"
+ import sys
+
+ gym.write_text(_FAKE_GYM.format(python=sys.executable))
+ gym.chmod(0o755)
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_BIN", str(gym))
+ monkeypatch.setattr(backend, "nemo_gym_version", lambda _bin: "0.7.0")
+ monkeypatch.setattr("shutil.which", lambda name: f"/usr/bin/{name}")
+ monkeypatch.setattr(commands, "_docker_daemon_error", lambda _env: None)
+ monkeypatch.setattr(gym_runner, "_model_endpoint", lambda model: (model or "m", "http://127.0.0.1:9/v1", "k"))
+ rows = commands._nemo_gym_doctor_rows(["codex"], "docker", {})
+ assert rows == [
+ ("NeMo Gym CLI", "pass", f"{gym} (nemo-gym 0.7.0)"),
+ ("NeMo Gym backend", "pass", "docker sandbox ready"),
+ ]
+
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_BIN", str(tmp_path / "missing"))
+ rows = commands._nemo_gym_doctor_rows(["codex", "goose"], "local", {})
+ assert rows[0][:2] == ("NeMo Gym CLI", "fail")
+ details = " ".join(detail for _name, status, detail in rows[1:] if status == "fail")
+ assert "goose" in details and "docker only" in details
+
+
+def test_tier3_doctor_accepts_backend_option() -> None:
+ from click.testing import CliRunner
+
+ from skillevaluator.cli import cli
+
+ result = CliRunner().invoke(cli, ["tier3", "doctor", "--help"])
+ assert result.exit_code == 0 and "--backend" in result.output
+
+
+def test_fake_gym_run_stages_native_harbor_tasks(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skillevaluator.tier3.nemo_gym import runner as gym_runner
+
+ config = "schema_version: 1\nharbor:\n task_source: native_harbor\ngrading:\n mode: custom_only\n"
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch, config=config)
+ task = skill / "evals" / "harbor" / "case-001"
+ (task / "environment").mkdir(parents=True)
+ (task / "tests").mkdir()
+ (task / "task.toml").write_text(
+ 'schema_version = "1.3"\n\n[task]\nname = "nvidia/case-001"\n\n[metadata]\nentry_id = "case-001"\n\n'
+ "[agent]\ntimeout_sec = 300.0\n\n[verifier]\ntimeout_sec = 600.0\n\n[environment]\n"
+ 'skills_dir = "/workspace/skills"\n'
+ )
+ (task / "instruction.md").write_text("Native instruction NATIVE-7341.\n")
+ (task / "environment" / "Dockerfile").write_text("FROM python:3.12-slim\nWORKDIR /workspace\n")
+ (task / "tests" / "test.sh").write_text("#!/bin/bash\necho 1 > /logs/verifier/reward.txt\n")
+ staged: dict[str, str] = {}
+ original_stage = gym_runner.stage_for_gym
+
+ def recording_stage(arm_dir: Path, *args, **kwargs) -> None:
+ original_stage(arm_dir, *args, **kwargs)
+ for instruction in arm_dir.glob("*/instruction.md"):
+ staged[arm_dir.name] = instruction.read_text()
+ assert "skills_dir" not in (instruction.parent / "task.toml").read_text()
+
+ monkeypatch.setattr(gym_runner, "stage_for_gym", recording_stage)
+ # The fake Gym writes what the native test.sh writes: only reward.txt.
+ monkeypatch.setenv("FAKE_GYM_REWARD_TXT", "1")
+ result = _run_fake_gym(skill, tmp_path)
+ assert set(staged) == {"with", "without"}
+ assert all("NATIVE-7341" in text for text in staged.values())
+ run_config = json.loads((Path(result["run_dir"]) / "run_config.json").read_text())
+ assert run_config["task_source"] == "native_harbor"
+ assert result.get("execution_status") != "failed", result.get("execution_errors")
+ assert result["agents"]["codex"]["num_trials_with"] == 1
+ assert result["agents"]["codex"]["num_trials_without"] == 1
+
+
+def test_fake_gym_run_reuses_the_shared_base_image(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skillevaluator.tier3.harbor import adapter
+ from skillevaluator.tier3.nemo_gym import runner as gym_runner
+
+ skill, _env_log = _fake_gym_skill(
+ tmp_path, monkeypatch, config="schema_version: 1\nharbor:\n base_image_mode: rebuild\n"
+ )
+ builds: list[bool] = []
+
+ def fake_build(*_args, force_rebuild: bool = False, **_kwargs) -> str:
+ builds.append(force_rebuild)
+ return "skillevaluator-base:test"
+
+ monkeypatch.setattr(adapter, "build_eval_base_image", fake_build)
+ dockerfiles: list[str] = []
+ original_stage = gym_runner.stage_for_gym
+
+ def recording_stage(arm_dir: Path, *args, **kwargs) -> None:
+ original_stage(arm_dir, *args, **kwargs)
+ dockerfiles.extend(path.read_text() for path in arm_dir.glob("*/environment/Dockerfile"))
+
+ monkeypatch.setattr(gym_runner, "stage_for_gym", recording_stage)
+ result = _run_fake_gym(skill, tmp_path)
+ assert builds == [True]
+ assert dockerfiles and all("FROM skillevaluator-base:test" in text for text in dockerfiles)
+ run_config = json.loads((Path(result["run_dir"]) / "run_config.json").read_text())
+ assert run_config["harbor"]["base_image_mode"] == "rebuild"
+
+
+class _RecordingReporter:
+ def __init__(self) -> None:
+ self.plans: list = []
+ self.events: list = []
+
+ def start(self, plan) -> None:
+ self.plans.append(plan)
+
+ def set_secret_values(self, values) -> None:
+ del values
+
+ def emit(self, event) -> None:
+ self.events.append(event)
+
+ def heartbeat(self) -> None:
+ pass
+
+ def close(self) -> None:
+ pass
+
+
+def _native_task(skill: Path, extra: str = "") -> Path:
+ task = skill / "evals" / "harbor" / "case-001"
+ (task / "environment").mkdir(parents=True)
+ (task / "tests").mkdir()
+ (task / "task.toml").write_text(
+ 'schema_version = "1.3"\n\n[task]\nname = "nvidia/case-001"\n\n[metadata]\nentry_id = "case-001"\n\n'
+ '[agent]\ntimeout_sec = 300.0\n\n[environment]\nskills_dir = "/workspace/skills"\n' + extra
+ )
+ (task / "instruction.md").write_text("Native instruction.\n")
+ (task / "environment" / "Dockerfile").write_text("FROM python:3.12-slim\n")
+ (task / "tests" / "test.sh").write_text("#!/bin/bash\necho 1 > /logs/verifier/reward.txt\n")
+ return task
+
+
+def test_codex_inherits_the_task_environment_without_runtime_env(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ config = "schema_version: 1\nharbor:\n task_source: native_harbor\ngrading:\n mode: custom_only\n"
+ skill, env_log = _fake_gym_skill(tmp_path, monkeypatch, config=config)
+ _native_task(skill, '\n[environment.env]\nSERVICE_URL = "http://svc:8080"\n')
+ _run_fake_gym(skill, tmp_path, skip_baseline=True)
+ override = "++codex_agent.responses_api_agents.codex_agent.inherit_sandbox_environment=true"
+ launches = [json.loads(line) for line in env_log.read_text().splitlines()]
+ assert launches and all(override in launch["argv"] for launch in launches)
+
+
+def test_reward_txt_is_scored_like_harbor(tmp_path: Path) -> None:
+ from skillevaluator.tier3.nemo_gym.results import read_verifier_rewards
+
+ logs = tmp_path / "logs"
+ logs.mkdir()
+ (logs / "reward.txt").write_text("0.5\n")
+ assert read_verifier_rewards(logs) == {"reward": 0.5}
+ (logs / "reward.txt").write_text("nan\n")
+ assert read_verifier_rewards(logs) is None
+ (logs / "reward.json").write_text(json.dumps({"overall": 0.9}))
+ assert read_verifier_rewards(logs) == {"overall": 0.9}
+ row = {
+ "_ng_task_id": {"taskset": "arm", "task_id": "t1"},
+ "verifier_return_code": 0,
+ "verifier_logs_dir": str(tmp_path / "txt"),
+ }
+ (tmp_path / "txt").mkdir()
+ (tmp_path / "txt" / "reward.txt").write_text("1\n")
+ job = tmp_path / "job"
+ errors = write_job_from_rollouts([row], job, eval_name="codex__m", task_case_ids={"t1": "case-1"}, n_attempts=1)
+ assert errors == []
+ trial = json.loads((job / "t1__gym001" / "result.json").read_text())
+ assert trial["verifier_result"]["rewards"] == {"entry_id": "case-1", "reward": 1.0}
+
+
+def test_rollout_row_failures_are_redacted(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch)
+ secret = "gw-policy-0a1b2c3d4e5f6789"
+ monkeypatch.setenv(MODEL_API_KEY_ENV, secret)
+ monkeypatch.setenv("FAKE_GYM_FAILURE", f"AuthenticationError: 401 invalid key {secret}")
+ result = _run_fake_gym(skill, tmp_path, skip_baseline=True, max_cases=1)
+ run_dir = Path(result["run_dir"])
+ assert "AuthenticationError" in json.dumps(result)
+ assert secret not in json.dumps(result)
+ assert all(secret not in path.read_text() for path in run_dir.rglob("*.json"))
+
+
+def test_cli_checks_gym_settings_before_autopilot_writes_a_dataset(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ from click.testing import CliRunner
+
+ from skillevaluator.cli import cli
+ from skillevaluator.evaluation import EvaluationService
+
+ skill = tmp_path / "calc"
+ skill.mkdir()
+ (skill / "SKILL.md").write_text("---\nname: calc\ndescription: Adds numbers.\n---\n# Calc\n")
+ gym = tmp_path / "gym"
+ gym.write_text("#!/bin/sh\n")
+ gym.chmod(0o755)
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_BIN", str(gym))
+ monkeypatch.setattr(
+ EvaluationService, "create_autopilot_dataset", lambda *_args, **_kwargs: pytest.fail("must not generate")
+ )
+ base = ["evaluate", str(skill), "--backend", "nemo-gym", "--autopilot", "--progress", "off"]
+ cases = [
+ ({"SKILL_EVAL_NEMO_GYM_TIMEOUT_S": "abc"}, [], "SKILL_EVAL_NEMO_GYM_TIMEOUT_S"),
+ ({"SKILL_EVAL_NEMO_GYM_MODEL_URL": "http://127.0.0.1:9/v1"}, [], "SKILL_EVAL_NEMO_GYM_MODEL_API_KEY"),
+ (
+ {"SKILL_EVAL_NEMO_GYM_MODEL_URL": "http://u:[email protected]:9/v1", MODEL_API_KEY_ENV: "k"},
+ [],
+ "username or password",
+ ),
+ ({}, ["--override-cpus", "0"], "--override-cpus"),
+ ({}, ["--override-memory-mb", "0"], "--override-memory-mb"),
+ ]
+ for env, flags, expected in cases:
+ with monkeypatch.context() as patched:
+ for name, value in env.items():
+ patched.setenv(name, value)
+ result = CliRunner().invoke(cli, [*base, *flags])
+ assert result.exit_code == 2, (env, flags, result.output)
+ assert expected in result.output, (expected, result.output)
+ assert not (skill / "evals").exists()
+
+
+def test_missing_dataset_is_rejected_before_a_run_dir_is_reserved(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from skillevaluator.tier3.harbor.runner import _MISSING_EVALS_DATASET_ERROR
+
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch)
+ (skill / "evals" / "evals.json").unlink()
+ result = _run_fake_gym(skill, tmp_path)
+ # The same advice as Harbor: create-eval-dataset needs EVAL.md, --prompt or --grounding skill.
+ assert result == {"error": [_MISSING_EVALS_DATASET_ERROR]}
+ results_root = tmp_path / "results"
+ assert not results_root.exists() or not any(results_root.iterdir())
+
+
+def test_native_task_mcp_servers_are_rejected(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skillevaluator.tier3.nemo_gym.backend import NATIVE_MCP_SERVERS_ERROR, nemo_gym_config_errors
+
+ config = "schema_version: 1\nharbor:\n task_source: native_harbor\ngrading:\n mode: custom_only\n"
+ skill, env_log = _fake_gym_skill(tmp_path, monkeypatch, config=config)
+ _native_task(skill, '\n[[environment.mcp_servers]]\nname = "files"\ntransport = "stdio"\ncommand = "srv"\n')
+ assert NATIVE_MCP_SERVERS_ERROR in nemo_gym_config_errors(skill)
+ result = _run_fake_gym(skill, tmp_path)
+ assert NATIVE_MCP_SERVERS_ERROR in json.dumps(result)
+ assert not env_log.exists()
+ staged = tmp_path / "staged" / "case-001"
+ staged.mkdir(parents=True)
+ (staged / "task.toml").write_text((skill / "evals" / "harbor" / "case-001" / "task.toml").read_text())
+ with pytest.raises(ValueError, match="mcp_servers"):
+ stage_for_gym(staged.parent)
+
+
+def test_stage_for_gym_applies_resource_overrides_and_scales_the_default_verifier_timeout(tmp_path: Path) -> None:
+ import tomllib
+
+ with_env = tmp_path / "a" / "t1"
+ with_env.mkdir(parents=True)
+ (with_env / "task.toml").write_text(
+ '[agent]\ntimeout_sec = 300.0\n\n[verifier.env]\nX = "1"\n\n[environment]\ncpus = 2\nmemory_mb = 4096\n'
+ )
+ stage_for_gym(with_env.parent, timeout_multiplier=2.0, resource_overrides={"cpus": 4, "memory_mb": 8192})
+ data = tomllib.loads((with_env / "task.toml").read_text())
+ assert data["environment"]["cpus"] == 4 and data["environment"]["memory_mb"] == 8192
+ assert data["verifier"]["timeout_sec"] == 1200.0 and data["verifier"]["env"] == {"X": "1"}
+ assert data["agent"]["timeout_sec"] == 600.0
+
+ no_env = tmp_path / "b" / "t1"
+ no_env.mkdir(parents=True)
+ (no_env / "task.toml").write_text("[verifier]\ntimeout_sec = 100.0\n")
+ stage_for_gym(no_env.parent, timeout_multiplier=2.0, resource_overrides={"cpus": 4})
+ data = tomllib.loads((no_env / "task.toml").read_text())
+ assert data["environment"]["cpus"] == 4 and data["verifier"]["timeout_sec"] == 200.0
+
+
+def test_native_tasks_get_cpu_and_memory_overrides(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, keep_staged_tasks: None
+) -> None:
+ import tomllib
+
+ config = "schema_version: 1\nharbor:\n task_source: native_harbor\ngrading:\n mode: custom_only\n"
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch, config=config)
+ _native_task(skill)
+ result = _run_fake_gym(skill, tmp_path, skip_baseline=True, override_cpus=4, override_memory_mb=8192)
+ staged = next((Path(result["run_dir"]) / "_harbor-tasks" / "codex" / "with").glob("*/task.toml"))
+ environment = tomllib.loads(staged.read_text())["environment"]
+ assert environment["cpus"] == 4 and environment["memory_mb"] == 8192
+
+
+def test_results_root_is_excluded_from_the_repo_context(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skillevaluator.tier3.nemo_gym import runner as gym_runner
+
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch)
+ seen: list[tuple[Path, ...]] = []
+ from skillevaluator.tier3.harbor import adapter
+
+ original = adapter.generate_harbor_tasks
+
+ def recording(*args, repo_context_exclude_paths=(), **kwargs):
+ seen.append(tuple(repo_context_exclude_paths))
+ return original(*args, repo_context_exclude_paths=repo_context_exclude_paths, **kwargs)
+
+ monkeypatch.setattr(adapter, "generate_harbor_tasks", recording)
+ del gym_runner
+ _run_fake_gym(skill, tmp_path, skip_baseline=True, max_cases=1)
+ assert seen and all(tmp_path / "results" in paths for paths in seen)
+
+
+def test_failed_base_image_build_is_degraded(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skillevaluator.tier3.harbor import adapter
+
+ skill, _env_log = _fake_gym_skill(
+ tmp_path, monkeypatch, config="schema_version: 1\nharbor:\n base_image_mode: rebuild\n"
+ )
+ monkeypatch.setattr(adapter, "build_eval_base_image", lambda *_args, **_kwargs: "")
+ reporter = _RecordingReporter()
+ _run_fake_gym(skill, tmp_path, skip_baseline=True, max_cases=1, progress_reporter=reporter)
+ images = [event for event in reporter.events if event.stage == "docker-images" and event.state != "running"]
+ assert [(event.state, event.detail) for event in images] == [
+ ("degraded", "base image build failed; falling back to per-task Dockerfiles")
+ ]
+
+
+def test_gym_run_starts_the_reporter_with_its_run_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch)
+ reporter = _RecordingReporter()
+ result = _run_fake_gym(skill, tmp_path, progress_reporter=reporter)
+ assert len(reporter.plans) == 1
+ plan = reporter.plans[0]
+ assert plan.output_dir == result["run_dir"] and plan.case_count == 2 and plan.matrix_trials == 4
+
+
+def test_live_marks_score_reward_logs_and_skip_normalized_gym_jobs(tmp_path: Path) -> None:
+ from skillevaluator.tier3.case_summary import live_case_marks
+
+ run_dir = tmp_path / "run"
+ arm = run_dir / "_nemo-gym" / "codex-with"
+ arm.mkdir(parents=True)
+ logs = tmp_path / "logs"
+ logs.mkdir()
+ (logs / "reward.json").write_text(json.dumps({"overall": 0.9}))
+ txt_logs = tmp_path / "txt"
+ txt_logs.mkdir()
+ (txt_logs / "reward.txt").write_text("0\n")
+ rows = [
+ {"_ng_task_id": {"task_id": "calc-001"}, "verifier_return_code": 0, "verifier_logs_dir": str(logs)},
+ {"_ng_task_id": {"task_id": "calc-002"}, "verifier_return_code": 0, "verifier_logs_dir": str(txt_logs)},
+ ]
+ (arm / "rollouts.jsonl").write_text("".join(json.dumps(row) + "\n" for row in rows))
+ write_job_from_rollouts(
+ rows,
+ run_dir / "_harbor-jobs" / "calc-codex-with",
+ eval_name="codex__m",
+ task_case_ids={"calc-001": "calc-001", "calc-002": "calc-002"},
+ n_attempts=1,
+ )
+ marks, running = live_case_marks(run_dir, ["codex"])
+ with_skill = marks["codex"]["with_skill"]
+ assert len(with_skill["calc-001"]) == 1 and len(with_skill["calc-002"]) == 1
+ from skillevaluator.tier3.case_summary import ERROR
+
+ assert ERROR not in with_skill["calc-001"] + with_skill["calc-002"]
+ assert with_skill["calc-001"] != with_skill["calc-002"]
+ assert running == set()
+
+
+def test_adc_refresh_follows_the_policy_key_source(monkeypatch: pytest.MonkeyPatch) -> None:
+ from skillevaluator import provider_config
+ from skillevaluator.tier3.nemo_gym import runner as gym_runner
+
+ monkeypatch.setattr(provider_config, "refresh_host_vertex_adc_environment", lambda *_args, **_kwargs: "token-c")
+ base = {"OPENAI_API_KEY": "token-b", MODEL_API_KEY_ENV: "token-a"}
+ refreshed, _timeout = gym_runner._refresh_adc_credentials(base, policy_uses_provider_key=True, timeout_s=60)
+ assert refreshed[MODEL_API_KEY_ENV] == "token-c" and refreshed["OPENAI_API_KEY"] == "token-c"
+ refreshed, _timeout = gym_runner._refresh_adc_credentials(base, policy_uses_provider_key=False, timeout_s=60)
+ assert refreshed[MODEL_API_KEY_ENV] == "token-a"
+
+
+def test_second_interrupt_during_stop_still_kills_the_gym_group(tmp_path: Path) -> None:
+ import sys
+ import time
+
+ from skillevaluator.tier3.nemo_gym.runner import _run_gym
+
+ class _InterruptingReporter(_RecordingReporter):
+ def emit(self, event) -> None:
+ del event
+ raise KeyboardInterrupt
+
+ pid_file = tmp_path / "leader.pid"
+ script = (
+ "import os, signal, time\n"
+ "signal.signal(signal.SIGTERM, signal.SIG_IGN)\n"
+ f"open({str(pid_file)!r}, 'w').write(str(os.getpid()))\n"
+ "time.sleep(60)\n"
+ )
+ with (tmp_path / "gym.log").open("w") as log, pytest.raises(KeyboardInterrupt):
+ _run_gym(
+ [sys.executable, "-c", script],
+ cwd=tmp_path,
+ env=dict(os.environ),
+ log=log,
+ timeout_s=1,
+ reporter=_InterruptingReporter(),
+ )
+ leader = int(pid_file.read_text())
+ for _ in range(50):
+ try:
+ os.kill(leader, 0)
+ except ProcessLookupError:
+ break
+ time.sleep(0.1)
+ else:
+ pytest.fail("Gym leader survived a second interrupt")
+
+
+def test_eperm_race_while_stopping_is_treated_as_exited(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ import sys
+
+ from skillevaluator.tier3.harbor import runner as harbor_runner
+ from skillevaluator.tier3.nemo_gym.runner import _run_gym
+
+ def racing_terminate(process, **_kwargs) -> None:
+ process.kill()
+ process.wait()
+ raise PermissionError(1, "Operation not permitted")
+
+ monkeypatch.setattr(harbor_runner, "_terminate_harbor_process_tree", racing_terminate)
+ with (tmp_path / "gym.log").open("w") as log:
+ code = _run_gym(
+ [sys.executable, "-c", "import time; time.sleep(60)"],
+ cwd=tmp_path,
+ env=dict(os.environ),
+ log=log,
+ timeout_s=0.5,
+ )
+ assert code is None
+
+
+def test_doctor_fails_without_a_policy_endpoint_or_docker_daemon(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from skillevaluator.tier3 import commands
+ from skillevaluator.tier3.nemo_gym import backend
+ from skillevaluator.tier3.nemo_gym import runner as gym_runner
+
+ gym = tmp_path / "gym"
+ import sys
+
+ gym.write_text(_FAKE_GYM.format(python=sys.executable))
+ gym.chmod(0o755)
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_BIN", str(gym))
+ monkeypatch.setattr(backend, "nemo_gym_version", lambda _bin: "0.7.0")
+
+ def no_endpoint(_model):
+ raise ValueError("--backend nemo-gym needs a model, an OpenAI-compatible base URL and an API key")
+
+ monkeypatch.setattr(gym_runner, "_model_endpoint", no_endpoint)
+ docker_daemon_error = commands._docker_daemon_error
+ monkeypatch.setattr(commands, "_docker_daemon_error", lambda _env: None)
+ rows = commands._nemo_gym_doctor_rows(["codex"], "docker", {})
+ assert (
+ "NeMo Gym backend",
+ "fail",
+ "codex: --backend nemo-gym needs a model, an OpenAI-compatible base URL and an API key",
+ ) in rows
+
+ bin_dir = tmp_path / "bin"
+ bin_dir.mkdir()
+ docker = bin_dir / "docker"
+ docker.write_text(
+ "#!/bin/sh\necho 'Cannot connect to the Docker daemon at unix:///var/run/docker.sock' >&2\nexit 1\n"
+ )
+ docker.chmod(0o755)
+ monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}/usr/bin{os.pathsep}/bin")
+ error = docker_daemon_error({"PATH": os.environ["PATH"]})
+ assert error is not None and "Cannot connect to the Docker daemon" in error
+
+
+def test_unsupported_gym_sandbox_is_rejected_before_launch(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skillevaluator.tier3.nemo_gym.backend import nemo_gym_settings_errors
+
+ skill, env_log = _fake_gym_skill(tmp_path, monkeypatch)
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_SANDBOX", "local")
+ assert any("SKILL_EVAL_NEMO_GYM_SANDBOX=local" in error for error in nemo_gym_settings_errors())
+ result = _run_fake_gym(skill, tmp_path)
+ assert "SKILL_EVAL_NEMO_GYM_SANDBOX=local" in json.dumps(result)
+ assert not env_log.exists()
+
+
+def test_excess_rollouts_are_reported_and_not_collected(tmp_path: Path) -> None:
+ logs = tmp_path / "logs"
+ logs.mkdir()
+ (logs / "reward.json").write_text(json.dumps({"overall": 1.0}))
+ row = {"_ng_task_id": {"task_id": "t1"}, "verifier_return_code": 0, "verifier_logs_dir": str(logs)}
+ job = tmp_path / "job"
+ errors = write_job_from_rollouts(
+ [row, dict(row)], job, eval_name="codex__m", task_case_ids={"t1": "case-1"}, n_attempts=1
+ )
+ assert errors == ["NeMo Gym returned 2/1 rollouts for case case-1; the 1 extra rollout(s) were not collected"]
+ assert sorted(path.name for path in job.iterdir() if path.is_dir()) == ["t1__gym001"]
+
+
+def test_memory_override_replaces_a_legacy_memory_key(tmp_path: Path) -> None:
+ import tomllib
+
+ task = tmp_path / "arm" / "t1"
+ task.mkdir(parents=True)
+ (task / "task.toml").write_text('[environment]\ncpus = 2\nmemory = "4G"\n')
+ stage_for_gym(task.parent, resource_overrides={"memory_mb": 8192})
+ environment = tomllib.loads((task / "task.toml").read_text())["environment"]
+ assert environment == {"cpus": 2, "memory_mb": 8192}
+
+
+def _make_gym_stop_fail(monkeypatch: pytest.MonkeyPatch, *, deny_final_kill: bool) -> list[int]:
+ """Make stopping a Gym run fail the way a PermissionError from killpg does; return the leaders left alive.
+
+ With ``deny_final_kill`` the last SIGKILL is refused too, so the group stays alive and unconfirmed.
+ """
+ from skillevaluator.tier3.harbor import runner as harbor_runner
+
+ stuck: list[int] = []
+ real_terminate = harbor_runner._terminate_harbor_process_tree
+ real_killpg = os.killpg
+
+ def failing_terminate(process, **kwargs) -> None:
+ if "--help" in process.args:
+ return real_terminate(process, **kwargs)
+ stuck.append(process.pid)
+ raise PermissionError(1, "Operation not permitted")
+
+ def denied_killpg(pgid: int, sig: int) -> None:
+ if deny_final_kill and pgid in stuck:
+ raise PermissionError(1, "Operation not permitted")
+ real_killpg(pgid, sig)
+
+ monkeypatch.setattr(harbor_runner, "_terminate_harbor_process_tree", failing_terminate)
+ monkeypatch.setattr(os, "killpg", denied_killpg)
+ monkeypatch.setattr(harbor_runner, "_HARBOR_RUN_REAP_SECONDS", 0.3)
+ return stuck
+
+
+def _kill_leaders(pids: list[int]) -> None:
+ import contextlib
+ import signal
+
+ for pid in pids:
+ with contextlib.suppress(ProcessLookupError):
+ os.kill(pid, signal.SIGKILL)
+
+
[email protected](os.name != "posix", reason="requires POSIX process groups and signals")
+def test_stop_failure_during_an_interrupt_keeps_the_interrupt(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ import signal
+ import sys
+ import threading
+
+ from skillevaluator.tier3.nemo_gym.runner import _run_gym
+
+ class _InterruptOnce(_RecordingReporter):
+ pass
+
+ reporter = _InterruptOnce()
+ stuck = _make_gym_stop_fail(monkeypatch, deny_final_kill=True)
+ threading.Timer(0.5, lambda: os.kill(os.getpid(), signal.SIGINT)).start()
+ try:
+ with (tmp_path / "gym.log").open("w") as log, pytest.raises(KeyboardInterrupt) as raised:
+ _run_gym(
+ [sys.executable, "-c", "import time; time.sleep(60)"],
+ cwd=tmp_path,
+ env=dict(os.environ),
+ log=log,
+ timeout_s=30,
+ reporter=reporter,
+ )
+ finally:
+ _kill_leaders(stuck)
+ assert isinstance(raised.value.__cause__, RuntimeError)
+ # The interrupt still ends the run, and the progress output says Gym may still be running.
+ assert any(
+ event.stage == "cleanup" and event.state == "failed" and "could not be confirmed stopped" in event.detail
+ for event in reporter.events
+ )
+
+
[email protected](os.name != "posix", reason="requires POSIX process groups and signals")
+def test_failed_stop_gets_a_final_kill_and_the_timeout_is_still_reported(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import sys
+
+ from skillevaluator.tier3.nemo_gym.runner import _run_gym
+
+ stuck = _make_gym_stop_fail(monkeypatch, deny_final_kill=False)
+ try:
+ with (tmp_path / "gym.log").open("w") as log:
+ code = _run_gym(
+ [sys.executable, "-c", "import time; time.sleep(60)"],
+ cwd=tmp_path,
+ env=dict(os.environ),
+ log=log,
+ timeout_s=0.5,
+ )
+ assert code is None
+ assert len(stuck) == 1
+ with pytest.raises(ProcessLookupError):
+ os.kill(stuck[0], 0)
+ finally:
+ _kill_leaders(stuck)
+
+
[email protected](os.name != "posix", reason="requires POSIX process groups and signals")
+def test_gym_group_that_cannot_be_confirmed_stopped_raises(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ import sys
+
+ from skillevaluator.tier3.nemo_gym.runner import GymCleanupError, _run_gym
+
+ stuck = _make_gym_stop_fail(monkeypatch, deny_final_kill=True)
+ try:
+ with (tmp_path / "gym.log").open("w") as log, pytest.raises(GymCleanupError) as raised:
+ _run_gym(
+ [sys.executable, "-c", "import time; time.sleep(60)"],
+ cwd=tmp_path,
+ env=dict(os.environ),
+ log=log,
+ timeout_s=0.5,
+ )
+ finally:
+ _kill_leaders(stuck)
+ assert isinstance(raised.value.__cause__, PermissionError)
+ assert f"process group {stuck[0]}" in str(raised.value)
+
+
[email protected](os.name != "posix", reason="requires POSIX process groups and signals")
[email protected]("hanging_launch", [1, 2])
+def test_unconfirmed_gym_stop_launches_nothing_more_and_keeps_finished_arms(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, hanging_launch: int
+) -> None:
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch)
+ probe_gym = os.environ["SKILL_EVAL_NEMO_GYM_BIN"]
+ launches = tmp_path / "launches"
+ hanging_gym = tmp_path / "hanging-gym"
+ # Launches before ``hanging_launch`` run the fake Gym to completion; that launch hangs.
+ hanging_gym.write_text(
+ f"#!{sys.executable}\nimport os, sys, time\nfrom pathlib import Path\n"
+ "if sys.argv[1:] == ['eval', 'run', '--help']:\n"
+ f" os.execv({probe_gym!r}, [{probe_gym!r}, *sys.argv[1:]])\n"
+ f"launches = Path({str(launches)!r})\n"
+ "earlier = launches.read_text().split() if launches.exists() else []\n"
+ "with launches.open('a') as launched: launched.write(f'{os.getpid()}\\n')\n"
+ f"if len(earlier) + 1 < {hanging_launch}:\n"
+ f" os.execv({probe_gym!r}, [{probe_gym!r}, *sys.argv[1:]])\n"
+ "time.sleep(60)\n"
+ )
+ hanging_gym.chmod(0o755)
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_BIN", str(hanging_gym))
+ # A finishing launch needs time to complete; a lone hanging launch only needs to time out.
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_TIMEOUT_S", "1" if hanging_launch == 1 else "15")
+ stuck = _make_gym_stop_fail(monkeypatch, deny_final_kill=True)
+ reporter = _RecordingReporter()
+ try:
+ result = _run_fake_gym(skill, tmp_path, n_attempts=1, max_cases=1, progress_reporter=reporter)
+ finally:
+ _kill_leaders(stuck)
+ launched = [int(pid) for pid in launches.read_text().split()]
+ # Nothing launched after the group that would not stop.
+ assert len(launched) == hanging_launch and launched[-1:] == stuck
+ assert result["execution_status"] == "failed"
+ assert Path(result["result_path"]).is_file()
+ errors = result["execution_errors"]
+ assert any(error.startswith("codex ") and "could not be confirmed stopped" in error for error in errors)
+ agent = result["agents"]["codex"]
+ if hanging_launch == 1:
+ assert any("without-skill: gym eval run was not started" in error for error in errors)
+ assert agent["num_trials_with"] == 0
+ else:
+ # The with-skill arm finished before the baseline hung: its trial is still scored.
+ assert agent["num_trials_with"] == 1
+ assert agent["num_trials_without"] == 0
+ assert any(error.startswith("codex ") and "gym eval run timed out after" in error for error in errors)
+ assert any(
+ event.stage == "agent:codex" and event.state == "failed" and "could not be confirmed stopped" in event.detail
+ for event in reporter.events
+ )
+ # The summary without --verbose still says Gym may be running, also when an arm finished.
+ from rich.console import Console
+
+ from skillevaluator.tier3.result_display import render_evaluation_result
+
+ assert any("may still be running" in warning for warning in result["warnings"])
+ console = Console(record=True, width=1000)
+ render_evaluation_result(result, console=console, verbose=False, skill_path=skill)
+ assert "may still be running" in console.export_text()
+
+
[email protected](os.name != "posix", reason="requires POSIX process groups and signals")
+def test_gym_group_member_that_outlives_the_leader_is_not_confirmed_stopped(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import contextlib
+ import signal
+ import time
+
+ from skillevaluator.tier3.harbor import runner as harbor_runner
+ from skillevaluator.tier3.nemo_gym.runner import GymCleanupError, _run_gym
+
+ ready = tmp_path / "member.pid"
+ leader = (
+ "import pathlib, subprocess, sys, time\n"
+ "member = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'])\n"
+ f"pathlib.Path({str(ready)!r}).write_text(str(member.pid))\n"
+ "time.sleep(60)\n"
+ )
+ groups: list[int] = []
+ real_killpg = os.killpg
+
+ def failing_terminate(process, **_kwargs) -> None:
+ # Fail the stop, as a refused killpg does, once the member has joined the group.
+ deadline = time.monotonic() + 60
+ while not ready.exists() and time.monotonic() < deadline:
+ time.sleep(0.05)
+ groups.append(process.pid)
+ raise PermissionError(1, "Operation not permitted")
+
+ def leader_only_kill(pgid: int, sig: int) -> None:
+ # The final SIGKILL reaches only the leader, so it is reaped while the member stays in its group.
+ if pgid in groups and sig == signal.SIGKILL:
+ os.kill(pgid, sig)
+ else:
+ real_killpg(pgid, sig)
+
+ monkeypatch.setattr(harbor_runner, "_terminate_harbor_process_tree", failing_terminate)
+ monkeypatch.setattr(os, "killpg", leader_only_kill)
+ monkeypatch.setattr(harbor_runner, "_HARBOR_RUN_REAP_SECONDS", 2.0)
+ try:
+ with (tmp_path / "gym.log").open("w") as log, pytest.raises(GymCleanupError):
+ _run_gym([sys.executable, "-c", leader], cwd=tmp_path, env=dict(os.environ), log=log, timeout_s=0.5)
+ finally:
+ for pgid in groups:
+ with contextlib.suppress(ProcessLookupError, PermissionError):
+ real_killpg(pgid, signal.SIGKILL)
+
+
[email protected](os.name != "posix", reason="requires POSIX process groups and signals")
+def test_permission_error_from_the_group_probe_is_retried(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skillevaluator.tier3.harbor import runner as harbor_runner
+ from skillevaluator.tier3.nemo_gym.runner import _run_gym
+
+ stuck = _make_gym_stop_fail(monkeypatch, deny_final_kill=False)
+ # Room for the denied probes and the one after them, even on a loaded machine.
+ monkeypatch.setattr(harbor_runner, "_HARBOR_RUN_REAP_SECONDS", 3.0)
+ stopping_killpg = os.killpg
+ denials = [0]
+
+ def probe_denied_twice(pgid: int, sig: int) -> None:
+ # macOS answers EPERM for a group of zombies until they are reaped: keep probing.
+ if sig == 0 and pgid in stuck and denials[0] < 2:
+ denials[0] += 1
+ raise PermissionError(1, "Operation not permitted")
+ stopping_killpg(pgid, sig)
+
+ monkeypatch.setattr(os, "killpg", probe_denied_twice)
+ try:
+ with (tmp_path / "gym.log").open("w") as log:
+ code = _run_gym(
+ [sys.executable, "-c", "import time; time.sleep(60)"],
+ cwd=tmp_path,
+ env=dict(os.environ),
+ log=log,
+ timeout_s=0.5,
+ )
+ finally:
+ _kill_leaders(stuck)
+ assert code is None
+ assert denials == [2]
+
+
[email protected](sys.platform != "linux", reason="needs Linux PR_SET_CHILD_SUBREAPER")
+def test_dead_gym_members_left_as_our_zombies_are_not_reported_running(tmp_path: Path) -> None:
+ import subprocess
+
+ import skillevaluator
+
+ # Like SkillEvaluator as a container's PID 1 without an init, a subreaper adopts Gym's orphans,
+ # and on Linux signal 0 still finds them as zombies until they are reaped.
+ script = tmp_path / "subreaper.py"
+ script.write_text(
+ "import ctypes, os, sys, time\n"
+ "from pathlib import Path\n"
+ "libc = ctypes.CDLL(None, use_errno=True)\n"
+ "if libc.prctl(36, 1, 0, 0, 0) != 0: # PR_SET_CHILD_SUBREAPER\n"
+ " raise OSError(ctypes.get_errno(), 'prctl(PR_SET_CHILD_SUBREAPER) failed')\n"
+ "from skillevaluator.tier3.harbor import runner as harbor_runner\n"
+ "from skillevaluator.tier3.nemo_gym.runner import _run_gym\n"
+ "ready = Path(sys.argv[1])\n"
+ "def failing_terminate(process, **_kwargs):\n"
+ " deadline = time.monotonic() + 60\n"
+ " while not ready.exists() and time.monotonic() < deadline:\n"
+ " time.sleep(0.05)\n"
+ " raise PermissionError(1, 'Operation not permitted')\n"
+ "harbor_runner._terminate_harbor_process_tree = failing_terminate\n"
+ "leader = (\n"
+ " 'import pathlib, subprocess, sys, time\\n'\n"
+ " \"member = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'])\\n\"\n"
+ " 'pathlib.Path(sys.argv[1]).write_text(str(member.pid))\\n'\n"
+ " 'time.sleep(60)\\n'\n"
+ ")\n"
+ "with open(os.devnull, 'w') as log:\n"
+ " code = _run_gym([sys.executable, '-c', leader, str(ready)], cwd=ready.parent,\n"
+ " env=dict(os.environ), log=log, timeout_s=0.5)\n"
+ "print(code)\n"
+ )
+ source_root = str(Path(skillevaluator.__file__).resolve().parents[1])
+ env = {**os.environ, "PYTHONPATH": os.pathsep.join(filter(None, [source_root, os.environ.get("PYTHONPATH")]))}
+ completed = subprocess.run(
+ [sys.executable, str(script), str(tmp_path / "member.pid")],
+ capture_output=True,
+ text=True,
+ timeout=180,
+ env=env,
+ check=False,
+ )
+ assert completed.returncode == 0, completed.stderr
+ assert completed.stdout.strip() == "None"
+
+
+def test_incompatible_gym_cli_is_rejected_before_staging(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skillevaluator.tier3.nemo_gym.backend import nemo_gym_cli_error
+
+ skill, env_log = _fake_gym_skill(tmp_path, monkeypatch)
+ old_gym = tmp_path / "old-gym"
+ old_gym.write_text("#!/bin/sh\necho 'usage: gym eval run [--input INPUT]'\nexit 2\n")
+ old_gym.chmod(0o755)
+ assert "exited 2" in (nemo_gym_cli_error(str(old_gym)) or "")
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_BIN", str(old_gym))
+ result = _run_fake_gym(skill, tmp_path)
+ assert "exited 2" in json.dumps(result)
+ assert not env_log.exists()
+ results_root = tmp_path / "results"
+ assert not results_root.exists() or not any(results_root.iterdir())
+
+
+def test_direct_run_probes_once_before_provider_resolution_and_staging(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import sys
+
+ from skillevaluator import provider_config
+ from skillevaluator.tier3.nemo_gym import runner as gym_runner
+
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch)
+ events = tmp_path / "preflight-events"
+ gym = os.environ["SKILL_EVAL_NEMO_GYM_BIN"]
+ wrapper = tmp_path / "gym-wrapper"
+ wrapper.write_text(
+ f"#!{sys.executable}\nimport os, sys\nfrom pathlib import Path\n"
+ "if sys.argv[1:] == ['eval', 'run', '--help']:\n"
+ f" with Path({str(events)!r}).open('a') as log: log.write('probe\\n')\n"
+ f"os.execv({gym!r}, [{gym!r}, *sys.argv[1:]])\n"
+ )
+ wrapper.chmod(0o755)
+ monkeypatch.setenv("SKILL_EVAL_NEMO_GYM_BIN", str(wrapper))
+ resolve_provider = provider_config.resolve_llm_provider
+ stage = gym_runner.stage_for_gym
+
+ def recording_provider():
+ with events.open("a") as log:
+ log.write("provider\n")
+ return resolve_provider()
+
+ def recording_stage(*args, **kwargs):
+ with events.open("a") as log:
+ log.write("stage\n")
+ return stage(*args, **kwargs)
+
+ monkeypatch.setattr(provider_config, "resolve_llm_provider", recording_provider)
+ monkeypatch.setattr(gym_runner, "stage_for_gym", recording_stage)
+ result = _run_fake_gym(skill, tmp_path, n_attempts=1, max_cases=1)
+ assert result["execution_status"] == "succeeded"
+ observed = events.read_text().splitlines()
+ assert observed.count("probe") == 1, observed
+ assert observed.index("probe") < observed.index("provider") < observed.index("stage")
+
+
+def test_gym_cli_probe_ignores_wrapped_option_prose_starting_with_tasks(tmp_path: Path) -> None:
+ from skillevaluator.tier3.nemo_gym.backend import nemo_gym_cli_error
+
+ # The 792fa142 help wraps --only-tasks at 80 columns onto a line that starts with "tasks".
+ gym = tmp_path / "gym"
+ gym.write_text(
+ "#!/bin/sh\ncat <<'HELP'\n"
+ "usage: gym eval run [-h] [--sandbox PROVIDER] [--agent AGENT] [--only-tasks PATTERNS]\n"
+ " [--model-type NAME] [--model MODEL] [--model-url MODEL_URL]\n"
+ " [--output OUTPUT] [--concurrency CONCURRENCY]\n\n"
+ "options:\n"
+ " --sandbox PROVIDER Sandbox provider.\n"
+ " --agent AGENT Agent harness.\n"
+ " --only-tasks PATTERNS\n"
+ " Comma-separated glob patterns that select the\n"
+ " tasks of a task TARGET run.\n"
+ " --model-type NAME Model server type.\n"
+ " --model MODEL Policy model.\n"
+ " --model-url MODEL_URL Policy URL.\n"
+ " --output OUTPUT Rollouts JSONL.\n"
+ " --concurrency CONCURRENCY\n"
+ " Parallel rollouts.\n"
+ "HELP\n"
+ )
+ gym.chmod(0o755)
+ error = nemo_gym_cli_error(str(gym))
+ assert error is not None and "missing: positional tasks directory." in error
+
+
+ ("option", "value", "flag"),
+ [
+ ("reuse_baseline", "latest", "--reuse-baseline"),
+ ("compare_to", "latest", "--compare-to"),
+ ("max_agent_tokens", 1000, "--max-agent-tokens"),
+ ("max_judge_calls", 5, "--max-judge-calls"),
+ ("max_attempts_total", 1, "--max-attempts-total"),
+ ("max_cost_usd", 1.0, "--max-cost-usd"),
+ ("price_file", Path("prices.json"), "--price-file"),
+ ],
+)
+def test_nemo_gym_rejects_unsupported_run_options(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, option: str, value: object, flag: str
+) -> None:
+ from skillevaluator.tier3.workflow import nemo_gym_preflight_errors
+
+ with pytest.raises(ValueError, match=re.escape(f"{flag} is not supported with --backend nemo-gym")):
+ _evaluate(monkeypatch, tmp_path, backend="nemo-gym", **{option: value})
+ errors = nemo_gym_preflight_errors(tmp_path, {"agents": "codex", "env_mode": "docker", option: value})
+ assert f"{flag} is not supported with --backend nemo-gym yet" in errors
+
+
+def test_nemo_gym_rejects_budget_config(tmp_path: Path) -> None:
+ from skillevaluator.tier3.nemo_gym.backend import nemo_gym_config_errors
+
+ (tmp_path / "evals").mkdir()
+ (tmp_path / "evals" / "config.yml").write_text("schema_version: 1\nharbor:\n max_attempts_total: 1\n")
+ assert "harbor.max_attempts_total is not supported with --backend nemo-gym yet" in nemo_gym_config_errors(tmp_path)
+ assert not any(
+ "max_attempts_total" in error
+ for error in nemo_gym_config_errors(tmp_path, run_options={"max_attempts_total": 2})
+ )
+
+
+def test_autopilot_skips_harbor_agent_preflight_for_nemo_gym(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ from click.testing import CliRunner
+
+ from skillevaluator import cli as cli_module
+ from skillevaluator.evaluation import EvaluationService
+ from skillevaluator.tier3 import workflow
+ from skillevaluator.tier3.harbor import runner
+
+ seen: list[dict[str, object]] = []
+ prepare_dataset = cli_module._ensure_autopilot_dataset
+
+ def _prepare(path, **kwargs):
+ seen.append(kwargs["evaluation_params"])
+ return prepare_dataset(path, **kwargs)
+
+ def _generate(_self, path, *, use_llm):
+ assert use_llm is True
+ (path / "evals").mkdir(exist_ok=True)
+ (path / "evals" / "evals.json").write_text(
+ json.dumps({"skill_name": "s", "evals": [{"id": "sum", "prompt": "Add 2 and 3.", "expected_output": "5"}]})
+ )
+
+ def _stop_evaluation(*_args, **_kwargs):
+ raise click.ClickException("stop after generation")
+
+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "openai")
+ monkeypatch.setenv("OPENAI_API_KEY", "test-generation-key")
+ monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
+ monkeypatch.setattr(workflow, "nemo_gym_preflight_errors", lambda *_args: [])
+ monkeypatch.setattr(
+ runner,
+ "_resolve_agent_runtime_plan",
+ lambda **_kwargs: pytest.fail("Gym must not use Harbor agent credentials"),
+ )
+ monkeypatch.setattr(
+ runner, "_check_prerequisites", lambda **_kwargs: pytest.fail("Gym must not check Harbor prerequisites")
+ )
+ monkeypatch.setattr(cli_module, "_ensure_autopilot_dataset", _prepare)
+ monkeypatch.setattr(EvaluationService, "create_autopilot_dataset", _generate)
+ monkeypatch.setattr(EvaluationService, "evaluate", _stop_evaluation)
+ (tmp_path / "SKILL.md").write_text("---\nname: s\ndescription: d\n---\n")
+ result = CliRunner().invoke(
+ cli_module.cli, ["evaluate", str(tmp_path), "--backend", "nemo-gym", "--autopilot", "--agents", "claude-code"]
+ )
+ assert "stop after generation" in result.output
+ assert (tmp_path / "evals" / "evals.json").is_file()
+ assert len(seen) == 1
+ assert seen[0]["backend"] == "nemo-gym"
+ assert seen[0]["agents"] == "claude-code"
diff --git a/tests/test_nemo_gym_main_integration.py b/tests/test_nemo_gym_main_integration.py
new file mode 100644
index 00000000..84e8929d
--- /dev/null
+++ b/tests/test_nemo_gym_main_integration.py
@@ -0,0 +1,205 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+"""New Harbor features must not silently weaken Gym execution controls."""
+
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+from tests.test_nemo_gym_backend import _evaluate, _fake_gym_skill, _run_fake_gym
+
+
+ ("option", "value"),
+ [
+ ("reuse_baseline", "latest"),
+ ("compare_to", "latest"),
+ ("max_agent_tokens", 100),
+ ("max_judge_calls", 2),
+ ("max_attempts_total", 2),
+ ("max_cost_usd", 0.25),
+ ("max_agent_tokens", 0),
+ ("max_judge_calls", 0),
+ ("max_attempts_total", 0),
+ ("max_cost_usd", 0.0),
+ ("price_file", Path("prices.json")),
+ ],
+)
+def test_gym_dispatch_rejects_unsupported_baseline_and_budget_options(monkeypatch, tmp_path, option, value):
+ with pytest.raises(ValueError, match=option.replace("_", "-")):
+ _evaluate(monkeypatch, tmp_path, backend="nemo-gym", **{option: value})
+
+
+ ("option", "value"),
+ [
+ ("reuse-baseline", "latest"),
+ ("compare-to", "latest"),
+ ("max-agent-tokens", "100"),
+ ("max-judge-calls", "2"),
+ ("max-attempts-total", "2"),
+ ("max-cost-usd", "0.25"),
+ ("max-agent-tokens", "0"),
+ ("max-judge-calls", "0"),
+ ("max-attempts-total", "0"),
+ ("max-cost-usd", "0"),
+ ("price-file", "prices.json"),
+ ],
+)
+def test_gym_direct_workflow_rejects_unsupported_options_before_generation(monkeypatch, tmp_path, option, value):
+ from skillevaluator.cli import evaluate
+ from skillevaluator.evaluation import EvaluationService
+ from skillevaluator.tier3.workflow import build_tier3_workflow
+
+ skill, _env_log = _fake_gym_skill(tmp_path, monkeypatch)
+ dataset = skill / "evals" / "evals.json"
+ dataset.unlink()
+ if option == "price-file":
+ price_file = tmp_path / value
+ price_file.write_text("{}")
+ value = str(price_file)
+ extra_args = []
+ if option == "max-cost-usd":
+ price_file = tmp_path / "prices.json"
+ price_file.write_text("{}")
+ extra_args = ["--price-file", str(price_file)]
+ monkeypatch.setattr(
+ EvaluationService,
+ "create_autopilot_dataset",
+ lambda *_args, **_kwargs: pytest.fail("unsupported Gym options must fail before generation"),
+ )
+ result = CliRunner().invoke(
+ build_tier3_workflow(evaluate),
+ [
+ str(skill),
+ "--backend",
+ "nemo-gym",
+ "--agents",
+ "codex",
+ "--progress",
+ "off",
+ f"--{option}",
+ value,
+ *extra_args,
+ ],
+ )
+ assert result.exit_code != 0, result.output
+ assert f"--{option}" in result.output, result.output
+ assert "not supported" in result.output, result.output
+ assert not dataset.exists()
+
+
+ ("option", "config"),
+ [
+ ("max_agent_tokens", "max_agent_tokens: 100"),
+ ("max_judge_calls", "max_judge_calls: 2"),
+ ("max_attempts_total", "max_attempts_total: 2"),
+ ("max_cost_usd", "max_cost_usd: 0.25\n price_file: prices.json"),
+ ("max_agent_tokens", "max_agent_tokens: 0"),
+ ("max_judge_calls", "max_judge_calls: 0"),
+ ("max_attempts_total", "max_attempts_total: 0"),
+ ("max_cost_usd", "max_cost_usd: 0\n price_file: prices.json"),
+ ("price_file", "price_file: prices.json"),
+ ("tolerate_baseline_timeouts", "tolerate_baseline_timeouts: true"),
+ ],
+)
[email protected]("entrypoint", ["runner", "workflow"])
+def test_gym_rejects_config_budget_before_generation_or_execution(monkeypatch, tmp_path, option, config, entrypoint):
+ skill, env_log = _fake_gym_skill(tmp_path, monkeypatch, f"schema_version: 1\nharbor:\n {config}\n")
+ if entrypoint == "runner":
+ result = _run_fake_gym(skill, tmp_path)
+ assert result.get("error"), result
+ assert f"harbor.{option}" in "; ".join(result["error"]), result
+ else:
+ from skillevaluator.cli import evaluate
+ from skillevaluator.evaluation import EvaluationService
+ from skillevaluator.tier3.workflow import build_tier3_workflow
+
+ dataset = skill / "evals" / "evals.json"
+ dataset.unlink()
+ monkeypatch.setattr(
+ EvaluationService,
+ "create_autopilot_dataset",
+ lambda *_args, **_kwargs: pytest.fail("unsupported Gym config must fail before generation"),
+ )
+ result = CliRunner().invoke(
+ build_tier3_workflow(evaluate),
+ [str(skill), "--backend", "nemo-gym", "--agents", "codex", "--progress", "off"],
+ )
+ assert result.exit_code != 0, result.output
+ assert f"harbor.{option}" in result.output, result.output
+ assert "not supported" in result.output, result.output
+ assert not dataset.exists()
+ assert not (tmp_path / "results").exists()
+ assert not env_log.exists()
+
+
+def test_gym_dispatch_rejects_enabled_baseline_timeout_tolerance(monkeypatch, tmp_path):
+ with pytest.raises(ValueError, match="--tolerate-baseline-timeouts is not supported with --backend nemo-gym"):
+ _evaluate(monkeypatch, tmp_path, backend="nemo-gym", tolerate_baseline_timeouts=True)
+ # Off is Gym's own behavior, so an explicit --no-tolerate-baseline-timeouts reaches the runner.
+ calls = _evaluate(monkeypatch, tmp_path, backend="nemo-gym", tolerate_baseline_timeouts=False)
+ assert calls["nemo-gym"]["tolerate_baseline_timeouts"] is False
+
+
+ ("flag", "config", "expected"),
+ [
+ (True, "", "--tolerate-baseline-timeouts is not supported"),
+ (None, "tolerate_baseline_timeouts: true", "harbor.tolerate_baseline_timeouts is not supported"),
+ (False, "tolerate_baseline_timeouts: true", None),
+ (None, "tolerate_baseline_timeouts: false", None),
+ ],
+)
+def test_gym_preflight_baseline_timeout_tolerance_flag_overrides_config(tmp_path, flag, config, expected):
+ from skillevaluator.tier3.workflow import nemo_gym_preflight_errors
+
+ (tmp_path / "evals").mkdir()
+ (tmp_path / "evals" / "config.yml").write_text(f"schema_version: 1\nharbor:\n {config}\n" if config else "")
+ params = {"agents": "codex", "env_mode": "docker", "tolerate_baseline_timeouts": flag}
+ tolerance_errors = [error for error in nemo_gym_preflight_errors(tmp_path, params) if "tolerate" in error]
+ assert tolerance_errors == ([f"{expected} with --backend nemo-gym yet"] if expected else [])
+
+
+def test_gym_runner_rejects_enabled_tolerance_but_lets_the_flag_override_config(monkeypatch, tmp_path):
+ skill, env_log = _fake_gym_skill(
+ tmp_path, monkeypatch, "schema_version: 1\nharbor:\n tolerate_baseline_timeouts: true\n"
+ )
+ rejected = _run_fake_gym(skill, tmp_path, tolerate_baseline_timeouts=True)
+ assert "--tolerate-baseline-timeouts is not supported with --backend nemo-gym yet" in rejected["error"], rejected
+ assert not any("harbor.tolerate_baseline_timeouts" in error for error in rejected["error"]), rejected
+ assert not (tmp_path / "results").exists()
+ assert not env_log.exists()
+
+ allowed = _run_fake_gym(skill, tmp_path, tolerate_baseline_timeouts=False)
+ assert allowed.get("execution_status") == "succeeded", allowed
+
+
+ "runtime_env",
+ ["FOO: ${SKILL_EVAL_TEST_UNSET_RUNTIME_VAR}", "MY_API_KEY: ${SKILL_EVAL_TEST_UNSET_RUNTIME_VAR}"],
+)
+def test_gym_rejects_bad_runtime_env_before_reserving_a_run_folder(monkeypatch, tmp_path, runtime_env):
+ monkeypatch.delenv("SKILL_EVAL_TEST_UNSET_RUNTIME_VAR", raising=False)
+ skill, env_log = _fake_gym_skill(
+ tmp_path, monkeypatch, f"schema_version: 1\nharbor:\n runtime_env:\n {runtime_env}\n"
+ )
+ result = _run_fake_gym(skill, tmp_path)
+ assert result.get("error"), result
+ assert not (tmp_path / "results").exists()
+ assert not env_log.exists()
+
+
[email protected](("cli_value", "config"), [(0, ""), (None, "schema_version: 1\nharbor:\n max_agents: 0\n")])
+def test_gym_rejects_max_agents_below_one_like_harbor(monkeypatch, tmp_path, cli_value, config):
+ skill, env_log = _fake_gym_skill(tmp_path, monkeypatch, config)
+ result = _run_fake_gym(skill, tmp_path, max_agents=cli_value)
+ assert "max_agents must be >= 1" in "; ".join(result.get("error") or []), result
+ assert not (tmp_path / "results").exists()
+ assert not env_log.exists()
+
+
+def test_gym_dispatch_passes_max_agents(monkeypatch, tmp_path):
+ calls = _evaluate(monkeypatch, tmp_path, backend="nemo-gym", max_agents=3)
+ assert calls["nemo-gym"]["max_agents"] == 3
diff --git a/tests/tier3/test_failed_skill_reads.py b/tests/tier3/test_failed_skill_reads.py
index e69ea0de..7164e9e9 100644
--- a/tests/tier3/test_failed_skill_reads.py
+++ b/tests/tier3/test_failed_skill_reads.py
@@ -131,6 +131,29 @@ def test_failed_compound_shell_read_keeps_credit(grader, command) -> None:
assert scorer.check_routing([read], "demo-skill")["score"] == 1.0
+ "command",
+ (
+ "/bin/bash -lc 'cat /skills/demo-skill/SKILL.md'",
+ "bash -c 'cat /skills/demo-skill/SKILL.md'",
+ ),
+)
+def test_failed_wrapped_shell_read_is_not_activation(grader, command) -> None:
+ _, scorer = grader
+ read = {
+ "action": "Bash",
+ "action_input": {"command": command},
+ "observation": "cat: /skills/demo-skill/SKILL.md: No such file or directory",
+ "is_error": True,
+ }
+ execute = {"action": "Bash", "action_input": {"command": "python scripts/run.py"}, "observation": "ok"}
+ assert scorer.check_activation([read], "demo-skill")["score"] == 0.0
+ assert scorer.check_routing([read], "demo-skill")["score"] == 0.0
+ assert scorer.check_workflow_order([read, execute], expected_skill="demo-skill")["score"] == 0.0
+ wrapped_compound = {**read, "action_input": {"command": "bash -lc 'cat /skills/demo-skill/SKILL.md && ls'"}}
+ assert scorer.check_activation([wrapped_compound], "demo-skill")["score"] == 0.75
+
+
def test_failed_native_skill_call_is_not_activation(grader) -> None:
extractor, scorer = grader
trajectory = {
diff --git a/tests/tier3/test_plugin_signals.py b/tests/tier3/test_plugin_signals.py
index d6a5e191..030528f2 100644
--- a/tests/tier3/test_plugin_signals.py
+++ b/tests/tier3/test_plugin_signals.py
@@ -395,12 +395,17 @@ class TestShellReadsAgainstTheScoredCheck:
@pytest.mark.parametrize(
"command",
- ["sudo cat skills/alpha/SKILL.md", "bash -lc 'cat skills/alpha/SKILL.md'", "tac skills/alpha/SKILL.md"],
+ ["sudo cat skills/alpha/SKILL.md", "tac skills/alpha/SKILL.md"],
)
def test_lenient_reads_credit_the_member_but_not_the_score(self, command: str) -> None:
assert not checks._cmd_reads_skill_md(command)
assert self._credited(command) == ["alpha"]
+ def test_shell_wrapped_reads_credit_the_member_and_the_score(self) -> None:
+ command = "bash -lc 'cat skills/alpha/SKILL.md'"
+ assert checks._cmd_reads_skill_md(command)
+ assert self._credited(command) == ["alpha"]
+
def test_shell_variables_are_expanded_only_by_the_scored_check(self) -> None:
command = "D=skills/alpha; cat $D/SKILL.md"
assert checks._cmd_reads_skill_md(command)