"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
feat: add SKILL.md generation for AI agent discovery (Phase 6.5)
Alon Tevet65f3cf9df7a3
diff --git a/cli-anything-plugin/HARNESS.md b/cli-anything-plugin/HARNESS.mdindex 9b16737ef..64c2b20e3 100644--- a/cli-anything-plugin/HARNESS.md+++ b/cli-anything-plugin/HARNESS.md@@ -221,6 +221,89 @@ The TEST.md now serves as both the test plan (written before implementation) andthe test results documentation (appended after execution), providing a completerecord of the testing process.+### Phase 6.5: SKILL.md Generation++Generate a SKILL.md file that makes the CLI discoverable and usable by AI agents+through the skill-creator methodology. This file serves as a self-contained skill+definition that can be loaded by Claude Code or other AI assistants.++**Purpose:** SKILL.md files follow a standard format that enables AI agents to:+- Discover the CLI's capabilities+- Understand command structure and usage+- Generate correct command invocations+- Handle output programmatically++**SKILL.md Structure:**++1. **YAML Frontmatter** — Triggering metadata for skill discovery:+ ```yaml+ ---+ name: "cli-anything-<software>"+ description: "Brief description of what the CLI does"+ ---+ ```++2. **Markdown Body** — Usage instructions including:+ - Installation prerequisites+ - Basic command syntax+ - Command groups and their functions+ - Usage examples+ - Agent-specific guidance (JSON output, error handling)++**Generation Process:**++1. **Extract CLI metadata** using `skill_generator.py`:+ ```python+ from skill_generator import generate_skill_file++ skill_path = generate_skill_file(+ harness_path="/path/to/agent-harness",+ output_path="skills/<software>_SKILL.md"+ )+ ```++2. **The generator automatically extracts:**+ - Software name and version from setup.py+ - Command groups from the CLI file (Click decorators)+ - Documentation from README.md+ - System package requirements++3. **Customize the template** (optional):+ - Default template: `templates/SKILL.md.template`+ - Uses Jinja2 placeholders for dynamic content+ - Can be extended for software-specific sections++**Output Location:**++By default, SKILL.md files are generated in the `skills/` directory:+```+<software>/+└── agent-harness/+ └── skills/+ └── <software>_SKILL.md+```++**Manual Generation:**++```bash+cd cli-anything-plugin+python skill_generator.py /path/to/software/agent-harness -o skills/software_SKILL.md+```++**Integration with CLI Build:**++The SKILL.md generation should be run after Phase 6 (Test Documentation) completes+successfully, ensuring the CLI is fully documented and tested before creating the+skill definition.++**Key Principles:**++- SKILL.md must be self-contained (no external dependencies for understanding)+- Include agent-specific guidance for programmatic usage+- Document `--json` flag usage for machine-readable output+- List all command groups with brief descriptions+- Provide realistic examples that demonstrate common workflows+## Critical Lessons Learned### Use the Real Software — Don't Reimplement Itdiff --git a/cli-anything-plugin/README.md b/cli-anything-plugin/README.mdindex 9e07f841f..1d19351fc 100644--- a/cli-anything-plugin/README.md+++ b/cli-anything-plugin/README.md@@ -66,14 +66,15 @@ Build a complete CLI harness for any software application. Accepts a local path/cli-anything https://github.com/blender/blender```-This runs all 7 phases:+This runs all phases:1. Source Acquisition (clone if GitHub URL)2. Codebase Analysis3. CLI Architecture Design4. Implementation5. Test Planning6. Test Implementation & Documentation-7. PyPI Publishing and Installation+7. SKILL.md Generation+8. PyPI Publishing and Installation### `/cli-anything:refine <software-path> [focus]`@@ -209,6 +210,16 @@ Run and document:**Output:** `TEST.md` Part 2 (the results)+### Phase 6.5: SKILL.md Generation++Generate AI-discoverable skill definition:+- Extract CLI metadata using `skill_generator.py`+- Generate SKILL.md with YAML frontmatter (name, description)+- Include command groups, examples, and agent-specific guidance+- Output to `skills/<software>_SKILL.md`++**Output:** SKILL.md file for AI agent discovery+### Phase 7: PyPI Publishing and InstallationPackage and install:@@ -227,6 +238,8 @@ Package and install:└── agent-harness/├── <SOFTWARE>.md # Software-specific SOP├── setup.py # PyPI config (find_namespace_packages)+ ├── skills/ # Generated skill definitions+ │ └── <software>_SKILL.md # AI-discoverable skill file└── cli_anything/ # Namespace package (NO __init__.py)└── <software>/ # Sub-package (HAS __init__.py)├── README.md # Installation and usage@@ -302,6 +315,13 @@ The cli-anything methodology has successfully built CLIs for:- Architecture analysis- Test plans and results+### SKILL.md Generation+- Automatic skill definition generation for AI agent discovery+- YAML frontmatter with name and description for triggering+- Command groups and usage examples+- Agent-specific guidance for programmatic usage+- Follows skill-creator methodology+### PyPI Distribution- PEP 420 namespace packages under `cli_anything.*`- Unified package naming: `cli-anything-<software>`@@ -332,8 +352,9 @@ The cli-anything methodology has successfully built CLIs for:3. **Test thoroughly** - Aim for 100% pass rate4. **Document everything** - Future you will thank you5. **Use the validation command** - Catch issues early-6. **Install to PATH** - Make CLIs discoverable by running Phase 7-7. **Publish to PyPI** - Share your CLI with the community+6. **Generate SKILL.md** - Make CLIs discoverable by AI agents+7. **Install to PATH** - Make CLIs discoverable by running Phase 7+8. **Publish to PyPI** - Share your CLI with the community## Installation and Distribution@@ -416,6 +437,13 @@ Inspired by the ralph-loop plugin's iterative development approach.## Version History+### 1.1.0 (2026-03-12)+- Added SKILL.md generation (Phase 6.5)+- New `skill_generator.py` module for extracting CLI metadata+- Jinja2-based `SKILL.md.template` for customizable skill definitions+- SKILL.md files follow skill-creator methodology with YAML frontmatter+- AI agents can discover and use generated CLIs via SKILL.md files+### 1.0.0 (2026-03-05)- Initial release- Support for 4 commands: cli-anything, refine, test, validatediff --git a/cli-anything-plugin/commands/cli-anything.md b/cli-anything-plugin/commands/cli-anything.mdindex 86e49a374..d907bd54a 100644--- a/cli-anything-plugin/commands/cli-anything.md+++ b/cli-anything-plugin/commands/cli-anything.md@@ -69,6 +69,13 @@ This command implements the complete cli-anything methodology to build a product- Appends full test results to `TEST.md`- Documents test coverage and any gaps+### Phase 6.5: SKILL.md Generation+- Extracts CLI metadata using `skill_generator.py`+- Generates SKILL.md with YAML frontmatter and Markdown body+- Includes command groups, examples, and agent-specific guidance+- Outputs to `skills/<software>_SKILL.md` by default+- Makes the CLI discoverable and usable by AI agents+### Phase 7: PyPI Publishing and Installation- Creates `setup.py` with `find_namespace_packages(include=["cli_anything.*"])`- Package name: `cli-anything-<software>`, namespace: `cli_anything.<software>`@@ -120,5 +127,6 @@ The command succeeds when:5. Subprocess tests use `_resolve_cli()` and pass with `CLI_ANYTHING_FORCE_INSTALLED=1`6. TEST.md contains both plan and results7. README.md documents installation and usage-8. setup.py is created and local installation works-9. CLI is available in PATH as `cli-anything-<software>`+8. SKILL.md is generated with proper YAML frontmatter and command documentation+9. setup.py is created and local installation works+10. CLI is available in PATH as `cli-anything-<software>`diff --git a/cli-anything-plugin/skill_generator.py b/cli-anything-plugin/skill_generator.pynew file mode 100644index 000000000..6366a2822--- /dev/null+++ b/cli-anything-plugin/skill_generator.py@@ -0,0 +1,497 @@+"""+SKILL.md Generator for CLI-Anything++This module extracts metadata from CLI-Anything harnesses and generates+SKILL.md files following the skill-creator methodology.++The generated SKILL.md files contain:+- YAML frontmatter with name and description (triggering metadata)+- Markdown body with usage instructions+- Command documentation+- Examples for AI agents+"""++import os+import json+import re+from pathlib import Path+from typing import Optional+from dataclasses import dataclass, field+++@dataclass+class CommandInfo:+ """Information about a CLI command."""+ name: str+ description: str+++@dataclass+class CommandGroup:+ """A group of related CLI commands."""+ name: str+ description: str+ commands: list[CommandInfo] = field(default_factory=list)+++@dataclass+class Example:+ """An example of CLI usage."""+ title: str+ description: str+ code: str+++@dataclass+class SkillMetadata:+ """Metadata extracted from a CLI-Anything harness."""+ skill_name: str+ skill_description: str+ software_name: str+ skill_intro: str+ version: str+ system_package: Optional[str] = None+ command_groups: list[CommandGroup] = field(default_factory=list)+ examples: list[Example] = field(default_factory=list)+++def extract_cli_metadata(harness_path: str) -> SkillMetadata:+ """+ Extract metadata from a CLI-Anything harness directory.++ Args:+ harness_path: Path to the agent-harness directory++ Returns:+ SkillMetadata containing extracted information+ """+ harness_path = Path(harness_path)++ # Find the cli_anything/<software> directory+ cli_anything_dir = harness_path / "cli_anything"+ software_dirs = [d for d in cli_anything_dir.iterdir()+ if d.is_dir() and (d / "__init__.py").exists()]++ if not software_dirs:+ raise ValueError(f"No CLI package found in {harness_path}")++ software_dir = software_dirs[0]+ software_name = software_dir.name++ # Extract metadata from README.md+ readme_path = software_dir / "README.md"+ skill_intro = ""+ system_package = None++ if readme_path.exists():+ readme_content = readme_path.read_text(encoding="utf-8")+ skill_intro = extract_intro_from_readme(readme_content)+ system_package = extract_system_package(readme_content)++ # Extract version from setup.py+ setup_path = harness_path / "setup.py"+ version = "1.0.0"++ if setup_path.exists():+ version = extract_version_from_setup(setup_path)++ # Extract commands from CLI file+ cli_file = software_dir / f"{software_name}_cli.py"+ command_groups = []++ if cli_file.exists():+ command_groups = extract_commands_from_cli(cli_file)++ # Generate examples based on software type+ examples = generate_examples(software_name, command_groups)++ # Build skill name and description+ skill_name = f"cli-anything-{software_name}"+ skill_description = f"Command-line interface for {software_name.title()} - {skill_intro[:100]}..."++ return SkillMetadata(+ skill_name=skill_name,+ skill_description=skill_description,+ software_name=software_name,+ skill_intro=skill_intro,+ version=version,+ system_package=system_package,+ command_groups=command_groups,+ examples=examples+ )+++def extract_intro_from_readme(content: str) -> str:+ """Extract introduction text from README content."""+ # Find the first paragraph after the title+ lines = content.split("\n")+ intro_lines = []+ in_intro = False++ for line in lines:+ line = line.strip()+ if not line:+ if in_intro and intro_lines:+ break+ continue+ if line.startswith("# "):+ in_intro = True+ continue+ if line.startswith("##"):+ break+ if in_intro:+ intro_lines.append(line)++ return " ".join(intro_lines) or f"CLI interface for the software."+++def extract_system_package(content: str) -> Optional[str]:+ """Extract system package installation command from README."""+ # Look for apt/brew install patterns+ patterns = [+ r"`apt install ([\w\-]+)`",+ r"`brew install ([\w\-]+)`",+ r"apt-get install ([\w\-]+)",+ ]++ for pattern in patterns:+ match = re.search(pattern, content)+ if match:+ package = match.group(1)+ if "apt" in pattern:+ return f"apt install {package}"+ elif "brew" in pattern:+ return f"brew install {package}"++ return None+++def extract_version_from_setup(setup_path: Path) -> str:+ """Extract version from setup.py."""+ content = setup_path.read_text(encoding="utf-8")+ match = re.search(r'version\s*=\s*["\']([^"\']+)["\']', content)+ if match:+ return match.group(1)+ return "1.0.0"+++def extract_commands_from_cli(cli_path: Path) -> list[CommandGroup]:+ """Extract command groups and commands from CLI file."""+ content = cli_path.read_text(encoding="utf-8")+ groups = []++ # Find Click group decorators+ # Pattern: @click.group() or @<group_name>.group()+ group_pattern = r'@(\w+)\.group\([^)]*\)(?:\s*@click\.[^\n]+)*\s*def\s+(\w+)\([^)]*\):\s*"""([^"]*)"""'++ for match in re.finditer(group_pattern, content, re.MULTILINE):+ decorator_name = match.group(1)+ group_func = match.group(2)+ group_doc = match.group(3).strip()++ group_name = group_func.replace("_", " ").title()+ if not group_name:+ group_name = group_func.title()++ groups.append(CommandGroup(+ name=group_name,+ description=group_doc or f"Commands for {group_name.lower()} operations.",+ commands=[]+ ))++ # Find Click command decorators+ # Pattern: @<group>.command() followed by def <name>(): """doc"""+ command_pattern = r'@(\w+)\.command\([^)]*\)(?:\s*@click\.[^\n]+)*\s*def\s+(\w+)\([^)]*\):\s*"""([^"]*)"""'++ for match in re.finditer(command_pattern, content, re.MULTILINE):+ group_name = match.group(1)+ cmd_name = match.group(2)+ cmd_doc = match.group(3).strip()++ # Find the matching group+ for group in groups:+ if group.name.lower().replace(" ", "_") == group_name.lower():+ group.commands.append(CommandInfo(+ name=cmd_name.replace("_", "-"),+ description=cmd_doc or f"Execute {cmd_name} operation."+ ))++ # If no groups found, create a default one with all commands+ if not groups:+ default_group = CommandGroup(+ name="General",+ description="General commands for the CLI.",+ commands=[]+ )++ for match in re.finditer(command_pattern, content, re.MULTILINE):+ cmd_name = match.group(2)+ cmd_doc = match.group(3).strip()+ default_group.commands.append(CommandInfo(+ name=cmd_name.replace("_", "-"),+ description=cmd_doc or f"Execute {cmd_name} operation."+ ))++ if default_group.commands:+ groups.append(default_group)++ return groups+++def generate_examples(software_name: str, command_groups: list[CommandGroup]) -> list[Example]:+ """Generate usage examples based on software type and available commands."""+ examples = []++ # Basic project creation example+ examples.append(Example(+ title="Create a New Project",+ description=f"Create a new {software_name} project file.",+ code=f"""cli-anything-{software_name} project new -o myproject.json+# Or with JSON output for programmatic use+cli-anything-{software_name} --json project new -o myproject.json"""+ ))++ # REPL usage example+ examples.append(Example(+ title="Interactive REPL Session",+ description="Start an interactive session with undo/redo support.",+ code=f"""cli-anything-{software_name}+# Enter commands interactively+# Use 'help' to see available commands+# Use 'undo' and 'redo' for history navigation"""+ ))++ # Export example if export commands exist+ for group in command_groups:+ if "export" in group.name.lower():+ examples.append(Example(+ title="Export Project",+ description="Export the project to a final output format.",+ code=f"""cli-anything-{software_name} --project myproject.json export render output.pdf --overwrite"""+ ))+ break++ return examples+++def generate_skill_md(metadata: SkillMetadata, template_path: Optional[str] = None) -> str:+ """+ Generate SKILL.md content from metadata using Jinja2 template.++ Args:+ metadata: SkillMetadata containing CLI information+ template_path: Optional path to custom template file++ Returns:+ Generated SKILL.md content as string+ """+ try:+ from jinja2 import Environment, FileSystemLoader+ except ImportError:+ # Fallback to simple string formatting if Jinja2 not available+ return generate_skill_md_simple(metadata)++ # Load template+ if template_path is None:+ template_path = Path(__file__).parent / "templates" / "SKILL.md.template"+ else:+ template_path = Path(template_path)++ if not template_path.exists():+ return generate_skill_md_simple(metadata)++ env = Environment(loader=FileSystemLoader(template_path.parent))+ template = env.get_template(template_path.name)++ # Render template+ return template.render(+ skill_name=metadata.skill_name,+ skill_description=metadata.skill_description,+ software_name=metadata.software_name,+ skill_intro=metadata.skill_intro,+ version=metadata.version,+ system_package=metadata.system_package,+ command_groups=[{+ "name": g.name,+ "description": g.description,+ "commands": [{"name": c.name, "description": c.description} for c in g.commands]+ } for g in metadata.command_groups],+ examples=[{+ "title": e.title,+ "description": e.description,+ "code": e.code+ } for e in metadata.examples]+ )+++def generate_skill_md_simple(metadata: SkillMetadata) -> str:+ """Generate SKILL.md without Jinja2 dependency."""+ lines = [+ "---",+ f'name: "{metadata.skill_name}"',+ f'description: "{metadata.skill_description}"',+ "---",+ "",+ f"# {metadata.skill_name}",+ "",+ metadata.skill_intro,+ "",+ "## Installation",+ "",+ f"This CLI is installed as part of the cli-anything-{metadata.software_name} package:",+ "",+ f"```bash",+ f"pip install cli-anything-{metadata.software_name}",+ f"```",+ "",+ "**Prerequisites:**",+ "- Python 3.10+",+ f"- {metadata.software_name.title()} must be installed on your system",+ ]++ if metadata.system_package:+ lines.extend([+ f"- Install {metadata.software_name}: `{metadata.system_package}`"+ ])++ lines.extend([+ "",+ "## Usage",+ "",+ "### Basic Commands",+ "",+ "```bash",+ "# Show help",+ f"cli-anything-{metadata.software_name} --help",+ "",+ "# Start interactive REPL mode",+ f"cli-anything-{metadata.software_name}",+ "",+ "# Create a new project",+ f"cli-anything-{metadata.software_name} project new -o project.json",+ "",+ "# Run with JSON output (for agent consumption)",+ f"cli-anything-{metadata.software_name} --json project info -p project.json",+ "```",+ "",+ ])++ # Add command groups+ if metadata.command_groups:+ lines.append("## Command Groups")+ lines.append("")++ for group in metadata.command_groups:+ lines.append(f"### {group.name}")+ lines.append("")+ lines.append(group.description)+ lines.append("")++ if group.commands:+ lines.append("| Command | Description |")+ lines.append("|---------|-------------|")+ for cmd in group.commands:+ lines.append(f"| `{cmd.name}` | {cmd.description} |")+ lines.append("")++ # Add examples+ if metadata.examples:+ lines.append("## Examples")+ lines.append("")++ for example in metadata.examples:+ lines.append(f"### {example.title}")+ lines.append("")+ lines.append(example.description)+ lines.append("")+ lines.append("```bash")+ lines.append(example.code)+ lines.append("```")+ lines.append("")++ # Add AI agent guidance+ lines.extend([+ "## For AI Agents",+ "",+ "When using this CLI programmatically:",+ "",+ "1. **Always use `--json` flag** for parseable output",+ "2. **Check return codes** - 0 for success, non-zero for errors",+ "3. **Parse stderr** for error messages on failure",+ "4. **Use absolute paths** for all file operations",+ "5. **Verify outputs exist** after export operations",+ "",+ "## Version",+ "",+ metadata.version,+ ])++ return "\n".join(lines)+++def generate_skill_file(harness_path: str, output_path: Optional[str] = None,+ template_path: Optional[str] = None) -> str:+ """+ Generate a SKILL.md file for a CLI-Anything harness.++ Args:+ harness_path: Path to the agent-harness directory+ output_path: Optional output path for SKILL.md (default: skills/SKILL.md)+ template_path: Optional path to custom Jinja2 template++ Returns:+ Path to the generated SKILL.md file+ """+ # Extract metadata+ metadata = extract_cli_metadata(harness_path)++ # Generate content+ content = generate_skill_md(metadata, template_path)++ # Determine output path+ if output_path is None:+ # Default to skills/ directory+ output_path = Path("skills") / f"{metadata.software_name}_SKILL.md"+ else:+ output_path = Path(output_path)++ # Ensure output directory exists+ output_path.parent.mkdir(parents=True, exist_ok=True)++ # Write file+ output_path.write_text(content, encoding="utf-8")++ return str(output_path)+++# CLI interface for standalone usage+if __name__ == "__main__":+ import argparse++ parser = argparse.ArgumentParser(+ description="Generate SKILL.md for CLI-Anything harnesses"+ )+ parser.add_argument(+ "harness_path",+ help="Path to the agent-harness directory"+ )+ parser.add_argument(+ "-o", "--output",+ help="Output path for SKILL.md (default: skills/<software>_SKILL.md)",+ default=None+ )+ parser.add_argument(+ "-t", "--template",+ help="Path to custom Jinja2 template",+ default=None+ )++ args = parser.parse_args()++ output_file = generate_skill_file(+ args.harness_path,+ args.output,+ args.template+ )++ print(f"Generated: {output_file}")diff --git a/cli-anything-plugin/templates/SKILL.md.template b/cli-anything-plugin/templates/SKILL.md.templatenew file mode 100644index 000000000..12620456f--- /dev/null+++ b/cli-anything-plugin/templates/SKILL.md.template@@ -0,0 +1,119 @@+---+name: "{{ skill_name }}"+description: "{{ skill_description }}"+---++# {{ skill_name }}++{{ skill_intro }}++## Installation++This CLI is installed as part of the cli-anything-{{ software_name }} package:++```bash+pip install cli-anything-{{ software_name }}+```++**Prerequisites:**+- Python 3.10++- {{ software_name }} must be installed on your system+{% if system_package %}+- Install {{ software_name }}: `{{ system_package }}`+{% endif %}++## Usage++### Basic Commands++```bash+# Show help+cli-anything-{{ software_name }} --help++# Start interactive REPL mode+cli-anything-{{ software_name }}++# Create a new project+cli-anything-{{ software_name }} project new -o project.json++# Run with JSON output (for agent consumption)+cli-anything-{{ software_name }} --json project info -p project.json+```++### REPL Mode++When invoked without a subcommand, the CLI enters an interactive REPL session:++```bash+cli-anything-{{ software_name }}+# Enter commands interactively with tab-completion and history+```++## Command Groups++{% for group in command_groups %}+### {{ group.name }}++{{ group.description }}++| Command | Description |+|---------|-------------|+{% for cmd in group.commands %}+| `{{ cmd.name }}` | {{ cmd.description }} |+{% endfor %}++{% endfor %}+## Examples++{% for example in examples %}+### {{ example.title }}++{{ example.description }}++```bash+{{ example.code }}+```++{% endfor %}+## State Management++The CLI maintains session state with:++- **Undo/Redo**: Up to 50 levels of history+- **Project persistence**: Save/load project state as JSON+- **Session tracking**: Track modifications and changes++## Output Formats++All commands support dual output modes:++- **Human-readable** (default): Tables, colors, formatted text+- **Machine-readable** (`--json` flag): Structured JSON for agent consumption++```bash+# Human output+cli-anything-{{ software_name }} project info -p project.json++# JSON output for agents+cli-anything-{{ software_name }} --json project info -p project.json+```++## For AI Agents++When using this CLI programmatically:++1. **Always use `--json` flag** for parseable output+2. **Check return codes** - 0 for success, non-zero for errors+3. **Parse stderr** for error messages on failure+4. **Use absolute paths** for all file operations+5. **Verify outputs exist** after export operations++## More Information++- Full documentation: See README.md in the package+- Test coverage: See TEST.md in the package+- Methodology: See HARNESS.md in the cli-anything-plugin++## Version++{{ version }}