File size: 7,609 Bytes
3fbbaab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#!/usr/bin/env python3
"""

catalog_builder.py -- Build a bulk skill catalog in the wiki.



Creates ~/.claude/skill-wiki/catalog.md listing ALL installed skills/agents

with name, path, line count, and category. This is the master index — individual

entity pages (entities/skills/*.md) are created on-demand by the router.



Usage:

    python catalog_builder.py \

      --wiki ~/.claude/skill-wiki \

      --skills-dir ~/.claude/skills \

      --agents-dir ~/.claude/agents \

      [--extra-dirs /path1 /path2]   # additional skill repos



Also adds newly found skills to the wiki index.md and appends to log.md.

"""

import argparse
import re
import sys
from datetime import datetime, timezone
from pathlib import Path

from ctx_config import cfg

TODAY = datetime.now(timezone.utc).strftime("%Y-%m-%d")


def scan_skills_dir(skills_dir: Path) -> list[dict]:
    """Scan a directory for skills (subdirs with SKILL.md)."""
    results: list[dict[str, object]] = []
    if not skills_dir.exists():
        return results

    for item in sorted(skills_dir.iterdir()):
        if item.is_dir():
            skill_md = item / "SKILL.md"
            if skill_md.exists():
                try:
                    lines = len(skill_md.read_text(encoding="utf-8", errors="replace").splitlines())
                except Exception as exc:
                    print(f"Warning: failed to read skill file {skill_md}: {exc}", file=sys.stderr)
                    lines = 0
                results.append({
                    "name": item.name,
                    "path": str(skill_md),
                    "lines": lines,
                    "type": "skill",
                    "over_180": lines > cfg.line_threshold,
                })
    return results


def scan_agents_dir(agents_dir: Path) -> list[dict]:
    """Scan a directory for flat agent .md files."""
    results: list[dict[str, object]] = []
    if not agents_dir.exists():
        return results

    for item in sorted(agents_dir.glob("*.md")):
        try:
            lines = len(item.read_text(encoding="utf-8", errors="replace").splitlines())
        except Exception as exc:
            print(f"Warning: failed to read agent file {item}: {exc}", file=sys.stderr)
            lines = 0
        results.append({
            "name": item.stem,
            "path": str(item),
            "lines": lines,
            "type": "agent",
            "over_180": lines > cfg.line_threshold,
        })
    return results


def build_catalog(

    wiki_dir: Path,

    skills_dir: Path,

    agents_dir: Path,

    extra_dirs: list[Path],

) -> dict:
    """Build catalog.md in the wiki and return stats."""
    all_items: list[dict] = []

    # Scan primary dirs
    all_items.extend(scan_skills_dir(skills_dir))
    all_items.extend(scan_agents_dir(agents_dir))

    # Scan extra dirs (additional skill repos)
    for extra in extra_dirs:
        if extra.is_dir():
            # Try both patterns: dir/SKILL.md and flat *.md
            sub_skills = scan_skills_dir(extra)
            if sub_skills:
                all_items.extend(sub_skills)
            else:
                all_items.extend(scan_agents_dir(extra))

    # Stats
    total = len(all_items)
    over_180 = sum(1 for i in all_items if i["over_180"])
    skills_count = sum(1 for i in all_items if i["type"] == "skill")
    agents_count = sum(1 for i in all_items if i["type"] == "agent")

    # Build catalog.md
    lines = [
        "# Skill Catalog",
        "",
        f"> Auto-generated by catalog_builder.py on {TODAY}.",
        "> Individual wiki pages are created on-demand when skills are loaded by the router.",
        "",
        "## Summary",
        "",
        "| Metric | Count |",
        "|--------|-------|",
        f"| Total items | {total} |",
        f"| Skills (SKILL.md) | {skills_count} |",
        f"| Agents (flat .md) | {agents_count} |",
        f"| Items > 180 lines | {over_180} |",
        f"| Items ≤ 180 lines | {total - over_180} |",
        "",
        "## All Skills",
        "",
        "| Name | Type | Lines | Over 180 | Path |",
        "|------|------|-------|----------|------|",
    ]

    for item in all_items:
        flag = "⚠" if item["over_180"] else ""
        lines.append(
            f"| {item['name']} | {item['type']} | {item['lines']} | {flag} | `{item['path']}` |"
        )

    catalog_path = wiki_dir / "catalog.md"
    catalog_path.write_text("\n".join(lines) + "\n", encoding="utf-8")

    return {
        "total": total,
        "skills": skills_count,
        "agents": agents_count,
        "over_180": over_180,
        "catalog_path": str(catalog_path),
    }


def update_wiki_index(wiki_dir: Path, stats: dict) -> None:
    """Update index.md with catalog reference."""
    index_path = wiki_dir / "index.md"
    if not index_path.exists():
        return

    content = index_path.read_text(encoding="utf-8")
    catalog_ref = "- [[catalog]] - Full skill catalog (all installed items)"

    if "[[catalog]]" not in content:
        # Insert under ## Skills section
        lines = content.split("\n")
        for i, line in enumerate(lines):
            if line.strip() == "## Skills":
                lines.insert(i + 1, catalog_ref)
                break
        else:
            lines.append(catalog_ref)
        content = "\n".join(lines)

    # Update total count
    content = re.sub(
        r"Total pages: \d+",
        f"Total pages: {stats['total']}",
        content,
    )
    content = re.sub(
        r"Last updated: [\d-]+",
        f"Last updated: {TODAY}",
        content,
    )
    index_path.write_text(content, encoding="utf-8")


def append_log(wiki_dir: Path, stats: dict) -> None:
    """Append catalog build entry to log.md."""
    log_path = wiki_dir / "log.md"
    if not log_path.exists():
        return

    entry = (
        f"\n## [{TODAY}] catalog-build | all-skills\n"
        f"- Total items cataloged: {stats['total']}\n"
        f"- Skills: {stats['skills']}, Agents: {stats['agents']}\n"
        f"- Over 180 lines (micro-skill candidates): {stats['over_180']}\n"
        f"- Catalog written to: {stats['catalog_path']}\n"
    )
    with open(log_path, "a", encoding="utf-8") as f:
        f.write(entry)


def main() -> None:
    parser = argparse.ArgumentParser(description="Build bulk skill catalog in wiki")
    parser.add_argument("--wiki", default=str(cfg.wiki_dir), help="Wiki directory")
    parser.add_argument("--skills-dir", default=str(cfg.skills_dir), help="Skills directory")
    parser.add_argument("--agents-dir", default=str(cfg.agents_dir), help="Agents directory")
    parser.add_argument("--extra-dirs", nargs="*", default=[], help="Additional skill directories")
    args = parser.parse_args()

    wiki_dir = Path(args.wiki)
    if not wiki_dir.exists():
        print(f"Wiki not initialized at {wiki_dir}. Run wiki_sync.py --init first.", file=sys.stderr)
        sys.exit(1)

    stats = build_catalog(
        wiki_dir=wiki_dir,
        skills_dir=Path(args.skills_dir),
        agents_dir=Path(args.agents_dir),
        extra_dirs=[Path(d) for d in args.extra_dirs],
    )

    update_wiki_index(wiki_dir, stats)
    append_log(wiki_dir, stats)

    print(f"Catalog built: {stats['total']} items ({stats['over_180']} over 180 lines)")
    print(f"Written to: {stats['catalog_path']}")


if __name__ == "__main__":
    main()