From 27cb854f1720d5db15d683a8b26ee7815751d411 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Fri, 20 Nov 2026 18:09:04 -0800 Subject: [PATCH 1/9] feat(policy): add operator host and hook URL allowlists and run options Add three optional validation policy keys: mcp.allowed_private_hosts (private MCP hosts the operator trusts), hooks.allowed_urls (trusted hook URL prefixes) and endpoints.resolve (whether declared endpoints may be resolved). A new validators module normalizes the allowlists without DNS lookups: at most 64 entries of bounded length, no control, format or surrogate characters, URL prefixes only in hooks.allowed_urls, and no cloud metadata endpoints. Each policy block must be a mapping that holds only its own key. The keys feed the policy digest and appear in the policy summary as counts, only when set, so the default policy's digest and summary are unchanged. The bounded policy loader is unchanged. Add a frozen run options dataclass to evaluation/options.py. It validates its load mode, lift mode, MCP probe switch and environment grants, trial retries, allowlists and policy on construction; the grant bounds are module constants. It is not exported from skillevaluator.evaluation. Accept an optional top-level block with load and lift_mode keys, and harbor.trial_retries (0 to 5), in evals/config.yml. The new block checks its keys with the existing _unknown_keys helper, like the top level and the harbor, skill_workspace and grading sections, so a non-string key such as 1, yes or ~ is reported as a config error instead of raising TypeError. Add a helper to tier3/results_location.py that picks a results directory from an explicit path, SKILLEVALUATOR_RESULTS_DIR or /results, without creating it. No check, probe or Tier 3 step uses the new policy keys or the values of the new evals/config.yml keys, and no CLI command or public API entry point reaches the options dataclass or the results helper yet, so no check, finding or score changes. A policy file with mcp, hooks or endpoints blocks is now validated instead of having them ignored with a warning, and an evals/config.yml with the new keys now loads instead of being rejected. The existing public-policy compatibility test now asserts that these keys change the digest and appear in the summary only as counts. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Narendran Raghavan --- src/skillevaluator/evaluation/options.py | 63 +++++++++ src/skillevaluator/tier3/evals_config.py | 23 ++- src/skillevaluator/tier3/results_location.py | 8 ++ .../validators/plugin_policy.py | 77 ++++++++++ src/skillevaluator/validators/policy.py | 52 ++++++- ...rivate_foundations_public_compatibility.py | 9 +- tests/tier3/test_evals_config.py | 1 + tests/tier3/test_public_plugin_workflow.py | 37 +++++ tests/validators/test_public_plugin_policy.py | 131 ++++++++++++++++++ 9 files changed, 397 insertions(+), 4 deletions(-) create mode 100644 src/skillevaluator/validators/plugin_policy.py create mode 100644 tests/tier3/test_public_plugin_workflow.py create mode 100644 tests/validators/test_public_plugin_policy.py diff --git a/src/skillevaluator/evaluation/options.py b/src/skillevaluator/evaluation/options.py index a7b3facaa..c8afb4fd2 100644 --- a/src/skillevaluator/evaluation/options.py +++ b/src/skillevaluator/evaluation/options.py @@ -14,6 +14,13 @@ from pathlib import Path from typing import Any +# Public dataclass annotations must remain resolvable by API schema consumers. +from skillevaluator.validators.policy import ValidationPolicy + +# Bounds on ``PluginOptions.probe_mcp_env``: how many grants, and the length of each. +MAX_PROBE_MCP_ENV_GRANTS = 64 +MAX_PROBE_MCP_ENV_GRANT_CHARS = 512 + @dataclass class EvaluationOptions: @@ -93,3 +100,59 @@ class DatasetOptions: def engine_kwargs(self) -> dict[str, Any]: return {f.name: getattr(self, f.name) for f in fields(self) if f.name != "skill_path"} + + +@dataclass(frozen=True) +class PluginOptions: + """Plugin runtime controls; unset values defer to authored configuration. + + ``policy`` is the operator's validation policy. Its severity overrides + decide which manifest and component findings refuse the run before any + agent starts, as they decide Tier 1 blocking. ``None`` keeps each check's + default severity. + """ + + plugin_load: str | None = None + lift_mode: str | None = None + probe_mcp: bool | None = None + probe_mcp_env: tuple[str, ...] = () + trial_retries: int | None = None + repo_root: Path | None = None + allowed_private_hosts: tuple[str, ...] = () + hook_allowed_urls: tuple[str, ...] = () + policy: ValidationPolicy | None = None + + def __post_init__(self) -> None: + from skillevaluator.validators.plugin_policy import normalize_plugin_allowlist + + if self.policy is not None and not isinstance(self.policy, ValidationPolicy): + raise ValueError("policy must be a ValidationPolicy") + object.__setattr__( + self, + "allowed_private_hosts", + normalize_plugin_allowlist(self.allowed_private_hosts, "mcp.allowed_private_hosts", 255), + ) + object.__setattr__( + self, "hook_allowed_urls", normalize_plugin_allowlist(self.hook_allowed_urls, "hooks.allowed_urls", 2048) + ) + for name, choices in ( + ("plugin_load", {"wrapper", "native", "auto"}), + ("lift_mode", {"effectiveness", "integration", "both", "ladder"}), + ): + value = getattr(self, name) + if value is not None and (not isinstance(value, str) or value not in choices): + raise ValueError(f"{name} must be one of: {', '.join(sorted(choices))}") + if self.probe_mcp is not None and type(self.probe_mcp) is not bool: + raise ValueError("probe_mcp must be a boolean") + if self.trial_retries is not None and (type(self.trial_retries) is not int or not 0 <= self.trial_retries <= 5): + raise ValueError("trial_retries must be an integer between 0 and 5") + if ( + not isinstance(self.probe_mcp_env, tuple) + or len(self.probe_mcp_env) > MAX_PROBE_MCP_ENV_GRANTS + or any( + not isinstance(value, str) or len(value) > MAX_PROBE_MCP_ENV_GRANT_CHARS for value in self.probe_mcp_env + ) + ): + raise ValueError( + f"probe_mcp_env must contain at most {MAX_PROBE_MCP_ENV_GRANTS} bounded environment grants" + ) diff --git a/src/skillevaluator/tier3/evals_config.py b/src/skillevaluator/tier3/evals_config.py index a3e759d84..8c6b60838 100644 --- a/src/skillevaluator/tier3/evals_config.py +++ b/src/skillevaluator/tier3/evals_config.py @@ -44,8 +44,9 @@ } GRADING_MODES = {"default", "default_plus_custom", "custom_only", *GRADING_MODE_ALIASES} -_TOP_LEVEL_KEYS = {"schema_version", "harbor", "skill_workspace", "grading"} +_TOP_LEVEL_KEYS = {"schema_version", "harbor", "skill_workspace", "grading", "plugin"} _HARBOR_KEYS = { + "trial_retries", "task_source", "custom_dockerfile_mode", "base_image_mode", @@ -247,6 +248,21 @@ def _validate_config(raw: dict[str, Any], config_path: Path) -> dict[str, Any]: raise EvalsConfigError(f"{config_path}: schema_version must be 1") out: dict[str, Any] = {"schema_version": 1} + if "plugin" in raw: + plugin_raw = raw["plugin"] + if not isinstance(plugin_raw, dict): + raise EvalsConfigError(f"{config_path}: plugin must be a mapping") + unknown = _unknown_keys(plugin_raw, {"load", "lift_mode"}, config_path, "plugin") + if unknown: + raise EvalsConfigError(f"{config_path}: unknown plugin key(s): {', '.join(sorted(unknown))}") + plugin = {} + for key, choices in ( + ("load", {"wrapper", "native", "auto"}), + ("lift_mode", {"effectiveness", "integration", "both", "ladder"}), + ): + if key in plugin_raw: + plugin[key] = _enum(plugin_raw[key], choices, config_path, f"plugin.{key}") + out["plugin"] = plugin harbor_raw = raw.get("harbor") if harbor_raw is not None: if not isinstance(harbor_raw, dict): @@ -257,6 +273,11 @@ def _validate_config(raw: dict[str, Any], config_path: Path) -> dict[str, Any]: raise EvalsConfigError(f"{config_path}: unknown harbor key(s): {', '.join(sorted(unknown_harbor))}") harbor: dict[str, Any] = {} + if "trial_retries" in harbor_raw: + retries = _int_at_least(harbor_raw["trial_retries"], 0, config_path, "harbor.trial_retries") + if retries > 5: + raise EvalsConfigError(f"{config_path}: harbor.trial_retries must be between 0 and 5") + harbor["trial_retries"] = retries if "task_source" in harbor_raw: harbor["task_source"] = _enum( harbor_raw["task_source"], diff --git a/src/skillevaluator/tier3/results_location.py b/src/skillevaluator/tier3/results_location.py index 7aec72fa2..56e8c9f07 100644 --- a/src/skillevaluator/tier3/results_location.py +++ b/src/skillevaluator/tier3/results_location.py @@ -56,6 +56,14 @@ def legacy_results_root(skill_path: Path) -> Path: return skill_path.expanduser().resolve() / "evals" / "results" +def plugin_results_directory(plugin_root: Path, requested: Path | None = None) -> Path: + """Select a public plugin results base without creating an authored evals tree.""" + if requested is not None: + return requested + configured = os.environ.get(ENV_RESULTS_DIR) + return Path(configured).expanduser() if configured else plugin_root / "results" + + def skill_results_name(skill_path: Path) -> str: """Return the directory name used under an external results root.""" return skill_path.expanduser().resolve().name diff --git a/src/skillevaluator/validators/plugin_policy.py b/src/skillevaluator/validators/plugin_policy.py new file mode 100644 index 000000000..b408189d3 --- /dev/null +++ b/src/skillevaluator/validators/plugin_policy.py @@ -0,0 +1,77 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Bounded operator allowlists shared by component checks and runtime proof.""" + +from __future__ import annotations + +import ipaddress +import unicodedata +from urllib.parse import urlsplit + + +def normalize_plugin_allowlist(value: object, key: str, max_chars: int) -> tuple[str, ...]: + """Validate entries without DNS and preserve the existing host matcher rules.""" + if value is None: + return () + if not isinstance(value, (list, tuple)) or len(value) > 64: + raise ValueError(f"{key} must be a list of at most 64 strings") + if not value: + return () + # Default policies stay cheap for ordinary skills and base installations. + from skillevaluator.plugin_component_risk import hook_url_entry_problem + from skillevaluator.validators.mcp_static import HostAllowlist, classify_endpoint_host + from skillevaluator.validators.url_policy import url_ambiguities + + normalized = [] + for raw in value: + if not isinstance(raw, str) or not raw.strip() or len(raw) > max_chars: + raise ValueError(f"{key} entries must be nonempty strings of at most {max_chars} characters") + if any(unicodedata.category(char) in {"Cc", "Cf", "Cs"} for char in raw): + raise ValueError(f"{key} entries cannot contain control or invisible characters") + entry = raw.strip() + if "://" in entry: + if ( + key != "hooks.allowed_urls" + or hook_url_entry_problem(entry) is not None + or url_ambiguities(entry, percent_in_host=True) + ): + raise ValueError(f"{key} contains an invalid URL prefix") + parsed = urlsplit(entry) + if parsed.scheme.lower() not in {"http", "https"}: + raise ValueError(f"{key} URL prefixes must use HTTP or HTTPS") + host = parsed.hostname + else: + if any(char.isspace() for char in entry) or any(char in entry for char in "@?#\\"): + raise ValueError(f"{key} contains an invalid host pattern") + if "/" in entry or ":" in entry: + try: + ipaddress.ip_network( + entry[1:-1] if entry.startswith("[") and entry.endswith("]") else entry, strict=False + ) + except ValueError as exc: + raise ValueError(f"{key} contains an invalid IP address or network") from exc + if "*" in entry and (not entry.startswith("*.") or "*" in entry[2:]): + raise ValueError(f"{key} contains an invalid host wildcard") + hosts = HostAllowlist.from_entries((entry,)) + if not (hosts.names or hosts.suffixes or hosts.networks): + raise ValueError(f"{key} contains an invalid host pattern") + host = entry + endpoint = classify_endpoint_host(host) if host else None + if endpoint is not None and endpoint.kind == "metadata": + raise ValueError(f"{key} cannot allow cloud metadata endpoints") + normalized.append(entry) + return tuple(dict.fromkeys(normalized)) + + +def plugin_policy_block(data: dict, name: str, known: set[str]) -> dict: + """Reject misspelled controls instead of silently widening operator intent.""" + block = data.get(name) + if block is None: + return {} + if not isinstance(block, dict) or not all(isinstance(key, str) for key in block) or set(block) - known: + raise ValueError(f"{name} policy must be a mapping with only {', '.join(sorted(known))}") + return block + + +def overlay_sets(data: dict, block: str, key: str) -> bool: + value = data.get(block) + return isinstance(value, dict) and key in value diff --git a/src/skillevaluator/validators/policy.py b/src/skillevaluator/validators/policy.py index 7730dcae9..20f7a3eab 100644 --- a/src/skillevaluator/validators/policy.py +++ b/src/skillevaluator/validators/policy.py @@ -33,6 +33,7 @@ from skillevaluator.logging_config import get_logger from skillevaluator.models.result import Severity, ValidationResult from skillevaluator.utils.structured_data import StructuredDataError, load_bounded_yaml +from skillevaluator.validators.plugin_policy import normalize_plugin_allowlist, overlay_sets, plugin_policy_block logger = get_logger(__name__) @@ -79,6 +80,23 @@ class ValidationPolicy: severity_overrides: dict[str, Severity] = field(default_factory=dict) metadata_id_requirement: str = DEFAULT_METADATA_ID_REQUIREMENT source: Path | None = None + mcp_allowed_private_hosts: tuple[str, ...] = () + hook_allowed_urls: tuple[str, ...] = () + resolve_endpoints: bool = False + + def __post_init__(self) -> None: + object.__setattr__( + self, + "mcp_allowed_private_hosts", + normalize_plugin_allowlist(self.mcp_allowed_private_hosts, "mcp.allowed_private_hosts", 255), + ) + object.__setattr__( + self, + "hook_allowed_urls", + normalize_plugin_allowlist(self.hook_allowed_urls, "hooks.allowed_urls", 2048), + ) + if type(self.resolve_endpoints) is not bool: + raise ValueError("endpoints.resolve must be a boolean") @property def digest(self) -> str: @@ -90,6 +108,12 @@ def digest(self) -> str: "severity_overrides": {key: value.value for key, value in sorted(self.severity_overrides.items())}, "metadata_id_requirement": self.metadata_id_requirement, } + if self.mcp_allowed_private_hosts: + payload["mcp_allowed_private_hosts"] = sorted(self.mcp_allowed_private_hosts) + if self.hook_allowed_urls: + payload["hook_allowed_urls"] = sorted(self.hook_allowed_urls) + if self.resolve_endpoints: + payload["resolve_endpoints"] = True canonical = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode() return f"sha256:{hashlib.sha256(canonical).hexdigest()}" @@ -124,7 +148,7 @@ def is_author_email_acceptable(self, author: str) -> bool: def to_dict(self) -> dict[str, Any]: """Serialize for inclusion in reports (read-only summary).""" - return { + summary = { "profile": self.profile, "audience": self.audience, "digest": self.digest, @@ -133,6 +157,13 @@ def to_dict(self) -> dict[str, Any]: "metadata_id_requirement": self.metadata_id_requirement, "source": str(self.source) if self.source else None, } + if self.mcp_allowed_private_hosts: + summary["mcp_allowed_private_host_count"] = len(self.mcp_allowed_private_hosts) + if self.hook_allowed_urls: + summary["hook_allowed_url_count"] = len(self.hook_allowed_urls) + if self.resolve_endpoints: + summary["resolve_endpoints"] = True + return summary # --------------------------------------------------------------------------- @@ -168,7 +199,7 @@ def _coerce_email_regex(value: Any, source: str) -> re.Pattern[str] | None: return None -_KNOWN_TOP_LEVEL_KEYS = {"profile", "identity", "severity_overrides"} +_KNOWN_TOP_LEVEL_KEYS = {"profile", "identity", "severity_overrides", "mcp", "hooks", "endpoints"} _KNOWN_IDENTITY_KEYS = {"author_email_regex", "metadata_id_requirement"} @@ -252,6 +283,9 @@ def _policy_from_data( if sev is not None: severity_overrides[key] = sev + mcp = plugin_policy_block(data, "mcp", {"allowed_private_hosts"}) + hooks = plugin_policy_block(data, "hooks", {"allowed_urls"}) + endpoints = plugin_policy_block(data, "endpoints", {"resolve"}) return ValidationPolicy( profile=profile_name, audience="all", @@ -259,6 +293,9 @@ def _policy_from_data( severity_overrides=severity_overrides, metadata_id_requirement=metadata_id_requirement, source=source, + mcp_allowed_private_hosts=mcp.get("allowed_private_hosts", ()), + hook_allowed_urls=hooks.get("allowed_urls", ()), + resolve_endpoints=False if endpoints.get("resolve") is None else endpoints["resolve"], ) @@ -321,6 +358,17 @@ def load_policy_file( custom.metadata_id_requirement if overlay_sets_id_requirement else base.metadata_id_requirement ), source=path, + mcp_allowed_private_hosts=( + custom.mcp_allowed_private_hosts + if overlay_sets(custom_data, "mcp", "allowed_private_hosts") + else base.mcp_allowed_private_hosts + ), + hook_allowed_urls=( + custom.hook_allowed_urls if overlay_sets(custom_data, "hooks", "allowed_urls") else base.hook_allowed_urls + ), + resolve_endpoints=( + custom.resolve_endpoints if overlay_sets(custom_data, "endpoints", "resolve") else base.resolve_endpoints + ), ) diff --git a/tests/cli/test_private_foundations_public_compatibility.py b/tests/cli/test_private_foundations_public_compatibility.py index 4aa4a6625..58d3ca140 100644 --- a/tests/cli/test_private_foundations_public_compatibility.py +++ b/tests/cli/test_private_foundations_public_compatibility.py @@ -105,7 +105,7 @@ def test_forced_private_format_cli_preserves_failure_and_all_reports( assert sarif["runs"][0]["results"][0]["ruleId"].endswith("/manifest_missing") -def test_private_policy_keys_do_not_change_public_policy(tmp_path: Path) -> None: +def test_plugin_policy_keys_are_explicit_and_redacted_in_the_public_summary(tmp_path: Path) -> None: baseline = tmp_path / "baseline.yaml" baseline.write_text("{}\n", encoding="utf-8") candidate = tmp_path / "candidate.yaml" @@ -119,4 +119,11 @@ def test_private_policy_keys_do_not_change_public_policy(tmp_path: Path) -> None actual = load_policy_file(candidate).to_dict() expected.pop("source") actual.pop("source") + assert actual["digest"] != expected["digest"] + assert actual.pop("mcp_allowed_private_host_count") == 1 + assert actual.pop("hook_allowed_url_count") == 1 + assert actual.pop("resolve_endpoints") is True + actual.pop("digest") + expected.pop("digest") assert actual == expected + assert "10.0.0.1" not in json.dumps(actual) and "example.com" not in json.dumps(actual) diff --git a/tests/tier3/test_evals_config.py b/tests/tier3/test_evals_config.py index 9470b3d20..b292e5fc3 100644 --- a/tests/tier3/test_evals_config.py +++ b/tests/tier3/test_evals_config.py @@ -330,6 +330,7 @@ def test_load_evals_config_accepts_a_list_at_the_entry_limit(tmp_path): ), pytest.param("schema_version: 1\nskill_workspace:\n on: invalid\n", "skill_workspace", id="skill-workspace"), pytest.param("schema_version: 1\ngrading:\n 2: invalid\n", "grading", id="grading"), + pytest.param("schema_version: 1\nplugin:\n 1: invalid\n", "plugin", id="plugin"), ], ) def test_load_evals_config_rejects_non_string_keys(tmp_path, document, field): diff --git a/tests/tier3/test_public_plugin_workflow.py b/tests/tier3/test_public_plugin_workflow.py new file mode 100644 index 000000000..02eefd45f --- /dev/null +++ b/tests/tier3/test_public_plugin_workflow.py @@ -0,0 +1,37 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Public runtime options and the shared service boundary.""" + +from pathlib import Path + +import pytest + +from skillevaluator.evaluation import EvaluationOptions +from skillevaluator.evaluation.options import PluginOptions + + +@pytest.mark.parametrize("value", [-1, 6, True, 1.5]) +def test_public_retry_option_is_a_bounded_integer(value): + with pytest.raises(ValueError, match="trial_retries"): + PluginOptions(trial_retries=value) + + +@pytest.mark.parametrize( + "field,value", + [("plugin_load", "other"), ("lift_mode", "other"), ("probe_mcp", 1), ("policy", {}), ("policy", "default")], +) +def test_public_options_validate_direct_api_values(field, value): + with pytest.raises(ValueError, match=field): + PluginOptions(**{field: value}) + + +def test_plugin_controls_do_not_leak_into_skill_engine_kwargs(): + assert ( + not {"plugin_load", "lift_mode", "probe_mcp", "trial_retries"} + & EvaluationOptions(Path("skill")).engine_kwargs().keys() + ) + + +@pytest.mark.parametrize("value", ["strict", {"MCP_DECLARATION.*": "critical"}]) +def test_plugin_policy_must_be_a_validation_policy(value): + with pytest.raises(ValueError, match="policy"): + PluginOptions(policy=value) diff --git a/tests/validators/test_public_plugin_policy.py b/tests/validators/test_public_plugin_policy.py new file mode 100644 index 000000000..c6a291692 --- /dev/null +++ b/tests/validators/test_public_plugin_policy.py @@ -0,0 +1,131 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Operator plugin policy is bounded, explicit and bound to report provenance.""" + +import hashlib +import json + +import pytest + +from skillevaluator.validators import policy as policy_module +from skillevaluator.validators.policy import ValidationPolicy, load_policy_file + + +def test_default_policy_digest_and_summary_stay_compatible(): + policy = ValidationPolicy() + payload = { + "profile": "default", + "audience": "all", + "author_email_regex": None, + "severity_overrides": {}, + "metadata_id_requirement": "ignore", + } + expected = ( + "sha256:" + hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()).hexdigest() + ) + assert policy.digest == expected + assert set(policy.to_dict()) == { + "profile", + "audience", + "digest", + "author_email_regex", + "severity_overrides", + "metadata_id_requirement", + "source", + } + + +def test_allowlists_are_typed_redacted_and_order_independent(): + first = ValidationPolicy( + mcp_allowed_private_hosts=("127.0.0.1", "*.corp.example"), + hook_allowed_urls=("https://hooks.example.test/events",), + ) + second = ValidationPolicy( + mcp_allowed_private_hosts=("*.corp.example", "127.0.0.1"), + hook_allowed_urls=("https://hooks.example.test/events",), + ) + assert first.digest == second.digest != ValidationPolicy().digest + summary = first.to_dict() + assert summary["mcp_allowed_private_host_count"] == 2 + assert summary["hook_allowed_url_count"] == 1 + assert "corp.example" not in json.dumps(summary) and "hooks.example.test" not in json.dumps(summary) + assert first.resolve_endpoints is False + + +def test_existing_host_patterns_and_ip_notation_remain_supported(): + entries = ("localhost", "*.corp.example", "10.0.0.0/8", "::1", "[::1]") + assert ValidationPolicy(mcp_allowed_private_hosts=entries).mcp_allowed_private_hosts == entries + + +@pytest.mark.parametrize( + "value", + [ + "localhost", + {"host": "localhost"}, + [True], + [1], + [""], + ["x" * 256], + ["a"] * 65, + ["local\nlocalhost"], + ["169.254.169.254"], + ["metadata.google.internal"], + ["https://localhost"], + ["localhost/path"], + ["localhost:9000"], + ["*"], + ], +) +def test_invalid_mcp_host_entries_fail_closed(value): + with pytest.raises(ValueError): + ValidationPolicy(mcp_allowed_private_hosts=value) + + +@pytest.mark.parametrize( + "value", + [ + ["https://user:secret@hooks.example.test"], + ["https://hooks.example.test/path?token=secret"], + ["https://hooks.example.test/#fragment"], + ["https://169.254.169.254/latest"], + ["ftp://hooks.example.test"], + ["x" * 2049], + ["https://hooks.example.test/\u202e"], + ], +) +def test_invalid_hook_url_prefixes_fail_closed(value): + with pytest.raises(ValueError): + ValidationPolicy(hook_allowed_urls=value) + + +@pytest.mark.parametrize("value", ["true", 1, [], {}]) +def test_endpoint_opt_in_requires_boolean(value): + with pytest.raises(ValueError, match=r"endpoints\.resolve"): + ValidationPolicy(resolve_endpoints=value) + + +def test_custom_overlay_preserves_omitted_keys_and_allows_explicit_clearing(tmp_path, monkeypatch): + base = ValidationPolicy( + mcp_allowed_private_hosts=("localhost",), + hook_allowed_urls=("https://hooks.example.test/",), + resolve_endpoints=True, + ) + monkeypatch.setattr(policy_module, "load_profile", lambda _name: base) + path = tmp_path / "policy.yml" + path.write_text("mcp: {}\nhooks: {}\nendpoints: {}\n") + preserved = load_policy_file(path) + assert preserved.mcp_allowed_private_hosts == base.mcp_allowed_private_hosts + assert preserved.hook_allowed_urls == base.hook_allowed_urls and preserved.resolve_endpoints is True + path.write_text("mcp:\n allowed_private_hosts: []\nhooks:\n allowed_urls: null\nendpoints:\n resolve: false\n") + cleared = load_policy_file(path) + assert cleared.mcp_allowed_private_hosts == cleared.hook_allowed_urls == () + assert cleared.resolve_endpoints is False + + +@pytest.mark.parametrize( + "document", ["mcp: []", "hooks: 3", "endpoints:\n unexpected: true", "mcp:\n allow_all: true"] +) +def test_plugin_policy_blocks_reject_unknown_shapes(tmp_path, document): + path = tmp_path / "policy.yml" + path.write_text(document) + with pytest.raises(ValueError): + load_policy_file(path) From a57940df76a8d0fee59410dd257a5737b6e8bb0a Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Fri, 20 Nov 2026 20:38:51 -0800 Subject: [PATCH 2/9] fix(policy): reject ambiguous allowlist hosts and test the new settings Host entries can no longer contain '%'. The host matcher percent-decodes an entry, so %2A, a%20b or 0.0.0.0%2F0 loaded as names or networks that had skipped the syntax checks. A host that starts with '.' (the error points to the '*.suffix' form) or has an empty label is rejected, and the host of a URL entry follows the same wildcard and label rules, so http://*/ no longer loads. With --backend nemo-gym, the config check rejects harbor.trial_retries above 0 and the load and lift_mode settings of the new top-level block, which no Gym run reads. Limit the run options docstring to what the class does. Add CHANGELOG entries for the policy and evals/config.yml parsing changes. Add tests for the evals/config.yml settings, the run options bounds and allowlists, the allowlist normalizer and parser rules, and the results-directory helper. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Narendran Raghavan --- CHANGELOG.md | 12 +++ src/skillevaluator/evaluation/options.py | 10 +- src/skillevaluator/tier3/nemo_gym/backend.py | 6 ++ .../validators/plugin_policy.py | 28 ++++-- tests/test_nemo_gym_backend.py | 34 +++++++ tests/test_results_location.py | 32 ++++++ tests/tier3/test_evals_config.py | 38 +++++++ tests/tier3/test_public_plugin_workflow.py | 33 +++++++ tests/validators/test_public_plugin_policy.py | 99 ++++++++++++++----- 9 files changed, 253 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 19d1cc5ac..ec14f948d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,18 @@ All notable changes to SkillEvaluator are documented in this file. when the catalog has no eligible entries to compare against. These queries return an empty result without constructing the provider client, including when that provider is missing or unreachable. +- Validation policy files accept `mcp.allowed_private_hosts`, + `hooks.allowed_urls` and `endpoints.resolve`. These blocks were ignored with an + `Ignoring unknown top-level key(s)` warning; now a malformed block stops + `validate --policy` with an error, and a valid one changes the policy digest + recorded in result metadata and adds entry counts, never the hosts or URLs, + to the policy summary. No check reads these settings yet. +- `evals/config.yml` accepts `harbor.trial_retries` (0 to 5) and an optional + top-level block with `load` and `lift_mode`, which were rejected as unknown + keys. They are validated now and reserved for a Tier 3 workflow for prepared + runtime packages. No command reads them yet, so skill runs ignore them, and + `--backend nemo-gym` rejects a config that sets `trial_retries` above 0, + `load` or `lift_mode`. ### Documentation diff --git a/src/skillevaluator/evaluation/options.py b/src/skillevaluator/evaluation/options.py index c8afb4fd2..70ab0a4b7 100644 --- a/src/skillevaluator/evaluation/options.py +++ b/src/skillevaluator/evaluation/options.py @@ -104,12 +104,12 @@ def engine_kwargs(self) -> dict[str, Any]: @dataclass(frozen=True) class PluginOptions: - """Plugin runtime controls; unset values defer to authored configuration. + """Run controls for a prepared runtime package, validated on construction. - ``policy`` is the operator's validation policy. Its severity overrides - decide which manifest and component findings refuse the run before any - agent starts, as they decide Tier 1 blocking. ``None`` keeps each check's - default severity. + Every field is unset by default (``None`` or empty). Construction checks + every field except ``repo_root`` and normalizes the two allowlists by the + validation policy rules. The class only holds these values; it applies + none of them. ``policy`` must be a ``ValidationPolicy`` when given. """ plugin_load: str | None = None diff --git a/src/skillevaluator/tier3/nemo_gym/backend.py b/src/skillevaluator/tier3/nemo_gym/backend.py index a6ebc966b..a03d5a3eb 100644 --- a/src/skillevaluator/tier3/nemo_gym/backend.py +++ b/src/skillevaluator/tier3/nemo_gym/backend.py @@ -379,6 +379,12 @@ def nemo_gym_config_errors( 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") + # No Gym run reads these settings; zero retries is Gym's own behavior. + if harbor.get("trial_retries"): + errors.append("harbor.trial_retries is not supported with --backend nemo-gym yet") + errors.extend( + f"plugin.{name} is not supported with --backend nemo-gym" for name in sorted(config.get("plugin") or {}) + ) if mcp_error := mcp_servers_error(skill_path): errors.append(mcp_error) if uses_native_harbor_tasks(skill_path, harbor.get("task_source", "auto")) and native_mcp_servers_declared( diff --git a/src/skillevaluator/validators/plugin_policy.py b/src/skillevaluator/validators/plugin_policy.py index b408189d3..c454987e6 100644 --- a/src/skillevaluator/validators/plugin_policy.py +++ b/src/skillevaluator/validators/plugin_policy.py @@ -18,7 +18,7 @@ def normalize_plugin_allowlist(value: object, key: str, max_chars: int) -> tuple return () # Default policies stay cheap for ordinary skills and base installations. from skillevaluator.plugin_component_risk import hook_url_entry_problem - from skillevaluator.validators.mcp_static import HostAllowlist, classify_endpoint_host + from skillevaluator.validators.mcp_static import classify_endpoint_host from skillevaluator.validators.url_policy import url_ambiguities normalized = [] @@ -39,8 +39,11 @@ def normalize_plugin_allowlist(value: object, key: str, max_chars: int) -> tuple if parsed.scheme.lower() not in {"http", "https"}: raise ValueError(f"{key} URL prefixes must use HTTP or HTTPS") host = parsed.hostname + if host: + _check_host_pattern(host, key) else: - if any(char.isspace() for char in entry) or any(char in entry for char in "@?#\\"): + # The host matcher percent-decodes an entry, so '%' could spell any rejected character. + if any(char.isspace() for char in entry) or any(char in entry for char in "%@?#\\"): raise ValueError(f"{key} contains an invalid host pattern") if "/" in entry or ":" in entry: try: @@ -49,11 +52,7 @@ def normalize_plugin_allowlist(value: object, key: str, max_chars: int) -> tuple ) except ValueError as exc: raise ValueError(f"{key} contains an invalid IP address or network") from exc - if "*" in entry and (not entry.startswith("*.") or "*" in entry[2:]): - raise ValueError(f"{key} contains an invalid host wildcard") - hosts = HostAllowlist.from_entries((entry,)) - if not (hosts.names or hosts.suffixes or hosts.networks): - raise ValueError(f"{key} contains an invalid host pattern") + _check_host_pattern(entry, key) host = entry endpoint = classify_endpoint_host(host) if host else None if endpoint is not None and endpoint.kind == "metadata": @@ -62,6 +61,21 @@ def normalize_plugin_allowlist(value: object, key: str, max_chars: int) -> tuple return tuple(dict.fromkeys(normalized)) +def _check_host_pattern(host: str, key: str) -> None: + """Reject a host that the matcher would keep as a name no real host can have.""" + from skillevaluator.validators.mcp_static import HostAllowlist + + if "*" in host and (not host.startswith("*.") or "*" in host[2:]): + raise ValueError(f"{key} contains an invalid host wildcard") + hosts = HostAllowlist.from_entries((host,)) + if not (hosts.names or hosts.suffixes or hosts.networks): + raise ValueError(f"{key} contains an invalid host pattern") + if any(name.startswith(".") for name in hosts.names): + raise ValueError(f"{key} contains a host that starts with '.'; use the '*.suffix' form to allow subdomains") + if any(".." in name for name in (*hosts.names, *hosts.suffixes)): + raise ValueError(f"{key} contains a host with an empty label") + + def plugin_policy_block(data: dict, name: str, known: set[str]) -> dict: """Reject misspelled controls instead of silently widening operator intent.""" block = data.get(name) diff --git a/tests/test_nemo_gym_backend.py b/tests/test_nemo_gym_backend.py index fb69260a0..bc21e51fa 100644 --- a/tests/test_nemo_gym_backend.py +++ b/tests/test_nemo_gym_backend.py @@ -1379,6 +1379,40 @@ def test_config_errors_let_cli_overrides_win(tmp_path: Path) -> None: ) +@pytest.mark.parametrize( + ("setting", "error"), + [ + pytest.param( + "harbor:\n trial_retries: 2\n", + "harbor.trial_retries is not supported with --backend nemo-gym yet", + id="trial-retries", + ), + pytest.param("plugin:\n load: wrapper\n", "plugin.load is not supported with --backend nemo-gym", id="load"), + pytest.param( + "plugin:\n lift_mode: effectiveness\n", + "plugin.lift_mode is not supported with --backend nemo-gym", + id="lift-mode", + ), + ], +) +def test_config_errors_reject_settings_gym_does_not_read(tmp_path: Path, setting: str, error: str) -> None: + from skillevaluator.tier3.nemo_gym.backend import nemo_gym_config_errors + + (tmp_path / "evals").mkdir() + (tmp_path / "evals" / "config.yml").write_text(f"schema_version: 1\n{setting}", encoding="utf-8") + assert nemo_gym_config_errors(tmp_path) == [error] + + +def test_config_errors_accept_zero_trial_retries_and_an_empty_block(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\nplugin: {}\nharbor:\n trial_retries: 0\n", encoding="utf-8" + ) + assert nemo_gym_config_errors(tmp_path) == [] + + def test_workflow_preflight_rejects_environment_kwarg(tmp_path: Path) -> None: import click diff --git a/tests/test_results_location.py b/tests/test_results_location.py index 26acbebea..130538fa0 100644 --- a/tests/test_results_location.py +++ b/tests/test_results_location.py @@ -600,3 +600,35 @@ def mock_windows_reparse(path: Path, metadata: os.stat_result) -> bool: monkeypatch.setattr(results_location, "_path_is_link_or_reparse", mock_windows_reparse) assert resolve_latest_results(skill_path, cli_results_dir, environ={}) == expected + + +@pytest.mark.parametrize( + ("requested", "configured", "expected"), + [ + pytest.param("requested", "~/configured", "requested", id="request-wins"), + pytest.param(None, "~/configured", "home/configured", id="environment-expands-home"), + pytest.param(None, "", "root/results", id="empty-environment"), + pytest.param(None, None, "root/results", id="unset-environment"), + ], +) +def test_results_directory_prefers_request_then_environment_then_root( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + requested: str | None, + configured: str | None, + expected: str, +) -> None: + home = tmp_path / "home" + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("USERPROFILE", str(home)) + if configured is None: + monkeypatch.delenv(results_location.ENV_RESULTS_DIR, raising=False) + else: + monkeypatch.setenv(results_location.ENV_RESULTS_DIR, configured) + + selected = results_location.plugin_results_directory( + tmp_path / "root", None if requested is None else tmp_path / requested + ) + + assert selected == tmp_path / expected + assert list(tmp_path.iterdir()) == [] diff --git a/tests/tier3/test_evals_config.py b/tests/tier3/test_evals_config.py index b292e5fc3..a9548f3d6 100644 --- a/tests/tier3/test_evals_config.py +++ b/tests/tier3/test_evals_config.py @@ -340,6 +340,44 @@ def test_load_evals_config_rejects_non_string_keys(tmp_path, document, field): load_evals_config(skill) +@pytest.mark.parametrize("retries", [0, 5]) +def test_load_evals_config_reads_load_lift_mode_and_trial_retries(tmp_path, retries): + skill = _skill_with_config( + tmp_path, + f"schema_version: 1\nplugin:\n load: native\n lift_mode: ladder\nharbor:\n trial_retries: {retries}\n", + ) + + config, _ = load_evals_config(skill) + + assert config["plugin"] == {"load": "native", "lift_mode": "ladder"} + assert config["harbor"]["trial_retries"] == retries + + +@pytest.mark.parametrize( + ("document", "message"), + [ + pytest.param("harbor:\n trial_retries: 6\n", r"harbor\.trial_retries must be between 0 and 5", id="retries-6"), + pytest.param("harbor:\n trial_retries: -1\n", r"harbor\.trial_retries must be >= 0", id="retries-negative"), + pytest.param( + "harbor:\n trial_retries: true\n", r"harbor\.trial_retries must be an integer", id="retries-bool" + ), + pytest.param( + "harbor:\n trial_retries: 1.5\n", r"harbor\.trial_retries must be an integer", id="retries-float" + ), + pytest.param("plugin:\n load: eager\n", r"plugin\.load must be one of: auto, native, wrapper", id="load"), + pytest.param("plugin:\n lift_mode: all\n", r"plugin\.lift_mode must be one of: both, ", id="lift-mode"), + pytest.param("plugin:\n loader: native\n", r"unknown plugin key\(s\): loader", id="unknown-key"), + pytest.param("plugin:\n", "plugin must be a mapping", id="null-block"), + pytest.param("plugin:\n - load\n", "plugin must be a mapping", id="list-block"), + ], +) +def test_load_evals_config_rejects_invalid_load_lift_mode_and_trial_retries(tmp_path, document, message): + skill = _skill_with_config(tmp_path, f"schema_version: 1\n{document}") + + with pytest.raises(EvalsConfigError, match=f": {message}"): + load_evals_config(skill) + + @pytest.mark.parametrize( ("content", "message"), [ diff --git a/tests/tier3/test_public_plugin_workflow.py b/tests/tier3/test_public_plugin_workflow.py index 02eefd45f..5c82c10e1 100644 --- a/tests/tier3/test_public_plugin_workflow.py +++ b/tests/tier3/test_public_plugin_workflow.py @@ -15,6 +15,39 @@ def test_public_retry_option_is_a_bounded_integer(value): PluginOptions(trial_retries=value) +@pytest.mark.parametrize("value", [["A"], ("A",) * 65, ("x" * 513,), (1,)]) +def test_probe_mcp_env_is_a_bounded_tuple_of_strings(value): + with pytest.raises(ValueError, match="probe_mcp_env"): + PluginOptions(probe_mcp_env=value) + + +def test_probe_mcp_env_accepts_grants_at_the_bounds(): + grants = ("x" * 512,) * 64 + assert PluginOptions(probe_mcp_env=grants).probe_mcp_env == grants + + +@pytest.mark.parametrize( + ("field", "value", "match"), + [ + ("allowed_private_hosts", ("169.254.169.254",), "cloud metadata"), + ("allowed_private_hosts", (".corp.example",), r"\*\.suffix"), + ("hook_allowed_urls", ("ftp://h.example.test",), "HTTP or HTTPS"), + ], +) +def test_run_option_allowlists_follow_the_policy_rules(field, value, match): + with pytest.raises(ValueError, match=match): + PluginOptions(**{field: value}) + + +def test_run_option_allowlists_are_stripped_and_deduplicated(): + options = PluginOptions( + allowed_private_hosts=(" localhost ", "localhost"), + hook_allowed_urls=(" https://h.example.test/ ", "https://h.example.test/"), + ) + assert options.allowed_private_hosts == ("localhost",) + assert options.hook_allowed_urls == ("https://h.example.test/",) + + @pytest.mark.parametrize( "field,value", [("plugin_load", "other"), ("lift_mode", "other"), ("probe_mcp", 1), ("policy", {}), ("policy", "default")], diff --git a/tests/validators/test_public_plugin_policy.py b/tests/validators/test_public_plugin_policy.py index c6a291692..cdfb52fd1 100644 --- a/tests/validators/test_public_plugin_policy.py +++ b/tests/validators/test_public_plugin_policy.py @@ -56,47 +56,82 @@ def test_existing_host_patterns_and_ip_notation_remain_supported(): assert ValidationPolicy(mcp_allowed_private_hosts=entries).mcp_allowed_private_hosts == entries +def test_allowlist_entries_are_stripped_and_deduplicated(): + policy = ValidationPolicy( + mcp_allowed_private_hosts=(" localhost ", "localhost", "*.corp.example "), + hook_allowed_urls=(" https://hooks.example.test/ ", "https://hooks.example.test/"), + ) + assert policy.mcp_allowed_private_hosts == ("localhost", "*.corp.example") + assert policy.hook_allowed_urls == ("https://hooks.example.test/",) + + @pytest.mark.parametrize( - "value", + ("value", "match"), [ - "localhost", - {"host": "localhost"}, - [True], - [1], - [""], - ["x" * 256], - ["a"] * 65, - ["local\nlocalhost"], - ["169.254.169.254"], - ["metadata.google.internal"], - ["https://localhost"], - ["localhost/path"], - ["localhost:9000"], - ["*"], + ("localhost", "must be a list of at most 64 strings"), + ({"host": "localhost"}, "must be a list of at most 64 strings"), + ([True], "nonempty strings of at most 255 characters"), + ([1], "nonempty strings of at most 255 characters"), + ([""], "nonempty strings of at most 255 characters"), + (["x" * 256], "nonempty strings of at most 255 characters"), + (["a"] * 65, "must be a list of at most 64 strings"), + (["local\nlocalhost"], "control or invisible"), + (["local\u200bhost"], "control or invisible"), + (["localhost\u0000"], "control or invisible"), + (["169.254.169.254"], "cloud metadata"), + (["metadata.google.internal"], "cloud metadata"), + (["https://localhost"], "invalid URL prefix"), + (["localhost/path"], "invalid IP address or network"), + (["localhost:9000"], "invalid IP address or network"), + (["*"], "invalid host wildcard"), + (["user@localhost"], "invalid host pattern"), + (["a?b"], "invalid host pattern"), + (["a#b"], "invalid host pattern"), + (["a\\b"], "invalid host pattern"), + (["%2A"], "invalid host pattern"), + (["a%20b"], "invalid host pattern"), + (["example.com%3a8080"], "invalid host pattern"), + (["user%40localhost"], "invalid host pattern"), + (["0.0.0.0%2F0"], "invalid host pattern"), + ([".corp.example"], r"starts with '\.'.*\*\.suffix"), + (["\uff0ecorp.example"], r"starts with '\.'"), + (["example..com"], "empty label"), + (["*..corp.example"], "empty label"), ], ) -def test_invalid_mcp_host_entries_fail_closed(value): - with pytest.raises(ValueError): +def test_invalid_mcp_host_entries_fail_closed(value, match): + with pytest.raises(ValueError, match=match): ValidationPolicy(mcp_allowed_private_hosts=value) @pytest.mark.parametrize( - "value", + ("value", "match"), [ - ["https://user:secret@hooks.example.test"], - ["https://hooks.example.test/path?token=secret"], - ["https://hooks.example.test/#fragment"], - ["https://169.254.169.254/latest"], - ["ftp://hooks.example.test"], - ["x" * 2049], - ["https://hooks.example.test/\u202e"], + (["https://user:secret@hooks.example.test"], "invalid URL prefix"), + (["https://hooks.example.test/path?token=secret"], "invalid URL prefix"), + (["https://hooks.example.test/#fragment"], "invalid URL prefix"), + # Only the URL-ambiguity check rejects a percent-encoded host. + (["https://hooks%2Eexample.test/"], "invalid URL prefix"), + (["https://169.254.169.254/latest"], "cloud metadata"), + (["ftp://hooks.example.test"], "HTTP or HTTPS"), + (["x" * 2049], "nonempty strings of at most 2048 characters"), + (["https://hooks.example.test/\u202e"], "control or invisible"), + (["http://*/"], "invalid host wildcard"), + (["http://*.*/"], "invalid host wildcard"), + (["https://.hooks.example.test/"], r"starts with '\.'"), + (["https://hooks..example.test/"], "empty label"), ], ) -def test_invalid_hook_url_prefixes_fail_closed(value): - with pytest.raises(ValueError): +def test_invalid_hook_url_prefixes_fail_closed(value, match): + with pytest.raises(ValueError, match=match): ValidationPolicy(hook_allowed_urls=value) +def test_hook_url_prefixes_keep_the_host_wildcard_form(): + entries = ("https://*.hooks.example.test/events", "hooks.example.test") + assert ValidationPolicy(hook_allowed_urls=entries).hook_allowed_urls == entries + + @pytest.mark.parametrize("value", ["true", 1, [], {}]) def test_endpoint_opt_in_requires_boolean(value): with pytest.raises(ValueError, match=r"endpoints\.resolve"): @@ -121,6 +156,16 @@ def test_custom_overlay_preserves_omitted_keys_and_allows_explicit_clearing(tmp_ assert cleared.resolve_endpoints is False +def test_null_block_keeps_the_base_value_and_null_resolve_clears_it(tmp_path, monkeypatch): + base = ValidationPolicy(mcp_allowed_private_hosts=("localhost",), resolve_endpoints=True) + monkeypatch.setattr(policy_module, "load_profile", lambda _name: base) + path = tmp_path / "policy.yml" + path.write_text("mcp: null\nendpoints:\n resolve: null\n", encoding="utf-8") + loaded = load_policy_file(path) + assert loaded.mcp_allowed_private_hosts == ("localhost",) + assert loaded.resolve_endpoints is False + + @pytest.mark.parametrize( "document", ["mcp: []", "hooks: 3", "endpoints:\n unexpected: true", "mcp:\n allow_all: true"] ) From 37804ed4b153f3cde3ce5088adfe2aae15a03243 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Sun, 22 Nov 2026 19:41:11 -0800 Subject: [PATCH 3/9] fix(policy): reject wildcard URL prefixes and report ignored plugin settings Match hook URL prefixes to exact hosts, keep bare wildcard patterns, and reject dead host labels with leading or trailing hyphens. Report plugin settings ignored during ordinary Harbor skill runs. Signed-off-by: Narendran Raghavan --- CHANGELOG.md | 12 ++++++------ src/skillevaluator/tier3/harbor/runner.py | 9 +++++++++ src/skillevaluator/validators/plugin_policy.py | 9 ++++++++- tests/test_tier3_progress.py | 17 +++++++++++++++++ tests/validators/test_public_plugin_policy.py | 6 ++++-- 5 files changed, 44 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ec14f948d..187c34ced 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,13 +19,13 @@ All notable changes to SkillEvaluator are documented in this file. `Ignoring unknown top-level key(s)` warning; now a malformed block stops `validate --policy` with an error, and a valid one changes the policy digest recorded in result metadata and adds entry counts, never the hosts or URLs, - to the policy summary. No check reads these settings yet. + to the policy summary. A hook URL prefix requires an exact host. Use a bare + wildcard host pattern to allow all paths on its matching subdomains. - `evals/config.yml` accepts `harbor.trial_retries` (0 to 5) and an optional - top-level block with `load` and `lift_mode`, which were rejected as unknown - keys. They are validated now and reserved for a Tier 3 workflow for prepared - runtime packages. No command reads them yet, so skill runs ignore them, and - `--backend nemo-gym` rejects a config that sets `trial_retries` above 0, - `load` or `lift_mode`. + `plugin` block with `load` and `lift_mode`, which were rejected as unknown + keys. These settings are reserved for prepared runtime packages. Harbor skill + runs warn when they ignore these settings. `--backend nemo-gym` rejects a + config that sets `trial_retries` above 0, `load` or `lift_mode`. ### Documentation diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.py index 8c645b304..63af19ecd 100644 --- a/src/skillevaluator/tier3/harbor/runner.py +++ b/src/skillevaluator/tier3/harbor/runner.py @@ -5571,6 +5571,15 @@ def _run_harbor_eval_impl( return {"error": [str(exc)]} harbor_config = config.get("harbor", {}) + if _private_runtime_hooks() is None: + plugin_controls = [f"plugin.{name}" for name in sorted(config.get("plugin", {}))] + if harbor_config.get("trial_retries"): + plugin_controls.append("harbor.trial_retries") + if plugin_controls: + logger.warning( + "Only prepared plugin runs use these settings. The skill run ignores %s.", + ", ".join(plugin_controls), + ) workspace_config = config.get("skill_workspace", {}) grading_config = config.get("grading", {}) n_attempts = n_attempts if n_attempts is not None else harbor_config.get("n_attempts", 1) diff --git a/src/skillevaluator/validators/plugin_policy.py b/src/skillevaluator/validators/plugin_policy.py index c454987e6..9400a79c3 100644 --- a/src/skillevaluator/validators/plugin_policy.py +++ b/src/skillevaluator/validators/plugin_policy.py @@ -41,6 +41,8 @@ def normalize_plugin_allowlist(value: object, key: str, max_chars: int) -> tuple host = parsed.hostname if host: _check_host_pattern(host, key) + if "*" in host: + raise ValueError(f"{key} URL prefix host must be exact. Use a bare wildcard host pattern instead.") else: # The host matcher percent-decodes an entry, so '%' could spell any rejected character. if any(char.isspace() for char in entry) or any(char in entry for char in "%@?#\\"): @@ -72,8 +74,13 @@ def _check_host_pattern(host: str, key: str) -> None: raise ValueError(f"{key} contains an invalid host pattern") if any(name.startswith(".") for name in hosts.names): raise ValueError(f"{key} contains a host that starts with '.'; use the '*.suffix' form to allow subdomains") - if any(".." in name for name in (*hosts.names, *hosts.suffixes)): + names = (*hosts.names, *hosts.suffixes) + if any(".." in name for name in names): raise ValueError(f"{key} contains a host with an empty label") + if not hosts.networks and any( + label.startswith("-") or label.endswith("-") for name in names for label in name.split(".") + ): + raise ValueError(f"{key} contains an invalid host label. Hyphens must be inside a label.") def plugin_policy_block(data: dict, name: str, known: set[str]) -> dict: diff --git a/tests/test_tier3_progress.py b/tests/test_tier3_progress.py index 5e368f7c3..83b78e479 100644 --- a/tests/test_tier3_progress.py +++ b/tests/test_tier3_progress.py @@ -4118,6 +4118,23 @@ def unexpected_provider_resolution() -> None: assert transitions.count(("run-finished", "failed")) == 1 +def test_ordinary_harbor_warns_about_plugin_only_config(tmp_path, monkeypatch, caplog) -> None: + from skillevaluator.tier3.evals_config import load_evals_config + + runner, skill = _stub_runner(monkeypatch, tmp_path) + monkeypatch.setattr(runner, "load_evals_config", load_evals_config) + (skill / "evals" / "config.yml").write_text( + "schema_version: 1\nharbor:\n trial_retries: 2\nplugin:\n load: native\n lift_mode: integration\n", + encoding="utf-8", + ) + + runner.run_harbor_eval(skill, ["codex"]) + + assert "Only prepared plugin runs use these settings" in caplog.text + for name in ("harbor.trial_retries", "plugin.load", "plugin.lift_mode"): + assert name in caplog.text + + @pytest.mark.parametrize("kind", ["symlink", "hardlink"]) def test_runner_returns_error_for_unsafe_evals_config(tmp_path: Path, kind: str) -> None: from skillevaluator.tier3.harbor import runner diff --git a/tests/validators/test_public_plugin_policy.py b/tests/validators/test_public_plugin_policy.py index cdfb52fd1..fdb1c0459 100644 --- a/tests/validators/test_public_plugin_policy.py +++ b/tests/validators/test_public_plugin_policy.py @@ -96,6 +96,7 @@ def test_allowlist_entries_are_stripped_and_deduplicated(): ([".corp.example"], r"starts with '\.'.*\*\.suffix"), (["\uff0ecorp.example"], r"starts with '\.'"), (["example..com"], "empty label"), + (["-"], "invalid host label"), (["*..corp.example"], "empty label"), ], ) @@ -118,6 +119,7 @@ def test_invalid_mcp_host_entries_fail_closed(value, match): (["https://hooks.example.test/\u202e"], "control or invisible"), (["http://*/"], "invalid host wildcard"), (["http://*.*/"], "invalid host wildcard"), + (["https://*.hooks.example.test/events"], "URL prefix host must be exact"), (["https://.hooks.example.test/"], r"starts with '\.'"), (["https://hooks..example.test/"], "empty label"), ], @@ -127,8 +129,8 @@ def test_invalid_hook_url_prefixes_fail_closed(value, match): ValidationPolicy(hook_allowed_urls=value) -def test_hook_url_prefixes_keep_the_host_wildcard_form(): - entries = ("https://*.hooks.example.test/events", "hooks.example.test") +def test_hook_allowlist_accepts_exact_url_prefixes_and_wildcard_host_patterns(): + entries = ("https://hooks.example.test/events", "*.hooks.example.test") assert ValidationPolicy(hook_allowed_urls=entries).hook_allowed_urls == entries From 5921a40c9f46c9a3ee6840b61df239ed6fc9e390 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Sun, 22 Nov 2026 19:46:32 -0800 Subject: [PATCH 4/9] fix(policy): check wildcard spelling after host normalization Signed-off-by: Narendran Raghavan --- src/skillevaluator/validators/plugin_policy.py | 4 ++++ tests/validators/test_public_plugin_policy.py | 2 ++ 2 files changed, 6 insertions(+) diff --git a/src/skillevaluator/validators/plugin_policy.py b/src/skillevaluator/validators/plugin_policy.py index 9400a79c3..1b6e45e2e 100644 --- a/src/skillevaluator/validators/plugin_policy.py +++ b/src/skillevaluator/validators/plugin_policy.py @@ -75,6 +75,10 @@ def _check_host_pattern(host: str, key: str) -> None: if any(name.startswith(".") for name in hosts.names): raise ValueError(f"{key} contains a host that starts with '.'; use the '*.suffix' form to allow subdomains") names = (*hosts.names, *hosts.suffixes) + # Host patterns already had their wildcard removed by the matcher. A + # remaining asterisk is a literal introduced by normalization. + if any("*" in name for name in names): + raise ValueError(f"{key} contains an invalid host wildcard") if any(".." in name for name in names): raise ValueError(f"{key} contains a host with an empty label") if not hosts.networks and any( diff --git a/tests/validators/test_public_plugin_policy.py b/tests/validators/test_public_plugin_policy.py index fdb1c0459..ca2c64931 100644 --- a/tests/validators/test_public_plugin_policy.py +++ b/tests/validators/test_public_plugin_policy.py @@ -84,6 +84,7 @@ def test_allowlist_entries_are_stripped_and_deduplicated(): (["localhost/path"], "invalid IP address or network"), (["localhost:9000"], "invalid IP address or network"), (["*"], "invalid host wildcard"), + (["\uff0a.corp.example"], "invalid host wildcard"), (["user@localhost"], "invalid host pattern"), (["a?b"], "invalid host pattern"), (["a#b"], "invalid host pattern"), @@ -120,6 +121,7 @@ def test_invalid_mcp_host_entries_fail_closed(value, match): (["http://*/"], "invalid host wildcard"), (["http://*.*/"], "invalid host wildcard"), (["https://*.hooks.example.test/events"], "URL prefix host must be exact"), + (["https://\uff0a.hooks.example.test/events"], "invalid host wildcard"), (["https://.hooks.example.test/"], r"starts with '\.'"), (["https://hooks..example.test/"], "empty label"), ], From 2ff02e48692365db970afba9994fc8699731ea68 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Sun, 22 Nov 2026 21:10:17 -0800 Subject: [PATCH 5/9] fix(policy): check host entry characters after fullwidth folding The host matcher folds fullwidth forms to ASCII, so a host entry such as a fullwidth at sign, colon or slash loaded as a name that no host can match. Run the whitespace, reserved-character and IP-network checks on the NFKC form of the entry as well, and cover the fullwidth spellings in the invalid host entry cases. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Narendran Raghavan --- src/skillevaluator/validators/plugin_policy.py | 8 +++++--- tests/validators/test_public_plugin_policy.py | 8 ++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/skillevaluator/validators/plugin_policy.py b/src/skillevaluator/validators/plugin_policy.py index 1b6e45e2e..51c11cc19 100644 --- a/src/skillevaluator/validators/plugin_policy.py +++ b/src/skillevaluator/validators/plugin_policy.py @@ -45,12 +45,14 @@ def normalize_plugin_allowlist(value: object, key: str, max_chars: int) -> tuple raise ValueError(f"{key} URL prefix host must be exact. Use a bare wildcard host pattern instead.") else: # The host matcher percent-decodes an entry, so '%' could spell any rejected character. - if any(char.isspace() for char in entry) or any(char in entry for char in "%@?#\\"): + # It also folds fullwidth forms to ASCII, so check the folded spelling as well. + folded = unicodedata.normalize("NFKC", entry) + if any(char.isspace() for char in folded) or any(char in folded for char in "%@?#\\"): raise ValueError(f"{key} contains an invalid host pattern") - if "/" in entry or ":" in entry: + if "/" in folded or ":" in folded: try: ipaddress.ip_network( - entry[1:-1] if entry.startswith("[") and entry.endswith("]") else entry, strict=False + folded[1:-1] if folded.startswith("[") and folded.endswith("]") else folded, strict=False ) except ValueError as exc: raise ValueError(f"{key} contains an invalid IP address or network") from exc diff --git a/tests/validators/test_public_plugin_policy.py b/tests/validators/test_public_plugin_policy.py index ca2c64931..0a0d25429 100644 --- a/tests/validators/test_public_plugin_policy.py +++ b/tests/validators/test_public_plugin_policy.py @@ -94,6 +94,14 @@ def test_allowlist_entries_are_stripped_and_deduplicated(): (["example.com%3a8080"], "invalid host pattern"), (["user%40localhost"], "invalid host pattern"), (["0.0.0.0%2F0"], "invalid host pattern"), + (["user\uff20localhost"], "invalid host pattern"), + (["a\uff1fb"], "invalid host pattern"), + (["a\uff03b"], "invalid host pattern"), + (["a\uff3cb"], "invalid host pattern"), + (["\uff05\uff12\uff41"], "invalid host pattern"), + (["example.com\uff1a8080"], "invalid IP address or network"), + (["corp\uff0fpath"], "invalid IP address or network"), + (["\uff11\uff10.\uff10.\uff10.\uff10\uff0f\uff19\uff19"], "invalid IP address or network"), ([".corp.example"], r"starts with '\.'.*\*\.suffix"), (["\uff0ecorp.example"], r"starts with '\.'"), (["example..com"], "empty label"), From fb295717baf25e605e2f90b83759e1adbcaf9c17 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan <32655573+rng1995@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:41:00 -0800 Subject: [PATCH 6/9] feat(tier1): add a runner for the bounded static checks (#853) * feat(tier1): add a runner for the bounded static checks Add a Tier 1 runner (a new module in tier1/) for the existing bounded static-check assembler, which checks a folder whose manifest declares member skills and other components such as hooks and MCP servers. The runner runs those checks with the options of a Tier 1 skill run. No CLI command or public API entry point reaches it yet, so there is no user-visible change. - New runner: check selection and skips, LLM verification, quality settings, PII waivers, policy allowlists, fail-fast, progress and the SkillSpector baseline. Each result is reported under a Tier 1 check name with publication evidence. - Check assembler (tier1/): injectable check factories, fail-fast and progress callbacks. repo_root and the hook URL allowlist reach the dependency and endpoint checks, and a complete tree snapshot records a success detail. - validate_inventory_schema passes repo_root to the dependency records. collect_endpoint_targets adds the hosts of hook URL allowlist prefixes to hook endpoint targets only, not to MCP targets. - Static evidence projection (reporting/): a result counts as blocking only when its canonical status is failed, so a scan that is only incomplete stays incomplete. Only three report modules that no CLI command reaches call the projection. - reporting/base.py: assess_publication no longer counts the quality-score name of a result scoped to a member skill as a separate target identity. The result's publication target is still compared. The tests call the runner directly, because no command routes to it yet. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Narendran Raghavan * fix(tier1): report the dependency audit and honor fail-fast in the runner - Tag the dependency audit with its check and report it as "Dependency Vulnerability Audit" under the dependency check, as a skill run does. - Resolve both paths before mapping a SkillSpector baseline into the scan view, and keep the source path when no staged copy exists. - Stop fail-fast after a failed tree staging or endpoint check. - Reject schema in the skip list: the manifest and component check always runs and is reported under it. - Name PII waiver review rows relative to the target, as the PII findings are named. - Add runner tests for these fixes and for the policy, previous version, repo root and continue-on-failure wiring. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Narendran Raghavan --------- Signed-off-by: Narendran Raghavan Co-authored-by: Claude Opus 5.5 --- src/skillevaluator/plugin_dependency_audit.py | 11 +- src/skillevaluator/reporting/base.py | 27 +- src/skillevaluator/reporting/plugin_static.py | 5 +- src/skillevaluator/tier1/plugin_checks.py | 106 +++- src/skillevaluator/tier1/plugin_public.py | 331 +++++++++++ .../validators/private_plugin_schema.py | 5 +- tests/cli/test_public_plugin_publication.py | 122 ++++ tests/cli/test_public_plugin_static.py | 538 ++++++++++++++++++ .../reporting/test_private_static_reports.py | 31 + tests/test_progress_output.py | 18 + tests/validators/test_public_plugin_policy.py | 16 + tests/validators/test_security.py | 81 +++ tests/validators/test_skillspector_scope.py | 13 + 13 files changed, 1279 insertions(+), 25 deletions(-) create mode 100644 src/skillevaluator/tier1/plugin_public.py create mode 100644 tests/cli/test_public_plugin_publication.py create mode 100644 tests/cli/test_public_plugin_static.py diff --git a/src/skillevaluator/plugin_dependency_audit.py b/src/skillevaluator/plugin_dependency_audit.py index 762f8960a..d93d86c73 100644 --- a/src/skillevaluator/plugin_dependency_audit.py +++ b/src/skillevaluator/plugin_dependency_audit.py @@ -392,7 +392,11 @@ def collect_audit_inputs( def collect_endpoint_targets( - mcp: Iterable[Any], hooks: Iterable[Any], *, allowed_hosts: tuple[str, ...] = () + mcp: Iterable[Any], + hooks: Iterable[Any], + *, + allowed_hosts: tuple[str, ...] = (), + hook_allowed_urls: tuple[str, ...] = (), ) -> tuple[EndpointTarget, ...]: """Preserve every MCP, OAuth metadata, and HTTP hook source attribution.""" targets = [] @@ -411,9 +415,12 @@ def collect_endpoint_targets( value, "mcp", f"{declaration.name}.{field_name}", declaration.file, allowed_hosts=allowed_hosts ) ) + from skillevaluator.plugin_component_risk import hook_allowlist_hosts + + hook_hosts = tuple(dict.fromkeys((*allowed_hosts, *hook_allowlist_hosts(hook_allowed_urls)))) for hook in hooks: if isinstance(hook.url, str) and hook.url: - targets.append(EndpointTarget(hook.url, "hook", hook.id, hook.file, allowed_hosts=allowed_hosts)) + targets.append(EndpointTarget(hook.url, "hook", hook.id, hook.file, allowed_hosts=hook_hosts)) return tuple(targets) diff --git a/src/skillevaluator/reporting/base.py b/src/skillevaluator/reporting/base.py index 4b7600ec7..2d77f65e2 100644 --- a/src/skillevaluator/reporting/base.py +++ b/src/skillevaluator/reporting/base.py @@ -2500,20 +2500,31 @@ def assess_publication( peer_skill_names: dict[str, str] = {} for result in results: - if not is_tier3_result(result) and result_publication_evidence(result) is None: + producer = result_publication_evidence(result) + if not is_tier3_result(result) and producer is None: continue metadata = result.metadata if isinstance(result.metadata, dict) else {} candidates: list[object] = [metadata.get("skill_name"), metadata.get("target_skill_name")] - quality = metadata.get("quality_scores") - if isinstance(quality, dict): - candidates.append(quality.get("skill_name")) - quality_all = metadata.get("quality_scores_all") - if isinstance(quality_all, list): - candidates.extend(item.get("skill_name") for item in quality_all if isinstance(item, dict)) + result_target = _result_publication_target(result) + member_quality = bool( + producer is not None + and producer.tier == 1 + and producer.check_id == "quality" + and isinstance(metadata.get("plugin_member"), str) + and metadata["plugin_member"] + and result_target is not None + ) + if not member_quality: + quality = metadata.get("quality_scores") + if isinstance(quality, dict): + candidates.append(quality.get("skill_name")) + quality_all = metadata.get("quality_scores_all") + if isinstance(quality_all, list): + candidates.extend(item.get("skill_name") for item in quality_all if isinstance(item, dict)) agent_eval_payload = metadata.get("agent_eval") if isinstance(agent_eval_payload, dict): candidates.append(_agent_eval_consistent_text_field(agent_eval_payload, "skill_name")) - if (result_target := _result_publication_target(result)) is not None: + if result_target is not None: candidates.append(result_target.skill_name) for candidate in candidates: if (key := _publication_identity_key(candidate)) is not None: diff --git a/src/skillevaluator/reporting/plugin_static.py b/src/skillevaluator/reporting/plugin_static.py index 4a0fb9ef7..e4114c246 100644 --- a/src/skillevaluator/reporting/plugin_static.py +++ b/src/skillevaluator/reporting/plugin_static.py @@ -14,6 +14,7 @@ from typing import TYPE_CHECKING, Any from urllib.parse import urlsplit, urlunsplit +from skillevaluator.reporting.run_status import Status, result_status from skillevaluator.utils.redaction import redact_sensitive_text from skillevaluator.utils.rich_markup import strip_terminal_controls @@ -296,8 +297,8 @@ def project_plugin_static(results: list[ValidationResult]) -> StaticPluginReport block = _mapping(metadata.get("plugin")) severities: dict[str, Counter] = {} incomplete |= result.is_incomplete or len(result.findings) > MAX_INPUT_ROWS - blocked |= bool(result.gate_failures) or ( - not result.passed and not result.is_incomplete and metadata.get("optional_skip") is not True + blocked |= result_status(result) is Status.FAILED and ( + bool(result.gate_failures) or metadata.get("optional_skip") is not True ) for finding in islice(result.findings, MAX_INPUT_ROWS): severity = getattr(finding.severity, "value", finding.severity) diff --git a/src/skillevaluator/tier1/plugin_checks.py b/src/skillevaluator/tier1/plugin_checks.py index 350863bd3..2237934e5 100644 --- a/src/skillevaluator/tier1/plugin_checks.py +++ b/src/skillevaluator/tier1/plugin_checks.py @@ -7,6 +7,7 @@ import hashlib import tempfile +from collections.abc import Callable from dataclasses import dataclass from pathlib import Path, PurePosixPath @@ -43,6 +44,7 @@ class PrivatePluginChecks: claude_validate: bool = False allowed_private_hosts: tuple[str, ...] = () hook_allowed_urls: tuple[str, ...] = () + repo_root: Path | None = None def _tree_checks(): @@ -257,7 +259,17 @@ def _run_hygiene(validator, snapshot: Path, views: dict[str, Path], skills: list return result -def run_plugin_validation(path: Path, *, options: PrivatePluginChecks | None = None) -> list[ValidationResult]: +def run_plugin_validation( + path: Path, + *, + options: PrivatePluginChecks | None = None, + tree_checks_factory: Callable | None = None, + skill_checks_factory: Callable | None = None, + fail_fast: bool = False, + on_check: Callable[[str], None] | None = None, + on_check_plan: Callable[[int], None] | None = None, + on_check_complete: Callable[[str, ValidationResult], None] | None = None, +) -> list[ValidationResult]: """Assemble a private run; network collectors require independent explicit options.""" options = options or PrivatePluginChecks() unknown = options.checks - (TREE_CHECKS | SKILL_CHECKS) @@ -267,6 +279,10 @@ def run_plugin_validation(path: Path, *, options: PrivatePluginChecks | None = N path, allowed_private_hosts=options.allowed_private_hosts, hook_allowed_urls=options.hook_allowed_urls ) if inventory is None: + if on_check_plan is not None: + on_check_plan(1) + if on_check is not None: + on_check("schema") result = ValidationResult(validator_name=VALIDATOR_NAME) result.add_finding( Finding( @@ -278,17 +294,38 @@ def run_plugin_validation(path: Path, *, options: PrivatePluginChecks | None = N ) ) result.mark_scan_incomplete("plugin-inventory") + if on_check_complete is not None: + on_check_complete("schema", result) return [result] root = inventory.root + scan_checks = options.checks & TREE_CHECKS + skill_checks = options.checks & SKILL_CHECKS + skills = sorted({m.path for m in inventory.components if m.type == "skill" and m.path and not m.problem}) + if on_check_plan is not None: + scan_count = 0 + if inventory.tree_complete: + unit_count = 1 + len(set(skills) - {"."}) + scan_count = len(scan_checks - {"hygiene"}) * unit_count + int("hygiene" in scan_checks) + scan_count += len(skill_checks) * len(skills) + on_check_plan(1 + scan_count + options.audit_dependencies + options.resolve_endpoints + options.claude_validate) # Composition is mandatory even for a narrowed scanner selection: a declared # but unreadable tree cannot claim complete coverage. - schema = validate_inventory_schema(inventory) + if on_check is not None: + on_check("schema") + schema = validate_inventory_schema(inventory, repo_root=options.repo_root) results = [schema] - scan_checks = options.checks & TREE_CHECKS - skill_checks = options.checks & SKILL_CHECKS + if on_check_complete is not None: + on_check_complete("schema", schema) + + def finish() -> list[ValidationResult]: + inventory.attribute_findings(f for result in results[1:] for f in result.findings) + schema.metadata["plugin"]["component_inventory"] = inventory.component_inventory() + return results + + if fail_fast and not schema.passed: + return finish() source_files = inventory.source_files source_complete = inventory.tree_complete - skills = sorted({m.path for m in inventory.components if m.type == "skill" and m.path and not m.problem}) if scan_checks or skill_checks: snapshot_result = ValidationResult(validator_name="Private Tree Coverage") if not inventory.tree_complete: @@ -304,14 +341,22 @@ def run_plugin_validation(path: Path, *, options: PrivatePluginChecks | None = N if hashlib.sha256(copied_manifest.read_bytes()).hexdigest() != inventory.manifest_sha256: raise SecurePathError("source_changed", "Selected manifest changed during staging.") views = _partition_views(view, Path(scratch) / "scanner-views", source_files, skills) - for key, (validator, runner) in _tree_checks().items(): + tree_validators = tree_checks_factory(root, view, views) if tree_checks_factory else _tree_checks() + for key, (validator, runner) in tree_validators.items(): if key not in scan_checks: continue if key == "hygiene": + if on_check is not None: + on_check(key) result = _run_hygiene(validator, view, views, skills, root) result.validator_name = validator.name result.validator_description = validator.description + result.metadata.update(plugin_check="hygiene", plugin_scan_scope="whole_tree") results.append(result) + if on_check_complete is not None: + on_check_complete(key, result) + if fail_fast and not result.passed: + return finish() continue if runner is None: runner = ( @@ -320,6 +365,8 @@ def run_plugin_validation(path: Path, *, options: PrivatePluginChecks | None = N or validator._validate_single_asset ) for unit, scan_view in views.items(): + if on_check is not None: + on_check(key) result = _invoke_scan(runner, scan_view, key) result.validator_name = validator.name result.validator_description = validator.description @@ -327,9 +374,13 @@ def run_plugin_validation(path: Path, *, options: PrivatePluginChecks | None = N result.metadata["plugin_scan_scope"] = "root_owned" if unit == "." else "declared_skill" _attribute_scan_result(result, unit, scan_view, root) results.append(result) + if on_check_complete is not None: + on_check_complete(key, result) + if fail_fast and not result.passed: + return finish() # Every audited client skill receives its own quality/lint/ # version/schema checks; root-owned files are scanned once above. - validators = _skill_checks() + validators = skill_checks_factory() if skill_checks_factory else _skill_checks() for relative in skills: target = view / relative if not any((target / name).is_file() for name in ("SKILL.md", "skill.md")): @@ -347,17 +398,30 @@ def run_plugin_validation(path: Path, *, options: PrivatePluginChecks | None = N for key, validator in validators.items(): if key not in skill_checks: continue + if on_check is not None: + on_check(key) result = validator.validate(target) result.validator_name = validator.name result.validator_description = validator.description result.metadata.update(plugin_check=key, plugin_member=relative) _rebase(result, view, root) results.append(result) + if on_check_complete is not None: + on_check_complete(key, result) + if fail_fast and not result.passed: + return finish() snapshot_result.metadata.update( source_files=len(source_files), scan_units=list(views), complete=not snapshot_result.is_incomplete, ) + if not snapshot_result.is_incomplete: + snapshot_result.add_success( + "plugin_tree_snapshot", + "Staged the complete plugin source tree into immutable scan units", + source_files=len(source_files), + scan_units=len(views), + ) results.append(snapshot_result) except (SecurePathError, OSError): source_complete = False @@ -372,8 +436,12 @@ def run_plugin_validation(path: Path, *, options: PrivatePluginChecks | None = N ) snapshot_result.mark_scan_incomplete("plugin-source-tree") results.append(snapshot_result) + if fail_fast and not snapshot_result.passed: + return finish() declarations = inventory.all_mcp_declarations() if options.audit_dependencies: + if on_check is not None: + on_check("dependency") if not (scan_checks or skill_checks) and source_complete: try: files = _scan_sources(root, skills) @@ -388,12 +456,22 @@ def run_plugin_validation(path: Path, *, options: PrivatePluginChecks | None = N reader = PluginRootReader(root) inputs = collect_audit_inputs(reader, source_files, mcp=declarations) audit = run_dependency_audits(reader, inputs) + audit.metadata["plugin_check"] = "dependency" if not source_complete: audit.mark_scan_incomplete("dependency-source-discovery") results.append(audit) + if on_check_complete is not None: + on_check_complete("dependency", audit) + if fail_fast and not audit.passed: + return finish() if options.resolve_endpoints: + if on_check is not None: + on_check("endpoint-resolution") targets = collect_endpoint_targets( - declarations, inventory.hook_records, allowed_hosts=options.allowed_private_hosts + declarations, + inventory.hook_records, + allowed_hosts=options.allowed_private_hosts, + hook_allowed_urls=options.hook_allowed_urls, ) summary, findings = EndpointChecker().check(targets) result = ValidationResult(validator_name="Private Endpoint Checks") @@ -403,7 +481,13 @@ def run_plugin_validation(path: Path, *, options: PrivatePluginChecks | None = N if summary.get("incomplete") or not inventory.complete: result.mark_scan_incomplete("endpoint-resolution") results.append(result) + if on_check_complete is not None: + on_check_complete("endpoint-resolution", result) + if fail_fast and not result.passed: + return finish() if options.claude_validate: + if on_check is not None: + on_check("claude-validate") results.append( ClaudePluginValidateParity().validate( root, @@ -411,6 +495,6 @@ def run_plugin_validation(path: Path, *, options: PrivatePluginChecks | None = N skillevaluator_fields=skillevaluator_manifest_fields([schema], VALIDATOR_NAME), ) ) - inventory.attribute_findings(f for result in results[1:] for f in result.findings) - schema.metadata["plugin"]["component_inventory"] = inventory.component_inventory() - return results + if on_check_complete is not None: + on_check_complete("claude-validate", results[-1]) + return finish() diff --git a/src/skillevaluator/tier1/plugin_public.py b/src/skillevaluator/tier1/plugin_public.py new file mode 100644 index 000000000..06bf2395e --- /dev/null +++ b/src/skillevaluator/tier1/plugin_public.py @@ -0,0 +1,331 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Public static options over the shared bounded plugin composition.""" + +from __future__ import annotations + +import time +from pathlib import Path + +from skillevaluator.models.result import ValidationResult + + +class _SourceWaivers: + """Match immutable scan-view paths against their original logical paths. + + Coverage is recorded for the whole target, so a waiver review row names + its file relative to the target (``skills/a/SKILL.md``), as the PII + findings do, rather than relative to the member skill's scan unit. + """ + + def __init__(self, waivers, view: Path, source: Path, root: Path): + self.waivers, self.view, self.source, self.root = waivers, view, source, root + + def cover(self, _path: Path) -> None: + self.waivers.cover(self.root) + + def matcher(self, path: Path): + return self.waivers.matcher(self.source / path.relative_to(self.view)) + + +def run_public_plugin_validation( + target_path: Path, + *, + checks=None, + skip=None, + use_llm=False, + llm_verify=False, + min_score=70, + quality_config=None, + pii_waivers=None, + previous_version=None, + policy=None, + fail_fast=False, + continue_on_failure=False, + on_check=None, + skillspector_baseline=None, + repo_root=None, + resolve_endpoints=False, + claude_validate=False, + target_root=None, +) -> list[ValidationResult]: + """Run the bounded plugin checks with the options of a Tier 1 skill run. + + The ``security`` check scans the root of the plugin and each nested skill + as separate units. The root unit, which holds every file that no nested + skill owns, accepts SkillSpector missing references as a skill scan does: + it is judged against the plugin's source tree, whose listing marks a file + left out of the staged copy, or a file of a nested skill, as not inspected, + so a line that names one stays incomplete. The unit of a nested skill + accepts none, because its lines may name a file elsewhere in the plugin. + + *target_root* is the folder that the plugin belongs to when a caller + validates that folder one skill at a time, as ``validate`` does for a + folder of skills. The ``security`` check then accepts no SkillSpector + missing reference, because the plugin's instructions may name a file + elsewhere in the folder. + + ``schema`` cannot be skipped: the manifest and component check always + runs and is reported under it. + """ + from skillevaluator.cli_core import resolve_plugin_path + from skillevaluator.constants import PLUGIN_CONTAINED_MODE, PLUGIN_MANIFEST_TYPE, PLUGIN_MODE + from skillevaluator.tier1 import commands as public + from skillevaluator.tier1.plugin_checks import PrivatePluginChecks, run_plugin_validation + from skillevaluator.validators.base import continue_on_failure_scope + from skillevaluator.validators.pii_waivers import PIIWaiverSet, configured_pii_categories + + root = resolve_plugin_path(target_path) + enabled, skipped = public._enabled_checks(checks), public.skipped_checks(skip) + unknown = (enabled - public.RECOGNIZED_CHECKS) | (skipped - public.SKIPPABLE_CHECKS) + if unknown: + result = ValidationResult(validator_name="Tier 1 option validation") + result.add_error(f"Unknown Tier 1 check(s): {', '.join(sorted(unknown))}") + return [result] + if "schema" in skipped: + result = ValidationResult(validator_name="Tier 1 option validation") + result.add_error("The schema check cannot be skipped: the manifest and component check always runs.") + return [result] + active = enabled - skipped + selected = active - {"dependency", "harness"} + if "code-integrity" in active: + selected |= {"hygiene", "secrets"} - skipped + selected = frozenset(selected) + initial_target = public.publication_target_from_path(root) + loaded_waivers = None + + def tree_factory(source_root, snapshot, views): + nonlocal loaded_waivers + from skillevaluator.validators.security import _rewrite_path_prefix + + snapshot_by_view = {view.resolve(): (snapshot / unit).resolve() for unit, view in views.items()} + # The root scan unit holds every file that no nested skill owns. + root_view = views["."].resolve() if "." in views else None + plugin_root = Path(source_root).resolve() + + class SnapshotSecurityValidator(public.SecurityValidator): + def _skillspector_issue_scopes(self, issues, components, *, source_root, report_truncated): + # Scanner inputs are partitioned, but reachability must include + # references from every component in the immutable full tree. + if source_root is not None and (scope_root := snapshot_by_view.get(source_root.resolve())) is not None: + issues = _rewrite_path_prefix(issues, str(source_root), str(scope_root)) + components = _rewrite_path_prefix(components, str(source_root), str(scope_root)) + source_root = scope_root + return super()._skillspector_issue_scopes( + issues, components, source_root=source_root, report_truncated=report_truncated + ) + + def _validate_skillspector_report(self, *args, scanned_root=None, reference_root=None, **kwargs): + # The root scan unit accepts missing references as a skill scan + # does, also beside nested skills. Like the artifact-free copy of + # a skill scan, it is judged against the source tree, whose + # listing also names what the staged copy left out and the files + # of each nested skill, which the root scan did not inspect. The + # scan unit of a nested skill, or a plugin in a folder validated + # part by part (target_root), still accepts none. + if root_view is not None and scanned_root == root_view: + scanned_root, reference_root = plugin_root, self.target_root or plugin_root + return super()._validate_skillspector_report( + *args, scanned_root=scanned_root, reference_root=reference_root, **kwargs + ) + + def mapped_option(path): + # SkillSpector excludes only the exact --baseline file, so a + # baseline inside the target must point at the staged copy that + # is scanned. A baseline that was not staged keeps its own path. + if path is None: + return None + absolute = Path(path).expanduser().resolve() + for unit in sorted(views, key=lambda item: len(Path(item).parts), reverse=True): + source = (Path(source_root) / unit).resolve() + if absolute.is_relative_to(source): + candidate = views[unit] / absolute.relative_to(source) + return candidate if candidate.is_file() else absolute + return absolute + + security = SnapshotSecurityValidator( + use_llm=use_llm, + verify_llm=llm_verify, + content_type="plugin", + skillspector_reference_root=snapshot, + skillspector_baseline=mapped_option(skillspector_baseline), + target_root=target_root, + ) + pii = public.SecurityValidator(use_llm=False, verify_llm=llm_verify) + if pii_waivers is not None and "pii" in selected: + loaded_waivers = PIIWaiverSet.load(pii_waivers, configured_pii_categories(pii.pii_patterns)) + source_by_view = {view: source_root / unit for unit, view in views.items()} + + def verify(result, validator, view): + if llm_verify and result.findings: + try: + validator._verify_findings_with_llm(result, view) + except Exception as exc: + result.mark_scan_incomplete("llm-verification") + result.add_warning( + f"Optional verification unavailable ({type(exc).__name__}); static findings retained." + ) + return result + + def security_scan(view): + return verify(security._run_skillspector(view), security, view) + + def pii_scan(view): + if loaded_waivers is not None: + pii._pii_waivers = _SourceWaivers(loaded_waivers, view, source_by_view[view], plugin_root) + try: + return verify(pii._scan_for_pii(view), pii, view) + finally: + pii._pii_waivers = None + + return { + "security": (security, security_scan), + "pii": (pii, pii_scan), + "secrets": (public.SecretsValidator(), None), + "code-integrity": (public.CodeRiskValidator(), None), + "hygiene": (public.HygieneValidator(), None), + "unicode": (public.UnicodeSmuggleValidator(), None), + "license": (public.LicenseValidator(), None), + } + + def skill_factory(): + return { + "schema": public.SchemaValidator(policy=policy), + "quality": public.QualityScoreValidator(min_score=min_score, quality_config=quality_config), + "lint": public.ScriptLintValidator(), + "version": public.VersionValidator(previous_version=previous_version), + } + + notified = set() + progress_total, progress_step, progress_started = 0, 0, 0.0 + + def plan_progress(total): + nonlocal progress_total + progress_total = total + + def notify(check): + nonlocal progress_step, progress_started + canonical = "code-integrity" if check in {"hygiene", "secrets"} else check + if on_check is None: + progress_step += 1 + progress_started = time.monotonic() + public.progress_console.print( + f"[{progress_step}/{progress_total}] {canonical} ...", markup=False, highlight=False + ) + return + if canonical in active and canonical not in notified: + notified.add(canonical) + on_check(canonical) + + def complete_progress(check, result): + if on_check is not None: + return + canonical = "code-integrity" if check in {"hygiene", "secrets"} else check + outcome = ( + f"incomplete: {', '.join(result.incomplete_scans)}" + if result.is_incomplete + else "ok" + if result.passed + else f"{result.summary.errors} error(s)" + ) + if result.summary.warnings: + outcome += f", {result.summary.warnings} warning(s)" + public.progress_console.print( + f"[{progress_step}/{progress_total}] {canonical} done in {time.monotonic() - progress_started:.1f}s ({outcome})", + markup=False, + highlight=False, + ) + + with continue_on_failure_scope(continue_on_failure): + results = run_plugin_validation( + target_path, + options=PrivatePluginChecks( + checks=selected, + audit_dependencies="dependency" in active, + resolve_endpoints=resolve_endpoints or bool(policy and policy.resolve_endpoints), + claude_validate=claude_validate, + allowed_private_hosts=policy.mcp_allowed_private_hosts if policy else (), + hook_allowed_urls=policy.hook_allowed_urls if policy else (), + repo_root=repo_root, + ), + tree_checks_factory=tree_factory, + skill_checks_factory=skill_factory, + fail_fast=fail_fast and not continue_on_failure, + on_check=notify, + on_check_plan=plan_progress, + on_check_complete=complete_progress, + ) + if loaded_waivers is not None: + waiver_result = ValidationResult(validator_name="PII Waiver Review", metadata={"plugin_check": "pii"}) + for finding, is_error in loaded_waivers.findings(root): + waiver_result.add_structured_finding(finding, is_error=is_error) + if loaded_waivers.applied: + waiver_result.add_message(f"PII waivers suppressed {len(loaded_waivers.applied)} reviewed PII value(s)") + results.append(waiver_result) + if "harness" in active: + # Native-plugin profiles are exposed through harness-check; combined + # validation does not yet run that separate advisory. + harness = ValidationResult(validator_name="Harness Compatibility", metadata={"plugin_check": "harness"}) + harness.add_success( + "harness_applicability", + "Not applicable in combined validation; use harness-check to assess native plugin loading.", + not_applicable=True, + ) + results.append(harness) + public_names = { + "Private Manifest and Component Checks": "Plugin Schema & Component Checks", + "Private Tree Coverage": "Plugin Tree Coverage", + "Private Endpoint Checks": "Plugin Endpoint Checks", + } + # Both tree scans run on SecurityValidator instances, so they share its name. + # Report each under its skill-run and --skip name; the panel maps checks by name. + scan_names = { + "security": ("Security Scan", None), + "pii": ("PII Scan", "Detect PII and local identifiers"), + } + skill_members_present = any( + member.get("type") == "skill" and member.get("path") and not member.get("problem") + for result in results + for member in result.metadata.get("plugin", {}).get("component_inventory", {}).get("components", []) + ) + for result in results: + result.validator_name = public_names.get(result.validator_name, result.validator_name) + if result.metadata.get("plugin_check") == "dependency": + result.validator_name = "Dependency Vulnerability Audit" + scan = scan_names.get(result.metadata.get("plugin_check")) + if scan is not None and result.validator_name == "Security & PII Scanning": + result.validator_name = scan[0] + result.validator_description = scan[1] or result.validator_description + if result.validator_name == "Plugin Schema & Component Checks" and result.passed and not result.is_incomplete: + result.add_success("plugin_schema", "Completed bounded plugin manifest and component checks") + if plugin := result.metadata.get("plugin"): + chosen = next((row for row in plugin.get("manifest_declarations", []) if row.get("selected")), None) + if chosen: + result.metadata["manifest_type"] = chosen["manifest_type"] + result.metadata["plugin_mode"] = ( + PLUGIN_MODE if chosen["manifest_type"] == PLUGIN_MANIFEST_TYPE else PLUGIN_CONTAINED_MODE + ) + plugin.update({key: chosen[key] for key in ("name", "version") if chosen.get(key) is not None}) + check = result.metadata.get("plugin_check", "schema") + check = "code-integrity" if check in {"hygiene", "secrets"} else check + if "endpoint_resolution" in result.metadata: + check = "schema" + public.stamp_publication_evidence([result], tier=1, check_id=check) + public.stamp_tier1_required_checks([result], skill_like=skill_members_present) + omitted = [(check, name) for check in enabled & skipped for name in public._SKIPPED_VALIDATORS[check]] + if "code-integrity" in active and "secrets" in skipped: + omitted.append(("code-integrity", "Secrets Detection")) + for check, name in omitted: + result = ValidationResult( + validator_name=name, + metadata={ + "skipped": True, + "skipped_by_user": True, + "skip_reason": public.SKIP_REASON, + }, + ) + public.stamp_publication_evidence([result], tier=1, check_id=check) + public.stamp_tier1_required_checks([result], skill_like=skill_members_present) + results.append(result) + public._stamp_tier1_scan_scope(results, root) + public.finalize_publication_target(results, root, initial_target) + return results diff --git a/src/skillevaluator/validators/private_plugin_schema.py b/src/skillevaluator/validators/private_plugin_schema.py index 9f2fa41c7..1bb9aa2cf 100644 --- a/src/skillevaluator/validators/private_plugin_schema.py +++ b/src/skillevaluator/validators/private_plugin_schema.py @@ -6,6 +6,7 @@ from __future__ import annotations import re +from pathlib import Path from typing import TYPE_CHECKING from pydantic import ValidationError @@ -31,7 +32,7 @@ MAX_SCHEMA_FINDINGS = 100 -def validate_inventory_schema(inventory: PluginInventory) -> ValidationResult: +def validate_inventory_schema(inventory: PluginInventory, *, repo_root: Path | None = None) -> ValidationResult: """Validate every declared format and compose its inventory findings. The additional manifests remain audit sources even when another client is @@ -191,7 +192,7 @@ def validate_inventory_schema(inventory: PluginInventory) -> ValidationResult: "manifest_declarations": declarations, } inventory_metadata = result.metadata["plugin"] - dependencies = dependency_records(inventory) + dependencies = dependency_records(inventory, repo_root=repo_root) result.merge(dependencies) result.metadata["plugin"] = {**inventory_metadata, **dependencies.metadata.get("plugin", {})} result.metadata["plugin"]["component_inventory"] = inventory.component_inventory() diff --git a/tests/cli/test_public_plugin_publication.py b/tests/cli/test_public_plugin_publication.py new file mode 100644 index 000000000..4a4e55bde --- /dev/null +++ b/tests/cli/test_public_plugin_publication.py @@ -0,0 +1,122 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Completed plugin checks certify their actual source and applicable lineup.""" + +import json +from pathlib import Path + +import pytest + +from skillevaluator.models.result import ValidationResult +from skillevaluator.reporting.base import ( + assess_publication, + missing_tier1_publication_checks, + result_has_execution_evidence, +) +from skillevaluator.tier1.plugin_public import run_public_plugin_validation +from skillevaluator.utils.secure_fs import SecurePathError +from skillevaluator.utils.tool_runner import ToolResult, Tools +from skillevaluator.validators.security import SecurityValidator + +CORE_CHECKS = "schema,security,pii,license,code-integrity,unicode" + + +@pytest.fixture +def clean_scanners(monkeypatch): + def skillspector(*_args, **_kwargs): + result = ValidationResult() + result.add_success("skillspector", "Scanner completed without findings") + return result + + monkeypatch.setattr(SecurityValidator, "_run_skillspector", skillspector) + monkeypatch.setattr(Tools.gitleaks, "_path", "/fixture/gitleaks") + monkeypatch.setattr( + Tools.gitleaks, + "run", + lambda *_args, **_kwargs: ToolResult(success=True, stdout="[]", stderr="", exit_code=0), + ) + + +def plugin(root: Path, *, with_member: bool) -> Path: + manifest = root / ".claude-plugin/plugin.json" + manifest.parent.mkdir(parents=True) + manifest.write_text( + json.dumps({"name": "demo", "version": "1.0.0", "description": "Demo plugin"}), encoding="utf-8" + ) + license_text = (Path(__file__).parents[2] / "LICENSE").read_text(encoding="utf-8") + (root / "LICENSE").write_text(license_text, encoding="utf-8") + if with_member: + member = root / "skills/simple" + member.mkdir(parents=True) + fixture = (Path(__file__).parents[1] / "fixtures/skills/simple/SKILL.md").read_text(encoding="utf-8") + (member / "SKILL.md").write_text( + fixture.replace("name: simple", "name: simple\nlicense: Apache-2.0"), encoding="utf-8" + ) + (member / "LICENSE").write_text(license_text, encoding="utf-8") + return root + + +def assessment(results): + for result in results: + result.metadata["benchmark_policy"] = {"tier2_required": False, "tier3_required": False} + return assess_publication(results, expected_skill_name="demo") + + +@pytest.mark.parametrize("with_member", [False, True]) +def test_complete_plugin_lineup_has_publication_execution_evidence(tmp_path, clean_scanners, with_member): + root = plugin(tmp_path / "demo", with_member=with_member) + results = run_public_plugin_validation(root, min_score=0, on_check=lambda _check: None) + + assert all(result.passed and not result.is_incomplete for result in results) + assert all(result_has_execution_evidence(result) for result in results) + assert assessment(results).status == "pass" + + +def test_core_only_run_cannot_certify_discovered_member_checks(tmp_path, clean_scanners): + root = plugin(tmp_path / "demo", with_member=True) + results = run_public_plugin_validation(root, checks=CORE_CHECKS, on_check=lambda _check: None) + + assert all(result.passed and not result.is_incomplete for result in results) + assert missing_tier1_publication_checks(results) == ("lint", "quality", "version") + assert assessment(results).status == "incomplete" + + +@pytest.mark.parametrize("mutation", ["unscoped-quality", "different-parent"]) +def test_member_quality_does_not_hide_other_target_identity_conflicts(tmp_path, clean_scanners, mutation): + root = plugin(tmp_path / "demo", with_member=True) + results = run_public_plugin_validation(root, min_score=0, on_check=lambda _check: None) + quality = next(result for result in results if result.metadata.get("plugin_check") == "quality") + assert quality.metadata["quality_scores"]["skill_name"] == "simple" + if mutation == "unscoped-quality": + quality.metadata.pop("plugin_member") + else: + quality.metadata["publication_target"]["skill_name"] = "different-parent" + + assert assessment(results).status == "incomplete" + assert "Validation results contain conflicting target skill identities." in assessment(results).reasons + + +@pytest.mark.parametrize("manifest", [None, "{broken"]) +def test_missing_or_malformed_manifest_cannot_claim_complete_schema(tmp_path, manifest): + root = plugin(tmp_path / "demo", with_member=False) + target = root / ".claude-plugin/plugin.json" + target.unlink() if manifest is None else target.write_text(manifest, encoding="utf-8") + results = run_public_plugin_validation(root, checks="schema", on_check=lambda _check: None) + + assert not results[0].passed + assert not any(detail.check_name == "plugin_schema" for detail in results[0].success_details) + assert assessment(results).status != "pass" + + +def test_failed_snapshot_does_not_claim_completed_tree_coverage(tmp_path, clean_scanners, monkeypatch): + root = plugin(tmp_path / "demo", with_member=True) + + def changed(*_args, **_kwargs): + raise SecurePathError("source_changed", "Source changed while staging") + + monkeypatch.setattr("skillevaluator.tier1.plugin_checks._snapshot", changed) + results = run_public_plugin_validation(root, checks=CORE_CHECKS, on_check=lambda _check: None) + coverage = next(result for result in results if result.validator_name == "Plugin Tree Coverage") + + assert coverage.is_incomplete + assert not coverage.success_details + assert assessment(results).status != "pass" diff --git a/tests/cli/test_public_plugin_static.py b/tests/cli/test_public_plugin_static.py new file mode 100644 index 000000000..9582ef3ca --- /dev/null +++ b/tests/cli/test_public_plugin_static.py @@ -0,0 +1,538 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Public discovery and static dispatch use the bounded component implementation.""" + +import json +from datetime import timedelta +from pathlib import Path + +import pytest +import yaml + +from skillevaluator.cli_core import detect_content_type, resolve_plugin_path +from skillevaluator.models.result import ValidationResult +from skillevaluator.publication_identity import publication_target_from_path +from skillevaluator.tier1.commands import run_validation +from skillevaluator.tier1.plugin_public import run_public_plugin_validation +from skillevaluator.validators.pii_waivers import pii_evidence_sha256, today_utc +from skillevaluator.validators.policy import ValidationPolicy +from skillevaluator.validators.security import SecurityValidator + + +def _plugin(root, *, member=True): + manifest = root / ".claude-plugin/plugin.json" + manifest.parent.mkdir(parents=True) + manifest.write_text('{"name":"demo"}', encoding="utf-8") + if member: + skill = root / "skills/a/SKILL.md" + skill.parent.mkdir(parents=True) + skill.write_text("---\nname: a\ndescription: Follow the workflow.\n---\nBody.\n", encoding="utf-8") + return root + + +@pytest.mark.parametrize( + "manifest,payload", + [ + ( + "agent_plugin.yaml", + "name: demo\nauthor:\n email: dev@example.com\nskills:\n refs: [github::org/repo::skills::demo]\n", + ), + (".claude-plugin/plugin.json", '{"name":"demo"}'), + ], +) +def test_all_profiles_detect_from_directory_or_manifest(tmp_path, manifest, payload): + path = tmp_path / manifest + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(payload, encoding="utf-8") + assert detect_content_type(tmp_path) == "plugin" + assert detect_content_type(path) == "plugin" + assert resolve_plugin_path(path) == tmp_path + schema = run_public_plugin_validation(path, checks="schema")[0] + assert schema.passed and not schema.is_incomplete + assert not any(finding.check_name == "manifest_missing_or_unsafe" for finding in schema.findings) + assert schema.metadata["publication_target"] == publication_target_from_path(tmp_path) + + +def test_unrelated_plugin_json_does_not_change_skill_detection(tmp_path): + (tmp_path / "plugin.json").write_text('{"name":"unrelated"}', encoding="utf-8") + (tmp_path / "SKILL.md").write_text( + "---\nname: ordinary\ndescription: Ordinary skill.\n---\nBody.", encoding="utf-8" + ) + assert detect_content_type(tmp_path) == "skill" + + +def test_bundled_quality_receives_public_options_once(tmp_path, monkeypatch): + from skillevaluator.tier1 import commands + + manifest = tmp_path / ".claude-plugin/plugin.json" + manifest.parent.mkdir() + manifest.write_text(json.dumps({"name": "demo"}), encoding="utf-8") + member = tmp_path / "skills/a/SKILL.md" + member.parent.mkdir(parents=True) + member.write_text("---\nname: a\ndescription: A skill.\n---\nBody.", encoding="utf-8") + seen = [] + + class Quality: + name = "Quality check" + description = "Fixture quality" + + def __init__(self, **options): + seen.append(options) + + def validate(self, path): + assert (path / "SKILL.md").is_file() + return ValidationResult() + + monkeypatch.setattr(commands, "QualityScoreValidator", Quality) + config = tmp_path / "quality.yml" + results = run_public_plugin_validation(tmp_path, checks="quality", min_score=91, quality_config=config) + assert seen == [{"min_score": 91, "quality_config": config}] + assert any(result.metadata.get("plugin_member") == "skills/a" for result in results) + + +def test_schema_failure_stops_before_scanner_construction_when_fail_fast(tmp_path, monkeypatch): + from skillevaluator.tier1 import commands + + manifest = tmp_path / ".claude-plugin/plugin.json" + manifest.parent.mkdir() + manifest.write_text("{broken", encoding="utf-8") + + def forbidden(*args, **kwargs): + pytest.fail("A scanner was constructed after a schema failure") + + monkeypatch.setattr(commands, "SecurityValidator", forbidden) + results = run_public_plugin_validation(tmp_path, fail_fast=True) + assert any(not result.passed for result in results) + + +@pytest.fixture +def plugin_with_local_scanners(tmp_path, monkeypatch): + from skillevaluator.tier1 import commands + + root = tmp_path / "plugin" + manifest = root / ".claude-plugin/plugin.json" + manifest.parent.mkdir(parents=True) + manifest.write_text('{"name":"demo"}', encoding="utf-8") + member = root / "skills/demo/SKILL.md" + member.parent.mkdir(parents=True) + member.write_text( + "---\nname: demo\ndescription: Use when checking project workflows.\n" + "license: MIT\nmetadata:\n author: Demo Author\n---\n" + "# Demo\n\n## Instructions\n\nRead the project and explain its workflow.\n", + encoding="utf-8", + ) + + def clean_external_scan(_validator, _path): + result = ValidationResult() + result.add_success("external_scan", "External scanner completed") + return result + + monkeypatch.setattr(commands.SecurityValidator, "_run_skillspector", clean_external_scan) + monkeypatch.setattr(commands.SecretsValidator, "_validate_single_skill", clean_external_scan) + return root, member.parent + + +def test_default_plugin_retains_real_checks_and_records_harness_applicability(plugin_with_local_scanners): + from skillevaluator.publication_evidence import tier1_required_checks + from skillevaluator.reporting.base import missing_tier1_publication_checks + from skillevaluator.reporting.presentation import result_execution_status + + root, _member = plugin_with_local_scanners + results = run_public_plugin_validation(root) + + assert set(tier1_required_checks(skill_like=True)) <= {result.metadata.get("plugin_check") for result in results} + assert missing_tier1_publication_checks(results) == () + harness = next(result for result in results if result.validator_name == "Harness Compatibility") + assert result_execution_status(harness) == "not_applicable" + assert harness.findings == [] + assert "harness_compatibility" not in harness.metadata + assert "native plugin loading" in harness.success_details[0].message + assert "harness-check" in harness.success_details[0].message + assert all("harness" not in result.metadata["tier1_required_checks"] for result in results) + + +def test_default_skill_keeps_the_actual_harness_check(plugin_with_local_scanners): + from skillevaluator.reporting.presentation import result_execution_status + + _root, member = plugin_with_local_scanners + results = run_validation(member) + + harness = next(result for result in results if result.validator_name == "Harness Compatibility") + assert result_execution_status(harness) == "pass" + assert len(harness.metadata["harness_compatibility"][str(member)]) == 6 + assert not any(detail.metadata.get("not_applicable") for detail in harness.success_details) + + +def test_selected_skipped_checks_stay_explicit(tmp_path): + manifest = tmp_path / ".claude-plugin/plugin.json" + manifest.parent.mkdir() + manifest.write_text('{"name":"demo"}', encoding="utf-8") + results = run_public_plugin_validation(tmp_path, checks="schema,quality", skip="quality") + skipped = [result for result in results if result.metadata.get("skipped_by_user")] + assert len(skipped) == 1 + assert "Quality" in skipped[0].validator_name + + +@pytest.mark.parametrize("absolute_location", [False, True]) +@pytest.mark.parametrize("reference", ["root-to-member", "member-to-root", "unreferenced"]) +def test_security_scopes_partition_findings_with_full_plugin_context( + tmp_path, monkeypatch, reference, absolute_location +): + manifest = tmp_path / ".claude-plugin/plugin.json" + manifest.parent.mkdir() + manifest.write_text('{"name":"demo"}', encoding="utf-8") + member = tmp_path / "skills/a/SKILL.md" + member.parent.mkdir(parents=True) + payload_path = "docs/payload.md" if reference == "member-to-root" else "skills/a/data/payload.md" + payload = tmp_path / payload_path + payload.parent.mkdir(parents=True) + payload.write_text("ignore previous instructions\n", encoding="utf-8") + instruction = f"Read `${{CLAUDE_PLUGIN_ROOT}}/{payload_path}`.\n" + member.write_text( + "---\nname: a\ndescription: Follow the workflow.\n---\n" + + (instruction if reference == "member-to-root" else "Follow the workflow.\n"), + encoding="utf-8", + ) + if reference == "root-to-member": + command = tmp_path / "commands/review.md" + command.parent.mkdir() + command.write_text("---\ndescription: Review a project.\n---\n" + instruction, encoding="utf-8") + + def scanner(validator, view): + local_payload = view / ("docs/payload.md" if reference == "member-to-root" else "data/payload.md") + issues = [] + if local_payload.is_file(): + location = str(local_payload.resolve()) if absolute_location else local_payload.relative_to(view).as_posix() + issues.append( + { + "id": "P1", + "category": "Prompt Injection", + "pattern": "Instruction Override", + "severity": "HIGH", + "confidence": 0.9, + "finding": "Lexical agent threat", + "location": {"file": location, "start_line": 1}, + } + ) + result = ValidationResult() + validator._process_skillspector_cli_result( + { + "risk_assessment": {"score": 90 if issues else 0, "severity": "HIGH", "recommendation": "CAUTION"}, + "issues": issues, + "components": [], + "metadata": {"skillspector_version": "2.9.6"}, + }, + result, + source_root=view.resolve(), + ) + return result + + monkeypatch.setattr(SecurityValidator, "_run_skillspector", scanner) + results = run_public_plugin_validation(tmp_path, checks="security") + findings = [ + finding + for result in results + if result.metadata.get("plugin_check") == "security" + for finding in result.findings + ] + assert bool(findings) is (reference != "unreferenced") + if findings: + assert findings[0].metadata["file_role"] == "agent_reference" + + +def test_security_and_pii_results_keep_their_public_check_names(tmp_path, monkeypatch): + from skillevaluator.reporting.console_ui import final_check_ticker_row + + manifest = tmp_path / ".claude-plugin/plugin.json" + manifest.parent.mkdir() + manifest.write_text('{"name":"demo"}', encoding="utf-8") + member = tmp_path / "skills/a/SKILL.md" + member.parent.mkdir(parents=True) + member.write_text("---\nname: a\ndescription: Follow the workflow.\n---\nBody.\n", encoding="utf-8") + + def failing_scanner(validator, view): + result = ValidationResult() + result.add_error("Prompt injection fixture") + return result + + monkeypatch.setattr(SecurityValidator, "_run_skillspector", failing_scanner) + results = run_public_plugin_validation(tmp_path, checks="security,pii") + names: dict[str, set[str]] = {} + for result in results: + if (check := result.metadata.get("plugin_check")) in {"security", "pii"}: + names.setdefault(check, set()).add(result.validator_name) + assert names == {"security": {"Security Scan"}, "pii": {"PII Scan"}} + row = final_check_ticker_row(["security", "pii"], results) + assert "".join(text for text, _style in row.segments) == "✗ security · ✓ pii" + + +def test_dependency_audit_keeps_its_tier1_name_and_check(tmp_path, monkeypatch): + from types import SimpleNamespace + + from skillevaluator.plugin_dependency_audit import run_dependency_audits + from skillevaluator.reporting.console_ui import final_check_ticker_row + from skillevaluator.tier1 import plugin_checks + from skillevaluator.utils.tool_runner import ToolResult + + root = _plugin(tmp_path, member=False) + (root / "requirements.txt").write_text("requests==2.0.0\n", encoding="utf-8") + + def scan(_args, **_kwargs): + vulnerability = {"id": "CVE-fixture", "fix_versions": [], "severity": "high"} + payload = {"dependencies": [{"name": "requests", "version": "2.0.0", "vulns": [vulnerability]}]} + return ToolResult(True, json.dumps(payload), "", 1) + + scanner = SimpleNamespace(is_available=True, run=scan) + monkeypatch.setattr( + plugin_checks, + "run_dependency_audits", + lambda reader, inputs: run_dependency_audits(reader, inputs, tools={"pip_audit": scanner}), + ) + results = run_public_plugin_validation(root, checks="dependency", on_check=lambda _check: None) + + audit = next(result for result in results if "cve_summary" in result.metadata.get("plugin", {})) + assert audit.validator_name == "Dependency Vulnerability Audit" + assert audit.metadata["publication_evidence"]["check_id"] == "dependency" + assert not audit.passed + others = [result for result in results if result is not audit] + assert all(result.metadata["publication_evidence"]["check_id"] != "dependency" for result in others) + row = final_check_ticker_row(["schema", "dependency"], results) + assert "".join(text for text, _style in row.segments) == "✓ schema · ✗ dependency" + + +def test_schema_cannot_be_skipped_because_the_manifest_check_always_runs(tmp_path): + root = _plugin(tmp_path, member=False) + (root / ".claude-plugin/plugin.json").write_text('{"name": 5}', encoding="utf-8") + results = run_public_plugin_validation(root, checks="schema,unicode", skip="schema") + + assert [result.validator_name for result in results] == ["Tier 1 option validation"] + assert not results[0].passed + assert "schema" in results[0].errors[0] + + +@pytest.mark.parametrize("spelling", ["absolute", "relative", "symlinked", "pruned"]) +def test_skillspector_baseline_maps_to_its_staged_copy_only_when_staged(tmp_path, monkeypatch, spelling): + root = _plugin(tmp_path / "demo") + folder = "evals" if spelling == "pruned" else "config" + baseline = root / folder / "baseline.yaml" + baseline.parent.mkdir() + baseline.write_text("version: 1\n", encoding="utf-8") + target, option = root, baseline + if spelling == "relative": + monkeypatch.chdir(tmp_path) + target, option = Path("demo"), Path(f"demo/{folder}/baseline.yaml") + elif spelling == "symlinked": + link = tmp_path / "link" + link.symlink_to(root, target_is_directory=True) + option = link / folder / "baseline.yaml" + scans = [] + + def scanner(validator, view): + mapped = validator.skillspector_baseline + scans.append((view.resolve(), mapped, mapped.is_file())) + result = ValidationResult() + result.add_success("skillspector", "Scanner completed without findings") + return result + + monkeypatch.setattr(SecurityValidator, "_run_skillspector", scanner) + run_public_plugin_validation(target, checks="security", skillspector_baseline=option, on_check=lambda _check: None) + + root_view = next(view for view, _mapped, _exists in scans if view.name == "demo") + assert len(scans) == 2 + for _view, mapped, exists in scans: + assert exists + if spelling == "pruned": + # evals/ is not staged, so the scan keeps the source file. + assert mapped == baseline.resolve() + else: + assert mapped == root_view / folder / "baseline.yaml" + + +@pytest.mark.parametrize("granted", [None, "mcp", "hook"]) +@pytest.mark.parametrize("resolve", [False, True]) +def test_policy_endpoint_options_reach_the_checks_and_each_allowlist_covers_its_own_targets(tmp_path, granted, resolve): + root = _plugin(tmp_path, member=False) + (root / ".mcp.json").write_text( + json.dumps({"mcpServers": {"remote": {"type": "http", "url": "https://10.1.2.3/mcp"}}}), encoding="utf-8" + ) + hook = {"type": "http", "url": "https://10.1.2.4/events"} + (root / "hooks").mkdir() + (root / "hooks/hooks.json").write_text( + json.dumps({"hooks": {"PostToolUse": [{"matcher": "Write", "hooks": [hook]}]}}), encoding="utf-8" + ) + policy = ValidationPolicy( + resolve_endpoints=resolve, + mcp_allowed_private_hosts=("10.1.2.3",) if granted == "mcp" else (), + hook_allowed_urls=("https://10.1.2.4/events",) if granted == "hook" else (), + ) + # IP-literal endpoints are classified without DNS or a request. + results = run_public_plugin_validation(root, checks="harness", policy=policy, on_check=lambda _check: None) + + flagged = {kind for kind in ("mcp", "hook") if kind != granted} + schema_checks = {"mcp": "mcp_endpoint_private", "hook": "plugin_hook_http_endpoint_private"} + private = {finding.check_name for finding in results[0].findings if finding.check_name.endswith("_private")} + assert private == {schema_checks[kind] for kind in flagged} + endpoints = [result for result in results if result.validator_name == "Plugin Endpoint Checks"] + assert len(endpoints) == int(resolve) + if resolve: + files = {"mcp": ".mcp.json", "hook": "hooks/hooks.json"} + resolved = { + finding.file_path for finding in endpoints[0].findings if finding.check_name == "endpoint_resolves_private" + } + assert resolved == {files[kind] for kind in flagged} + + +def test_pii_waivers_name_member_files_as_the_pii_findings_do(tmp_path): + reviewed, unreviewed = "boss@company.com", "ops@company.com" + root = _plugin(tmp_path / "demo") + (root / "contact.md").write_text(f"# Contact\nWrite to {reviewed}.\nOr {unreviewed}.\n", encoding="utf-8") + (root / "skills/a/SKILL.md").write_text( + f"---\nname: a\ndescription: Follow the workflow.\n---\nWrite to {reviewed}.\nOr {unreviewed}.\n", + encoding="utf-8", + ) + + def waiver(waiver_id, file, line): + return { + "id": waiver_id, + "category": "emails", + "file": file, + "line": line, + "evidence_sha256": pii_evidence_sha256("emails", reviewed), + "reason": "Public support address of the documented service", + "owner": "docs-team", + "created": (today_utc() - timedelta(days=1)).isoformat(), + "expires": (today_utc() + timedelta(days=30)).isoformat(), + } + + waivers = tmp_path / "pii-waivers.yaml" + waivers.write_text( + yaml.safe_dump( + { + "version": 1, + "waivers": [waiver("ROOT", "demo/contact.md", 2), waiver("MEMBER", "demo/skills/a/SKILL.md", 5)], + } + ), + encoding="utf-8", + ) + results = run_public_plugin_validation(root, checks="pii", pii_waivers=waivers, on_check=lambda _check: None) + + found = {(f.file_path, f.line_number) for r in results for f in r.findings if f.category == "PII"} + reviews = { + (f.check_name, f.file_path, f.line_number) for r in results for f in r.findings if f.category == "PII_WAIVER" + } + assert reviewed not in " ".join(f.message for r in results for f in r.findings) + assert found == {("contact.md", 3), ("skills/a/SKILL.md", 6)} + assert reviews == {("applied-pii-waiver", path, line - 1) for path, line in found} + + +@pytest.mark.parametrize("continue_on_failure", [False, True]) +@pytest.mark.parametrize("step", ["scan", "member", "staging", "dependency", "endpoint"]) +def test_fail_fast_stops_after_any_failing_step_unless_continuing(tmp_path, monkeypatch, step, continue_on_failure): + from skillevaluator.tier1 import commands, plugin_checks + from skillevaluator.utils.secure_fs import SecurePathError + + root = _plugin(tmp_path) + started = [] + + def fixture(name, *, passed=True): + def run(*_args, **_kwargs): + started.append(name) + result = ValidationResult(validator_name=f"Fixture {name}") + if not passed: + result.add_error(f"{name} fixture failed") + return result + + return run + + class FailingQuality: + name, description = "Quality check", "Fixture quality" + + def __init__(self, **_options): + pass + + validate = staticmethod(fixture("quality", passed=False)) + + def endpoint_check(_self, _targets): + started.append("endpoint") + return {"incomplete": step == "endpoint"}, [] + + def broken_snapshot(*_args, **_kwargs): + raise SecurePathError("source_changed", "Source changed while staging") + + monkeypatch.setattr(SecurityValidator, "_run_skillspector", fixture("security", passed=step != "scan")) + monkeypatch.setattr(commands, "QualityScoreValidator", FailingQuality) + monkeypatch.setattr(plugin_checks, "run_dependency_audits", fixture("dependency", passed=step != "dependency")) + monkeypatch.setattr(plugin_checks.EndpointChecker, "check", endpoint_check) + monkeypatch.setattr(plugin_checks.ClaudePluginValidateParity, "validate", fixture("parity")) + if step == "staging": + monkeypatch.setattr(plugin_checks, "_snapshot", broken_snapshot) + checks, later, options = { + "scan": ("security,unicode", "unicode", {}), + "member": ("quality,lint", "lint", {}), + "staging": ("unicode,dependency", "dependency", {}), + "dependency": ("dependency", "endpoint", {"resolve_endpoints": True}), + "endpoint": ("harness", "parity", {"resolve_endpoints": True, "claude_validate": True}), + }[step] + results = run_public_plugin_validation( + root, + checks=checks, + fail_fast=True, + continue_on_failure=continue_on_failure, + on_check=lambda _check: None, + **options, + ) + + ran = set(started) | {result.metadata.get("plugin_check") for result in results} + assert any(not result.passed for result in results) + assert (later in ran) is continue_on_failure + + +@pytest.mark.parametrize( + "validator,check,options", + [ + ("SchemaValidator", "schema", {"policy": ValidationPolicy(mcp_allowed_private_hosts=("10.1.2.3",))}), + ("VersionValidator", "version", {"previous_version": "1.2.3"}), + ], +) +def test_member_checks_receive_the_run_options(tmp_path, monkeypatch, validator, check, options): + from skillevaluator.tier1 import commands + + root = _plugin(tmp_path) + seen = [] + + class Recorder: + name, description = "Fixture check", "Fixture" + + def __init__(self, **kwargs): + seen.append(kwargs) + + def validate(self, path): + assert (path / "SKILL.md").is_file() + return ValidationResult() + + monkeypatch.setattr(commands, validator, Recorder) + results = run_public_plugin_validation(root, checks=check, on_check=lambda _check: None, **options) + + assert seen == [options] + assert any( + result.metadata.get("plugin_check") == check and result.metadata.get("plugin_member") == "skills/a" + for result in results + ) + + +def test_repo_root_reaches_the_dependency_records(tmp_path): + root = tmp_path / "demo" + root.mkdir() + (root / "agent_plugin.yaml").write_text( + "name: demo\nauthor:\n email: dev@example.com\nskills:\n refs: [github::org/repo::skills::demo]\n", + encoding="utf-8", + ) + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + ignored = "The supplied repository root does not contain this component tree" + + def messages(**options): + results = run_public_plugin_validation(root, checks="schema", on_check=lambda _check: None, **options) + return " ".join(results[0].messages) + + assert ignored not in messages() + assert ignored in messages(repo_root=elsewhere) diff --git a/tests/reporting/test_private_static_reports.py b/tests/reporting/test_private_static_reports.py index 310734a48..064eb39b6 100644 --- a/tests/reporting/test_private_static_reports.py +++ b/tests/reporting/test_private_static_reports.py @@ -470,6 +470,37 @@ def test_conflicting_source_identity_is_explicit_and_never_a_static_pass(): assert "conflicting source" in json.dumps(payload).lower() +@pytest.mark.parametrize("block", [None, "high", "critical", "medium-policy", "minimum-score"]) +def test_incomplete_only_gates_share_the_canonical_status_without_hiding_real_failures(block): + schema = ValidationResult(validator_name="Plugin Schema", metadata={"plugin": {"name": "partial-demo"}}) + security = ValidationResult(validator_name="Security Scan") + security.mark_scan_incomplete("skillspector") + security.fail_gate("skillspector reports incomplete analysis: reference_unresolved at SKILL.md:4") + security.add_finding(Finding("SECURITY", Severity.MEDIUM, "rug-pull", "Retained advisory", "SKILL.md")) + results = [schema, security] + if block == "minimum-score": + quality = ValidationResult(validator_name="Quality Score") + quality.fail_gate("Quality score 50.0/100 is below the required 70/100 in SKILL.md") + results.append(quality) + elif block is not None: + security.add_structured_finding( + Finding("SECURITY", "medium" if block == "medium-policy" else block, "known-risk", "Known risk", "run.py"), + is_error=True, + ) + + output = renderers().render_plugin_static_reports(results, reporters=reporters()) + report = json.loads(output["json"]) + + expected = "incomplete" if block is None else "failed" + assert report["overall_status"] == expected + assert report["plugin_static"]["status"] == expected + assert report["results"][1]["findings"][0]["message"] == "Retained advisory" + if block == "minimum-score": + assert "Quality score 50.0/100 is below the required 70/100" in output["html"] + elif block is not None: + assert "Known risk" in output["html"] + + def test_private_metadata_is_read_once_per_result_for_the_six_outputs(): class CountedMetadata(dict): reads = 0 diff --git a/tests/test_progress_output.py b/tests/test_progress_output.py index 135f658fd..91cb106c6 100644 --- a/tests/test_progress_output.py +++ b/tests/test_progress_output.py @@ -91,3 +91,21 @@ def test_step_count_excludes_skill_only_checks_for_plugin(self, tmp_path, progre assert "[1/1] schema ..." in output assert "quality" not in output assert "lint" not in output + + def test_plugin_progress_covers_bundled_checks_and_duration(self, tmp_path, progress_capture): + from skillevaluator.tier1.plugin_public import run_public_plugin_validation + + manifest = tmp_path / ".claude-plugin/plugin.json" + manifest.parent.mkdir() + manifest.write_text('{"name":"demo"}', encoding="utf-8") + member = tmp_path / "skills/a/SKILL.md" + member.parent.mkdir(parents=True) + member.write_text("---\nname: a\ndescription: Follow the workflow.\n---\nBody.\n", encoding="utf-8") + + run_public_plugin_validation(tmp_path, checks="schema,quality", min_score=0) + + output = progress_capture.getvalue() + assert "[1/3] schema ..." in output + assert "[2/3] schema ..." in output + assert "[3/3] quality ..." in output + assert output.count("done in") == 3 diff --git a/tests/validators/test_public_plugin_policy.py b/tests/validators/test_public_plugin_policy.py index 0a0d25429..800f4b6a0 100644 --- a/tests/validators/test_public_plugin_policy.py +++ b/tests/validators/test_public_plugin_policy.py @@ -3,6 +3,7 @@ import hashlib import json +from types import SimpleNamespace import pytest @@ -186,3 +187,18 @@ def test_plugin_policy_blocks_reject_unknown_shapes(tmp_path, document): path.write_text(document) with pytest.raises(ValueError): load_policy_file(path) + + +def test_hook_endpoint_grants_do_not_apply_to_mcp_targets(): + from skillevaluator.plugin_dependency_audit import collect_endpoint_targets + + mcp = SimpleNamespace(name="server", file=".mcp.json", config={"url": "https://192.168.1.10/mcp"}) + hook = SimpleNamespace(id="hook", file="hooks.json", url="https://192.168.1.10/events") + targets = collect_endpoint_targets( + [mcp], + [hook], + allowed_hosts=("corp.example",), + hook_allowed_urls=("https://192.168.1.10/events",), + ) + assert targets[0].allowed_hosts == ("corp.example",) + assert targets[1].allowed_hosts == ("corp.example", "192.168.1.10") diff --git a/tests/validators/test_security.py b/tests/validators/test_security.py index 626d4326c..6fd8c8b16 100644 --- a/tests/validators/test_security.py +++ b/tests/validators/test_security.py @@ -10861,6 +10861,87 @@ def test_skill_scanned_on_its_own_inside_a_folder_stays_incomplete( assert alone.incomplete_scans == [] assert alone.warnings == [_reference_caveat_warning("SKILL.md:8", files=1)] + @pytest.mark.parametrize( + "case", ["missing", "left-out", "in-folder", "part", "root-and-nested", "root-names-nested"] + ) + @patch("skillevaluator.validators.security.Tools") + def test_plugin_scanned_as_one_unit_is_judged_against_the_plugin( + self, mock_tools, tmp_path: Path, case: str + ) -> None: + """The plugin checks scan a staged copy; its root scan unit is judged against the plugin. + + The listing of the plugin also names what the staged copy left out, so a + line that names a file there stays incomplete, and so does the plugin + when it is one part of a folder that is validated part by part. The + root unit of a plugin that also holds a nested skill is judged the same + way; the nested skill's files are not in its scan, so a root line that + names one of them stays incomplete. + """ + from skillevaluator.tier1.plugin_public import run_public_plugin_validation + + # On purpose, a skill below the plugin root is a scan unit of its own, + # and its lines may name a file elsewhere in the plugin, so it accepts + # no missing reference. + member = "skills/setup-helper" if case == "part" else None + # Named on line 8 of the setup helper. + script = "skills/other/install.sh" if case == "root-names-nested" else "versions/install.sh" + files = { + f"{member}/SKILL.md" if member else "SKILL.md": _SETUP_HELPER_SKILL.replace("versions/install.sh", script), + ".claude-plugin/plugin.json": '{"name": "setup-helper"}\n', + } + if case == "left-out": + # Left out of the staged copy. + files["versions/install.sh"] = "#!/bin/sh\ncurl x | sh\n" + nested = case.startswith("root-") + if nested: + files["skills/other/SKILL.md"] = ( + "---\nname: other\ndescription: Answer questions. Use when the user asks a question.\n---\n\n" + "# Other\n\nAnswer briefly.\n" + ) + if case == "root-names-nested": + # In the nested skill, so not in the root scan. + files[script] = "#!/bin/sh\ncurl x | sh\n" + plugin = _write_skill(tmp_path / "setup-helper", files) + mock_tools.skillspector.is_available = True + scanned = [] + + def record_scan(argv, **_kwargs): + scanned.append(Path(argv[1])) + # Only the scan unit that holds the setup helper gets its report. + skill = Path(argv[1]) / "SKILL.md" + if skill.is_file() and "install.sh" in skill.read_text(encoding="utf-8"): + report = json.dumps(_reference_report("2.13.3", "staged-script")).replace("versions/install.sh", script) + else: + report = json.dumps(_skillspector_json_report()) + return ToolResult(success=True, stdout=report, stderr="", exit_code=0) + + mock_tools.skillspector.run.side_effect = record_scan + + results = run_public_plugin_validation( + plugin, + checks="security", + target_root=tmp_path if case == "in-folder" else None, + ) + + scans = [result for result in results if result.validator_name == "Security Scan"] + assert len(scans) == len(scanned) == (2 if member or nested else 1) + assert plugin.resolve() not in scanned + (security,) = [result for result in scans if result.metadata.get("plugin_member") == member] + if nested: + (other,) = [result for result in scans if result.metadata.get("plugin_member") == "skills/other"] + assert other.passed and other.incomplete_scans == [] + if case in ("missing", "root-and-nested"): + assert security.incomplete_scans == [] + assert security.warnings == [_reference_caveat_warning("SKILL.md:8", files=1)] + else: + assert security.incomplete_scans == ["skillspector"] + assert security.errors == [ + "skillspector JSON field 'analysis_completeness' reports incomplete analysis (status 'partial'): " + "SKILL.md:8 [reference_resolution; reference_missing]; security scan did not complete" + + _REFERENCE_REJECTION_HELP + ] + assert not security.warnings + @pytest.mark.parametrize("manifest", [False, True]) @pytest.mark.parametrize("workers", [1, 2]) @patch("skillevaluator.validators.security.Tools") diff --git a/tests/validators/test_skillspector_scope.py b/tests/validators/test_skillspector_scope.py index 6f8d91198..9bd2c6edc 100644 --- a/tests/validators/test_skillspector_scope.py +++ b/tests/validators/test_skillspector_scope.py @@ -1824,6 +1824,19 @@ def test_run_validation_scopes_only_detected_agent_artifacts( assert kwargs["content_type"] == expected_scope assert kwargs["skillspector_reference_root"] == (sample_skill_dir if content_type == "plugin" else None) + def test_plugin_without_a_manifest_refuses_before_scanner_construction( + self, monkeypatch: pytest.MonkeyPatch, sample_skill_dir: Path + ) -> None: + from skillevaluator.tier1.plugin_public import run_public_plugin_validation + + monkeypatch.setattr(tier1_commands, "SecurityValidator", _RecordingSecurityValidator) + _RecordingSecurityValidator.instances = [] + + results = run_public_plugin_validation(sample_skill_dir, checks="security") + + assert not _RecordingSecurityValidator.instances + assert any(not result.passed for result in results) + def test_standalone_security_scan_stays_unrestricted( self, monkeypatch: pytest.MonkeyPatch, sample_skill_dir: Path ) -> None: From eef20d6b13b5e512a443fdd1c2fe14b5bb281c70 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan <32655573+rng1995@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:41:48 -0800 Subject: [PATCH 7/9] feat(tier3): add a workflow for prepared runtime packages (#854) * feat(tier3): add a workflow for prepared runtime packages Add a Tier 3 workflow function in a new module. Given a source directory with a supported manifest, it validates the component inventory, prepares a runtime package in a temporary wrapper, runs the package through the existing evaluation engine and retains its runtime evidence. Add the engine changes it relies on: the verified authored source for the results root, full repo context and publication identity; bounded setup retries; fail-closed unstaged skill and rule references; MCP probe grant notes before error text; and saved runtime evidence and the report content label for results rebuilt from a run directory. No CLI command or public API entry point reaches the workflow yet; only its tests call it. With no prepared package active, the new source-path hook returns its argument and a Tier 3 result keeps the typed skill path's name, so skill runs keep their behavior. A skill report rebuilt from a run directory keeps the Skill label and gains no warning. Co-Authored-By: Claude Opus 5.5 Co-authored-by: Christopher Kevin Signed-off-by: Narendran Raghavan * fix(tier3): keep saved run feedback and verifier datasets out of the workflow run - Refresh the run report with the feedback the run saved, so its Insights output and what_to_fix.json are not replaced by rule-based text. - Leave member evaluation directories, including a legacy eval/ dataset, out of full repo context staged from the authored source. - Resolve include, decoy_manifest and price_file from the resolved source. - Refuse a results root inside the source outside results/ (or evals/results/ when evals/ exists), which the source digest would count. - Name the file and the cause when the config or a grader cannot be read. - Add tests for the refusals, the authored settings fallback, the results directory variable and the runner path under prepared-package hooks. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Narendran Raghavan * fix(tier3): recognize trusted aliases of plugin results paths Apply the same trusted-root alias normalization as the publication digest and output-directory validator before checking in-source results. Cover mixed macOS path spellings and relative results in an aliased working directory. Signed-off-by: Narendran Raghavan --------- Signed-off-by: Narendran Raghavan Co-authored-by: Claude Opus 5.5 Co-authored-by: Christopher Kevin --- src/skillevaluator/evaluation/tier3_report.py | 11 +- .../reporting/plugin_reports.py | 18 +- .../reporting/plugin_runtime.py | 2 +- src/skillevaluator/tier3/commands.py | 4 +- src/skillevaluator/tier3/harbor/adapter.py | 36 +- src/skillevaluator/tier3/harbor/runner.py | 20 +- src/skillevaluator/tier3/mcp_proof.py | 59 +- .../tier3/plugin_comparisons.py | 4 + src/skillevaluator/tier3/plugin_execution.py | 16 +- src/skillevaluator/tier3/plugin_prepare.py | 10 +- src/skillevaluator/tier3/plugin_workflow.py | 261 ++++++++ .../test_saved_plugin_completeness.py | 42 ++ tests/tier3/test_mcp_proof.py | 71 ++- tests/tier3/test_plugin_prepare.py | 116 ++++ tests/tier3/test_public_plugin_source.py | 317 +++++++++ tests/tier3/test_public_plugin_workflow.py | 599 +++++++++++++++++- 16 files changed, 1543 insertions(+), 43 deletions(-) create mode 100644 src/skillevaluator/tier3/plugin_workflow.py create mode 100644 tests/reporting/test_saved_plugin_completeness.py create mode 100644 tests/tier3/test_public_plugin_source.py diff --git a/src/skillevaluator/evaluation/tier3_report.py b/src/skillevaluator/evaluation/tier3_report.py index 2476fdc1e..aa0550057 100644 --- a/src/skillevaluator/evaluation/tier3_report.py +++ b/src/skillevaluator/evaluation/tier3_report.py @@ -586,7 +586,12 @@ def agent_eval_result_from_directory( from skillevaluator.tier3.next_steps import next_steps payload["next_steps"] = next_steps(source, run_dir=run_dir, fixes=load_case_findings(run_dir)) - return _validation_result_from_payload(payload) + result = _validation_result_from_payload(payload) + if result is not None: + from skillevaluator.reporting.plugin_reports import attach_saved_plugin_evidence + + attach_saved_plugin_evidence(result, run_dir, engine_result) + return result def _persisted_run_result(run_dir: Path) -> dict[str, Any] | None: @@ -746,7 +751,9 @@ def render_agent_eval_html_report( reporter = HTMLReporter( target_path=str(skill_path), - content_label="Skill", + content_label="Plugin" + if result.metadata.get("plugin") or result.metadata.get("plugin_runtime_report") + else "Skill", report_scope="tier3", tabs=[{"id": "tier3", "label": "Tier 3: Live Agent Evaluation"}], # The run records the filesystem entry name, which a lexical alias diff --git a/src/skillevaluator/reporting/plugin_reports.py b/src/skillevaluator/reporting/plugin_reports.py index 1636d6d89..faa45fe00 100644 --- a/src/skillevaluator/reporting/plugin_reports.py +++ b/src/skillevaluator/reporting/plugin_reports.py @@ -29,10 +29,21 @@ def mark_incomplete_plugin_package(result: ValidationResult, engine_result: obje result.mark_scan_incomplete("plugin-components") +def _snapshot_records_incomplete_package(payload: dict) -> bool: + # The runtime projection writes a "preparation" limitation exactly when the + # prepared package was incomplete. The saved result.json has no package + # provenance, so a report rebuilt from the run directory reads it here. + return any( + section["key"] == "diagnostics" and any(row[0] == "preparation" for row in section["rows"]) + for section in payload["sections"] + ) + + def attach_saved_plugin_evidence(result: ValidationResult, run_dir: Path, engine_result: dict | None) -> None: """Attach passive evidence without changing the canonical score payload. - The result is also marked incomplete when the prepared plugin package was incomplete. + The result is also marked incomplete when the prepared plugin package was + incomplete, as recorded by the live run or by its saved snapshot. """ from skillevaluator.reporting.plugin_runtime_io import RUNTIME_REPORT_FILENAME, load_plugin_runtime_report @@ -52,7 +63,10 @@ def attach_saved_plugin_evidence(result: ValidationResult, run_dir: Path, engine report = runtime_report_from_payload(live) else: report = load_plugin_runtime_report(run_dir) - result.metadata["plugin_runtime_report"] = report.payload() + payload = report.payload() + result.metadata["plugin_runtime_report"] = payload + if _snapshot_records_incomplete_package(payload): + result.mark_scan_incomplete("plugin-components") except (OSError, ValueError): result.metadata["plugin_runtime_report_error"] = "Saved plugin runtime evidence is unavailable" result.add_warning("Saved plugin runtime evidence is unavailable") diff --git a/src/skillevaluator/reporting/plugin_runtime.py b/src/skillevaluator/reporting/plugin_runtime.py index d0b566bf9..a15cfb504 100644 --- a/src/skillevaluator/reporting/plugin_runtime.py +++ b/src/skillevaluator/reporting/plugin_runtime.py @@ -414,7 +414,7 @@ def project_plugin_runtime( projection.add("run", "Execution status", result.get("execution_status") or "unknown") if "attempts" in provenance: projection.add("run", "Setup attempts", _count(provenance["attempts"])) - for reason in islice(provenance.get("retry_reasons") or (), 2): + for reason in islice(provenance.get("retry_reasons") or (), 5): projection.add("run", "Setup retry reason", reason) source = _mapping(provenance.get("source") or observed.get("source")) source = { diff --git a/src/skillevaluator/tier3/commands.py b/src/skillevaluator/tier3/commands.py index 5a336ffc2..9a05f3611 100644 --- a/src/skillevaluator/tier3/commands.py +++ b/src/skillevaluator/tier3/commands.py @@ -769,7 +769,9 @@ def evaluate( "--agent-model provided for agent(s) not selected by -a/--agents: " + ", ".join(unknown_model_agents) ) - output_dir = resolve_results_root(skill_path, results_dir) + from skillevaluator.tier3.plugin_execution import runtime_source_path + + output_dir = resolve_results_root(runtime_source_path(skill_path), results_dir) if execution_backend == NEMO_GYM_BACKEND: from skillevaluator.tier3.nemo_gym.runner import run_nemo_gym_eval diff --git a/src/skillevaluator/tier3/harbor/adapter.py b/src/skillevaluator/tier3/harbor/adapter.py index 146b6f374..ed56d9954 100644 --- a/src/skillevaluator/tier3/harbor/adapter.py +++ b/src/skillevaluator/tier3/harbor/adapter.py @@ -859,6 +859,28 @@ def _is_runtime_evaluator_directory(path: Path) -> bool: return any(os.path.lexists(path / f"dataset{extension}") for extension in DATASET_EXTENSIONS) +def _is_member_dataset_path(path: Path, source_root: Path) -> bool: + """Return whether *path* is in an evaluator directory of *source_root* or of a skill inside it. + + Applies the agent-visible skill copy's rule (see ``_runtime_skill_copy_ignore``) + to an authored source staged as repository context: ``evals/``, or a legacy + ``eval/`` holding a dataset, directly under the source root or under any + directory with a skill manifest. + """ + root = Path(os.path.abspath(source_root)) # noqa: PTH100 -- lexical, as the repository walk + try: + parts = Path(os.path.abspath(path)).relative_to(root).parts # noqa: PTH100 + except ValueError: + return False + owner = root + for part in parts: + candidate = owner / part + if (owner == root or _skill_manifest(owner) is not None) and _is_runtime_evaluator_directory(candidate): + return True + owner = candidate + return False + + def _runtime_skill_copy_ignore(skill_root: Path, excluded_roots: Sequence[Path] = ()): """Build a root-aware ignore callback for an agent-visible skill copy.""" @@ -1306,6 +1328,15 @@ def _stage_repo_context( if not source_skill_path: return {"mode": "none", "files": []} + authored_source = False + if mode == "full": + from skillevaluator.tier3.plugin_execution import runtime_source_path + + authored = runtime_source_path(source_skill_path) + if authored != source_skill_path: + authored_source = True + excluded_roots = (*excluded_roots, authored / "evals") + source_skill_path = authored source_skill_path = source_skill_path.resolve() skill_md = _skill_manifest(source_skill_path) repo_root = resolve_repo_context_root(source_skill_path) @@ -1343,7 +1374,10 @@ def _is_excluded_output(path: Path) -> bool: repo_root, authenticated_output_roots, resolved_excluded_roots, - lambda path: publication_source_path_is_excluded(source_skill_path, path), + lambda path: ( + publication_source_path_is_excluded(source_skill_path, path) + or (authored_source and _is_member_dataset_path(path, source_skill_path)) + ), ): if _is_excluded_output(src): continue diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.py index 32a5cbd75..d612bc233 100644 --- a/src/skillevaluator/tier3/harbor/runner.py +++ b/src/skillevaluator/tier3/harbor/runner.py @@ -5551,13 +5551,21 @@ def _run_harbor_eval_impl( reporter.emit(ProgressEvent(stage="configuration", state="failed", detail=str(exc))) return {"error": [str(exc)]} + from skillevaluator.tier3.plugin_execution import runtime_source_path + + publication_source = runtime_source_path(skill_path) + publication_name = ( + _snapshot_publication_target.get("skill_name", publication_source.name) + if _snapshot_publication_target and publication_source != skill_path + else publication_source.name + ) if _evaluator_skill_path is None: assert forwarded is not None forwarded.pop("skill_path") forwarded.pop("agents") with ExitStack() as snapshot_stack: try: - snapshot_publication_target = publication_target_from_path(skill_path) + snapshot_publication_target = publication_target_from_path(publication_source) evaluator_skill_path = snapshot_stack.enter_context(private_evaluator_skill_snapshot(skill_path)) snapshot_config, _ = load_evals_config(evaluator_skill_path) snapshot_workspace = snapshot_config.get("skill_workspace", {}) @@ -5588,7 +5596,7 @@ def _run_harbor_eval_impl( forwarded["_decoy_workspace_paths"] = [*manual, *frozen] forwarded["_decoy_workspace_source_paths"] = source_paths forwarded["_decoy_manifest"] = manifest - if publication_target_from_path(skill_path) != snapshot_publication_target: + if publication_target_from_path(publication_source) != snapshot_publication_target: raise ValueError("Publication source changed while its private evaluator snapshot was created") except (OSError, ValueError) as exc: reporter.emit(ProgressEvent(stage="configuration", state="failed", detail=str(exc))) @@ -6147,7 +6155,7 @@ def _run_owned_publication_fields() -> dict[str, Any]: if isinstance(reason_code, str): conflict["reason_code"] = reason_code return {"publication_target": None, "publication_target_conflict": conflict} - run_end_target = publication_target_from_path(skill_path) + run_end_target = publication_target_from_path(publication_source) if run_end_target == publication_target: return { "publication_target": dict(publication_target) if publication_target is not None else None, @@ -6181,7 +6189,7 @@ def _persist_pre_execution_failure(errors: list[str]) -> dict[str, Any]: """Retain redacted probe provenance for failures after run reservation.""" published_errors, error_total = _published_execution_errors(errors) failed_result: dict[str, Any] = { - "skill_name": skill_path.name, + "skill_name": publication_name, "execution_status": "failed", "execution_errors": published_errors, "execution_error_details_total": error_total, @@ -6457,7 +6465,7 @@ def emit_control(variant: str, members: Sequence[Path], *, _agent: str = agent) ) if not _runtime_context_is_bound_to_publication_target( - skill_path, + publication_source, staged_task_paths, reference_skills_dir=reference_skills_dir, workspace_skill_paths=_decoy_workspace_source_paths or workspace_skills, @@ -6852,7 +6860,7 @@ def _join_interrupted_agents() -> None: "baseline": baseline, "comparison_identity": identity, "expected_case_ids": case_ids, - "skill_name": skill_path.name, + "skill_name": publication_name, "run_id": run_id, **_run_owned_publication_fields(), "run_dir": str(run_dir), diff --git a/src/skillevaluator/tier3/mcp_proof.py b/src/skillevaluator/tier3/mcp_proof.py index a39238afa..38ccbe42f 100644 --- a/src/skillevaluator/tier3/mcp_proof.py +++ b/src/skillevaluator/tier3/mcp_proof.py @@ -18,11 +18,14 @@ ``$VAR`` reference is expanded from the host environment only when the user grants that variable through ``EvidenceOptions.env_grants`` (``NAME`` for every server, ``NAME=HOST`` or ``NAME@SERVER`` for one); a header that references any other -variable is not sent, and the variable is never read. Each server's detail -records which variables were sent to which host. The whole probe, DNS lookup -included, runs under one deadline, and a transport error that the ``mcp`` -client only logs (an oversized body, an off-origin SSE endpoint) ends the -probe at once. +variable is not sent, and the variable is never read. A granted variable that +is unset or empty leaves its header out. Once the host resolves and passes the +endpoint policy, each server's detail names the granted variables its headers +carry for that host, before any error text, as a probe that fails may not have +sent them; a DNS failure or a server that is not probed names none, as nothing +was sent. The whole probe, DNS lookup included, runs under one deadline, and a +transport error that the ``mcp`` client only logs (an oversized body, an +off-origin SSE endpoint) ends the probe at once. After the run, :func:`apply_in_agent_mcp_proof` updates each server from the with-plugin arm's ``plugin_signals_summary.mcp_calls.by_server`` and each @@ -250,20 +253,20 @@ def declared_mcp_proof(targets: Iterable[Mapping[str, Any]], detail: str = NOT_R def _resolve_headers( headers: Mapping[str, Any], environ: Mapping[str, str], expand_env: Iterable[str] = () ) -> tuple[dict[str, str], list[str], list[str], list[str]]: - """Return ``(headers to send, unset variables, withheld variables, sent variables)``. + """Return ``(headers to send, unset variables, withheld variables, variables placed in headers)``. A header whose ``${VAR}``/``$VAR`` references all name variables in ``expand_env`` (the names opted in for this server) is sent with them - resolved from ``environ``; one that references an opted-in but unset - variable is dropped (``unset``). A header that references any variable not - opted in for this server is dropped without reading that variable - (``withheld``). Literal headers are sent as declared. + resolved from ``environ``; one that references an opted-in but unset or + empty variable is dropped (``unset``). A header that references any + variable not opted in for this server is dropped without reading that + variable (``withheld``). Literal headers are sent as declared. """ allowed = frozenset(expand_env) resolved: dict[str, str] = {} missing: list[str] = [] withheld: list[str] = [] - sent: list[str] = [] + placed: list[str] = [] for key, value in headers.items(): if not isinstance(key, str) or not isinstance(value, str): continue @@ -277,24 +280,30 @@ def _resolve_headers( missing.extend(unset) continue resolved[key] = _HEADER_REF_RE.sub(lambda match: environ[match.group(1) or match.group(2)], value) - sent.extend(names) - return resolved, sorted(set(missing)), sorted(set(withheld)), sorted(set(sent)) + placed.extend(names) + return resolved, sorted(set(missing)), sorted(set(withheld)), sorted(set(placed)) -def _header_note(missing: list[str], withheld: list[str], sent: list[str] | None = None, host: str = "") -> str: +def _header_note(missing: list[str], withheld: list[str], granted: list[str] | None = None, host: str = "") -> str: + # Granted, not sent: a probe that fails may not have sent its headers. note = "" - if sent: - note += f"; sent {', '.join(sent)} to {host or 'the server'}" + if granted: + note += f"; granted {', '.join(granted)} for {host or 'the server'}" if withheld: note += ( f"; headers not sent because they reference host variables without a private environment grant " f"for this server: {', '.join(withheld)}" ) if missing: - note += f"; headers skipped because unset: {', '.join(missing)}" + note += f"; headers skipped because unset or empty: {', '.join(missing)}" return note +def _failure_detail(kind: str, error: str, note: str) -> str: + """Detail of a failed probe: the header note comes first, so the length cap cuts the error, not the note.""" + return f"{kind} probe failed{note}; error: {error}" if note else f"{kind} probe failed: {error}" + + def _address_policy(address: str, allowlist: HostAllowlist, *, name_allowed: bool, label: str) -> bool: """Return True for an allowed private address; raise for a refused one; False when public. @@ -713,7 +722,11 @@ def probe_mcp_server( server), ``NAME=HOST`` (servers whose URL host is HOST) or ``NAME@SERVER`` (that server). Only names opted in for this server are read from ``environ`` (the process environment when ``None``) into its declared - headers, and the detail records which names were sent to which host. + headers. Once the host resolves and passes the endpoint policy, the + detail names the granted variables this server's headers carry for its + host, and those left out because they are unset or empty, before any + error text, so that cutting a long error to ``MAX_DETAIL_CHARS`` keeps + them. A DNS failure or a refused endpoint names none, as nothing was sent. ``total_timeout`` bounds the whole probe, DNS lookup included. """ url = str(target.get("url") or "") @@ -729,12 +742,12 @@ def probe_mcp_server( except _ProbeRefused as refused: return _entry(refused.status, refused.detail) raw_headers = target.get("headers") - headers, missing, withheld, sent = _resolve_headers( + headers, missing, withheld, granted = _resolve_headers( raw_headers if isinstance(raw_headers, Mapping) else {}, os.environ if environ is None else environ, _allowed_env(target, [parse_env_grant(value) for value in expand_env]), ) - note = _header_note(missing, withheld, sent, _target_host(url)) + note = _header_note(missing, withheld, granted, _target_host(url)) try: import anyio import mcp # noqa: F401 -- availability check @@ -744,7 +757,7 @@ def probe_mcp_server( ) remaining = total_timeout - (time.monotonic() - started) if remaining <= 0: - return _entry(STATUS_UNREACHABLE, f"{kind} probe failed: timed out after {total_timeout:g}s") + return _entry(STATUS_UNREACHABLE, _failure_detail(kind, f"timed out after {total_timeout:g}s", note)) try: tools, schemas = anyio.run( lambda: _probe_session(url, kind, headers, addresses=addresses, total_timeout=remaining) @@ -755,10 +768,10 @@ def probe_mcp_server( cause = _root_cause(exc) message = str(cause) or type(cause).__name__ if isinstance(cause, _ProbeFailed): - return _entry(STATUS_UNREACHABLE, f"{kind} probe failed: {message}{note}") + return _entry(STATUS_UNREACHABLE, _failure_detail(kind, message, note)) if isinstance(cause, TimeoutError): message = f"timed out after {total_timeout:g}s" - return _entry(STATUS_UNREACHABLE, f"{kind} probe failed: {type(cause).__name__}: {message}{note}") + return _entry(STATUS_UNREACHABLE, _failure_detail(kind, f"{type(cause).__name__}: {message}", note)) entry = _entry(STATUS_REACHABLE_HOST, f"initialize and tools/list succeeded over {kind}{note}", tools) if schemas: entry["input_schemas"] = schemas diff --git a/src/skillevaluator/tier3/plugin_comparisons.py b/src/skillevaluator/tier3/plugin_comparisons.py index ab55c184f..78e7768ec 100644 --- a/src/skillevaluator/tier3/plugin_comparisons.py +++ b/src/skillevaluator/tier3/plugin_comparisons.py @@ -190,6 +190,10 @@ def begin_attempt(self) -> None: self.data = {"status": "not_collected", "agents": {}, "errors": []} self.loose_plan = LoosePartsPlan(requested=self.options.loose_parts, order=self.agents) + def source_path(self, default: Path) -> Path: + resolve = getattr(self.native, "source_path", None) + return resolve(default) if callable(resolve) else default + def configure_agent_routes(self, paths: Mapping[str, str]) -> None: """Bind the coordinator-resolved routes once for this engine attempt.""" self.task_sets = {} diff --git a/src/skillevaluator/tier3/plugin_execution.py b/src/skillevaluator/tier3/plugin_execution.py index 0dacb7966..5f17003da 100644 --- a/src/skillevaluator/tier3/plugin_execution.py +++ b/src/skillevaluator/tier3/plugin_execution.py @@ -59,6 +59,12 @@ def active_runtime() -> PrivateRuntimeHooks | None: return _ACTIVE_RUNTIME.get() +def runtime_source_path(default: Path) -> Path: + """Use the verified authored source when executing its generated package.""" + resolve = getattr(active_runtime(), "source_path", None) + return resolve(default) if callable(resolve) else default + + @contextmanager def private_runtime(hooks: PrivateRuntimeHooks) -> Iterator[PrivateRuntimeHooks]: """Activate ``hooks`` for the evaluation run inside the block.""" @@ -133,6 +139,10 @@ def baseline_agent_import_path(self, agent: str, base_import_path: str | None) - return private_agent_import_path(agent, base_import_path) + def source_path(self, default: Path) -> Path: + """A prepared package binds the generated wrapper to this authored source.""" + return self.source.plugin_root if self.package is not None else default + def stage_with_arm(self, agent: str, task_dirs: Sequence[Path]) -> None: decision = self.decisions.get(agent) if decision is None or not decision.native: @@ -356,8 +366,8 @@ def run_private_evaluation( and the run's own status survives a failed publication or cleanup. Cancellation (``KeyboardInterrupt``) is never retried and still cleans up. """ - if not 0 <= max_setup_retries <= MAX_SETUP_RETRIES: - raise ValueError(f"max_setup_retries must be between 0 and {MAX_SETUP_RETRIES}") + if type(max_setup_retries) is not int or not 0 <= max_setup_retries <= 5: + raise ValueError("max_setup_retries must be an integer between 0 and 5") if evaluate is None: from skillevaluator.evaluation.service import EvaluationService @@ -404,6 +414,7 @@ def evaluate_prepared_plugin( evidence_options: EvidenceOptions | None = None, observer_factory: Callable[..., RuntimeEvidenceObserver] | None = None, comparison_options: ComparisonOptions | None = None, + max_setup_retries: int = MAX_SETUP_RETRIES, ) -> PrivateRunOutcome: """Evaluate a prepared plugin through the existing engine and remove the operation-owned staging. @@ -527,6 +538,7 @@ def cleanup() -> None: evaluate=evaluate, publish=publish_with_evidence, cleanup=cleanup, + max_setup_retries=max_setup_retries, ) diff --git a/src/skillevaluator/tier3/plugin_prepare.py b/src/skillevaluator/tier3/plugin_prepare.py index 3b3ac9b06..ea14a215d 100644 --- a/src/skillevaluator/tier3/plugin_prepare.py +++ b/src/skillevaluator/tier3/plugin_prepare.py @@ -184,7 +184,13 @@ def prepare_runtime_package( for member in selected: if member.problem is not None: audit.append(AuditRow(member.type, member.name, member.path, f"unresolved: {member.problem}")) - elif member.type == "skill" and member.path: + elif member.type in {"skill", "rule"} and not member.path: + # A skill or rule reference without a bundled path has no content to + # stage. Keep it visible and never score the plugin as if it had loaded. + state = member.dependency_state or "unclassified" + audit.append(AuditRow(member.type, member.name, None, f"not staged: {state} reference")) + incomplete.append(f"{member.type} reference '{member.name}' was not staged ({state})") + elif member.type == "skill": if openclaw and member.path == ".": audit.append(AuditRow("skill", member.name, member.path, OPENCLAW_ROOT_SKILL_REASON)) else: @@ -509,7 +515,7 @@ def refuse(kind: str, name: str, message: str | None) -> None: rules=tuple( (member.name, member.text or "") for member in inventory.selected_components - if member.type == "rule" and not member.problem + if member.type == "rule" and member.path and not member.problem ), mcp_servers=tuple(portable_mcp), plugin_file_mcp_servers=tuple(plugin_file_mcp), diff --git a/src/skillevaluator/tier3/plugin_workflow.py b/src/skillevaluator/tier3/plugin_workflow.py new file mode 100644 index 000000000..07f701b22 --- /dev/null +++ b/src/skillevaluator/tier3/plugin_workflow.py @@ -0,0 +1,261 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Public plugin workflow over shared preparation and execution.""" + +from __future__ import annotations + +import os +import tempfile +from collections.abc import Callable +from dataclasses import replace +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from skillevaluator.utils.secure_fs import SecurePathError, SecureRoot +from skillevaluator.utils.structured_data import StructuredDataError + +if TYPE_CHECKING: + from skillevaluator.evaluation.options import EvaluationOptions, PluginOptions + +MAX_CONFIG_BYTES = 256 * 1024 + + +def _load_config(root: Path) -> tuple[dict[str, Any], dict[str, bytes]]: + from skillevaluator.tier3.evals_config import ( + CONFIG_FILENAMES, + EvalsConfigError, + _parse_config_text, + _validate_config, + ) + + config: dict[str, Any] = {} + controls: dict[str, bytes] = {} + relative = Path("evals") + try: + with SecureRoot(root) as reader: + for name in CONFIG_FILENAMES: + relative = Path("evals") / name + if os.path.lexists(root / relative): + raw, _ = reader.read_bytes(relative, MAX_CONFIG_BYTES) + # The engine's parser: a YAML error names the file, line, column and problem. + parsed = _parse_config_text(raw.decode("utf-8-sig"), root / relative) + if not isinstance(parsed, dict): + raise EvalsConfigError(f"{root / relative}: plugin eval config must be a nonempty mapping") + config = _validate_config(parsed, root / relative) + break + for name in ("grader.py", "grader.sh", "tests/grader.py", "tests/grader.sh"): + relative = Path("evals") / name + if os.path.lexists(root / relative): + controls[name], _ = reader.read_bytes(relative, MAX_CONFIG_BYTES) + except (SecurePathError, OSError, UnicodeError, StructuredDataError) as exc: + raise EvalsConfigError( + f"Cannot read bounded plugin eval configuration or grader {relative.as_posix()}: {exc}" + ) from exc + return config, controls + + +def _check_results_location(source: Path, results: Path) -> None: + """Refuse run output inside the source where its publication digest would count it. + + The digest skips only ``results/`` and, when ``evals/`` already exists, + ``evals/results/``. Output anywhere else in the source would change the + digest between run start and run end. + """ + from skillevaluator.tier3.harbor.adapter import _path_is_canonically_contained, _path_is_excluded + from skillevaluator.utils.path_security import canonicalize_trusted_root_alias + + # Match the digest and output-directory validation for trusted platform + # aliases such as macOS /var. Keep other symlinks visible to those checks. + source = canonicalize_trusted_root_alias(source.absolute()) + results = canonicalize_trusted_root_alias(results.expanduser().absolute()) + if not _path_is_excluded(results, (source,)): + return + allowed = [source / "results"] + if (source / "evals").is_dir() and not (source / "evals").is_symlink(): + allowed.append(source / "evals" / "results") + if not any(_path_is_canonically_contained(results, root) for root in allowed): + raise ValueError( + "A results root inside the plugin source must be under its results/ directory, or under " + f"evals/results/ when evals/ exists; use an external --results-dir otherwise: {results}" + ) + + +def evaluate_plugin( + options: EvaluationOptions, + *, + plugin_options: PluginOptions, + evaluate: Callable[[EvaluationOptions], dict[str, Any]], +) -> dict[str, Any]: + """Prepare, run and retain one plugin using the existing engine boundary.""" + import yaml + + from skillevaluator.models.result import Severity + from skillevaluator.plugin_inventory import plugin_inventory_for_root + from skillevaluator.provider_config import resolve_llm_provider + from skillevaluator.tier3.commands import parse_agents, resolve_agents, validate_agents + from skillevaluator.tier3.dataset_utils import DATASET_EXTENSIONS + from skillevaluator.tier3.nemo_gym.backend import HARBOR_BACKEND, normalize_backend + from skillevaluator.tier3.plugin_comparisons import ComparisonOptions + from skillevaluator.tier3.plugin_evidence import EvidenceOptions + from skillevaluator.tier3.plugin_execution import evaluate_prepared_plugin + from skillevaluator.tier3.plugin_prepare import SourceIdentity, prepare_runtime_package + from skillevaluator.tier3.results_location import plugin_results_directory + from skillevaluator.validators.private_plugin_schema import validate_inventory_schema + + if normalize_backend(options.backend) != HARBOR_BACKEND: + raise ValueError("Plugin evaluation requires --backend harbor; other backends cannot load plugin components") + if options.skip_with_skill: + raise ValueError("Plugin runs require the with-plugin arm; omit --skip-with-skill") + inventory = plugin_inventory_for_root( + options.skill_path, + allowed_private_hosts=plugin_options.allowed_private_hosts, + hook_allowed_urls=plugin_options.hook_allowed_urls, + ) + if inventory is None: + raise ValueError("No supported plugin manifest was found") + expected = SourceIdentity.of(inventory) + config, controls = _load_config(inventory.root) + authored = config.get("plugin", {}) + load = plugin_options.plugin_load or authored.get("load", "wrapper") + mode = plugin_options.lift_mode or authored.get("lift_mode", "effectiveness") + retries = plugin_options.trial_retries + if retries is None: + retries = config.get("harbor", {}).get("trial_retries", 0) + if config.get("harbor", {}).get("task_source") == "native_harbor": + raise ValueError("Plugin runs require an evals dataset or member datasets; native_harbor is unsupported") + if plugin_options.probe_mcp_env and not plugin_options.probe_mcp: + raise ValueError("--probe-mcp-env requires --probe-mcp") + results_dir = plugin_results_directory(inventory.root, options.results_dir) + _check_results_location(inventory.root, results_dir) + validation = validate_inventory_schema(inventory, repo_root=plugin_options.repo_root) + policy = plugin_options.policy + # Block on the severities Tier 1 reports: the operator's policy overrides each check's default. + blocking = [ + finding + for finding in validation.findings + if (policy.severity_for(finding.category, finding.check_name, finding.severity) if policy else finding.severity) + in {Severity.CRITICAL, Severity.HIGH} + ] + package = prepare_runtime_package(inventory, expected=expected, blocking_findings=blocking) + agents = parse_agents(options.agents) + if options.agents is None: + agents = resolve_agents(None, provider=resolve_llm_provider().provider) + if not agents or validate_agents(agents): + raise ValueError("Select supported agents with --agents") + options = replace(options, agents=",".join(agents), results_dir=results_dir) + dataset = next( + ( + inventory.root / "evals" / f"evals{extension}" + for extension in DATASET_EXTENSIONS + if os.path.lexists(inventory.root / "evals" / f"evals{extension}") + ), + None, + ) + comparison = ( + None if mode == "effectiveness" else ComparisonOptions(member_skills=True, loose_parts=mode == "ladder") + ) + if mode == "integration": + options = replace(options, skip_baseline=True) + evidence = EvidenceOptions( + probe_mcp=bool(plugin_options.probe_mcp), + env_grants=plugin_options.probe_mcp_env, + allowed_private_hosts=plugin_options.allowed_private_hosts, + ) + # The engine resolves relative paths against the skill it runs, which is the temporary wrapper. + # Resolve them against the authored source first: ``include`` and ``decoy_manifest`` from the + # source's real parent directory, ``price_file`` from the source directory, as the engine does + # from a skill's resolved path (a lexical parent of ``.`` or a link would be wrong). + source_root = inventory.root.resolve() + workspace_config = config.get("skill_workspace", {}) + if include := workspace_config.get("include"): + workspace_config["include"] = [str(source_root.parent / Path(path).expanduser()) for path in include] + if manifest := workspace_config.get("decoy_manifest"): + workspace_config["decoy_manifest"] = str(source_root.parent / Path(manifest).expanduser()) + harbor_config = config.get("harbor", {}) + if price_file := harbor_config.get("price_file"): + harbor_config["price_file"] = str(source_root / Path(price_file).expanduser()) + staged_config = yaml.safe_dump(config).encode("utf-8") if config else None + + def run_prepared(prepared: EvaluationOptions) -> dict[str, Any]: + if staged_config is not None: + (prepared.skill_path / "evals" / "config.yml").write_bytes(staged_config) + for name, raw in controls.items(): + target = prepared.skill_path / "evals" / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + if name.endswith(".sh"): + target.chmod(0o700) + environment = inventory.root / "evals" / "environment" + if os.path.lexists(environment): + from skillevaluator.tier3.harbor.secure_copy import copytree_secure + from skillevaluator.tier3.plugin_prepare import verify_source_identity + + verify_source_identity(package) + copytree_secure( + environment, + prepared.skill_path / "evals" / "environment", + replace_existing=True, + allowed_root=inventory.root, + ) + verify_source_identity(package) + return evaluate(prepared) + + with tempfile.TemporaryDirectory(prefix="skilleval-public-plugin-") as temporary: + outcome = evaluate_prepared_plugin( + package, + options, + work_dir=Path(temporary), + load=load, + evals_source=dataset, + evaluate=run_prepared, + comparison_options=comparison, + evidence_options=evidence, + max_setup_retries=retries, + ) + result = outcome.result + result["plugin_inventory"] = validation.metadata.get("plugin", {}) + result["plugin_provenance"] = { + **{key: value for key, value in outcome.provenance.items() if key != "runtime_report"}, + "attempts": outcome.attempts, + "retry_reasons": outcome.retry_reasons, + "load": load, + "lift_mode": mode, + } + if payload := outcome.provenance.get("runtime_report"): + result["plugin_runtime_report"] = payload + for key in ("publication_error", "cleanup_error"): + if error := getattr(outcome, key): + result["plugin_provenance"][key] = error + if result.get("run_dir") and isinstance(result.get("agents"), dict) and result["agents"]: + from skillevaluator.evaluation.tier3_feedback_chat import saved_feedback_for_run + from skillevaluator.evaluation.tier3_report import render_agent_eval_html_report + from skillevaluator.utils.redaction import redact_printable_text + + try: + run_dir = Path(result["run_dir"]) + refreshed = render_agent_eval_html_report( + inventory.root, + run_dir, + output_path=run_dir / "report.html", + env_mode=options.env_mode, + engine_result=result, + use_llm_judge=False, + include_benchmark=True, + # Reuse the feedback the run's own report pass saved (Insights output and + # what_to_fix.json) instead of replacing it with rule-based text. + saved_feedback=saved_feedback_for_run(result, run_dir), + ) + result["report_path"] = str(refreshed) + result["benchmark_path"] = str(refreshed.with_name("tier3-benchmark.md")) + result["report_status"] = "complete" + except Exception as exc: + warning = redact_printable_text( + f"Runtime report refresh unavailable: {type(exc).__name__}: {exc}", max_len=600 + ) + result["plugin_provenance"]["runtime_report_render_error"] = warning + result.setdefault("warnings", []).append(warning) + result["report_status"] = "degraded" + for key in ("report_path", "benchmark_path"): + if (path := result.get(key)) and not Path(path).is_file(): + result.pop(key, None) + return result diff --git a/tests/reporting/test_saved_plugin_completeness.py b/tests/reporting/test_saved_plugin_completeness.py new file mode 100644 index 000000000..0f63ec46b --- /dev/null +++ b/tests/reporting/test_saved_plugin_completeness.py @@ -0,0 +1,42 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Saved reports retain preparation limitations without live engine state.""" + +import pytest + +from skillevaluator.models import ValidationResult +from skillevaluator.reporting.plugin_reports import attach_saved_plugin_evidence +from skillevaluator.reporting.plugin_runtime import project_plugin_runtime +from skillevaluator.reporting.plugin_runtime_io import save_plugin_runtime_report + + +@pytest.mark.parametrize("engine_result", [None, {}, {"plugin_provenance": {"complete": True}}]) +@pytest.mark.parametrize("prepared_complete", [True, False]) +def test_saved_preparation_evidence_preserves_incomplete_mark(tmp_path, engine_result, prepared_complete): + report = project_plugin_runtime( + { + "run_dir": str(tmp_path), + "execution_status": "completed", + "runtime_evidence": {"evidence_complete": False}, + }, + provenance={"plugin": "sample", "complete": prepared_complete}, + ) + save_plugin_runtime_report(report, tmp_path) + result = ValidationResult(validator_name="AGENT_EVAL", metadata={"agent_eval": {"quality": 0.7}}) + + attach_saved_plugin_evidence(result, tmp_path, engine_result) + + assert ("plugin-components" in result.incomplete_scans) is not prepared_complete + assert result.metadata["plugin_runtime_report"] == report.payload() + assert result.metadata["agent_eval"] == {"quality": 0.7} + + +def test_live_preparation_snapshot_preserves_incomplete_mark_when_saved_file_absent(tmp_path): + report = project_plugin_runtime( + {"run_dir": str(tmp_path), "runtime_evidence": {"evidence_complete": True}}, + provenance={"plugin": "sample", "complete": False}, + ) + result = ValidationResult(validator_name="AGENT_EVAL") + + attach_saved_plugin_evidence(result, tmp_path, {"plugin_runtime_report": report.payload()}) + + assert "plugin-components" in result.incomplete_scans diff --git a/tests/tier3/test_mcp_proof.py b/tests/tier3/test_mcp_proof.py index 85c010ce0..2f411d12f 100644 --- a/tests/tier3/test_mcp_proof.py +++ b/tests/tier3/test_mcp_proof.py @@ -18,6 +18,7 @@ import pytest from skillevaluator.tier3.mcp_proof import ( + MAX_DETAIL_CHARS, NOT_REQUESTED_DETAIL, _check_endpoint, _ProbeRefused, @@ -304,7 +305,7 @@ def test_an_explicit_empty_environment_is_not_the_host_environment( entry = probe_mcp_server(target, allowed_private_hosts=LOCAL, expand_env=("DOCS_TOKEN",), environ={}) assert seen == [{}] - assert "headers skipped because unset: DOCS_TOKEN" in entry["detail"] + assert "headers skipped because unset or empty: DOCS_TOKEN" in entry["detail"] def test_probe_connects_only_to_policy_checked_addresses(monkeypatch: pytest.MonkeyPatch) -> None: @@ -677,10 +678,76 @@ def test_probe_mcp_env_can_be_scoped_to_one_host_or_server( for (name, entry), headers in zip(proof.items(), expected, strict=True): host = f"{name}.test" assert entry["status"] == "reachable-host" - assert (f"sent DOCS_TOKEN to {host}" in entry["detail"]) is bool(headers), entry["detail"] + assert (f"granted DOCS_TOKEN for {host}" in entry["detail"]) is bool(headers), entry["detail"] assert "tok-123" not in json.dumps(entry) +@pytest.mark.parametrize("value", ["tok-123", ""], ids=["set", "empty"]) +def test_a_failed_probe_names_its_grants_before_the_error(monkeypatch: pytest.MonkeyPatch, value: str) -> None: + """A long transport error is cut, not the grant note; a probe that fails may not have sent its headers.""" + import skillevaluator.tier3.mcp_proof as proof + + async def refuse(*_args: Any, **_kwargs: Any) -> Any: + raise OSError("connection refused" + " by the remote host" * 30) + + monkeypatch.setattr(proof, "_probe_session", refuse) + target = { + "name": "docs", + "url": "https://docs.example.com/mcp", + "headers": {"Authorization": "Bearer ${DOCS_TOKEN}"}, + } + + entry = probe_mcp_server( + target, + expand_env=("DOCS_TOKEN=docs.example.com",), + environ={"DOCS_TOKEN": value}, + resolver=lambda _host, _port: ["93.184.216.34"], + ) + + assert entry["status"] == "unreachable" + # An empty variable leaves its header out, like an unset one. + note = "granted DOCS_TOKEN for docs.example.com" if value else "headers skipped because unset or empty: DOCS_TOKEN" + assert f" probe failed; {note}; error: OSError: connection refused by the remote host" in entry["detail"] + assert len(entry["detail"]) == MAX_DETAIL_CHARS + assert "sent" not in entry["detail"] + + +@pytest.mark.parametrize( + ("addresses", "detail"), + [(None, "DNS resolution failed: gaierror"), ([], "DNS resolution returned no addresses")], + ids=["dns-error", "no-addresses"], +) +def test_a_dns_failure_names_no_grants( + monkeypatch: pytest.MonkeyPatch, addresses: list[str] | None, detail: str +) -> None: + """A host that does not resolve is never contacted, so its detail names no variables.""" + import skillevaluator.tier3.mcp_proof as proof + + def resolver(_host: str, _port: int) -> list[str]: + if addresses is None: + raise socket.gaierror(socket.EAI_NONAME, "name does not resolve") + return addresses + + async def never(*_args: Any, **_kwargs: Any) -> Any: + raise AssertionError("a host that does not resolve is never contacted") + + monkeypatch.setattr(proof, "_probe_session", never) + target = { + "name": "docs", + "url": "https://docs.example.com/mcp", + "headers": {"Authorization": "Bearer ${DOCS_TOKEN}"}, + } + + entry = probe_mcp_server( + target, + expand_env=("DOCS_TOKEN=docs.example.com",), + environ={"DOCS_TOKEN": "tok-123"}, + resolver=resolver, + ) + + assert entry == {"status": "unreachable", "tools": [], "detail": detail} + + @pytest.mark.parametrize( "value", ["NOT-A-NAME", "DOCS_TOKEN=", "DOCS_TOKEN=bad host", "DOCS_TOKEN=docs.test:443", "DOCS_TOKEN@", "1TOKEN=docs.test"], diff --git a/tests/tier3/test_plugin_prepare.py b/tests/tier3/test_plugin_prepare.py index b2cb6efdf..596c3233e 100644 --- a/tests/tier3/test_plugin_prepare.py +++ b/tests/tier3/test_plugin_prepare.py @@ -6,20 +6,30 @@ from __future__ import annotations import json +import shutil +import subprocess from dataclasses import replace from pathlib import Path import pytest +from skillevaluator.evaluation.options import EvaluationOptions +from skillevaluator.models.result import Severity from skillevaluator.plugin_inventory import plugin_inventory_for_root +from skillevaluator.tier3.plugin_execution import evaluate_prepared_plugin +from skillevaluator.tier3.plugin_native import PluginLoadError from skillevaluator.tier3.plugin_prepare import ( PreparationError, SourceIdentity, prepare_runtime_package, + stage_wrapper_skill, verify_source_identity, + wrapper_skill_name, ) +from skillevaluator.validators.private_plugin_schema import validate_inventory_schema SKILL = "---\nname: demo\ndescription: Demo skill.\n---\nBody.\n" +requires_git = pytest.mark.skipif(shutil.which("git") is None, reason="git is unavailable") def _tree(root: Path, files: dict) -> Path: @@ -109,3 +119,109 @@ def test_permission_bypass_hook_is_recorded_as_a_native_refusal(tmp_path: Path) source = prepare_runtime_package(_inventory(tmp_path)).native_source assert [hook.rel for hook in source.hooks] == ["hooks/hooks.json"] assert [kind for kind, _, _ in source.refusals] == ["hook"] + + +SAME_SKILL = "github::owner/repo::skills::csv-loader" +SAME_RULE = "github::owner/repo::rules::style.md" +OTHER_SKILL = "github::other/lib::skills::csv-loader" +OTHER_RULE = "github::other/lib::rules::style.md" + + +def _bundle_plugin(root: Path, refs: dict[str, list[str]], *, origin: str | None, packaged: bool = False) -> Path: + """A clone with shared skills and rules, and a bundle-reference plugin whose refs point at them.""" + files: dict = { + "skills/csv-loader/SKILL.md": SKILL, + "rules/style.md": "# Style\n\nUse snake_case column names.\n", + "plugins/myplug/agent_plugin.yaml": { + "name": "myplug", + "description": "CSV helper plugin", + "version": "1.0.0", + "author": {"email": "dev@example.com"}, + **{section: {"refs": values} for section, values in refs.items()}, + }, + "plugins/myplug/evals/evals.json": [{"id": "c1", "prompt": "Load data.csv", "expected_output": "rows"}], + } + if packaged: + files["plugins/myplug/skills/demo/SKILL.md"] = SKILL + _tree(root, files) + subprocess.run(["git", "init", "-q", str(root)], check=True, stdin=subprocess.DEVNULL) + if origin is not None: + subprocess.run( + ["git", "-C", str(root), "remote", "add", "origin", origin], check=True, stdin=subprocess.DEVNULL + ) + return root / "plugins" / "myplug" + + +def _validated_package(plugin: Path): + """Prepare as ``evaluate-plugin`` does: Tier 1 classifies the refs, and only HIGH/CRITICAL findings block.""" + inventory = _inventory(plugin) + validation = validate_inventory_schema(inventory) + blocking = [finding for finding in validation.findings if finding.severity in {Severity.CRITICAL, Severity.HIGH}] + return prepare_runtime_package(inventory, blocking_findings=blocking) + + +@requires_git +@pytest.mark.parametrize( + ("refs", "origin", "state"), + [ + ({"skills": [SAME_SKILL], "rules": [SAME_RULE]}, "https://github.com/owner/repo.git", "referenced"), + ({"skills": [OTHER_SKILL], "rules": [OTHER_RULE]}, "https://github.com/owner/repo.git", "external"), + ({"skills": [SAME_SKILL], "rules": [SAME_RULE]}, None, "unresolved"), + ({"skills": [SAME_SKILL]}, "https://github.com/owner/repo.git", "referenced"), + ], + ids=["same-repo", "external", "no-origin", "skill-only"], +) +def test_references_outside_the_plugin_root_fail_closed( + tmp_path: Path, refs: dict[str, list[str]], origin: str | None, state: str +) -> None: + plugin = _bundle_plugin(tmp_path / "repo", refs, origin=origin) + package = _validated_package(plugin) + expected = [(kind[:-1], ref) for kind, values in refs.items() for ref in values] + + assert package.skills == () and package.rules == () + assert package.native_source.rules == () + assert sorted((row.type, row.name, row.reason) for row in package.audit) == sorted( + (kind, ref, f"not staged: {state} reference") for kind, ref in expected + ) + assert sorted(package.incomplete_reasons) == sorted( + f"{kind} reference '{ref}' was not staged ({state})" for kind, ref in expected + ) + assert not package.complete + assert not package.runnable + wrapper = stage_wrapper_skill( + package, tmp_path / wrapper_skill_name(package.plugin_name), evals_source=plugin / "evals" / "evals.json" + ) + assert "## Rule:" not in (wrapper.path / "SKILL.md").read_text(encoding="utf-8") + with pytest.raises(PluginLoadError, match=f"was not staged \\({state}\\)"): + evaluate_prepared_plugin( + package, + EvaluationOptions(skill_path=plugin), + work_dir=tmp_path, + evaluate=lambda _: pytest.fail("an unstaged plugin must not reach the engine"), + ) + + +@requires_git +def test_packaged_members_still_run_but_the_package_is_incomplete(tmp_path: Path) -> None: + plugin = _bundle_plugin( + tmp_path / "repo", {"rules": [SAME_RULE]}, origin="https://github.com/owner/repo.git", packaged=True + ) + package = _validated_package(plugin) + + assert [member.name for member in package.skills] == ["demo"] + assert package.rules == () and package.native_source.rules == () + assert package.runnable + assert package.incomplete_reasons == (f"rule reference '{SAME_RULE}' was not staged (referenced)",) + assert not package.complete + + +def test_unclassified_references_are_listed_as_not_staged(tmp_path: Path) -> None: + # Without the Tier 1 dependency classification, the state is still named. + _tree(tmp_path, {"agent_plugin.yaml": {"name": "bundle", "rules": {"refs": [OTHER_RULE]}}}) + package = prepare_runtime_package(_inventory(tmp_path)) + + assert [(row.type, row.name, row.reason) for row in package.audit] == [ + ("rule", OTHER_RULE, "not staged: unclassified reference") + ] + assert package.incomplete_reasons == (f"rule reference '{OTHER_RULE}' was not staged (unclassified)",) + assert package.native_source.rules == () and not package.runnable diff --git a/tests/tier3/test_public_plugin_source.py b/tests/tier3/test_public_plugin_source.py new file mode 100644 index 000000000..1fb357f04 --- /dev/null +++ b/tests/tier3/test_public_plugin_source.py @@ -0,0 +1,317 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Generated plugin packages keep their verified authored source context.""" + +import json +import shutil +from contextlib import nullcontext +from pathlib import Path +from types import SimpleNamespace + +import pytest +from test_public_plugin_workflow import _default_results_location, _plugin, evaluate_plugin # noqa: F401 + +from skillevaluator.evaluation import EvaluationOptions, EvaluationService + + +@pytest.mark.parametrize("absolute", [False, True], ids=["sibling", "absolute"]) +def test_workspace_includes_keep_authored_source_context(tmp_path, monkeypatch, absolute): + import yaml + + from skillevaluator.tier3.evals_config import load_evals_config + from skillevaluator.tier3.harbor.runner import _workspace_skills + + root = _plugin(tmp_path / "plugin") + helper = tmp_path / "helper" + helper.mkdir() + (helper / "SKILL.md").write_text( + "---\nname: helper\ndescription: Separate helper.\n---\nHelper body.\n", encoding="utf-8" + ) + (root / "evals").mkdir() + (root / "evals/config.yml").write_text( + yaml.safe_dump( + { + "schema_version": 1, + "skill_workspace": {"mode": "group", "include": [str(helper) if absolute else "helper"]}, + } + ), + encoding="utf-8", + ) + seen = [] + + def engine(self, options, *, progress_reporter=None): + config, _ = load_evals_config(options.skill_path) + seen.extend(_workspace_skills(options.skill_path, config["skill_workspace"]["include"])) + return {"execution_status": "succeeded"} + + monkeypatch.setattr(EvaluationService, "evaluate", engine) + evaluate_plugin(EvaluationOptions(root, agents="claude-code")) + assert seen == [helper] + + +@pytest.mark.parametrize("absolute", [False, True], ids=["relative", "absolute"]) +def test_price_file_and_decoy_manifest_keep_authored_source_context(tmp_path, monkeypatch, absolute): + import yaml + + from skillevaluator.tier3 import decoys + from skillevaluator.tier3.evals_config import load_evals_config + from skillevaluator.tier3.harbor.runner import _decoy_workspace_skills, _resolve_harbor_price_file + + root = _plugin(tmp_path / "plugin") + (root / "evals").mkdir() + price_book = root / "evals/prices.json" + price_book.write_text("{}", encoding="utf-8") + manifest = tmp_path / "decoys.json" + manifest.write_text("{}", encoding="utf-8") + (root / "evals/config.yml").write_text( + yaml.safe_dump( + { + "schema_version": 1, + "harbor": { + "max_cost_usd": 1.0, + "price_file": str(price_book) if absolute else "evals/prices.json", + }, + "skill_workspace": {"mode": "group", "decoy_manifest": str(manifest) if absolute else "decoys.json"}, + } + ), + encoding="utf-8", + ) + seen = {} + + def load_manifest(target, manifest_path): + seen["manifest"] = manifest_path + return [], {"selected": []} + + def engine(self, options, *, progress_reporter=None): + config, _ = load_evals_config(options.skill_path) + seen["price_file"] = _resolve_harbor_price_file(None, config["harbor"], options.skill_path) + _decoy_workspace_skills(options.skill_path, config["skill_workspace"], "group") + return {"execution_status": "succeeded"} + + monkeypatch.setattr(decoys, "load_decoy_manifest", load_manifest) + monkeypatch.setattr(EvaluationService, "evaluate", engine) + evaluate_plugin(EvaluationOptions(root, agents="claude-code")) + # The price book is read from the plugin, and the manifest from the plugin's parent, as for a skill. + assert seen["price_file"] == price_book.resolve() and seen["price_file"].is_file() + assert seen["manifest"].resolve() == manifest.resolve() + + +def test_missing_workspace_include_remains_an_error(tmp_path, monkeypatch): + from skillevaluator.tier3.evals_config import load_evals_config + from skillevaluator.tier3.harbor.runner import _workspace_skills + + root = _plugin(tmp_path / "plugin") + (root / "evals").mkdir() + (root / "evals/config.yml").write_text( + "schema_version: 1\nskill_workspace:\n mode: group\n include: [missing-helper]\n", encoding="utf-8" + ) + + def engine(self, options, *, progress_reporter=None): + config, _ = load_evals_config(options.skill_path) + _workspace_skills(options.skill_path, config["skill_workspace"]["include"]) + return {"execution_status": "succeeded"} + + monkeypatch.setattr(EvaluationService, "evaluate", engine) + with pytest.raises(ValueError, match="Included skill path is not a skill"): + evaluate_plugin(EvaluationOptions(root, agents="claude-code")) + + +def test_custom_environment_assets_survive_staging(tmp_path, monkeypatch): + root = _plugin(tmp_path / "plugin") + environment = root / "evals/environment" + (environment / "sidecar").mkdir(parents=True) + (environment / "Dockerfile").write_text("FROM python:3.12-slim\nCOPY sidecar /sidecar\n", encoding="utf-8") + (environment / "sidecar/config.txt").write_text("fixture", encoding="utf-8") + seen = {} + + def engine(self, options, *, progress_reporter=None): + target = options.skill_path / "evals/environment" + seen["dockerfile"] = (target / "Dockerfile").read_text(encoding="utf-8") + seen["asset"] = (target / "sidecar/config.txt").read_text(encoding="utf-8") + return {"execution_status": "succeeded"} + + monkeypatch.setattr(EvaluationService, "evaluate", engine) + evaluate_plugin(EvaluationOptions(root, agents="claude-code")) + assert seen == {"dockerfile": "FROM python:3.12-slim\nCOPY sidecar /sidecar\n", "asset": "fixture"} + + +@pytest.mark.parametrize("comparison", [False, True], ids=["native-hooks", "comparison-hooks"]) +def test_copy_repo_uses_original_source_and_excludes_verifier_inputs(tmp_path, monkeypatch, comparison): + from skillevaluator.plugin_inventory import plugin_inventory_for_root + from skillevaluator.tier3.harbor import adapter + from skillevaluator.tier3.plugin_comparisons import ComparisonOptions, ComparisonRuntime + from skillevaluator.tier3.plugin_execution import NativeRuntimeHooks, private_runtime, runtime_source_path + from skillevaluator.tier3.plugin_prepare import prepare_runtime_package + + root = _plugin(tmp_path / "repo/plugin") + (root.parent / "README.md").write_text("surrounding repository context", encoding="utf-8") + (root.parent / ".env").write_text("PRIVATE_FIXTURE=do-not-copy", encoding="utf-8") + (root / "evals").mkdir() + (root / "evals/grader.py").write_text("evaluator-only fixture", encoding="utf-8") + package = prepare_runtime_package(plugin_inventory_for_root(root)) + hooks = NativeRuntimeHooks(package.native_source, {}, package=package) + active = ( + ComparisonRuntime(hooks, package, ComparisonOptions(), ["claude-code"], baseline=True) if comparison else hooks + ) + wrapper = tmp_path / "work/temporary-wrapper" + wrapper.mkdir(parents=True) + (wrapper / "SKILL.md").write_text("generated wrapper", encoding="utf-8") + + def repository(source): + assert source == root + return root.parent + + monkeypatch.setattr(adapter, "resolve_repo_context_root", repository) + with private_runtime(active): + assert runtime_source_path(wrapper) == root + for baseline in (False, True): + env = tmp_path / f"env-{baseline}" + env.mkdir() + metadata = adapter._stage_repo_context( + env, source_skill_path=wrapper, mode="full", exclude_source_skill=baseline + ) + assert (env / "repo/README.md").read_text(encoding="utf-8") == "surrounding repository context" + assert not (env / "repo/.env").exists() + assert not (env / "repo/plugin/evals").exists() + assert not (env / "repo/plugin/skills/a/evals").exists() + assert (env / "repo/plugin/.claude-plugin/plugin.json").exists() is (not baseline) + assert metadata["repo_root"] == str(root.parent) + assert runtime_source_path(wrapper) == wrapper + + +def test_copy_repo_excludes_member_datasets_in_the_legacy_layout(tmp_path, monkeypatch): + from skillevaluator.plugin_inventory import plugin_inventory_for_root + from skillevaluator.tier3.harbor import adapter + from skillevaluator.tier3.plugin_execution import NativeRuntimeHooks, private_runtime + from skillevaluator.tier3.plugin_prepare import prepare_runtime_package, stage_wrapper_skill + + root = _plugin(tmp_path / "repo/plugin") + legacy = root / "skills/b" + (legacy / "eval").mkdir(parents=True) + (legacy / "SKILL.md").write_text("---\nname: b\ndescription: Legacy member.\n---\nBody.\n", encoding="utf-8") + (legacy / "eval/dataset.json").write_text( + json.dumps([{"id": "legacy", "prompt": "Use b.", "expected_output": "FIXTURE-ANSWER"}]), encoding="utf-8" + ) + (legacy / "eval/notes.md").write_text("verifier-only notes", encoding="utf-8") + # A directory named eval without a dataset is ordinary skill content, as in the wrapper. + (root / "skills/a/eval").mkdir() + (root / "skills/a/eval/helper.md").write_text("runtime helper", encoding="utf-8") + package = prepare_runtime_package(plugin_inventory_for_root(root)) + (tmp_path / "work").mkdir() + wrapper = stage_wrapper_skill(package, tmp_path / "work/wrapper") + # The preparer reads the legacy member dataset, and the wrapper leaves it out. + cases = json.loads((wrapper.path / "evals/evals.json").read_text(encoding="utf-8")) + assert "b-legacy" in [case["id"] for case in cases] + assert not (wrapper.path / "skills/b/eval").exists() + monkeypatch.setattr(adapter, "resolve_repo_context_root", lambda _source: root.parent) + + with private_runtime(NativeRuntimeHooks(package.native_source, {}, package=package)): + env = tmp_path / "env" + env.mkdir() + metadata = adapter._stage_repo_context(env, source_skill_path=wrapper.path, mode="full") + + staged = {entry["container"] for entry in metadata["files"]} + assert "/workspace/repo/plugin/skills/b/SKILL.md" in staged + assert not (env / "repo/plugin/skills/b/eval").exists() + assert not any("FIXTURE-ANSWER" in path.read_text(encoding="utf-8") for path in env.rglob("*") if path.is_file()) + assert (env / "repo/plugin/skills/a/eval/helper.md").read_text(encoding="utf-8") == "runtime helper" + + +def test_relative_source_spelling_resolves_paths_from_its_real_parent(tmp_path, monkeypatch): + import yaml + + from skillevaluator.tier3 import decoys + from skillevaluator.tier3.evals_config import load_evals_config + from skillevaluator.tier3.harbor.runner import ( + _decoy_workspace_skills, + _resolve_harbor_price_file, + _workspace_skills, + ) + + root = _plugin(tmp_path / "plugin") + helper = tmp_path / "helper" + helper.mkdir() + (helper / "SKILL.md").write_text("---\nname: helper\ndescription: Separate helper.\n---\nBody.\n", encoding="utf-8") + (tmp_path / "decoys.json").write_text("{}", encoding="utf-8") + (root / "evals").mkdir() + (root / "evals/prices.json").write_text("{}", encoding="utf-8") + (root / "evals/config.yml").write_text( + yaml.safe_dump( + { + "schema_version": 1, + "harbor": {"max_cost_usd": 1.0, "price_file": "evals/prices.json"}, + "skill_workspace": {"mode": "group", "include": ["helper"], "decoy_manifest": "decoys.json"}, + } + ), + encoding="utf-8", + ) + seen = {} + + def load_manifest(target, manifest_path): + seen["manifest"] = manifest_path + return [], {"selected": []} + + def engine(self, options, *, progress_reporter=None): + config, _ = load_evals_config(options.skill_path) + seen["include"] = _workspace_skills(options.skill_path, config["skill_workspace"]["include"]) + seen["price_file"] = _resolve_harbor_price_file(None, config["harbor"], options.skill_path) + _decoy_workspace_skills(options.skill_path, config["skill_workspace"], "group") + return {"execution_status": "succeeded"} + + monkeypatch.setattr(decoys, "load_decoy_manifest", load_manifest) + monkeypatch.setattr(EvaluationService, "evaluate", engine) + # Run from inside the source, which names it ``.``: its lexical parent is ``.`` too. + monkeypatch.chdir(root) + evaluate_plugin(EvaluationOptions(Path(), agents="claude-code")) + assert seen["include"] == [helper.resolve()] + assert Path(seen["manifest"]).resolve() == (tmp_path / "decoys.json").resolve() + assert seen["price_file"] == (root / "evals/prices.json").resolve() + + +def _case_alias(path): + alias = path.with_name(path.name.upper()) + if not alias.exists(): + pytest.skip("case-sensitive filesystem") + return alias + + +@pytest.mark.parametrize("hooks", [True, False], ids=["prepared-package", "no-hooks"]) +@pytest.mark.parametrize("alias", [False, True], ids=["plain", "case-alias"]) +def test_engine_publishes_a_prepared_package_as_its_authored_source(tmp_path, monkeypatch, hooks, alias): + from skillevaluator.plugin_inventory import plugin_inventory_for_root + from skillevaluator.publication_identity import publication_target_from_path + from skillevaluator.tier3 import commands + from skillevaluator.tier3.plugin_execution import NativeRuntimeHooks, private_runtime + from skillevaluator.tier3.plugin_prepare import prepare_runtime_package, stage_wrapper_skill, wrapper_skill_name + from skillevaluator.tier3.results_location import skill_results_name + from test_tier3_progress import _stub_runner + + root = _plugin(tmp_path / "plugin") + source = _case_alias(root) if alias and hooks else root + package = prepare_runtime_package(plugin_inventory_for_root(source)) + _, wrapper = _stub_runner(monkeypatch, tmp_path / "work", skill_name=wrapper_skill_name(package.plugin_name)) + shutil.rmtree(wrapper) + stage_wrapper_skill(package, wrapper) + typed = _case_alias(wrapper) if alias and not hooks else wrapper + monkeypatch.setattr(commands, "resolve_llm_provider", lambda: SimpleNamespace(provider="openai")) + results = tmp_path / "results" + # With hooks, include a member skill of the authored source: the runtime-context check + # binds it only when it checks the source, not the wrapper. + extra = {"skill_workspace_mode": "group", "include_skills": (source / "skills/a",)} if hooks else {} + options = EvaluationOptions(typed, agents="claude-code", results_dir=results, **extra) + runtime = ( + private_runtime(NativeRuntimeHooks(package.native_source, {}, package=package)) if hooks else nullcontext() + ) + with runtime: + result = EvaluationService().evaluate(options) + # With hooks, the authored source's recorded name (its entry name, also for an alias); + # without, the typed skill path's name, as for any skill. + published = source if hooks else typed + name = publication_target_from_path(source)["skill_name"] if hooks else typed.resolve().name + assert name == (root.name if hooks else typed.name) + + assert result["execution_status"] == "succeeded", result + assert "publication_target_conflict" not in result, result["publication_target_conflict"] + assert result["publication_target"] == publication_target_from_path(published) + saved = json.loads(Path(result["result_path"]).read_text(encoding="utf-8")) + assert result["skill_name"] == saved["skill_name"] == name + assert Path(result["run_dir"]).parent == results / skill_results_name(published) diff --git a/tests/tier3/test_public_plugin_workflow.py b/tests/tier3/test_public_plugin_workflow.py index 5c82c10e1..87e920f65 100644 --- a/tests/tier3/test_public_plugin_workflow.py +++ b/tests/tier3/test_public_plugin_workflow.py @@ -1,12 +1,21 @@ # SPDX-License-Identifier: Apache-2.0 """Public runtime options and the shared service boundary.""" +import json +import os from pathlib import Path import pytest -from skillevaluator.evaluation import EvaluationOptions +from skillevaluator.evaluation import EvaluationOptions, EvaluationService from skillevaluator.evaluation.options import PluginOptions +from skillevaluator.tier3.results_location import ENV_RESULTS_DIR + + +@pytest.fixture(autouse=True) +def _default_results_location(monkeypatch): + # The results-directory helper prefers this variable over ``/results``. + monkeypatch.delenv(ENV_RESULTS_DIR, raising=False) @pytest.mark.parametrize("value", [-1, 6, True, 1.5]) @@ -64,7 +73,595 @@ def test_plugin_controls_do_not_leak_into_skill_engine_kwargs(): ) +def _plugin(root): + files = { + ".claude-plugin/plugin.json": {"name": "demo"}, + "skills/a/SKILL.md": "---\nname: a\ndescription: Fixture member.\n---\nBody.\n", + "skills/a/evals/evals.json": [{"id": "one", "prompt": "Use a."}], + } + for relative, value in files.items(): + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(value if isinstance(value, str) else json.dumps(value), encoding="utf-8") + return root + + +def evaluate_plugin(options, *, plugin_options=None): + """Run the plugin workflow with ``EvaluationService.evaluate`` as its engine callback.""" + from skillevaluator.tier3.plugin_workflow import evaluate_plugin as run_plugin_workflow + + service = EvaluationService() + return run_plugin_workflow( + options, + plugin_options=plugin_options or PluginOptions(), + evaluate=lambda prepared: service.evaluate(prepared, progress_reporter=None), + ) + + +@pytest.mark.parametrize("backend", ["nemo-gym", "gym"]) +def test_plugin_backend_is_rejected_before_preparation_or_execution(tmp_path, monkeypatch, backend): + root = _plugin(tmp_path / "plugin") + + def forbidden(*args, **kwargs): + pytest.fail("Unsupported plugin backend reached preparation or execution") + + monkeypatch.setattr("skillevaluator.tier3.plugin_prepare.prepare_runtime_package", forbidden) + monkeypatch.setattr(EvaluationService, "evaluate", forbidden) + + with pytest.raises(ValueError, match=r"Plugin evaluation requires.*harbor"): + evaluate_plugin(EvaluationOptions(root, agents="claude-code", backend=backend)) + + +@pytest.mark.parametrize( + "run_options,plugin_options,config,error", + [ + ({"skip_with_skill": True}, {}, None, "omit --skip-with-skill"), + ({}, {}, "schema_version: 1\nharbor:\n task_source: native_harbor\n", "native_harbor is unsupported"), + ({}, {"probe_mcp_env": ("FIXTURE_TOKEN",)}, None, "--probe-mcp-env requires --probe-mcp"), + ], + ids=["skip-with-skill", "native-harbor", "env-grants-without-probing"], +) +def test_unsupported_run_settings_are_refused_before_preparation_or_execution( + tmp_path, monkeypatch, run_options, plugin_options, config, error +): + root = _plugin(tmp_path / "plugin") + if config is not None: + (root / "evals").mkdir() + (root / "evals/config.yml").write_text(config, encoding="utf-8") + + def forbidden(*args, **kwargs): + pytest.fail("A refused run reached preparation or execution") + + monkeypatch.setattr("skillevaluator.tier3.plugin_prepare.prepare_runtime_package", forbidden) + monkeypatch.setattr(EvaluationService, "evaluate", forbidden) + + with pytest.raises(ValueError, match=error): + evaluate_plugin( + EvaluationOptions(root, agents="claude-code", **run_options), plugin_options=PluginOptions(**plugin_options) + ) + + +def test_public_workflow_uses_real_preparation_and_cleans_up(tmp_path, monkeypatch): + from skillevaluator.tier3 import plugin_execution + + root = _plugin(tmp_path / "plugin") + seen = {} + + def engine(self, options, *, progress_reporter=None): + seen.update(root=options.skill_path, results=options.results_dir, hooks=plugin_execution.active_runtime()) + seen["cases"] = json.loads((options.skill_path / "evals/evals.json").read_text(encoding="utf-8")) + return {"execution_status": "succeeded"} + + monkeypatch.setattr(EvaluationService, "evaluate", engine) + result = evaluate_plugin(EvaluationOptions(root, agents="claude-code")) + assert seen["hooks"] is not None + assert seen["results"] == root / "results" + assert seen["cases"][0]["expected_skill"] == "a" + assert not seen["root"].exists() and plugin_execution.active_runtime() is None + assert result["plugin_runtime_report"]["execution_status"] == "succeeded" + assert result["plugin_provenance"]["load"] == "wrapper" + assert result["plugin_provenance"]["lift_mode"] == "effectiveness" + assert result["plugin_provenance"]["attempts"] == 1 + + +def test_results_location_variable_replaces_the_source_results(tmp_path, monkeypatch): + root = _plugin(tmp_path / "plugin") + monkeypatch.setenv(ENV_RESULTS_DIR, str(tmp_path / "shared-results")) + seen = {} + + def engine(self, options, *, progress_reporter=None): + seen["results"] = options.results_dir + return {"execution_status": "succeeded"} + + monkeypatch.setattr(EvaluationService, "evaluate", engine) + evaluate_plugin(EvaluationOptions(root, agents="claude-code")) + assert seen["results"] == tmp_path / "shared-results" + + +@pytest.mark.parametrize( + "location,allowed", + [("out", False), ("evals/other", False), ("results/nested", True), ("evals/results", True)], +) +def test_results_inside_the_source_must_use_its_results_directories(tmp_path, monkeypatch, location, allowed): + from skillevaluator.tier3.plugin_prepare import prepare_runtime_package + + root = _plugin(tmp_path / "plugin") + # The publication digest of the source ignores output only under these directories. + (root / "evals").mkdir() + (root / "evals/config.yml").write_text("schema_version: 1\n", encoding="utf-8") + calls = [] + + def prepare(*args, **kwargs): + calls.append("prepare") + return prepare_runtime_package(*args, **kwargs) + + monkeypatch.setattr("skillevaluator.tier3.plugin_prepare.prepare_runtime_package", prepare) + monkeypatch.setattr( + EvaluationService, "evaluate", lambda *_a, **_kw: calls.append("engine") or {"execution_status": "succeeded"} + ) + options = EvaluationOptions(root, agents="claude-code", results_dir=root / location) + if allowed: + evaluate_plugin(options) + assert calls == ["prepare", "engine"] + else: + with pytest.raises(ValueError, match="results root inside the plugin source"): + evaluate_plugin(options) + assert calls == [] + + +def test_results_directory_accepts_trusted_platform_root_alias(tmp_path, monkeypatch): + from skillevaluator.utils.path_security import canonicalize_trusted_root_alias + + root = _plugin(tmp_path.resolve() / "plugin") + real_prefix = Path("/private/var") + alias = Path("/var") + if not root.is_relative_to(real_prefix) or canonicalize_trusted_root_alias(alias) != real_prefix: + pytest.skip("requires the trusted macOS /var root alias") + aliased_root = alias / root.relative_to(real_prefix) + seen = [] + monkeypatch.setattr( + EvaluationService, + "evaluate", + lambda _self, options, **_kw: seen.append(options.results_dir) or {"execution_status": "succeeded"}, + ) + + evaluate_plugin(EvaluationOptions(root, agents="claude-code", results_dir=aliased_root / "results")) + monkeypatch.chdir(aliased_root) + evaluate_plugin(EvaluationOptions(aliased_root, agents="claude-code", results_dir=Path("results"))) + + assert [path.resolve() for path in seen] == [root / "results", root / "results"] + + +def test_evals_results_needs_an_existing_evals_directory(tmp_path, monkeypatch): + root = _plugin(tmp_path / "plugin") + monkeypatch.setattr(EvaluationService, "evaluate", lambda *_a, **_kw: pytest.fail("refused run reached the engine")) + # Creating evals/ for the output would itself change the source's publication digest. + with pytest.raises(ValueError, match="results root inside the plugin source"): + evaluate_plugin(EvaluationOptions(root, agents="claude-code", results_dir=root / "evals/results")) + assert not (root / "evals").exists() + + +def test_authored_settings_apply_when_run_options_are_unset(tmp_path, monkeypatch): + from skillevaluator.tier3 import plugin_execution + from skillevaluator.validators import private_plugin_schema + + root = _plugin(tmp_path / "plugin") + (root / "evals").mkdir() + (root / "evals/config.yml").write_text( + "schema_version: 1\nharbor:\n trial_retries: 2\nplugin:\n load: auto\n lift_mode: integration\n", + encoding="utf-8", + ) + seen = {} + run_private_evaluation = plugin_execution.run_private_evaluation + validate_inventory_schema = private_plugin_schema.validate_inventory_schema + + def run(*args, **kwargs): + seen["retries"] = kwargs["max_setup_retries"] + return run_private_evaluation(*args, **kwargs) + + def validate(inventory, **kwargs): + seen["repo_root"] = kwargs.get("repo_root") + return validate_inventory_schema(inventory, **kwargs) + + def engine(self, options, *, progress_reporter=None): + seen["skip_baseline"] = options.skip_baseline + return {"execution_status": "succeeded"} + + monkeypatch.setattr(plugin_execution, "run_private_evaluation", run) + monkeypatch.setattr(private_plugin_schema, "validate_inventory_schema", validate) + monkeypatch.setattr(EvaluationService, "evaluate", engine) + result = evaluate_plugin( + EvaluationOptions(root, agents="claude-code"), plugin_options=PluginOptions(repo_root=tmp_path) + ) + assert result["plugin_provenance"]["load"] == "auto" + assert result["plugin_provenance"]["lift_mode"] == "integration" + # Integration mode runs no baseline arm. + assert seen == {"retries": 2, "repo_root": tmp_path, "skip_baseline": True} + + +def test_root_dataset_and_authored_config_survive_staging(tmp_path, monkeypatch): + import yaml + + root = _plugin(tmp_path / "plugin") + (root / "evals").mkdir() + (root / "evals/evals.json").write_text('[{"id":"root-case","prompt":"Do root task."}]', encoding="utf-8") + (root / "evals/config.yml").write_text( + "schema_version: 1\nharbor:\n n_attempts: 3\n trial_retries: 1\nplugin:\n load: auto\n" + " lift_mode: both\ngrading:\n mode: custom_only\n", + encoding="utf-8", + ) + (root / "evals/grader.py").write_text("print('fixture')\n", encoding="utf-8") + seen = {} + + def engine(self, options, *, progress_reporter=None): + seen["config"] = yaml.safe_load((options.skill_path / "evals/config.yml").read_text(encoding="utf-8")) + seen["grader"] = (options.skill_path / "evals/grader.py").read_text(encoding="utf-8") + seen["cases"] = json.loads((options.skill_path / "evals/evals.json").read_text(encoding="utf-8")) + return {"execution_status": "succeeded"} + + monkeypatch.setattr(EvaluationService, "evaluate", engine) + result = evaluate_plugin( + EvaluationOptions(root, agents="claude-code"), + plugin_options=PluginOptions(plugin_load="wrapper", lift_mode="effectiveness", trial_retries=0), + ) + assert seen["config"]["harbor"]["n_attempts"] == 3 + assert seen["config"]["grading"]["mode"] == "custom_only" + assert seen["grader"] == "print('fixture')\n" + assert [case["id"] for case in seen["cases"]] == ["root-case"] + assert result["plugin_provenance"]["load"] == "wrapper" + assert result["plugin_provenance"]["lift_mode"] == "effectiveness" + + +@pytest.mark.parametrize( + "graders,selected", + [ + (("tests/grader.py",), "tests/grader.py"), + (("tests/grader.sh",), "tests/grader.sh"), + (("tests/grader.py", "tests/grader.sh"), "tests/grader.py"), + (("grader.sh", "tests/grader.py", "tests/grader.sh"), "grader.sh"), + (("grader.py", "grader.sh", "tests/grader.py", "tests/grader.sh"), "grader.py"), + ], +) +def test_custom_graders_preserve_engine_selection(tmp_path, monkeypatch, graders, selected): + from skillevaluator.tier3.harbor.adapter import _copy_custom_grader + + root = _plugin(tmp_path / "plugin") + (root / "evals").mkdir() + (root / "evals/config.yml").write_text("schema_version: 1\ngrading:\n mode: custom_only\n", encoding="utf-8") + for relative in graders: + path = root / "evals" / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(f"fixture {relative}\n", encoding="utf-8") + task = tmp_path / "task" + + def engine(self, options, *, progress_reporter=None): + assert _copy_custom_grader(task, options.skill_path, "custom_only") + return {"execution_status": "succeeded"} + + monkeypatch.setattr(EvaluationService, "evaluate", engine) + evaluate_plugin(EvaluationOptions(root, agents="claude-code")) + staged = task / "tests" / Path(selected).name + assert staged.read_text(encoding="utf-8") == f"fixture {selected}\n" + if os.name == "posix" and staged.suffix == ".sh": + assert staged.stat().st_mode & 0o111 + + +@pytest.mark.parametrize("mode", ["custom_only", "default_plus_custom"]) +def test_missing_custom_grader_preserves_engine_policy(tmp_path, monkeypatch, mode): + from skillevaluator.tier3.harbor.adapter import _copy_custom_grader + + root = _plugin(tmp_path / "plugin") + (root / "evals").mkdir() + (root / "evals/config.yml").write_text(f"schema_version: 1\ngrading:\n mode: {mode}\n", encoding="utf-8") + + def engine(self, options, *, progress_reporter=None): + assert _copy_custom_grader(tmp_path / "task", options.skill_path, mode) is False + return {"execution_status": "succeeded"} + + monkeypatch.setattr(EvaluationService, "evaluate", engine) + if mode == "custom_only": + with pytest.raises(FileNotFoundError, match="requires evals/grader"): + evaluate_plugin(EvaluationOptions(root, agents="claude-code")) + else: + evaluate_plugin(EvaluationOptions(root, agents="claude-code")) + + +@pytest.mark.parametrize("link", ["file", "directory", "broken"]) +def test_nested_grader_links_are_refused(tmp_path, link): + from skillevaluator.tier3.evals_config import EvalsConfigError + from skillevaluator.tier3.plugin_workflow import _load_config + + root = _plugin(tmp_path / "plugin") + nested = root / "evals/tests" + nested.parent.mkdir() + outside = tmp_path / "outside" + outside.mkdir() + (outside / "grader.py").write_text("fixture\n", encoding="utf-8") + try: + if link == "directory": + nested.symlink_to(outside, target_is_directory=True) + else: + nested.mkdir() + target = outside / ("missing.py" if link == "broken" else "grader.py") + (nested / "grader.py").symlink_to(target) + except (OSError, NotImplementedError): + pytest.skip("symlinks unavailable") + with pytest.raises(EvalsConfigError, match=r"Cannot read bounded .* evals/tests/grader\.py: \S"): + _load_config(root) + + +def test_nested_graders_retain_the_bounded_read_limit(tmp_path): + from skillevaluator.tier3.evals_config import EvalsConfigError + from skillevaluator.tier3.plugin_workflow import MAX_CONFIG_BYTES, _load_config + + root = _plugin(tmp_path / "plugin") + nested = root / "evals/tests" + nested.mkdir(parents=True) + (nested / "grader.py").write_bytes(b"x" * (MAX_CONFIG_BYTES + 1)) + # The error names the file and the reason, not only the fixed prefix. + with pytest.raises( + EvalsConfigError, + match=rf"Cannot read bounded .* evals/tests/grader\.py: Selected file exceeds the {MAX_CONFIG_BYTES}-byte limit", + ): + _load_config(root) + + +def test_invalid_config_yaml_reports_the_file_and_position(tmp_path): + from skillevaluator.tier3.evals_config import EvalsConfigError + from skillevaluator.tier3.plugin_workflow import _load_config + + root = _plugin(tmp_path / "plugin") + (root / "evals").mkdir() + (root / "evals/config.yml").write_text( + "schema_version: 1\nharbor: {n_attempts: 1, n_attempts: 2}\n", encoding="utf-8" + ) + # As the engine reports it for a skill: the file, then the line, column and problem. + with pytest.raises(EvalsConfigError, match=r"config\.yml: invalid YAML: line 2, column 9: .*duplicate mapping key"): + _load_config(root) + + +def test_unsafe_mcp_refused_before_engine_call(tmp_path, monkeypatch): + from skillevaluator.tier3.plugin_prepare import PreparationError + + root = _plugin(tmp_path / "plugin") + (root / ".claude-plugin/plugin.json").write_text( + json.dumps( + { + "name": "demo", + "mcpServers": {"unsafe": {"command": "npx", "args": ["dangerous@latest"]}}, + } + ), + encoding="utf-8", + ) + + def never(*args, **kwargs): + pytest.fail("Blocked package reached the engine") + + monkeypatch.setattr(EvaluationService, "evaluate", never) + with pytest.raises(PreparationError, match="policy blocks"): + evaluate_plugin(EvaluationOptions(root, agents="claude-code")) + + +def _mcp_plugin(root, package): + root = _plugin(root) + manifest = {"name": "demo", "mcpServers": {"server": {"command": "npx", "args": [package]}}} + (root / ".claude-plugin/plugin.json").write_text(json.dumps(manifest), encoding="utf-8") + return root + + +def _policy(tmp_path, overrides): + import yaml + + from skillevaluator.validators.policy import resolve_policy + + path = tmp_path / "policy.yaml" + path.write_text(yaml.safe_dump({"severity_overrides": overrides}), encoding="utf-8") + return resolve_policy(policy_path=path) + + +def test_policy_that_raises_a_finding_to_blocking_stops_the_run_before_the_engine(tmp_path, monkeypatch): + from skillevaluator.tier3.plugin_prepare import PreparationError + + # An unpinned package is a MEDIUM finding by default, so only the override makes it blocking. + root = _mcp_plugin(tmp_path / "plugin", "some-package") + policy = _policy(tmp_path, {"MCP_DECLARATION.mcp_unpinned_package": "critical"}) + calls = [] + monkeypatch.setattr(EvaluationService, "evaluate", lambda *_a, **_kw: calls.append(1) or {"execution_status": "x"}) + + evaluate_plugin(EvaluationOptions(root, agents="claude-code")) + assert calls == [1] + with pytest.raises(PreparationError, match="policy blocks runtime evaluation: mcp_unpinned_package"): + evaluate_plugin( + EvaluationOptions(root, agents="claude-code"), plugin_options=PluginOptions(policy=policy) + ) + assert calls == [1] + + +def test_policy_that_lowers_a_blocking_finding_lets_the_run_start(tmp_path, monkeypatch): + from skillevaluator.tier3.plugin_prepare import PreparationError + + # A floating package version is a HIGH finding by default. + root = _mcp_plugin(tmp_path / "plugin", "some-package@latest") + policy = _policy(tmp_path, {"MCP_DECLARATION.*": "medium"}) + calls = [] + monkeypatch.setattr( + EvaluationService, "evaluate", lambda *_a, **_kw: calls.append(1) or {"execution_status": "succeeded"} + ) + + with pytest.raises(PreparationError, match="mcp_command_floating_version"): + evaluate_plugin(EvaluationOptions(root, agents="claude-code")) + assert calls == [] + result = evaluate_plugin( + EvaluationOptions(root, agents="claude-code"), plugin_options=PluginOptions(policy=policy) + ) + assert calls == [1] + assert result["plugin_runtime_report"]["execution_status"] == "succeeded" + + @pytest.mark.parametrize("value", ["strict", {"MCP_DECLARATION.*": "critical"}]) def test_plugin_policy_must_be_a_validation_policy(value): with pytest.raises(ValueError, match="policy"): PluginOptions(policy=value) + + +@pytest.mark.parametrize("promote", [True, False], ids=["promoted-medium-blocks", "demoted-high-runs"]) +def test_runtime_preparation_uses_effective_policy_severity(tmp_path, monkeypatch, promote): + from skillevaluator.models.result import Severity + from skillevaluator.tier3.plugin_prepare import PreparationError + from skillevaluator.validators.policy import ValidationPolicy + + root = _plugin(tmp_path / "plugin") + if promote: + manifest = root / ".cursor-plugin/plugin.json" + manifest.parent.mkdir() + manifest.write_text('{"name":"other"}', encoding="utf-8") + overrides = {"PLUGIN_SCHEMA.plugin_manifest_conflict": Severity.HIGH} + else: + (root / ".claude-plugin/plugin.json").write_text( + json.dumps({"name": "demo", "mcpServers": {"server": {"command": "npx", "args": ["demo@latest"]}}}), + encoding="utf-8", + ) + overrides = {"MCP_DECLARATION.*": Severity.LOW} + engine_roots = [] + + def engine(self, options, *, progress_reporter=None): + engine_roots.append(options.skill_path) + return {"execution_status": "succeeded"} + + monkeypatch.setattr(EvaluationService, "evaluate", engine) + options = PluginOptions(policy=ValidationPolicy(severity_overrides=overrides)) + if promote: + with pytest.raises(PreparationError, match="plugin_manifest_conflict"): + evaluate_plugin(EvaluationOptions(root, agents="claude-code"), plugin_options=options) + assert engine_roots == [] + else: + result = evaluate_plugin( + EvaluationOptions(root, agents="claude-code"), plugin_options=options + ) + assert result["execution_status"] == "succeeded" + assert len(engine_roots) == 1 and not engine_roots[0].exists() + + +def _scored_run(run_dir): + from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS + + for arm in ("with-skill", "without-skill"): + summary = run_dir / "opencode" / arm / "summary.json" + summary.parent.mkdir(parents=True) + summary.write_text( + json.dumps( + { + "scores": dict.fromkeys(DEFAULT_METRICS, 0.8), + "metrics": list(DEFAULT_METRICS), + "num_trials": 1, + "execution_status": "succeeded", + "execution_errors": [], + "expected_attempts": 1, + "scored_attempts": 1, + } + ), + encoding="utf-8", + ) + (run_dir / "run_config.json").write_text("{}", encoding="utf-8") + (run_dir / "result.json").write_text(json.dumps({"run_id": run_dir.name, "agents": {}}), encoding="utf-8") + return run_dir + + +@pytest.mark.parametrize("complete", [True, False], ids=["complete", "incomplete"]) +def test_refreshed_run_report_is_incomplete_when_the_package_is(tmp_path, monkeypatch, complete): + root = _plugin(tmp_path / "plugin") + if not complete: + # A bundle-reference plugin: its packaged skill still runs, but the rule outside the root is never staged. + (root / ".claude-plugin/plugin.json").unlink() + manifest = { + "name": "demo", + "description": "Fixture.", + "version": "1.0.0", + "author": {"email": "dev@example.com"}, + "rules": {"refs": ["github::other/lib::rules::style.md"]}, + } + (root / "agent_plugin.yaml").write_text(json.dumps(manifest), encoding="utf-8") + run_dir = _scored_run(tmp_path / "results" / "demo" / "20261110_010001") + + def engine(self, options, *, progress_reporter=None): + return { + "execution_status": "succeeded", + "run_id": run_dir.name, + "run_dir": str(run_dir), + "agents": {"opencode": {"with_skill": {}}}, + } + + monkeypatch.setattr(EvaluationService, "evaluate", engine) + result = evaluate_plugin(EvaluationOptions(root, agents="opencode")) + + assert result["plugin_provenance"]["complete"] is complete + assert result["report_status"] == "complete" + # The run-directory report that evaluate-plugin links carries the same incomplete mark as the requested formats. + report = Path(result["report_path"]).read_text(encoding="utf-8") + assert ("plugin-components" in report) is not complete + + +# What a run saves in result.json after its own report pass (Insights output included). +SAVED_FEEDBACK = { + "schema_version": "1.0", + "conclusions": [ + { + "severity": "fail", + "title": "Skill effect", + "message": "per-case result: skill hurts (saved by the run).", + "source": "deterministic", + }, + {"severity": "warn", "title": "Saved conclusion", "message": "Written by the run's Insights pass"}, + ], + "recommendations": [{"severity": "warn", "title": "Saved recommendation", "message": "Kept from the run"}], + "suggestions": ["Saved suggestion"], + "suggestions_v2": [], +} +SAVED_FIXES = [ + { + "case": "one", + "scope": "opencode", + "kind": "skill hurts", + "what": "passes 1/1 without the skill but 0/1 with it", + "attempts_lost": 1, + "action": "Saved fix from the run", + } +] + + +def test_refreshed_run_report_keeps_the_feedback_the_run_saved(tmp_path, monkeypatch): + from skillevaluator.evaluation import insights_judge + from skillevaluator.tier3 import case_summary + + root = _plugin(tmp_path / "plugin") + run_dir = _scored_run(tmp_path / "results" / "demo" / "20261110_010001") + cases = { + "with_skill": {"cases": {"one": {"attempts": [{"passed": False, "trial": "one__1", "score": 0.4}]}}}, + "without_skill": {"cases": {"one": {"attempts": [{"passed": True, "trial": "one__1", "score": 0.6}]}}}, + } + engine_result = { + "execution_status": "succeeded", + "run_id": run_dir.name, + "run_dir": str(run_dir), + "agents": {"opencode": {"pass_at_k": cases}}, + "tier3_feedback": SAVED_FEEDBACK, + } + (run_dir / "result.json").write_text(json.dumps(engine_result), encoding="utf-8") + (run_dir / "what_to_fix.json").write_text(json.dumps(SAVED_FIXES), encoding="utf-8") + saved_fixes = (run_dir / "what_to_fix.json").read_bytes() + calls = [] + monkeypatch.setattr(insights_judge, "build_insights", lambda *_a, **_kw: calls.append("insights") or {}) + monkeypatch.setattr(case_summary, "_llm_actions", lambda _issues, *_a: calls.append("what_to_fix") or []) + monkeypatch.setattr(EvaluationService, "evaluate", lambda *_a, **_kw: json.loads(json.dumps(engine_result))) + + result = evaluate_plugin(EvaluationOptions(root, agents="opencode")) + + assert result["report_status"] == "complete" + assert calls == [] + # The refresh reuses the saved feedback: no rule-based rebuild replaces it in the result, + # the report or the run's what_to_fix.json. + assert result["tier3_feedback"] == SAVED_FEEDBACK + assert (run_dir / "what_to_fix.json").read_bytes() == saved_fixes + report = Path(result["report_path"]).read_text(encoding="utf-8") + for text in ("Saved conclusion", "Saved recommendation", "Saved suggestion"): + assert text in report From 28bb908998e7985ee7594201502f98cc276c8f38 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Sun, 22 Nov 2026 22:44:56 -0800 Subject: [PATCH 8/9] fix(policy): reject non-ASCII brackets in allowlist entries Signed-off-by: Narendran Raghavan --- .../validators/plugin_policy.py | 9 ++++-- tests/validators/test_public_plugin_policy.py | 28 +++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/src/skillevaluator/validators/plugin_policy.py b/src/skillevaluator/validators/plugin_policy.py index 51c11cc19..ca02d6c49 100644 --- a/src/skillevaluator/validators/plugin_policy.py +++ b/src/skillevaluator/validators/plugin_policy.py @@ -49,11 +49,14 @@ def normalize_plugin_allowlist(value: object, key: str, max_chars: int) -> tuple folded = unicodedata.normalize("NFKC", entry) if any(char.isspace() for char in folded) or any(char in folded for char in "%@?#\\"): raise ValueError(f"{key} contains an invalid host pattern") + bracketed = folded.startswith("[") and folded.endswith("]") + # The matcher strips ASCII brackets before folding, so an entry + # whose brackets only become ASCII here would remain a literal name. + if bracketed and not (entry.startswith("[") and entry.endswith("]")): + raise ValueError(f"{key} contains an invalid IP address or network") if "/" in folded or ":" in folded: try: - ipaddress.ip_network( - folded[1:-1] if folded.startswith("[") and folded.endswith("]") else folded, strict=False - ) + ipaddress.ip_network(folded[1:-1] if bracketed else folded, strict=False) except ValueError as exc: raise ValueError(f"{key} contains an invalid IP address or network") from exc _check_host_pattern(entry, key) diff --git a/tests/validators/test_public_plugin_policy.py b/tests/validators/test_public_plugin_policy.py index 800f4b6a0..6407c4f8b 100644 --- a/tests/validators/test_public_plugin_policy.py +++ b/tests/validators/test_public_plugin_policy.py @@ -8,6 +8,7 @@ import pytest from skillevaluator.validators import policy as policy_module +from skillevaluator.validators.mcp_static import HostAllowlist, classify_endpoint_host from skillevaluator.validators.policy import ValidationPolicy, load_policy_file @@ -57,6 +58,33 @@ def test_existing_host_patterns_and_ip_notation_remain_supported(): assert ValidationPolicy(mcp_allowed_private_hosts=entries).mcp_allowed_private_hosts == entries +@pytest.mark.parametrize("setting", ["mcp_allowed_private_hosts", "hook_allowed_urls"]) +@pytest.mark.parametrize( + "entry", ["\uff3b::1\uff3d", "\uff3b127.0.0.1\uff3d", "\uff3b10.0.0.0/8\uff3d", "\uff3b::1]", "[::1\uff3d"] +) +def test_bare_ip_allowlist_entries_reject_brackets_the_matcher_cannot_parse(setting, entry): + with pytest.raises(ValueError, match="invalid IP address or network"): + ValidationPolicy(**{setting: (entry,)}) + + +@pytest.mark.parametrize( + "entry,allowed,denied", + [ + ("[::1]", "::1", "127.0.0.1"), + ("\uff11\uff12\uff17\uff0e\uff10\uff0e\uff10\uff0e\uff11", "127.0.0.1", "127.0.0.2"), + ("\uff11\uff10\uff0e\uff10\uff0e\uff10\uff0e\uff10\uff0f\uff18", "10.1.2.3", "192.168.1.1"), + ("münchen.corp.example", "xn--mnchen-3ya.corp.example", "other.corp.example"), + ], +) +def test_bare_allowlist_keeps_accepted_matcher_normalization(entry, allowed, denied): + policy = ValidationPolicy(mcp_allowed_private_hosts=(entry,)) + hosts = HostAllowlist.from_entries(policy.mcp_allowed_private_hosts) + + assert policy.mcp_allowed_private_hosts == (entry,) + assert hosts.allows_host(allowed, classify_endpoint_host(allowed)) + assert not hosts.allows_host(denied, classify_endpoint_host(denied)) + + def test_allowlist_entries_are_stripped_and_deduplicated(): policy = ValidationPolicy( mcp_allowed_private_hosts=(" localhost ", "localhost", "*.corp.example "), From ea31b2162e689d804f55a44bcc929267ab31762a Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Sun, 22 Nov 2026 23:04:33 -0800 Subject: [PATCH 9/9] test(tier3): allow CPU variance in masking linearity checks Signed-off-by: Narendran Raghavan --- tests/tier3/test_security_finding_evidence.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/tier3/test_security_finding_evidence.py b/tests/tier3/test_security_finding_evidence.py index f74929dfc..92ac2d5f0 100644 --- a/tests/tier3/test_security_finding_evidence.py +++ b/tests/tier3/test_security_finding_evidence.py @@ -2780,11 +2780,12 @@ def test_masking_credentials_behind_flags_grows_linearly_with_the_text(make_text def _grows_linearly(in_pieces: float, whole: float) -> bool: """Whether masking a text whole took *whole* CPU seconds against *in_pieces* for the text in pieces: about as long. - The margin allows for the whole text's larger working set on a loaded CI - runner. A reading that grows with the square of the text takes twice as - long whole or more: each of ten pieces does a hundredth of its work. + The margin allows for the extra cache and memory costs of the whole + text's larger working set on CI. Pure quadratic work takes ten times as + long whole, since each of ten pieces does a hundredth of that work. The + simulated controls also cover linear work with a quadratic component. """ - return whole < 1.6 * in_pieces + 0.05 + return whole < 1.75 * in_pieces + 0.05 @pytest.mark.parametrize( @@ -2792,6 +2793,7 @@ def _grows_linearly(in_pieces: float, whole: float) -> bool: [ pytest.param(lambda length: length * 1e-5, True, id="linear"), pytest.param(lambda length: length * 1e-5 * (1 + length / 2_000_000), True, id="linear-with-a-small-tail"), + pytest.param(lambda length: length * 1e-5 * (1 + length / 230_000), True, id="linear-with-a-moderate-tail"), pytest.param(lambda length: length * 1e-5 * (1 + length / 200_000), False, id="linear-with-a-large-tail"), pytest.param(lambda length: length * length * 1e-9, False, id="quadratic"), ],