CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

trysac/skill-linter

Lint agent skill folders (SKILL.md) for frontmatter, name, description limits, trigger cues, body length and broken links. Use when the user asks to validate, review or fix a SKILL.md before committing or publishing.

Quality

97%

Does it follow best practices?

Run evals on this skill

Adds up to 20 points to the overall score

View guide
SecuritybySnyk

Low

Low-risk findings worth noting

Overview
Quality
Evals
Security
Files

skill_lint.pyscripts/

#!/usr/bin/env python3
"""Lint agent skill folders (SKILL.md) against the Agent Skills format (standard library only).

Usage:
    python3 skill_lint.py PATH [PATH ...] [--format text|json] [--strict] [--max-body-lines N]

PATH is a skill folder, a folder tree that contains skills, or a SKILL.md file.
Exit codes: 0 no errors (warnings count only with --strict), 1 errors, 2 usage error.
The script only reads files; it never runs their content and makes no network calls.
Rules S000-S009 are described in references/rules.md.
"""

from __future__ import annotations

import argparse
import json
import os
import re
import stat
import sys
from pathlib import Path

SKILL_FILE = "SKILL.md"
MAX_SKILL_FILES = 10_000
MAX_FILE_BYTES = 1_048_576
NAME_MAX = 64
DESCRIPTION_MAX = 1024
COMPATIBILITY_MAX = 500
BODY_MAX_LINES = 500
RESERVED_WORDS = ("anthropic", "claude")
TRIGGER_CUES = ("use when", "when the user", "trigger")
NAME_RE = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
XML_TAG_RE = re.compile(r"<[A-Za-z/][^>]{0,200}>")
SEVERITY = {"S005": "warning", "S006": "warning"}  # every other rule is an error

KEY_RE = re.compile(r"([A-Za-z_][A-Za-z0-9_.-]*):(?:[ \t]+(.*))?")
NESTED_RE = re.compile(r"( +)([A-Za-z_][A-Za-z0-9_.-]*):(?:[ \t]+(.*))?")
BLOCK_RE = re.compile(r"[>|][+-]?")
UNSUPPORTED_START = "[{&*!%@`|>"
ESCAPES = {'"': '"', "\\": "\\", "n": "\n", "t": "\t", "/": "/"}
FENCE_RE = re.compile(r"^ {0,3}(`{3,}|~{3,})(.*)$")
SCHEME_RE = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*:")
PERCENT_RE = re.compile(rb"%([0-9A-Fa-f]{2})")
LINK_RE = re.compile(
    r"\[(?:[^\[\]]|\[[^\[\]]*\]){0,1000}\]"
    r"\(\s*(?P<target><[^<>\n]{1,2000}>|(?:[^\s()<>]|\([^\s()]*\)){1,2000})"
    r"""(?:\s+(?:"[^"]*"|'[^']*'))?\s*\)"""
)


class Unsupported(Exception):
    """Frontmatter syntax outside the supported subset."""

    def __init__(self, line: int, reason: str) -> None:
        super().__init__(reason)
        self.line = line
        self.reason = reason


def quote(text: str, limit: int = 80) -> str:
    safe = "".join(c if c.isprintable() else "?" for c in text[:limit])
    return safe + "..." if len(text) > limit else safe


# --- frontmatter ------------------------------------------------------------------------------


def parse_scalar(text: str, line: int) -> str:
    if not text or text.startswith("#"):
        return ""
    if text[0] in "\"'":
        return parse_quoted(text, line)
    if text[0] in UNSUPPORTED_START:
        raise Unsupported(line, f"value starting with {text[0]!r} is not supported")
    cut = text.find(" #")
    return (text if cut < 0 else text[:cut]).strip()


def parse_quoted(text: str, line: int) -> str:
    delim, out, i = text[0], [], 1
    while i < len(text):
        ch = text[i]
        if ch == delim:
            if delim == "'" and text[i + 1 : i + 2] == "'":
                out.append("'")
                i += 2
                continue
            tail = text[i + 1 :].strip()
            if tail and not tail.startswith("#"):
                raise Unsupported(line, "unexpected text after quoted string")
            return "".join(out)
        if delim == '"' and ch == "\\":
            repl = ESCAPES.get(text[i + 1 : i + 2])
            if repl is None:
                raise Unsupported(line, "unsupported escape sequence")
            out.append(repl)
            i += 2
            continue
        out.append(ch)
        i += 1
    raise Unsupported(line, "unterminated quoted string")


def skip_indented(lines: list[str], start: int, end: int) -> int:
    i = start
    while i < end and (not lines[i].strip() or lines[i].startswith(" ")):
        i += 1
    return i


def parse_map(lines: list[str], start: int, stop: int):
    result: dict[str, str] = {}
    indent = -1
    for i in range(start, stop):
        text = lines[i].strip()
        if not text or text.startswith("#"):
            continue
        m = NESTED_RE.fullmatch(lines[i].rstrip())
        if m is None or indent not in (-1, len(m.group(1))):
            raise Unsupported(i + 1, f"cannot parse {quote(text)}")
        indent = len(m.group(1))
        if m.group(2) in result:
            raise Unsupported(i + 1, f"duplicate key '{m.group(2)}'")
        result[m.group(2)] = parse_scalar(m.group(3) or "", i + 1)
    return result if result else ""


def fold(block: list[str], folded: bool) -> str:
    content = [line for line in block if line.strip()]
    if not content:
        return ""
    if folded:
        return " ".join(line.strip() for line in content)
    indent = min(len(line) - len(line.lstrip(" ")) for line in content)
    return "\n".join(line[indent:] if line.strip() else "" for line in block).strip("\n")


def parse_frontmatter(lines: list[str]):
    """Return (fields, key_lines, errors, body_start); body_start is None without fences."""
    if not lines or lines[0].rstrip() != "---":
        return {}, {}, [(1, "file must start with a '---' frontmatter fence")], None
    close = next((i for i in range(1, len(lines)) if lines[i].rstrip() == "---"), None)
    if close is None:
        return {}, {}, [(1, "frontmatter is not closed by a '---' fence")], None
    fields: dict = {}
    key_lines: dict[str, int] = {}
    errors: list[tuple[int, str]] = []
    try:
        i = 1
        while i < close:
            raw = lines[i]
            if not raw.strip() or raw.strip().startswith("#"):
                i += 1
                continue
            m = KEY_RE.fullmatch(raw.rstrip())
            if m is None:
                raise Unsupported(i + 1, f"cannot parse {quote(raw.strip())}")
            key, rest = m.group(1), (m.group(2) or "").strip()
            if key in fields:
                raise Unsupported(i + 1, f"duplicate key '{key}'")
            key_lines[key] = i + 1
            if not rest:
                stop = skip_indented(lines, i + 1, close)
                fields[key] = parse_map(lines, i + 1, stop)
                i = stop
            elif BLOCK_RE.fullmatch(rest):
                stop = skip_indented(lines, i + 1, close)
                fields[key] = fold(lines[i + 1 : stop], rest[0] == ">")
                i = stop
            else:
                fields[key] = parse_scalar(rest, i + 1)
                i += 1
    except Unsupported as exc:
        errors = [(exc.line, f"unsupported frontmatter syntax: {exc.reason}")]
    return fields, key_lines, errors, close + 2


# --- links ------------------------------------------------------------------------------------


def mask_code_spans(line: str) -> str:
    """Blank inline code spans (matching backtick runs) in linear time."""
    if "`" not in line:
        return line
    runs = [(m.start(), m.end()) for m in re.finditer(r"`+", line)]
    following = [-1] * len(runs)
    last_seen: dict[int, int] = {}
    for i in range(len(runs) - 1, -1, -1):
        length = runs[i][1] - runs[i][0]
        following[i] = last_seen.get(length, -1)
        last_seen[length] = i
    chars = list(line)
    i = 0
    while i < len(runs):
        closer = following[i]
        if closer == -1:
            i += 1
            continue
        for pos in range(runs[i][0], runs[closer][1]):
            chars[pos] = " "
        i = closer + 1
    return "".join(chars)


def iter_link_targets(lines: list[str], first_line: int):
    fence = None
    for offset, line in enumerate(lines):
        m = FENCE_RE.match(line)
        if fence is None:
            if m and not (m.group(1)[0] == "`" and "`" in m.group(2)):
                fence = (m.group(1)[0], len(m.group(1)))
                continue
        else:
            if (
                m
                and m.group(1)[0] == fence[0]
                and len(m.group(1)) >= fence[1]
                and not m.group(2).strip()
            ):
                fence = None
            continue
        for found in LINK_RE.finditer(mask_code_spans(line)):
            yield first_line + offset, found.group("target")


def normalize_target(raw: str) -> str | None:
    target = raw[1:-1] if raw.startswith("<") and raw.endswith(">") else raw
    if not target or target[0] in "#/" or SCHEME_RE.match(target):
        return None
    cut = min((i for i in (target.find("?"), target.find("#")) if i >= 0), default=len(target))
    decoded = PERCENT_RE.sub(lambda m: bytes([int(m.group(1), 16)]), target[:cut].encode("utf-8"))
    return decoded.decode("utf-8", errors="replace") or None


# --- rules ------------------------------------------------------------------------------------


def read_text(path: Path) -> str:
    try:
        info = os.lstat(path)
    except OSError:
        raise ValueError("SKILL.md cannot be read") from None
    if stat.S_ISLNK(info.st_mode):
        raise ValueError("SKILL.md is a symlink")
    if not stat.S_ISREG(info.st_mode):
        raise ValueError("SKILL.md is not a regular file")
    if info.st_size > MAX_FILE_BYTES:
        raise ValueError(f"SKILL.md is {info.st_size} bytes (max {MAX_FILE_BYTES})")
    try:
        return path.read_bytes().decode("utf-8-sig")
    except UnicodeDecodeError:
        raise ValueError("SKILL.md is not valid UTF-8") from None
    except OSError:
        raise ValueError("SKILL.md cannot be read") from None


def lint_skill(skill_dir: Path, max_body_lines: int = BODY_MAX_LINES) -> list[dict]:
    """Return findings (dicts with path, line, rule, severity, message) for one folder."""
    path = (skill_dir / SKILL_FILE).as_posix()
    found: list[dict] = []

    def report(line: int, rule: str, message: str) -> None:
        sev = SEVERITY.get(rule, "error")
        found.append(
            {"path": path, "line": line, "rule": rule, "severity": sev, "message": message}
        )

    try:
        text = read_text(skill_dir / SKILL_FILE)
    except ValueError as exc:
        report(1, "S000", str(exc))
        return found
    lines = [ln.removesuffix("\r") for ln in text.split("\n")]
    if lines and lines[-1] == "":
        lines.pop()
    fields, key_lines, errors, body_start = parse_frontmatter(lines)
    for line, message in errors:
        report(line, "S001", message)
    if body_start is None:
        return found
    if not errors:
        check_fields(fields, key_lines, skill_dir, report)
    body = lines[body_start - 1 :]
    if len(body) > max_body_lines:
        report(
            body_start + max_body_lines,
            "S006",
            f"body has {len(body)} lines (max {max_body_lines})",
        )
    check_links(body, body_start, skill_dir, report)
    return found


def required(fields: dict, key_lines: dict, key: str, report) -> str | None:
    value = fields.get(key)
    if value is None or (isinstance(value, str) and not value.strip()):
        report(1, "S002", f"missing required field '{key}'")
        return None
    if not isinstance(value, str):
        report(key_lines[key], "S001", f"'{key}' must be a plain string")
        return None
    return value


def check_fields(fields: dict, key_lines: dict, skill_dir: Path, report) -> None:
    name = required(fields, key_lines, "name", report)
    description = required(fields, key_lines, "description", report)
    if name is not None:
        line = key_lines["name"]
        try:
            folder = skill_dir.resolve().name
        except (OSError, RuntimeError):
            folder = skill_dir.name
        if len(name) > NAME_MAX or NAME_RE.fullmatch(name) is None:
            report(
                line,
                "S003",
                f"name {quote(name)} must be 1-{NAME_MAX} chars of a-z, 0-9 and inner '-'",
            )
        elif name != folder:
            report(line, "S003", f"name {quote(name)} does not match folder {quote(folder)}")
        if XML_TAG_RE.search(name):
            report(line, "S009", "name contains an XML tag")
        word = next((w for w in RESERVED_WORDS if w in name.lower()), None)
        if word:
            report(line, "S009", f"name contains reserved word '{word}'")
    if description is not None:
        line = key_lines["description"]
        if len(description) > DESCRIPTION_MAX:
            report(
                line, "S004", f"description has {len(description)} chars (max {DESCRIPTION_MAX})"
            )
        if XML_TAG_RE.search(description):
            report(line, "S009", "description contains an XML tag")
        if not any(cue in description.lower() for cue in TRIGGER_CUES):
            report(line, "S005", f"description has no trigger cue (e.g. '{TRIGGER_CUES[0]}')")
    compat = fields.get("compatibility")
    if isinstance(compat, str) and len(compat) > COMPATIBILITY_MAX:
        report(
            key_lines["compatibility"],
            "S004",
            f"compatibility has {len(compat)} chars (max {COMPATIBILITY_MAX})",
        )
    meta = fields.get("metadata")
    if isinstance(meta, str) and meta.strip():
        report(key_lines["metadata"], "S001", "metadata must be a one-level map")


def check_links(body: list[str], first_line: int, skill_dir: Path, report) -> None:
    try:
        base = skill_dir.resolve()
    except (OSError, RuntimeError):
        return
    for line, raw in iter_link_targets(body, first_line):
        target = normalize_target(raw)
        if target is None:
            continue
        try:
            resolved = (base / target).resolve()
        except (OSError, RuntimeError, ValueError):
            report(line, "S007", f"link target cannot be resolved: {quote(raw)}")
            continue
        if not resolved.is_relative_to(base):
            report(line, "S008", f"link escapes the skill folder: {quote(raw)}")
        elif not os.path.exists(resolved):
            report(line, "S007", f"link target not found: {quote(raw)}")


# --- command line -----------------------------------------------------------------------------


def find_skill_dirs(root: Path) -> list[Path]:
    found: list[Path] = []
    for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
        dirnames.sort()
        if SKILL_FILE in filenames:
            found.append(Path(dirpath))
            if len(found) >= MAX_SKILL_FILES:
                break
    return found


def collect(paths: list[str]) -> list[Path]:
    dirs: list[Path] = []
    for raw in paths:
        path = Path(raw)
        try:
            mode = os.stat(path).st_mode
        except OSError:
            raise ValueError(f"path not found: {quote(raw)}") from None
        if stat.S_ISDIR(mode):
            found = find_skill_dirs(path)
        elif path.name == SKILL_FILE and stat.S_ISREG(mode):
            found = [path.parent]
        else:
            raise ValueError(f"not a folder or {SKILL_FILE}: {quote(raw)}")
        dirs += [d for d in found if d not in dirs]
    return dirs[:MAX_SKILL_FILES]


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Lint agent skill folders (SKILL.md).")
    parser.add_argument("paths", nargs="+", metavar="PATH")
    parser.add_argument("--format", choices=("text", "json"), default="text", dest="fmt")
    parser.add_argument("--strict", action="store_true", help="exit 1 on warnings as well")
    parser.add_argument("--max-body-lines", type=int, default=BODY_MAX_LINES, metavar="N")
    try:
        args = parser.parse_args(argv)
    except SystemExit as exc:
        return exc.code if isinstance(exc.code, int) else 2
    try:
        dirs = collect(args.paths)
    except ValueError as exc:
        print(f"skill-lint: {exc}", file=sys.stderr)
        return 2
    if not dirs:
        print("no SKILL.md found", file=sys.stderr)
    findings = [f for d in dirs for f in lint_skill(d, args.max_body_lines)]
    findings.sort(key=lambda f: (f["path"], f["line"], f["rule"]))
    if args.fmt == "json":
        print(json.dumps(findings))
    else:
        for f in findings:
            print(f"{f['path']}:{f['line']}: {f['severity']} {f['rule']} {f['message']}")
    failed = any(f["severity"] == "error" for f in findings) or (args.strict and bool(findings))
    return 1 if failed else 0


if __name__ == "__main__":
    sys.exit(main())

SKILL.md

tile.json