Yokan / rebuild
Course 1 8624561

validate_skills.py

.codex/skills/compose-kotlin-agent-skills/scripts/validate_skills.py

configuration / resource418 lines
1#!/usr/bin/env python32"""3Validate all SKILL.md files in the compose-kotlin-agent-skills repository.45Checks:6  - YAML frontmatter exists with required keys: name, description7  - name field constraints (kebab-case, max 64 chars, no reserved words)8  - description constraints (non-empty, max 1024 chars, no XML tags)9  - Internal markdown links resolve to existing files10  - SKILL.md body line count warning if > 500 lines11  - Optional: lock-file parity (--lock-check api/skills.lock)12  - Optional: JUnit XML report (--junit results.xml)1314Exit code 0 = pass, 1 = failure (for CI).15"""1617from __future__ import annotations1819import argparse20import hashlib21import re22import sys23import xml.etree.ElementTree as ET24from dataclasses import dataclass, field25from pathlib import Path2627FRONTMATTER_RE = re.compile(r"\A---\s*\n(.*?)\n---\s*\n", re.DOTALL)28LINK_RE = re.compile(r"\]\(([^)]+)\)")29NAME_RE = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$")30RESERVED_NAME_SUBSTRINGS = ("anthropic", "claude")31MAX_NAME_LEN = 6432MAX_DESC_LEN = 102433MAX_BODY_LINES = 50034SKIP_LINK_PREFIXES = ("http://", "https://", "mailto:", "#")353637@dataclass38class Issue:39    path: Path40    message: str41    severity: str = "error"  # error | warning424344@dataclass45class ValidationResult:46    issues: list[Issue] = field(default_factory=list)4748    @property49    def errors(self) -> list[Issue]:50        return [i for i in self.issues if i.severity == "error"]5152    @property53    def warnings(self) -> list[Issue]:54        return [i for i in self.issues if i.severity == "warning"]5556    def ok(self, strict: bool) -> bool:57        if self.errors:58            return False59        if strict and self.warnings:60            return False61        return True626364def parse_simple_yaml(block: str) -> dict[str, str]:65    """Parse minimal YAML frontmatter (key: value and multiline > descriptions)."""66    data: dict[str, str] = {}67    current_key: str | None = None68    multiline_buffer: list[str] = []6970    for line in block.splitlines():71        if line.strip().startswith("#"):72            continue73        if re.match(r"^[A-Za-z0-9_-]+:\s*>", line):74            current_key = line.split(":", 1)[0].strip()75            multiline_buffer = []76            continue77        if current_key and (line.startswith(" ") or line.startswith("\t")):78            multiline_buffer.append(line.strip())79            continue80        if current_key and multiline_buffer:81            data[current_key] = " ".join(multiline_buffer).strip()82            current_key = None83            multiline_buffer = []84        match = re.match(r"^([A-Za-z0-9_-]+):\s*(.*)$", line)85        if match:86            key, value = match.group(1), match.group(2).strip()87            if value.startswith('"') and value.endswith('"'):88                value = value[1:-1]89            elif value.startswith("'") and value.endswith("'"):90                value = value[1:-1]91            data[key] = value92    if current_key and multiline_buffer:93        data[current_key] = " ".join(multiline_buffer).strip()94    return data959697def validate_frontmatter(path: Path, content: str, result: ValidationResult) -> str | None:98    match = FRONTMATTER_RE.match(content)99    if not match:100        result.issues.append(Issue(path, "Missing YAML frontmatter (must start with ---)"))101        return None102103    fm = parse_simple_yaml(match.group(1))104    body = content[match.end() :]105106    if "name" not in fm or not fm["name"].strip():107        result.issues.append(Issue(path, "Frontmatter missing required field: name"))108    else:109        name = fm["name"].strip()110        if len(name) > MAX_NAME_LEN:111            result.issues.append(Issue(path, f"name exceeds {MAX_NAME_LEN} chars: {len(name)}"))112        if not NAME_RE.match(name):113            result.issues.append(114                Issue(path, f"name must be kebab-case lowercase: '{name}'")115            )116        for reserved in RESERVED_NAME_SUBSTRINGS:117            if reserved in name:118                result.issues.append(Issue(path, f"name must not contain '{reserved}'"))119120    if "description" not in fm or not fm["description"].strip():121        result.issues.append(Issue(path, "Frontmatter missing required field: description"))122    else:123        desc = fm["description"].strip()124        if len(desc) > MAX_DESC_LEN:125            result.issues.append(126                Issue(path, f"description exceeds {MAX_DESC_LEN} chars: {len(desc)}")127            )128        if "<" in desc or ">" in desc:129            result.issues.append(Issue(path, "description must not contain XML tags"))130        if "Use when" not in desc and "use when" not in desc.lower():131            result.issues.append(132                Issue(133                    path,134                    "description should include 'Use when...' trigger phrases",135                    severity="warning",136                )137            )138139    body_lines = body.count("\n") + (1 if body.strip() else 0)140    if body_lines > MAX_BODY_LINES:141        result.issues.append(142            Issue(143                path,144                f"SKILL.md body has {body_lines} lines (max recommended {MAX_BODY_LINES})",145                severity="warning",146            )147        )148149    return body150151152def resolve_link(skill_path: Path, repo_root: Path, target: str) -> Path | None:153    target = target.strip()154    if not target or any(target.startswith(p) for p in SKIP_LINK_PREFIXES):155        return None156    if target.startswith("/"):157        candidate = repo_root / target.lstrip("/")158    else:159        candidate = (skill_path.parent / target).resolve()160    return candidate161162163def validate_links(skill_path: Path, body: str, repo_root: Path, result: ValidationResult) -> None:164    for raw_target in LINK_RE.findall(body):165        target = raw_target.split("#", 1)[0].strip()166        if not target:167            continue168        resolved = resolve_link(skill_path, repo_root, target)169        if resolved is None:170            continue171        try:172            resolved.relative_to(repo_root.resolve())173        except ValueError:174            result.issues.append(175                Issue(skill_path, f"Link escapes repo: {raw_target}", severity="warning")176            )177            continue178        if not resolved.exists():179            result.issues.append(Issue(skill_path, f"Broken link: {raw_target}"))180181182def find_skill_files(repo_root: Path) -> list[Path]:183    skills: list[Path] = []184    root_skill = repo_root / "SKILL.md"185    if root_skill.is_file():186        skills.append(root_skill)187    for path in repo_root.rglob("SKILL.md"):188        if path == root_skill:189            continue190        if ".git" in path.parts:191            continue192        skills.append(path)193    return sorted(skills)194195196def compute_lock_entries(repo_root: Path, skill_files: list[Path]) -> dict[str, str]:197    """Return { relative_skill_path: md5 } for every SKILL.md."""198    entries: dict[str, str] = {}199    for path in skill_files:200        rel = path.relative_to(repo_root).as_posix()201        digest = hashlib.md5(path.read_bytes()).hexdigest()202        entries[rel] = digest203    return entries204205206def parse_lock_file(lock_path: Path) -> dict[str, str]:207    """Parse api/skills.lock lines of the form: <md5>  <relative/path>"""208    entries: dict[str, str] = {}209    if not lock_path.is_file():210        return entries211    for raw in lock_path.read_text(encoding="utf-8").splitlines():212        line = raw.strip()213        if not line or line.startswith("#"):214            continue215        parts = line.split(None, 1)216        if len(parts) != 2:217            continue218        digest, rel = parts219        entries[rel.strip()] = digest.strip()220    return entries221222223def validate_lock(224    repo_root: Path,225    skill_files: list[Path],226    lock_path: Path,227    result: ValidationResult,228) -> None:229    actual = compute_lock_entries(repo_root, skill_files)230    expected = parse_lock_file(lock_path)231232    if not expected:233        result.issues.append(234            Issue(lock_path, f"Lock file is empty or missing: {lock_path}", severity="error")235        )236        return237238    actual_keys = set(actual.keys())239    expected_keys = set(expected.keys())240241    for missing in sorted(expected_keys - actual_keys):242        result.issues.append(243            Issue(lock_path, f"Lock entry references missing skill: {missing}")244        )245    for added in sorted(actual_keys - expected_keys):246        result.issues.append(247            Issue(248                lock_path,249                f"New skill not registered in lock file: {added} — run scripts/update_lock.sh or bump api/skills.lock",250            )251        )252    for shared in sorted(actual_keys & expected_keys):253        if actual[shared] != expected[shared]:254            result.issues.append(255                Issue(256                    lock_path,257                    f"Lock stale for {shared} (expected {expected[shared][:8]}…, "258                    f"actual {actual[shared][:8]}…) — run: ./scripts/update_lock.sh",259                    severity="error",260                )261            )262263264def validate_repo(repo_root: Path, strict: bool) -> tuple[ValidationResult, list[Path]]:265    result = ValidationResult()266    skill_files = find_skill_files(repo_root)267268    if not skill_files:269        result.issues.append(Issue(repo_root, "No SKILL.md files found"))270        return result, skill_files271272    for skill_path in skill_files:273        try:274            content = skill_path.read_text(encoding="utf-8")275        except OSError as exc:276            result.issues.append(Issue(skill_path, f"Cannot read file: {exc}"))277            continue278        body = validate_frontmatter(skill_path, content, result)279        if body is not None:280            validate_links(skill_path, body, repo_root, result)281282    # Folder name should match frontmatter name when skill is in skills/<name>/283    for skill_path in skill_files:284        if skill_path.parent.parent.name != "skills":285            continue286        match = FRONTMATTER_RE.match(skill_path.read_text(encoding="utf-8"))287        if not match:288            continue289        fm = parse_simple_yaml(match.group(1))290        expected_dir = fm.get("name", "").strip()291        if expected_dir and skill_path.parent.name != expected_dir:292            result.issues.append(293                Issue(294                    skill_path,295                    f"Folder '{skill_path.parent.name}' must match frontmatter name '{expected_dir}'",296                    severity="warning",297                )298            )299300    return result, skill_files301302303def print_report(result: ValidationResult, repo_root: Path) -> None:304    print(f"Validating skills in: {repo_root.resolve()}")305    print("-" * 60)306    if not result.issues:307        print("OK — all checks passed.")308        return309    for issue in result.issues:310        prefix = "ERROR" if issue.severity == "error" else "WARN "311        try:312            rel = issue.path.relative_to(repo_root)313        except ValueError:314            rel = issue.path315        print(f"{prefix} {rel}: {issue.message}")316    print("-" * 60)317    print(f"Errors: {len(result.errors)}  Warnings: {len(result.warnings)}")318319320def write_junit(result: ValidationResult, skill_files: list[Path], repo_root: Path, junit_path: Path) -> None:321    suite = ET.Element(322        "testsuite",323        attrib={324            "name": "skill-lint",325            "tests": str(max(len(skill_files), 1)),326            "failures": str(len(result.errors)),327            "errors": "0",328            "skipped": "0",329        },330    )331    issues_by_path: dict[str, list[Issue]] = {}332    for issue in result.issues:333        try:334            key = issue.path.relative_to(repo_root).as_posix()335        except ValueError:336            key = str(issue.path)337        issues_by_path.setdefault(key, []).append(issue)338339    targets = [p.relative_to(repo_root).as_posix() for p in skill_files] or ["repo"]340    for target in targets:341        case = ET.SubElement(suite, "testcase", attrib={"classname": "skill-lint", "name": target})342        for issue in issues_by_path.get(target, []):343            tag = "failure" if issue.severity == "error" else "system-out"344            node = ET.SubElement(case, tag, attrib={"message": issue.message[:200]})345            node.text = issue.message346347    junit_path.parent.mkdir(parents=True, exist_ok=True)348    tree = ET.ElementTree(suite)349    tree.write(junit_path, encoding="utf-8", xml_declaration=True)350351352def write_lock(skill_files: list[Path], repo_root: Path, lock_path: Path) -> None:353    entries = compute_lock_entries(repo_root, skill_files)354    lock_path.parent.mkdir(parents=True, exist_ok=True)355    lines = ["# compose-kotlin-agent-skills — skill registry", "# Format: <md5>  <relative path>", ""]356    for rel in sorted(entries):357        lines.append(f"{entries[rel]}  {rel}")358    lock_path.write_text("\n".join(lines) + "\n", encoding="utf-8")359360361def main() -> int:362    parser = argparse.ArgumentParser(description="Validate Agent SKILL.md files")363    parser.add_argument(364        "--root",365        type=Path,366        default=None,367        help="Repository root (default: parent of scripts/)",368    )369    parser.add_argument(370        "--strict",371        action="store_true",372        help="Treat warnings as failures",373    )374    parser.add_argument(375        "--lock-check",376        type=Path,377        default=None,378        help="Verify skill set matches the given api/skills.lock file",379    )380    parser.add_argument(381        "--write-lock",382        type=Path,383        default=None,384        help="(Re)generate the lock file at the given path and exit 0",385    )386    parser.add_argument(387        "--junit",388        type=Path,389        default=None,390        help="Write JUnit XML report to the given path",391    )392    args = parser.parse_args()393394    repo_root = args.root or Path(__file__).resolve().parent.parent395    if not (repo_root / "SKILL.md").is_file() and not list(repo_root.rglob("SKILL.md")):396        print(f"No SKILL.md under {repo_root}", file=sys.stderr)397        return 1398399    result, skill_files = validate_repo(repo_root, args.strict)400401    if args.write_lock is not None:402        write_lock(skill_files, repo_root, args.write_lock)403        print(f"Wrote lock file: {args.write_lock}")404405    if args.lock_check is not None:406        validate_lock(repo_root, skill_files, args.lock_check, result)407408    print_report(result, repo_root)409410    if args.junit is not None:411        write_junit(result, skill_files, repo_root, args.junit)412        print(f"Wrote JUnit report: {args.junit}")413414    return 0 if result.ok(args.strict) else 1415416417if __name__ == "__main__":418    sys.exit(main())419

Search chapters, reference and source filenames.