#!/usr/bin/env python3 """Validate Agent Skill frontmatter.""" from __future__ import annotations import re import shutil import subprocess import tempfile from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parents[1] SKILLS = ROOT / "skills" NAME_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$") def skill_files() -> list[Path]: return sorted(SKILLS.glob("*/SKILL.md")) def frontmatter(path: Path) -> str: lines = path.read_text(encoding="utf-8").splitlines() if not lines or lines[0] != "---": raise ValueError("missing opening frontmatter fence") for index, line in enumerate(lines[1:], start=2): if line == "---": return "\n".join(lines[1 : index - 1]) + "\n" raise ValueError("missing closing frontmatter fence") def parse_yaml_with_pyyaml(text: str) -> dict[str, Any] | None: try: import yaml # type: ignore[import-untyped] except ModuleNotFoundError: return None data = yaml.safe_load(text) if not isinstance(data, dict): raise ValueError("frontmatter is not a mapping") return data def lint_yaml_with_yamlfmt(text: str) -> None: yamlfmt = shutil.which("yamlfmt") if not yamlfmt: raise ValueError("install PyYAML or run under mise so yamlfmt is available") with tempfile.TemporaryDirectory() as tmp: path = Path(tmp) / "frontmatter.yaml" path.write_text(text, encoding="utf-8") result = subprocess.run( [yamlfmt, "-lint", str(path)], capture_output=True, check=False, text=True, ) if result.returncode: raise ValueError((result.stderr or result.stdout).strip()) def parse_shallow_yaml(text: str) -> dict[str, str]: data: dict[str, str] = {} lines = text.splitlines() index = 0 while index < len(lines): line = lines[index] index += 1 if not line or line.startswith(" "): continue match = re.match(r"^([A-Za-z0-9_-]+):(?:\s*(.*))?$", line) if not match: continue key, value = match.groups() value = value or "" if value in {">", "|-", "|"}: block: list[str] = [] while index < len(lines) and (not lines[index] or lines[index].startswith(" ")): block.append(lines[index].strip()) index += 1 value = "\n".join(block).strip() if (value.startswith('"') and value.endswith('"')) or ( value.startswith("'") and value.endswith("'") ): value = value[1:-1] data[key] = value return data def parse_frontmatter(text: str) -> dict[str, Any]: data = parse_yaml_with_pyyaml(text) if data is not None: return data lint_yaml_with_yamlfmt(text) return parse_shallow_yaml(text) def validate(path: Path) -> list[str]: errors: list[str] = [] try: data = parse_frontmatter(frontmatter(path)) except Exception as error: # noqa: BLE001 return [str(error)] name = data.get("name") description = data.get("description") if not isinstance(name, str) or not name: errors.append("missing string field: name") elif not NAME_RE.fullmatch(name): errors.append(f"invalid skill name: {name!r}") elif path.parent.name != name: errors.append(f"directory/name mismatch: {path.parent.name!r} != {name!r}") if not isinstance(description, str) or not description.strip(): errors.append("missing string field: description") elif len(description) > 1024: errors.append(f"description too long: {len(description)} > 1024") return errors def main() -> int: failed = False for path in skill_files(): errors = validate(path) if not errors: continue failed = True rel = path.relative_to(ROOT) for error in errors: print(f"{rel}: {error}") return int(failed) if __name__ == "__main__": raise SystemExit(main())