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.

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

"""
Single source of truth for the evals/ directory structure.

Every file and directory that the SkillEvaluator toolchain recognises inside a skill's
``evals/`` directory is declared here.  This module is consumed by:

  - ``skillevaluator info evals``  — prints the annotated tree for discovery
  - ``skillevaluator validate``    — checks a skill directory against the spec
  - Runtime code (adapter, runner)   — can import constants instead of hard-coding paths
"""

from __future__ import annotations

import functools
import logging
import os
import re
import unicodedata
from collections.abc import Iterator, Mapping, Sequence
from dataclasses import dataclass, field
from enum import Enum
from itertools import chain
from pathlib import Path
from typing import Any

from skillevaluator.constants import EXECUTABLE_SKILL_DIRS
from skillevaluator.tier3.case_ids import validate_case_ids
from skillevaluator.utils.redaction import redact_printable_text

logger = logging.getLogger(__name__)


# ---------------------------------------------------------------------------
# Data model
# ---------------------------------------------------------------------------


class Requirement(Enum):
    REQUIRED = "REQUIRED"
    OPTIONAL = "optional"


class Scope(Enum):
    HARBOR = "Harbor"
    OUTPUT = "output"  # generated by evaluation runs, not authored


@dataclass
class EntrySpec:
    """One file or directory in the evals/ tree."""

    rel_path: str
    kind: str  # "file" or "dir"
    requirement: Requirement
    scope: Scope
    description: str
    formats: list[str] = field(default_factory=list)
    validation_notes: list[str] = field(default_factory=list)
    example: str = ""


# ---------------------------------------------------------------------------
# The spec — every recognised path inside evals/
# ---------------------------------------------------------------------------

DATASET_EXTENSIONS = (".json", ".jsonl", ".yaml", ".yml")

EVALS_SPEC: list[EntrySpec] = [
    # -- Dataset --
    EntrySpec(
        rel_path="evals/evals.json",
        kind="file",
        requirement=Requirement.REQUIRED,
        scope=Scope.HARBOR,
        description="Golden evaluation dataset. Without this, agent evaluation cannot run.",
        formats=[".json", ".jsonl", ".yaml", ".yml"],
        validation_notes=[
            "Preferred format follows agentskills.io: a top-level object with skill_name and evals[].",
            "agentskills.io entries must have at least: id, prompt, expected_output.",
            "Legacy flat arrays are still accepted for now but emit a CI deprecation warning.",
            "Legacy entries must have at least: id, question.",
            "Legacy recommended fields: expected_skill, ground_truth, expected_behavior.",
            "Use acceptable_skills (or legacy alias acceptable_alternates) when a closely related skill should receive partial routing credit.",
            "Write prompts as a user would ask, and expected output and assertions about the task outcome. "
            "The no-skill baseline is graded on the same prompt, expected output and assertions without the "
            "skill installed, so a prompt that points at the skill's files, or an assertion that the agent read "
            "SKILL.md or used the skill, cannot be met by the baseline. Whether the skill was used is scored "
            "separately (skill_execution); `skillevaluator tier3 validate` warns about such entries.",
        ],
        example="""\
{
  "skill_name": "my-skill",
  "evals": [
    {
      "id": "my-skill-001",
      "prompt": "Summarize the failing checks in build.log",
      "expected_output": "The three failing checks, each with its error line",
      "assertions": [
        "Lists every failing check from build.log",
        "Quotes the error line for each failing check"
      ]
    }
  ]
}""",
    ),
    EntrySpec(
        rel_path="evals/config.yml",
        kind="file",
        requirement=Requirement.OPTIONAL,
        scope=Scope.HARBOR,
        description="SkillEvaluator Harbor execution policy: attempts, pass threshold, Dockerfile/base-image modes, runtime env, pre-agent setup, optional agent runtime preflight, agent models, workspace staging, and grading mode.",
        formats=[".yml", ".yaml"],
        validation_notes=[
            "schema_version must be 1.",
            "Supported harbor keys include task_source (auto|evals_json|native_harbor), custom_dockerfile_mode, base_image_mode, n_attempts, pass_threshold, stop_on_pass, n_concurrent, max_agents, max_cases, timeout_multiplier, agent_runtime_preflight, tolerate_baseline_timeouts, runtime_env, pre_agent_setup, and agents.<name>.model.",
            "passthrough_env and setup_commands are accepted as compatibility aliases for runtime_env and pre_agent_setup.",
            "Supported skill_workspace keys: mode (isolated|group), include.",
            "Supported grading keys: mode (default|default_plus_custom|custom_only).",
            "pre_agent_setup/setup_commands is allowed only with --skip-baseline; paired runs reject skill-owned setup code.",
            "CLI flags override config values.",
        ],
        example="""\
schema_version: 1

harbor:
  task_source: auto
  custom_dockerfile_mode: preserve
  base_image_mode: reuse
  n_attempts: 3
  pass_threshold: 0.50
  stop_on_pass: true
  agent_runtime_preflight: false
  runtime_env:
    - SERVICE_API_TOKEN
  pre_agent_setup:
    - service-cli auth login --token "$SERVICE_API_TOKEN"
    - service-cli whoami >/dev/null

  agents:
    claude-code:
      model: aws/anthropic/bedrock-claude-opus-4-8

skill_workspace:
  mode: isolated
  include: []

grading:
  mode: default
""",
    ),
    EntrySpec(
        rel_path="evals/config.yaml",
        kind="file",
        requirement=Requirement.OPTIONAL,
        scope=Scope.HARBOR,
        description="YAML alternative for evals/config.yml.",
        formats=[".yaml"],
        validation_notes=["Same schema as evals/config.yml."],
    ),
    EntrySpec(
        rel_path="evals/harbor/",
        kind="dir",
        requirement=Requirement.OPTIONAL,
        scope=Scope.HARBOR,
        description="User-owned native Harbor task source for BYOT/custom grader workflows.",
        validation_notes=[
            "SkillEvaluator never mutates this source in place; it stages with-skill/baseline copies under evals/results/.",
            "Use skillevaluator validate --harbor-contract for task/reward-contract checks.",
            "When grading.mode is default or default_plus_custom, case IDs should match evals/evals.json.",
        ],
    ),
    EntrySpec(
        rel_path="evals/grader.py",
        kind="file",
        requirement=Requirement.OPTIONAL,
        scope=Scope.HARBOR,
        description="Top-level BYOG Python custom grader staged into generated Harbor tasks.",
        formats=[".py"],
        validation_notes=[
            "Run with grading.mode default_plus_custom or custom_only.",
            "Read /logs/agent/trajectory.json and /tests/entry.json as needed.",
            "Write /logs/verifier/reward.json and preferably /logs/verifier/reward.txt.",
        ],
    ),
    EntrySpec(
        rel_path="evals/grader.sh",
        kind="file",
        requirement=Requirement.OPTIONAL,
        scope=Scope.HARBOR,
        description="Top-level BYOG shell custom grader staged into generated Harbor tasks.",
        formats=[".sh"],
        validation_notes=[
            "Run with grading.mode default_plus_custom or custom_only.",
            "Read /logs/agent/trajectory.json and /tests/entry.json as needed.",
            "Write /logs/verifier/reward.json and preferably /logs/verifier/reward.txt.",
        ],
    ),
    # -- Developer guidance --
    EntrySpec(
        rel_path="evals/EVAL.md",
        kind="file",
        requirement=Requirement.OPTIONAL,
        scope=Scope.HARBOR,
        description="Developer eval guidance for dataset generation. "
        "Parsed by create-eval-dataset for questions, expected behaviors, and notes.",
        formats=[".md"],
        validation_notes=["Markdown file. Freeform, but headings like '## Questions' help the generator."],
    ),
    # -- Input files --
    EntrySpec(
        rel_path="evals/files/",
        kind="dir",
        requirement=Requirement.OPTIONAL,
        scope=Scope.HARBOR,
        description="Shared pool of test data, configs, and sample documents that eval entries can stage "
        "into /workspace/input/ inside containers.",
        validation_notes=[
            "Any file types. An entry with files stages only its declared paths; "
            "omitting files copies this entire directory for backward compatibility."
        ],
    ),
    # -- Custom environment --
    EntrySpec(
        rel_path="evals/environment/",
        kind="dir",
        requirement=Requirement.OPTIONAL,
        scope=Scope.HARBOR,
        description="Custom Harbor container environment directory.",
        validation_notes=["Only used in Harbor mode."],
    ),
    EntrySpec(
        rel_path="evals/environment/Dockerfile",
        kind="file",
        requirement=Requirement.OPTIONAL,
        scope=Scope.HARBOR,
        description="Custom Dockerfile. Use when the default python:3.12-slim is not enough "
        "(e.g., system packages, specific runtimes).",
        formats=["Dockerfile"],
        validation_notes=[
            "Must be <= 20KB.",
            "First non-comment line must start with FROM.",
            "If absent, auto-generated from scripts/requirements.txt + scripts/apt-packages.txt.",
            "Build context is environment/ — COPY paths must be relative to it "
            "(e.g. COPY skills/ not COPY environment/skills/).",
        ],
    ),
    EntrySpec(
        rel_path="evals/environment/docker-compose.yaml",
        kind="file",
        requirement=Requirement.OPTIONAL,
        scope=Scope.HARBOR,
        description="Docker Compose for sidecar services (databases, APIs, mock servers) "
        "launched alongside the agent container.",
        formats=[".yaml", ".yml"],
        validation_notes=["Also accepted as docker-compose.yml."],
    ),
    EntrySpec(
        rel_path="evals/environment/mcp_servers.toml",
        kind="file",
        requirement=Requirement.OPTIONAL,
        scope=Scope.HARBOR,
        description="MCP server declarations injected into the container's task.toml.",
        formats=[".toml"],
        validation_notes=[
            "Uses TOML array-of-tables: [[mcp_servers]].",
            "Each entry needs 'name' plus either 'url' or 'command'.",
            'Command-based servers need transport = "stdio" (auto-inferred if missing).',
            'URL-based servers default to transport = "sse".',
        ],
        example="""\
[[mcp_servers]]
name = "my-api"
url = "http://localhost:8080"

[[mcp_servers]]
name = "my-tool"
command = "python /workspace/tools/server.py"
transport = "stdio"
""",
    ),
    EntrySpec(
        rel_path="evals/environment/<subdirs>/",
        kind="dir",
        requirement=Requirement.OPTIONAL,
        scope=Scope.HARBOR,
        description="Additional directories copied into the container environment "
        "(config files, seed data for sidecars).",
        validation_notes=["Any directory name except __pycache__ and .git."],
    ),
    # -- Results (output) --
    EntrySpec(
        rel_path="evals/results/",
        kind="dir",
        requirement=Requirement.OPTIONAL,
        scope=Scope.OUTPUT,
        description="Output directory — generated by evaluation runs. "
        "Do not create manually; populated by evaluate and Harbor.",
        validation_notes=[
            "latest symlink points to the most recent run.",
            "<timestamp>/<agent>/with-skill/ and without-skill/ hold evaluation outputs.",
            "See: skillevaluator info results",
        ],
    ),
]

# Also document the scripts/ deps that affect container builds:
SCRIPTS_SPEC: list[EntrySpec] = [
    EntrySpec(
        rel_path="scripts/requirements.txt",
        kind="file",
        requirement=Requirement.OPTIONAL,
        scope=Scope.HARBOR,
        description="Python pip dependencies. Auto-detected and installed when no custom Dockerfile is provided.",
        formats=[".txt"],
        validation_notes=["Standard pip requirements format. One package per line."],
    ),
    EntrySpec(
        rel_path="scripts/apt-packages.txt",
        kind="file",
        requirement=Requirement.OPTIONAL,
        scope=Scope.HARBOR,
        description="System apt packages. Auto-detected and installed when no custom Dockerfile is provided.",
        formats=[".txt"],
        validation_notes=["One package name per line. Comments with # are ignored."],
    ),
]

DATASET_REQUIRED_FIELDS = {"id", "question"}
AGENTSKILLS_REQUIRED_FIELDS = {"id", "prompt", "expected_output"}
DATASET_RECOMMENDED_FIELDS = {"expected_skill", "ground_truth", "expected_behavior"}

DOCKERFILE_MAX_BYTES = 20_000
_EVALS_CONFIG_REL_PATHS = ("evals/config.yml", "evals/config.yaml")


# ---------------------------------------------------------------------------
# Validation helpers
# ---------------------------------------------------------------------------


@dataclass
class CheckResult:
    path: str
    status: str  # "ok", "missing", "warning", "error"
    message: str


def validate_skillevaluators(skill_path: Path) -> list[CheckResult]:
    """Validate a skill's evals/ directory against the spec.

    Returns a list of check results — one per spec entry, plus any
    additional checks (dataset field validation, Dockerfile rules, etc.).
    """
    results: list[CheckResult] = []

    # 1. Required dataset
    _check_dataset(skill_path, results)

    # 2. Walk spec entries
    for spec in EVALS_SPEC:
        if spec.rel_path == "evals/evals.json":
            continue  # handled above
        if spec.scope == Scope.OUTPUT:
            continue  # not something the developer authors

        if "<subdirs>" in spec.rel_path:
            continue  # wildcard — not individually checkable

        target = skill_path / spec.rel_path.rstrip("/")
        if spec.kind == "dir":
            if target.is_dir():
                results.append(CheckResult(spec.rel_path, "ok", spec.description))
            # Dirs are always optional — don't warn about absence
        elif target.exists() or (spec.rel_path in _EVALS_CONFIG_REL_PATHS and os.path.lexists(target)):
            # A broken config symlink is checked too: loading rejects it, as the run does.
            results.append(CheckResult(spec.rel_path, "ok", spec.description))
            _run_file_checks(target, spec, results)
            # Optional files — no warning for absence

    # 3. scripts/ deps
    for spec in SCRIPTS_SPEC:
        target = skill_path / spec.rel_path
        if target.exists():
            results.append(CheckResult(spec.rel_path, "ok", spec.description))

    # 4. Check for unrecognised files in evals/
    _check_unrecognised(skill_path, results)

    return results


def validate_tier3_source(skill_path: Path) -> tuple[str, list[CheckResult]]:
    """Resolve and validate the Tier 3 source selected by a skill."""
    from skillevaluator.tier3.dataset_utils import find_eval_file
    from skillevaluator.tier3.evals_config import EvalsConfigError, load_evals_config

    try:
        config, config_path = load_evals_config(skill_path)
    except EvalsConfigError as exc:
        return "invalid", [CheckResult("evals/config.yml", "error", str(exc))]

    configured = str((config.get("harbor") or {}).get("task_source") or "auto")
    evals_file = find_eval_file(skill_path)
    native_dir = skill_path / "evals" / "harbor"

    if configured == "auto":
        if evals_file is not None:
            source = "evals_json"
        elif native_dir.is_dir():
            source = "native_harbor"
        else:
            return "missing", [
                CheckResult(
                    "evals/",
                    "error",
                    "No Tier 3 task source found. Add evals/evals.{json,jsonl,yaml,yml} "
                    "or an evals/harbor native task source.",
                )
            ]
    else:
        source = configured

    if source == "evals_json":
        if evals_file is None:
            selected_at = str(config_path) if config_path else "the default configuration"
            return source, [
                CheckResult(
                    "evals/evals.json",
                    "error",
                    f"Tier 3 source evals_json was selected by {selected_at}, but no supported eval dataset exists.",
                )
            ]
        results = [CheckResult(str(evals_file.relative_to(skill_path)), "ok", "Tier 3 eval dataset found.")]
        _validate_dataset_contents(evals_file, results, skill_path=skill_path)
        return source, results

    if source == "native_harbor":
        if not native_dir.is_dir():
            return source, [
                CheckResult(
                    "evals/harbor/",
                    "error",
                    "Tier 3 source native_harbor was selected, but evals/harbor does not exist.",
                )
            ]
        return source, validate_harbor_contract(skill_path)

    return "invalid", [CheckResult("evals/config.yml", "error", f"Unsupported Tier 3 task source: {source}")]


def validate_harbor_contract(skill_path: Path) -> list[CheckResult]:
    """Validate the BYOT Harbor task contract without mutating user files."""
    results: list[CheckResult] = []
    harbor_dir = skill_path / "evals" / "harbor"
    top_level_graders = [
        skill_path / "evals" / "grader.py",
        skill_path / "evals" / "grader.sh",
    ]
    existing_top_level_graders = [path for path in top_level_graders if path.exists()]

    if not harbor_dir.is_dir():
        if existing_top_level_graders:
            for grader in existing_top_level_graders:
                rel = f"evals/{grader.name}"
                results.append(CheckResult(rel, "ok", "Top-level custom grader found for BYOG generated tasks."))
                _validate_custom_grader_file(grader, rel, results)
            return results
        results.append(
            CheckResult(
                "evals/harbor/",
                "error",
                "BYOT Harbor task source missing. Create one with: skillevaluator init-harbor-task <path>, "
                "or create a top-level BYOG grader with: skillevaluator init-custom-grader <path>",
            )
        )
        return results

    results.append(CheckResult("evals/harbor/", "ok", "BYOT Harbor task source found."))

    dataset_toml = harbor_dir / "dataset.toml"
    task_names: list[str] = []
    if dataset_toml.exists():
        results.append(CheckResult("evals/harbor/dataset.toml", "ok", "Harbor dataset manifest found."))
        try:
            import tomllib

            data = tomllib.loads(dataset_toml.read_text(encoding="utf-8"))
            tasks = data.get("tasks", [])
            if isinstance(tasks, list):
                task_names = [str(task.get("name")) for task in tasks if isinstance(task, dict) and task.get("name")]
            if not task_names:
                results.append(
                    CheckResult(
                        "evals/harbor/dataset.toml",
                        "warning",
                        "No [[tasks]] entries found. Harbor may have no cases to run.",
                    )
                )
        except Exception as e:
            results.append(CheckResult("evals/harbor/dataset.toml", "error", f"Invalid TOML: {e}"))
    else:
        results.append(CheckResult("evals/harbor/dataset.toml", "error", "Harbor dataset manifest is required."))

    case_dirs = [path for path in sorted(harbor_dir.iterdir()) if path.is_dir() and not path.name.startswith(".")]
    if not case_dirs:
        results.append(
            CheckResult(
                "evals/harbor/<case>/",
                "error",
                "No Harbor case directories found.",
            )
        )

    for case_dir in case_dirs:
        rel = f"evals/harbor/{case_dir.name}"
        task_toml = case_dir / "task.toml"
        instruction = case_dir / "instruction.md"
        grader = case_dir / "tests" / "grader.py"
        shell_grader = case_dir / "tests" / "grader.sh"
        test_sh = case_dir / "tests" / "test.sh"
        dockerfile = case_dir / "environment" / "Dockerfile"

        if task_toml.exists():
            results.append(CheckResult(f"{rel}/task.toml", "ok", "Harbor task definition found."))
            try:
                import tomllib

                tomllib.loads(task_toml.read_text(encoding="utf-8"))
            except Exception as e:
                results.append(CheckResult(f"{rel}/task.toml", "error", f"Invalid TOML: {e}"))
        else:
            results.append(CheckResult(f"{rel}/task.toml", "error", "Harbor task definition is required."))

        if instruction.exists():
            results.append(CheckResult(f"{rel}/instruction.md", "ok", "Task instruction found."))
        else:
            results.append(CheckResult(f"{rel}/instruction.md", "warning", "No instruction.md found."))

        if grader.exists() or shell_grader.exists() or test_sh.exists():
            if grader.exists():
                results.append(CheckResult(f"{rel}/tests/grader.py", "ok", "Custom grader entrypoint found."))
                _validate_custom_grader_file(grader, f"{rel}/tests/grader.py", results)
            if shell_grader.exists():
                results.append(CheckResult(f"{rel}/tests/grader.sh", "ok", "Custom shell grader entrypoint found."))
                _validate_custom_grader_file(shell_grader, f"{rel}/tests/grader.sh", results)
            if test_sh.exists():
                results.append(CheckResult(f"{rel}/tests/test.sh", "ok", "Verifier shell entrypoint found."))
        else:
            results.append(
                CheckResult(
                    f"{rel}/tests/",
                    "warning",
                    "No custom grader/test entrypoint found. SkillEvaluator can inject default grading when enabled.",
                )
            )

        if dockerfile.exists():
            text = dockerfile.read_text(encoding="utf-8", errors="ignore")
            if "COPY" in text.upper() and "skills" in text.lower():
                results.append(
                    CheckResult(
                        f"{rel}/environment/Dockerfile",
                        "warning",
                        "Dockerfile appears to copy skills. SkillEvaluator stages target/baseline skills in generated copies; "
                        "source BYOT tasks should avoid hardcoding the target skill.",
                    )
                )

    evals_file = skill_path / "evals" / "evals.json"
    if evals_file.exists() and case_dirs:
        try:
            from .dataset_utils import load_dataset_entries

            entry_ids = {str(entry.get("id")) for entry in load_dataset_entries(evals_file)}
            missing = [
                case_dir.name
                for case_dir in case_dirs
                if case_dir.name not in entry_ids and f"nvidia/{case_dir.name}" not in task_names
            ]
            if missing:
                results.append(
                    CheckResult(
                        "evals/evals.json",
                        "warning",
                        "BYOT case metadata not found for: "
                        + ", ".join(missing)
                        + ". Default grading needs matching evals.json ids unless grading.mode=custom_only.",
                    )
                )
        except Exception as e:
            results.append(CheckResult("evals/evals.json", "warning", f"Could not check BYOT metadata ids: {e}"))

    return results


def _check_dataset(skill_path: Path, results: list[CheckResult]) -> bool:
    """Check for the required dataset file. Returns True if found."""
    evals_dir = skill_path / "evals"
    if not evals_dir.is_dir():
        results.append(
            CheckResult(
                "evals/",
                "missing",
                "No evals/ directory found. Add task guidance in evals/EVAL.md or pass --prompt, or retain "
                "matching Tier 3 traces, then run skillevaluator create-eval-dataset <path>. "
                "For an explicitly skill-derived starter, run "
                "skillevaluator create-eval-dataset <path> --grounding skill.",
            )
        )
        return False

    for ext in DATASET_EXTENSIONS:
        candidate = evals_dir / f"evals{ext}"
        if candidate.exists():
            results.append(
                CheckResult(
                    f"evals/evals{ext}",
                    "ok",
                    f"Dataset found ({candidate.stat().st_size} bytes).",
                )
            )
            _validate_dataset_contents(candidate, results, skill_path=skill_path)
            return True

    results.append(
        CheckResult(
            "evals/evals.json",
            "error",
            "REQUIRED dataset file missing. Accepted names: "
            + ", ".join(f"evals{e}" for e in DATASET_EXTENSIONS)
            + ". Add task guidance in evals/EVAL.md or pass --prompt, or retain matching Tier 3 traces "
            "before running skillevaluator create-eval-dataset <path>. For an explicitly skill-derived starter, "
            "run skillevaluator create-eval-dataset <path> --grounding skill.",
        )
    )
    return False


# Reading a SKILL.md that names no other location ("read SKILL.md", "reads the
# skill's SKILL.md") means the skill's own instructions. A SKILL.md the task is
# about, such as one the agent writes or one in the user's project, is not.
# "Followed the SKILL.md workflow" counts; "follows the SKILL.md format" names
# the file format (see below), and "the following SKILL.md" is the task's file.
_READ_VERB_RE = (
    r"(?:read|reads|reading|load|loads|loaded|loading|open|opens|opened|consult(?:s|ed)?"
    r"|cat|(?<!the\s)follow(?:s|ed|ing)?)"
)
_SKILL_MD_QUALIFIER_RE = r"(?:the|its|this|that|own|skill['\u2019]s)"
# Nouns after SKILL.md that make it the file format or other skills' files
# ("SKILL.md files", "the SKILL.md frontmatter format", "following SKILL.md best
# practices"), not this skill's instructions. Skills that write skills use this
# wording in ordinary prompts. One modifier may come between; a connective may
# not ("read SKILL.md and files in references/" still reads the skill's own
# SKILL.md).
_SKILL_MD_GENERIC_NOUN_RE = (
    r"(?:(?!(?:and|or|then|but|before|after|to|for|with)\b)[\w-]+\s+)?"
    r"(?:files|format|conventions|spec|specification|standard|template|schema"
    r"|guidelines|practices|structure|rules|requirements|layout)\b"
)
_SKILL_USE_VERB_RE = (
    r"(?:use|used|uses|using|invok(?:e|ed|es|ing)|activat(?:e|ed|es|ing)|load(?:s|ed|ing)?"
    r"|identif(?:y|ied|ies|ying))"
)
# What may follow "used <name>" when the name stands for the skill: the end of
# the clause or a connective. CLI arguments ("using glab mr list") or a noun
# ("the input PDF") mean the CLI or file the skill is named after.
_SKILL_NAME_END_RE = r"(?=\s*(?:$|[.,;:!?)]|(?:and|to|for|before|after|then|first)\b))"
# Verbs and interpreters before a script name that mean the script was run.
# "called" is not one: "a file called review.py" names the file.
_RUN_VERB_RE = (
    r"(?:ran|run|runs|running|execut(?:e|ed|es|ing)|invok(?:e|ed|es|ing)|call(?:s|ing)?"
    r"|python3?|bash|sh|node)"
)
# "Used review.py" means it ran only when the name ends the clause or CLI
# arguments follow ("used review.py to check", "using review.py --all"). "Uses
# main.py's parser" or "uses utils.py helpers" names a file, maybe the user's.
_SCRIPT_USE_VERB_RE = r"us(?:e|ed|es|ing)"
_SCRIPT_ARGS_RE = r"(?=\s+(?:-{1,2}\w|[\w.~-]*/|[\w~-]+\.[a-z]\w*\b))"
# Script file types listed from the skill's scripts/ and tools/ directories.
_SKILL_SCRIPT_SUFFIXES = frozenset({".py", ".sh", ".bash", ".js", ".mjs", ".cjs", ".ts", ".rb", ".pl", ".ps1"})
# Negation must immediately precede the verb, with at most one adverb.
# Clause events are consumed once, so "not ... without first reading" can be
# recognized as requiring a read without rescanning every growing prefix.
_CLAUSE_STATE_RE = re.compile(
    r"(?P<break>[.,;:!?\n]|\b(?:and|but|then)\b)"
    r"|(?P<cancel>\b(?:before|until|till|while|after|yet|unless|prior\s+to|ahead\s+of|skip(?:s|ped|ping)?"
    r"|forget(?:s|ting)?|forgot|fail(?:s|ed|ing)?|neglect(?:s|ed|ing)?)\b)"
    r"|(?P<negative>\b(?:no|not|never|without)\b|n['\u2019]t\b)",
    re.IGNORECASE,
)
_NEGATED_PREFIX_RE = re.compile(
    rf"(?P<negative>\b(?:not|never|without)\b|n['\u2019]t\b)\s+"
    rf"(?:(?:\w+ly|ever|even|first|once|also|really)\s+)?"
    rf"(?:(?:{_READ_VERB_RE}|{_SKILL_USE_VERB_RE}|{_RUN_VERB_RE})\s+(?:the\s+)?)?$",
    re.IGNORECASE,
)
_NEGATIVE_SUBJECT_RE = re.compile(
    r"\bno\s+(?:(?!(?:before|until|without|and|or|but|then)\b)[\w-]+\s+){0,3}(?:agents?|trials?)\s+$",
    re.IGNORECASE,
)
_INDIRECT_NEGATED_PREFIX_RE = re.compile(
    r"(?:\b(?:not|never|without)\b|n['\u2019]t\b)\s+"
    r"(?:need\s+to|required\s+to|ask(?:\s+the\s+user)?\s+to|ask\s+questions?\s+or)\s+$",
    re.IGNORECASE,
)
# Dataset aliases are literal data, never regex source. One fixed marker keeps
# compiled patterns independent of the number and size of expected_skill values.
_SKILL_NAME_MARKER = "\x00name\x00"
_MATCH_EXCERPT_CHARS = 80
_MAX_FIELD_VALUES = 1000
_MARKDOWN_LINK_RE = re.compile(r"\[([^\[\]\n]+)\]\([^()\n]*\)")


def _skill_files_re(skill_name: str | None) -> str:
    """Wording that names the skill's own files: skills/<name>, <name>/SKILL.md, or reading a bare SKILL.md."""
    qualifier = _SKILL_MD_QUALIFIER_RE
    skill_place = "skill"
    alternatives = []
    if skill_name:
        name = re.escape(skill_name)
        qualifier = rf"(?:{_SKILL_MD_QUALIFIER_RE}|{name}(?:['\u2019]s)?)"
        skill_place = rf"(?:skill|{name})"
        alternatives += [rf"\bskills/{name}(?![\w-])", rf"(?<![\w-]){name}/SKILL\.md\b"]
    # "SKILL.md in ./my-skill" names another skill's file; "in the skill
    # directory" or "from the installed skill" is still this skill's own.
    elsewhere = rf"\s+(?:in|of|from|under|inside)\s+(?!(?:the\s+|its\s+|this\s+)?(?:installed\s+|own\s+)?{skill_place}(?![\w-]))"
    alternatives.append(
        rf"\b{_READ_VERB_RE}(?:\s+{qualifier})*\s+(?:(?:the\s+)?contents\s+of\s+)?[`'\"*_\[]*SKILL\.md\b"
        rf"(?![`'\"*_\]]*(?:{elsewhere}|\s+{_SKILL_MD_GENERIC_NOUN_RE}))"
    )
    return "|".join(alternatives)


@functools.lru_cache(maxsize=64)
def _prompt_skill_files_re(skill_name: str | None, skill_scripts: tuple[str, ...] = ()) -> re.Pattern[str]:
    """A prompt that points the agent at the skill's own files, which the no-skill baseline is never given."""
    return _skill_use_assertion_re(skill_name or "", skill_scripts, prompt=True)


@functools.lru_cache(maxsize=64)
def _skill_use_assertion_re(
    skill_name: str | None, skill_scripts: tuple[str, ...] = (), *, prompt: bool = False
) -> re.Pattern[str]:
    """Graded text about using the skill: its files, its name called a skill, "used <name>", or running its scripts.

    A skill named after the CLI or file format it wraps (glab, kubectl, pdf)
    shares that name with work the baseline can do, so "used <name>" counts only
    when the name ends the clause ("used release-review and found ..."), not
    when CLI arguments or a noun follow it ("listed using glab mr list") or
    "the" comes before it ("loaded the PDF"). "the <name> skill" is still caught.
    A skill script counts when a run verb or interpreter comes before its name
    ("ran review.py", "python3 ./review.py"), when "used" does and the name
    ends the clause or CLI arguments follow it, or when the text names it under
    scripts/ or tools/.
    """
    name = re.escape(skill_name or "")
    alternatives = [
        _skill_files_re(skill_name),
        rf"\b(?:{_SKILL_USE_VERB_RE}|{_READ_VERB_RE})\s+(?:(?:the|this|its|that)(?:\s+installed)?|installed)\s+skill\b"
        rf"(?![\w-]|\.\w|\s+(?:levels?|sets?)\b)",
    ]
    if skill_name:
        alternatives.extend(
            [
                rf"(?<![\w-]){name}(?![\w-])(?:\s+(?:as|is)(?:\s+(?:the|a))?(?:\s+right)?)?"
                rf"\s+skill\b(?![\w-]|\.\w|\s+(?:levels?|sets?)\b)",
                rf"\bskill\s+(?:named\s+|called\s+)?[`'\"]?{name}(?![\w-])",
            ]
        )
    # A template may explicitly route with "Use <name> to ...". Naming it as a
    # skill or pointing at its files/scripts requires the unavailable install.
    if not prompt and skill_name:
        alternatives.append(rf"\b{_SKILL_USE_VERB_RE}\s+[`'\"]?{name}(?![\w-])[`'\"]?{_SKILL_NAME_END_RE}")
    for script in skill_scripts:
        script = _normalized_match_text(script)
        script_name = rf"{re.escape(script)}(?![\w-]|\.\w)"
        script_ref = rf"(?:the\s+)?[`'\"]?(?:[\w.~-]*/)*{script_name}"
        alternatives += [
            rf"(?<![\w.-])(?:scripts|tools)/{script_name}",
            rf"\b{_RUN_VERB_RE}\s+(?:-[\w-]+\s+)*{script_ref}",
            rf"\b{_SCRIPT_USE_VERB_RE}\s+{script_ref}[`'\"]?(?:{_SKILL_NAME_END_RE}|{_SCRIPT_ARGS_RE})",
        ]
    return re.compile("|".join(alternatives), re.IGNORECASE)


def _first_unnegated_match(pattern: re.Pattern[str], text: str) -> str | None:
    """A bounded excerpt of the first positive requirement, in linear scan order."""
    events = iter(_CLAUSE_STATE_RE.finditer(text))
    event = next(events, None)
    negatives = 0
    for match in pattern.finditer(text):
        while event is not None and event.start() < match.start():
            negatives = negatives + 1 if event.lastgroup == "negative" else 0
            event = next(events, None)
        prefix_start = max(0, match.start() - 256)
        # Report interpretation can describe absent activation: "no positive
        # with-skill trial loaded the skill". Keep this direct subject bounded;
        # "no agent proceeds before reading" still requires a read.
        negative_subject = _NEGATIVE_SUBJECT_RE.search(text, prefix_start, match.start())
        indirect_negative = _INDIRECT_NEGATED_PREFIX_RE.search(text, prefix_start, match.start())
        negated = _NEGATED_PREFIX_RE.search(text, prefix_start, match.start())
        if not (negative_subject or indirect_negative or negated) or negatives % 2 == 0:
            return text[match.start() : min(match.end(), match.start() + _MATCH_EXCERPT_CHARS)]
    return None


def _normalized_match_text(text: str) -> str:
    """Normalize ordinary Unicode and Markdown spellings, without mapping homoglyphs."""
    text = "".join(char for char in unicodedata.normalize("NFKC", text) if unicodedata.category(char) != "Cf")
    text = _MARKDOWN_LINK_RE.sub(r"\1", text)
    return text.replace("**", "").replace("`", "")


def _prepared_skill_name(skill_name: str | None) -> tuple[str, str]:
    """Prepare an identity once per case, without retaining contributor aliases globally."""
    name = _normalized_match_text(skill_name or "")
    return name, name.casefold()


def _mask_skill_name(text: str, name: str, folded_name: str | None = None) -> str:
    """Replace whole literal identities without compiling contributor-controlled regexes."""
    folded_text = text.casefold()
    folded_name = name.casefold() if folded_name is None else folded_name
    offsets = None
    if len(folded_text) != len(text):
        # Casefold can expand a character (ß -> ss); retain original offsets so
        # these aliases work without changing the diagnostic's other spelling.
        offsets = [index for index, char in enumerate(text) for _ in char.casefold()]
    parts = []
    consumed = search_at = 0
    while (found := folded_text.find(folded_name, search_at)) >= 0:
        search_at = found + len(folded_name)
        start = offsets[found] if offsets is not None else found
        end = offsets[search_at - 1] + 1 if offsets is not None else search_at
        before = text[start - 1] if start else ""
        after = text[end : end + 1]
        if (
            (before and (before.isalnum() or before in "_-"))
            or (after and (after.isalnum() or after in "_-"))
            or text[start:end].casefold() != folded_name
        ):
            continue
        parts.extend((text[consumed:start], _SKILL_NAME_MARKER))
        consumed = end
    if not consumed:
        return text
    parts.append(text[consumed:])
    return "".join(parts)


def _match_skill_text(
    text: str,
    skill_name: str | None,
    skill_scripts: Sequence[str],
    *,
    prompt: bool,
    prepared_name: tuple[str, str] | None = None,
) -> str | None:
    text = _normalized_match_text(text)
    name, folded_name = prepared_name if prepared_name is not None else _prepared_skill_name(skill_name)
    scripts = tuple(skill_scripts)
    generic_pattern = _prompt_skill_files_re(None, scripts) if prompt else _skill_use_assertion_re("", scripts)
    # Check generic wording first: an identity like "skill" or "read" must
    # not mask the noun or verb in "read SKILL.md" and bypass validation.
    matched = _first_unnegated_match(generic_pattern, text)
    if matched is None and name:
        masked = _mask_skill_name(text, name, folded_name)
        if masked is not text:
            pattern = (
                _prompt_skill_files_re(_SKILL_NAME_MARKER, scripts)
                if prompt
                else _skill_use_assertion_re(_SKILL_NAME_MARKER, scripts)
            )
            matched = _first_unnegated_match(pattern, masked)
    if matched is None:
        return None
    # Restore only a bounded name fragment; neither huge aliases nor the
    # internal marker may reach terminal, JSON or CI diagnostics.
    return matched.replace(_SKILL_NAME_MARKER, name[:_MATCH_EXCERPT_CHARS]).split("\x00", 1)[0][:_MATCH_EXCERPT_CHARS]


def _prompt_skill_files_match(prompt: str, skill_name: str | None, skill_scripts: Sequence[str] = ()) -> str | None:
    """The prompt text that points the agent at the skill's own files, or None."""
    return _match_skill_text(prompt, skill_name, skill_scripts, prompt=True)


def _skill_use_match(text: str, skill_name: str | None, skill_scripts: Sequence[str] = ()) -> str | None:
    """The expected-output or assertion text that grades skill use, or None."""
    return _match_skill_text(text, skill_name, skill_scripts, prompt=False)


def _skill_script_names(skill_path: Path) -> tuple[str, ...]:
    """File names of the skill's scripts in scripts/ and tools/, which the no-skill baseline does not have."""
    names: set[str] = set()
    for dirname in EXECUTABLE_SKILL_DIRS:
        directory = skill_path / dirname
        try:
            names.update(
                item.name
                for item in directory.iterdir()
                if item.suffix.lower() in _SKILL_SCRIPT_SUFFIXES and item.is_file()
            )
        except OSError:
            continue
    return tuple(sorted(names))


def _authored_field(entry: dict[str, Any], runtime_key: str, agentskills_key: str) -> str:
    """The field name the author wrote: the agentskills.io name when the runtime value came from it."""
    if agentskills_key in entry and entry.get(agentskills_key) == entry.get(runtime_key):
        return agentskills_key
    return runtime_key


def _field_string_leaves(value: Any) -> tuple[list[str], str | None]:
    """Read at most 1000 values without copying huge containers or expanding aliases."""
    pending: list[tuple[Iterator[Any], int | None]] = [(iter((value,)), None)]
    visited: set[int] = set()
    active: set[int] = set()
    leaves: list[str] = []
    values_read = 0
    while pending:
        iterator, identity = pending[-1]
        try:
            item = next(iterator)
        except StopIteration:
            pending.pop()
            if identity is not None:
                active.remove(identity)
            continue
        values_read += 1
        if values_read > _MAX_FIELD_VALUES:
            return leaves, "limit"
        if isinstance(item, str):
            leaves.append(item)
        elif isinstance(item, (Mapping, list, tuple)):
            identity = id(item)
            if identity in active:
                return leaves, "cycle"
            if identity in visited:
                continue
            visited.add(identity)
            active.add(identity)
            children = chain(item, item.values()) if isinstance(item, Mapping) else iter(item)
            pending.append((children, identity))
    return leaves, None


def _string_leaves(value: Any) -> tuple[list[str], bool]:
    """Strings in a field and whether checking was incomplete (including a cycle)."""
    leaves, reason = _field_string_leaves(value)
    return leaves, reason is not None


def _quoted(text: str) -> str:
    """A bounded, printable and credential-redacted diagnostic excerpt."""
    return repr(redact_printable_text(" ".join(text.split()), max_len=_MATCH_EXCERPT_CHARS, max_input_chars=320))


def _baseline_fairness_warnings(
    entry: dict[str, Any], *, skill_scripts: Sequence[str] = (), skill_names: Sequence[str] = ()
) -> list[str]:
    """Explain dataset text the no-skill baseline is graded on but cannot satisfy.

    ``entry`` is a normalized dataset entry; ``skill_scripts`` are the file
    names of the skill's own scripts. This is a wording heuristic, so it can
    miss skill use phrased another way and can flag task text that shares the
    skill's name.
    """
    warnings = []
    prompt = entry.get("question")
    declared_name = entry.get("expected_skill")
    names = tuple(
        dict.fromkeys(name.strip() for name in (*skill_names, declared_name) if isinstance(name, str) and name.strip())
    ) or (None,)
    prepared_names = tuple(_prepared_skill_name(name) for name in names)
    scripts = tuple(skill_scripts)

    def read(field_name: str, value: Any) -> list[tuple[str, str]]:
        leaves, reason = _field_string_leaves(value)
        if reason == "limit":
            warnings.append(
                f"{field_name} has more than {_MAX_FIELD_VALUES} values, so it was not fully checked for skill use. "
                "Keep it to a short string or a list of strings."
            )
        elif reason == "cycle":
            warnings.append(
                f"{field_name} contains a cyclic value, so it was not fully checked for skill use. "
                "Use a finite string or list of strings."
            )
        return [(field_name, leaf) for leaf in leaves]

    for field_name, prompt_text in read(_authored_field(entry, "question", "prompt"), prompt):
        matched = next(
            (
                match
                for name in prepared_names
                if (match := _match_skill_text(prompt_text, None, scripts, prompt=True, prepared_name=name))
            ),
            None,
        )
        if matched:
            warnings.append(
                f"{field_name} points at the skill's files ({_quoted(matched)}). The no-skill "
                "baseline gets the same prompt without the skill, so it cannot follow it. Describe the task instead; "
                "skill_execution measures whether the skill was used."
            )
            break
    texts = read(_authored_field(entry, "ground_truth", "expected_output"), entry.get("ground_truth"))
    texts += read(_authored_field(entry, "expected_behavior", "assertions"), entry.get("expected_behavior"))
    for field_name, text in texts:
        matched = next(
            (
                match
                for name in prepared_names
                if (match := _match_skill_text(text, None, scripts, prompt=False, prepared_name=name))
            ),
            None,
        )
        if matched:
            warnings.append(
                f"{field_name} grades skill use ({_quoted(matched)}), which the no-skill baseline is also graded "
                "on. Keep it about the task outcome; skill_execution scores skill use separately."
            )
            break
    return warnings


def _skill_identity_names(skill_path: Path) -> tuple[str, ...]:
    """Directory and declared identities, with bounded frontmatter input/parsing."""
    from skillevaluator.plugin_markdown import parse_markdown

    names = [skill_path.name]
    try:
        with (skill_path / "SKILL.md").open(encoding="utf-8") as source:
            name = parse_markdown(source.read(128 * 1024)).name
        if name and name not in names:
            names.append(name)
    except (OSError, UnicodeError):
        pass
    return tuple(names)


def _validate_dataset_contents(path: Path, results: list[CheckResult], *, skill_path: Path | None = None) -> None:
    """Validate the contents of a dataset file."""
    from .dataset_utils import load_dataset_entries_with_format
    from .eval_core.declarative_checks import validate_declarative_checks

    try:
        entries, dataset_format = load_dataset_entries_with_format(path)
    except Exception as e:
        results.append(CheckResult(str(path), "error", f"Cannot parse dataset: {e}"))
        return

    if dataset_format == "legacy":
        results.append(
            CheckResult(
                str(path.name),
                "warning",
                "Deprecated eval dataset format: legacy flat entries are still accepted, "
                "but new datasets should use the agentskills.io shape "
                '{"skill_name": "...", "evals": [{"id": "...", "prompt": "...", '
                '"expected_output": "..."}]}. '
                "Preview migration with: skillevaluator tier3 migrate-dataset SOURCE --skill-name NAME; "
                "write a new destination with --output DESTINATION.",
            )
        )

    if not entries:
        results.append(CheckResult(str(path), "error", "Dataset is empty (0 entries)."))
        return

    results.append(
        CheckResult(
            str(path.name),
            "ok",
            f"Dataset has {len(entries)} {'entry' if len(entries) == 1 else 'entries'}.",
        )
    )
    case_ids_valid = True
    try:
        validate_case_ids(entry.get("id") for entry in entries)
    except ValueError as exc:
        results.append(CheckResult(str(path.name), "error", str(exc)))
        case_ids_valid = False

    skill_path = skill_path or path.parent.parent
    skill_has_scripts = any((skill_path / "scripts").glob("*.py"))
    skill_scripts = _skill_script_names(skill_path)
    skill_names = _skill_identity_names(skill_path)
    required_fields_valid = True

    for i, entry in enumerate(entries):
        entry_id = entry.get("id", f"<index {i}>")
        required_fields = AGENTSKILLS_REQUIRED_FIELDS if dataset_format == "agentskills" else DATASET_REQUIRED_FIELDS
        missing_required = required_fields - set(entry.keys())
        if missing_required:
            required_fields_valid = False
            results.append(
                CheckResult(
                    f"entry {entry_id}",
                    "error",
                    f"Missing required fields: {', '.join(sorted(missing_required))}",
                )
            )
        if "checks" in entry:
            for error in validate_declarative_checks(entry["checks"]):
                results.append(CheckResult(f"entry {entry_id}", "error", error))
        missing_recommended = DATASET_RECOMMENDED_FIELDS - set(entry.keys())
        if dataset_format == "legacy" and missing_recommended:
            results.append(
                CheckResult(
                    f"entry {entry_id}",
                    "warning",
                    f"Missing recommended fields: {', '.join(sorted(missing_recommended))}",
                )
            )
        for warning in _baseline_fairness_warnings(entry, skill_scripts=skill_scripts, skill_names=skill_names):
            results.append(CheckResult(f"entry {entry_id}", "warning", warning))
        if dataset_format == "legacy" and "expected_script" not in entry and skill_has_scripts:
            results.append(
                CheckResult(
                    f"entry {entry_id}",
                    "warning",
                    "expected_script is missing, but this skill has scripts. "
                    "Add expected_script or set expected_script: null if no script should be run.",
                )
            )

    if case_ids_valid and required_fields_valid:
        try:
            from skillevaluator.tier3.dataset_sufficiency import generation_coverage_summary
            from skillevaluator.tier3.harbor.report_data import summarize_dataset_entries

            coverage = summarize_dataset_entries(entries)
            results.append(
                CheckResult(
                    "Dataset size",
                    "ok",
                    generation_coverage_summary(coverage["total_tasks"], coverage["negative_tasks"]),
                )
            )
        except (TypeError, ValueError):
            pass


def _run_file_checks(target: Path, spec: EntrySpec, results: list[CheckResult]) -> None:
    """Run spec-specific validation on an existing file."""
    if spec.rel_path in ("evals/grader.py", "evals/grader.sh"):
        _validate_custom_grader_file(target, spec.rel_path, results)

    if "Dockerfile" in spec.rel_path:
        size = target.stat().st_size
        if size > DOCKERFILE_MAX_BYTES:
            results.append(
                CheckResult(
                    spec.rel_path,
                    "error",
                    f"Dockerfile exceeds {DOCKERFILE_MAX_BYTES // 1000}KB limit ({size} bytes).",
                )
            )
        else:
            content = target.read_text(encoding="utf-8")
            lines = [ln.strip() for ln in content.splitlines() if ln.strip() and not ln.strip().startswith("#")]
            if not lines or not lines[0].upper().startswith("FROM"):
                results.append(
                    CheckResult(
                        spec.rel_path,
                        "error",
                        "Dockerfile must start with a FROM instruction.",
                    )
                )
            for i, ln in enumerate(content.splitlines(), 1):
                upper = ln.strip().upper()
                if upper.startswith("COPY") and "environment/" in ln:
                    results.append(
                        CheckResult(
                            spec.rel_path,
                            "error",
                            f"Line {i}: COPY references 'environment/' but the build context IS "
                            f"environment/. Use relative paths (e.g. 'COPY skills/' not "
                            f"'COPY environment/skills/').",
                        )
                    )
                    break

    if "mcp_servers.toml" in spec.rel_path:
        _validate_mcp_toml(target, results)

    if spec.rel_path in _EVALS_CONFIG_REL_PATHS:
        _validate_evals_config(target, results)


def _validate_custom_grader_file(path: Path, rel_path: str, results: list[CheckResult]) -> None:
    text = path.read_text(encoding="utf-8", errors="ignore")
    if "reward.json" not in text and "reward.txt" not in text:
        results.append(
            CheckResult(
                rel_path,
                "warning",
                "Custom graders should write /logs/verifier/reward.json or reward.txt.",
            )
        )
    if path.suffix == ".py":
        try:
            compile(text, str(path), "exec")
        except SyntaxError as e:
            results.append(CheckResult(rel_path, "error", f"Invalid Python custom grader: {e.msg}"))


def _validate_evals_config(path: Path, results: list[CheckResult]) -> None:
    try:
        from .evals_config import load_evals_config

        load_evals_config(path.parent.parent)
    except Exception as e:
        results.append(CheckResult(str(path), "error", f"Invalid evals config: {e}"))


def _validate_mcp_toml(path: Path, results: list[CheckResult]) -> None:
    try:
        import tomllib
    except ImportError:
        try:
            import tomli as tomllib  # type: ignore[no-redef]
        except ImportError:
            results.append(CheckResult(str(path), "warning", "Cannot validate: tomllib/tomli not available."))
            return

    try:
        data = tomllib.loads(path.read_text(encoding="utf-8"))
    except Exception as e:
        results.append(CheckResult(str(path), "error", f"Invalid TOML: {e}"))
        return

    servers = data.get("mcp_servers", [])
    if not isinstance(servers, list):
        results.append(
            CheckResult(
                str(path),
                "error",
                f"Expected [[mcp_servers]] array of tables, got {type(servers).__name__}.",
            )
        )
        return

    from .evals_config import load_allowed_runtime_env

    allowed_runtime_env = load_allowed_runtime_env(path.parent.parent.parent)

    for i, s in enumerate(servers):
        if not isinstance(s, dict) or "name" not in s:
            results.append(
                CheckResult(
                    str(path),
                    "error",
                    f"Entry {i}: missing 'name' field.",
                )
            )
            continue
        if "url" not in s and "command" not in s:
            results.append(
                CheckResult(
                    str(path),
                    "error",
                    f"Entry '{s['name']}': needs 'url' or 'command'.",
                )
            )
        elif "command" in s and s.get("transport") != "stdio":
            results.append(
                CheckResult(
                    str(path),
                    "warning",
                    f"Entry '{s['name']}': command-based server should set transport = \"stdio\". "
                    f'Harbor defaults to "sse" which requires a url. '
                    f"The adapter will auto-infer this, but explicit is better.",
                )
            )
        try:
            from skillevaluator.tier3.harbor.adapter import validate_mcp_server_declarations

            validate_mcp_server_declarations([s], allowed_runtime_env=allowed_runtime_env)
        except ValueError as exc:
            results.append(
                CheckResult(
                    str(path),
                    "error",
                    str(exc),
                )
            )


def _check_unrecognised(skill_path: Path, results: list[CheckResult]) -> None:
    """Warn about files in evals/ that the toolchain doesn't recognise."""
    evals_dir = skill_path / "evals"
    if not evals_dir.is_dir():
        return

    known_top_level = {
        "evals.json",
        "evals.jsonl",
        "evals.yaml",
        "evals.yml",
        "config.yml",
        "config.yaml",
        "EVAL.md",
        "files",
        "environment",
        "results",
        "harbor",
        "grader.py",
        "grader.sh",
    }

    for child in sorted(evals_dir.iterdir()):
        if child.name.startswith(".") or child.name == "__pycache__":
            continue
        if child.name not in known_top_level:
            results.append(
                CheckResult(
                    f"evals/{child.name}",
                    "warning",
                    "Unrecognised file/directory. The toolchain will ignore this.",
                )
            )

    env_dir = evals_dir / "environment"
    if env_dir.is_dir():
        known_env = {"Dockerfile", "docker-compose.yaml", "docker-compose.yml", "mcp_servers.toml"}
        for child in sorted(env_dir.iterdir()):
            if child.name.startswith(".") or child.name == "__pycache__":
                continue
            if child.name not in known_env and not child.is_dir():
                results.append(
                    CheckResult(
                        f"evals/environment/{child.name}",
                        "warning",
                        "Unrecognised file in environment/. "
                        "Only Dockerfile, docker-compose.yaml, mcp_servers.toml, and subdirectories are used.",
                    )
                )