Skip to content

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

132 KB
Raw Blame
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

from __future__ import annotations

import contextvars
import json
import shutil
import subprocess
import threading
from collections.abc import Callable
from datetime import timedelta
from pathlib import Path

import pytest
from click.testing import CliRunner

from skillevaluator import cli as cli_module
from skillevaluator.cli import cli
from skillevaluator.tier3.commands import parse_agent_model_overrides, parse_agents, resolve_agents

FIXTURE = Path(__file__).parent / "fixtures" / "skills" / "simple"


def test_version_check_is_in_the_default_tier1_lineup() -> None:
    from skillevaluator.tier1.commands import DEFAULT_CHECKS, OPTIONAL_CHECKS, enabled_check_lineup

    assert "version" in DEFAULT_CHECKS
    assert "version" not in OPTIONAL_CHECKS
    assert enabled_check_lineup(None) == list(DEFAULT_CHECKS)
    assert enabled_check_lineup("security,version") == ["version", "security"]


def test_validate_passes_explicit_previous_version(monkeypatch, tmp_path: Path) -> None:
    from skillevaluator import cli as cli_module

    captured: list[str | None] = []

    def _run_validation(_target: Path, **kwargs):
        captured.append(kwargs["previous_version"])
        return []

    monkeypatch.setattr(cli_module, "run_validation", _run_validation)
    monkeypatch.setattr(cli_module, "emit_reports", lambda *_args, **_kwargs: True)

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            "--no-tier3",
            str(FIXTURE),
            "--no-dedup",
            "--checks",
            "version",
            "--previous-version",
            "1.2.0",
            "--output-dir",
            str(tmp_path / "reports"),
        ],
    )

    assert result.exit_code == 0, result.output
    assert captured == ["1.2.0"]


@pytest.mark.parametrize(
    "command",
    [
        ["validate", "--no-tier3", "--no-dedup", "--no-llm", "--checks", "security"],
        ["security-scan"],
        ["tier1", "security-scan"],
        ["tier1", "--checks", "security", "--no-llm"],
        ["tier1", "validate", "--checks", "security", "--no-llm"],
    ],
    ids=["validate", "security-scan", "tier1-security-scan", "tier1", "tier1-validate"],
)
def test_explicit_skillspector_baseline_reaches_the_security_scan(
    command: list[str], monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    from skillevaluator.models.result import ValidationResult
    from skillevaluator.validators.security import SecurityValidator

    baseline = tmp_path / "approved-baseline.yaml"
    baseline.write_text('version: 2\nrules:\n  - id: "PE5"\n    reason: "Reviewed"\n', encoding="utf-8")
    seen: list[Path | None] = []

    def _run_skillspector(self: SecurityValidator, _path: Path) -> ValidationResult:
        seen.append(self.skillspector_baseline)
        return ValidationResult()

    monkeypatch.setattr(SecurityValidator, "_run_skillspector", _run_skillspector)
    monkeypatch.chdir(tmp_path)

    result = CliRunner().invoke(
        cli,
        [
            *command,
            str(FIXTURE),
            "--skillspector-baseline",
            baseline.name,
            "-r",
            "json",
            "-o",
            str(tmp_path / "reports"),
        ],
    )

    assert result.exit_code == 0, result.output
    assert seen == [baseline.resolve()]


@pytest.mark.parametrize(
    "command",
    [
        ["validate", "--no-tier3", "--no-dedup", "--no-llm"],
        ["tier1", "--no-llm"],
    ],
    ids=["validate", "tier1"],
)
def test_skillspector_baseline_and_skip_both_reach_the_run(
    command: list[str], monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    """``--skip`` on another check must not drop the baseline, and vice versa."""
    from skillevaluator.models.result import ValidationResult
    from skillevaluator.validators.security import SecurityValidator

    baseline = tmp_path / "approved-baseline.yaml"
    baseline.write_text('version: 2\nrules:\n  - id: "PE5"\n    reason: "Reviewed"\n', encoding="utf-8")
    seen: list[Path | None] = []

    def _run_skillspector(self: SecurityValidator, _path: Path) -> ValidationResult:
        seen.append(self.skillspector_baseline)
        return ValidationResult()

    monkeypatch.setattr(SecurityValidator, "_run_skillspector", _run_skillspector)
    reports = tmp_path / "reports"

    result = CliRunner().invoke(
        cli,
        [
            *command,
            str(FIXTURE),
            "--checks",
            "security,unicode",
            "--skip",
            "unicode",
            "--skillspector-baseline",
            str(baseline),
            "-r",
            "json",
            "-o",
            str(reports),
        ],
    )

    assert result.exit_code == 0, result.output
    assert seen == [baseline.resolve()]
    (report,) = reports.rglob("*.json")
    by_name = {entry["validator"]: entry for entry in json.loads(report.read_text(encoding="utf-8"))["results"]}
    assert by_name["Unicode Smuggling Detection"]["skip_reason"] == "skipped with --skip"


def test_skillspector_baseline_must_name_an_existing_file(tmp_path: Path) -> None:
    result = CliRunner().invoke(
        cli, ["security-scan", str(FIXTURE), "--skillspector-baseline", str(tmp_path / "missing.yaml")]
    )

    assert result.exit_code == 2
    assert "--skillspector-baseline" in result.output


def test_claude_alias_is_canonicalized_and_deduplicated() -> None:
    assert parse_agents("claude, claude-code, opencode, claude") == ["claude-code", "opencode"]


@pytest.mark.parametrize(
    ("provider", "expected"),
    [
        ("nv_build", ["opencode"]),
        ("openai", ["codex"]),
        ("anthropic", ["claude-code"]),
        ("bedrock", ["claude-code"]),
        ("openai-compatible", ["codex"]),
    ],
)
def test_agent_default_follows_the_selected_provider(provider: str, expected: list[str]) -> None:
    assert resolve_agents(None, provider=provider) == expected


def test_explicit_agent_selection_overrides_the_provider_default() -> None:
    assert resolve_agents("codex,claude", provider="nv_build") == ["codex", "claude-code"]


def test_claude_alias_model_override_uses_canonical_agent_name() -> None:
    assert parse_agent_model_overrides(("claude=anthropic/claude-sonnet",)) == {
        "claude-code": ["anthropic/claude-sonnet"]
    }


def test_claude_alias_and_canonical_model_overrides_are_rejected() -> None:
    with pytest.raises(ValueError, match=r"claude.*claude-code.*same agent"):
        parse_agent_model_overrides(
            (
                "claude=anthropic/claude-sonnet",
                "claude-code=anthropic/claude-opus",
            )
        )


def test_repeated_canonical_model_overrides_are_rejected() -> None:
    with pytest.raises(ValueError, match=r"claude-code.*claude-code.*one model"):
        parse_agent_model_overrides(
            (
                "claude-code=anthropic/claude-sonnet",
                "claude-code=anthropic/claude-opus",
            )
        )


def test_validate_fixture_no_llm(tmp_path: Path) -> None:
    result = CliRunner().invoke(
        cli,
        [
            "validate",
            "--no-tier3",
            str(FIXTURE),
            "--verbose",
            "--no-llm",
            "--no-dedup",
            "--checks",
            "schema,quality,lint",
            "--output-dir",
            str(tmp_path / "reports"),
        ],
    )

    assert result.exit_code == 0, result.output
    assert "Passed required checks" in result.output


def test_validate_reports_malformed_policy_without_traceback(tmp_path: Path) -> None:
    policy = tmp_path / "broken-policy.yaml"
    policy.write_text("severity_overrides: [", encoding="utf-8")

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            "--no-tier3",
            str(FIXTURE),
            "--no-llm",
            "--no-dedup",
            "--checks",
            "schema",
            "--policy",
            str(policy),
        ],
    )

    assert result.exit_code == 1
    assert f"Invalid policy YAML in {policy}" in result.output
    assert isinstance(result.exception, SystemExit)


def test_validate_prints_tier1_section_banner(tmp_path: Path) -> None:
    # The Tier 1 section is announced as it runs so it is visibly reported in
    # CI logs (SkillEvaluator parity), not only inside the final combined report.
    result = CliRunner().invoke(
        cli,
        [
            "validate",
            "--no-tier3",
            str(FIXTURE),
            "--verbose",
            "--no-llm",
            "--no-dedup",
            "--checks",
            "schema,quality,lint",
            "--output-dir",
            str(tmp_path / "reports"),
        ],
    )

    assert result.exit_code == 0, result.output
    assert "Tier 1: Security and Static Validation" in result.output


def test_validate_tier1_banner_is_stable_in_narrow_terminal(monkeypatch, tmp_path: Path) -> None:
    monkeypatch.setenv("COLUMNS", "20")

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            "--no-tier3",
            str(FIXTURE),
            "--verbose",
            "--no-llm",
            "--no-dedup",
            "--checks",
            "schema,quality,lint",
            "--output-dir",
            str(tmp_path / "reports"),
        ],
    )

    assert result.exit_code == 0, result.output
    assert "Tier 1: Security and Static Validation" in result.output


def test_validate_flushes_tier1_results_before_tier3(monkeypatch) -> None:
    # Tier 1 (and Tier 2) results must reach the terminal BEFORE the
    # long-running Tier 3 agent evaluation, so they remain visible in CI even
    # when Tier 3 is slow or interrupted. Tier 3 is stubbed to keep the test
    # fast and offline.
    from skillevaluator import cli as cli_module
    from skillevaluator.models.result import ValidationResult

    def _stub_agent_eval(*_args, **_kwargs) -> ValidationResult:
        result = ValidationResult(
            validator_name="AGENT_EVAL",
            validator_description="Tier 3: Live Agent Evaluation",
        )
        result.add_warning("stubbed Tier 3")
        # Tier 3 truth remains failed in the report, while validate's exit code
        # is gated only by the Tier 1/Tier 2 snapshot.
        result.passed = False
        return result

    monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _stub_agent_eval)

    runner = CliRunner()
    with runner.isolated_filesystem():
        result = runner.invoke(
            cli,
            [
                "validate",
                "--no-autopilot",
                str(FIXTURE),
                "--verbose",
                "--no-llm",
                "--no-dedup",
                "--agent-eval",
                "--checks",
                "schema",
            ],
        )

    assert result.exit_code == 0, result.output
    out = result.output
    assert "Tier 1: Security and Static Validation" in out
    assert "Tier 3: Live Agent Evaluation" in out
    # The interim Tier 1 summary table is flushed ahead of the Tier 3 section.
    assert out.index("Validation Results") < out.index("Tier 3: Live Agent Evaluation")


def test_validate_help_exposes_optional_agent_runtime_preflight() -> None:
    result = CliRunner().invoke(cli, ["validate", "--help"])

    assert result.exit_code == 0, result.output
    assert "--agent-runtime-preflight" in result.output
    assert "--no-agent-runtime-preflight" in result.output
    assert "default: disabled" in " ".join(result.output.split())


@pytest.mark.parametrize(
    ("flag", "expected"),
    [
        ("--agent-runtime-preflight", True),
        ("--no-agent-runtime-preflight", False),
    ],
)
def test_validate_forwards_agent_runtime_preflight_override(
    monkeypatch, tmp_path: Path, flag: str, expected: bool
) -> None:
    from skillevaluator import cli as cli_module
    from skillevaluator.models.result import ValidationResult

    captured: dict[str, object] = {}

    def _tier3(*_args, **kwargs) -> ValidationResult:
        captured.update(kwargs)
        result = ValidationResult(validator_name="AGENT_EVAL")
        result.add_success("agent_eval", "ok")
        return result

    monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _tier3)

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            "--no-autopilot",
            str(FIXTURE),
            "--no-llm",
            "--no-tier2",
            "--tier3",
            flag,
            "--checks",
            "schema",
            "--output-dir",
            str(tmp_path / "reports"),
        ],
    )

    assert result.exit_code == 0, result.output
    assert captured["agent_runtime_preflight"] is expected


def test_tier1_lint_scripts_fixture() -> None:
    result = CliRunner().invoke(cli, ["tier1", "lint-scripts", str(FIXTURE)])

    assert result.exit_code == 0, result.output
    assert "SCRIPT_LINT" in result.output


def test_create_dataset_dry_run_no_llm() -> None:
    result = CliRunner().invoke(
        cli, ["create-eval-dataset", str(FIXTURE), "--no-llm", "--dry-run", "--grounding", "skill"]
    )

    assert result.exit_code == 0, result.output
    assert "Dry run" in result.output
    assert '"prompt"' in result.output


def test_init_custom_grader_creates_valid_starter(tmp_path: Path) -> None:
    skill_path = tmp_path / "simple"
    shutil.copytree(FIXTURE, skill_path)

    result = CliRunner().invoke(cli, ["init-custom-grader", str(skill_path)])

    assert result.exit_code == 0, result.output
    assert (skill_path / "evals" / "grader.py").exists()
    assert (skill_path / "evals" / "config.yml").exists()
    assert "mode: default_plus_custom" in (skill_path / "evals" / "config.yml").read_text(encoding="utf-8")


def test_init_harbor_task_creates_valid_contract(tmp_path: Path) -> None:
    skill_path = tmp_path / "simple"
    shutil.copytree(FIXTURE, skill_path)

    result = CliRunner().invoke(cli, ["init-harbor-task", str(skill_path), "--with-config"])

    assert result.exit_code == 0, result.output
    assert (skill_path / "evals" / "harbor" / "case-001" / "task.toml").exists()

    validate = CliRunner().invoke(cli, ["tier3", "validate", str(skill_path), "--harbor-contract"])

    assert validate.exit_code == 0, validate.output
    assert "all checks passed" in validate.output


def _plain_text(text: str) -> str:
    """Strip ANSI escape codes (CI may set FORCE_COLOR, making rich emit them)."""
    import re

    return re.sub(r"\x1b\[[0-9;]*m", "", text)


def test_validate_quiet_default_renders_pipeline_view() -> None:
    # Without --verbose the compact pipeline view replaces the banner/table
    # stream: tier sections, a verdict panel, and report pointers.
    runner = CliRunner()
    with runner.isolated_filesystem():
        result = runner.invoke(
            cli, ["validate", "--no-tier3", str(FIXTURE), "--no-llm", "--no-tier2", "--tier1-checks", "schema,quality"]
        )

    out = _plain_text(result.output)
    assert result.exit_code == 0, result.output
    assert "Tier 1 · Static & Security" in out
    assert "skill: simple" in out
    assert "✓ schema" in out  # the per-check ticker persists with final states
    assert "PASS" in out
    assert ".html" in out and ".json" in out
    # Verbose-stream furniture must not leak into the quiet view.
    assert "Tier 1: Security and Static Validation" not in out
    assert "Validation Results" not in out


def test_validate_quiet_always_writes_html_and_json_reports() -> None:
    runner = CliRunner()
    with runner.isolated_filesystem():
        result = runner.invoke(
            cli, ["validate", "--no-tier3", str(FIXTURE), "--no-llm", "--no-dedup", "--checks", "schema"]
        )
        assert result.exit_code == 0, result.output
        reports = list(Path("reports").iterdir())
        assert any(p.suffix == ".html" for p in reports), reports
        assert any(p.suffix == ".json" for p in reports), reports


@pytest.mark.parametrize("in_git_checkout", [False, True], ids=("plain-folder", "git-checkout"))
def test_validate_json_names_a_clean_single_skill_and_records_the_evaluator(
    tmp_path: Path,
    in_git_checkout: bool,
) -> None:
    """A clean skill run with only the schema check has no finding path or
    quality score to name the skill by, and inside a Git checkout the report
    target is the remote URL. The JSON must still list the one skill."""
    from skillevaluator import __version__

    if in_git_checkout and shutil.which("git") is None:
        pytest.skip("git is not installed")
    repo = tmp_path / "repo"
    skill = repo / "skills" / "simple"
    shutil.copytree(FIXTURE, skill)
    manifest = skill / "SKILL.md"
    manifest.write_text(
        manifest.read_text(encoding="utf-8").replace(
            "description: Summarize", "description: Use when notes need action items. Summarize"
        ),
        encoding="utf-8",
    )
    if in_git_checkout:
        subprocess.run(["git", "init", "-q", str(repo)], check=True)
        subprocess.run(
            ["git", "-C", str(repo), "remote", "add", "origin", "https://github.com/example/skills.git"],
            check=True,
        )
    output_dir = tmp_path / "reports"

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            str(skill),
            "--tiers",
            "1",
            "--checks",
            "schema",
            "--no-llm",
            "--report",
            "json",
            "--output-dir",
            str(output_dir),
        ],
    )

    assert result.exit_code == 0, result.output
    report = json.loads(next(output_dir.glob("skillevaluator-output-*.json")).read_text(encoding="utf-8"))
    assert report["skills"] == [{"name": "simple", "passed": True, "issue_count": 0}]
    assert [item["name"] for contributor in report["contributors"] for item in contributor["items"]] == ["simple"]
    assert report["version"] == __version__
    if in_git_checkout:
        assert report["target_path"].startswith("https://github.com/example/skills/")
    else:
        assert report["target_path"] == str(skill.resolve())
    assert report["top_issues"] == []
    assert report["gating"]["tiers"]["1"]["validator_policies"] == [
        {"validator": "Schema & Repository Governance", "blocking": True}
    ]
    benchmark = (output_dir / "BENCHMARK.md").read_text(encoding="utf-8")
    assert "- Skill: `simple`" in benchmark
    assert f"- Evaluator version: `{__version__}`" in benchmark


def test_validate_json_keeps_one_skills_entry_per_rule_of_a_rules_folder(team_rule_dir: Path, tmp_path: Path) -> None:
    """Only a skill directory names its one skill explicitly. A rules folder
    groups its results per rule file, so naming the folder would fold both
    rules into one entry."""
    output_dir = tmp_path / "reports"

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            str(team_rule_dir),
            "--tiers",
            "1",
            "--checks",
            "schema",
            "--no-llm",
            "--report",
            "json",
            "--output-dir",
            str(output_dir),
        ],
    )

    assert result.exit_code == 0, result.output
    report = json.loads(next(output_dir.glob("skillevaluator-output-*.json")).read_text(encoding="utf-8"))
    assert sorted(entry["name"] for entry in report["skills"]) == ["error-handling", "testing"]
    assert not (output_dir / "BENCHMARK.md").exists()


def test_validate_default_reports_do_not_write_into_authored_sibling_skill(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator.tier3.output_provenance import is_generated_output_root

    skill = tmp_path / "simple"
    shutil.copytree(FIXTURE, skill)
    authored_sibling = tmp_path / "reports"
    shutil.copytree(FIXTURE, authored_sibling)
    sibling_manifest = authored_sibling / "SKILL.md"
    sibling_manifest.write_text(
        sibling_manifest.read_text(encoding="utf-8").replace("name: simple", "name: reports"),
        encoding="utf-8",
    )
    initial_files = {
        path.relative_to(authored_sibling): path.read_bytes() for path in authored_sibling.rglob("*") if path.is_file()
    }
    private_state = tmp_path / "private-state"
    private_state.mkdir(mode=0o700)
    monkeypatch.setenv("SKILLEVALUATOR_OUTPUT_PROVENANCE_KEY_FILE", str(private_state / "key"))
    monkeypatch.chdir(tmp_path)

    result = CliRunner().invoke(
        cli,
        ["validate", "--no-tier3", "simple", "--no-llm", "--no-tier2", "--checks", "schema", "--report", "json"],
    )

    output_root = tmp_path / "simple-reports"
    assert result.exit_code == 0, result.output
    assert (output_root / "BENCHMARK.md").is_file()
    assert is_generated_output_root(output_root)
    assert {
        path.relative_to(authored_sibling): path.read_bytes() for path in authored_sibling.rglob("*") if path.is_file()
    } == initial_files


def test_validate_default_in_skill_reports_do_not_mutate_publication_target(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator.publication_identity import publication_target_from_path
    from skillevaluator.tier3.output_provenance import is_generated_output_root

    skill = tmp_path / "simple"
    shutil.copytree(FIXTURE, skill)
    private_state = tmp_path / "private-state"
    private_state.mkdir(mode=0o700)
    monkeypatch.setenv("SKILLEVALUATOR_OUTPUT_PROVENANCE_KEY_FILE", str(private_state / "key"))
    monkeypatch.chdir(skill)
    initial_target = publication_target_from_path(skill)
    assert initial_target is not None

    result = CliRunner().invoke(
        cli,
        ["validate", "--no-tier3", ".", "--no-llm", "--no-tier2", "--checks", "schema", "--report", "json"],
    )

    assert result.exit_code == 0, result.output
    assert (skill.with_name("simple-reports") / "BENCHMARK.md").is_file()
    assert is_generated_output_root(skill.with_name("simple-reports"))
    assert not (skill / "reports").exists()
    assert publication_target_from_path(skill) == initial_target


def test_validate_default_in_skill_reports_refuses_unowned_sibling(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    skill = tmp_path / "simple"
    shutil.copytree(FIXTURE, skill)
    sibling = skill.with_name("simple-reports")
    sibling.mkdir()
    authored = sibling / "BENCHMARK.md"
    authored.write_text("author-owned sentinel\n", encoding="utf-8")
    private_state = tmp_path / "private-state"
    private_state.mkdir(mode=0o700)
    monkeypatch.setenv("SKILLEVALUATOR_OUTPUT_PROVENANCE_KEY_FILE", str(private_state / "key"))
    monkeypatch.chdir(skill)

    result = CliRunner().invoke(
        cli,
        ["validate", "--no-tier3", ".", "--no-llm", "--no-tier2", "--checks", "schema", "--report", "json"],
    )

    assert result.exit_code != 0
    assert "safely reserve default report output" in result.output.lower()
    assert "marker is missing, invalid, or bound to another path" in " ".join(result.output.split())
    assert "-o/--output-dir" in result.output
    assert authored.read_text(encoding="utf-8") == "author-owned sentinel\n"
    assert list(sibling.iterdir()) == [authored]


def test_validate_default_reports_under_changing_ownership_keys_end_with_an_actionable_refusal(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    """A new ownership key per run (a fresh HOME, a new container) cannot reuse earlier default folders."""
    from skillevaluator.tier3.output_provenance import is_generated_output_root

    workspace = tmp_path / "workspace"
    shutil.copytree(FIXTURE, workspace / "simple")
    monkeypatch.chdir(workspace)
    command = ["validate", "--no-tier3", "simple", "--no-llm", "--no-tier2", "--checks", "schema", "--report", "json"]

    def run_with_key(name: str, *extra: str):
        state = tmp_path / name
        state.mkdir(mode=0o700)
        monkeypatch.setenv("SKILLEVALUATOR_OUTPUT_PROVENANCE_KEY_FILE", str(state / "key"))
        return CliRunner().invoke(cli, [*command, *extra])

    first = run_with_key("first-home")
    assert first.exit_code == 0, first.output
    assert is_generated_output_root(workspace / "reports")

    second = run_with_key("second-home")
    assert second.exit_code == 0, second.output
    assert is_generated_output_root(workspace / "simple-reports")
    kept = {path: path.read_bytes() for path in workspace.rglob("*") if path.is_file()}

    third = run_with_key("third-home")
    assert third.exit_code != 0
    message = " ".join(third.output.split())
    assert "safely reserve default report output directory" in message.lower()
    assert "Choose a report directory with -o/--output-dir." in message
    assert {path: path.read_bytes() for path in workspace.rglob("*") if path.is_file()} == kept

    chosen = run_with_key("fourth-home", "-o", str(tmp_path / "chosen-reports"))
    assert chosen.exit_code == 0, chosen.output
    assert (tmp_path / "chosen-reports" / "BENCHMARK.md").is_file()


def test_validate_rejects_case_alias_output_inside_publication_target(
    tmp_path: Path,
) -> None:
    from skillevaluator.publication_identity import publication_target_from_path

    skill = tmp_path / "Demo"
    shutil.copytree(FIXTURE, skill)
    alias = skill.with_name("demo")
    if not alias.exists() or not alias.samefile(skill):
        pytest.skip("filesystem treats differently cased paths as distinct")
    output_dir = alias / "custom-reports"
    initial_target = publication_target_from_path(skill)

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            "--no-tier3",
            str(skill),
            "--no-llm",
            "--no-tier2",
            "--checks",
            "schema",
            "--output-dir",
            str(output_dir),
        ],
    )

    assert result.exit_code != 0
    assert "report output" in result.output.lower()
    assert not output_dir.exists()
    assert publication_target_from_path(skill) == initial_target


def _same_entry_alias(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
    recorded_name: str,
    alias_name: str,
) -> Path:
    """Return a lexical alias that opens the skill entry recorded as *recorded_name*.

    Case- and normalization-insensitive filesystems (the macOS and Windows
    defaults) provide such aliases natively. Elsewhere, simulate one: create
    the entry under the alias spelling and let its parent directory report the
    recorded spelling, as an insensitive filesystem does.
    """
    from skillevaluator import publication_identity

    recorded = tmp_path / recorded_name
    shutil.copytree(FIXTURE, recorded)
    alias = tmp_path / alias_name
    if alias.exists() and alias.samefile(recorded) and {entry.name for entry in tmp_path.iterdir()} == {recorded_name}:
        return alias
    shutil.rmtree(recorded)
    shutil.copytree(FIXTURE, alias)
    entry_name = publication_identity._canonical_directory_entry_name

    def recorded_entry_name(path: Path) -> str:
        name = entry_name(path)
        return recorded_name if name == alias_name else name

    monkeypatch.setattr(publication_identity, "_canonical_directory_entry_name", recorded_entry_name)
    return alias


@pytest.mark.parametrize(
    ("recorded_name", "alias_name"),
    [("simple", "SIMPLE"), ("caf\u00e9", "cafe\u0301"), ("caf\u00e9", "CAFE\u0301")],
    ids=["case", "unicode-normalization", "case-and-normalization"],
)
def test_validate_same_entry_alias_expects_recorded_publication_name(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
    recorded_name: str,
    alias_name: str,
) -> None:
    alias = _same_entry_alias(monkeypatch, tmp_path, recorded_name, alias_name)
    output_dir = tmp_path / "reports"

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            str(alias),
            "--no-llm",
            "--no-autopilot",
            "--tiers",
            "1,3",
            "--checks",
            "version,lint",
            "--report",
            "json",
            "--output-dir",
            str(output_dir),
        ],
    )

    assert result.exit_code == 0, result.output
    benchmark = (output_dir / "BENCHMARK.md").read_text(encoding="utf-8")
    report = json.loads(next(output_dir.glob("skillevaluator-output-*.json")).read_text(encoding="utf-8"))
    assert f"# Skill Benchmark: {recorded_name}" in benchmark
    # The row gets past the identity binding checks; only the narrowed
    # --checks lineup keeps Tier 1 from certifying publication.
    assert "Missing canonical source identity" not in benchmark
    assert "| Tier 1 | Static validation | **INCOMPLETE** | Required Tier 1 checks did not run:" in benchmark
    assert report["tier3"]["skill_name"] == recorded_name
    assert report["tier3"]["summary"]["skill_name"] == recorded_name
    identity_reasons = [
        reason
        for reason in report["publication"]["reasons"]
        if "different" in reason or "conflicting" in reason or "lack one canonical" in reason
    ]
    assert identity_reasons == []


def test_tier3_run_report_expects_recorded_publication_name(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator.evaluation import tier3_report
    from skillevaluator.models.result import ValidationResult
    from skillevaluator.reporting import HTMLReporter

    alias = _same_entry_alias(monkeypatch, tmp_path, "simple", "SIMPLE")
    run_dir = tmp_path / "run"
    run_dir.mkdir()
    expected_names: list[str | None] = []
    monkeypatch.setattr(
        tier3_report,
        "agent_eval_result_from_directory",
        lambda *_args, **_kwargs: ValidationResult(validator_name="AGENT_EVAL"),
    )
    monkeypatch.setattr(HTMLReporter, "save", lambda self, *_args: expected_names.append(self.expected_skill_name))

    tier3_report.render_agent_eval_html_report(alias, run_dir)

    assert expected_names == ["simple"]


def test_validate_rejects_arbitrary_in_skill_report_output_before_validation(tmp_path: Path) -> None:
    from skillevaluator.publication_identity import publication_target_from_path

    skill = tmp_path / "simple"
    shutil.copytree(FIXTURE, skill)
    output_dir = skill / "custom-reports"
    initial_target = publication_target_from_path(skill)
    assert initial_target is not None

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            "--no-tier3",
            str(skill),
            "--no-llm",
            "--no-tier2",
            "--checks",
            "schema",
            "--output-dir",
            str(output_dir),
        ],
    )

    assert result.exit_code != 0
    assert "report output" in result.output.lower()
    assert not output_dir.exists()
    assert publication_target_from_path(skill) == initial_target


def test_standalone_tier1_rejects_in_skill_report_output_before_validation(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator import cli as cli_module

    skill = tmp_path / "simple"
    shutil.copytree(FIXTURE, skill)
    output_dir = skill / "custom-reports"
    calls: list[Path] = []
    monkeypatch.setattr(cli_module, "run_quality_check", lambda path, **_kwargs: calls.append(path) or [])

    result = CliRunner().invoke(
        cli,
        ["quality-check", str(skill), "--report", "json", "--output-dir", str(output_dir)],
    )

    assert result.exit_code != 0
    assert "report output" in result.output.lower()
    assert calls == []
    assert not output_dir.exists()


def _quality_check_messages(
    command: list[str],
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
    *extra_args: str,
) -> list[str]:
    shutil.copytree(FIXTURE, tmp_path / "simple")
    private_state = tmp_path / "private-state"
    private_state.mkdir(mode=0o700)
    monkeypatch.setenv("SKILLEVALUATOR_OUTPUT_PROVENANCE_KEY_FILE", str(private_state / "key"))
    monkeypatch.chdir(tmp_path)

    result = CliRunner().invoke(
        cli,
        [*command, "simple", "--min-score", "0", "--report", "json", "--output-dir", "out", *extra_args],
    )

    assert result.exit_code == 0, result.output
    report = json.loads((tmp_path / "out" / "skillevaluator-quality.json").read_text(encoding="utf-8"))
    return [finding["message"] for result in report["results"] for finding in result["findings"]]


@pytest.mark.parametrize("command", [["quality-check"], ["tier1", "quality-check"]])
def test_quality_check_uses_packaged_default_quality_config(
    command: list[str],
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    messages = _quality_check_messages(command, tmp_path, monkeypatch)

    assert "No prerequisites/requirements documented" in messages
    assert "No limitations documented" in messages
    assert "No troubleshooting section documented" in messages


@pytest.mark.parametrize("command", [["quality-check"], ["tier1", "quality-check"]])
def test_quality_check_applies_custom_quality_config(
    command: list[str],
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    (tmp_path / "quality.yaml").write_text(
        'expected_headers:\n  - heading: "## Security"\n'
        "    message: No security notes documented\n    suggestion: Add security notes\n",
        encoding="utf-8",
    )

    messages = _quality_check_messages(command, tmp_path, monkeypatch, "--quality-config", "quality.yaml")

    assert "No security notes documented" in messages
    assert "No limitations documented" not in messages


@pytest.mark.parametrize("command", [["quality-check"], ["tier1", "quality-check"]])
def test_quality_check_rejects_missing_quality_config(command: list[str], tmp_path: Path) -> None:
    result = CliRunner().invoke(cli, [*command, str(FIXTURE), "--quality-config", str(tmp_path / "missing.yaml")])

    assert result.exit_code == 2
    assert "does not exist" in result.output


def _validate_quality_messages(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, *extra_args: str) -> list[str]:
    shutil.copytree(FIXTURE, tmp_path / "simple")
    private_state = tmp_path / "private-state"
    private_state.mkdir(mode=0o700)
    monkeypatch.setenv("SKILLEVALUATOR_OUTPUT_PROVENANCE_KEY_FILE", str(private_state / "key"))
    monkeypatch.chdir(tmp_path)

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            "--no-tier3",
            "simple",
            "--no-llm",
            "--no-tier2",
            "--tier1-checks",
            "schema,quality",
            "--min-score",
            "0",
            "--report",
            "json",
            "--output-dir",
            "out",
            *extra_args,
        ],
    )

    assert result.exit_code == 0, result.output
    (report_path,) = (tmp_path / "out").glob("skillevaluator-output-*.json")
    report = json.loads(report_path.read_text(encoding="utf-8"))
    return [finding["message"] for result in report["results"] for finding in result["findings"]]


def test_validate_uses_packaged_default_quality_config(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
    messages = _validate_quality_messages(tmp_path, monkeypatch)

    assert "No prerequisites/requirements documented" in messages
    assert "No limitations documented" in messages
    assert "No troubleshooting section documented" in messages


def test_validate_applies_custom_quality_config(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
    (tmp_path / "quality.yaml").write_text(
        'expected_headers:\n  - heading: "## Security"\n'
        "    message: No security notes documented\n    suggestion: Add security notes\n",
        encoding="utf-8",
    )

    messages = _validate_quality_messages(tmp_path, monkeypatch, "--quality-config", "quality.yaml")

    assert "No security notes documented" in messages
    assert "No limitations documented" not in messages


def _tier1_quality_messages(
    command: list[str],
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
    *extra_args: str,
) -> list[str]:
    shutil.copytree(FIXTURE, tmp_path / "simple")
    private_state = tmp_path / "private-state"
    private_state.mkdir(mode=0o700)
    monkeypatch.setenv("SKILLEVALUATOR_OUTPUT_PROVENANCE_KEY_FILE", str(private_state / "key"))
    monkeypatch.chdir(tmp_path)

    result = CliRunner().invoke(
        cli,
        [
            *command,
            "simple",
            "--checks",
            "schema,quality",
            "--no-llm",
            "--min-score",
            "0",
            "--report",
            "json",
            "--output-dir",
            "out",
            *extra_args,
        ],
    )

    assert result.exit_code == 0, result.output
    report = json.loads((tmp_path / "out" / "skillevaluator-tier1.json").read_text(encoding="utf-8"))
    return [finding["message"] for result in report["results"] for finding in result["findings"]]


@pytest.mark.parametrize("command", [["tier1"], ["tier1", "validate"]])
def test_tier1_workflow_uses_packaged_default_quality_config(
    command: list[str],
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    messages = _tier1_quality_messages(command, tmp_path, monkeypatch)

    assert "No prerequisites/requirements documented" in messages
    assert "No limitations documented" in messages
    assert "No troubleshooting section documented" in messages


@pytest.mark.parametrize("command", [["tier1"], ["tier1", "validate"]])
def test_tier1_workflow_applies_custom_quality_config(
    command: list[str],
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    (tmp_path / "quality.yaml").write_text(
        'expected_headers:\n  - heading: "## Security"\n'
        "    message: No security notes documented\n    suggestion: Add security notes\n",
        encoding="utf-8",
    )

    messages = _tier1_quality_messages(command, tmp_path, monkeypatch, "--quality-config", "quality.yaml")

    assert "No security notes documented" in messages
    assert "No limitations documented" not in messages


_INVALID_QUALITY_CONFIG_COMMANDS = [
    ["quality-check"],
    ["tier1", "quality-check"],
    ["tier1"],
    ["tier1", "validate"],
    ["validate", "--no-tier3", "--no-llm", "--no-tier2", "--checks", "schema,quality"],
    # The config is validated up front even when the quality check is not selected.
    ["validate", "--no-tier3", "--no-llm", "--no-tier2", "--checks", "schema"],
]


@pytest.mark.parametrize("command", _INVALID_QUALITY_CONFIG_COMMANDS)
@pytest.mark.parametrize(
    ("config", "expected"),
    [
        ("not: [valid\n", "invalid YAML: line 2, column 1:"),
        (
            'expected_headers:\n  - heading: "## Limitations"\n    point: 10\n'
            "    message: Missing\n    suggestion: Add it\n",
            "unknown key(s) in expected_headers[0]: point",
        ),
    ],
)
def test_cli_rejects_invalid_quality_config_as_usage_error(
    command: list[str],
    config: str,
    expected: str,
    tmp_path: Path,
) -> None:
    config_path = tmp_path / "quality.yaml"
    config_path.write_text(config, encoding="utf-8")

    result = CliRunner().invoke(cli, [*command, str(FIXTURE), "--quality-config", str(config_path)])

    output = _plain_text(result.output)
    assert result.exit_code == 2, result.output
    assert "Invalid value for '--quality-config'" in output
    assert expected in output
    assert "Traceback" not in output


_PII_WAIVER_COMMANDS = {
    "pii-scan": (["pii-scan"], "skillevaluator-pii.json"),
    "tier1-pii-scan": (["tier1", "pii-scan"], "skillevaluator-pii.json"),
    "tier1": (["tier1", "--checks", "pii", "--no-llm"], "skillevaluator-tier1.json"),
    "validate": (
        ["validate", "--no-tier3", "--no-llm", "--no-tier2", "--checks", "pii"],
        "skillevaluator-output-*.json",
    ),
}


def _pii_waiver_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, command: str, *extra_args: str):
    """Run a PII-scanning command on a copy of the fixture with one non-placeholder address in it."""
    from skillevaluator.validators.pii_waivers import pii_evidence_sha256, today_utc

    skill = tmp_path / "simple"
    shutil.copytree(FIXTURE, skill)
    (skill / "contact.md").write_text("# Contact\nWrite to [email protected] for access.\n", encoding="utf-8")
    waiver = {
        "id": "PII-001",
        "category": "emails",
        "file": "simple/contact.md",
        "line": 2,
        "evidence_sha256": pii_evidence_sha256("emails", "[email protected]"),
        "reason": "Public support address of the documented service",
        "owner": "docs-team",
        "created": (today_utc() - timedelta(days=1)).isoformat(),
        "expires": (today_utc() + timedelta(days=300)).isoformat(),
    }
    (tmp_path / "pii-waivers.yaml").write_text(json.dumps({"version": 1, "waivers": [waiver]}), encoding="utf-8")
    monkeypatch.chdir(tmp_path)
    args, report_glob = _PII_WAIVER_COMMANDS[command]

    result = CliRunner().invoke(cli, [*args, "simple", "--report", "json", "--output-dir", "out", *extra_args])

    (report_path,) = (tmp_path / "out").glob(report_glob)
    report = json.loads(report_path.read_text(encoding="utf-8"))
    checks = [finding["check_name"] for entry in report["results"] for finding in entry["findings"]]
    return result, checks


@pytest.mark.parametrize("command", list(_PII_WAIVER_COMMANDS))
def test_pii_waivers_option_applies_reviewed_waivers(
    command: str,
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    result, checks = _pii_waiver_run(tmp_path, monkeypatch, command, "--pii-waivers", "pii-waivers.yaml")

    assert result.exit_code == 0, result.output
    assert "emails" not in checks
    assert "applied-pii-waiver" in checks


@pytest.mark.parametrize("command", list(_PII_WAIVER_COMMANDS))
def test_pii_scan_without_waivers_still_fails(command: str, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
    result, checks = _pii_waiver_run(tmp_path, monkeypatch, command)

    assert result.exit_code != 0
    assert "emails" in checks
    assert "applied-pii-waiver" not in checks


@pytest.mark.parametrize("command", list(_PII_WAIVER_COMMANDS))
def test_cli_rejects_invalid_pii_waivers_as_usage_error(command: str, tmp_path: Path) -> None:
    waivers = tmp_path / "pii-waivers.yaml"
    waivers.write_text("version: 1\nwaivers:\n  - id: PII-001\n    category: emails\n", encoding="utf-8")
    args, _report = _PII_WAIVER_COMMANDS[command]

    result = CliRunner().invoke(cli, [*args, str(FIXTURE), "--pii-waivers", str(waivers)])

    output = _plain_text(result.output)
    assert result.exit_code == 2, result.output
    assert "Invalid value for '--pii-waivers'" in output
    assert "waivers[0] is missing: file, line" in output
    assert "Traceback" not in output


@pytest.mark.parametrize("symlinked", [False, True], ids=["file", "symlinked-file"])
@pytest.mark.parametrize("workers", [None, "2"], ids=["serial", "parallel"])
def test_catalog_validate_reports_each_waiver_only_in_its_own_skill(
    workers: str | None,
    symlinked: bool,
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    """One waiver file serves the catalog; no child may report its siblings' waivers as stale.

    A symlinked waiver file keeps the link's directory as the base of its entries
    in every child, serial or parallel.
    """
    from skillevaluator.validators.pii_waivers import pii_evidence_sha256, today_utc

    names = ("one", "two", "three")
    waivers = []
    for index, name in enumerate(names, 1):
        skill = tmp_path / "catalog" / name
        shutil.copytree(FIXTURE, skill)
        manifest = skill / "SKILL.md"
        manifest.write_text(
            manifest.read_text(encoding="utf-8").replace("name: simple", f"name: {name}"), encoding="utf-8"
        )
        address = f"{name}@company.com"
        (skill / "contact.md").write_text(f"# Contact\nWrite to {address} for access.\n", encoding="utf-8")
        waivers.append(
            {
                "id": f"PII-00{index}",
                "category": "emails",
                "file": f"catalog/{name}/contact.md",
                "line": 2,
                "evidence_sha256": pii_evidence_sha256("emails", address),
                "reason": "Public support address of the documented service",
                "owner": "docs-team",
                "created": (today_utc() - timedelta(days=1)).isoformat(),
                "expires": (today_utc() + timedelta(days=300)).isoformat(),
            }
        )
    waiver_text = json.dumps({"version": 1, "waivers": waivers})
    if symlinked:
        shared = tmp_path.parent / f"{tmp_path.name}-shared"
        shared.mkdir()
        (shared / "pii-waivers.yaml").write_text(waiver_text, encoding="utf-8")
        try:
            (tmp_path / "pii-waivers.yaml").symlink_to(shared / "pii-waivers.yaml")
        except OSError as exc:
            pytest.skip(f"cannot create a symlink here: {exc}")
    else:
        (tmp_path / "pii-waivers.yaml").write_text(waiver_text, encoding="utf-8")
    monkeypatch.chdir(tmp_path)
    args = ["validate", "--no-tier3", "--no-llm", "--no-tier2", "--checks", "pii", "--pii-waivers", "pii-waivers.yaml"]
    if workers:
        args += ["--workers", workers]

    result = CliRunner().invoke(cli, [*args, "catalog", "--report", "json", "--output-dir", "out"])

    assert result.exit_code == 0, result.output
    for index, name in enumerate(names, 1):
        (report_path,) = (tmp_path / "out" / name).glob("skillevaluator-output-*.json")
        report = json.loads(report_path.read_text(encoding="utf-8"))
        dispositions = [
            (finding["check_name"], finding["metadata"]["waiver_id"], finding["file_path"])
            for entry in report["results"]
            for finding in entry["findings"]
            if finding["category"] == "PII_WAIVER"
        ]
        assert dispositions == [("applied-pii-waiver", f"PII-00{index}", "contact.md")], name
    summary = json.loads((tmp_path / "out" / "catalog-summary.json").read_text(encoding="utf-8"))
    assert summary["severity_totals"]["low"] == 0
    assert summary["passed"] == 3


def test_standalone_tier2_rejects_in_skill_report_output_before_validation(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator.tier2 import commands as tier2_commands

    skill = tmp_path / "simple"
    shutil.copytree(FIXTURE, skill)
    output_dir = skill / "custom-reports"
    calls: list[Path] = []
    monkeypatch.setattr(
        tier2_commands,
        "run_context_optimization_check",
        lambda path, **_kwargs: calls.append(path) or [],
    )

    result = CliRunner().invoke(
        cli,
        ["context-optimization-check", str(skill), "--report", "json", "--output-dir", str(output_dir)],
    )

    assert result.exit_code != 0
    assert "report output" in result.output.lower()
    assert calls == []
    assert not output_dir.exists()


@pytest.mark.parametrize(
    ("command", "runner_name"),
    [
        ("quality-check", "run_quality_check"),
        ("rubric-eval", "run_rubric_eval"),
        ("security-scan", "run_security_scan"),
        ("pii-scan", "run_pii_scan"),
        ("lint-scripts", "run_lint_scripts"),
        ("similarity-check", "run_similarity_check"),
        ("context-optimization-check", "run_context_optimization_check"),
        ("dedup-scan", "run_dedup_scan"),
    ],
)
def test_standalone_cli_only_report_does_not_reserve_output_storage(
    command: str,
    runner_name: str,
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator import cli as cli_module
    from skillevaluator.tier2 import commands as tier2_commands

    skill = tmp_path / "simple"
    shutil.copytree(FIXTURE, skill)
    private_state = tmp_path / "private-state"
    private_state.mkdir(mode=0o700)
    monkeypatch.setenv("SKILLEVALUATOR_OUTPUT_PROVENANCE_KEY_FILE", str(private_state / "key"))
    monkeypatch.chdir(skill)

    runner_module = tier2_commands if hasattr(tier2_commands, runner_name) else cli_module
    calls: list[bool] = []
    monkeypatch.setattr(runner_module, runner_name, lambda *_args, **_kwargs: calls.append(True) or [])

    result = CliRunner().invoke(cli, [command, ".", "--report", "cli"])

    assert result.exit_code == 0, result.output
    assert calls == [True]
    assert not skill.with_name("simple-reports").exists()
    assert not (skill / "reports").exists()


def test_validate_tier_aliases_and_selector(monkeypatch) -> None:
    from skillevaluator import cli as cli_module
    from skillevaluator.models.result import ValidationResult

    calls: dict[str, bool] = {}

    def _tier1(*_args, **_kwargs) -> list[ValidationResult]:
        result = ValidationResult(validator_name="SCHEMA")
        result.add_success("schema", "ok")
        return [result]

    def _tier2(*_args, **_kwargs) -> list[ValidationResult]:
        calls["tier2"] = True
        result = ValidationResult(validator_name="Tier 2 Deduplication")
        result.add_success("dedup", "ok")
        return [result]

    def _tier3(*_args, **_kwargs) -> ValidationResult:
        calls["tier3"] = True
        result = ValidationResult(validator_name="AGENT_EVAL")
        result.add_success("agent_eval", "ok")
        return result

    monkeypatch.setattr(cli_module, "run_validation", _tier1)
    monkeypatch.setattr(cli_module, "_run_dedup_or_skip", _tier2)
    monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _tier3)

    runner = CliRunner()
    with runner.isolated_filesystem():
        result = runner.invoke(
            cli, ["validate", "--no-autopilot", str(FIXTURE), "--no-llm", "--tiers", "1,3", "--checks", "schema"]
        )
    assert result.exit_code == 0, result.output
    assert calls == {"tier3": True}

    calls.clear()
    with runner.isolated_filesystem():
        result = runner.invoke(
            cli, ["validate", "--no-autopilot", str(FIXTURE), "--no-llm", "--no-tier2", "--tier3", "--checks", "schema"]
        )
    assert result.exit_code == 0, result.output
    assert calls == {"tier3": True}

    result = CliRunner().invoke(cli, ["validate", str(FIXTURE), "--tiers", "2,3"])
    assert result.exit_code != 0
    assert "Tier 1 always runs" in result.output
    result = CliRunner().invoke(cli, ["validate", str(FIXTURE), "--tiers", "1,9"])
    assert result.exit_code != 0


def test_validate_excludes_report_output_from_tier3_repo_context(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator import cli as cli_module
    from skillevaluator.models.result import ValidationResult
    from skillevaluator.tier3.output_provenance import is_generated_output_root

    skill = tmp_path / "repo" / "simple"
    shutil.copytree(FIXTURE, skill)
    output_dir = skill.parent / "reports"
    captured: dict[str, object] = {}

    def _tier3(*_args, **kwargs) -> ValidationResult:
        captured.update(kwargs)
        result = ValidationResult(validator_name="AGENT_EVAL")
        result.add_warning("stubbed")
        return result

    monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _tier3)

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            str(skill),
            "--no-llm",
            "--no-tier2",
            "--tier3",
            "--copy-repo",
            "--checks",
            "schema",
            "--output-dir",
            str(output_dir),
        ],
    )

    assert result.exit_code == 0, result.output
    assert captured["repo_context_exclude_paths"] == (output_dir,)
    assert is_generated_output_root(output_dir)


@pytest.mark.parametrize("output_dir", [".", "missing/.."])
def test_validate_copy_repo_rejects_repo_root_report_output_before_tier3(
    output_dir: str,
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator import cli as cli_module

    repo = tmp_path / "repo"
    skill = repo / "skills" / "simple"
    shutil.copytree(FIXTURE, skill)
    (repo / ".git").mkdir()
    monkeypatch.chdir(repo)
    calls: list[Path] = []
    monkeypatch.setattr(
        cli_module,
        "_run_agent_eval_or_skip",
        lambda target, **_kwargs: calls.append(target),
    )

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            "skills/simple",
            "--no-llm",
            "--no-tier2",
            "--tier3",
            "--copy-repo",
            "--checks",
            "schema",
            "--output-dir",
            output_dir,
        ],
    )

    assert result.exit_code != 0
    assert "with --copy-repo" in result.output.lower()
    assert "repository root" in result.output.lower()
    assert "dedicated path" in result.output.lower()
    assert calls == []


def test_validate_linked_context_rejects_authored_in_repo_report_output_before_tier3(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator import cli as cli_module

    repo = tmp_path / "repo"
    skill = repo / "skills" / "simple"
    shutil.copytree(FIXTURE, skill)
    (repo / ".git").mkdir()
    authored_output = repo / "docs"
    authored_output.mkdir()
    guide = authored_output / "guide.md"
    guide.write_text("authored dependency\n", encoding="utf-8")
    calls: list[Path] = []
    monkeypatch.setattr(
        cli_module,
        "_run_agent_eval_or_skip",
        lambda path, **_kwargs: calls.append(path),
    )

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            str(skill),
            "--no-llm",
            "--no-tier2",
            "--tier3",
            "--checks",
            "schema",
            "--output-dir",
            str(authored_output),
        ],
    )

    assert result.exit_code == 2
    assert "Tier 3 linked-context staging" in result.output
    assert "generated-output directory" in result.output
    assert calls == []
    assert guide.read_text(encoding="utf-8") == "authored dependency\n"


def test_validate_tier3_rejects_authored_report_output_inside_included_skill(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator import cli as cli_module

    repo = tmp_path / "target-repo"
    skill = repo / "skills" / "simple"
    shutil.copytree(FIXTURE, skill)
    (repo / ".git").mkdir()
    included_skill = tmp_path / "included-repo" / "skills" / "helper"
    shutil.copytree(FIXTURE, included_skill)
    authored_output = included_skill / "references"
    authored_output.mkdir()
    guide = authored_output / "guide.md"
    guide.write_text("authored dependency\n", encoding="utf-8")
    calls: list[Path] = []
    monkeypatch.setattr(
        cli_module,
        "_run_agent_eval_or_skip",
        lambda path, **_kwargs: calls.append(path),
    )

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            str(skill),
            "--no-llm",
            "--no-tier2",
            "--tier3",
            "--checks",
            "schema",
            "--include-skills",
            str(included_skill),
            "--output-dir",
            str(authored_output),
        ],
    )

    assert result.exit_code == 2
    assert "Tier 3 linked-context staging" in result.output
    assert "generated-output directory" in result.output
    assert calls == []
    assert guide.read_text(encoding="utf-8") == "authored dependency\n"


def test_validate_tier3_allows_report_output_elsewhere_in_included_skill_repo(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator import cli as cli_module
    from skillevaluator.models.result import ValidationResult

    repo = tmp_path / "target-repo"
    skill = repo / "skills" / "simple"
    shutil.copytree(FIXTURE, skill)
    (repo / ".git").mkdir()
    included_repo = tmp_path / "included-repo"
    included_skill = included_repo / "skills" / "helper"
    shutil.copytree(FIXTURE, included_skill)
    output_dir = included_repo / "reports"
    output_dir.mkdir()
    sentinel = output_dir / "authored.txt"
    sentinel.write_text("keep me\n", encoding="utf-8")
    captured: dict[str, object] = {}

    def _tier3(*_args, **kwargs) -> ValidationResult:
        captured.update(kwargs)
        result = ValidationResult(validator_name="AGENT_EVAL")
        result.add_warning("stubbed")
        return result

    monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _tier3)

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            str(skill),
            "--no-llm",
            "--no-tier2",
            "--tier3",
            "--copy-repo",
            "--checks",
            "schema",
            "--report",
            "cli",
            "--include-skills",
            str(included_skill),
            "--output-dir",
            str(output_dir),
        ],
    )

    assert result.exit_code == 0, result.output
    assert captured["repo_context_exclude_paths"] == (output_dir,)
    assert sentinel.read_text(encoding="utf-8") == "keep me\n"
    assert (output_dir / "BENCHMARK.md").is_file()


def test_validate_copy_repo_rejects_authored_report_subtree_before_tier3(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator import cli as cli_module

    repo = tmp_path / "repo"
    skill = repo / "skills" / "simple"
    shutil.copytree(FIXTURE, skill)
    (repo / ".git").mkdir()
    authored_output = repo / "src"
    authored_output.mkdir()
    authored = authored_output / "app.py"
    authored.write_text("print('authored')\n", encoding="utf-8")
    calls: list[Path] = []
    monkeypatch.setattr(
        cli_module,
        "_run_agent_eval_or_skip",
        lambda target, **_kwargs: calls.append(target),
    )

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            str(skill),
            "--no-llm",
            "--no-tier2",
            "--tier3",
            "--copy-repo",
            "--checks",
            "schema",
            "--report",
            "cli",
            "--output-dir",
            str(authored_output),
        ],
    )

    assert result.exit_code != 0
    assert "dedicated skillevaluator generated-output directory" in result.output.lower()
    assert authored.read_text(encoding="utf-8") == "print('authored')\n"
    assert calls == []


def test_validate_copy_repo_allows_report_output_above_repo_root(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator import cli as cli_module
    from skillevaluator.models.result import ValidationResult

    repo = tmp_path / "workspace" / "repo"
    skill = repo / "skills" / "simple"
    shutil.copytree(FIXTURE, skill)
    (repo / ".git").mkdir()
    output_dir = repo.parent.parent
    captured: dict[str, object] = {}

    def _tier3(*_args, **kwargs) -> ValidationResult:
        captured.update(kwargs)
        result = ValidationResult(validator_name="AGENT_EVAL")
        result.add_warning("stubbed")
        return result

    monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _tier3)

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            str(skill),
            "--no-llm",
            "--no-tier2",
            "--tier3",
            "--copy-repo",
            "--checks",
            "schema",
            "--report",
            "cli",
            "--output-dir",
            str(output_dir),
        ],
    )

    assert result.exit_code == 0, result.output
    assert captured["repo_context_exclude_paths"] == (output_dir,)


def test_validate_full_runs_autopilot_dataset(monkeypatch) -> None:
    from skillevaluator import cli as cli_module
    from skillevaluator.models.result import ValidationResult

    generated: list[Path] = []
    monkeypatch.setattr(
        cli_module, "_ensure_autopilot_dataset", lambda path, **_kwargs: generated.append(path) or "auto-generated"
    )

    def _tier3(*_args, **_kwargs) -> ValidationResult:
        result = ValidationResult(validator_name="AGENT_EVAL")
        result.add_success("agent_eval", "ok")
        return result

    monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _tier3)

    runner = CliRunner()
    with runner.isolated_filesystem():
        result = runner.invoke(
            cli, ["validate", str(FIXTURE), "--no-llm", "--no-tier2", "--full", "--checks", "schema"]
        )
    assert result.exit_code == 0, result.output
    assert generated, "--full must run the autopilot dataset flow"


def test_validate_autopilot_generates_source_before_tier_identity_capture(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator import cli as cli_module
    from skillevaluator.models.result import ValidationResult
    from skillevaluator.publication_identity import publication_target_from_path

    skill = tmp_path / "simple"
    shutil.copytree(FIXTURE, skill)
    generated_target: list[dict[str, str]] = []
    emitted_results: list[ValidationResult] = []

    def generate(path: Path, **_kwargs: object) -> str:
        evals = path / "evals"
        evals.mkdir()
        (evals / "evals.json").write_text(
            json.dumps(
                {
                    "skill_name": path.name,
                    "evals": [{"id": "simple-001", "prompt": "Summarize this note."}],
                }
            ),
            encoding="utf-8",
        )
        target = publication_target_from_path(path)
        assert target is not None
        generated_target.append(target)
        return "auto-generated"

    def tier3(path: Path, **_kwargs: object) -> ValidationResult:
        target = publication_target_from_path(path)
        assert target is not None
        result = ValidationResult(validator_name="AGENT_EVAL")
        result.add_success("agent_eval", "ok")
        result.metadata.update(
            {
                "execution_status": "succeeded",
                "publication_target": target,
            }
        )
        return result

    def capture(results: list[ValidationResult], **_kwargs: object) -> bool:
        emitted_results.extend(results)
        return True

    monkeypatch.setattr(cli_module, "_ensure_autopilot_dataset", generate)
    monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", tier3)
    monkeypatch.setattr(cli_module, "emit_reports", capture)

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            str(skill),
            "--no-llm",
            "--no-tier2",
            "--autopilot",
            "--checks",
            "schema",
            "-o",
            str(tmp_path / "out"),
        ],
    )

    assert result.exit_code == 0, result.output
    assert len(generated_target) == 1
    tier_targets = [item.metadata.get("publication_target") for item in emitted_results]
    assert len(tier_targets) >= 2
    assert all(target == generated_target[0] for target in tier_targets)


def test_validate_catalog_runs_each_skill_as_separate_job() -> None:
    runner = CliRunner()
    with runner.isolated_filesystem():
        catalog = Path("catalog")
        for name in ("simple", "simple2"):
            shutil.copytree(FIXTURE, catalog / name)
        # keep frontmatter name matching the directory for the copy
        second = catalog / "simple2" / "SKILL.md"
        second.write_text(second.read_text(encoding="utf-8").replace("name: simple", "name: simple2"), encoding="utf-8")
        result = runner.invoke(
            cli,
            [
                "validate",
                "--no-tier3",
                str(catalog.resolve()),
                "--no-llm",
                "--no-dedup",
                "--checks",
                "quality",
                "-o",
                "out",
            ],
        )

        out = _plain_text(result.output)
        assert "skill 1/2 · simple" in out
        assert "skill 2/2 · simple2" in out
        assert "Catalog Result" in out
        assert "all 2 skills passed" in out
        assert result.exit_code == 0, result.output
        assert any(Path("out/simple").glob("*.html"))
        assert any(Path("out/simple2").glob("*.html"))
        summary_path = Path("out/catalog-summary.json")
        assert summary_path.is_file()
        summary = json.loads(summary_path.read_text(encoding="utf-8"))
        assert summary["total"] == 2
        assert summary["passed"] == 2
        assert summary["overall_passed"] is True
        assert len(summary["skills"]) == 2


def test_validate_catalog_workers_runs_skills_in_parallel() -> None:
    runner = CliRunner()
    with runner.isolated_filesystem():
        catalog = Path("catalog")
        for name in ("simple", "simple2"):
            shutil.copytree(FIXTURE, catalog / name)
        second = catalog / "simple2" / "SKILL.md"
        second.write_text(
            second.read_text(encoding="utf-8").replace("name: simple", "name: simple2"),
            encoding="utf-8",
        )
        result = runner.invoke(
            cli,
            [
                "validate",
                "--no-tier3",
                str(catalog.resolve()),
                "--workers",
                "2",
                "--no-llm",
                "--no-dedup",
                "--checks",
                "quality",
                "-r",
                "html",
                "-o",
                "out",
            ],
        )

        out = _plain_text(result.output)
        assert "parallel catalog mode" in out
        assert "Catalog Result" in out
        assert result.exit_code == 0, result.output
        summary = json.loads(Path("out/catalog-summary.json").read_text(encoding="utf-8"))
        assert summary["total"] == 2
        assert summary["passed"] == 2
        assert any(Path("out/simple").glob("*.html"))
        assert any(Path("out/simple2").glob("*.html"))


_EVALUATED_REPOSITORY = "NVIDIA/NVFlare"
_EVALUATED_COMMIT = "2263a2ebdab903e87f7e7c0a001d22c3a926a9cf"
_EVALUATOR_CONTAINER = "ghcr.io/nvidia/skillevaluator@sha256:" + "0117bc2e" * 8


def test_catalog_child_argv_carries_the_evaluated_source(tmp_path: Path) -> None:
    """A parallel child renders its own card, so it needs the parent's identity."""
    from skillevaluator.cli import _catalog_child_argv_from_ctx, validate

    skill_dir = tmp_path / "catalog" / "simple"
    skill_dir.mkdir(parents=True)
    output_dir = tmp_path / "out" / "simple"
    ctx = validate.make_context(
        "validate",
        [
            str(skill_dir),
            "--workers",
            "2",
            "--evaluated-source-repository",
            _EVALUATED_REPOSITORY,
            "--evaluated-source-revision",
            _EVALUATED_COMMIT,
            "--evaluator-container-revision",
            _EVALUATOR_CONTAINER,
        ],
    )

    argv = _catalog_child_argv_from_ctx(ctx, skill_dir, output_dir)

    for option, value in (
        ("--evaluated-source-repository", _EVALUATED_REPOSITORY),
        ("--evaluated-source-revision", _EVALUATED_COMMIT),
        ("--evaluator-container-revision", _EVALUATOR_CONTAINER),
    ):
        assert option in argv
        assert argv[argv.index(option) + 1] == value
    # The child validates one skill, so re-sending --workers would fan out again.
    assert "--workers" not in argv


def test_catalog_child_argv_forwards_the_skillspector_baseline(tmp_path: Path) -> None:
    from skillevaluator.cli import _catalog_child_argv_from_ctx, validate

    skill_dir = tmp_path / "catalog" / "simple"
    skill_dir.mkdir(parents=True)
    baseline = tmp_path / "approved-baseline.yaml"
    baseline.write_text('version: 2\nrules:\n  - id: "PE5"\n    reason: "Reviewed"\n', encoding="utf-8")
    ctx = validate.make_context(
        "validate",
        [str(skill_dir), "--workers", "2", "--skillspector-baseline", str(baseline)],
    )

    argv = _catalog_child_argv_from_ctx(ctx, skill_dir, tmp_path / "out" / "simple")

    assert argv[argv.index("--skillspector-baseline") + 1] == str(baseline.resolve())


def test_catalog_child_argv_forwards_every_validate_option() -> None:
    """The allowlist is explicit, so a new option is silently dropped by default.

    Each parameter is either forwarded by name or listed below with the reason
    it must not reach a child.
    """
    import inspect

    from skillevaluator.cli import _catalog_child_argv_from_ctx, validate

    not_forwarded = {
        "catalog_root": "each child is given the folder it was found in, not the parent's own value",
        "target_path": "the child is given one skill directory, not the catalog root",
        "content_type": "the child re-detects the type of the single skill it is handed",
        "workers": "forwarding it would make each child fan out again",
        "output_dir": "each child is given its own per-skill output directory",
    }
    source = inspect.getsource(_catalog_child_argv_from_ctx)

    dropped = [
        param.name
        for param in validate.params
        if f'params.get("{param.name}"' not in source and f'params["{param.name}"]' not in source
    ]

    assert sorted(dropped) == sorted(not_forwarded)


def test_catalog_child_argv_forwards_run_budget_options(tmp_path: Path) -> None:
    from skillevaluator.cli import _catalog_child_argv_from_ctx, validate

    skill_dir = tmp_path / "catalog" / "simple"
    skill_dir.mkdir(parents=True)
    price_file = tmp_path / "prices.json"
    price_file.write_text("{}", encoding="utf-8")
    ctx = validate.make_context(
        "validate",
        [
            str(skill_dir),
            "--max-agent-tokens",
            "120",
            "--max-judge-calls",
            "5",
            "--max-attempts-total",
            "9",
            "--max-cost-usd",
            "2.5",
            "--price-file",
            str(price_file),
        ],
    )

    argv = _catalog_child_argv_from_ctx(ctx, skill_dir, tmp_path / "out" / "simple")

    for option, value in (
        ("--max-agent-tokens", "120"),
        ("--max-judge-calls", "5"),
        ("--max-attempts-total", "9"),
        ("--max-cost-usd", "2.5"),
        ("--price-file", str(price_file.resolve())),
    ):
        assert option in argv
        assert argv[argv.index(option) + 1] == value


def test_validate_catalog_workers_records_the_evaluated_source_on_every_card() -> None:
    runner = CliRunner()
    with runner.isolated_filesystem():
        catalog = Path("catalog")
        for name in ("simple", "simple2"):
            shutil.copytree(FIXTURE, catalog / name)
        second = catalog / "simple2" / "SKILL.md"
        second.write_text(
            second.read_text(encoding="utf-8").replace("name: simple", "name: simple2"),
            encoding="utf-8",
        )
        result = runner.invoke(
            cli,
            [
                "validate",
                "--no-tier3",
                str(catalog.resolve()),
                "--workers",
                "2",
                "--no-llm",
                "--no-dedup",
                "--checks",
                "quality",
                "-r",
                "html",
                "--evaluated-source-repository",
                _EVALUATED_REPOSITORY,
                "--evaluated-source-revision",
                _EVALUATED_COMMIT,
                "--evaluator-container-revision",
                _EVALUATOR_CONTAINER,
                "-o",
                "out",
            ],
        )

        assert result.exit_code == 0, result.output
        for name in ("simple", "simple2"):
            card = Path("out") / name / "BENCHMARK.md"
            text = card.read_text(encoding="utf-8")
            assert f"- Evaluated source: `{_EVALUATED_REPOSITORY}`" in text
            assert f"- Evaluated source revision: `{_EVALUATED_COMMIT}`" in text


def test_validate_catalog_workers_accepts_options_before_target_path() -> None:
    runner = CliRunner()
    with runner.isolated_filesystem():
        catalog = Path("catalog")
        shutil.copytree(FIXTURE, catalog / "simple")
        result = runner.invoke(
            cli,
            [
                "validate",
                "--no-tier3",
                "--workers",
                "2",
                str(catalog.resolve()),
                "--no-llm",
                "--no-dedup",
                "--checks",
                "quality",
                "-o",
                "out",
            ],
        )

        assert result.exit_code == 0, result.output
        summary = json.loads(Path("out/catalog-summary.json").read_text(encoding="utf-8"))
        assert summary["total"] == 1
        assert summary["passed"] == 1


def test_validate_catalog_workers_preserves_min_score_and_json_format() -> None:
    runner = CliRunner()
    with runner.isolated_filesystem():
        catalog = Path("catalog")
        shutil.copytree(FIXTURE, catalog / "simple")
        result = runner.invoke(
            cli,
            [
                "validate",
                "--no-tier3",
                str(catalog.resolve()),
                "--workers",
                "2",
                "--no-llm",
                "--no-dedup",
                "--checks",
                "quality",
                "-r",
                "json",
                "-o",
                "out",
            ],
        )
        assert result.exit_code == 0, result.output
        assert any(Path("out/simple").glob("skillevaluator-output-*.json"))


def test_validate_catalog_workers_cli_only_report_format() -> None:
    runner = CliRunner()
    with runner.isolated_filesystem():
        catalog = Path("catalog")
        shutil.copytree(FIXTURE, catalog / "simple")
        result = runner.invoke(
            cli,
            [
                "validate",
                "--no-tier3",
                str(catalog.resolve()),
                "--workers",
                "2",
                "--no-llm",
                "--no-dedup",
                "--checks",
                "quality",
                "-r",
                "cli",
                "-o",
                "out",
            ],
        )
        assert result.exit_code == 0, result.output
        assert not any(Path("out/simple").glob("*.html"))
        assert not any(Path("out/simple").glob("skillevaluator-output-*.json"))


def test_validate_catalog_workers_implicit_default_reports() -> None:
    runner = CliRunner()
    with runner.isolated_filesystem():
        catalog = Path("catalog")
        shutil.copytree(FIXTURE, catalog / "simple")
        result = runner.invoke(
            cli,
            [
                "validate",
                "--no-tier3",
                str(catalog.resolve()),
                "--workers",
                "2",
                "--no-llm",
                "--no-dedup",
                "--checks",
                "quality",
                "-o",
                "out",
            ],
        )
        assert result.exit_code == 0, result.output
        assert any(Path("out/simple").glob("*.html"))
        assert any(Path("out/simple").glob("skillevaluator-output-*.json"))


def test_validate_records_json_report_name_for_catalog_binding(monkeypatch) -> None:
    from skillevaluator import cli as cli_module

    monkeypatch.setattr(cli_module, "run_validation", lambda *_args, **_kwargs: [])
    monkeypatch.setattr(cli_module, "emit_reports", lambda *_args, **_kwargs: True)

    runner = CliRunner()
    with runner.isolated_filesystem():
        result = runner.invoke(
            cli,
            ["validate", "--no-tier3", str(FIXTURE), "--no-llm", "--no-tier2", "--checks", "schema", "-o", "out"],
        )

    assert result.exit_code == 0, result.output
    assert cli_module._consume_validate_json_report() is not None


def _handoff_overlap_results(
    *,
    record_alpha: str,
    record_beta: str,
    run_in_context: bool,
) -> dict[str, str | None]:
    """Record two handoffs, then consume both after a barrier (overlap window)."""
    alpha_ctx = contextvars.Context()
    beta_ctx = contextvars.Context()
    barrier = threading.Barrier(2)
    results: dict[str, str | None] = {}
    thread_errors: list[BaseException] = []

    def alpha_lane() -> None:
        cli_module._record_validate_json_report(record_alpha)
        barrier.wait()
        results["alpha"] = cli_module._consume_validate_json_report()

    def beta_lane() -> None:
        cli_module._record_validate_json_report(record_beta)
        barrier.wait()
        results["beta"] = cli_module._consume_validate_json_report()

    def run_lane(ctx: contextvars.Context, lane: Callable[[], None]) -> None:
        try:
            if run_in_context:
                ctx.run(lane)
            else:
                lane()
        except BaseException as exc:
            thread_errors.append(exc)

    threads = (
        threading.Thread(target=run_lane, args=(alpha_ctx, alpha_lane)),
        threading.Thread(target=run_lane, args=(beta_ctx, beta_lane)),
    )
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()
    if thread_errors:
        raise thread_errors[0]
    return results


def test_validate_json_report_handoff_isolated_between_invocations() -> None:
    """Distinct Context instances keep each basename when record/consume overlap."""
    results = _handoff_overlap_results(
        record_alpha="skillevaluator-output-alpha.json",
        record_beta="skillevaluator-output-beta.json",
        run_in_context=True,
    )
    assert results["alpha"] == "skillevaluator-output-alpha.json"
    assert results["beta"] == "skillevaluator-output-beta.json"


def test_validate_json_report_handoff_module_global_leaks_under_overlap(
    monkeypatch,
) -> None:
    """A single module-global slot returns the last writer after overlapping records."""
    slot: str | None = None

    def _record(report_name: str | None) -> None:
        nonlocal slot
        slot = report_name

    def _consume() -> str | None:
        nonlocal slot
        report_name = slot
        slot = None
        return report_name

    monkeypatch.setattr(cli_module, "_record_validate_json_report", _record)
    monkeypatch.setattr(cli_module, "_consume_validate_json_report", _consume)

    results = _handoff_overlap_results(
        record_alpha="skillevaluator-output-alpha.json",
        record_beta="skillevaluator-output-beta.json",
        run_in_context=False,
    )
    assert results != {
        "alpha": "skillevaluator-output-alpha.json",
        "beta": "skillevaluator-output-beta.json",
    }


def test_catalog_summary_binds_exact_json_report_not_sarif_sidecar(monkeypatch) -> None:
    from skillevaluator.models.result import ValidationResult

    def _emit(results, *, report_formats, output_dir, basename, **_kwargs):
        output_dir.mkdir(parents=True, exist_ok=True)
        standard = output_dir / f"{basename}.json"
        sarif = output_dir / f"{basename}.sarif.json"
        standard.write_text(
            json.dumps({"overall_status": "pass", "severity_counts": {"high": 2}}),
            encoding="utf-8",
        )
        sarif.write_text("{}", encoding="utf-8")
        return all(result.passed for result in results)

    monkeypatch.setattr(
        cli_module, "run_validation", lambda *_args, **_kwargs: [ValidationResult(validator_name="Schema")]
    )
    monkeypatch.setattr(cli_module, "emit_reports", _emit)

    runner = CliRunner()
    with runner.isolated_filesystem():
        catalog = Path("catalog")
        shutil.copytree(FIXTURE, catalog / "simple")
        result = runner.invoke(
            cli,
            [
                "validate",
                "--no-tier3",
                str(catalog.resolve()),
                "--no-llm",
                "--no-dedup",
                "--checks",
                "schema",
                "-r",
                "json",
                "-r",
                "sarif",
                "-o",
                "out",
            ],
        )

        assert result.exit_code == 0, result.output
        summary = json.loads(Path("out/catalog-summary.json").read_text(encoding="utf-8"))
        skill = summary["skills"][0]
        assert skill["json_report"].endswith(".json")
        assert not skill["json_report"].endswith(".sarif.json")
        assert skill["severity_counts"] == {"high": 2}


def test_catalog_summary_same_second_rerun_overwrites_json(monkeypatch) -> None:
    from skillevaluator.models.result import Finding, Severity, ValidationResult

    failing = ValidationResult(validator_name="Schema")
    failing.add_structured_finding(
        Finding(
            category="SCHEMA",
            severity=Severity.HIGH,
            check_name="frontmatter_format",
            message="missing frontmatter",
            file_path="SKILL.md",
        ),
        is_error=True,
    )
    outcomes = [[ValidationResult(validator_name="Schema")], [failing]]

    def _run_validation(_target: Path, **_kwargs):
        return outcomes.pop(0)

    def _emit(results, *, report_formats, output_dir, basename, **_kwargs):
        output_dir.mkdir(parents=True, exist_ok=True)
        report = output_dir / f"{basename}.json"
        report.write_text(
            json.dumps(
                {
                    "overall_passed": all(result.passed for result in results),
                    "overall_status": "pass" if all(result.passed for result in results) else "fail",
                    "severity_counts": {"high": 0 if all(result.passed for result in results) else 3},
                }
            ),
            encoding="utf-8",
        )
        return all(result.passed for result in results)

    monkeypatch.setattr(cli_module, "run_validation", _run_validation)
    monkeypatch.setattr(cli_module, "emit_reports", _emit)
    monkeypatch.setattr(
        "skillevaluator.utils.helpers.make_timestamped_basename",
        lambda _prefix: "skillevaluator-output-20260908T000000",
    )

    runner = CliRunner()
    with runner.isolated_filesystem():
        catalog = Path("catalog")
        shutil.copytree(FIXTURE, catalog / "simple")
        first = runner.invoke(
            cli,
            [
                "validate",
                "--no-tier3",
                str(catalog.resolve()),
                "--no-llm",
                "--no-dedup",
                "--checks",
                "schema",
                "-r",
                "json",
                "-o",
                "out",
            ],
        )
        second = runner.invoke(
            cli,
            [
                "validate",
                "--no-tier3",
                str(catalog.resolve()),
                "--no-llm",
                "--no-dedup",
                "--checks",
                "schema",
                "-r",
                "json",
                "-o",
                "out",
            ],
        )

        assert first.exit_code == 0, first.output
        assert second.exit_code != 0, second.output
        summary = json.loads(Path("out/catalog-summary.json").read_text(encoding="utf-8"))
        skill = summary["skills"][0]
        assert skill["json_report"] == "skillevaluator-output-20260908T000000.json"
        assert skill["overall_status"] == "fail"
        assert skill["severity_counts"] == {"high": 3}


def test_write_catalog_summary_rejects_symlinked_parent(tmp_path: Path) -> None:
    external = tmp_path / "external"
    external.mkdir()
    reports = tmp_path / "reports"
    reports.symlink_to(external, target_is_directory=True)
    output_dir = reports / "new" / "nested"

    with pytest.raises(ValueError, match=r"symlink|reparse"):
        cli_module._write_catalog_summary(output_dir, [])

    assert not (external / "new").exists()


def test_catalog_skill_entry_skips_stale_json_without_report_name(tmp_path: Path) -> None:
    skill_dir = tmp_path / "simple"
    skill_dir.mkdir()
    stale = skill_dir / "skillevaluator-output-19990101T000000.json"
    stale.write_text(
        json.dumps({"overall_passed": True, "severity_counts": {"high": 7}}),
        encoding="utf-8",
    )
    entry = cli_module._catalog_skill_entry(
        "simple",
        skill_dir,
        passed=False,
        reason="validation failed",
        json_report_name=None,
    )
    assert "overall_passed" not in entry
    assert "severity_counts" not in entry


def test_validate_catalog_default_reports_cannot_overwrite_reports_skill(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    catalog = tmp_path / "catalog"
    for name in ("simple", "reports"):
        shutil.copytree(FIXTURE, catalog / name)
        manifest = catalog / name / "SKILL.md"
        manifest.write_text(
            manifest.read_text(encoding="utf-8").replace("name: simple", f"name: {name}"),
            encoding="utf-8",
        )
    reports_manifest = catalog / "reports" / "SKILL.md"
    authored = reports_manifest.read_text(encoding="utf-8")
    private_state = tmp_path / "private-state"
    private_state.mkdir(mode=0o700)
    monkeypatch.setenv("SKILLEVALUATOR_OUTPUT_PROVENANCE_KEY_FILE", str(private_state / "key"))
    monkeypatch.chdir(catalog)

    result = CliRunner().invoke(
        cli,
        ["validate", "--no-tier3", ".", "--no-llm", "--no-tier2", "--checks", "schema"],
    )

    assert result.exit_code == 0, result.output
    output_root = catalog.with_name("catalog-reports")
    assert (output_root / "simple" / "BENCHMARK.md").is_file()
    assert (output_root / "reports" / "BENCHMARK.md").is_file()
    assert reports_manifest.read_text(encoding="utf-8") == authored
    assert not (catalog / "reports" / "BENCHMARK.md").exists()


def test_validate_catalog_threads_whole_report_root_to_tier3(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator import cli as cli_module
    from skillevaluator.models.result import ValidationResult

    catalog = tmp_path / "repo" / "catalog"
    for name in ("simple", "simple2"):
        shutil.copytree(FIXTURE, catalog / name)
        manifest = catalog / name / "SKILL.md"
        manifest.write_text(
            manifest.read_text(encoding="utf-8").replace("name: simple", f"name: {name}"),
            encoding="utf-8",
        )
    report_root = catalog.parent / "reports"
    captured: list[tuple[Path, ...]] = []

    def _tier3(*_args, **kwargs) -> ValidationResult:
        captured.append(kwargs["repo_context_exclude_paths"])
        result = ValidationResult(validator_name="AGENT_EVAL")
        result.add_warning("stubbed")
        return result

    monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _tier3)

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            str(catalog),
            "--no-llm",
            "--no-tier2",
            "--tier3",
            "--copy-repo",
            "--checks",
            "schema",
            "--output-dir",
            str(report_root),
        ],
    )

    assert result.exit_code == 0, result.output
    assert len(captured) == 2
    assert all(report_root in exclusions for exclusions in captured)


def test_validate_catalog_rejects_one_previous_version_for_every_skill() -> None:
    runner = CliRunner()
    with runner.isolated_filesystem():
        catalog = Path("catalog")
        for name in ("simple", "simple2"):
            shutil.copytree(FIXTURE, catalog / name)
        second = catalog / "simple2" / "SKILL.md"
        second.write_text(second.read_text(encoding="utf-8").replace("name: simple", "name: simple2"), encoding="utf-8")

        result = runner.invoke(
            cli,
            [
                "validate",
                "--no-tier3",
                str(catalog.resolve()),
                "--no-llm",
                "--no-dedup",
                "--checks",
                "version",
                "--previous-version",
                "1.2.0",
            ],
        )

        assert result.exit_code != 0
        assert "cannot be reused for a catalog" in result.output
        assert not Path("skillevaluator-results").exists()


def test_validate_quiet_failing_run_renders_verdict_and_fails_cleanly(monkeypatch) -> None:
    # Regression: a failing DEFAULT (quiet) run must render the verdict panel
    # and exit via the machine-readable ClickException — not an AttributeError.
    from skillevaluator import cli as cli_module
    from skillevaluator.models.result import Finding, Severity, ValidationResult

    failing = ValidationResult(validator_name="Schema & Repository Governance")
    failing.add_structured_finding(
        Finding(
            category="SCHEMA",
            severity=Severity.HIGH,
            check_name="frontmatter_format",
            message="SKILL.md must have YAML frontmatter between --- markers",
            file_path="SKILL.md",
            suggestion="Add frontmatter block: start with '---', add YAML content, end with '---'",
        ),
        is_error=True,
    )
    monkeypatch.setattr(cli_module, "run_validation", lambda *_args, **_kwargs: [failing])

    runner = CliRunner()
    with runner.isolated_filesystem():
        result = runner.invoke(
            cli, ["validate", "--no-tier3", str(FIXTURE), "--no-llm", "--no-tier2", "--checks", "schema"]
        )

    out = _plain_text(result.output)
    assert result.exit_code != 0
    assert result.exception is None or isinstance(result.exception, SystemExit), result.output
    assert "FAIL" in out
    assert "Schema & Repository Governance failed" in out
    assert "validation failed" in out  # machine-readable line preserved


def test_validate_quiet_tier3_execution_errors_do_not_render_green(monkeypatch) -> None:
    # Regression: a Tier 3 result that ran but reported execution errors must
    # not render as a green pass or claim "all tiers passed" (it stays
    # advisory: the exit code is unaffected).
    from skillevaluator import cli as cli_module
    from skillevaluator.models.result import ValidationResult

    def _tier3(*_args, **_kwargs) -> ValidationResult:
        result = ValidationResult(validator_name="AGENT_EVAL")
        result.add_error("2 of 2 trials crashed")
        result.metadata["agent_eval"] = {
            "execution_status": "failed",
            "execution_errors": ["2 of 2 trials crashed"],
            "summary": {
                "schema_version": "2.0",
                "execution_status": "failed",
                "agents_run": ["codex"],
                "verdict": "fail",
                "skill_name": "simple",
                "best_agent": "codex",
                "overall_score": 0.0,
                "overall_lift": 0.0,
                "environment": "docker",
                "runtime_seconds": 1.0,
            },
            "agents_run": ["codex"],
            "verdict": "fail",
            "overall_score": 0.0,
            "overall_lift": 0.0,
            "agents": {},
            "cases": [],
            "recommendations": [],
            "conclusions": [],
            "insights": [],
            "dimensions": [],
            "evaluators": {},
        }
        return result

    monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _tier3)

    runner = CliRunner()
    with runner.isolated_filesystem():
        result = runner.invoke(
            cli, ["validate", "--no-autopilot", str(FIXTURE), "--no-llm", "--no-tier2", "--tier3", "--checks", "schema"]
        )

    out = _plain_text(result.output)
    assert result.exit_code == 0, result.output  # advisory: gate unaffected
    assert "✗ fail" in out
    assert "2 of 2 trials crashed" in out
    assert "all 2 tiers passed" not in out
    assert "advisory" in out


def test_validate_quiet_handles_oversized_tier3_skip_reason(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator import cli as cli_module
    from skillevaluator.evaluation.tier3_report import advisory_skip_result

    safe_reason = "Live evaluation runtime unavailable"
    oversized_integer = 1 << 40_000

    def _tier3(*_args, **_kwargs):
        result = advisory_skip_result(safe_reason, skill_name="simple")
        result.metadata["skip_reason"] = oversized_integer
        result.metadata["agent_eval"]["provenance"]["message"] = oversized_integer
        return result

    monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _tier3)
    output_dir = tmp_path / "reports"

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            "--no-autopilot",
            str(FIXTURE.resolve()),
            "--no-llm",
            "--no-tier2",
            "--tier3",
            "--checks",
            "schema",
            "--output-dir",
            str(output_dir),
        ],
    )

    assert result.exit_code == 0, result.output
    assert safe_reason in _plain_text(result.output)
    assert (output_dir / "BENCHMARK.md").is_file()


def test_validate_quiet_renders_untrusted_skip_reason_as_bounded_inert_text(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator import cli as cli_module
    from skillevaluator.evaluation.tier3_report import advisory_skip_result

    unsafe_reason = (
        "[/bold] [link=https://example.invalid]click[/link]\n"
        "## Publication Recommendation\n\x1b[31mforged\u202e " + "x" * 1_000_000
    )

    def _tier3(*_args, **_kwargs):
        result = advisory_skip_result("Safe fallback reason", skill_name="simple")
        result.metadata["skip_reason"] = unsafe_reason
        return result

    monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _tier3)
    output_dir = tmp_path / "reports"

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            "--no-autopilot",
            str(FIXTURE.resolve()),
            "--no-llm",
            "--no-tier2",
            "--tier3",
            "--checks",
            "schema",
            "--report",
            "cli",
            "--output-dir",
            str(output_dir),
        ],
    )

    output = _plain_text(result.output)
    assert result.exit_code == 0, result.output
    assert "[/bold]" in output
    assert "[link=https://example.invalid]click[/link]" in output
    assert "\n## Publication Recommendation\n" not in output
    assert "\x1b" not in output and "\u202e" not in output
    assert "x" * 1024 not in output
    assert "…" in output
    assert len(output) < 100_000
    assert (output_dir / "BENCHMARK.md").is_file()


def test_validate_autopilot_generation_failure_degrades_to_skip(monkeypatch) -> None:
    # Regression: a dataset-generation failure must not abort validate after
    # Tier 1/2 already ran — Tier 3 skips with the reason and the reports and
    # verdict still render (Tier 3 is advisory).
    import click

    from skillevaluator import cli as cli_module
    from skillevaluator.models.result import ValidationResult

    def _boom(*_args, **_kwargs) -> str:
        raise click.ClickException("no provider key")

    def _tier3(*_args, **_kwargs) -> ValidationResult:
        result = ValidationResult(validator_name="AGENT_EVAL")
        result.add_warning("Skipped: evals.json missing")
        result.metadata.update({"execution_status": "skipped", "skip_reason": "evals.json missing"})
        return result

    monkeypatch.setattr(cli_module, "_ensure_autopilot_dataset", _boom)
    monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _tier3)

    runner = CliRunner()
    with runner.isolated_filesystem():
        result = runner.invoke(
            cli,
            ["validate", str(FIXTURE), "--no-llm", "--no-tier2", "--autopilot", "--checks", "schema", "-o", "out"],
        )

        out = _plain_text(result.output)
        assert result.exit_code == 0, result.output
        assert "autopilot dataset generation failed: no provider key" in out
        # The whole point: Tier 1 reports survive the Tier 3 dataset failure.
        assert any(Path("out").glob("*.html")), "reports must still be written"


def test_partial_agent_eval_result_carries_engine_errors(monkeypatch, tmp_path) -> None:
    # A run that produced usable per-agent results alongside recorded errors
    # is a ran-with-errors advisory, not a skip: errors carried (deduplicated),
    # passed False, never skipped.
    from skillevaluator import cli as cli_module
    from skillevaluator.evaluation import tier3_report
    from skillevaluator.models.result import ValidationResult
    from skillevaluator.tier3 import results_location

    run_dir = tmp_path / "results" / "20260709_000000"
    run_dir.mkdir(parents=True)

    def _normalized(*_args, **_kwargs) -> ValidationResult:
        result = ValidationResult(validator_name="AGENT_EVAL")
        result.add_success("agent_eval", "ok")
        return result

    monkeypatch.setattr(tier3_report, "agent_eval_result_from_run", _normalized)
    monkeypatch.setattr(results_location, "resolve_latest_results", lambda *_a, **_k: run_dir)

    engine_result = {
        "agents": {"codex": {}},
        "run_dir": str(run_dir),
        "execution_errors": ["agent codex crashed", "agent codex crashed"],
    }
    result = cli_module._partial_agent_eval_result(
        tmp_path,
        engine_result=engine_result,
        failure="agent codex crashed",
        results_dir=None,
        env_mode="docker",
    )
    assert result is not None
    assert result.passed is False
    assert result.errors == ["agent codex crashed"]


def test_partial_agent_eval_result_rejects_stale_results(monkeypatch, tmp_path) -> None:
    # The normalizer reads the skill's ``latest`` results; a mismatch with the
    # engine's run_dir means an OLDER run would be reported as fresh output —
    # degrade to the skip path instead.
    from skillevaluator import cli as cli_module
    from skillevaluator.tier3 import results_location

    run_dir = tmp_path / "results" / "fresh"
    run_dir.mkdir(parents=True)
    stale = tmp_path / "results" / "stale"
    stale.mkdir()
    monkeypatch.setattr(results_location, "resolve_latest_results", lambda *_a, **_k: stale)

    engine_result = {"agents": {"codex": {}}, "run_dir": str(run_dir), "execution_errors": ["boom"]}
    partial = cli_module._partial_agent_eval_result(
        tmp_path, engine_result=engine_result, failure="boom", results_dir=None, env_mode="docker"
    )
    assert partial is None


def test_run_agent_eval_partial_run_returns_ran_with_errors(monkeypatch, tmp_path) -> None:
    # End-to-end through _run_agent_eval_or_skip: an engine result with usable
    # agents data AND execution errors no longer collapses into a skip (which
    # discarded real results) — it returns the ran-with-errors advisory shape
    # the pipeline view renders red.
    from skillevaluator import cli as cli_module
    from skillevaluator.evaluation import tier3_report
    from skillevaluator.evaluation.service import EvaluationService
    from skillevaluator.models.result import ValidationResult
    from skillevaluator.tier3 import results_location

    run_dir = tmp_path / "results" / "20260709_010101"
    run_dir.mkdir(parents=True)
    engine = {
        "agents": {"codex": {"with_skill": {}}},
        "run_dir": str(run_dir),
        "execution_status": "failed",
        "execution_errors": ["1 of 2 agents crashed"],
        "error": ["1 of 2 agents crashed"],
    }

    def _normalized(*_args, **_kwargs) -> ValidationResult:
        result = ValidationResult(validator_name="AGENT_EVAL")
        result.add_success("agent_eval", "ok")
        return result

    monkeypatch.setattr(EvaluationService, "evaluate", lambda _self, _options, **_k: engine)
    monkeypatch.setattr(tier3_report, "agent_eval_result_from_run", _normalized)
    monkeypatch.setattr(results_location, "resolve_latest_results", lambda *_a, **_k: run_dir)

    result = cli_module._run_agent_eval_or_skip(
        tmp_path,
        agents="codex",
        env_mode="docker",
        skip_baseline=False,
        n_concurrent=None,
        max_agents=None,
        validate_source=False,
    )
    assert result.passed is False
    assert "1 of 2 agents crashed" in result.errors
    assert (result.metadata or {}).get("execution_status") != "skipped"


def test_validate_tier2_default_is_blocking_and_can_be_advisory(monkeypatch) -> None:
    from skillevaluator import cli as cli_module
    from skillevaluator.models.result import ValidationResult

    tier1 = ValidationResult(validator_name="SCHEMA")
    tier1.add_success("schema", "ok")

    def _tier2(*_args, **_kwargs) -> list[ValidationResult]:
        result = ValidationResult(validator_name="Context Deduplication")
        result.add_error("dedup failed")
        return [result]

    monkeypatch.setattr(cli_module, "run_validation", lambda *_args, **_kwargs: [tier1])
    monkeypatch.setattr(cli_module, "_run_dedup_or_skip", _tier2)

    runner = CliRunner()
    with runner.isolated_filesystem():
        blocking = runner.invoke(cli, ["validate", "--no-tier3", str(FIXTURE), "--checks", "schema"])
        advisory = runner.invoke(
            cli,
            ["validate", "--no-tier3", str(FIXTURE), "--checks", "schema", "--no-block-on-dedup"],
        )

    assert blocking.exit_code != 0
    assert "failed in Tier 2" in _plain_text(blocking.output)
    assert advisory.exit_code == 0, advisory.output


def test_validate_no_dedup_keeps_exit_success_but_publication_is_incomplete(tmp_path: Path) -> None:
    output_dir = tmp_path / "reports"

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            "--no-tier3",
            str(FIXTURE.resolve()),
            "--no-llm",
            "--no-dedup",
            "--checks",
            "schema",
            "--report",
            "json",
            "--output-dir",
            str(output_dir),
        ],
    )

    assert result.exit_code == 0, result.output
    benchmark = (output_dir / "BENCHMARK.md").read_text(encoding="utf-8")
    assert "Overall verdict: INCOMPLETE" in benchmark
    assert "## Publication Recommendation" not in benchmark
    assert "- Tier 2 evidence: required for publication" in benchmark
    assert "| Tier 2 | Semantic deduplication | **NOT RUN** |" in benchmark

    report = json.loads(next(output_dir.glob("skillevaluator-output-*.json")).read_text(encoding="utf-8"))
    assert report["overall_status"] == "passed"
    assert report["benchmark_policy"] == {
        "tier2_required": True,
        "tier3_required": True,
    }


def test_validate_tiers_selector_does_not_create_publication_waiver(monkeypatch, tmp_path: Path) -> None:
    from skillevaluator import cli as cli_module
    from skillevaluator.evaluation.tier3_report import advisory_skip_result
    from skillevaluator.publication_identity import stamp_publication_target

    def _optional_tier3_skip(*_args, **_kwargs):
        result = advisory_skip_result("Live evaluation intentionally omitted", skill_name="simple")
        result.metadata["agent_eval"]["benchmark_policy"] = {"tier3_required": False}
        stamp_publication_target([result], Path(_args[0]))
        return result

    monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _optional_tier3_skip)
    output_dir = tmp_path / "reports"

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            "--no-autopilot",
            str(FIXTURE.resolve()),
            "--no-llm",
            "--tiers",
            "1,3",
            "--checks",
            "schema",
            "--report",
            "json",
            "--output-dir",
            str(output_dir),
        ],
    )

    assert result.exit_code == 0, result.output
    benchmark = (output_dir / "BENCHMARK.md").read_text(encoding="utf-8")
    assert "Overall verdict: INCOMPLETE" in benchmark
    assert "## Publication Recommendation" not in benchmark
    assert "- Tier 2 evidence: required for publication" in benchmark
    assert "| Tier 2 | Semantic deduplication | **NOT RUN** |" in benchmark

    report = json.loads(next(output_dir.glob("skillevaluator-output-*.json")).read_text(encoding="utf-8"))
    assert report["benchmark_policy"] == {
        "tier2_required": True,
        "tier3_required": False,
    }


def test_validate_nonblocking_dedup_failure_does_not_certify_publication(monkeypatch, tmp_path: Path) -> None:
    from skillevaluator import cli as cli_module
    from skillevaluator.models.result import ValidationResult
    from skillevaluator.publication_evidence import stamp_publication_evidence
    from skillevaluator.publication_identity import stamp_publication_target

    def _failed_tier2(*_args, **_kwargs) -> list[ValidationResult]:
        result = ValidationResult(validator_name="Similarity Check")
        result.add_error("Similarity scan failed")
        # Isolate the Tier 2 publication contract from the separately tested
        # default-required Tier 3 policy.
        result.metadata["benchmark_policy"] = {"tier3_required": False}
        stamp_publication_evidence([result], tier=2, check_id="similarity")
        stamp_publication_target([result], Path(_args[0]))
        return [result]

    monkeypatch.setattr(cli_module, "_run_dedup_or_skip", _failed_tier2)
    output_dir = tmp_path / "reports"

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            "--no-tier3",
            str(FIXTURE.resolve()),
            "--no-llm",
            "--checks",
            "schema",
            "--no-block-on-dedup",
            "--report",
            "json",
            "--output-dir",
            str(output_dir),
        ],
    )

    assert result.exit_code == 0, result.output
    benchmark = (output_dir / "BENCHMARK.md").read_text(encoding="utf-8")
    assert "Overall verdict: FAIL" in benchmark
    assert "## Publication Recommendation" not in benchmark
    assert "- Tier 2 evidence: required for publication" in benchmark
    assert "| Tier 2 | Semantic deduplication | **FAILED** |" in benchmark

    report = json.loads(next(output_dir.glob("skillevaluator-output-*.json")).read_text(encoding="utf-8"))
    assert report["overall_status"] == "passed"
    assert report["gating"]["tiers"]["2"]["blocking"] is False
    assert report["benchmark_policy"] == {
        "tier2_required": True,
        "tier3_required": False,
    }


def test_validate_missing_tier3_source_respects_blocking_flag(monkeypatch, tmp_path: Path) -> None:
    from skillevaluator import cli as cli_module
    from skillevaluator.evaluation import EvaluationService
    from skillevaluator.models.result import ValidationResult

    skill = tmp_path / "source-skill"
    skill.mkdir()
    (skill / "SKILL.md").write_text("---\nname: source-skill\ndescription: test\n---\n")
    tier1 = ValidationResult(validator_name="SCHEMA")
    tier1.add_success("schema", "ok")
    monkeypatch.setattr(cli_module, "run_validation", lambda *_args, **_kwargs: [tier1])
    monkeypatch.setattr(
        EvaluationService,
        "evaluate",
        lambda *_args, **_kwargs: pytest.fail("source preflight must run before live evaluation"),
    )

    runner = CliRunner()
    advisory = runner.invoke(
        cli,
        [
            "validate",
            "--no-autopilot",
            str(skill),
            "--no-tier2",
            "--tier3",
            "--verbose",
            "--report",
            "json",
            "--output-dir",
            str(tmp_path / "advisory"),
        ],
    )
    blocking = runner.invoke(
        cli,
        [
            "validate",
            "--no-autopilot",
            str(skill),
            "--no-tier2",
            "--tier3",
            "--block-on-agent-eval",
            "--verbose",
            "--report",
            "json",
            "--output-dir",
            str(tmp_path / "blocking"),
        ],
    )

    assert advisory.exit_code == 0, advisory.output
    assert blocking.exit_code != 0

    advisory_report = json.loads(next((tmp_path / "advisory").glob("*.json")).read_text())
    blocking_report = json.loads(next((tmp_path / "blocking").glob("*.json")).read_text())
    assert advisory_report["tier3_applicability"]["applicability"] == "not_required"
    assert advisory_report["tier3"]["verdict"] == "neutral"
    assert advisory_report["gating"]["tiers"]["3"]["blocking"] is False
    assert advisory_report["overall_status"] == "passed"
    assert blocking_report["tier3_applicability"]["applicability"] == "required"
    assert blocking_report["tier3"]["verdict"] == "fail"
    assert blocking_report["gating"]["tiers"]["3"]["blocking"] is True
    assert blocking_report["overall_status"] == "failed"


@pytest.mark.parametrize(
    ("verdict", "score", "expected_exit_code"),
    [("pass", 0.9, 0), ("neutral", 0.45, 1), ("fail", 0.1, 1)],
)
def test_validate_block_on_agent_eval_gates_complete_tier3_verdict(
    monkeypatch,
    tmp_path: Path,
    verdict: str,
    score: float,
    expected_exit_code: int,
) -> None:
    from skillevaluator import cli as cli_module
    from skillevaluator.models.result import ValidationResult

    def _tier3(*_args, **_kwargs) -> ValidationResult:
        result = ValidationResult(validator_name="AGENT_EVAL")
        result.add_success("agent_eval", "Live evaluation completed")
        result.metadata["agent_eval"] = {
            "skill_name": "simple",
            "verdict": verdict,
            "execution_status": "succeeded",
            "evaluated_at": "2026-08-25T12:00:00+00:00",
            "evaluator_version": "0.9.0",
            "expected_attempts": 1,
            "scored_attempts": 1,
            "dataset_summary": {"total_tasks": 1},
            "dataset_digest": "sha256:" + "a" * 64,
            "dataset_digest_algorithm": "skill-evaluator-dataset-snapshot/1",
            "attempt_policy": {"max_attempts": 1, "pass_threshold": 0.5, "stop_on_pass": False},
            "summary": {
                "skill_name": "simple",
                "verdict": verdict,
                "execution_status": "succeeded",
                "environment": "docker",
                "expected_attempts": 1,
                "scored_attempts": 1,
            },
            "agents": {
                "codex": {
                    "model": "gpt-codex",
                    "execution_status": "succeeded",
                    "expected_attempts": 1,
                    "scored_attempts": 1,
                    "conditions": {
                        "with_skill": {
                            "execution_status": "succeeded",
                            "execution_errors": [],
                            "expected_attempts": 1,
                            "scored_attempts": 1,
                        },
                        "without_skill": {
                            "execution_status": "skipped",
                            "execution_errors": [],
                            "expected_attempts": 0,
                            "scored_attempts": 0,
                        },
                    },
                    "with_skill": score,
                    "dimensions": [
                        {"id": dimension, "with_skill": score}
                        for dimension in (
                            "security",
                            "correctness",
                            "discoverability",
                            "effectiveness",
                            "efficiency",
                        )
                    ],
                }
            },
        }
        return result

    monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _tier3)
    output_dir = tmp_path / verdict
    result = CliRunner().invoke(
        cli,
        [
            "validate",
            "--no-autopilot",
            str(FIXTURE),
            "--no-llm",
            "--no-tier2",
            "--tier3",
            "--block-on-agent-eval",
            "--checks",
            "schema",
            "--report",
            "json",
            "--output-dir",
            str(output_dir),
        ],
    )

    assert result.exit_code == expected_exit_code, result.output
    report = json.loads(next(output_dir.glob("*.json")).read_text(encoding="utf-8"))
    assert report["overall_passed"] is (expected_exit_code == 0)
    assert report["gating"]["tiers"]["3"]["blocking"] is True


def test_validate_quiet_honors_explicit_report_formats() -> None:
    # An explicit -r is a contract: "-r cli" renders the full Rich report
    # below the pipeline view (and writes no unrequested files); "-r json"
    # writes exactly json. Only the DEFAULT quiet run swaps in html+json.
    runner = CliRunner()
    with runner.isolated_filesystem():
        result = runner.invoke(
            cli,
            [
                "validate",
                "--no-tier3",
                str(FIXTURE),
                "--no-llm",
                "--no-dedup",
                "--checks",
                "schema",
                "-r",
                "cli",
                "-o",
                "out",
            ],
        )
        assert result.exit_code == 0, result.output
        assert "Validation Results" in _plain_text(result.output)
        assert not list(Path("out").glob("*.html"))
        assert not list(Path("out").glob("*.json"))

    with runner.isolated_filesystem():
        result = runner.invoke(
            cli,
            [
                "validate",
                "--no-tier3",
                str(FIXTURE),
                "--no-llm",
                "--no-dedup",
                "--checks",
                "schema",
                "-r",
                "json",
                "-o",
                "out",
            ],
        )
        assert result.exit_code == 0, result.output
        assert list(Path("out").glob("*.json"))
        assert not list(Path("out").glob("*.html"))


def test_validate_non_skill_cli_only_does_not_reserve_output_storage(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    from skillevaluator import cli as cli_module

    rules = tmp_path / "rules"
    rules.mkdir()
    sibling = rules.with_name("rules-reports")
    sibling.mkdir()
    authored = sibling / "owner.txt"
    authored.write_text("author-owned\n", encoding="utf-8")
    monkeypatch.chdir(rules)
    monkeypatch.setattr(cli_module, "run_validation", lambda *_args, **_kwargs: [])
    monkeypatch.setattr(cli_module, "emit_reports", lambda *_args, **_kwargs: True)

    result = CliRunner().invoke(
        cli,
        [
            "validate",
            ".",
            "--type",
            "rules",
            "--no-llm",
            "--no-tier2",
            "--checks",
            "schema",
            "--report",
            "cli",
        ],
    )

    assert result.exit_code == 0, result.output
    assert authored.read_text(encoding="utf-8") == "author-owned\n"
    assert list(sibling.iterdir()) == [authored]
    assert not (rules / "reports").exists()


def test_validate_catalog_survives_failing_skills(monkeypatch) -> None:
    # Regression: one failing skill must not abort the catalog — every skill
    # runs and the scoreboard prints.
    from skillevaluator import cli as cli_module
    from skillevaluator.models.result import Finding, Severity, ValidationResult

    def _failing_tier1(*_args, **_kwargs) -> list[ValidationResult]:
        failing = ValidationResult(validator_name="SCHEMA")
        failing.add_structured_finding(
            Finding(
                category="SCHEMA",
                severity=Severity.HIGH,
                check_name="x",
                message="boom",
                file_path="SKILL.md",
            ),
            is_error=True,
        )
        return [failing]

    monkeypatch.setattr(cli_module, "run_validation", _failing_tier1)

    runner = CliRunner()
    with runner.isolated_filesystem():
        catalog = Path("catalog")
        for name in ("simple", "simple2"):
            shutil.copytree(FIXTURE, catalog / name)
        result = runner.invoke(
            cli,
            [
                "validate",
                "--no-tier3",
                str(catalog.resolve()),
                "--no-llm",
                "--no-dedup",
                "--checks",
                "schema",
                "-o",
                "out",
            ],
        )

        out = _plain_text(result.output)
        assert "skill 1/2" in out and "skill 2/2" in out
        assert "Catalog Result" in out
        assert "0/2 skills passed" in out
        assert result.exit_code != 0
        summary = json.loads(Path("out/catalog-summary.json").read_text(encoding="utf-8"))
        assert summary["failed"] == 2
        assert summary["overall_passed"] is False
        assert all(not skill["passed"] for skill in summary["skills"])


def test_render_evaluation_result_invokes_findings_report(monkeypatch) -> None:
    # Regression: the per-evaluator findings panel (the feedback surface) must
    # be invoked after the score tables — the renderer existed but had no
    # caller. Its content is loaded from reward files in the run dir, so the
    # wiring (arguments included) is what this test pins.
    import io

    from rich.console import Console

    from skillevaluator.tier3.harbor import report as harbor_report
    from skillevaluator.tier3.result_display import render_evaluation_result

    calls: list[tuple] = []
    monkeypatch.setattr(harbor_report, "display_findings_report", lambda *args, **_kwargs: calls.append(args))

    result = {
        "skill_name": "simple",
        "run_dir": "/tmp/run",
        "execution_status": "succeeded",
        "agents": {
            "codex": {
                "execution_status": "succeeded",
                "num_trials_with": 1,
                "with_skill": {"security": 1.0},
                "without_skill": {"security": 1.0},
                "lift": {"overall": {"with_skill": 1.0, "without_skill": 0.5, "delta": 0.5}},
            }
        },
    }
    render_evaluation_result(result, console=Console(file=io.StringIO(), width=120))
    assert calls, "findings report must be invoked after the score tables"
    _harbor_result, skill_name, agent_list, results_dir = calls[0]
    assert skill_name == "simple"
    assert agent_list == ["codex"]
    assert str(results_dir) == "/tmp/run"


def test_summarize_tier1_lists_each_serious_finding() -> None:
    from skillevaluator.models.result import Finding, Severity, ValidationResult
    from skillevaluator.reporting.console_ui import summarize_tier1

    failing = ValidationResult(validator_name="Security Scan", passed=False)
    for message, severity, suggestion in (
        ("Tool Misuse: rm -rf ./build", Severity.HIGH, "Reject dangerous parameters."),
        ("YARA Match: rm -rf ./; without asking", Severity.HIGH, "Reject dangerous parameters."),
        ("Hook bypass: git commit --no-verify", Severity.CRITICAL, "Let the hooks run."),
        ("Unpinned npx package", Severity.HIGH, "Pin the package version."),
        ("Excessive Agency: without asking", Severity.MEDIUM, "Ask before acting."),
    ):
        failing.add_finding(
            Finding(
                category="SECURITY",
                severity=severity,
                check_name="skillspector",
                message=message,
                file_path="SKILL.md",
                suggestion=suggestion,
            )
        )

    _ok, rows = summarize_tier1([failing])
    rendered = ["".join(chunk for chunk, _style in row.segments) for row in rows]
    numbered = [row for row in rows if row.glyph in {"1", "2", "3"}]
    assert [row.segments[0][0] for row in numbered] == [
        "Tool Misuse: rm -rf ./build",
        "YARA Match: rm -rf ./; without asking",
        "Hook bypass: git commit --no-verify",
    ]
    assert sum("Reject dangerous parameters." in line for line in rendered) == 1
    assert any("+1 more in detailed reports" in line for line in rendered)
    assert not any("Excessive Agency" in line for line in rendered)


def test_summarize_tier2_lists_duplicate_details() -> None:
    # "duplicates found" alone is useless — the section must say WHAT
    # duplicated, up to three findings plus an overflow pointer.
    from skillevaluator.models.result import Finding, Severity, ValidationResult
    from skillevaluator.reporting.console_ui import summarize_tier2

    failing = ValidationResult(validator_name="Context Deduplication", passed=False)
    for index in range(5):
        failing.add_finding(
            Finding(
                category="CONTENT_DEDUP",
                severity=Severity.HIGH,
                check_name="context_dedup",
                message=f"Sections 'Setup {index}' and 'Install {index}' repeat the same guidance",
                file_path="SKILL.md",
            )
        )

    ran, ok, rows, _skip = summarize_tier2([failing])
    assert ran and not ok
    rendered = ["".join(chunk for chunk, _style in row.segments) for row in rows]
    assert any("duplicates found" in line for line in rendered)
    assert any("Sections 'Setup 0'" in line for line in rendered)
    duplicate_rows = [row for row in rows if row.glyph in {"1", "2", "3"}]
    assert len(duplicate_rows) == 3
    assert any(row.label == "what to fix" for row in rows)
    assert any("2 more" in line for line in rendered)


def test_summarize_tier2_does_not_blame_an_advisory_llm_refusal() -> None:
    # A refusal is advisory: when another cluster's analysis failed, the
    # summary must name that failure, not list the refusal as a duplicate.
    from skillevaluator.models.result import Finding, Severity, ValidationResult
    from skillevaluator.reporting.console_ui import summarize_tier2

    def refusal(severity: Severity) -> Finding:
        return Finding(
            category="CONTENT_DEDUP",
            severity=severity,
            check_name="llm_refused",
            message="The LLM declined to classify overlapping content within SKILL.md",
            file_path="SKILL.md",
        )

    incomplete = ValidationResult(validator_name="Context Deduplication")
    incomplete.add_finding(refusal(Severity.MEDIUM))
    incomplete.mark_scan_incomplete("deduplication-llm")
    incomplete.add_error("LLM analysis did not complete for 1 of 2 content clusters")

    ran, ok, rows, _skip = summarize_tier2([incomplete])
    assert ran and not ok
    rendered = ["".join(chunk for chunk, _style in row.segments) for row in rows]
    assert any("scan failed" in line for line in rendered)
    assert not any("duplicates found" in line for line in rendered)
    assert [row.label for row in rows if row.glyph == "✗"] == ["error"]
    assert any("1 of 2 content clusters" in line for line in rendered)
    assert not any("declined" in line for line in rendered)

    # A policy that raises the refusal to a blocking severity reports it as a scan failure.
    blocking = ValidationResult(validator_name="Context Deduplication")
    blocking.add_finding(refusal(Severity.HIGH))

    _ran, ok, rows, _skip = summarize_tier2([blocking])
    rendered = ["".join(chunk for chunk, _style in row.segments) for row in rows]
    assert not ok
    assert any("scan failed" in line for line in rendered)
    assert [row.label for row in rows if row.glyph == "✗"] == ["error"]

    advisory = ValidationResult(validator_name="Context Deduplication")
    advisory.add_finding(refusal(Severity.MEDIUM))
    _ran, ok, _rows, _skip = summarize_tier2([advisory])
    assert ok


def test_rerun_hint_preserves_run_shaping_flags(monkeypatch) -> None:
    # The FAIL panel's rerun line must echo the user's actual invocation:
    # dropping --min-score (etc.) means following the hint can silently
    # "pass" the failure away.
    from skillevaluator import cli as cli_module

    monkeypatch.setattr("sys.argv", ["/x/bin/skillevaluator", "validate", "./skill", "--min-score", "95"])
    assert cli_module._rerun_hint(Path("./skill"), agent_eval=False) == (
        "skillevaluator validate ./skill --min-score 95"
    )

    # Outside a CLI launch (tests, API embedding) fall back to the bare form.
    monkeypatch.setattr("sys.argv", ["pytest"])
    assert cli_module._rerun_hint(Path("./skill"), agent_eval=True).endswith("--tier3")


def test_validate_tiers_selector_is_authoritative_over_full(monkeypatch) -> None:
    # --full turns Tier 3 (and autopilot) on, but an explicit --tiers 1,2 must
    # turn both back off — the selector wins in both directions.
    from skillevaluator import cli as cli_module
    from skillevaluator.models.result import ValidationResult

    calls: dict[str, bool] = {}

    def _tier2(*_args, **_kwargs) -> list[ValidationResult]:
        result = ValidationResult(validator_name="Tier 2 Deduplication")
        result.add_success("dedup", "ok")
        return [result]

    def _tier3(*_args, **_kwargs) -> ValidationResult:
        calls["tier3"] = True
        result = ValidationResult(validator_name="AGENT_EVAL")
        result.add_success("agent_eval", "ok")
        return result

    def _generate(*_args, **_kwargs) -> str:
        calls["autopilot"] = True
        return "generated"

    monkeypatch.setattr(cli_module, "_run_dedup_or_skip", _tier2)
    monkeypatch.setattr(cli_module, "_run_agent_eval_or_skip", _tier3)
    monkeypatch.setattr(cli_module, "_ensure_autopilot_dataset", _generate)

    runner = CliRunner()
    with runner.isolated_filesystem():
        result = runner.invoke(
            cli, ["validate", str(FIXTURE), "--no-llm", "--full", "--tiers", "1,2", "--checks", "schema"]
        )

    assert result.exit_code == 0, result.output
    assert calls == {}, f"Tier 3/autopilot must not run under --tiers 1,2: {calls}"


def test_validate_catalog_reports_unexpected_errors(monkeypatch) -> None:
    # A crash inside one skill's pipeline must not abort the catalog silently:
    # the loop finishes, the scoreboard prints, and the reason is named.
    from skillevaluator import cli as cli_module

    def _boom(*_args, **_kwargs):
        raise RuntimeError("validator exploded")

    monkeypatch.setattr(cli_module, "run_validation", _boom)

    runner = CliRunner()
    with runner.isolated_filesystem():
        catalog = Path("catalog")
        for name in ("simple", "simple2"):
            shutil.copytree(FIXTURE, catalog / name)
        result = runner.invoke(
            cli,
            [
                "validate",
                "--no-tier3",
                str(catalog.resolve()),
                "--no-llm",
                "--no-dedup",
                "--checks",
                "schema",
                "-o",
                "out",
            ],
        )

        out = _plain_text(result.output)
        assert "Catalog Result" in out
        assert "unexpected error: validator exploded" in out
        assert result.exit_code != 0
        summary = json.loads(Path("out/catalog-summary.json").read_text(encoding="utf-8"))
        assert summary["failed"] == 2
        assert summary["skills"][0]["reason"] == "unexpected error: validator exploded"


def test_summarize_tier2_empty_results_name_a_reason() -> None:
    from skillevaluator.reporting.console_ui import summarize_tier2

    ran, ok, _rows, skip = summarize_tier2([])
    assert not ran and ok
    assert skip, "an empty Tier 2 result set must still explain the skip"


_PROVIDER_SKIP_MESSAGE = (
    "Tier 2 skipped: embedding setup is required.\n\n"
    "No provider is configured.\n"
    "For example, set:\n"
    "  export SKILL_EVAL_EMBEDDING_PROVIDER=openai\n"
    "  export OPENAI_API_KEY='your-api-key'\n\n"
    "To skip Tier 2, pass --no-dedup."
)


def _skipped_tier2(message: str):
    from skillevaluator.models.result import ValidationResult

    result = ValidationResult(validator_name="Tier 2 Deduplication")
    result.add_warning(message)
    result.metadata["skipped"] = True
    return result


def test_compact_skip_reason_keeps_setup_instructions() -> None:
    from skillevaluator.reporting.console_ui import summarize_tier2

    ran, ok, _rows, reason = summarize_tier2([_skipped_tier2(_PROVIDER_SKIP_MESSAGE)])

    assert not ran and ok
    assert reason.splitlines() == [
        "Tier 2 skipped: embedding setup is required.",
        "No provider is configured.",
        "For example, set:",
        "export SKILL_EVAL_EMBEDDING_PROVIDER=openai",
        "export OPENAI_API_KEY='your-api-key'",
        "To skip Tier 2, pass --no-dedup.",
    ]


def test_compact_skip_reason_stays_bounded_and_inert() -> None:
    import unicodedata

    from skillevaluator.reporting.console_ui import summarize_tier2

    hostile = "\n".join(
        [
            "\x1b]8;;https://example.invalid\x07click\x1b]8;;\x07 \x1b[31mred\u202e " + "x" * 500,
            *(f"line {index}" for index in range(40)),
        ]
    )

    _ran, _ok, _rows, reason = summarize_tier2([_skipped_tier2(hostile)])
    lines = reason.splitlines()

    assert len(lines) == 12
    assert all(len(line) <= 110 for line in lines)
    assert lines[0].startswith("click red ")
    assert lines[-1].endswith("\u2026")
    assert not any(unicodedata.category(character).startswith("C") for character in reason.replace("\n", ""))


def test_view_renders_multi_line_skip_reason_on_continuation_rows(capsys) -> None:
    from skillevaluator.reporting.console_ui import ValidateView, summarize_tier2

    _ran, _ok, _rows, reason = summarize_tier2([_skipped_tier2(_PROVIDER_SKIP_MESSAGE)])
    view = ValidateView(
        skill="skill: demo",
        tiers=[(1, "Static & Security", "static & security"), (2, "Deduplication", "deduplication")],
    )

    view.start()
    view.tier_start(0)
    view.tier_done(0, failed=False, rows=[])
    view.tier_skip(1, reason)
    view.stop()

    output = _plain_text(capsys.readouterr().out)
    assert "skipped     Tier 2 skipped: embedding setup is required." in output
    assert "export OPENAI_API_KEY='your-api-key'" in output
    assert "To skip Tier 2, pass --no-dedup." in output


def test_tier3_evaluate_visible_copy_owns_its_params() -> None:
    # The visible tier3 registration is a copy of the hidden top-level
    # command; sharing the mutable params list would let registration on one
    # silently mutate the other.
    from skillevaluator import cli as cli_module

    assert cli_module._tier3_evaluate_visible.params is not cli_module.evaluate.params
    assert [p.name for p in cli_module._tier3_evaluate_visible.params] == [p.name for p in cli_module.evaluate.params]


def test_compact_feedback_panel_filters_messages_rendered_in_detailed_panel(monkeypatch) -> None:
    # Regression (live duplicate-feedback bug): the detailed per-evaluator
    # findings report and the compact payload panel both rendered the same
    # suggestions after the score tables. The compact panel now filters items
    # that the detailed report says it rendered.
    import io

    from rich.console import Console

    from skillevaluator.tier3.harbor import report as harbor_report
    from skillevaluator.tier3.result_display import render_evaluation_result

    result = {
        "skill_name": "simple",
        "run_dir": "/tmp/run",
        "execution_status": "succeeded",
        "agents": {
            "codex": {
                "execution_status": "succeeded",
                "num_trials_with": 1,
                "with_skill": {"security": 1.0},
                "without_skill": {"security": 1.0},
                "lift": {"overall": {"with_skill": 1.0, "without_skill": 0.5, "delta": 0.5}},
            }
        },
        "tier3_feedback": {"recommendations": [{"suggestion": "Add more eval cases"}]},
    }

    monkeypatch.setattr(harbor_report, "display_findings_report", lambda *_a, **_k: {"Add more eval cases"})
    stream = io.StringIO()
    render_evaluation_result(result, console=Console(file=stream, width=200))
    assert "Feedback & Suggestions" not in stream.getvalue()

    monkeypatch.setattr(harbor_report, "display_findings_report", lambda *_a, **_k: set())
    stream = io.StringIO()
    render_evaluation_result(result, console=Console(file=stream, width=200))
    assert "Feedback & Suggestions" in stream.getvalue()
    assert "Add more eval cases" in stream.getvalue()


def test_display_findings_report_reports_whether_it_rendered(tmp_path) -> None:
    # The dedup gating relies on the return value: no reward files on disk
    # means nothing rendered and the caller must fall back.
    from skillevaluator.tier3.harbor.report import display_findings_report

    rendered = display_findings_report(
        {"agents": {"codex": {}}},
        "simple",
        ["codex"],
        tmp_path,
    )
    assert rendered == set()


def test_summarize_tier2_labels_scan_errors_as_errors_not_duplicates() -> None:
    """A failed scan with no findings must not claim duplicates were found."""
    from skillevaluator.models.result import ValidationResult
    from skillevaluator.reporting.console_ui import summarize_tier2

    crashed = ValidationResult(validator_name="Tier 2 Deduplication")
    crashed.add_error("Skill tree contains more than 4096 paths.")

    ran, ok, rows, _skip = summarize_tier2([crashed])

    assert ran and not ok
    rendered = [(row.label, "".join(chunk for chunk, _style in row.segments)) for row in rows]
    labels = [label for label, _text in rendered]
    texts = " | ".join(text for _label, text in rendered)
    assert "scan failed" in texts
    assert "duplicates found" not in texts
    assert "error" in labels and "duplicate" not in labels
    assert "more than 4096 paths" in texts


@pytest.mark.parametrize("check_name", ["path_count_limit", "chunk_count_limit", "embedding_error"])
def test_summarize_tier2_labels_structured_scan_failures_as_errors(check_name: str) -> None:
    from skillevaluator.models.result import Finding, Severity, ValidationResult
    from skillevaluator.reporting.console_ui import summarize_tier2

    failed_scan = ValidationResult(validator_name="Tier 2 Deduplication")
    failed_scan.add_finding(
        Finding(
            category="CONTENT_DEDUP",
            severity=Severity.CRITICAL,
            check_name=check_name,
            message="Tier 2 stopped before duplicate analysis completed.",
            file_path="SKILL.md",
        )
    )

    ran, ok, rows, _skip = summarize_tier2([failed_scan])

    assert ran and not ok
    rendered = [(row.label, "".join(chunk for chunk, _style in row.segments)) for row in rows]
    labels = [label for label, _text in rendered]
    texts = " | ".join(text for _label, text in rendered)
    assert "scan failed" in texts
    assert "duplicates found" not in texts
    assert "error" in labels and "duplicate" not in labels