Begin the spec creation process.


Hi! I'm here to help you create a detailed specification for your app.

Let's start with the basics:

1. **What do you want to call this project?**
2. **In your own words, what are you building?** (What problem does it solve? What does it do?)
3. **Who will use it** - just you, or others too?

Take your time - I'd love to hear about your project idea!


AutoCoder++ Claude SDK Wrapper for managing Project Development, This is just for me at the moment.


Great, thanks for sharing!

So you're building **AutoCoder++** - a Claude SDK wrapper to help you manage project development. And it's for your personal use right now.

Before I dive deeper, I'd love to understand a bit more about what you're envisioning:

**Can you tell me more about what "managing project development" means to you?**

For example:
- Is this a tool that helps you organize and track coding projects?
- Does it wrap the Claude API to automate certain development tasks?
- Is there a UI involved, or is it more of a CLI/backend tool?
- What's the main problem you're trying to solve that existing tools don't handle well?

Just describe it however makes sense to you - I'll figure out the technical details from there!


See: Autocode-remix/Autocoder-2.0/ARCHITECTURE.md


<tool_use_error>File does not exist.</tool_use_error>


Let me search for that file:


No files found


Bash

List contents of project directory


total 5
drwxr-xr-x 1 AzureAD+MikeSwanson 4096   0 Jan 11 08:16 ./
drwxr-xr-x 1 AzureAD+MikeSwanson 4096   0 Jan 11 08:16 ../
-rw-r--r-- 1 AzureAD+MikeSwanson 4096 215 Jan 11 08:16 .claude_settings.json
drwxr-xr-x 1 AzureAD+MikeSwanson 4096   0 Jan 11 08:16 prompts/


I see the project directory is fairly empty right now. The path you mentioned (`Autocode-remix/Autocoder-2.0/ARCHITECTURE.md`) doesn't exist in this project folder.

Do you have that ARCHITECTURE.md file somewhere else on your system? Perhaps you could:

1. **Share the path** where that file actually lives (maybe in a different folder?)
2. **Copy/paste the key parts** of what's in that document
3. **Describe the architecture** you have in mind

I want to understand your existing vision for AutoCoder++ so I can create an accurate spec!


     1→# Autocoder 2.0 - Complete Architecture Documentation
     2→
     3→## Executive Summary
     4→
     5→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.
     6→
     7→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.
     8→
     9→---
    10→
    11→## Table of Contents
    12→
    13→1. [System Overview](#system-overview)
    14→2. [Core Architecture](#core-architecture)
    15→3. [Agent System](#agent-system)
    16→4. [Server Architecture](#server-architecture)
    17→5. [UI Components](#ui-components)
    18→6. [Database Schema](#database-schema)
    19→7. [MCP Tools](#mcp-tools)
    20→8. [Configuration](#configuration)
    21→9. [Security Model](#security-model)
    22→10. [Items to Make Exceptional](#items-to-make-exceptional)
    23→
    24→---
    25→
    26→## System Overview
    27→
    28→### Technology Stack
    29→
    30→| Layer | Technology |
    31→|-------|------------|
    32→| AI Backend | Claude Agent SDK, Anthropic API |
    33→| Server | Python 3.11+, FastAPI, SQLAlchemy |
    34→| Database | SQLite (features.db, registry.db) |
    35→| Frontend | React 18, TypeScript, TanStack Query |
    36→| Styling | Tailwind CSS v4, Radix UI |
    37→| Real-time | WebSocket |
    38→| Testing | Playwright MCP (browser automation) |
    39→
    40→### Directory Structure
    41→
    42→```
    43→Autocoder-2.0/
    44→├── agent.py                 # Main agent session loop
    45→├── autonomous_agent_demo.py # CLI entry point
    46→├── client.py                # Claude SDK client configuration
    47→├── parallel_agent.py        # Parallel agent runner
    48→├── smart_orchestrator.py    # AI-driven parallelization
    49→├── progress.py              # Progress tracking & database queries
    50→├── prompts.py               # Prompt template loading with context
    51→├── registry.py              # Project registry (SQLite)
    52→├── security.py              # Bash command allowlist
    53→├── start.py                 # CLI launcher menu
    54→│
    55→├── api/
    56→│   └── database.py          # SQLAlchemy models
    57→│
    58→├── mcp_server/
    59→│   └── feature_mcp.py       # MCP server for feature management
    60→│
    61→├── server/
    62→│   ├── main.py              # FastAPI application
    63→│   ├── services/            # Business logic
    64→│   │   ├── agent_runner.py
    65→│   │   ├── credential_resolver.py
    66→│   │   ├── feature_graph.py
    67→│   │   ├── file_lock_manager.py
    68→│   │   ├── prompt_generator.py
    69→│   │   ├── resource_context.py
    70→│   │   ├── resource_manager.py
    71→│   │   ├── session_manager.py
    72→│   │   ├── smart_scheduler.py
    73→│   │   └── spec_generator.py
    74→│   └── routers/             # API endpoints
    75→│       ├── agent.py
    76→│       ├── features.py
    77→│       ├── filesystem.py
    78→│       ├── projects.py
    79→│       └── spec_creation.py
    80→│
    81→├── ui/                      # React frontend
    82→│   ├── src/
    83→│   │   ├── App.tsx
    84→│   │   ├── components/      # 24 UI components
    85→│   │   ├── hooks/           # React Query hooks
    86→│   │   ├── lib/             # API client, types
    87→│   │   └── styles/          # Tailwind theme
    88→│   └── dist/                # Production build
    89→│
    90→├── prompts/                 # Default prompt templates
    91→└── .claude/
    92→    ├── commands/            # Slash commands
    93→    ├── skills/              # AI skills
    94→    └── templates/           # Prompt templates
    95→```
    96→
    97→---
    98→
    99→## Core Architecture
   100→
   101→### Two-Agent Pattern
   102→
   103→```
   104→┌─────────────────────────────────────────────────────────────┐
   105→│                    APPLICATION SPEC                          │
   106→│                    (prompts/app_spec.txt)                   │
   107→└─────────────────────────────────────────────────────────────┘
   108→                              │
   109→                              ▼
   110→┌─────────────────────────────────────────────────────────────┐
   111→│                   INITIALIZER AGENT                          │
   112→│  • Reads app_spec.txt                                       │
   113→│  • Analyzes requirements                                    │
   114→│  • Creates features in SQLite with priorities               │
   115→│  • Defines test steps for each feature                      │
   116→└─────────────────────────────────────────────────────────────┘
   117→                              │
   118→                              ▼
   119→┌─────────────────────────────────────────────────────────────┐
   120→│                    FEATURES DATABASE                         │
   121→│  (features.db - SQLite)                                     │
   122→│  • priority: int (lower = higher priority)                  │
   123→│  • category: str                                            │
   124→│  • name: str                                                │
   125→│  • description: str                                         │
   126→│  • steps: str (JSON array of test steps)                    │
   127→│  • passes: bool                                             │
   128→│  • in_progress: bool                                        │
   129→└─────────────────────────────────────────────────────────────┘
   130→                              │
   131→                              ▼
   132→┌─────────────────────────────────────────────────────────────┐
   133→│                    CODING AGENT                              │
   134→│  Loop until all features pass:                              │
   135→│  1. Get next pending feature (highest priority)             │
   136→│  2. Implement the feature                                   │
   137→│  3. Run lint/type-check                                     │
   138→│  4. Run Playwright tests (unless YOLO mode)                 │
   139→│  5. Run regression tests on random passing features         │
   140→│  6. Mark feature as passing or retry                        │
   141→└─────────────────────────────────────────────────────────────┘
   142→```
   143→
   144→### Parallel Execution Model
   145→
   146→```
   147→┌─────────────────────────────────────────────────────────────┐
   148→│                   SMART ORCHESTRATOR                         │
   149→│  (smart_orchestrator.py)                                    │
   150→│                                                             │
   151→│  1. Analyze all pending features                            │
   152→│  2. Use Claude to identify parallelizable groups            │
   153→│  3. Detect file conflicts (feature_graph.py)                │
   154→│  4. Acquire file locks (file_lock_manager.py)               │
   155→│  5. Spawn parallel agents for non-conflicting features      │
   156→│  6. Merge results and handle conflicts                      │
   157→└─────────────────────────────────────────────────────────────┘
   158→                              │
   159→              ┌───────────────┼───────────────┐
   160→              ▼               ▼               ▼
   161→        ┌─────────┐     ┌─────────┐     ┌─────────┐
   162→        │ Agent 1 │     │ Agent 2 │     │ Agent 3 │
   163→        │Feature A│     │Feature B│     │Feature C│
   164→        └─────────┘     └─────────┘     └─────────┘
   165→              │               │               │
   166→              └───────────────┼───────────────┘
   167→                              ▼
   168→                    ┌─────────────────┐
   169→                    │  Result Merger  │
   170→                    │  & Verification │
   171→                    └─────────────────┘
   172→```
   173→
   174→---
   175→
   176→## Agent System
   177→
   178→### Main Agent Loop (`agent.py`)
   179→
   180→The agent runs in sessions with automatic continuation:
   181→
   182→```python
   183→async def run_agent_session(
   184→    project_dir: Path,
   185→    stop_event: Optional[asyncio.Event] = None,
   186→    pause_event: Optional[asyncio.Event] = None,
   187→    yolo_mode: bool = False,
   188→) -> dict
   189→```
   190→
   191→**Session Flow:**
   192→1. Check if `features.db` has features → determines initializer vs coding
   193→2. Create `ClaudeSDKClient` with security settings
   194→3. Load context-aware prompt with infrastructure info
   195→4. Send prompt and stream response
   196→5. Auto-continue with 3-second delay between sessions
   197→6. Repeat until all features pass or stopped
   198→
   199→### Claude SDK Client (`client.py`)
   200→
   201→```python
   202→class ClaudeSDKClient:
   203→    def create(
   204→        self,
   205→        model: str = "claude-sonnet-4-20250514",
   206→        mcp_servers: list = None,
   207→        system_prompt: str = None,
   208→        allowed_paths: list = None,
   209→    ) -> AgentConfig
   210→```
   211→
   212→**Configuration:**
   213→- Model: `claude-sonnet-4-20250514` (configurable)
   214→- Max tokens: 16384
   215→- Sandbox: **Disabled** for full system access
   216→- MCP Servers: Feature MCP, optionally Playwright MCP
   217→- Bash permissions: Extended allowlist (SSH, SCP, docker, etc.)
   218→
   219→### Parallel Agent Runner (`parallel_agent.py`)
   220→
   221→```python
   222→async def run_parallel_agents(
   223→    project_dir: Path,
   224→    max_concurrent: int = 3,
   225→    yolo_mode: bool = False,
   226→) -> dict
   227→```
   228→
   229→**Features:**
   230→- Spawns multiple agents working on non-conflicting features
   231→- Uses `asyncio.Semaphore` for concurrency control
   232→- Coordinates via `file_lock_manager.py`
   233→- Aggregates results from all agents
   234→
   235→### Smart Orchestrator (`smart_orchestrator.py`)
   236→
   237→```python
   238→class SmartOrchestrator:
   239→    async def run_smart_session(
   240→        self,
   241→        max_concurrent: int = 3,
   242→        yolo_mode: bool = False,
   243→    ) -> dict
   244→```
   245→
   246→**AI-Driven Parallelization:**
   247→1. Fetches all pending features
   248→2. Calls Claude to analyze and group parallelizable features
   249→3. Detects file-level conflicts using `FeatureGraph`
   250→4. Acquires locks on affected files
   251→5. Runs grouped features in parallel batches
   252→6. Handles merge conflicts and verification
   253→
   254→---
   255→
   256→## Server Architecture
   257→
   258→### FastAPI Application (`server/main.py`)
   259→
   260→**74 API Routes across 5 routers:**
   261→
   262→| Router | Prefix | Routes | Purpose |
   263→|--------|--------|--------|---------|
   264→| projects | `/api/projects` | 15 | Project CRUD, registry |
   265→| features | `/api/features` | 12 | Feature management |
   266→| agent | `/api/agent` | 10 | Agent control |
   267→| filesystem | `/api/filesystem` | 5 | Folder browser |
   268→| spec_creation | `/api/spec` | 3 | WebSocket spec wizard |
   269→
   270→**WebSocket Endpoints:**
   271→- `/ws/projects/{project_name}` - Real-time updates
   272→- `/api/spec/ws` - Interactive spec creation
   273→
   274→### Server Services
   275→
   276→#### 1. AgentRunner (`services/agent_runner.py`)
   277→Manages agent lifecycle with subprocess isolation.
   278→
   279→```python
   280→class AgentRunner:
   281→    async def start_agent(project_name: str, yolo: bool = False) -> dict
   282→    async def stop_agent(project_name: str) -> dict
   283→    async def pause_agent(project_name: str) -> dict
   284→    async def resume_agent(project_name: str) -> dict
   285→    def get_agent_status(project_name: str) -> AgentStatus
   286→```
   287→
   288→**Status States:** `idle`, `running`, `paused`, `crashed`
   289→
   290→#### 2. CredentialResolver (`services/credential_resolver.py`)
   291→Parses `credentials.md` for infrastructure access.
   292→
   293→```python
   294→class CredentialResolver:
   295→    def __init__(credentials_path: Path)
   296→    def get_credential(service_name: str) -> Optional[Credential]
   297→    def get_all_credentials() -> dict[str, Credential]
   298→    def resolve_for_resource(resource: Resource) -> Resource
   299→```
   300→
   301→**Parsed Format:**
   302→```markdown
   303→### Service Name
   304→- **Host:** hostname
   305→- **Username:** user
   306→- **Password:** secret
   307→```
   308→
   309→#### 3. FeatureGraph (`services/feature_graph.py`)
   310→Tracks dependencies and file conflicts.
   311→
   312→```python
   313→class FeatureGraph:
   314→    def add_feature(feature_id: str, files: list[str])
   315→    def get_conflicts(feature_id: str) -> list[str]
   316→    def get_safe_parallel_groups() -> list[list[str]]
   317→    def mark_completed(feature_id: str)
   318→```
   319→
   320→**Conflict Detection:**
   321→- Builds graph of feature → files mapping
   322→- Detects overlapping file modifications
   323→- Returns groups of non-conflicting features
   324→
   325→#### 4. FileLockManager (`services/file_lock_manager.py`)
   326→Async-safe file locking for parallel agents.
   327→
   328→```python
   329→class FileLockManager:
   330→    async def acquire(file_path: str, owner: str) -> bool
   331→    async def release(file_path: str, owner: str)
   332→    async def is_locked(file_path: str) -> bool
   333→    def get_owner(file_path: str) -> Optional[str]
   334→```
   335→
   336→**Implementation:**
   337→- Uses `asyncio.Lock` for thread safety
   338→- Supports timeout-based acquisition
   339→- Tracks lock ownership for debugging
   340→
   341→#### 5. PromptGenerator (`services/prompt_generator.py`)
   342→Generates context-rich prompts.
   343→
   344→```python
   345→class PromptGenerator:
   346→    def generate_initializer_prompt(project: Project) -> str
   347→    def generate_coding_prompt(project: Project, feature: Feature) -> str
   348→    def inject_context(prompt: str, context: dict) -> str
   349→```
   350→
   351→#### 6. ResourceContext (`services/resource_context.py`)
   352→Loads and merges infrastructure resources.
   353→
   354→```python
   355→def get_merged_resources(project_dir: Path) -> dict
   356→def get_infrastructure_context(project_name: str, project_dir: Path) -> str
   357→```
   358→
   359→**Resource Sources:**
   360→1. Global: `~/.autocoder/global_resources.json`
   361→2. Project: `{project}/resources.json`
   362→
   363→#### 7. ResourceManager (`services/resource_manager.py`)
   364→Tracks servers/services with verification.
   365→
   366→```python
   367→class ResourceManager:
   368→    def add_resource(name: str, resource: Resource)
   369→    def get_resource(name: str) -> Resource
   370→    async def verify_resource(name: str) -> bool
   371→    def list_resources() -> list[Resource]
   372→```
   373→
   374→**Resource Types:**
   375→- `server` - SSH-accessible machines
   376→- `service` - HTTP/HTTPS endpoints
   377→
   378→#### 8. SessionManager (`services/session_manager.py`)
   379→Manages agent sessions with persistence.
   380→
   381→```python
   382→class SessionManager:
   383→    def create_session(project_name: str) -> Session
   384→    def get_session(project_name: str) -> Optional[Session]
   385→    def end_session(project_name: str)
   386→    def get_session_logs(project_name: str) -> list[str]
   387→```
   388→
   389→#### 9. SmartScheduler (`services/smart_scheduler.py`)
   390→Prioritizes features intelligently.
   391→
   392→```python
   393→class SmartScheduler:
   394→    def get_next_feature(project_name: str) -> Optional[Feature]
   395→    def reorder_by_dependencies() -> list[Feature]
   396→    def get_parallel_batch(max_size: int) -> list[Feature]
   397→```
   398→
   399→**Scheduling Factors:**
   400→- Feature priority (lower = higher)
   401→- Dependency order
   402→- File conflict avoidance
   403→- Category grouping
   404→
   405→#### 10. SpecGenerator (`services/spec_generator.py`)
   406→Creates app specifications via conversation.
   407→
   408→```python
   409→class SpecGenerator:
   410→    async def start_conversation(initial_idea: str) -> ConversationState
   411→    async def continue_conversation(user_input: str) -> ConversationState
   412→    def generate_spec() -> str
   413→    def save_spec(project_dir: Path)
   414→```
   415→
   416→---
   417→
   418→## UI Components
   419→
   420→### Main Application (`ui/src/App.tsx`)
   421→
   422→**Features:**
   423→- Project selection dropdown
   424→- Kanban board (Pending → In Progress → Done)
   425→- Agent controls (Start/Stop/Pause/Resume)
   426→- YOLO mode toggle
   427→- Real-time progress bar
   428→- Log viewer
   429→
   430→### Component Library (24 components)
   431→
   432→| Component | Purpose |
   433→|-----------|---------|
   434→| `AgentControls.tsx` | Start/stop/pause/resume buttons |
   435→| `AgentStatusBadge.tsx` | Status indicator |
   436→| `FeatureCard.tsx` | Draggable feature card |
   437→| `FeatureColumn.tsx` | Kanban column |
   438→| `FolderBrowser.tsx` | Server-side filesystem browser |
   439→| `KanbanBoard.tsx` | Feature board layout |
   440→| `LogViewer.tsx` | Real-time log display |
   441→| `NewProjectModal.tsx` | Multi-step project wizard |
   442→| `ProgressBar.tsx` | Animated progress indicator |
   443→| `ProjectSelector.tsx` | Project dropdown |
   444→| `SpecCreationWizard.tsx` | Interactive spec builder |
   445→| `YoloModeToggle.tsx` | Lightning bolt toggle |
   446→
   447→### Design System
   448→
   449→**Neobrutalism Theme:**
   450→- Bold borders: `border-4 border-black`
   451→- Hard shadows: `shadow-[4px_4px_0_0_#000]`
   452→- Vibrant colors with CSS variables
   453→- Monospace fonts for code elements
   454→
   455→**Color Tokens:**
   456→```css
   457→--color-neo-pending: #fbbf24;   /* Yellow */
   458→--color-neo-progress: #22d3ee;  /* Cyan */
   459→--color-neo-done: #22c55e;      /* Green */
   460→--color-neo-error: #ef4444;     /* Red */
   461→```
   462→
   463→**Animations:**
   464→- `animate-slide-in` - Card entrance
   465→- `animate-pulse-neo` - Status indicator
   466→- `animate-shimmer` - Progress bar
   467→
   468→### React Query Hooks
   469→
   470→```typescript
   471→// ui/src/hooks/useProjects.ts
   472→useProjects()           // List all projects
   473→useProject(name)        // Get single project
   474→useCreateProject()      // Create new project
   475→useImportProject()      // Import existing project
   476→
   477→// ui/src/hooks/useFeatures.ts
   478→useFeatures(project)    // List features
   479→useUpdateFeature()      // Update feature status
   480→
   481→// ui/src/hooks/useAgent.ts
   482→useAgentStatus(project) // Current agent status
   483→useStartAgent()         // Start agent
   484→useStopAgent()          // Stop agent
   485→
   486→// ui/src/hooks/useWebSocket.ts
   487→useWebSocket(project)   // Real-time updates
   488→```
   489→
   490→---
   491→
   492→## Database Schema
   493→
   494→### Features Table (`features.db`)
   495→
   496→```sql
   497→CREATE TABLE features (
   498→    id INTEGER PRIMARY KEY AUTOINCREMENT,
   499→    priority INTEGER NOT NULL DEFAULT 0,
   500→    category TEXT NOT NULL,
   501→    name TEXT NOT NULL,
   502→    description TEXT NOT NULL,
   503→    steps TEXT NOT NULL,  -- JSON array
   504→    passes BOOLEAN NOT NULL DEFAULT FALSE,
   505→    in_progress BOOLEAN NOT NULL DEFAULT FALSE,
   506→    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
   507→    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
   508→);
   509→
   510→CREATE INDEX idx_features_priority ON features(priority);
   511→CREATE INDEX idx_features_passes ON features(passes);
   512→```
   513→
   514→### Project Registry (`~/.autocoder/registry.db`)
   515→
   516→```sql
   517→CREATE TABLE projects (
   518→    id INTEGER PRIMARY KEY AUTOINCREMENT,
   519→    name TEXT NOT NULL UNIQUE,
   520→    path TEXT NOT NULL,  -- POSIX format
   521→    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
   522→    last_accessed TIMESTAMP
   523→);
   524→```
   525→
   526→---
   527→
   528→## MCP Tools
   529→
   530→The Feature MCP server (`mcp_server/feature_mcp.py`) exposes 7 tools:
   531→
   532→| Tool | Purpose |
   533→|------|---------|
   534→| `feature_get_stats` | Get progress statistics (pending/in_progress/completed/total) |
   535→| `feature_get_next` | Get highest-priority pending feature |
   536→| `feature_get_for_regression` | Get random passing features for regression testing |
   537→| `feature_mark_passing` | Mark feature as complete |
   538→| `feature_mark_in_progress` | Mark feature as being worked on |
   539→| `feature_skip` | Move feature to end of queue |
   540→| `feature_create_bulk` | Initialize all features (used by initializer) |
   541→
   542→**MCP Server Configuration:**
   543→```python
   544→mcp_servers = [
   545→    {
   546→        "name": "feature-mcp",
   547→        "command": "python",
   548→        "args": [str(mcp_server_path), str(project_dir)],
   549→    }
   550→]
   551→```
   552→
   553→---
   554→
   555→## Configuration
   556→
   557→### Prompt Templates
   558→
   559→| Template | Location | Purpose |
   560→|----------|----------|---------|
   561→| `initializer_prompt.md` | `prompts/` or `.claude/templates/` | First session - create features |
   562→| `coding_prompt.md` | `prompts/` or `.claude/templates/` | Continuation - implement features |
   563→| `coding_prompt_yolo.md` | `prompts/` or `.claude/templates/` | YOLO mode - skip testing |
   564→| `app_spec.txt` | `prompts/` | Application specification (XML) |
   565→
   566→### Resource Configuration
   567→
   568→**Global Resources (`~/.autocoder/global_resources.json`):**
   569→```json
   570→{
   571→  "resources": {
   572→    "ServerName": {
   573→      "type": "server",
   574→      "scope": "global",
   575→      "host": "192.168.1.100",
   576→      "user": "admin",
   577→      "description": "Description",
   578→      "auth": {
   579→        "type": "ssh-password",
   580→        "credential_ref": "server-creds"
   581→      }
   582→    }
   583→  }
   584→}
   585→```
   586→
   587→**Project Resources (`{project}/resources.json`):**
   588→```json
   589→{
   590→  "resources": {
   591→    "LocalDB": {
   592→      "type": "service",
   593→      "scope": "project",
   594→      "url": "http://localhost:5432",
   595→      "description": "Project database"
   596→    }
   597→  }
   598→}
   599→```
   600→
   601→### Environment Variables
   602→
   603→| Variable | Default | Purpose |
   604→|----------|---------|---------|
   605→| `ANTHROPIC_API_KEY` | Required | Claude API authentication |
   606→| `AUTOCODER_PORT` | 8000 | Server port |
   607→| `AUTOCODER_HOST` | 0.0.0.0 | Server bind address |
   608→| `AUTOCODER_DEBUG` | false | Enable debug logging |
   609→
   610→---
   611→
   612→## Security Model
   613→
   614→### Defense-in-Depth Layers
   615→
   616→```
   617→┌─────────────────────────────────────────────────────────────┐
   618→│ Layer 1: OS-Level Sandbox (configurable)                    │
   619→│ - Process isolation                                         │
   620→│ - Currently DISABLED for full system access                 │
   621→└─────────────────────────────────────────────────────────────┘
   622→                              │
   623→┌─────────────────────────────────────────────────────────────┐
   624→│ Layer 2: Filesystem Restrictions                            │
   625→│ - allowed_paths: [project_dir, home_dir, /tmp]             │
   626→│ - Prevents access outside designated directories            │
   627→└─────────────────────────────────────────────────────────────┘
   628→                              │
   629→┌─────────────────────────────────────────────────────────────┐
   630→│ Layer 3: Bash Command Allowlist                             │
   631→│ - ALLOWED_COMMANDS whitelist in security.py                 │
   632→│ - Validates all bash commands before execution              │
   633→└─────────────────────────────────────────────────────────────┘
   634→```
   635→
   636→### Allowed Commands (`security.py`)
   637→
   638→```python
   639→ALLOWED_COMMANDS = {
   640→    # Package managers
   641→    "npm", "npx", "pip", "pip3", "cargo", "brew", "apt", "apt-get",
   642→
   643→    # Development tools
   644→    "node", "python", "python3", "git", "make", "cmake",
   645→
   646→    # File operations
   647→    "cat", "ls", "mkdir", "cp", "mv", "rm", "touch", "chmod",
   648→
   649→    # Infrastructure access (extended)
   650→    "ssh", "scp", "rsync", "curl", "wget",
   651→
   652→    # Container operations
   653→    "docker", "docker-compose",
   654→
   655→    # System operations
   656→    "systemctl", "service", "journalctl",
   657→
   658→    # Playwright
   659→    "playwright", "npx playwright",
   660→}
   661→```
   662→
   663→---
   664→
   665→## Items to Make Exceptional
   666→
   667→### 1. Multi-Model Support
   668→**Current:** Claude Sonnet only
   669→**Enhancement:** Support multiple AI models for different tasks
   670→
   671→```python
   672→class ModelRouter:
   673→    def select_model(task_type: str) -> str:
   674→        models = {
   675→            "analysis": "claude-opus-4",      # Complex reasoning
   676→            "coding": "claude-sonnet-4",      # Fast implementation
   677→            "review": "claude-haiku-3",       # Quick validation
   678→        }
   679→        return models.get(task_type, "claude-sonnet-4")
   680→```
   681→
   682→**Benefits:**
   683→- Use Opus for architectural decisions
   684→- Use Sonnet for code implementation
   685→- Use Haiku for quick validations
   686→- Optimize cost vs capability per task
   687→
   688→### 2. Intelligent Caching & Learning
   689→
   690→**Feature Learning System:**
   691→```python
   692→class FeatureLearning:
   693→    def record_implementation(feature: Feature, code: str, time: float)
   694→    def get_similar_implementations(feature: Feature) -> list[Example]
   695→    def suggest_approach(feature: Feature) -> str
   696→```
   697→
   698→**Benefits:**
   699→- Cache successful implementations
   700→- Suggest approaches from similar past features
   701→- Reduce token usage by reusing patterns
   702→- Build project-specific knowledge base
   703→
   704→### 3. Real-Time Collaboration
   705→
   706→**Live Editing Protocol:**
   707→```python
   708→class CollaborationHub:
   709→    async def broadcast_edit(file: str, change: Change)
   710→    async def request_human_review(file: str, line: int)
   711→    async def accept_human_edit(file: str, change: Change)
   712→```
   713→
   714→**Features:**
   715→- Watch mode for file changes
   716→- Human can edit while agent works
   717→- Conflict resolution with git-style markers
   718→- Pair programming mode
   719→
   720→### 4. Self-Healing & Adaptive Recovery
   721→
   722→**Automatic Recovery System:**
   723→```python
   724→class AdaptiveRecovery:
   725→    def detect_stuck_state() -> bool
   726→    def analyze_failure_pattern(logs: list[str]) -> FailureType
   727→    def generate_recovery_strategy() -> Strategy
   728→    def apply_recovery() -> bool
   729→```
   730→
   731→**Capabilities:**
   732→- Detect infinite loops or stuck states
   733→- Analyze error patterns across sessions
   734→- Auto-generate workarounds
   735→- Learn from past failures
   736→
   737→### 5. Comprehensive Test Generation
   738→
   739→**AI-Driven Testing:**
   740→```python
   741→class TestGenerator:
   742→    def generate_unit_tests(code: str) -> str
   743→    def generate_integration_tests(features: list) -> str
   744→    def generate_edge_cases(function: str) -> list[TestCase]
   745→    def generate_property_tests(type_signature: str) -> str
   746→```
   747→
   748→**Benefits:**
   749→- Auto-generate tests during implementation
   750→- Edge case discovery via AI reasoning
   751→- Property-based test generation
   752→- Mutation testing integration
   753→
   754→### 6. Visual Progress Dashboard
   755→
   756→**Enhanced Visualization:**
   757→- Dependency graph visualization (D3.js)
   758→- Real-time code diff viewer
   759→- Agent thought process timeline
   760→- Token usage analytics
   761→- Cost tracking per feature
   762→
   763→### 7. Git Integration
   764→
   765→**Smart Version Control:**
   766→```python
   767→class GitIntegration:
   768→    def create_feature_branch(feature: Feature) -> str
   769→    def commit_with_context(files: list, feature: Feature) -> str
   770→    def generate_pr_description(feature: Feature) -> str
   771→    def handle_merge_conflicts(conflicts: list) -> Resolution
   772→```
   773→
   774→**Features:**
   775→- Auto-create branches per feature
   776→- Meaningful commit messages from context
   777→- Auto-generate PR descriptions
   778→- AI-assisted conflict resolution
   779→
   780→### 8. Plugin Architecture
   781→
   782→**Extensibility System:**
   783→```python
   784→class PluginManager:
   785→    def register_hook(event: str, handler: Callable)
   786→    def register_tool(name: str, tool: MCPTool)
   787→    def register_validator(phase: str, validator: Callable)
   788→```
   789→
   790→**Plugin Types:**
   791→- Pre/post implementation hooks
   792→- Custom MCP tools
   793→- Additional validators
   794→- Custom reporters
   795→
   796→### 9. Cost Optimization
   797→
   798→**Token Budget Management:**
   799→```python
   800→class BudgetManager:
   801→    def set_project_budget(project: str, max_tokens: int)
   802→    def track_usage(project: str, tokens: int)
   803→    def get_cost_estimate(feature: Feature) -> float
   804→    def suggest_optimizations() -> list[Suggestion]
   805→```
   806→
   807→**Features:**
   808→- Per-project token budgets
   809→- Cost estimation before starting
   810→- Automatic prompt optimization
   811→- Usage analytics and trends
   812→
   813→### 10. Enterprise Features
   814→
   815→**Production Readiness:**
   816→- SSO/SAML authentication
   817→- Role-based access control
   818→- Audit logging
   819→- API rate limiting
   820→- Multi-tenant support
   821→- Compliance reporting (SOC2, GDPR)
   822→
   823→---
   824→
   825→## Quick Start
   826→
   827→```bash
   828→# 1. Install dependencies
   829→python -m venv venv
   830→venv\Scripts\activate  # Windows
   831→pip install -r requirements.txt
   832→
   833→# 2. Install UI dependencies
   834→cd ui && npm install && npm run build && cd ..
   835→
   836→# 3. Start the server
   837→start_ui.bat  # Windows
   838→./start_ui.sh # macOS/Linux
   839→
   840→# 4. Open browser to http://localhost:8000
   841→```
   842→
   843→---
   844→
   845→## Contributing
   846→
   847→1. Fork the repository
   848→2. Create a feature branch
   849→3. Make changes with tests
   850→4. Submit a pull request
   851→
   852→---
   853→
   854→*Last Updated: 2026-01-11*
   855→*Version: 2.0.0*
   856→

<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>

# 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*


Excellent! Now I have a complete picture. This is a sophisticated autonomous coding agent system - very impressive architecture!

Let me summarize what I understand about **AutoCoder++**:

---

**What you're building:** A Claude SDK-based autonomous coding system that:
1. **Initializer Agent** - Analyzes app specs and creates testable features in a SQLite database
2. **Coding Agent** - Systematically implements each feature with verification
3. **React UI** - Project management dashboard with Kanban board, real-time progress, agent controls
4. **Parallel Execution** - Smart orchestration for running multiple agents on non-conflicting features
5. **MCP Tools** - Feature management via Model Context Protocol

**Tech Stack:**
- Backend: Python 3.11+, FastAPI, SQLAlchemy, SQLite
- Frontend: React 18, TypeScript, TanStack Query, Tailwind CSS v4, Radix UI
- AI: Claude Agent SDK, Anthropic API
- Testing: Playwright MCP
- Real-time: WebSocket

---

Now, before I generate the spec, let me ask:

**How involved do you want to be in technical decisions?**

1. **Quick Mode (Recommended)** - Since you already have a detailed architecture, I'll translate it directly into the spec format
2. **Detailed Mode** - You want to review/modify specific aspects (database schema, API endpoints, feature priorities, etc.)

Also, I noticed the architecture doc includes a **"Items to Make Exceptional"** section with 10 enhancement areas.

**Which of these do you want included in the initial build?**

1. **Core system only** - Just the base two-agent pattern, UI, and parallel execution
2. **Core + select enhancements** - I'll ask which enhancements to include
3. **Everything** - Include all 10 enhancement areas in the spec


Additional considerations: 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


Perfect! You want the **full vision** - the core system plus all 10 enhancement areas. This is going to be a comprehensive, enterprise-grade autonomous coding platform.

Let me make sure I have the complete picture before generating the spec:

---

**Core System (from ARCHITECTURE.md):**
- Two-agent pattern (Initializer → Coding)
- React UI with Kanban board, agent controls, real-time updates
- FastAPI backend with 74+ API routes
- SQLite databases (features.db, registry.db)
- MCP tools for feature management
- Parallel agent execution with smart orchestration
- Security model (filesystem restrictions, command allowlist)

**All 10 Enhancements:**
1. Multi-Model Support (Opus/Sonnet/Haiku routing)
2. Intelligent Caching & Learning
3. Real-Time Collaboration
4. Self-Healing Recovery
5. AI-Driven Test Generation
6. Visual Progress Dashboard
7. Git Integration
8. Plugin Architecture
9. Cost Optimization
10. Enterprise Features (SSO, RBAC, audit, multi-tenant)

---

**A few clarifying questions:**

1. **Priority of enhancements** - Should I prioritize these in a specific order for implementation phases, or build everything in parallel where possible?

2. **Enterprise Features scope** - For multi-tenant support, is this:
   - **Personal multi-tenant** (you managing multiple isolated projects)
   - **Team multi-tenant** (multiple users with their own projects/permissions)
   - **Full SaaS multi-tenant** (organizations with billing, quotas, etc.)

3. **Authentication** - For SSO/RBAC, what's the primary auth method you want?
   - Local accounts (email/password)
   - OAuth (GitHub, Google, etc.)
   - Enterprise SSO (SAML/OIDC)
   - All of the above

4. **Anything to ADD or REMOVE** from what's in the architecture doc?

Once you confirm, I'll derive the feature count and generate the spec files!


I'll trust your judgement for all queations for now


Excellent! I appreciate the trust. Let me make the calls:

---

**My decisions:**

1. **Implementation Priority Order:**
   - **Phase 1:** Core system (two-agent pattern, UI, MCP tools, basic parallel execution)
   - **Phase 2:** Git Integration + Cost Optimization (essential for real-world use)
   - **Phase 3:** Multi-Model Support + Intelligent Caching (performance & efficiency)
   - **Phase 4:** Self-Healing Recovery + AI-Driven Test Generation (reliability)
   - **Phase 5:** Visual Progress Dashboard + Real-Time Collaboration (UX polish)
   - **Phase 6:** Plugin Architecture (extensibility)
   - **Phase 7:** Enterprise Features (SSO, RBAC, audit, multi-tenant)

2. **Enterprise Features:** Team multi-tenant (multiple users with their own projects/permissions) - practical for growing beyond personal use without over-engineering for full SaaS.

3. **Authentication:** All of the above - local accounts as default, OAuth for convenience (GitHub primarily since this is a dev tool), and SSO hooks for future enterprise needs.

---

**Feature Count Derivation:**

Based on the architecture and enhancements, here's my breakdown:

| Category | Features |
|----------|----------|
| **Core Agent System** | ~25 (agent lifecycle, session management, prompt loading, MCP integration) |
| **Feature Management** | ~20 (CRUD, priorities, dependencies, status tracking, bulk operations) |
| **React UI - Layout & Navigation** | ~15 (project selector, routing, responsive layout, theming) |
| **React UI - Kanban Board** | ~20 (columns, drag-drop, cards, filtering, sorting) |
| **React UI - Agent Controls** | ~15 (start/stop/pause/resume, status badges, YOLO toggle) |
| **Real-Time & WebSocket** | ~12 (connections, updates, reconnection, notifications) |
| **Parallel Execution** | ~18 (orchestration, file locks, conflict detection, result merging) |
| **Git Integration** | ~15 (branches, commits, PR generation, conflict resolution) |
| **Multi-Model Support** | ~10 (model routing, task classification, fallbacks) |
| **Intelligent Caching** | ~12 (implementation caching, similarity matching, suggestions) |
| **Cost Optimization** | ~12 (budgets, tracking, analytics, optimization suggestions) |
| **Self-Healing Recovery** | ~10 (stuck detection, failure analysis, recovery strategies) |
| **AI Test Generation** | ~12 (unit, integration, edge cases, property tests) |
| **Visual Dashboard** | ~18 (dependency graphs, diff viewer, token analytics, timelines) |
| **Real-Time Collaboration** | ~12 (watch mode, human edits, conflict markers) |
| **Plugin Architecture** | ~15 (hooks, tool registration, validators, lifecycle) |
| **Enterprise - Auth** | ~20 (local auth, OAuth, SSO, sessions, password management) |
| **Enterprise - RBAC** | ~15 (roles, permissions, protected routes, access control) |
| **Enterprise - Multi-Tenant** | ~12 (user isolation, project ownership, team management) |
| **Enterprise - Audit & Compliance** | ~10 (logging, reports, data export) |
| **API Endpoints** | ~25 (all REST routes, validation, error handling) |
| **Security** | ~12 (command allowlist, path restrictions, input validation) |

**Total: ~325 features**

---

This is a large, ambitious project. Does this breakdown look right to you, or should I adjust the scope?

Once you approve, I'll generate:
- `prompts/app_spec.txt` (full XML specification)
- `prompts/initializer_prompt.md` (updated with 325 feature count)
- `prompts/.spec_status.json` (completion signal)


go