# Vibn Phase-Based Project System

⚠️ **LEGACY DOCUMENTATION** - This document describes the old phase system.

**The new system is documented in `/lib/ai/types.ts` and uses a workflow-based architecture.**

New phases:
1. **Collector** - Document intake (conversational)
2. **Extractor** - Insight extraction (JSON)
3. **Vision** - Vision synthesis (JSON)
4. **MVP** - MVP planning (JSON)
5. **Marketing** - Marketing strategy (JSON, parallel)

See `/lib/ai/orchestrator.ts` for the state machine implementation.

---

## The 5 Phases (Legacy)

### Phase 1: Gathering
**Agent:** Gathering Agent  
**Goal:** Collect and analyze all project materials one item at a time

**What it does:**
- Goes through each context source (docs, GitHub, sessions)
- Extracts key insights from each
- Confirms each insight with user
- Stores confirmed insights

**Firestore Schema:**
```javascript
{
  currentPhase: 'gathering',
  phaseStatus: 'in_progress', // 'not_started' | 'in_progress' | 'completed'
  phaseData: {
    gathering: {
      startedAt: timestamp,
      insights: [
        {
          id: 'insight_1',
          source: 'Patient History Overview',
          sourceType: 'document',
          sourceId: 'QeC8EIDSkud1jrt6xSyF',
          insight: 'Using evidence-based diagnostic methods',
          extractedAt: timestamp,
          confirmed: true,
          confirmedAt: timestamp,
          usedInVision: false,
          category: 'feature'
        }
      ],
      completedAt: timestamp
    }
  }
}
```

**Completion Criteria:**
- All context sources analyzed
- All insights confirmed by user
- User says "That's everything" or "Ready to proceed"

---

### Phase 2: Vision
**Agent:** Vision Agent  
**Goal:** Extract Product Vision Board from confirmed insights

**What it does:**
- Reads all confirmed insights from Phase 1
- Extracts the 8 vision nodes
- Fills out 4-block Product Vision Board
- Gets user approval

**Firestore Schema:**
```javascript
{
  currentPhase: 'vision',
  phaseStatus: 'in_progress',
  phaseData: {
    vision: {
      startedAt: timestamp,
      data: {
        vision: 'One-sentence vision',
        who: 'Target users',
        need: 'Problem they face',
        product: 'Solution features',
        validation: 'Go-to-market strategy'
      },
      approved: true,
      approvedAt: timestamp,
      completedAt: timestamp
    }
  }
}
```

**Completion Criteria:**
- Vision board complete
- User approves with "Yes" or "Looks good"

---

### Phase 3: Scope
**Agent:** Scope Agent  
**Goal:** Define V1 MVP features

**What it does:**
- Takes vision board from Phase 2
- Helps user prioritize features (must-have, should-have, nice-to-have)
- Defines timeline estimate
- Creates V1 feature list

**Firestore Schema:**
```javascript
{
  currentPhase: 'scope',
  phaseStatus: 'in_progress',
  phaseData: {
    scope: {
      startedAt: timestamp,
      v1Features: ['Feature 1', 'Feature 2'],
      timeline: '3-6 months',
      priorities: {
        mustHave: [],
        shouldHave: [],
        niceToHave: []
      },
      completedAt: timestamp
    }
  }
}
```

---

### Phase 4: Blueprint
**Agent:** Blueprint Agent  
**Goal:** Technical architecture design

**What it does:**
- Takes V1 scope from Phase 3
- Defines tech stack
- Designs database schema
- Plans API structure

---

### Phase 5: Build
**Agent:** Build Agent (Future)  
**Goal:** Implementation guidance

---

## Why Phase Tracking?

### ✅ Prevents Repetition
Once Phase 1 is complete, you never re-analyze documents. Phase 2 uses the stored insights.

### ✅ User Confidence
User sees clear progress: "Gathering: ✅ | Vision: ✅ | Scope: 🔄"

### ✅ Resumable
User can leave and come back. The agent knows exactly where they left off.

### ✅ Traceable
Every insight is linked to its source. Vision board items trace back to specific documents.

---

## API Usage

### Get Current Phase
```typescript
GET /api/projects/phase?projectId=xxx

Response:
{
  currentPhase: 'gathering',
  phaseStatus: 'in_progress',
  phaseData: { /* phase-specific data */ },
  phaseHistory: []
}
```

### Start a Phase
```typescript
POST /api/projects/phase
{
  projectId: 'xxx',
  action: 'start',
  phase: 'gathering'
}
```

### Complete a Phase
```typescript
POST /api/projects/phase
{
  projectId: 'xxx',
  action: 'complete'
}
```

### Save Phase Data
```typescript
POST /api/projects/phase
{
  projectId: 'xxx',
  action: 'save_data',
  data: { /* phase-specific data */ }
}
```

### Add Gathering Insight
```typescript
POST /api/projects/phase
{
  projectId: 'xxx',
  action: 'add_insight',
  data: {
    id: 'insight_1',
    source: 'Document Name',
    sourceType: 'document',
    sourceId: 'doc_id',
    insight: 'Key finding...',
    extractedAt: timestamp,
    confirmed: true,
    confirmedAt: timestamp,
    usedInVision: false,
    category: 'feature'
  }
}
```

---

## Agent Selection Logic

```typescript
// In /api/ai/chat/route.ts

// 1. Check project phase
const projectPhase = project.currentPhase || 'gathering';
const phaseStatus = project.phaseStatus || 'not_started';

// 2. Select appropriate agent
let agentPrompt;
switch (projectPhase) {
  case 'gathering':
    agentPrompt = GATHERING_AGENT_PROMPT;
    break;
  case 'vision':
    agentPrompt = VISION_AGENT_PROMPT;
    break;
  case 'scope':
    agentPrompt = SCOPE_AGENT_PROMPT;
    break;
  // ... etc
}

// 3. Pass phase data to agent
const contextPayload = {
  ...existingContext,
  currentPhase: projectPhase,
  phaseStatus: phaseStatus,
  phaseData: project.phaseData || {}
};
```

---

## Migration Plan

### For Existing Projects
Run a migration script to add phase fields:

```javascript
// scripts/add-phase-tracking.ts
const projects = await adminDb.collection('projects').get();

for (const doc of projects.docs) {
  await doc.ref.update({
    currentPhase: 'gathering',
    phaseStatus: 'not_started',
    phaseData: {},
    phaseHistory: []
  });
}
```

---

## Next Steps

1. ✅ Phase tracking schema created
2. ✅ Phase API endpoints created
3. ✅ New projects auto-initialize with gathering phase
4. ⏳ Create Gathering Agent prompt
5. ⏳ Update chat route to use phase-based agent selection
6. ⏳ Build UI to show phase progress
7. ⏳ Create migration script for existing projects

