Coverage for little_loops / cli / generate_skill_descriptions.py: 81%
103 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-05-11 00:29 -0500
« prev ^ index » next coverage.py v7.12.0, created at 2026-05-11 00:29 -0500
1"""ll-generate-skill-descriptions: Auto-generate concise skill descriptions via Claude CLI.
3For each skills/*/SKILL.md that does NOT have disable-model-invocation: true,
4extract trigger keywords and body excerpt, prompt Claude (haiku) to produce a
5description ≤100 characters, and optionally write it back to the frontmatter.
7Dry-run by default. Use --apply to write back.
8"""
10from __future__ import annotations
12import argparse
13import re
14import sys
15from pathlib import Path
17__all__ = ["main_generate_skill_descriptions"]
19_MAX_DESC_LEN = 100
20_BODY_EXCERPT_CHARS = 500
23def _find_plugin_root() -> Path:
24 from little_loops.skill_expander import _find_plugin_root as _fpr
26 return _fpr()
29def _parse_frontmatter(text: str) -> tuple[dict[str, str], str]:
30 """Return (frontmatter_keys, body_text) from a SKILL.md string."""
31 if not text.startswith("---"):
32 return {}, text
33 end = text.find("---", 3)
34 if end == -1:
35 return {}, text
36 raw = text[3:end]
37 body = text[end + 3 :].lstrip("\n")
38 fm: dict[str, str] = {}
39 for line in raw.splitlines():
40 if ":" in line:
41 key, _, val = line.partition(":")
42 fm[key.strip()] = val.strip()
43 return fm, body
46def _extract_trigger_keywords(description: str) -> str:
47 """Pull the 'Trigger keywords:' line from a description field value."""
48 for line in description.splitlines():
49 if line.strip().lower().startswith("trigger keywords"):
50 return line.strip()
51 return ""
54def _build_prompt(skill_name: str, trigger_keywords: str, body_excerpt: str) -> str:
55 return (
56 f"Generate a single-line skill description for the '{skill_name}' skill.\n"
57 f"Rules:\n"
58 f"- Maximum {_MAX_DESC_LEN} characters total\n"
59 f"- No bullet points or newlines\n"
60 f"- Start with 'Use when' or a clear trigger phrase\n"
61 f"- Include the most important trigger keywords\n"
62 f"\nTrigger keywords: {trigger_keywords or '(none)'}\n"
63 f"Skill body excerpt:\n{body_excerpt[:_BODY_EXCERPT_CHARS]}\n"
64 f"\nRespond with ONLY the description text, nothing else."
65 )
68def _write_description_to_frontmatter(skill_md: Path, new_desc: str) -> None:
69 """Replace the description: field in SKILL.md frontmatter with new_desc."""
70 text = skill_md.read_text()
71 if not text.startswith("---"):
72 return
73 end = text.find("---", 3)
74 if end == -1:
75 return
76 fm_block = text[3:end]
77 after = text[end:]
79 # Replace existing description line (single-line only)
80 new_fm_block = re.sub(
81 r"^description:.*$",
82 f"description: {new_desc}",
83 fm_block,
84 flags=re.MULTILINE,
85 )
86 skill_md.write_text("---" + new_fm_block + after)
89def _process_skills(
90 skills_dir: Path, apply: bool, quiet: bool
91) -> tuple[int, int, int]:
92 """Process all skills; return (processed, skipped, errors)."""
93 from little_loops.subprocess_utils import run_claude_command
95 processed = skipped = errors = 0
97 for skill_md in sorted(skills_dir.glob("*/SKILL.md")):
98 skill_name = skill_md.parent.name
99 try:
100 text = skill_md.read_text()
101 except OSError as exc:
102 if not quiet:
103 print(f" ERROR {skill_name}: cannot read file: {exc}", file=sys.stderr)
104 errors += 1
105 continue
107 fm, body = _parse_frontmatter(text)
109 if fm.get("disable-model-invocation", "").lower() in ("true", "yes", "1"):
110 if not quiet:
111 print(f" SKIP {skill_name} (disable-model-invocation: true)")
112 skipped += 1
113 continue
115 trigger_keywords = _extract_trigger_keywords(fm.get("description", ""))
116 prompt = _build_prompt(skill_name, trigger_keywords, body)
118 result = run_claude_command(
119 command=prompt,
120 timeout=60,
121 )
123 if result.returncode != 0:
124 if not quiet:
125 print(f" ERROR {skill_name}: Claude returned exit {result.returncode}", file=sys.stderr)
126 errors += 1
127 continue
129 new_desc = result.stdout.strip().splitlines()[0].strip() if result.stdout.strip() else ""
131 if len(new_desc) > _MAX_DESC_LEN:
132 new_desc = new_desc[:_MAX_DESC_LEN]
134 if not new_desc:
135 if not quiet:
136 print(f" ERROR {skill_name}: empty description from Claude", file=sys.stderr)
137 errors += 1
138 continue
140 if apply:
141 _write_description_to_frontmatter(skill_md, new_desc)
142 if not quiet:
143 print(f" APPLY {skill_name}: {new_desc}")
144 else:
145 if not quiet:
146 print(f" DRY {skill_name}: {new_desc}")
148 processed += 1
150 return processed, skipped, errors
153def main_generate_skill_descriptions() -> int:
154 """Entry point for ll-generate-skill-descriptions CLI."""
155 parser = argparse.ArgumentParser(
156 prog="ll-generate-skill-descriptions",
157 description=(
158 "Auto-generate ≤100-char skill descriptions via Claude CLI. "
159 "Dry-run by default; use --apply to write back to SKILL.md frontmatter."
160 ),
161 formatter_class=argparse.RawDescriptionHelpFormatter,
162 epilog="""
163Examples:
164 ll-generate-skill-descriptions # Dry-run: preview generated descriptions
165 ll-generate-skill-descriptions --apply # Write descriptions back to SKILL.md files
166 ll-generate-skill-descriptions --quiet # Suppress per-skill output
167""",
168 )
169 parser.add_argument(
170 "--apply",
171 action="store_true",
172 default=False,
173 help="Write generated descriptions back to SKILL.md frontmatter (default: dry-run only)",
174 )
175 parser.add_argument(
176 "--quiet",
177 action="store_true",
178 default=False,
179 help="Suppress per-skill output; only print final summary",
180 )
182 args = parser.parse_args()
184 plugin_root = _find_plugin_root()
185 skills_dir = plugin_root / "skills"
187 if not skills_dir.exists():
188 print(f"ERROR: skills directory not found: {skills_dir}", file=sys.stderr)
189 return 1
191 mode = "APPLY" if args.apply else "DRY-RUN"
192 if not args.quiet:
193 print(f"ll-generate-skill-descriptions [{mode}]")
194 print(f"Skills dir: {skills_dir}")
195 print()
197 processed, skipped, errors = _process_skills(skills_dir, args.apply, args.quiet)
199 print(f"\nDone: {processed} generated, {skipped} skipped, {errors} errors")
200 return 0 if errors == 0 else 1