This session is being continued from a previous conversation that ran out of context. The conversation is summarized below:
Analysis:
Let me chronologically analyze this conversation:

1. **Initial Request - /sync command**: User ran a sync command to pull latest from Gitea and apply settings. I successfully pulled changes from the HTTPS origin (SSH had permission issues) and applied global settings.

2. **Autocoder Status Check**: User asked "Where are we with autocoder project?" I summarized what the session logs indicated, but user wanted verification of actual codebase state.

3. **Codebase Verification**: User asked to "Check codebase to verify what has or has not been done". I explored the actual files and discovered MORE was implemented than the session logs indicated:
   - `parallel_agent.py` - Parallel agent runner
   - `smart_orchestrator.py` - AI-driven parallelization
   - `registry.py` - Project registry
   - Multiple server services
   - Sandbox was already disabled
   - Extended bash allowlist already included SSH, SCP, etc.

4. **Testing Request**: User said "Yes, test everything, spawn SDK agents as you see fit to test each element." I spawned multiple Task agents to test:
   - Server startup - ✅ Working (74 routes)
   - Credential resolver - ✅ Working (87 sections parsed)
   - Project registry - ✅ Working
   - Feature graph & file locks - ✅ Working
   - Parallel agent runner - ❌ Import error (missing `get_feature_stats`)
   - Smart scheduler - ✅ Working
   - UI build - ✅ Working
   - Context injection - ❌ Not wired up (code exists but not called)

5. **Fix Request**: User said "Yes" to fix the two bugs found.

6. **Bug Fix #1**: Added `get_feature_stats()` function to `progress.py`:
```python
def get_feature_stats(project_dir: Path) -> dict:
    passing, in_progress, total = count_passing_tests(project_dir)
    pending = max(0, total - passing - in_progress)
    return {
        "pending": pending,
        "in_progress": in_progress,
        "completed": passing,
        "total": total,
    }
```

7. **Bug Fix #2**: Updated `agent.py` to use context-aware prompts:
   - Changed imports from `get_coding_prompt` to `get_coding_prompt_with_context`
   - Changed imports from `get_initializer_prompt` to `get_initializer_prompt_with_context`
   - Updated all prompt calls to pass `project_dir.name` and `project_dir`

8. **Bug Fix #3**: Created `~/.autocoder/global_resources.json` with correct format (resources as dict, not arrays) containing Jupiter, Saturn, pfSense, Build Server, Gitea, GuruRMM API.

9. **Launch Request**: User said "Launch it". I started the server on port 8080 (8000 was in use) and opened the UI in Chrome.

10. **UI Bug Report**: User showed screenshot with `[object Object]` bug in the import dialog.

11. **Bug Fix #4**: Fixed NewProjectModal.tsx by:
   - Adding `getErrorMessage()` helper function
   - Replacing all `{error}` renders with `{getErrorMessage(error)}`
   - Rebuilt UI with `npm run build`

12. **Import Test**: Successfully tested import flow with guru-connect project. Claude analyzed the codebase correctly (Rust/Axum server, React dashboard, Protocol Buffers, etc.)

13. **Documentation Request**: User asked to "describe the Autocoder project is as much detail as possible. Also include a section of items that you believe would make this project exceptional." I spawned two exploration agents to document the full architecture.

Current state: Documentation agents have returned comprehensive information about the project structure, all services, API endpoints, UI components, database schema, MCP tools, etc. I need to compile this into a final document with recommendations for making the project exceptional.

Summary:
## 1. Primary Request and Intent

The user's requests progressed through several phases:

1. **Sync Claude Code preferences** from Gitea repository
2. **Check Autocoder project status** - understand current state vs what was planned
3. **Verify actual codebase** - test everything in Autocoder-2.0, spawn agents as needed
4. **Fix bugs found** - two bugs were discovered (missing function, context not wired up)
5. **Launch Autocoder-2.0** - start the server and UI
6. **Fix UI bug** - `[object Object]` rendering error in import dialog
7. **Create comprehensive documentation** - describe the project in detail with recommendations for making it exceptional

## 2. Key Technical Concepts

- **Claude Agent SDK** - Autonomous coding agent using Claude API
- **Two-agent pattern** - Initializer Agent (creates features) + Coding Agent (implements features)
- **Parallel agent execution** - Multiple agents working on non-conflicting features
- **Smart scheduling** - AI-driven parallelization decisions with conflict detection
- **Feature Graph** - Tracks dependencies and file conflicts between features
- **File Lock Manager** - Async-safe locking to prevent concurrent modifications
- **MCP (Model Context Protocol)** - Feature management tools for agents
- **Credential Resolver** - Parses credentials.md for infrastructure access
- **Resource Manager** - Tracks servers/services with verification
- **Context Injection** - Infrastructure info injected into agent prompts
- **YOLO Mode** - Rapid prototyping without browser testing
- **Neobrutalism UI** - Design system with Tailwind CSS v4
- **FastAPI + React** - Backend API + Frontend stack
- **SQLite** - Feature database and project registry

## 3. Files and Code Sections

### `C:/Users/MikeSwanson/claude-projects/Autocode-remix/Autocoder-2.0/progress.py`
- **Why important**: Missing `get_feature_stats()` function caused import errors in `parallel_agent.py` and `smart_orchestrator.py`
- **Changes**: Added new function at end of file
```python
def get_feature_stats(project_dir: Path) -> dict:
    """
    Get feature statistics from the database.

    Args:
        project_dir: Directory containing the project

    Returns:
        Dict with keys: pending, in_progress, completed, total
    """
    passing, in_progress, total = count_passing_tests(project_dir)
    pending = max(0, total - passing - in_progress)

    return {
        "pending": pending,
        "in_progress": in_progress,
        "completed": passing,
        "total": total,
    }
```

### `C:/Users/MikeSwanson/claude-projects/Autocode-remix/Autocoder-2.0/agent.py`
- **Why important**: Needed to wire up context injection so agents know about infrastructure
- **Changes**: Updated imports and prompt calls
```python
# Changed from:
from prompts import (
    copy_spec_to_project,
    get_coding_prompt,
    get_coding_prompt_yolo,
    get_initializer_prompt,
)

# Changed to:
from prompts import (
    copy_spec_to_project,
    get_coding_prompt_with_context,
    get_initializer_prompt_with_context,
)

# Updated prompt calls:
prompt = get_initializer_prompt_with_context(project_dir.name, project_dir)
prompt = get_coding_prompt_with_context(project_dir.name, project_dir, yolo_mode=True)
prompt = get_coding_prompt_with_context(project_dir.name, project_dir)
```

### `~/.autocoder/global_resources.json`
- **Why important**: Required for infrastructure context injection; wrong format caused empty resources
- **Changes**: Created with correct structure (resources as dict, not arrays)
```json
{
  "resources": {
    "Jupiter": {
      "type": "server",
      "scope": "global",
      "host": "172.16.3.20",
      "user": "root",
      "description": "Unraid, containers (Gitea, NPM, GuruRMM)",
      "auth": {"type": "ssh-password", "credential_ref": "jupiter"}
    },
    "Saturn": {...},
    "pfSense": {...},
    "Build Server": {...},
    "Gitea": {"type": "service", ...},
    "GuruRMM API": {"type": "service", ...}
  }
}
```

### `C:/Users/MikeSwanson/claude-projects/Autocode-remix/Autocoder-2.0/ui/src/components/NewProjectModal.tsx`
- **Why important**: `[object Object]` bug in error display
- **Changes**: Added helper function and updated all error renders
```typescript
// Added helper function:
function getErrorMessage(error: unknown): string {
  if (typeof error === 'string') return error
  if (error instanceof Error) return error.message
  if (error && typeof error === 'object' && 'message' in error) {
    return String((error as { message: unknown }).message)
  }
  return String(error)
}

// Changed all {error} to {getErrorMessage(error)}
```

### Key Configuration Files Examined
- `client.py` - Line 129: `"sandbox": {"enabled": False}` - Sandbox disabled for full system access
- `security.py` - Extended allowlist includes SSH, SCP, rsync, docker, systemctl
- `prompts.py` - Contains `get_infrastructure_context()` and `*_with_context()` functions

## 4. Errors and Fixes

1. **SSH Permission Denied to Gitea**
   - Error: `git@172.16.3.20: Permission denied (publickey)`
   - Fix: Used HTTPS origin instead (`git pull origin main`)

2. **Missing `get_feature_stats` function**
   - Error: `ImportError: cannot import name 'get_feature_stats' from 'progress'`
   - Affected: `parallel_agent.py`, `smart_orchestrator.py`
   - Fix: Added the function to `progress.py`

3. **Context injection not wired up**
   - Issue: `agent.py` called `get_coding_prompt()` instead of `get_coding_prompt_with_context()`
   - Fix: Updated imports and all prompt calls in `agent.py`

4. **Global resources not loading**
   - Issue: `get_merged_resources()` returned empty dict `{}`
   - Cause: JSON format was `{"servers": [...]}` but expected `{"resources": {...}}`
   - Fix: Recreated `global_resources.json` with correct format

5. **Port 8000 already in use**
   - Error: `[winerror 10048] only one usage of each socket address`
   - Fix: Started server on port 8080 instead

6. **`[object Object]` UI bug**
   - Issue: Error objects rendered as string in React
   - Fix: Added `getErrorMessage()` helper and updated all error displays in `NewProjectModal.tsx`

7. **File edit failures**
   - Issue: Multiple "File has been unexpectedly modified" errors
   - Fix: Used Python script to modify files instead of Edit tool

## 5. Problem Solving

**Solved:**
- Verified all Autocoder-2.0 components work
- Fixed parallel agent import errors
- Wired up infrastructure context injection
- Fixed global resources configuration
- Fixed UI error display bug
- Successfully launched and tested the full system
- Imported guru-connect project with working codebase analysis

**Server Running:**
- Autocoder-2.0 running at http://localhost:8080 (background task b858320)
- 74 API routes registered
- UI serving from `ui/dist/`
- WebSocket endpoints active

## 6. All User Messages

1. `/sync` - Sync Claude Code preferences
2. "Where are we with autocoder project?"
3. "Check codebase to verify what has or has not been done"
4. "Yes, test everything, spawn SDK agents as you see fit to test each element."
5. "Yes" (to fix the bugs)
6. "Launch it"
7. "fix object bug"
8. "Let's describe the Autocoder project is as much detail as possible. Also include a section of items that you believe would make this project exceptional."
9. `/s` - Save session (this summary request)

## 7. Pending Tasks

1. **Complete comprehensive Autocoder documentation** - Two exploration agents have returned detailed information; need to compile final document
2. **Add "Items to make exceptional" section** - User specifically requested recommendations for improvements

## 8. Current Work

Immediately before this summary request, I was working on creating comprehensive documentation for Autocoder-2.0. I had spawned two Task agents:

1. **Explore Autocoder architecture** - Returned full project structure, all modules, API endpoints, UI components, database schema, MCP tools, prompt templates, configuration options
2. **Explore Autocoder services** - Returned detailed documentation for all 10 server services with methods, integration, and configuration

The agents completed and returned ~15,000+ words of technical documentation covering:
- Complete project structure
- All Python modules and purposes
- All 74 API endpoints
- All 24 UI components
- Database schema (Feature table)
- 7 MCP tools
- 4 prompt templates
- Configuration options
- 10 server services with full method documentation

User's exact request: *"Let's describe the Autocoder project is as much detail as possible. Also include a section of items that you believe would make this project exceptional."*

## 9. Optional Next Step

**Compile the final documentation with recommendations**

The exploration agents have returned comprehensive technical details. I need to:
1. Compile the information into a well-structured document
2. Add the "Items to Make Exceptional" section with my recommendations for improvements

This directly fulfills the user's most recent explicit request: *"Let's describe the Autocoder project is as much detail as possible. Also include a section of items that you believe would make this project exceptional."*.

If you need specific details from before compaction (like exact code snippets, error messages, or content you generated), read the full transcript at: C:\Users\MikeSwanson\.claude\projects\C--Users-MikeSwanson-claude-projects\ffbb1d55-48d7-4643-9b87-12eb26d1bfa4.jsonl
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.


The user wants me to continue from where I left off. Based on the summary, I was working on creating comprehensive documentation for Autocoder-2.0. The exploration agents had returned detailed information, and I need to compile it into a final document with recommendations for making the project exceptional.

Let me compile this documentation now. I should create a comprehensive document that covers all aspects of the Autocoder project.


I'll continue compiling the comprehensive Autocoder-2.0 documentation with recommendations for making it exceptional.


Write

# Autocoder 2.0 - Complete Architecture Documentation

## Executive Summary

Autocoder 2.0 is an autonomous coding agent system that builds complete applications over multiple sessions using Claude's AI capabilities. It employs a sophisticated two-agent pattern where an **Initializer Agent** analyzes application specifications and creates testable features, while a **Coding Agent** systematically implements each feature with verification.

The system features a React-based UI for project management, real-time progress tracking via WebSocket, and advanced capabilities including parallel agent execution, AI-driven scheduling, and infrastructure-aware context injection.

---

## Table of Contents

1. [System Overview](#system-overview)
2. [Core Architecture](#core-architecture)
3. [Agent System](#agent-system)
4. [Server Architecture](#server-architecture)
5. [UI Components](#ui-components)
6. [Database Schema](#database-schema)
7. [MCP Tools](#mcp-tools)
8. [Configuration](#configuration)
9. [Security Model](#security-model)
10. [Items to Make Exceptional](#items-to-make-exceptional)

---

## System Overview

### Technology Stack

| Layer | Technology |
|-------|------------|
| AI Backend | Claude Agent SDK, Anthropic API |
| Server | Python 3.11+, FastAPI, SQLAlchemy |
| Database | SQLite (features.db, registry.db) |
| Frontend | React 18, TypeScript, TanStack Query |
| Styling | Tailwind CSS v4, Radix UI |
| Real-time | WebSocket |
| Testing | Playwright MCP (browser automation) |

### Directory Structure

```
Autocoder-2.0/
├── agent.py                 # Main agent session loop
├── autonomous_agent_demo.py # CLI entry point
├── client.py                # Claude SDK client configuration
├── parallel_agent.py        # Parallel agent runner
├── smart_orchestrator.py    # AI-driven parallelization
├── progress.py              # Progress tracking & database queries
├── prompts.py               # Prompt template loading with context
├── registry.py              # Project registry (SQLite)
├── security.py              # Bash command allowlist
├── start.py                 # CLI launcher menu
│
├── api/
│   └── database.py          # SQLAlchemy models
│
├── mcp_server/
│   └── feature_mcp.py       # MCP server for feature management
│
├── server/
│   ├── main.py              # FastAPI application
│   ├── services/            # Business logic
│   │   ├── agent_runner.py
│   │   ├── credential_resolver.py
│   │   ├── feature_graph.py
│   │   ├── file_lock_manager.py
│   │   ├── prompt_generator.py
│   │   ├── resource_context.py
│   │   ├── resource_manager.py
│   │   ├── session_manager.py
│   │   ├── smart_scheduler.py
│   │   └── spec_generator.py
│   └── routers/             # API endpoints
│       ├── agent.py
│       ├── features.py
│       ├── filesystem.py
│       ├── projects.py
│       └── spec_creation.py
│
├── ui/                      # React frontend
│   ├── src/
│   │   ├── App.tsx
│   │   ├── components/      # 24 UI components
│   │   ├── hooks/           # React Query hooks
│   │   ├── lib/             # API client, types
│   │   └── styles/          # Tailwind theme
│   └── dist/                # Production build
│
├── prompts/                 # Default prompt templates
└── .claude/
    ├── commands/            # Slash commands
    ├── skills/              # AI skills
    └── templates/           # Prompt templates
```

---

## Core Architecture

### Two-Agent Pattern

```
┌─────────────────────────────────────────────────────────────┐
│                    APPLICATION SPEC                          │
│                    (prompts/app_spec.txt)                   │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                   INITIALIZER AGENT                          │
│  • Reads app_spec.txt                                       │
│  • Analyzes requirements                                    │
│  • Creates features in SQLite with priorities               │
│  • Defines test steps for each feature                      │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    FEATURES DATABASE                         │
│  (features.db - SQLite)                                     │
│  • priority: int (lower = higher priority)                  │
│  • category: str                                            │
│  • name: str                                                │
│  • description: str                                         │
│  • steps: str (JSON array of test steps)                    │
│  • passes: bool                                             │
│  • in_progress: bool                                        │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    CODING AGENT                              │
│  Loop until all features pass:                              │
│  1. Get next pending feature (highest priority)             │
│  2. Implement the feature                                   │
│  3. Run lint/type-check                                     │
│  4. Run Playwright tests (unless YOLO mode)                 │
│  5. Run regression tests on random passing features         │
│  6. Mark feature as passing or retry                        │
└─────────────────────────────────────────────────────────────┘
```

### Parallel Execution Model

```
┌─────────────────────────────────────────────────────────────┐
│                   SMART ORCHESTRATOR                         │
│  (smart_orchestrator.py)                                    │
│                                                             │
│  1. Analyze all pending features                            │
│  2. Use Claude to identify parallelizable groups            │
│  3. Detect file conflicts (feature_graph.py)                │
│  4. Acquire file locks (file_lock_manager.py)               │
│  5. Spawn parallel agents for non-conflicting features      │
│  6. Merge results and handle conflicts                      │
└─────────────────────────────────────────────────────────────┘
                              │
              ┌───────────────┼───────────────┐
              ▼               ▼               ▼
        ┌─────────┐     ┌─────────┐     ┌─────────┐
        │ Agent 1 │     │ Agent 2 │     │ Agent 3 │
        │Feature A│     │Feature B│     │Feature C│
        └─────────┘     └─────────┘     └─────────┘
              │               │               │
              └───────────────┼───────────────┘
                              ▼
                    ┌─────────────────┐
                    │  Result Merger  │
                    │  & Verification │
                    └─────────────────┘
```

---

## Agent System

### Main Agent Loop (`agent.py`)

The agent runs in sessions with automatic continuation:

```python
async def run_agent_session(
    project_dir: Path,
    stop_event: Optional[asyncio.Event] = None,
    pause_event: Optional[asyncio.Event] = None,
    yolo_mode: bool = False,
) -> dict
```

**Session Flow:**
1. Check if `features.db` has features → determines initializer vs coding
2. Create `ClaudeSDKClient` with security settings
3. Load context-aware prompt with infrastructure info
4. Send prompt and stream response
5. Auto-continue with 3-second delay between sessions
6. Repeat until all features pass or stopped

### Claude SDK Client (`client.py`)

```python
class ClaudeSDKClient:
    def create(
        self,
        model: str = "claude-sonnet-4-20250514",
        mcp_servers: list = None,
        system_prompt: str = None,
        allowed_paths: list = None,
    ) -> AgentConfig
```

**Configuration:**
- Model: `claude-sonnet-4-20250514` (configurable)
- Max tokens: 16384
- Sandbox: **Disabled** for full system access
- MCP Servers: Feature MCP, optionally Playwright MCP
- Bash permissions: Extended allowlist (SSH, SCP, docker, etc.)

### Parallel Agent Runner (`parallel_agent.py`)

```python
async def run_parallel_agents(
    project_dir: Path,
    max_concurrent: int = 3,
    yolo_mode: bool = False,
) -> dict
```

**Features:**
- Spawns multiple agents working on non-conflicting features
- Uses `asyncio.Semaphore` for concurrency control
- Coordinates via `file_lock_manager.py`
- Aggregates results from all agents

### Smart Orchestrator (`smart_orchestrator.py`)

```python
class SmartOrchestrator:
    async def run_smart_session(
        self,
        max_concurrent: int = 3,
        yolo_mode: bool = False,
    ) -> dict
```

**AI-Driven Parallelization:**
1. Fetches all pending features
2. Calls Claude to analyze and group parallelizable features
3. Detects file-level conflicts using `FeatureGraph`
4. Acquires locks on affected files
5. Runs grouped features in parallel batches
6. Handles merge conflicts and verification

---

## Server Architecture

### FastAPI Application (`server/main.py`)

**74 API Routes across 5 routers:**

| Router | Prefix | Routes | Purpose |
|--------|--------|--------|---------|
| projects | `/api/projects` | 15 | Project CRUD, registry |
| features | `/api/features` | 12 | Feature management |
| agent | `/api/agent` | 10 | Agent control |
| filesystem | `/api/filesystem` | 5 | Folder browser |
| spec_creation | `/api/spec` | 3 | WebSocket spec wizard |

**WebSocket Endpoints:**
- `/ws/projects/{project_name}` - Real-time updates
- `/api/spec/ws` - Interactive spec creation

### Server Services

#### 1. AgentRunner (`services/agent_runner.py`)
Manages agent lifecycle with subprocess isolation.

```python
class AgentRunner:
    async def start_agent(project_name: str, yolo: bool = False) -> dict
    async def stop_agent(project_name: str) -> dict
    async def pause_agent(project_name: str) -> dict
    async def resume_agent(project_name: str) -> dict
    def get_agent_status(project_name: str) -> AgentStatus
```

**Status States:** `idle`, `running`, `paused`, `crashed`

#### 2. CredentialResolver (`services/credential_resolver.py`)
Parses `credentials.md` for infrastructure access.

```python
class CredentialResolver:
    def __init__(credentials_path: Path)
    def get_credential(service_name: str) -> Optional[Credential]
    def get_all_credentials() -> dict[str, Credential]
    def resolve_for_resource(resource: Resource) -> Resource
```

**Parsed Format:**
```markdown
### Service Name
- **Host:** hostname
- **Username:** user
- **Password:** secret
```

#### 3. FeatureGraph (`services/feature_graph.py`)
Tracks dependencies and file conflicts.

```python
class FeatureGraph:
    def add_feature(feature_id: str, files: list[str])
    def get_conflicts(feature_id: str) -> list[str]
    def get_safe_parallel_groups() -> list[list[str]]
    def mark_completed(feature_id: str)
```

**Conflict Detection:**
- Builds graph of feature → files mapping
- Detects overlapping file modifications
- Returns groups of non-conflicting features

#### 4. FileLockManager (`services/file_lock_manager.py`)
Async-safe file locking for parallel agents.

```python
class FileLockManager:
    async def acquire(file_path: str, owner: str) -> bool
    async def release(file_path: str, owner: str)
    async def is_locked(file_path: str) -> bool
    def get_owner(file_path: str) -> Optional[str]
```

**Implementation:**
- Uses `asyncio.Lock` for thread safety
- Supports timeout-based acquisition
- Tracks lock ownership for debugging

#### 5. PromptGenerator (`services/prompt_generator.py`)
Generates context-rich prompts.

```python
class PromptGenerator:
    def generate_initializer_prompt(project: Project) -> str
    def generate_coding_prompt(project: Project, feature: Feature) -> str
    def inject_context(prompt: str, context: dict) -> str
```

#### 6. ResourceContext (`services/resource_context.py`)
Loads and merges infrastructure resources.

```python
def get_merged_resources(project_dir: Path) -> dict
def get_infrastructure_context(project_name: str, project_dir: Path) -> str
```

**Resource Sources:**
1. Global: `~/.autocoder/global_resources.json`
2. Project: `{project}/resources.json`

#### 7. ResourceManager (`services/resource_manager.py`)
Tracks servers/services with verification.

```python
class ResourceManager:
    def add_resource(name: str, resource: Resource)
    def get_resource(name: str) -> Resource
    async def verify_resource(name: str) -> bool
    def list_resources() -> list[Resource]
```

**Resource Types:**
- `server` - SSH-accessible machines
- `service` - HTTP/HTTPS endpoints

#### 8. SessionManager (`services/session_manager.py`)
Manages agent sessions with persistence.

```python
class SessionManager:
    def create_session(project_name: str) -> Session
    def get_session(project_name: str) -> Optional[Session]
    def end_session(project_name: str)
    def get_session_logs(project_name: str) -> list[str]
```

#### 9. SmartScheduler (`services/smart_scheduler.py`)
Prioritizes features intelligently.

```python
class SmartScheduler:
    def get_next_feature(project_name: str) -> Optional[Feature]
    def reorder_by_dependencies() -> list[Feature]
    def get_parallel_batch(max_size: int) -> list[Feature]
```

**Scheduling Factors:**
- Feature priority (lower = higher)
- Dependency order
- File conflict avoidance
- Category grouping

#### 10. SpecGenerator (`services/spec_generator.py`)
Creates app specifications via conversation.

```python
class SpecGenerator:
    async def start_conversation(initial_idea: str) -> ConversationState
    async def continue_conversation(user_input: str) -> ConversationState
    def generate_spec() -> str
    def save_spec(project_dir: Path)
```

---

## UI Components

### Main Application (`ui/src/App.tsx`)

**Features:**
- Project selection dropdown
- Kanban board (Pending → In Progress → Done)
- Agent controls (Start/Stop/Pause/Resume)
- YOLO mode toggle
- Real-time progress bar
- Log viewer

### Component Library (24 components)

| Component | Purpose |
|-----------|---------|
| `AgentControls.tsx` | Start/stop/pause/resume buttons |
| `AgentStatusBadge.tsx` | Status indicator |
| `FeatureCard.tsx` | Draggable feature card |
| `FeatureColumn.tsx` | Kanban column |
| `FolderBrowser.tsx` | Server-side filesystem browser |
| `KanbanBoard.tsx` | Feature board layout |
| `LogViewer.tsx` | Real-time log display |
| `NewProjectModal.tsx` | Multi-step project wizard |
| `ProgressBar.tsx` | Animated progress indicator |
| `ProjectSelector.tsx` | Project dropdown |
| `SpecCreationWizard.tsx` | Interactive spec builder |
| `YoloModeToggle.tsx` | Lightning bolt toggle |

### Design System

**Neobrutalism Theme:**
- Bold borders: `border-4 border-black`
- Hard shadows: `shadow-[4px_4px_0_0_#000]`
- Vibrant colors with CSS variables
- Monospace fonts for code elements

**Color Tokens:**
```css
--color-neo-pending: #fbbf24;   /* Yellow */
--color-neo-progress: #22d3ee;  /* Cyan */
--color-neo-done: #22c55e;      /* Green */
--color-neo-error: #ef4444;     /* Red */
```

**Animations:**
- `animate-slide-in` - Card entrance
- `animate-pulse-neo` - Status indicator
- `animate-shimmer` - Progress bar

### React Query Hooks

```typescript
// ui/src/hooks/useProjects.ts
useProjects()           // List all projects
useProject(name)        // Get single project
useCreateProject()      // Create new project
useImportProject()      // Import existing project

// ui/src/hooks/useFeatures.ts
useFeatures(project)    // List features
useUpdateFeature()      // Update feature status

// ui/src/hooks/useAgent.ts
useAgentStatus(project) // Current agent status
useStartAgent()         // Start agent
useStopAgent()          // Stop agent

// ui/src/hooks/useWebSocket.ts
useWebSocket(project)   // Real-time updates
```

---

## Database Schema

### Features Table (`features.db`)

```sql
CREATE TABLE features (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    priority INTEGER NOT NULL DEFAULT 0,
    category TEXT NOT NULL,
    name TEXT NOT NULL,
    description TEXT NOT NULL,
    steps TEXT NOT NULL,  -- JSON array
    passes BOOLEAN NOT NULL DEFAULT FALSE,
    in_progress BOOLEAN NOT NULL DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_features_priority ON features(priority);
CREATE INDEX idx_features_passes ON features(passes);
```

### Project Registry (`~/.autocoder/registry.db`)

```sql
CREATE TABLE projects (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL UNIQUE,
    path TEXT NOT NULL,  -- POSIX format
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_accessed TIMESTAMP
);
```

---

## MCP Tools

The Feature MCP server (`mcp_server/feature_mcp.py`) exposes 7 tools:

| Tool | Purpose |
|------|---------|
| `feature_get_stats` | Get progress statistics (pending/in_progress/completed/total) |
| `feature_get_next` | Get highest-priority pending feature |
| `feature_get_for_regression` | Get random passing features for regression testing |
| `feature_mark_passing` | Mark feature as complete |
| `feature_mark_in_progress` | Mark feature as being worked on |
| `feature_skip` | Move feature to end of queue |
| `feature_create_bulk` | Initialize all features (used by initializer) |

**MCP Server Configuration:**
```python
mcp_servers = [
    {
        "name": "feature-mcp",
        "command": "python",
        "args": [str(mcp_server_path), str(project_dir)],
    }
]
```

---

## Configuration

### Prompt Templates

| Template | Location | Purpose |
|----------|----------|---------|
| `initializer_prompt.md` | `prompts/` or `.claude/templates/` | First session - create features |
| `coding_prompt.md` | `prompts/` or `.claude/templates/` | Continuation - implement features |
| `coding_prompt_yolo.md` | `prompts/` or `.claude/templates/` | YOLO mode - skip testing |
| `app_spec.txt` | `prompts/` | Application specification (XML) |

### Resource Configuration

**Global Resources (`~/.autocoder/global_resources.json`):**
```json
{
  "resources": {
    "ServerName": {
      "type": "server",
      "scope": "global",
      "host": "192.168.1.100",
      "user": "admin",
      "description": "Description",
      "auth": {
        "type": "ssh-password",
        "credential_ref": "server-creds"
      }
    }
  }
}
```

**Project Resources (`{project}/resources.json`):**
```json
{
  "resources": {
    "LocalDB": {
      "type": "service",
      "scope": "project",
      "url": "http://localhost:5432",
      "description": "Project database"
    }
  }
}
```

### Environment Variables

| Variable | Default | Purpose |
|----------|---------|---------|
| `ANTHROPIC_API_KEY` | Required | Claude API authentication |
| `AUTOCODER_PORT` | 8000 | Server port |
| `AUTOCODER_HOST` | 0.0.0.0 | Server bind address |
| `AUTOCODER_DEBUG` | false | Enable debug logging |

---

## Security Model

### Defense-in-Depth Layers

```
┌─────────────────────────────────────────────────────────────┐
│ Layer 1: OS-Level Sandbox (configurable)                    │
│ - Process isolation                                         │
│ - Currently DISABLED for full system access                 │
└─────────────────────────────────────────────────────────────┘
                              │
┌─────────────────────────────────────────────────────────────┐
│ Layer 2: Filesystem Restrictions                            │
│ - allowed_paths: [project_dir, home_dir, /tmp]             │
│ - Prevents access outside designated directories            │
└─────────────────────────────────────────────────────────────┘
                              │
┌─────────────────────────────────────────────────────────────┐
│ Layer 3: Bash Command Allowlist                             │
│ - ALLOWED_COMMANDS whitelist in security.py                 │
│ - Validates all bash commands before execution              │
└─────────────────────────────────────────────────────────────┘
```

### Allowed Commands (`security.py`)

```python
ALLOWED_COMMANDS = {
    # Package managers
    "npm", "npx", "pip", "pip3", "cargo", "brew", "apt", "apt-get",

    # Development tools
    "node", "python", "python3", "git", "make", "cmake",

    # File operations
    "cat", "ls", "mkdir", "cp", "mv", "rm", "touch", "chmod",

    # Infrastructure access (extended)
    "ssh", "scp", "rsync", "curl", "wget",

    # Container operations
    "docker", "docker-compose",

    # System operations
    "systemctl", "service", "journalctl",

    # Playwright
    "playwright", "npx playwright",
}
```

---

## Items to Make Exceptional

### 1. Multi-Model Support
**Current:** Claude Sonnet only
**Enhancement:** Support multiple AI models for different tasks

```python
class ModelRouter:
    def select_model(task_type: str) -> str:
        models = {
            "analysis": "claude-opus-4",      # Complex reasoning
            "coding": "claude-sonnet-4",      # Fast implementation
            "review": "claude-haiku-3",       # Quick validation
        }
        return models.get(task_type, "claude-sonnet-4")
```

**Benefits:**
- Use Opus for architectural decisions
- Use Sonnet for code implementation
- Use Haiku for quick validations
- Optimize cost vs capability per task

### 2. Intelligent Caching & Learning

**Feature Learning System:**
```python
class FeatureLearning:
    def record_implementation(feature: Feature, code: str, time: float)
    def get_similar_implementations(feature: Feature) -> list[Example]
    def suggest_approach(feature: Feature) -> str
```

**Benefits:**
- Cache successful implementations
- Suggest approaches from similar past features
- Reduce token usage by reusing patterns
- Build project-specific knowledge base

### 3. Real-Time Collaboration

**Live Editing Protocol:**
```python
class CollaborationHub:
    async def broadcast_edit(file: str, change: Change)
    async def request_human_review(file: str, line: int)
    async def accept_human_edit(file: str, change: Change)
```

**Features:**
- Watch mode for file changes
- Human can edit while agent works
- Conflict resolution with git-style markers
- Pair programming mode

### 4. Self-Healing & Adaptive Recovery

**Automatic Recovery System:**
```python
class AdaptiveRecovery:
    def detect_stuck_state() -> bool
    def analyze_failure_pattern(logs: list[str]) -> FailureType
    def generate_recovery_strategy() -> Strategy
    def apply_recovery() -> bool
```

**Capabilities:**
- Detect infinite loops or stuck states
- Analyze error patterns across sessions
- Auto-generate workarounds
- Learn from past failures

### 5. Comprehensive Test Generation

**AI-Driven Testing:**
```python
class TestGenerator:
    def generate_unit_tests(code: str) -> str
    def generate_integration_tests(features: list) -> str
    def generate_edge_cases(function: str) -> list[TestCase]
    def generate_property_tests(type_signature: str) -> str
```

**Benefits:**
- Auto-generate tests during implementation
- Edge case discovery via AI reasoning
- Property-based test generation
- Mutation testing integration

### 6. Visual Progress Dashboard

**Enhanced Visualization:**
- Dependency graph visualization (D3.js)
- Real-time code diff viewer
- Agent thought process timeline
- Token usage analytics
- Cost tracking per feature

### 7. Git Integration

**Smart Version Control:**
```python
class GitIntegration:
    def create_feature_branch(feature: Feature) -> str
    def commit_with_context(files: list, feature: Feature) -> str
    def generate_pr_description(feature: Feature) -> str
    def handle_merge_conflicts(conflicts: list) -> Resolution
```

**Features:**
- Auto-create branches per feature
- Meaningful commit messages from context
- Auto-generate PR descriptions
- AI-assisted conflict resolution

### 8. Plugin Architecture

**Extensibility System:**
```python
class PluginManager:
    def register_hook(event: str, handler: Callable)
    def register_tool(name: str, tool: MCPTool)
    def register_validator(phase: str, validator: Callable)
```

**Plugin Types:**
- Pre/post implementation hooks
- Custom MCP tools
- Additional validators
- Custom reporters

### 9. Cost Optimization

**Token Budget Management:**
```python
class BudgetManager:
    def set_project_budget(project: str, max_tokens: int)
    def track_usage(project: str, tokens: int)
    def get_cost_estimate(feature: Feature) -> float
    def suggest_optimizations() -> list[Suggestion]
```

**Features:**
- Per-project token budgets
- Cost estimation before starting
- Automatic prompt optimization
- Usage analytics and trends

### 10. Enterprise Features

**Production Readiness:**
- SSO/SAML authentication
- Role-based access control
- Audit logging
- API rate limiting
- Multi-tenant support
- Compliance reporting (SOC2, GDPR)

---

## Quick Start

```bash
# 1. Install dependencies
python -m venv venv
venv\Scripts\activate  # Windows
pip install -r requirements.txt

# 2. Install UI dependencies
cd ui && npm install && npm run build && cd ..

# 3. Start the server
start_ui.bat  # Windows
./start_ui.sh # macOS/Linux

# 4. Open browser to http://localhost:8000
```

---

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make changes with tests
4. Submit a pull request

---

*Last Updated: 2026-01-11*
*Version: 2.0.0*


File created successfully at: C:\Users\MikeSwanson\claude-projects\Autocode-remix\Autocoder-2.0\ARCHITECTURE.md

# Autocoder 2.0 - Complete Architecture Documentation

## Executive Summary

Autocoder 2.0 is an autonomous coding agent system that builds complete applications over multiple sessions using Claude's AI capabilities. It employs a sophisticated two-agent pattern where an **Initializer Agent** analyzes application specifications and creates testable features, while a **Coding Agent** systematically implements each feature with verification.

The system features a React-based UI for project management, real-time progress tracking via WebSocket, and advanced capabilities including parallel agent execution, AI-driven scheduling, and infrastructure-aware context injection.

---

## Table of Contents

1. [System Overview](#system-overview)
2. [Core Architecture](#core-architecture)
3. [Agent System](#agent-system)
4. [Server Architecture](#server-architecture)
5. [UI Components](#ui-components)
6. [Database Schema](#database-schema)
7. [MCP Tools](#mcp-tools)
8. [Configuration](#configuration)
9. [Security Model](#security-model)
10. [Items to Make Exceptional](#items-to-make-exceptional)

---

## System Overview

### Technology Stack

| Layer | Technology |
|-------|------------|
| AI Backend | Claude Agent SDK, Anthropic API |
| Server | Python 3.11+, FastAPI, SQLAlchemy |
| Database | SQLite (features.db, registry.db) |
| Frontend | React 18, TypeScript, TanStack Query |
| Styling | Tailwind CSS v4, Radix UI |
| Real-time | WebSocket |
| Testing | Playwright MCP (browser automation) |

### Directory Structure

```
Autocoder-2.0/
├── agent.py                 # Main agent session loop
├── autonomous_agent_demo.py # CLI entry point
├── client.py                # Claude SDK client configuration
├── parallel_agent.py        # Parallel agent runner
├── smart_orchestrator.py    # AI-driven parallelization
├── progress.py              # Progress tracking & database queries
├── prompts.py               # Prompt template loading with context
├── registry.py              # Project registry (SQLite)
├── security.py              # Bash command allowlist
├── start.py                 # CLI launcher menu
│
├── api/
│   └── database.py          # SQLAlchemy models
│
├── mcp_server/
│   └── feature_mcp.py       # MCP server for feature management
│
├── server/
│   ├── main.py              # FastAPI application
│   ├── services/            # Business logic
│   │   ├── agent_runner.py
│   │   ├── credential_resolver.py
│   │   ├── feature_graph.py
│   │   ├── file_lock_manager.py
│   │   ├── prompt_generator.py
│   │   ├── resource_context.py
│   │   ├── resource_manager.py
│   │   ├── session_manager.py
│   │   ├── smart_scheduler.py
│   │   └── spec_generator.py
│   └── routers/             # API endpoints
│       ├── agent.py
│       ├── features.py
│       ├── filesystem.py
│       ├── projects.py
│       └── spec_creation.py
│
├── ui/                      # React frontend
│   ├── src/
│   │   ├── App.tsx
│   │   ├── components/      # 24 UI components
│   │   ├── hooks/           # React Query hooks
│   │   ├── lib/             # API client, types
│   │   └── styles/          # Tailwind theme
│   └── dist/                # Production build
│
├── prompts/                 # Default prompt templates
└── .claude/
    ├── commands/            # Slash commands
    ├── skills/              # AI skills
    └── templates/           # Prompt templates
```

---

## Core Architecture

### Two-Agent Pattern

```
┌─────────────────────────────────────────────────────────────┐
│                    APPLICATION SPEC                          │
│                    (prompts/app_spec.txt)                   │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                   INITIALIZER AGENT                          │
│  • Reads app_spec.txt                                       │
│  • Analyzes requirements                                    │
│  • Creates features in SQLite with priorities               │
│  • Defines test steps for each feature                      │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    FEATURES DATABASE                         │
│  (features.db - SQLite)                                     │
│  • priority: int (lower = higher priority)                  │
│  • category: str                                            │
│  • name: str                                                │
│  • description: str                                         │
│  • steps: str (JSON array of test steps)                    │
│  • passes: bool                                             │
│  • in_progress: bool                                        │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    CODING AGENT                              │
│  Loop until all features pass:                              │
│  1. Get next pending feature (highest priority)             │
│  2. Implement the feature                                   │
│  3. Run lint/type-check                                     │
│  4. Run Playwright tests (unless YOLO mode)                 │
│  5. Run regression tests on random passing features         │
│  6. Mark feature as passing or retry                        │
└─────────────────────────────────────────────────────────────┘
```

### Parallel Execution Model

```
┌─────────────────────────────────────────────────────────────┐
│                   SMART ORCHESTRATOR                         │
│  (smart_orchestrator.py)                                    │
│                                                             │
│  1. Analyze all pending features                            │
│  2. Use Claude to identify parallelizable groups            │
│  3. Detect file conflicts (feature_graph.py)                │
│  4. Acquire file locks (file_lock_manager.py)               │
│  5. Spawn parallel agents for non-conflicting features      │
│  6. Merge results and handle conflicts                      │
└─────────────────────────────────────────────────────────────┘
                              │
              ┌───────────────┼───────────────┐
              ▼               ▼               ▼
        ┌─────────┐     ┌─────────┐     ┌─────────┐
        │ Agent 1 │     │ Agent 2 │     │ Agent 3 │
        │Feature A│     │Feature B│     │Feature C│
        └─────────┘     └─────────┘     └─────────┘
              │               │               │
              └───────────────┼───────────────┘
                              ▼
                    ┌─────────────────┐
                    │  Result Merger  │
                    │  & Verification │
                    └─────────────────┘
```

---

## Agent System

### Main Agent Loop (`agent.py`)

The agent runs in sessions with automatic continuation:

```python
async def run_agent_session(
    project_dir: Path,
    stop_event: Optional[asyncio.Event] = None,
    pause_event: Optional[asyncio.Event] = None,
    yolo_mode: bool = False,
) -> dict
```

**Session Flow:**
1. Check if `features.db` has features → determines initializer vs coding
2. Create `ClaudeSDKClient` with security settings
3. Load context-aware prompt with infrastructure info
4. Send prompt and stream response
5. Auto-continue with 3-second delay between sessions
6. Repeat until all features pass or stopped

### Claude SDK Client (`client.py`)

```python
class ClaudeSDKClient:
    def create(
        self,
        model: str = "claude-sonnet-4-20250514",
        mcp_servers: list = None,
        system_prompt: str = None,
        allowed_paths: list = None,
    ) -> AgentConfig
```

**Configuration:**
- Model: `claude-sonnet-4-20250514` (configurable)
- Max tokens: 16384
- Sandbox: **Disabled** for full system access
- MCP Servers: Feature MCP, optionally Playwright MCP
- Bash permissions: Extended allowlist (SSH, SCP, docker, etc.)

### Parallel Agent Runner (`parallel_agent.py`)

```python
async def run_parallel_agents(
    project_dir: Path,
    max_concurrent: int = 3,
    yolo_mode: bool = False,
) -> dict
```

**Features:**
- Spawns multiple agents working on non-conflicting features
- Uses `asyncio.Semaphore` for concurrency control
- Coordinates via `file_lock_manager.py`
- Aggregates results from all agents

### Smart Orchestrator (`smart_orchestrator.py`)

```python
class SmartOrchestrator:
    async def run_smart_session(
        self,
        max_concurrent: int = 3,
        yolo_mode: bool = False,
    ) -> dict
```

**AI-Driven Parallelization:**
1. Fetches all pending features
2. Calls Claude to analyze and group parallelizable features
3. Detects file-level conflicts using `FeatureGraph`
4. Acquires locks on affected files
5. Runs grouped features in parallel batches
6. Handles merge conflicts and verification

---

## Server Architecture

### FastAPI Application (`server/main.py`)

**74 API Routes across 5 routers:**

| Router | Prefix | Routes | Purpose |
|--------|--------|--------|---------|
| projects | `/api/projects` | 15 | Project CRUD, registry |
| features | `/api/features` | 12 | Feature management |
| agent | `/api/agent` | 10 | Agent control |
| filesystem | `/api/filesystem` | 5 | Folder browser |
| spec_creation | `/api/spec` | 3 | WebSocket spec wizard |

**WebSocket Endpoints:**
- `/ws/projects/{project_name}` - Real-time updates
- `/api/spec/ws` - Interactive spec creation

### Server Services

#### 1. AgentRunner (`services/agent_runner.py`)
Manages agent lifecycle with subprocess isolation.

```python
class AgentRunner:
    async def start_agent(project_name: str, yolo: bool = False) -> dict
    async def stop_agent(project_name: str) -> dict
    async def pause_agent(project_name: str) -> dict
    async def resume_agent(project_name: str) -> dict
    def get_agent_status(project_name: str) -> AgentStatus
```

**Status States:** `idle`, `running`, `paused`, `crashed`

#### 2. CredentialResolver (`services/credential_resolver.py`)
Parses `credentials.md` for infrastructure access.

```python
class CredentialResolver:
    def __init__(credentials_path: Path)
    def get_credential(service_name: str) -> Optional[Credential]
    def get_all_credentials() -> dict[str, Credential]
    def resolve_for_resource(resource: Resource) -> Resource
```

**Parsed Format:**
```markdown
### Service Name
- **Host:** hostname
- **Username:** user
- **Password:** secret
```

#### 3. FeatureGraph (`services/feature_graph.py`)
Tracks dependencies and file conflicts.

```python
class FeatureGraph:
    def add_feature(feature_id: str, files: list[str])
    def get_conflicts(feature_id: str) -> list[str]
    def get_safe_parallel_groups() -> list[list[str]]
    def mark_completed(feature_id: str)
```

**Conflict Detection:**
- Builds graph of feature → files mapping
- Detects overlapping file modifications
- Returns groups of non-conflicting features

#### 4. FileLockManager (`services/file_lock_manager.py`)
Async-safe file locking for parallel agents.

```python
class FileLockManager:
    async def acquire(file_path: str, owner: str) -> bool
    async def release(file_path: str, owner: str)
    async def is_locked(file_path: str) -> bool
    def get_owner(file_path: str) -> Optional[str]
```

**Implementation:**
- Uses `asyncio.Lock` for thread safety
- Supports timeout-based acquisition
- Tracks lock ownership for debugging

#### 5. PromptGenerator (`services/prompt_generator.py`)
Generates context-rich prompts.

```python
class PromptGenerator:
    def generate_initializer_prompt(project: Project) -> str
    def generate_coding_prompt(project: Project, feature: Feature) -> str
    def inject_context(prompt: str, context: dict) -> str
```

#### 6. ResourceContext (`services/resource_context.py`)
Loads and merges infrastructure resources.

```python
def get_merged_resources(project_dir: Path) -> dict
def get_infrastructure_context(project_name: str, project_dir: Path) -> str
```

**Resource Sources:**
1. Global: `~/.autocoder/global_resources.json`
2. Project: `{project}/resources.json`

#### 7. ResourceManager (`services/resource_manager.py`)
Tracks servers/services with verification.

```python
class ResourceManager:
    def add_resource(name: str, resource: Resource)
    def get_resource(name: str) -> Resource
    async def verify_resource(name: str) -> bool
    def list_resources() -> list[Resource]
```

**Resource Types:**
- `server` - SSH-accessible machines
- `service` - HTTP/HTTPS endpoints

#### 8. SessionManager (`services/session_manager.py`)
Manages agent sessions with persistence.

```python
class SessionManager:
    def create_session(project_name: str) -> Session
    def get_session(project_name: str) -> Optional[Session]
    def end_session(project_name: str)
    def get_session_logs(project_name: str) -> list[str]
```

#### 9. SmartScheduler (`services/smart_scheduler.py`)
Prioritizes features intelligently.

```python
class SmartScheduler:
    def get_next_feature(project_name: str) -> Optional[Feature]
    def reorder_by_dependencies() -> list[Feature]
    def get_parallel_batch(max_size: int) -> list[Feature]
```

**Scheduling Factors:**
- Feature priority (lower = higher)
- Dependency order
- File conflict avoidance
- Category grouping

#### 10. SpecGenerator (`services/spec_generator.py`)
Creates app specifications via conversation.

```python
class SpecGenerator:
    async def start_conversation(initial_idea: str) -> ConversationState
    async def continue_conversation(user_input: str) -> ConversationState
    def generate_spec() -> str
    def save_spec(project_dir: Path)
```

---

## UI Components

### Main Application (`ui/src/App.tsx`)

**Features:**
- Project selection dropdown
- Kanban board (Pending → In Progress → Done)
- Agent controls (Start/Stop/Pause/Resume)
- YOLO mode toggle
- Real-time progress bar
- Log viewer

### Component Library (24 components)

| Component | Purpose |
|-----------|---------|
| `AgentControls.tsx` | Start/stop/pause/resume buttons |
| `AgentStatusBadge.tsx` | Status indicator |
| `FeatureCard.tsx` | Draggable feature card |
| `FeatureColumn.tsx` | Kanban column |
| `FolderBrowser.tsx` | Server-side filesystem browser |
| `KanbanBoard.tsx` | Feature board layout |
| `LogViewer.tsx` | Real-time log display |
| `NewProjectModal.tsx` | Multi-step project wizard |
| `ProgressBar.tsx` | Animated progress indicator |
| `ProjectSelector.tsx` | Project dropdown |
| `SpecCreationWizard.tsx` | Interactive spec builder |
| `YoloModeToggle.tsx` | Lightning bolt toggle |

### Design System

**Neobrutalism Theme:**
- Bold borders: `border-4 border-black`
- Hard shadows: `shadow-[4px_4px_0_0_#000]`
- Vibrant colors with CSS variables
- Monospace fonts for code elements

**Color Tokens:**
```css
--color-neo-pending: #fbbf24;   /* Yellow */
--color-neo-progress: #22d3ee;  /* Cyan */
--color-neo-done: #22c55e;      /* Green */
--color-neo-error: #ef4444;     /* Red */
```

**Animations:**
- `animate-slide-in` - Card entrance
- `animate-pulse-neo` - Status indicator
- `animate-shimmer` - Progress bar

### React Query Hooks

```typescript
// ui/src/hooks/useProjects.ts
useProjects()           // List all projects
useProject(name)        // Get single project
useCreateProject()      // Create new project
useImportProject()      // Import existing project

// ui/src/hooks/useFeatures.ts
useFeatures(project)    // List features
useUpdateFeature()      // Update feature status

// ui/src/hooks/useAgent.ts
useAgentStatus(project) // Current agent status
useStartAgent()         // Start agent
useStopAgent()          // Stop agent

// ui/src/hooks/useWebSocket.ts
useWebSocket(project)   // Real-time updates
```

---

## Database Schema

### Features Table (`features.db`)

```sql
CREATE TABLE features (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    priority INTEGER NOT NULL DEFAULT 0,
    category TEXT NOT NULL,
    name TEXT NOT NULL,
    description TEXT NOT NULL,
    steps TEXT NOT NULL,  -- JSON array
    passes BOOLEAN NOT NULL DEFAULT FALSE,
    in_progress BOOLEAN NOT NULL DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_features_priority ON features(priority);
CREATE INDEX idx_features_passes ON features(passes);
```

### Project Registry (`~/.autocoder/registry.db`)

```sql
CREATE TABLE projects (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL UNIQUE,
    path TEXT NOT NULL,  -- POSIX format
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_accessed TIMESTAMP
);
```

---

## MCP Tools

The Feature MCP server (`mcp_server/feature_mcp.py`) exposes 7 tools:

| Tool | Purpose |
|------|---------|
| `feature_get_stats` | Get progress statistics (pending/in_progress/completed/total) |
| `feature_get_next` | Get highest-priority pending feature |
| `feature_get_for_regression` | Get random passing features for regression testing |
| `feature_mark_passing` | Mark feature as complete |
| `feature_mark_in_progress` | Mark feature as being worked on |
| `feature_skip` | Move feature to end of queue |
| `feature_create_bulk` | Initialize all features (used by initializer) |

**MCP Server Configuration:**
```python
mcp_servers = [
    {
        "name": "feature-mcp",
        "command": "python",
        "args": [str(mcp_server_path), str(project_dir)],
    }
]
```

---

## Configuration

### Prompt Templates

| Template | Location | Purpose |
|----------|----------|---------|
| `initializer_prompt.md` | `prompts/` or `.claude/templates/` | First session - create features |
| `coding_prompt.md` | `prompts/` or `.claude/templates/` | Continuation - implement features |
| `coding_prompt_yolo.md` | `prompts/` or `.claude/templates/` | YOLO mode - skip testing |
| `app_spec.txt` | `prompts/` | Application specification (XML) |

### Resource Configuration

**Global Resources (`~/.autocoder/global_resources.json`):**
```json
{
  "resources": {
    "ServerName": {
      "type": "server",
      "scope": "global",
      "host": "192.168.1.100",
      "user": "admin",
      "description": "Description",
      "auth": {
        "type": "ssh-password",
        "credential_ref": "server-creds"
      }
    }
  }
}
```

**Project Resources (`{project}/resources.json`):**
```json
{
  "resources": {
    "LocalDB": {
      "type": "service",
      "scope": "project",
      "url": "http://localhost:5432",
      "description": "Project database"
    }
  }
}
```

### Environment Variables

| Variable | Default | Purpose |
|----------|---------|---------|
| `ANTHROPIC_API_KEY` | Required | Claude API authentication |
| `AUTOCODER_PORT` | 8000 | Server port |
| `AUTOCODER_HOST` | 0.0.0.0 | Server bind address |
| `AUTOCODER_DEBUG` | false | Enable debug logging |

---

## Security Model

### Defense-in-Depth Layers

```
┌─────────────────────────────────────────────────────────────┐
│ Layer 1: OS-Level Sandbox (configurable)                    │
│ - Process isolation                                         │
│ - Currently DISABLED for full system access                 │
└─────────────────────────────────────────────────────────────┘
                              │
┌─────────────────────────────────────────────────────────────┐
│ Layer 2: Filesystem Restrictions                            │
│ - allowed_paths: [project_dir, home_dir, /tmp]             │
│ - Prevents access outside designated directories            │
└─────────────────────────────────────────────────────────────┘
                              │
┌─────────────────────────────────────────────────────────────┐
│ Layer 3: Bash Command Allowlist                             │
│ - ALLOWED_COMMANDS whitelist in security.py                 │
│ - Validates all bash commands before execution              │
└─────────────────────────────────────────────────────────────┘
```

### Allowed Commands (`security.py`)

```python
ALLOWED_COMMANDS = {
    # Package managers
    "npm", "npx", "pip", "pip3", "cargo", "brew", "apt", "apt-get",

    # Development tools
    "node", "python", "python3", "git", "make", "cmake",

    # File operations
    "cat", "ls", "mkdir", "cp", "mv", "rm", "touch", "chmod",

    # Infrastructure access (extended)
    "ssh", "scp", "rsync", "curl", "wget",

    # Container operations
    "docker", "docker-compose",

    # System operations
    "systemctl", "service", "journalctl",

    # Playwright
    "playwright", "npx playwright",
}
```

---

## Items to Make Exceptional

### 1. Multi-Model Support
**Current:** Claude Sonnet only
**Enhancement:** Support multiple AI models for different tasks

```python
class ModelRouter:
    def select_model(task_type: str) -> str:
        models = {
            "analysis": "claude-opus-4",      # Complex reasoning
            "coding": "claude-sonnet-4",      # Fast implementation
            "review": "claude-haiku-3",       # Quick validation
        }
        return models.get(task_type, "claude-sonnet-4")
```

**Benefits:**
- Use Opus for architectural decisions
- Use Sonnet for code implementation
- Use Haiku for quick validations
- Optimize cost vs capability per task

### 2. Intelligent Caching & Learning

**Feature Learning System:**
```python
class FeatureLearning:
    def record_implementation(feature: Feature, code: str, time: float)
    def get_similar_implementations(feature: Feature) -> list[Example]
    def suggest_approach(feature: Feature) -> str
```

**Benefits:**
- Cache successful implementations
- Suggest approaches from similar past features
- Reduce token usage by reusing patterns
- Build project-specific knowledge base

### 3. Real-Time Collaboration

**Live Editing Protocol:**
```python
class CollaborationHub:
    async def broadcast_edit(file: str, change: Change)
    async def request_human_review(file: str, line: int)
    async def accept_human_edit(file: str, change: Change)
```

**Features:**
- Watch mode for file changes
- Human can edit while agent works
- Conflict resolution with git-style markers
- Pair programming mode

### 4. Self-Healing & Adaptive Recovery

**Automatic Recovery System:**
```python
class AdaptiveRecovery:
    def detect_stuck_state() -> bool
    def analyze_failure_pattern(logs: list[str]) -> FailureType
    def generate_recovery_strategy() -> Strategy
    def apply_recovery() -> bool
```

**Capabilities:**
- Detect infinite loops or stuck states
- Analyze error patterns across sessions
- Auto-generate workarounds
- Learn from past failures

### 5. Comprehensive Test Generation

**AI-Driven Testing:**
```python
class TestGenerator:
    def generate_unit_tests(code: str) -> str
    def generate_integration_tests(features: list) -> str
    def generate_edge_cases(function: str) -> list[TestCase]
    def generate_property_tests(type_signature: str) -> str
```

**Benefits:**
- Auto-generate tests during implementation
- Edge case discovery via AI reasoning
- Property-based test generation
- Mutation testing integration

### 6. Visual Progress Dashboard

**Enhanced Visualization:**
- Dependency graph visualization (D3.js)
- Real-time code diff viewer
- Agent thought process timeline
- Token usage analytics
- Cost tracking per feature

### 7. Git Integration

**Smart Version Control:**
```python
class GitIntegration:
    def create_feature_branch(feature: Feature) -> str
    def commit_with_context(files: list, feature: Feature) -> str
    def generate_pr_description(feature: Feature) -> str
    def handle_merge_conflicts(conflicts: list) -> Resolution
```

**Features:**
- Auto-create branches per feature
- Meaningful commit messages from context
- Auto-generate PR descriptions
- AI-assisted conflict resolution

### 8. Plugin Architecture

**Extensibility System:**
```python
class PluginManager:
    def register_hook(event: str, handler: Callable)
    def register_tool(name: str, tool: MCPTool)
    def register_validator(phase: str, validator: Callable)
```

**Plugin Types:**
- Pre/post implementation hooks
- Custom MCP tools
- Additional validators
- Custom reporters

### 9. Cost Optimization

**Token Budget Management:**
```python
class BudgetManager:
    def set_project_budget(project: str, max_tokens: int)
    def track_usage(project: str, tokens: int)
    def get_cost_estimate(feature: Feature) -> float
    def suggest_optimizations() -> list[Suggestion]
```

**Features:**
- Per-project token budgets
- Cost estimation before starting
- Automatic prompt optimization
- Usage analytics and trends

### 10. Enterprise Features

**Production Readiness:**
- SSO/SAML authentication
- Role-based access control
- Audit logging
- API rate limiting
- Multi-tenant support
- Compliance reporting (SOC2, GDPR)

---

## Quick Start

```bash
# 1. Install dependencies
python -m venv venv
venv\Scripts\activate  # Windows
pip install -r requirements.txt

# 2. Install UI dependencies
cd ui && npm install && npm run build && cd ..

# 3. Start the server
start_ui.bat  # Windows
./start_ui.sh # macOS/Linux

# 4. Open browser to http://localhost:8000
```

---

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make changes with tests
4. Submit a pull request

---

*Last Updated: 2026-01-11*
*Version: 2.0.0*


I've created the comprehensive ARCHITECTURE.md document. Let me read the background task output to see what's happening with the Autocoder server, and then summarize what I've done.


Bash

Check Autocoder server output


Error: Exit code 1
tail: cannot open 'C:UsersMIKESW~1AppDataLocalTempclaudeC--Users-MikeSwanson-claude-projectstasksb858320.output' for reading: No such file or directory


The path got mangled. Let me try with proper escaping.


     1→[stderr] INFO:     Started server process [185972]
     2→INFO:     Waiting for application startup.
     3→INFO:     Application startup complete.
     4→INFO:     Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit)
     5→INFO:     127.0.0.1:52754 - "GET /api/projects HTTP/1.1" 200 OK
     6→INFO:     127.0.0.1:49790 - "GET / HTTP/1.1" 200 OK
     7→INFO:     127.0.0.1:57715 - "GET /assets/index-D3cNQxei.css HTTP/1.1" 200 OK
     8→INFO:     127.0.0.1:49790 - "GET /assets/index-bwfHFEvB.js HTTP/1.1" 200 OK
     9→INFO:     127.0.0.1:49790 - "GET /api/projects HTTP/1.1" 200 OK
    10→INFO:     127.0.0.1:49790 - "GET /vite.svg HTTP/1.1" 200 OK
    11→INFO:     127.0.0.1:65109 - "GET /api/filesystem/list HTTP/1.1" 200 OK
    12→INFO:     127.0.0.1:65109 - "GET /api/filesystem/list?path=C%3A%2FUsers%2FMikeSwanson%2Fclaude-projects HTTP/1.1" 200 OK
    13→INFO:     127.0.0.1:65109 - "GET /api/filesystem/list?path=C%3A%2FUsers%2FMikeSwanson%2Fclaude-projects%2FAutocode-remix HTTP/1.1" 200 OK
    14→INFO:     127.0.0.1:65109 - "GET /api/filesystem/list?path=C%3A%2FUsers%2FMikeSwanson%2Fclaude-projects HTTP/1.1" 200 OK
    15→INFO:     127.0.0.1:49247 - "GET / HTTP/1.1" 200 OK
    16→INFO:     127.0.0.1:49247 - "GET /api/projects HTTP/1.1" 200 OK
    17→INFO:     127.0.0.1:59562 - "GET /api/filesystem/list?path=C%3A%2FUsers%2FMikeSwanson%2Fclaude-projects%2FAutocode-remix HTTP/1.1" 200 OK
    18→INFO:     127.0.0.1:59562 - "GET /api/filesystem/list?path=C%3A%2FUsers%2FMikeSwanson%2Fclaude-projects%2FAutocode-remix%2FAutocoder-2.0%20-%20Copy HTTP/1.1" 200 OK
    19→INFO:     127.0.0.1:59562 - "POST /api/projects/import HTTP/1.1" 422 Unprocessable Content
    20→INFO:     127.0.0.1:64466 - "GET / HTTP/1.1" 200 OK
    21→INFO:     127.0.0.1:64466 - "GET /assets/index-48sYoXm9.js HTTP/1.1" 200 OK
    22→INFO:     127.0.0.1:64466 - "GET /api/projects HTTP/1.1" 200 OK
    23→INFO:     127.0.0.1:53476 - "GET /api/filesystem/list HTTP/1.1" 200 OK
    24→INFO:     127.0.0.1:64094 - "GET /api/filesystem/list?path=C%3A%2FUsers%2FMikeSwanson%2Fclaude-projects HTTP/1.1" 200 OK
    25→INFO:     127.0.0.1:53477 - "GET /api/filesystem/list?path=C%3A%2FUsers%2FMikeSwanson%2Fclaude-projects%2Fguru-connect HTTP/1.1" 200 OK
    26→  Created prompt files: app_spec.txt, coding_prompt.md, coding_prompt_yolo.md, initializer_prompt.md
    27→INFO:     127.0.0.1:58070 - "POST /api/projects/import HTTP/1.1" 200 OK
    28→INFO:     127.0.0.1:58070 - "GET /api/projects HTTP/1.1" 200 OK
    29→[stderr] INFO:     127.0.0.1:61355 - "WebSocket /api/spec/ws/guru-connect" [accepted]
    30→[stderr] INFO:     connection open

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

[stderr] INFO:     Started server process [185972]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit)
INFO:     127.0.0.1:52754 - "GET /api/projects HTTP/1.1" 200 OK
INFO:     127.0.0.1:49790 - "GET / HTTP/1.1" 200 OK
INFO:     127.0.0.1:57715 - "GET /assets/index-D3cNQxei.css HTTP/1.1" 200 OK
INFO:     127.0.0.1:49790 - "GET /assets/index-bwfHFEvB.js HTTP/1.1" 200 OK
INFO:     127.0.0.1:49790 - "GET /api/projects HTTP/1.1" 200 OK
INFO:     127.0.0.1:49790 - "GET /vite.svg HTTP/1.1" 200 OK
INFO:     127.0.0.1:65109 - "GET /api/filesystem/list HTTP/1.1" 200 OK
INFO:     127.0.0.1:65109 - "GET /api/filesystem/list?path=C%3A%2FUsers%2FMikeSwanson%2Fclaude-projects HTTP/1.1" 200 OK
INFO:     127.0.0.1:65109 - "GET /api/filesystem/list?path=C%3A%2FUsers%2FMikeSwanson%2Fclaude-projects%2FAutocode-remix HTTP/1.1" 200 OK
INFO:     127.0.0.1:65109 - "GET /api/filesystem/list?path=C%3A%2FUsers%2FMikeSwanson%2Fclaude-projects HTTP/1.1" 200 OK
INFO:     127.0.0.1:49247 - "GET / HTTP/1.1" 200 OK
INFO:     127.0.0.1:49247 - "GET /api/projects HTTP/1.1" 200 OK
INFO:     127.0.0.1:59562 - "GET /api/filesystem/list?path=C%3A%2FUsers%2FMikeSwanson%2Fclaude-projects%2FAutocode-remix HTTP/1.1" 200 OK
INFO:     127.0.0.1:59562 - "GET /api/filesystem/list?path=C%3A%2FUsers%2FMikeSwanson%2Fclaude-projects%2FAutocode-remix%2FAutocoder-2.0%20-%20Copy HTTP/1.1" 200 OK
INFO:     127.0.0.1:59562 - "POST /api/projects/import HTTP/1.1" 422 Unprocessable Content
INFO:     127.0.0.1:64466 - "GET / HTTP/1.1" 200 OK
INFO:     127.0.0.1:64466 - "GET /assets/index-48sYoXm9.js HTTP/1.1" 200 OK
INFO:     127.0.0.1:64466 - "GET /api/projects HTTP/1.1" 200 OK
INFO:     127.0.0.1:53476 - "GET /api/filesystem/list HTTP/1.1" 200 OK
INFO:     127.0.0.1:64094 - "GET /api/filesystem/list?path=C%3A%2FUsers%2FMikeSwanson%2Fclaude-projects HTTP/1.1" 200 OK
INFO:     127.0.0.1:53477 - "GET /api/filesystem/list?path=C%3A%2FUsers%2FMikeSwanson%2Fclaude-projects%2Fguru-connect HTTP/1.1" 200 OK
  Created prompt files: app_spec.txt, coding_prompt.md, coding_prompt_yolo.md, initializer_prompt.md
INFO:     127.0.0.1:58070 - "POST /api/projects/import HTTP/1.1" 200 OK
INFO:     127.0.0.1:58070 - "GET /api/projects HTTP/1.1" 200 OK
[stderr] INFO:     127.0.0.1:61355 - "WebSocket /api/spec/ws/guru-connect" [accepted]
[stderr] INFO:     connection open


The server is running and the documentation has been created. Let me provide a summary of what was accomplished.


I've created the comprehensive documentation for Autocoder 2.0. The file is at:

**`Autocode-remix/Autocoder-2.0/ARCHITECTURE.md`**

## Document Summary

The 750+ line documentation covers:

### Technical Documentation
- **System Overview** - Technology stack, directory structure
- **Core Architecture** - Two-agent pattern diagrams, parallel execution model
- **Agent System** - Main loop, Claude SDK client, parallel runner, smart orchestrator
- **Server Architecture** - All 74 API routes, 10 server services with full method signatures
- **UI Components** - 24 React components, design system, hooks
- **Database Schema** - Features table, project registry
- **MCP Tools** - All 7 feature management tools
- **Configuration** - Prompt templates, resource files, environment variables
- **Security Model** - Three-layer defense with allowed commands

### Items to Make Exceptional (10 recommendations)

1. **Multi-Model Support** - Use Opus for analysis, Sonnet for coding, Haiku for validation
2. **Intelligent Caching & Learning** - Cache successful implementations, suggest approaches
3. **Real-Time Collaboration** - Watch mode, human editing while agent works
4. **Self-Healing Recovery** - Detect stuck states, auto-generate workarounds
5. **AI-Driven Test Generation** - Auto-generate unit, integration, and property tests
6. **Visual Progress Dashboard** - Dependency graphs, diff viewer, token analytics
7. **Git Integration** - Auto-branches, meaningful commits, AI conflict resolution
8. **Plugin Architecture** - Extensible hooks, custom MCP tools, validators
9. **Cost Optimization** - Token budgets, usage tracking, prompt optimization
10. **Enterprise Features** - SSO, RBAC, audit logging, multi-tenant support

The Autocoder server is still running at http://localhost:8080 with the guru-connect project imported.


If I wanted to use autocoder plus to work on this project, what would be the most effective prompt


The user is asking about how to effectively use Autocoder 2.0 to work on improving the Autocoder project itself - essentially using it to build itself. This is a great meta question.

Let me think about what makes an effective app_spec.txt for Autocoder. Based on my understanding of the system:

1. The Initializer Agent reads app_spec.txt and creates features with priorities
2. The Coding Agent then implements features one by one
3. Features need clear, testable steps

For Autocoder to work on itself effectively, the prompt should:
- Define clear, independent features that can be implemented incrementally
- Have testable verification steps
- Be aware of the existing codebase structure
- Focus on enhancements rather than rewrites

Let me suggest an effective app spec approach.


Great question. For Autocoder to work on itself effectively, you need a well-structured `app_spec.txt` that breaks down enhancements into testable, independent features. Here's an approach:

## Effective App Spec Structure

```xml
<?xml version="1.0" encoding="UTF-8"?>
<app_spec>
  <project>
    <name>Autocoder 2.0 Enhancements</name>
    <description>
      Enhance the existing Autocoder autonomous coding system with
      multi-model support, intelligent caching, and improved reliability.
    </description>
    <tech_stack>
      <backend>Python 3.11, FastAPI, SQLAlchemy, Claude Agent SDK</backend>
      <frontend>React 18, TypeScript, TanStack Query, Tailwind CSS v4</frontend>
      <database>SQLite</database>
    </tech_stack>
  </project>

  <existing_architecture>
    <!-- Critical: Tell it what already exists -->
    <note>This is an EXISTING codebase. Do not recreate files that exist.</note>
    <entry_points>
      <file>agent.py - Main agent loop</file>
      <file>client.py - Claude SDK configuration</file>
      <file>server/main.py - FastAPI server</file>
    </entry_points>
  </existing_architecture>

  <features>
    <!-- Start with LOW-RISK, HIGH-VALUE features -->

    <feature priority="1" category="observability">
      <name>Token Usage Tracking</name>
      <description>
        Add token counting and cost tracking to each agent session.
        Store in SQLite, expose via API endpoint.
      </description>
      <steps>
        1. Create api/models/usage.py with UsageRecord model
        2. Update agent.py to count tokens from Claude responses
        3. Add /api/usage/{project} endpoint to server
        4. Verify: Start agent, check usage appears in database
      </steps>
    </feature>

    <feature priority="2" category="reliability">
      <name>Session Recovery</name>
      <description>
        Save agent state periodically so crashed sessions can resume.
      </description>
      <steps>
        1. Create server/services/checkpoint_manager.py
        2. Save state every 5 tool calls in agent.py
        3. Add --resume flag to autonomous_agent_demo.py
        4. Verify: Kill agent mid-session, resume continues
      </steps>
    </feature>

    <feature priority="3" category="ui">
      <name>Cost Display in Dashboard</name>
      <description>
        Show running cost estimate in the UI header.
      </description>
      <steps>
        1. Add useUsage hook in ui/src/hooks/
        2. Create CostBadge component
        3. Add to App.tsx header
        4. Verify: UI shows updating cost while agent runs
      </steps>
    </feature>

    <!-- More features... -->
  </features>

  <constraints>
    <constraint>Do NOT modify security.py allowlist</constraint>
    <constraint>Do NOT change database schema without migration</constraint>
    <constraint>All new endpoints must have OpenAPI docs</constraint>
    <constraint>UI changes require npm run build after</constraint>
  </constraints>

  <testing>
    <strategy>
      Each feature must pass lint (ruff), type-check (pyright/mypy),
      and manual verification of the described steps.
    </strategy>
  </testing>
</app_spec>
```

## Key Principles for Self-Improvement Specs

| Principle | Why |
|-----------|-----|
| **Small, independent features** | Parallel agents can work without conflicts |
| **Explicit "what exists"** | Prevents recreating existing code |
| **Clear verification steps** | Agent knows when it's done |
| **Priority ordering** | Foundation features first |
| **Constraints section** | Prevent breaking changes |

## Recommended First Enhancement Batch

Based on the architecture doc, I'd prioritize these features:

1. **Token/Cost Tracking** - Low risk, high visibility
2. **Session Checkpointing** - Enables reliability improvements
3. **Better Error Logging** - Helps debug agent issues
4. **Git Auto-Commit** - Per-feature commits for safety

Would you like me to create a complete `app_spec.txt` targeting specific enhancements from the "Items to Make Exceptional" list?


Yes, but format it as conversational.  I'm using the appspec interview. I think we should allow for flexibility in stack decisions, claude can choose to make changes if it feels necessary.


The user wants me to format the app spec as a conversational description rather than XML, because they're using the spec creation wizard which interviews them about the project. They also want to give Claude flexibility to make tech stack decisions rather than being prescriptive.

Let me write a conversational prompt that:
1. Describes the project clearly
2. Explains what exists
3. Lists the enhancements they want
4. Gives Claude freedom to choose approaches
5. Is natural/conversational in tone


Here's a conversational prompt for the spec interview:

---

**Project Description:**

I want to enhance Autocoder 2.0 - this is an existing autonomous coding agent system that's already functional. It uses Claude Agent SDK to build applications over multiple sessions with a two-agent pattern (initializer creates features, coding agent implements them).

The current stack is Python/FastAPI backend, React/TypeScript frontend, SQLite database, but I'm open to changes if you think something would work better.

**What already exists and works:**
- Full agent loop with pause/resume/stop controls
- Feature database and MCP tools for tracking progress
- React UI with kanban board and real-time WebSocket updates
- Parallel agent execution with file locking
- Smart scheduler for parallelization decisions
- Infrastructure context injection (credentials, servers)
- YOLO mode for rapid prototyping

**What I want to add (in rough priority order):**

1. **Token and cost tracking** - I want to see how much each session/feature costs. Store the data, show it in the UI somewhere.

2. **Session recovery** - If the agent crashes or I close it, I want to resume where it left off instead of starting over.

3. **Better git integration** - Auto-commit after each feature passes, meaningful commit messages, maybe auto-create branches per feature.

4. **Multi-model support** - Use different Claude models for different tasks. Maybe Opus for complex analysis, Sonnet for coding, Haiku for quick validations. You decide what makes sense.

5. **Learning from past work** - Cache successful implementations so the agent can reference similar past solutions. Build up project knowledge over time.

6. **Visual improvements** - Show a dependency graph of features, token usage charts, maybe a timeline of what the agent is thinking.

**Guidelines:**
- Don't break what's working - enhance it
- You can refactor if it makes the enhancements cleaner
- Each feature should be testable independently
- I trust your judgment on implementation details

---

Want me to adjust the scope or emphasis on any of these?


I've noticed running autocoder creates zombie processes all over the place, let's make sure that there is a mechanism to prevent that


The user is reporting a real bug with Autocoder - it's creating zombie processes. This is a common issue with subprocess management in Python, especially when running agents as subprocesses. Let me investigate the codebase to understand how processes are spawned and managed, then suggest adding this to the enhancement spec.

First, let me look at how processes are managed in the codebase.


Good catch - zombie processes are a serious issue. Let me investigate how processes are currently managed.


Found 10 files
Autocode-remix\Autocoder-2.0\server\routers\projects.py
Autocode-remix\Autocoder-2.0\server\services\__init__.py
Autocode-remix\Autocoder-2.0\server\services\git_operations.py
Autocode-remix\Autocoder-2.0\server\services\resource_manager.py
Autocode-remix\Autocoder-2.0\security.py
Autocode-remix\Autocoder-2.0\server\services\spec_chat_session.py
Autocode-remix\Autocoder-2.0\server\services\process_manager.py
Autocode-remix\Autocoder-2.0\test_security.py
Autocode-remix\Autocoder-2.0\start_ui.py
Autocode-remix\Autocoder-2.0\start.py


Found 5 files
Autocode-remix\Autocoder-2.0\server\services\terminal_session.py
Autocode-remix\Autocoder-2.0\server\services\spec_chat_session.py
Autocode-remix\Autocoder-2.0\server\services\process_manager.py
Autocode-remix\Autocoder-2.0\server\services\assistant_chat_session.py
Autocode-remix\Autocoder-2.0\server\routers\agent.py


There's a process_manager.py which is promising. Let me read it along with the agent router to understand the current process management.