|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Generate or validate manifest.json from skill directories.""" |
| 3 | + |
| 4 | +import argparse |
| 5 | +import json |
| 6 | +import re |
| 7 | +import sys |
| 8 | +from datetime import datetime, timezone |
| 9 | +from pathlib import Path |
| 10 | + |
| 11 | + |
| 12 | +def extract_version_from_skill(skill_path: Path) -> str: |
| 13 | + """Extract version from SKILL.md frontmatter metadata.""" |
| 14 | + skill_md = skill_path / "SKILL.md" |
| 15 | + if not skill_md.exists(): |
| 16 | + raise ValueError(f"SKILL.md not found in {skill_path}") |
| 17 | + |
| 18 | + content = skill_md.read_text() |
| 19 | + |
| 20 | + # parse YAML frontmatter |
| 21 | + if not content.startswith("---"): |
| 22 | + raise ValueError(f"SKILL.md in {skill_path} missing frontmatter") |
| 23 | + |
| 24 | + end_idx = content.find("---", 3) |
| 25 | + if end_idx == -1: |
| 26 | + raise ValueError(f"SKILL.md in {skill_path} has unclosed frontmatter") |
| 27 | + |
| 28 | + frontmatter = content[3:end_idx] |
| 29 | + |
| 30 | + # extract version from metadata block |
| 31 | + version_match = re.search(r'version:\s*["\']?([^"\'\n]+)["\']?', frontmatter) |
| 32 | + if version_match: |
| 33 | + return version_match.group(1).strip() |
| 34 | + |
| 35 | + return "0.0.0" |
| 36 | + |
| 37 | + |
| 38 | +def get_skill_updated_at(skill_path: Path) -> str: |
| 39 | + """Get the most recent modification time of any file in the skill directory.""" |
| 40 | + latest_mtime = 0.0 |
| 41 | + for file_path in skill_path.rglob("*"): |
| 42 | + if file_path.is_file(): |
| 43 | + mtime = file_path.stat().st_mtime |
| 44 | + if mtime > latest_mtime: |
| 45 | + latest_mtime = mtime |
| 46 | + |
| 47 | + if latest_mtime == 0.0: |
| 48 | + return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") |
| 49 | + |
| 50 | + return datetime.fromtimestamp(latest_mtime, timezone.utc).strftime( |
| 51 | + "%Y-%m-%dT%H:%M:%SZ" |
| 52 | + ) |
| 53 | + |
| 54 | + |
| 55 | +def generate_manifest(repo_root: Path) -> dict: |
| 56 | + """Generate manifest from skill directories.""" |
| 57 | + skills = {} |
| 58 | + |
| 59 | + skills_dir = repo_root / "skills" |
| 60 | + |
| 61 | + for item in sorted(skills_dir.iterdir()): |
| 62 | + if not item.is_dir(): |
| 63 | + continue |
| 64 | + if item.name.startswith(".") or item.name == "scripts": |
| 65 | + continue |
| 66 | + |
| 67 | + skill_md = item / "SKILL.md" |
| 68 | + if not skill_md.exists(): |
| 69 | + continue |
| 70 | + |
| 71 | + skills[item.name] = { |
| 72 | + "version": extract_version_from_skill(item), |
| 73 | + "updated_at": get_skill_updated_at(item), |
| 74 | + } |
| 75 | + |
| 76 | + return { |
| 77 | + "version": "1", |
| 78 | + "updated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), |
| 79 | + "skills": skills, |
| 80 | + } |
| 81 | + |
| 82 | + |
| 83 | +def normalize_manifest(manifest: dict) -> dict: |
| 84 | + """Normalize manifest for comparison by excluding updated_at timestamps.""" |
| 85 | + normalized = manifest.copy() |
| 86 | + normalized.pop("updated_at", None) |
| 87 | + |
| 88 | + skills = {} |
| 89 | + for name, skill in manifest.get("skills", {}).items(): |
| 90 | + skill_copy = skill.copy() |
| 91 | + skill_copy.pop("updated_at", None) |
| 92 | + skills[name] = skill_copy |
| 93 | + |
| 94 | + normalized["skills"] = skills |
| 95 | + return normalized |
| 96 | + |
| 97 | + |
| 98 | +def validate_manifest(repo_root: Path) -> bool: |
| 99 | + """Validate that manifest.json is up to date. Returns True if valid.""" |
| 100 | + manifest_path = repo_root / "manifest.json" |
| 101 | + |
| 102 | + if not manifest_path.exists(): |
| 103 | + print("ERROR: manifest.json does not exist", file=sys.stderr) |
| 104 | + return False |
| 105 | + |
| 106 | + current_manifest = json.loads(manifest_path.read_text()) |
| 107 | + expected_manifest = generate_manifest(repo_root) |
| 108 | + |
| 109 | + # compare without timestamps |
| 110 | + current_normalized = normalize_manifest(current_manifest) |
| 111 | + expected_normalized = normalize_manifest(expected_manifest) |
| 112 | + |
| 113 | + if current_normalized != expected_normalized: |
| 114 | + print("ERROR: manifest.json is out of date", file=sys.stderr) |
| 115 | + print("\nExpected:", file=sys.stderr) |
| 116 | + print(json.dumps(expected_normalized, indent=2), file=sys.stderr) |
| 117 | + print("\nActual:", file=sys.stderr) |
| 118 | + print(json.dumps(current_normalized, indent=2), file=sys.stderr) |
| 119 | + return False |
| 120 | + |
| 121 | + print("manifest.json is up to date") |
| 122 | + return True |
| 123 | + |
| 124 | + |
| 125 | +def main() -> None: |
| 126 | + parser = argparse.ArgumentParser(description="Generate or validate manifest.json") |
| 127 | + parser.add_argument( |
| 128 | + "mode", |
| 129 | + nargs="?", |
| 130 | + default="generate", |
| 131 | + choices=["generate", "validate"], |
| 132 | + help="Mode: generate (creates manifest.json, default) or validate (checks if up to date)", |
| 133 | + ) |
| 134 | + |
| 135 | + args = parser.parse_args() |
| 136 | + repo_root = Path(__file__).parent.parent |
| 137 | + |
| 138 | + match args.mode: |
| 139 | + case "generate": |
| 140 | + manifest = generate_manifest(repo_root) |
| 141 | + manifest_path = repo_root / "manifest.json" |
| 142 | + manifest_path.write_text(json.dumps(manifest, indent=2) + "\n") |
| 143 | + print(f"Generated {manifest_path}") |
| 144 | + print(f"Found {len(manifest['skills'])} skill(s): {', '.join(manifest['skills'].keys())}") |
| 145 | + |
| 146 | + case "validate": |
| 147 | + is_valid = validate_manifest(repo_root) |
| 148 | + sys.exit(0 if is_valid else 1) |
| 149 | + |
| 150 | + |
| 151 | +if __name__ == "__main__": |
| 152 | + main() |
0 commit comments