Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
feat(tier3): let installed packages add custom execution backends (#215)
Roshni Malani7adf7f177c58
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 211d3f89..8820f38d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,16 @@ All notable changes to SkillEvaluator are documented in this file.### Added+- Custom execution backends. An installed package can add an `--env-mode`+ through the `skillevaluator.env_modes` entry-point group, naming an+ `EnvironmentBackendSpec` with a Harbor environment class plus the `--ek`+ kwargs, host variables, prerequisite hook, and optional agent wrappers that+ backend accepts. Custom execution backends follow the same kwarg and+ `runtime_env` policy as Harbor-native backends, may not forward agent,+ provider, or other backends' credentials, cannot replace a built-in mode or+ share a name with another installed package, are not named on published+ benchmark cards, and can be turned off with+ `SKILLEVALUATOR_DISABLE_CUSTOM_BACKENDS=1`.- Optional `skillevaluator dashboard` tables for comparing saved Tier 3 reportsand retained runs across skills, models, harnesses, recorded harnessfeatures, and skill conditions. Paired with/without differences cover score,diff --git a/docs/agents-and-sandboxes.mdx b/docs/agents-and-sandboxes.mdxindex 3a64e2a2..33c4c8d0 100644--- a/docs/agents-and-sandboxes.mdx+++ b/docs/agents-and-sandboxes.mdx@@ -166,6 +166,9 @@ the environment extra shown below when a managed backend needs one.| `mosaic` | Harbor-native | `harbor[mosaic]==0.24.0` || `local` | SkillEvaluator | Your machine, under an OS sandbox policy — see [Local mode](#local-mode). |+Installed packages can add more modes, for example an organization's internal+sandbox service. See [Custom execution backends](#custom-execution-backends).+<Tip>SkillEvaluator documents setup for `docker`, `kata`, and `local`. For any otherbackend, install the mapped Harbor extra or system CLI shown above, set the@@ -325,6 +328,102 @@ embedded credential URI, or raw secret value is rejected:Complex values use JSON syntax in the `KEY=VALUE` argument. Reference namesmust be trimmed and bounded; they cannot contain credential-bearing URIs.+## Custom execution backends++A Python package can add an `--env-mode` that runs trials on infrastructure+Harbor does not ship, without changing SkillEvaluator. The package registers+an entry point in the `skillevaluator.env_modes` group. The entry-point name+becomes the mode name, and its value names an `EnvironmentBackendSpec` (or a+function that returns one):++```toml+# pyproject.toml of the backend package+[project.entry-points."skillevaluator.env_modes"]+acme = "skillevaluator_acme.backend:SPEC"+```++```python+# skillevaluator_acme/backend.py+from skillevaluator.tier3_environments import EnvironmentBackendSpec++SPEC = EnvironmentBackendSpec(+ import_path="skillevaluator_acme.environment:AcmeEnvironment",+ environment_kwargs=frozenset({"profile", "lease_seconds"}),+ required_environment_kwargs=("profile",),+ host_env_vars=frozenset({"ACME_SANDBOX_URL", "ACME_SANDBOX_TOKEN"}),+ prerequisites="skillevaluator_acme.checks:prerequisites",+ install_hint="Install 'skillevaluator-acme' from your package index.",+)+```++`import_path` names a Harbor `BaseEnvironment` subclass. SkillEvaluator passes+it to `harbor run --env`, so the class receives the same evaluator-staged task+directory, verifier, and trial paths as a Harbor-native backend.++### What a backend must provide++- Support the Harbor release SkillEvaluator pins (`harbor==0.24.0`), including+ its environment constructor options.+- Run the evaluator-staged image: build each task's `environment/Dockerfile` as+ written, or an equivalent image with the same layers. Do not substitute a+ generic image.+- Preserve the task workspace: `/workspace` with the staged skills under the+ task's `skills_dir`, task input, and the agent working directory.+- Preserve the verifier contract: run `tests/` with the verifier environment+ SkillEvaluator stages, and return `/logs/verifier` and `/logs/agent`+ (including the trajectory) to the host.+- Clean up every trial resource, including after cancellation.++The acceptance test for a backend is a full SkillEvaluator Tier 3 run of a+skill with both the baseline and with-skill conditions on that backend. The+run must produce the expected scores, retain trajectories and verifier+artifacts, and leave no trial resources behind. Compare the results with the+same skill on `--env-mode docker`.++### Policy SkillEvaluator applies++A custom execution backend follows the same policy as the Harbor-native+backends:++- `--ek` accepts only the names in `environment_kwargs`. Names in+ `reserved_environment_kwargs`, SkillEvaluator's runtime-policy kwargs such as+ `network_policy` and `session_id`, and secret-bearing names or values are+ rejected.+- Only the upper-case variables in `host_env_vars` reach the Harbor process,+ in addition to the usual proxy, CA bundle, and locale variables. A skill's+ `harbor.runtime_env` cannot set them. A backend cannot forward agent or+ provider credentials (for example `ANTHROPIC_*`, `CLAUDE_*`, `CODEX_*`,+ `OPENAI_*`, `OPENCODE_*`, `NVIDIA_*`, `AWS_*`, `GITHUB_*`, `GH_*`, `HF_*`),+ another backend's credentials, judge settings, or process-control variables,+ because Harbor's stock agents read some of them and can copy them into the+ trial sandbox. `KUBECONFIG` is allowed. The runner supplies agent credentials+ per agent as it does for every backend.+- Harbor runs in a private working directory, so list host variables and `--ek`+ kwargs that hold file paths in `host_path_env_vars` and+ `host_path_environment_kwargs`; relative values are made absolute first.+- `skillevaluator doctor --env-mode <mode>` checks+ `required_environment_kwargs`, then runs the optional `prerequisites`+ function (`fn(environment_kwargs) -> list[str]`), then the environment+ class's Harbor `preflight()`. Diagnostics are redacted like built-in ones.+- Tasks with a `docker-compose.yaml` are rejected unless the backend sets+ `supports_docker_compose=True`.+- `agent_import_paths` may map an agent name to a Harbor agent class, for+ example one that uses a CLI already installed in the backend's image.+ Agents without an entry use Harbor's stock agent. When the evaluator+ provider needs its own wrapper (for example `SkillEvaluatorGatewayCodex` for+ Codex with an OpenAI-compatible gateway), the backend's class must subclass+ that wrapper; otherwise the run stops before any trial starts.++A custom execution backend cannot replace a built-in mode name, and a name+registered by more than one installed package is refused with every package+name until all but one is uninstalled. Listing the available modes reads+package metadata only; the backend module is imported when its mode is+selected. Published benchmark cards show a custom execution backend as+`Isolated sandbox` and do not name it. Set+`SKILLEVALUATOR_DISABLE_CUSTOM_BACKENDS=1` to ignore every installed custom+execution backend. Backend packages run with your privileges, so install only+ones you trust.+## Docker modeThe default path needs a running Docker daemon and Docker Compose v2 —diff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdxindex fda94771..e04cc5a5 100644--- a/docs/cli-reference.mdx+++ b/docs/cli-reference.mdx@@ -387,7 +387,7 @@ Use `skillevaluator tier3 PATH` for the complete workflow with automatic missing| Flag | Default | Effect || --- | --- | --- || `-a, --agents TEXT` | provider-native | Comma-separated Harbor agents. Defaults: NVIDIA Build=`opencode`, OpenAI=`codex`, Anthropic=`claude-code`. Supported: `claude-code`, `codex`, `opencode`; the alias `claude` is accepted for `claude-code`. See [Agents & Sandboxes](agents-and-sandboxes.mdx). |-| `--env-mode` | `docker` | Where trials run. SkillEvaluator exposes 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.24.0` extra; Harbor 0.24 has no `wandb` extra. Harbor's `cua-cloud`, `opensandbox`, `hf-sandbox`, `podman`, `prime`, and `smol` backends are not selectable. See the complete extras and prerequisites matrix in [Agents & Sandboxes](agents-and-sandboxes.mdx#where-trials-run). |+| `--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.24.0` extra; Harbor 0.24 has no `wandb` extra. Harbor's `cua-cloud`, `opensandbox`, `hf-sandbox`, `podman`, `prime`, and `smol` backends are not selectable. See the complete extras and prerequisites matrix in [Agents & Sandboxes](agents-and-sandboxes.mdx#where-trials-run). Installed packages can add more modes; see [Custom execution backends](agents-and-sandboxes.mdx#custom-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`, and `auth` for `cwsandbox`/`wandb`. Names the selected backend does not accept in Harbor 0.24.0 are rejected. See [Native backend constructor options](agents-and-sandboxes.mdx#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). |diff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.pyindex 1b3f7cae..b906a7bb 100644--- a/src/skillevaluator/cli.py+++ b/src/skillevaluator/cli.py@@ -56,7 +56,7 @@ from skillevaluator.tier1.commands import (run_security_scan,run_validation,)-from skillevaluator.tier3_environments import HARBOR_ENVIRONMENTS+from skillevaluator.tier3_environments import all_env_modesfrom skillevaluator.tier_group import TierGroupfrom skillevaluator.utils.path_security import resolve_repo_context_rootfrom skillevaluator.utils.rich_markup import escape_markup, strip_terminal_controls@@ -69,7 +69,7 @@ from skillevaluator.utils.tier2_paths import (CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]}-ENV_MODE_CHOICE = click.Choice(list(HARBOR_ENVIRONMENTS))+ENV_MODE_CHOICE = click.Choice(list(all_env_modes()))class _AliasChoice(click.Choice):diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.pyindex d75392db..1bbf4343 100644--- a/src/skillevaluator/tier3/harbor/runner.py+++ b/src/skillevaluator/tier3/harbor/runner.py@@ -166,7 +166,12 @@ from skillevaluator.tier3_environments import (HARBOR_ENVIRONMENT_KWARGS,HARBOR_VERSION,SKILLEVALUATOR_GKE_EXTRA_ENVIRONMENT_KWARGS,+ EnvironmentBackendError,+ EnvironmentBackendSpec,+ custom_backend_names,harbor_environment_type,+ is_env_mode,+ load_custom_backend,)from skillevaluator.utils.path_security import matches_filesystem_namefrom skillevaluator.utils.redaction import is_sensitive_key, redact_sensitive_text@@ -1180,6 +1185,91 @@ def is_operator_owned_or_provider_secret(name: str) -> bool:return upper.startswith(_OPERATOR_SECRET_PREFIXES)+# Harbor's stock agents read these from the Harbor process and can copy them into+# the trial sandbox, so a backend may never forward them.+_BACKEND_REFUSED_HOST_ENV_PREFIXES = (+ "ANTHROPIC_",+ "CLAUDE_",+ "CODEX_",+ "GEMINI_",+ "GH_",+ "GITHUB_",+ "GITLAB_",+ "HF_",+ "HUGGING_FACE_",+ "OPENAI_",+ "OPENCODE_",+)+# Shared, non-secret cluster configuration a Kubernetes-backed backend may need.+_BACKEND_ALLOWED_SHARED_HOST_ENV = frozenset({"KUBECONFIG"})+++def _backend_may_forward(name: str) -> bool:+ upper = name.upper()+ if upper in _HARBOR_BASE_ENV_VARS or upper in _BACKEND_ALLOWED_SHARED_HOST_ENV:+ return True+ other_backend_secret = any(+ upper in names and is_sensitive_key(upper) for names in _HARBOR_ENV_MODE_VARS.values()+ )+ return not (+ upper in _OPERATOR_OWNED_AGENT_ENV+ or upper in _RUNTIME_ENV_HOST_CONTROL_NAMES+ or upper.startswith(_RUNTIME_ENV_HOST_CONTROL_PREFIXES)+ or upper.startswith(_BACKEND_REFUSED_HOST_ENV_PREFIXES)+ or is_operator_owned_or_provider_secret(upper)+ or other_backend_secret+ )+++def _custom_backend(env_mode: str) -> EnvironmentBackendSpec | None:+ """Load an installed ``--env-mode`` backend and check the host variables it forwards."""+ try:+ backend = load_custom_backend(env_mode)+ except EnvironmentBackendError as exc:+ # Import and factory failures can quote backend configuration such as+ # endpoint URLs with credentials; redact them like preflight failures.+ detail = redact_progress_detail(str(exc), secret_values=secret_values_from_environment(os.environ))+ raise EnvironmentBackendError(detail or f"Custom execution backend '{env_mode}' could not be loaded") from None+ if backend is None:+ return None+ # A backend forwards its own backend settings only. Agent, provider, and other+ # backends' credentials, judge settings, and process-control variables stay+ # under evaluator policy.+ blocked = sorted(name for name in backend.host_env_vars if not _backend_may_forward(name))+ if blocked:+ raise EnvironmentBackendError(+ f"Custom execution backend '{env_mode}' may not forward evaluator-owned variable(s): {', '.join(blocked)}"+ )+ return backend+++def _env_mode_host_path_env_vars(env_mode: str) -> frozenset[str]:+ """Return a backend's host variables that name files, anchored before Harbor changes directory."""+ if env_mode in _HARBOR_ENV_MODE_VARS:+ return frozenset()+ try:+ backend = _custom_backend(env_mode)+ except EnvironmentBackendError:+ return frozenset()+ return backend.host_path_env_vars if backend is not None else frozenset()+++def _supported_env_modes() -> frozenset[str]:+ return HARBOR_ENV_MODES | frozenset(custom_backend_names())+++def _env_mode_host_env_vars(env_mode: str) -> frozenset[str]:+ """Return the backend host variables forwarded to Harbor for ``env_mode``."""+ if env_mode in _HARBOR_ENV_MODE_VARS:+ return _HARBOR_ENV_MODE_VARS[env_mode]+ try:+ backend = _custom_backend(env_mode)+ except EnvironmentBackendError:+ # Prerequisite checks report the load failure before any run starts.+ return frozenset()+ return backend.host_env_vars if backend is not None else frozenset()++def is_gke_vertex_workload_identity_active(env_mode: str,agents: Sequence[str] = ("claude-code",),@@ -1304,7 +1394,10 @@ def _harbor_launch_environment(env: Mapping[str, str]) -> dict[str, str]:def _absolute_host_path_kwargs(env_mode: str, environment_kwargs: Mapping[str, Any]) -> dict[str, Any]:"""Anchor relative host-path constructor kwargs before Harbor changes directory."""anchored = dict(environment_kwargs)- for name in _HOST_PATH_ENVIRONMENT_KWARGS.get(env_mode, frozenset()) & anchored.keys():+ path_kwargs = _HOST_PATH_ENVIRONMENT_KWARGS.get(env_mode, frozenset())+ if env_mode not in _HOST_PATH_ENVIRONMENT_KWARGS and (backend := _custom_backend(env_mode)) is not None:+ path_kwargs = backend.host_path_environment_kwargs+ for name in path_kwargs & anchored.keys():if isinstance(anchored[name], str):anchored[name] = _absolute_host_path(anchored[name])return anchored@@ -1495,9 +1588,19 @@ def _environment_kwarg_policy_error(env_mode: str, environment_kwargs: Mapping[sreturn "Environment kwargs are not supported for SkillEvaluator Docker mode"if env_mode == ENV_MODE_LOCAL:return "Environment kwargs are not supported for SkillEvaluator local mode"+ try:+ backend = _custom_backend(env_mode)+ except EnvironmentBackendError as exc:+ return str(exc)reserved = _HARBOR_RUNTIME_POLICY_KWARGS | _HARBOR_ENVIRONMENT_RUNTIME_POLICY_KWARGS.get(env_mode, frozenset())+ if backend is not None:+ reserved = reserved | backend.reserved_environment_kwargsif collisions := sorted(reserved & environment_kwargs.keys()):return "Environment kwarg(s) reserved for Harbor runtime policy: " + ", ".join(collisions)+ if backend is not None:+ if unknown := sorted(environment_kwargs.keys() - backend.environment_kwargs):+ return f"Custom execution backend '{env_mode}' does not accept environment kwarg(s): " + ", ".join(unknown)+ return Noneallowed_kwargs = HARBOR_ENVIRONMENT_KWARGS[env_mode]if env_mode == "gke":allowed_kwargs = allowed_kwargs | SKILLEVALUATOR_GKE_EXTRA_ENVIRONMENT_KWARGS@@ -1544,6 +1647,16 @@ def _kata_environment_kwarg_error(environment_kwargs: Mapping[str, Any]) -> strdef _staged_task_environment_error(env_mode: str, task_dirs: Iterable[Path]) -> str | None:"""Reject staged task environments the selected backend cannot run."""+ if (backend := _custom_backend(env_mode)) is not None:+ if backend.supports_docker_compose:+ return None+ for task_dir in task_dirs:+ if (task_dir / "environment" / "docker-compose.yaml").exists():+ return (+ f"Custom execution backend '{env_mode}' cannot run Docker Compose task '{task_dir.name}'; "+ "use a Dockerfile-only environment or another backend."+ )+ return Noneif env_mode == "mosaic":for task_dir in task_dirs:if (task_dir / "environment" / "docker-compose.yaml").exists():@@ -1632,14 +1745,16 @@ def build_harbor_run_command(verifier_env: Mapping[str, str] | None = None,environment_kwargs: Mapping[str, Any] | None = None,) -> list[str]:- """Build a Harbor invocation for a built-in environment type or local mode."""- if env_mode not in HARBOR_ENV_MODES:- raise ValueError(f"env_mode must be one of: {', '.join(sorted(HARBOR_ENV_MODES))}")+ """Build a Harbor invocation for a built-in or backend environment, or local mode."""+ if not is_env_mode(env_mode):+ raise ValueError(f"env_mode must be one of: {', '.join(sorted(_supported_env_modes()))}")+ backend = _custom_backend(env_mode)timeout_multiplier = _validated_timeout_multiplier(timeout_multiplier)if (agent_import_pathand env_mode not in HARBOR_DOCKER_ENGINE_ENV_MODES | {ENV_MODE_LOCAL}and agent_import_path not in _NATIVE_BACKEND_AGENT_IMPORT_PATHS+ and (backend is None or agent_import_path not in backend.agent_import_paths.values())):raise ValueError("agent_import_path is supported only with --env docker, kata, or local")validated_environment_kwargs = validate_environment_kwargs(@@ -1709,12 +1824,16 @@ def build_harbor_run_command(else:env_import_path = SECURE_DOCKER_ENV_IMPORT_PATHcommand.extend(["--env", env_import_path])+ elif backend is not None:+ command.extend(["--agent", agent_import_path or backend.agent_import_paths.get(agent, agent)])+ command.extend(["--env", backend.import_path])else:command.extend(["--agent", agent_import_path or agent, "--env", harbor_environment_type(env_mode)])for name, value in sorted(_harbor_agent_kwargs(agent, model, env_mode).items()):command.extend(["--ak", encode_environment_kwarg(name, value)])for name, value in sorted(validated_environment_kwargs.items()):- if name == "allow_workload_identity":+ # A SkillEvaluator GKE wrapper option, not a Harbor constructor kwarg.+ if env_mode == "gke" and name == "allow_workload_identity":continuecommand.extend(["--ek", encode_environment_kwarg(name, value)])# Alias kwargs come after operator kwargs, which may never set them.@@ -2018,7 +2137,9 @@ def _environment_kwarg_prerequisite_errors(return [name for name in names if not isinstance(kwargs.get(name), str) or not kwargs[name].strip()]required: tuple[str, ...] = ()- if env_mode == "gke":+ if (backend := _custom_backend(env_mode)) is not None:+ required = backend.required_environment_kwargs+ elif env_mode == "gke":required = ("cluster_name", "region", "namespace", "registry_location", "registry_name")elif env_mode == "ack":required = ("namespace",)@@ -2121,6 +2242,14 @@ def _cwsandbox_prerequisite_errors(env_mode: str) -> list[str]:def _environment_extra_install_hint(env_mode: str) -> str:+ if env_mode not in HARBOR_ENV_MODES and env_mode in custom_backend_names():+ try:+ backend = _custom_backend(env_mode)+ except EnvironmentBackendError:+ backend = None+ if backend is not None and backend.install_hint:+ return backend.install_hint+ return f"Reinstall the package that provides custom execution backend '{env_mode}'."extra = HARBOR_ENVIRONMENT_EXTRAS.get(env_mode)if extra is not None:return f"Install 'harbor[{extra}]=={HARBOR_VERSION}'."@@ -2273,6 +2402,53 @@ def _python_dotenv_prerequisite_error() -> str | None:)+def _custom_backend_prerequisite_errors(+ env_mode: str,+ backend: EnvironmentBackendSpec,+ environment_kwargs: Mapping[str, Any] | None,+) -> list[str]:+ """Run a backend's own prerequisite hook, then its environment class's Harbor ``preflight``."""+ secret_values = secret_values_from_environment(os.environ)+ try:+ # Import the environment module first so a missing backend SDK is reported+ # with the backend's install hint rather than as a generic preflight failure.+ importlib.import_module(backend.import_path.partition(":")[0])+ if backend.prerequisites is not None:+ from harbor.utils.import_path import import_symbol++ check = import_symbol(backend.prerequisites)+ errors = check(dict(environment_kwargs or {}))+ if not isinstance(errors, list | tuple) or not all(isinstance(error, str) for error in errors):+ return [f"Custom execution backend '{env_mode}' prerequisite hook must return a list of strings"]+ if errors:+ return [redact_progress_detail(error, secret_values=secret_values) or error for error in errors]+ from harbor.environments.factory import EnvironmentFactory++ EnvironmentFactory.run_preflight(None, import_path=backend.import_path)+ except ImportError as exc:+ detail = redact_progress_detail(_harbor_missing_dependency_summary(exc), secret_values=secret_values)+ return [+ f"Custom execution backend '{env_mode}' needs optional dependencies: {detail}. "+ f"{_environment_extra_install_hint(env_mode)}"+ ]+ except SystemExit as exc:+ detail = redact_progress_detail(exc, secret_values=secret_values) or "preflight exited without a diagnostic"+ return [f"Custom execution backend '{env_mode}' is not ready: {detail}"]+ except Exception as exc:+ if isinstance(exc.__cause__, ImportError):+ # Harbor's import_symbol wraps import failures in ValueError.+ detail = redact_progress_detail(+ _harbor_missing_dependency_summary(exc.__cause__), secret_values=secret_values+ )+ return [+ f"Custom execution backend '{env_mode}' needs optional dependencies: {detail}. "+ f"{_environment_extra_install_hint(env_mode)}"+ ]+ detail = redact_progress_detail(exc, secret_values=secret_values)+ return [f"Custom execution backend '{env_mode}' is not ready: {detail}"]+ return []++def _check_prerequisites(env_mode: str = DEFAULT_ENV_MODE,agents: list[str] | None = None,@@ -2280,9 +2456,15 @@ def _check_prerequisites(verify_live_cluster: bool = False,subprocess_env: Mapping[str, str] | None = None,) -> list[str]:- """Check Harbor and the selected environment (built-in, GKE, or local mode)."""- if env_mode not in HARBOR_ENV_MODES:- return [f"Unsupported Harbor environment '{env_mode}'. Choose one of: {', '.join(sorted(HARBOR_ENV_MODES))}"]+ """Check Harbor and the selected environment (built-in, backend, GKE, or local mode)."""+ if not is_env_mode(env_mode):+ return [+ f"Unsupported Harbor environment '{env_mode}'. Choose one of: {', '.join(sorted(_supported_env_modes()))}"+ ]+ try:+ _custom_backend(env_mode)+ except EnvironmentBackendError as exc:+ return [f"{exc}. {_environment_extra_install_hint(env_mode)}"]if dotenv_error := _python_dotenv_prerequisite_error():return [dotenv_error]if env_mode != "gke" and (kwarg_errors := _environment_kwarg_prerequisite_errors(env_mode, environment_kwargs)):@@ -2301,6 +2483,9 @@ def _check_prerequisites('uv tool install "skillevaluator[all] @ git+https://github.com/NVIDIA/SkillEvaluator.git"']+ if (backend := _custom_backend(env_mode)) is not None:+ return _custom_backend_prerequisite_errors(env_mode, backend, environment_kwargs)+if env_mode == "gke":gke_errors = list(_environment_kwarg_prerequisite_errors(env_mode, environment_kwargs))if not shutil.which("gcloud"):@@ -2491,7 +2676,7 @@ def _is_operator_owned_runtime_name(name: str, *, env_mode: str = DEFAULT_ENV_MOnormalized = name.upper()if (normalized in _RUNTIME_ENV_HOST_CONTROL_NAMES- or normalized in _HARBOR_ENV_MODE_VARS.get(env_mode, frozenset())+ or normalized in _env_mode_host_env_vars(env_mode)or normalized in _OPERATOR_OWNED_AGENT_ENVor normalized.startswith(_RUNTIME_ENV_HOST_CONTROL_PREFIXES)or is_operator_owned_or_provider_secret(name)@@ -2563,7 +2748,9 @@ def _harbor_subprocess_environment("""Build Harbor's minimal host environment without ambient secrets."""host_env = os.environenvironment = _selected_host_environment(_HARBOR_BASE_ENV_VARS, host_env)- environment.update(_selected_host_environment(_HARBOR_ENV_MODE_VARS.get(env_mode, frozenset()), host_env))+ environment.update(_selected_host_environment(_env_mode_host_env_vars(env_mode), host_env))+ for name in _env_mode_host_path_env_vars(env_mode) & environment.keys():+ environment[name] = _absolute_host_path(environment[name])if provider.provider == "bedrock":environment.update(_selected_host_environment(_BEDROCK_HOST_ENV_VARS, host_env))is_adc = (@@ -3157,6 +3344,30 @@ def _model_for_agent(def _agent_import_path(provider: ProviderConfig, agent: str, env_mode: str) -> str | None:+ """Select the agent wrapper the provider and the execution backend both require."""+ required = _provider_agent_import_path(provider, agent, env_mode)+ backend = None if env_mode in HARBOR_ENV_MODES else _custom_backend(env_mode)+ if backend is None or (selected := backend.agent_import_paths.get(agent)) is None:+ return required+ if required is None or selected == required:+ return selected+ # The provider needs its wrapper's routing; a backend wrapper may adapt setup+ # only by extending that wrapper, never by silently replacing it.+ from harbor.utils.import_path import import_symbol++ try:+ compatible = issubclass(import_symbol(selected), import_symbol(required))+ except (ImportError, TypeError, ValueError) as exc:+ raise ValueError(f"Custom execution backend '{env_mode}' agent wrapper {selected} could not be checked: {exc}") from None+ if not compatible:+ raise ValueError(+ f"Custom execution backend '{env_mode}' runs {agent} with {selected}, but the {provider.provider} "+ f"provider requires {required}; the backend wrapper must subclass it"+ )+ return selected+++def _provider_agent_import_path(provider: ProviderConfig, agent: str, env_mode: str) -> str | None:"""Select only the provider-specific wrappers required for this environment."""if provider.provider == "openai-compatible" and agent == "codex" and env_mode != ENV_MODE_LOCAL:return _GATEWAY_CODEX_IMPORT_PATH@@ -4344,9 +4555,9 @@ def _run_harbor_eval_impl(forwarded = dict(locals()) if _evaluator_skill_path is None else Nonestarted_at = _monotonic_start if _monotonic_start is not None else time.monotonic()reporter = safe_progress_reporter(progress_reporter or NullProgressReporter())- if env_mode not in HARBOR_ENV_MODES:+ if not is_env_mode(env_mode):reporter.emit(ProgressEvent(stage="configuration", state="failed", detail="unsupported environment"))- return {"error": [f"env_mode must be one of: {', '.join(sorted(HARBOR_ENV_MODES))}"]}+ return {"error": [f"env_mode must be one of: {', '.join(sorted(_supported_env_modes()))}"]}if not agents:reporter.emit(ProgressEvent(stage="configuration", state="failed", detail="no agents selected"))return {"error": ["At least one Harbor agent is required."]}@@ -4570,11 +4781,15 @@ def _run_harbor_eval_impl(except ValueError as exc:reporter.emit(ProgressEvent(stage="credential-validation", state="failed", detail=str(exc)))return {"error": [str(exc)]}- agent_import_paths = {- agent: import_path- for agent in agents- if (import_path := _agent_import_path(provider, agent, env_mode)) is not None- }+ try:+ agent_import_paths = {+ agent: import_path+ for agent in agents+ if (import_path := _agent_import_path(provider, agent, env_mode)) is not None+ }+ except (EnvironmentBackendError, ValueError) as exc:+ reporter.emit(ProgressEvent(stage="credential-validation", state="failed", detail=str(exc)))+ return {"error": [str(exc)]}runtime_secret_values = set().union(*(secret_values_from_environment(plan.subprocess_env) for plan in runtime_plans.values()))diff --git a/src/skillevaluator/tier3_environments.py b/src/skillevaluator/tier3_environments.pyindex bf63048c..2cfb017c 100644--- a/src/skillevaluator/tier3_environments.py+++ b/src/skillevaluator/tier3_environments.py@@ -1,14 +1,25 @@# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.# SPDX-License-Identifier: Apache-2.0-"""Built-in Harbor environment names available in the public Tier 3 surface.+"""Harbor environment names available in the public Tier 3 surface.This deliberately lives outside the Tier 3 package so that the base CLI canshow its command help without importing Harbor or any optional dependencies.+Installed packages may add modes through the ``skillevaluator.env_modes``+entry-point group; listing them reads package metadata only."""from __future__ import annotations+import os+import re+from collections.abc import Mapping+from dataclasses import dataclass, field+from functools import cache, lru_cache+from importlib.metadata import EntryPoint, entry_points+from types import MappingProxyType+from typing import Any+#: The exact Harbor release whose CLI, models, and environment interfaces this#: SkillEvaluator release targets; the ``tier3`` extra pins it.HARBOR_VERSION = "0.24.0"@@ -220,3 +231,187 @@ for _alias, _harbor_type in HARBOR_ENVIRONMENT_TYPE_ALIASES.items():SKILLEVALUATOR_GKE_EXTRA_ENVIRONMENT_KWARGS = frozenset({"allow_workload_identity", "autopilot"})ENV_MODE_LOCAL = "local"DEFAULT_ENV_MODE = "docker"+++# ---------------------------------------------------------------------------+# Custom execution backends+# ---------------------------------------------------------------------------++#: Entry-point group through which an installed package adds an ``--env-mode``.+#: The entry-point name is the mode name; its value names an ``EnvironmentBackendSpec``+#: instance, or a zero-argument callable that returns one.+ENV_MODE_ENTRY_POINT_GROUP = "skillevaluator.env_modes"+#: Set to ``1`` to ignore every installed custom execution backend.+DISABLE_CUSTOM_BACKENDS_ENV = "SKILLEVALUATOR_DISABLE_CUSTOM_BACKENDS"++_BACKEND_NAME_RE = re.compile(r"[a-z][a-z0-9]*(?:-[a-z0-9]+)*")+_IMPORT_PATH_RE = re.compile(r"[A-Za-z_][\w.]*:[A-Za-z_]\w*")+# Upper case only: SkillEvaluator compares host variable names case-insensitively.+_HOST_ENV_VAR_RE = re.compile(r"[A-Z_][A-Z0-9_]*")+++class EnvironmentBackendError(ValueError):+ """An installed custom execution backend could not be loaded or is malformed."""+++@dataclass(frozen=True)+class EnvironmentBackendSpec:+ """Describe one ``--env-mode`` that an installed package contributes.++ SkillEvaluator dispatches the mode to Harbor through ``--env IMPORT_PATH``+ and applies the same kwarg, credential, and runtime-env policy it applies to+ Harbor-native backends. The backend module is imported only when its mode is+ selected, so it may import Harbor at module level.+ """++ #: Harbor ``BaseEnvironment`` subclass, as ``package.module:ClassName``.+ import_path: str+ #: Constructor kwargs operators may pass with ``--ek`` beyond Harbor's base kwargs.+ environment_kwargs: frozenset[str] = frozenset()+ #: Kwargs that must be non-empty strings before a run starts.+ required_environment_kwargs: tuple[str, ...] = ()+ #: Accepted constructor kwargs that SkillEvaluator must never forward from operators.+ reserved_environment_kwargs: frozenset[str] = frozenset()+ #: Upper-case host variables forwarded to the Harbor process; skill ``runtime_env``+ #: cannot set them. Agent, provider, and other backends' credentials are refused.+ host_env_vars: frozenset[str] = frozenset()+ #: Members of ``host_env_vars`` that hold file paths; relative values are anchored to+ #: the caller's working directory because Harbor runs in a private directory.+ host_path_env_vars: frozenset[str] = frozenset()+ #: Members of ``environment_kwargs`` that hold host file paths, anchored the same way.+ host_path_environment_kwargs: frozenset[str] = frozenset()+ #: Per-agent Harbor agent import paths; unlisted agents use Harbor's stock agent.+ agent_import_paths: Mapping[str, str] = field(default_factory=dict)+ #: Whether the backend can run tasks that declare ``docker-compose.yaml`` sidecars.+ supports_docker_compose: bool = False+ #: Optional ``package.module:function`` called as ``fn(environment_kwargs) -> list[str]``+ #: before Harbor's own ``preflight``; each string is one blocking prerequisite error.+ prerequisites: str | None = None+ #: Shown when the environment class or a dependency it imports cannot be imported.+ install_hint: str = ""++ def __post_init__(self) -> None:+ if not isinstance(self.import_path, str) or not _IMPORT_PATH_RE.fullmatch(self.import_path):+ raise EnvironmentBackendError("import_path must be 'package.module:ClassName'")+ if self.prerequisites is not None and not _IMPORT_PATH_RE.fullmatch(str(self.prerequisites)):+ raise EnvironmentBackendError("prerequisites must be 'package.module:function'")+ for label, names in (+ ("environment_kwargs", self.environment_kwargs),+ ("required_environment_kwargs", self.required_environment_kwargs),+ ("reserved_environment_kwargs", self.reserved_environment_kwargs),+ ):+ if isinstance(names, str) or not all(isinstance(name, str) and name.isidentifier() for name in names):+ raise EnvironmentBackendError(f"{label} must be a collection of Python keyword names")+ if missing := sorted(set(self.required_environment_kwargs) - set(self.environment_kwargs)):+ raise EnvironmentBackendError("required_environment_kwargs must also be accepted: " + ", ".join(missing))+ if isinstance(self.host_env_vars, str) or not all(+ isinstance(name, str) and _HOST_ENV_VAR_RE.fullmatch(name) for name in self.host_env_vars+ ):+ raise EnvironmentBackendError("host_env_vars must be a collection of upper-case environment variable names")+ if missing := sorted(set(self.host_path_env_vars) - set(self.host_env_vars)):+ raise EnvironmentBackendError("host_path_env_vars must also be host_env_vars: " + ", ".join(missing))+ if missing := sorted(set(self.host_path_environment_kwargs) - set(self.environment_kwargs)):+ raise EnvironmentBackendError(+ "host_path_environment_kwargs must also be environment_kwargs: " + ", ".join(missing)+ )+ if not isinstance(self.agent_import_paths, Mapping) or not all(+ isinstance(agent, str) and isinstance(path, str) and _IMPORT_PATH_RE.fullmatch(path)+ for agent, path in self.agent_import_paths.items()+ ):+ raise EnvironmentBackendError("agent_import_paths must map agent names to 'package.module:ClassName'")+ object.__setattr__(self, "environment_kwargs", frozenset(self.environment_kwargs))+ object.__setattr__(self, "required_environment_kwargs", tuple(self.required_environment_kwargs))+ object.__setattr__(self, "reserved_environment_kwargs", frozenset(self.reserved_environment_kwargs))+ object.__setattr__(self, "host_env_vars", frozenset(self.host_env_vars))+ object.__setattr__(self, "host_path_env_vars", frozenset(self.host_path_env_vars))+ object.__setattr__(self, "host_path_environment_kwargs", frozenset(self.host_path_environment_kwargs))+ object.__setattr__(self, "agent_import_paths", MappingProxyType(dict(self.agent_import_paths)))+++def _custom_backends_disabled() -> bool:+ return os.environ.get(DISABLE_CUSTOM_BACKENDS_ENV, "").strip().lower() in {"1", "true", "yes"}+++@lru_cache(maxsize=1)+def _custom_backend_entry_points() -> Mapping[str, tuple[EntryPoint, ...]]:+ """Return installed custom backend entry points by mode name, without importing them."""+ selected: dict[str, dict[tuple[str | None, str | None, str], EntryPoint]] = {}+ for entry_point in entry_points(group=ENV_MODE_ENTRY_POINT_GROUP):+ name = entry_point.name+ # Built-in modes keep their reviewed behavior; a custom backend can never replace one.+ if name in HARBOR_ENV_MODES or not _BACKEND_NAME_RE.fullmatch(name):+ continue+ # EntryPoint equality ignores the owning distribution. Key on it so two+ # packages registering the same target still count as two claims, while+ # one distribution seen twice on sys.path counts once.+ dist = getattr(entry_point, "dist", None)+ identity = (+ dist.name.lower().replace("_", "-") if dist is not None else None,+ dist.version if dist is not None else None,+ entry_point.value,+ )+ selected.setdefault(name, {}).setdefault(identity, entry_point)+ return MappingProxyType({name: tuple(points.values()) for name, points in sorted(selected.items())})+++def _entry_point_source(entry_point: EntryPoint) -> str:+ dist = getattr(entry_point, "dist", None)+ return f"{dist.name} {dist.version}" if dist is not None else entry_point.value+++def custom_backend_names() -> tuple[str, ...]:+ """Return the ``--env-mode`` names contributed by installed custom execution backends."""+ if _custom_backends_disabled():+ return ()+ return tuple(_custom_backend_entry_points())+++def all_env_modes() -> tuple[str, ...]:+ """Return built-in modes followed by installed custom execution backends."""+ return (*HARBOR_ENVIRONMENTS, *custom_backend_names())+++def is_env_mode(env_mode: str) -> bool:+ """Return True for a built-in or custom ``--env-mode``."""+ return env_mode in HARBOR_ENV_MODES or env_mode in custom_backend_names()+++def load_custom_backend(env_mode: str) -> EnvironmentBackendSpec | None:+ """Load the custom backend behind ``env_mode``; return None for built-in or unknown modes."""+ if env_mode in HARBOR_ENV_MODES or env_mode not in custom_backend_names():+ return None+ return _load_custom_backend(env_mode)+++@cache+def _load_custom_backend(env_mode: str) -> EnvironmentBackendSpec:+ claims = _custom_backend_entry_points()[env_mode]+ if len(claims) > 1:+ # Install order would otherwise decide which backend runs.+ raise EnvironmentBackendError(+ f"Custom execution backend '{env_mode}' is registered by more than one package: "+ + ", ".join(sorted(_entry_point_source(point) for point in claims))+ + ". Uninstall all but one"+ )+ entry_point = claims[0]+ try:+ loaded: Any = entry_point.load()+ backend = loaded if isinstance(loaded, EnvironmentBackendSpec) else loaded() if callable(loaded) else loaded+ except EnvironmentBackendError as exc:+ raise EnvironmentBackendError(f"Custom execution backend '{env_mode}' is invalid: {exc}") from None+ except Exception as exc:+ raise EnvironmentBackendError(+ f"Custom execution backend '{env_mode}' ({entry_point.value!r}) could not be loaded: "+ f"{type(exc).__name__}: {exc}"+ ) from None+ if not isinstance(backend, EnvironmentBackendSpec):+ raise EnvironmentBackendError(+ f"Custom execution backend '{env_mode}' ({entry_point.value!r}) must provide an EnvironmentBackendSpec"+ )+ return backend+++def clear_custom_backend_cache() -> None:+ """Forget discovered custom backends, for tests and long-lived processes that install packages."""+ _custom_backend_entry_points.cache_clear()+ _load_custom_backend.cache_clear()diff --git a/tests/test_custom_backend_package.py b/tests/test_custom_backend_package.pynew file mode 100644index 00000000..bdff7dc2--- /dev/null+++ b/tests/test_custom_backend_package.py@@ -0,0 +1,237 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""A separately installed custom execution backend, exercised from fresh processes.++The registry unit tests patch ``entry_points``; this test builds a real wheel for+an independent package, installs it into its own directory, and checks+discovery, ``doctor``, and Harbor's own import-path dispatch in new interpreters.+"""++from __future__ import annotations++import base64+import hashlib+import json+import os+import shutil+import subprocess+import sys+import textwrap+import zipfile+from pathlib import Path++import pytest++_DIST = "skillevaluator-demo-backend"+_PACKAGE = "skillevaluator_demo_backend"+_VERSION = "0.1.0"+_MODULES = {+ f"{_PACKAGE}/__init__.py": '"""Demo custom execution backend."""\n',+ f"{_PACKAGE}/spec.py": textwrap.dedent(+ """+ from skillevaluator.tier3_environments import EnvironmentBackendSpec++ SPEC = EnvironmentBackendSpec(+ import_path="skillevaluator_demo_backend.environment:DemoEnvironment",+ environment_kwargs=frozenset({"endpoint", "lease_seconds"}),+ required_environment_kwargs=("endpoint",),+ host_env_vars=frozenset({"DEMO_BACKEND_URL"}),+ prerequisites="skillevaluator_demo_backend.checks:prerequisites",+ install_hint="Install skillevaluator-demo-backend.",+ )+ """+ ),+ f"{_PACKAGE}/checks.py": textwrap.dedent(+ """+ def prerequisites(environment_kwargs):+ if environment_kwargs.get("endpoint") == "https://down.example":+ return ["demo backend endpoint is down"]+ return []+ """+ ),+ f"{_PACKAGE}/environment.py": textwrap.dedent(+ """+ from harbor.environments.base import BaseEnvironment+++ class DemoEnvironment(BaseEnvironment):+ def __init__(self, *args, endpoint, lease_seconds=600, **kwargs):+ self.endpoint = endpoint+ self.lease_seconds = lease_seconds+ super().__init__(*args, **kwargs)++ @staticmethod+ def type():+ return "demo-backend"++ @classmethod+ def preflight(cls):+ return None++ def _validate_definition(self):+ return None++ async def start(self, force_build):+ raise NotImplementedError++ async def stop(self, delete):+ raise NotImplementedError++ async def exec(self, command, cwd=None, env=None, timeout_sec=None, user=None):+ raise NotImplementedError++ async def upload_file(self, source_path, target_path):+ raise NotImplementedError++ async def upload_dir(self, source_dir, target_dir):+ raise NotImplementedError++ async def download_file(self, source_path, target_path):+ raise NotImplementedError++ async def download_dir(self, source_dir, target_dir):+ raise NotImplementedError+ """+ ),+}+++def _record_line(name: str, data: bytes) -> str:+ digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode()+ return f"{name},sha256={digest},{len(data)}"+++def _build_wheel(destination: Path) -> Path:+ """Write a standards-conforming pure-Python wheel for the demo backend."""+ info = f"{_PACKAGE}-{_VERSION}.dist-info"+ files = {name: content.encode() for name, content in _MODULES.items()}+ files[f"{info}/METADATA"] = f"Metadata-Version: 2.1\nName: {_DIST}\nVersion: {_VERSION}\n".encode()+ files[f"{info}/WHEEL"] = (+ b"Wheel-Version: 1.0\nGenerator: skillevaluator-test\nRoot-Is-Purelib: true\nTag: py3-none-any\n"+ )+ files[f"{info}/entry_points.txt"] = f"[skillevaluator.env_modes]\ndemo-backend = {_PACKAGE}.spec:SPEC\n".encode()+ record = [_record_line(name, data) for name, data in files.items()] + [f"{info}/RECORD,,"]+ files[f"{info}/RECORD"] = ("\n".join(record) + "\n").encode()+ wheel = destination / f"{_PACKAGE}-{_VERSION}-py3-none-any.whl"+ with zipfile.ZipFile(wheel, "w") as archive:+ for name, data in files.items():+ archive.writestr(name, data)+ return wheel++[email protected](scope="module")+def installed_backend(tmp_path_factory: pytest.TempPathFactory) -> Path:+ root = tmp_path_factory.mktemp("custom-backend")+ wheel = _build_wheel(root)+ target = root / "site"+ uv = shutil.which("uv")+ if uv is not None:+ subprocess.run(+ [uv, "pip", "install", "--offline", "--no-deps", "--target", str(target), str(wheel)],+ check=True,+ capture_output=True,+ timeout=120,+ )+ else:+ # Installing a pure wheel is unpacking it into a purelib directory.+ with zipfile.ZipFile(wheel) as archive:+ archive.extractall(target)+ assert (target / f"{_PACKAGE}-{_VERSION}.dist-info" / "entry_points.txt").is_file()+ return target+++def _fresh_python(+ site: Path, code: str, *args: str, extra_env: dict[str, str] | None = None+) -> subprocess.CompletedProcess[str]:+ env = {key: value for key, value in os.environ.items() if not key.startswith("SKILLEVALUATOR_DISABLE")}+ env["PYTHONPATH"] = os.pathsep.join(filter(None, [str(site), env.get("PYTHONPATH", "")]))+ env.update(extra_env or {})+ return subprocess.run(+ [sys.executable, "-c", code, *args], capture_output=True, text=True, timeout=300, env=env, check=False+ )+++def test_installed_package_is_discovered_without_importing_it(installed_backend: Path) -> None:+ result = _fresh_python(+ installed_backend,+ "import json, sys; from skillevaluator.cli import ENV_MODE_CHOICE; "+ "print(json.dumps([ENV_MODE_CHOICE.choices[-1], 'skillevaluator_demo_backend' in sys.modules]))",+ )+ assert result.returncode == 0, result.stderr+ assert json.loads(result.stdout) == ["demo-backend", False]+++def test_doctor_runs_the_installed_backend_checks(installed_backend: Path) -> None:+ cli = "from skillevaluator.cli import cli; cli()"+ ready = _fresh_python(+ installed_backend,+ cli,+ "doctor",+ "--env-mode",+ "demo-backend",+ "-a",+ "opencode",+ "--ek",+ "endpoint=https://up.example",+ )+ down = _fresh_python(+ installed_backend,+ cli,+ "doctor",+ "--env-mode",+ "demo-backend",+ "-a",+ "opencode",+ "--ek",+ "endpoint=https://down.example",+ )+ missing = _fresh_python(installed_backend, cli, "doctor", "--env-mode", "demo-backend", "-a", "opencode")++ ready_row = next(line for line in ready.stdout.splitlines() if "demo-backend prerequisite" in line)+ assert "pass" in ready_row and "ready" in ready_row+ assert "demo backend endpoint is down" in down.stdout+ assert "requires non-empty string --environment-kwarg for: endpoint" in " ".join(missing.stdout.split())+++def test_harbor_dispatches_the_installed_environment_class(installed_backend: Path, tmp_path: Path) -> None:+ code = textwrap.dedent(+ """+ import json, sys+ from pathlib import Path+ from harbor.environments.factory import EnvironmentFactory+ from harbor.models.task.config import EnvironmentConfig+ from harbor.models.trial.config import EnvironmentConfig as TrialEnvironmentConfig+ from harbor.models.trial.paths import TrialPaths+ from skillevaluator.tier3.harbor.runner import build_harbor_run_command++ root = Path(sys.argv[1])+ command = build_harbor_run_command(+ dataset_path=root / "dataset", agent="opencode", job_name="demo", env_mode="demo-backend",+ environment_kwargs={"endpoint": "https://up.example", "lease_seconds": 900},+ )+ import_path = command[command.index("--env") + 1]+ kwargs = {}+ for index, value in enumerate(command):+ if value == "--ek":+ name, raw = command[index + 1].split("=", 1)+ kwargs[name] = json.loads(raw)+ (root / "env").mkdir()+ environment = EnvironmentFactory.create_environment_from_config(+ TrialEnvironmentConfig(import_path=import_path, kwargs=kwargs),+ environment_dir=root / "env", environment_name="demo", session_id="session",+ trial_paths=TrialPaths(trial_dir=root / "trial"), task_env_config=EnvironmentConfig(),+ )+ print(json.dumps([import_path, type(environment).__module__, environment.type(),+ environment.endpoint, environment.lease_seconds]))+ """+ )+ result = _fresh_python(installed_backend, code, str(tmp_path))+ assert result.returncode == 0, result.stderr+ assert json.loads(result.stdout.splitlines()[-1]) == [+ "skillevaluator_demo_backend.environment:DemoEnvironment",+ "skillevaluator_demo_backend.environment",+ "demo-backend",+ "https://up.example",+ 900,+ ]diff --git a/tests/test_custom_execution_backends.py b/tests/test_custom_execution_backends.pynew file mode 100644index 00000000..c907155f--- /dev/null+++ b/tests/test_custom_execution_backends.py@@ -0,0 +1,566 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Custom execution backends contributed by installed packages through entry points."""++from __future__ import annotations++import json+import subprocess+import sys+import types+from collections.abc import Iterator+from importlib.metadata import EntryPoint+from pathlib import Path++import pytest++from skillevaluator import tier3_environments+from skillevaluator.tier3.harbor import runner+from skillevaluator.tier3.harbor.runner import build_harbor_run_command+from skillevaluator.tier3_environments import (+ DISABLE_CUSTOM_BACKENDS_ENV,+ ENV_MODE_ENTRY_POINT_GROUP,+ EnvironmentBackendError,+ EnvironmentBackendSpec,+)++_MODULE = "skillevaluator_test_backend"+_ENV_IMPORT_PATH = f"{_MODULE}:AcmeEnvironment"+_AGENT_IMPORT_PATH = f"{_MODULE}:AcmeClaudeCode"+++class _AcmeEnvironment:+ preflight_calls = 0+ preflight_error: Exception | None = None++ @classmethod+ def preflight(cls) -> None:+ cls.preflight_calls += 1+ if cls.preflight_error is not None:+ raise cls.preflight_error+++def _spec(**overrides: object) -> EnvironmentBackendSpec:+ options: dict[str, object] = {+ "import_path": _ENV_IMPORT_PATH,+ "environment_kwargs": frozenset({"endpoint", "profile", "lease_seconds", "pool"}),+ "required_environment_kwargs": ("endpoint",),+ "reserved_environment_kwargs": frozenset({"pool"}),+ "host_env_vars": frozenset({"ACME_SANDBOX_TOKEN", "ACME_SANDBOX_URL"}),+ "agent_import_paths": {"claude-code": _AGENT_IMPORT_PATH},+ "prerequisites": f"{_MODULE}:check",+ "install_hint": "Install 'skillevaluator-acme'.",+ }+ options.update(overrides)+ return EnvironmentBackendSpec(**options) # type: ignore[arg-type]+++def backend_module(monkeypatch: pytest.MonkeyPatch) -> Iterator[types.ModuleType]:+ module = types.ModuleType(_MODULE)+ module.AcmeEnvironment = _AcmeEnvironment # type: ignore[attr-defined]+ module.AcmeClaudeCode = object # type: ignore[attr-defined]+ module.SPEC = _spec() # type: ignore[attr-defined]+ module.check = lambda kwargs: [] if kwargs.get("endpoint") != "down" else ["acme endpoint is down"] # type: ignore[attr-defined]+ module.make_spec = _spec # type: ignore[attr-defined]+ module.broken = 42 # type: ignore[attr-defined]+ monkeypatch.setitem(sys.modules, _MODULE, module)+ monkeypatch.delenv(DISABLE_CUSTOM_BACKENDS_ENV, raising=False)+ _AcmeEnvironment.preflight_calls = 0+ _AcmeEnvironment.preflight_error = None+ yield module+ tier3_environments.clear_custom_backend_cache()+++def _install(monkeypatch: pytest.MonkeyPatch, **entries: str) -> None:+ points = [EntryPoint(name=name, value=value, group=ENV_MODE_ENTRY_POINT_GROUP) for name, value in entries.items()]+ monkeypatch.setattr(+ tier3_environments, "entry_points", lambda *, group: points if group == ENV_MODE_ENTRY_POINT_GROUP else []+ )+ tier3_environments.clear_custom_backend_cache()+++def acme(backend_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch) -> types.ModuleType:+ _install(monkeypatch, acme=f"{_MODULE}:SPEC")+ return backend_module+++def test_installed_backends_extend_the_env_mode_list(acme: types.ModuleType) -> None:+ assert tier3_environments.custom_backend_names() == ("acme",)+ assert tier3_environments.all_env_modes()[-1] == "acme"+ assert tier3_environments.is_env_mode("acme")+ assert not tier3_environments.is_env_mode("acme-unknown")+ assert tier3_environments.load_custom_backend("docker") is None+++def test_backends_cannot_replace_built_in_modes_or_use_invalid_names(+ backend_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch+) -> None:+ _install(monkeypatch, docker=f"{_MODULE}:SPEC", local=f"{_MODULE}:SPEC", Bad_Name=f"{_MODULE}:SPEC")++ assert tier3_environments.custom_backend_names() == ()+ command = build_harbor_run_command(dataset_path="/tmp/dataset", agent="opencode", job_name="d", env_mode="docker")+ assert command[command.index("--env") + 1] != _ENV_IMPORT_PATH+++def test_backends_can_be_disabled(acme: types.ModuleType, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv(DISABLE_CUSTOM_BACKENDS_ENV, "1")++ assert tier3_environments.custom_backend_names() == ()+ assert "Unsupported Harbor environment" in runner._check_prerequisites(env_mode="acme")[0]+++def test_listing_backends_does_not_import_them(+ backend_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch+) -> None:+ _install(monkeypatch, acme="skillevaluator_missing_backend_module:SPEC")++ assert tier3_environments.all_env_modes()[-1] == "acme"+ with pytest.raises(EnvironmentBackendError, match="could not be loaded"):+ tier3_environments.load_custom_backend("acme")+++def test_entry_point_may_name_a_factory(backend_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch) -> None:+ _install(monkeypatch, acme=f"{_MODULE}:make_spec", junk=f"{_MODULE}:broken")++ assert tier3_environments.load_custom_backend("acme") == _spec()+ with pytest.raises(EnvironmentBackendError, match="must provide an EnvironmentBackendSpec"):+ tier3_environments.load_custom_backend("junk")+++def test_backend_mode_dispatches_through_harbor_import_paths(acme: types.ModuleType) -> None:+ command = build_harbor_run_command(+ dataset_path="/tmp/dataset",+ agent="claude-code",+ job_name="acme",+ env_mode="acme",+ environment_kwargs={"endpoint": "https://sandbox.example", "lease_seconds": 600},+ )++ assert command[command.index("--env") + 1] == _ENV_IMPORT_PATH+ assert command[command.index("--agent") + 1] == _AGENT_IMPORT_PATH+ ek = [command[index + 1] for index, value in enumerate(command) if value == "--ek"]+ assert ek == [f"endpoint={json.dumps('https://sandbox.example')}", "lease_seconds=600"]++ stock = build_harbor_run_command(dataset_path="/tmp/dataset", agent="opencode", job_name="acme", env_mode="acme")+ assert stock[stock.index("--agent") + 1] == "opencode"+++def test_backend_agent_wrappers_are_the_only_extra_agent_paths_allowed(acme: types.ModuleType) -> None:+ command = build_harbor_run_command(+ dataset_path="/tmp/dataset",+ agent="claude-code",+ job_name="acme",+ env_mode="acme",+ agent_import_path=_AGENT_IMPORT_PATH,+ )+ assert command[command.index("--agent") + 1] == _AGENT_IMPORT_PATH++ with pytest.raises(ValueError, match="agent_import_path is supported only"):+ build_harbor_run_command(+ dataset_path="/tmp/dataset",+ agent="claude-code",+ job_name="acme",+ env_mode="acme",+ agent_import_path="attacker.module:Agent",+ )+++ ("kwargs", "message"),+ [+ ({"unknown": "x"}, "does not accept environment kwarg(s): unknown"),+ ({"pool": "shared"}, "reserved for Harbor runtime policy: pool"),+ ({"network_policy": "open"}, "reserved for Harbor runtime policy: network_policy"),+ ({"session_id": "s"}, "reserved for Harbor runtime policy: session_id"),+ ],+)+def test_backend_kwargs_follow_evaluator_policy(acme: types.ModuleType, kwargs: dict[str, str], message: str) -> None:+ with pytest.raises(ValueError, match=message.replace("(", r"\(").replace(")", r"\)")):+ build_harbor_run_command(+ dataset_path="/tmp/dataset",+ agent="opencode",+ job_name="acme",+ env_mode="acme",+ environment_kwargs=kwargs,+ )+++def test_backend_kwargs_cannot_carry_secrets(acme: types.ModuleType) -> None:+ with pytest.raises(ValueError, match="secret-bearing"):+ build_harbor_run_command(+ dataset_path="/tmp/dataset",+ agent="opencode",+ job_name="acme",+ env_mode="acme",+ environment_kwargs={"api_token": "rt-123456"},+ )+++def test_backend_prerequisites_run_required_kwargs_hook_and_harbor_preflight(acme: types.ModuleType) -> None:+ assert runner._check_prerequisites(env_mode="acme", environment_kwargs={}) == [+ "Harbor environment 'acme' requires non-empty string --environment-kwarg for: endpoint"+ ]+ assert _AcmeEnvironment.preflight_calls == 0++ assert runner._check_prerequisites(env_mode="acme", environment_kwargs={"endpoint": "down"}) == [+ "acme endpoint is down"+ ]+ assert _AcmeEnvironment.preflight_calls == 0++ assert runner._check_prerequisites(env_mode="acme", environment_kwargs={"endpoint": "https://up"}) == []+ assert _AcmeEnvironment.preflight_calls == 1++ _AcmeEnvironment.preflight_error = RuntimeError("ACME_SANDBOX_URL is not set")+ assert runner._check_prerequisites(env_mode="acme", environment_kwargs={"endpoint": "https://up"}) == [+ "Custom execution backend 'acme' is not ready: ACME_SANDBOX_URL is not set"+ ]+++def test_backend_load_failure_is_a_prerequisite_error_with_install_hint(+ backend_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch+) -> None:+ _install(monkeypatch, acme="skillevaluator_missing_backend_module:SPEC")++ [error] = runner._check_prerequisites(env_mode="acme")+ assert "could not be loaded" in error+ assert "Reinstall the package that provides custom execution backend 'acme'" in error+++def test_backend_host_variables_reach_harbor_and_are_protected_from_skills(acme: types.ModuleType) -> None:+ assert runner._env_mode_host_env_vars("acme") == frozenset({"ACME_SANDBOX_TOKEN", "ACME_SANDBOX_URL"})+ assert runner._env_mode_host_env_vars("daytona") == runner._HARBOR_ENV_MODE_VARS["daytona"]++ resolved, errors = runner._resolve_runtime_env({"ACME_SANDBOX_URL": "https://attacker.example"}, env_mode="acme")+ assert resolved == {}+ assert errors == ["harbor.runtime_env.ACME_SANDBOX_URL controls the host process and is not allowed"]+++ "name",+ [+ "ANTHROPIC_API_KEY",+ "ANTHROPIC_AUTH_TOKEN",+ "CLAUDE_CODE_OAUTH_TOKEN",+ "CLAUDE_FORCE_OAUTH",+ "CODEX_AUTH_JSON_PATH",+ "CODEX_FORCE_AUTH_JSON",+ "OPENAI_BASE_URL",+ "OPENCODE_CONFIG",+ "GITHUB_TOKEN",+ "GH_TOKEN",+ "HF_TOKEN",+ "NVIDIA_API_KEY",+ "DAYTONA_API_KEY",+ "MODAL_TOKEN_SECRET",+ "RUNTA_TOKEN",+ "AWS_SECRET_ACCESS_KEY",+ "LD_PRELOAD",+ "SKILLEVALUATOR_X",+ ],+)+def test_backends_cannot_forward_evaluator_owned_variables(+ backend_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch, name: str+) -> None:+ backend_module.SPEC = _spec(host_env_vars=frozenset({"ACME_SANDBOX_URL", name})) # type: ignore[attr-defined]+ _install(monkeypatch, acme=f"{_MODULE}:SPEC")++ with pytest.raises(EnvironmentBackendError, match=f"may not forward evaluator-owned variable.*{name}"):+ build_harbor_run_command(dataset_path="/tmp/dataset", agent="opencode", job_name="acme", env_mode="acme")+ assert runner._env_mode_host_env_vars("acme") == frozenset()+ assert "may not forward" in runner._check_prerequisites(env_mode="acme")[0]+++def test_backend_compose_support_gates_staged_tasks(+ acme: types.ModuleType, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ task = tmp_path / "task-a"+ (task / "environment").mkdir(parents=True)+ (task / "environment" / "Dockerfile").write_text("FROM python:3.12-slim\n", encoding="utf-8")+ assert runner._staged_task_environment_error("acme", [task]) is None++ (task / "environment" / "docker-compose.yaml").write_text("services: {}\n", encoding="utf-8")+ assert "cannot run Docker Compose task 'task-a'" in str(runner._staged_task_environment_error("acme", [task]))++ acme.SPEC = _spec(supports_docker_compose=True) # type: ignore[attr-defined]+ _install(monkeypatch, acme=f"{_MODULE}:SPEC")+ assert runner._staged_task_environment_error("acme", [task]) is None+++ ("overrides", "message"),+ [+ ({"import_path": "not-an-import-path"}, "import_path"),+ ({"prerequisites": "nope"}, "prerequisites"),+ ({"environment_kwargs": "endpoint"}, "environment_kwargs"),+ ({"required_environment_kwargs": ("region",)}, "must also be accepted: region"),+ ({"host_env_vars": frozenset({"BAD-NAME"})}, "host_env_vars"),+ ({"host_env_vars": frozenset({"acme_sandbox_url"})}, "upper-case"),+ ({"host_env_vars": frozenset({"Acme_Sandbox_Url"})}, "upper-case"),+ ({"host_path_env_vars": frozenset({"ACME_CONFIG"})}, "host_path_env_vars must also be host_env_vars"),+ ({"host_path_environment_kwargs": frozenset({"kubeconfig"})}, "must also be environment_kwargs"),+ ({"agent_import_paths": {"claude-code": "nope"}}, "agent_import_paths"),+ ],+)+def test_backend_descriptors_are_validated(overrides: dict[str, object], message: str) -> None:+ with pytest.raises(EnvironmentBackendError, match=message):+ _spec(**overrides)+++def test_cli_offers_installed_custom_backends(tmp_path: Path) -> None:+ dist = tmp_path / "skillevaluator_acme_backend-0.0.0.dist-info"+ dist.mkdir()+ (dist / "METADATA").write_text("Metadata-Version: 2.1\nName: skillevaluator-acme-backend\nVersion: 0.0.0\n")+ (dist / "entry_points.txt").write_text(f"[{ENV_MODE_ENTRY_POINT_GROUP}]\nacme = {_MODULE}:SPEC\n")+ code = (+ "import sys; sys.path.insert(0, sys.argv[1]);"+ "from skillevaluator.cli import ENV_MODE_CHOICE; print(ENV_MODE_CHOICE.choices[-1])"+ )+ result = subprocess.run(+ [sys.executable, "-c", code, str(tmp_path)], capture_output=True, text=True, check=True, timeout=120+ )++ assert result.stdout.strip() == "acme"+++def test_backends_may_forward_kubeconfig_and_their_own_backend_settings(+ backend_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch+) -> None:+ host = frozenset({"KUBECONFIG", "ACME_SANDBOX_URL", "ACME_SANDBOX_TOKEN", "HTTPS_PROXY"})+ backend_module.SPEC = _spec(host_env_vars=host) # type: ignore[attr-defined]+ _install(monkeypatch, acme=f"{_MODULE}:SPEC")++ assert runner._env_mode_host_env_vars("acme") == host+++def test_backend_path_settings_are_anchored_before_harbor_changes_directory(+ backend_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ from skillevaluator.provider_config import ProviderConfig++ backend_module.SPEC = _spec( # type: ignore[attr-defined]+ environment_kwargs=frozenset({"endpoint", "ca_file"}),+ host_env_vars=frozenset({"ACME_CONFIG", "ACME_SANDBOX_URL"}),+ host_path_env_vars=frozenset({"ACME_CONFIG"}),+ host_path_environment_kwargs=frozenset({"ca_file"}),+ )+ _install(monkeypatch, acme=f"{_MODULE}:SPEC")+ monkeypatch.chdir(tmp_path)+ monkeypatch.setenv("ACME_CONFIG", "acme/config.yaml")+ monkeypatch.setenv("ACME_SANDBOX_URL", "https://sandbox.example")++ environment = runner._harbor_subprocess_environment(+ env_mode="acme",+ provider=ProviderConfig(+ provider="anthropic", model="claude", api_key="sk-ant", base_url=None, litellm_model="m", region=None+ ),+ configured_runtime_env={},+ provider_env={},+ )+ assert environment["ACME_CONFIG"] == str(tmp_path / "acme" / "config.yaml")+ assert environment["ACME_SANDBOX_URL"] == "https://sandbox.example"++ command = build_harbor_run_command(+ dataset_path="/tmp/dataset",+ agent="opencode",+ job_name="acme",+ env_mode="acme",+ environment_kwargs={"endpoint": "https://x", "ca_file": "certs/ca.pem"},+ )+ ek = [command[index + 1] for index, value in enumerate(command) if value == "--ek"]+ assert f"ca_file={json.dumps(str(tmp_path / 'certs' / 'ca.pem'))}" in ek+++def test_install_hint_is_shown_when_the_environment_dependencies_are_missing(+ backend_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch+) -> None:+ real_import = runner.importlib.import_module++ def import_module(name: str, *args: object, **kwargs: object) -> object:+ if name == "skillevaluator_test_backend_env":+ raise ModuleNotFoundError("No module named 'acme_sdk'", name="acme_sdk")+ return real_import(name, *args, **kwargs)++ backend_module.SPEC = _spec(import_path="skillevaluator_test_backend_env:AcmeEnvironment") # type: ignore[attr-defined]+ _install(monkeypatch, acme=f"{_MODULE}:SPEC")+ monkeypatch.setattr(runner.importlib, "import_module", import_module)++ [error] = runner._check_prerequisites(env_mode="acme", environment_kwargs={"endpoint": "https://up"})+ assert "needs optional dependencies: No module named 'acme_sdk'" in error+ assert "Install 'skillevaluator-acme'." in error+ assert _AcmeEnvironment.preflight_calls == 0+++def test_install_hint_is_shown_when_harbor_wraps_the_import_failure(+ acme: types.ModuleType, monkeypatch: pytest.MonkeyPatch+) -> None:+ def _wrapped(_cls: object, _type: object, import_path: str | None = None) -> None:+ try:+ raise ModuleNotFoundError("No module named 'acme_sdk'")+ except ModuleNotFoundError as exc:+ raise ValueError(f"Failed to import module '{import_path}'") from exc++ from harbor.environments.factory import EnvironmentFactory++ monkeypatch.setattr(EnvironmentFactory, "run_preflight", classmethod(_wrapped))+ [error] = runner._check_prerequisites(env_mode="acme", environment_kwargs={"endpoint": "https://up"})+ assert "needs optional dependencies: No module named 'acme_sdk'" in error+ assert "Install 'skillevaluator-acme'." in error+++def _write_dist(root: Path, name: str, value: str) -> None:+ dist = root / f"{name.replace('-', '_')}-1.0.dist-info"+ dist.mkdir(parents=True)+ (dist / "METADATA").write_text(f"Metadata-Version: 2.1\nName: {name}\nVersion: 1.0\n")+ (dist / "entry_points.txt").write_text(f"[{ENV_MODE_ENTRY_POINT_GROUP}]\nshared = {value}\n")+++def test_a_mode_name_claimed_by_two_packages_is_ambiguous(+ backend_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ _write_dist(tmp_path, "aaa-backend", f"{_MODULE}:SPEC")+ _write_dist(tmp_path, "zzz-backend", f"{_MODULE}:make_spec")+ monkeypatch.syspath_prepend(str(tmp_path))+ tier3_environments.clear_custom_backend_cache()++ assert "shared" in tier3_environments.custom_backend_names()+ with pytest.raises(+ EnvironmentBackendError, match=r"registered by more than one package: aaa-backend 1\.0, zzz-backend 1\.0"+ ):+ tier3_environments.load_custom_backend("shared")+ [error] = runner._check_prerequisites(env_mode="shared")+ assert "aaa-backend 1.0, zzz-backend 1.0" in error+++def test_public_benchmark_cards_do_not_name_custom_backends(acme: types.ModuleType) -> None:+ from skillevaluator.reporting import benchmark++ assert benchmark._publication_safe_environment("acme") == "Isolated sandbox"+ assert benchmark._publication_safe_environment("docker") == "docker"+++def test_identical_targets_from_two_packages_are_still_ambiguous(+ backend_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ _write_dist(tmp_path, "aaa-backend", f"{_MODULE}:SPEC")+ _write_dist(tmp_path, "zzz-backend", f"{_MODULE}:SPEC")+ monkeypatch.syspath_prepend(str(tmp_path))+ tier3_environments.clear_custom_backend_cache()++ with pytest.raises(EnvironmentBackendError, match=r"aaa-backend 1\.0, zzz-backend 1\.0"):+ tier3_environments.load_custom_backend("shared")+++def test_one_package_seen_twice_on_the_path_is_one_claim(+ backend_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ _write_dist(tmp_path / "first", "aaa-backend", f"{_MODULE}:SPEC")+ _write_dist(tmp_path / "second", "aaa-backend", f"{_MODULE}:SPEC")+ monkeypatch.syspath_prepend(str(tmp_path / "first"))+ monkeypatch.syspath_prepend(str(tmp_path / "second"))+ tier3_environments.clear_custom_backend_cache()++ assert tier3_environments.load_custom_backend("shared") == _spec()+++def test_backends_may_accept_allow_workload_identity_and_receive_it(+ backend_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch+) -> None:+ backend_module.SPEC = _spec(environment_kwargs=frozenset({"endpoint", "allow_workload_identity"})) # type: ignore[attr-defined]+ _install(monkeypatch, acme=f"{_MODULE}:SPEC")++ command = build_harbor_run_command(+ dataset_path="/tmp/dataset",+ agent="opencode",+ job_name="acme",+ env_mode="acme",+ environment_kwargs={"allow_workload_identity": True},+ )+ assert "allow_workload_identity=true" in [command[i + 1] for i, value in enumerate(command) if value == "--ek"]+++_SYNTHETIC_TOKEN = "acme-synthetic-token-7f3c9e1a"+++def test_backend_load_failures_are_redacted_everywhere_they_surface(+ backend_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch+) -> None:+ def broken_factory() -> EnvironmentBackendSpec:+ raise RuntimeError(f"cannot reach https://ci:{_SYNTHETIC_TOKEN}@sandbox.example/v1 with {_SYNTHETIC_TOKEN}")++ backend_module.broken_factory = broken_factory # type: ignore[attr-defined]+ monkeypatch.setenv("ACME_SANDBOX_TOKEN", _SYNTHETIC_TOKEN)+ _install(monkeypatch, acme=f"{_MODULE}:broken_factory")++ [doctor_error] = runner._check_prerequisites(env_mode="acme")+ policy_error = runner._environment_kwarg_policy_error("acme", {"endpoint": "https://x"})+ with pytest.raises(EnvironmentBackendError) as raised:+ build_harbor_run_command(dataset_path="/tmp/dataset", agent="opencode", job_name="acme", env_mode="acme")++ for message in (doctor_error, str(policy_error), str(raised.value)):+ assert "could not be loaded" in message+ assert _SYNTHETIC_TOKEN not in message+ assert "<redacted>" in message+++def _codex_wrappers(module: types.ModuleType) -> None:+ from harbor.agents.installed.codex import Codex++ from skillevaluator.tier3.harbor.local_agents import SkillEvaluatorGatewayCodex++ class PrebuiltGatewayCodex(SkillEvaluatorGatewayCodex):+ """Keeps gateway routing; adapts setup for a non-root backend."""++ class PrebuiltCodex(Codex):+ """Adapts setup but drops the gateway routing."""++ module.PrebuiltGatewayCodex = PrebuiltGatewayCodex # type: ignore[attr-defined]+ module.PrebuiltCodex = PrebuiltCodex # type: ignore[attr-defined]+++def _provider(name: str) -> object:+ from skillevaluator.provider_config import ProviderConfig++ return ProviderConfig(+ provider=name, model="m", api_key="k", base_url="https://gateway.example/v1", litellm_model="m", region=None+ )++[email protected]("provider", ["openai", "openai-compatible"])+def test_runtime_keeps_a_backend_codex_wrapper_that_extends_the_provider_wrapper(+ backend_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch, provider: str+) -> None:+ _codex_wrappers(backend_module)+ wrapper = f"{_MODULE}:PrebuiltGatewayCodex"+ backend_module.SPEC = _spec(agent_import_paths={"codex": wrapper}) # type: ignore[attr-defined]+ _install(monkeypatch, acme=f"{_MODULE}:SPEC")++ selected = runner._agent_import_path(_provider(provider), "codex", "acme")+ assert selected == wrapper+ command = build_harbor_run_command(+ dataset_path="/tmp/dataset", agent="codex", job_name="acme", env_mode="acme", agent_import_path=selected+ )+ assert command[command.index("--agent") + 1] == wrapper+++def test_runtime_refuses_a_backend_codex_wrapper_that_drops_gateway_routing(+ backend_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch+) -> None:+ _codex_wrappers(backend_module)+ backend_module.SPEC = _spec(agent_import_paths={"codex": f"{_MODULE}:PrebuiltCodex"}) # type: ignore[attr-defined]+ _install(monkeypatch, acme=f"{_MODULE}:SPEC")++ assert runner._agent_import_path(_provider("openai"), "codex", "acme") == f"{_MODULE}:PrebuiltCodex"+ with pytest.raises(+ ValueError, match=r"requires skillevaluator\.tier3\.harbor\.local_agents:SkillEvaluatorGatewayCodex"+ ):+ runner._agent_import_path(_provider("openai-compatible"), "codex", "acme")+++def test_runtime_uses_the_provider_wrapper_when_the_backend_names_none(acme: types.ModuleType) -> None:+ assert (+ runner._agent_import_path(_provider("openai-compatible"), "codex", "acme") == runner._GATEWAY_CODEX_IMPORT_PATH+ )+ assert runner._agent_import_path(_provider("openai"), "codex", "acme") is None