# ORCH-111: Git worktree management

## Objective

Implement git worktree management for agent isolation in the orchestrator service. Each agent should work in its own worktree to prevent conflicts when multiple agents work on the same repository.

## Approach

1. **Phase 1: RED - Write failing tests** (TDD)
   - Test worktree creation with proper naming convention
   - Test worktree cleanup on completion
   - Test conflict handling (worktree already exists)
   - Test listing active worktrees
   - Test error handling for invalid paths

2. **Phase 2: GREEN - Implement WorktreeManagerService**
   - Create NestJS service with dependency injection
   - Integrate with GitOperationsService
   - Use simple-git for worktree operations
   - Implement worktree naming: `agent-{agentId}-{taskId}`
   - Add comprehensive error handling

3. **Phase 3: REFACTOR - Polish and optimize**
   - Extract helper methods
   - Improve error messages
   - Add detailed logging
   - Ensure clean code structure

## Worktree Commands

```bash
# Create worktree
git worktree add <path> -b <branch>

# Remove worktree
git worktree remove <path>

# List worktrees
git worktree list

# Prune stale worktrees
git worktree prune
```

## Naming Convention

Worktrees will be named: `agent-{agentId}-{taskId}`

Example:

- `agent-abc123-task-456`
- `agent-def789-task-789`

Worktrees will be created in: `{repoPath}_worktrees/agent-{agentId}-{taskId}/`

## Implementation Plan

### Tests to Write (RED)

1. **createWorktree()**
   - ✓ Creates worktree with correct naming
   - ✓ Creates branch for worktree
   - ✓ Returns worktree path
   - ✓ Throws error if worktree already exists
   - ✓ Throws error on git command failure

2. **removeWorktree()**
   - ✓ Removes worktree successfully
   - ✓ Handles non-existent worktree gracefully
   - ✓ Throws error on removal failure

3. **listWorktrees()**
   - ✓ Returns empty array when no worktrees
   - ✓ Lists all active worktrees
   - ✓ Parses worktree info correctly

4. **cleanupWorktree()**
   - ✓ Removes worktree on agent completion
   - ✓ Logs cleanup activity
   - ✓ Handles cleanup errors gracefully

### Service Methods

```typescript
class WorktreeManagerService {
  // Create worktree for agent
  async createWorktree(
    repoPath: string,
    agentId: string,
    taskId: string,
    baseBranch: string = "develop"
  ): Promise<WorktreeInfo>;

  // Remove worktree
  async removeWorktree(worktreePath: string): Promise<void>;

  // List all worktrees for a repo
  async listWorktrees(repoPath: string): Promise<WorktreeInfo[]>;

  // Cleanup worktree on agent completion
  async cleanupWorktree(agentId: string, taskId: string): Promise<void>;
}
```

## Progress

- [x] Create scratchpad
- [x] Write failing tests (RED) - 24 tests written
- [x] Implement WorktreeManagerService (GREEN) - All tests pass
- [x] Refactor and polish (REFACTOR) - Code clean and documented
- [x] Verify test coverage ≥85% - **98.64% coverage achieved**
- [x] Integration with Git module - Module updated and exported
- [x] Build verification - Build passes
- [x] All tests pass - 169 tests passing (24 new)
- [x] Create Gitea issue - Issue #246 created
- [x] Close issue with completion notes - Issue #246 closed

## Testing

### Unit Tests

All tests use mocked simple-git to avoid actual git operations:

```typescript
const mockGit = {
  raw: vi.fn(),
};

vi.mock("simple-git", () => ({
  simpleGit: vi.fn(() => mockGit),
}));
```

### Test Coverage

- Target: ≥85% coverage
- Focus: All public methods
- Edge cases: Errors, conflicts, cleanup

## Notes

### Integration with GitOperationsService

- WorktreeManagerService depends on GitOperationsService
- GitOperationsService provides basic git operations
- WorktreeManagerService adds worktree-specific functionality

### Error Handling

- All git errors wrapped in GitOperationError
- Detailed error messages for debugging
- Graceful handling of missing worktrees

### Logging

- Log all worktree operations (create, remove, cleanup)
- Include agent and task IDs in logs
- Log errors with full context

### Dependencies

- Blocked by: ORCH-110 (Git operations) ✓ COMPLETE
- Uses: simple-git library
- Integrates with: GitOperationsService

## Completion Criteria

- [x] All tests pass
- [x] Test coverage ≥85%
- [x] Service implements all required methods
- [x] Proper error handling
- [x] NestJS module integration
- [x] Comprehensive logging
- [x] Code follows project patterns
- [x] Gitea issue created and closed
