Skip to content

notque/vexjoy-agent / skills/meta/docs-sync-checker

docs-sync-checker

Verified

Detect documentation drift against filesystem state.

FileKindSize
SKILL.mdskill md11.6 KB
references/documentation-structure.mdmarkdown2.9 KB
references/integration-guide.mdmarkdown2.8 KB
references/sync-rules.mdmarkdown2.0 KB
scripts/generate_report.pyexecutablescript10.4 KB
scripts/parse_docs.pyexecutablescript10.6 KB
scripts/scan_tools.pyexecutablescript14.1 KB
scripts/validate.pyexecutablescript8.1 KB

scripts/scan_tools.py

View on GitHub
#!/usr/bin/env python3
"""
Tool discovery script for docs-sync-checker skill.
Scans repository for skills, agents, and commands.
"""

__version__ = "1.0.0"

import argparse
import json
import re
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional

# YAML block scalar indicators: `|`, `>`, with optional chomping/indent markers.
_BLOCK_SCALAR = re.compile(r"^[|>][+-]?[0-9]?$")


class ToolScanner:
    """Discover all tools in repository."""

    def __init__(self, repo_root: Path, debug: bool = False):
        self.repo_root = Path(repo_root).resolve()
        self.debug = debug
        self.errors: List[str] = []

    def log(self, message: str) -> None:
        """Log debug message."""
        if self.debug:
            print(f"[DEBUG] {message}", file=sys.stderr)

    def parse_yaml_frontmatter(self, file_path: Path) -> Optional[Dict[str, str]]:
        """
        Extract YAML frontmatter from markdown file.

        Returns dict with required name and description fields and an optional version.
        """
        try:
            with open(file_path, "r", encoding="utf-8") as f:
                content = f.read()

            # Check for YAML frontmatter
            if not content.startswith("---"):
                self.log(f"No YAML frontmatter in {file_path}")
                return None

            # Extract frontmatter
            parts = content.split("---", 2)
            if len(parts) < 3:
                self.log(f"Malformed YAML frontmatter in {file_path}")
                return None

            frontmatter = parts[1].strip()

            # Parse YAML fields (simple regex-based parsing)
            yaml_data = {}
            for line in frontmatter.split("\n"):
                line = line.strip()
                if not line or line.startswith("#"):
                    continue

                # Match "key: value" pattern
                match = re.match(r"^(\w+):\s*(.+)$", line)
                if match:
                    key, value = match.groups()
                    yaml_data[key] = value.strip()

            # Validate required fields
            required_fields = ["name", "description"]
            for field in required_fields:
                if field not in yaml_data:
                    error = f"Missing required field '{field}' in {file_path}"
                    self.log(error)
                    self.errors.append(error)
                    return None

            return yaml_data

        except Exception as e:
            error = f"Error parsing {file_path}: {e}"
            self.log(error)
            self.errors.append(error)
            return None

    @staticmethod
    def _is_symlinked(path: Path, root: Path) -> bool:
        """True when path or a directory between it and root is a symlink."""
        current = path
        while current != root and root in current.parents:
            if current.is_symlink():
                return True
            current = current.parent
        return False

    def scan_skills(self) -> List[Dict[str, Any]]:
        """
        Scan skills/ directory for SKILL.md files.

        Returns list of skill metadata dicts.
        """
        skills = []
        skills_dir = self.repo_root / "skills"

        if not skills_dir.exists():
            self.log(f"Skills directory not found: {skills_dir}")
            return skills

        self.log(f"Scanning skills directory: {skills_dir}")

        # Skills are category-nested: skills/<category>/<name>/SKILL.md.
        for skill_file in sorted(skills_dir.rglob("SKILL.md")):
            skill_dir = skill_file.parent
            yaml_data = self.parse_yaml_frontmatter(skill_file)
            if yaml_data:
                if yaml_data["name"] != skill_dir.name:
                    self.errors.append(
                        f"Skill name '{yaml_data['name']}' does not match directory '{skill_dir.name}' in {skill_file}"
                    )
                    continue
                skill = {
                    "name": yaml_data["name"],
                    "description": yaml_data["description"],
                    "path": str(skill_file.relative_to(self.repo_root)),
                    "directory": skill_dir.name,
                }
                if "version" in yaml_data:
                    skill["version"] = yaml_data["version"]
                # Promoted and symlinked (private) skills stay out of the
                # generated catalog, so the parser must not expect them there.
                if yaml_data.get("promoted_to"):
                    skill["promoted_to"] = yaml_data["promoted_to"]
                if self._is_symlinked(skill_file, skills_dir):
                    skill["private"] = True
                skills.append(skill)
                self.log(f"Found skill: {yaml_data['name']} at {skill_file}")

        return skills

    def scan_agents(self) -> List[Dict[str, Any]]:
        """
        Scan agents/ directory for *.md files with YAML frontmatter.

        Returns list of agent metadata dicts.
        """
        agents = []
        agents_dir = self.repo_root / "agents"

        if not agents_dir.exists():
            self.log(f"Agents directory not found: {agents_dir}")
            return agents

        self.log(f"Scanning agents directory: {agents_dir}")

        # Find all .md files in agents/*.md (not subdirectories)
        for agent_file in agents_dir.glob("*.md"):
            if not agent_file.is_file():
                continue

            yaml_data = self.parse_yaml_frontmatter(agent_file)
            if yaml_data:
                if yaml_data["name"] != agent_file.stem:
                    self.errors.append(
                        f"Agent name '{yaml_data['name']}' does not match filename '{agent_file.stem}' in {agent_file}"
                    )
                    continue
                agent = {
                    "name": yaml_data["name"],
                    "description": yaml_data["description"],
                    "path": str(agent_file.relative_to(self.repo_root)),
                }
                if "version" in yaml_data:
                    agent["version"] = yaml_data["version"]
                if agent_file.is_symlink():
                    agent["private"] = True
                agents.append(agent)
                self.log(f"Found agent: {yaml_data['name']} at {agent_file}")

        return agents

    def scan_commands(self) -> List[Dict[str, Any]]:
        """
        Scan commands/ directory for *.md files.

        Returns list of command metadata dicts.
        Handles namespaced commands (commands/code/cleanup.md → code/cleanup)
        """
        commands = []
        commands_dir = self.repo_root / "commands"

        if not commands_dir.exists():
            self.log(f"Commands directory not found: {commands_dir}")
            return commands

        self.log(f"Scanning commands directory: {commands_dir}")

        # Find all .md files in commands/**/*.md (recursive)
        for command_file in commands_dir.rglob("*.md"):
            if not command_file.is_file():
                continue

            # Determine namespace and command name
            rel_path = command_file.relative_to(commands_dir)
            parts = rel_path.parts

            if len(parts) == 1:
                # Top-level command: commands/do.md → do
                namespace = None
                command_name = parts[0].replace(".md", "")
            else:
                # Namespaced command: commands/code/cleanup.md → code/cleanup
                namespace = parts[0]
                command_name = "/".join(parts[:-1]) + "/" + parts[-1].replace(".md", "")

            # Try to extract description from file (optional)
            description = self._extract_command_description(command_file)

            commands.append(
                {
                    "name": command_name,
                    "namespace": namespace,
                    "path": str(command_file.relative_to(self.repo_root)),
                    "description": description,
                }
            )
            self.log(f"Found command: {command_name} at {command_file}")

        return commands

    def _extract_command_description(self, file_path: Path) -> str:
        """
        Extract description from command file.

        Tries to find first paragraph or header after title.
        """
        try:
            with open(file_path, "r", encoding="utf-8") as f:
                lines = f.readlines()

            # Frontmatter `description:` is authoritative when present.
            if lines and lines[0].strip() == "---":
                for i, line in enumerate(lines[1:], start=1):
                    if line.strip() == "---":
                        break
                    match = re.match(r"^description:\s*(.+)$", line.strip())
                    if not match:
                        continue
                    value = match.group(1).strip()
                    if not _BLOCK_SCALAR.match(value):
                        return value.strip("\"'")
                    # Block scalar (`|`, `>`, `|-`, ...): join the indented lines that follow.
                    body = []
                    for cont in lines[i + 1 :]:
                        if cont.strip() and not cont[:1].isspace():
                            break
                        if cont.strip():
                            body.append(cont.strip())
                    if body:
                        return " ".join(body)[:200]
                    break  # empty block: fall back to the first paragraph

            # Look for first paragraph after title (# Title)
            found_title = False
            for line in lines:
                line = line.strip()

                # Skip empty lines
                if not line:
                    continue

                # Skip title line
                if line.startswith("#") and not found_title:
                    found_title = True
                    continue

                # First non-empty, non-header line after title
                if found_title and not line.startswith("#"):
                    return line[:200]  # Max 200 chars

            return "Command description not available"

        except Exception as e:
            self.log(f"Could not extract description from {file_path}: {e}")  # security-review: ignore (log line, not SQL)  # fmt: skip
            return "Command description not available"

    def scan_all(self, types: Optional[List[str]] = None) -> Dict[str, Any]:
        """
        Scan all tool types.

        Args:
            types: List of types to scan ('skills', 'agents', 'commands')
                   If None, scan all types.

        Returns:
            Dict with scan results and metadata.
        """
        from datetime import datetime

        if types is None:
            types = ["skills", "agents", "commands"]

        results = {
            "scan_timestamp": datetime.utcnow().isoformat() + "Z",
            "repo_root": str(self.repo_root),
            "scan_version": __version__,
        }

        if "skills" in types:
            results["skills"] = self.scan_skills()
            self.log(f"Found {len(results['skills'])} skills")

        if "agents" in types:
            results["agents"] = self.scan_agents()
            self.log(f"Found {len(results['agents'])} agents")

        if "commands" in types:
            results["commands"] = self.scan_commands()
            self.log(f"Found {len(results['commands'])} commands")

        # Add error summary
        if self.errors:
            results["errors"] = self.errors
            results["error_count"] = len(self.errors)

        return results


def main():
    """Main entry point."""
    parser = argparse.ArgumentParser(
        description="Scan repository for skills, agents, and commands",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument("--repo-root", type=Path, required=True, help="Repository root directory")
    parser.add_argument("--types", type=str, help="Comma-separated list of types to scan (skills,agents,commands)")
    parser.add_argument("--output", type=Path, help="Output JSON file (default: stdout)")
    parser.add_argument("--debug", action="store_true", help="Enable debug logging")

    args = parser.parse_args()

    # Parse types
    types = None
    if args.types:
        types = [t.strip() for t in args.types.split(",")]

    # Validate repo root
    if not args.repo_root.exists():
        print(
            json.dumps(
                {
                    "status": "error",
                    "error_type": "RepositoryNotFound",
                    "message": f"Repository root not found: {args.repo_root}",
                },
                indent=2,
            ),
            file=sys.stderr,
        )
        sys.exit(1)

    try:
        # Scan repository
        scanner = ToolScanner(args.repo_root, debug=args.debug)
        results = scanner.scan_all(types=types)

        # Add summary
        total_tools = sum(
            [len(results.get("skills", [])), len(results.get("agents", [])), len(results.get("commands", []))]
        )

        results["summary"] = {
            "total_tools": total_tools,
            "skills_count": len(results.get("skills", [])),
            "agents_count": len(results.get("agents", [])),
            "commands_count": len(results.get("commands", [])),
        }

        # Output results
        output_json = json.dumps(results, indent=2, ensure_ascii=False)

        if args.output:
            args.output.parent.mkdir(parents=True, exist_ok=True)
            with open(args.output, "w", encoding="utf-8") as f:
                f.write(output_json)
            print(f"Scan results written to: {args.output}", file=sys.stderr)
        else:
            print(output_json)

        # Exit with error if scan had errors
        if results.get("errors"):
            print(f"\nWarning: {len(results['errors'])} errors during scan", file=sys.stderr)
            sys.exit(1)

        sys.exit(0)

    except Exception as e:
        print(
            json.dumps({"status": "error", "error_type": type(e).__name__, "message": str(e)}, indent=2),
            file=sys.stderr,
        )
        sys.exit(2)


if __name__ == "__main__":
    main()
rea-changelog-updatemorluto/reaPrepare or rewrite REA release changelogs and GitHub release notes from pinned Git history, with verified contributor thanks and Release Please synchronization.Stars: 469kUpdated Claude CodeCodexVerifiedInstall
academy-guideanthropics/skillsStop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content.Stars: 197kUpdated Claude CodeCodexVerifiedInstall
claude-apianthropics/skillsReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file).Stars: 197kUpdated Claude CodeCodexUnverifiedInstall
doc-coauthoringanthropics/skillsGuide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks.Stars: 197kUpdated Claude CodeCodexVerifiedInstall