Skip to content

Latest commit

 

History

History
795 lines (616 loc) · 18.1 KB

File metadata and controls

795 lines (616 loc) · 18.1 KB

AI Minions - Usage Examples

Real-world examples of how to use the AI Minions plugin effectively.

Example 1: Building a User Authentication System

Request

/smart-implement Create a complete user authentication system with email/password login, registration, and JWT tokens

What Happens

  1. Orchestrator receives the request

  2. Domain Analyzer determines:

    RECOMMENDATION: PARALLEL_SPLIT
    REASONING: Clear frontend/backend split with auth API as contract
    
    DOMAINS_INVOLVED:
    - Frontend: Login form, registration form, protected routes
    - Backend: Auth API, JWT generation, password hashing, user model
    
    SHARED_CONTRACTS:
    - POST /api/auth/register
    - POST /api/auth/login
    - GET /api/auth/me
    - Auth types (User, LoginRequest, RegisterRequest)
    
  3. API Contract Designer creates:

    // src/contracts/auth.contract.ts
    export interface RegisterRequest {
      email: string;
      password: string;
      name: string;
    }
    
    export interface LoginRequest {
      email: string;
      password: string;
    }
    
    export interface AuthResponse {
      token: string;
      user: User;
    }
    
    export interface User {
      id: string;
      email: string;
      name: string;
      createdAt: string;
    }
  4. Parallel Execution:

    • Frontend Specialist builds:

      • LoginForm.tsx with validation
      • RegisterForm.tsx with validation
      • Auth context for state management
      • Protected route wrapper
      • Token storage in localStorage
    • Backend Specialist builds:

      • POST /api/auth/register with bcrypt hashing
      • POST /api/auth/login with JWT generation
      • GET /api/auth/me with JWT verification
      • User model in database
      • Auth middleware
  5. Reviewer improves:

    • Adds rate limiting to prevent brute force
    • Improves password strength validation
    • Adds ARIA labels to forms
    • Implements proper error handling
    • Adds loading states

Result

Complete, production-ready authentication system built in parallel with best practices.


Example 2: Adding a Real-Time Chat Feature

Request

/smart-implement Add real-time chat to the application with message history

What Happens

  1. Domain Analyzer determines:

    RECOMMENDATION: PARALLEL_SPLIT
    DOMAINS_INVOLVED:
    - Frontend: Chat UI, message list, input, WebSocket client
    - Backend: WebSocket server, message storage, room management
    - Database: Messages table, rooms table
    
  2. API Contract Designer creates:

    // WebSocket events contract
    export interface SendMessageEvent {
      roomId: string;
      content: string;
      userId: string;
    }
    
    export interface ReceiveMessageEvent {
      id: string;
      roomId: string;
      userId: string;
      userName: string;
      content: string;
      timestamp: string;
    }
    
    // REST endpoints
    // GET /api/rooms/:roomId/messages
    // POST /api/rooms/:roomId/join
  3. Parallel Execution:

    • Frontend: Chat UI, WebSocket connection, message rendering
    • Backend: Socket.io server, message broadcast, persistence
  4. Reviewer adds:

    • Message sanitization (XSS prevention)
    • Typing indicators
    • Read receipts
    • Accessibility for screen readers
    • Connection status indicator

Example 3: Simple UI Fix

Request

/smart-implement Fix the loading spinner on the submit button

What Happens

  1. Domain Analyzer determines:

    RECOMMENDATION: SINGLE_DOMAIN
    REASONING: Pure frontend change, no backend involvement
    
  2. Frontend Specialist implements:

    <button
      onClick={handleSubmit}
      disabled={isLoading}
      className="relative"
    >
      {isLoading ? (
        <>
          <span className="opacity-0">Submit</span>
          <span className="absolute inset-0 flex items-center justify-center">
            <Spinner />
          </span>
        </>
      ) : (
        'Submit'
      )}
    </button>
  3. Reviewer improves:

    • Adds ARIA label for screen readers
    • Ensures keyboard accessibility
    • Adds smooth transition

Example 4: Performance Optimization

Request

/improve the product listing page for performance

What Happens

  1. Reviewer analyzes the page:

    • Measures current performance
    • Identifies bottlenecks
  2. Improvements Made:

    ✅ Added pagination (was loading all 10,000 products)
    ✅ Implemented lazy loading for images
    ✅ Added React.memo to ProductCard
    ✅ Optimized database query with indexes
    ✅ Added caching with Redis (5min TTL)
    ✅ Reduced bundle size (removed unused deps)
    
    RESULTS:
    - Page load: 4.2s → 0.8s
    - First paint: 2.1s → 0.4s
    - Bundle size: 2.3MB → 0.9MB
    

Example 5: Accessibility Audit

Request

/improve for accessibility

What Happens

  1. Reviewer performs comprehensive a11y audit:

  2. Issues Found & Fixed:

    ✅ Added alt text to 47 images
    ✅ Fixed heading hierarchy (was jumping from h1 to h4)
    ✅ Added ARIA labels to icon buttons
    ✅ Improved color contrast (15 violations fixed)
    ✅ Fixed keyboard navigation (added tab index)
    ✅ Added focus indicators
    ✅ Improved form labels (every input now has label)
    ✅ Added skip-to-content link
    
    WCAG COMPLIANCE:
    - Before: 67% (Level A)
    - After: 98% (Level AA)
    

Example 6: Security Review

Request

/improve the API endpoints for security

What Happens

  1. Reviewer performs security audit:

  2. Vulnerabilities Found & Fixed:

    🔒 Critical: SQL injection in user search
       Fixed: Using parameterized queries
    
    🔒 High: No rate limiting on login endpoint
       Fixed: Added express-rate-limit (5 attempts/15min)
    
    🔒 High: Passwords stored in plain text
       Fixed: Implemented bcrypt hashing
    
    🔒 Medium: CORS allowing all origins
       Fixed: Restricted to specific domains
    
    🔒 Medium: No CSRF protection
       Fixed: Added CSRF tokens
    
    🔒 Low: Exposing stack traces in errors
       Fixed: Generic error messages in production
    

Example 7: E-commerce Checkout Flow

Request

/smart-implement Build a checkout flow with cart, shipping, and payment

What Happens

  1. Domain Analyzer: Multi-step, multi-domain feature
  2. API Contract Designer: Creates contracts for cart, shipping, payment APIs
  3. Parallel Execution:
    • Frontend: Cart UI, shipping form, payment integration (Stripe)
    • Backend: Cart management, shipping calculation, payment processing
  4. Reviewer adds:
    • Form validation with clear error messages
    • Loading states for each step
    • Success/failure notifications
    • Mobile responsive design
    • Accessibility (keyboard navigation, screen reader)
    • Security (payment data never touches server, using Stripe tokens)

Example 8: Code Refactoring

Request

/improve the user service - it's become too large

What Happens

  1. Reviewer analyzes user.service.ts (450 lines):

  2. Refactoring Applied:

    ✅ Split into multiple services:
       - user.service.ts (core user operations)
       - user-validation.service.ts (validation logic)
       - user-notification.service.ts (email notifications)
       - user-analytics.service.ts (tracking events)
    
    ✅ Extracted common patterns:
       - BaseService class for shared functionality
       - Error handling utilities
    
    ✅ Improved testability:
       - Added dependency injection
       - Created interfaces for external dependencies
    
    ✅ Added comprehensive tests:
       - user.service.test.ts
       - user-validation.service.test.ts
    
    METRICS:
    - Average function length: 45 lines → 12 lines
    - Cyclomatic complexity: 18 → 4
    - Test coverage: 0% → 87%
    

Tips for Best Results

1. Be Specific

❌ /smart-implement add comments
✅ /smart-implement Add a comment system to blog posts with replies, likes, and moderation

2. Let the AI Split Work

✅ /smart-implement Build a dashboard with analytics
   → AI will determine if frontend/backend split makes sense

3. Use /improve Liberally

# After any major feature
/improve

# Focus on specific areas
/improve for security
/improve for performance
/improve for accessibility

4. Trust the Reviewer

The reviewer has full autonomy. It will:

  • Fix issues automatically
  • Report what it did and why
  • Follow best practices

5. Review Complex Features

For large features, do a post-implementation review:

/smart-implement [large feature]
# Wait for completion
/improve the [feature name]  # Extra review pass

When to Use Each Command

Use /smart-implement when:

  • Building new features
  • Need parallel execution
  • Want automatic quality review
  • Full-stack or multi-domain work

Use /improve when:

  • Code review needed
  • Optimizing existing code
  • Security audit
  • Accessibility improvements
  • Performance optimization
  • Code quality enhancement

Use direct agent invocation when:

  • Very specific, targeted work
  • Want to skip orchestration
  • Need just one specialist

Example:

@frontend-specialist create a loading skeleton for the user list
@backend-specialist add caching to the products API
@reviewer security audit the authentication system

Workflow Recommendations

For New Features

1. /smart-implement [feature description]
2. Wait for completion + auto-review
3. Optionally: /improve [feature] for extra polish

For Bug Fixes

1. Identify the issue
2. /smart-implement fix [describe the bug]
3. Reviewer automatically validates the fix

For Refactoring

1. /improve [file or feature to refactor]
2. Reviewer analyzes and refactors
3. Review the changes

For Quality Audits

# Security
/improve for security

# Performance
/improve for performance

# Accessibility
/improve for accessibility

# All domains
/improve


Example 9: Parallel Execution with Conflict Detection

Request

/parallel-execute Add user profile page with avatar upload and settings page

What Happens

  1. Conflict Detector runs AST analysis:

    # Behind the scenes:
    node ast-analyzer.js src/ > ast-results.json
    node dependency-graph.js ast-results.json > execution-plan.json
  2. Analysis Results:

    {
      "conflictZones": [
        {
          "files": ["src/types/user.ts"],
          "reason": "Both tasks need to extend User type",
          "canParallelize": false
        }
      ],
      "parallelZones": [
        {
          "zone1": ["src/components/UserProfile.tsx"],
          "zone2": ["src/components/Settings.tsx"],
          "canParallelize": true
        }
      ],
      "executionWaves": [
        {
          "wave": 1,
          "tasks": ["Extend User type with avatar and settings fields"]
        },
        {
          "wave": 2,
          "tasks": ["Build profile page", "Build settings page"],
          "parallelizable": true
        }
      ]
    }
  3. API Contract Designer creates zone boundaries:

    // src/contracts/user-zones.contract.ts
    export const ZONE_SHARED: ExecutionZone = {
      zoneId: 'shared',
      responsibility: 'Type definitions',
      safeToModify: ['src/types/user.ts'],
      mustNotTouch: []
    };
    
    export const ZONE_PROFILE: ExecutionZone = {
      zoneId: 'profile',
      responsibility: 'User profile UI',
      safeToModify: ['src/components/UserProfile.tsx', 'src/hooks/useProfile.ts'],
      mustNotTouch: ['src/types/**', 'src/components/Settings.tsx']
    };
    
    export const ZONE_SETTINGS: ExecutionZone = {
      zoneId: 'settings',
      responsibility: 'Settings UI',
      safeToModify: ['src/components/Settings.tsx', 'src/hooks/useSettings.ts'],
      mustNotTouch: ['src/types/**', 'src/components/UserProfile.tsx']
    };
  4. Parallel Executor runs wave-based execution:

    Wave 1: @backend-specialist
            "Extend User type with avatarUrl and settings fields"
            ↓ completes in 2 minutes
    
    Wave 2: @frontend-specialist (profile task)
            "Build UserProfile.tsx using User type"
            
            @frontend-specialist (settings task)
            "Build Settings.tsx using User type"
            
            ↓ both run concurrently, complete in 5 minutes
    
    Total time: 7 minutes (vs 12 minutes sequential)
    Speedup: 42%
    
  5. Validation runs automatically:

    ✅ npm test: 52/52 tests passed
    ✅ npm run typecheck: No errors
    ✅ npm run lint: No issues
    ✅ npm run e2e: 27/27 scenarios passed
    

Result

✅ Parallel Execution Complete

Execution ID: exec-2025-01-10-abc123
Duration: 7m 23s
Sequential Estimate: 12m 30s
Speedup: 42% faster

Waves: 2
Tasks Completed: 3
Tasks Failed: 0

FILES MODIFIED: 8
COMMITS: 3
TESTS: All passed

Example 10: Validation Workflow

Request

/validate-work

First Run (No Config)

🔧 Validation Configuration Wizard

How should validation run?
→ 1) auto_local - Run local tests automatically, prompt for E2E

📝 Local Validation Commands
Detected:
  1) npm test
  2) npm run typecheck
  3) npm run lint

Use detected commands? [Y/n]: y

🌐 E2E Tests
E2E command: npm run e2e
Browser: chromium

💾 Configuration saved!

Subsequent Runs

▶ Running Local Validation

→ npm test
  ✅ 47 tests passed (12.3s)
  
→ npm run typecheck
  ✅ No type errors (3.2s)
  
→ npm run lint
  ✅ No issues (2.1s)

✅ Local tests passed. Run E2E tests? [Y/n]: y

▶ Running E2E Validation

→ npm run e2e
  ✅ 23 scenarios passed (45.7s)

═══════════════════════════════════════════════
  VALIDATION REPORT
═══════════════════════════════════════════════

LOCAL: ✅ PASSED (17.6s)
E2E: ✅ PASSED (45.7s)
TOTAL: 63.3s

RECOMMENDATION: ✅ Ready for code review
═══════════════════════════════════════════════

Auto-Fix Example

▶ Running Local Validation

→ npm test
  ❌ 44/47 tests passed, 3 failed (12.3s)
     UserProfile.test.tsx: Expected avatarUrl to be defined
  
→ npm run typecheck
  ❌ 1 error (3.2s)
     src/types/user.ts: Property 'avatarUrl' missing

📊 Self-Validation Analysis

Root Cause:
- Missing avatarUrl field in User type
- Test fixtures don't have avatarUrl

Fix Plan:
1. Add 'avatarUrl: string | null' to User type
2. Update test fixtures to include avatarUrl

Apply fixes? [Y/n]: y

✅ Applied fix 1: Updated User type
✅ Applied fix 2: Updated test fixtures

▶ Re-running validation...

→ npm test
  ✅ 47 tests passed (12.1s)
  
→ npm run typecheck
  ✅ No errors (3.0s)

✅ All tests now pass (after fixes)

Example 11: Analyzing Conflicts

Request

/analyze-conflicts src/components/ src/app/api/

Output

═══════════════════════════════════════════════
  CONFLICT ANALYSIS REPORT
═══════════════════════════════════════════════

Files Analyzed: 24
Dependencies: 156

CONFLICT ZONES: 2

Zone 1: Circular Dependencies
  Files:
    - src/components/UserProfile.tsx
    - src/hooks/useUserProfile.ts
    - src/components/UserAvatar.tsx
  Reason: Circular imports
  Can Parallelize: ❌ No
  Recommendation: Refactor to break cycle

Zone 2: High Coupling
  Files:
    - src/components/UserCard.tsx
    - src/app/api/users/route.ts
  Reason: Share 12 symbols from User type
  Can Parallelize: ✅ Yes (with contract)
  Recommendation: Define User type contract first

PARALLEL ZONES: 3

Zone 1: Frontend Components (8 files)
  Independent: ✅ Yes
  Can run with: Backend API

Zone 2: Backend API (6 files)
  Independent: ✅ Yes
  Can run with: Frontend Components

Zone 3: Utilities (4 files)
  Independent: ✅ Yes
  Can run with: All zones

HIGHLY CONNECTED FILES:

1. src/types/user.ts
   Connections: 12
   Role: Central type hub
   Recommendation: Modify in Wave 1

2. src/lib/api/client.ts
   Connections: 11
   Role: API client used widely

RECOMMENDATIONS:
✅ Safe to parallelize frontend + backend
✅ Define User type contract first
⚠️  Refactor circular dependencies
═══════════════════════════════════════════════

Example 12: Complex Multi-Domain Feature

Request

/parallel-execute Build analytics dashboard with charts, filters, export, and real-time updates

What Happens

  1. Conflict Detector identifies 4 zones:

    • Shared types (Wave 1)
    • Frontend UI (Wave 2)
    • Backend API (Wave 2)
    • WebSocket server (Wave 2)
    • Export service (Wave 3, depends on API)
  2. Execution Plan:

    Wave 1: [Shared Types]
      - Task 1: Define AnalyticsData, ChartConfig, ExportOptions types (2 min)
    
    Wave 2: [Parallel - 3 tasks]
      - Task 2: Build dashboard UI with Chart.js (6 min)
      - Task 3: Create REST API endpoints for analytics (5 min)
      - Task 4: WebSocket server for real-time updates (5 min)
    
    Wave 3: [Sequential]
      - Task 5: CSV/PDF export service (3 min)
    
    Total: 2 + max(6,5,5) + 3 = 11 minutes
    Sequential would be: 2 + 6 + 5 + 5 + 3 = 21 minutes
    Speedup: 48%
    
  3. Validation catches integration issue:

    ❌ E2E test "real-time chart updates" failed
    
    Issue: WebSocket events not matching expected format
    Root Cause: Frontend expects 'data' field, backend sends 'value' field
    
    Fix: Updated backend to use 'data' field (contract violation)
    
    ✅ Re-validation passed
    

Result

Complete analytics dashboard in 11 minutes with safe parallel execution, comprehensive validation, and one auto-fixed integration issue.


Pro Tip: The more context you provide, the better the results. Include details about:

  • What the feature should do
  • Edge cases to handle
  • Performance requirements
  • User experience expectations

The AI Minions will handle the rest! 🤖✨