Files
stack/docs/scratchpads/orch-111-worktrees.md
Jason Woltje 12abdfe81d feat(#93): implement agent spawn via federation
Implements FED-010: Agent Spawn via Federation feature that enables
spawning and managing Claude agents on remote federated Mosaic Stack
instances via COMMAND message type.

Features:
- Federation agent command types (spawn, status, kill)
- FederationAgentService for handling agent operations
- Integration with orchestrator's agent spawner/lifecycle services
- API endpoints for spawning, querying status, and killing agents
- Full command routing through federation COMMAND infrastructure
- Comprehensive test coverage (12/12 tests passing)

Architecture:
- Hub → Spoke: Spawn agents on remote instances
- Command flow: FederationController → FederationAgentService →
  CommandService → Remote Orchestrator
- Response handling: Remote orchestrator returns agent status/results
- Security: Connection validation, signature verification

Files created:
- apps/api/src/federation/types/federation-agent.types.ts
- apps/api/src/federation/federation-agent.service.ts
- apps/api/src/federation/federation-agent.service.spec.ts

Files modified:
- apps/api/src/federation/command.service.ts (agent command routing)
- apps/api/src/federation/federation.controller.ts (agent endpoints)
- apps/api/src/federation/federation.module.ts (service registration)
- apps/orchestrator/src/api/agents/agents.controller.ts (status endpoint)
- apps/orchestrator/src/api/agents/agents.module.ts (lifecycle integration)

Testing:
- 12/12 tests passing for FederationAgentService
- All command service tests passing
- TypeScript compilation successful
- Linting passed

Refs #93

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-03 14:37:06 -06:00

176 lines
4.4 KiB
Markdown

# 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