diff --git a/.claude/commands/eureka/deploy-flow.md b/.claude/commands/eureka/deploy-flow.md new file mode 100644 index 0000000..e1cb9ab --- /dev/null +++ b/.claude/commands/eureka/deploy-flow.md @@ -0,0 +1,70 @@ +# Eureka Deploy Flow Agent + +You are an autonomous deployment agent for the Eureka platform. Execute the complete deployment workflow. + +## Workflow Steps + +Execute these steps in order: + +### Step 1: Check Git Status +```bash +git status +git branch --show-current +``` +- Identify current branch +- Check for uncommitted changes +- Check for untracked files + +### Step 2: Stage Changes +If there are changes to commit: +```bash +git add -A +``` + +### Step 3: Commit Changes +If there are staged changes: +```bash +git commit -m "Deploy: $(date +%Y-%m-%d_%H:%M:%S)" +``` +Use a descriptive commit message if the user provided context. + +### Step 4: Push to Eureka Remote +```bash +git push eureka $(git branch --show-current) +``` +If push fails, try: +```bash +git push -u eureka $(git branch --show-current) +``` + +### Step 5: Trigger Deployment +```bash +eureka deploy trigger --yes +``` + +### Step 6: Monitor Status +```bash +eureka deploy status +``` +Wait a few seconds and check status again if still building. + +## Error Handling + +- **No eureka remote**: Run `eureka init` first +- **Push rejected**: Check if remote has changes, pull first if needed +- **Deploy failed**: Check `eureka deploy logs` for details +- **No app_id**: Run `eureka setup` to configure + +## Success Criteria + +- All changes committed and pushed +- Deployment triggered successfully +- Status shows "building" or "deployed" + +## Output + +Report: +1. Files changed/committed +2. Push result +3. Deployment status +4. Deployed URL (when available) diff --git a/.claude/commands/eureka/deploy-logs.md b/.claude/commands/eureka/deploy-logs.md new file mode 100644 index 0000000..9ed7e7c --- /dev/null +++ b/.claude/commands/eureka/deploy-logs.md @@ -0,0 +1,63 @@ +--- +description: View deployment logs from Eureka platform +allowed-tools: Read, Bash, Glob +--- + +# Eureka Deploy Logs + +**Input**: "$ARGUMENTS" + +--- + +## PURPOSE + +View the deployment logs from the Eureka platform to debug issues or monitor progress. + +--- + +## EXECUTION FLOW + +### ═══════════════════════════════════════════════════════════════ +### PHASE 1: Fetch Logs +### ═══════════════════════════════════════════════════════════════ + +#### 1.1: Run Logs Command + +```bash +# Default: last 100 lines +eureka deploy logs + +# Custom tail count +eureka deploy logs --tail 200 +``` + +#### 1.2: Parse Arguments + +If `$ARGUMENTS` contains a number, use it as tail count: +```bash +TAIL_COUNT="${ARGUMENTS:-100}" +eureka deploy logs --tail "$TAIL_COUNT" +``` + +--- + +## ARGUMENTS + +| Argument | Default | Description | +|----------|---------|-------------| +| `[tail]` | `100` | Number of log lines to show | +| `--id ` | Latest | Specific deployment ID | +| `--follow` | `false` | Follow logs in real-time | + +## EXAMPLES + +```bash +# View last 100 lines +/eureka:deploy-logs + +# View last 500 lines +/eureka:deploy-logs 500 + +# View specific deployment +/eureka:deploy-logs --id dep_abc123 +``` diff --git a/.claude/commands/eureka/deploy-status.md b/.claude/commands/eureka/deploy-status.md new file mode 100644 index 0000000..ab53cff --- /dev/null +++ b/.claude/commands/eureka/deploy-status.md @@ -0,0 +1,55 @@ +--- +description: Check deployment status on Eureka platform +allowed-tools: Read, Bash, Glob +--- + +# Eureka Deploy Status + +**Input**: "$ARGUMENTS" + +--- + +## PURPOSE + +Check the current deployment status of the application on the Eureka platform. + +--- + +## EXECUTION FLOW + +### ═══════════════════════════════════════════════════════════════ +### PHASE 1: Check Status +### ═══════════════════════════════════════════════════════════════ + +#### 1.1: Run Status Command + +```bash +eureka deploy status --verbose +``` + +#### 1.2: Display Results + +The command will show: +- Current deployment status (pending, building, deploying, deployed, failed) +- Version information +- Environment +- Timestamps +- Deployment URL (if deployed) + +--- + +## ARGUMENTS + +| Argument | Default | Description | +|----------|---------|-------------| +| `--verbose` | `false` | Show detailed logs | + +## EXAMPLES + +```bash +# Check current deployment status +/eureka:deploy-status + +# Check with verbose output +/eureka:deploy-status --verbose +``` diff --git a/.claude/commands/eureka/deploy.md b/.claude/commands/eureka/deploy.md new file mode 100644 index 0000000..e219771 --- /dev/null +++ b/.claude/commands/eureka/deploy.md @@ -0,0 +1,279 @@ +--- +description: Deploy application to Eureka platform (creates app if needed) +allowed-tools: Read, Write, Edit, Bash, Glob, Grep +--- + +# Eureka Deploy + +**Input**: "$ARGUMENTS" + +--- + +## PURPOSE + +Deploy the current project to the Eureka platform. If no `app_id` is configured, automatically creates a new directory app first, then triggers the deployment. + +--- + +## ⛔ CRITICAL RULES + +### MUST DO +1. **MUST** check for existing `app_id` in `.claude/eureka-factory.yaml` first +2. **MUST** create a new app via API if no `app_id` exists +3. **MUST** save the new `app_id` to config after creation +4. **MUST** display deployment status after triggering + +### CANNOT DO +1. **CANNOT** deploy without valid API key +2. **CANNOT** skip app creation if `app_id` is missing +3. **CANNOT** proceed if API calls fail + +--- + +## EXECUTION FLOW + +### ═══════════════════════════════════════════════════════════════ +### PHASE 1: Configuration Check +### ═══════════════════════════════════════════════════════════════ + +#### 1.1: Display Start Banner + +``` +╔══════════════════════════════════════════════════════════════╗ +║ 🚀 EUREKA DEPLOY ║ +╠══════════════════════════════════════════════════════════════╣ +║ Deploying to Eureka Platform... ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +#### 1.2: Check Configuration + +Read the configuration file: +```bash +# Check if config exists +cat .claude/eureka-factory.yaml 2>/dev/null || cat .claude/eureka-factory.yml 2>/dev/null || echo "NO_CONFIG" +``` + +**Extract from config:** +- `api_key` - Required for all operations +- `app_id` - If exists, skip app creation +- `api_endpoint` - Optional custom endpoint + +#### 1.3: Validate API Key + +If no `api_key` found: +``` +╔══════════════════════════════════════════════════════════════╗ +║ ❌ NO API KEY CONFIGURED ║ +╠══════════════════════════════════════════════════════════════╣ +║ Run `eureka setup` to configure your credentials. ║ +╚══════════════════════════════════════════════════════════════╝ +``` +**STOP EXECUTION** + +--- + +### ═══════════════════════════════════════════════════════════════ +### PHASE 2: App Creation (if needed) +### ═══════════════════════════════════════════════════════════════ + +#### 2.1: Check for app_id + +If `app_id` exists in config → **SKIP TO PHASE 3** + +If `app_id` is missing: + +``` +╔══════════════════════════════════════════════════════════════╗ +║ 📁 CREATING DIRECTORY APP ║ +╠══════════════════════════════════════════════════════════════╣ +║ No app_id found. Creating new app on Eureka... ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +#### 2.2: Determine App Name + +Use the project directory name as the default app name: +```bash +APP_NAME=$(basename $(pwd)) +echo "App name: $APP_NAME" +``` + +Or use argument if provided: `$ARGUMENTS` as app name + +#### 2.3: Create App via API + +```bash +# Create app using eureka CLI +eureka deploy trigger --name "$APP_NAME" --type other --yes +``` + +**If the command is not available, use direct API call:** + +```bash +API_KEY="" +API_ENDPOINT="" + +curl -X POST "${API_ENDPOINT}/v1/apps" \ + -H "Content-Type: application/json" \ + -H "X-API-Key: ${API_KEY}" \ + -d "{\"name\": \"${APP_NAME}\", \"type\": \"other\"}" +``` + +#### 2.4: Save app_id to Config + +Extract `app_id` from API response and update config: + +```yaml +# .claude/eureka-factory.yaml +api_key: +project_id: +repo_id: +app_id: # Add this line +``` + +``` +╔══════════════════════════════════════════════════════════════╗ +║ ✅ APP CREATED ║ +╠══════════════════════════════════════════════════════════════╣ +║ App ID: ║ +║ Saved to: .claude/eureka-factory.yaml ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +--- + +### ═══════════════════════════════════════════════════════════════ +### PHASE 3: Trigger Deployment +### ═══════════════════════════════════════════════════════════════ + +#### 3.1: Trigger Deploy + +```bash +# Using eureka CLI +eureka deploy trigger --yes + +# Or direct API call +curl -X POST "${API_ENDPOINT}/v1/apps/${APP_ID}/deployments" \ + -H "Content-Type: application/json" \ + -H "X-API-Key: ${API_KEY}" \ + -d '{"environment": "production"}' +``` + +#### 3.2: Display Deployment Status + +``` +╔══════════════════════════════════════════════════════════════╗ +║ ✅ DEPLOYMENT TRIGGERED ║ +╠══════════════════════════════════════════════════════════════╣ +║ Deployment ID: ║ +║ Status: PENDING ║ +║ Environment: production ║ +║ Version: ║ +╠══════════════════════════════════════════════════════════════╣ +║ Use `/eureka:deploy-status` to check progress ║ +║ Use `/eureka:deploy-logs` to view logs ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +--- + +## ARGUMENTS + +| Argument | Default | Description | +|----------|---------|-------------| +| `[app-name]` | Directory name | Name for new app (only used if creating) | +| `--env ` | `production` | Deployment environment | +| `--branch ` | Current branch | Git branch to deploy | +| `--force` | `false` | Force deploy even if already deploying | + +## EXAMPLES + +```bash +# Deploy current project (creates app if needed) +/eureka:deploy + +# Deploy with custom app name +/eureka:deploy my-awesome-app + +# Deploy specific branch to staging +/eureka:deploy --env staging --branch develop + +# Force redeploy +/eureka:deploy --force +``` + +--- + +## ERROR HANDLING + +### No Configuration +``` +❌ No configuration found. +Run `eureka setup` to configure credentials. +``` + +### App Creation Failed +``` +❌ Failed to create app: +Check your API key and try again. +``` + +### Deployment Failed +``` +❌ Deployment failed: +Use `/eureka:deploy-logs` to see details. +``` + +--- + +## FLOW DIAGRAM + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ /eureka:deploy │ +├─────────────────────────────────────────────────────────────────┤ +│ │ │ +│ ▼ │ +│ ┌─────────────────┐ │ +│ │ Check Config │ │ +│ └────────┬────────┘ │ +│ │ │ +│ ┌─────────▼─────────┐ │ +│ │ Has API Key? │ │ +│ └─────────┬─────────┘ │ +│ │ │ +│ NO │ YES │ +│ ┌────────────────────┼────────────────────┐ │ +│ ▼ ▼ │ +│ ┌───────────┐ ┌─────────────────┐ │ +│ │ ERROR │ │ Has app_id? │ │ +│ │ No Key │ └────────┬────────┘ │ +│ └───────────┘ │ │ +│ NO │ YES │ +│ ┌───────────────────┼──────────┐ │ +│ ▼ ▼ │ +│ ┌─────────────────┐ ┌──────────────┐ +│ │ Create App │ │ │ +│ │ via API │ │ │ +│ └────────┬────────┘ │ │ +│ │ │ │ +│ ▼ │ │ +│ ┌─────────────────┐ │ │ +│ │ Save app_id │ │ │ +│ │ to Config │ │ │ +│ └────────┬────────┘ │ │ +│ │ │ │ +│ └───────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌─────────────────┐ │ +│ │ Trigger Deploy │ │ +│ └────────┬────────┘ │ +│ │ │ +│ ▼ │ +│ ┌─────────────────┐ │ +│ │ Show Status │ │ +│ └─────────────────┘ │ +└─────────────────────────────────────────────────────────────────┘ +``` diff --git a/.claude/commands/eureka/index.md b/.claude/commands/eureka/index.md new file mode 100644 index 0000000..be575e1 --- /dev/null +++ b/.claude/commands/eureka/index.md @@ -0,0 +1,595 @@ +--- +description: Generate comprehensive project documentation for engineers and non-engineers +allowed-tools: Read, Write, Edit, Bash, Task, TodoWrite, Glob, Grep +--- + +# Eureka Index - Project Documentation Generator + +**Input**: "$ARGUMENTS" + +--- + +## PURPOSE + +Generate comprehensive, dual-audience documentation by analyzing the current project structure using **parallel agent execution**. The output is designed to be understandable for **both engineers and non-engineers**. + +### Documentation Layers + +| Layer | Audience | Content | +|-------|----------|---------| +| Executive Summary | Everyone | Project purpose, value, capabilities | +| Architecture Overview | Everyone | Visual diagrams, technology stack | +| Getting Started | Semi-technical | Setup, basic usage, configuration | +| Feature Guide | Non-engineers | Plain-language feature descriptions | +| API Reference | Engineers | Endpoints, schemas, authentication | +| Component Catalog | Engineers | Props, interfaces, usage examples | +| Data Models | Both | ER diagrams + plain descriptions | +| Glossary | Non-engineers | Technical terms explained | + +--- + +## EXECUTION ARCHITECTURE + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ PARALLEL EXECUTION PIPELINE │ +├─────────────────────────────────────────────────────────────────────┤ +│ │ +│ PHASE 1: PARALLEL ANALYSIS (run_in_background: true) │ +│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌────────────┐ │ +│ │ Structure │ │ API │ │ Components │ │ Models │ │ +│ │ Analyzer │ │ Analyzer │ │ Analyzer │ │ Analyzer │ │ +│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ └─────┬──────┘ │ +│ │ │ │ │ │ +│ ▼ ▼ ▼ ▼ │ +│ PHASE 2: SYNCHRONIZATION │ +│ ┌─────────────────────────────────────────────────────────────┐ │ +│ │ Merge & Create Unified Analysis │ │ +│ └─────────────────────────────────────────────────────────────┘ │ +│ │ │ +│ ▼ │ +│ PHASE 3: PARALLEL DOCUMENTATION (run_in_background: true) │ +│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌────────────┐ │ +│ │ Main Doc │ │ API Docs │ │ Components │ │ Quick │ │ +│ │ Generator │ │ Generator │ │ Generator │ │ Reference │ │ +│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ └─────┬──────┘ │ +│ │ │ │ │ │ +│ ▼ ▼ ▼ ▼ │ +│ PHASE 4: FINALIZATION │ +│ ┌─────────────────────────────────────────────────────────────┐ │ +│ │ HTML Generation + Validation + Summary │ │ +│ └─────────────────────────────────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +--- + +## ⛔ CRITICAL RULES + +### MUST DO +1. **MUST** launch analysis agents in parallel using `run_in_background: true` +2. **MUST** wait for all analysis agents before synchronization +3. **MUST** launch documentation agents in parallel after synchronization +4. **MUST** include both technical and non-technical descriptions +5. **MUST** validate generated documentation against actual code + +### CANNOT DO +1. **CANNOT** make up features that don't exist +2. **CANNOT** skip the parallel analysis phase +3. **CANNOT** generate docs without synchronizing analysis results + +--- + +## EXECUTION FLOW + +### ═══════════════════════════════════════════════════════════════ +### PHASE 1: Parallel Analysis +### ═══════════════════════════════════════════════════════════════ + +#### 1.1: Display Start Banner & Setup +``` +╔══════════════════════════════════════════════════════════════╗ +║ 📚 EUREKA INDEX - Parallel Documentation Generator ║ +╠══════════════════════════════════════════════════════════════╣ +║ Launching parallel analysis agents... ║ +║ Output: Dual-audience documentation (Engineer + Non-Engineer)║ +╚══════════════════════════════════════════════════════════════╝ +``` + +```bash +OUTPUT_DIR="${ARGUMENTS:-docs}" +mkdir -p "$OUTPUT_DIR" +echo "📁 Output directory: $OUTPUT_DIR" +``` + +#### 1.2: Launch Parallel Analysis Agents + +**CRITICAL: Launch ALL four agents in a SINGLE message with multiple Task tool calls:** + +``` +Launch these 4 Task agents IN PARALLEL (single message, multiple tool calls): + +┌─────────────────────────────────────────────────────────────────┐ +│ AGENT 1: Structure Analyzer │ +├─────────────────────────────────────────────────────────────────┤ +│ Task tool with: │ +│ subagent_type: "Explore" │ +│ run_in_background: true │ +│ prompt: | │ +│ # PROJECT STRUCTURE ANALYSIS │ +│ │ +│ Analyze the project structure and return findings. │ +│ │ +│ ## Tasks │ +│ 1. Identify project type (package.json, requirements.txt, │ +│ Cargo.toml, go.mod, pom.xml) │ +│ 2. Extract metadata (name, version, description) │ +│ 3. Map directory structure with purposes │ +│ 4. Identify tech stack (language, framework, database) │ +│ 5. List key dependencies with plain English purposes │ +│ │ +│ ## Output Format (YAML) │ +│ ```yaml │ +│ project: │ +│ name: "..." │ +│ version: "..." │ +│ description: "..." │ +│ type: "node|python|rust|go|java|other" │ +│ tech_stack: │ +│ language: "..." │ +│ framework: "..." │ +│ database: "..." │ +│ structure: │ +│ directories: │ +│ - path: "..." │ +│ purpose: "..." │ +│ file_count: N │ +│ dependencies: │ +│ - name: "..." │ +│ purpose: "plain English" │ +│ ``` │ +└─────────────────────────────────────────────────────────────────┘ + +┌─────────────────────────────────────────────────────────────────┐ +│ AGENT 2: API Analyzer │ +├─────────────────────────────────────────────────────────────────┤ +│ Task tool with: │ +│ subagent_type: "Explore" │ +│ run_in_background: true │ +│ prompt: | │ +│ # API ENDPOINTS ANALYSIS │ +│ │ +│ Find and analyze all API endpoints in the project. │ +│ │ +│ ## Search Patterns │ +│ - Next.js App Router: app/api/**/route.ts │ +│ - Next.js Pages: pages/api/**/*.ts │ +│ - Express: router.get/post/put/delete │ +│ - FastAPI: @app.get/post/put/delete │ +│ - GraphQL: Query/Mutation resolvers │ +│ │ +│ ## Output Format (YAML) │ +│ ```yaml │ +│ api_endpoints: │ +│ - method: "GET|POST|PUT|DELETE" │ +│ path: "/api/..." │ +│ handler_file: "path/to/file.ts" │ +│ description: "plain English" │ +│ request_body: "schema if POST/PUT" │ +│ response: "schema summary" │ +│ auth_required: true|false │ +│ ``` │ +│ │ +│ If no APIs found, return: api_endpoints: [] │ +└─────────────────────────────────────────────────────────────────┘ + +┌─────────────────────────────────────────────────────────────────┐ +│ AGENT 3: Components Analyzer │ +├─────────────────────────────────────────────────────────────────┤ +│ Task tool with: │ +│ subagent_type: "Explore" │ +│ run_in_background: true │ +│ prompt: | │ +│ # UI COMPONENTS ANALYSIS │ +│ │ +│ Find and analyze all UI components in the project. │ +│ │ +│ ## Search Patterns │ +│ - React: components/**/*.tsx, function Component() │ +│ - Vue: components/**/*.vue, + + + ``` + + ### Visual Design Standards + + **Hero Section**: + - Full viewport height or 80vh minimum + - Gradient or subtle pattern background + - Large, bold headline (48-72px) + - Clear visual hierarchy + - Floating elements or subtle animation + + **Feature Cards**: + - Icon + Title + Description + - Subtle hover effects (scale, shadow) + - Consistent spacing (24-32px gaps) + - 3-column on desktop, 1 on mobile + + **How It Works**: + - Visual step indicators (1, 2, 3) + - Connecting lines or arrows + - Icons or illustrations per step + - Horizontal on desktop, vertical on mobile + + **FAQ Accordion**: + - Click to expand/collapse + - Smooth animation (max-height transition) + - Plus/minus or chevron indicator + - Category grouping + + **Micro-interactions**: + - Button hover: scale(1.02) + shadow + - Card hover: translateY(-4px) + shadow + - Smooth scroll for anchor links + - Fade-in on scroll (intersection observer) + + ### CSS Requirements + + ```css + /* CSS Custom Properties from branding.json */ + :root { + --color-primary: ...; + --color-secondary: ...; + --font-heading: ...; + --radius: ...; + } + + /* Dark mode */ + @media (prefers-color-scheme: dark) { + :root { + --color-bg: var(--color-bg-dark); + ... + } + } + + /* Responsive breakpoints */ + /* Mobile: < 640px */ + /* Tablet: 640-1024px */ + /* Desktop: > 1024px */ + ``` + + ### JavaScript Requirements + - FAQ accordion functionality + - Smooth scroll for navigation + - Optional: Scroll-triggered animations + - Dark mode toggle (optional) + - Mobile menu toggle + + ### Performance + - Single HTML file (no external dependencies) + - Inline critical CSS + - Minimal JavaScript + - Optimized for Core Web Vitals + - < 100KB total size + + Write complete HTML to: $DOCS_DIR/landing.html +``` + +--- + +### ═══════════════════════════════════════════════════════════════ +### PHASE 4: Finalization +### ═══════════════════════════════════════════════════════════════ + +#### 4.1: Validate Generated Files + +Verify all files exist: +- `$DOCS_DIR/branding.json` +- `$DOCS_DIR/content.json` +- `$DOCS_DIR/faq.json` +- `$DOCS_DIR/seo.json` +- `$DOCS_DIR/landing.html` + +#### 4.2: Display Completion Banner + +``` +╔══════════════════════════════════════════════════════════════╗ +║ ✅ LANDING PAGE GENERATED SUCCESSFULLY ║ +╠══════════════════════════════════════════════════════════════╣ +║ Output Directory: $DOCS_DIR ║ +╠══════════════════════════════════════════════════════════════╣ +║ Files Created: ║ +║ 🎨 branding.json (Colors, typography, style guide) ║ +║ 📝 content.json (Hero, features, how-it-works) ║ +║ ❓ faq.json (Q&A content by category) ║ +║ 🔍 seo.json (Meta tags, Open Graph, Schema) ║ +║ 🌐 landing.html (Designer-quality landing page) ║ +╠══════════════════════════════════════════════════════════════╣ +║ Landing Page Features: ║ +║ ✅ Hero with compelling headline + CTAs ║ +║ ✅ Feature grid with icons ║ +║ ✅ How It Works visual flow ║ +║ ✅ Interactive FAQ accordion ║ +║ ✅ Responsive (mobile-first) ║ +║ ✅ Dark mode support ║ +║ ✅ SEO optimized ║ +║ ✅ Single file, no dependencies ║ +╠══════════════════════════════════════════════════════════════╣ +║ Next Steps: ║ +║ → Open landing.html in browser to preview ║ +║ → Customize colors in branding.json ║ +║ → Add real screenshots/images ║ +║ → Deploy to your hosting ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +--- + +## ARGUMENTS + +| Argument | Default | Description | +|----------|---------|-------------| +| `[docs_dir]` | `docs` | Directory containing documentation from /eureka:index | +| `--style` | `modern` | Design style: modern, minimal, bold, corporate | +| `--theme` | `auto` | Color theme: auto, light, dark | + +## EXAMPLES + +```bash +# Generate landing page from default docs directory +/eureka:landing + +# Generate from custom documentation directory +/eureka:landing my-docs + +# Generate with specific style +/eureka:landing --style minimal + +# Generate dark-only theme +/eureka:landing --theme dark +``` + +--- + +## DESIGN STYLE OPTIONS + +### Modern (Default) +- Gradient backgrounds +- Rounded corners (12-16px) +- Soft shadows +- Vibrant accent colors +- Floating elements + +### Minimal +- Clean white space +- Thin borders +- Muted colors +- Typography-focused +- Subtle interactions + +### Bold +- Strong colors +- Large typography +- High contrast +- Geometric shapes +- Impactful CTAs + +### Corporate +- Professional blues/grays +- Structured layout +- Trust indicators +- Clean lines +- Conservative animations + +--- + +## OUTPUT STRUCTURE + +``` +docs/ +├── analysis.yml (from /eureka:index) +├── PROJECT_DOCUMENTATION.md +├── API_REFERENCE.md +├── COMPONENTS.md +├── QUICK_REFERENCE.md +├── index.html (documentation HTML) +│ +├── branding.json (NEW - concept branding) +├── content.json (NEW - marketing content) +├── faq.json (NEW - Q&A content) +├── seo.json (NEW - SEO metadata) +└── landing.html (NEW - landing page) +``` + +--- + +## BRANDING SYSTEM + +The generated branding.json provides a complete design system: + +```json +{ + "brand": { + "name": "Project Name", + "tagline": "Your compelling tagline", + "value_proposition": "What makes it unique" + }, + "colors": { + "primary": "#6366f1", + "secondary": "#8b5cf6", + "accent": "#f59e0b", + "background": "#ffffff", + "background_dark": "#0f172a", + "text": "#1e293b", + "text_muted": "#64748b" + }, + "typography": { + "heading_font": "Inter, system-ui, sans-serif", + "body_font": "Inter, system-ui, sans-serif", + "mono_font": "JetBrains Mono, Consolas, monospace" + }, + "style": { + "border_radius": "12px", + "shadow_sm": "0 1px 2px rgba(0,0,0,0.05)", + "shadow_md": "0 4px 6px -1px rgba(0,0,0,0.1)", + "shadow_lg": "0 10px 15px -3px rgba(0,0,0,0.1)", + "gradient": "linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)" + } +} +``` + +This can be used to: +- Maintain consistent branding across all pages +- Generate CSS custom properties +- Create Figma/design tool exports +- Build component libraries diff --git a/.claude/commands/guardrail/analyze.md b/.claude/commands/guardrail/analyze.md new file mode 100644 index 0000000..4620c31 --- /dev/null +++ b/.claude/commands/guardrail/analyze.md @@ -0,0 +1,243 @@ +--- +description: Analyze codebase and generate project manifest from existing code +allowed-tools: Read, Write, Bash, Glob, Grep, Task, AskUserQuestion +--- + +# Analyze Codebase and Generate Manifest + +Analyze the current codebase and generate all files needed for the guardrail workflow system. + +## Arguments + +- `$ARGUMENTS` - Optional flags: + - `--force` - Overwrite existing manifest without asking + - `--dry-run` - Preview manifest without writing + - `--deep` - Use AI agent for deeper analysis + - `` - Custom project name + +## Generated Files + +This command creates: +1. `project_manifest.json` - Entity definitions and dependencies +2. `.workflow/index.yml` - Version tracking index +3. `.workflow/versions/` - Directory for version snapshots + +## Quick Execution (Default) + +### Step 1: Run the Python analyzer script +```bash +python3 skills/guardrail-orchestrator/scripts/analyze_codebase.py --path . $ARGUMENTS +``` + +If the script succeeds, continue to Step 2. + +### Step 2: Initialize Workflow Directory Structure [MANDATORY] +```bash +# Create workflow directory structure +mkdir -p .workflow/versions + +# Create index.yml if it doesn't exist +if [ ! -f .workflow/index.yml ]; then + cat > .workflow/index.yml << 'EOF' +versions: [] +latest_version: null +total_versions: 0 +EOF + echo "Created .workflow/index.yml" +fi +``` + +### Step 3: Display Summary +``` +╔══════════════════════════════════════════════════════════════╗ +║ ✅ GUARDRAIL INITIALIZED ║ +╠══════════════════════════════════════════════════════════════╣ +║ Files Created: ║ +║ ✓ project_manifest.json ║ +║ ✓ .workflow/index.yml ║ +║ ✓ .workflow/versions/ ║ +╠══════════════════════════════════════════════════════════════╣ +║ Ready to use: ║ +║ /workflow:spawn Start a new feature ║ +║ /guardrail:status Check project status ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +## Deep Analysis Mode (--deep flag) + +**Use the Task tool to spawn an Explore agent for comprehensive codebase analysis** + +Use Task tool with: + subagent_type: "Explore" + prompt: | + Analyze this codebase thoroughly and return structured information about: + + 1. **Pages** (Next.js App Router): + - Find all page.tsx files in app/ directory + - Extract route paths from file locations + - Identify components imported/used + - Identify API dependencies (fetch calls) + + 2. **Components**: + - Find all .tsx files in app/components/ + - Extract component names and exports + - Extract prop interfaces/types + - Identify child component dependencies + + 3. **API Routes**: + - Find all route.ts files in app/api/ + - Extract HTTP methods (GET, POST, PUT, DELETE, PATCH) + - Identify request/response types + - Extract path parameters + + 4. **Database/Types**: + - Find type definitions in app/lib/ + - Extract interfaces and type aliases + - Identify database schemas/tables + + 5. **Dependencies**: + - Which components are used by which pages + - Which APIs are called by which components + - Which database tables are used by which APIs + + Return the analysis as structured JSON sections. + +### Phase 2: Generate Manifest + +Based on the analysis, create `project_manifest.json` with this structure: + +```json +{ + "project": { + "name": "", + "version": "1.0.0", + "created_at": "", + "description": "" + }, + "state": { + "current_phase": "IMPLEMENTATION_PHASE", + "approval_status": { + "manifest_approved": true, + "approved_by": "analyzer", + "approved_at": "" + }, + "revision_history": [ + { + "action": "MANIFEST_GENERATED", + "timestamp": "", + "details": "Generated from existing codebase analysis" + } + ] + }, + "entities": { + "pages": [ + { + "id": "page_", + "path": "/", + "file_path": "app//page.tsx", + "status": "IMPLEMENTED", + "description": "", + "components": ["comp_", ...], + "data_dependencies": ["api_", ...] + } + ], + "components": [ + { + "id": "comp_", + "name": "", + "file_path": "app/components/.tsx", + "status": "IMPLEMENTED", + "description": "", + "props": { + "": { + "type": "", + "optional": true|false, + "description": "" + } + } + } + ], + "api_endpoints": [ + { + "id": "api__", + "path": "/api/", + "method": "GET|POST|PUT|DELETE|PATCH", + "file_path": "app/api//route.ts", + "status": "IMPLEMENTED", + "description": "", + "request": { + "params": {}, + "query": {}, + "body": {} + }, + "response": { + "type": "", + "description": "" + } + } + ], + "database_tables": [ + { + "id": "table_", + "name": "", + "file_path": "app/lib/db.ts", + "status": "IMPLEMENTED", + "description": "", + "columns": {} + } + ] + }, + "dependencies": { + "component_to_page": {}, + "api_to_component": {}, + "table_to_api": {} + }, + "types": {} +} +``` + +### Phase 3: Entity Naming Conventions + +Use these ID formats: +- **Pages**: `page_` (e.g., `page_home`, `page_tasks`, `page_task_detail`) +- **Components**: `comp_` (e.g., `comp_task_list`, `comp_filter_bar`) +- **APIs**: `api__` (e.g., `api_list_tasks`, `api_create_task`) +- **Tables**: `table_` (e.g., `table_tasks`, `table_users`) + +### Phase 4: Write Manifest + +1. Write the generated manifest to `project_manifest.json` +2. Validate JSON syntax +3. Display summary: + +``` +╔══════════════════════════════════════════════════════════════╗ +║ 📊 MANIFEST GENERATED ║ +╠══════════════════════════════════════════════════════════════╣ +║ Project: ║ +║ Generated: ║ +╠══════════════════════════════════════════════════════════════╣ +║ ENTITIES DISCOVERED ║ +║ 📄 Pages: X ║ +║ 🧩 Components: X ║ +║ 🔌 APIs: X ║ +║ 🗄️ Tables: X ║ +╠══════════════════════════════════════════════════════════════╣ +║ Status: All entities marked as IMPLEMENTED ║ +║ Phase: IMPLEMENTATION_PHASE ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +## Options + +If manifest already exists, ask user: +1. **Overwrite** - Replace existing manifest +2. **Merge** - Add new entities, keep existing +3. **Cancel** - Abort operation + +## Notes + +- All discovered entities are marked as `IMPLEMENTED` since they already exist +- Project starts in `IMPLEMENTATION_PHASE` since code exists +- Use this command to bring existing projects under guardrail management +- After generation, use `/guardrail:validate` to verify manifest accuracy diff --git a/.claude/commands/guardrail/approve.md b/.claude/commands/guardrail/approve.md new file mode 100644 index 0000000..1a04a9a --- /dev/null +++ b/.claude/commands/guardrail/approve.md @@ -0,0 +1,47 @@ +--- +description: Approve design and transition to IMPLEMENTATION_PHASE (Reviewer mode) +allowed-tools: Read, Write, Bash +--- + +# Approve Design (Reviewer Mode) + +✅ **REVIEWER MODE ACTIVATED** + +Approve the current design and enable implementation. + +## CRITICAL RULES + +You are acting as the **REVIEWER AGENT**. + +✅ **ALLOWED**: +- Read any file +- Update approval status in manifest +- Transition phases + +❌ **BLOCKED**: +- Write ANY code files +- You cannot implement anything + +## Steps + +1. **Verify Phase**: Must be in `DESIGN_REVIEW` + +2. **Run Full Validation**: +```bash +python3 "$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_manifest.py" --strict +``` + +3. **If Valid**, update manifest: + - Set `state.approval_status.manifest_approved = true` + - Set `state.approval_status.approved_by = "reviewer"` + - Set `state.approval_status.approved_at = ` + +4. **Transition to Implementation**: +```bash +python3 "$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/transition_phase.py" --to IMPLEMENTATION_PHASE +``` + +5. **Show Results**: + - List all entities now with status `APPROVED` + - Explain that code can now be written for these entities + - Suggest `/guardrail:implement` to start diff --git a/.claude/commands/guardrail/design.md b/.claude/commands/guardrail/design.md new file mode 100644 index 0000000..e5138aa --- /dev/null +++ b/.claude/commands/guardrail/design.md @@ -0,0 +1,81 @@ +--- +description: Design a new feature by adding entities to manifest (Architect mode) +allowed-tools: Read, Write, Bash +--- + +# Design Feature (Architect Mode) + +🏗️ **ARCHITECT MODE ACTIVATED** + +Design the feature: "$ARGUMENTS" + +## CRITICAL RULES + +You are now acting as the **ARCHITECT AGENT**. + +✅ **ALLOWED**: +- Read any file +- Write to `project_manifest.json` ONLY +- Run validation scripts + +❌ **BLOCKED**: +- Write ANY code files (.ts, .tsx, .css, .sql, .js, .jsx) +- You CANNOT write implementation code yet + +## Workflow + +1. **Verify Phase**: Check `project_manifest.json` - must be in `DESIGN_PHASE` + +2. **Analyze Requirements**: Break down "$ARGUMENTS" into: + - Pages needed (routes/screens) + - Components needed (UI elements) + - API endpoints needed (backend routes) + - Database tables needed (data storage) + +3. **Define Each Entity** in manifest with: + - Unique ID following naming convention + - Complete specification (props, schemas, columns) + - `status: "DEFINED"` + - File path where it will be implemented + +4. **Update Manifest**: Add all entities to `project_manifest.json` + +5. **Validate**: Run `python3 skills/guardrail-orchestrator/scripts/validate_manifest.py` + +6. **Summarize**: List what was added and suggest `/guardrail:review` + +## Entity Templates + +### Page +```json +{ + "id": "page_[name]", + "path": "/[route]", + "file_path": "src/pages/[name]/index.tsx", + "status": "DEFINED", + "components": [], + "data_dependencies": [] +} +``` + +### Component +```json +{ + "id": "comp_[name]", + "name": "[PascalCase]", + "file_path": "src/components/[Name]/index.tsx", + "status": "DEFINED", + "props": {} +} +``` + +### API Endpoint +```json +{ + "id": "api_[action]_[resource]", + "path": "/api/v1/[resource]", + "method": "GET|POST|PUT|DELETE", + "file_path": "src/api/[resource]/[action].ts", + "status": "DEFINED" +} +``` diff --git a/.claude/commands/guardrail/implement.md b/.claude/commands/guardrail/implement.md new file mode 100644 index 0000000..cb151e3 --- /dev/null +++ b/.claude/commands/guardrail/implement.md @@ -0,0 +1,74 @@ +--- +description: Implement an approved entity from the manifest +allowed-tools: Read, Write, Bash +--- + +# Implement Entity + +Implement the entity: "$ARGUMENTS" + +## CRITICAL RULES + +⚠️ **GUARDRAIL ENFORCEMENT ACTIVE** + +You can ONLY write to files that: +1. Are defined in `project_manifest.json` +2. Have status = `APPROVED` +3. Match the `file_path` in the manifest EXACTLY + +## Steps + +1. **Verify Phase**: Must be in `IMPLEMENTATION_PHASE` + +2. **Find Entity** in manifest: + - If "$ARGUMENTS" is `--all`: implement all APPROVED entities + - Otherwise: find the specific entity by ID + +3. **For Each Entity**: + + a. **Load Definition** from manifest + + b. **Verify Status** is `APPROVED` + + c. **Generate Code** matching the specification: + - Props must match manifest exactly + - Types must match manifest exactly + - File path must match `file_path` in manifest + + d. **Write File** to the exact path in manifest + + e. **Run Validations**: + ```bash + npm run lint --if-present + npm run type-check --if-present + ``` + +4. **Status Updates** (handled by post-hook): + - Entity status changes to `IMPLEMENTED` + - Timestamp recorded + +## Code Templates + +### Component (Frontend) +```tsx +import React from 'react'; + +interface [Name]Props { + // From manifest.props +} + +export const [Name]: React.FC<[Name]Props> = (props) => { + return ( + // Implementation + ); +}; +``` + +### API Endpoint (Backend) +```typescript +import { Request, Response } from 'express'; + +export async function handler(req: Request, res: Response) { + // From manifest.request/response schemas +} +``` diff --git a/.claude/commands/guardrail/init.md b/.claude/commands/guardrail/init.md new file mode 100644 index 0000000..94db4f3 --- /dev/null +++ b/.claude/commands/guardrail/init.md @@ -0,0 +1,67 @@ +--- +description: Initialize a new guardrailed project with manifest +allowed-tools: Bash, Write, Read +--- + +# Initialize Guardrailed Project + +Initialize a new project called "$ARGUMENTS" with guardrail enforcement and workflow system. + +## Generated Files + +This command creates: +1. `project_manifest.json` - Entity definitions and dependencies +2. `.workflow/index.yml` - Version tracking index +3. `.workflow/versions/` - Directory for version snapshots + +## Steps + +### Step 1: Run the initialization script +```bash +python3 skills/guardrail-orchestrator/scripts/init_project.py --name "$ARGUMENTS" --path . +``` + +### Step 2: Initialize Workflow Directory Structure [MANDATORY] +```bash +# Create workflow directory structure +mkdir -p .workflow/versions + +# Create index.yml if it doesn't exist +if [ ! -f .workflow/index.yml ]; then + cat > .workflow/index.yml << 'EOF' +versions: [] +latest_version: null +total_versions: 0 +EOF +fi +``` + +### Step 3: Verify and Display Summary +```bash +# Verify files exist +ls project_manifest.json .workflow/index.yml +``` + +Display: +``` +╔══════════════════════════════════════════════════════════════╗ +║ ✅ PROJECT INITIALIZED ║ +╠══════════════════════════════════════════════════════════════╣ +║ Project: $ARGUMENTS ║ +║ Phase: DESIGN_PHASE ║ +╠══════════════════════════════════════════════════════════════╣ +║ Files Created: ║ +║ ✓ project_manifest.json ║ +║ ✓ .workflow/index.yml ║ +║ ✓ .workflow/versions/ ║ +╠══════════════════════════════════════════════════════════════╣ +║ Next Steps: ║ +║ /guardrail:design Design features in manifest ║ +║ /workflow:spawn Start automated workflow ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +## Notes +- Project starts in **DESIGN_PHASE** (manifest edits only) +- Use `/guardrail:design` for manual design workflow +- Use `/workflow:spawn` for automated design + implementation diff --git a/.claude/commands/guardrail/review.md b/.claude/commands/guardrail/review.md new file mode 100644 index 0000000..908610d --- /dev/null +++ b/.claude/commands/guardrail/review.md @@ -0,0 +1,32 @@ +--- +description: Request design review and transition to DESIGN_REVIEW phase +allowed-tools: Read, Write, Bash +--- + +# Request Design Review + +Transition the project from DESIGN_PHASE to DESIGN_REVIEW. + +## Steps + +1. **Validate Manifest**: +```bash +python3 "$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_manifest.py" --strict +``` + +2. **If Valid**, transition phase: +```bash +python3 "$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/transition_phase.py" --to DESIGN_REVIEW +``` + +3. **Show Review Checklist**: + - [ ] All pages have at least one component + - [ ] All components have defined props with types + - [ ] All APIs have request/response schemas + - [ ] All database tables have primary keys + - [ ] No orphan components + - [ ] No circular dependencies + +4. **Explain Next Steps**: + - Use `/guardrail:approve` to approve and move to implementation + - Use `/guardrail:reject ` to send back for fixes diff --git a/.claude/commands/guardrail/status.md b/.claude/commands/guardrail/status.md new file mode 100644 index 0000000..53ba37e --- /dev/null +++ b/.claude/commands/guardrail/status.md @@ -0,0 +1,27 @@ +--- +description: Show current project phase, entity counts, and pending work +allowed-tools: Read, Bash +--- + +# Guardrail Status + +Display the current guardrail project status. + +## Steps + +1. Read `project_manifest.json` + +2. Display: + - **Current Phase**: `state.current_phase` + - **Approval Status**: `state.approval_status.manifest_approved` + - **Entity Counts**: + - Pages: count by status (DEFINED/APPROVED/IMPLEMENTED) + - Components: count by status + - API Endpoints: count by status + - Database Tables: count by status + - **Recent History**: last 5 items from `state.revision_history` + +3. Show available actions for current phase: + - DESIGN_PHASE: Can use `/guardrail:design`, then `/guardrail:review` + - DESIGN_REVIEW: Can use `/guardrail:approve` or `/guardrail:reject` + - IMPLEMENTATION_PHASE: Can use `/guardrail:implement` diff --git a/.claude/commands/guardrail/validate.md b/.claude/commands/guardrail/validate.md new file mode 100644 index 0000000..4467e50 --- /dev/null +++ b/.claude/commands/guardrail/validate.md @@ -0,0 +1,29 @@ +--- +description: Validate manifest integrity and completeness +allowed-tools: Bash, Read +--- + +# Validate Manifest + +Run validation checks on `project_manifest.json`. + +## Command + +```bash +python3 "$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_manifest.py" $ARGUMENTS +``` + +## Options + +- No arguments: Basic validation +- `--strict`: Treat warnings as errors + +## What It Checks + +1. **Structure**: Required top-level keys exist +2. **Pages**: Have paths, components, file_paths +3. **Components**: Have props with types, valid dependencies +4. **APIs**: Have methods, paths, request/response schemas +5. **Database**: Tables have primary keys, valid foreign keys +6. **Dependencies**: No orphans, no circular references +7. **Naming**: Follows conventions diff --git a/.claude/commands/guardrail/verify.md b/.claude/commands/guardrail/verify.md new file mode 100644 index 0000000..e6d03e1 --- /dev/null +++ b/.claude/commands/guardrail/verify.md @@ -0,0 +1,57 @@ +--- +description: Verify implementation matches manifest specifications +allowed-tools: Bash, Read +--- + +# Verify Implementation + +Run verification to ensure all implemented code matches the manifest specifications. + +## Command + +```bash +python3 "$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/verify_implementation.py" --project-root "$CLAUDE_PROJECT_DIR" $ARGUMENTS +``` + +## Options + +- No arguments: Basic verification +- `--verbose` or `-v`: Include warnings +- `--json`: Output as JSON for programmatic use + +## What It Checks + +For each entity in the manifest: + +### Components +- File exists at specified `file_path` +- Component name is exported +- Props interface matches manifest definition + +### Pages +- File exists at specified `file_path` +- Has `export default` (Next.js requirement) +- Uses specified component dependencies + +### API Endpoints +- File exists at specified `file_path` +- HTTP method handler exists (GET, POST, PUT, DELETE) +- Request parameters are handled + +### Database Tables +- File exists at specified `file_path` +- Column definitions present +- CRUD operations implemented + +## Example Output + +``` +✅ [component] comp_button + File: app/components/Button.tsx + +❌ [component] comp_missing + File: app/components/Missing.tsx + ❌ ERROR: File not found + +SUMMARY: 17/18 passed, 1 failed, 3 warnings +``` diff --git a/.claude/commands/workflow/approve.md b/.claude/commands/workflow/approve.md new file mode 100644 index 0000000..8bedd42 --- /dev/null +++ b/.claude/commands/workflow/approve.md @@ -0,0 +1,87 @@ +--- +description: Approve a workflow gate (design or implementation) +allowed-tools: Read, Write, Bash +--- + +# Approve Workflow Gate + +Approve gate: "$ARGUMENTS" + +## Valid Gates +- `design` - Approve the design phase (entities + tasks) +- `implementation` - Approve the implementation phase (all code) + +## Steps + +### 1. Validate Gate +- If "$ARGUMENTS" is not `design` or `implementation`: STOP and show usage + +### 2. Check Workflow State +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py exists +``` + +If no active workflow: +``` +❌ No active workflow found. + Start a new workflow with: /workflow:spawn "feature name" +``` + +### 3. Verify Current Phase + +**For design approval**: +- Current phase must be `AWAITING_DESIGN_APPROVAL` +- If not: Report error with current phase + +**For implementation approval**: +- Current phase must be `AWAITING_IMPL_APPROVAL` +- If not: Report error with current phase + +### 4. Execute Approval + +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py approve $ARGUMENTS +``` + +### 5. Transition to Next Phase + +**If design approved**: +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition DESIGN_APPROVED +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition IMPLEMENTING +``` + +**If implementation approved**: +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition IMPL_APPROVED +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition COMPLETING +``` + +### 6. Report + +**Design Approved**: +``` +╔══════════════════════════════════════════════════════════════╗ +║ ✅ DESIGN APPROVED ║ +╠══════════════════════════════════════════════════════════════╣ +║ The design has been approved. Implementation will begin. ║ +║ ║ +║ Next steps: ║ +║ /workflow:frontend --next Start frontend tasks ║ +║ /workflow:backend --next Start backend tasks ║ +║ /workflow:resume Auto-continue workflow ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +**Implementation Approved**: +``` +╔══════════════════════════════════════════════════════════════╗ +║ ✅ IMPLEMENTATION APPROVED ║ +╠══════════════════════════════════════════════════════════════╣ +║ All implementations have been approved. ║ +║ ║ +║ Next steps: ║ +║ /workflow:complete --all Mark all tasks as done ║ +║ /workflow:resume Auto-complete workflow ║ +╚══════════════════════════════════════════════════════════════╝ +``` diff --git a/.claude/commands/workflow/backend.md b/.claude/commands/workflow/backend.md new file mode 100644 index 0000000..59b253b --- /dev/null +++ b/.claude/commands/workflow/backend.md @@ -0,0 +1,85 @@ +--- +description: Implement backend tasks (Backend agent) +allowed-tools: Read, Write, Edit, Bash +--- + +# Backend Agent - Implementation Mode + +⚙️ **BACKEND AGENT ACTIVATED** + +Implement task: "$ARGUMENTS" + +## CRITICAL RULES + +You are now the **BACKEND AGENT**. + +✅ **ALLOWED**: +- Read any file +- Write new files (API routes, DB) +- Edit existing backend files +- Run Bash (build, lint, type-check, tests) + +✅ **ALLOWED FILES**: +- `app/api/**/*` +- `app/lib/**/*` +- `prisma/**/*` +- `db/**/*` + +## Workflow + +### Step 1: Load Task +First, get the version-specific tasks directory: +```bash +TASKS_DIR=$(python3 skills/guardrail-orchestrator/scripts/version_manager.py tasks-dir) +``` + +Read the task file: `$TASKS_DIR/$ARGUMENTS.yml` +- If "$ARGUMENTS" is `--next`: find first task with `agent: backend` and `status: pending` + +### Step 2: Update Workflow State +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py task in_progress +``` + +### Step 3: Verify Prerequisites +- Check entity is `APPROVED` in `project_manifest.json` +- Check all `dependencies` tasks are `completed` +- If blocked: + ```bash + python3 skills/guardrail-orchestrator/scripts/workflow_manager.py task blocked + ``` + Stop and report blocker. + +### Step 4: Implement +For each file in `file_paths`: +1. Read manifest entity specification +2. Generate code matching spec exactly: + - HTTP methods must match manifest + - Request params must match manifest + - Response types must match manifest +3. Follow existing project patterns + +### Step 5: Validate +Run validations: +```bash +npm run lint +npm run build +``` + +### Step 6: Update Task Status +Update the task file: +```yaml +status: review +completed_at: +``` + +Update workflow state: +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py task review +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py progress --tasks-impl +``` + +### Step 7: Report +- List implemented files +- Show validation results +- Suggest: `/workflow:review $ARGUMENTS` diff --git a/.claude/commands/workflow/complete.md b/.claude/commands/workflow/complete.md new file mode 100644 index 0000000..e9923d8 --- /dev/null +++ b/.claude/commands/workflow/complete.md @@ -0,0 +1,66 @@ +--- +description: Mark approved task as completed +allowed-tools: Read, Write, Bash +--- + +# Complete Task + +Mark task "$ARGUMENTS" as completed. + +## Prerequisites +- Task must have `status: approved` +- All acceptance criteria verified by reviewer + +## Steps + +### 1. Read Task +First, get the version-specific tasks directory: +```bash +TASKS_DIR=$(python3 skills/guardrail-orchestrator/scripts/version_manager.py tasks-dir) +``` + +Read `$TASKS_DIR/$ARGUMENTS.yml` + +### 2. Verify Status +- If `status` is NOT `approved`: STOP and report error +- If `status` is `approved`: proceed + +### 3. Update Task +Update the task file with: +```yaml +status: completed +completed_at: +``` + +### 4. Update Workflow State +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py task completed +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py progress --tasks-completed +``` + +### 5. Update Manifest (if applicable) +For each entity in `entity_ids`: +- Update entity status to `IMPLEMENTED` in `project_manifest.json` + +### 6. Check Workflow Completion +Check if all tasks are now completed: +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py status +``` + +If all tasks completed, transition to implementation approval: +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition AWAITING_IMPL_APPROVAL +``` + +### 7. Report +``` +✅ Task completed: $ARGUMENTS + +Entities implemented: + - + - + +Next: /workflow:status to see remaining tasks + /workflow:complete --all to complete all approved tasks +``` diff --git a/.claude/commands/workflow/design.md b/.claude/commands/workflow/design.md new file mode 100644 index 0000000..fba6842 --- /dev/null +++ b/.claude/commands/workflow/design.md @@ -0,0 +1,476 @@ +--- +description: Design system architecture with ER diagram, API contracts, and UI structure +allowed-tools: Read, Write, Edit, Bash, Task, TodoWrite +--- + +# Workflow Design - System Architecture Phase + +**Input**: "$ARGUMENTS" + +--- + +## PURPOSE + +This command creates a comprehensive **design document** that serves as the source of truth for implementation. It defines: + +1. **Data Layer** - ER diagram with models, fields, relations +2. **API Layer** - REST endpoints with request/response contracts +3. **UI Layer** - Pages and components with data requirements +4. **Dependency Graph** - Layered execution order for parallel tasks + +--- + +## ⛔ CRITICAL RULES + +### MUST DO +1. **MUST** create `design_document.yml` with ALL layers defined +2. **MUST** run `validate_design.py` to generate dependency graph +3. **MUST** verify no circular dependencies before proceeding +4. **MUST** show layered execution plan to user + +### CANNOT DO +1. **CANNOT** create tasks without design document +2. **CANNOT** skip validation step +3. **CANNOT** proceed if validation fails + +--- + +## EXECUTION FLOW + +### ═══════════════════════════════════════════════════════════════ +### STEP 1: Initialize Design Session +### ═══════════════════════════════════════════════════════════════ + +#### 1.1: Get Current Version +```bash +# Get active version from workflow +VERSION_ID=$(cat .workflow/current.yml 2>/dev/null | grep "active_version:" | awk '{print $2}') +if [ -z "$VERSION_ID" ]; then + echo "ERROR: No active workflow. Run /workflow:spawn first" + exit 1 +fi +echo "VERSION_ID=$VERSION_ID" +``` + +#### 1.2: Create Design Directory +```bash +mkdir -p .workflow/versions/$VERSION_ID/design +mkdir -p .workflow/versions/$VERSION_ID/contexts +mkdir -p .workflow/versions/$VERSION_ID/tasks +``` + +#### 1.3: Display Design Start Banner +``` +╔══════════════════════════════════════════════════════════════╗ +║ 📐 SYSTEM DESIGN PHASE ║ +╠══════════════════════════════════════════════════════════════╣ +║ Feature: $ARGUMENTS ║ +║ Version: $VERSION_ID ║ +╠══════════════════════════════════════════════════════════════╣ +║ You will define: ║ +║ Layer 1: Data Models (ER Diagram) ║ +║ Layer 2: API Endpoints (REST Contracts) ║ +║ Layer 3: Pages & Components (UI Structure) ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +--- + +### ═══════════════════════════════════════════════════════════════ +### STEP 2: Analyze Requirements & Design System +### ═══════════════════════════════════════════════════════════════ + +**Use Task tool with system-architect agent:** + +``` +Use Task tool with: + subagent_type: "system-architect" + prompt: | + # SYSTEM ARCHITECT - Design Document Creation + + ## INPUT + Feature: "$ARGUMENTS" + Version: $VERSION_ID + Output: .workflow/versions/$VERSION_ID/design/design_document.yml + + ## YOUR MISSION + Create a comprehensive design document following the schema in: + skills/guardrail-orchestrator/schemas/design_document.yml + + ## ANALYSIS PROCESS + + ### Phase A: Understand Requirements + 1. Read the feature description carefully + 2. Identify the core user flows + 3. Determine what data needs to be stored + 4. Identify what APIs are needed + 5. Plan the UI structure + + ### Phase B: Design Data Layer (ER Diagram) + For each entity needed: + - Define fields with types and constraints + - Define relations to other entities + - Define validations + - Consider indexes for performance + + ### Phase C: Design API Layer + For each endpoint needed: + - Define HTTP method and path + - Define request body schema (for POST/PUT/PATCH) + - Define response schemas for all status codes + - Define authentication requirements + - Link to data models used + + ### Phase D: Design UI Layer + For each page needed: + - Define route path + - List data requirements (which APIs) + - List components used + - Define auth requirements + + For each component needed: + - Define props interface + - Define events emitted + - List child components + - List APIs called directly (if any) + + ## OUTPUT FORMAT + + Create `.workflow/versions/$VERSION_ID/design/design_document.yml`: + + ```yaml + # Design Document + workflow_version: "$VERSION_ID" + feature: "$ARGUMENTS" + created_at: + status: draft + revision: 1 + + # LAYER 1: DATA MODELS + data_models: + - id: model_ + name: + description: "" + table_name: + fields: + - name: id + type: uuid + constraints: [primary_key] + - name: + type: + constraints: [] + # If enum: + enum_values: [, ] + relations: + - type: + target: model_ + foreign_key: + on_delete: + timestamps: true + validations: + - field: + rule: "" + message: "" + + # LAYER 2: API ENDPOINTS + api_endpoints: + - id: api__ + method: + path: /api/ + summary: "" + description: "" + # For POST/PUT/PATCH: + request_body: + content_type: application/json + schema: + type: object + properties: + - name: + type: + required: + validations: [] + responses: + - status: 200 + description: "Success" + schema: + type: object + properties: + - name: + type: + - status: 400 + description: "Validation error" + schema: + type: object + properties: + - name: error + type: string + depends_on_models: [model_] + auth: + required: + roles: [, ] + + # LAYER 3: PAGES + pages: + - id: page_ + name: "" + path: / + layout: + data_needs: + - api_id: api_ + purpose: "" + on_load: + components: [component_, component_] + auth: + required: + roles: [] + redirect: /login + + # LAYER 3: COMPONENTS + components: + - id: component_ + name: + props: + - name: + type: + required: + description: "" + events: + - name: + payload: "" + description: "" + uses_apis: [] + uses_components: [component_] + variants: [, ] + ``` + + ## DESIGN PRINCIPLES + + 1. **Start with Data**: What data is needed? Design models first. + 2. **APIs Serve UI**: What operations does UI need? Design APIs next. + 3. **UI Consumes APIs**: Pages/Components use APIs. Design UI last. + 4. **Explicit Dependencies**: Every relation must be clearly defined. + 5. **Contracts First**: API request/response schemas are contracts. + + ## VERIFICATION + + After creating the design document, verify: + 1. Every API references existing models + 2. Every page references existing APIs and components + 3. Every component references existing child components + 4. No circular dependencies + + ## OUTPUT + + After creating the file, output: + ``` + === DESIGN DOCUMENT CREATED === + + Data Models: X + API Endpoints: X + Pages: X + Components: X + + File: .workflow/versions/$VERSION_ID/design/design_document.yml + ``` +``` + +--- + +### ═══════════════════════════════════════════════════════════════ +### STEP 3: Validate Design & Generate Dependency Graph +### ═══════════════════════════════════════════════════════════════ + +#### 3.1: Run Design Validation [MANDATORY] +```bash +python3 skills/guardrail-orchestrator/scripts/validate_design.py \ + .workflow/versions/$VERSION_ID/design/design_document.yml \ + --output-dir .workflow/versions/$VERSION_ID +``` + +**This generates:** +- `.workflow/versions/$VERSION_ID/dependency_graph.yml` - Layered execution order +- `.workflow/versions/$VERSION_ID/contexts/*.yml` - Per-entity context snapshots +- `.workflow/versions/$VERSION_ID/tasks/*.yml` - Tasks with full context + +#### 3.2: Check Validation Result +```bash +VALIDATION_EXIT=$? +if [ $VALIDATION_EXIT -ne 0 ]; then + echo "❌ Design validation failed. Fix errors and re-run." + exit 1 +fi +``` + +**BLOCK IF**: Validation fails → Display errors, do not proceed + +--- + +### ═══════════════════════════════════════════════════════════════ +### STEP 4: Display Layered Execution Plan +### ═══════════════════════════════════════════════════════════════ + +Read the generated dependency graph and display: + +``` +╔══════════════════════════════════════════════════════════════╗ +║ 📊 DEPENDENCY GRAPH - EXECUTION LAYERS ║ +╠══════════════════════════════════════════════════════════════╣ +║ ║ +║ Layer 1: DATA MODELS (Parallel) ║ +║ ───────────────────────────────────────────── ║ +║ 📦 model_user → backend ║ +║ 📦 model_post → backend ║ +║ ║ +║ Layer 2: API ENDPOINTS (Parallel, after Layer 1) ║ +║ ───────────────────────────────────────────── ║ +║ 🔌 api_create_user → backend (needs: model_user) ║ +║ 🔌 api_list_users → backend (needs: model_user) ║ +║ 🔌 api_create_post → backend (needs: model_user, model_post)║ +║ ║ +║ Layer 3: UI (Parallel, after Layer 2) ║ +║ ───────────────────────────────────────────── ║ +║ 🧩 component_user_card → frontend ║ +║ 📄 page_users → frontend (needs: api_list_users) ║ +║ ║ +╠══════════════════════════════════════════════════════════════╣ +║ EXECUTION SUMMARY ║ +║ Total entities: X ║ +║ Total layers: X ║ +║ Max parallelism: X (tasks can run simultaneously) ║ +║ Critical path: X layers deep ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +--- + +### ═══════════════════════════════════════════════════════════════ +### STEP 5: Display Design Summary for Approval +### ═══════════════════════════════════════════════════════════════ + +``` +╔══════════════════════════════════════════════════════════════╗ +║ 🛑 DESIGN APPROVAL REQUIRED ║ +╠══════════════════════════════════════════════════════════════╣ +║ Feature: $ARGUMENTS ║ +║ Version: $VERSION_ID ║ +╠══════════════════════════════════════════════════════════════╣ +║ DESIGN DOCUMENT ║ +║ 📦 Data Models: X ║ +║ 🔌 API Endpoints: X ║ +║ 📄 Pages: X ║ +║ 🧩 Components: X ║ +╠══════════════════════════════════════════════════════════════╣ +║ GENERATED ARTIFACTS ║ +║ ✅ Dependency graph calculated ║ +║ ✅ Context snapshots created (X files) ║ +║ ✅ Implementation tasks created (X tasks) ║ +╠══════════════════════════════════════════════════════════════╣ +║ EXECUTION PLAN ║ +║ Layer 1: X tasks (parallel) → backend ║ +║ Layer 2: X tasks (parallel) → backend ║ +║ Layer 3: X tasks (parallel) → frontend ║ +╠══════════════════════════════════════════════════════════════╣ +║ FILES CREATED ║ +║ .workflow/versions/$VERSION_ID/design/design_document.yml ║ +║ .workflow/versions/$VERSION_ID/dependency_graph.yml ║ +║ .workflow/versions/$VERSION_ID/contexts/*.yml ║ +║ .workflow/versions/$VERSION_ID/tasks/*.yml ║ +╠══════════════════════════════════════════════════════════════╣ +║ NEXT STEPS ║ +║ Review the design above, then: ║ +║ /workflow:approve - Proceed to implementation ║ +║ /workflow:reject - Request design changes ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +--- + +### ═══════════════════════════════════════════════════════════════ +### STEP 6: Transition Workflow State +### ═══════════════════════════════════════════════════════════════ + +```bash +# Update progress +TASK_COUNT=$(ls .workflow/versions/$VERSION_ID/tasks/*.yml 2>/dev/null | wc -l) +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py progress \ + --tasks-created $TASK_COUNT + +# Transition to awaiting approval +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition AWAITING_DESIGN_APPROVAL +``` + +--- + +## CONTEXT SNAPSHOT EXAMPLE + +Each task gets a context file like `.workflow/versions/$VERSION_ID/contexts/api_create_user.yml`: + +```yaml +task_id: task_create_api_create_user +entity_id: api_create_user +workflow_version: v001 + +target: + type: api + definition: + method: POST + path: /api/users + request_body: + properties: + - name: email + type: string + required: true + validations: [email] + - name: password + type: string + required: true + validations: [min:8] + responses: + - status: 201 + schema: { id, email, name, created_at } + - status: 400 + schema: { error, details } + - status: 409 + schema: { error } + +related: + models: + - id: model_user + definition: + name: User + fields: + - { name: id, type: uuid } + - { name: email, type: string } + - { name: password_hash, type: string } + +dependencies: + entity_ids: [model_user] + +files: + to_create: + - app/api/users/route.ts + reference: + - path: app/api/health/route.ts + purpose: "API route pattern" + +acceptance: + - criterion: "POST /api/users returns 201 on success" + verification: "curl -X POST /api/users with valid data" + - criterion: "Returns 409 if email exists" + verification: "Test with duplicate email" +``` + +--- + +## USAGE + +```bash +# After /workflow:spawn, run design: +/workflow:design + +# This will: +# 1. Create comprehensive design document +# 2. Validate and generate dependency graph +# 3. Create tasks with full context +# 4. Wait for approval before implementation +``` diff --git a/.claude/commands/workflow/diff.md b/.claude/commands/workflow/diff.md new file mode 100644 index 0000000..d24800d --- /dev/null +++ b/.claude/commands/workflow/diff.md @@ -0,0 +1,193 @@ +--- +description: Compare workflow versions and show manifest changes +allowed-tools: Read, Bash +--- + +# Workflow Version Diff + +Compare workflow versions to see what changed in the project manifest. + +## EXECUTION PROTOCOL + +### Step 1: Parse Arguments + +``` +IF "$ARGUMENTS" = "": + MODE = "current" (diff latest version with current) +ELSE IF "$ARGUMENTS" matches "v\d+ v\d+": + MODE = "versions" (diff two specific versions) +ELSE IF "$ARGUMENTS" matches "v\d+": + MODE = "single" (diff specific version with current) +ELSE IF "$ARGUMENTS" = "--changelog" or "--log": + MODE = "changelog" (show all version changelogs) +ELSE IF "$ARGUMENTS" contains "--json": + OUTPUT = "json" +``` + +### Step 2: Get Available Versions + +```bash +python3 skills/guardrail-orchestrator/scripts/manifest_diff.py versions +``` + +### Step 3: Execute Diff Based on Mode + +**MODE: current (default)** +```bash +# Get latest version +LATEST=$(ls -1 .workflow/versions/ 2>/dev/null | tail -1) + +# Diff with current manifest +python3 skills/guardrail-orchestrator/scripts/manifest_diff.py diff $LATEST current +``` + +**MODE: versions (e.g., "v001 v002")** +```bash +# Diff two specific versions +python3 skills/guardrail-orchestrator/scripts/manifest_diff.py diff v001 v002 +``` + +**MODE: single (e.g., "v001")** +```bash +# Diff specific version with current +python3 skills/guardrail-orchestrator/scripts/manifest_diff.py diff v001 +``` + +**MODE: changelog** +```bash +# Show all changelogs +python3 skills/guardrail-orchestrator/scripts/manifest_diff.py changelog +``` + +**JSON output** +```bash +# Add --json for programmatic use +python3 skills/guardrail-orchestrator/scripts/manifest_diff.py diff v001 --json +``` + +### Step 4: Display Results + +The script outputs: + +``` +╔══════════════════════════════════════════════════════════════════════╗ +║ MANIFEST DIFF: v001 → v002 ║ +╠══════════════════════════════════════════════════════════════════════╣ +║ SUMMARY ║ +║ + Added: 3 ║ +║ ~ Modified: 2 ║ +║ - Removed: 1 ║ +║ = Unchanged: 5 ║ +╠══════════════════════════════════════════════════════════════════════╣ +║ BY TYPE ║ +║ pages: +1 ║ +║ components: +2 ~1 ║ +║ api_endpoints: ~1 -1 ║ +╠══════════════════════════════════════════════════════════════════════╣ +║ ➕ ADDED ║ +║ + 📄 Profile (app/profile/page.tsx) ║ +║ + 🧩 Button (app/components/Button.tsx) ║ +║ + 🧩 Modal (app/components/Modal.tsx) ║ +╠══════════════════════════════════════════════════════════════════════╣ +║ 📝 MODIFIED ║ +║ ~ 🧩 Header (app/components/Header.tsx) ║ +║ dependencies: [] → ['Button'] ║ +║ ~ 🔌 users (app/api/users/route.ts) ║ +║ status: PENDING → IMPLEMENTED ║ +╠══════════════════════════════════════════════════════════════════════╣ +║ ➖ REMOVED ║ +║ - 🔌 legacy (app/api/legacy/route.ts) ║ +╚══════════════════════════════════════════════════════════════════════╝ +``` + +--- + +## USAGE EXAMPLES + +```bash +# Compare latest version with current manifest +/workflow:diff + +# Compare two specific versions +/workflow:diff v001 v002 + +# Compare specific version with current +/workflow:diff v003 + +# Show all version changelogs +/workflow:diff --changelog + +# Output as JSON +/workflow:diff v001 --json +``` + +--- + +## WHAT IT SHOWS + +### Entity Changes +- **Added**: New pages, components, API endpoints, etc. +- **Modified**: Status changes, dependency updates, path changes +- **Removed**: Deleted entities from manifest + +### Entity Type Icons +- 📄 page +- 🧩 component +- 🔌 api_endpoint +- 📚 lib +- 🪝 hook +- 📝 type +- ⚙️ config + +### Change Details +- Entity name and file path +- Specific field changes with before/after values +- Summary statistics by type + +--- + +## CHANGELOG MODE + +Show version history with changes: + +```bash +/workflow:diff --changelog +``` + +Output: +``` +╔══════════════════════════════════════════════════════════════════════╗ +║ CHANGELOG: v001 ║ +╠══════════════════════════════════════════════════════════════════════╣ +║ Feature: User authentication ║ +║ Status: completed ║ +║ Started: 2025-01-15 10:30:00 ║ +║ Completed: 2025-01-15 14:45:00 ║ +╠══════════════════════════════════════════════════════════════════════╣ +║ CHANGES ║ +║ + Added page: Login ║ +║ + Added page: Register ║ +║ + Added component: AuthForm ║ +║ + Added api_endpoint: auth ║ +╚══════════════════════════════════════════════════════════════════════╝ +``` + +--- + +## INTEGRATION + +### Uses Version Snapshots + +The diff tool uses snapshots created by version_manager.py: +- `snapshot_before/manifest.json` - Manifest at version start +- `snapshot_after/manifest.json` - Manifest at version completion + +These are automatically created when: +- `/workflow:spawn` initializes a new version +- `/workflow:complete` marks a version as done + +### Related Commands + +- `/workflow:history` - List all workflow versions +- `/workflow:status` - Show current workflow state +- `/workflow:changelog ` - Alias for `--changelog` diff --git a/.claude/commands/workflow/frontend.md b/.claude/commands/workflow/frontend.md new file mode 100644 index 0000000..94582d8 --- /dev/null +++ b/.claude/commands/workflow/frontend.md @@ -0,0 +1,85 @@ +--- +description: Implement frontend tasks (Frontend agent) +allowed-tools: Read, Write, Edit, Bash +--- + +# Frontend Agent - Implementation Mode + +🎨 **FRONTEND AGENT ACTIVATED** + +Implement task: "$ARGUMENTS" + +## CRITICAL RULES + +You are now the **FRONTEND AGENT**. + +✅ **ALLOWED**: +- Read any file +- Write new files (components, pages) +- Edit existing UI files +- Run Bash (build, lint, type-check) + +✅ **ALLOWED FILES**: +- `app/components/**/*` +- `app/**/page.tsx` +- `app/**/layout.tsx` +- `app/globals.css` + +## Workflow + +### Step 1: Load Task +First, get the version-specific tasks directory: +```bash +TASKS_DIR=$(python3 skills/guardrail-orchestrator/scripts/version_manager.py tasks-dir) +``` + +Read the task file: `$TASKS_DIR/$ARGUMENTS.yml` +- If "$ARGUMENTS" is `--next`: find first task with `agent: frontend` and `status: pending` + +### Step 2: Update Workflow State +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py task in_progress +``` + +### Step 3: Verify Prerequisites +- Check entity is `APPROVED` in `project_manifest.json` +- Check all `dependencies` tasks are `completed` +- If blocked: + ```bash + python3 skills/guardrail-orchestrator/scripts/workflow_manager.py task blocked + ``` + Stop and report blocker. + +### Step 4: Implement +For each file in `file_paths`: +1. Read manifest entity specification +2. Generate code matching spec exactly: + - Props must match manifest + - Types must match manifest + - File path must match manifest +3. Follow existing project patterns + +### Step 5: Validate +Run validations: +```bash +npm run lint +npm run build +``` + +### Step 6: Update Task Status +Update the task file: +```yaml +status: review +completed_at: +``` + +Update workflow state: +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py task review +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py progress --tasks-impl +``` + +### Step 7: Report +- List implemented files +- Show validation results +- Suggest: `/workflow:review $ARGUMENTS` diff --git a/.claude/commands/workflow/history.md b/.claude/commands/workflow/history.md new file mode 100644 index 0000000..d434888 --- /dev/null +++ b/.claude/commands/workflow/history.md @@ -0,0 +1,94 @@ +--- +description: Show workflow version history +allowed-tools: Read, Bash +--- + +# Workflow History + +Display version history of all workflow sessions. + +## Usage +``` +/workflow:history # List all versions +/workflow:history v001 # Show details for specific version +/workflow:history --changelog # Show changelog for current version +``` + +## Steps + +### 1. List All Versions (default) +```bash +python3 skills/guardrail-orchestrator/scripts/version_manager.py history +``` + +### 2. Show Version Details +If "$ARGUMENTS" is a version (e.g., `v001`): +```bash +python3 skills/guardrail-orchestrator/scripts/version_manager.py changelog $ARGUMENTS +``` + +### 3. Display Format + +**Version List**: +``` +╔══════════════════════════════════════════════════════════════════════╗ +║ WORKFLOW VERSION HISTORY ║ +╠══════════════════════════════════════════════════════════════════════╣ +║ ✅ v003: Dashboard with analytics ║ +║ Started: 2025-01-16T16:00:00 | Tasks: 12 | Ops: 45 ║ +║ ────────────────────────────────────────────────────────────────── ║ +║ ✅ v002: Task filters and search ║ +║ Started: 2025-01-16T14:00:00 | Tasks: 8 | Ops: 28 ║ +║ ────────────────────────────────────────────────────────────────── ║ +║ ✅ v001: User authentication ║ +║ Started: 2025-01-16T10:00:00 | Tasks: 5 | Ops: 18 ║ +╚══════════════════════════════════════════════════════════════════════╝ +``` + +**Version Changelog**: +``` +╔══════════════════════════════════════════════════════════════════════╗ +║ CHANGELOG: v001 ║ +╠══════════════════════════════════════════════════════════════════════╣ +║ Feature: User authentication ║ +║ Status: completed ║ +╠══════════════════════════════════════════════════════════════════════╣ +║ CREATED ║ +║ + [page] page_login ║ +║ app/login/page.tsx ║ +║ + [component] component_LoginForm ║ +║ app/components/LoginForm.tsx ║ +║ + [api] api_auth ║ +║ app/api/auth/route.ts ║ +║ UPDATED ║ +║ ~ [component] component_Header ║ +║ DELETED ║ +║ (none) ║ +╠══════════════════════════════════════════════════════════════════════╣ +║ SUMMARY ║ +║ Entities: +3 ~1 -0 ║ +║ Files: +4 ~2 -0 ║ +╚══════════════════════════════════════════════════════════════════════╝ +``` + +### 4. Show Task Sessions +If `$ARGUMENTS` includes `--tasks`: +List all task sessions for the version with their operations: + +``` +Task Sessions for v001: +───────────────────────────────────────────────── +🎨 task_create_LoginPage (frontend) + Status: completed | Duration: 5m 32s + Operations: + + CREATE file: app/login/page.tsx + ~ UPDATE manifest: project_manifest.json + Review: ✅ approved + +⚙️ task_create_AuthAPI (backend) + Status: completed | Duration: 8m 15s + Operations: + + CREATE file: app/api/auth/route.ts + + CREATE file: app/lib/auth.ts + Review: ✅ approved +``` diff --git a/.claude/commands/workflow/reject.md b/.claude/commands/workflow/reject.md new file mode 100644 index 0000000..9eec98c --- /dev/null +++ b/.claude/commands/workflow/reject.md @@ -0,0 +1,113 @@ +--- +description: Reject a workflow gate and request changes +allowed-tools: Read, Write, Bash +--- + +# Reject Workflow Gate + +Reject gate with reason: "$ARGUMENTS" + +## Usage +``` +/workflow:reject design "Need more API endpoints for authentication" +/workflow:reject implementation "Login form missing validation" +``` + +## Steps + +### 1. Parse Arguments +Extract: +- `gate`: First word (design | implementation) +- `reason`: Remaining text in quotes + +If invalid format: +``` +❌ Usage: /workflow:reject "reason" + + Examples: + /workflow:reject design "Need user profile page" + /workflow:reject implementation "Missing error handling" +``` + +### 2. Check Workflow State +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py exists +``` + +If no active workflow: +``` +❌ No active workflow found. +``` + +### 3. Verify Current Phase + +**For design rejection**: +- Current phase must be `AWAITING_DESIGN_APPROVAL` + +**For implementation rejection**: +- Current phase must be `AWAITING_IMPL_APPROVAL` + +### 4. Execute Rejection + +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py reject "" +``` + +### 5. Transition to Revision Phase + +**If design rejected**: +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition DESIGN_REJECTED +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition DESIGNING +``` + +**If implementation rejected**: +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition IMPL_REJECTED +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition IMPLEMENTING +``` + +### 6. Report + +**Design Rejected**: +``` +╔══════════════════════════════════════════════════════════════╗ +║ ❌ DESIGN REJECTED ║ +╠══════════════════════════════════════════════════════════════╣ +║ Reason: ║ +║ ║ +║ The workflow has returned to the DESIGNING phase. ║ +║ Revision count: X ║ +║ ║ +║ Next steps: ║ +║ /workflow:design --revise Revise the design ║ +║ /workflow:resume Auto-revise and continue ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +**Implementation Rejected**: +``` +╔══════════════════════════════════════════════════════════════╗ +║ ❌ IMPLEMENTATION REJECTED ║ +╠══════════════════════════════════════════════════════════════╣ +║ Reason: ║ +║ ║ +║ The workflow has returned to the IMPLEMENTING phase. ║ +║ Revision count: X ║ +║ ║ +║ Tasks requiring fixes will be marked as 'pending'. ║ +║ ║ +║ Next steps: ║ +║ /workflow:frontend --next Fix frontend tasks ║ +║ /workflow:backend --next Fix backend tasks ║ +║ /workflow:resume Auto-fix and continue ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +### 7. Update Related Tasks (Implementation Rejection) + +If implementation was rejected, identify tasks related to the rejection reason and mark them as pending: + +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py task pending +``` diff --git a/.claude/commands/workflow/resume.md b/.claude/commands/workflow/resume.md new file mode 100644 index 0000000..3c51afb --- /dev/null +++ b/.claude/commands/workflow/resume.md @@ -0,0 +1,159 @@ +--- +description: Resume an interrupted workflow from saved state +allowed-tools: Read, Write, Edit, Bash, AskUserQuestion, TodoWrite +--- + +# Workflow Orchestrator - Resume + +Resume a previously interrupted or paused workflow. + +## EXECUTION PROTOCOL + +### Step 1: Load Workflow State + +Read `.workflow/current.yml`: +- If not found: Report "No workflow to resume" and exit +- If found: Load state and continue + +### Step 2: Display Resume Summary + +``` +╔══════════════════════════════════════════════════════════════╗ +║ 🔄 RESUMING WORKFLOW ║ +╠══════════════════════════════════════════════════════════════╣ +║ Workflow ID: ║ +║ Feature: ║ +║ Started: ║ +║ Last Updated: ║ +╠══════════════════════════════════════════════════════════════╣ +║ CURRENT STATE ║ +║ Phase: ║ +║ Resume Point: ║ +╠══════════════════════════════════════════════════════════════╣ +║ PROGRESS ║ +║ Entities Designed: ║ +║ Tasks Created: ║ +║ Tasks Implemented: ║ +║ Tasks Reviewed: ║ +║ Tasks Completed: ║ +╠══════════════════════════════════════════════════════════════╣ +║ LAST ERROR (if any): ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +### Step 3: Confirm Resume + +**Ask user**: +- Option 1: "Continue - Resume from current point" +- Option 2: "Restart Phase - Redo current phase from beginning" +- Option 3: "Abort - Cancel workflow entirely" + +### Step 4: Resume Based on Phase + +**INITIALIZING**: +→ Continue to DESIGNING phase + +**DESIGNING**: +→ Continue architect work +→ Resume creating entities/tasks + +**AWAITING_DESIGN_APPROVAL**: +→ Present design summary again +→ Ask for approval + +**DESIGN_APPROVED**: +→ Continue to IMPLEMENTING phase + +**DESIGN_REJECTED**: +→ Show rejection reason +→ Return to DESIGNING with feedback + +**IMPLEMENTING**: +→ Find incomplete tasks +→ Continue implementation from next pending task + +**REVIEWING**: +→ Find tasks awaiting review +→ Continue review process + +**SECURITY_REVIEW**: +→ Continue security scanning +→ Run: `python3 skills/guardrail-orchestrator/scripts/security_scan.py --project-dir . --severity HIGH` +→ Run: `python3 skills/guardrail-orchestrator/scripts/validate_api_contract.py --project-dir .` +→ If passed: Transition to AWAITING_IMPL_APPROVAL +→ If critical issues: Return to IMPLEMENTING with security feedback + +**AWAITING_IMPL_APPROVAL**: +→ Present implementation summary again +→ Ask for approval + +**IMPL_APPROVED**: +→ Continue to COMPLETING phase + +**IMPL_REJECTED**: +→ Show rejection reason +→ Return to IMPLEMENTING with feedback + +**COMPLETING**: +→ Continue marking tasks complete + +**PAUSED**: +→ Resume from `resume_point.phase` + +**FAILED**: +→ Show error details +→ Ask user how to proceed: + - Retry failed operation + - Skip and continue + - Abort workflow + +### Step 5: Continue Workflow + +Execute remaining phases following `/workflow:spawn` protocol. + +## TASK-LEVEL RESUME + +If resuming during IMPLEMENTING phase: + +1. **Identify incomplete tasks**: + ```yaml + # Resume from first task not in 'completed' or 'approved' + resume_task: tasks.pending[0] || tasks.in_progress[0] || tasks.review[0] + ``` + +2. **Skip completed work**: + - Don't recreate files that exist and are valid + - Don't re-run validations that passed + +3. **Continue from failure point**: + - If task failed mid-implementation, restart that task + - If validation failed, show error and retry + +## STATE RECOVERY + +If `.workflow/current.yml` is corrupted: + +1. **Check for backup**: `.workflow/current.yml.bak` +2. **Attempt recovery from manifest**: + - Read `project_manifest.json` for entity status + - Scan version-specific tasks directory for task status + - Reconstruct workflow state +3. **If unrecoverable**: + - Report error + - Suggest starting fresh with `/workflow:spawn` + +## ABORT WORKFLOW + +If user chooses to abort: + +1. **Confirm abort**: + "This will cancel the workflow. Files already created will remain. Continue?" + +2. **If confirmed**: + - Archive state to `.workflow/history/_aborted.yml` + - Clear `.workflow/current.yml` + - Report: "Workflow aborted. Created files remain in place." + +3. **Cleanup options**: + - Offer to rollback created files (if git available) + - Offer to keep partial implementation diff --git a/.claude/commands/workflow/review.md b/.claude/commands/workflow/review.md new file mode 100644 index 0000000..c021dc8 --- /dev/null +++ b/.claude/commands/workflow/review.md @@ -0,0 +1,526 @@ +--- +description: Review implementation (Reviewer agent) +allowed-tools: Read, Bash +--- + +# Reviewer Agent - Review Mode + +**Input**: "$ARGUMENTS" + +--- + +## CRITICAL ENFORCEMENT RULES + +**YOU ARE IN READ-ONLY MODE. VIOLATIONS WILL BE BLOCKED.** + +### MUST DO (Non-Negotiable) +1. **MUST** run all validation checks (build, typecheck, lint, test, API contract) +2. **MUST** verify every file in task's `file_paths` exists +3. **MUST** read and analyze each implemented file +4. **MUST** check against acceptance_criteria in task file +5. **MUST** output structured review report (format below) +6. **MUST** run workflow_manager.py to update task status + +### CANNOT DO (Strictly Forbidden) +1. **CANNOT** create files (Write tool blocked) +2. **CANNOT** modify files (Edit tool blocked) +3. **CANNOT** fix issues yourself - only report them +4. **CANNOT** approve tasks with missing files +5. **CANNOT** approve if ANY validation check fails +6. **CANNOT** skip any validation check + +### ALLOWED ACTIONS +- Read any file +- Run Bash commands (build, lint, test, typecheck, ls, cat, grep) +- Output review reports +- Update task status via workflow_manager.py + +--- + +## VALIDATION CHECKS MATRIX + +| Check | Command | Blocks Approval | When | +|-------|---------|-----------------|------| +| Build | `npm run build` | YES | Always | +| TypeScript | `npx tsc --noEmit` | YES | Always | +| Async/Await | `python3 verify_async.py` | YES | Always | +| Lint | `npm run lint` | YES (if --strict) | --strict mode | +| Unit Tests | `npm test -- --passWithNoTests` | YES (if --strict) | --strict mode | +| API Contract | `python3 validate_api_contract.py` | YES | Always | +| Security Scan | `python3 security_scan.py` | YES (critical) | Always | +| Files Exist | `ls -la` each file | YES | Always | + +**Note:** For comprehensive security audit, use `/workflow:security --full` + +--- + +## ARGUMENT PARSING + +``` +IF "$ARGUMENTS" contains "--auto": + MODE = AUTO (batch review all tasks) + STRICT = "$ARGUMENTS" contains "--strict" + FULL = "$ARGUMENTS" contains "--full" +ELSE IF "$ARGUMENTS" = "--next": + MODE = SINGLE (next pending task) +ELSE: + MODE = SINGLE (specific task: "$ARGUMENTS") +``` + +--- + +## MODE: AUTO REVIEW (--auto) + +### Step A1: Get Active Version [MANDATORY] +```bash +VERSION_ID=$(python3 skills/guardrail-orchestrator/scripts/version_manager.py current) +TASKS_DIR=".workflow/versions/$VERSION_ID/tasks" +``` + +### Step A2: Run Global Validations [MANDATORY] + +#### 2.1 Build Check +```bash +npm run build 2>&1 +BUILD_EXIT=$? +echo "BUILD_EXIT=$BUILD_EXIT" +``` + +#### 2.2 TypeScript Strict Check +```bash +npx tsc --noEmit 2>&1 +TS_EXIT=$? +echo "TS_EXIT=$TS_EXIT" +``` + +#### 2.3 Async/Await Check [MANDATORY] +```bash +python3 skills/guardrail-orchestrator/scripts/verify_async.py --path . 2>&1 +ASYNC_EXIT=$? +echo "ASYNC_EXIT=$ASYNC_EXIT" +``` + +This catches runtime errors at build time: +- `fetch()` without `await` +- `.json()` without `await` +- `Promise.all()` without `await` +- Floating promises (unawaited async calls) + +**Exit codes:** +- 0 = PASS (no high-severity issues) +- 1 = HIGH severity issues found (blocks approval) + +#### 2.4 Lint Check (if --strict or --full) +```bash +npm run lint 2>&1 +LINT_EXIT=$? +echo "LINT_EXIT=$LINT_EXIT" +``` + +#### 2.5 Unit Tests (if --strict or --full) +```bash +npm test -- --passWithNoTests 2>&1 +TEST_EXIT=$? +echo "TEST_EXIT=$TEST_EXIT" +``` + +#### 2.6 API Contract Validation [MANDATORY] +```bash +python3 skills/guardrail-orchestrator/scripts/validate_api_contract.py --project-dir . 2>&1 +API_EXIT=$? +echo "API_EXIT=$API_EXIT" +``` + +This validates: +- Frontend API calls have matching backend endpoints +- HTTP methods match (GET, POST, PUT, DELETE) +- Request bodies are sent where expected +- Response handling matches backend output + +#### 2.7 Security Scan [MANDATORY] +```bash +# Run comprehensive security scanner +python3 skills/guardrail-orchestrator/scripts/security_scan.py \ + --project-dir . \ + --severity HIGH +SECURITY_EXIT=$? +echo "SECURITY_EXIT=$SECURITY_EXIT" +``` + +**Security scan checks:** +- Hardcoded secrets (API keys, passwords, tokens) +- SQL injection vulnerabilities +- XSS risks (dangerouslySetInnerHTML, innerHTML) +- Command injection patterns +- Path traversal vulnerabilities +- NoSQL injection risks +- SSRF vulnerabilities +- Prototype pollution +- Insecure authentication patterns +- CORS misconfigurations +- Sensitive data exposure +- Debug code in production + +**Exit codes:** +- 0 = PASS (no critical/high issues) +- 1 = HIGH issues found (warning) +- 2 = CRITICAL issues found (blocks approval) + +**For full security audit, run:** `/workflow:security --full` + +### Step A3: Gather All Tasks [MANDATORY] +```bash +ls $TASKS_DIR/*.yml 2>/dev/null +``` +**MUST process ALL task files found** + +### Step A4: Review Each Task [MANDATORY] + +For EACH task file: + +```bash +# Extract file_paths from task +TASK_FILES=$(grep -A 20 "file_paths:" "$TASK_FILE" | grep -E "^\s+-" | sed 's/.*- //') +``` + +**Check each file exists**: +```bash +for file in $TASK_FILES; do + if [ -f "$file" ]; then + echo "EXISTS: $file" + else + echo "MISSING: $file" + MISSING_COUNT=$((MISSING_COUNT + 1)) + fi +done +``` + +**Determine task verdict**: +``` +IF all files exist + AND BUILD_EXIT = 0 + AND TS_EXIT = 0 + AND ASYNC_EXIT = 0 + AND API_EXIT = 0 + AND SECURITY_EXIT != 2 (no critical security issues) + AND (not --strict OR (LINT_EXIT = 0 AND TEST_EXIT = 0)): + -> TASK_VERDICT = APPROVED +ELSE: + -> TASK_VERDICT = REJECTED + -> Record reason (missing files / build failure / type error / async issue / API mismatch / security issue) +``` + +**Security exit codes:** +- 0 = PASS +- 1 = HIGH issues (warning, doesn't block unless --strict) +- 2 = CRITICAL issues (always blocks) + +### Step A5: Batch Update [MANDATORY] + +For APPROVED tasks: +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py task approved +``` + +For REJECTED tasks: +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py task pending +``` + +### Step A6: Auto Review Report [MANDATORY] + +**MUST output this exact format**: +``` ++======================================================================+ +| REVIEW COMPLETE | ++======================================================================+ +| Version: $VERSION_ID | +| Mode: AUTO [STRICT if --strict] [FULL if --full] | ++======================================================================+ +| VALIDATION RESULTS | ++----------------------------------------------------------------------+ +| Build: PASS (exit 0) / FAIL (exit $BUILD_EXIT) | +| TypeScript: PASS (exit 0) / FAIL (exit $TS_EXIT) | +| Async/Await: PASS / FAIL (X high, Y medium issues) | +| Lint: PASS / FAIL / SKIPPED | +| Tests: PASS / FAIL / SKIPPED | +| API Contract: PASS / FAIL (X errors, Y warnings) | +| Security: PASS / WARNING / CRITICAL | +| (C:X H:X M:X L:X issues) | ++======================================================================+ +| API CONTRACT DETAILS | ++----------------------------------------------------------------------+ +| Frontend calls: X matched, Y unmatched | +| Backend endpoints: X defined, Y unused | +| Method mismatches: X | +| Body mismatches: X | ++======================================================================+ +| TASK RESULTS | ++----------------------------------------------------------------------+ +| Total: X tasks | +| Approved: X tasks | +| Rejected: X tasks | +| Skipped: X tasks (already completed) | ++======================================================================+ +| APPROVED TASKS | +| - task_create_Button | +| - task_create_Form | ++----------------------------------------------------------------------+ +| REJECTED TASKS | +| - task_create_Modal | +| Reason: Missing file app/components/Modal.tsx | +| - task_update_API | +| Reason: API contract error - endpoint not found | ++======================================================================+ +| SECURITY WARNINGS | +| - src/lib/api.ts:15 - Possible hardcoded API key | +| - app/page.tsx:42 - dangerouslySetInnerHTML usage | ++======================================================================+ +``` + +### Step A7: Next Steps [MANDATORY] + +**IF all approved**: +``` +All tasks approved. +Next: Run `/workflow:approve implementation` to continue. +``` + +**IF any rejected**: +``` +Some tasks need fixes. + +API Contract Issues: + For frontend issues: Fix the API call URL or method + For backend issues: Create or fix the API endpoint + +For each rejected task, run: + /workflow:frontend (for frontend tasks) + /workflow:backend (for backend tasks) + +Then re-run: /workflow:review --auto +``` + +--- + +## MODE: SINGLE TASK REVIEW (--next or task_id) + +### Step S1: Get Task [MANDATORY] +```bash +VERSION_ID=$(python3 skills/guardrail-orchestrator/scripts/version_manager.py current) +TASKS_DIR=".workflow/versions/$VERSION_ID/tasks" +``` + +**IF --next**: +```bash +# Find first task with status: pending or status: implemented +TASK_FILE=$(grep -l "status: pending\|status: implemented" $TASKS_DIR/*.yml 2>/dev/null | head -1) +``` + +**IF specific task_id**: +```bash +TASK_FILE="$TASKS_DIR/$ARGUMENTS.yml" +``` + +**BLOCK IF**: Task file does not exist -> Error: "Task not found: $ARGUMENTS" + +### Step S2: Read Task Spec [MANDATORY] +```bash +cat "$TASK_FILE" +``` + +Extract: +- `id`: Task identifier +- `file_paths`: List of files to verify +- `acceptance_criteria`: List of requirements to check + +### Step S3: Run All Validations [MANDATORY] + +```bash +# Build +npm run build 2>&1 +BUILD_EXIT=$? + +# TypeScript +npx tsc --noEmit 2>&1 +TS_EXIT=$? + +# API Contract +python3 skills/guardrail-orchestrator/scripts/validate_api_contract.py --project-dir . 2>&1 +API_EXIT=$? +``` + +**MUST capture and report all exit codes** + +### Step S4: Verify Files Exist [MANDATORY] + +For each path in `file_paths`: +```bash +ls -la "$path" 2>/dev/null && echo "EXISTS" || echo "MISSING" +``` + +**Record**: +- FILES_EXIST = true/false +- MISSING_FILES = list of missing paths + +### Step S5: Read and Analyze Files [MANDATORY] + +For each EXISTING file: +1. Read file content +2. Check against acceptance_criteria: + - [ ] File exports correct components/functions + - [ ] Props/types match manifest spec + - [ ] Code follows project patterns + - [ ] No obvious bugs or issues +3. Check API contract compliance: + - [ ] Frontend calls use correct endpoints + - [ ] HTTP methods are appropriate + - [ ] Request bodies are properly structured + - [ ] Response handling is correct + +### Step S6: Determine Verdict [MANDATORY] + +``` +IF BUILD_EXIT = 0 + AND TS_EXIT = 0 + AND API_EXIT = 0 + AND FILES_EXIST = true + AND acceptance_criteria met: + -> VERDICT = APPROVED +ELSE: + -> VERDICT = REQUEST_CHANGES + -> Record all issues found +``` + +### Step S7: Update Task Status [MANDATORY] + +**IF APPROVED**: +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py task $TASK_ID approved +``` + +**IF REQUEST_CHANGES**: +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py task $TASK_ID pending +``` + +### Step S8: Output Review Report [MANDATORY] + +**MUST output this exact format**: +``` ++======================================================================+ +| TASK REVIEW | ++======================================================================+ +| Task: $TASK_ID | +| Version: $VERSION_ID | ++======================================================================+ +| VALIDATION CHECKS | ++----------------------------------------------------------------------+ +| Build: PASS / FAIL | +| TypeScript: PASS / FAIL | +| API Contract: PASS / FAIL | +| Files exist: PASS / FAIL (X/Y files) | +| Acceptance criteria: PASS / PARTIAL / FAIL | +| Code quality: PASS / ISSUES | ++======================================================================+ +| API CONTRACT STATUS | ++----------------------------------------------------------------------+ +| Endpoint calls: X found, Y matched | +| Method correctness: PASS / X mismatches | +| Request bodies: PASS / X issues | +| Response handling: PASS / ISSUES | ++======================================================================+ +| VERDICT: APPROVED / REQUEST_CHANGES | ++======================================================================+ +| [If REQUEST_CHANGES, list all issues:] | +| 1. Missing file: app/components/Button.tsx | +| 2. TypeScript error: Type 'string' not assignable to 'number' | +| 3. API contract: POST /api/users called but endpoint expects GET | +| 4. API contract: Frontend sends body but backend ignores it | +| 5. Acceptance criterion not met: "Must support dark mode" | ++======================================================================+ +``` + +### Step S9: Next Steps [MANDATORY] + +**IF APPROVED**: +``` +Task approved. +Next: Run `/workflow:complete $TASK_ID` to mark as done. + Or run `/workflow:review --next` to review next task. +``` + +**IF REQUEST_CHANGES**: +``` +Changes requested. + +Issues to fix: + [List specific issues with file locations] + +For API contract issues: + - If frontend issue: Fix the fetch/axios call in [file:line] + - If backend issue: Update the API route handler in [file] + +Fix issues and re-run: + /workflow:frontend $TASK_ID (for frontend tasks) + /workflow:backend $TASK_ID (for backend tasks) +Then: /workflow:review $TASK_ID +``` + +--- + +## USAGE EXAMPLES + +```bash +# Review specific task +/workflow:review task_create_Button + +# Review next pending task +/workflow:review --next + +# Auto-review all tasks (standard - build + types + API) +/workflow:review --auto + +# Auto-review all tasks (strict - includes lint + tests) +/workflow:review --auto --strict + +# Full review with all checks +/workflow:review --auto --full +``` + +--- + +## API CONTRACT VALIDATION DETAILS + +The API contract validator checks: + +### Frontend Analysis +- **fetch()** calls with `/api/` paths +- **axios** requests (get, post, put, delete) +- **useSWR** data fetching hooks +- **Custom API clients** (api.get, api.post, etc.) + +### Backend Analysis +- **Next.js App Router**: `app/api/*/route.ts` exports (GET, POST, PUT, DELETE) +- **Next.js Pages Router**: `pages/api/*.ts` with req.method checks +- **Express-style**: router.get/post/etc patterns + +### Validation Rules +1. **Endpoint Existence**: Every frontend call must have a matching backend route +2. **Method Match**: GET calls must hit GET endpoints, POST to POST, etc. +3. **Body Alignment**: POST/PUT calls should send bodies, GET should not +4. **Unused Endpoints**: Backend routes not called by frontend (warnings) + +--- + +## ENFORCEMENT CHECKLIST + +Before completing this command, verify: +- [ ] Build command executed and exit code captured +- [ ] TypeScript check executed and exit code captured +- [ ] API contract validation executed and exit code captured +- [ ] All file_paths verified with ls command +- [ ] Security scan completed +- [ ] Structured review report output (exact format above) +- [ ] Task status updated via workflow_manager.py +- [ ] Next steps clearly stated diff --git a/.claude/commands/workflow/security.md b/.claude/commands/workflow/security.md new file mode 100644 index 0000000..d76fd24 --- /dev/null +++ b/.claude/commands/workflow/security.md @@ -0,0 +1,342 @@ +--- +description: Run comprehensive security audit (Security Reviewer agent) +allowed-tools: Read, Bash, Grep, Task +--- + +# Security Reviewer Agent - Security Audit Mode + +**Input**: "$ARGUMENTS" + +--- + +## CRITICAL CONSTRAINTS + +**YOU ARE IN READ-ONLY MODE FOR ANALYSIS.** + +### MUST DO (Non-Negotiable) +1. **MUST** run automated security scanner +2. **MUST** analyze all CRITICAL and HIGH findings +3. **MUST** check dependency vulnerabilities +4. **MUST** review security configurations +5. **MUST** output structured security report +6. **MUST** provide remediation guidance + +### CANNOT DO (Strictly Forbidden) +1. **CANNOT** modify source files +2. **CANNOT** fix issues directly +3. **CANNOT** approve with CRITICAL issues +4. **CANNOT** skip any security category + +--- + +## ARGUMENT PARSING + +``` +IF "$ARGUMENTS" contains "--quick": + MODE = QUICK (scanner only) +ELSE IF "$ARGUMENTS" contains "--full": + MODE = FULL (scanner + deep analysis + deps + config) +ELSE: + MODE = STANDARD (scanner + deps) + +SEVERITY = extract from --severity [critical|high|medium|low] +OUTPUT = extract from --json (JSON output) or text +``` + +--- + +## EXECUTION FLOW + +### Step 1: Run Automated Security Scanner [MANDATORY] + +```bash +python3 skills/guardrail-orchestrator/scripts/security_scan.py \ + --project-dir . \ + --severity ${SEVERITY:-LOW} \ + ${OUTPUT:+--json} +``` + +**Capture output and exit code:** +```bash +SCAN_EXIT=$? +echo "SCAN_EXIT=$SCAN_EXIT" +``` + +**Exit codes:** +- 0 = PASS (no critical/high issues) +- 1 = HIGH issues found +- 2 = CRITICAL issues found + +### Step 2: Dependency Audit [MANDATORY unless --quick] + +```bash +echo "=== Dependency Audit ===" +npm audit --json 2>/dev/null || echo '{"vulnerabilities":{}}' +``` + +**Parse npm audit results:** +- Count critical, high, moderate, low vulnerabilities +- List affected packages and versions +- Note if fixes available (`npm audit fix`) + +### Step 3: Deep Analysis [FULL mode only] + +For each CRITICAL/HIGH finding from scanner: + +#### 3.1 Data Flow Tracing +Use Task agent with security-engineer subagent: +``` +Analyze data flow for vulnerability at [file:line]. +Trace user input from source to sink. +Identify all potential attack vectors. +Assess exploitability and impact. +``` + +#### 3.2 Attack Vector Analysis +For each vulnerability type: +- SQL Injection → Check if input reaches query without sanitization +- XSS → Check if input reaches DOM without encoding +- Command Injection → Check if input reaches shell without escaping +- Path Traversal → Check if input reaches file system without validation + +### Step 4: Configuration Review [FULL mode only] + +#### 4.1 CORS Configuration +```bash +grep -rn "cors\|Access-Control" app/ src/ pages/ --include="*.ts" --include="*.tsx" --include="*.js" +``` + +Check for: +- Wildcard origins (`*`) +- Credentials with permissive origins +- Missing CORS on sensitive endpoints + +#### 4.2 Security Headers +```bash +grep -rn "helmet\|Content-Security-Policy\|X-Frame-Options\|X-XSS-Protection" . --include="*.ts" --include="*.js" +``` + +Check for: +- Helmet middleware usage +- CSP configuration +- X-Frame-Options +- X-Content-Type-Options + +#### 4.3 Authentication Configuration +```bash +grep -rn "jwt\|session\|auth\|cookie" app/ src/ pages/ --include="*.ts" --include="*.tsx" +``` + +Check for: +- JWT algorithm (avoid 'none', prefer RS256) +- Session configuration +- Cookie flags (httpOnly, secure, sameSite) + +#### 4.4 Environment Variables +```bash +# Check .env files are gitignored +cat .gitignore 2>/dev/null | grep -E "\.env" + +# Check for env var usage +grep -rn "process\.env\." app/ src/ --include="*.ts" --include="*.tsx" | head -20 +``` + +### Step 5: Manual Review Checklist [FULL mode only] + +Read each file modified in current workflow and verify: + +**Input Validation** +- [ ] All user inputs validated +- [ ] Type checking enforced +- [ ] Length limits applied +- [ ] Format validation (email, URL, etc.) + +**Output Encoding** +- [ ] HTML encoding for DOM insertion +- [ ] URL encoding for URLs +- [ ] JSON encoding for API responses + +**Database Security** +- [ ] Parameterized queries used +- [ ] No string concatenation in queries +- [ ] Proper ORM usage + +**Authentication/Authorization** +- [ ] Auth checks on protected routes +- [ ] Role-based access control +- [ ] Session validation + +**Error Handling** +- [ ] Generic error messages to users +- [ ] No stack traces in production +- [ ] No sensitive data in logs + +### Step 6: Generate Security Report [MANDATORY] + +**MUST output this exact format:** + +``` ++======================================================================+ +| SECURITY AUDIT REPORT | ++======================================================================+ +| Mode: QUICK / STANDARD / FULL | +| Date: [current date] | +| Project: [project name from package.json] | ++======================================================================+ +| RISK ASSESSMENT | ++----------------------------------------------------------------------+ +| Overall Risk: CRITICAL / HIGH / MEDIUM / LOW / PASS | +| | +| Static Analysis: X issues (C:X H:X M:X L:X) | +| Dependencies: X vulnerabilities | +| Configuration: X concerns | ++======================================================================+ +| CRITICAL ISSUES (Immediate Action Required) | ++----------------------------------------------------------------------+ +| [1] [CATEGORY] Title | +| Location: file:line | +| CWE: CWE-XXX | +| OWASP: A0X:2021-Category | +| Evidence: [code snippet] | +| Impact: [description of potential attack] | +| Fix: [specific remediation steps] | +| | +| [2] ... | ++======================================================================+ +| HIGH ISSUES (Fix Before Production) | ++----------------------------------------------------------------------+ +| [3] ... | ++======================================================================+ +| MEDIUM ISSUES (Should Fix) | ++----------------------------------------------------------------------+ +| [4] ... | ++======================================================================+ +| DEPENDENCY VULNERABILITIES | ++----------------------------------------------------------------------+ +| Package Version Severity Fix Available | +| lodash 4.17.20 HIGH npm audit fix | +| axios 0.21.0 MEDIUM npm audit fix | ++======================================================================+ +| CONFIGURATION CONCERNS | ++----------------------------------------------------------------------+ +| - CORS: Wildcard origin detected in src/middleware.ts | +| - Session: Missing httpOnly flag on auth cookie | +| - Headers: No CSP header configured | ++======================================================================+ +| REMEDIATION PRIORITY | ++----------------------------------------------------------------------+ +| 1. [CRITICAL] Rotate exposed API key in src/lib/api.ts | +| 2. [CRITICAL] Fix SQL injection in app/api/users/route.ts | +| 3. [HIGH] Update lodash to 4.17.21 | +| 4. [HIGH] Add input validation to user registration | +| 5. [MEDIUM] Configure CSP headers | ++======================================================================+ +| VERDICT | ++----------------------------------------------------------------------+ +| FAIL - X critical issues must be fixed before deployment | +| or | +| PASS - No blocking security issues found | ++======================================================================+ +``` + +--- + +## VERDICT DETERMINATION + +### FAIL Conditions +- Any CRITICAL issue found +- 3+ HIGH issues found +- Critical npm vulnerabilities without fix +- Exposed secrets or credentials + +### PASS WITH WARNINGS +- Only MEDIUM/LOW issues +- All HIGH issues have accepted risk +- Dependencies have fixes available + +### PASS +- No CRITICAL/HIGH issues +- Dependencies up to date +- Configurations reviewed + +--- + +## POST-AUDIT ACTIONS + +### If FAIL: +``` +SECURITY AUDIT FAILED + +Blocking issues must be fixed: +1. [List critical issues] + +For each issue: + /workflow:frontend - if frontend issue + /workflow:backend - if backend issue + +Then re-run: /workflow:security +``` + +### If PASS: +``` +SECURITY AUDIT PASSED + +Proceed with: /workflow:review --auto +``` + +--- + +## USAGE EXAMPLES + +```bash +# Quick scan (automated scanner only) +/workflow:security --quick + +# Standard scan (scanner + dependencies) +/workflow:security + +# Full audit (all checks) +/workflow:security --full + +# Filter by severity +/workflow:security --severity high + +# JSON output for CI/CD +/workflow:security --json +``` + +--- + +## INTEGRATION WITH CI/CD + +### Pre-commit Hook +```bash +python3 skills/guardrail-orchestrator/scripts/security_scan.py \ + --project-dir . --severity HIGH --strict +``` + +### GitHub Actions +```yaml +- name: Security Scan + run: | + python3 skills/guardrail-orchestrator/scripts/security_scan.py \ + --project-dir . --json > security-report.json + + if [ $? -ne 0 ]; then + echo "Security issues found!" + cat security-report.json + exit 1 + fi +``` + +--- + +## ENFORCEMENT CHECKLIST + +Before completing this command, verify: +- [ ] Automated scanner executed +- [ ] All categories analyzed +- [ ] Dependencies audited (unless --quick) +- [ ] Structured report output +- [ ] Remediation guidance provided +- [ ] Clear verdict stated diff --git a/.claude/commands/workflow/spawn.md b/.claude/commands/workflow/spawn.md new file mode 100644 index 0000000..43d6053 --- /dev/null +++ b/.claude/commands/workflow/spawn.md @@ -0,0 +1,1542 @@ +--- +description: Automated workflow orchestrator with approval gates and sub-agent delegation +allowed-tools: Read, Write, Edit, Bash, Task, AskUserQuestion, TodoWrite +--- + +# Workflow Orchestrator - Spawn + +**Input**: "$ARGUMENTS" + +--- + +## ⛔ CRITICAL ENFORCEMENT RULES + +**READ THESE RULES BEFORE ANY ACTION. VIOLATIONS WILL CORRUPT THE WORKFLOW.** + +### 🔴 MUST DO (Non-Negotiable) +1. **MUST** run version_manager.py create BEFORE any design work +2. **MUST** verify phase state BEFORE each transition +3. **MUST** run validation script AFTER each phase completes +4. **MUST** capture and display script output (never assume success) +5. **MUST** create task files in `.workflow/versions/vXXX/tasks/` (version-specific) +6. **MUST** wait for Task agents to fully complete before proceeding +7. **MUST** run `npm run build` and verify exit code = 0 before approval + +### 🚫 CANNOT DO (Strictly Forbidden) +1. **CANNOT** skip phases or combine phases +2. **CANNOT** proceed if any verification fails +3. **CANNOT** assume task files exist - must verify with `ls` +4. **CANNOT** assume build passes - must run and check exit code +5. **CANNOT** transition without running the transition script +6. **CANNOT** mark workflow complete if any task is not 'approved' +7. **CANNOT** proceed to IMPLEMENTING if no task files exist + +### ⚠️ BLOCKING CONDITIONS +These conditions **HALT** the workflow immediately: + +| Condition | Blocked Phase | Resolution | +|-----------|---------------|------------| +| `project_manifest.json` missing | INITIALIZE | Create manifest first | +| No task files created | DESIGNING → IMPLEMENTING | Architect must create tasks | +| Build fails | IMPLEMENTING → REVIEWING | Fix build errors | +| Files missing | REVIEWING | Implement missing files | +| Version mismatch | Any | Run `/workflow:status` | + +--- + +## ARGUMENT PARSING + +``` +FULL_AUTO_MODE = "$ARGUMENTS" contains "--full-auto" +AUTO_MODE = "$ARGUMENTS" contains "--auto" AND NOT "--full-auto" +MANUAL_MODE = NOT AUTO_MODE AND NOT FULL_AUTO_MODE +FEATURE = "$ARGUMENTS" with "--auto" and "--full-auto" removed and trimmed +``` + +### Mode Comparison + +| Aspect | Manual | --auto | --full-auto | +|--------|--------|--------|-------------| +| Requirements | User provides all | AI asks questions with options | AI expands autonomously | +| Questions | None | Until AI has enough info | Only acceptance criteria | +| Design Approval | Manual | Auto-approve | Auto-approve | +| Impl Approval | Manual | Auto if validation passes | Auto if validation passes | +| Best For | Full control | Guided discovery | Quick prototyping | + +### --auto Behavior (Interactive Discovery) +- **PHASE 1.5**: AI asks clarifying questions with multiple-choice options +- Questions continue until AI determines requirements are complete +- Examples: "What auth method?", "Need password reset?", "Which OAuth providers?" +- Gate 1 (design approval): Auto-approve +- Gate 2 (impl approval): Auto-approve IF validation passes +- **STILL RUNS**: All validation checks, build verification + +### --full-auto Behavior (AI-Driven Expansion) +- **PHASE 1.5**: AI autonomously analyzes and expands the idea +- AI generates comprehensive requirements from brief input +- **ONLY ASKS**: Acceptance criteria ("How will you know this is done?") +- Gate 1 (design approval): Auto-approve +- Gate 2 (impl approval): Auto-approve IF validation passes +- **STILL RUNS**: All validation checks, build verification + +--- + +## PHASE EXECUTION PROTOCOL + +### ═══════════════════════════════════════════════════════════════ +### PHASE 1: INITIALIZE +### ═══════════════════════════════════════════════════════════════ + +**Entry Condition**: Command invoked +**Exit Condition**: Version created, session started, phase = DESIGNING + +#### Step 1.1: Parse Arguments [MANDATORY] +``` +Extract: AUTO_MODE, FEATURE +Validate: FEATURE is not empty +``` +**BLOCK IF**: FEATURE is empty → Ask user for feature description + +#### Step 1.2: Verify Prerequisites [MANDATORY] +```bash +# MUST run this check - do not skip +ls project_manifest.json +``` +**BLOCK IF**: File does not exist → Error: "Run /guardrail:init or /guardrail:analyze first" + +```bash +# Create workflow directory if missing (auto-recovery) +mkdir -p .workflow/versions +if [ ! -f .workflow/index.yml ]; then + cat > .workflow/index.yml << 'EOF' +versions: [] +latest_version: null +total_versions: 0 +EOF +fi +``` + +#### Step 1.3: Create Version [MANDATORY] +```bash +python3 skills/guardrail-orchestrator/scripts/version_manager.py create "$FEATURE" +``` +**MUST capture output** and extract VERSION_ID (e.g., "v004") +**BLOCK IF**: Script fails → Error with script output + +#### Step 1.4: Display Start Banner [MANDATORY] +``` +╔══════════════════════════════════════════════════════════════╗ +║ 🚀 WORKFLOW STARTED ║ +╠══════════════════════════════════════════════════════════════╣ +║ Version: $VERSION_ID ║ +║ Feature: $FEATURE ║ +║ Mode: $MODE (AUTO/INTERACTIVE) ║ +║ Tasks: .workflow/versions/$VERSION_ID/tasks/ ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +#### Step 1.5: Transition [MANDATORY] +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition DESIGNING +``` +**VERIFY**: Script exits with code 0 + +--- + +### ═══════════════════════════════════════════════════════════════ +### PHASE 1.5: REQUIREMENTS GATHERING (--auto and --full-auto only) +### ═══════════════════════════════════════════════════════════════ + +**Entry Condition**: Phase = DESIGNING, Mode = AUTO_MODE or FULL_AUTO_MODE +**Exit Condition**: Requirements documented, ready for design +**SKIP IF**: MANUAL_MODE (proceed directly to PHASE 2) + +--- + +#### IF AUTO_MODE: Interactive Requirements Discovery + +**Purpose**: Ask clarifying questions until AI has enough information to design the system. + +##### Step 1.5.1: Initialize Requirements Document +```bash +mkdir -p .workflow/versions/$VERSION_ID/requirements +``` + +Create requirements tracking: +```yaml +# .workflow/versions/$VERSION_ID/requirements/discovery.yml +feature: "$FEATURE" +status: gathering +questions_asked: 0 +requirements: [] +ready_for_design: false +``` + +##### Step 1.5.2: Question Loop [MANDATORY] + +**REPEAT until ready_for_design = true:** + +Use AskUserQuestion tool to gather requirements: + +``` +Use AskUserQuestion with intelligent questions based on feature type. + +Question categories to explore: +1. SCOPE: What exactly should this feature do? +2. USERS: Who will use this? What roles? +3. DATA: What information needs to be stored? +4. ACTIONS: What operations can users perform? +5. AUTH: What security/permissions are needed? +6. UI: What screens/components are needed? +7. INTEGRATIONS: Any external services? +8. EDGE CASES: What happens when X fails? +``` + +**Example Question Flow for "add user authentication":** + +``` +Round 1 - Authentication Type: + Question: "What authentication method do you need?" + Options: + - "Email/Password (Recommended)" - Traditional login with email and password + - "OAuth Social Login" - Login with Google, GitHub, etc. + - "Magic Link" - Passwordless email link login + - "Multi-factor" - 2FA with authenticator apps + [multiSelect: true] + +Round 2 - (If OAuth selected) Providers: + Question: "Which OAuth providers should be supported?" + Options: + - "Google (Recommended)" - Most common, easy setup + - "GitHub" - Popular for developer tools + - "Apple" - Required for iOS apps + - "Microsoft" - Common for enterprise + [multiSelect: true] + +Round 3 - User Data: + Question: "What user information should be stored?" + Options: + - "Basic (name, email)" - Minimal user profile + - "Extended (+ avatar, bio)" - Social features + - "Professional (+ company, role)" - B2B applications + - "Custom fields" - I'll specify additional fields + [multiSelect: false] + +Round 4 - Features: + Question: "Which additional features do you need?" + Options: + - "Password reset" - Email-based password recovery + - "Email verification" - Confirm email ownership + - "Remember me" - Persistent sessions + - "Account deletion" - GDPR compliance + [multiSelect: true] + +Round 5 - UI Components: + Question: "What UI components are needed?" + Options: + - "Login page" - Standalone login screen + - "Registration page" - New user signup + - "Profile page" - View/edit user info + - "Settings page" - Account settings + [multiSelect: true] +``` + +##### Step 1.5.3: Evaluate Completeness [MANDATORY] + +After each round, evaluate if requirements are sufficient: + +``` +READY_FOR_DESIGN = true IF ALL of these are answered: + - [ ] Core functionality is clear + - [ ] Data model requirements are known + - [ ] API operations are identified + - [ ] UI screens are listed + - [ ] Authentication/authorization is defined + - [ ] Key edge cases are addressed +``` + +**If NOT ready**: Generate next question based on gaps +**If ready**: Proceed to Step 1.5.4 + +##### Step 1.5.4: Generate Requirements Summary [MANDATORY] + +Save gathered requirements: +```yaml +# .workflow/versions/$VERSION_ID/requirements/summary.yml +feature: "$FEATURE" +gathered_at: +questions_asked: X +mode: auto + +requirements: + authentication: + methods: [email_password, oauth_google] + features: [password_reset, email_verification] + + data_model: + user_fields: [name, email, avatar, bio] + additional_entities: [] + + ui_components: + pages: [login, register, profile] + components: [login_form, user_avatar] + + api_endpoints: + - POST /api/auth/login + - POST /api/auth/register + - POST /api/auth/forgot-password + - GET /api/users/me + +acceptance_criteria: + - User can register with email/password + - User can login with Google OAuth + - User can reset forgotten password + - User profile displays correctly +``` + +##### Step 1.5.5: Display Requirements Summary [MANDATORY] +``` +╔══════════════════════════════════════════════════════════════╗ +║ 📋 REQUIREMENTS GATHERED ║ +╠══════════════════════════════════════════════════════════════╣ +║ Feature: $FEATURE ║ +║ Questions asked: X ║ +╠══════════════════════════════════════════════════════════════╣ +║ SCOPE DEFINED ║ +║ ✅ Authentication: Email/Password + Google OAuth ║ +║ ✅ Features: Password reset, Email verification ║ +║ ✅ User Data: Name, email, avatar, bio ║ +║ ✅ UI: Login, Register, Profile pages ║ +╠══════════════════════════════════════════════════════════════╣ +║ Proceeding to DESIGN phase... ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +--- + +#### IF FULL_AUTO_MODE: AI-Driven Expansion + +**Purpose**: AI autonomously expands brief input into comprehensive requirements. +Only asks user for acceptance criteria. + +##### Step 1.5.1: Autonomous Analysis [MANDATORY] + +Use Task tool to expand requirements: + +``` +Use Task tool with: + subagent_type: "requirements-analyst" + prompt: | + # REQUIREMENTS ANALYST - Autonomous Expansion + + ## INPUT + Feature request: "$FEATURE" + + ## YOUR MISSION + Expand this brief feature request into comprehensive requirements. + Think like a senior product manager. + + ## ANALYSIS PROCESS + + 1. **Understand Intent** + - What problem is the user trying to solve? + - What is the core value proposition? + - Who are the target users? + + 2. **Expand Scope** + - What are the obvious features needed? + - What are commonly expected features users don't mention? + - What are the MVP requirements vs nice-to-haves? + + 3. **Data Requirements** + - What entities need to be stored? + - What are the relationships between entities? + - What fields does each entity need? + + 4. **API Design** + - What CRUD operations are needed? + - What custom operations are needed? + - What authentication/authorization is required? + + 5. **UI Components** + - What pages/screens are needed? + - What reusable components are needed? + - What is the user flow? + + 6. **Edge Cases** + - What happens on errors? + - What are the validation rules? + - What are the security considerations? + + ## OUTPUT FORMAT + + Create: .workflow/versions/$VERSION_ID/requirements/expanded.yml + + ```yaml + feature: "$FEATURE" + expanded_at: + mode: full_auto + + analysis: + problem_statement: "" + target_users: "" + core_value: "
" + + scope: + mvp_features: + - + - + future_features: + - + + data_model: + entities: + - name: + fields: [, ] + relations: [] + + api_endpoints: + - method: POST + path: /api/xxx + purpose: + + ui_structure: + pages: + - name: + route: / + purpose: + components: + - name: + purpose: + + security: + authentication: + authorization: + + edge_cases: + - scenario: + handling: + ``` + + ## OUTPUT + After creating the file, output a summary of your analysis. +``` + +##### Step 1.5.2: Display Expanded Requirements [MANDATORY] +``` +╔══════════════════════════════════════════════════════════════╗ +║ 🤖 AI-EXPANDED REQUIREMENTS ║ +╠══════════════════════════════════════════════════════════════╣ +║ Original: "$FEATURE" ║ +╠══════════════════════════════════════════════════════════════╣ +║ EXPANDED SCOPE ║ +║ Problem: ║ +║ Users: ║ +║ Value: ║ +╠══════════════════════════════════════════════════════════════╣ +║ MVP FEATURES ║ +║ • Feature 1 ║ +║ • Feature 2 ║ +║ • Feature 3 ║ +╠══════════════════════════════════════════════════════════════╣ +║ DATA MODEL ║ +║ 📦 Entity1 (X fields) ║ +║ 📦 Entity2 (Y fields) ║ +╠══════════════════════════════════════════════════════════════╣ +║ API ENDPOINTS: X ║ +║ UI PAGES: X ║ +║ COMPONENTS: X ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +##### Step 1.5.3: Ask for Acceptance Criteria [MANDATORY] + +**This is the ONLY question in full-auto mode:** + +``` +Use AskUserQuestion: + Question: "Based on the expanded requirements above, what are your acceptance criteria? How will you know this feature is complete and working?" + + Options: + - "Looks good - use AI-suggested criteria" + Description: "AI will generate acceptance criteria based on the requirements" + - "I'll specify my own criteria" + Description: "Enter your own acceptance criteria" + - "Add to AI criteria" + Description: "Use AI criteria plus add my own" +``` + +**If user chooses "Looks good"**: AI generates acceptance criteria +**If user chooses "I'll specify"**: Prompt user for criteria +**If user chooses "Add to"**: Combine AI + user criteria + +##### Step 1.5.4: Finalize Requirements [MANDATORY] + +Save final requirements with acceptance criteria: +```yaml +# .workflow/versions/$VERSION_ID/requirements/final.yml +feature: "$FEATURE" +mode: full_auto +finalized_at: + +# ... expanded requirements ... + +acceptance_criteria: + - criterion: "User can successfully register" + verification: "Submit registration form, verify account created" + - criterion: "User can login with credentials" + verification: "Login with valid credentials, verify session created" + - criterion: "Invalid login shows error" + verification: "Login with wrong password, verify error message" + # ... more criteria +``` + +##### Step 1.5.5: Display Final Summary [MANDATORY] +``` +╔══════════════════════════════════════════════════════════════╗ +║ ✅ REQUIREMENTS FINALIZED ║ +╠══════════════════════════════════════════════════════════════╣ +║ Feature: $FEATURE ║ +║ Mode: Full-Auto ║ +╠══════════════════════════════════════════════════════════════╣ +║ ACCEPTANCE CRITERIA ║ +║ ☐ User can successfully register ║ +║ ☐ User can login with credentials ║ +║ ☐ Invalid login shows error ║ +║ ☐ Password reset works via email ║ +╠══════════════════════════════════════════════════════════════╣ +║ Proceeding to DESIGN phase (auto-approved)... ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +--- + +#### IF MANUAL_MODE: Skip to Design + +**No requirements gathering phase. Proceed directly to PHASE 2.** + +--- + +### ═══════════════════════════════════════════════════════════════ +### PHASE 2: DESIGNING (Enhanced with Design Document) +### ═══════════════════════════════════════════════════════════════ + +**Entry Condition**: Phase = DESIGNING (verified) +**Exit Condition**: Design document validated, dependency graph generated, tasks with context created + +#### Step 2.1: Verify Phase State [MANDATORY] +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py status +``` +**BLOCK IF**: Current phase is not DESIGNING + +#### Step 2.2: Create Design Directories [MANDATORY] +```bash +mkdir -p .workflow/versions/$VERSION_ID/design +mkdir -p .workflow/versions/$VERSION_ID/contexts +mkdir -p .workflow/versions/$VERSION_ID/tasks +``` + +#### Step 2.3: Spawn Architect Agent for Design Document [MANDATORY] +**MUST use Task tool to create comprehensive design document**: + +``` +Use Task tool with: + subagent_type: "system-architect" + prompt: | + # SYSTEM ARCHITECT - Design Document Creation + # VERSION $VERSION_ID + + ## STRICT REQUIREMENTS + Create a COMPLETE design document. Partial designs = failure. + + ## INPUT + Feature: "$FEATURE" + Version: $VERSION_ID + Output: .workflow/versions/$VERSION_ID/design/design_document.yml + Schema: skills/guardrail-orchestrator/schemas/design_document.yml + + ## DESIGN PROCESS + + ### Phase A: Analyze Requirements + 1. Break down "$FEATURE" into user stories + 2. Identify data that needs to be stored + 3. Identify operations users can perform + 4. Plan the UI structure + + ### Phase B: Design Data Layer (LAYER 1) + Create data_models section with: + - id: model_ + - name: PascalCase entity name + - table_name: snake_case + - fields: [name, type, constraints] + - relations: [type, target, foreign_key, on_delete] + - timestamps: true + - validations: [field, rule, message] + + ### Phase C: Design API Layer (LAYER 2) + Create api_endpoints section with: + - id: api__ + - method: GET|POST|PUT|PATCH|DELETE + - path: /api/ + - request_body: (for POST/PUT/PATCH) + - responses: [{status, description, schema}] + - depends_on_models: [model_ids] + - auth: {required, roles} + + ### Phase D: Design UI Layer (LAYER 3) + Create pages section with: + - id: page_ + - path: / + - data_needs: [{api_id, purpose, on_load}] + - components: [component_ids] + - auth: {required, roles, redirect} + + Create components section with: + - id: component_ + - name: PascalCaseName + - props: [{name, type, required, description}] + - events: [{name, payload, description}] + - uses_apis: [api_ids] + - uses_components: [component_ids] + + ## OUTPUT FORMAT + Create file: .workflow/versions/$VERSION_ID/design/design_document.yml + + ```yaml + workflow_version: "$VERSION_ID" + feature: "$FEATURE" + created_at: + status: draft + revision: 1 + + data_models: + - id: model_ + name: + # ... full model definition + + api_endpoints: + - id: api__ + method: + path: /api/ + # ... full endpoint definition + + pages: + - id: page_ + path: / + # ... full page definition + + components: + - id: component_ + name: + # ... full component definition + ``` + + ## ALSO UPDATE project_manifest.json + Add entities under appropriate sections with status: "PENDING" + + ## VERIFICATION + Before finishing, verify the design document exists: + ```bash + cat .workflow/versions/$VERSION_ID/design/design_document.yml | head -20 + ``` + + ## OUTPUT SUMMARY + ``` + === DESIGN DOCUMENT CREATED === + Data Models: X + API Endpoints: X + Pages: X + Components: X + File: .workflow/versions/$VERSION_ID/design/design_document.yml + ``` +``` + +#### Step 2.4: Validate Design & Generate Artifacts [MANDATORY] +**Run design validation to generate dependency graph, contexts, and tasks**: + +```bash +python3 skills/guardrail-orchestrator/scripts/validate_design.py \ + .workflow/versions/$VERSION_ID/design/design_document.yml \ + --output-dir .workflow/versions/$VERSION_ID +``` + +**This generates:** +- `dependency_graph.yml` - Layered execution order +- `contexts/*.yml` - Per-entity context snapshots for subagents +- `tasks/*.yml` - Implementation tasks with full context + +**BLOCK IF**: Validation fails (exit code != 0) → Display errors, re-run design + +#### Step 2.4.5: Generate API Contract & Shared Types [MANDATORY] +**Generate the API contract that binds frontend and backend implementations**: + +```bash +python3 skills/guardrail-orchestrator/scripts/generate_api_contract.py \ + .workflow/versions/$VERSION_ID/design/design_document.yml \ + --output-dir .workflow/versions/$VERSION_ID +``` + +**This generates:** +- `contracts/api_contract.yml` - Strict API type definitions +- `app/types/api.ts` - Shared TypeScript interfaces + +**CRITICAL**: Both frontend and backend agents MUST import from `app/types/api.ts`. +This ensures type safety and contract compliance. + +**BLOCK IF**: Generation fails → Display errors, re-run design + +#### Step 2.5: Verify Generated Artifacts [MANDATORY] +```bash +# Check dependency graph exists +ls .workflow/versions/$VERSION_ID/dependency_graph.yml + +# Check API contract exists +ls .workflow/versions/$VERSION_ID/contracts/api_contract.yml + +# Check shared types file exists +ls app/types/api.ts + +# Count generated tasks +TASK_COUNT=$(ls .workflow/versions/$VERSION_ID/tasks/*.yml 2>/dev/null | wc -l) +echo "Tasks generated: $TASK_COUNT" + +# Count context files +CONTEXT_COUNT=$(ls .workflow/versions/$VERSION_ID/contexts/*.yml 2>/dev/null | wc -l) +echo "Context files: $CONTEXT_COUNT" +``` + +**BLOCK IF**: TASK_COUNT = 0 → Error: "No tasks generated from design" +**BLOCK IF**: API contract missing → Error: "API contract not generated" + +#### Step 2.6: Display Layered Execution Plan [MANDATORY] +Read dependency_graph.yml and display: + +``` +╔══════════════════════════════════════════════════════════════╗ +║ 📊 EXECUTION LAYERS (Dependency Graph) ║ +╠══════════════════════════════════════════════════════════════╣ +║ ║ +║ Layer 1: DATA MODELS (Parallel) ║ +║ ───────────────────────────────────────────── ║ +║ 📦 model_xxx → backend [no deps] ║ +║ 📦 model_yyy → backend [no deps] ║ +║ ║ +║ Layer 2: API ENDPOINTS (After Layer 1) ║ +║ ───────────────────────────────────────────── ║ +║ 🔌 api_xxx → backend [needs: model_xxx] ║ +║ 🔌 api_yyy → backend [needs: model_xxx, model_yyy] ║ +║ ║ +║ Layer 3: UI (After Layer 2) ║ +║ ───────────────────────────────────────────── ║ +║ 🧩 component_xxx → frontend [no deps] ║ +║ 📄 page_xxx → frontend [needs: api_xxx, component_xxx]║ +║ ║ +╠══════════════════════════════════════════════════════════════╣ +║ EXECUTION SUMMARY ║ +║ Total tasks: X ║ +║ Total layers: X ║ +║ Max parallelism: X tasks can run simultaneously ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +#### Step 2.7: Transition [MANDATORY] +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py progress \ + --tasks-created $TASK_COUNT +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition AWAITING_DESIGN_APPROVAL +``` + +#### Step 2.8: Display Design Summary [MANDATORY] +``` +╔══════════════════════════════════════════════════════════════╗ +║ 📐 DESIGN COMPLETE - AWAITING APPROVAL ║ +╠══════════════════════════════════════════════════════════════╣ +║ Feature: $FEATURE ║ +║ Version: $VERSION_ID ║ +╠══════════════════════════════════════════════════════════════╣ +║ DESIGN DOCUMENT ║ +║ 📦 Data Models: X ║ +║ 🔌 API Endpoints: X ║ +║ 📄 Pages: X ║ +║ 🧩 Components: X ║ +╠══════════════════════════════════════════════════════════════╣ +║ GENERATED ARTIFACTS ║ +║ ✅ Design document created ║ +║ ✅ Dependency graph calculated ║ +║ ✅ Context snapshots: X files ║ +║ ✅ Implementation tasks: X tasks ║ +╠══════════════════════════════════════════════════════════════╣ +║ Each subagent will receive FULL CONTEXT including: ║ +║ - Target entity definition ║ +║ - Related model/API definitions ║ +║ - Input/output contracts ║ +║ - Acceptance criteria ║ +╠══════════════════════════════════════════════════════════════╣ +║ 👆 Review the execution layers above ║ +║ ║ +║ If design looks correct: /workflow:approve ║ +║ If changes needed: /workflow:reject "reason" ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +--- + +### ═══════════════════════════════════════════════════════════════ +### PHASE 3: GATE 1 - Design Approval +### ═══════════════════════════════════════════════════════════════ + +**Entry Condition**: Phase = AWAITING_DESIGN_APPROVAL +**Exit Condition**: Design approved, phase = IMPLEMENTING + +#### IF AUTO_MODE = true: +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py approve design +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition IMPLEMENTING +``` +Output: "✅ Design auto-approved. Proceeding to implementation." + +#### IF AUTO_MODE = false: +Use AskUserQuestion: +``` +Question: "Review the design. How do you want to proceed?" +Options: + 1. "Approve - Continue to implementation" + 2. "Reject - Revise design" + 3. "Pause - Save and exit" +``` + +**On Approve**: Run transition commands above +**On Reject**: Return to Phase 2 +**On Pause**: Output resume command and stop + +--- + +### ═══════════════════════════════════════════════════════════════ +### PHASE 4: IMPLEMENTING (Team-Based Parallel Execution) +### ═══════════════════════════════════════════════════════════════ + +**Entry Condition**: Phase = IMPLEMENTING (verified) +**Exit Condition**: Both teams complete, build passes, API contract validated + +**TEAM-BASED PARALLELISM**: Two specialized agents run in parallel: +- **Backend Team**: Implements models + APIs (Layer 1 + Layer 2) +- **Frontend Team**: Implements components + pages (Layer 3) + +Both teams share the same API contract (`app/types/api.ts`) ensuring type safety. + +#### Step 4.1: Verify Phase State [MANDATORY] +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py status +``` +**BLOCK IF**: Phase is not IMPLEMENTING + +#### Step 4.2: Load Contract and Tasks [MANDATORY] +```bash +# Read API contract +cat .workflow/versions/$VERSION_ID/contracts/api_contract.yml + +# Verify shared types exist +ls app/types/api.ts + +# Count backend and frontend tasks +BACKEND_TASKS=$(grep -l 'agent: backend' .workflow/versions/$VERSION_ID/tasks/*.yml 2>/dev/null | wc -l) +FRONTEND_TASKS=$(grep -l 'agent: frontend' .workflow/versions/$VERSION_ID/tasks/*.yml 2>/dev/null | wc -l) +echo "Backend tasks: $BACKEND_TASKS" +echo "Frontend tasks: $FRONTEND_TASKS" +``` + +#### Step 4.3: Launch Both Teams IN PARALLEL [MANDATORY] +**CRITICAL**: Launch BOTH agents in a SINGLE message with TWO Task tool calls. +This enables true parallel execution. + +``` +╔══════════════════════════════════════════════════════════════╗ +║ 🚀 LAUNCHING PARALLEL TEAMS ║ +╠══════════════════════════════════════════════════════════════╣ +║ ║ +║ ┌─────────────────┐ ┌─────────────────┐ ║ +║ │ BACKEND TEAM │ || │ FRONTEND TEAM │ ║ +║ │ │ || │ │ ║ +║ │ • Models │ || │ • Components │ ║ +║ │ • APIs │ || │ • Pages │ ║ +║ │ │ || │ │ ║ +║ │ Exports: │ || │ Imports: │ ║ +║ │ /api/* routes │ ──→→ ──→│ app/types/api │ ║ +║ └─────────────────┘ └─────────────────┘ ║ +║ ║ +║ SHARED CONTRACT: app/types/api.ts ║ +║ ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +##### Step 4.3.1: Spawn Backend Team Agent [IN PARALLEL] +``` +Use Task tool with: + subagent_type: "backend-architect" + prompt: | + # BACKEND TEAM - VERSION $VERSION_ID + + ## YOUR MISSION + Implement ALL backend tasks (models + APIs) for this workflow. + You own the entire backend layer. + + ## CRITICAL: API CONTRACT COMPLIANCE + You MUST import types from the shared types file: + ```typescript + import type { User, CreateUserRequest, ... } from '@/types/api'; + ``` + + The API contract is at: .workflow/versions/$VERSION_ID/contracts/api_contract.yml + The shared types are at: app/types/api.ts + + **DO NOT** create your own types. Use the shared types. + + ## TASK FILES + Read all backend tasks: + ```bash + ls .workflow/versions/$VERSION_ID/tasks/task_*model*.yml + ls .workflow/versions/$VERSION_ID/tasks/task_*api*.yml + ``` + + ## IMPLEMENTATION ORDER + 1. **First**: Implement ALL models (Layer 1) + - Add to prisma/schema.prisma + - Run: npx prisma generate + + 2. **Then**: Implement ALL API endpoints (Layer 2) + - Create app/api/*/route.ts files + - Import shared types from @/types/api + - Implement request validation + - Return responses matching contract types + + ## FOR EACH TASK + 1. Read the task file and context file + 2. Read reference files for patterns + 3. Implement following the contract + 4. Verify with TypeScript + + ## VERIFICATION + After all tasks: + ```bash + npx prisma generate 2>&1 || true + npx tsc --noEmit 2>&1 || true + ``` + + ## OUTPUT FORMAT + ``` + === BACKEND TEAM COMPLETE === + Models implemented: + - model_xxx: app/api/... ✓ + + APIs implemented: + - api_xxx: app/api/.../route.ts ✓ + - api_yyy: app/api/.../route.ts ✓ + + Contract compliance: + - Types imported from @/types/api ✓ + - All endpoints match contract ✓ + + TypeScript: PASS/FAIL + Prisma: PASS/FAIL + ``` +``` + +##### Step 4.3.2: Spawn Frontend Team Agent [IN PARALLEL] +``` +Use Task tool with: + subagent_type: "frontend-architect" + prompt: | + # FRONTEND TEAM - VERSION $VERSION_ID + + ## YOUR MISSION + Implement ALL frontend tasks (components + pages) for this workflow. + You own the entire frontend layer. + + ## CRITICAL: API CONTRACT COMPLIANCE + You MUST import types from the shared types file: + ```typescript + import type { User, ApiError, ... } from '@/types/api'; + import { API_PATHS } from '@/types/api'; + ``` + + The API contract is at: .workflow/versions/$VERSION_ID/contracts/api_contract.yml + The shared types are at: app/types/api.ts + + **DO NOT** create your own API types. Use the shared types. + + ## TASK FILES + Read all frontend tasks: + ```bash + ls .workflow/versions/$VERSION_ID/tasks/task_*component*.yml + ls .workflow/versions/$VERSION_ID/tasks/task_*page*.yml + ``` + + ## IMPLEMENTATION + For EACH task: + 1. Read the task file and context file + 2. Read reference files for patterns + 3. Create component/page file + 4. Import types from @/types/api + 5. Use API_PATHS for fetch calls + 6. Type all props, state, and API responses + + ## API CALL PATTERN (USE THIS) + ```typescript + import type { User, CreateUserRequest } from '@/types/api'; + import { API_PATHS } from '@/types/api'; + + // Type-safe API call + const response = await fetch(API_PATHS.CREATE_USER, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(data satisfies CreateUserRequest), + }); + const result: User = await response.json(); + ``` + + ## VERIFICATION + After all tasks: + ```bash + npx tsc --noEmit 2>&1 || true + ``` + + ## OUTPUT FORMAT + ``` + === FRONTEND TEAM COMPLETE === + Components implemented: + - component_xxx: app/components/Xxx.tsx ✓ + + Pages implemented: + - page_xxx: app/xxx/page.tsx ✓ + + Contract compliance: + - Types imported from @/types/api ✓ + - API calls use API_PATHS ✓ + + TypeScript: PASS/FAIL + ``` +``` + +**IMPORTANT**: You MUST send BOTH Task tool calls in a SINGLE message. +This enables parallel execution. Do NOT wait for one to complete. + +#### Step 4.4: Wait for Both Teams [MANDATORY] +**MUST wait for BOTH agents to complete before proceeding.** + +Display progress: +``` +╔══════════════════════════════════════════════════════════════╗ +║ ⏳ TEAMS EXECUTING... ║ +╠══════════════════════════════════════════════════════════════╣ +║ Backend Team: 🔄 In Progress ║ +║ Frontend Team: 🔄 In Progress ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +#### Step 4.5: Post-Implementation Verification [MANDATORY] +```bash +# Verify build passes +npm run build +echo "Exit code: $?" +``` +**BLOCK IF**: Exit code != 0 → Error with build output + +```bash +# Verify all task files have corresponding implementation files +for task in .workflow/versions/$VERSION_ID/tasks/*.yml; do + grep "to_create:" -A 10 "$task" | grep -E "^\s+-" | sed 's/.*- //' | while read path; do + if [ ! -f "$path" ]; then + echo "MISSING: $path" + fi + done +done +``` +**BLOCK IF**: Any file MISSING → List missing files, halt workflow + +#### Step 4.6: Validate API Contract Compliance [MANDATORY] +```bash +# Run contract validation +python3 skills/guardrail-orchestrator/scripts/validate_against_contract.py \ + .workflow/versions/$VERSION_ID/contracts/api_contract.yml \ + --project-dir . +CONTRACT_EXIT=$? +echo "CONTRACT_EXIT=$CONTRACT_EXIT" +``` + +**Validates:** +- All backend routes exist and match contract methods +- All frontend components import from shared types +- All API calls use correct paths and methods + +**BLOCK IF**: CONTRACT_EXIT != 0 → Display violations, halt workflow + +#### Step 4.7: Display Implementation Summary [MANDATORY] +``` +╔══════════════════════════════════════════════════════════════╗ +║ ✅ PARALLEL IMPLEMENTATION COMPLETE ║ +╠══════════════════════════════════════════════════════════════╣ +║ Backend Team: ║ +║ Models: X implemented ║ +║ APIs: X implemented ║ +║ ║ +║ Frontend Team: ║ +║ Components: X implemented ║ +║ Pages: X implemented ║ +╠══════════════════════════════════════════════════════════════╣ +║ API Contract: VALID ✓ ║ +║ Shared Types: app/types/api.ts ✓ ║ +║ Build: PASS ✓ ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +#### Step 4.8: Transition [MANDATORY] +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition REVIEWING +``` + +--- + +### ═══════════════════════════════════════════════════════════════ +### PHASE 5: REVIEWING +### ═══════════════════════════════════════════════════════════════ + +**Entry Condition**: Phase = REVIEWING (verified) +**Exit Condition**: All checks pass, ready for approval + +#### Step 5.1: Verify Phase State [MANDATORY] +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py status +``` +**BLOCK IF**: Phase is not REVIEWING + +#### IF AUTO_MODE = true: Automated Review + +##### Step 5.2a: Run Build Validation [MANDATORY] +```bash +npm run build 2>&1 +BUILD_EXIT=$? +``` + +##### Step 5.2b: Generate Implementation Visualization [MANDATORY] +**MUST show user what was built before review:** + +```bash +python3 skills/guardrail-orchestrator/scripts/visualize_implementation.py --manifest project_manifest.json +``` + +This displays: +- 📱 Page structure with routes +- 🧩 Component hierarchy tree +- 🔌 API endpoints with methods +- 📊 Implementation statistics (lines, hooks, types) + +##### Step 5.3a: Check All Files Exist [MANDATORY] +```bash +MISSING_COUNT=0 +for task in .workflow/versions/$VERSION_ID/tasks/*.yml; do + grep "file_paths:" -A 20 "$task" | grep -E "^\s+-\s+" | sed 's/.*- //' | while read path; do + if [ ! -f "$path" ]; then + echo "MISSING: $path" + MISSING_COUNT=$((MISSING_COUNT + 1)) + fi + done +done +echo "Missing files: $MISSING_COUNT" +``` + +##### Step 5.4a: Auto-Decision [MANDATORY] +``` +IF BUILD_EXIT = 0 AND MISSING_COUNT = 0: + → Display: "✅ AUTO-REVIEW PASSED" + → Run: python3 .../workflow_manager.py transition SECURITY_REVIEW + → Proceed to Phase 5.5 (Security Review) +ELSE: + → Display: "❌ AUTO-REVIEW FAILED" + → List all failures (build errors, missing files) + → HALT workflow + → Output: "Fix issues and run /workflow:resume" +``` + +##### Step 5.5a: Auto Review Report [MANDATORY] +``` +╔══════════════════════════════════════════════════════════════╗ +║ 🔍 AUTO REVIEW RESULTS ║ +╠══════════════════════════════════════════════════════════════╣ +║ Build: PASS / FAIL ║ +║ Files: X/Y exist ║ +║ Decision: AUTO-APPROVED / AUTO-REJECTED ║ +╠══════════════════════════════════════════════════════════════╣ +║ IMPLEMENTATION SUMMARY ║ +║ Pages: X implemented ║ +║ Components: X implemented ║ +║ API Endpoints: X implemented ║ +║ Total Lines: X ║ +╠══════════════════════════════════════════════════════════════╣ +║ 👆 See visualization above for details ║ +╠══════════════════════════════════════════════════════════════╣ +║ [If failed, list specific failures here] ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +--- + +#### IF AUTO_MODE = false: Agent Review + +##### Step 5.2b: Generate Implementation Visualization [MANDATORY] +**MUST show user what was built before spawning reviewer:** + +```bash +python3 skills/guardrail-orchestrator/scripts/visualize_implementation.py --manifest project_manifest.json +``` + +This shows the user: +- Pages with their routes and components +- Component hierarchy and relationships +- API endpoints with HTTP methods +- Code statistics and metrics + +##### Step 5.3b: Spawn Reviewer Agent [MANDATORY] +``` +Use Task tool with: + subagent_type: "quality-engineer" + prompt: | + # REVIEWER AGENT - VERSION $VERSION_ID + + ## STRICT REQUIREMENTS + Review ALL tasks. Report ALL issues. No partial reviews. + + ## REVIEW CHECKLIST (FOR EACH TASK) + + Task files: .workflow/versions/$VERSION_ID/tasks/*.yml + + For each task: + 1. [ ] Read task file + 2. [ ] Verify ALL file_paths exist + 3. [ ] Read each file, verify: + - [ ] Exports match manifest + - [ ] Types are correct + - [ ] No TypeScript errors + - [ ] Follows project patterns + 4. [ ] Check acceptance_criteria met + + ## VALIDATION (RUN THESE) + ```bash + npm run build + npm run lint 2>/dev/null || echo "No lint configured" + ``` + + ## OUTPUT FORMAT (REQUIRED) + ``` + === REVIEW REPORT === + + TASK: task_create_xxx + - Files: EXIST / MISSING (list) + - Build: PASS / FAIL + - Quality: PASS / ISSUES (list) + - Verdict: APPROVED / NEEDS_CHANGES + + [Repeat for each task] + + SUMMARY + - Total tasks: X + - Approved: X + - Need changes: X + - Overall: PASS / FAIL + ``` +``` + +##### Step 5.3b: Transition to Security Review [MANDATORY] +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition SECURITY_REVIEW +``` + +--- + +### ═══════════════════════════════════════════════════════════════ +### PHASE 5.5: SECURITY REVIEW +### ═══════════════════════════════════════════════════════════════ + +**Entry Condition**: Phase = SECURITY_REVIEW (verified) +**Exit Condition**: Security scan passes (no CRITICAL issues), ready for approval + +#### Step 5.5.1: Verify Phase State [MANDATORY] +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py status +``` +**BLOCK IF**: Phase is not SECURITY_REVIEW + +#### Step 5.5.2: Run Security Scanner [MANDATORY] +```bash +python3 skills/guardrail-orchestrator/scripts/security_scan.py \ + --project-dir . \ + --severity HIGH +SECURITY_EXIT=$? +echo "SECURITY_EXIT=$SECURITY_EXIT" +``` + +**Exit codes:** +- 0 = PASS (no critical/high issues) +- 1 = HIGH issues found (warning in normal mode, blocks in --strict) +- 2 = CRITICAL issues found (always blocks) + +#### Step 5.5.3: API Contract Validation [MANDATORY] +```bash +# Validate against generated contract (types and routes) +python3 skills/guardrail-orchestrator/scripts/validate_against_contract.py \ + .workflow/versions/$VERSION_ID/contracts/api_contract.yml \ + --project-dir . +CONTRACT_EXIT=$? +echo "CONTRACT_EXIT=$CONTRACT_EXIT" + +# Also run static API analysis +python3 skills/guardrail-orchestrator/scripts/validate_api_contract.py \ + --project-dir . +API_EXIT=$? +echo "API_EXIT=$API_EXIT" +``` + +**Contract Validation Checks:** +- Backend routes exist and export correct HTTP methods +- Frontend files import from shared types (@/types/api) +- Types not recreated locally (must use shared types) + +**Static API Validation Checks:** +- Frontend API calls have matching backend endpoints +- HTTP methods match (GET, POST, PUT, DELETE) +- Request bodies are sent where expected + +#### Step 5.5.4: Security Decision [MANDATORY] + +##### IF AUTO_MODE = true: +``` +IF SECURITY_EXIT = 0 AND API_EXIT = 0 AND CONTRACT_EXIT = 0: + → Display: "✅ SECURITY & CONTRACT VALIDATION PASSED" + → Transition to AWAITING_IMPL_APPROVAL +ELSE IF SECURITY_EXIT = 2: + → Display: "❌ CRITICAL SECURITY ISSUES - BLOCKING" + → List all critical issues + → Transition to IMPLEMENTING (must fix) + → HALT workflow +ELSE IF CONTRACT_EXIT = 2: + → Display: "❌ CONTRACT VIOLATIONS - BLOCKING" + → List all contract violations + → Transition to IMPLEMENTING (must fix) + → HALT workflow +ELSE IF SECURITY_EXIT = 1 OR CONTRACT_EXIT = 1: + → Display: "⚠️ HIGH SEVERITY ISSUES - WARNING" + → List high severity issues and contract warnings + → Continue to approval (warning only in auto mode) +``` + +##### IF AUTO_MODE = false: +Use AskUserQuestion: +``` +Question: "Security scan found issues. How do you want to proceed?" +Options: + 1. "Accept risks - Continue to approval" (if no CRITICAL) + 2. "Fix issues - Return to implementation" + 3. "Run full audit - /workflow:security --full" +``` + +#### Step 5.5.5: Display Security Report [MANDATORY] +``` +╔══════════════════════════════════════════════════════════════╗ +║ 🔒 SECURITY & CONTRACT REVIEW RESULTS ║ +╠══════════════════════════════════════════════════════════════╣ +║ Security Scan: PASS / WARNING / CRITICAL ║ +║ Critical: X issues ║ +║ High: X issues ║ +║ Medium: X issues ║ +║ Low: X issues ║ +╠══════════════════════════════════════════════════════════════╣ +║ Contract Compliance: PASS / WARNING / FAIL ║ +║ Backend routes: X of X verified ║ +║ Type imports: X files checked ║ +║ Violations: X ║ +╠══════════════════════════════════════════════════════════════╣ +║ API Static Analysis: PASS / FAIL ║ +║ Matched calls: X ║ +║ Unmatched: X ║ +║ Method errors: X ║ +╠══════════════════════════════════════════════════════════════╣ +║ [If issues found, list top 5 with file locations] ║ +╠══════════════════════════════════════════════════════════════╣ +║ VERDICT: APPROVED / NEEDS_FIXES ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +#### Step 5.5.6: Transition [MANDATORY] +```bash +# If security passed +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition AWAITING_IMPL_APPROVAL + +# If security failed (CRITICAL issues) +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition IMPLEMENTING +``` + +--- + +### ═══════════════════════════════════════════════════════════════ +### PHASE 6: GATE 2 - Implementation Approval +### ═══════════════════════════════════════════════════════════════ + +**Entry Condition**: Phase = AWAITING_IMPL_APPROVAL +**Exit Condition**: Implementation approved, phase = COMPLETING + +**Note**: In AUTO_MODE, this gate is handled in Phase 5 + +#### IF AUTO_MODE = false: +Use AskUserQuestion: +``` +Question: "Review complete. How do you want to proceed?" +Options: + 1. "Approve - Mark as complete" + 2. "Reject - Request fixes" + 3. "Pause - Save and exit" +``` + +**On Approve**: +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py approve implementation +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition COMPLETING +``` + +**On Reject**: Provide feedback, return to Phase 4 +**On Pause**: Output resume command and stop + +--- + +### ═══════════════════════════════════════════════════════════════ +### PHASE 7: COMPLETING +### ═══════════════════════════════════════════════════════════════ + +**Entry Condition**: Phase = COMPLETING (verified) +**Exit Condition**: Version marked complete, success report displayed + +#### Step 7.1: Verify Phase State [MANDATORY] +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py status +``` +**BLOCK IF**: Phase is not COMPLETING + +#### Step 7.2: Update Task Statuses [MANDATORY] +```bash +# Mark all tasks as completed +for task in .workflow/versions/$VERSION_ID/tasks/*.yml; do + sed -i '' 's/status: .*/status: completed/' "$task" 2>/dev/null || \ + sed -i 's/status: .*/status: completed/' "$task" +done +``` + +#### Step 7.3: Update Manifest Statuses [MANDATORY] +Update all entities referenced in tasks from "PENDING" to "IMPLEMENTED" + +#### Step 7.4: Complete Version [MANDATORY] +```bash +python3 skills/guardrail-orchestrator/scripts/version_manager.py complete +``` +**VERIFY**: Script exits with code 0 + +#### Step 7.5: Final Report [MANDATORY] + +**IF AUTO_MODE = true**: Display completion-only report (NO next steps) +``` +╔══════════════════════════════════════════════════════════════╗ +║ ✅ WORKFLOW COMPLETED (AUTO) ║ +╠══════════════════════════════════════════════════════════════╣ +║ Version: $VERSION_ID ║ +║ Feature: $FEATURE ║ +╠══════════════════════════════════════════════════════════════╣ +║ SUMMARY ║ +║ Tasks completed: X ║ +║ Files created: X ║ +║ Files modified: X ║ +║ Build: PASS ║ +╚══════════════════════════════════════════════════════════════╝ +``` +**DO NOT** include "NEXT STEPS" in AUTO mode - the workflow is complete. + +**IF AUTO_MODE = false**: Display full report with next steps +``` +╔══════════════════════════════════════════════════════════════╗ +║ ✅ WORKFLOW COMPLETED ║ +╠══════════════════════════════════════════════════════════════╣ +║ Version: $VERSION_ID ║ +║ Feature: $FEATURE ║ +║ Mode: INTERACTIVE ║ +╠══════════════════════════════════════════════════════════════╣ +║ SUMMARY ║ +║ Tasks completed: X ║ +║ Files created: X ║ +║ Files modified: X ║ +╠══════════════════════════════════════════════════════════════╣ +║ NEXT STEPS ║ +║ npm run dev Test the feature ║ +║ /workflow:history View all versions ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +--- + +## USAGE + +```bash +# Manual mode (full control, stops at all gates) +/workflow:spawn add user profile page + +# Auto mode (guided discovery with questions, auto-approves gates) +/workflow:spawn --auto add user authentication + +# Full-auto mode (AI expands idea, only asks for acceptance criteria) +/workflow:spawn --full-auto add dark mode toggle +``` + +### Mode Selection Guide + +| Use Case | Recommended Mode | Why | +|----------|------------------|-----| +| Complex feature, unclear requirements | `--auto` | AI guides you through requirements | +| Quick prototype, trust AI judgment | `--full-auto` | Fast, minimal input needed | +| Specific requirements already known | Manual | Full control over every step | +| Learning the workflow | Manual | See all gates and decisions | +| Production feature | `--auto` | Ensures requirements are complete | + +### Examples + +```bash +# Manual - full control +/workflow:spawn add user authentication + +# Auto - AI asks questions until requirements are clear +/workflow:spawn --auto add user authentication +# AI asks: "What auth method?" → "OAuth providers?" → "Password reset?" → etc. + +# Full-auto - AI expands idea, you approve criteria +/workflow:spawn --full-auto add user authentication +# AI expands: "I'll add login, register, password reset, OAuth, profile..." +# AI asks: "What are your acceptance criteria?" +``` + +--- + +## ERROR RECOVERY + +| Error | Command | +|-------|---------| +| Workflow interrupted | `/workflow:resume` | +| Check current state | `/workflow:status` | +| View history | `/workflow:history` | +| Skip to specific phase | Not allowed - must follow sequence | + +--- + +## ENFORCEMENT CHECKLIST + +Before completing this command, verify: +- [ ] Version created with version_manager.py +- [ ] Phase transitions logged with workflow_manager.py +- [ ] Task files exist in .workflow/versions/$VERSION_ID/tasks/ +- [ ] Build passes (exit code 0) +- [ ] All file_paths in tasks exist +- [ ] Final report displayed diff --git a/.claude/commands/workflow/status.md b/.claude/commands/workflow/status.md new file mode 100644 index 0000000..d3723fa --- /dev/null +++ b/.claude/commands/workflow/status.md @@ -0,0 +1,119 @@ +--- +description: Show workflow status and task summary +allowed-tools: Read, Bash +--- + +# Workflow Status + +Display current workflow status and task breakdown. + +## Steps + +### 1. Check Active Workflow +```bash +python3 skills/guardrail-orchestrator/scripts/workflow_manager.py status +``` + +If active workflow exists, display workflow state. +If no workflow, continue with manual task scan. + +### 2. Read Project Manifest +Check `project_manifest.json` for: +- Current phase +- Entity counts by status + +### 3. Scan Tasks +Get the version-specific tasks directory: +```bash +TASKS_DIR=$(python3 skills/guardrail-orchestrator/scripts/version_manager.py tasks-dir) +``` + +Read all `$TASKS_DIR/*.yml` files and count by: +- Status (pending, in_progress, review, approved, completed, blocked) +- Agent (frontend, backend, reviewer) +- Type (create, update, delete, review) + +### 4. Display Summary + +``` +╔══════════════════════════════════════════════════════════════╗ +║ WORKFLOW STATUS ║ +╠══════════════════════════════════════════════════════════════╣ +║ Active Workflow: | None ║ +║ Feature: ║ +║ Phase: ║ +╠══════════════════════════════════════════════════════════════╣ +║ APPROVAL GATES ║ +║ 🛑 Design: ║ +║ 🛑 Implementation: ║ +╠══════════════════════════════════════════════════════════════╣ +║ TASKS BY STATUS ║ +║ ⏳ Pending: X ║ +║ 🔄 In Progress: X ║ +║ 🔍 Review: X ║ +║ ✅ Approved: X ║ +║ ✓ Completed: X ║ +║ 🚫 Blocked: X ║ +╠══════════════════════════════════════════════════════════════╣ +║ TASKS BY AGENT ║ +║ 🎨 Frontend: X pending, X completed ║ +║ ⚙️ Backend: X pending, X completed ║ +║ 🔍 Reviewer: X pending ║ +╠══════════════════════════════════════════════════════════════╣ +║ NEXT ACTIONS ║ +║ /workflow:frontend --next (X tasks available) ║ +║ /workflow:backend --next (X tasks available) ║ +║ /workflow:review --next (X tasks to review) ║ +║ /workflow:resume (continue workflow) ║ +╚══════════════════════════════════════════════════════════════╝ +``` + +### 5. Show Design Visualization +**If in DESIGNING or AWAITING_DESIGN_APPROVAL phase**, display visual design: + +```bash +python3 skills/guardrail-orchestrator/scripts/visualize_design.py --manifest project_manifest.json +``` + +This shows: +- 📱 Page flow diagram +- 📄 Page details with components +- 🧩 Component hierarchy +- 🔌 API endpoints +- 🔄 Data flow architecture + +### 5b. Show Implementation Visualization +**If in REVIEWING, SECURITY_REVIEW, or AWAITING_IMPL_APPROVAL phase**, display what was built: + +```bash +python3 skills/guardrail-orchestrator/scripts/visualize_implementation.py --manifest project_manifest.json +``` + +This shows: +- 📱 Page structure with routes +- 🧩 Component hierarchy and relationships +- 🔌 API endpoints with HTTP methods +- 📊 Implementation statistics (lines, hooks, types) +- 🌳 Component tree view + +### 6. List Pending Tasks +Show table of tasks ready to work on: + +| Task ID | Type | Agent | Priority | Dependencies | +|---------|------|-------|----------|--------------| + +### 7. Show Approval Instructions + +**If AWAITING_DESIGN_APPROVAL**: +``` +🛑 Design approval required. Review the entities and tasks, then: + - Approve: /workflow:approve design + - Reject: /workflow:reject design "reason" +``` + +**If AWAITING_IMPL_APPROVAL**: +``` +🛑 Implementation approval required. Review the code, then: + - Approve: /workflow:approve implementation + - Reject: /workflow:reject implementation "reason" +``` diff --git a/.claude/eureka-factory.yaml b/.claude/eureka-factory.yaml new file mode 100644 index 0000000..4dca46f --- /dev/null +++ b/.claude/eureka-factory.yaml @@ -0,0 +1,4 @@ +api_key: pk_user_8d080a1a699dc2a1769ca99ded0ca39fa80324b8713cf55ea7fecc1c372379a6 +project_id: "" +repo_id: "" +app_id: cmjb04ana0001qp0tijyy9emq diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..8ab61e4 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,225 @@ +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_bash.py\" --command \"$TOOL_INPUT_COMMAND\"" + } + ] + }, + { + "matcher": "Task", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_workflow.py\" --operation task --input \"$TOOL_INPUT\"" + } + ] + }, + { + "matcher": "Write", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_workflow.py\" --operation write --file \"$TOOL_INPUT_FILE_PATH\"" + }, + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_write.py\" --manifest \"$CLAUDE_PROJECT_DIR/project_manifest.json\" --file \"$TOOL_INPUT_FILE_PATH\"" + } + ] + }, + { + "matcher": "Edit", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_workflow.py\" --operation edit --file \"$TOOL_INPUT_FILE_PATH\"" + }, + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_write.py\" --manifest \"$CLAUDE_PROJECT_DIR/project_manifest.json\" --file \"$TOOL_INPUT_FILE_PATH\"" + } + ] + }, + { + "matcher": "MultiEdit", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_workflow.py\" --operation edit --file \"$TOOL_INPUT_FILE_PATH\"" + }, + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_write.py\" --manifest \"$CLAUDE_PROJECT_DIR/project_manifest.json\" --file \"$TOOL_INPUT_FILE_PATH\"" + } + ] + }, + { + "matcher": "NotebookEdit", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_workflow.py\" --operation edit --file \"$TOOL_INPUT_NOTEBOOK_PATH\"" + }, + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_write.py\" --manifest \"$CLAUDE_PROJECT_DIR/project_manifest.json\" --file \"$TOOL_INPUT_NOTEBOOK_PATH\"" + } + ] + }, + { + "matcher": "mcp__serena__create_text_file", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_workflow.py\" --operation write --input \"$TOOL_INPUT\"" + }, + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_write.py\" --manifest \"$CLAUDE_PROJECT_DIR/project_manifest.json\" --file \"$TOOL_INPUT_FILE_PATH\"" + } + ] + }, + { + "matcher": "mcp__serena__replace_content", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_workflow.py\" --operation edit --input \"$TOOL_INPUT\"" + }, + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_write.py\" --manifest \"$CLAUDE_PROJECT_DIR/project_manifest.json\" --file \"$TOOL_INPUT_FILE_PATH\"" + } + ] + }, + { + "matcher": "mcp__serena__replace_symbol_body", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_workflow.py\" --operation edit --input \"$TOOL_INPUT\"" + }, + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_write.py\" --manifest \"$CLAUDE_PROJECT_DIR/project_manifest.json\" --file \"$TOOL_INPUT_FILE_PATH\"" + } + ] + }, + { + "matcher": "mcp__morphllm-fast-apply__write_file", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_workflow.py\" --operation write --input \"$TOOL_INPUT\"" + }, + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_write.py\" --manifest \"$CLAUDE_PROJECT_DIR/project_manifest.json\" --file \"$TOOL_INPUT_FILE_PATH\"" + } + ] + }, + { + "matcher": "mcp__morphllm-fast-apply__tiny_edit_file", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_workflow.py\" --operation edit --input \"$TOOL_INPUT\"" + }, + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_write.py\" --manifest \"$CLAUDE_PROJECT_DIR/project_manifest.json\" --file \"$TOOL_INPUT_FILE_PATH\"" + } + ] + }, + { + "matcher": "mcp__filesystem__write_file", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_workflow.py\" --operation write --input \"$TOOL_INPUT\"" + }, + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_write.py\" --manifest \"$CLAUDE_PROJECT_DIR/project_manifest.json\" --file \"$TOOL_INPUT_PATH\"" + } + ] + }, + { + "matcher": "mcp__filesystem__edit_file", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_workflow.py\" --operation edit --input \"$TOOL_INPUT\"" + }, + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_write.py\" --manifest \"$CLAUDE_PROJECT_DIR/project_manifest.json\" --file \"$TOOL_INPUT_PATH\"" + } + ] + }, + { + "matcher": "mcp__filesystem__create_directory", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_workflow.py\" --operation write --input \"$TOOL_INPUT\"" + } + ] + }, + { + "matcher": "mcp__filesystem__move_file", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/validate_workflow.py\" --operation write --input \"$TOOL_INPUT\"" + } + ] + } + ], + "PostToolUse": [ + { + "matcher": "Write", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/post_write.py\" --manifest \"$CLAUDE_PROJECT_DIR/project_manifest.json\" --file \"$TOOL_INPUT_FILE_PATH\"" + } + ] + }, + { + "matcher": "Edit", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/post_write.py\" --manifest \"$CLAUDE_PROJECT_DIR/project_manifest.json\" --file \"$TOOL_INPUT_FILE_PATH\"" + } + ] + }, + { + "matcher": "Task", + "hooks": [ + { + "type": "command", + "command": "echo '🔄 Agent task completed. Verify outputs before proceeding.'" + } + ] + } + ], + "Stop": [ + { + "matcher": "", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/skills/guardrail-orchestrator/scripts/workflow_manager.py\" status 2>/dev/null || echo '🛡️ Session complete (no active workflow)'" + } + ] + } + ] + } +} diff --git a/.mcp.json b/.mcp.json new file mode 100644 index 0000000..be99453 --- /dev/null +++ b/.mcp.json @@ -0,0 +1,16 @@ +{ + "mcpServers": { + "eureka-docs": { + "command": "npx", + "args": ["eureka-docs-server"], + "env": {} + }, + "eureka-imagen": { + "command": "npx", + "args": ["eureka-imagen-server"], + "env": { + "IMAGEROUTER_API_KEY": "${IMAGEROUTER_API_KEY}" + } + } + } +} diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..4e6e5d9 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,1182 @@ +# 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 + +# Interactive workflow (stops at approval gates) +/workflow:spawn +``` + +### 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 # 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 +# or +/guardrail:init +``` + +### 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//.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.yml # REQUIRED: Skill manifest +├── agents/ # REQUIRED: Agent definitions +│ └── .yml +├── schemas/ # OPTIONAL: Data schemas +│ └── .yml +├── scripts/ # OPTIONAL: Python/Bash scripts +│ └── .py +└── templates/ # OPTIONAL: HTML/MD templates + └── .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//agents/.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 | `-` | `backend-architect`, `frontend-engineer` | +| Review agents | `-reviewer` | `security-reviewer`, `code-reviewer` | +| Analysis agents | `-analyzer` | `codebase-analyzer`, `dependency-analyzer` | +| Writer agents | `-writer` | `doc-writer`, `test-writer` | + +--- + +### Creating a Schema + +Schemas define the structure of YAML/JSON data files. + +#### File Location +``` +skills//schemas/.yml +``` + +#### Schema File Format + +```yaml +# Schema metadata +version: "1.0" +description: What this schema defines + +# Top-level structure +: + 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//scripts/.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 [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//templates/.html +``` + +#### Placeholder Conventions + +```html + +{{VARIABLE_NAME}} + + + +
default content
+ + + +{{#IF_CONDITION}} + Content shown if condition is true +{{/IF_CONDITION}} + + +{{#EACH_ITEMS}} +
{{ITEM_NAME}}
+{{/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// + □ Create skill.yml manifest + □ Define triggers and capabilities + +□ 3. CREATE THE AGENT(S) + □ Create agents/.yml + □ Define allowed/blocked tools + □ Define responsibilities and outputs + +□ 4. CREATE SCHEMAS (if needed) + □ Create schemas/.yml + □ Define data structure + □ Add validation rules + +□ 5. CREATE SCRIPTS (if needed) + □ Create scripts/.py + □ Handle CLI arguments + □ Add error handling + +□ 6. CREATE TEMPLATES (if needed) + □ Create templates/.html + □ Add CSS styling + □ Use placeholder conventions + +□ 7. CREATE THE COMMAND + □ Create .claude/commands//.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. diff --git a/skills/documentation-generator/agents/doc-writer.yml b/skills/documentation-generator/agents/doc-writer.yml new file mode 100644 index 0000000..06f8b56 --- /dev/null +++ b/skills/documentation-generator/agents/doc-writer.yml @@ -0,0 +1,152 @@ +# Documentation Writer Agent +# Specialized agent for generating dual-audience documentation + +name: doc-writer +role: Documentation Specialist +description: | + Expert in creating comprehensive documentation that serves both technical + and non-technical audiences. Specializes in translating complex technical + concepts into accessible language while maintaining technical accuracy. + +capabilities: + - Analyze project structure and extract key information + - Generate visual ASCII diagrams for architecture + - Write plain-language descriptions of technical features + - Create technical reference documentation + - Build glossaries for technical terms + - Structure documentation for multiple audience levels + +allowed_tools: + - Read + - Write + - Edit + - Glob + - Grep + - Bash + +blocked_tools: + - Task # Should not spawn sub-agents + +allowed_files: + - "docs/**/*" + - "*.md" + - "package.json" + - "project_manifest.json" + - "tsconfig.json" + - "requirements.txt" + - "pyproject.toml" + - "Cargo.toml" + - "go.mod" + +responsibilities: + - Analyze source code to understand functionality + - Extract API endpoints and document them + - Document components with props and usage + - Create ER diagrams for data models + - Write executive summaries for stakeholders + - Build glossaries for technical terms + - Generate quick reference cards + +outputs: + - PROJECT_DOCUMENTATION.md (main documentation) + - QUICK_REFERENCE.md (one-page summary) + - API_REFERENCE.md (detailed API docs) + - COMPONENTS.md (component catalog) + - GLOSSARY.md (term definitions) + +cannot_do: + - Modify source code + - Change project configuration + - Run tests or builds + - Deploy or publish + +writing_principles: + non_technical: + - Lead with "What" and "Why", not "How" + - Use analogies and real-world comparisons + - Avoid acronyms; spell them out first time + - Use bullet points over paragraphs + - Include visual diagrams + - Focus on value and outcomes + + technical: + - Include in collapsible
sections + - Provide code examples with syntax highlighting + - Reference file paths and line numbers + - Include type definitions and interfaces + - Link to source files + - Document edge cases and error handling + +documentation_sections: + executive_summary: + audience: everyone + purpose: Project purpose, value proposition, key capabilities + format: Plain English, no jargon + + architecture_overview: + audience: everyone + purpose: Visual system understanding + format: ASCII diagrams, technology tables + + getting_started: + audience: semi-technical + purpose: Quick onboarding + format: Step-by-step with explanations + + feature_guide: + audience: non-technical + purpose: Feature documentation + format: What/Why/How (simplified) + + api_reference: + audience: developers + purpose: API documentation + format: Endpoints, schemas, examples + + component_catalog: + audience: developers + purpose: UI component documentation + format: Props, events, usage examples + + data_models: + audience: both + purpose: Data structure documentation + format: ER diagrams + plain descriptions + + glossary: + audience: non-technical + purpose: Term definitions + format: Term -> Plain English definition + +ascii_diagram_templates: + system_architecture: | + ┌─────────────────────────────────────────────────────────┐ + │ [System Name] │ + ├─────────────────────────────────────────────────────────┤ + │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ + │ │ [Layer] │───▶│ [Layer] │───▶│ [Layer] │ │ + │ └─────────────┘ └─────────────┘ └─────────────┘ │ + └─────────────────────────────────────────────────────────┘ + + entity_relationship: | + ┌──────────────┐ ┌──────────────┐ + │ [Entity] │ │ [Entity] │ + ├──────────────┤ ├──────────────┤ + │ id (PK) │──────▶│ id (PK) │ + │ field │ │ foreign_key │ + └──────────────┘ └──────────────┘ + + data_flow: | + [Source] ──▶ [Process] ──▶ [Output] + │ │ │ + ▼ ▼ ▼ + [Storage] [Transform] [Display] + +quality_checklist: + - All referenced files exist + - All code examples are syntactically correct + - No broken internal links + - Technical details wrapped in
+ - Plain English explanations for all features + - Glossary includes all technical terms used + - ASCII diagrams render correctly in markdown diff --git a/skills/documentation-generator/schemas/documentation_output.yml b/skills/documentation-generator/schemas/documentation_output.yml new file mode 100644 index 0000000..2a3e335 --- /dev/null +++ b/skills/documentation-generator/schemas/documentation_output.yml @@ -0,0 +1,274 @@ +# Documentation Output Schema +# Defines the structure for generated documentation + +version: "1.0" +description: Schema for dual-audience project documentation + +output_files: + main_documentation: + filename: PROJECT_DOCUMENTATION.md + required: true + sections: + - executive_summary + - quick_start + - architecture_overview + - features + - for_developers + - glossary + + quick_reference: + filename: QUICK_REFERENCE.md + required: true + sections: + - commands + - key_files + - api_endpoints + - environment_variables + + api_reference: + filename: API_REFERENCE.md + required: false + condition: has_api_endpoints + sections: + - authentication + - endpoints_by_resource + - error_codes + - rate_limiting + + components: + filename: COMPONENTS.md + required: false + condition: has_ui_components + sections: + - component_index + - component_details + - usage_examples + +section_schemas: + executive_summary: + description: High-level project overview for all audiences + fields: + project_name: + type: string + required: true + tagline: + type: string + required: true + max_length: 100 + description: One-line description in plain English + what_it_does: + type: string + required: true + description: 2-3 sentences, no technical jargon + who_its_for: + type: string + required: true + description: Target audience in plain English + key_capabilities: + type: array + items: + capability: string + description: string + min_items: 3 + max_items: 8 + + quick_start: + description: Getting started guide for new users + fields: + prerequisites: + type: array + items: + tool: string + purpose: string # Plain English explanation + install_command: string + installation_steps: + type: array + items: + step: integer + command: string + explanation: string # What this does + basic_usage: + type: string + description: Simple example of how to use + + architecture_overview: + description: Visual system architecture + fields: + system_diagram: + type: string + format: ascii_art + required: true + technology_stack: + type: array + items: + layer: string + technology: string + purpose: string # Plain English + directory_structure: + type: string + format: tree + required: true + + features: + description: Feature documentation for all audiences + fields: + features: + type: array + items: + name: string + what_it_does: string # Plain English + how_to_use: string # Simple instructions + example: string # Code or usage example + technical_notes: string # For engineers, optional + + api_endpoint: + description: Single API endpoint documentation + fields: + method: + type: enum + values: [GET, POST, PUT, PATCH, DELETE] + path: + type: string + pattern: "^/api/" + summary: + type: string + description: Plain English description + description: + type: string + description: Detailed explanation + authentication: + type: object + fields: + required: boolean + type: string # bearer, api_key, session + request: + type: object + fields: + content_type: string + body_schema: object + query_params: array + path_params: array + responses: + type: array + items: + status: integer + description: string + schema: object + examples: + type: array + items: + name: string + request: object + response: object + + component: + description: UI component documentation + fields: + name: + type: string + pattern: "^[A-Z][a-zA-Z]*$" # PascalCase + path: + type: string + description: + type: string + description: Plain English purpose + props: + type: array + items: + name: string + type: string + required: boolean + default: any + description: string + events: + type: array + items: + name: string + payload: string + description: string + usage_example: + type: string + format: code + dependencies: + type: array + items: string + + data_model: + description: Data model documentation + fields: + name: + type: string + description: + type: string + description: What data it represents (plain English) + table_name: + type: string + fields: + type: array + items: + name: string + type: string + description: string # Plain English + constraints: array + relations: + type: array + items: + type: enum + values: [has_one, has_many, belongs_to, many_to_many] + target: string + description: string + + glossary_term: + description: Technical term definition + fields: + term: + type: string + required: true + definition: + type: string + required: true + description: Plain English definition + see_also: + type: array + items: string + description: Related terms + +audience_markers: + non_technical: + indicator: "📖" + description: "For all readers" + technical: + indicator: "🔧" + description: "For developers" + wrapper: "
🔧 Technical Details...content...
" + +formatting_rules: + headings: + h1: "# Title" + h2: "## Section" + h3: "### Subsection" + code_blocks: + language_hints: required + max_lines: 30 + tables: + alignment: left + max_columns: 5 + diagrams: + format: ascii_art + max_width: 80 + links: + internal: "[text](#anchor)" + external: "[text](url)" + file_reference: "`path/to/file`" + +validation_rules: + - name: no_broken_links + description: All internal links must resolve + - name: code_syntax + description: All code blocks must be syntactically valid + - name: file_references + description: All referenced files must exist + - name: glossary_coverage + description: All technical terms must be in glossary + - name: diagram_rendering + description: ASCII diagrams must render correctly diff --git a/skills/documentation-generator/schemas/project_analysis.yml b/skills/documentation-generator/schemas/project_analysis.yml new file mode 100644 index 0000000..23ad329 --- /dev/null +++ b/skills/documentation-generator/schemas/project_analysis.yml @@ -0,0 +1,272 @@ +# Project Analysis Schema +# Defines the structure for project analysis output + +version: "1.0" +description: Schema for analyzing project structure before documentation generation + +project_analysis: + project: + type: object + required: true + fields: + name: + type: string + required: true + source: package.json/name or directory name + version: + type: string + required: false + source: package.json/version + description: + type: string + required: false + source: package.json/description or README.md first paragraph + type: + type: enum + values: [node, python, rust, go, java, dotnet, ruby, php, other] + detection: + node: package.json + python: requirements.txt, pyproject.toml, setup.py + rust: Cargo.toml + go: go.mod + java: pom.xml, build.gradle + dotnet: "*.csproj, *.sln" + ruby: Gemfile + php: composer.json + repository: + type: string + source: package.json/repository or .git/config + + tech_stack: + type: object + required: true + fields: + language: + type: string + description: Primary programming language + framework: + type: string + description: Main application framework + detection: + next: "next" in dependencies + react: "react" in dependencies without "next" + vue: "vue" in dependencies + angular: "@angular/core" in dependencies + express: "express" in dependencies + fastapi: "fastapi" in requirements + django: "django" in requirements + flask: "flask" in requirements + rails: "rails" in Gemfile + database: + type: string + description: Database system if any + detection: + prisma: "@prisma/client" in dependencies + mongoose: "mongoose" in dependencies + typeorm: "typeorm" in dependencies + sequelize: "sequelize" in dependencies + sqlalchemy: "sqlalchemy" in requirements + ui_framework: + type: string + description: UI component framework if any + detection: + tailwind: "tailwindcss" in devDependencies + mui: "@mui/material" in dependencies + chakra: "@chakra-ui/react" in dependencies + shadcn: "shadcn" patterns in components + key_dependencies: + type: array + items: + name: string + version: string + purpose: string # Plain English explanation + categorization: + core: Framework, runtime dependencies + database: ORM, database clients + auth: Authentication libraries + ui: UI component libraries + testing: Test frameworks + build: Build tools, bundlers + utility: Helper libraries + + structure: + type: object + required: true + fields: + source_dir: + type: string + description: Main source code directory + detection: + - src/ + - app/ + - lib/ + - source/ + directories: + type: array + items: + path: string + purpose: string # Plain English description + file_count: integer + key_files: array + common_mappings: + src/components: "UI components" + src/pages: "Application pages/routes" + src/api: "API route handlers" + src/lib: "Utility functions and shared code" + src/hooks: "Custom React hooks" + src/context: "React context providers" + src/store: "State management" + src/types: "TypeScript type definitions" + src/styles: "Global styles and themes" + prisma/: "Database schema and migrations" + public/: "Static assets" + tests/: "Test files" + __tests__/: "Test files (Jest convention)" + + features: + type: array + description: Main features/capabilities of the project + items: + name: string + description: string # Plain English + technical_notes: string # For engineers + files: array # Key file paths + detection_patterns: + authentication: + keywords: [auth, login, logout, session, jwt, oauth] + files: ["**/auth/**", "**/login/**"] + user_management: + keywords: [user, profile, account, register, signup] + files: ["**/user/**", "**/users/**"] + api: + keywords: [api, endpoint, route, handler] + files: ["**/api/**", "**/routes/**"] + database: + keywords: [model, entity, schema, migration, prisma] + files: ["**/models/**", "**/prisma/**"] + file_upload: + keywords: [upload, file, storage, s3, blob] + files: ["**/upload/**", "**/storage/**"] + search: + keywords: [search, filter, query] + files: ["**/search/**"] + notifications: + keywords: [notification, email, sms, push] + files: ["**/notification/**", "**/email/**"] + + components: + type: array + description: UI components found in the project + items: + id: string # component_ + name: string # PascalCase + path: string + description: string + props: string # Props summary + dependencies: array # Imported components + detection: + react: "export (default )?(function|const) [A-Z]" + vue: "