# TASK_11: Conversation Management Tools
**Created By**: Adder_2 | **Priority**: MEDIUM | **Duration**: 4 hours
**Technique Focus**: iTerm2 tab management, state preservation, conversation lifecycle
**Size Constraint**: Target <200 lines total, integrated into existing server.py
## π¦ Status & Assignment
**Status**: IN_PROGRESS
**Assigned**: Adder_2
**Dependencies**: TASK_4 (Agent & Session Management)
**Blocking**: TASK_12 (Integration & Testing)
## π Required Reading (Complete before starting)
- [ ] **Server Implementation**: `src/core/server.py` - Existing conversation tool skeletons
- [ ] **iTerm Manager**: `src/core/iterm_manager.py` - Tab management functionality
- [ ] **Agent Manager**: `src/core/agent_manager.py` - Agent state management
- [ ] **Types**: `src/types/communication.py` - ConversationClearResult, ConversationStartResult
## π― Objective & Context
**Goal**: Implement conversation management tools for clearing and restarting agent conversations
**Context**: Agents run in iTerm2 tabs with Claude Code processes - need clean conversation management
<thinking>
Conversation Management Analysis:
1. clear_agent_conversation:
- Close current iTerm2 tab
- Optionally preserve agent state
- Update agent status
- Handle active processes gracefully
2. start_new_agent_conversation:
- Create new iTerm2 tab for existing agent
- Restore agent context if requested
- Re-inject ADDER+ prompt with agent name
- Update agent references to new tab/process
</thinking>
## β
Implementation Subtasks (Sequential completion)
### Phase 1: Clear Conversation Implementation
- [ ] **Subtask 1.1**: Implement agent lookup and validation
- [ ] **Subtask 1.2**: Add iTerm2 tab closing with process cleanup
- [ ] **Subtask 1.3**: Implement state preservation logic
- [ ] **Subtask 1.4**: Update agent status and references
### Phase 2: Start Conversation Implementation
- [ ] **Subtask 2.1**: Implement new tab creation for existing agent
- [ ] **Subtask 2.2**: Add Claude Code process spawning
- [ ] **Subtask 2.3**: Implement context restoration and prompt injection
- [ ] **Subtask 2.4**: Update agent state with new tab/process IDs
### Phase 3: Error Handling & Integration
- [ ] **Subtask 3.1**: Add comprehensive error handling
- [ ] **Subtask 3.2**: Implement recovery for partial failures
- [ ] **Subtask 3.3**: Add health check integration
- [ ] **Subtask 3.4**: Create tests for both tools
## π§ Implementation Details
### **Tool 1: clear_agent_conversation**
```python
@self.mcp.tool(
name="clear_agent_conversation",
description="Close current iTerm2 tab for agent (clears conversation)",
tags={"conversation", "management", "clear"}
)
async def clear_conversation_tool(
agent_name: str,
preserve_state: bool = True,
ctx: Context = None
) -> Dict[str, Any]:
```
**Parameters:**
- `agent_name`: Name of the agent (Agent_#)
- `preserve_state`: Whether to save agent state before clearing
- `ctx`: MCP context for progress reporting
**Process Flow:**
1. Validate agent name and find agent
2. Check agent is active
3. If preserve_state:
- Save current agent state
- Record conversation metadata
4. Gracefully terminate Claude Code process
5. Close iTerm2 tab
6. Update agent status to CONVERSATION_CLEARED
7. Return result with operation details
### **Tool 2: start_new_agent_conversation**
```python
@self.mcp.tool(
name="start_new_agent_conversation",
description="Open new iTerm2 tab for agent (starts fresh conversation)",
tags={"conversation", "management", "start"}
)
async def start_conversation_tool(
agent_name: str,
restore_context: bool = True,
ctx: Context = None
) -> Dict[str, Any]:
```
**Parameters:**
- `agent_name`: Name of the agent (Agent_#)
- `restore_context`: Whether to restore previous context
- `ctx`: MCP context for progress reporting
**Process Flow:**
1. Validate agent name and find agent
2. Check agent state allows new conversation
3. Create new iTerm2 tab in session window
4. Spawn new Claude Code process
5. If restore_context:
- Load saved state
- Inject context into new conversation
6. Inject ADDER+ prompt with agent name
7. Update agent state with new tab/process IDs
8. Update status to ACTIVE
9. Return result with new tab/process info
### **Integration Points**
- **AgentManager**: For agent lookup and state updates
- **ITermManager**: For tab creation/closing
- **ClaudeCodeManager**: For process management
- **StateManager**: For state preservation/restoration
### **Error Handling**
- Agent not found
- Agent in invalid state
- iTerm2 connection issues
- Process termination failures
- State preservation errors
- Tab creation failures
## ποΈ State Management
### **Agent State Transitions**
```
ACTIVE β CONVERSATION_CLEARING β CONVERSATION_CLEARED
CONVERSATION_CLEARED β CONVERSATION_STARTING β ACTIVE
```
### **Preserved State Structure**
```python
{
"agent_id": "agent_123",
"conversation_metadata": {
"messages_sent": 42,
"duration_minutes": 30,
"last_activity": "2025-06-26T10:30:00Z"
},
"context": {
"working_directory": "/path/to/project",
"active_files": ["main.py", "test.py"],
"custom_state": {...}
}
}
```
## β
Success Criteria
- [ ] Both tools fully implemented
- [ ] Proper iTerm2 tab lifecycle management
- [ ] State preservation/restoration working
- [ ] Agent status correctly updated
- [ ] Error handling comprehensive
- [ ] Health checks integrated
- [ ] All tests passing
## π Error Recovery Strategy
1. **Tab Close Failure**: Force terminate process, mark agent as UNKNOWN
2. **Process Termination Failure**: Use force kill, log warning
3. **State Save Failure**: Continue operation, warn user
4. **Tab Creation Failure**: Retry with backoff, fail gracefully
5. **Context Restore Failure**: Start clean, notify user
## π Testing Scenarios
1. Clear conversation for active agent
2. Clear with state preservation disabled
3. Clear already cleared agent (idempotent)
4. Start new conversation after clear
5. Start with context restoration
6. Start without previous context
7. Handle missing agents
8. Handle iTerm2 failures
9. Concurrent conversation operations