Coverage for little_loops / cli / generate_skill_descriptions.py: 0%
99 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-05-28 13:07 -0500
« prev ^ index » next coverage.py v7.12.0, created at 2026-05-28 13:07 -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.
32 Thin wrapper around ``little_loops.frontmatter.parse_skill_frontmatter``
33 that preserves the historical ``(fm, body)`` tuple return shape.
34 """
35 from little_loops.frontmatter import parse_skill_frontmatter
37 if not text.startswith("---"):
38 return {}, text
39 end = text.find("---", 3)
40 if end == -1:
41 return {}, text
42 body = text[end + 3 :].lstrip("\n")
43 fm = parse_skill_frontmatter(text)
44 return fm, body
47def _extract_trigger_keywords(description: str) -> str:
48 """Pull the 'Trigger keywords:' line from a description field value."""
49 for line in description.splitlines():
50 if line.strip().lower().startswith("trigger keywords"):
51 return line.strip()
52 return ""
55def _build_prompt(skill_name: str, trigger_keywords: str, body_excerpt: str) -> str:
56 return (
57 f"Generate a single-line skill description for the '{skill_name}' skill.\n"
58 f"Rules:\n"
59 f"- Maximum {_MAX_DESC_LEN} characters total\n"
60 f"- No bullet points or newlines\n"
61 f"- Start with 'Use when' or a clear trigger phrase\n"
62 f"- Include the most important trigger keywords\n"
63 f"\nTrigger keywords: {trigger_keywords or '(none)'}\n"
64 f"Skill body excerpt:\n{body_excerpt[:_BODY_EXCERPT_CHARS]}\n"
65 f"\nRespond with ONLY the description text, nothing else."
66 )
69def _write_description_to_frontmatter(skill_md: Path, new_desc: str) -> None:
70 """Replace the description: field in SKILL.md frontmatter with new_desc."""
71 text = skill_md.read_text()
72 if not text.startswith("---"):
73 return
74 end = text.find("---", 3)
75 if end == -1:
76 return
77 fm_block = text[3:end]
78 after = text[end:]
80 # Replace existing description line (single-line only)
81 new_fm_block = re.sub(
82 r"^description:.*$",
83 f"description: {new_desc}",
84 fm_block,
85 flags=re.MULTILINE,
86 )
87 skill_md.write_text("---" + new_fm_block + after)
90def _process_skills(skills_dir: Path, apply: bool, quiet: bool) -> tuple[int, int, int]:
91 """Process all skills; return (processed, skipped, errors)."""
92 from little_loops.subprocess_utils import run_claude_command
94 processed = skipped = errors = 0
96 for skill_md in sorted(skills_dir.glob("*/SKILL.md")):
97 skill_name = skill_md.parent.name
98 try:
99 text = skill_md.read_text()
100 except OSError as exc:
101 if not quiet:
102 print(f" ERROR {skill_name}: cannot read file: {exc}", file=sys.stderr)
103 errors += 1
104 continue
106 fm, body = _parse_frontmatter(text)
108 if fm.get("disable-model-invocation", "").lower() in ("true", "yes", "1"):
109 if not quiet:
110 print(f" SKIP {skill_name} (disable-model-invocation: true)")
111 skipped += 1
112 continue
114 trigger_keywords = _extract_trigger_keywords(fm.get("description", ""))
115 prompt = _build_prompt(skill_name, trigger_keywords, body)
117 result = run_claude_command(
118 command=prompt,
119 timeout=60,
120 )
122 if result.returncode != 0:
123 if not quiet:
124 print(
125 f" ERROR {skill_name}: Claude returned exit {result.returncode}",
126 file=sys.stderr,
127 )
128 errors += 1
129 continue
131 new_desc = result.stdout.strip().splitlines()[0].strip() if result.stdout.strip() else ""
133 if len(new_desc) > _MAX_DESC_LEN:
134 new_desc = new_desc[:_MAX_DESC_LEN]
136 if not new_desc:
137 if not quiet:
138 print(f" ERROR {skill_name}: empty description from Claude", file=sys.stderr)
139 errors += 1
140 continue
142 if apply:
143 _write_description_to_frontmatter(skill_md, new_desc)
144 if not quiet:
145 print(f" APPLY {skill_name}: {new_desc}")
146 else:
147 if not quiet:
148 print(f" DRY {skill_name}: {new_desc}")
150 processed += 1
152 return processed, skipped, errors
155def main_generate_skill_descriptions() -> int:
156 """Entry point for ll-generate-skill-descriptions CLI."""
157 parser = argparse.ArgumentParser(
158 prog="ll-generate-skill-descriptions",
159 description=(
160 "Auto-generate ≤100-char skill descriptions via Claude CLI. "
161 "Dry-run by default; use --apply to write back to SKILL.md frontmatter."
162 ),
163 formatter_class=argparse.RawDescriptionHelpFormatter,
164 epilog="""
165Examples:
166 ll-generate-skill-descriptions # Dry-run: preview generated descriptions
167 ll-generate-skill-descriptions --apply # Write descriptions back to SKILL.md files
168 ll-generate-skill-descriptions --quiet # Suppress per-skill output
169""",
170 )
171 parser.add_argument(
172 "--apply",
173 action="store_true",
174 default=False,
175 help="Write generated descriptions back to SKILL.md frontmatter (default: dry-run only)",
176 )
177 parser.add_argument(
178 "--quiet",
179 action="store_true",
180 default=False,
181 help="Suppress per-skill output; only print final summary",
182 )
184 args = parser.parse_args()
186 plugin_root = _find_plugin_root()
187 skills_dir = plugin_root / "skills"
189 if not skills_dir.exists():
190 print(f"ERROR: skills directory not found: {skills_dir}", file=sys.stderr)
191 return 1
193 mode = "APPLY" if args.apply else "DRY-RUN"
194 if not args.quiet:
195 print(f"ll-generate-skill-descriptions [{mode}]")
196 print(f"Skills dir: {skills_dir}")
197 print()
199 processed, skipped, errors = _process_skills(skills_dir, args.apply, args.quiet)
201 print(f"\nDone: {processed} generated, {skipped} skipped, {errors} errors")
202 return 0 if errors == 0 else 1