project-standalo-note-to-app/.claude/commands/workflow/spawn.md

92 KiB

description allowed-tools agents
Automated workflow orchestrator with approval gates and sub-agent delegation Read, Write, Edit, Bash, Task, AskUserQuestion, TodoWrite workflow-orchestrator, workflow-reviewer, workflow-validator, type-generator, backend-implementer, frontend-implementer, deployer

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

CUSTOM AGENTS

Use these project-specific agents at the indicated phases:

Agent When to Use Phase Parallel
workflow-orchestrator Overall workflow coordination and delegation All phases -
workflow-reviewer Gap analysis after design changes DESIGN_REVIEW -
type-generator Generate TypeScript types from design Pre-IMPLEMENTING -
backend-implementer Prisma models, API routes, server logic IMPLEMENTING Yes
frontend-implementer React components, pages, client logic IMPLEMENTING Yes
workflow-validator Validate implementation against design During/after IMPLEMENTING -
deployer Deploy to Eureka platform After APPROVAL / COMPLETED -

Parallel Execution

Backend + Frontend run in parallel:

Use Task tool with:                    Use Task tool with:
  subagent_type: "general-purpose"       subagent_type: "general-purpose"
  prompt: |                              prompt: |
    You are backend-implementer.           You are frontend-implementer.
    [Read .claude/agents/backend-          [Read .claude/agents/frontend-
     implementer.md]                        implementer.md]
    Task: Implement backend tasks...       Task: Implement frontend tasks...

CRITICAL: Send BOTH Task calls in a SINGLE message for parallel execution.

Agent Invocation

To use custom agents, invoke via Task tool:

Use Task tool with:
  subagent_type: "general-purpose"
  prompt: |
    You are the workflow-validator agent.
    [Read .claude/agents/workflow-validator.md for full instructions]

    Task: Validate implementation against design document...

Or reference agent directly:

Use the workflow-validator agent to check implementation compliance.

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]

# 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"

# 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]

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]

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)


Step 1.5.0: Launch Background Context Gatherer [PARALLEL - ALL MODES]

CRITICAL: Launch this agent IMMEDIATELY at the start of Phase 1.5. It runs in the BACKGROUND while you ask questions, gathering existing project context so the design phase has full information ready.

Use Task tool with:
  subagent_type: "general-purpose"
  run_in_background: true
  prompt: |
    You are the context-gatherer agent.
    Read and follow: .claude/agents/context-gatherer.md

    ## YOUR MISSION
    Gather all existing project context QUICKLY so the design phase can use it.
    You are running in BACKGROUND while the main workflow asks user questions.

    ## GATHER THESE (in parallel where possible):

    ### 1. Project Manifest
    ```bash
    cat project_manifest.json 2>/dev/null | head -200
    ```

    ### 2. Existing Design Documents
    ```bash
    find .workflow/versions -name "design_document.yml" 2>/dev/null | head -3 | xargs -I{} head -100 {}
    ```

    ### 3. Relations/Dependencies
    ```bash
    find .workflow/versions -name "relations.yml" 2>/dev/null | head -3 | xargs -I{} cat {}
    ```

    ### 4. Existing Codebase Structure
    ```bash
    # Prisma models
    cat prisma/schema.prisma 2>/dev/null | grep -A 15 "^model " | head -80

    # API routes
    find app/api -name "route.ts" 2>/dev/null | head -15

    # Pages
    find app -name "page.tsx" -not -path "*/api/*" 2>/dev/null | head -15

    # Components
    find app/components components -name "*.tsx" 2>/dev/null | head -20

    # Types
    find types app/types -name "*.ts" 2>/dev/null | head -10
    ```

    ### 5. Detect Patterns
    ```bash
    # Tech stack from package.json
    cat package.json 2>/dev/null | grep -E '"(next|react|prisma|@prisma|tailwind)"' | head -10
    ```

    ## OUTPUT
    Write consolidated context to: .workflow/gathered_context.yml

    Include:
    - existing_models: list with fields and relations
    - existing_apis: list with methods and paths
    - existing_pages: list with routes
    - existing_components: list with props
    - dependency_chains: what depends on what
    - detected_patterns: naming, file structure, imports
    - reference_implementations: good examples to follow

    ## SPEED REQUIREMENT
    Complete within 15 seconds. Use head/grep to limit output.
    DO NOT ask questions - you are background process.

WHY PARALLEL: While this agent gathers context, continue with questions below. The gathered context will be ready when design phase starts.


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
mkdir -p .workflow/versions/$VERSION_ID/requirements

Create requirements tracking:

# .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:

# .workflow/versions/$VERSION_ID/requirements/summary.yml
feature: "$FEATURE"
gathered_at: <timestamp>
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: <timestamp>
    mode: full_auto

    analysis:
      problem_statement: "<what problem this solves>"
      target_users: "<who will use this>"
      core_value: "<main benefit>"

    scope:
      mvp_features:
        - <feature 1>
        - <feature 2>
      future_features:
        - <feature for later>

    data_model:
      entities:
        - name: <Entity>
          fields: [<field1>, <field2>]
          relations: [<relation>]

    api_endpoints:
      - method: POST
        path: /api/xxx
        purpose: <what it does>

    ui_structure:
      pages:
        - name: <PageName>
          route: /<path>
          purpose: <what user does here>
      components:
        - name: <ComponentName>
          purpose: <what it displays/does>

    security:
      authentication: <method>
      authorization: <rules>

    edge_cases:
      - scenario: <what could go wrong>
        handling: <how to handle it>
    ```

    ## 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: <problem statement>                               ║
║   Users: <target users>                                      ║
║   Value: <core 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:

# .workflow/versions/$VERSION_ID/requirements/final.yml
feature: "$FEATURE"
mode: full_auto
finalized_at: <timestamp>

# ... 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]

python3 skills/guardrail-orchestrator/scripts/workflow_manager.py status

BLOCK IF: Current phase is not DESIGNING

Step 2.2: Create Design Directories [MANDATORY]

mkdir -p .workflow/versions/$VERSION_ID/design
mkdir -p .workflow/versions/$VERSION_ID/contexts
mkdir -p .workflow/versions/$VERSION_ID/tasks

Step 2.2.5: Retrieve Background Context [MANDATORY]

Wait for and retrieve the gathered context from the background agent:

# Check if gathered context exists (background agent completed)
if [ -f ".workflow/gathered_context.yml" ]; then
  echo "✅ Background context gathered successfully"
  cat .workflow/gathered_context.yml | head -100
else
  echo "⚠️ Background context not yet available, proceeding without"
fi

Display gathered context summary:

╔══════════════════════════════════════════════════════════════╗
║ 📊 EXISTING PROJECT CONTEXT (Gathered in Background)         ║
╠══════════════════════════════════════════════════════════════╣
║ Existing Models:     X (list: model_user, model_post, ...)   ║
║ Existing APIs:       X (list: api_get_users, ...)            ║
║ Existing Pages:      X (list: page_home, ...)                ║
║ Existing Components: X (list: component_header, ...)         ║
╠══════════════════════════════════════════════════════════════╣
║ DEPENDENCIES TO CONSIDER                                     ║
║   Most connected: model_user (used by X entities)            ║
║   Reusable: component_header, component_card, ...            ║
╠══════════════════════════════════════════════════════════════╣
║ This context will be passed to the architect agent below.    ║
╚══════════════════════════════════════════════════════════════╝

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

    ## 🔴 CRITICAL: READ EXISTING CONTEXT FIRST
    Before designing, READ the gathered context to understand what already exists:
    ```bash
    cat .workflow/gathered_context.yml 2>/dev/null
    ```

    This tells you:
    - **Existing models** you can reference or extend (don't recreate!)
    - **Existing APIs** you can reuse
    - **Existing components** you can compose
    - **Dependency chains** to understand impact
    - **Patterns** to follow for consistency

    ## DESIGN PRINCIPLES WITH CONTEXT

    1. **REUSE before CREATE**: If model_user exists, use it - don't create model_customer
    2. **EXTEND over DUPLICATE**: Add fields to existing models when appropriate
    3. **FOLLOW PATTERNS**: Match existing naming (camelCase, PascalCase, file paths)
    4. **DECLARE DEPENDENCIES**: Link new entities to existing ones explicitly

    ## DESIGN PROCESS

    ### Phase A: Analyze Requirements + Existing Context
    1. Read gathered_context.yml for existing entities
    2. Break down "$FEATURE" into user stories
    3. Identify what ALREADY EXISTS vs what's NEW
    4. Plan integrations with existing entities

    ### Phase B: Design Data Layer (LAYER 1)
    Create data_models section with:
    - id: model_<name>
    - 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_<verb>_<resource>
    - method: GET|POST|PUT|PATCH|DELETE
    - path: /api/<path>
    - 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_<name>
    - path: /<route>
    - data_needs: [{api_id, purpose, on_load}]
    - components: [component_ids]
    - auth: {required, roles, redirect}

    Create components section with:
    - id: component_<name>
    - 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: <timestamp>
    status: draft
    revision: 1

    data_models:
      - id: model_<name>
        name: <Name>
        # ... full model definition

    api_endpoints:
      - id: api_<verb>_<resource>
        method: <METHOD>
        path: /api/<path>
        # ... full endpoint definition

    pages:
      - id: page_<name>
        path: /<route>
        # ... full page definition

    components:
      - id: component_<name>
        name: <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:

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:

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.4.6: Build Entity Relationship Graph [MANDATORY]

Build the relationship graph for impact analysis and validation:

python3 skills/guardrail-orchestrator/scripts/build_relations.py \
  --design-doc .workflow/versions/$VERSION_ID/design/design_document.yml \
  --project-dir . \
  --output .workflow/versions/$VERSION_ID/relations.yml

This generates:

  • relations.yml - Entity relationship graph with:
    • Database → API → Component → Page dependency chains
    • Impact chains (what breaks if X changes)
    • Type mappings for validation
    • Circular dependency detection

Used for:

  • Change impact analysis during updates
  • Type alignment validation during review
  • Relationship integrity checks

BLOCK IF: Generation fails or circular dependencies detected

Step 2.5: Verify Generated Artifacts [MANDATORY]

# 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]

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, types generated, phase = IMPLEMENTING

IF AUTO_MODE = true:

python3 skills/guardrail-orchestrator/scripts/workflow_manager.py approve design
python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition DESIGN_APPROVED

Output: " Design auto-approved. Generating types..."

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 3.5: TYPE GENERATION (MANDATORY)

═══════════════════════════════════════════════════════════════

Entry Condition: Phase = DESIGN_APPROVED Exit Condition: TypeScript types generated, phase = IMPLEMENTING

CRITICAL: This phase generates shared types that ALL agents MUST use. Skipping this phase will result in type mismatches between frontend and backend.

Step 3.5.1: Generate TypeScript Types [MANDATORY]

python3 skills/guardrail-orchestrator/scripts/generate_types.py \
  .workflow/versions/$VERSION_ID/design/design_document.yml \
  --output-dir types

This generates:

  • types/types.ts - All data model interfaces
  • types/component-props.ts - Component prop interfaces with typed objects
  • types/api-types.ts - Request/response types for API endpoints
  • types/index.ts - Re-exports all types

Step 3.5.2: Verify Types Generated [MANDATORY]

# Check all type files exist
ls types/types.ts types/component-props.ts types/api-types.ts types/index.ts

# Show type summary
echo "=== Generated Types ==="
grep "^export interface" types/types.ts | wc -l
grep "^export interface" types/component-props.ts | wc -l
grep "^export interface" types/api-types.ts | wc -l

BLOCK IF: Any type file missing → Error: "Type generation failed"

Step 3.5.3: Display Type Generation Summary [MANDATORY]

╔══════════════════════════════════════════════════════════════╗
║ 📋 TYPES GENERATED                                           ║
╠══════════════════════════════════════════════════════════════╣
║ types/types.ts           - X model interfaces                ║
║ types/component-props.ts - X component prop interfaces       ║
║ types/api-types.ts       - X API request/response types      ║
╠══════════════════════════════════════════════════════════════╣
║ ⚠️  ALL AGENTS MUST:                                         ║
║   1. Import types from @/types                               ║
║   2. Use typed object props (not flat props)                 ║
║   3. Implement ALL events from design                        ║
╚══════════════════════════════════════════════════════════════╝

Step 3.5.4: Generate Implementation Context Summary [MANDATORY]

Create a consolidated context file that agents MUST read before EVERY task:

# Create implementation context summary
cat > .workflow/versions/$VERSION_ID/IMPLEMENTATION_CONTEXT.md << CONTEXT_EOF
# Implementation Context - VERSION $VERSION_ID

## ⚠️ AGENTS MUST READ THIS FILE BEFORE EVERY TASK

---

## 1. GENERATED TYPES (Source of Truth)

### Model Types (types/types.ts)
```typescript
$(cat types/types.ts | grep -A 5 "^export interface" | head -50)

Component Props (types/component-props.ts)

$(cat types/component-props.ts | grep -A 10 "^export interface" | head -80)

API Types (types/api-types.ts)

$(cat types/api-types.ts | grep -A 5 "^export interface" | head -50)

2. MANDATORY IMPORT PATTERNS

For Components:

// ✅ CORRECT - Always import from generated types
import type { ComponentNameProps } from '@/types/component-props';
import type { Song, Album, Artist } from '@/types';

// ❌ WRONG - Never define your own interfaces
interface ComponentNameProps { ... }

For API Routes:

// ✅ CORRECT - Always import from generated types
import type { CreateSongRequest, CreateSongResponse } from '@/types/api-types';
import type { Song } from '@/types';

// ❌ WRONG - Never define your own types
type CreateSongRequest = { ... }

3. PROP STRUCTURE RULES

Object Props (CORRECT):

// Design says: song: Song
function SongCard({ song, showArtist, onPlay }: SongCardProps) {
  return <div>{song.title} by {song.artist?.name}</div>;
}

Flat Props (WRONG - DO NOT DO THIS):

// ❌ WRONG - Flattening the Song object
function SongCard({ id, title, artistName }: SongCardProps) {
  return <div>{title} by {artistName}</div>;
}

4. EVENT IMPLEMENTATION

All events from design MUST be implemented:

// If design specifies: onPlay, onAddToPlaylist, onShare
function SongCard({ song, onPlay, onAddToPlaylist, onShare }: SongCardProps) {
  return (
    <div>
      <button onClick={() => onPlay?.({ songId: song.id })}>Play</button>
      <button onClick={() => onAddToPlaylist?.({ songId: song.id })}>Add</button>
      <button onClick={() => onShare?.({ songId: song.id })}>Share</button>
    </div>
  );
}

5. REFERENCE FILES

Before implementing ANY task, read:

  1. This file: .workflow/versions/$VERSION_ID/IMPLEMENTATION_CONTEXT.md
  2. Task file: .workflow/versions/$VERSION_ID/tasks/task_<entity_id>.yml
  3. Context file: .workflow/versions/$VERSION_ID/contexts/<entity_id>.yml
  4. Generated types: types/types.ts, types/component-props.ts, types/api-types.ts

6. VALIDATION COMMAND

After implementing, always run:

python3 skills/guardrail-orchestrator/scripts/workflow_manager.py validate --checklist

CONTEXT_EOF


**Display confirmation:**

╔══════════════════════════════════════════════════════════════╗ ║ 📋 IMPLEMENTATION CONTEXT GENERATED ║ ╠══════════════════════════════════════════════════════════════╣ ║ File: .workflow/versions/$VERSION_ID/IMPLEMENTATION_CONTEXT.md║ ║ ║ ║ ⚠️ ALL AGENTS MUST READ THIS FILE BEFORE EVERY TASK ║ ╚══════════════════════════════════════════════════════════════╝


#### Step 3.5.5: Transition to IMPLEMENTING [MANDATORY]
```bash
python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition IMPLEMENTING

═══════════════════════════════════════════════════════════════

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]

python3 skills/guardrail-orchestrator/scripts/workflow_manager.py status

BLOCK IF: Phase is not IMPLEMENTING

Step 4.2: Load Contract and Tasks [MANDATORY]

# 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-implementer"
  prompt: |
    # BACKEND TEAM - VERSION $VERSION_ID

    ## AGENT INSTRUCTIONS
    Read and follow: .claude/agents/backend-implementer.md

    ## YOUR MISSION
    Implement ALL backend tasks (models + APIs) for this workflow.
    You own the entire backend layer.

    ## 🔴 MANDATORY: READ CONTEXT BEFORE EVERY TASK

    ### FIRST - Read Implementation Context (DO THIS NOW)
    ```bash
    # READ THIS FILE FIRST - Contains all rules and type definitions
    cat .workflow/versions/$VERSION_ID/IMPLEMENTATION_CONTEXT.md
    ```

    This file contains:
    - All generated type interfaces
    - Mandatory import patterns
    - Prop structure rules
    - Validation requirements

    ### THEN - For EACH task, read these files:
    ```bash
    # 1. Task definition
    cat .workflow/versions/$VERSION_ID/tasks/task_<entity_id>.yml

    # 2. Entity context with full schema
    cat .workflow/versions/$VERSION_ID/contexts/<entity_id>.yml

    # 3. Generated types (verify before implementing)
    cat types/types.ts
    cat types/api-types.ts
    ```

    ## ⚠️ CRITICAL: TYPE COMPLIANCE (MANDATORY)

    ### Import Types in ALL Files
    ```typescript
    // ✅ CORRECT - Import from generated types
    import type { User, Song, Album } from '@/types';
    import type { CreateUserRequest, CreateUserResponse } from '@/types/api-types';

    // ❌ WRONG - Do NOT define your own types
    interface User { ... }  // FORBIDDEN
    ```

    ### Match Design Exactly
    - Field names MUST match design document
    - Types MUST match generated types
    - All fields from design MUST be implemented

    ## 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)
       - READ context file FIRST for field definitions
       - Add to prisma/schema.prisma matching design EXACTLY
       - Run: npx prisma generate

    2. **Then**: Implement ALL API endpoints (Layer 2)
       - READ context file FIRST for request/response schemas
       - Create app/api/*/route.ts files
       - Import types from @/types and @/types/api-types
       - Implement request validation matching design
       - Return responses matching generated types

    ## FOR EACH TASK (MANDATORY SEQUENCE)
    1. ⚠️ READ .workflow/versions/$VERSION_ID/IMPLEMENTATION_CONTEXT.md
    2. READ task file: .workflow/versions/$VERSION_ID/tasks/task_*.yml
    3. READ context file: .workflow/versions/$VERSION_ID/contexts/<entity_id>.yml
    4. VERIFY generated types: types/types.ts, types/api-types.ts
    5. IMPLEMENT following the design EXACTLY
    6. VERIFY with TypeScript

    ## VERIFICATION
    After all tasks:
    ```bash
    npx prisma generate 2>&1 || true
    npx tsc --noEmit 2>&1 || true
    python3 skills/guardrail-orchestrator/scripts/workflow_manager.py validate --checklist
    ```

    ## OUTPUT FORMAT
    ```
    === BACKEND TEAM COMPLETE ===

    Context files read:
      - IMPLEMENTATION_CONTEXT.md ✓
      - X task files ✓
      - X context files ✓

    Models implemented:
      - model_xxx: prisma/schema.prisma ✓

    APIs implemented:
      - api_xxx: app/api/.../route.ts ✓
      - api_yyy: app/api/.../route.ts ✓

    Type compliance:
      - Types imported from @/types ✓
      - All fields match design ✓

    TypeScript: PASS/FAIL
    Prisma: PASS/FAIL
    Validation: PASS/FAIL
    ```
Step 4.3.2: Spawn Frontend Team Agent [IN PARALLEL]
Use Task tool with:
  subagent_type: "frontend-implementer"
  prompt: |
    # FRONTEND TEAM - VERSION $VERSION_ID

    ## AGENT INSTRUCTIONS
    Read and follow: .claude/agents/frontend-implementer.md

    ## YOUR MISSION
    Implement ALL frontend tasks (components + pages) for this workflow.
    You own the entire frontend layer.

    ## 🔴 MANDATORY: READ CONTEXT BEFORE EVERY TASK

    ### FIRST - Read Implementation Context (DO THIS NOW)
    ```bash
    # READ THIS FILE FIRST - Contains all rules and type definitions
    cat .workflow/versions/$VERSION_ID/IMPLEMENTATION_CONTEXT.md
    ```

    This file contains:
    - All generated type interfaces
    - Mandatory import patterns
    - Prop structure rules (object vs flat)
    - Event implementation requirements
    - Validation requirements

    ### THEN - For EACH task, read these files:
    ```bash
    # 1. Task definition
    cat .workflow/versions/$VERSION_ID/tasks/task_<entity_id>.yml

    # 2. Entity context with props, events, and component hierarchy
    cat .workflow/versions/$VERSION_ID/contexts/<entity_id>.yml

    # 3. Generated types (verify before implementing)
    cat types/component-props.ts
    cat types/types.ts
    ```

    ## ⚠️ CRITICAL: TYPE COMPLIANCE (MANDATORY)

    ### Import Types in ALL Files
    ```typescript
    // ✅ CORRECT - Import from generated types
    import type { SongCardProps } from '@/types/component-props';
    import type { Song, Album, Artist } from '@/types';

    // ❌ WRONG - Do NOT define your own props
    interface SongCardProps { ... }  // FORBIDDEN
    ```

    ### Use Object Props (NOT Flat Props)
    ```typescript
    // ✅ CORRECT - Use typed object from design
    function SongCard({ song, showArtist, onPlay }: SongCardProps) {
      return <div>{song.title} by {song.artist?.name}</div>;
    }

    // ❌ WRONG - Flattening the object
    function SongCard({ id, title, artistName }: SongCardProps) {
      return <div>{title} by {artistName}</div>;
    }
    ```

    ### Implement ALL Events from Design
    Check component-props.ts for event handlers and implement ALL of them.

    ## 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
    ```

    ## FOR EACH TASK (MANDATORY SEQUENCE)
    1. ⚠️ READ .workflow/versions/$VERSION_ID/IMPLEMENTATION_CONTEXT.md
    2. READ task file: .workflow/versions/$VERSION_ID/tasks/task_*.yml
    3. READ context file: .workflow/versions/$VERSION_ID/contexts/<entity_id>.yml
    4. VERIFY generated types: types/component-props.ts, types/types.ts
    5. CHECK props interface - note ALL props and events
    6. IMPLEMENT following the design EXACTLY
    7. VERIFY all events are implemented

    ## IMPLEMENTATION CHECKLIST (FOR EACH COMPONENT)
    - [ ] Read IMPLEMENTATION_CONTEXT.md
    - [ ] Read context file for props and events
    - [ ] Import props interface from @/types/component-props
    - [ ] Import model types from @/types
    - [ ] Use object props (song: Song, not id, title, ...)
    - [ ] Implement ALL event handlers from design
    - [ ] Destructure props matching design EXACTLY

    ## VERIFICATION
    After all tasks:
    ```bash
    npx tsc --noEmit 2>&1 || true
    python3 skills/guardrail-orchestrator/scripts/workflow_manager.py validate --checklist
    ```

    ## OUTPUT FORMAT
    ```
    === FRONTEND TEAM COMPLETE ===

    Context files read:
      - IMPLEMENTATION_CONTEXT.md ✓
      - X task files ✓
      - X context files ✓

    Components implemented:
      - component_xxx: app/components/Xxx.tsx ✓
        Props: Imported from @/types/component-props ✓
        Events: onPlay, onAddToPlaylist ✓

    Pages implemented:
      - page_xxx: app/xxx/page.tsx ✓

    Type compliance:
      - Types imported from @/types ✓
      - Object props used (not flat) ✓
      - All events implemented ✓

    TypeScript: PASS/FAIL
    Validation: 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: Implementation Validation [MANDATORY]

Run implementation validation with checklist to verify design compliance:

# Run implementation validator
python3 skills/guardrail-orchestrator/scripts/workflow_manager.py validate --checklist
VALIDATE_EXIT=$?
echo "VALIDATE_EXIT=$VALIDATE_EXIT"

Validation checks:

  • Components import from @/types/component-props
  • Components use object props (not flat props)
  • All events from design are implemented
  • API routes exist and match design
  • Prisma models match design fields

BLOCK IF: VALIDATE_EXIT != 0 → Show errors and halt

Step 4.6: Post-Implementation Verification [MANDATORY]

# Verify build passes
npm run build
echo "Exit code: $?"

BLOCK IF: Exit code != 0 → Error with build output

# 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.1: Display Implementation Checklist [MANDATORY]

# Show the implementation checklist
python3 skills/guardrail-orchestrator/scripts/workflow_manager.py checklist show
╔══════════════════════════════════════════════════════════════╗
║ 📋 IMPLEMENTATION CHECKLIST                                  ║
╠══════════════════════════════════════════════════════════════╣
║                                                              ║
║ COMPONENTS                                                   ║
║   ✅ component_song_card     - types imported, events ok     ║
║   ✅ component_album_card    - types imported, events ok     ║
║   ❌ component_player        - missing onSeek event          ║
║                                                              ║
║ APIs                                                         ║
║   ✅ api_get_songs           - route exists, methods ok      ║
║   ✅ api_create_song         - route exists, methods ok      ║
║                                                              ║
║ MODELS                                                       ║
║   ✅ model_song              - all fields match design       ║
║   ✅ model_album             - all fields match design       ║
║                                                              ║
╠══════════════════════════════════════════════════════════════╣
║ Errors: X  |  Warnings: Y  |  Passed: Z                      ║
╚══════════════════════════════════════════════════════════════╝

BLOCK IF: Any errors in checklist → Fix errors before proceeding

Step 4.7: Validate API Contract Compliance [MANDATORY]

# 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.8: 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.9: Transition [MANDATORY]

python3 skills/guardrail-orchestrator/scripts/workflow_manager.py transition INTEGRATING

═══════════════════════════════════════════════════════════════

PHASE 4.5: INTEGRATING (Connect New Features to Existing Project)

═══════════════════════════════════════════════════════════════

Entry Condition: Phase = INTEGRATING (verified) Exit Condition: New features integrated with existing project, navigation/imports/wiring complete

PURPOSE: This phase ensures newly implemented components, pages, and APIs are actually usable in the application - not just isolated implementations.

Step 4.5.1: Verify Phase State [MANDATORY]

python3 skills/guardrail-orchestrator/scripts/workflow_manager.py status

BLOCK IF: Phase is not INTEGRATING

Step 4.5.2: Discover Existing Project Structure [MANDATORY]

# Find navigation files
echo "=== Navigation Files ==="
find app components -name '*nav*' -o -name '*sidebar*' -o -name '*menu*' 2>/dev/null | head -10

# Find layout files
echo "=== Layout Files ==="
find app -name 'layout.tsx' 2>/dev/null

# Find existing routes/pages
echo "=== Existing Pages ==="
find app -name 'page.tsx' 2>/dev/null | head -20

Step 4.5.3: Spawn Integrator Agent [MANDATORY]

CRITICAL: The integrator agent connects new implementations to the existing project.

Use Task tool with:
  subagent_type: "general-purpose"
  prompt: |
    # INTEGRATOR AGENT - VERSION $VERSION_ID

    ## AGENT INSTRUCTIONS
    Read and follow: .claude/agents/integrator.yml

    ## YOUR MISSION
    Connect newly implemented components, pages, and APIs with the existing project.
    Without integration, new features are useless - they exist but users can't access them.

    ## 🔴 MANDATORY: READ CONTEXT FIRST
    ```bash
    cat .workflow/versions/$VERSION_ID/IMPLEMENTATION_CONTEXT.md
    cat .workflow/versions/$VERSION_ID/design/design_document.yml
    ```

    ## INTEGRATION TASKS

    ### 1. NAVIGATION INTEGRATION
    Find where navigation/sidebar is defined and add links to new pages:

    ```bash
    # Find navigation components
    grep -r "navItems\|menuItems\|navigation" app/ components/ --include="*.tsx" -l
    ```

    For each new page in design_document.yml:
    - Add a navigation link/menu item
    - Use the correct path from design
    - Import any needed icons

    ### 2. COMPONENT USAGE INTEGRATION
    Import and use new components in appropriate places:

    For each new component:
    - Identify which pages should use it (from design data_needs)
    - Import the component
    - Add to JSX in appropriate location
    - Pass required props

    ### 3. API WIRING
    Connect new APIs to frontend components:

    For pages with data_needs in design:
    - Add useSWR/fetch calls for the API
    - Handle loading and error states
    - Pass data to components

    ### 4. BARREL EXPORTS
    Update index.ts files to export new components:

    ```bash
    # Find index files
    find components lib -name 'index.ts' 2>/dev/null
    ```

    For each new component:
    - Add export to nearest index.ts

    ## DISCOVERY COMMANDS
    ```bash
    # Find existing navigation structure
    grep -rn "href=\|to=" app/ components/ --include="*.tsx" | head -20

    # Find existing data fetching patterns
    grep -rn "useSWR\|useQuery\|fetch(" app/ --include="*.tsx" | head -20

    # Find existing component imports
    grep -rn "from '@/components" app/ --include="*.tsx" | head -20
    ```

    ## OUTPUT FORMAT
    ```
    === INTEGRATION COMPLETE ===

    NAVIGATION UPDATES:
      ✅ app/layout.tsx: Added link to /songs
      ✅ components/Sidebar.tsx: Added Songs menu item

    COMPONENT INTEGRATIONS:
      ✅ app/dashboard/page.tsx: Imported and used SongList
      ✅ app/songs/page.tsx: Wired to /api/songs

    API WIRING:
      ✅ app/songs/page.tsx: Added useSWR('/api/songs')

    BARREL EXPORTS:
      ✅ components/index.ts: Added SongCard, SongList exports

    TypeScript: PASS/FAIL
    Build: PASS/FAIL
    ```

Step 4.5.4: Validate Integration [MANDATORY]

# Run integration validator
python3 skills/guardrail-orchestrator/scripts/validate_integration.py \
  --design-doc .workflow/versions/$VERSION_ID/design/design_document.yml \
  --project-dir .
INTEGRATION_EXIT=$?
echo "INTEGRATION_EXIT=$INTEGRATION_EXIT"

Validates:

  • New pages are accessible via navigation
  • New components are imported and used
  • New APIs are called from frontend
  • Barrel exports are updated

BLOCK IF: INTEGRATION_EXIT = 2 (critical failures) WARNING IF: INTEGRATION_EXIT = 1 (warnings)

Step 4.5.5: Verify Build Still Passes [MANDATORY]

npm run build
BUILD_EXIT=$?
echo "BUILD_EXIT=$BUILD_EXIT"

BLOCK IF: Build fails after integration changes

Step 4.5.6: Display Integration Summary [MANDATORY]

╔══════════════════════════════════════════════════════════════╗
║ 🔗 INTEGRATION COMPLETE                                      ║
╠══════════════════════════════════════════════════════════════╣
║                                                              ║
║ NAVIGATION:                                                  ║
║   ✅ /songs added to sidebar                                 ║
║   ✅ /albums added to sidebar                                ║
║                                                              ║
║ COMPONENT USAGE:                                             ║
║   ✅ SongCard used in 2 files                                ║
║   ✅ AlbumCard used in 1 file                                ║
║                                                              ║
║ API WIRING:                                                  ║
║   ✅ /api/songs called from app/songs/page.tsx               ║
║   ✅ /api/albums called from app/albums/page.tsx             ║
║                                                              ║
║ BUILD:      PASS ✓                                           ║
║ TYPESCRIPT: PASS ✓                                           ║
║                                                              ║
╠══════════════════════════════════════════════════════════════╣
║ New features are now accessible in the application!          ║
╚══════════════════════════════════════════════════════════════╝

Step 4.5.7: Transition to Review [MANDATORY]

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]

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]
npm run build 2>&1
BUILD_EXIT=$?
Step 5.2b: Generate Implementation Visualization [MANDATORY]

MUST show user what was built before review:

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]
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:

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: "workflow-validator"
  prompt: |
    # REVIEWER AGENT - VERSION $VERSION_ID

    ## AGENT INSTRUCTIONS
    Read and follow: .claude/agents/workflow-validator.md

    ## 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]
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]

python3 skills/guardrail-orchestrator/scripts/workflow_manager.py status

BLOCK IF: Phase is not SECURITY_REVIEW

Step 5.5.2: Run Security Scanner [MANDATORY]

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]

# 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]

# 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:

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]

python3 skills/guardrail-orchestrator/scripts/workflow_manager.py status

BLOCK IF: Phase is not COMPLETING

Step 7.2: Update Task Statuses [MANDATORY]

# 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]

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

# 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

# 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