# Koder 4000 (K4000)

AI-assisted task development and code review system using MCP (Model Context Protocol).

## Overview

K4000 provides a unified MCP server that helps LLMs create well-defined tasks and perform thorough code reviews:

**`k4000-mcp`** - Single server providing:
- Task analysis, gap identification, Q&A management, and development tracking
- Code review from 5 perspectives with iterative feedback loops
- Progress logging for context restoration across sessions

## Building

```bash
cargo build --release
```

Binary will be at:
- `target/release/k4000-mcp`

## Configuration

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `K4000_MAX_ITERATIONS` | `3` | Max review iterations before asking human (review server only) |

### Project Configuration

K4000 supports project-level configuration via `tasks/.config/config.toml`. This file controls behavior that applies to all tasks in the project.

**Location:** `{project}/tasks/.config/config.toml`

**Example config.toml:**

```toml
# K4000 Project Configuration

# Feature approval mode controls whether the agent waits for human approval
# between features during implementation.
#
# Values:
#   - "manual" (default): Agent pauses after each feature and asks user
#                         for approval before starting the next feature
#   - "auto": Agent proceeds to the next feature automatically
#
feature_approval_mode = "auto"

# Maximum number of verification loops for acceptance criteria before failing.
#
# Values:
#   - Integer >= 1 (default: 5)
#
acceptance_criteria_max_iterations = 5

# Automatically create a git commit when a task is marked as done.
#
# When enabled, K4000 will stage only the files modified during the task
# (tracked via review files) and commit them with a message containing
# the task name and description.
#
# Values:
#   - false (default): No automatic commit
#   - true: Automatically commit when task status is set to 'done'
#
# Note: If the commit fails (e.g., pre-commit hook fails), the status
# change to 'done' will be blocked.
#
auto_commit_on_done = false
```

**Settings:**

| Setting | Default | Description |
|---------|---------|-------------|
| `feature_approval_mode` | `manual` | Controls feature-to-feature workflow. `manual` = pause and ask, `auto` = proceed automatically |
| `acceptance_criteria_max_iterations` | `5` | Max verification loops before failing acceptance criteria |
| `auto_commit_on_done` | `false` | Automatically git commit task files when marking task as done |

**Task-Level Override:**

Individual tasks can override the project setting via their `TaskState.feature_approval_mode` field. The priority order is:
1. Task-level override (if set)
2. Project config (`tasks/.config/config.toml`)
3. Default (`manual`)

## MCP Server Setup

Add to your MCP client configuration (e.g., Claude Code's `mcp_servers.json`):

```json
{
  "k4000": {
    "command": "/path/to/k4000-mcp"
  }
}
```

## IMPORTANT: Automatic Workflow Behavior

When using K4000, Claude MUST follow these automatic behaviors:

### After Implementation Completes → Automatically Start Review

When implementation is finished (tests pass, code is written), Claude MUST:
1. Set task status to `reviewing`
2. Immediately call `create_review_session` with the modified files
3. Review from all 5 perspectives and submit findings
4. DO NOT wait for user to ask for review - it happens automatically

### After Fixing Review Issues → Automatically Re-review

When Claude fixes issues from a review, it MUST:
1. After fixing each batch of issues, call `complete_iteration` with `start_next=true`
2. Immediately start a new review of the fixed code
3. Continue this loop until either:
   - All critical/high findings are resolved → call `approve_review`
   - Max iterations reached → ask user if they want to continue
4. DO NOT wait for user to request re-review - it happens automatically

### The Review Loop

```
implement code
    ↓
[AUTOMATIC] create_review_session
    ↓
[AUTOMATIC] submit_findings (all 5 perspectives)
    ↓
fix critical/high issues
    ↓
[AUTOMATIC] complete_iteration(start_next=true)
    ↓
[AUTOMATIC] re-review fixed code
    ↓
(repeat until approved or max iterations)
```

## Feature Right-Sizing Guidelines

**CRITICAL**: Each feature MUST be completable in ONE context window (~one agent iteration).

The agent should be able to start fresh with no memory of previous work and complete the feature before running out of context. If a feature is too big, the LLM runs out of context before finishing.

### The 2-3 Sentence Rule

**If you cannot describe a feature's change in 2-3 sentences, it is too big and MUST be split.**

This rule applies to individual features, not the overall task. Each feature in `feature-list.json` should be small enough that its implementation can be explained concisely.

### Right-Sized Features (Good Examples)

These are appropriate feature sizes:
- Add a database column + migration
- Create a single UI component
- Implement one server action
- Add a filter to an existing list
- Write tests for one module
- Add validation to a form field
- Create a single API endpoint

### Too Big Features (Must Split)

These features are too large and must be broken down:

| Too Big | Split Into |
|---------|------------|
| "Build the entire dashboard" | Schema, queries, components, filters (4 features) |
| "Add authentication" | Schema, middleware, login UI, session handling (4 features) |
| "Refactor the API" | One feature per endpoint |
| "Implement user management" | User model, CRUD endpoints, UI components, permissions (4+ features) |

### Validation Before Saving Features

**MANDATORY**: Before calling `save_features`, the agent MUST:

1. **Evaluate each feature** against the 2-3 sentence rule
2. **Check for scope creep** - features that try to do too much
3. **Identify splitting opportunities** - if a feature has multiple distinct parts

If ANY feature fails the 2-3 sentence rule:
- The agent MUST NOT call `save_features`
- The agent MUST ask the human for permission to proceed OR split the feature
- Only human override can allow saving an oversized feature

**Example validation dialogue:**
```
Agent: "Feature F3 'Implement complete user authentication system' is too large.
       It includes login, registration, password reset, and session management.
       
       I recommend splitting into:
       - F3a: Login endpoint and UI
       - F3b: Registration endpoint and UI  
       - F3c: Password reset flow
       - F3d: Session management middleware
       
       Should I split this feature, or do you want to proceed with the large feature anyway?"
```

## Task Development Workflow

### Directory Structure

K4000 uses a `tasks/` folder in your project with subfolders for each task:

```text
project/
  tasks/
    .config/                   # K4000 project configuration
      config.toml              # Project settings (feature_approval_mode, etc.)
    my-task/
      task.md                  # User's original description (READ ONLY for K4000)
      plan.md                  # Implementation plan + estimate (K4000 writes)
      feature-list.json        # Extracted features with steps and acceptance criteria
      questions.json           # Q&A in JSON format
      state.json               # Task lifecycle state (status, timestamps, review info)
      progress.txt             # Progress log
      .review/                 # Review sessions (hidden)
        review-*.json
      mockup.png               # User can add other assets
```

### File Responsibilities

| File | Created By | Read By | Written By |
|------|------------|---------|------------|
| task.md | User | K4000, User | User only |
| plan.md | K4000 | K4000, User | K4000 |
| feature-list.json | K4000 | K4000, User | K4000 |
| questions.json | K4000 | K4000, User | K4000 |
| state.json | K4000 | K4000 | K4000 |
| progress.txt | K4000 | K4000, User | K4000 |
| .review/*.json | K4000 | K4000 | K4000 |

### Progress Tracking

K4000 automatically logs progress to `progress.txt` in each task folder. This helps agents quickly understand the state of work when starting with a fresh context window.

#### progress.txt Format

Two formats are supported:
- **Standard**: `[timestamp] [agent] message`
- **With feature**: `[timestamp] [agent] [feature_id] message`

```
[2026-01-08T10:30:00Z] [k4000] Task created
[2026-01-08T10:30:05Z] [k4000] Task analysis started
[2026-01-08T10:31:00Z] [k4000] 5 features saved to feature-list.json
[2026-01-08T10:32:00Z] [k4000] 6 questions generated, awaiting answers
[2026-01-08T10:45:00Z] [k4000] All questions answered, status set to ready
[2026-01-08T11:00:00Z] [k4000] Status changed: ready -> implementing
[2026-01-08T11:15:00Z] [claude] [F1] Starting implementation of storage layer
[2026-01-08T11:30:00Z] [claude] [F1] Added StateManager struct to storage.rs
[2026-01-08T11:45:00Z] [claude] [F1] Completed storage layer, all tests pass
[2026-01-08T12:00:00Z] [k4000] Feature F1 verified and marked as passing (1/5)
[2026-01-08T12:15:00Z] [k4000] Review session created (iteration 1, 3 files)
[2026-01-08T12:30:00Z] [k4000] Review findings submitted: 5 new (0 critical, 2 high)
[2026-01-08T13:00:00Z] [k4000] Review approved
```

Each entry has:
- **Timestamp**: ISO 8601 format in UTC
- **Agent name**: Who performed the action (`k4000` for automatic, agent name for explicit)
- **Feature ID** (optional): Which feature this relates to (e.g., `F1`, `F2`)
- **Message**: Description of what happened

#### Automatic Logging

K4000 automatically logs progress when:
- Task is created
- Task analysis starts
- Features are saved
- Questions are generated
- Questions are answered
- Status changes
- Implementation plan is updated
- Feature verification starts
- Features are verified
- Review session is created
- Review findings are submitted
- Review iteration completes
- Review is approved

#### Explicit Logging by Agents

Agents SHOULD log progress explicitly during implementation to help future context restoration. Use `log_progress` to record:

**What to log:**
- Starting work on a feature (include `feature_id`)
- Code additions/changes summarized (what file, what was added)
- Completing a feature
- Encountering blockers or issues
- Resolving bugs
- Undoing or reverting changes
- Important implementation decisions

**Example calls:**
```
# Starting a feature
log_progress(task_name="my-task", agent_name="claude", feature_id="F1", message="Starting API endpoint implementation")

# Code added
log_progress(task_name="my-task", agent_name="claude", feature_id="F1", message="Added auth middleware to src/middleware/auth.rs")

# Completing work
log_progress(task_name="my-task", agent_name="claude", feature_id="F1", message="Completed JWT validation, tests pass")

# Blocker encountered
log_progress(task_name="my-task", agent_name="claude", message="Blocked: database schema migration needed before F2")

# Bug fixed
log_progress(task_name="my-task", agent_name="claude", feature_id="F2", message="Fixed null pointer in user lookup (was missing null check)")

# Without feature_id (general progress)
log_progress(task_name="my-task", agent_name="claude", message="All unit tests passing, ready for review")
```

**Guidelines for good log messages:**
- Keep messages concise but informative (1 sentence)
- Include file names when relevant (e.g., "Added X to src/foo.rs")
- Use present tense for actions ("Adding...", "Fixed...", "Completed...")
- Reference feature IDs when working on specific features

#### Context Restoration

When starting a new session, agents should call `get_progress` to understand the current state:
```
get_progress(task_name="my-task")
```

This returns the full progress log, helping the agent understand:
- What has been done
- What the current status is
- Who did what and when
- Which features have been worked on

### Phase 1: Task Definition

1. **Create Task**: Use `create_task` with name and description
   - Name is slugified: lowercase, spaces→hyphens, special chars removed, max 40 chars
   - Always uses current working directory's `./tasks/` folder
   - Creates `tasks/{slugified-name}/` folder with `task.md` containing raw description
   - Sets initial status to `draft`
   - **IMPORTANT**: After creation, Claude MUST ask user if they want to analyze the task
2. **Analyze Task**: Use `analyze_task` to identify gaps in the specification
3. **Extract Features**: During analysis, identify discrete features and save with `save_features`
   - Features are written to `feature-list.json`
   - Each feature has: id, category, description, steps (verification steps), acceptance_criteria, passes
   - Optional fields: complexity, dependencies
   - Priority is determined by array order (first = highest priority)
4. **Generate Questions**: After feature extraction, generate clarifying questions and save with `save_questions`
   - Questions are written to `questions.md`
   - Questions should reference specific features when applicable (e.g., "For F1: ...")
5. **Answer Questions**: Human provides answers via `save_qa_response`
   - Answers are updated in `questions.md`
6. **Update Plan**: Incorporate answers and create implementation plan with `update_task_plan`
   - Plan is written to `plan.md`
7. **Generate Estimate**: Before starting implementation, generate a time estimate (see Phase 1.7)

### Phase 1.5: Feature List

During analysis, Claude MUST extract discrete features from the task description:

#### feature-list.json Structure

```json
[
  {
    "id": "F1",
    "category": "functional",
    "description": "Short description of what this feature does",
    "steps": [
      "Step 1 to verify the feature works",
      "Step 2 to verify",
      "Step 3 to verify"
    ],
    "acceptance_criteria": [
      "Clear, objective, testable outcome",
      "Second acceptance criterion"
    ],
    "passes": false,
    "complexity": "moderate",
    "dependencies": ["F2"]
  },
  {
    "id": "F2",
    "category": "api",
    "description": "Another feature description",
    "steps": [
      "Verification step 1",
      "Verification step 2"
    ],
    "acceptance_criteria": [
      "Objective success metric",
      "Observable completion condition"
    ],
    "passes": false
  }
]
```

#### Feature Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | string | yes | Unique identifier (F1, F2, etc.) |
| category | string | yes | Free-form category (functional, ui, api, security, etc.) |
| description | string | yes | What this feature does |
| steps | string[] | yes | Verification steps to confirm feature works (LLM provides these) |
| acceptance_criteria | string[] | yes | Clear, objective, testable criteria for done |
| passes | boolean | yes | Whether all steps and acceptance criteria have been verified (set via mark_feature_complete) |
| complexity | string | no | simple, moderate, complex |
| dependencies | string[] | no | IDs of features this depends on |

**Priority**: Determined by array order (first item = highest priority)

Features help:
- Track implementation progress with verification steps and acceptance criteria
- Identify scope and complexity
- Structure question generation per-feature
- Validate completion before marking task as done
- **IMPORTANT**: `mark_feature_complete` validates that all steps and acceptance criteria are verified before setting `passes=true`

### Phase 1.6: Implementation Plan (AUTOMATIC - Before Implementation)

After all questions are answered and before generating the estimate, Claude MUST write an Implementation Plan to `plan.md`:

#### plan.md Structure

```markdown
---
name: my-task
description: Brief description
status: ready
parts:
  - src/api.rs
  - src/db.rs
estimate:
  optimistic: 2 hours
  normal: 4 hours
  pessimistic: 8 hours
---

# Implementation Plan

## Feature Sizing Checklist

Before implementation, verify each feature is right-sized:

- [ ] Each feature can be described in 2-3 sentences
- [ ] Each feature is completable in one context window
- [ ] No feature tries to do too much (check for "and", "also", "plus")

**Right-sized examples:** Add a DB column, create a single component, implement one endpoint
**Too big (split these):** "Build the dashboard", "Add authentication", "Refactor the API"

If any feature is too large, split it or get human approval before proceeding.

## Task Summary

| ID | Task | Files |
|----|------|-------|
| T1 | Short task description | `path/to/file.rs` |
| T2 | Another task | `path/to/other.rs`, `another.rs` |

## Tasks

- [ ] **T1**: Detailed description of what needs to be done
- [ ] **T2**: Another detailed task description

## Testing Considerations

- How to test the implementation
- Edge cases to verify

---

## Estimate

**Senior Developer Profile:** 5+ years experience, familiar with the project's tech stack.

| Scenario | Time |
|----------|------|
| Optimistic | X hours |
| Normal | Y hours |
| Pessimistic | Z hours |

### Assumptions
- [Key assumption 1]
- [Key assumption 2]
```

### Phase 1.7: Estimation (AUTOMATIC - Before Implementation)

After all questions are answered and the Implementation Plan is complete, Claude MUST generate a time estimate before proceeding to implementation:

1. **Analyze Complexity**: Review the complete task definition, Implementation Plan, and testing considerations
2. **Generate Three-Point Estimate**: Create estimates for:
   - **Optimistic**: Best case scenario, everything goes smoothly
   - **Normal**: Most likely scenario with typical challenges
   - **Pessimistic**: Worst case with unexpected complications
3. **Document Assumptions**: List key assumptions that affect the estimate
4. **Write to plan.md**: Include the estimate in the plan.md frontmatter and body

#### Senior Developer Profile
Estimates assume a senior developer with:
- 5+ years of professional experience
- Familiarity with the project's tech stack
- Understanding of the codebase architecture

### Phase 2: Implementation (TDD)

1. Set task status to `implementing` using `set_task_status`
   - **The response will include all features with their acceptance criteria**
   - **Present these to the user and confirm they look correct before proceeding**
2. Write tests first based on the task document
3. Implement code to make tests pass
4. Run tests to verify implementation
5. **Mark features complete**: As each feature is fully implemented, call `mark_feature_complete`
6. **If plan changes**: Update `plan.md` to reflect reality using `update_task_plan`
7. **AUTOMATIC**: When done, proceed directly to Phase 3 by calling `set_task_status` with `status="reviewing"` and `files=[...]`

**Note**: All features must be marked complete before the task can be set to `done` status.

### Phase 3: Code Review (MANDATORY)

**IMPORTANT**: Code review is MANDATORY. The system will BLOCK setting status to `done` unless:
1. A review session exists for this task
2. The review has been approved via `approve_review`

This phase starts AUTOMATICALLY after implementation:

1. **Start Review**: Call `set_task_status` with `status="reviewing"` and `files=[list of modified files]`
   - This returns instructions to call `create_review_session`
   - Then call `create_review_session` with task name and the files
2. **Review All Perspectives**: Review code and call `submit_findings` for each:
   - `bugs` - Potential bugs and logic errors
   - `best_practices` - Coding standards and patterns
   - `security` - Security vulnerabilities
   - `performance` - Performance issues
   - `simplification` - Code that could be simpler
3. **Fix Issues**: Address findings by severity (critical → high → medium → low)
4. **Re-review**: After fixes, call `complete_iteration(start_next=true)` and repeat review
5. **Approve**: When no critical/high findings remain, call `approve_review`
6. **Done**: Set task status to `done` (will fail if review not approved)

## MCP Tools

All tools are available through the unified `k4000-mcp` server.

### Task Management Tools

| Tool | Description |
|------|-------------|
| `list_project_tasks` | **PRIMARY** - List tasks in the current project's ./tasks/ directory |
| `list_tasks` | List tasks (optionally filtered by project_path) |
| `create_task` | Create a new task (slugifies name, creates tasks/{slug}/ with raw description in task.md, ALWAYS prompts to analyze) |
| `get_task_status` | Get current status and full state of a task |
| `get_task_document` | Get the task.md content (user's original description) |
| `analyze_task` | Analyze task to identify gaps and generate questions |
| `get_project_context` | Get project structure context |
| `save_features` | Save extracted features to feature-list.json (MUST validate sizing first - see Feature Right-Sizing Guidelines) |
| `mark_feature_complete` | Start feature completion - returns steps and acceptance criteria to verify |
| `mark_feature_verified` | Confirm all steps and acceptance criteria verified and set passes=true |
| `save_questions` | Save clarifying questions to questions.md |
| `save_qa_response` | Save human's answer to questions.md |
| `update_task_plan` | Update the plan.md with implementation plan and estimate |
| `set_task_status` | Update task status (validates features complete before allowing 'done') |
| `log_progress` | Log a progress entry to progress.txt (with optional feature_id) |
| `get_progress` | Get the progress log for context restoration |
| `migrate_tasks` | Migrate old features/ folder to new tasks/ format |

### Code Review Tools

| Tool | Description |
|------|-------------|
| `create_review_session` | Start a new review for a task |
| `get_review_session` | Get current review state and findings |
| `list_reviews` | List all reviews for a task |
| `submit_findings` | Submit review findings |
| `mark_finding_resolved` | Mark a finding as resolved |
| `check_iteration_limit` | Check if iteration limit reached |
| `approve_review` | Approve the review (requires no critical/high findings) |
| `complete_iteration` | Complete iteration and optionally start next |
| `get_findings_summary` | Get summary of unresolved findings |

### Tool Usage: Discovering Tasks

When a user wants to see which tasks exist, use `list_project_tasks`:
- Shows only tasks in the **current project's** `./tasks/` directory
- Uses current working directory by default
- Shows status (done/implementing/untracked) and question counts
- Shows whether task.md, plan.md, questions.md exist
- Alerts if old features/ folder exists (migration available)

### Task Statuses

- `draft` - Initial state, being defined
- `analyzing` - Under analysis for gaps
- `awaiting_answers` - Questions generated, waiting for human
- `ready` - All questions answered, ready for implementation
- `implementing` - Code being written
- `reviewing` - Under code review (AUTOMATIC after implementing)
- `done` - Completed

### Finding Severities

- `critical` - Must be fixed before approval
- `high` - Must be fixed before approval
- `medium` - Should be fixed
- `low` - Nice to fix
- `info` - Informational note

### Migration from features/ to tasks/

If a project has an old `features/` folder, use `migrate_tasks` to convert:
- Creates `tasks/{name}/` folder for each feature
- Extracts description to `task.md`
- Extracts Q&A to `questions.json`
- Extracts Implementation Plan + Estimate to `plan.md`
- Creates slim `state.json` in each task folder
- Moves review files to `{task}/.review/`
- Optionally deletes old `features/` folder

## Data Storage

All data is stored in the project's `tasks/` directory. Each task is self-contained in its own folder:

```text
{project_path}/
  tasks/
    .config/
      config.toml              # Project-level settings
    {task-name}/
      task.md                  # User's original description
      plan.md                  # Implementation plan + estimate
      feature-list.json        # Features with verification steps
      questions.json           # Q&A pairs
      state.json               # Task lifecycle state
      progress.txt             # Progress log
      .review/
        review-{id}.json       # Review sessions
```

## Example Workflow

```
# 0. Discover existing tasks in the current project
list_project_tasks()
# Returns tasks from ./tasks/ directory with status info
# If features/ folder exists, suggests migration

# 0.5. (Optional) Migrate from old features/ format
migrate_tasks(project_path="/path/to/project", delete_old=true)

# 1. Create task (creates tasks/user-auth/ folder with task.md)
create_task(
  name="user-auth",
  description="Add user authentication with JWT tokens",
  project_path="/path/to/project"
)

# 2. Analyze and generate questions
analyze_task(task_name="user-auth", project_path="/path/to/project")

# 3. Extract features to feature-list.json
save_features(task_name="user-auth", features_json="[{\"id\": \"F1\", \"category\": \"functional\", \"description\": \"Generate JWT tokens for authenticated users\", \"steps\": [\"Call login endpoint with valid credentials\", \"Verify JWT token is returned\", \"Decode token and verify claims\"], \"acceptance_criteria\": [\"JWT token returned for valid credentials\", \"Token includes expected claims\"]}]")

# 4. Save questions to questions.json (reference features where applicable)
save_questions(task_name="user-auth", questions_json="[{\"id\": \"q1\", \"question\": \"For F1: What JWT expiration time?\", \"category\": \"clarification\"}]")

# 5. Human answers questions
save_qa_response(task_name="user-auth", question_id="q1", answer="Use bcrypt")

# 6. Write implementation plan and estimate to plan.md
update_task_plan(task_name="user-auth", content="...")

# 7. Start implementation
set_task_status(task_name="user-auth", status="implementing")

# 8. [Claude implements the task, writes tests, etc.]
#    If plan changes during implementation, update plan.md
#    Mark features complete as they are implemented:
mark_feature_complete(task_name="user-auth", feature_id="F1")

# 9. AUTOMATIC: Start review immediately after implementation
set_task_status(task_name="user-auth", status="reviewing")
create_review_session(task_name="user-auth", files=["src/auth.rs", "src/jwt.rs"])

# 10. AUTOMATIC: Submit findings from all perspectives
submit_findings(task_name="user-auth", review_id="...", findings_json="[...]")

# 11. Fix issues found in review

# 12. AUTOMATIC: Complete iteration and re-review
complete_iteration(task_name="user-auth", review_id="...", start_next=true)

# 13. AUTOMATIC: Review again, submit new findings, fix, repeat...

# 14. When no critical/high findings remain:
approve_review(task_name="user-auth", review_id="...")

# 15. Mark task done (requires all features to be complete)
set_task_status(task_name="user-auth", status="done")
```
