# Issue #59 GAMEPLAN - Issue Management CLI Tool with Plugin Architecture

## 🎯 Mission Statement

Create a unified CLI wrapper/facade for issue management that provides a consistent interface across multiple backends (Gitea, local files, future Jira) to improve Claude's efficiency and eliminate API call failures.

---

## 📋 Issue Analysis

### Problem Statement
- **Current Pain Point**: Claude sometimes misses existing issue functions and tries direct API calls that fail
- **Root Cause**: Fragmented issue management tools scattered across Makefile targets and tddai_cli.py
- **Impact**: Workflow inefficiencies, failed operations, inconsistent issue interactions

### Success Criteria
1. ✅ Unified CLI interface for all issue operations
2. ✅ Plugin architecture supporting multiple backends
3. ✅ Gitea plugin integrating existing functionality
4. ✅ Local file-based plugin for offline/repo-only workflows
5. ✅ Improved Claude workflow efficiency
6. ✅ Extensible foundation for future backends (Jira, GitHub, etc.)

---

## 🏗️ Architecture Design

### Core Components

#### 1. Issue Management CLI (`markitect issues`)
```bash
markitect issues list                    # List all issues
markitect issues list --state open      # List open issues
markitect issues show 59                # Show specific issue
markitect issues create "Title" "Body"  # Create new issue
markitect issues comment 59 "Comment"   # Add comment
markitect issues close 59               # Close issue
markitect issues config                 # Show/configure backend
```

#### 2. Plugin Architecture
```
markitect/
├── issues/
│   ├── __init__.py           # Core CLI interface
│   ├── manager.py            # Issue manager with plugin loading
│   ├── base.py               # Abstract base plugin interface
│   ├── plugins/
│   │   ├── __init__.py
│   │   ├── gitea.py          # Gitea backend plugin
│   │   ├── local.py          # Local file backend plugin
│   │   └── jira.py           # Future Jira plugin
│   └── models.py             # Issue data models
```

#### 3. Plugin Interface
```python
class IssueBackend(ABC):
    @abstractmethod
    def list_issues(self, state: Optional[str] = None) -> List[Issue]

    @abstractmethod
    def get_issue(self, issue_id: str) -> Issue

    @abstractmethod
    def create_issue(self, title: str, body: str) -> Issue

    @abstractmethod
    def add_comment(self, issue_id: str, comment: str) -> None

    @abstractmethod
    def close_issue(self, issue_id: str) -> None
```

---

## 🎯 TDD8 Implementation Phases

### Phase 1: ISSUE Analysis
**Scope**: Understand existing infrastructure and design plugin architecture

**Tasks**:
1. ✅ Analyze current tddai_cli.py issue management functions
2. ✅ Review Makefile issue targets and integration points
3. ✅ Design plugin architecture and interfaces
4. ✅ Define CLI command structure and user experience
5. ✅ Identify integration points with existing MarkiTect CLI

**Deliverable**: Architecture design and interface definitions

### Phase 2: TEST - Core Infrastructure Tests
**Scope**: Write failing tests for plugin architecture and CLI interface

**Test Categories**:
1. **Plugin Manager Tests**
   - Plugin discovery and loading
   - Backend switching and configuration
   - Error handling for missing/invalid plugins

2. **CLI Interface Tests**
   - Command parsing and routing
   - Output formatting consistency
   - Error message standardization

3. **Mock Plugin Tests**
   - Abstract interface compliance
   - Plugin lifecycle management

**Deliverable**: Comprehensive test suite (initially failing)

### Phase 3: RED - Verify Test Failures
**Scope**: Confirm all tests fail before implementation

**Validation**:
- Plugin loading fails (no plugins exist)
- CLI commands fail (no implementation)
- Interface violations detected properly
- Error handling works as expected

### Phase 4: GREEN - Minimal Implementation
**Scope**: Implement core infrastructure to pass tests

**Implementation Priority**:
1. **Core Models**: Issue, Comment data classes
2. **Plugin Manager**: Discovery, loading, configuration
3. **Base CLI**: Command structure and routing
4. **Mock Plugin**: For testing and validation

**Deliverable**: Basic plugin architecture with mock backend

### Phase 5: GREEN+ - Gitea Plugin Implementation
**Scope**: Implement Gitea plugin integrating existing functionality

**Integration Tasks**:
1. **Migrate tddai_cli.py Functions**: Extract and adapt existing Gitea code
2. **API Integration**: Reuse existing Gitea API connections
3. **Configuration**: Inherit existing URL and authentication settings
4. **Testing**: Verify compatibility with current workflows

**Deliverable**: Fully functional Gitea plugin

### Phase 6: GREEN++ - Local File Plugin
**Scope**: Implement file-based local issue management

**Features**:
1. **Directory Structure**: `.markitect/issues/` with markdown files
2. **Issue Format**: YAML frontmatter + markdown body
3. **State Management**: File naming and organization
4. **Git Integration**: Version control friendly format

**File Structure**:
```
.markitect/issues/
├── open/
│   ├── 059-issue-management-cli.md
│   └── 060-next-feature.md
├── closed/
│   └── 058-completed-issue.md
└── config.yml
```

**Deliverable**: Offline-capable local issue management

### Phase 7: REFACTOR - Code Quality & Performance
**Scope**: Clean up architecture and optimize performance

**Improvements**:
1. **Code Quality**: Remove duplication, improve naming
2. **Performance**: Caching, lazy loading of plugins
3. **Error Handling**: Comprehensive error messages
4. **Documentation**: Inline documentation and help text

### Phase 8: DOCUMENT - CLI Help & Documentation
**Scope**: Update CLI help and create user documentation

**Documentation Tasks**:
1. **CLI Help**: Comprehensive help for all commands
2. **Plugin Development**: Guide for creating new backend plugins
3. **Configuration**: Backend setup and switching instructions
4. **Migration**: Guide from existing tddai_cli.py usage

### Phase 9: REFINE - Integration & Polish
**Scope**: Polish integration with existing MarkiTect CLI

**Integration Tasks**:
1. **CLI Integration**: Seamless integration with `markitect` command
2. **Backward Compatibility**: Maintain existing Makefile targets
3. **Configuration**: Integration with existing config system
4. **Testing**: End-to-end workflow validation

### Phase 10: PUBLISH - Deployment & Issue Closure
**Scope**: Commit implementation and close Issue #59

**Deployment Tasks**:
1. **Git Commit**: Comprehensive commit with all changes
2. **Issue Closure**: Close Issue #59 with implementation summary
3. **Documentation Update**: Update NEXT_SESSION_BRIEFING.md
4. **Future Planning**: Identify follow-up improvements

---

## 🛠️ Technical Implementation Details

### CLI Integration Strategy
```python
# Add to markitect/cli.py
@cli.group()
def issues():
    """Issue management with multiple backend support."""
    pass

@issues.command()
@click.option('--state', type=click.Choice(['open', 'closed', 'all']), default='all')
@click.option('--backend', help='Override configured backend')
def list(state, backend):
    """List issues from configured backend."""
    manager = IssueManager(backend=backend)
    issues = manager.list_issues(state=state)
    # Format and display
```

### Plugin Discovery Mechanism
```python
class IssueManager:
    def __init__(self, backend: Optional[str] = None):
        self.backend = backend or self._get_configured_backend()
        self.plugin = self._load_plugin(self.backend)

    def _discover_plugins(self) -> Dict[str, Type[IssueBackend]]:
        # Plugin discovery logic
        pass
```

### Configuration Strategy
```yaml
# .markitect/config/issues.yml
default_backend: gitea
backends:
  gitea:
    url: "http://92.205.130.254:32166"
    repo: "coulomb/markitect_project"
  local:
    directory: ".markitect/issues"
    auto_git: true
```

---

## 🧪 Testing Strategy

### Test Categories
1. **Unit Tests**: Individual plugin methods and CLI commands
2. **Integration Tests**: Plugin manager with real/mock backends
3. **End-to-End Tests**: Complete workflows from CLI to backend
4. **Compatibility Tests**: Existing Makefile target compatibility

### Mock Strategy
- **Gitea Mock**: Simulate API responses for testing
- **Local Mock**: Temporary filesystem for testing
- **Network Mock**: Handle API failures gracefully

### Test Data
- **Sample Issues**: Realistic issue data for testing
- **Edge Cases**: Error conditions, malformed data
- **Performance**: Large issue lists, concurrent operations

---

## 🎯 Success Metrics

### Functional Success
- ✅ All issue operations work through unified CLI
- ✅ Plugin switching works seamlessly
- ✅ Existing workflows remain compatible
- ✅ Error handling provides clear guidance

### Performance Success
- ✅ Response times under 2 seconds for list operations
- ✅ Plugin loading under 500ms
- ✅ No regression in existing functionality

### User Experience Success
- ✅ Claude can perform all issue operations without API failures
- ✅ Clear, consistent CLI interface across backends
- ✅ Helpful error messages and guidance
- ✅ Backward compatibility with existing tools

---

## 🚀 Development Timeline

### Sprint 1 (TDD8 Phases 1-4): Foundation
- **Duration**: 2-3 hours
- **Deliverable**: Core plugin architecture with tests
- **Milestone**: Mock plugin working through CLI

### Sprint 2 (TDD8 Phases 5-6): Backend Implementation
- **Duration**: 3-4 hours
- **Deliverable**: Gitea and Local plugins functional
- **Milestone**: All backends operational

### Sprint 3 (TDD8 Phases 7-10): Polish & Integration
- **Duration**: 2-3 hours
- **Deliverable**: Production-ready integration
- **Milestone**: Issue #59 complete and closed

**Total Estimated Time**: 7-10 hours across multiple sessions

---

## 🔄 Next Steps

### Immediate Actions
1. **Start TDD8 Cycle**: `make tdd-start NUM=59`
2. **Create Test Workspace**: Set up Issue #59 TDD environment
3. **Begin ISSUE Phase**: Analyze existing code and design interfaces
4. **Write Failing Tests**: Comprehensive test coverage for plugin architecture

### Long-term Vision
- **Extensible Backend System**: Easy addition of new issue management systems
- **Unified Developer Experience**: Consistent issue management regardless of backend
- **Offline Capabilities**: Local file-based workflows for environments without external services
- **Enterprise Integration**: Future support for Jira, Azure DevOps, etc.

---

*GAMEPLAN Generated: October 1, 2025*
*Target: Issue #59 - Issue Management CLI Tool*
*Strategy: TDD8 with Plugin Architecture*
*Estimated Completion: 7-10 hours across multiple sessions*