Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
feat: add pre-commit hooks for offline Tier 1 skill checks (#690)
Matt Van Horn8fe9723db992
diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yamlnew file mode 100644index 00000000..296073d0--- /dev/null+++ b/.pre-commit-hooks.yaml@@ -0,0 +1,35 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++# Offline Tier 1 hooks for skill repositories. Each hook maps the files+# pre-commit passes to skill roots and runs one key-free check per skill.+# The files pattern covers every skill directory the schema check allows.+# require_serial keeps every file in one process, so each skill is checked+# and printed once instead of once per parallel chunk.+# See docs/repository-integration.mdx.++- id: skillevaluator-quality+ name: SkillEvaluator quality score+ description: Score each touched skill against the quality bar. Offline; no API key, network, Docker, or scanner download.+ entry: skillevaluator precommit-run quality+ language: python+ require_serial: true+ files: '(^|/)((SKILL|skill)\.md$|(agents|assets|config|evals|references|scripts|tests|tools)/)'++- id: skillevaluator-schema+ name: SkillEvaluator schema+ description: Validate SKILL.md frontmatter and skill layout. Offline; no API key, network, Docker, or scanner download.+ entry: skillevaluator precommit-run schema+ language: python+ require_serial: true+ files: '(^|/)((SKILL|skill)\.md$|(agents|assets|config|evals|references|scripts|tests|tools)/)'++- id: skillevaluator-lint-scripts+ name: SkillEvaluator script lint+ description: Advisory lint of Python scripts in a touched skill. Offline; no API key, network, Docker, or scanner download.+ entry: skillevaluator precommit-run lint-scripts+ language: python+ require_serial: true+ # Findings are advisory and never fail the commit; verbose shows them anyway.+ verbose: true+ files: '(^|/)((SKILL|skill)\.md$|(agents|assets|config|evals|references|scripts|tests|tools)/)'diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 74ff1867..f3a4fafc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,11 @@ All notable changes to SkillEvaluator are documented in this file.### Added+- Pre-commit hooks for offline Tier 1 skill checks: `.pre-commit-hooks.yaml`+ exposes `skillevaluator-quality`, `skillevaluator-schema`, and+ `skillevaluator-lint-scripts`. A hidden `skillevaluator precommit-run` entry+ maps changed files to skill roots and runs each check without an API key,+ network, Docker, or scanner download.- The Tier 3 report data and JSON report record which execution backend ran theevaluation, as `execution_backend` (`harbor` or `nemo-gym`), next to the sandbox`environment`.diff --git a/docs/AGENTS.md b/docs/AGENTS.mdindex a94e4b71..ca5751c5 100644--- a/docs/AGENTS.md+++ b/docs/AGENTS.md@@ -29,7 +29,7 @@ folder holds MDX pages published to <https://docs.nvidia.com/skills/skillevaluat- `benchmark-rollout.mdx` — regenerating and promoting `BENCHMARK.md` cards- `github-actions.mdx` — skill check workflow setup and optional hosted PR feedback- `cli-onboarding.mdx` — released GitHub setup wizard-- `repository-integration.mdx` — choose GitHub or GitLab for skill checks+- `repository-integration.mdx` — choose GitHub or GitLab for skill checks; pre-commit hooks- `gitlab-ci.mdx` — reusable skill checks and downloadable GitLab reports- `advanced-ci.mdx` — secondary opt-in prerequisites and all-tier reference- `ci-integration.mdx` — exit codes, GitHub Actions recipe, progressive adoptiondiff --git a/docs/README.md b/docs/README.mdindex 4a22de9f..acfe46dc 100644--- a/docs/README.md+++ b/docs/README.md@@ -26,7 +26,7 @@ contributors making non-trivial edits.- `benchmark-rollout.mdx` — regenerating and promoting `BENCHMARK.md` cards- `github-actions.mdx` — reusable skill checks and optional hosted PR feedback- `cli-onboarding.mdx` — install the CLI, automate GitHub setup and open an optional test PR-- `repository-integration.mdx` — choose GitHub or GitLab for skill checks+- `repository-integration.mdx` — choose GitHub or GitLab for skill checks; pre-commit hooks- `gitlab-ci.mdx` — reusable skill checks and downloadable GitLab reports- `advanced-ci.mdx` — secondary opt-in prerequisites and all-tier reference- `ci-integration.mdx` — exit codes, GitHub Actions recipe, progressive adoptiondiff --git a/docs/repository-integration.mdx b/docs/repository-integration.mdxindex b0638523..cf91d402 100644--- a/docs/repository-integration.mdx+++ b/docs/repository-integration.mdx@@ -70,6 +70,104 @@ in the public repository. No demo-repository access is needed.workflow files. Additional evaluation stages require a separate opt-in.</Note>+## Pre-commit hooks++Run the deterministic, key-free Tier 1 checks on the skills a commit touches,+without waiting for CI. The hooks install SkillEvaluator from this repository+and call a hidden `skillevaluator precommit-run` entry that maps each changed+file to its skill root (the nearest ancestor that contains `SKILL.md`, or a+lowercase `skill.md` that the schema check then flags; names match exactly on+every OS),+de-duplicates those roots, and runs one check per skill. The hooks set+`require_serial: true` so pre-commit passes all files to one process and a+skill is not checked once per parallel chunk.++Files that are not inside a skill are ignored. Deleted skills are skipped.+Reports are not written into the repository.++### Install++Add a `.pre-commit-config.yaml` at the root of the skill repository and pin+`rev` to a released tag that includes+[`.pre-commit-hooks.yaml`](https://github.com/NVIDIA/SkillEvaluator/blob/main/.pre-commit-hooks.yaml).+Replace `<release tag>` in the example with that tag; `v0.9.0` and earlier+releases do not include the hooks.++The hooks use `language: python`, so pre-commit builds their environment with+the Python it runs under unless told otherwise. SkillEvaluator needs Python+3.12, 3.13, or 3.14; under an older or newer interpreter the first commit fails+while installing the hook with a pip `Requires-Python` error. That includes+macOS `/usr/bin/python3` (3.9), Ubuntu 22.04 (3.10), and Debian 12 (3.11).+Set `default_language_version` to a supported interpreter on your `PATH`, as+the example does, or set `language_version` on each hook:++```yaml title=".pre-commit-config.yaml"+default_language_version:+ python: python3.13+repos:+ - repo: https://github.com/NVIDIA/SkillEvaluator+ rev: <release tag>+ hooks:+ - id: skillevaluator-quality+ args: ["--min-score", "70"]+ - id: skillevaluator-schema+ - id: skillevaluator-lint-scripts+```++Then `pre-commit install`. The first commit (or `pre-commit install+--install-hooks`) builds the hook environment, which needs network access to+fetch SkillEvaluator and its dependencies from the pinned repo and PyPI; later+runs reuse the cached environment. On each commit, pre-commit passes the changed+skill files (`SKILL.md`, `skill.md`, and anything under the skill directories the+schema check allows: `agents/`, `assets/`, `config/`, `evals/`, `references/`,+`scripts/`, `tests/`, `tools/`) to the selected hooks.++`--min-score` and `--quality-config` are forwarded to the quality check, the+same options `quality-check` takes. Omit `args` to keep the default quality bar+of 70 and the packaged `quality-default.yaml`. To score commits the same way CI+does, pass the same config file, with a path relative to the repository root:++```yaml+ - id: skillevaluator-quality+ args: ["--min-score", "80", "--quality-config", "quality.yaml"]+```++### What each hook checks++| Hook id | Check | Needs |+| --- | --- | --- |+| `skillevaluator-quality` | Composite quality score (`quality-check`) | Python 3.12-3.14 only |+| `skillevaluator-schema` | `SKILL.md` frontmatter and skill layout (`validate --tiers 1 --checks schema`; honours `SKILLEVALUATOR_PROFILE`) | Python 3.12-3.14 only |+| `skillevaluator-lint-scripts` | Advisory Python script lint (`lint-scripts`) | Python 3.12-3.14 only |++Each hook prints one compact line per skill (`PASS` or `FAIL`) and exits+non-zero when any skill fails. Script lint findings are advisory, so that hook+does not fail the commit on style warnings. It prints the finding count and the+first three findings for each skill, and sets `verbose: true` so pre-commit+shows that output even though the hook passes. Run `skillevaluator lint-scripts`+on the skill to see every finding.++### What the hooks do not run++Once the hook environment is installed, running the checks stays offline: no+API key, no network, no Docker, and no scanner download.++They do **not** run:++- Security scans (`security-scan`, Gitleaks, SkillSpector, Semgrep). The first+ full scan can download pinned scanner releases.+- `doctor` / `health-check`, which probe those scanners.+- Default `validate` (or `--tiers 1` without `--checks`). That lineup includes+ security and code-integrity scans.+- LLM-backed rubric scoring, Tier 2 deduplication, and Tier 3 live evaluation.++Other keyless static checks (PII, license, Unicode, version, harness) are also+omitted from the hook set. Run them with `validate --tiers 1` in CI once the+scanners the remaining checks need are installed. Use the+[GitHub](/skills/skillevaluator/github-actions) or+[GitLab](/skills/skillevaluator/gitlab-ci) templates for scanner-backed CI, and+[Gate Your CI](/skills/skillevaluator/ci-integration) for a copy-paste job.+## Other CI systemsThe container contains the same evaluator runtime, and the CLI can also run indiff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.pyindex dee2e0f9..131af78a 100644--- a/src/skillevaluator/cli.py+++ b/src/skillevaluator/cli.py@@ -31,6 +31,7 @@ from skillevaluator.doctor import DEFAULT_PROBE_TIMEOUT_SEC, MAX_PROBE_TIMEOUT_Sfrom skillevaluator.harness.report import harness_block, harness_note, harness_panel, write_json_blockfrom skillevaluator.logging_config import setup_loggingfrom skillevaluator.models.result import ValidationResult+from skillevaluator.precommit import CHECKSfrom skillevaluator.quality_config import QualityConfigError, load_quality_configfrom skillevaluator.reporting.console_ui import (TierRow,@@ -3342,6 +3343,32 @@ def lint_scripts(target_path: Path, report_formats: tuple[str, ...], output_dir:raise click.ClickException("script lint failed")[email protected]("precommit-run", hidden=True)+ "--min-score",+ type=int,+ default=QUALITY_DEFAULT_MIN_SCORE,+ show_default=True,+ help="Minimum quality score (0-100) when the quality check runs.",+)+ "--quality-config",+ type=QUALITY_CONFIG_PATH,+ default=None,+ help="Override the packaged quality-default.yaml when the quality check runs.",+)[email protected]("check", type=click.Choice(list(CHECKS)))[email protected]("paths", nargs=-1, type=str)+def precommit_run(min_score: int, quality_config: Path | None, check: str, paths: tuple[str, ...]) -> None:+ """Map changed files to skill roots and run one offline Tier 1 check per skill."""+ from skillevaluator.precommit import run_precommit++ code, lines = run_precommit(check, paths, min_score=min_score, quality_config=quality_config)+ for line in lines:+ click.echo(line)+ raise SystemExit(code)++@cli.command("similarity-check")@click.argument("content_path", type=click.Path(exists=True, path_type=Path))@click.option("--type", "content_type", default="auto", type=click.Choice(["skill", "rules", "workflows", "auto"]))diff --git a/src/skillevaluator/precommit.py b/src/skillevaluator/precommit.pynew file mode 100644index 00000000..939856a8--- /dev/null+++ b/src/skillevaluator/precommit.py@@ -0,0 +1,260 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Map changed files to skill roots and run one offline Tier 1 check per skill."""++from __future__ import annotations++from collections.abc import Iterable, Sequence+from pathlib import Path+from typing import TYPE_CHECKING++from skillevaluator.constants import QUALITY_DEFAULT_MIN_SCORE, SCAN_EXCLUDED_DIRS, SKILL_MANIFEST_VARIANTS+from skillevaluator.tier1.commands import run_lint_scripts, run_quality_check+from skillevaluator.validators.policy import resolve_policy+from skillevaluator.validators.schema import SchemaValidator++if TYPE_CHECKING:+ from skillevaluator.models.result import ValidationResult++CHECK_QUALITY = "quality"+CHECK_SCHEMA = "schema"+CHECK_LINT_SCRIPTS = "lint-scripts"+CHECKS = (CHECK_QUALITY, CHECK_SCHEMA, CHECK_LINT_SCRIPTS)+LINT_FINDINGS_SHOWN = 3+++def parse_hook_path(value: str | Path) -> Path:+ """Interpret a pre-commit path in the host platform's own spelling.++ pre-commit passes tracked paths as the host spells them. On POSIX a+ backslash is a valid filename character, so it is kept as is; on Windows+ ``Path`` already treats it as a separator.+ """+ return Path(value)+++def _has_skill_manifest(directory: Path, cache: dict[Path, bool] | None = None) -> bool:+ """Return True when *directory* holds a manifest named exactly as in ``SKILL_MANIFEST_VARIANTS``.++ Names are compared as stored on disk, so the result is the same on+ case-insensitive (macOS, Windows) and case-sensitive (Linux) filesystems.+ When *cache* is given, each directory is listed at most once per cache.+ """+ if cache is not None and directory in cache:+ return cache[directory]+ try:+ found = any(child.name in SKILL_MANIFEST_VARIANTS and child.is_file() for child in directory.iterdir())+ except OSError:+ found = False+ if cache is not None:+ cache[directory] = found+ return found+++def _in_excluded_dir(directory: Path, limit: Path) -> bool:+ """Return True when *directory*, relative to *limit*, sits in a ``SCAN_EXCLUDED_DIRS`` folder.++ Folder-mode validation skips manifests under these folders (eval fixtures,+ version snapshots, results), so the hook does the same.+ """+ try:+ relative = directory.resolve().relative_to(limit)+ except (OSError, ValueError):+ return False+ return any(part in SCAN_EXCLUDED_DIRS for part in relative.parts)+++def skill_root_for(+ path: str | Path,+ *,+ cwd: Path | None = None,+ _cache: dict[Path, Path | None] | None = None,+ _manifest_cache: dict[Path, bool] | None = None,+) -> Path | None:+ """Return the nearest ancestor of *path* that contains ``SKILL.md`` or ``skill.md``.++ Deleted skills and paths that never sit under a skill are ignored. Search+ stops at *cwd* (the repository root pre-commit runs from) so a stray+ manifest above the project is not treated as a skill root. A manifest in+ a ``SCAN_EXCLUDED_DIRS`` folder (``evals/``, ``.versions/``, ...) is not+ a skill root either; the walk continues up to the real skill.++ ``_cache`` and ``_manifest_cache`` let ``collect_skill_roots`` share+ lookups across paths so each directory is listed once per invocation.+ """+ cwd = Path.cwd() if cwd is None else Path(cwd)+ candidate = parse_hook_path(path)+ if not candidate.is_absolute():+ candidate = cwd / candidate+ if candidate.name in SKILL_MANIFEST_VARIANTS:+ start = candidate.parent+ elif candidate.exists() and candidate.is_dir():+ start = candidate+ else:+ start = candidate.parent++ if _cache is not None and start in _cache:+ return _cache[start]++ try:+ limit = cwd.resolve()+ except OSError:+ limit = cwd++ root: Path | None = None+ for ancestor in [start, *start.parents]:+ if not _in_excluded_dir(ancestor, limit) and _has_skill_manifest(ancestor, _manifest_cache):+ try:+ root = ancestor.resolve()+ except OSError:+ root = ancestor+ break+ try:+ if ancestor.resolve() == limit:+ break+ except OSError:+ if ancestor == cwd:+ break+ if _cache is not None:+ _cache[start] = root+ return root+++def collect_skill_roots(paths: Iterable[str | Path], *, cwd: Path | None = None) -> list[Path]:+ """Return unique skill roots for *paths*, in first-seen order."""+ roots: list[Path] = []+ seen: set[Path] = set()+ start_cache: dict[Path, Path | None] = {}+ manifest_cache: dict[Path, bool] = {}+ for raw in paths:+ root = skill_root_for(raw, cwd=cwd, _cache=start_cache, _manifest_cache=manifest_cache)+ if root is None or root in seen:+ continue+ seen.add(root)+ roots.append(root)+ return roots+++def _quality_score(results: Sequence[ValidationResult]) -> float | None:+ for result in results:+ scores = result.metadata.get("quality_scores")+ if isinstance(scores, dict) and "overall_score" in scores:+ try:+ return float(scores["overall_score"])+ except (TypeError, ValueError):+ return None+ return None+++def _strip_location(message: str) -> str:+ """Return the first line of *message* without its absolute-path location.++ YAML parse errors carry context lines (a copy of the offending source), so+ only the first line is kept to hold the one-line-per-skill format.+ """+ first_line = message.splitlines()[0] if message else ""+ return first_line.split(" in /", 1)[0]+++def _first_error(results: Sequence[ValidationResult]) -> str:+ for result in results:+ for message in (*result.gate_failures, *result.errors):+ return _strip_location(message)+ return ""+++def _lint_findings(results: Sequence[ValidationResult]) -> list[str]:+ return [_strip_location(message) for result in results for message in (*result.errors, *result.warnings)]+++def format_lint_findings(results: Sequence[ValidationResult], *, limit: int = LINT_FINDINGS_SHOWN) -> list[str]:+ """Return indented lines for the first *limit* script lint findings."""+ findings = _lint_findings(results)+ lines = [f" {message}" for message in findings[:limit]]+ if len(findings) > limit:+ lines.append(f" ... and {len(findings) - limit} more (run `skillevaluator lint-scripts` for all)")+ return lines+++def format_result_line(+ skill_name: str,+ check: str,+ results: Sequence[ValidationResult],+ *,+ min_score: int,+) -> str:+ """Return one compact PASS/FAIL line for a skill."""+ passed = all(result.passed for result in results)+ status = "PASS" if passed else "FAIL"+ extra = ""+ if check == CHECK_QUALITY:+ score = _quality_score(results)+ if score is not None:+ extra = f" {score:.1f}/100"+ if not passed:+ if score is not None and score < min_score:+ extra += f" (min {min_score})"+ elif detail := _first_error(results):+ extra += f" {detail}"+ elif check == CHECK_LINT_SCRIPTS:+ count = len(_lint_findings(results))+ extra = f" {count} finding{'' if count == 1 else 's'}"+ elif not passed:+ detail = _first_error(results)+ if detail:+ extra = f" {detail}"+ return f"{status} {skill_name} {check}{extra}"+++def run_check(+ check: str, skill_root: Path, *, min_score: int, quality_config: Path | None = None+) -> list[ValidationResult]:+ """Run one offline check against a single skill directory. Never writes reports.++ *quality_config* replaces the packaged quality-default.yaml for the quality+ check, the same way ``quality-check --quality-config`` does.+ """+ if check == CHECK_QUALITY:+ return run_quality_check(skill_root, min_score=min_score, quality_config=quality_config)+ if check == CHECK_SCHEMA:+ # Same policy as ``validate``: ``SKILLEVALUATOR_PROFILE`` picks the profile.+ return [SchemaValidator(policy=resolve_policy()).validate(skill_root)]+ if check == CHECK_LINT_SCRIPTS:+ return run_lint_scripts(skill_root)+ raise ValueError(f"Unknown check: {check}")+++def run_precommit(+ check: str,+ paths: Sequence[str | Path],+ *,+ min_score: int = QUALITY_DEFAULT_MIN_SCORE,+ quality_config: Path | None = None,+ cwd: Path | None = None,+) -> tuple[int, list[str]]:+ """Run *check* once per skill touched by *paths*.++ Returns ``(exit_code, lines)``. Exit code is 1 when any skill fails and 0+ otherwise, including when every path is outside a skill or the skill was+ deleted. A check that raises for one skill is reported as a FAIL line for+ that skill and the remaining skills are still checked.+ """+ if check not in CHECKS:+ raise ValueError(f"Unknown check: {check}")+ lines: list[str] = []+ failed = False+ for root in collect_skill_roots(paths, cwd=cwd):+ try:+ results = run_check(check, root, min_score=min_score, quality_config=quality_config)+ except Exception as exc: # one broken skill must not hide the others+ lines.append(f"FAIL {root.name} {check} error: {type(exc).__name__}: {exc}")+ failed = True+ continue+ line = format_result_line(root.name, check, results, min_score=min_score)+ lines.append(line)+ if check == CHECK_LINT_SCRIPTS:+ lines.extend(format_lint_findings(results))+ if not all(result.passed for result in results):+ failed = True+ return (1 if failed else 0, lines)diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.jsonindex 86abb786..d18d7ad8 100644--- a/tests/golden/cli_surface.json+++ b/tests/golden/cli_surface.json@@ -1714,6 +1714,48 @@}]},+ "precommit-run": {+ "params": [+ {+ "default": "70",+ "name": "min_score",+ "opts": [+ "--min-score"+ ],+ "param_type": "option",+ "type": "integer"+ },+ {+ "name": "quality_config",+ "opts": [+ "--quality-config"+ ],+ "param_type": "option",+ "type": "file"+ },+ {+ "choices": [+ "quality",+ "schema",+ "lint-scripts"+ ],+ "name": "check",+ "opts": [+ "check"+ ],+ "param_type": "argument",+ "required": true+ },+ {+ "name": "paths",+ "opts": [+ "paths"+ ],+ "param_type": "argument",+ "type": "text"+ }+ ]+ },"quality-check": {"params": [{diff --git a/tests/test_precommit.py b/tests/test_precommit.pynew file mode 100644index 00000000..10a340c4--- /dev/null+++ b/tests/test_precommit.py@@ -0,0 +1,624 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++from __future__ import annotations++import os+import re+import shlex+import socket+import subprocess+import sys+from pathlib import Path++import pytest+import yaml+from click.testing import CliRunner++from skillevaluator.cli import cli+from skillevaluator.constants import DEFAULT_ALLOWED_SKILL_DIRS+from skillevaluator.precommit import (+ CHECKS,+ collect_skill_roots,+ run_precommit,+ skill_root_for,+)+from skillevaluator.tier1.commands import run_quality_check++REPO = Path(__file__).resolve().parents[1]++_VALID_SKILL_MD = """\+---+name: {name}+description: A {name} skill used to test pre-commit path mapping. Use when checking offline Tier 1 hooks.+metadata:+ author: Test Author <[email protected]>+---++# {title}++## Instructions++1. Run the documented command.++## Examples++Example of {name}.+"""+++def _write_skill(parent: Path, name: str, *, body: str | None = None) -> Path:+ skill = parent / name+ skill.mkdir(parents=True)+ text = body if body is not None else _VALID_SKILL_MD.format(name=name, title=name.replace("-", " ").title())+ (skill / "SKILL.md").write_text(text, encoding="utf-8")+ return skill+++def test_skill_root_maps_nested_skill_not_outer(tmp_path: Path) -> None:+ outer = _write_skill(tmp_path, "outer")+ inner = _write_skill(outer, "inner")+ script = inner / "scripts" / "run.py"+ script.parent.mkdir()+ script.write_text("print(0)\n", encoding="utf-8")++ assert skill_root_for(script, cwd=tmp_path) == inner.resolve()+ assert skill_root_for(inner / "SKILL.md", cwd=tmp_path) == inner.resolve()+ assert skill_root_for(outer / "SKILL.md", cwd=tmp_path) == outer.resolve()+++def test_skill_root_ignores_files_outside_a_skill(tmp_path: Path) -> None:+ _write_skill(tmp_path / "skills", "sample")+ readme = tmp_path / "README.md"+ readme.write_text("notes\n", encoding="utf-8")+ stray = tmp_path / "docs" / "guide.md"+ stray.parent.mkdir()+ stray.write_text("guide\n", encoding="utf-8")++ assert skill_root_for(readme, cwd=tmp_path) is None+ assert skill_root_for(stray, cwd=tmp_path) is None+ assert skill_root_for("README.md", cwd=tmp_path) is None+++def test_skill_root_skips_deleted_skill(tmp_path: Path) -> None:+ skills = tmp_path / "skills"+ kept = _write_skill(skills, "kept")+ deleted = skills / "gone" / "scripts" / "run.py"++ assert skill_root_for(deleted, cwd=tmp_path) is None+ assert skill_root_for(skills / "gone" / "SKILL.md", cwd=tmp_path) is None+ assert skill_root_for(kept / "SKILL.md", cwd=tmp_path) == kept.resolve()+++def test_skill_root_skips_version_snapshot_manifest(tmp_path: Path) -> None:+ skill = _write_skill(tmp_path / "skills", "demo-skill")+ snapshot = _write_skill(skill / ".versions", "1.0.0")++ assert skill_root_for(snapshot / "SKILL.md", cwd=tmp_path) == skill.resolve()+ assert skill_root_for("skills/demo-skill/.versions/1.0.0/SKILL.md", cwd=tmp_path) == skill.resolve()+ assert run_precommit("schema", [snapshot / "SKILL.md"], cwd=tmp_path) == (0, ["PASS demo-skill schema"])+++def test_skill_root_skips_eval_fixture_manifest(tmp_path: Path) -> None:+ skill = _write_skill(tmp_path / "skills", "demo-skill")+ fixture = _write_skill(skill / "evals" / "fixtures", "Bad_Fixture", body="not a valid manifest\n")+ data = fixture / "data.json"+ data.write_text("{}\n", encoding="utf-8")++ assert skill_root_for(fixture / "SKILL.md", cwd=tmp_path) == skill.resolve()+ assert skill_root_for(data, cwd=tmp_path) == skill.resolve()+ assert collect_skill_roots([fixture / "SKILL.md", data], cwd=tmp_path) == [skill.resolve()]+++def test_skill_root_ignores_excluded_dir_names_above_cwd(tmp_path: Path) -> None:+ repo = tmp_path / "results" / "repo"+ skill = _write_skill(repo / "skills", "demo-skill")++ assert skill_root_for(skill / "SKILL.md", cwd=repo) == skill.resolve()+++def test_collect_skill_roots_lists_each_directory_once(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ skills = tmp_path / "skills"+ alpha = _write_skill(skills, "alpha")+ beta = _write_skill(alpha, "beta")+ alpha_scripts = alpha / "scripts"+ beta_scripts = beta / "scripts"+ alpha_scripts.mkdir()+ beta_scripts.mkdir()+ staged: list[Path] = []+ for index in range(200):+ for folder in (alpha_scripts, beta_scripts):+ script = folder / f"run_{index}.py"+ script.write_text("print(0)\n", encoding="utf-8")+ staged.append(script.relative_to(tmp_path))+ stray = tmp_path / "docs" / "guide.md"+ stray.parent.mkdir()+ stray.write_text("guide\n", encoding="utf-8")+ staged.append(Path("docs/guide.md"))++ listed: list[Path] = []+ real_iterdir = Path.iterdir++ def counting_iterdir(self: Path):+ listed.append(self)+ return real_iterdir(self)++ monkeypatch.setattr(Path, "iterdir", counting_iterdir)++ roots = collect_skill_roots(staged, cwd=tmp_path)++ assert roots == [alpha.resolve(), beta.resolve()]+ assert len(listed) == len(set(listed))+ assert len(listed) <= 8++[email protected](sys.platform != "win32", reason="backslash is a separator only on Windows")+def test_skill_root_accepts_windows_style_separators(tmp_path: Path) -> None:+ skill = _write_skill(tmp_path / "skills", "win-skill")+ script = skill / "scripts" / "run.py"+ script.parent.mkdir()+ script.write_text("print(0)\n", encoding="utf-8")++ mapped = skill_root_for(r"skills\win-skill\scripts\run.py", cwd=tmp_path)+ assert mapped == skill.resolve()+ assert skill_root_for(r"skills\win-skill\SKILL.md", cwd=tmp_path) == skill.resolve()++[email protected](sys.platform == "win32", reason="backslash is a valid filename character only on POSIX")+def test_skill_root_keeps_literal_backslash_in_posix_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ skill = _write_skill(tmp_path, "literal\\skill", body="# Broken\n\nNo frontmatter.\n")+ assert skill.name == "literal\\skill"+ # A same-named slash path must not be found instead.+ assert not (tmp_path / "literal" / "skill").exists()++ relative = "literal\\skill/SKILL.md"+ assert skill_root_for(relative, cwd=tmp_path) == skill.resolve()++ code, lines = run_precommit("schema", [relative], cwd=tmp_path)+ assert code == 1+ assert len(lines) == 1+ assert lines[0].startswith("FAIL literal\\skill schema")++ monkeypatch.chdir(tmp_path)+ result = CliRunner().invoke(cli, ["precommit-run", "schema", relative])+ assert result.exit_code == 1, result.output+ assert "FAIL literal\\skill schema" in result.output+++def test_collect_skill_roots_deduplicates_and_preserves_order(tmp_path: Path) -> None:+ skills = tmp_path / "skills"+ first = _write_skill(skills, "alpha")+ second = _write_skill(skills, "beta")+ (first / "scripts").mkdir()+ (first / "scripts" / "a.py").write_text("print(1)\n", encoding="utf-8")+ (first / "references").mkdir()+ (first / "references" / "note.md").write_text("note\n", encoding="utf-8")++ roots = collect_skill_roots(+ [+ first / "scripts" / "a.py",+ first / "SKILL.md",+ second / "SKILL.md",+ first / "references" / "note.md",+ tmp_path / "README.md",+ ],+ cwd=tmp_path,+ )+ assert roots == [first.resolve(), second.resolve()]+++def test_precommit_quality_exit_codes(tmp_path: Path) -> None:+ skill = _write_skill(tmp_path, "sample-skill")+ paths = [str(skill / "SKILL.md")]++ passed_code, passed_lines = run_precommit("quality", paths, min_score=0, cwd=tmp_path)+ assert passed_code == 0+ assert len(passed_lines) == 1+ assert passed_lines[0].startswith("PASS sample-skill quality ")+ assert "/100" in passed_lines[0]++ failed_code, failed_lines = run_precommit("quality", paths, min_score=100, cwd=tmp_path)+ assert failed_code == 1+ assert failed_lines[0].startswith("FAIL sample-skill quality ")+ assert "(min 100)" in failed_lines[0]+++def test_precommit_quality_names_error_when_score_meets_minimum(tmp_path: Path) -> None:+ body = _VALID_SKILL_MD.format(name="xml-skill", title="Xml Skill").replace(+ "description: A xml-skill", "description: A <b>xml</b> skill"+ )+ skill = _write_skill(tmp_path, "xml-skill", body=body)++ code, lines = run_precommit("quality", [str(skill / "SKILL.md")], min_score=0, cwd=tmp_path)+ assert code == 1+ assert lines[0].startswith("FAIL xml-skill quality ")+ assert "(min " not in lines[0]+ assert lines[0].endswith("[QUALITY-HIGH] Description contains XML tags")+++def test_precommit_schema_exit_codes(tmp_path: Path) -> None:+ valid = _write_skill(tmp_path, "valid-skill")+ invalid = _write_skill(+ tmp_path,+ "broken-skill",+ body="# Broken\n\nNo frontmatter.\n",+ )++ code, lines = run_precommit("schema", [str(valid / "SKILL.md")], cwd=tmp_path)+ assert code == 0+ assert lines == ["PASS valid-skill schema"]++ code, lines = run_precommit("schema", [str(invalid / "SKILL.md")], cwd=tmp_path)+ assert code == 1+ assert lines[0].startswith("FAIL broken-skill schema ")+++def test_precommit_lint_scripts_is_advisory_pass(tmp_path: Path) -> None:+ skill = _write_skill(tmp_path, "lint-skill")+ script = skill / "scripts" / "run.py"+ script.parent.mkdir()+ script.write_text("print(1)\n", encoding="utf-8")++ code, lines = run_precommit("lint-scripts", [str(script)], cwd=tmp_path)+ assert code == 0+ assert lines[0].startswith("PASS lint-skill lint-scripts ")+ assert lines[0].endswith(" findings")+++def test_precommit_lint_scripts_prints_count_and_first_findings(tmp_path: Path) -> None:+ skill = _write_skill(tmp_path, "lint-skill")+ script = skill / "scripts" / "run.py"+ script.parent.mkdir()+ script.write_text("x = 42\nprint(x * 3600)\n", encoding="utf-8")++ code, lines = run_precommit("lint-scripts", [str(script)], cwd=tmp_path)+ assert code == 0+ assert lines[0] == "PASS lint-skill lint-scripts 4 findings"+ assert len(lines) == 5+ assert all(line.startswith(" ") for line in lines[1:])+ assert all(" in /" not in line for line in lines[1:])+ assert any("SCRIPT_LINT" in line for line in lines[1:4])+ assert lines[4] == " ... and 1 more (run `skillevaluator lint-scripts` for all)"+++def test_lint_scripts_hook_is_verbose() -> None:+ hooks = yaml.safe_load((REPO / ".pre-commit-hooks.yaml").read_text(encoding="utf-8"))+ by_id = {hook["id"]: hook for hook in hooks}+ assert by_id["skillevaluator-lint-scripts"]["verbose"] is True+++def test_precommit_ignores_unrelated_and_deleted_paths(tmp_path: Path) -> None:+ code, lines = run_precommit(+ "schema",+ ["README.md", "skills/missing/SKILL.md", "docs/notes.md"],+ cwd=tmp_path,+ )+ assert code == 0+ assert lines == []++[email protected]("check", CHECKS)+def test_precommit_does_not_write_reports(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, check: str) -> None:+ monkeypatch.chdir(tmp_path)+ skill = _write_skill(tmp_path, "sample-skill")+ script = skill / "scripts" / "run.py"+ script.parent.mkdir()+ script.write_text("print(1)\n", encoding="utf-8")+ before = sorted(tmp_path.rglob("*"))++ code, _lines = run_precommit(check, [str(skill / "SKILL.md"), str(script)], min_score=0, cwd=tmp_path)++ assert code == 0+ assert sorted(tmp_path.rglob("*")) == before+++def test_precommit_fails_when_an_earlier_skill_fails(tmp_path: Path) -> None:+ broken = _write_skill(tmp_path, "broken-skill", body="# Broken\n\nNo frontmatter.\n")+ valid = _write_skill(tmp_path, "valid-skill")++ code, lines = run_precommit("schema", [str(broken / "SKILL.md"), str(valid / "SKILL.md")], cwd=tmp_path)++ assert code == 1+ assert len(lines) == 2+ assert lines[0].startswith("FAIL broken-skill schema")+ assert lines[1] == "PASS valid-skill schema"+++def test_precommit_reports_skill_that_raises_and_checks_the_rest(tmp_path: Path) -> None:+ broken = tmp_path / "latin1-skill"+ broken.mkdir()+ text = _VALID_SKILL_MD.format(name="latin1-skill", title="Caf\u00e9 Skill")+ (broken / "SKILL.md").write_bytes(text.encode("latin-1"))+ valid = _write_skill(tmp_path, "valid-skill")++ code, lines = run_precommit(+ "quality", [str(broken / "SKILL.md"), str(valid / "SKILL.md")], min_score=0, cwd=tmp_path+ )++ assert code == 1+ assert len(lines) == 2+ assert lines[0].startswith("FAIL latin1-skill quality error: UnicodeDecodeError: ")+ assert lines[1].startswith("PASS valid-skill quality")+++def test_skill_root_finds_repo_root_skill_from_relative_path(tmp_path: Path) -> None:+ (tmp_path / "SKILL.md").write_text(_VALID_SKILL_MD.format(name="root-skill", title="Root Skill"), encoding="utf-8")+ (tmp_path / "scripts").mkdir()+ (tmp_path / "scripts" / "a.py").write_text("print(1)\n", encoding="utf-8")++ assert skill_root_for("scripts/a.py", cwd=tmp_path) == tmp_path.resolve()+ assert skill_root_for("SKILL.md", cwd=tmp_path) == tmp_path.resolve()+++def test_skill_root_ignores_manifest_above_cwd(tmp_path: Path) -> None:+ (tmp_path / "SKILL.md").write_text(_VALID_SKILL_MD.format(name="outside", title="Outside"), encoding="utf-8")+ repo = tmp_path / "repo"+ (repo / "scripts").mkdir(parents=True)+ (repo / "scripts" / "a.py").write_text("print(1)\n", encoding="utf-8")++ assert skill_root_for("scripts/a.py", cwd=repo) is None+ assert skill_root_for(repo / "scripts" / "a.py", cwd=repo) is None+ assert run_precommit("schema", ["scripts/a.py"], cwd=repo) == (0, [])+++def test_precommit_cli_exit_codes(tmp_path: Path) -> None:+ skill = _write_skill(tmp_path, "cli-skill")+ runner = CliRunner()++ passed = runner.invoke(+ cli,+ ["precommit-run", "--min-score", "70", "quality", str(skill / "SKILL.md")],+ )+ assert passed.exit_code == 0, passed.output+ assert "PASS cli-skill quality" in passed.output++ failed = runner.invoke(+ cli,+ ["precommit-run", "--min-score", "100", "quality", str(skill / "SKILL.md")],+ )+ assert failed.exit_code == 1, failed.output+ assert "FAIL cli-skill quality" in failed.output+ assert "(min 100)" in failed.output++ # pre-commit appends hook args after the entry, then filenames.+ interleaved = runner.invoke(+ cli,+ ["precommit-run", "quality", "--min-score", "100", str(skill / "SKILL.md")],+ )+ assert interleaved.exit_code == 1, interleaved.output+ assert "(min 100)" in interleaved.output+++def test_precommit_cli_maps_relative_paths_from_cwd(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _write_skill(tmp_path / "skills", "valid-skill")+ _write_skill(tmp_path / "skills", "broken-skill", body="# Broken\n\nNo frontmatter.\n")+ monkeypatch.chdir(tmp_path)+ runner = CliRunner()++ passed = runner.invoke(cli, ["precommit-run", "schema", "skills/valid-skill/SKILL.md", "README.md"])+ assert passed.exit_code == 0, passed.output+ assert passed.output.splitlines() == ["PASS valid-skill schema"]++ failed = runner.invoke(+ cli,+ ["precommit-run", "schema", "skills/broken-skill/SKILL.md", "skills/valid-skill/SKILL.md"],+ )+ assert failed.exit_code == 1, failed.output+ output = failed.output.splitlines()+ assert len(output) == 2+ assert output[0].startswith("FAIL broken-skill schema")+ assert output[1] == "PASS valid-skill schema"+++def test_precommit_run_is_hidden_from_main_help() -> None:+ runner = CliRunner()+ help_result = runner.invoke(cli, ["--help"])+ assert help_result.exit_code == 0+ assert "precommit-run" not in help_result.output++ command_help = runner.invoke(cli, ["precommit-run", "--help"])+ assert command_help.exit_code == 0+ assert "quality" in command_help.output+ assert "schema" in command_help.output+ assert "lint-scripts" in command_help.output+++def test_precommit_hooks_yaml_entries_resolve_to_commands() -> None:+ hooks_path = REPO / ".pre-commit-hooks.yaml"+ hooks = yaml.safe_load(hooks_path.read_text(encoding="utf-8"))+ assert isinstance(hooks, list)+ assert hooks, "expected at least one hook"++ runner = CliRunner()+ ids = []+ for hook in hooks:+ assert hook["language"] == "python"+ assert hook.get("files")+ assert hook.get("require_serial") is True, hook["id"]+ ids.append(hook["id"])+ parts = shlex.split(hook["entry"])+ assert parts[0] == "skillevaluator"+ assert parts[1:]+ result = runner.invoke(cli, [*parts[1:], "--help"])+ assert result.exit_code == 0, f"{hook['id']}: {result.output}"+ command_name = parts[1]+ assert command_name in cli.commands+ if len(parts) > 2:+ check = parts[2]+ assert check in CHECKS++ assert ids == [+ "skillevaluator-quality",+ "skillevaluator-schema",+ "skillevaluator-lint-scripts",+ ]+++def test_precommit_hooks_yaml_files_cover_every_allowed_skill_dir() -> None:+ hooks = yaml.safe_load((REPO / ".pre-commit-hooks.yaml").read_text(encoding="utf-8"))+ for hook in hooks:+ pattern = re.compile(hook["files"])+ assert pattern.search("skills/x/SKILL.md"), hook["id"]+ assert pattern.search("skills/x/skill.md"), hook["id"]+ for directory in sorted(DEFAULT_ALLOWED_SKILL_DIRS):+ assert pattern.search(f"skills/x/{directory}/file.py"), f"{hook['id']}: {directory}/"+ assert pattern.search("SKILL.md"), hook["id"]+ assert pattern.search("scripts/run.py"), hook["id"]+ for path in (+ "README.md",+ "docs/guide.md",+ "src/skillevaluator/cli.py",+ "skills/x/notes.md",+ "skills/x/SKILL.md.bak",+ "skills/x/Skill.md",+ "skills/x/myscripts/run.py",+ "skills/x/scripts.py",+ ):+ assert not pattern.search(path), f"{hook['id']}: {path}"++[email protected]("check", CHECKS)+def test_precommit_checks_open_no_sockets_or_subprocesses(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, check: str+) -> None:+ attempts: list[str] = []++ def _blocked(name: str):+ def _raise(*args, **kwargs):+ attempts.append(name)+ raise AssertionError(f"pre-commit check attempted {name}")++ return _raise++ monkeypatch.setattr(socket.socket, "connect", _blocked("socket.connect"))+ monkeypatch.setattr(socket.socket, "connect_ex", _blocked("socket.connect_ex"))+ monkeypatch.setattr(socket, "create_connection", _blocked("socket.create_connection"))+ monkeypatch.setattr(socket, "getaddrinfo", _blocked("socket.getaddrinfo"))+ monkeypatch.setattr(subprocess.Popen, "__init__", _blocked("subprocess.Popen"))+ monkeypatch.setattr(os, "system", _blocked("os.system"))+ if hasattr(os, "posix_spawn"):+ monkeypatch.setattr(os, "posix_spawn", _blocked("os.posix_spawn"))++ skill = _write_skill(tmp_path, "offline-skill")+ script = skill / "scripts" / "run.py"+ script.parent.mkdir()+ script.write_text("import os\nprint(os.getcwd())\n", encoding="utf-8")++ code, lines = run_precommit(check, [str(skill / "SKILL.md"), str(script)], min_score=0, cwd=tmp_path)++ assert attempts == []+ assert code == 0, lines+ assert lines[0].startswith(f"PASS offline-skill {check}")+++def _write_lowercase_manifest_skill(parent: Path, name: str) -> Path:+ skill = parent / name+ skill.mkdir(parents=True)+ text = _VALID_SKILL_MD.format(name=name, title=name.replace("-", " ").title())+ (skill / "skill.md").write_text(text, encoding="utf-8")+ return skill+++def test_skill_root_finds_lowercase_manifest(tmp_path: Path) -> None:+ skill = _write_lowercase_manifest_skill(tmp_path / "skills", "lower-skill")+ (skill / "scripts").mkdir()+ (skill / "scripts" / "a.py").write_text("print(1)\n", encoding="utf-8")++ assert skill_root_for(skill / "skill.md", cwd=tmp_path) == skill.resolve()+ assert skill_root_for("skills/lower-skill/scripts/a.py", cwd=tmp_path) == skill.resolve()+++def test_skill_root_matches_manifest_names_exactly(tmp_path: Path) -> None:+ # A differently cased name such as Skill.md is not a manifest on any OS,+ # so a case-insensitive filesystem must not map it to a skill either.+ skill = tmp_path / "skills" / "odd-case"+ skill.mkdir(parents=True)+ (skill / "Skill.md").write_text("# Odd\n", encoding="utf-8")++ assert skill_root_for(skill / "Skill.md", cwd=tmp_path) is None+++def test_precommit_schema_reports_lowercase_manifest(tmp_path: Path) -> None:+ skill = _write_lowercase_manifest_skill(tmp_path / "skills", "lower-skill")++ code, lines = run_precommit("schema", [str(skill / "skill.md")], cwd=tmp_path)++ assert code == 1+ assert len(lines) == 1+ assert lines[0].startswith("FAIL lower-skill schema")+ assert "non-canonical name 'skill.md'" in lines[0]+++def _score_from_line(line: str) -> float:+ match = re.search(r" (\d+\.\d)/100", line)+ assert match, line+ return float(match.group(1))+++def test_precommit_quality_uses_quality_config(tmp_path: Path) -> None:+ skill = _write_skill(tmp_path, "config-skill")+ config = tmp_path / "quality.yaml"+ config.write_text("expected_headers: []\n", encoding="utf-8")+ paths = [str(skill / "SKILL.md")]++ _code, default_lines = run_precommit("quality", paths, min_score=0, cwd=tmp_path)+ _code, config_lines = run_precommit("quality", paths, min_score=0, quality_config=config, cwd=tmp_path)++ (expected,) = run_quality_check(skill, min_score=0, quality_config=config)+ expected_score = float(expected.metadata["quality_scores"]["overall_score"])+ assert _score_from_line(config_lines[0]) == pytest.approx(round(expected_score, 1))+ assert _score_from_line(config_lines[0]) > _score_from_line(default_lines[0])+++def test_precommit_cli_forwards_quality_config(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _write_skill(tmp_path / "skills", "config-skill")+ (tmp_path / "quality.yaml").write_text("expected_headers: []\n", encoding="utf-8")+ monkeypatch.chdir(tmp_path)+ runner = CliRunner()+ path = "skills/config-skill/SKILL.md"++ default = runner.invoke(cli, ["precommit-run", "quality", "--min-score", "0", path])+ # pre-commit appends hook args after the entry, then filenames.+ configured = runner.invoke(+ cli, ["precommit-run", "quality", "--min-score", "0", "--quality-config", "quality.yaml", path]+ )++ assert default.exit_code == 0, default.output+ assert configured.exit_code == 0, configured.output+ assert _score_from_line(configured.output) > _score_from_line(default.output)+++def test_precommit_cli_rejects_invalid_quality_config(tmp_path: Path) -> None:+ skill = _write_skill(tmp_path, "config-skill")+ runner = CliRunner()++ missing = runner.invoke(+ cli, ["precommit-run", "quality", "--quality-config", str(tmp_path / "missing.yaml"), str(skill / "SKILL.md")]+ )+ assert missing.exit_code == 2+ assert "does not exist" in missing.output+++def test_precommit_schema_follows_the_profile_env_var(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ skill = _write_skill(tmp_path, "profile-skill")++ monkeypatch.delenv("SKILLEVALUATOR_PROFILE", raising=False)+ code, lines = run_precommit("schema", [str(skill / "SKILL.md")], cwd=tmp_path)+ assert code == 0+ assert lines == ["PASS profile-skill schema"]++ monkeypatch.setenv("SKILLEVALUATOR_PROFILE", "registry")+ code, lines = run_precommit("schema", [str(skill / "SKILL.md")], cwd=tmp_path)+ assert code == 1+ assert lines[0].startswith("FAIL profile-skill schema ")+++def test_precommit_fail_line_stays_on_one_line_for_yaml_errors(tmp_path: Path) -> None:+ body = "---\nname: bad-yaml\ndescription: [unclosed\nversion: 1.0.0\n---\n\n# Bad\n"+ skill = _write_skill(tmp_path, "bad-yaml", body=body)++ code, lines = run_precommit("schema", [str(skill / "SKILL.md")], cwd=tmp_path)+ assert code == 1+ assert len(lines) == 1+ assert "\n" not in lines[0]+ assert lines[0].startswith("FAIL bad-yaml schema ")