# OpenAI SDK Integration - Project Manager Agent Brief

**Project:** OpenAI SDK Integration v2.1 FINAL + Addendum
**Duration:** 8-9 weeks (54-65 days)
**Status:** Ready for implementation
**Risk Level:** MEDIUM-LOW (with mitigation strategies)

---

## Your Role: Project Manager Agent

You are the single coordinating agent responsible for managing the complete implementation of OpenAI SDK integration into Kollabor CLI. Your responsibilities include:

1. **Phase Management:** Execute all 10 implementation phases in sequence
2. **Agent Coordination:** Spawn and manage specialized GLM agents for parallel work
3. **Quality Assurance:** Ensure all success criteria met for each phase
4. **Risk Management:** Implement mitigation strategies when issues arise
5. **Progress Tracking:** Maintain phase completion status and blockers
6. **Documentation:** Keep implementation log with decisions and deviations

---

## Project Context

### What You're Building

Integration of OpenAI's official SDK alongside existing Anthropic support, enabling:
- Multi-provider architecture (OpenAI + Anthropic)
- Secure API key storage with 4-tier fallback
- Unified streaming interface across providers
- Tool calling with both providers
- Profile switching during conversations
- Enterprise-ready deployment options

### Critical Success Factors

1. **Security:** API keys stored securely (OS keyring + encrypted fallback)
2. **Compatibility:** All 9 existing plugins continue working
3. **Quality:** 65%+ test coverage achieved
4. **Performance:** No regressions vs current (within 5%)
5. **Enterprise:** Works in Docker, K8s, CI/CD, serverless

### Source Documents

**Primary Specification:**
- `/Users/malmazan/dev/kollabor-cli/docs/specs/openai-sdk-integration-spec-v2.1-FINAL.md`
  - 2,353 lines
  - 10 implementation phases
  - 315+ test cases defined
  - Complete code implementations

**Critical Addendum:**
- `/Users/malmazan/dev/kollabor-cli/docs/specs/openai-sdk-integration-spec-v2.1-ADDENDUM.md`
  - 3,088 lines
  - Addresses 4 priority concerns
  - Keyring fallback strategy (CRITICAL)
  - Resource testing methodology
  - Tool accumulator migration
  - Provider registry integration

**Read both documents completely before starting Phase 0.**

---

## Work Breakdown Structure (WBS)

### Phase 0: Current System Analysis (Days 1-4)

**Objective:** Thoroughly understand existing codebase before making changes

**Duration:** 3-4 days
**Risk:** LOW
**Dependencies:** None

**Agents to Spawn (5 agents in parallel):**

```bash
tglm Phase0AnalyzeSchema "Analyze current message schema in api_communication_service.py. Document request/response structure, all fields and types. Output: docs/analysis/current-message-schema.md"

tglm Phase0AnalyzeHooks "Document hook system structure. Verify Hook dataclass has plugin_name field (not plugin object). List all plugins and hook usage. Output: docs/analysis/hook-system-audit.md"

tglm Phase0AnalyzeErrors "Document current error handling patterns. Find all exception handlers, document error messages to users. Output: docs/analysis/error-handling-patterns.md"

tglm Phase0AnalyzeTools "Document tool_executor.py implementation, tool call format, Question Gate integration, pending tool queue management. Output: docs/analysis/tool-system.md"

tglm Phase0AnalyzeMessages "Document llm_service.py message preparation, system prompt handling, conversation history formatting, MCP integration. Output: docs/analysis/message-building.md"
```

**Success Criteria:**
- [ ] 5 analysis documents created in `docs/analysis/`
- [ ] Hook.plugin_name confirmed (not plugin object)
- [ ] All 5 tool call sites identified and documented
- [ ] Question Gate flow fully mapped
- [ ] Integration points identified for Phase 6

**Your Actions:**
1. Spawn all 5 agents in parallel
2. Monitor progress with `tlist` and `tcapture`
3. Review all 5 analysis documents
4. Validate completeness before proceeding
5. Create `docs/analysis/PHASE0-COMPLETE.md` with summary

**Blockers to Watch:**
- Agents stuck on understanding complex flows
- Missing documentation in codebase
- Unclear integration points

**Mitigation:**
- Use `tmsg` to provide clarification
- Reference CLAUDE.md for codebase patterns
- If stuck >4 hours, escalate to human

---

### Phase 1: Foundation & Type System (Days 5-9)

**Objective:** Build secure foundation (models, errors, security with 4-tier keyring fallback)

**Duration:** 4-5 days
**Risk:** LOW
**Dependencies:** Phase 0 complete

**Agents to Spawn (3 agents in sequence):**

```bash
# Day 5-6
tglm Phase1FoundationModels "Implement core/llm/providers/models.py (200-250 lines). All Pydantic models with validators. Unit tests (150+ lines). Target: 80%+ coverage. Follow spec lines 1248-1273."

# Day 7-8 (after models complete)
tglm Phase1FoundationErrors "Implement core/llm/providers/errors.py (220-250 lines). Complete error hierarchy for BOTH OpenAI AND Anthropic. Unit tests (120+ lines). Include map_anthropic_error() from spec lines 728-864. Target: 80%+ coverage."

# Day 9-11 (after errors complete) - LONGEST TASK
tglm Phase1FoundationSecurity "Implement core/llm/providers/security.py (450-500 lines). CRITICAL: Use 4-tier fallback from ADDENDUM Priority 0. Tier 1: OS keyring, Tier 2: AES-256-GCM encrypted file, Tier 3: env vars, Tier 4: plaintext with opt-in. APIKeyManager, EncryptedFileKeyStorage, EnvironmentKeyStorage, PlaintextKeyStorage, URLValidator, LoggingRedactor. Unit tests (350+ lines). Target: 75%+ coverage."
```

**Success Criteria:**
- [ ] models.py: All Pydantic models validate correctly
- [ ] errors.py: Both OpenAI AND Anthropic errors mapped
- [ ] security.py: 4-tier fallback system works on all platforms
- [ ] Keyring storage tested on macOS/Windows/Linux
- [ ] Encrypted file backend encrypts properly (AES-256-GCM)
- [ ] Deep logging redaction tested (recursive)
- [ ] All unit tests pass
- [ ] Coverage: models 80%+, errors 80%+, security 75%+

**Your Actions:**
1. Spawn Phase1FoundationModels first
2. Wait for completion, review code
3. Spawn Phase1FoundationErrors after models done
4. Wait for completion, review error mapping
5. Spawn Phase1FoundationSecurity after errors done
6. **CRITICAL:** Test 4-tier fallback on minimal Docker container
7. Run all unit tests: `pytest tests/unit/test_provider_*.py`
8. Check coverage: `pytest --cov=core.llm.providers --cov-report=html`

**Blockers to Watch:**
- Keyring unavailable on test system (use encrypted file fallback)
- Encryption dependencies missing (add cryptography to requirements)
- Pydantic validation too strict (adjust validators)

**Mitigation:**
- Test on multiple platforms (macOS, Linux, Docker)
- Have encrypted file fallback ready
- Environment variable mode for CI testing

**Phase 1 Deliverables:**
- `core/llm/providers/models.py`
- `core/llm/providers/errors.py`
- `core/llm/providers/security.py`
- `tests/unit/test_provider_models.py`
- `tests/unit/test_provider_errors.py`
- `tests/unit/test_provider_security.py`
- Coverage report showing 75-80%+

---

### Phase 2: Transformation Layer (Days 10-14)

**Objective:** Build response transformers and tool accumulator

**Duration:** 4-5 days
**Risk:** MEDIUM (JSON accumulation complexity)
**Dependencies:** Phase 1 complete

**Agents to Spawn (2 agents in sequence):**

```bash
# Day 10-12 (3 days)
tglm Phase2ImplementTransformers "Implement core/llm/providers/transformers.py (600-700 lines). ToolCallAccumulator with edge case handling, OpenAIResponseTransformer with streaming, AnthropicResponseTransformer with thinking blocks, ToolSchemaTransformer (bidirectional). Handle malformed JSON gracefully. Follow spec lines 1282-1300. Target: 75%+ coverage."

# Day 13-14 (2 days, after transformers complete)
tglm Phase2TestTransformers "Comprehensive transformer tests (400+ lines). Test incremental tool accumulation, malformed JSON handling, schema conversion both ways, property-based tests with Hypothesis, all content block types. Follow spec lines 1739-1783. Target: 80%+ coverage."
```

**Success Criteria:**
- [ ] Tool arguments accumulate correctly (incremental JSON)
- [ ] Schema transformation works bidirectionally (OpenAI ↔ Anthropic)
- [ ] All edge cases handled (malformed JSON, empty chunks, unicode)
- [ ] Property tests pass with Hypothesis
- [ ] Streaming transformers handle thinking blocks (Anthropic)
- [ ] Coverage: 75%+ implementation, 80%+ tests

**Your Actions:**
1. Spawn Phase2ImplementTransformers
2. Monitor for JSON parsing issues
3. Test with real-world tool call sequences
4. Spawn Phase2TestTransformers after implementation
5. Review property-based tests for meaningful coverage
6. Run tests: `pytest tests/unit/test_transformers.py -v`

**Blockers to Watch:**
- Incremental JSON accumulation fails on split boundaries
- Schema transformation loses data
- Thinking blocks not preserved
- Property tests too slow

**Mitigation:**
- Test with various JSON split points
- Compare before/after schema transformation
- Add buffer for multi-byte unicode characters
- Limit property test iterations if slow

**Phase 2 Deliverables:**
- `core/llm/providers/transformers.py`
- `tests/unit/test_transformers.py`
- Property tests with Hypothesis
- Coverage report

---

### Phase 3: Provider Registry & Base (Days 15-18)

**Objective:** Build provider registry and base classes

**Duration:** 3-4 days
**Risk:** LOW (well-understood pattern)
**Dependencies:** Phase 2 complete

**Agents to Spawn (3 agents in sequence):**

```bash
# Day 15-16
tglm Phase3ProviderRegistry "Implement core/llm/providers/registry.py (200-250 lines). Decorator-based registration (@register_provider), thread-safe operations, provider listing and discovery. Unit tests (100+ lines). Follow spec lines 1310-1325. Target: 80%+ coverage."

# Day 16-17 (after registry)
tglm Phase3ProviderBase "Implement core/llm/providers/base.py (250-300 lines). LLMProvider ABC with full lifecycle, request tracking for safe shutdown, atomic operations with locking. Unit tests (120+ lines). Follow spec lines 1320-1337. Target: 75%+ coverage."

# Day 17-18 (after base)
tglm Phase3TestProviderBase "Lifecycle tests (80+ lines), concurrency tests (60+ lines), shutdown safety tests (40+ lines). Test provider registration, creation, listing. Target: 75%+ coverage."
```

**Success Criteria:**
- [ ] Registry is thread-safe
- [ ] Providers self-register with decorator
- [ ] Lifecycle is robust (init, request tracking, shutdown)
- [ ] Concurrent requests handled safely
- [ ] All tests pass
- [ ] Coverage: 75-80%+

**Your Actions:**
1. Spawn agents sequentially
2. Test thread safety with concurrent requests
3. Verify decorator registration works
4. Test lifecycle edge cases
5. Run tests: `pytest tests/unit/test_provider_lifecycle.py -v`

**Blockers to Watch:**
- Race conditions in registry
- Provider cleanup incomplete
- Request tracking incorrect

**Mitigation:**
- Add asyncio.Lock for thread safety
- Test with pytest-asyncio
- Track active requests carefully

**Phase 3 Deliverables:**
- `core/llm/providers/registry.py`
- `core/llm/providers/base.py`
- `tests/unit/test_provider_lifecycle.py`
- Thread safety tests

---

### Phase 4: Provider Implementations (Days 19-25)

**Objective:** Implement OpenAI and Anthropic providers

**Duration:** 6-7 days
**Risk:** MEDIUM (OpenAI SDK nuances)
**Dependencies:** Phase 3 complete

**Agents to Spawn (4 agents - 2 parallel, 2 sequential):**

```bash
# PARALLEL GROUP 1 (Days 19-21, 3 days)
tglm Phase4OpenAIProviderCore "Implement core/llm/providers/openai_provider.py core (300-350 lines). SDK client initialization, configuration validation with @register_provider, non-streaming implementation. Basic tests (200+ lines). Follow spec lines 1342-1361." &

tglm Phase4AnthropicProviderWrapper "Implement core/llm/providers/anthropic_provider.py (250-300 lines). Wrap APICommunicationService, use AnthropicResponseTransformer, register with @register_provider. Maintain exact backward compatibility. Tests (180+ lines). Follow spec lines 1342-1361." &

wait  # Wait for parallel group to complete

# SEQUENTIAL (Days 22-23, 2 days)
tglm Phase4OpenAIProviderStreaming "Add streaming to OpenAIProvider (200-250 lines). Integrate ToolCallAccumulator, handle stream cancellation. Streaming tests (150+ lines). Depends on OpenAIProviderCore."

# SEQUENTIAL (Days 24-25, 2 days, after all above)
tglm Phase4ProviderTesting "Integration tests for both providers (300+ lines). Mock OpenAI API with respx, mock Anthropic responses, test real-world chunk sequences, test ALL error types. Follow spec lines 1821-1875. Target: 70%+ coverage."
```

**Success Criteria:**
- [ ] Both providers fully functional
- [ ] All errors properly mapped
- [ ] Streaming works correctly with both
- [ ] Tool calling works with both
- [ ] Integration tests pass
- [ ] Mock tests cover error scenarios
- [ ] Coverage: 70%+

**Your Actions:**
1. Spawn OpenAI and Anthropic agents in parallel
2. Monitor both with `tlist`, `tcapture`
3. Review both implementations
4. Spawn streaming agent after core complete
5. Spawn testing agent after all implementations
6. Test with real API keys (if available)
7. Run: `pytest tests/integration/test_providers.py -v`

**Blockers to Watch:**
- OpenAI SDK version incompatibility
- Streaming chunking differs from expected
- Tool call format differences
- API rate limits during testing

**Mitigation:**
- Pin openai>=1.12.0 in requirements
- Test streaming with respx mocks
- Reference OpenAI SDK docs for format
- Use mocks for most tests

**Phase 4 Deliverables:**
- `core/llm/providers/openai_provider.py`
- `core/llm/providers/anthropic_provider.py`
- `tests/integration/test_providers.py`
- Mock API tests with respx

---

### Phase 5: Integration Updates (Days 26-31)

**Objective:** Update all integration points for UnifiedResponse format

**Duration:** 5-6 days
**Risk:** HIGH (touches core files)
**Dependencies:** Phase 4 complete

**Agents to Spawn (5 agents - 3 parallel, 2 sequential):**

```bash
# PARALLEL GROUP (Days 26-28, 3 days)
tglm Phase5ToolCallingIntegration "Update core/llm/tool_executor.py (150-200 lines changes). Adapt for UnifiedResponse format, tool result formatting for both providers, tool schema transformation integration. Tests (120+ lines). Follow ADDENDUM Priority 2 for migration strategy." &

tglm Phase5ConversationLoggerIntegration "Update core/llm/conversation_logger.py (100-150 lines changes). Store provider metadata in logs, migrate existing log format. Tests (80+ lines)." &

tglm Phase5ResponseParserIntegration "Update core/llm/response_parser.py (80-120 lines changes). Parse UnifiedResponse format, Question Gate integration with new format. Tests (60+ lines)." &

wait  # Wait for parallel group

# SEQUENTIAL (Days 29-30, after parallel group)
tglm Phase5MessageDisplayIntegration "Update core/llm/message_display_service.py (150-200 lines changes). Display StreamingResponse format, preserve Anthropic thinking blocks. Tests (100+ lines). Depends on ResponseParser."

# SEQUENTIAL (Day 31, after message display)
tglm Phase5MCPIntegration "Verify core/llm/mcp_integration.py compatibility. Test MCP tools with both providers, tool format transformation, context injection tests (80+ lines)."
```

**Success Criteria:**
- [ ] All integration points updated
- [ ] Tool calling works end-to-end
- [ ] Conversation logging includes provider
- [ ] Message display preserves thinking blocks
- [ ] Question Gate still works
- [ ] MCP integration verified
- [ ] All existing tests still pass

**Your Actions:**
1. **CRITICAL:** Back up core files before changes
2. Spawn 3 parallel agents first
3. Review each carefully for breaking changes
4. Run existing test suite after each integration
5. Spawn sequential agents after parallel complete
6. Test Question Gate specifically
7. Test MCP tools with both providers
8. Run full test suite: `pytest tests/`

**Blockers to Watch:**
- Breaking changes to existing code
- Question Gate breaks
- MCP tools fail with new format
- Tests start failing

**Mitigation:**
- Git commit after each successful integration
- Feature flags to rollback if needed
- Test Question Gate explicitly
- Keep backward compatibility where possible

**Phase 5 Deliverables:**
- Updated integration files
- All integration tests passing
- Question Gate verification
- MCP compatibility verification

---

### Phase 6: LLMService Integration (Days 32-39)

**Objective:** Integrate provider registry into LLMService with 3-phase tool migration

**Duration:** 7-8 days (was 5-6, extended per ADDENDUM Priority 2)
**Risk:** HIGH (15+ call sites, streaming changes)
**Dependencies:** Phase 5 complete

**Agents to Spawn (3 agents in sequence):**

```bash
# Days 32-34 (3 days) - Phase 6a: Wrapper Pattern (LOW RISK)
tglm Phase6aProviderIntegration "Phase 6a WRAPPER PATTERN (low risk). Modify core/llm/llm_service.py:
1. Add ProviderRegistry and APIKeyManager (lines 172-186)
2. Add ToolCallAccumulator in LEGACY mode
3. Provider initialization on startup
4. Update 5 call sites to use accumulator (lines 1107,1621,1653,1867,1899)
5. Profile switching with locking
6. Tests (250+ lines)
Follow ADDENDUM Priority 2 Phase 6a and Priority 3 integration code. CRITICAL: Use legacy mode accumulator first. Target: existing tests pass unchanged."

# Days 35-37 (3 days) - Phase 6b: Explicit Accumulation (MEDIUM RISK)
tglm Phase6bToolMigration "Phase 6b EXPLICIT ACCUMULATION (medium risk). After 6a complete and tested:
1. Switch ToolCallAccumulator to EXPLICIT mode
2. Add delta handling to streaming
3. Remove batch retrieval from api_service
4. Add feature flag: core.llm.use_explicit_tool_accumulation
5. Comparison testing between modes
6. Tests (180+ lines)
Follow ADDENDUM Priority 2 Phase 6b. CRITICAL: Test both modes produce same results. Target: tool execution identical before/after."

# Days 38-39 (2 days) - Phase 6c: End-to-end Testing (HIGH RISK)
tglm Phase6cE2ETesting "End-to-end LLM service tests (300+ lines):
1. Provider switching during conversation
2. Tool execution with both providers (both accumulator modes)
3. Error handling and recovery
4. Conversation persistence
5. Question Gate with new format
Follow spec lines 1432-1461 and ADDENDUM Priority 2 Phase 6c. Target: 70%+ coverage, all scenarios pass."
```

**Success Criteria:**
- [ ] Phase 6a: All existing tests pass (wrapper transparent)
- [ ] Phase 6b: Tool execution identical in both modes
- [ ] Feature flag allows rollback to legacy mode
- [ ] LLMService works with both providers
- [ ] Profile switching is atomic
- [ ] All 5 call sites updated correctly
- [ ] No regressions in Question Gate
- [ ] Coverage: 70%+

**Your Actions:**
1. **CRITICAL:** Create backup: `cp core/llm/llm_service.py core/llm/llm_service.py.backup`
2. Spawn Phase6a agent first
3. **STOP:** Test thoroughly before 6b
4. Run FULL test suite after 6a
5. Verify tool execution unchanged
6. Only proceed to 6b if 6a perfect
7. Spawn Phase6b after 6a validated
8. Test comparison between modes
9. Spawn Phase6c for final validation
10. Run: `pytest tests/integration/test_llm_service.py -v`

**Blockers to Watch:**
- Wrapper breaks existing functionality (ROLLBACK)
- Explicit mode produces different results (STAY ON 6a)
- Provider switching fails
- Tool accumulation incorrect
- Tests start failing

**Mitigation:**
- Phase 6a MUST be perfect before 6b
- Use feature flag for rollback
- Comparison tests between modes
- Can stay on Phase 6a if needed
- Git commit after each sub-phase

**Phase 6 Deliverables:**
- Updated `core/llm/llm_service.py`
- ToolCallAccumulator integration
- Feature flag for mode switching
- Comparison tests
- Full test suite passing

---

### Phase 7: Configuration & Migration (Days 40-44)

**Objective:** Extend config, implement migration with 4-tier keyring support

**Duration:** 4-5 days
**Risk:** MEDIUM (migration complexity)
**Dependencies:** Phase 6 complete

**Agents to Spawn (3 agents in sequence):**

```bash
# Day 40-41 (2 days)
tglm Phase7ConfigExtension "Extend configuration schema (150-200 lines changes). Add provider field validation, OpenAI-specific field validation, configuration version tracking. Tests (100+ lines). Follow spec lines 1463-1494."

# Day 41-43 (2-3 days, after config extension)
tglm Phase7ProfileMigration "Implement core/config/migration.py (300-350 lines). Automatic profile migration with provider detection (FIXED ORDER from spec line 869-921), migrate keys to selected keyring backend (4-tier fallback), atomic migration with temp files, rollback on failure. Tests (200+ lines). CRITICAL: Use provider detection from spec, test with all 4 keyring backends."

# Day 43-44 (1-2 days, after migration)
tglm Phase7ProfileCommand "Extend core/commands/profile_command.py (200-250 lines changes). OpenAI profile creation wizard, profile validation on creation, masked key input, profile testing (verify API key works). Tests (120+ lines). Follow spec lines 1463-1494."
```

**Success Criteria:**
- [ ] Migration is atomic and safe
- [ ] Rollback works correctly
- [ ] Keys migrated to appropriate backend (keyring/encrypted/env)
- [ ] Provider detection correct (Anthropic before OpenAI)
- [ ] Azure detection works
- [ ] Profile command creates valid profiles
- [ ] All 4 keyring backends tested
- [ ] Coverage: 70%+

**Your Actions:**
1. Spawn config extension first
2. Test config validation
3. Spawn migration after config done
4. **CRITICAL:** Test migration on backup config first
5. Test all 4 keyring backends:
   - Tier 1: OS keyring (if available)
   - Tier 2: Encrypted file
   - Tier 3: Environment variables
   - Tier 4: Plaintext (with opt-in)
6. Verify provider detection order
7. Test rollback functionality
8. Spawn profile command last
9. Run: `pytest tests/integration/test_config_migration.py -v`

**Blockers to Watch:**
- Migration corrupts config
- Rollback doesn't work
- Provider detection wrong order
- Keys not migrated correctly
- Keyring backend unavailable

**Mitigation:**
- Always create backup first
- Test migration on copy
- Atomic write with temp files
- Test all 4 fallback tiers
- Verify provider detection order matches spec

**Phase 7 Deliverables:**
- `core/config/migration.py`
- Extended configuration schema
- Updated profile command
- Migration tests
- Rollback tests

---

### Phase 8: Hook Compatibility (Days 45-48)

**Objective:** Ensure all existing plugins work with new hook format

**Duration:** 3-4 days
**Risk:** MEDIUM (plugin compatibility)
**Dependencies:** Phase 6 complete (not Phase 7)

**Agents to Spawn (2 agents in sequence):**

```bash
# Day 45-46 (2 days)
tglm Phase8HookAdapter "Implement core/events/hook_adapter.py (200-250 lines). Plugin instance tracking (FIXED from ADDENDUM), use hook.plugin_name not hook.plugin, version detection, format conversion. Tests (150+ lines). Follow ADDENDUM Priority 0 lines 1079-1197 for CRITICAL fix."

# Day 47-48 (2 days, after adapter)
tglm Phase8HookTesting "Test with ALL 9 existing plugins (200+ lines). Verify no crashes, test version detection, test data format compatibility, integration tests. Follow spec lines 1498-1520. Find all plugin files and test each one. Target: 80%+ coverage."
```

**Success Criteria:**
- [ ] All 9 existing plugins work without crashes
- [ ] Hook adapter uses plugin_name correctly
- [ ] Version detection accurate
- [ ] Hook data properly adapted
- [ ] No plugin modifications needed
- [ ] Coverage: 80%+

**Your Actions:**
1. **CRITICAL:** List all 9 existing plugins first
2. Find plugins: `find plugins/ -name "*plugin.py" -type f`
3. Spawn adapter agent
4. Review adapter for plugin_name usage
5. Spawn testing agent after adapter
6. Test each plugin individually
7. Verify no crashes or errors
8. Run: `pytest tests/integration/test_hook_compatibility.py -v`

**Blockers to Watch:**
- Plugin crashes with new format
- Hook adapter uses wrong field
- Version detection fails
- Plugin behavior changes

**Mitigation:**
- Use hook.plugin_name (string) not hook.plugin (object)
- Track plugin instances separately
- Test each plugin in isolation
- Provide migration guide for plugin authors

**Phase 8 Deliverables:**
- `core/events/hook_adapter.py`
- Plugin compatibility tests
- All 9 plugins tested
- No crashes or breaking changes

---

### Phase 9: Status Display & UI (Days 49-52)

**Objective:** Update UI to show provider information

**Duration:** 3-4 days
**Risk:** LOW (cosmetic changes)
**Dependencies:** Phase 8 complete

**Agents to Spawn (2 agents in parallel):**

```bash
# PARALLEL (Days 49-51)
tglm Phase9StatusDisplay "Update status line components (100-150 lines changes). Show current provider, provider-specific icons/colors, model name with context. Tests (60+ lines). Follow spec lines 1523-1545." &

tglm Phase9UIProviders "Update terminal banner (80-120 lines changes), provider switching messages, error display with provider context, profile validation feedback. Tests (50+ lines). Follow spec lines 1523-1545." &

wait

# Day 52 - Integration testing
```

**Success Criteria:**
- [ ] Status shows provider clearly
- [ ] Visual indicators work (icons/colors)
- [ ] Errors show provider context
- [ ] Banner updated with provider info
- [ ] User-friendly messages
- [ ] Coverage: 55%+ (UI is hard to test)

**Your Actions:**
1. Spawn both agents in parallel
2. Review UI changes for clarity
3. Test manually with both providers
4. Verify status updates on profile switch
5. Check error messages include provider
6. Run: `pytest tests/unit/test_status_display.py -v`

**Blockers to Watch:**
- UI rendering issues
- Color codes not working
- Status update lag
- Unclear messaging

**Mitigation:**
- Test on multiple terminals
- Use plain text fallbacks
- Keep messages concise
- Test with screen readers (accessibility)

**Phase 9 Deliverables:**
- Updated status components
- Updated UI elements
- Manual testing verification

---

### Phase 10: Documentation & Final Testing (Days 53-58)

**Objective:** Complete documentation and comprehensive testing

**Duration:** 5-6 days
**Risk:** MEDIUM (coverage targets)
**Dependencies:** All phases 1-9 complete

**Agents to Spawn (4 agents - 3 parallel, 1 sequential):**

```bash
# PARALLEL GROUP (Days 53-55, 3 days)
tglm Phase10UserDocs "Write docs/guides/openai-setup.md with configuration examples, troubleshooting guide, migration guide. Include 4-tier keyring setup for all platforms. Follow ADDENDUM Priority 0 enterprise deployment guides." &

tglm Phase10DevDocs "Write docs/reference/provider-interface.md with provider implementation guide, architecture diagrams, transformation layer docs. Include hook compatibility guide." &

tglm Phase10TestDocs "Write docs/testing/provider-testing.md with test strategy documentation, coverage reports, test running guide. Include resource lifecycle testing methodology from ADDENDUM Priority 1." &

wait

# SEQUENTIAL (Days 56-58, 3 days, after all above)
tglm Phase10FinalTesting "Complete end-to-end integration tests (400+ lines):
1. All user workflows (profile creation, provider switching, tool calling)
2. All error scenarios (auth, rate limit, network, timeout)
3. Performance testing (memory leaks, latency, throughput) using ADDENDUM Priority 1 methodology
4. Security audit (key storage, logging redaction, URL validation)
5. Resource lifecycle tests (memory, FDs, connections, threads)
6. Coverage verification (target 65%+)
Follow spec lines 1547-1586 and ADDENDUM Priority 1 resource testing."
```

**Success Criteria:**
- [ ] Complete documentation (user + dev + testing)
- [ ] All integration tests pass
- [ ] Performance acceptable (no regressions)
- [ ] Security audit passes
- [ ] 65%+ coverage achieved
- [ ] No memory leaks (<1MB/100ops)
- [ ] No FD leaks (<5/100ops)
- [ ] All user workflows tested

**Your Actions:**
1. Spawn 3 doc agents in parallel
2. Review all documentation for clarity
3. Test examples in user docs
4. Spawn final testing agent
5. **CRITICAL:** Run resource lifecycle tests with tools:
   - tracemalloc for memory
   - psutil for FDs
   - memray for detailed profiling
6. Run full test suite: `pytest tests/ --cov=core.llm.providers --cov-report=html`
7. Check coverage report
8. Perform security audit
9. Test on multiple platforms (macOS, Linux, Docker)
10. Create final report

**Blockers to Watch:**
- Coverage below 65%
- Memory leaks detected
- Performance regressions
- Security issues found
- Documentation incomplete

**Mitigation:**
- Add tests for uncovered code
- Fix leaks using memray profiling
- Optimize slow paths
- Fix security issues immediately
- Iterate on documentation

**Phase 10 Deliverables:**
- Complete documentation
- All integration tests
- Performance tests
- Security audit report
- Coverage report (65%+)
- Final implementation report

---

## Project Management Guidelines

### Daily Routine

**Morning (30 minutes):**
1. Check all active agents: `tlist`
2. Review overnight progress: `tcapture <agent> 50`
3. Update phase status in tracking doc
4. Identify blockers

**Midday (15 minutes):**
1. Check agent progress
2. Review any completed work
3. Spawn next agents if ready
4. Address any issues

**Evening (30 minutes):**
1. Review day's progress
2. Commit completed work
3. Update tracking document
4. Plan tomorrow's agents

### Agent Management Best Practices

**Spawning Agents:**
```bash
# Good: Specific, measurable task
tglm Phase2TestTransformers "Write comprehensive tests for transformers.py (400+ lines). Test incremental JSON, malformed handling, schema conversion. Output: tests/unit/test_transformers.py. Target: 80%+ coverage."

# Bad: Vague, open-ended task
tglm WriteTests "Write some tests for the new code"
```

**Monitoring Agents:**
```bash
# Check all active agents
tlist

# View recent output (last 50 lines)
tcapture Phase2TestTransformers 50

# Send message to agent
tmsg Phase2TestTransformers "Focus on edge cases for JSON accumulation"

# Stop stuck agent
tstop Phase2TestTransformers
```

**Parallel vs Sequential:**
- Parallel: Tasks with no dependencies
- Sequential: Tasks that depend on previous output
- Use `&` and `wait` for parallel spawning

### Quality Gates

**Before Proceeding to Next Phase:**
1. All tests pass for current phase
2. Coverage meets target
3. Code review complete (by you)
4. Integration tests pass
5. No critical bugs
6. Documentation updated

**If Quality Gate Fails:**
1. Stop spawning new agents
2. Analyze failure cause
3. Fix issues or spawn repair agent
4. Re-test thoroughly
5. Only proceed when gate passes

### Risk Management

**High-Risk Phases:**
- Phase 5: Integration updates (touches core)
- Phase 6: LLMService integration (15+ call sites)

**Mitigation:**
- Extra testing before proceeding
- Create backups before changes
- Feature flags for rollback
- Commit frequently
- Test incrementally

**If Critical Issue Found:**
1. Document issue clearly
2. Assess impact (blocker vs non-blocker)
3. If blocker: stop current work
4. Spawn agent to fix issue
5. Re-test affected areas
6. Update risk register

### Progress Tracking

Create tracking document: `docs/specs/IMPLEMENTATION-PROGRESS.md`

```markdown
# OpenAI SDK Integration - Implementation Progress

## Phase Status
- [x] Phase 0: Analysis (Days 1-4) - COMPLETE 2026-01-20
- [x] Phase 1: Foundation (Days 5-9) - COMPLETE 2026-01-26
- [IN PROGRESS] Phase 2: Transformation (Days 10-14) - Started 2026-01-27
- [ ] Phase 3: Registry (Days 15-18)
- [ ] Phase 4: Providers (Days 19-25)
- [ ] Phase 5: Integration (Days 26-31)
- [ ] Phase 6: LLMService (Days 32-39)
- [ ] Phase 7: Config/Migration (Days 40-44)
- [ ] Phase 8: Hook Compat (Days 45-48)
- [ ] Phase 9: UI Updates (Days 49-52)
- [ ] Phase 10: Docs/Testing (Days 53-58)

## Current Focus
Phase 2: Transformation Layer
- Active agents: Phase2ImplementTransformers
- Status: 50% complete
- Blockers: None
- Next: Phase2TestTransformers after implementation

## Coverage Status
- Phase 1: 78% (target 75%+) ✓
- Phase 2: TBD (target 75%+)
- Overall: TBD (target 65%+)

## Risks/Issues
1. [RESOLVED] Keyring unavailable on Linux - using encrypted file fallback
2. [OPEN] JSON accumulation complex - monitoring Phase2ImplementTransformers

## Key Decisions
- 2026-01-24: Using 4-tier keyring fallback (not keyring-only)
- 2026-01-26: All security tests pass on Docker Alpine

## Next Milestones
- Phase 2 complete: 2026-01-31 (target)
- Phase 6 complete: 2026-02-14 (target)
- Final completion: 2026-03-07 (target)
```

### Communication with Human

**When to Escalate:**
1. Critical blocker >8 hours
2. Security issue found
3. Design decision needed
4. Spec ambiguity found
5. Timeline slipping >3 days
6. Test coverage can't reach target

**Escalation Format:**
```markdown
ESCALATION: [Brief Description]

Phase: Phase X
Severity: HIGH/MEDIUM/LOW
Impact: [Description of impact]
Attempted Solutions: [What you tried]
Recommendation: [What you suggest]
Need Decision On: [Specific question]
```

**Status Reports:**
Weekly summary:
```markdown
Week X Status Report (Days Y-Z)

Completed:
- Phase 1: Foundation & Security ✓
- Phase 2: Transformation Layer ✓

In Progress:
- Phase 3: Provider Registry (Day 2 of 4)

Blockers:
- None

Metrics:
- Test Coverage: 76% (target 65%+) ✓
- Tests Passing: 142/142 ✓
- Performance: No regressions ✓

Next Week:
- Complete Phase 3
- Start Phase 4 (providers)

Risks:
- Phase 4 may take extra day due to OpenAI SDK complexity
```

### Testing Strategy

**Unit Tests (Run Frequently):**
```bash
# Run all unit tests
pytest tests/unit/ -v

# Run specific module
pytest tests/unit/test_provider_security.py -v

# With coverage
pytest tests/unit/ --cov=core.llm.providers --cov-report=html
```

**Integration Tests (Run After Each Phase):**
```bash
# All integration tests
pytest tests/integration/ -v

# Specific integration test
pytest tests/integration/test_providers.py -v
```

**Resource Lifecycle Tests (Phase 10):**
```bash
# Memory leak detection
pytest tests/integration/test_resource_lifecycle.py -v

# With memray profiling
memray run pytest tests/integration/test_resource_lifecycle.py
memray flamegraph memray-pytest-*.bin
```

**Full Test Suite (Before Phase Completion):**
```bash
# Everything
pytest tests/ --cov=core.llm --cov-report=html -v

# Check coverage
open htmlcov/index.html
```

### Version Control

**Commit Strategy:**
- Commit after each agent completes
- Commit after each sub-phase (6a, 6b, 6c)
- Create tags after each phase

**Commit Message Format:**
```bash
git commit -m "Phase X: [Component] - [Brief Description]

- Implemented X, Y, Z
- Tests: N passing
- Coverage: X%

Agent: PhaseXAgentName"
```

**Phase Tags:**
```bash
git tag -a phase-1-complete -m "Phase 1: Foundation & Security Complete"
git tag -a phase-6a-complete -m "Phase 6a: Wrapper Pattern Complete"
```

### Documentation Requirements

**Code Documentation:**
- All public functions have docstrings
- All classes have docstrings
- Complex logic has inline comments
- Type hints on all functions

**Architecture Documentation:**
- Update architecture docs after major changes
- Keep diagrams current
- Document design decisions

**User Documentation:**
- Setup guides
- Configuration examples
- Troubleshooting guides
- Migration guides

### Success Metrics

**Technical Metrics:**
- Test coverage: 65%+ overall
- All tests passing
- No memory leaks (<1MB/100ops)
- No FD leaks (<5/100ops)
- Performance: no regressions (within 5%)

**Functional Metrics:**
- Both providers working
- Tool calling functional
- Profile switching atomic
- All 9 plugins compatible
- Question Gate preserved

**Quality Metrics:**
- Code review completed
- Documentation complete
- Security audit passed
- Performance tested
- Enterprise scenarios tested

---

## Final Checklist

Before declaring project complete:

**Code Quality:**
- [ ] All code reviewed
- [ ] All tests passing (315+ tests)
- [ ] Coverage ≥65%
- [ ] No linting errors
- [ ] Type hints complete
- [ ] Docstrings complete

**Functionality:**
- [ ] OpenAI provider works
- [ ] Anthropic provider works
- [ ] Tool calling works (both providers)
- [ ] Profile switching works
- [ ] Question Gate works
- [ ] MCP integration works
- [ ] All 9 plugins work

**Security:**
- [ ] 4-tier keyring fallback works
- [ ] API keys stored securely
- [ ] Logging redaction works
- [ ] URL validation works
- [ ] No key leakage in errors
- [ ] Security audit passed

**Performance:**
- [ ] No memory leaks
- [ ] No FD leaks
- [ ] No connection leaks
- [ ] No thread leaks
- [ ] Streaming latency acceptable
- [ ] Profile switching <1s

**Enterprise:**
- [ ] Works in Docker
- [ ] Works in Kubernetes
- [ ] Works in CI/CD
- [ ] Works in Lambda
- [ ] Encrypted file backend works
- [ ] Environment variable mode works

**Documentation:**
- [ ] User guide complete
- [ ] Developer guide complete
- [ ] Testing guide complete
- [ ] API reference complete
- [ ] Migration guide complete
- [ ] Troubleshooting guide complete

**Deployment:**
- [ ] pyproject.toml updated
- [ ] requirements.txt updated
- [ ] CHANGELOG.md updated
- [ ] README.md updated
- [ ] Version bumped

---

## Your First Steps

1. **Read Both Specs Completely:**
   - Read spec v2.1 FINAL (2,353 lines)
   - Read ADDENDUM (3,088 lines)
   - Understand all 4 priority fixes
   - Note critical sections

2. **Set Up Tracking:**
   - Create `docs/specs/IMPLEMENTATION-PROGRESS.md`
   - Initialize phase status
   - Set up risk register
   - Create decision log

3. **Start Phase 0:**
   - Spawn 5 analysis agents in parallel
   - Monitor progress
   - Review analysis documents
   - Validate completeness

4. **Begin Phase 1:**
   - After Phase 0 validated
   - Start with models agent
   - Proceed sequentially
   - Test after each agent

5. **Maintain Momentum:**
   - Daily agent monitoring
   - Frequent commits
   - Regular testing
   - Weekly status reports

---

## Remember

**Your Role:** You are the project manager. You coordinate agents, ensure quality, manage risks, and deliver the complete implementation.

**Your Authority:** You can spawn agents, stop agents, make implementation decisions, and escalate when needed.

**Your Responsibility:** Deliver a working, tested, documented OpenAI SDK integration in 8-9 weeks.

**Your Success:** When all 10 phases are complete, all tests pass, coverage is 65%+, and both providers work flawlessly.

---

**GOOD LUCK! BEGIN WITH PHASE 0.**
