     1→"""
     2→Prompt Loading Utilities
     3→========================
     4→
     5→Functions for loading prompt templates with project-specific support.
     6→
     7→Fallback chain:
     8→1. Project-specific: {project_dir}/prompts/{name}.md
     9→2. Base template: .claude/templates/{name}.template.md
    10→
    11→Context injection:
    12→- Infrastructure context from ResourceManager (servers, services)
    13→- Credential context from CredentialResolver (with redacted secrets)
    14→"""
    15→
    16→import shutil
    17→from pathlib import Path
    18→from typing import TYPE_CHECKING
    19→
    20→if TYPE_CHECKING:
    21→    from server.services.resource_manager import ResourceManager
    22→    from server.services.credential_resolver import CredentialResolver
    23→
    24→# Base templates location (generic templates)
    25→TEMPLATES_DIR = Path(__file__).parent / ".claude" / "templates"
    26→
    27→
    28→def get_project_prompts_dir(project_dir: Path) -> Path:
    29→    """Get the prompts directory for a specific project."""
    30→    return project_dir / "prompts"
    31→
    32→
    33→def load_prompt(name: str, project_dir: Path | None = None) -> str:
    34→    """
    35→    Load a prompt template with fallback chain.
    36→
    37→    Fallback order:
    38→    1. Project-specific: {project_dir}/prompts/{name}.md
    39→    2. Base template: .claude/templates/{name}.template.md
    40→
    41→    Args:
    42→        name: The prompt name (without extension), e.g., "initializer_prompt"
    43→        project_dir: Optional project directory for project-specific prompts
    44→
    45→    Returns:
    46→        The prompt content as a string
    47→
    48→    Raises:
    49→        FileNotFoundError: If prompt not found in any location
    50→    """
    51→    # 1. Try project-specific first
    52→    if project_dir:
    53→        project_prompts = get_project_prompts_dir(project_dir)
    54→        project_path = project_prompts / f"{name}.md"
    55→        if project_path.exists():
    56→            try:
    57→                return project_path.read_text(encoding="utf-8")
    58→            except (OSError, PermissionError) as e:
    59→                print(f"Warning: Could not read {project_path}: {e}")
    60→
    61→    # 2. Try base template
    62→    template_path = TEMPLATES_DIR / f"{name}.template.md"
    63→    if template_path.exists():
    64→        try:
    65→            return template_path.read_text(encoding="utf-8")
    66→        except (OSError, PermissionError) as e:
    67→            print(f"Warning: Could not read {template_path}: {e}")
    68→
    69→    raise FileNotFoundError(
    70→        f"Prompt '{name}' not found in:\n"
    71→        f"  - Project: {project_dir / 'prompts' if project_dir else 'N/A'}\n"
    72→        f"  - Templates: {TEMPLATES_DIR}"
    73→    )
    74→
    75→
    76→def get_initializer_prompt(project_dir: Path | None = None) -> str:
    77→    """Load the initializer prompt (project-specific if available)."""
    78→    return load_prompt("initializer_prompt", project_dir)
    79→
    80→
    81→def get_coding_prompt(project_dir: Path | None = None) -> str:
    82→    """Load the coding agent prompt (project-specific if available)."""
    83→    return load_prompt("coding_prompt", project_dir)
    84→
    85→
    86→def get_coding_prompt_yolo(project_dir: Path | None = None) -> str:
    87→    """Load the YOLO mode coding agent prompt (project-specific if available)."""
    88→    return load_prompt("coding_prompt_yolo", project_dir)
    89→
    90→
    91→def get_app_spec(project_dir: Path) -> str:
    92→    """
    93→    Load the app spec from the project.
    94→
    95→    Checks in order:
    96→    1. Project prompts directory: {project_dir}/prompts/app_spec.txt
    97→    2. Project root (legacy): {project_dir}/app_spec.txt
    98→
    99→    Args:
   100→        project_dir: The project directory

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

"""
Prompt Loading Utilities
========================

Functions for loading prompt templates with project-specific support.

Fallback chain:
1. Project-specific: {project_dir}/prompts/{name}.md
2. Base template: .claude/templates/{name}.template.md

Context injection:
- Infrastructure context from ResourceManager (servers, services)
- Credential context from CredentialResolver (with redacted secrets)
"""

import shutil
from pathlib import Path
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from server.services.resource_manager import ResourceManager
    from server.services.credential_resolver import CredentialResolver

# Base templates location (generic templates)
TEMPLATES_DIR = Path(__file__).parent / ".claude" / "templates"

def get_project_prompts_dir(project_dir: Path) -> Path:
    """Get the prompts directory for a specific project."""
    return project_dir / "prompts"

def load_prompt(name: str, project_dir: Path | None = None) -> str:
    """
    Load a prompt template with fallback chain.

    Fallback order:
    1. Project-specific: {project_dir}/prompts/{name}.md
    2. Base template: .claude/templates/{name}.template.md

    Args:
        name: The prompt name (without extension), e.g., "initializer_prompt"
        project_dir: Optional project directory for project-specific prompts

    Returns:
        The prompt content as a string

    Raises:
        FileNotFoundError: If prompt not found in any location
    """
    # 1. Try project-specific first
    if project_dir:
        project_prompts = get_project_prompts_dir(project_dir)
        project_path = project_prompts / f"{name}.md"
        if project_path.exists():
            try:
                return project_path.read_text(encoding="utf-8")
            except (OSError, PermissionError) as e:
                print(f"Warning: Could not read {project_path}: {e}")

    # 2. Try base template
    template_path = TEMPLATES_DIR / f"{name}.template.md"
    if template_path.exists():
        try:
            return template_path.read_text(encoding="utf-8")
        except (OSError, PermissionError) as e:
            print(f"Warning: Could not read {template_path}: {e}")

    raise FileNotFoundError(
        f"Prompt '{name}' not found in:\n"
        f"  - Project: {project_dir / 'prompts' if project_dir else 'N/A'}\n"
        f"  - Templates: {TEMPLATES_DIR}"
    )

def get_initializer_prompt(project_dir: Path | None = None) -> str:
    """Load the initializer prompt (project-specific if available)."""
    return load_prompt("initializer_prompt", project_dir)

def get_coding_prompt(project_dir: Path | None = None) -> str:
    """Load the coding agent prompt (project-specific if available)."""
    return load_prompt("coding_prompt", project_dir)

def get_coding_prompt_yolo(project_dir: Path | None = None) -> str:
    """Load the YOLO mode coding agent prompt (project-specific if available)."""
    return load_prompt("coding_prompt_yolo", project_dir)

def get_app_spec(project_dir: Path) -> str:
    """
    Load the app spec from the project.

    Checks in order:
    1. Project prompts directory: {project_dir}/prompts/app_spec.txt
    2. Project root (legacy): {project_dir}/app_spec.txt

    Args:
        project_dir: The project directory


     1→"""
     2→Project Registry Module
     3→=======================
     4→
     5→Cross-platform project registry for storing project name to path mappings.
     6→Uses SQLite database stored at ~/.autocoder/registry.db.
     7→"""
     8→
     9→import logging
    10→import os
    11→import re
    12→from contextlib import contextmanager
    13→from datetime import datetime
    14→from pathlib import Path
    15→from typing import Any
    16→
    17→from sqlalchemy import Column, DateTime, Integer, String, Text, ForeignKey, create_engine
    18→from sqlalchemy.ext.declarative import declarative_base
    19→from sqlalchemy.orm import sessionmaker
    20→
    21→# Module logger
    22→logger = logging.getLogger(__name__)
    23→
    24→
    25→# =============================================================================
    26→# Exceptions
    27→# =============================================================================
    28→
    29→class RegistryError(Exception):
    30→    """Base registry exception."""
    31→    pass
    32→
    33→
    34→class RegistryNotFound(RegistryError):
    35→    """Registry file doesn't exist."""
    36→    pass
    37→
    38→
    39→class RegistryCorrupted(RegistryError):
    40→    """Registry database is corrupted."""
    41→    pass
    42→
    43→
    44→class RegistryPermissionDenied(RegistryError):
    45→    """Can't read/write registry file."""
    46→    pass
    47→
    48→
    49→# =============================================================================
    50→# SQLAlchemy Model
    51→# =============================================================================
    52→
    53→Base = declarative_base()
    54→
    55→
    56→class Project(Base):
    57→    """SQLAlchemy model for registered projects."""
    58→    __tablename__ = "projects"
    59→
    60→    name = Column(String(50), primary_key=True, index=True)
    61→    path = Column(String, nullable=False)  # POSIX format for cross-platform
    62→    created_at = Column(DateTime, nullable=False)
    63→
    64→
    65→class ReferenceFolder(Base):
    66→    """SQLAlchemy model for reference folders linked to projects."""
    67→    __tablename__ = "reference_folders"
    68→
    69→    id = Column(Integer, primary_key=True, autoincrement=True)
    70→    project_name = Column(String(50), ForeignKey("projects.name", ondelete="CASCADE"), nullable=False, index=True)
    71→    path = Column(String, nullable=False)  # POSIX format
    72→    alias = Column(String(100), nullable=True)  # Optional friendly name
    73→    description = Column(Text, nullable=True)  # What this reference is for
    74→    created_at = Column(DateTime, nullable=False)
    75→
    76→
    77→# =============================================================================
    78→# Database Connection
    79→# =============================================================================
    80→

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

"""
Project Registry Module
=======================

Cross-platform project registry for storing project name to path mappings.
Uses SQLite database stored at ~/.autocoder/registry.db.
"""

import logging
import os
import re
from contextlib import contextmanager
from datetime import datetime
from pathlib import Path
from typing import Any

from sqlalchemy import Column, DateTime, Integer, String, Text, ForeignKey, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# Module logger
logger = logging.getLogger(__name__)

# =============================================================================
# Exceptions
# =============================================================================

class RegistryError(Exception):
    """Base registry exception."""
    pass

class RegistryNotFound(RegistryError):
    """Registry file doesn't exist."""
    pass

class RegistryCorrupted(RegistryError):
    """Registry database is corrupted."""
    pass

class RegistryPermissionDenied(RegistryError):
    """Can't read/write registry file."""
    pass

# =============================================================================
# SQLAlchemy Model
# =============================================================================

Base = declarative_base()

class Project(Base):
    """SQLAlchemy model for registered projects."""
    __tablename__ = "projects"

    name = Column(String(50), primary_key=True, index=True)
    path = Column(String, nullable=False)  # POSIX format for cross-platform
    created_at = Column(DateTime, nullable=False)

class ReferenceFolder(Base):
    """SQLAlchemy model for reference folders linked to projects."""
    __tablename__ = "reference_folders"

    id = Column(Integer, primary_key=True, autoincrement=True)
    project_name = Column(String(50), ForeignKey("projects.name", ondelete="CASCADE"), nullable=False, index=True)
    path = Column(String, nullable=False)  # POSIX format
    alias = Column(String(100), nullable=True)  # Optional friendly name
    description = Column(Text, nullable=True)  # What this reference is for
    created_at = Column(DateTime, nullable=False)

# =============================================================================
# Database Connection
# =============================================================================


     1→"""
     2→Pydantic Schemas
     3→================
     4→
     5→Request/Response models for the API endpoints.
     6→"""
     7→
     8→import base64
     9→from datetime import datetime
    10→from typing import Literal
    11→
    12→from pydantic import BaseModel, Field, field_validator
    13→
    14→# ============================================================================
    15→# Project Schemas
    16→# ============================================================================
    17→
    18→class ProjectCreate(BaseModel):
    19→    """Request schema for creating a new project."""
    20→    name: str = Field(..., min_length=1, max_length=50, pattern=r'^[a-zA-Z0-9_-]+$')
    21→    path: str = Field(..., min_length=1, description="Absolute path to project directory")
    22→    spec_method: Literal["claude", "manual"] = "claude"
    23→
    24→
    25→class ProjectStats(BaseModel):
    26→    """Project statistics."""
    27→    passing: int = 0
    28→    in_progress: int = 0
    29→    total: int = 0
    30→    percentage: float = 0.0
    31→
    32→
    33→class ProjectSummary(BaseModel):
    34→    """Summary of a project for list view."""
    35→    name: str
    36→    path: str
    37→    has_spec: bool
    38→    stats: ProjectStats
    39→
    40→
    41→class ProjectDetail(BaseModel):
    42→    """Detailed project information."""
    43→    name: str
    44→    path: str
    45→    has_spec: bool
    46→    stats: ProjectStats
    47→    prompts_dir: str
    48→
    49→
    50→class ProjectPrompts(BaseModel):
    51→    """Project prompt files content."""
    52→    app_spec: str = ""
    53→    initializer_prompt: str = ""
    54→    coding_prompt: str = ""
    55→
    56→
    57→class ProjectPromptsUpdate(BaseModel):
    58→    """Request schema for updating project prompts."""
    59→    app_spec: str | None = None
    60→    initializer_prompt: str | None = None
    61→    coding_prompt: str | None = None
    62→
    63→
    64→class ProjectImport(BaseModel):
    65→    """Request schema for importing an existing project."""
    66→    name: str = Field(..., min_length=1, max_length=50, pattern=r'^[a-zA-Z0-9_-]+$')
    67→    path: str = Field(..., min_length=1, description="Absolute path to existing project")
    68→
    69→
    70→class CodebaseAnalysis(BaseModel):
    71→    """Analysis of an existing codebase."""
    72→    total_files: int = 0
    73→    file_types: dict[str, int] = {}
    74→    detected_stack: dict[str, str] = {}
    75→    has_claude_md: bool = False
    76→    claude_md_content: str | None = None
    77→    has_readme: bool = False
    78→    readme_content: str | None = None
    79→    directories: list[str] = []
    80→    entry_points: list[str] = []
    81→    project_name: str | None = None
    82→
    83→
    84→class ProjectImportResponse(BaseModel):
    85→    """Response for project import."""
    86→    project: ProjectSummary
    87→    analysis: CodebaseAnalysis
    88→    is_import: bool = True
    89→
    90→
    91→# ============================================================================
    92→# Feature Schemas
    93→# ============================================================================
    94→
    95→class FeatureBase(BaseModel):
    96→    """Base feature attributes."""
    97→    category: str
    98→    name: str
    99→    description: str
   100→    steps: list[str]

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

"""
Pydantic Schemas
================

Request/Response models for the API endpoints.
"""

import base64
from datetime import datetime
from typing import Literal

from pydantic import BaseModel, Field, field_validator

# ============================================================================
# Project Schemas
# ============================================================================

class ProjectCreate(BaseModel):
    """Request schema for creating a new project."""
    name: str = Field(..., min_length=1, max_length=50, pattern=r'^[a-zA-Z0-9_-]+$')
    path: str = Field(..., min_length=1, description="Absolute path to project directory")
    spec_method: Literal["claude", "manual"] = "claude"

class ProjectStats(BaseModel):
    """Project statistics."""
    passing: int = 0
    in_progress: int = 0
    total: int = 0
    percentage: float = 0.0

class ProjectSummary(BaseModel):
    """Summary of a project for list view."""
    name: str
    path: str
    has_spec: bool
    stats: ProjectStats

class ProjectDetail(BaseModel):
    """Detailed project information."""
    name: str
    path: str
    has_spec: bool
    stats: ProjectStats
    prompts_dir: str

class ProjectPrompts(BaseModel):
    """Project prompt files content."""
    app_spec: str = ""
    initializer_prompt: str = ""
    coding_prompt: str = ""

class ProjectPromptsUpdate(BaseModel):
    """Request schema for updating project prompts."""
    app_spec: str | None = None
    initializer_prompt: str | None = None
    coding_prompt: str | None = None

class ProjectImport(BaseModel):
    """Request schema for importing an existing project."""
    name: str = Field(..., min_length=1, max_length=50, pattern=r'^[a-zA-Z0-9_-]+$')
    path: str = Field(..., min_length=1, description="Absolute path to existing project")

class CodebaseAnalysis(BaseModel):
    """Analysis of an existing codebase."""
    total_files: int = 0
    file_types: dict[str, int] = {}
    detected_stack: dict[str, str] = {}
    has_claude_md: bool = False
    claude_md_content: str | None = None
    has_readme: bool = False
    readme_content: str | None = None
    directories: list[str] = []
    entry_points: list[str] = []
    project_name: str | None = None

class ProjectImportResponse(BaseModel):
    """Response for project import."""
    project: ProjectSummary
    analysis: CodebaseAnalysis
    is_import: bool = True

# ============================================================================
# Feature Schemas
# ============================================================================

class FeatureBase(BaseModel):
    """Base feature attributes."""
    category: str
    name: str
    description: str
    steps: list[str]


Let me check one more set of files - the package.json and a couple key service files:


     1→{
     2→  "name": "autocoder",
     3→  "private": true,
     4→  "version": "1.0.0",
     5→  "type": "module",
     6→  "scripts": {
     7→    "dev": "vite",
     8→    "build": "tsc -b && vite build",
     9→    "lint": "eslint .",
    10→    "preview": "vite preview"
    11→  },
    12→  "dependencies": {
    13→    "@radix-ui/react-dialog": "^1.1.2",
    14→    "@radix-ui/react-dropdown-menu": "^2.1.2",
    15→    "@radix-ui/react-tooltip": "^1.1.3",
    16→    "@tanstack/react-query": "^5.60.0",
    17→    "canvas-confetti": "^1.9.4",
    18→    "clsx": "^2.1.1",
    19→    "lucide-react": "^0.460.0",
    20→    "react": "^18.3.1",
    21→    "react-dom": "^18.3.1",
    22→    "react-markdown": "^10.1.0"
    23→  },
    24→  "devDependencies": {
    25→    "@eslint/js": "^9.13.0",
    26→    "@tailwindcss/vite": "^4.0.0-beta.4",
    27→    "@types/canvas-confetti": "^1.9.0",
    28→    "@types/react": "^18.3.12",
    29→    "@types/react-dom": "^18.3.1",
    30→    "@vitejs/plugin-react": "^4.3.3",
    31→    "eslint": "^9.13.0",
    32→    "eslint-plugin-react-hooks": "^5.0.0",
    33→    "eslint-plugin-react-refresh": "^0.4.14",
    34→    "globals": "^15.11.0",
    35→    "tailwindcss": "^4.0.0-beta.4",
    36→    "typescript": "~5.6.2",
    37→    "typescript-eslint": "^8.11.0",
    38→    "vite": "^5.4.10"
    39→  }
    40→}
    41→

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


     1→"""
     2→Agent Process Manager
     3→=====================
     4→
     5→Manages the lifecycle of agent subprocesses per project.
     6→Provides start/stop/pause/resume functionality with cross-platform support.
     7→"""
     8→
     9→import asyncio
    10→import logging
    11→import re
    12→import subprocess
    13→import sys
    14→import threading
    15→from datetime import datetime
    16→from pathlib import Path
    17→from typing import Awaitable, Callable, Literal, Set
    18→
    19→import psutil
    20→
    21→logger = logging.getLogger(__name__)
    22→
    23→# Patterns for sensitive data that should be redacted from output
    24→SENSITIVE_PATTERNS = [
    25→    r'sk-[a-zA-Z0-9]{20,}',  # Anthropic API keys
    26→    r'ANTHROPIC_API_KEY=[^\s]+',
    27→    r'api[_-]?key[=:][^\s]+',
    28→    r'token[=:][^\s]+',
    29→    r'password[=:][^\s]+',
    30→    r'secret[=:][^\s]+',
    31→    r'ghp_[a-zA-Z0-9]{36,}',  # GitHub personal access tokens
    32→    r'gho_[a-zA-Z0-9]{36,}',  # GitHub OAuth tokens
    33→    r'ghs_[a-zA-Z0-9]{36,}',  # GitHub server tokens
    34→    r'ghr_[a-zA-Z0-9]{36,}',  # GitHub refresh tokens
    35→    r'aws[_-]?access[_-]?key[=:][^\s]+',  # AWS keys
    36→    r'aws[_-]?secret[=:][^\s]+',
    37→]
    38→
    39→
    40→def sanitize_output(line: str) -> str:
    41→    """Remove sensitive information from output lines."""
    42→    for pattern in SENSITIVE_PATTERNS:
    43→        line = re.sub(pattern, '[REDACTED]', line, flags=re.IGNORECASE)
    44→    return line
    45→
    46→
    47→class AgentProcessManager:
    48→    """
    49→    Manages agent subprocess lifecycle for a single project.
    50→
    51→    Provides start/stop/pause/resume with cross-platform support via psutil.
    52→    Supports multiple output callbacks for WebSocket clients.
    53→    """
    54→
    55→    def __init__(
    56→        self,
    57→        project_name: str,
    58→        project_dir: Path,
    59→        root_dir: Path,
    60→    ):
    61→        """
    62→        Initialize the process manager.
    63→
    64→        Args:
    65→            project_name: Name of the project
    66→            project_dir: Absolute path to the project directory
    67→            root_dir: Root directory of the autonomous-coding-ui project
    68→        """
    69→        self.project_name = project_name
    70→        self.project_dir = project_dir
    71→        self.root_dir = root_dir
    72→        self.process: subprocess.Popen | None = None
    73→        self._status: Literal["stopped", "running", "paused", "crashed"] = "stopped"
    74→        self.started_at: datetime | None = None
    75→        self._output_task: asyncio.Task | None = None
    76→        self.yolo_mode: bool = False  # YOLO mode for rapid prototyping
    77→
    78→        # Support multiple callbacks (for multiple WebSocket clients)
    79→        self._output_callbacks: Set[Callable[[str], Awaitable[None]]] = set()
    80→        self._status_callbacks: Set[Callable[[str], Awaitable[None]]] = set()

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

"""
Agent Process Manager
=====================

Manages the lifecycle of agent subprocesses per project.
Provides start/stop/pause/resume functionality with cross-platform support.
"""

import asyncio
import logging
import re
import subprocess
import sys
import threading
from datetime import datetime
from pathlib import Path
from typing import Awaitable, Callable, Literal, Set

import psutil

logger = logging.getLogger(__name__)

# Patterns for sensitive data that should be redacted from output
SENSITIVE_PATTERNS = [
    r'sk-[a-zA-Z0-9]{20,}',  # Anthropic API keys
    r'ANTHROPIC_API_KEY=[^\s]+',
    r'api[_-]?key[=:][^\s]+',
    r'token[=:][^\s]+',
    r'password[=:][^\s]+',
    r'secret[=:][^\s]+',
    r'ghp_[a-zA-Z0-9]{36,}',  # GitHub personal access tokens
    r'gho_[a-zA-Z0-9]{36,}',  # GitHub OAuth tokens
    r'ghs_[a-zA-Z0-9]{36,}',  # GitHub server tokens
    r'ghr_[a-zA-Z0-9]{36,}',  # GitHub refresh tokens
    r'aws[_-]?access[_-]?key[=:][^\s]+',  # AWS keys
    r'aws[_-]?secret[=:][^\s]+',
]

def sanitize_output(line: str) -> str:
    """Remove sensitive information from output lines."""
    for pattern in SENSITIVE_PATTERNS:
        line = re.sub(pattern, '[REDACTED]', line, flags=re.IGNORECASE)
    return line

class AgentProcessManager:
    """
    Manages agent subprocess lifecycle for a single project.

    Provides start/stop/pause/resume with cross-platform support via psutil.
    Supports multiple output callbacks for WebSocket clients.
    """

    def __init__(
        self,
        project_name: str,
        project_dir: Path,
        root_dir: Path,
    ):
        """
        Initialize the process manager.

        Args:
            project_name: Name of the project
            project_dir: Absolute path to the project directory
            root_dir: Root directory of the autonomous-coding-ui project
        """
        self.project_name = project_name
        self.project_dir = project_dir
        self.root_dir = root_dir
        self.process: subprocess.Popen | None = None
        self._status: Literal["stopped", "running", "paused", "crashed"] = "stopped"
        self.started_at: datetime | None = None
        self._output_task: asyncio.Task | None = None
        self.yolo_mode: bool = False  # YOLO mode for rapid prototyping

        # Support multiple callbacks (for multiple WebSocket clients)
        self._output_callbacks: Set[Callable[[str], Awaitable[None]]] = set()
        self._status_callbacks: Set[Callable[[str], Awaitable[None]]] = set()


Perfect! Now I have comprehensive information about the Autocoder-2.0 project. Let me create a thorough documentation report.

## Autocoder-2.0 Project - Complete Documentation

### 1. PROJECT OVERVIEW

**Autocoder-2.0** is an autonomous AI coding agent system that leverages Claude's Agent SDK to build complete applications across multiple sessions. It uses a two-agent pattern:
- **Initializer Agent** (Session 1): Reads app specifications and creates features in a SQLite database
- **Coding Agent** (Subsequent Sessions): Implements features one by one, marking them passing

The system includes a React-based web UI for real-time monitoring, REST API backend, and advanced features like YOLO mode for rapid prototyping.

---

### 2. COMPLETE PROJECT STRUCTURE

```
C:/Users/MikeSwanson/claude-projects/Autocode-remix/Autocoder-2.0/
├── .claude/                          # Claude Code integration
│   ├── commands/
│   │   ├── checkpoint.md
│   │   ├── create-spec.md            # /create-spec slash command
│   │   └── import-spec.md
│   ├── skills/
│   │   └── frontend-design/SKILL.md  # UI design skill
│   ├── settings.json
│   └── templates/                    # Prompt templates
│       ├── app_spec.template.txt
│       ├── coding_prompt.template.md
│       ├── coding_prompt_yolo.template.md
│       └── initializer_prompt.template.md
├── api/
│   ├── __init__.py
│   ├── database.py                   # SQLAlchemy models (Feature)
│   └── migration.py
├── mcp_server/
│   ├── __init__.py
│   └── feature_mcp.py                # MCP server for feature tools
├── server/
│   ├── __init__.py
│   ├── main.py                       # FastAPI application entry
│   ├── websocket.py                  # WebSocket handler
│   ├── schemas.py                    # Pydantic models
│   ├── routers/
│   │   ├── __init__.py
│   │   ├── agent.py                  # Agent control endpoints
│   │   ├── assistant_chat.py         # Chat assistant endpoints
│   │   ├── features.py               # Feature CRUD endpoints
│   │   ├── filesystem.py             # Filesystem browser API
│   │   ├── git.py                    # Git operations API
│   │   ├── projects.py               # Project management CRUD
│   │   ├── scheduler.py              # Task scheduling API
│   │   ├── spec_creation.py          # Spec creation WebSocket
│   │   └── terminal.py               # Terminal session API
│   └── services/
│       ├── __init__.py
│       ├── assistant_chat_session.py # Chat session management
│       ├── assistant_database.py     # Chat history persistence
│       ├── credential_resolver.py    # Credential management
│       ├── feature_graph.py          # Feature dependency analysis
│       ├── file_lock.py              # Distributed file locking
│       ├── git_operations.py         # Git command wrappers
│       ├── process_manager.py        # Agent subprocess lifecycle
│       ├── resource_manager.py       # Infrastructure resources
│       ├── smart_scheduler.py        # Task scheduling engine
│       ├── spec_chat_session.py      # Spec creation chat state
│       └── terminal_session.py       # Terminal session handling
├── ui/                               # React frontend
│   ├── src/
│   │   ├── App.tsx                   # Main app component
│   │   ├── main.tsx                  # React entry point
│   │   ├── vite-env.d.ts
│   │   ├── components/               # React components
│   │   │   ├── AddFeatureForm.tsx
│   │   │   ├── AgentControl.tsx
│   │   │   ├── AgentThought.tsx
│   │   │   ├── AssistantChat.tsx
│   │   │   ├── AssistantFAB.tsx
│   │   │   ├── AssistantPanel.tsx
│   │   │   ├── ChatMessage.tsx
│   │   │   ├── DebugLogViewer.tsx
│   │   │   ├── DeleteProjectModal.tsx
│   │   │   ├── FeatureCard.tsx
│   │   │   ├── FeatureModal.tsx
│   │   │   ├── FolderBrowser.tsx
│   │   │   ├── GitPanel.tsx
│   │   │   ├── KanbanBoard.tsx
│   │   │   ├── KanbanColumn.tsx
│   │   │   ├── NewProjectModal.tsx
│   │   │   ├── ProgressDashboard.tsx
│   │   │   ├── ProjectSelector.tsx
│   │   │   ├── QuestionOptions.tsx
│   │   │   ├── ReferenceFoldersPanel.tsx
│   │   │   ├── SetupWizard.tsx
│   │   │   ├── SpecCreationChat.tsx
│   │   │   ├── TerminalChat.tsx
│   │   │   └── TypingIndicator.tsx
│   │   ├── hooks/
│   │   │   ├── useFeatureSound.ts
│   │   │   ├── useCelebration.ts
│   │   │   ├── useProjects.ts         # React Query data fetching
│   │   │   └── useWebSocket.ts        # WebSocket real-time updates
│   │   ├── lib/
│   │   │   ├── api.ts                 # REST API client
│   │   │   └── types.ts               # TypeScript type definitions
│   │   ├── styles/
│   │   │   └── globals.css            # Tailwind CSS v4 theme
│   │   └── ...
│   ├── dist/                          # Pre-built production UI
│   ├── public/                        # Static assets
│   ├── package.json
│   ├── vite.config.ts
│   ├── tsconfig.json
│   └── ...
├── agent.py                           # Agent session logic
├── autonomous_agent_demo.py           # CLI entry point for agent
├── client.py                          # Claude SDK client factory
├── config.py                          # Configuration management
├── progress.py                        # Progress tracking utilities
├── prompts.py                         # Prompt loading with fallback
├── registry.py                        # Cross-platform project registry
├── security.py                        # Bash command allowlist
├── smart_orchestrator.py              # Multi-agent orchestration
├── parallel_agent.py                  # Parallel agent implementation
├── start.py                           # CLI menu launcher
├── start_ui.py                        # Web UI server launcher
├── start.bat / start.sh               # Entry point scripts
├── start_ui.bat / start_ui.sh         # Web UI entry scripts
├── requirements.txt                   # Python dependencies
├── CLAUDE.md                          # Claude Code integration guide
├── README.md                          # Project documentation
├── LICENSE.md                         # AGPL v3 license
└── venv/                              # Python virtual environment
```

---

### 3. PYTHON MODULES AND THEIR PURPOSES

#### **Core Entry Points**
- **`autonomous_agent_demo.py`** - Main CLI entry point for running the agent. Supports project directory (absolute or registered name), model selection, max iterations, and YOLO mode flag.
- **`start.py`** - Interactive CLI menu for project creation/selection and agent startup.
- **`start_ui.py`** - FastAPI server launcher that serves the React UI at http://localhost:8888.

#### **Agent Logic**
- **`agent.py`** - Core agent session loop using Claude Agent SDK. Handles:
  - Sending prompts to Claude
  - Receiving and streaming responses
  - Tool use output handling
  - Session state management
  - Auto-continuation between sessions (3-second delay)

- **`client.py`** - Claude SDK client factory that creates configured clients with:
  - Multi-layered security (sandbox, filesystem restrictions, command allowlist)
  - MCP server registration (Feature tools, Playwright tools)
  - Tool filtering for YOLO mode
  - Model selection

- **`security.py`** - Bash command validation with allowlist approach. Defines `ALLOWED_COMMANDS` including:
  - File operations: ls, cat, cp, mkdir, rm, chmod, etc.
  - Development tools: npm, python, cargo, docker
  - Version control: git, gh
  - Network: curl, wget, ping, ssh, scp
  - Process management: ps, lsof, kill, pkill

#### **Configuration & Persistence**
- **`config.py`** - Centralized configuration management. Loads from `~/.autocoder/config.json` with dataclass-based structure for:
  - Git agent config (auto-commit, auto-push, commit style)
  - Parallel config (max agents, lock timeouts)
  - Security config (sandbox, allowed hosts)
  - Paths config (credentials, resources, logs)
  - UI config (theme, sounds, celebrations)

- **`registry.py`** - Cross-platform project registry using SQLite at `~/.autocoder/registry.db`. Stores:
  - Project name → absolute path mappings (POSIX format for cross-platform compatibility)
  - Reference folders linked to projects (for codebase references)
  - Created timestamps for audit trails
  - Uses SQLAlchemy ORM for database abstraction

#### **Utilities**
- **`prompts.py`** - Prompt template loading with fallback chain:
  1. Project-specific: `{project_dir}/prompts/{name}.md`
  2. Base template: `.claude/templates/{name}.template.md`
  - Supports prompt context injection (infrastructure, credentials)

- **`progress.py`** - Progress tracking and reporting:
  - Database queries for feature statistics
  - N8N webhook notifications on test progress
  - Progress summary display

- **`smart_orchestrator.py`** - Multi-agent orchestration engine

- **`parallel_agent.py`** - Parallel agent implementation for concurrent feature development

#### **API & Database**
- **`api/database.py`** - SQLAlchemy ORM models:
  - `Feature` table with columns: id, priority, category, name, description, steps (JSON), passes (boolean), in_progress (boolean)
  - Cross-platform SQLite URL generation
  - Schema migration for backward compatibility

- **`api/migration.py`** - Database schema migrations

---

### 4. SERVER API ENDPOINTS (from server/routers/)

#### **Agent Router** (`server/routers/agent.py`)
- `GET /api/projects/{project_name}/agent/status` - Get agent status (running/paused/stopped/crashed)
- `POST /api/projects/{project_name}/agent/start` - Start agent (with optional YOLO mode)
- `POST /api/projects/{project_name}/agent/stop` - Stop agent
- `POST /api/projects/{project_name}/agent/pause` - Pause agent
- `POST /api/projects/{project_name}/agent/resume` - Resume paused agent

#### **Projects Router** (`server/routers/projects.py`)
- `GET /api/projects` - List all registered projects
- `POST /api/projects` - Create new project
- `GET /api/projects/{project_name}` - Get project details
- `PUT /api/projects/{project_name}` - Update project
- `DELETE /api/projects/{project_name}` - Delete project
- `GET /api/projects/{project_name}/prompts` - Get project prompts (app_spec, initializer, coding)
- `PUT /api/projects/{project_name}/prompts` - Update prompts
- `POST /api/projects/import` - Import existing project
- `POST /api/projects/{project_name}/analyze` - Analyze codebase

#### **Features Router** (`server/routers/features.py`)
- `GET /api/projects/{project_name}/features` - List all features (grouped by status: pending, in_progress, done)
- `POST /api/projects/{project_name}/features` - Create new feature manually
- `GET /api/projects/{project_name}/features/{feature_id}` - Get feature details
- `DELETE /api/projects/{project_name}/features/{feature_id}` - Delete feature
- `PATCH /api/projects/{project_name}/features/{feature_id}/skip` - Move feature to end of queue

#### **Spec Creation Router** (`server/routers/spec_creation.py`)
- WebSocket: `/ws/spec-creation/{conversation_id}` - Interactive spec creation chat with Claude

#### **Filesystem Router** (`server/routers/filesystem.py`)
- `GET /api/filesystem/list` - List directory contents (server-side)
- `GET /api/filesystem/exists` - Check if path exists
- `GET /api/filesystem/read` - Read file contents
- `GET /api/filesystem/tree` - Get directory tree

#### **Terminal Router** (`server/routers/terminal.py`)
- WebSocket: `/ws/terminal/{project_name}` - Interactive terminal session

#### **Git Router** (`server/routers/git.py`)
- `GET /api/projects/{project_name}/git/status` - Git status
- `GET /api/projects/{project_name}/git/log` - Git commit history
- `POST /api/projects/{project_name}/git/commit` - Create commit
- `POST /api/projects/{project_name}/git/push` - Push changes
- `GET /api/projects/{project_name}/git/branches` - List branches

#### **Scheduler Router** (`server/routers/scheduler.py`)
- Task scheduling endpoints for automated operations

#### **Assistant Chat Router** (`server/routers/assistant_chat.py`)
- WebSocket: `/ws/chat/{conversation_id}` - Multi-turn conversation with Claude Assistant

#### **WebSocket Handler** (`server/websocket.py`)
- `GET /ws/projects/{project_name}` - Real-time agent updates:
  - `progress` - Feature statistics (passing/total)
  - `agent_status` - Agent state changes
  - `log` - Agent output streaming
  - `feature_update` - Feature status changes

---

### 5. UI COMPONENTS (from ui/src/components/)

#### **Core Components**
- **`App.tsx`** - Main app wrapper with:
  - Project selection state
  - Keyboard shortcuts (Ctrl+1 through Ctrl+4 for panels)
  - WebSocket connection management
  - Feature celebration on completion

- **`ProjectSelector.tsx`** - Project selection dropdown with load states

- **`KanbanBoard.tsx`** & **`KanbanColumn.tsx`** - Kanban view of features grouped by status

#### **Agent Control**
- **`AgentControl.tsx`** - Start/stop/pause/resume buttons with YOLO mode toggle
- **`AgentThought.tsx`** - Display agent reasoning/thoughts in real-time

#### **Feature Management**
- **`FeatureCard.tsx`** - Individual feature display (name, category, status)
- **`FeatureModal.tsx`** - Detailed feature view with steps
- **`AddFeatureForm.tsx`** - Manual feature creation form

#### **Project Creation**
- **`NewProjectModal.tsx`** - Multi-step project creation wizard:
  - Step 1: Basic info (name, type)
  - Step 2: Specification method (Claude-assisted or manual)
  - Step 3: Folder selection
  - Step 4: Spec generation/entry

- **`FolderBrowser.tsx`** - Server-side filesystem browser for selecting project location

- **`SetupWizard.tsx`** - Initial setup flow

#### **Advanced Features**
- **`SpecCreationChat.tsx`** - Interactive chat with Claude for generating app specs
- **`TerminalChat.tsx`** - Terminal emulation with command execution
- **`GitPanel.tsx`** - Git operations UI (status, commit, push, branches)
- **`ReferenceFoldersPanel.tsx`** - Link and manage code reference folders
- **`AssistantChat.tsx`** & **`AssistantPanel.tsx`** - AI assistant chat sidebar

#### **Utilities & UX**
- **`ProgressDashboard.tsx`** - Feature completion statistics display
- **`DebugLogViewer.tsx`** - Expandable debug log panel
- **`ChatMessage.tsx`** - Message rendering in chat interfaces
- **`QuestionOptions.tsx`** - Multiple choice UI for spec creation
- **`TypingIndicator.tsx`** - Loading animation
- **`AssistantFAB.tsx`** - Floating action button for assistant
- **`DeleteProjectModal.tsx`** - Project deletion confirmation

#### **Styling**
- **`globals.css`** - Tailwind CSS v4 custom theme with:
  - CSS variables for colors (neo-pending: yellow, neo-progress: cyan, neo-done: green)
  - Custom animations: `animate-slide-in`, `animate-pulse-neo`, `animate-shimmer`
  - Neobrutalism design system

---

### 6. DATABASE SCHEMA (from api/database.py)

#### **Feature Table**
```
TABLE: features
├── id (Integer, PK, autoincrement)
├── priority (Integer, indexed, default=999)
├── category (String(100), required)
│   └── Examples: "functional", "style", "performance", "security"
├── name (String(255), required)
├── description (Text, required)
├── steps (JSON array, required)
│   └── Each element: implementation/test step as string
├── passes (Boolean, indexed, default=False)
│   └── Indicates feature is complete and verified
└── in_progress (Boolean, indexed, default=False)
    └── Indicates feature is currently being worked on
```

#### **Key Relationships**
- One-to-many: Project → Features
- Features are ordered by priority (ascending) within a project
- `passes=True` features are considered "done"
- `in_progress=True` prevents concurrent work on same feature

---

### 7. MCP SERVER TOOLS (from mcp_server/feature_mcp.py)

#### **Feature Management Tools**

**`feature_get_stats()`**
- Returns: JSON with `{passing, in_progress, total, percentage}`
- Use: Track overall progress

**`feature_get_next()`**
- Returns: Next highest-priority pending feature (passes=false, ordered by priority)
- Use: Determine what to work on next

**`feature_get_for_regression(limit=3)`**
- Returns: Random passing features for regression testing
- Args: limit (1-10, default 3)
- Use: Verify previously implemented features still work

**`feature_mark_passing(feature_id)`**
- Updates: Sets passes=true, clears in_progress flag
- Returns: Updated feature details
- Use: Mark feature complete after verification

**`feature_skip(feature_id)`**
- Updates: Moves feature to end of priority queue (priority = max+1)
- Returns: Skip details (id, name, old_priority, new_priority)
- Use: Defer feature due to dependencies or blockers

**`feature_mark_in_progress(feature_id)`**
- Updates: Sets in_progress=true
- Returns: Updated feature details
- Use: Claim a feature to prevent concurrent work

**`feature_clear_in_progress(feature_id)`**
- Updates: Sets in_progress=false
- Returns: Updated feature details
- Use: Unstick stuck features or abandon work

**`feature_create_bulk(features)`**
- Args: List of feature dicts {category, name, description, steps}
- Returns: {created: count}
- Use: Initializer agent creates all features from app spec

---

### 8. PROMPT TEMPLATES (from .claude/templates/)

#### **`initializer_prompt.template.md`**
- **Purpose**: First session setup
- **Key Sections**:
  - Role definition as Initializer Agent
  - Read app_spec.txt for requirements
  - Create exactly [FEATURE_COUNT] features using feature_create_bulk
  - Feature requirements: mix of functional/style, narrow/comprehensive tests
  - Mandatory test categories (20 categories required)
  - Feature generation guidelines
  - Setup project structure

#### **`coding_prompt.template.md`**
- **Purpose**: Continuation sessions for feature implementation
- **Key Sections**:
  - Get bearings: pwd, ls, read app_spec.txt, claude-progress.txt, git log
  - Start servers from init.sh
  - Regression testing: verify 1-2 core features before new work
  - Feature workflow:
    - Get next feature (feature_get_next)
    - Mark in-progress (feature_mark_in_progress)
    - Implement and test
    - Verify with Playwright/browser testing
    - Mark passing (feature_mark_passing)
  - Handle failures: fix immediately before moving to new features
  - Regression testing: periodically run feature_get_for_regression

#### **`coding_prompt_yolo.template.md`**
- **Purpose**: Rapid prototyping mode (no browser testing)
- **Key Differences**:
  - Skip Playwright tools (no browser automation)
  - Skip regression testing (feature_get_for_regression)
  - Features marked passing after lint/type-check only
  - Focus on code scaffolding speed

#### **`app_spec.template.txt`**
- **Purpose**: XML template for application specifications
- **Sections**:
  - Project metadata (name, description, tech stack)
  - Detailed requirements
  - Feature list (structured for parser)
  - Success criteria

---

### 9. CONFIGURATION OPTIONS (from config.py)

#### **GitAgentConfig**
```python
auto_commit: bool = True
auto_push: bool = False
commit_style: str = "conventional"  # "conventional", "simple", "detailed"
push_on: list[str] = ["feature_complete", "session_end"]
pull_before: list[str] = ["code_review", "feature_start"]
```

#### **ParallelConfig**
```python
enabled: bool = True
max_agents: int = 3
lock_timeout_seconds: int = 3600
```

#### **SecurityConfig**
```python
sandbox_enabled: bool = False  # Disabled for full system access
allowed_hosts: list[str] = []  # Empty = all allowed
```

#### **PathsConfig**
```python
credentials_path: str = "~/claude-projects/shared-data/credentials.md"
global_resources_path: str = "~/.autocoder/global_resources.json"
session_logs_path: str = "~/claude-projects/session-logs"
```

#### **UIConfig**
```python
theme: str = "neobrutalism"
show_agent_thoughts: bool = True
sound_enabled: bool = True
celebration_enabled: bool = True
```

#### **AutocoderConfig (Main)**
```python
version: str = "2.0.0"
default_model: str = "claude-sonnet-4-20250514"
git_agent: GitAgentConfig
parallel: ParallelConfig
security: SecurityConfig
paths: PathsConfig
ui: UIConfig
```

**Location**: `~/.autocoder/config.json` (auto-created on first run)

---

### 10. ADDITIONAL KEY SERVICES

#### **Process Manager** (`server/services/process_manager.py`)
- Manages agent subprocess lifecycle per project
- Supports start/stop/pause/resume with cross-platform psutil
- Streams subprocess output to WebSocket clients
- Output sanitization: redacts API keys, tokens, passwords
- Status tracking: stopped, running, paused, crashed
- Health checks to detect crashed processes

#### **Credential Resolver** (`server/services/credential_resolver.py`)
- Loads credentials from `shared-data/credentials.md`
- Provides redacted credentials to agents
- Supports service-specific lookups

#### **Feature Graph** (`server/services/feature_graph.py`)
- Analyzes feature dependencies
- Detects circular dependencies
- Topological sorting for optimal feature order

#### **File Lock** (`server/services/file_lock.py`)
- Distributed file locking with timeout
- Prevents concurrent agent modification
- Cross-platform support

#### **Git Operations** (`server/services/git_operations.py`)
- Wraps git commands
- Commit/push automation
- Branch management
- History tracking

#### **Resource Manager** (`server/services/resource_manager.py`)
- Infrastructure resource tracking
- Server registry (Jupiter, Saturn, pfSense, Build Server)
- Service endpoints (Gitea, NPM, GuruRMM API)

#### **Smart Scheduler** (`server/services/smart_scheduler.py`)
- Task scheduling engine
- Cron-like scheduling
- Priority-based execution

#### **Spec Chat Session** (`server/services/spec_chat_session.py`)
- Manages multi-turn conversation for spec generation
- Context preservation across turns

#### **Assistant Chat Session** (`server/services/assistant_chat_session.py`)
- Multi-turn conversation state
- History persistence to SQLite

#### **Terminal Session** (`server/services/terminal_session.py`)
- Interactive terminal emulation
- Command execution in project directory

---

### 11. TECHNOLOGY STACK

#### **Backend**
- **Python 3.x** with virtual environment
- **FastAPI** - REST API framework
- **SQLAlchemy** - ORM for database
- **SQLite** - Lightweight database
- **Claude Agent SDK** - Claude API integration
- **psutil** - Cross-platform process management
- **Pydantic** - Data validation

#### **Frontend**
- **React 18** - UI framework
- **TypeScript** - Type-safe development
- **Vite** - Build tooling
- **Tailwind CSS v4** - Utility-first styling
- **Radix UI** - Accessible components
- **TanStack Query** - Data fetching/caching
- **Lucide React** - Icon library
- **React Markdown** - Markdown rendering
- **Canvas Confetti** - Celebration animations

#### **Security**
- Defense-in-depth: OS-level sandbox + filesystem restrictions + command allowlist
- Cross-origin restrictions (localhost only)
- Sensitive data redaction in process output
- CORS middleware for localhost

---

### 12. KEY WORKFLOWS

#### **Initializer Agent Workflow (Session 1)**
1. Read `app_spec.txt`
2. Create features using `feature_create_bulk` (exact count)
3. Initialize git repository
4. Scaffold project structure
5. Create prompt files for future sessions

#### **Coding Agent Workflow (Sessions 2+)**
1. Get bearings: read spec, progress notes, git history
2. Start required servers (if not running)
3. Regression test: verify 1-2 core features
4. Loop until no features remaining:
   - `feature_get_next()` - Get next feature
   - `feature_mark_in_progress(id)` - Claim it
   - Implement feature
   - Test with browser automation (Playwright)
   - `feature_mark_passing(id)` or `feature_skip(id)`
5. Auto-continue with 3-second delay

#### **YOLO Mode Workflow**
- Skip browser testing
- Skip regression testing
- Mark features passing after lint/type-check
- Faster iteration for prototyping

#### **Project Creation Workflow (UI)**
1. Enter project name and type
2. Choose spec method: Claude-assisted or manual
3. Select project folder location
4. Generate/enter specification
5. Create project in registry
6. Initialize `features.db`

---

### 13. KEY FILES AND THEIR LOCATIONS

| Component | File Path |
|-----------|-----------|
| Agent Logic | `agent.py` |
| CLI Launcher | `start.py` |
| UI Server | `start_ui.py` |
| SDK Client | `client.py` |
| Security | `security.py` |
| Database Models | `api/database.py` |
| MCP Tools | `mcp_server/feature_mcp.py` |
| FastAPI App | `server/main.py` |
| WebSocket Handler | `server/websocket.py` |
| Agent Router | `server/routers/agent.py` |
| Features Router | `server/routers/features.py` |
| Projects Router | `server/routers/projects.py` |
| Process Manager | `server/services/process_manager.py` |
| Registry | `registry.py` |
| Config | `config.py` |
| React App | `ui/src/App.tsx` |
| Tailwind Theme | `ui/src/styles/globals.css` |
| Package.json | `ui/package.json` |
| Init Templates | `.claude/templates/` |

---

### 14. ENVIRONMENT & DEPENDENCIES

**Python Requirements** (from `requirements.txt`):
- Claude Agent SDK
- FastAPI + Uvicorn
- SQLAlchemy
- Pydantic
- psutil
- python-dotenv

**Node.js Dependencies** (from `ui/package.json`):
- React 18.3.1
- TypeScript 5.6.2
- Tailwind CSS 4.0.0
- Vite 5.4.10
- TanStack Query 5.60.0
- Radix UI components
- Lucide React icons

**Configuration Files**:
- `~/.autocoder/registry.db` - Project registry (auto-created)
- `~/.autocoder/config.json` - Configuration (auto-created)
- `.env` - Optional environment variables (N8N webhook, etc.)

---

This comprehensive documentation covers the complete Autocoder-2.0 system including all modules, endpoints, components, database schema, MCP tools, configuration options, and key workflows. The system is designed for autonomous, long-running AI-powered development with safety-first design principles and cross-platform support.