project-standalo-sonic-cloud/CLAUDE.md

1183 lines
33 KiB
Markdown

# Project Instructions
## Overview
This project uses the **Guardrail Workflow System** - a hook-enforced development workflow that **prevents AI from bypassing the design-approve-implement cycle**.
## Workflow Enforcement Architecture
### How AI is Forced to Follow Workflows
```
┌─────────────────────────────────────────────────────────────────┐
│ HOOK ENFORCEMENT LAYER │
├─────────────────────────────────────────────────────────────────┤
│ PreToolUse Hooks intercept ALL file operations: │
│ │
│ Write/Edit/MultiEdit → validate_workflow.py → validate_write.py│
│ Task (agents) → validate_workflow.py (agent restrictions)│
│ MCP tools → validate_workflow.py (serena, morphllm) │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ PHASE STATE MACHINE │
├─────────────────────────────────────────────────────────────────┤
│ INITIALIZING → DESIGNING → AWAITING_DESIGN_APPROVAL │
│ │ │ │ │
│ │ │ ┌────────┴────────┐ │
│ │ │ ▼ ▼ │
│ │ │ DESIGN_APPROVED DESIGN_REJECTED │
│ │ │ │ │ │
│ │ │ ▼ │ │
│ │ │ IMPLEMENTING ←─────────┘ │
│ │ │ │ │
│ │ │ ▼ │
│ │ │ REVIEWING │
│ │ │ │ │
│ │ │ ▼ │
│ │ │ 🔒 SECURITY_REVIEW ←───────┐ │
│ │ │ │ │ │
│ │ │ ▼ │ │
│ │ │ AWAITING_IMPL_APPROVAL │ │
│ │ │ │ │ │
│ │ │ ┌─────┴─────┐ │ │
│ │ │ ▼ ▼ │ │
│ │ │ IMPL_APPROVED IMPL_REJECTED─┘ │
│ │ │ │ │
│ │ │ ▼ │
│ │ │ COMPLETING │
│ │ │ │ │
│ │ │ ▼ │
│ │ │ COMPLETED │
└─────────────────────────────────────────────────────────────────┘
```
### Tool Restrictions by Phase
| Phase | Write/Edit | Task (Agents) | Allowed Files |
|-------|------------|---------------|---------------|
| **NO_WORKFLOW** | ✅ Allowed | ✅ Allowed | Any |
| **DESIGNING** | ⛔ Blocked | system-architect only | manifest, .workflow/, tasks/*.yml |
| **AWAITING_DESIGN_APPROVAL** | ⛔ Blocked | ⛔ Blocked | None |
| **IMPLEMENTING** | ✅ Allowed | frontend/backend only | Files in task file_paths |
| **REVIEWING** | ⛔ Blocked | quality-engineer only | None (read-only) |
| **SECURITY_REVIEW** | ⛔ Blocked | security-engineer only | None (read-only) |
| **AWAITING_IMPL_APPROVAL** | ⛔ Blocked | ⛔ Blocked | None |
| **COMPLETED** | ⛔ Blocked | ⛔ Blocked | None |
### Enforcement Scripts
| Script | Purpose | Exit Codes |
|--------|---------|------------|
| `validate_workflow.py` | Phase-based blocking | 0=allow, 1=block |
| `validate_write.py` | Manifest path validation | 0=allow, 1=block |
| `workflow_manager.py` | State transitions | Manages .workflow/versions/ |
| `version_manager.py` | Version lifecycle | Creates/completes versions |
### What Happens When AI Tries to Bypass
```
AI attempts: Write tool to create app/components/Button.tsx
Hook intercepts → validate_workflow.py --operation write --file "app/components/Button.tsx"
Script checks:
1. Current phase = DESIGNING
2. File is NOT in always_allowed list
3. Returns exit code 1
Output to AI:
⛔ WORKFLOW VIOLATION: Cannot write implementation files during DESIGNING
Current Phase: DESIGNING
File: app/components/Button.tsx
During DESIGNING phase, only these files can be modified:
- project_manifest.json
- .workflow/versions/vXXX/tasks/*.yml
Complete design and get approval before implementing.
```
---
## Workflow Commands
### Starting a Workflow
```bash
# Automated workflow (auto-approves if validation passes)
/workflow:spawn --auto <feature description>
# Interactive workflow (stops at approval gates)
/workflow:spawn <feature description>
```
### Checking Status
```bash
/workflow:status # Current workflow state
/workflow:history # All workflow versions
```
### Approval Gates
```bash
/workflow:approve # Approve current gate (design or implementation)
/workflow:reject # Reject with feedback
```
### Resuming
```bash
/workflow:resume # Continue interrupted workflow
```
---
## Guardrail Commands (Manual Flow)
For granular control without full orchestration:
### Design Phase
```bash
/guardrail:init <project> # Initialize manifest
/guardrail:design # Add entities to manifest
/guardrail:review # Request design review
/guardrail:approve # Approve design
```
### Implementation Phase
```bash
/guardrail:implement # Implement approved entity
/guardrail:verify # Verify implementation
/guardrail:validate # Validate manifest integrity
```
### Analysis
```bash
/guardrail:analyze # Analyze existing codebase
/guardrail:status # Show project status
```
---
## Project Structure
```
project/
├── .claude/
│ ├── commands/
│ │ ├── eureka/ # Eureka utility commands
│ │ │ └── index.md # Documentation generator
│ │ ├── guardrail/ # Manual workflow commands
│ │ └── workflow/ # Orchestrated workflow commands
│ └── settings.json # Hook configurations (enforcement)
├── .workflow/
│ ├── current.yml # Active version pointer
│ ├── index.yml # Version registry
│ └── versions/
│ └── vXXX/
│ ├── session.yml # Workflow state
│ └── tasks/ # Task definitions
│ └── task_*.yml
├── skills/
│ ├── guardrail-orchestrator/
│ │ ├── agents/ # Agent role definitions
│ │ ├── schemas/ # YAML schemas
│ │ └── scripts/ # Enforcement scripts
│ └── documentation-generator/
│ ├── agents/ # doc-writer agent
│ ├── schemas/ # Documentation schemas
│ ├── scripts/ # Analysis & generation scripts
│ └── templates/ # HTML template
├── project_manifest.json # Entity definitions
└── CLAUDE.md # This file
```
---
## Development Guidelines
### MANDATORY: Follow the Workflow
1. **Never write implementation files directly** - hooks will block you
2. **Start with `/workflow:spawn`** or `/guardrail:init`
3. **Design first** - add entities to manifest
4. **Get approval** - wait for gate approval
5. **Then implement** - only after approval
### Workflow State Files
- `.workflow/current.yml` - Points to active version
- `.workflow/versions/vXXX/session.yml` - Phase state, approvals
- `.workflow/versions/vXXX/tasks/*.yml` - Task definitions
### Manifest Structure
```json
{
"project": { "name": "...", "version": "..." },
"state": { "current_phase": "DESIGN_PHASE" },
"entities": {
"components": [
{
"id": "component_button",
"name": "Button",
"status": "PENDING|APPROVED|IMPLEMENTED",
"file_path": "app/components/Button.tsx"
}
],
"pages": [...],
"api_endpoints": [...]
}
}
```
---
## Quick Start
### Option 1: Automated Workflow
```bash
# Single command - runs entire workflow
/workflow:spawn --auto add user authentication
```
### Option 2: Interactive Workflow
```bash
# Step-by-step with approval gates
/workflow:spawn add user profile page
# Wait for design...
/workflow:approve # Approve design
# Wait for implementation...
/workflow:approve # Approve implementation
```
### Option 3: Manual Guardrail
```bash
/guardrail:init my-feature
/guardrail:design
/guardrail:approve
/guardrail:implement
/guardrail:verify
```
---
## Troubleshooting
### "WORKFLOW VIOLATION" Error
You tried to write files outside the allowed phase. Check:
```bash
/workflow:status
```
Then follow the workflow:
1. If DESIGNING → finish design, get approval
2. If REVIEWING → wait for review to complete
3. If AWAITING_*_APPROVAL → approve or reject
### "No active workflow" Error
Start a workflow first:
```bash
/workflow:spawn <feature>
# or
/guardrail:init <project>
```
### Resuming After Interruption
```bash
/workflow:resume
```
---
## Hook Configuration Reference
The enforcement is configured in `.claude/settings.json`:
### Enforced Tools (ALL BLOCKED without workflow)
| Tool | Validator | What's Checked |
|------|-----------|----------------|
| **Bash** | `validate_bash.py` | Blocks `>`, `>>`, `tee`, `sed -i`, `cp`, `mv`, `rm` |
| **Write** | `validate_workflow.py` + `validate_write.py` | Phase + manifest paths |
| **Edit** | `validate_workflow.py` + `validate_write.py` | Phase + manifest paths |
| **MultiEdit** | `validate_workflow.py` + `validate_write.py` | Phase + manifest paths |
| **NotebookEdit** | `validate_workflow.py` + `validate_write.py` | Phase + manifest paths |
| **Task** | `validate_workflow.py` | Agent type vs phase |
| **mcp__serena__*** | `validate_workflow.py` + `validate_write.py` | All Serena writes |
| **mcp__morphllm__*** | `validate_workflow.py` + `validate_write.py` | All Morphllm writes |
| **mcp__filesystem__*** | `validate_workflow.py` + `validate_write.py` | All filesystem writes |
### Bash Commands - Blocked Patterns
These bash patterns are **blocked** unless writing to allowed paths:
```bash
# Redirections
echo "x" > file.txt # BLOCKED
cat > file.txt # BLOCKED
command >> file.txt # BLOCKED
# File operations
tee file.txt # BLOCKED
cp source dest # BLOCKED
mv source dest # BLOCKED
rm file.txt # BLOCKED
touch file.txt # BLOCKED
# In-place edits
sed -i 's/x/y/' file # BLOCKED
awk -i inplace # BLOCKED
# Here documents
cat << EOF > file # BLOCKED
```
### Bash Commands - Always Allowed
```bash
# Reading
cat file.txt # OK (no redirect)
head/tail/grep/find # OK
ls, pwd, cd # OK
# Running
npm run build # OK
npm test # OK
node script.js # OK
python script.py # OK (no redirect)
# Git (read operations)
git status/log/diff # OK
git branch/show # OK
```
### Enforcement Scripts
| Script | Purpose |
|--------|---------|
| `validate_workflow.py` | Phase-based blocking, instructs `/workflow:spawn` |
| `validate_write.py` | Manifest path validation |
| `validate_bash.py` | Shell command pattern blocking |
| `validate_api_contract.py` | Frontend-backend API contract validation |
| `workflow_manager.py` | State machine transitions |
| `post_write.py` | Auto-update entity status after writes |
| `visualize_design.py` | ASCII art design visualization |
---
## Review Command (Quality Gates)
The `/workflow:review` command runs comprehensive quality checks before approving implementation.
### Validation Checks
| Check | Command | Blocks Approval | Mode |
|-------|---------|-----------------|------|
| Build | `npm run build` | YES | Always |
| TypeScript | `npx tsc --noEmit` | YES | Always |
| Lint | `npm run lint` | YES | --strict |
| Tests | `npm test` | YES | --strict |
| API Contract | `validate_api_contract.py` | YES | Always |
| Security | Pattern scan | WARNING | Always |
### API Contract Validation
The API contract validator ensures frontend and backend are aligned:
**Frontend Detection**:
- `fetch('/api/...')` calls
- `axios.get/post/put/delete()` requests
- `useSWR()` data fetching
- Custom API clients
**Backend Detection**:
- Next.js App Router: `app/api/*/route.ts` exports (GET, POST, etc.)
- Next.js Pages Router: `pages/api/*.ts` req.method checks
- Express-style: `router.get/post()` patterns
**Validation Rules**:
1. **Endpoint Existence**: Frontend calls must have matching backend routes
2. **Method Match**: GET calls → GET endpoints, POST → POST, etc.
3. **Body Alignment**: POST/PUT should send bodies, GET should not
4. **Unused Detection**: Warns about backend routes not called by frontend
### Security Scan
Checks for common security issues:
- Hardcoded passwords, API keys, secrets
- SQL injection patterns (`query.*${`)
- XSS risks (`dangerouslySetInnerHTML`)
- Console statements in production code
### Usage
```bash
# Standard review (build + types + API contract + security)
/workflow:review --auto
# Strict review (adds lint + tests)
/workflow:review --auto --strict
# Full review (all checks)
/workflow:review --auto --full
```
---
## Security Audit Command
For comprehensive security analysis, use the dedicated security command:
```bash
# Quick scan (automated scanner only)
/workflow:security --quick
# Standard scan (scanner + dependencies)
/workflow:security
# Full audit (scanner + deps + config review + deep analysis)
/workflow:security --full
```
### Security Categories Checked
| Category | CWE | OWASP | Severity |
|----------|-----|-------|----------|
| Hardcoded Secrets | CWE-798 | A07 | CRITICAL |
| SQL Injection | CWE-89 | A03 | CRITICAL |
| Command Injection | CWE-78 | A03 | CRITICAL |
| XSS | CWE-79 | A03 | HIGH |
| Path Traversal | CWE-22 | A01 | HIGH |
| NoSQL Injection | CWE-943 | A03 | HIGH |
| SSRF | CWE-918 | A10 | HIGH |
| Prototype Pollution | CWE-1321 | A03 | HIGH |
| Insecure Auth | CWE-287 | A07 | HIGH |
| CORS Misconfiguration | CWE-942 | A01 | MEDIUM |
| Sensitive Data Exposure | CWE-200 | A02 | MEDIUM |
| Insecure Dependencies | CWE-1104 | A06 | MEDIUM |
### Exit Codes
- **0**: PASS - No critical/high issues
- **1**: WARNING - High issues found
- **2**: CRITICAL - Critical issues found (blocks deployment)
---
## Documentation Generation
Generate comprehensive project documentation for **both engineers and non-engineers** using the `/eureka:index` command.
### Quick Start
```bash
# Generate documentation in docs/ folder
/eureka:index
# Generate in custom folder
/eureka:index my-docs
```
### Output Files
| File | Audience | Description |
|------|----------|-------------|
| `index.html` | **Non-engineers** | Beautiful HTML - just open in browser! |
| `PROJECT_DOCUMENTATION.md` | Both | Main documentation |
| `QUICK_REFERENCE.md` | Both | One-page reference card |
| `API_REFERENCE.md` | Engineers | Detailed API documentation |
| `COMPONENTS.md` | Engineers | Component catalog |
| `analysis.yml` | Engineers | Raw project analysis data |
### Documentation Structure
```
╔══════════════════════════════════════════════════════════════╗
║ DUAL-AUDIENCE DESIGN ║
╠══════════════════════════════════════════════════════════════╣
║ ║
║ FOR NON-ENGINEERS (HTML): FOR ENGINEERS (MD): ║
║ ───────────────────────── ───────────────────── ║
║ • Clean, professional view • Git-friendly format ║
║ • Technical details hidden • Editable source ║
║ • Click to expand if needed • Full technical specs ║
║ • Works on mobile • Code examples ║
║ • Print to PDF • Type definitions ║
║ ║
╚══════════════════════════════════════════════════════════════╝
```
### Documentation Sections
| Section | Audience | Content |
|---------|----------|---------|
| Executive Summary | Everyone | What it does, who it's for |
| Architecture Overview | Everyone | Visual diagrams, tech stack |
| Getting Started | Semi-technical | Setup, installation |
| Feature Guide | Non-engineers | Plain-language descriptions |
| API Reference | Engineers | Endpoints, schemas (collapsible) |
| Component Catalog | Engineers | Props, events (collapsible) |
| Data Models | Both | ER diagrams + descriptions |
| Glossary | Non-engineers | Technical terms explained |
### HTML Features
The generated `index.html` includes:
- **Responsive design** - Works on desktop, tablet, and mobile
- **Dark mode** - Automatically adapts to system preferences
- **Sidebar navigation** - Easy section jumping
- **Collapsible technical details** - Non-engineers see clean view
- **Print-friendly** - Can be saved as PDF
- **Single file** - No dependencies, just open in browser
### For Non-Engineers
Simply open `docs/index.html` in your web browser. You'll see:
1. **Executive Summary** - What the project does in plain English
2. **Feature Guide** - What each feature does and how to use it
3. **Glossary** - Explanations of technical terms
Technical details are hidden by default. Click "🔧 Technical Details" to expand if curious.
### For Engineers
Use the Markdown files for:
- Version control (git-friendly)
- Easy editing and updates
- Integration with documentation systems
- Full technical specifications
Or use the HTML and click "🔧 Technical Details" to see code examples, props, and schemas.
### Example Output
```
docs/
├── index.html # 🌐 Open this in browser!
├── PROJECT_DOCUMENTATION.md # 📄 Main docs (markdown)
├── QUICK_REFERENCE.md # 📄 Quick reference card
├── API_REFERENCE.md # 📄 API details
├── COMPONENTS.md # 📄 Component catalog
└── analysis.yml # 📊 Raw analysis data
```
---
## Template Development Guide
This section explains how to create new **commands**, **skills**, and **agents** for the Eureka framework.
### Templates Directory Structure
```
templates/
├── .claude/
│ ├── commands/ # Slash commands
│ │ ├── eureka/ # /eureka:* commands
│ │ │ └── index.md
│ │ ├── guardrail/ # /guardrail:* commands
│ │ │ ├── init.md
│ │ │ ├── design.md
│ │ │ └── ...
│ │ └── workflow/ # /workflow:* commands
│ │ ├── spawn.md
│ │ ├── design.md
│ │ └── ...
│ └── settings.json # Hooks configuration
├── skills/ # Skill packages
│ ├── guardrail-orchestrator/
│ │ ├── skill.yml # Skill manifest
│ │ ├── agents/ # Agent definitions
│ │ │ ├── orchestrator.yml
│ │ │ ├── architect.yml
│ │ │ └── ...
│ │ ├── schemas/ # YAML schemas
│ │ │ ├── design_document.yml
│ │ │ └── ...
│ │ └── scripts/ # Python scripts
│ │ ├── validate_workflow.py
│ │ └── ...
│ │
│ └── documentation-generator/
│ ├── skill.yml
│ ├── agents/
│ │ └── doc-writer.yml
│ ├── schemas/
│ │ ├── documentation_output.yml
│ │ └── project_analysis.yml
│ ├── scripts/
│ │ ├── analyze_project.py
│ │ └── generate_html.py
│ └── templates/
│ └── documentation.html
├── CLAUDE.md # Project instructions
└── .mcp.json # MCP server config
```
---
### Creating a New Command
Commands are markdown files that define executable workflows.
#### File Location
```
templates/.claude/commands/<namespace>/<command>.md
```
#### Command File Format
```markdown
---
description: Short description shown in command list
allowed-tools: Read, Write, Edit, Bash, Task, TodoWrite
---
# Command Title
**Input**: "$ARGUMENTS"
---
## PURPOSE
Explain what this command does and when to use it.
---
## ⛔ CRITICAL RULES
### MUST DO
1. **MUST** do this thing
2. **MUST** do another thing
### CANNOT DO
1. **CANNOT** do this
2. **CANNOT** do that
---
## EXECUTION FLOW
### ═══════════════════════════════════════════════════════════════
### PHASE 1: Phase Name
### ═══════════════════════════════════════════════════════════════
#### 1.1: Step Name
```bash
# Commands to execute
echo "Hello"
```
#### 1.2: Another Step
**Use Task tool with agent:**
```
Use Task tool with:
subagent_type: "agent-name"
prompt: |
Instructions for the agent...
```
---
### ═══════════════════════════════════════════════════════════════
### PHASE 2: Next Phase
### ═══════════════════════════════════════════════════════════════
[Continue with more phases...]
---
## USAGE
```bash
/namespace:command
/namespace:command argument
/namespace:command --flag value
```
```
#### Command Conventions
| Element | Convention |
|---------|------------|
| Namespace | Lowercase, matches folder name (`eureka`, `workflow`) |
| Command name | Lowercase, matches file name without `.md` |
| Phases | Use `═══` banners with PHASE N headers |
| Steps | Use `####` with numbered steps (1.1, 1.2) |
| Banners | ASCII art boxes for important output |
| Arguments | Reference as `$ARGUMENTS` |
---
### Creating a New Skill
Skills are packages that bundle agents, schemas, scripts, and templates.
#### Skill Directory Structure
```
skills/<skill-name>/
├── skill.yml # REQUIRED: Skill manifest
├── agents/ # REQUIRED: Agent definitions
│ └── <agent-name>.yml
├── schemas/ # OPTIONAL: Data schemas
│ └── <schema-name>.yml
├── scripts/ # OPTIONAL: Python/Bash scripts
│ └── <script-name>.py
└── templates/ # OPTIONAL: HTML/MD templates
└── <template-name>.html
```
#### skill.yml Format
```yaml
# Skill manifest
name: skill-name
version: "1.0.0"
description: |
Multi-line description of what this skill does.
# Activation triggers
triggers:
commands:
- "/namespace:command"
keywords:
- "trigger phrase"
- "another trigger"
# Components
agents:
- agent-name
schemas:
- schema-name.yml
scripts:
- script-name.py
templates:
- template-name.html
# Capabilities list
capabilities:
- Capability one
- Capability two
# Output files
outputs:
primary:
- output-file.md
optional:
- optional-file.md
# Tool dependencies
dependencies:
required:
- Read tool
- Write tool
optional:
- Bash tool
```
---
### Creating a New Agent
Agents are YAML files that define specialized AI personas.
#### File Location
```
skills/<skill-name>/agents/<agent-name>.yml
```
#### Agent File Format
```yaml
# Agent Definition
name: agent-name
role: Agent Role Title
description: |
Multi-line description of what this agent specializes in
and when it should be used.
# Tool permissions
allowed_tools:
- Read
- Write
- Edit
- Glob
- Grep
blocked_tools:
- Task # Prevent sub-agent spawning
- Bash # Prevent shell access
# File access restrictions
allowed_files:
- "docs/**/*"
- "*.md"
- "package.json"
# What this agent does
responsibilities:
- First responsibility
- Second responsibility
- Third responsibility
# What this agent produces
outputs:
- output-file.md
- another-output.yml
# Restrictions
cannot_do:
- Cannot modify source code
- Cannot run tests
- Cannot deploy
# Agent-specific configuration
custom_config:
key: value
nested:
setting: value
```
#### Agent Naming Conventions
| Type | Naming Pattern | Examples |
|------|----------------|----------|
| Task agents | `<domain>-<role>` | `backend-architect`, `frontend-engineer` |
| Review agents | `<domain>-reviewer` | `security-reviewer`, `code-reviewer` |
| Analysis agents | `<domain>-analyzer` | `codebase-analyzer`, `dependency-analyzer` |
| Writer agents | `<domain>-writer` | `doc-writer`, `test-writer` |
---
### Creating a Schema
Schemas define the structure of YAML/JSON data files.
#### File Location
```
skills/<skill-name>/schemas/<schema-name>.yml
```
#### Schema File Format
```yaml
# Schema metadata
version: "1.0"
description: What this schema defines
# Top-level structure
<root_element>:
type: object
required: true
fields:
field_name:
type: string|integer|boolean|array|object|enum
required: true|false
description: What this field represents
default: default_value
enum_field:
type: enum
values: [value1, value2, value3]
array_field:
type: array
items:
field: type
another: type
min_items: 1
max_items: 10
nested_object:
type: object
fields:
nested_field:
type: string
# Validation rules
validation_rules:
- name: rule_name
description: What this rule checks
# Processing instructions
processing:
step_1:
description: First processing step
step_2:
description: Second processing step
```
---
### Creating a Script
Scripts automate validation, generation, or transformation tasks.
#### File Location
```
skills/<skill-name>/scripts/<script-name>.py
```
#### Script Template
```python
#!/usr/bin/env python3
"""
Script Name
Brief description of what this script does.
"""
import os
import sys
import json
from pathlib import Path
from typing import Dict, List, Any, Optional
# Try optional imports
try:
import yaml
except ImportError:
yaml = None
def main_function(input_path: Path, output_path: Optional[Path] = None) -> Dict[str, Any]:
"""
Main processing function.
Args:
input_path: Path to input file
output_path: Optional path for output
Returns:
Processing result
"""
# Implementation here
pass
def main():
"""CLI entry point."""
if len(sys.argv) < 2:
print("Usage: script_name.py <input> [output]", file=sys.stderr)
sys.exit(1)
input_path = Path(sys.argv[1])
output_path = Path(sys.argv[2]) if len(sys.argv) > 2 else None
if not input_path.exists():
print(f"Error: Input not found: {input_path}", file=sys.stderr)
sys.exit(1)
result = main_function(input_path, output_path)
# Output result
if output_path:
output_path.write_text(json.dumps(result, indent=2))
print(f"Output written to: {output_path}")
else:
print(json.dumps(result, indent=2))
if __name__ == '__main__':
main()
```
#### Script Conventions
| Convention | Description |
|------------|-------------|
| Exit codes | `0` = success, `1` = error, `2` = critical |
| Input | Accept file paths as arguments |
| Output | Write to stdout or specified file |
| Dependencies | Handle missing imports gracefully |
| Errors | Print to stderr with clear messages |
---
### Creating a Template
Templates are HTML/Markdown files with placeholders.
#### File Location
```
skills/<skill-name>/templates/<template-name>.html
```
#### Placeholder Conventions
```html
<!-- Simple placeholder -->
{{VARIABLE_NAME}}
<!-- Section placeholder (replaced by generated HTML) -->
<!-- SECTION_PLACEHOLDER -->
<div>default content</div>
<!-- END_SECTION -->
<!-- Conditional sections -->
{{#IF_CONDITION}}
Content shown if condition is true
{{/IF_CONDITION}}
<!-- Loop sections -->
{{#EACH_ITEMS}}
<div>{{ITEM_NAME}}</div>
{{/EACH_ITEMS}}
```
---
### Checklist: Creating a New Feature
When creating a new feature, follow this checklist:
```
□ 1. PLAN THE FEATURE
□ Define the purpose and scope
□ Identify target users (engineers/non-engineers/both)
□ List required capabilities
□ 2. CREATE THE SKILL
□ Create skill directory: skills/<skill-name>/
□ Create skill.yml manifest
□ Define triggers and capabilities
□ 3. CREATE THE AGENT(S)
□ Create agents/<agent-name>.yml
□ Define allowed/blocked tools
□ Define responsibilities and outputs
□ 4. CREATE SCHEMAS (if needed)
□ Create schemas/<schema-name>.yml
□ Define data structure
□ Add validation rules
□ 5. CREATE SCRIPTS (if needed)
□ Create scripts/<script-name>.py
□ Handle CLI arguments
□ Add error handling
□ 6. CREATE TEMPLATES (if needed)
□ Create templates/<template-name>.html
□ Add CSS styling
□ Use placeholder conventions
□ 7. CREATE THE COMMAND
□ Create .claude/commands/<namespace>/<command>.md
□ Add YAML front-matter
□ Define execution phases
□ Add usage examples
□ 8. UPDATE DOCUMENTATION
□ Update CLAUDE.md
□ Add to Project Structure section
□ Document new commands
```
---
### Example: Creating a "Report Generator" Feature
Here's a complete example of creating a new feature:
#### 1. Create Skill Directory
```
skills/report-generator/
├── skill.yml
├── agents/
│ └── report-writer.yml
├── schemas/
│ └── report_format.yml
├── scripts/
│ └── generate_report.py
└── templates/
└── report.html
```
#### 2. skill.yml
```yaml
name: report-generator
version: "1.0.0"
description: Generate project status reports
triggers:
commands:
- "/eureka:report"
keywords:
- "generate report"
- "status report"
agents:
- report-writer
outputs:
primary:
- report.html
- report.md
```
#### 3. agents/report-writer.yml
```yaml
name: report-writer
role: Report Generation Specialist
description: Creates project status reports
allowed_tools:
- Read
- Write
- Glob
- Grep
responsibilities:
- Analyze project status
- Generate executive summaries
- Create visual charts
outputs:
- report.html
- report.md
```
#### 4. .claude/commands/eureka/report.md
```markdown
---
description: Generate project status report
allowed-tools: Read, Write, Task, Glob
---
# Eureka Report Generator
**Input**: "$ARGUMENTS"
## EXECUTION FLOW
### PHASE 1: Analyze Project
[...]
### PHASE 2: Generate Report
[...]
```
#### 5. Update CLAUDE.md
Add documentation for the new `/eureka:report` command.