# Koder 4000 - Implementation Plan

## Overview

Koder 4000 is a multi-process MCP (Model Context Protocol) system for AI-assisted feature development. It consists of two MCP servers:

1. **Feature Analyzer MCP** - Analyzes feature documents, identifies gaps, manages Q&A, generates complete definitions and implementation plans
2. **Code Review MCP** - Orchestrates code review with multiple specialized agents (bugs, best practices, security, performance, simplification)

## Architecture Decisions

Based on user requirements:
- **MCP SDK**: rmcp crate
- **LLM Access**: Via MCP client (Claude Code orchestrates LLM calls, MCPs manage state)
- **Storage**: File system only (JSON + Markdown)
- **Architecture**: Multi-process (separate MCP servers)

## Project Structure

```
k4000/
├── Cargo.toml                    # Workspace root
├── CLAUDE.md                     # Instructions for Claude Code
├── README.md
│
├── crates/
│   ├── k4000-core/               # Shared types, traits, errors
│   │   ├── Cargo.toml
│   │   └── src/
│   │       ├── lib.rs
│   │       ├── types/
│   │       │   ├── mod.rs
│   │       │   ├── feature.rs    # FeatureDocument, FeatureStatus, Question, etc.
│   │       │   └── review.rs     # ReviewSession, ReviewFinding, Severity, etc.
│   │       ├── storage.rs        # StateManager for file operations
│   │       └── error.rs          # K4000Error, K4000Result
│   │
│   ├── k4000-feature-mcp/        # Feature Analyzer MCP Server
│   │   ├── Cargo.toml
│   │   └── src/
│   │       ├── main.rs           # Entry point, stdio transport
│   │       └── server.rs         # MCP tools implementation
│   │
│   └── k4000-review-mcp/         # Code Review MCP Server
│       ├── Cargo.toml
│       └── src/
│           ├── main.rs           # Entry point, stdio transport
│           └── server.rs         # MCP tools implementation
│
├── config/
│   └── default.toml              # Default configuration
│
└── data/                         # Runtime data (gitignored)
    └── features/                 # Feature documents and state
        └── {feature-name}/
            ├── feature.md        # Human-readable markdown
            ├── state.json        # Feature state
            └── review-{id}.json  # Review sessions
```

## Core Types

### Feature Document (`k4000-core/src/types/feature.rs`)

```rust
pub enum FeatureStatus {
    Draft,           // Initial markdown created
    Analyzing,       // Being analyzed for gaps
    AwaitingAnswers, // Waiting for human Q&A responses
    Ready,           // Complete definition generated
    Implementing,    // Claude Code is building it
    Reviewing,       // In code review cycle
    Done,            // Complete
}

pub struct Question {
    pub id: String,
    pub question: String,
    pub answered: bool,
    pub answer: Option<String>,
    pub category: QuestionCategory,
}

pub struct FeatureState {
    pub name: String,
    pub status: FeatureStatus,
    pub created_at: String,
    pub updated_at: String,
    pub questions: Vec<Question>,
    pub current_review: Option<String>,
    pub review_iterations: u32,
}
```

### Review Types (`k4000-core/src/types/review.rs`)

```rust
pub enum Severity { Critical, High, Medium, Low, Info }
pub enum ReviewCategory { Bugs, BestPractices, Security, Performance, Simplification }

pub struct ReviewFinding {
    pub id: String,
    pub category: ReviewCategory,
    pub file: String,
    pub line: Option<u32>,
    pub severity: Severity,
    pub description: String,
    pub suggestion: Option<String>,
    pub resolved: bool,
}

pub struct ReviewSession {
    pub id: String,
    pub feature_name: String,
    pub iteration: u32,
    pub status: ReviewStatus,
    pub files_reviewed: Vec<String>,
    pub findings: Vec<ReviewFinding>,
}
```

## MCP Tools

### Feature Analyzer MCP Tools

| Tool | Description | Parameters |
|------|-------------|------------|
| `create_feature` | Create new feature from description | `name`, `description`, `project_path` |
| `analyze_feature` | Analyze feature document for gaps, reads project code for context | `feature_name`, `project_path` |
| `get_project_context` | Analyze project structure, patterns, and architecture | `project_path` |
| `get_feature_status` | Get current status | `feature_name` |
| `get_feature_document` | Get markdown content | `feature_name` |
| `save_questions` | Save clarifying questions | `feature_name`, `questions_json` |
| `save_qa_response` | Save answer to question | `feature_name`, `question_id`, `answer` |
| `update_feature_document` | Update markdown with new sections | `feature_name`, `content` |
| `set_feature_status` | Update status | `feature_name`, `status` |
| `list_features` | List all features | (none) |

### Code Review MCP Tools

| Tool | Description | Parameters |
|------|-------------|------------|
| `submit_for_review` | Submit code for review | `feature_name`, `files_json`, `diff` |
| `save_review_findings` | Save findings from analysis | `feature_name`, `review_id`, `findings_json` |
| `get_review_status` | Get review summary | `feature_name`, `review_id` |
| `get_review_results` | Get all findings | `feature_name`, `review_id` |
| `mark_finding_resolved` | Mark finding as fixed | `feature_name`, `review_id`, `finding_id` |
| `check_iteration_limit` | Check if too many iterations, prompts human to continue | `feature_name`, `max_iterations?` |
| `complete_review` | Finalize review session | `feature_name`, `review_id`, `recommendation` |

## Workflow

### Phase 1: Feature Analysis
1. Human creates markdown in `data/features/{name}/feature.md`
2. Claude Code calls `create_feature` with project path
3. Claude calls `get_project_context` to understand:
   - Project structure and file organization
   - Existing code patterns and architecture
   - Technology stack and dependencies
   - Testing patterns and conventions
4. Claude calls `analyze_feature` which:
   - Analyzes the feature document for gaps
   - Cross-references with project context
   - Identifies integration points
5. Claude calls `save_questions` with clarifying questions (informed by project context)
6. Human answers via `save_qa_response`
7. Claude generates Complete Definition section via `update_feature_document`
8. Claude generates Plan section (with specific files to modify/create) via `update_feature_document`
9. Status becomes `Ready`

### Phase 2: Implementation
1. Human reviews document, makes changes
2. Human instructs Claude Code to implement
3. Claude follows TDD, implements feature
4. Status becomes `Implementing`

### Phase 3: Code Review Loop
1. Claude calls `submit_for_review` with changed files and diff
2. Claude analyzes code from 5 perspectives (bugs, best practices, security, performance, simplification)
3. Claude calls `save_review_findings` for each category
4. If findings exist:
   - Claude fixes issues
   - Calls `mark_finding_resolved` for each fix
   - Calls `submit_for_review` again (new iteration)
5. `check_iteration_limit` checks iteration count (default: 5 iterations)
   - If limit reached, asks human: "Continue with more iterations?"
   - Human can approve continuation or manually review
6. When approved, Claude calls `complete_review`

### Phase 4: Completion
1. Claude adds `Finishing Thoughts` section if noteworthy
2. Claude updates project documentation
3. Status becomes `Done`

## Dependencies

```toml
[workspace.dependencies]
# Async runtime
tokio = { version = "1", features = ["full"] }

# MCP
rmcp = { version = "0.3", features = ["server", "transport-io"] }

# Serialization
serde = { version = "1", features = ["derive"] }
serde_json = "1"

# Error handling
anyhow = "1.0"
thiserror = "2"

# Time & IDs
chrono = { version = "0.4", features = ["serde"] }
uuid = { version = "1", features = ["v4", "serde"] }
```

## Implementation Order

### Step 1: Project Setup
- Create workspace Cargo.toml
- Create k4000-core crate with types
- Implement StateManager for file operations
- Write unit tests for state management

### Step 2: Feature Analyzer MCP
- Create k4000-feature-mcp crate
- Implement MCP server with rmcp
- Add tools: `list_features`, `get_feature_status`, `get_feature_document`
- Add tools: `create_feature`, `save_questions`, `save_qa_response`
- Add tools: `update_feature_document`, `set_feature_status`
- Test with manual stdio interaction

### Step 3: Code Review MCP
- Create k4000-review-mcp crate
- Implement MCP server with rmcp
- Add tools: `submit_for_review`, `save_review_findings`
- Add tools: `get_review_status`, `get_review_results`
- Add tools: `mark_finding_resolved`, `check_iteration_limit`, `complete_review`
- Test with manual stdio interaction

### Step 4: Integration
- Update CLAUDE.md with workflow instructions
- Configure Claude Code to use both MCP servers
- Create example feature document
- End-to-end test with Claude Code
- Document setup and usage

## File Formats

### feature.md (Human-readable)
```markdown
# Feature: {name}

## Description
{Original description}

---

## Q & A

### Q1: {question}
**Answer:** {answer}

---

## Complete Definition
{AI-generated complete spec}

---

## Plan
1. {step}
2. {step}

---

## Finishing Thoughts
{Notable observations}
```

### state.json
```json
{
  "name": "feature-name",
  "status": "analyzing",
  "created_at": "2025-11-27T12:00:00Z",
  "updated_at": "2025-11-27T14:30:00Z",
  "questions": [...],
  "current_review": null,
  "review_iterations": 0
}
```

### review-{id}.json
```json
{
  "id": "abc123",
  "feature_name": "feature-name",
  "iteration": 1,
  "status": "complete",
  "files_reviewed": ["src/lib.rs"],
  "findings": [...]
}
```

## Configuration

### Claude Code MCP Configuration
```json
{
  "mcpServers": {
    "k4000-feature": {
      "command": "./target/release/k4000-feature-mcp",
      "env": {
        "K4000_DATA_DIR": "./data"
      }
    },
    "k4000-review": {
      "command": "./target/release/k4000-review-mcp",
      "env": {
        "K4000_DATA_DIR": "./data"
      }
    }
  }
}
```

## Design Notes

### What This MVP Excludes (Defer for Later)
- Database storage (files sufficient for single-user)
- Web UI (CLI/MCP only)
- Concurrent feature processing
- Direct LLM calls from MCP (Claude Code orchestrates)
- Complex plugin system (built-in agents only)
- Authentication (local tool)
- CI/CD integration

### Future Extensibility Points
- Storage trait can be introduced when database needed
- ReviewAgent trait can be added for plugin system
- Configuration can be expanded with TOML files
- Multi-project support via ProjectId field
