{%- set md = multi_developer if multi_developer else {} -%}
{%- set identity_cfg = md.get('identity', {}) -%}
{%- set context_cfg = md.get('context', {}) -%}
{%- set collab_cfg = md.get('collaboration', {}) -%}
{%- set dialogue_cfg = md.get('dialogue_protocol', {}) -%}
{%- set primary = identity_cfg.get('primary', 'git_username') -%}
{%- set fallback = identity_cfg.get('fallback', 'system_user') -%}
{%- set normalize = identity_cfg.get('normalize', True) -%}
{%- set agg_file = context_cfg.get('aggregation_file', 'docs/CONTEXT.md') -%}
{%- set auto_sync = context_cfg.get('auto_sync', True) -%}
{%- set collab_file = collab_cfg.get('file', 'docs/developers/COLLABORATION.md') -%}
# X. Multi-Developer/Agent Collaboration Protocol

> **v0.5.0+ supports multiple developers or AI Agents collaborating on the same project**

## 10.1 Collaboration Mode Overview

VibeCollab supports the following collaboration scenarios:
- **Multi-person**: Multiple developers working on the same project
- **Multi-Agent**: Multiple AI Agents dividing different tasks
- **Hybrid**: Human developers + AI Agents in mixed teams

### Core Principles

1. **Independent Workspace**: Each developer maintains their own `CONTEXT.md`, no interference
2. **Smart Aggregation**: System automatically aggregates a global view, providing overall status
3. **Clear Collaboration**: Track task dependencies and handoffs via `COLLABORATION.md`
4. **Auto Identity Detection**: Automatically identifies the current developer based on Git config
5. **Conflict Prevention**: Proactively detects potential cross-developer work conflicts

## 10.2 Directory Structure

Project structure in multi-developer mode:

```
project/
+-- CONTRIBUTING_AI.md
+-- project.yaml
+-- docs/
    +-- CONTEXT.md            # Global aggregated view (auto-generated, read-only)
    +-- CHANGELOG.md          # Global changelog
    +-- DECISIONS.md          # Global decision records
    +-- developers/           # Developer workspaces
        +-- COLLABORATION.md  # Collaboration document
        +-- dev/              # DEV role directory
        |   +-- CONTEXT.md    # DEV's work context
        |   +-- .metadata.yaml # Metadata (role rules, etc.)
        +-- qa/               # QA role directory
            +-- CONTEXT.md
            +-- .metadata.yaml
```

## 10.3 Developer Identity Detection

The system automatically identifies developer identity through the following strategies:

**Detection Strategy**:
- **Primary**: `{{ primary }}` 
  - `git_username`: Uses `git config user.name`
  - `system_user`: Uses system username ($USER / $USERNAME)
  - `manual`: Manually specified (via env var `VIBECOLLAB_DEVELOPER`)
- **Fallback**: `{{ fallback }}` (used when primary fails)
- **Name Normalization**: {{ 'enabled' if normalize else 'disabled' }} (lowercase, spaces to underscores, remove special chars)

**Use CLI to check current identity**:
```bash
vibecollab dev whoami
```

## 10.4 Context Management

### 10.4.1 Independent Context

Each developer maintains their own `CONTEXT.md`, recording:
- Currently active tasks
- Recently completed work
- Pending issues
- Technical debt

**Update command**:
```bash
# Manually update timestamp (usually auto-executed at dialogue end)
vibecollab dev sync
```

### 10.4.2 Global Context Aggregation

The system automatically aggregates all developer contexts into a global view (`{{ agg_file }}`):

- [!] **Read-only file**: Do not manually edit the global CONTEXT.md
- **Aggregated content**: 
  - Overall project status
  - Each developer's work progress
  - Cross-developer dependencies
  - Global technical debt
- **Update timing**: {{ 'Auto-updated at dialogue end' if auto_sync else 'Manual via `vibecollab dev sync`' }}

**Manually trigger aggregation**:
```bash
vibecollab dev sync --aggregate
```

## 10.5 Collaboration Document Management

### 10.5.1 COLLABORATION.md

`{{ collab_file }}` records cross-developer collaboration:

**Contents**:
1. **Task Assignment Matrix**: Who is responsible for what, who are collaborators
2. **Dependencies**: Task dependency relationships
3. **Handoff Records**: Task transfers from one developer to another
4. **Collaboration Conventions**: Team collaboration conventions and rules

**Example Format**:
```markdown
## Task Assignment Matrix

| Task | Owner | Collaborator | Status | Dependencies |
|------|-------|-------------|--------|--------------|
| TASK-DEV-001: User Auth | dev | qa | IN_PROGRESS | - |
| TASK-DEV-002: DB Design | arch | - | DONE | - |
| TASK-DEV-003: API Dev | dev | - | TODO | TASK-DEV-002 |

## Handoff Records

### TASK-DEV-001: User Auth
- **Handoff Time**: 2026-02-10 14:30
- **From**: arch
- **To**: dev
- **Reason**: arch completed DB design, dev takes over frontend integration
- **Notes**: API endpoints are complete, docs at docs/api.md
```

### 10.5.2 View Collaboration Status

```bash
# List all developers
vibecollab dev list

# View specific developer status
vibecollab dev status dev

# Initialize new developer context
vibecollab dev init --developer qa
```

## 10.6 Dialogue Flow Adaptation

### 10.6.1 On Dialogue Start

In multi-developer mode, the AI should at dialogue start:

```
1. Read global aggregated CONTEXT.md (understand overall status)
2. Read current developer's CONTEXT.md (understand own progress)
3. Read COLLABORATION.md (understand collaboration relationships)
4. Identify current developer identity (vibecollab dev whoami)
5. Confirm this dialogue's goal
```

### 10.6.2 On Dialogue End

```
1. Update current developer's CONTEXT.md
2. Update global CHANGELOG.md
3. If cross-developer collaboration occurred, update COLLABORATION.md
4. Auto-trigger context aggregation (generate new global CONTEXT.md)
5. Git commit (record current developer's commit)
```

### 10.6.3 Special Considerations for Multi-Developer Scenarios

**Scenario 1: Task Dependencies**
- DEV's task depends on ARCH's task completion
- AI should annotate dependencies in COLLABORATION.md
- DEV should check dependent task status before starting

**Scenario 2: Task Handoff**
- ARCH completes phase work, hands off to DEV
- Record handoff info in COLLABORATION.md
- DEV reads handoff notes when taking over

**Scenario 3: Parallel Development**
- DEV and QA develop different modules simultaneously
- Each maintains independent CONTEXT.md
- Use global aggregation to track each other's progress

## 10.7 Conflict Detection & Prevention (v0.5.1+)

> **Feature: Automatically detect potential cross-developer work conflicts**

### 10.7.1 Conflict Types

The system detects the following conflict types:

1. **File Conflicts**: Multiple developers modifying the same file
2. **Task Conflicts**: Multiple developers responsible for the same or overlapping tasks
3. **Dependency Conflicts**: Inconsistent or circular task dependencies
4. **Naming Conflicts**: Multiple developers creating identically named functions/classes/modules

### 10.7.2 Conflict Detection Commands

```bash
# Detect conflicts between current developer and others
vibecollab dev conflicts

# Verbose mode (show conflict details)
vibecollab dev conflicts --verbose

# Detect conflicts between specific developers
vibecollab dev conflicts --between dev qa
```

### 10.7.3 Conflict Resolution Flow

```
1. [AI] Detect potential conflict
2. [AI] Annotate conflict warning in CONTEXT.md
3. [AI] Prompt user to check conflict details
4. [Human] Decide resolution:
   - Coordinate division of work
   - Merge work
   - Reassign tasks
5. [AI] Update COLLABORATION.md with resolution
```

### 10.7.4 Conflict Prevention Tips

- [x] Define clear task boundaries, avoid overlapping responsibilities
- [x] Keep COLLABORATION.md task assignments up to date
- [x] Use task dependency annotations to avoid circular dependencies
- [x] Regularly run `vibecollab dev conflicts` checks
- [x] Check global CONTEXT.md before major changes to understand others' progress

## 10.8 CLI Command Reference

```bash
# Developer Identity
vibecollab dev whoami                    # View current developer identity
vibecollab dev switch <developer>        # Switch to specified developer (v0.5.4+)
vibecollab dev switch                    # Interactive developer selection (v0.5.4+)
vibecollab dev switch --clear            # Clear switch, restore default detection (v0.5.4+)

# Developer Management
vibecollab dev list                      # List all developers
vibecollab dev status <developer>        # View developer status
vibecollab dev init --developer <name>   # Initialize new developer

# Context Sync
vibecollab dev sync                      # Update metadata timestamp
vibecollab dev sync --aggregate          # Regenerate global aggregation

# Conflict Detection (v0.5.1+)
vibecollab dev conflicts                 # Detect conflicts
vibecollab dev conflicts --verbose       # Detailed conflict report

# AI Human-Machine Interaction (v0.5.8+)
vibecollab ai ask "question"             # Single-turn AI question (auto-inject project context)
vibecollab ai ask "question" --no-context # Without project context injection
vibecollab ai ask "question" -v          # Show detailed info
vibecollab ai chat                       # Multi-turn dialogue mode (exit/quit/bye to quit)

# Agent Autonomous Mode (v0.5.8+)
vibecollab ai agent plan                 # Read-only analysis, generate action plan
vibecollab ai agent run                  # Single Plan->Execute->Solidify cycle
vibecollab ai agent run --dry-run        # Dry run, output plan only without execution
vibecollab ai agent serve                # Long-running Agent service (default 50 cycles)
vibecollab ai agent serve -n 10          # Specify max cycles
vibecollab ai agent status               # View Agent running status

# Agent Onboarding (v0.7.0+)
vibecollab onboard                       # AI onboarding guide (project overview/progress/todos)
vibecollab onboard -d <developer>        # From specific developer perspective
vibecollab onboard --json                # JSON output (for Agent consumption)
vibecollab next                          # Action suggestions (prioritized next steps)
vibecollab next --json                   # JSON output

# Insight Accumulation (v0.7.0+)
vibecollab insight list [--active-only]  # List all insights
vibecollab insight show <id>             # View insight details
vibecollab insight add --title ...       # Create insight
vibecollab insight search --tags t1,t2   # Search by tags
vibecollab insight use <id>              # Record usage, reward weight
vibecollab insight decay [--dry-run]     # Execute weight decay
vibecollab insight check [--json]        # Consistency check
vibecollab insight delete <id> [-y]      # Delete insight
vibecollab insight bookmark <id>         # Bookmark insight
vibecollab insight trace <id>            # Trace tree visualization
vibecollab insight who <id>              # Cross-developer usage info
vibecollab insight stats                 # Cross-developer sharing stats

# Task Management + Insight Auto-Association (v0.7.1+)
vibecollab task create --id TASK-DEV-001 --role DEV --feature "..."  # Create task (auto-associate Insight)
vibecollab task list [--status TODO] [--assignee x]                  # List tasks
vibecollab task show <id>                # View task details (with associated Insights)
vibecollab task suggest <id> [-n 5]      # Recommend Insights for existing task

# Protocol Check + Health
vibecollab check                         # Protocol compliance check
vibecollab check --strict                # Strict mode
vibecollab check --insights              # Include Insight consistency check
vibecollab health [--json]               # Project health signals (v0.5.9+)
```

## 10.9 Best Practices

### For AI Agents

1. **On dialogue start**: Run `vibecollab onboard -d <name>` for full project awareness
2. **Context restoration**: Read both global and personal CONTEXT.md
3. **Collaboration awareness**: Check COLLABORATION.md before modifying shared resources
4. **Timely sync**: Update context and trigger aggregation at dialogue end
5. **Conflict sensitivity**: Alert users immediately when potential conflicts are found
6. **Three-step loop**: `onboard` (where am I) -> work -> `next` (what's next) -> `check` (self-check)

### For Human Developers

1. **Clear division**: Clearly record task assignments in COLLABORATION.md
2. **Regular sync**: Frequently check global CONTEXT.md for team progress
3. **Handoff standards**: Record background and status in detail during task handoffs
4. **Conflict checks**: Run conflict detection before major changes
5. **Doc timeliness**: Update personal CONTEXT.md promptly after completing phase work

### Migrating Single-Developer Projects

If the project was originally single-developer, you can migrate smoothly:

```bash
# Method 1: Use CLI command
vibecollab dev migrate

# Method 2: Enable in project.yaml
multi_developer:
  enabled: true

# Then regenerate protocol docs
vibecollab generate
```

After migration:
- Original `docs/CONTEXT.md` is backed up as `docs/CONTEXT.md.backup`
- Creates `docs/developers/{developer}/CONTEXT.md`
- Auto-generates new global aggregated `docs/CONTEXT.md`

---
