Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:28:02 +08:00
commit 4ea8c8d0b0
15 changed files with 4003 additions and 0 deletions

View File

@@ -0,0 +1,467 @@
---
name: documentation-update
description: Regenerates documentation files (agents.md, agent-skills.md, plugins.md, usage.md) from marketplace data using Jinja templates. Use when plugins are added, updated, or removed to keep documentation in sync.
---
# Documentation Update Skill
This skill automatically regenerates documentation files in the `docs/` directory by reading the marketplace catalog and applying Jinja2 templates.
## Purpose
Maintain synchronized documentation by:
- Generating agent reference documentation
- Creating skill catalog documentation
- Building plugin directory
- Updating usage guides
- Ensuring consistency across all docs
## When to Use
Use this skill when:
- A new plugin is added to the marketplace
- An existing plugin is updated (components added/removed)
- Agent or skill metadata changes
- Documentation needs to be regenerated
- Ensuring docs match marketplace state
## Documentation Files
This skill generates four main documentation files:
### 1. agents.md
Complete reference of all agents across all plugins:
- Organized by plugin
- Lists agent name, description, and model
- Includes links to agent files
- Shows agent capabilities and use cases
### 2. agent-skills.md
Catalog of all skills with progressive disclosure details:
- Organized by plugin
- Lists skill name and description
- Shows "Use when" triggers
- Includes skill structure information
### 3. plugins.md
Directory of all plugins in the marketplace:
- Organized by category
- Shows plugin name, description, and version
- Lists components (agents, commands, skills)
- Provides installation and usage information
### 4. usage.md
Usage guide and command reference:
- Getting started instructions
- Command usage examples
- Workflow patterns
- Integration guides
## Template Structure
Templates are stored in `assets/` using Jinja2 syntax:
```
assets/
├── agents.md.j2
├── agent-skills.md.j2
├── plugins.md.j2
└── usage.md.j2
```
### Template Variables
All templates receive the following context:
```python
{
"marketplace": {
"name": "marketplace-name",
"owner": {...},
"metadata": {...},
"plugins": [...]
},
"plugins_by_category": {
"category-name": [plugin1, plugin2, ...]
},
"all_agents": [
{
"plugin": "plugin-name",
"name": "agent-name",
"file": "agent-file.md",
"description": "...",
"model": "..."
}
],
"all_skills": [
{
"plugin": "plugin-name",
"name": "skill-name",
"path": "skill-path",
"description": "..."
}
],
"all_commands": [
{
"plugin": "plugin-name",
"name": "command-name",
"file": "command-file.md",
"description": "..."
}
],
"stats": {
"total_plugins": 10,
"total_agents": 25,
"total_commands": 15,
"total_skills": 30
}
}
```
## Python Script
The skill includes a Python script `doc_generator.py` that:
1. **Loads marketplace.json**
- Reads the marketplace catalog
- Validates structure
- Builds component index
2. **Scans Plugin Files**
- Reads agent/command frontmatter
- Extracts skill metadata
- Builds comprehensive component list
3. **Prepares Template Context**
- Organizes plugins by category
- Creates component indexes
- Calculates statistics
4. **Renders Templates**
- Applies Jinja2 templates
- Generates documentation files
- Writes to docs/ directory
### Usage
```bash
# Generate all documentation files
python doc_generator.py
# Generate specific file only
python doc_generator.py --file agents
# Dry run (show output without writing)
python doc_generator.py --dry-run
# Specify custom paths
python doc_generator.py \
--marketplace .claude-plugin/marketplace.json \
--templates plugins/claude-plugin/skills/documentation-update/assets \
--output docs
```
## Integration with Commands
The `/claude-plugin:create` and `/claude-plugin:update` commands should invoke this skill automatically after marketplace updates:
### Workflow
```
1. Plugin operation completes (add/update/remove)
2. Marketplace.json is updated
3. Invoke documentation-update skill
4. Documentation files regenerated
5. Changes ready to commit
```
### Example Integration
```python
# After creating/updating plugin
print("Updating documentation...")
# Run doc generator
import subprocess
result = subprocess.run(
["python", "plugins/claude-plugin/skills/documentation-update/doc_generator.py"],
capture_output=True,
text=True
)
if result.returncode == 0:
print("✓ Documentation updated")
else:
print(f"❌ Documentation update failed: {result.stderr}")
```
## Template Examples
### agents.md.j2
```jinja2
# Agent Reference
This document lists all agents available across plugins in the marketplace.
{% for category, plugins in plugins_by_category.items() %}
## {{ category|title }}
{% for plugin in plugins %}
### {{ plugin.name }}
{{ plugin.description }}
**Agents:**
{% for agent in all_agents %}
{% if agent.plugin == plugin.name %}
- **{{ agent.name }}** (`{{ agent.model }}`)
- {{ agent.description }}
- File: `plugins/{{ plugin.name }}/agents/{{ agent.file }}`
{% endif %}
{% endfor %}
{% endfor %}
{% endfor %}
---
*Last updated: {{ now }}*
*Total agents: {{ stats.total_agents }}*
```
### agent-skills.md.j2
```jinja2
# Agent Skills Reference
This document catalogs all skills with progressive disclosure patterns.
{% for plugin in marketplace.plugins %}
## {{ plugin.name }}
{{ plugin.description }}
**Skills:**
{% for skill in all_skills %}
{% if skill.plugin == plugin.name %}
### {{ skill.name }}
{{ skill.description }}
- **Location:** `plugins/{{ plugin.name }}/skills/{{ skill.path }}/`
- **Structure:** SKILL.md + assets/ + references/
{% endif %}
{% endfor %}
{% endfor %}
---
*Last updated: {{ now }}*
*Total skills: {{ stats.total_skills }}*
```
## Error Handling
### Marketplace Not Found
```
Error: Marketplace file not found: .claude-plugin/marketplace.json
Suggestion: Ensure marketplace.json exists
```
### Template Not Found
```
Error: Template file not found: assets/agents.md.j2
Suggestion: Ensure all template files exist in assets/
```
### Invalid Plugin Structure
```
Warning: Plugin 'plugin-name' missing components
Suggestion: Verify plugin has agents or commands
```
### Frontmatter Parse Error
```
Warning: Could not parse frontmatter in agents/agent-name.md
Suggestion: Check YAML frontmatter syntax
```
## Best Practices
1. **Always Regenerate After Changes**
- Run after every plugin add/update/remove
- Ensure docs stay synchronized
- Commit documentation with plugin changes
2. **Validate Before Generation**
- Run marketplace validation first
- Fix any errors or warnings
- Ensure all files exist
3. **Review Generated Output**
- Check generated files for correctness
- Verify formatting and links
- Test any code examples
4. **Template Maintenance**
- Keep templates simple and readable
- Use consistent formatting
- Document template variables
5. **Version Control**
- Commit documentation changes
- Include in pull requests
- Document significant changes
## Template Customization
### Adding New Sections
To add a new section to a template:
1. **Modify Template**
```jinja2
## New Section
{% for plugin in marketplace.plugins %}
### {{ plugin.name }}
[Your content here]
{% endfor %}
```
2. **Update Context (if needed)**
- Add new data to template context in doc_generator.py
- Process additional metadata
3. **Test Output**
- Run generator with dry-run
- Verify formatting
- Check for errors
### Creating New Templates
To add a new documentation file:
1. **Create Template**
- Add `assets/newdoc.md.j2`
- Define structure and content
2. **Update Script**
- Add to doc_generator.py template list
- Define output path
3. **Test Generation**
- Run generator
- Verify output
- Commit template and output
## File Structure
```
plugins/claude-plugin/skills/documentation-update/
├── SKILL.md # This file
├── doc_generator.py # Python implementation
├── assets/ # Jinja2 templates
│ ├── agents.md.j2
│ ├── agent-skills.md.j2
│ ├── plugins.md.j2
│ └── usage.md.j2
└── references/ # Optional examples
└── template-examples.md
```
## Requirements
- Python 3.8+
- No external dependencies (uses standard library only)
- Access to `.claude-plugin/marketplace.json`
- Read access to plugin directories
- Write access to `docs/` directory
## Success Criteria
After running this skill:
- ✓ All documentation files generated
- ✓ Content matches marketplace state
- ✓ All links are valid
- ✓ Formatting is consistent
- ✓ Statistics are accurate
- ✓ No template rendering errors
## Maintenance
### Updating Templates
When marketplace structure changes:
1. **Assess Impact**
- Identify affected templates
- Determine required changes
2. **Update Templates**
- Modify Jinja2 templates
- Test with current data
3. **Update Script**
- Adjust context preparation if needed
- Add new data processing
4. **Validate Output**
- Regenerate all docs
- Review changes
- Test links and formatting
### Version Compatibility
- Templates should handle missing fields gracefully
- Use Jinja2 default filters for optional data
- Validate marketplace version compatibility
## Example Output
The skill generates comprehensive, well-formatted documentation:
- **agents.md**: ~500-1000 lines for 20-30 agents
- **agent-skills.md**: ~300-600 lines for 30-50 skills
- **plugins.md**: ~400-800 lines for 10-20 plugins
- **usage.md**: ~200-400 lines of usage information
All files include:
- Clear structure and headings
- Formatted tables where appropriate
- Links to source files
- Statistics and metadata
- Last updated timestamp

View File

@@ -0,0 +1,73 @@
# Agent Skills Reference
This document catalogs all agent skills with progressive disclosure patterns across the marketplace.
## Overview
- **Total Skills**: {{ stats.total_skills }}
- **Total Plugins**: {{ stats.total_plugins }}
- **Last Updated**: {{ now }}
---
## What are Agent Skills?
Agent skills are modular knowledge packages that use progressive disclosure architecture:
1. **Metadata** (Frontmatter) - Always loaded
2. **Instructions** - Core guidance loaded when activated
3. **Resources** (assets/) - Loaded on demand
All skills follow the [Anthropic Agent Skills Specification](https://github.com/anthropics/skills/blob/main/agent_skills_spec.md).
---
{% for plugin in marketplace.plugins %}
## {{ plugin.name }}
**Description**: {{ plugin.description }}
**Version**: {{ plugin.version }}
{% if plugin.skills %}
**Skills**:
{% for skill in all_skills %}
{% if skill.plugin == plugin.name %}
### {{ skill.name }}
{{ skill.description }}
**Location**: `plugins/{{ plugin.name }}/skills/{{ skill.path }}/`
**Structure**:
- `SKILL.md` - Skill definition with frontmatter
- `assets/` - Templates, configurations, examples
- `references/` - Additional documentation
{% endif %}
{% endfor %}
{% else %}
*No skills defined*
{% endif %}
---
{% endfor %}
## Progressive Disclosure Benefits
- **Token Efficiency**: Load only relevant knowledge when needed
- **Specialized Expertise**: Deep domain knowledge without bloat
- **Clear Activation**: Explicit triggers prevent unwanted invocation
- **Composability**: Mix and match skills across workflows
- **Maintainability**: Isolated updates don't affect other skills
## Using Skills
Skills are automatically invoked by agents when their trigger conditions are met. You can also manually invoke skills when needed for specific operations.
---
*This documentation is automatically generated from the marketplace catalog.*
*Last updated: {{ now }}*

View File

@@ -0,0 +1,64 @@
# Agent Reference
This document provides a comprehensive reference of all agents available across plugins in the marketplace.
## Overview
- **Total Agents**: {{ stats.total_agents }}
- **Total Plugins**: {{ stats.total_plugins }}
- **Last Updated**: {{ now }}
---
{% for category, plugins in plugins_by_category.items() %}
## {{ category|title }} Agents
{% for plugin in plugins %}
### {{ plugin.name }}
**Description**: {{ plugin.description }}
**Version**: {{ plugin.version }}
{% if plugin.agents %}
**Agents**:
{% for agent in all_agents %}
{% if agent.plugin == plugin.name %}
#### {{ agent.name }}
- **Model**: `{{ agent.model }}`
- **Description**: {{ agent.description }}
- **Location**: `plugins/{{ plugin.name }}/agents/{{ agent.file }}`
{% endif %}
{% endfor %}
{% else %}
*No agents defined*
{% endif %}
---
{% endfor %}
{% endfor %}
## Usage
To use an agent from the command line:
```bash
# Invoke with Task tool
Use Task tool with subagent_type="<agent-name>"
```
## Model Distribution
Agents are optimized for specific models based on their complexity:
- **Haiku**: Fast execution for deterministic tasks
- **Sonnet**: Complex reasoning and architecture decisions
---
*This documentation is automatically generated from the marketplace catalog.*
*Last updated: {{ now }}*

View File

@@ -0,0 +1,88 @@
# Plugin Directory
Complete catalog of all plugins available in the marketplace.
## Overview
- **Total Plugins**: {{ stats.total_plugins }}
- **Total Agents**: {{ stats.total_agents }}
- **Total Commands**: {{ stats.total_commands }}
- **Total Skills**: {{ stats.total_skills }}
- **Last Updated**: {{ now }}
---
{% for category, plugins in plugins_by_category.items() %}
## {{ category|title }}
{% for plugin in plugins %}
### {{ plugin.name }}
{{ plugin.description }}
**Version**: {{ plugin.version }}
**Author**: {% if plugin.author %}{{ plugin.author.name }}{% else %}{{ marketplace.owner.name }}{% endif %}
**License**: {{ plugin.license }}
{% if plugin.keywords %}
**Keywords**: {{ plugin.keywords|join(', ') }}
{% endif %}
**Components**:
{% if plugin.agents %}
- **Agents**: {{ plugin.agents|length }}
{% endif %}
{% if plugin.commands %}
- **Commands**: {{ plugin.commands|length }}
{% endif %}
{% if plugin.skills %}
- **Skills**: {{ plugin.skills|length }}
{% endif %}
**Location**: `{{ plugin.source }}`
{% if plugin.homepage %}
**Homepage**: {{ plugin.homepage }}
{% endif %}
{% if plugin.repository %}
**Repository**: {{ plugin.repository }}
{% endif %}
---
{% endfor %}
{% endfor %}
## Plugin Architecture
Each plugin follows these principles:
- **Single Responsibility**: One plugin does one thing well
- **Composability**: Mix and match plugins based on needs
- **Context Efficiency**: Smaller tools for better LLM performance
- **Maintainability**: Isolated updates, clear boundaries
## Installation
All plugins are included in this marketplace. To use a plugin:
1. Ensure the plugin directory exists in `plugins/`
2. Use agents via the Task tool
3. Use commands via slash commands
4. Skills are automatically loaded when needed
## Categories
Plugins are organized into the following categories:
{% for category in plugins_by_category.keys() %}
- **{{ category|title }}**: {{ plugins_by_category[category]|length }} plugin(s)
{% endfor %}
---
*This documentation is automatically generated from the marketplace catalog.*
*Last updated: {{ now }}*

View File

@@ -0,0 +1,250 @@
# Usage Guide
Comprehensive guide for using Claude Code plugins, agents, commands, and skills from this marketplace.
## Overview
This marketplace provides {{ stats.total_plugins }} plugin(s) with:
- {{ stats.total_agents }} specialized agent(s)
- {{ stats.total_commands }} command(s)
- {{ stats.total_skills }} skill(s)
**Last Updated**: {{ now }}
---
## Quick Start
### Using Agents
Agents are specialized domain experts invoked via the Task tool:
```
Use Task tool with subagent_type="<agent-name>"
```
**Example**:
```
Use Task tool with subagent_type="plugin-architect" to design a new plugin
```
### Using Commands
Commands are slash commands for specific workflows:
```bash
/<command-name> [arguments]
```
**Available Commands**:
{% for command in all_commands %}
- `{{ command.name }}` - {{ command.description }}
- Plugin: {{ command.plugin }}
- File: `plugins/{{ command.plugin }}/commands/{{ command.file }}`
{% endfor %}
### Using Skills
Skills are automatically invoked by agents when their trigger conditions are met. Skills provide:
- Modular knowledge packages
- Progressive disclosure (metadata → instructions → resources)
- Spec-compliant with Anthropic guidelines
**Available Skills**:
{% for skill in all_skills %}
- `{{ skill.name }}` - {{ skill.description }}
- Plugin: {{ skill.plugin }}
- Path: `plugins/{{ skill.plugin }}/skills/{{ skill.path }}/`
{% endfor %}
---
## Common Workflows
### Creating a New Plugin
Use the `claude-plugin` plugin to create new plugins:
```bash
# Create a new plugin
/create <plugin-name> "<description>" [components]
# Example
/create golang-advanced "Advanced Go development tools" agents,commands,skills
```
### Updating an Existing Plugin
Modify plugins by adding, updating, or removing components:
```bash
# Add a new agent
/update <plugin-name> add agent <agent-name>
# Modify a command
/update <plugin-name> modify command <command-name>
# Remove a skill
/update <plugin-name> remove skill <skill-name>
```
### Working with Agents
Invoke agents for specialized tasks:
```
# For architecture and design
Use Task tool with subagent_type="plugin-architect"
# Add your task description
[Describe what you need the agent to do]
```
---
## Plugin Architecture
### Directory Structure
```
plugins/
├── <plugin-name>/
│ ├── agents/ # Specialized agents (optional)
│ │ └── agent.md
│ ├── commands/ # Slash commands (optional)
│ │ └── command.md
│ └── skills/ # Agent skills (optional)
│ └── skill-name/
│ ├── SKILL.md
│ ├── assets/
│ └── references/
```
### Component Requirements
Each plugin must have:
- At least one agent OR one command
- Proper YAML frontmatter in all files
- Clear, focused purpose
- Entry in marketplace.json
---
## Agent Reference
### Available Agents
{% for agent in all_agents %}
#### {{ agent.name }}
- **Plugin**: {{ agent.plugin }}
- **Model**: {{ agent.model }}
- **Description**: {{ agent.description }}
- **Invocation**: `Use Task tool with subagent_type="{{ agent.name }}"`
{% endfor %}
### Model Selection
Agents use different models based on task complexity:
- **Haiku**: Fast execution for deterministic tasks
- Code generation from specs
- Test creation
- Documentation generation
- **Sonnet**: Complex reasoning and architecture
- System design
- Security audits
- Language expertise
- Multi-agent orchestration
---
## Best Practices
### When Creating Plugins
1. **Single Responsibility**: One plugin, one purpose
2. **Clear Naming**: Use hyphen-case, be descriptive
3. **Complete Documentation**: Include frontmatter and examples
4. **Spec Compliance**: Follow Anthropic guidelines
5. **Test Thoroughly**: Verify functionality before committing
### When Using Agents
1. **Choose the Right Agent**: Match agent expertise to task
2. **Provide Clear Context**: Detailed task descriptions
3. **Use Appropriate Models**: Haiku for speed, Sonnet for complexity
4. **Compose When Needed**: Combine multiple agents for complex workflows
### When Working with Skills
1. **Progressive Disclosure**: Load only what's needed
2. **Clear Triggers**: Use explicit activation criteria
3. **Modular Design**: Keep skills focused and reusable
4. **Document Well**: Include usage examples
---
## Marketplace Management
### Adding Plugins
Plugins are added via the marketplace update process:
1. Create plugin directory and components
2. Update `.claude-plugin/marketplace.json`
3. Regenerate documentation
### Updating Documentation
Documentation is automatically generated from the marketplace:
```bash
# Regenerate all docs
python plugins/claude-plugin/skills/documentation-update/doc_generator.py
# Generate specific file
python plugins/claude-plugin/skills/documentation-update/doc_generator.py --file agents
```
---
## Categories
Plugins are organized by category:
{% for category, plugins in plugins_by_category.items() %}
### {{ category|title }}
{% for plugin in plugins %}
- **{{ plugin.name }}** - {{ plugin.description }}
{% endfor %}
{% endfor %}
---
## Getting Help
- **Documentation**: See `docs/` directory for detailed references
- **Architecture**: See `docs/architecture.md` for design principles
- **Contributing**: See `.github/CONTRIBUTING.md` for contribution guidelines
---
## Resources
- [Architecture Documentation](./architecture.md)
- [Agent Reference](./agents.md)
- [Skills Reference](./agent-skills.md)
- [Plugin Directory](./plugins.md)
---
*This documentation is automatically generated from the marketplace catalog.*
*Last updated: {{ now }}*

View File

@@ -0,0 +1,476 @@
#!/usr/bin/env python3
"""
Documentation Generator
Generates documentation files from marketplace data using Jinja2 templates.
"""
import json
import os
import sys
import re
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Any, Optional
import argparse
# Try to use real Jinja2 if available, otherwise use SimpleTemplate fallback
try:
from jinja2 import Template as Jinja2Template
USE_JINJA2 = True
except ImportError:
USE_JINJA2 = False
class SimpleTemplate:
"""Minimal Jinja2-like template engine"""
def __init__(self, template_str: str):
self.template = template_str
def apply_filter(self, value: Any, filter_name: str) -> Any:
"""Apply a filter to a value"""
if filter_name == 'title':
return str(value).replace('-', ' ').replace('_', ' ').title()
elif filter_name == 'length':
return len(value) if hasattr(value, '__len__') else 0
elif filter_name.startswith('join'):
# Extract separator from filter (e.g., "join(', ')")
match = re.search(r"join\(['\"]([^'\"]*)['\"]\)", filter_name)
if match and isinstance(value, list):
separator = match.group(1)
return separator.join(str(v) for v in value)
return str(value)
return value
def resolve_value(self, expr: str, context: Dict[str, Any]) -> Any:
"""Resolve a variable expression with optional filters"""
# Split expression and filters
parts = expr.strip().split('|')
var_expr = parts[0].strip()
filters = [f.strip() for f in parts[1:]]
# Resolve the base variable
value = context
for key in var_expr.split('.'):
key = key.strip()
if isinstance(value, dict):
value = value.get(key, '')
elif hasattr(value, key):
value = getattr(value, key)
else:
value = ''
break
# Apply filters
for filter_name in filters:
value = self.apply_filter(value, filter_name)
return value
def render(self, context: Dict[str, Any]) -> str:
"""Render template with context"""
result = self.template
# Handle nested loops with .items(): {% for key, value in dict.items() %}...{% endfor %}
items_pattern = r'{%\s*for\s+(\w+)\s*,\s*(\w+)\s+in\s+([\w.]+)\.items\(\)\s*%}(.*?){%\s*endfor\s*%}'
def replace_items_loop(match):
key_var = match.group(1)
value_var = match.group(2)
dict_name = match.group(3)
loop_body = match.group(4)
dict_obj = self.resolve_value(dict_name, context)
if not isinstance(dict_obj, dict):
return ""
output = []
for key, value in dict_obj.items():
loop_context = context.copy()
loop_context[key_var] = key
loop_context[value_var] = value
# Recursively render the loop body
template = SimpleTemplate(loop_body)
body_result = template.render(loop_context)
output.append(body_result)
return "".join(output)
result = re.sub(items_pattern, replace_items_loop, result, flags=re.DOTALL)
# Handle loops with .keys(): {% for key in dict.keys() %}...{% endfor %}
keys_pattern = r'{%\s*for\s+(\w+)\s+in\s+([\w.]+)\.keys\(\)\s*%}(.*?){%\s*endfor\s*%}'
def replace_keys_loop(match):
var_name = match.group(1)
dict_name = match.group(2)
loop_body = match.group(3)
dict_obj = self.resolve_value(dict_name, context)
if not isinstance(dict_obj, dict):
return ""
output = []
for key in dict_obj.keys():
loop_context = context.copy()
loop_context[var_name] = key
# Recursively render the loop body
template = SimpleTemplate(loop_body)
body_result = template.render(loop_context)
output.append(body_result)
return "".join(output)
result = re.sub(keys_pattern, replace_keys_loop, result, flags=re.DOTALL)
# Handle regular loops: {% for item in items %}...{% endfor %}
for_pattern = r'{%\s*for\s+(\w+)\s+in\s+([\w.]+)\s*%}(.*?){%\s*endfor\s*%}'
def replace_for(match):
var_name = match.group(1)
list_name = match.group(2)
loop_body = match.group(3)
items = self.resolve_value(list_name, context)
if not isinstance(items, (list, dict)):
return ""
# Handle both lists and dict values
if isinstance(items, dict):
items = list(items.values())
output = []
for item in items:
loop_context = context.copy()
loop_context[var_name] = item
# If item is a dict, also add its keys directly to context for easier access
if isinstance(item, dict):
for key, value in item.items():
loop_context[f"{var_name}.{key}"] = value
# Recursively render the loop body
template = SimpleTemplate(loop_body)
body_result = template.render(loop_context)
output.append(body_result)
return "".join(output)
result = re.sub(for_pattern, replace_for, result, flags=re.DOTALL)
# Handle conditionals with comparison: {% if var1 == var2 %}...{% endif %}
if_compare_pattern = r'{%\s*if\s+([\w.]+)\s*==\s*([\w.]+)\s*%}(.*?){%\s*endif\s*%}'
def replace_if_compare(match):
left_expr = match.group(1)
right_expr = match.group(2)
body = match.group(3)
left_val = self.resolve_value(left_expr, context)
right_val = self.resolve_value(right_expr, context)
if left_val == right_val:
template = SimpleTemplate(body)
return template.render(context)
return ""
result = re.sub(if_compare_pattern, replace_if_compare, result, flags=re.DOTALL)
# Handle conditionals with else: {% if condition %}...{% else %}...{% endif %}
if_else_pattern = r'{%\s*if\s+([\w.]+)\s*%}(.*?){%\s*else\s*%}(.*?){%\s*endif\s*%}'
def replace_if_else(match):
condition = match.group(1)
true_body = match.group(2)
false_body = match.group(3)
cond_val = self.resolve_value(condition, context)
if cond_val:
template = SimpleTemplate(true_body)
return template.render(context)
else:
template = SimpleTemplate(false_body)
return template.render(context)
result = re.sub(if_else_pattern, replace_if_else, result, flags=re.DOTALL)
# Handle simple conditionals: {% if condition %}...{% endif %}
if_pattern = r'{%\s*if\s+([\w.]+)\s*%}(.*?){%\s*endif\s*%}'
def replace_if(match):
condition = match.group(1)
body = match.group(2)
cond_val = self.resolve_value(condition, context)
if cond_val:
template = SimpleTemplate(body)
return template.render(context)
return ""
result = re.sub(if_pattern, replace_if, result, flags=re.DOTALL)
# Replace variables with filters: {{ variable|filter }}
var_pattern = r'{{\s*([\w.|()\'",\s]+)\s*}}'
def replace_var(match):
expr = match.group(1)
value = self.resolve_value(expr, context)
return str(value) if value is not None else ''
result = re.sub(var_pattern, replace_var, result)
# Clean up any remaining template syntax
result = re.sub(r'{%.*?%}', '', result)
result = re.sub(r'{{.*?}}', '', result)
return result
class DocGenerator:
"""Generates documentation from marketplace data"""
def __init__(
self,
marketplace_path: str = ".claude-plugin/marketplace.json",
templates_dir: str = "plugins/claude-plugin/skills/documentation-update/assets",
output_dir: str = "docs",
):
self.marketplace_path = Path(marketplace_path)
self.templates_dir = Path(templates_dir)
self.output_dir = Path(output_dir)
self.marketplace_data: Dict[str, Any] = {}
def load_marketplace(self) -> None:
"""Load marketplace.json"""
if not self.marketplace_path.exists():
raise FileNotFoundError(f"Marketplace not found: {self.marketplace_path}")
with open(self.marketplace_path, 'r') as f:
self.marketplace_data = json.load(f)
def extract_frontmatter(self, file_path: Path) -> Dict[str, str]:
"""Extract YAML frontmatter from a markdown file"""
if not file_path.exists():
return {}
try:
with open(file_path, 'r') as f:
content = f.read()
# Match frontmatter between --- delimiters
match = re.match(r'^---\s*\n(.*?)\n---\s*\n', content, re.DOTALL)
if not match:
return {}
frontmatter_text = match.group(1)
frontmatter = {}
# Simple YAML parsing (key: value)
for line in frontmatter_text.split('\n'):
if ':' in line:
key, value = line.split(':', 1)
frontmatter[key.strip()] = value.strip().strip('"\'')
return frontmatter
except Exception as e:
print(f"Warning: Could not parse frontmatter in {file_path}: {e}")
return {}
def build_context(self) -> Dict[str, Any]:
"""Build template context from marketplace data"""
context = {
"marketplace": self.marketplace_data,
"now": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"plugins_by_category": {},
"all_agents": [],
"all_skills": [],
"all_commands": [],
"stats": {
"total_plugins": 0,
"total_agents": 0,
"total_commands": 0,
"total_skills": 0,
},
}
if "plugins" not in self.marketplace_data:
return context
plugins = self.marketplace_data["plugins"]
context["stats"]["total_plugins"] = len(plugins)
# Organize plugins by category
for plugin in plugins:
category = plugin.get("category", "general")
if category not in context["plugins_by_category"]:
context["plugins_by_category"][category] = []
context["plugins_by_category"][category].append(plugin)
plugin_name = plugin.get("name", "")
plugin_dir = Path(f"plugins/{plugin_name}")
# Extract agent information
if "agents" in plugin:
for agent_path in plugin["agents"]:
agent_file = agent_path.replace("./agents/", "")
full_path = plugin_dir / agent_path.lstrip('./')
frontmatter = self.extract_frontmatter(full_path)
context["all_agents"].append({
"plugin": plugin_name,
"name": frontmatter.get("name", agent_file.replace(".md", "")),
"file": agent_file,
"description": frontmatter.get("description", ""),
"model": frontmatter.get("model", ""),
})
context["stats"]["total_agents"] += len(plugin["agents"])
# Extract command information
if "commands" in plugin:
for cmd_path in plugin["commands"]:
cmd_file = cmd_path.replace("./commands/", "")
full_path = plugin_dir / cmd_path.lstrip('./')
frontmatter = self.extract_frontmatter(full_path)
context["all_commands"].append({
"plugin": plugin_name,
"name": frontmatter.get("name", cmd_file.replace(".md", "")),
"file": cmd_file,
"description": frontmatter.get("description", ""),
})
context["stats"]["total_commands"] += len(plugin["commands"])
# Extract skill information
if "skills" in plugin:
for skill_path in plugin["skills"]:
skill_name = skill_path.replace("./skills/", "")
full_path = plugin_dir / skill_path.lstrip('./') / "SKILL.md"
frontmatter = self.extract_frontmatter(full_path)
context["all_skills"].append({
"plugin": plugin_name,
"name": frontmatter.get("name", skill_name),
"path": skill_name,
"description": frontmatter.get("description", ""),
})
context["stats"]["total_skills"] += len(plugin["skills"])
return context
def render_template(self, template_name: str, context: Dict[str, Any]) -> str:
"""Render a template with context"""
template_path = self.templates_dir / f"{template_name}.md.j2"
if not template_path.exists():
raise FileNotFoundError(f"Template not found: {template_path}")
with open(template_path, 'r') as f:
template_content = f.read()
if USE_JINJA2:
# Use real Jinja2 for full compatibility
template = Jinja2Template(template_content)
return template.render(**context)
else:
# Fallback to SimpleTemplate
template = SimpleTemplate(template_content)
return template.render(context)
def generate_all(self, dry_run: bool = False, specific_file: Optional[str] = None) -> None:
"""Generate all documentation files"""
self.load_marketplace()
context = self.build_context()
docs_to_generate = {
"agents": "agents.md",
"agent-skills": "agent-skills.md",
"plugins": "plugins.md",
"usage": "usage.md",
}
if specific_file:
if specific_file not in docs_to_generate:
raise ValueError(f"Unknown documentation file: {specific_file}")
docs_to_generate = {specific_file: docs_to_generate[specific_file]}
for template_name, output_file in docs_to_generate.items():
try:
print(f"Generating {output_file}...")
content = self.render_template(template_name, context)
if dry_run:
print(f"\n--- {output_file} ---")
print(content[:500] + "..." if len(content) > 500 else content)
print()
else:
output_path = self.output_dir / output_file
output_path.parent.mkdir(parents=True, exist_ok=True)
with open(output_path, 'w') as f:
f.write(content)
print(f"✓ Generated {output_path}")
except Exception as e:
print(f"❌ Error generating {output_file}: {e}")
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(description="Generate documentation from marketplace")
parser.add_argument(
"--marketplace",
default=".claude-plugin/marketplace.json",
help="Path to marketplace.json",
)
parser.add_argument(
"--templates",
default="plugins/claude-plugin/skills/documentation-update/assets",
help="Path to templates directory",
)
parser.add_argument(
"--output",
default="docs",
help="Output directory for documentation",
)
parser.add_argument(
"--file",
choices=["agents", "agent-skills", "plugins", "usage"],
help="Generate specific file only",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Show output without writing files",
)
args = parser.parse_args()
try:
generator = DocGenerator(
marketplace_path=args.marketplace,
templates_dir=args.templates,
output_dir=args.output,
)
generator.generate_all(dry_run=args.dry_run, specific_file=args.file)
if not args.dry_run:
print("\n✓ Documentation generation complete")
except Exception as e:
print(f"❌ Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()