# Feature Factory
#
# From user story to deployed feature. A captain agent coordinates a team
# of specialists to design, implement, test, and document a complete feature.
# Watch an entire engineering team's workflow automated.
#
# Usage: Describe a feature and watch it get built.

input feature: "Description of the feature to implement"
input codebase_context: "Brief description of the codebase (optional)"

# The Captain: Coordinates everything, maintains context across the build
agent captain:
  model: sonnet
  persist: project     # Remembers across features
  prompt: """
You are the Tech Lead coordinating feature development.

Your responsibilities:
- Break features into implementable tasks
- Review all work before it merges
- Maintain architectural consistency
- Make technical decisions when needed
- Keep the build moving forward

You've worked on this codebase before. Reference prior decisions.
"""

# Specialists
agent architect:
  model: opus
  prompt: """
You are a software architect. You design systems that are:
- Simple (no unnecessary complexity)
- Extensible (but not over-engineered)
- Consistent with existing patterns

Produce clear technical designs with file paths and interfaces.
"""

agent implementer:
  model: opus
  prompt: """
You are a senior developer. You write:
- Clean, idiomatic code
- Following existing project patterns
- With clear variable names and structure
- Minimal but sufficient comments

You implement exactly what's specified, nothing more.
"""

agent tester:
  model: sonnet
  prompt: """
You are a QA engineer. You write:
- Unit tests for individual functions
- Integration tests for workflows
- Edge case tests
- Clear test names that document behavior

Aim for high coverage of the new code.
"""

agent documenter:
  model: sonnet
  prompt: """
You are a technical writer. You create:
- Clear API documentation
- Usage examples
- README updates
- Inline JSDoc/docstrings where needed

Match existing documentation style.
"""

# ============================================================================
# Phase 1: Understand the codebase
# ============================================================================

session: captain
  prompt: """
Starting feature implementation: {feature}

First, let me understand the current codebase.
"""

let codebase_analysis = session "Analyze codebase structure"
  prompt: """
Explore the codebase to understand:
1. Directory structure and organization
2. Key patterns used (state management, API style, etc.)
3. Testing approach
4. Where this feature would fit

Use Glob and Read tools to explore. Be thorough but efficient.
"""
  context: codebase_context

# ============================================================================
# Phase 2: Design
# ============================================================================

let design = session: architect
  prompt: """
Design the implementation for: {feature}

Based on the codebase analysis, produce:
1. High-level approach (2-3 sentences)
2. Files to create/modify (with paths)
3. Key interfaces/types to define
4. Integration points with existing code
5. Potential risks or decisions needed

Keep it simple. Match existing patterns.
"""
  context: { feature, codebase_analysis }

# Captain reviews design
let design_approved = resume: captain
  prompt: """
Review this design:
- Does it fit our architecture?
- Is it the simplest approach?
- Any risks or concerns?
- Any decisions I need to make?

Return APPROVED or specific concerns.
"""
  context: design

if **design needs adjustment**:
  design = session: architect
    prompt: "Revise design based on tech lead feedback"
    context: { design, design_approved }

# ============================================================================
# Phase 3: Implementation
# ============================================================================

resume: captain
  prompt: "Design approved. Breaking into implementation tasks."
  context: design

let tasks = resume: captain
  prompt: """
Break the design into ordered implementation tasks.
Each task should be:
- Small enough to implement in one session
- Have clear acceptance criteria
- List file(s) to modify

Return as numbered list with dependencies.
"""
  context: design

# Implement each task sequentially
for task in tasks:
  resume: captain
    prompt: "Starting task: {task}"

  let implementation = session: implementer
    prompt: """
Implement this task:
{task}

Follow the design spec. Match existing code patterns.
Write the actual code using Edit/Write tools.
"""
    context: { task, design, codebase_analysis }
    retry: 2
    backoff: exponential

  # Captain reviews each piece
  let review = resume: captain
    prompt: """
Review this implementation:
- Does it match the design?
- Code quality acceptable?
- Any issues to fix before continuing?

Be specific if changes needed.
"""
    context: { task, implementation }

  if **implementation needs fixes**:
    session: implementer
      prompt: "Fix issues noted in review"
      context: { implementation, review }

# ============================================================================
# Phase 4: Testing
# ============================================================================

resume: captain
  prompt: "Implementation complete. Starting test phase."

let tests = session: tester
  prompt: """
Write tests for the new feature:
1. Unit tests for new functions/methods
2. Integration tests for the feature flow
3. Edge cases and error handling

Use the project's existing test framework and patterns.
Actually create the test files.
"""
  context: { design, codebase_analysis }

# Run tests
let test_results = session "Run test suite"
  prompt: """
Run all tests:
1. npm test / pytest / cargo test (whatever this project uses)
2. Report results
3. If failures, identify which tests failed and why
"""

loop until **all tests pass** (max: 5):
  if **tests are failing**:
    let fix = session: implementer
      prompt: "Fix failing tests. Either fix the code or fix the test if it's wrong."
      context: test_results

    test_results = session "Re-run tests after fix"
      prompt: "Run tests again and report results"

# ============================================================================
# Phase 5: Documentation
# ============================================================================

resume: captain
  prompt: "Tests passing. Final phase: documentation."

parallel:
  api_docs = session: documenter
    prompt: """
Document the new feature's API:
- Function/method signatures
- Parameters and return values
- Usage examples
- Add to existing docs structure
"""
    context: design

  readme_update = session: documenter
    prompt: """
Update README if needed:
- Add feature to feature list
- Add usage example if user-facing
- Update any outdated sections
"""
    context: { design, codebase_analysis }

# ============================================================================
# Phase 6: Final Review & Commit
# ============================================================================

resume: captain
  prompt: """
Feature complete! Final review:

1. All tasks implemented
2. Tests passing
3. Documentation updated

Prepare final summary and create commit.
"""
  context: { design, tests, api_docs }

session "Create feature commit"
  prompt: """
Stage all changes and create a well-structured commit:
1. git add -A
2. git commit with message following conventional commits:
   feat: {feature short description}

   - Implementation details
   - Tests added
   - Docs updated
"""

# Final report
output summary = resume: captain
  prompt: """
Feature Factory Complete!

Generate final report:
- Feature: {feature}
- Files created/modified: [list]
- Tests added: [count]
- Time from start to finish
- Any notes for future work

This feature is ready for PR review.
"""
