From 04b6af91918a0c92d130a793e495d562574cbdaf Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 21:16:58 +0200 Subject: [PATCH 01/27] auto-claude: subtask-1-1 - Create docs/ directory with Docsify index.html entry point MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Create docs/index.html with Docsify v4 configuration - Configure Mermaid plugin for diagram rendering - Add search plugin for documentation search - Include copy-code plugin for code block copying - Add custom styling for better readability - Update .gitignore to track docs/ directory 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- .gitignore | 2 +- docs/index.html | 87 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 docs/index.html diff --git a/.gitignore b/.gitignore index 7f53e4c59a..aad64ee4f8 100644 --- a/.gitignore +++ b/.gitignore @@ -161,5 +161,5 @@ dev/ _bmad/ _bmad-output/ .claude/ -/docs +# NOTE: /docs was previously ignored but is now tracked for project documentation OPUS_ANALYSIS_AND_IDEAS.md diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000000..9b56cc8720 --- /dev/null +++ b/docs/index.html @@ -0,0 +1,87 @@ + + + + + + Auto-Claude Documentation + + + + + +
Loading documentation...
+ + + + + + + + + + + + + From 678372c566de19b68bf501a8285e903d730504da Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 21:19:28 +0200 Subject: [PATCH 02/27] auto-claude: subtask-1-2 - Create documentation home page (README.md) with project overview MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add docs/README.md as Docsify home page - Include comprehensive project overview and tech stack - Add documentation structure navigation - Include project structure and quick reference - Add "Last updated" timestamp for automation hook compatibility 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/README.md | 133 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 docs/README.md diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000000..a6c4aaaa4c --- /dev/null +++ b/docs/README.md @@ -0,0 +1,133 @@ +# Auto-Claude Technical Documentation + +**Comprehensive technical documentation for developers working with the Auto-Claude codebase.** + +> Last updated: 2025-06-29 + +--- + +## Overview + +Auto-Claude is an autonomous multi-agent coding framework that plans, builds, and validates software. This documentation provides technical onboarding materials for developers who want to understand, contribute to, or extend the project. + +### What is Auto-Claude? + +Auto-Claude combines a **Python backend** (agent system, project analysis, context management) with a **TypeScript/React frontend** (Electron desktop application) to provide: + +- **Autonomous task execution** - Describe your goal; agents handle planning, implementation, and validation +- **Parallel agent management** - Run multiple builds simultaneously with up to 12 agent terminals +- **Isolated workspaces** - All changes happen in git worktrees, keeping your main branch safe +- **Self-validating QA** - Built-in quality assurance loop catches issues before you review +- **Cross-session memory** - Agents retain insights across sessions for smarter builds + +--- + +## Documentation Structure + +This documentation is organized in progressive complexity, from high-level overviews to detailed component specifications. + +### Getting Started + +- **[Getting Started](getting-started.md)** - Quick start guide for new developers + +### Architecture + +- **[Architecture Overview](architecture/overview.md)** - High-level system architecture +- **[Backend Architecture](architecture/backend.md)** - Python agent system architecture +- **[Frontend Architecture](architecture/frontend.md)** - Electron/React application architecture +- **[Integration](architecture/integration.md)** - Frontend-backend communication + +### Component Documentation + +- **[Backend Components](components/backend/)** - Python module documentation +- **[Frontend Components](components/frontend/)** - TypeScript/React component documentation + +### Diagrams + +- **[Use Cases](diagrams/use-cases.md)** - Use case diagrams +- **[Sequence Diagrams](diagrams/sequences.md)** - Interaction flow diagrams +- **[Class Diagrams](diagrams/classes.md)** - Type and class structure diagrams + +--- + +## Tech Stack + +| Layer | Technology | Purpose | +|-------|------------|---------| +| **Desktop App** | Electron 39.x | Cross-platform desktop container | +| **UI Framework** | React 19.x | Component-based user interface | +| **Build Tool** | Vite + electron-vite | Fast development and bundling | +| **Styling** | Tailwind CSS 4.x | Utility-first styling | +| **State Management** | Zustand 5.x | Lightweight state management | +| **Backend Runtime** | Python 3.12+ | Agent system runtime | +| **Agent Framework** | Claude Agent SDK | AI agent capabilities | +| **Memory System** | Graphiti | Cross-session context retention | + +--- + +## Project Structure + +``` +Auto-Claude/ +├── apps/ +│ ├── backend/ # Python agent system +│ │ ├── agents/ # Agent implementations +│ │ ├── analysis/ # Project analyzers +│ │ ├── cli/ # Command-line interface +│ │ ├── context/ # Context management +│ │ ├── core/ # Core services +│ │ ├── ideation/ # Feature ideation +│ │ ├── implementation_plan/ # Plan structures +│ │ └── integrations/ # External integrations +│ └── frontend/ # Electron application +│ └── src/ +│ ├── main/ # Electron main process +│ └── renderer/ # React renderer process +├── docs/ # This documentation +├── guides/ # User guides +├── scripts/ # Build utilities +└── tests/ # Test suite +``` + +--- + +## Quick Reference + +### Running the Application + +```bash +# Development mode +npm run dev + +# Build and run +npm start +``` + +### Backend CLI + +```bash +cd apps/backend + +# Create a spec interactively +python spec_runner.py --interactive + +# Run autonomous build +python run.py --spec 001 +``` + +### Useful Links + +- **Repository**: [github.com/AndyMik90/Auto-Claude](https://github.com/AndyMik90/Auto-Claude) +- **Discord Community**: [Join](https://discord.gg/KCXaPBr4Dj) +- **Contributing Guide**: [CONTRIBUTING.md](https://github.com/AndyMik90/Auto-Claude/blob/main/CONTRIBUTING.md) + +--- + +## How to Use This Documentation + +1. **New to the project?** Start with [Getting Started](getting-started.md) +2. **Understanding the architecture?** Read [Architecture Overview](architecture/overview.md) +3. **Working on a specific area?** Navigate to the relevant component documentation +4. **Looking for diagrams?** Check the [Diagrams](diagrams/use-cases.md) section + +Use the sidebar navigation to explore topics, or use the search feature to find specific content. From 5305266d539a21cb6e4e50c4464f383966d0c3fe Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 21:21:24 +0200 Subject: [PATCH 03/27] auto-claude: subtask-1-3 - Create sidebar navigation structure (_sidebar.md) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add hierarchical navigation with Architecture, Components, and Diagrams sections - Link to Getting Started, all architecture pages, backend/frontend components - Support progressive complexity browsing from overview to detailed docs 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/_sidebar.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 docs/_sidebar.md diff --git a/docs/_sidebar.md b/docs/_sidebar.md new file mode 100644 index 0000000000..7414b7530d --- /dev/null +++ b/docs/_sidebar.md @@ -0,0 +1,34 @@ + + +- [Home](/) +- [Getting Started](getting-started.md) + +--- + +- **Architecture** + - [Overview](architecture/overview.md) + - [Backend Architecture](architecture/backend.md) + - [Frontend Architecture](architecture/frontend.md) + - [Integration](architecture/integration.md) + +--- + +- **Components** + - **Backend** + - [Agents System](components/backend/agents.md) + - [Analysis Module](components/backend/analysis.md) + - [CLI Commands](components/backend/cli.md) + - [Core Services](components/backend/core.md) + - [Planning & Integrations](components/backend/planning.md) + - **Frontend** + - [Main Process](components/frontend/main-process.md) + - [IPC Handlers](components/frontend/ipc-handlers.md) + - [Renderer Components](components/frontend/renderer.md) + - [State Management](components/frontend/state.md) + +--- + +- **Diagrams** + - [Use Cases](diagrams/use-cases.md) + - [Sequence Diagrams](diagrams/sequences.md) + - [Class Diagrams](diagrams/classes.md) From 607b4bf01aad6b8ef2a8047ede089b0b9c8a442a Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 21:23:47 +0200 Subject: [PATCH 04/27] auto-claude: subtask-1-4 - Create getting-started.md with quick start guide for new developers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add comprehensive getting started documentation including: - Prerequisites and installation instructions (Python, Node.js, CMake) - Quick start commands for development environment - Project layout overview - Backend and frontend development setup - Environment configuration guide - Running the application (dev and production modes) - Backend CLI usage examples - Testing instructions for both backend and frontend - Pre-commit hooks setup - Troubleshooting common issues - Next steps with links to architecture documentation 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/getting-started.md | 363 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 363 insertions(+) create mode 100644 docs/getting-started.md diff --git a/docs/getting-started.md b/docs/getting-started.md new file mode 100644 index 0000000000..7d879b3f9d --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,363 @@ +# Getting Started + +**Quick start guide for new developers working with the Auto-Claude codebase.** + +--- + +## Prerequisites + +Before getting started, ensure you have the following installed: + +| Requirement | Version | Purpose | +|-------------|---------|---------| +| **Python** | 3.12+ | Backend runtime | +| **Node.js** | 24+ | Frontend development | +| **npm** | 10+ | Package management | +| **Git** | Latest | Version control | +| **CMake** | Latest | Native dependency builds | + +### Installing Python 3.12 + +**Windows:** +```bash +winget install Python.Python.3.12 +``` + +**macOS:** +```bash +brew install python@3.12 +``` + +**Linux (Ubuntu/Debian):** +```bash +sudo apt install python3.12 python3.12-venv +``` + +### Installing Node.js + +**Windows:** +```bash +winget install OpenJS.NodeJS +``` + +**macOS:** +```bash +brew install node +``` + +**Linux (Ubuntu/Debian):** +```bash +curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash - +sudo apt install -y nodejs +``` + +--- + +## Quick Start + +The fastest way to get the development environment running: + +```bash +# Clone the repository +git clone https://github.com/AndyMik90/Auto-Claude.git +cd Auto-Claude + +# Install all dependencies (both frontend and backend) +npm run install:all + +# Run in development mode +npm run dev + +# Or build and run production +npm start +``` + +That's it! The Electron application should launch with hot-reload enabled for development. + +--- + +## Project Layout + +Understanding the project structure is essential for effective development: + +``` +Auto-Claude/ +├── apps/ +│ ├── backend/ # Python agent system +│ │ ├── agents/ # Agent implementations (base, session, memory) +│ │ ├── analysis/ # Project analyzers +│ │ ├── cli/ # Command-line interface +│ │ ├── context/ # Context building and search +│ │ ├── core/ # Core services (auth, workspace) +│ │ ├── ideation/ # Feature ideation +│ │ ├── implementation_plan/ # Plan structures +│ │ └── integrations/ # External integrations (Graphiti, Linear) +│ └── frontend/ # Electron application +│ └── src/ +│ ├── main/ # Electron main process +│ │ ├── agent/ # Agent management +│ │ ├── terminal/ # PTY management +│ │ └── ipc-handlers/ # IPC communication +│ └── renderer/ # React renderer +│ ├── components/ # UI components +│ ├── stores/ # Zustand stores +│ └── hooks/ # Custom React hooks +├── docs/ # Technical documentation (you are here) +├── guides/ # User guides +├── scripts/ # Build and automation scripts +└── tests/ # Test suite +``` + +--- + +## Development Setup + +### Backend Setup + +The Python backend can be set up manually or via npm scripts: + +**Using npm (Recommended):** +```bash +npm run install:backend +``` + +**Manual Setup:** +```bash +cd apps/backend + +# Create virtual environment +# Windows: +py -3.12 -m venv .venv +.venv\Scripts\activate + +# macOS/Linux: +python3.12 -m venv .venv +source .venv/bin/activate + +# Install dependencies +pip install -r requirements.txt + +# Set up environment +cp .env.example .env +# Edit .env and add your CLAUDE_CODE_OAUTH_TOKEN +``` + +### Frontend Setup + +```bash +cd apps/frontend + +# Install dependencies +npm install + +# Start development server (hot-reload enabled) +npm run dev + +# Build for production +npm run build + +# Package for distribution +npm run package +``` + +--- + +## Environment Configuration + +Create a `.env` file in `apps/backend/` with the following: + +```bash +# Required: Claude API authentication +CLAUDE_CODE_OAUTH_TOKEN=your_token_here + +# Optional: Enable Graphiti memory integration +GRAPHITI_ENABLED=false +``` + +> **Tip:** Get your OAuth token by running `claude setup-token` in your terminal. + +--- + +## Running the Application + +### Development Mode + +Development mode enables hot-reload for both frontend and backend: + +```bash +# From repository root +npm run dev +``` + +This starts: +- Electron main process with hot-reload +- React renderer with Vite dev server +- Backend Python environment + +### Production Mode + +```bash +# Build and run +npm start + +# Or build first, then run +npm run build +npm run start:prod +``` + +--- + +## Backend CLI + +The backend provides CLI commands for running agent tasks: + +```bash +cd apps/backend + +# Activate virtual environment +source .venv/bin/activate # or .venv\Scripts\activate on Windows + +# Create a spec interactively +python spec_runner.py --interactive + +# Run autonomous build for a spec +python run.py --spec 001 + +# Run QA validation +python run.py --spec 001 --qa +``` + +--- + +## Running Tests + +### Backend Tests + +```bash +# From repository root +npm run test:backend + +# Or using pytest directly +cd apps/backend +.venv/Scripts/pytest.exe ../tests -v # Windows +.venv/bin/pytest ../tests -v # macOS/Linux + +# Run specific tests +npm run test:backend -- tests/test_security.py -v +``` + +### Frontend Tests + +```bash +cd apps/frontend + +# Run unit tests +npm test + +# Run with watch mode +npm run test:watch + +# Run E2E tests (requires built app) +npm run build +npm run test:e2e + +# Linting and type checking +npm run lint +npm run typecheck +``` + +--- + +## Pre-commit Hooks + +The project uses pre-commit hooks to maintain code quality: + +```bash +# Install pre-commit (if not already installed) +pip install pre-commit + +# Install the git hooks +pre-commit install +``` + +### What Runs on Commit + +| Hook | Scope | Description | +|------|-------|-------------| +| **ruff** | `apps/backend/` | Python linter with auto-fix | +| **ruff-format** | `apps/backend/` | Python code formatter | +| **eslint** | `apps/frontend/` | TypeScript/React linter | +| **typecheck** | `apps/frontend/` | TypeScript type checking | +| **trailing-whitespace** | All files | Removes trailing whitespace | +| **end-of-file-fixer** | All files | Ensures files end with newline | + +--- + +## Next Steps + +Now that your environment is set up: + +1. **[Architecture Overview](architecture/overview.md)** - Understand the system design +2. **[Backend Architecture](architecture/backend.md)** - Deep dive into the Python agent system +3. **[Frontend Architecture](architecture/frontend.md)** - Learn about the Electron/React application +4. **[Integration](architecture/integration.md)** - See how frontend and backend communicate + +### Useful Resources + +- **[CONTRIBUTING.md](https://github.com/AndyMik90/Auto-Claude/blob/main/CONTRIBUTING.md)** - Contribution guidelines +- **[CLAUDE.md](https://github.com/AndyMik90/Auto-Claude/blob/main/CLAUDE.md)** - Project context and codebase overview +- **[Discord Community](https://discord.gg/KCXaPBr4Dj)** - Get help and connect with contributors + +--- + +## Troubleshooting + +### Windows: node-gyp Errors + +If npm install fails with node-gyp errors: + +1. Download [Visual Studio Build Tools 2022](https://visualstudio.microsoft.com/visual-cpp-build-tools/) +2. Select "Desktop development with C++" workload +3. In "Individual Components", add "MSVC v143 - VS 2022 C++ x64/x86 Spectre-mitigated libs" +4. Restart your terminal and run `npm install` again + +### Python Version Issues + +Ensure you're using Python 3.12+: + +```bash +python --version # Should show 3.12.x or higher +``` + +If you have multiple Python versions, use explicit paths: + +```bash +# Windows +py -3.12 -m venv .venv + +# macOS/Linux +python3.12 -m venv .venv +``` + +### Environment Variable Not Found + +If you see errors about missing environment variables: + +1. Ensure `.env` file exists in `apps/backend/` +2. Copy from example: `cp apps/backend/.env.example apps/backend/.env` +3. Add your `CLAUDE_CODE_OAUTH_TOKEN` + +--- + +## Summary + +| Task | Command | +|------|---------| +| Install all dependencies | `npm run install:all` | +| Run development mode | `npm run dev` | +| Run production | `npm start` | +| Run backend tests | `npm run test:backend` | +| Run frontend tests | `cd apps/frontend && npm test` | +| Build for distribution | `npm run build` | + +You're now ready to start developing with Auto-Claude! From 3f810819e11ee2d21c656d0efe2d16acdba8762a Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 21:26:17 +0200 Subject: [PATCH 05/27] auto-claude: subtask-2-1 - Create architecture overview page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add high-level architecture documentation with Mermaid diagrams showing: - System architecture: Electron + Python multi-process design - Process communication flow with sequence diagram - Frontend components (Main/Renderer process organization) - Backend components (Agent, Analysis, Context, Core systems) - Task execution pipeline and agent lifecycle - Technology stack summary - Security model layers 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/architecture/overview.md | 269 ++++++++++++++++++++++++++++++++++ 1 file changed, 269 insertions(+) create mode 100644 docs/architecture/overview.md diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md new file mode 100644 index 0000000000..d4be87730c --- /dev/null +++ b/docs/architecture/overview.md @@ -0,0 +1,269 @@ +# Architecture Overview + +This document provides a high-level view of Auto-Claude's architecture, explaining how the Electron frontend and Python backend work together to deliver an autonomous coding experience. + +## System Architecture + +Auto-Claude follows a **desktop-first, multi-process architecture** combining Electron for the user interface with Python for AI agent execution. + +```mermaid +flowchart TB + subgraph Frontend["Frontend (Electron)"] + direction TB + Main["Main Process
TypeScript"] + Renderer["Renderer Process
React + Zustand"] + Preload["Preload Scripts
IPC Bridge"] + end + + subgraph Backend["Backend (Python)"] + direction TB + Agent["Agent System
Claude Agent SDK"] + Analysis["Project Analysis"] + Context["Context Builder"] + Memory["Graphiti Memory"] + end + + Main <--> |IPC| Renderer + Preload --> Main + Preload --> Renderer + Main <--> |"Process Spawn
NDJSON Streaming"| Agent + Agent --> Analysis + Agent --> Context + Agent --> Memory + + style Frontend fill:#e3f2fd,stroke:#1976d2 + style Backend fill:#fff3e0,stroke:#f57c00 +``` + +## Core Design Principles + +| Principle | Implementation | +|-----------|----------------| +| **Process Isolation** | Electron main/renderer separation; Python runs as child process | +| **Security First** | Context isolation, sandboxed tools, dynamic command allowlisting | +| **Real-time Streaming** | NDJSON protocol for live agent output | +| **Memory Persistence** | Graphiti integration for cross-session learning | +| **Modular Architecture** | Clear boundaries between UI, orchestration, and AI logic | + +## Process Communication Flow + +The system uses a layered communication approach: + +```mermaid +sequenceDiagram + participant User + participant Renderer as Renderer
(React) + participant Main as Main Process
(Electron) + participant Python as Python Backend
(Agent) + participant Claude as Claude API + + User->>Renderer: Create Task + Renderer->>Main: IPC: start-task + Main->>Python: Spawn process with args + Python->>Claude: Agent SDK call + Claude-->>Python: Response stream + Python-->>Main: NDJSON output + Main-->>Renderer: IPC: task-update + Renderer-->>User: Live UI updates +``` + +## Component Overview + +### Frontend Components + +The Electron frontend is organized into three main areas: + +```mermaid +flowchart LR + subgraph Main["Main Process"] + AM[AgentManager] + TM[TerminalManager] + IPC[IPC Handlers] + PM[ProfileManager] + end + + subgraph Renderer["Renderer Process"] + App[App.tsx] + Stores[Zustand Stores] + Components[UI Components] + Hooks[Custom Hooks] + end + + subgraph Services["Main Services"] + FileWatcher[File Watcher] + Insights[Insights Service] + Changelog[Changelog Service] + GitHub[GitHub Integration] + end + + Main <--> Renderer + Main --> Services +``` + +| Component | Purpose | +|-----------|---------| +| **AgentManager** | Spawns and manages Python agent processes | +| **TerminalManager** | PTY management for interactive terminals | +| **IPC Handlers** | Bridge between renderer and main process | +| **Zustand Stores** | Application state management | +| **UI Components** | React components (dialogs, panels, cards) | + +### Backend Components + +The Python backend handles AI agent execution and project analysis: + +```mermaid +flowchart TB + subgraph Agents["Agent System"] + Base[BaseAgent] + Session[SessionManager] + Memory[MemoryManager] + Planner[Planner Agent] + Coder[Coder Agent] + end + + subgraph Analysis["Analysis System"] + PA[ProjectAnalyzer] + FA[FrameworkAnalyzer] + RC[RiskClassifier] + SS[SecurityScanner] + end + + subgraph Context["Context System"] + CB[ContextBuilder] + CS[ContextSearch] + GI[Graphiti Integration] + end + + subgraph Core["Core Services"] + Client[Claude SDK Client] + Auth[Auth Manager] + Workspace[Workspace Manager] + end + + Base --> Session + Base --> Memory + Planner --> Base + Coder --> Base + + PA --> FA + PA --> RC + PA --> SS + + CB --> CS + CB --> GI + + Core --> Agents + Agents --> Analysis + Agents --> Context +``` + +| Module | Purpose | +|--------|---------| +| **agents/** | Agent implementations (planner, coder, QA) | +| **analysis/** | Project analysis and risk classification | +| **context/** | Context building, search, and memory | +| **core/** | Claude SDK client, auth, workspace setup | +| **cli/** | Command-line interface modules | + +## Data Flow + +### Task Execution Pipeline + +```mermaid +flowchart LR + subgraph Input + Task[Task Definition] + Spec[Spec File] + Plan[Implementation Plan] + end + + subgraph Execution + Planner[Planner Agent] + Coder[Coder Agent] + QA[QA Agent] + end + + subgraph Output + Code[Code Changes] + Commits[Git Commits] + Report[QA Report] + end + + Task --> Spec + Spec --> Planner + Planner --> Plan + Plan --> Coder + Coder --> Code + Code --> QA + QA --> Commits + QA --> Report +``` + +### Agent Lifecycle + +1. **Initialization**: Main process spawns Python with spec arguments +2. **Planning**: Planner agent analyzes spec and creates implementation plan +3. **Execution**: Coder agent implements subtasks with Claude SDK +4. **Validation**: QA agent reviews and validates changes +5. **Finalization**: Commits created, workspace cleaned up + +## Technology Stack + +### Frontend + +| Technology | Version | Purpose | +|------------|---------|---------| +| Electron | 39.x | Desktop application framework | +| React | 19.x | UI component library | +| TypeScript | 5.x | Type-safe JavaScript | +| Zustand | 5.x | State management | +| Tailwind CSS | 4.x | Utility-first styling | +| Radix UI | - | Accessible UI primitives | + +### Backend + +| Technology | Version | Purpose | +|------------|---------|---------| +| Python | 3.12+ | Runtime environment | +| Claude Agent SDK | - | AI agent execution | +| Graphiti | - | Memory and context persistence | +| python-dotenv | - | Environment configuration | + +## Security Model + +Auto-Claude implements multiple security layers: + +```mermaid +flowchart TB + subgraph Security["Security Layers"] + CI[Context Isolation] + SB[Sandboxed Tools] + DA[Dynamic Allowlisting] + WT[Worktree Isolation] + end + + subgraph Enforcement + Main[Main Process] + Core[Core Security] + Workspace[Workspace Manager] + end + + CI --> Main + SB --> Core + DA --> Core + WT --> Workspace +``` + +| Layer | Description | +|-------|-------------| +| **Context Isolation** | Electron renderer cannot access Node.js APIs directly | +| **Sandboxed Tools** | Agent tools have restricted filesystem and command access | +| **Dynamic Allowlisting** | Commands allowed based on detected project stack | +| **Worktree Isolation** | Git worktrees isolate feature development | + +## Next Steps + +- [Backend Architecture](./backend.md) - Deep dive into Python agent system +- [Frontend Architecture](./frontend.md) - Electron main/renderer organization +- [Integration Guide](./integration.md) - Frontend-backend communication details From 63e9f8bc71f57c5712a37387a2c980a0d3f96e56 Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 21:32:03 +0200 Subject: [PATCH 06/27] auto-claude: subtask-2-2 - Create backend architecture page documenting Python agent system MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Create comprehensive backend architecture documentation with: - Agent system architecture (coder, planner, session, memory) - Analysis system structure (service, project, framework analyzers) - Context system components (builder, search, graphiti integration) - Core infrastructure (client, auth, workspace, recovery) - CLI command structure - 15 Mermaid diagrams showing class relationships, data flows, and sequences - Module structures with file listings - Integration patterns for external services (Claude, Linear, Graphiti, GitHub) - Custom MCP tools documentation - Error handling and recovery strategies 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/architecture/backend.md | 649 +++++++++++++++++++++++++++++++++++ 1 file changed, 649 insertions(+) create mode 100644 docs/architecture/backend.md diff --git a/docs/architecture/backend.md b/docs/architecture/backend.md new file mode 100644 index 0000000000..88eefa3415 --- /dev/null +++ b/docs/architecture/backend.md @@ -0,0 +1,649 @@ +# Backend Architecture + +The Auto-Claude backend is a Python-based autonomous coding system built on the Claude Agent SDK. This document provides a comprehensive overview of its modular architecture, key components, and data flows. + +## Architecture Overview + +The backend is organized into focused modules with clear responsibilities: + +```mermaid +flowchart TB + subgraph Entry["Entry Points"] + Agent[agent.py] + CLI[cli/] + API[core/] + end + + subgraph Agents["Agent System"] + Coder[Coder Agent] + Planner[Planner Agent] + Session[Session Manager] + MemoryMgr[Memory Manager] + Tools[Custom Tools] + end + + subgraph Analysis["Analysis System"] + PA[Project Analyzer] + SA[Service Analyzer] + FA[Framework Analyzer] + Detectors[Context Detectors] + end + + subgraph Context["Context & Memory"] + Builder[Context Builder] + Search[Context Search] + Graphiti[Graphiti Integration] + FileMem[File-based Memory] + end + + subgraph Core["Core Infrastructure"] + Client[Claude SDK Client] + Auth[Auth Manager] + Workspace[Workspace Manager] + Recovery[Recovery Manager] + end + + Entry --> Agents + Agents --> Analysis + Agents --> Context + Context --> Core + Core --> Client + + style Entry fill:#e8f5e9,stroke:#4caf50 + style Agents fill:#e3f2fd,stroke:#1976d2 + style Analysis fill:#fff3e0,stroke:#f57c00 + style Context fill:#fce4ec,stroke:#e91e63 + style Core fill:#f3e5f5,stroke:#9c27b0 +``` + +## Agent System + +The agent system is the heart of Auto-Claude, executing autonomous coding tasks through the Claude Agent SDK. + +### Module Structure + +``` +apps/backend/agents/ +├── __init__.py # Public API exports (lazy loading) +├── base.py # Shared constants and configuration +├── coder.py # Main autonomous agent loop +├── planner.py # Follow-up planner logic +├── session.py # Session execution and tracking +├── memory_manager.py # Dual-layer memory system +├── utils.py # Git operations and plan management +└── tools_pkg/ # Custom MCP tools + ├── models.py # Tool definitions + ├── permissions.py # Tool access control + ├── registry.py # MCP server creation + └── tools/ # Tool implementations + ├── memory.py # Memory tools + ├── progress.py # Build progress tools + ├── qa.py # QA tools + └── subtask.py # Subtask management +``` + +### Agent Class Relationships + +```mermaid +classDiagram + class CoderAgent { + +run_autonomous_agent() + -recovery_manager + -status_manager + -task_logger + } + + class PlannerAgent { + +run_followup_planner() + -client + -prompt_generator + } + + class SessionManager { + +run_agent_session() + +post_session_processing() + -tool_tracking + -logging + } + + class MemoryManager { + +save_session_memory() + +get_graphiti_context() + +debug_memory_system_status() + -graphiti_client + -file_fallback + } + + class RecoveryManager { + +record_attempt() + +get_recovery_hints() + +mark_subtask_stuck() + -attempt_history + -good_commits + } + + CoderAgent --> SessionManager : uses + CoderAgent --> MemoryManager : uses + CoderAgent --> RecoveryManager : uses + PlannerAgent --> SessionManager : uses + SessionManager --> MemoryManager : saves to +``` + +### Coder Agent Flow + +The main autonomous agent loop handles the complete build lifecycle: + +```mermaid +sequenceDiagram + participant Run as run_autonomous_agent() + participant Check as Pre-Session Checks + participant Session as run_agent_session() + participant Post as post_session_processing() + participant Memory as MemoryManager + + Run->>Check: Check for PAUSE file + Check->>Check: Get next subtask + Check->>Session: Generate prompt + Session->>Session: Create SDK client + Session->>Session: Execute with Claude SDK + Session-->>Run: (status, response) + Run->>Post: Process results + Post->>Post: Check subtask status + Post->>Memory: Save session insights + Post->>Post: Update Linear (if enabled) + Post-->>Run: success/failure + + alt Subtask completed + Run->>Run: Continue to next + else Stuck after 3 attempts + Run->>Run: Mark as stuck + end +``` + +### Memory System + +The backend uses a dual-layer memory system for session persistence: + +```mermaid +flowchart LR + subgraph Primary["Primary: Graphiti"] + G1[Semantic Search] + G2[Cross-Session Context] + G3[Knowledge Graph] + end + + subgraph Fallback["Fallback: File-based"] + F1[JSON Files] + F2[session_insights/] + F3[Zero Dependencies] + end + + Session[Session Complete] --> Check{Graphiti Enabled?} + Check -->|Yes| Primary + Check -->|No| Fallback + Primary -->|Fails| Fallback + + style Primary fill:#e3f2fd,stroke:#1976d2 + style Fallback fill:#fff3e0,stroke:#f57c00 +``` + +| Memory Type | Use Case | Features | +|-------------|----------|----------| +| **Graphiti** | Production | Semantic search, entity extraction, cross-session learning | +| **File-based** | Development | JSON files, no external dependencies, always available | + +## Analysis System + +The analysis system automatically detects project structure, frameworks, and services. + +### Module Structure + +``` +apps/backend/analysis/ +├── analyzer.py # CLI facade +├── project_analyzer.py # Full project analysis +├── analyzers/ +│ ├── base.py # BaseAnalyzer class +│ ├── service_analyzer.py # Single service analysis +│ ├── project_analyzer_module.py # Monorepo detection +│ ├── framework_analyzer.py # Framework detection +│ ├── route_detector.py # API route detection +│ ├── database_detector.py # Database model detection +│ ├── context_analyzer.py # Context extraction +│ └── context/ # Specialized detectors +│ ├── api_docs_detector.py +│ ├── auth_detector.py +│ ├── env_detector.py +│ ├── jobs_detector.py +│ ├── migrations_detector.py +│ ├── monitoring_detector.py +│ └── services_detector.py +├── risk_classifier.py # Change risk assessment +├── security_scanner.py # Security vulnerability detection +└── insight_extractor.py # Session insight extraction +``` + +### Analyzer Class Hierarchy + +```mermaid +classDiagram + class BaseAnalyzer { + <> + +path: Path + +analyze() + #_find_files() + #_read_file() + } + + class ServiceAnalyzer { + +name: str + +analysis: dict + +analyze() + -_detect_language_and_framework() + -_detect_service_type() + -_find_entry_points() + } + + class ProjectAnalyzer { + +project_dir: Path + +analyze() + -_detect_if_monorepo() + -_find_all_services() + -_map_dependencies() + } + + class FrameworkAnalyzer { + +detect_language_and_framework() + -_check_package_json() + -_check_requirements() + -_check_go_mod() + } + + class ContextAnalyzer { + +analyze_context() + -_extract_env_vars() + -_find_config_files() + } + + BaseAnalyzer <|-- ServiceAnalyzer + BaseAnalyzer <|-- ProjectAnalyzer + ServiceAnalyzer --> FrameworkAnalyzer : uses + ServiceAnalyzer --> ContextAnalyzer : uses +``` + +### Analysis Pipeline + +```mermaid +flowchart LR + subgraph Detection + Lang[Language Detection] + Frame[Framework Detection] + Type[Service Type] + end + + subgraph Extraction + Routes[API Routes] + Models[Database Models] + Deps[Dependencies] + end + + subgraph Context + Env[Environment Vars] + Auth[Auth Patterns] + Jobs[Background Jobs] + end + + Input[Project Dir] --> Detection + Detection --> Extraction + Extraction --> Context + Context --> Output[project_index.json] +``` + +## Context System + +The context system builds and searches contextual information for agent prompts. + +### Module Structure + +``` +apps/backend/context/ +├── builder.py # Context builder +├── search.py # Context search +├── categorizer.py # File categorization +├── keyword_extractor.py # Keyword extraction +├── pattern_discovery.py # Pattern detection +├── service_matcher.py # Service matching +├── graphiti_integration.py # Memory integration +├── models.py # Data models +├── serialization.py # JSON serialization +└── constants.py # Configuration +``` + +### Context Building Flow + +```mermaid +flowchart TB + subgraph Input + Subtask[Subtask Definition] + Plan[Implementation Plan] + Project[Project Files] + end + + subgraph Processing + Keywords[Keyword Extraction] + Category[File Categorization] + Patterns[Pattern Discovery] + Service[Service Matching] + end + + subgraph Output + Context[Context Object] + Prompt[Enriched Prompt] + end + + Subtask --> Keywords + Plan --> Service + Project --> Category + Category --> Patterns + Keywords --> Context + Patterns --> Context + Service --> Context + Context --> Prompt + + style Processing fill:#e3f2fd,stroke:#1976d2 +``` + +| Component | Purpose | +|-----------|---------| +| **ContextBuilder** | Orchestrates context creation from multiple sources | +| **ContextSearch** | Searches relevant files and patterns | +| **PatternDiscovery** | Identifies code patterns and conventions | +| **GraphitiIntegration** | Queries memory for historical context | + +## Core Infrastructure + +The core module provides fundamental services used across the backend. + +### Module Structure + +``` +apps/backend/core/ +├── agent.py # Agent execution utilities +├── client.py # Claude SDK client factory +├── auth.py # Authentication management +├── workspace.py # Workspace management +├── workspace/ +│ ├── setup.py # Workspace initialization +│ ├── finalization.py # Cleanup and commit +│ ├── git_utils.py # Git operations +│ ├── display.py # Progress display +│ └── models.py # Data structures +├── worktree.py # Git worktree management +├── progress.py # Build progress tracking +├── phase_event.py # Execution phase events +└── debug.py # Debug utilities +``` + +### Client Creation Flow + +```mermaid +sequenceDiagram + participant Caller + participant ClientFactory as create_client() + participant Auth as AuthManager + participant MCP as MCP Server + participant SDK as Claude SDK + + Caller->>ClientFactory: create_client(project_dir, spec_dir, model) + ClientFactory->>Auth: Get credentials + Auth-->>ClientFactory: OAuth token + ClientFactory->>MCP: Create auto-claude tools + MCP-->>ClientFactory: MCP server instance + ClientFactory->>SDK: ClaudeSDKClient(options) + SDK-->>Caller: client instance +``` + +### Workspace Lifecycle + +```mermaid +flowchart LR + subgraph Setup + Init[Initialize] + Branch[Create Branch] + Worktree[Setup Worktree] + end + + subgraph Execution + Agent[Run Agent] + Commits[Create Commits] + Track[Track Changes] + end + + subgraph Finalization + Merge[Merge Changes] + Cleanup[Cleanup Worktree] + Report[Generate Report] + end + + Setup --> Execution + Execution --> Finalization +``` + +## CLI System + +The CLI provides command-line access to all backend functionality. + +### Module Structure + +``` +apps/backend/cli/ +├── main.py # CLI entry point +├── build_commands.py # Build-related commands +├── spec_commands.py # Spec management +├── qa_commands.py # QA operations +├── batch_commands.py # Batch processing +├── followup_commands.py # Follow-up planning +├── workspace_commands.py # Workspace management +├── input_handlers.py # Input validation +└── utils.py # CLI utilities +``` + +### Command Categories + +```mermaid +flowchart TB + CLI[auto-claude CLI] + + subgraph BuildCmds["Build Commands"] + Build[build] + Plan[plan] + Continue[continue] + end + + subgraph SpecCmds["Spec Commands"] + Create[create-spec] + List[list-specs] + Status[status] + end + + subgraph QACmds["QA Commands"] + QA[qa] + Review[review] + Approve[approve] + end + + subgraph UtilityCmds["Utility Commands"] + Analyze[analyze] + Index[index] + Clean[clean] + end + + CLI --> BuildCmds + CLI --> SpecCmds + CLI --> QACmds + CLI --> UtilityCmds +``` + +## Integration Patterns + +### External Integrations + +```mermaid +flowchart LR + Backend[Backend] + + subgraph External + Claude[Claude API] + Linear[Linear API] + Graphiti[Graphiti] + GitHub[GitHub API] + end + + Backend <-->|Agent SDK| Claude + Backend <-->|Task Tracking| Linear + Backend <-->|Memory| Graphiti + Backend <-->|PR/Issues| GitHub +``` + +| Integration | Purpose | Module | +|-------------|---------|--------| +| **Claude API** | AI agent execution | `core/client.py` | +| **Linear** | Task progress tracking | `integrations/linear/` | +| **Graphiti** | Memory and context | `integrations/graphiti/` | +| **GitHub** | Repository operations | `core/workspace/` | + +### Custom MCP Tools + +The backend provides custom MCP tools for reliable agent operations: + +```mermaid +flowchart TB + subgraph Tools["Custom MCP Tools"] + UpdateStatus[update_subtask_status] + GetProgress[get_build_progress] + RecordDiscovery[record_discovery] + RecordGotcha[record_gotcha] + GetContext[get_session_context] + UpdateQA[update_qa_status] + end + + subgraph Benefits + Reliable[100% Reliable JSON] + TypeSafe[Type-safe Operations] + Reduced[Reduced Context Usage] + end + + Tools --> Benefits +``` + +## Data Structures + +### Implementation Plan + +```mermaid +classDiagram + class ImplementationPlan { + +feature: str + +workflow_type: str + +phases: List~Phase~ + +summary: PlanSummary + +status: PlanStatus + } + + class Phase { + +id: str + +name: str + +type: PhaseType + +subtasks: List~Subtask~ + +depends_on: List~str~ + } + + class Subtask { + +id: str + +description: str + +service: str + +files_to_modify: List~str~ + +files_to_create: List~str~ + +verification: Verification + +status: SubtaskStatus + } + + class Verification { + +type: str + +command: str + +expected: str + } + + ImplementationPlan "1" --> "*" Phase + Phase "1" --> "*" Subtask + Subtask "1" --> "1" Verification +``` + +### Session Insights + +```mermaid +classDiagram + class SessionInsights { + +session_number: int + +subtasks_completed: List~str~ + +discoveries: Discoveries + +what_worked: List~str~ + +what_failed: List~str~ + +recommendations: List~str~ + } + + class Discoveries { + +files_understood: Dict + +patterns_found: List~str~ + +gotchas_encountered: List~str~ + } + + SessionInsights --> Discoveries +``` + +## Error Handling and Recovery + +### Recovery Strategy + +```mermaid +flowchart TB + Attempt[Subtask Attempt] + + Attempt --> Success{Success?} + Success -->|Yes| RecordGood[Record Good Commit] + Success -->|No| CheckCount{Attempts >= 3?} + + CheckCount -->|No| GetHints[Get Recovery Hints] + GetHints --> Retry[Retry with Context] + Retry --> Attempt + + CheckCount -->|Yes| MarkStuck[Mark as Stuck] + MarkStuck --> NotifyLinear[Notify Linear] + NotifyLinear --> Manual[Require Manual Intervention] + + style Success fill:#e8f5e9,stroke:#4caf50 + style MarkStuck fill:#ffebee,stroke:#f44336 +``` + +| Recovery Feature | Description | +|------------------|-------------| +| **Attempt Tracking** | Records each attempt with approach and errors | +| **Good Commits** | Stores successful commits for rollback safety | +| **Recovery Hints** | Provides context from failed attempts | +| **Stuck Detection** | Marks subtasks as stuck after max retries | + +## Performance Considerations + +| Aspect | Implementation | +|--------|----------------| +| **Lazy Imports** | `__getattr__` pattern avoids circular dependencies | +| **Streaming Output** | NDJSON for real-time progress updates | +| **Concurrent Analysis** | Service analyzers can run in parallel | +| **Memory Caching** | Graphiti caches for repeated queries | + +## Next Steps + +- [Analysis Module](../components/backend/analysis.md) - Detailed analyzer documentation +- [Agents Module](../components/backend/agents.md) - Agent implementation details +- [CLI Module](../components/backend/cli.md) - Command-line interface reference +- [Core Module](../components/backend/core.md) - Core services documentation From 296157c1c923b315ad2602677a9b572e65420332 Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 21:36:02 +0200 Subject: [PATCH 07/27] auto-claude: subtask-2-3 - Create frontend architecture page documenting Elec MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add comprehensive frontend architecture documentation covering: - Electron main/renderer process separation - Main process components (AgentManager, TerminalManager, IPC handlers) - Preload bridge and context isolation - Renderer process with React and Zustand state management - Terminal integration with xterm.js and node-pty - Component hierarchy and routing - Security model and performance optimizations - 13 mermaid diagrams for visual architecture representation 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/architecture/frontend.md | 634 ++++++++++++++++++++++++++++++++++ 1 file changed, 634 insertions(+) create mode 100644 docs/architecture/frontend.md diff --git a/docs/architecture/frontend.md b/docs/architecture/frontend.md new file mode 100644 index 0000000000..725dd21f98 --- /dev/null +++ b/docs/architecture/frontend.md @@ -0,0 +1,634 @@ +# Frontend Architecture + +The Auto-Claude frontend is an Electron-based desktop application built with React and TypeScript. This document provides a comprehensive overview of the main/renderer process architecture, component organization, and state management patterns. + +## Architecture Overview + +The frontend follows Electron's multi-process architecture with strict separation between the main process (Node.js) and renderer process (Chromium): + +```mermaid +flowchart TB + subgraph Main["Main Process (Node.js)"] + direction TB + Entry[index.ts
App Initialization] + AM[AgentManager
Process Orchestration] + TM[TerminalManager
PTY Management] + IPC[IPC Handlers
Message Bridge] + Services[Main Services
File Watcher, Insights, Changelog] + end + + subgraph Preload["Preload Scripts"] + API[electronAPI
Context Bridge] + end + + subgraph Renderer["Renderer Process (Chromium)"] + direction TB + App[App.tsx
Root Component] + Stores[Zustand Stores
State Management] + Components[React Components
UI Layer] + Hooks[Custom Hooks
IPC Listeners] + end + + Entry --> AM + Entry --> TM + Entry --> IPC + Entry --> Services + + Main <-->|IPC| Preload + Preload -->|contextBridge| Renderer + + App --> Stores + App --> Components + Components --> Hooks + + style Main fill:#e3f2fd,stroke:#1976d2 + style Preload fill:#fff3e0,stroke:#f57c00 + style Renderer fill:#e8f5e9,stroke:#4caf50 +``` + +## Core Design Principles + +| Principle | Implementation | +|-----------|----------------| +| **Process Isolation** | Main process handles system operations; renderer handles UI only | +| **Context Isolation** | Renderer cannot access Node.js APIs directly; uses contextBridge | +| **Type Safety** | Shared TypeScript types between processes | +| **Reactive State** | Zustand stores with IPC event listeners for real-time updates | +| **Modular IPC** | Domain-specific handler modules for maintainability | + +## Main Process + +The main process handles all Node.js operations including file system access, process spawning, and system integration. + +### Entry Point Structure + +``` +apps/frontend/src/main/ +├── index.ts # App initialization and window creation +├── ipc-setup.ts # IPC handler registration facade +├── ipc-handlers/ # Domain-specific IPC handlers +│ ├── project-handlers.ts # Project CRUD +│ ├── task-handlers.ts # Task execution +│ ├── terminal-handlers.ts # Terminal operations +│ ├── settings-handlers.ts # App settings +│ ├── github/ # GitHub integration +│ └── context/ # Project context +├── agent/ # Agent process management +│ ├── agent-manager.ts # Main orchestrator +│ ├── agent-process.ts # Process spawning +│ ├── agent-queue.ts # Task queuing +│ ├── agent-state.ts # State tracking +│ └── parsers/ # Output parsing +├── terminal/ # Terminal management +│ ├── terminal-manager.ts # Main orchestrator +│ ├── pty-manager.ts # PTY process handling +│ └── session-handler.ts # Session persistence +└── services/ # Background services + ├── file-watcher.ts # File change detection + ├── insights-service.ts # AI insights + └── changelog-service.ts # Changelog generation +``` + +### AgentManager + +The AgentManager orchestrates Python agent processes for task execution, roadmap generation, and ideation: + +```mermaid +classDiagram + class AgentManager { + -state: AgentState + -events: AgentEvents + -processManager: AgentProcessManager + -queueManager: AgentQueueManager + +configure(pythonPath, autoBuildPath) + +startSpecCreation(taskId, projectPath, ...) + +startTaskExecution(taskId, projectPath, ...) + +startRoadmapGeneration(projectId, ...) + +killTask(taskId) + +isRunning(taskId) + } + + class AgentState { + -processes: Map + +hasProcess(taskId) + +getRunningTaskIds() + } + + class AgentProcessManager { + +spawnProcess(taskId, args, env, type) + +killProcess(taskId) + +getCombinedEnv(projectPath) + } + + class AgentQueueManager { + +startRoadmapGeneration() + +startIdeationGeneration() + +stopRoadmap(projectId) + } + + AgentManager --> AgentState : uses + AgentManager --> AgentProcessManager : uses + AgentManager --> AgentQueueManager : uses +``` + +### TerminalManager + +The TerminalManager provides PTY-based terminal emulation for interactive Claude Code sessions: + +```mermaid +flowchart LR + subgraph TerminalManager + TM[TerminalManager
Facade] + PTY[PTYManager
Process Control] + Session[SessionHandler
Persistence] + Parser[OutputParser
Pattern Detection] + end + + subgraph Features + Interactive[Interactive PTY] + RateLimit[Rate Limit Detection] + History[Command History] + Restore[Session Restore] + end + + TM --> PTY + TM --> Session + PTY --> Parser + + PTY --> Interactive + Parser --> RateLimit + Session --> History + Session --> Restore +``` + +| Component | Purpose | +|-----------|---------| +| **PTYManager** | Spawns and manages pseudo-terminal processes | +| **SessionHandler** | Persists terminal sessions across app restarts | +| **OutputParser** | Detects rate limits and special patterns in output | + +### IPC Handler Organization + +IPC handlers are organized by domain for maintainability: + +```mermaid +flowchart TB + subgraph IPC["IPC Handler Modules"] + Project[project-handlers.ts
Project CRUD, Init] + Task[task-handlers.ts
Task Execution] + Terminal[terminal-handlers.ts
Terminal Ops] + Settings[settings-handlers.ts
App Settings] + GitHub[github/
OAuth, PRs, Issues] + Context[context/
Memory, Index] + Roadmap[roadmap-handlers.ts
Generation] + end + + Main[Main Process] --> IPC + IPC <-->|invoke/handle| Renderer[Renderer] + + style IPC fill:#e3f2fd,stroke:#1976d2 +``` + +## Preload Bridge + +The preload script creates a secure bridge between main and renderer processes using Electron's contextBridge: + +```mermaid +sequenceDiagram + participant R as Renderer + participant P as Preload + participant M as Main Process + + R->>P: window.electronAPI.getProjects() + P->>M: ipcRenderer.invoke('get-projects') + M->>M: Handle request + M-->>P: IPC response + P-->>R: Promise + + Note over P: contextBridge.exposeInMainWorld
creates window.electronAPI +``` + +### API Surface + +The preload exposes a unified `electronAPI` object: + +```typescript +// Available in renderer as window.electronAPI +interface ElectronAPI { + // Projects + getProjects(): Promise> + addProject(path: string): Promise> + removeProject(id: string): Promise> + + // Tasks + startTask(taskId: string, options: TaskOptions): Promise> + stopTask(taskId: string): Promise> + + // Terminals + createTerminal(options: TerminalOptions): Promise> + writeTerminal(id: string, data: string): Promise + + // Events (returns cleanup function) + onTaskProgress(callback: (taskId, plan) => void): () => void + onTerminalData(callback: (id, data) => void): () => void +} +``` + +## Renderer Process + +The renderer process runs in a Chromium browser context, handling all UI rendering with React. + +### Application Structure + +``` +apps/frontend/src/renderer/ +├── App.tsx # Root component with routing +├── main.tsx # React entry point +├── stores/ # Zustand state stores +│ ├── project-store.ts # Project state +│ ├── task-store.ts # Task state +│ ├── terminal-store.ts # Terminal state +│ ├── settings-store.ts # App settings +│ ├── roadmap-store.ts # Roadmap state +│ └── ideation-store.ts # Ideation state +├── hooks/ # Custom React hooks +│ ├── useIpc.ts # IPC event listeners +│ └── useTerminal.ts # Terminal utilities +├── components/ # UI components +│ ├── ui/ # Base UI primitives (Radix) +│ ├── settings/ # Settings dialogs +│ ├── task-detail/ # Task detail views +│ ├── github-issues/ # GitHub integration +│ └── changelog/ # Changelog components +└── i18n/ # Internationalization +``` + +### Component Hierarchy + +```mermaid +flowchart TB + App[App.tsx] + + subgraph Layout + TabBar[ProjectTabBar] + Sidebar[Sidebar] + Content[Main Content Area] + end + + subgraph Views + Kanban[KanbanBoard] + Terminal[TerminalGrid] + Roadmap[Roadmap] + Insights[Insights] + Context[Context] + GitHub[GitHubIssues/PRs] + end + + subgraph Modals + TaskWizard[TaskCreationWizard] + TaskDetail[TaskDetailModal] + Settings[AppSettingsDialog] + RateLimit[RateLimitModal] + end + + App --> Layout + Content --> Views + App --> Modals + + style App fill:#e3f2fd,stroke:#1976d2 + style Views fill:#e8f5e9,stroke:#4caf50 +``` + +### Key Components + +| Component | Purpose | +|-----------|---------| +| **App.tsx** | Root component, view routing, global state initialization | +| **Sidebar** | Navigation between views (Kanban, Roadmap, Insights, etc.) | +| **ProjectTabBar** | Browser-like tabs for multiple open projects | +| **KanbanBoard** | Task management with drag-and-drop columns | +| **TerminalGrid** | Grid of interactive terminal sessions | +| **TaskDetailModal** | Detailed task view with logs and progress | + +## State Management + +### Zustand Store Architecture + +State is managed through domain-specific Zustand stores with IPC synchronization: + +```mermaid +flowchart LR + subgraph Stores["Zustand Stores"] + Project[useProjectStore
Projects, Tabs] + Task[useTaskStore
Tasks, Progress] + Terminal[useTerminalStore
Sessions] + Settings[useSettingsStore
App Settings] + Roadmap[useRoadmapStore
Roadmap Data] + end + + subgraph IPC["IPC Events"] + Progress[task-progress] + Status[task-status] + TermData[terminal-data] + RoadmapEvt[roadmap-complete] + end + + IPC --> Stores + Stores --> Components[React Components] + + style Stores fill:#e3f2fd,stroke:#1976d2 +``` + +### Store Pattern Example + +```typescript +// Zustand store with actions and selectors +interface ProjectState { + projects: Project[]; + activeProjectId: string | null; + openProjectIds: string[]; + + // Actions + setProjects: (projects: Project[]) => void; + openProjectTab: (projectId: string) => void; + closeProjectTab: (projectId: string) => void; + + // Selectors + getActiveProject: () => Project | undefined; + getProjectTabs: () => Project[]; +} + +export const useProjectStore = create((set, get) => ({ + projects: [], + activeProjectId: null, + openProjectIds: [], + + openProjectTab: (projectId) => { + const state = get(); + if (!state.openProjectIds.includes(projectId)) { + set({ + openProjectIds: [...state.openProjectIds, projectId], + activeProjectId: projectId + }); + // Persist to main process + window.electronAPI.saveTabState({...}); + } + }, + // ... +})); +``` + +### IPC Event Listeners + +The `useIpcListeners` hook sets up event subscriptions for real-time updates: + +```mermaid +sequenceDiagram + participant Main as Main Process + participant Hook as useIpcListeners + participant Store as Zustand Store + participant UI as React Component + + Main->>Hook: onTaskProgress(taskId, plan) + Hook->>Store: updateTaskFromPlan(taskId, plan) + Store->>UI: State change triggers re-render + UI->>UI: Display updated progress +``` + +## Terminal Integration + +### Terminal Architecture + +The terminal system uses xterm.js in the renderer with node-pty in the main process: + +```mermaid +flowchart TB + subgraph Renderer["Renderer Process"] + XTerm[xterm.js
Terminal Emulator] + Component[Terminal.tsx
React Component] + end + + subgraph Main["Main Process"] + PTY[node-pty
PTY Process] + Manager[TerminalManager] + Store[Session Store] + end + + Component --> XTerm + XTerm <-->|IPC: write/data| PTY + Manager --> PTY + Manager --> Store + + style Renderer fill:#e8f5e9,stroke:#4caf50 + style Main fill:#e3f2fd,stroke:#1976d2 +``` + +### Terminal Session Flow + +```mermaid +sequenceDiagram + participant User + participant Component as Terminal.tsx + participant Store as TerminalStore + participant IPC as IPC Bridge + participant PTY as TerminalManager + + User->>Component: Open terminal view + Component->>Store: Get sessions + Store->>IPC: createTerminal() + IPC->>PTY: Spawn PTY process + PTY-->>IPC: Terminal ID + IPC-->>Store: Session created + Store-->>Component: Render terminal + + User->>Component: Type command + Component->>IPC: writeTerminal(id, data) + IPC->>PTY: Write to PTY + PTY-->>IPC: onTerminalData(id, output) + IPC-->>Component: Render output +``` + +## Window Management + +### Browser Window Configuration + +The main window is configured for optimal desktop app experience: + +```typescript +mainWindow = new BrowserWindow({ + width: 1400, + height: 900, + minWidth: 1000, + minHeight: 700, + titleBarStyle: 'hiddenInset', // macOS native look + trafficLightPosition: { x: 15, y: 10 }, + webPreferences: { + preload: join(__dirname, '../preload/index.mjs'), + sandbox: false, + contextIsolation: true, // Security: isolate contexts + nodeIntegration: false, // Security: no Node in renderer + backgroundThrottling: false // Keep terminals responsive + } +}); +``` + +### Dev vs Production Loading + +```mermaid +flowchart TB + Init[Window Created] + Check{is.dev?} + + Init --> Check + Check -->|Yes| DevURL[loadURL
localhost:5173] + Check -->|No| ProdFile[loadFile
renderer/index.html] + + DevURL --> DevTools[Open DevTools] +``` + +## Event System + +### Main Process Events + +```mermaid +flowchart LR + subgraph Emitters + Agent[AgentManager] + Terminal[TerminalManager] + FileWatch[FileWatcher] + end + + subgraph Events + TaskProg[task-progress] + TaskErr[task-error] + TermData[terminal-data] + RateLimit[rate-limit] + FileChange[file-changed] + end + + subgraph Handlers + IPC[IPC Forwarder] + Renderer[Renderer Process] + end + + Agent --> TaskProg + Agent --> TaskErr + Terminal --> TermData + Terminal --> RateLimit + FileWatch --> FileChange + + Events --> IPC + IPC --> Renderer +``` + +### Rate Limit Handling + +```mermaid +sequenceDiagram + participant PTY as Terminal PTY + participant Parser as OutputParser + participant TM as TerminalManager + participant IPC as IPC Bridge + participant Modal as RateLimitModal + + PTY->>Parser: Terminal output + Parser->>Parser: Detect rate limit pattern + Parser->>TM: Rate limit detected + TM->>IPC: Emit rate-limit event + IPC->>Modal: Show modal with reset time + Modal->>Modal: Countdown timer +``` + +## Technology Stack + +| Technology | Version | Purpose | +|------------|---------|---------| +| Electron | 39.x | Desktop application framework | +| React | 19.x | UI component library | +| TypeScript | 5.x | Type-safe JavaScript | +| Zustand | 5.x | Lightweight state management | +| Tailwind CSS | 4.x | Utility-first CSS framework | +| Radix UI | - | Accessible UI primitives | +| xterm.js | - | Terminal emulator | +| node-pty | - | PTY process management | +| Vite | 6.x | Build tool and dev server | + +## Security Model + +### Context Isolation + +The renderer process is fully isolated from Node.js: + +```mermaid +flowchart TB + subgraph Blocked["Blocked in Renderer"] + FS[fs module] + Child[child_process] + OS[os module] + end + + subgraph Allowed["Allowed via contextBridge"] + API[window.electronAPI] + Safe[Curated, typed methods] + end + + Renderer[Renderer Process] --> Allowed + Renderer -.->|X| Blocked + + style Blocked fill:#ffebee,stroke:#f44336 + style Allowed fill:#e8f5e9,stroke:#4caf50 +``` + +### Security Layers + +| Layer | Implementation | +|-------|----------------| +| **contextIsolation** | Renderer cannot access preload scope | +| **nodeIntegration: false** | No Node.js APIs in renderer | +| **sandbox: false** | Required for node-pty (controlled risk) | +| **Typed IPC** | All IPC methods are typed and validated | + +## Performance Optimizations + +| Optimization | Implementation | +|--------------|----------------| +| **backgroundThrottling: false** | Terminals stay responsive when unfocused | +| **Debounced Tab State** | Tab state saves are debounced to reduce IPC | +| **Lazy Store Loading** | Stores load data on demand | +| **Virtualized Lists** | Long lists use windowing for performance | +| **Memoized Selectors** | Zustand selectors prevent unnecessary re-renders | + +## Build Configuration + +### Development + +```bash +# Start renderer dev server (Vite) +pnpm dev:frontend + +# Watches for changes and hot-reloads +# Main process: Uses electron-vite for HMR +# Renderer: Uses Vite's fast refresh +``` + +### Production + +```mermaid +flowchart LR + Build[pnpm build:frontend] + + subgraph Output + Main[out/main/
Bundled main process] + Preload[out/preload/
Preload scripts] + Renderer[out/renderer/
React app bundle] + end + + Build --> Output + Output --> Pack[electron-builder
Package for OS] +``` + +## Next Steps + +- [Overview Architecture](./overview.md) - High-level system overview +- [Backend Architecture](./backend.md) - Python agent system details +- [Integration Guide](./integration.md) - Frontend-backend communication From da5b5c4f9b265275f98b3ac8605169c24d8638d2 Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 21:40:20 +0200 Subject: [PATCH 08/27] auto-claude: subtask-2-4 - Create integration documentation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add comprehensive frontend-backend integration documentation with: - IPC channel architecture and flow types - Task execution sequence diagrams - Process spawning and environment configuration - Agent event system and phase protocol - Preload API layer structure - NDJSON streaming protocol - Rate limit handling and auto-swap flows - Terminal integration with Claude Code - File watcher integration - Error handling patterns and security layers Includes 15+ Mermaid diagrams (sequence, flowchart, state) showing communication between Electron main/renderer and Python backend. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/architecture/integration.md | 784 +++++++++++++++++++++++++++++++ 1 file changed, 784 insertions(+) create mode 100644 docs/architecture/integration.md diff --git a/docs/architecture/integration.md b/docs/architecture/integration.md new file mode 100644 index 0000000000..246a5bc495 --- /dev/null +++ b/docs/architecture/integration.md @@ -0,0 +1,784 @@ +# Frontend-Backend Integration + +This document provides detailed documentation on how the Electron frontend and Python backend communicate through IPC (Inter-Process Communication) and process spawning mechanisms. + +## Communication Architecture + +Auto-Claude uses a layered communication architecture that separates concerns between the UI, orchestration, and AI execution layers. + +```mermaid +flowchart TB + subgraph Renderer["Renderer Process (React)"] + UI[UI Components] + Hooks[Custom Hooks] + Stores[Zustand Stores] + API[electronAPI] + end + + subgraph Preload["Preload Scripts"] + Bridge[Context Bridge] + TaskAPI[Task API] + AgentAPI[Agent API] + TermAPI[Terminal API] + end + + subgraph Main["Main Process (Electron)"] + IPC[IPC Handlers] + AM[AgentManager] + PM[ProcessManager] + TM[TerminalManager] + EvtFwd[Event Forwarder] + end + + subgraph Backend["Python Backend"] + Agent[Agent Process] + Stream[NDJSON Stream] + Claude[Claude API] + end + + UI --> API + API --> Bridge + Bridge --> IPC + IPC --> AM + AM --> PM + PM --> Agent + Agent --> Stream + Stream --> EvtFwd + EvtFwd --> Stores + Stores --> UI + + style Renderer fill:#e3f2fd,stroke:#1976d2 + style Preload fill:#e8f5e9,stroke:#4caf50 + style Main fill:#fff3e0,stroke:#f57c00 + style Backend fill:#fce4ec,stroke:#e91e63 +``` + +## IPC Channel Architecture + +The system uses a comprehensive set of IPC channels organized by domain. Each channel follows a consistent naming convention: `domain:action`. + +### Channel Categories + +| Category | Prefix | Purpose | +|----------|--------|---------| +| **Tasks** | `task:` | Task CRUD, execution control, worktree management | +| **Projects** | `project:` | Project lifecycle, settings | +| **Terminal** | `terminal:` | PTY sessions, Claude Code integration | +| **Claude Profiles** | `claude:` | Multi-account management, rate limiting | +| **Roadmap** | `roadmap:` | Feature generation, AI planning | +| **GitHub** | `github:` | Issue integration, PR review, auto-fix | +| **Insights** | `insights:` | AI-powered codebase chat | + +### Channel Flow Types + +```mermaid +flowchart LR + subgraph Request["Request Channels"] + direction TB + R1[ipcMain.handle] + R2["Promise-based"] + R3["Bidirectional"] + end + + subgraph Fire["Fire-and-Forget"] + direction TB + F1[ipcMain.on] + F2["No response"] + F3["Start/Stop actions"] + end + + subgraph Events["Event Channels"] + direction TB + E1[webContents.send] + E2["Main → Renderer"] + E3["Streaming updates"] + end + + Renderer -->|"invoke()"| Request + Renderer -->|"send()"| Fire + Events -->|"on()"| Renderer + + style Request fill:#e8f5e9,stroke:#4caf50 + style Fire fill:#fff3e0,stroke:#f57c00 + style Events fill:#e3f2fd,stroke:#1976d2 +``` + +## Task Execution Flow + +The complete flow from user action to code generation involves multiple communication layers. + +### Task Start Sequence + +```mermaid +sequenceDiagram + participant User + participant UI as React UI + participant Store as Zustand Store + participant API as electronAPI + participant IPC as IPC Handler + participant AM as AgentManager + participant PM as ProcessManager + participant Py as Python Backend + participant Claude as Claude API + + User->>UI: Click "Start Task" + UI->>Store: updateTaskStatus('in_progress') + UI->>API: task.start(taskId) + API->>IPC: ipcRenderer.send('task:start') + + IPC->>IPC: Validate git repo + IPC->>IPC: Check authentication + IPC->>AM: startSpecCreation() or startTaskExecution() + + AM->>AM: Check auth profile + AM->>AM: Build command args + AM->>PM: spawnProcess(taskId, args, env) + + PM->>PM: Setup environment + PM->>Py: spawn(python, [script, ...args]) + + Note over PM,Py: NDJSON streaming begins + + Py->>Claude: Agent SDK call + Claude-->>Py: Response stream + Py-->>PM: stdout: {"phase": "planning", ...} + PM-->>AM: emit('execution-progress') + AM-->>IPC: Forward to renderer + IPC-->>Store: Update task state + Store-->>UI: Re-render with progress +``` + +### Process Spawning Details + +The AgentProcessManager handles all Python process lifecycle management: + +```mermaid +flowchart TB + subgraph Setup["Process Setup"] + Validate[Validate Paths] + Env[Build Environment] + Args[Construct Arguments] + end + + subgraph Spawn["Spawning"] + Python[Get Python Path] + Parse[Parse Command] + Create[Create Child Process] + end + + subgraph Management["Lifecycle Management"] + Track[Track in State] + Buffer[Buffer Output] + Parse2[Parse Phase Events] + Emit[Emit Progress] + end + + subgraph Cleanup["Cleanup"] + Kill[Kill Process] + RateLimit[Detect Rate Limit] + Auth[Detect Auth Failure] + Exit[Handle Exit] + end + + Setup --> Spawn + Spawn --> Management + Management --> Cleanup + + style Setup fill:#e8f5e9,stroke:#4caf50 + style Spawn fill:#e3f2fd,stroke:#1976d2 + style Management fill:#fff3e0,stroke:#f57c00 + style Cleanup fill:#fce4ec,stroke:#e91e63 +``` + +### Environment Configuration + +Process environment is built from multiple sources: + +```mermaid +flowchart LR + subgraph Sources["Environment Sources"] + System[process.env] + AutoBuild[.env file] + Profile[Claude Profile] + Project[Project Settings] + end + + subgraph Merge["Merge Process"] + Combine[getCombinedEnv] + Setup[setupProcessEnvironment] + end + + subgraph Final["Final Environment"] + Python[PYTHONUNBUFFERED=1] + Encoding[PYTHONIOENCODING=utf-8] + ProfileEnv[CLAUDE_* vars] + GraphitiUrl[GRAPHITI_MCP_URL] + end + + Sources --> Merge --> Final +``` + +| Variable | Source | Purpose | +|----------|--------|---------| +| `PYTHONUNBUFFERED` | Hardcoded | Real-time output streaming | +| `PYTHONIOENCODING` | Hardcoded | UTF-8 output encoding | +| `PYTHONUTF8` | Hardcoded | Force UTF-8 mode | +| `CLAUDE_*` | Profile Manager | API credentials, model config | +| `GRAPHITI_MCP_URL` | Project Settings | Memory integration | +| Custom vars | Auto-Claude .env | Provider keys, custom config | + +## Agent Event System + +The agent system uses EventEmitter patterns to propagate state changes through the application. + +### Event Flow Architecture + +```mermaid +sequenceDiagram + participant Py as Python Process + participant PM as ProcessManager + participant AM as AgentManager + participant Handler as Event Handler + participant IPC as IPC Bridge + participant Store as Zustand Store + participant UI as React Component + + Py->>PM: stdout: __EXEC_PHASE__:coding:message + PM->>PM: Parse phase event + PM->>AM: emit('execution-progress', data) + AM->>Handler: Forward event + Handler->>Handler: Map phase to status + Handler->>IPC: webContents.send('task:executionProgress') + IPC->>Store: on('executionProgress', update) + Store->>UI: Zustand selector trigger + UI->>UI: Re-render with new state +``` + +### Supported Events + +| Event | Source | Data | Purpose | +|-------|--------|------|---------| +| `log` | stdout/stderr | String | Raw process output | +| `execution-progress` | Phase parser | Phase, progress, subtask | UI progress tracking | +| `exit` | Process | Code, process type | Task completion/failure | +| `error` | Process/Runtime | Error message | Error display | +| `sdk-rate-limit` | Output parser | Rate limit info | Profile switching | +| `auth-failure` | Output parser | Auth details | Re-authentication prompt | +| `auto-swap-restart-task` | Rate limit handler | Task ID, new profile | Automatic retry | + +### Phase Protocol + +The Python backend emits structured phase events for UI synchronization: + +```mermaid +stateDiagram-v2 + [*] --> idle + idle --> planning: Start task + planning --> coding: Plan complete + coding --> qa_review: Code complete + qa_review --> qa_fixing: Issues found + qa_fixing --> qa_review: Fixes applied + qa_review --> complete: QA approved + coding --> failed: Error + qa_review --> failed: Critical error + complete --> [*] + failed --> [*] +``` + +Phase events are emitted as structured markers: + +``` +__EXEC_PHASE__:planning:Creating implementation plan... +__EXEC_PHASE__:coding:subtask-1-1:Implementing feature X +__EXEC_PHASE__:qa_review:Running QA review... +__EXEC_PHASE__:complete:Build completed successfully +``` + +## IPC Handler Architecture + +IPC handlers are organized into domain-specific modules for maintainability. + +### Handler Registration Flow + +```mermaid +flowchart TB + subgraph Setup["App Initialization"] + Main[main.ts] + Create[Create Managers] + Init[Initialize Services] + end + + subgraph Register["Handler Registration"] + SetupIPC[setupIpcHandlers] + Project[registerProjectHandlers] + Task[registerTaskHandlers] + Terminal[registerTerminalHandlers] + Agent[registerAgentEventsHandlers] + Settings[registerSettingsHandlers] + More[... 12 more modules] + end + + subgraph Managers["Shared Managers"] + AM[AgentManager] + TM[TerminalManager] + PM[PythonEnvManager] + Window[getMainWindow] + end + + Setup --> Register + Managers --> Register + + style Setup fill:#e8f5e9,stroke:#4caf50 + style Register fill:#e3f2fd,stroke:#1976d2 + style Managers fill:#fff3e0,stroke:#f57c00 +``` + +### Handler Module Structure + +Each handler module follows a consistent pattern: + +```typescript +export function registerDomainHandlers( + agentManager: AgentManager, + getMainWindow: () => BrowserWindow | null +): void { + // Request handlers (Promise-based) + ipcMain.handle(IPC_CHANNELS.DOMAIN_ACTION, async (_, ...args) => { + return { success: true, data: result }; + }); + + // Fire-and-forget handlers + ipcMain.on(IPC_CHANNELS.DOMAIN_START, (_, ...args) => { + agentManager.startProcess(...args); + }); + + // Event forwarding + agentManager.on('event', (data) => { + const mainWindow = getMainWindow(); + mainWindow?.webContents.send(IPC_CHANNELS.DOMAIN_EVENT, data); + }); +} +``` + +## Preload API Layer + +The preload scripts create a secure bridge between renderer and main processes. + +### API Structure + +```mermaid +flowchart TB + subgraph Preload["Preload Layer"] + Index[index.ts] + Create[createElectronAPI] + Expose[contextBridge.exposeInMainWorld] + end + + subgraph APIs["Domain APIs"] + TaskAPI[task-api.ts] + ProjectAPI[project-api.ts] + TerminalAPI[terminal-api.ts] + AgentAPI[agent-api.ts] + ModuleAPIs[modules/] + end + + subgraph Modules["Module APIs"] + GitHub[github-api.ts] + Roadmap[roadmap-api.ts] + Insights[insights-api.ts] + Changelog[changelog-api.ts] + Ideation[ideation-api.ts] + end + + Index --> Create + Create --> APIs + APIs --> Modules + Create --> Expose + + style Preload fill:#e8f5e9,stroke:#4caf50 + style APIs fill:#e3f2fd,stroke:#1976d2 + style Modules fill:#fff3e0,stroke:#f57c00 +``` + +### API Pattern + +```typescript +// preload/api/task-api.ts +export function createTaskAPI() { + return { + // Request methods (invoke) + list: (projectId: string) => + ipcRenderer.invoke(IPC_CHANNELS.TASK_LIST, projectId), + + // Fire-and-forget methods (send) + start: (taskId: string, options?: TaskStartOptions) => + ipcRenderer.send(IPC_CHANNELS.TASK_START, taskId, options), + + // Event subscriptions (on) + onProgress: (callback: (taskId: string, plan: Plan) => void) => { + const handler = (_: unknown, taskId: string, plan: Plan) => + callback(taskId, plan); + ipcRenderer.on(IPC_CHANNELS.TASK_PROGRESS, handler); + return () => ipcRenderer.removeListener(IPC_CHANNELS.TASK_PROGRESS, handler); + }, + }; +} +``` + +## Process Communication Protocol + +Communication between Electron main process and Python backend uses NDJSON (Newline-Delimited JSON) streaming over stdout/stderr. + +### Stream Processing + +```mermaid +sequenceDiagram + participant Py as Python Process + participant Buffer as Output Buffer + participant Parser as Line Parser + participant Phase as Phase Parser + participant Emit as Event Emitter + + loop Continuous Stream + Py->>Buffer: data chunk + Buffer->>Buffer: Append to buffer + Buffer->>Parser: Split by newlines + + loop Each complete line + Parser->>Parser: Trim whitespace + Parser->>Phase: Check for phase marker + alt Has __EXEC_PHASE__ + Phase->>Emit: emit('execution-progress') + end + Parser->>Emit: emit('log', line) + end + + Note over Buffer: Keep incomplete line in buffer + end +``` + +### Phase Event Parsing + +```mermaid +flowchart TB + subgraph Input["Input Processing"] + Log[Log Line] + Check[Check for Marker] + end + + subgraph Structured["Structured Events"] + Parse[parsePhaseEvent] + Extract[Extract phase, message, subtask] + end + + subgraph Fallback["Fallback Detection"] + Lower[Lowercase match] + Keywords[Keyword patterns] + end + + subgraph Validation["Validation"] + Regress[Check regression] + Terminal[Check terminal state] + end + + subgraph Output["Output"] + Return[Return phase update] + Null[Return null] + end + + Log --> Check + Check -->|Has marker| Structured + Check -->|No marker| Fallback + Structured --> Validation + Fallback --> Validation + Validation -->|Valid| Return + Validation -->|Invalid| Null + + style Input fill:#e8f5e9,stroke:#4caf50 + style Structured fill:#e3f2fd,stroke:#1976d2 + style Fallback fill:#fff3e0,stroke:#f57c00 + style Validation fill:#fce4ec,stroke:#e91e63 + style Output fill:#f3e5f5,stroke:#9c27b0 +``` + +## Rate Limit Handling + +The system includes sophisticated rate limit detection and automatic profile switching. + +### Rate Limit Flow + +```mermaid +sequenceDiagram + participant Py as Python Process + participant PM as ProcessManager + participant Detect as Rate Limit Detector + participant Profile as Profile Manager + participant AM as AgentManager + participant UI as React UI + + Py->>PM: Process exits (code != 0) + PM->>Detect: detectRateLimit(output) + + alt Rate Limit Detected + Detect->>Profile: Check auto-switch settings + + alt Auto-switch enabled + Profile->>Profile: getBestAvailableProfile() + + alt Alternative available + Profile->>Profile: setActiveProfile(newId) + Profile->>AM: emit('auto-swap-restart-task') + AM->>AM: restartTask(taskId, newProfileId) + AM->>UI: Notify swap occurred + else No alternative + Profile->>UI: Show rate limit modal + end + else Auto-switch disabled + Detect->>UI: Show rate limit modal + end + else No rate limit + PM->>Detect: detectAuthFailure(output) + + alt Auth failure + Detect->>UI: Show auth failure modal + else Other error + PM->>UI: Show error message + end + end +``` + +### Profile Switching State + +```mermaid +stateDiagram-v2 + [*] --> Running: Task started + Running --> RateLimited: Rate limit hit + + RateLimited --> CheckSettings: Detect rate limit + CheckSettings --> AutoSwap: Auto-switch enabled + CheckSettings --> ManualModal: Auto-switch disabled + + AutoSwap --> FindProfile: Check alternatives + FindProfile --> SwapAndRestart: Profile found + FindProfile --> ManualModal: No alternatives + + SwapAndRestart --> Running: Task restarted + ManualModal --> UserAction: User selects profile + UserAction --> Running: Retry with new profile + UserAction --> [*]: User cancels + + Running --> Complete: Task finishes + Complete --> [*] +``` + +## Terminal Integration + +The terminal system provides PTY-based interactive sessions with Claude Code integration. + +### Terminal Session Flow + +```mermaid +sequenceDiagram + participant UI as Terminal UI + participant API as electronAPI + participant TM as TerminalManager + participant PTY as node-pty + participant Shell as System Shell + participant Claude as Claude Code + + UI->>API: terminal.create(options) + API->>TM: Create PTY + TM->>PTY: spawn(shell, args, options) + PTY->>Shell: Start shell process + + UI->>API: terminal.invokeClaude(sessionId) + API->>TM: Inject Claude command + TM->>PTY: write('claude\\r') + PTY->>Shell: Execute command + Shell->>Claude: Start Claude Code + + loop Interactive Session + Claude->>PTY: Output + PTY->>TM: onData callback + TM->>UI: webContents.send('terminal:output') + + UI->>API: terminal.input(data) + API->>TM: Forward to PTY + TM->>PTY: write(data) + PTY->>Claude: User input + end +``` + +### Terminal Event Handling + +```mermaid +flowchart TB + subgraph Events["Terminal Events"] + Output[terminal:output] + Exit[terminal:exit] + Title[terminal:titleChange] + Session[terminal:claudeSession] + RateLimit[terminal:rateLimit] + OAuth[terminal:oauthToken] + end + + subgraph Handlers["Event Handlers"] + Display[Update display] + Cleanup[Cleanup session] + Tab[Update tab title] + Store[Store session ID] + Modal[Show rate limit modal] + Auth[Store OAuth token] + end + + Output --> Display + Exit --> Cleanup + Title --> Tab + Session --> Store + RateLimit --> Modal + OAuth --> Auth + + style Events fill:#e3f2fd,stroke:#1976d2 + style Handlers fill:#fff3e0,stroke:#f57c00 +``` + +## File Watcher Integration + +The file watcher monitors spec directories for implementation plan changes. + +### Watcher Flow + +```mermaid +sequenceDiagram + participant Task as Task Start + participant FW as FileWatcher + participant FS as File System + participant Handler as Change Handler + participant IPC as IPC Bridge + participant Store as Zustand Store + + Task->>FW: watch(taskId, specDir) + FW->>FS: chokidar.watch(planPath) + + loop File Changes + FS->>FW: 'change' event + FW->>Handler: Read and parse JSON + Handler->>Handler: Validate plan structure + Handler->>FW: emit('progress', plan) + FW->>IPC: webContents.send('task:progress') + IPC->>Store: Update task subtasks + end + + Task->>FW: unwatch(taskId) + FW->>FS: Stop watching +``` + +## Error Handling Patterns + +### Error Propagation + +```mermaid +flowchart TB + subgraph Sources["Error Sources"] + Process[Process Error] + Parse[Parse Error] + IPC[IPC Error] + Auth[Auth Error] + RateLimit[Rate Limit] + end + + subgraph Handling["Error Handling"] + Detect[Error Detection] + Classify[Error Classification] + Format[Format Error] + end + + subgraph Response["Response Actions"] + Emit[Emit to UI] + Retry[Automatic Retry] + Modal[Show Modal] + Log[Console Log] + end + + Sources --> Handling + Handling --> Response + + style Sources fill:#fce4ec,stroke:#e91e63 + style Handling fill:#fff3e0,stroke:#f57c00 + style Response fill:#e3f2fd,stroke:#1976d2 +``` + +### Error Response Patterns + +| Error Type | Detection | Response | +|------------|-----------|----------| +| **Rate Limit** | Output pattern matching | Auto-swap or modal | +| **Auth Failure** | Output pattern matching | Auth modal | +| **Process Crash** | Exit code != 0 | Error notification | +| **IPC Timeout** | Promise rejection | Error toast | +| **Parse Error** | JSON.parse failure | Fallback handling | + +## Security Considerations + +### Context Isolation + +```mermaid +flowchart TB + subgraph Renderer["Renderer Process"] + React[React App] + API[window.electronAPI] + end + + subgraph Preload["Preload Script"] + Bridge[contextBridge] + Sanitize[Input Sanitization] + end + + subgraph Main["Main Process"] + Validate[Validation Layer] + Handlers[IPC Handlers] + Core[Core Logic] + end + + React -->|"Limited API"| API + API -->|"Secure Bridge"| Bridge + Bridge -->|"Validated Input"| Validate + Validate --> Handlers + Handlers --> Core + + style Renderer fill:#fce4ec,stroke:#e91e63 + style Preload fill:#fff3e0,stroke:#f57c00 + style Main fill:#e8f5e9,stroke:#4caf50 +``` + +### Security Layers + +| Layer | Protection | +|-------|------------| +| **Context Isolation** | Renderer cannot access Node.js APIs | +| **Preload Bridge** | Only exposed APIs available to renderer | +| **Input Validation** | All IPC inputs validated before processing | +| **Path Sanitization** | Python paths validated before spawning | +| **Credential Isolation** | OAuth tokens stored securely by profile | + +## Performance Optimizations + +### Streaming Efficiency + +- **Buffered Output**: Lines buffered until complete before processing +- **Sequence Numbers**: Events ordered by sequence for consistent UI updates +- **Debounced Updates**: File watcher debounces rapid changes +- **Lazy Parsing**: Phase events parsed only when markers detected + +### Resource Management + +- **Process Tracking**: All spawned processes tracked for cleanup +- **Event Cleanup**: IPC listeners removed on component unmount +- **Watcher Cleanup**: File watchers stopped when tasks complete +- **Memory Limits**: Output buffers limited to prevent memory leaks + +## Next Steps + +- [Architecture Overview](./overview.md) - High-level system architecture +- [Backend Architecture](./backend.md) - Python agent system details +- [Frontend Architecture](./frontend.md) - Electron application structure From 5c961f8d0ced13176806faea4ec61e20e9bc67f0 Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 21:44:35 +0200 Subject: [PATCH 09/27] auto-claude: subtask-3-1 - Create agents module documentation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add comprehensive documentation for the agents module covering: - base.py: Shared constants and configuration - session.py: Session execution and post-processing - memory_manager.py: Dual-layer memory system (Graphiti + file-based) - coder.py: Main autonomous agent loop - planner.py: Follow-up planner for completed specs - utils.py: Git and plan management utilities Includes 15+ Mermaid diagrams: - Class diagrams showing module relationships - Flowcharts for agent loops and memory flows - Sequence diagrams for session processing - Architecture overviews 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/components/backend/agents.md | 925 ++++++++++++++++++++++++++++++ 1 file changed, 925 insertions(+) create mode 100644 docs/components/backend/agents.md diff --git a/docs/components/backend/agents.md b/docs/components/backend/agents.md new file mode 100644 index 0000000000..ebdb34055a --- /dev/null +++ b/docs/components/backend/agents.md @@ -0,0 +1,925 @@ +# Agents Module + +The agents module is the core of Auto-Claude's autonomous coding system. It provides a modular architecture for running AI-powered coding agents that implement tasks defined in implementation plans. + +## Module Overview + +The agents module is organized into focused submodules with clear responsibilities: + +```mermaid +flowchart TB + subgraph Public["Public API (__init__.py)"] + RunAgent[run_autonomous_agent] + RunPlanner[run_followup_planner] + MemAPI[Memory Functions] + SessionAPI[Session Functions] + UtilsAPI[Utility Functions] + end + + subgraph Internal["Internal Modules"] + Base[base.py] + Coder[coder.py] + Planner[planner.py] + Session[session.py] + MemMgr[memory_manager.py] + Utils[utils.py] + end + + Public --> Internal + + style Public fill:#e3f2fd,stroke:#1976d2 + style Internal fill:#fff3e0,stroke:#f57c00 +``` + +## Module Structure + +``` +apps/backend/agents/ +├── __init__.py # Public API with lazy imports +├── base.py # Shared constants and configuration +├── coder.py # Main autonomous agent loop +├── planner.py # Follow-up planner for completed specs +├── session.py # Session execution and post-processing +├── memory_manager.py # Dual-layer memory system +└── utils.py # Git and plan management utilities +``` + +## Class Diagram + +```mermaid +classDiagram + class AgentsModule { + <> + +run_autonomous_agent() + +run_followup_planner() + +save_session_memory() + +get_graphiti_context() + +post_session_processing() + +run_agent_session() + } + + class BaseModule { + <> + +AUTO_CONTINUE_DELAY_SECONDS: int + +HUMAN_INTERVENTION_FILE: str + +logger: Logger + } + + class CoderAgent { + +run_autonomous_agent(project_dir, spec_dir, model, max_iterations, verbose, source_spec_dir) + -recovery_manager: RecoveryManager + -status_manager: StatusManager + -task_logger: TaskLogger + -_handle_session_result() + -_process_planning_phase() + -_process_coding_phase() + } + + class PlannerAgent { + +run_followup_planner(project_dir, spec_dir, model, verbose) bool + -status_manager: StatusManager + -task_logger: TaskLogger + -_validate_plan_update() + } + + class SessionManager { + +run_agent_session(client, message, spec_dir, verbose, phase) tuple + +post_session_processing(spec_dir, project_dir, subtask_id, session_num, ...) bool + -_stream_response() + -_handle_tool_use() + -_log_tool_result() + } + + class MemoryManager { + +debug_memory_system_status() void + +get_graphiti_context(spec_dir, project_dir, subtask) str + +save_session_memory(spec_dir, project_dir, subtask_id, session_num, success, subtasks_completed, discoveries) tuple + +save_session_to_graphiti() bool + -_build_insights_structure() + -_try_graphiti_save() + -_fallback_to_file() + } + + class UtilsModule { + +get_latest_commit(project_dir) str + +get_commit_count(project_dir) int + +load_implementation_plan(spec_dir) dict + +find_subtask_in_plan(plan, subtask_id) dict + +find_phase_for_subtask(plan, subtask_id) dict + +sync_plan_to_source(spec_dir, source_spec_dir) bool + } + + AgentsModule --> BaseModule : uses constants + AgentsModule --> CoderAgent : exposes + AgentsModule --> PlannerAgent : exposes + AgentsModule --> SessionManager : exposes + AgentsModule --> MemoryManager : exposes + AgentsModule --> UtilsModule : exposes + CoderAgent --> SessionManager : uses + CoderAgent --> MemoryManager : uses + CoderAgent --> UtilsModule : uses + PlannerAgent --> SessionManager : uses + SessionManager --> MemoryManager : saves to + SessionManager --> UtilsModule : uses +``` + +## Base Module + +The `base.py` module provides shared constants and configuration used across all agent modules. + +### Constants + +| Constant | Value | Description | +|----------|-------|-------------| +| `AUTO_CONTINUE_DELAY_SECONDS` | `3` | Delay between automatic session continuations | +| `HUMAN_INTERVENTION_FILE` | `"PAUSE"` | Filename that triggers agent pause | + +### Usage Pattern + +```python +from .base import AUTO_CONTINUE_DELAY_SECONDS, HUMAN_INTERVENTION_FILE + +# Check for human intervention +pause_file = spec_dir / HUMAN_INTERVENTION_FILE +if pause_file.exists(): + # Handle pause request + pass + +# Auto-continue delay +await asyncio.sleep(AUTO_CONTINUE_DELAY_SECONDS) +``` + +## Coder Agent + +The coder agent (`coder.py`) implements the main autonomous coding loop that processes implementation plans and executes subtasks. + +### Architecture + +```mermaid +flowchart TB + subgraph Init["Initialization"] + Recovery[Create RecoveryManager] + Status[Create StatusManager] + Logger[Create TaskLogger] + Memory[Debug Memory Status] + end + + subgraph CheckPhase["Phase Detection"] + FirstRun{First Run?} + Planning[Planning Phase] + Coding[Coding Phase] + end + + subgraph MainLoop["Main Loop"] + CheckPause[Check PAUSE File] + CheckIter[Check Max Iterations] + GetSubtask[Get Next Subtask] + GenPrompt[Generate Prompt] + RunSession[Run Agent Session] + PostProcess[Post-Session Processing] + end + + subgraph HandleResult["Result Handling"] + Complete[Build Complete] + Continue[Continue to Next] + Error[Handle Error] + Stuck[Mark as Stuck] + end + + Init --> CheckPhase + FirstRun -->|Yes| Planning + FirstRun -->|No| Coding + Planning --> MainLoop + Coding --> MainLoop + CheckPause --> CheckIter + CheckIter --> GetSubtask + GetSubtask --> GenPrompt + GenPrompt --> RunSession + RunSession --> PostProcess + PostProcess --> HandleResult + Continue --> CheckPause + Error --> CheckPause + + style Init fill:#e8f5e9,stroke:#4caf50 + style MainLoop fill:#e3f2fd,stroke:#1976d2 + style HandleResult fill:#fff3e0,stroke:#f57c00 +``` + +### Function Signature + +```python +async def run_autonomous_agent( + project_dir: Path, + spec_dir: Path, + model: str, + max_iterations: int | None = None, + verbose: bool = False, + source_spec_dir: Path | None = None, +) -> None +``` + +### Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| `project_dir` | `Path` | Root directory for the project | +| `spec_dir` | `Path` | Directory containing the spec (`.auto-claude/specs/001-name/`) | +| `model` | `str` | Claude model to use (e.g., `"claude-sonnet-4-20250514"`) | +| `max_iterations` | `int \| None` | Maximum session iterations (None for unlimited) | +| `verbose` | `bool` | Whether to show detailed tool output | +| `source_spec_dir` | `Path \| None` | Original spec directory for worktree sync | + +### Key Features + +1. **Planning Phase Detection**: Automatically detects first run and initiates planning +2. **Recovery Management**: Tracks attempts and provides recovery hints +3. **Status Updates**: Maintains real-time status for UI display +4. **Linear Integration**: Updates Linear tasks when enabled +5. **Graphiti Context**: Retrieves relevant memory context for each subtask + +### Session Flow Sequence + +```mermaid +sequenceDiagram + participant Main as run_autonomous_agent + participant Check as Pre-Checks + participant Prompt as Prompt Generator + participant Client as Claude SDK + participant Session as run_agent_session + participant Post as post_session_processing + participant Memory as MemoryManager + + Main->>Check: Check PAUSE file + Check->>Check: Get next subtask + Check->>Prompt: Generate subtask prompt + Prompt->>Prompt: Load file context + Prompt->>Memory: Get Graphiti context + Memory-->>Prompt: Memory context (if available) + Prompt-->>Main: Complete prompt + Main->>Client: Create client + Main->>Session: Run session + Session->>Client: Execute with SDK + Client-->>Session: Response stream + Session-->>Main: (status, response) + Main->>Post: Process session results + Post->>Memory: Save session insights + Post-->>Main: success/failure + + alt status == "complete" + Main->>Main: Print banner, exit + else status == "continue" + Main->>Main: Sleep, continue loop + else status == "error" + Main->>Main: Log error, retry + end +``` + +## Planner Agent + +The planner agent (`planner.py`) handles follow-up planning sessions for adding new subtasks to completed specs. + +### Architecture + +```mermaid +flowchart LR + subgraph Input + Request[FOLLOWUP_REQUEST.md] + ExistingPlan[Existing Plan] + end + + subgraph Processing + StatusMgr[Initialize StatusManager] + Client[Create Claude Client] + Prompt[Generate Planner Prompt] + Session[Run Planning Session] + end + + subgraph Validation + CheckPlan{Plan Updated?} + CheckPending{Has Pending?} + ResetStatus[Reset Plan Status] + end + + subgraph Output + Success[Return True] + Failure[Return False] + end + + Input --> Processing + Processing --> Validation + CheckPlan -->|Yes| CheckPending + CheckPlan -->|No| Failure + CheckPending -->|Yes| ResetStatus + CheckPending -->|No| Failure + ResetStatus --> Success + + style Processing fill:#e3f2fd,stroke:#1976d2 + style Validation fill:#fff3e0,stroke:#f57c00 +``` + +### Function Signature + +```python +async def run_followup_planner( + project_dir: Path, + spec_dir: Path, + model: str, + verbose: bool = False, +) -> bool +``` + +### Parameters + +| Parameter | Type | Description | +|-----------|------|-------------| +| `project_dir` | `Path` | Root directory for the project | +| `spec_dir` | `Path` | Directory containing the completed spec | +| `model` | `str` | Claude model to use | +| `verbose` | `bool` | Whether to show detailed output | + +### Key Behaviors + +1. **Single Session**: Runs one planning session (doesn't enter coding loop) +2. **Plan Validation**: Verifies new subtasks were added +3. **Status Reset**: Automatically resets plan status to `in_progress` +4. **Error Handling**: Provides clear feedback on planning failures + +## Session Manager + +The session module (`session.py`) handles running agent sessions and post-session processing. + +### Class Diagram + +```mermaid +classDiagram + class SessionManager { + <> + +run_agent_session(client, message, spec_dir, verbose, phase) tuple~str,str~ + +post_session_processing(spec_dir, project_dir, subtask_id, ...) bool + } + + class ClaudeSDKClient { + +query(message) + +receive_response() AsyncIterator + } + + class RecoveryManager { + +record_attempt(subtask_id, session, success, approach, error) + +record_good_commit(commit_hash, subtask_id) + +get_attempt_count(subtask_id) int + } + + class TaskLogger { + +log(text, type, phase) + +tool_start(name, input, phase) + +tool_end(name, success, result, detail, phase) + +log_error(error, phase) + } + + class StatusManager { + +update_subtasks(completed, total, in_progress) + } + + SessionManager --> ClaudeSDKClient : executes with + SessionManager --> RecoveryManager : records attempts + SessionManager --> TaskLogger : logs activity + SessionManager --> StatusManager : updates status +``` + +### run_agent_session + +Runs a single agent session using the Claude Agent SDK. + +```python +async def run_agent_session( + client: ClaudeSDKClient, + message: str, + spec_dir: Path, + verbose: bool = False, + phase: LogPhase = LogPhase.CODING, +) -> tuple[str, str] +``` + +#### Response Stream Handling + +```mermaid +flowchart TB + subgraph Input + Query[Send Query] + end + + subgraph Stream["Response Stream"] + Receive[Receive Message] + CheckType{Message Type?} + end + + subgraph AssistantMsg["AssistantMessage"] + TextBlock[TextBlock - Print text] + ToolBlock[ToolUseBlock - Log tool] + end + + subgraph UserMsg["UserMessage"] + ToolResult[ToolResultBlock] + CheckBlocked{Blocked?} + CheckError{Error?} + LogSuccess[Log Success] + LogError[Log Error] + LogBlocked[Log Blocked] + end + + subgraph Output + CheckComplete{Build Complete?} + ReturnComplete[Return "complete"] + ReturnContinue[Return "continue"] + ReturnError[Return "error"] + end + + Query --> Receive + Receive --> CheckType + CheckType -->|AssistantMessage| TextBlock + CheckType -->|AssistantMessage| ToolBlock + CheckType -->|UserMessage| ToolResult + ToolResult --> CheckBlocked + CheckBlocked -->|Yes| LogBlocked + CheckBlocked -->|No| CheckError + CheckError -->|Yes| LogError + CheckError -->|No| LogSuccess + + TextBlock --> Receive + ToolBlock --> Receive + LogSuccess --> Receive + LogError --> Receive + LogBlocked --> Receive + + Receive -->|Stream End| CheckComplete + CheckComplete -->|Yes| ReturnComplete + CheckComplete -->|No| ReturnContinue + + style Stream fill:#e3f2fd,stroke:#1976d2 + style AssistantMsg fill:#e8f5e9,stroke:#4caf50 + style UserMsg fill:#fff3e0,stroke:#f57c00 +``` + +### post_session_processing + +Processes session results and updates memory automatically. + +```python +async def post_session_processing( + spec_dir: Path, + project_dir: Path, + subtask_id: str, + session_num: int, + commit_before: str | None, + commit_count_before: int, + recovery_manager: RecoveryManager, + linear_enabled: bool = False, + status_manager: StatusManager | None = None, + source_spec_dir: Path | None = None, +) -> bool +``` + +#### Post-Processing Flow + +```mermaid +flowchart TB + Start[Post-Session Start] + Sync[Sync Plan to Source] + LoadPlan[Load Implementation Plan] + FindSubtask[Find Subtask in Plan] + CheckCommits[Check for New Commits] + + CheckStatus{Subtask Status?} + + subgraph Completed["Status: completed"] + RecordSuccess[Record Successful Attempt] + RecordCommit[Record Good Commit] + NotifyLinear[Update Linear] + ExtractInsights[Extract Session Insights] + SaveMemory[Save to Memory] + end + + subgraph InProgress["Status: in_progress"] + RecordPartial[Record Partial Attempt] + SavePartialCommit[Save Partial Commit] + NotifyLinearFail[Notify Linear of Failure] + ExtractPartialInsights[Extract Insights] + end + + subgraph Failed["Status: pending/failed"] + RecordFailed[Record Failed Attempt] + NotifyLinearError[Notify Linear of Error] + end + + Start --> Sync + Sync --> LoadPlan + LoadPlan --> FindSubtask + FindSubtask --> CheckCommits + CheckCommits --> CheckStatus + CheckStatus -->|completed| Completed + CheckStatus -->|in_progress| InProgress + CheckStatus -->|other| Failed + + Completed --> ReturnTrue[Return True] + InProgress --> ReturnFalse[Return False] + Failed --> ReturnFalse + + style Completed fill:#e8f5e9,stroke:#4caf50 + style InProgress fill:#fff3e0,stroke:#f57c00 + style Failed fill:#ffebee,stroke:#f44336 +``` + +## Memory Manager + +The memory manager (`memory_manager.py`) implements a dual-layer memory system for session persistence. + +### Memory Architecture + +```mermaid +flowchart TB + subgraph Primary["PRIMARY: Graphiti"] + G1[Semantic Search] + G2[Knowledge Graph] + G3[Cross-Session Context] + G4[Entity Extraction] + end + + subgraph Fallback["FALLBACK: File-based"] + F1[JSON Files] + F2[session_insights/] + F3[Zero Dependencies] + F4[Always Available] + end + + Session[Session Complete] --> Check{Graphiti Enabled?} + Check -->|Yes| TryGraphiti[Try Graphiti Save] + TryGraphiti --> Success{Success?} + Success -->|Yes| Done[Done - graphiti] + Success -->|No| UseFallback[Use Fallback] + Check -->|No| UseFallback + UseFallback --> Fallback + Fallback --> DoneFallback[Done - file] + + style Primary fill:#e3f2fd,stroke:#1976d2 + style Fallback fill:#fff3e0,stroke:#f57c00 +``` + +### Function: debug_memory_system_status + +Prints memory system status for debugging (when `DEBUG=true`). + +```python +def debug_memory_system_status() -> None +``` + +### Function: get_graphiti_context + +Retrieves relevant context from Graphiti for the current subtask. + +```python +async def get_graphiti_context( + spec_dir: Path, + project_dir: Path, + subtask: dict, +) -> str | None +``` + +#### Context Retrieval Flow + +```mermaid +sequenceDiagram + participant Caller + participant GetContext as get_graphiti_context + participant GraphitiMem as GraphitiMemory + participant Format as Formatter + + Caller->>GetContext: subtask data + GetContext->>GetContext: Check Graphiti enabled + alt Not Enabled + GetContext-->>Caller: None + end + GetContext->>GraphitiMem: Create instance + GetContext->>GetContext: Build search query + GetContext->>GraphitiMem: get_relevant_context(query) + GraphitiMem-->>GetContext: context_items + GetContext->>GraphitiMem: get_session_history(limit=3) + GraphitiMem-->>GetContext: session_history + GetContext->>GraphitiMem: close() + GetContext->>Format: Format sections + Format-->>GetContext: Markdown string + GetContext-->>Caller: Formatted context +``` + +### Function: save_session_memory + +Saves session insights using the dual-layer approach. + +```python +async def save_session_memory( + spec_dir: Path, + project_dir: Path, + subtask_id: str, + session_num: int, + success: bool, + subtasks_completed: list[str], + discoveries: dict | None = None, +) -> tuple[bool, str] +``` + +#### Return Values + +| Storage Type | Description | +|--------------|-------------| +| `("graphiti", True)` | Successfully saved to Graphiti | +| `("file", True)` | Successfully saved to file-based storage | +| `("none", False)` | Both storage methods failed | + +### Insights Structure + +```mermaid +classDiagram + class SessionInsights { + +subtasks_completed: List~str~ + +discoveries: Discoveries + +what_worked: List~str~ + +what_failed: List~str~ + +recommendations_for_next_session: List~str~ + } + + class Discoveries { + +files_understood: Dict~str,str~ + +patterns_found: List~str~ + +gotchas_encountered: List~str~ + +file_insights: List~FileInsight~ + } + + class FileInsight { + +file_path: str + +description: str + +category: str + } + + SessionInsights --> Discoveries + Discoveries --> FileInsight +``` + +## Utils Module + +The utils module (`utils.py`) provides helper functions for git operations and plan management. + +### Function Overview + +```mermaid +flowchart LR + subgraph Git["Git Operations"] + GetCommit[get_latest_commit] + GetCount[get_commit_count] + end + + subgraph Plan["Plan Management"] + LoadPlan[load_implementation_plan] + FindSubtask[find_subtask_in_plan] + FindPhase[find_phase_for_subtask] + end + + subgraph Sync["Sync Operations"] + SyncPlan[sync_plan_to_source] + end + + Git --> Project[Project Directory] + Plan --> SpecDir[Spec Directory] + Sync --> Both[Both Directories] + + style Git fill:#e3f2fd,stroke:#1976d2 + style Plan fill:#e8f5e9,stroke:#4caf50 + style Sync fill:#fff3e0,stroke:#f57c00 +``` + +### Git Operations + +#### get_latest_commit + +```python +def get_latest_commit(project_dir: Path) -> str | None +``` + +Returns the hash of the latest git commit, or `None` if unavailable. + +#### get_commit_count + +```python +def get_commit_count(project_dir: Path) -> int +``` + +Returns the total number of commits in the repository. + +### Plan Management + +#### load_implementation_plan + +```python +def load_implementation_plan(spec_dir: Path) -> dict | None +``` + +Loads and parses the `implementation_plan.json` file. + +#### find_subtask_in_plan + +```python +def find_subtask_in_plan(plan: dict, subtask_id: str) -> dict | None +``` + +Finds a subtask by ID in the plan, searching all phases. + +#### find_phase_for_subtask + +```python +def find_phase_for_subtask(plan: dict, subtask_id: str) -> dict | None +``` + +Returns the phase containing the specified subtask. + +### Sync Operations + +#### sync_plan_to_source + +```python +def sync_plan_to_source(spec_dir: Path, source_spec_dir: Path | None) -> bool +``` + +Syncs `implementation_plan.json` from worktree back to main project. + +```mermaid +flowchart LR + Check{Source Specified?} + Check -->|No| ReturnFalse[Return False] + Check -->|Yes| ComparePaths{Same Path?} + ComparePaths -->|Yes| ReturnFalse + ComparePaths -->|No| CheckExists{Plan Exists?} + CheckExists -->|No| ReturnFalse + CheckExists -->|Yes| CopyFile[Copy to Source] + CopyFile --> ReturnTrue[Return True] + + style ReturnTrue fill:#e8f5e9,stroke:#4caf50 + style ReturnFalse fill:#ffebee,stroke:#f44336 +``` + +## Lazy Import Pattern + +The `__init__.py` uses Python's `__getattr__` for lazy imports to avoid circular dependencies: + +```mermaid +flowchart TB + Import[Import agents.function] + GetAttr["__getattr__(name)"] + + subgraph Checks["Name Routing"] + CheckConstants{Constants?} + CheckCoder{Coder?} + CheckMemory{Memory?} + CheckPlanner{Planner?} + CheckSession{Session?} + CheckUtils{Utils?} + end + + subgraph Imports["Lazy Imports"] + ImportBase[from .base import ...] + ImportCoder[from .coder import ...] + ImportMemory[from .memory_manager import ...] + ImportPlanner[from .planner import ...] + ImportSession[from .session import ...] + ImportUtils[from .utils import ...] + end + + Import --> GetAttr + GetAttr --> Checks + CheckConstants -->|Yes| ImportBase + CheckCoder -->|Yes| ImportCoder + CheckMemory -->|Yes| ImportMemory + CheckPlanner -->|Yes| ImportPlanner + CheckSession -->|Yes| ImportSession + CheckUtils -->|Yes| ImportUtils + + style Checks fill:#e3f2fd,stroke:#1976d2 + style Imports fill:#e8f5e9,stroke:#4caf50 +``` + +### Exported API + +| Category | Functions | +|----------|-----------| +| **Main API** | `run_autonomous_agent`, `run_followup_planner` | +| **Memory** | `debug_memory_system_status`, `get_graphiti_context`, `save_session_memory`, `save_session_to_graphiti` | +| **Session** | `run_agent_session`, `post_session_processing` | +| **Utils** | `get_latest_commit`, `get_commit_count`, `load_implementation_plan`, `find_subtask_in_plan`, `find_phase_for_subtask`, `sync_plan_to_source` | +| **Constants** | `AUTO_CONTINUE_DELAY_SECONDS`, `HUMAN_INTERVENTION_FILE` | + +## Integration Points + +### External Dependencies + +```mermaid +flowchart LR + Agents[Agents Module] + + subgraph External["External Services"] + Claude[Claude Agent SDK] + Linear[Linear API] + Graphiti[Graphiti Memory] + end + + subgraph Internal["Internal Modules"] + Core[core/client] + Recovery[recovery] + Progress[progress] + Prompts[prompts] + UI[ui] + end + + Agents <-->|Execute| Claude + Agents <-->|Track| Linear + Agents <-->|Remember| Graphiti + Agents --> Core + Agents --> Recovery + Agents --> Progress + Agents --> Prompts + Agents --> UI + + style External fill:#fce4ec,stroke:#e91e63 + style Internal fill:#e8f5e9,stroke:#4caf50 +``` + +### Key Dependencies + +| Module | Purpose | +|--------|---------| +| `claude_agent_sdk` | AI agent execution | +| `linear_updater` | Task progress tracking | +| `graphiti_memory` | Cross-session memory | +| `recovery` | Attempt tracking and rollback | +| `progress` | Build status tracking | +| `prompt_generator` | Dynamic prompt creation | +| `ui` | Status display and formatting | + +## Error Handling + +### Recovery Strategy + +```mermaid +flowchart TB + Attempt[Session Attempt] + CheckSuccess{Success?} + + subgraph Success["On Success"] + RecordGood[Record Good Commit] + SaveInsights[Save Session Insights] + UpdateLinear[Update Linear Progress] + end + + subgraph Failure["On Failure"] + RecordFailed[Record Failed Attempt] + CheckAttempts{Attempts >= 3?} + GetHints[Get Recovery Hints] + MarkStuck[Mark as Stuck] + NotifyStuck[Notify Linear - Stuck] + end + + Attempt --> CheckSuccess + CheckSuccess -->|Yes| Success + CheckSuccess -->|No| Failure + RecordFailed --> CheckAttempts + CheckAttempts -->|No| GetHints + GetHints --> Retry[Retry with Context] + Retry --> Attempt + CheckAttempts -->|Yes| MarkStuck + MarkStuck --> NotifyStuck + NotifyStuck --> Manual[Require Manual Intervention] + + style Success fill:#e8f5e9,stroke:#4caf50 + style Failure fill:#ffebee,stroke:#f44336 +``` + +### Error States + +| State | Trigger | Action | +|-------|---------|--------| +| **continue** | Session completed normally | Auto-continue to next subtask | +| **complete** | All subtasks done | Print banner, exit loop | +| **error** | Exception during session | Log error, retry with fresh session | +| **stuck** | 3+ failed attempts | Mark subtask as stuck, notify user | + +## Performance Considerations + +| Aspect | Implementation | +|--------|----------------| +| **Lazy Imports** | `__getattr__` pattern avoids loading unused modules | +| **Streaming Output** | Real-time display of agent responses | +| **Memory Fallback** | File-based storage when Graphiti unavailable | +| **Worktree Sync** | Efficient plan synchronization for isolated builds | + +## Next Steps + +- [Session Module](./session.md) - Detailed session management documentation +- [Memory System](./memory.md) - Memory architecture deep dive +- [Recovery Module](./recovery.md) - Error recovery and rollback +- [Custom Tools](./tools.md) - MCP tools for agent operations From 81a0976ea3ec656c093b69ef33e8f15d747b5ee9 Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 21:49:58 +0200 Subject: [PATCH 10/27] auto-claude: subtask-3-2 - Create analysis module documentation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added comprehensive documentation for the analysis module covering: - ProjectAnalyzer: Full project analysis with monorepo detection - ServiceAnalyzer: Individual service analysis with deep context - RiskClassifier: Risk assessment and validation recommendations - SecurityScanner: Secrets detection, SAST, and dependency audits - InsightExtractor: Session insight extraction for Graphiti memory - CIDiscovery: CI/CD configuration parsing - TestDiscovery: Test framework detection Includes 15+ Mermaid diagrams (flowcharts, class diagrams, sequence diagrams) showing architecture, data flow, and integration points. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/components/backend/analysis.md | 1147 +++++++++++++++++++++++++++ 1 file changed, 1147 insertions(+) create mode 100644 docs/components/backend/analysis.md diff --git a/docs/components/backend/analysis.md b/docs/components/backend/analysis.md new file mode 100644 index 0000000000..b6b6b7e182 --- /dev/null +++ b/docs/components/backend/analysis.md @@ -0,0 +1,1147 @@ +# Analysis Module + +The analysis module provides comprehensive code analysis, project scanning, and risk assessment capabilities for Auto-Claude. It automatically detects project structure, frameworks, services, and potential security issues. + +## Module Overview + +The analysis module is organized into focused submodules with clear responsibilities: + +```mermaid +flowchart TB + subgraph Public["Public API (__init__.py)"] + ProjectAnalyzer[ProjectAnalyzer] + ServiceAnalyzer[ServiceAnalyzer] + RiskClassifier[RiskClassifier] + SecurityScanner[SecurityScanner] + CIDiscovery[CIDiscovery] + TestDiscovery[TestDiscovery] + end + + subgraph Analyzers["Analyzers Subpackage"] + Base[base.py] + FrameworkAnalyzer[framework_analyzer.py] + RouteDetector[route_detector.py] + DatabaseDetector[database_detector.py] + ContextAnalyzer[context_analyzer.py] + end + + subgraph Scanners["Scanning Modules"] + InsightExtractor[insight_extractor.py] + SecScan[security_scanner.py] + RiskClass[risk_classifier.py] + end + + Public --> Analyzers + Public --> Scanners + + style Public fill:#e3f2fd,stroke:#1976d2 + style Analyzers fill:#fff3e0,stroke:#f57c00 + style Scanners fill:#e8f5e9,stroke:#4caf50 +``` + +## Module Structure + +``` +apps/backend/analysis/ +├── __init__.py # Public API exports +├── analyzer.py # Facade to modular analyzer system +├── project_analyzer.py # Security profile analyzer +├── risk_classifier.py # Risk assessment from complexity analysis +├── security_scanner.py # Consolidated security scanning +├── insight_extractor.py # Session insight extraction +├── ci_discovery.py # CI/CD configuration parsing +├── test_discovery.py # Test framework detection +└── analyzers/ # Modular analyzer subpackage + ├── __init__.py # Subpackage exports + ├── base.py # Base analyzer and constants + ├── project_analyzer_module.py # Project analysis + ├── service_analyzer.py # Service analysis + ├── framework_analyzer.py # Framework detection + ├── route_detector.py # API route detection + ├── database_detector.py # Database model detection + ├── context_analyzer.py # Context extraction + ├── port_detector.py # Port detection + └── context/ # Context-specific detectors + ├── api_docs_detector.py + ├── auth_detector.py + ├── env_detector.py + ├── jobs_detector.py + ├── migrations_detector.py + ├── monitoring_detector.py + └── services_detector.py +``` + +## Class Diagram + +```mermaid +classDiagram + class AnalysisModule { + <> + +ProjectAnalyzer + +ModularProjectAnalyzer + +ServiceAnalyzer + +RiskClassifier + +SecurityScanner + +CIDiscovery + +TestDiscovery + } + + class ProjectAnalyzer { + -project_dir: Path + -index: dict + +analyze() dict + -_detect_project_type() + -_find_and_analyze_services() + -_analyze_infrastructure() + -_detect_conventions() + -_map_dependencies() + } + + class ServiceAnalyzer { + -path: Path + -name: str + -analysis: dict + +analyze() dict + -_detect_language_and_framework() + -_detect_service_type() + -_find_key_directories() + -_find_entry_points() + -_detect_dependencies() + } + + class RiskClassifier { + -_cache: dict + +load_assessment(spec_dir) RiskAssessment + +should_skip_validation(spec_dir) bool + +get_required_test_types(spec_dir) list + +requires_security_scan(spec_dir) bool + +get_risk_level(spec_dir) str + +get_validation_summary(spec_dir) dict + } + + class SecurityScanner { + -_bandit_available: bool + -_npm_available: bool + +scan(project_dir, spec_dir, ...) SecurityScanResult + -_run_secrets_scan() + -_run_sast_scans() + -_run_dependency_audits() + -_run_bandit() + -_run_npm_audit() + } + + class CIDiscovery { + -_cache: dict + +discover(project_dir) CIConfig + -_parse_github_actions() + -_parse_gitlab_ci() + -_parse_circleci() + -_parse_jenkinsfile() + } + + class TestDiscovery { + -_cache: dict + +discover(project_dir) TestDiscoveryResult + -_detect_package_manager() + -_discover_js_frameworks() + -_discover_python_frameworks() + } + + AnalysisModule --> ProjectAnalyzer : exports + AnalysisModule --> ServiceAnalyzer : exports + AnalysisModule --> RiskClassifier : exports + AnalysisModule --> SecurityScanner : exports + AnalysisModule --> CIDiscovery : exports + AnalysisModule --> TestDiscovery : exports + ProjectAnalyzer --> ServiceAnalyzer : uses +``` + +## Project Analyzer + +The `ProjectAnalyzer` class analyzes entire projects, detecting monorepo structures, services, infrastructure, and conventions. + +### Architecture + +```mermaid +flowchart TB + subgraph Input + ProjectDir[Project Directory] + end + + subgraph Detection["Detection Phase"] + DetectType[Detect Project Type] + IsMonorepo{Is Monorepo?} + Single[Single Project] + Monorepo[Monorepo] + end + + subgraph Analysis["Analysis Phase"] + FindServices[Find & Analyze Services] + AnalyzeInfra[Analyze Infrastructure] + DetectConventions[Detect Conventions] + MapDeps[Map Dependencies] + end + + subgraph Output + ProjectIndex[Project Index JSON] + end + + ProjectDir --> DetectType + DetectType --> IsMonorepo + IsMonorepo -->|Yes| Monorepo + IsMonorepo -->|No| Single + Monorepo --> FindServices + Single --> FindServices + FindServices --> AnalyzeInfra + AnalyzeInfra --> DetectConventions + DetectConventions --> MapDeps + MapDeps --> ProjectIndex + + style Detection fill:#e3f2fd,stroke:#1976d2 + style Analysis fill:#fff3e0,stroke:#f57c00 +``` + +### Monorepo Detection + +The analyzer detects monorepos through multiple indicators: + +| Indicator | Detection Method | +|-----------|------------------| +| **Tool Configuration** | `pnpm-workspace.yaml`, `lerna.json`, `nx.json`, `turbo.json`, `rush.json` | +| **Directory Structure** | `packages/` or `apps/` directories | +| **Multiple Services** | 2+ directories with service root files | + +### Service Root Files + +Files that indicate a service/package root: + +```mermaid +flowchart LR + subgraph JavaScript + PackageJSON[package.json] + end + + subgraph Python + Requirements[requirements.txt] + Pyproject[pyproject.toml] + end + + subgraph Rust + CargoToml[Cargo.toml] + end + + subgraph Go + GoMod[go.mod] + end + + subgraph Other + Gemfile[Gemfile] + ComposerJSON[composer.json] + Makefile[Makefile] + Dockerfile[Dockerfile] + end +``` + +### Infrastructure Analysis + +```mermaid +flowchart TB + subgraph Docker["Docker Detection"] + Compose[docker-compose.yml] + Dockerfile[Dockerfile] + DockerDir[docker/] + end + + subgraph CI["CI/CD Detection"] + GHA[.github/workflows/] + GitLab[.gitlab-ci.yml] + CircleCI[.circleci/] + end + + subgraph Deploy["Deployment Detection"] + Vercel[vercel.json] + Netlify[netlify.toml] + Fly[fly.toml] + Heroku[Procfile] + end + + Docker --> Infrastructure[Infrastructure Map] + CI --> Infrastructure + Deploy --> Infrastructure + + style Docker fill:#e3f2fd,stroke:#1976d2 + style CI fill:#e8f5e9,stroke:#4caf50 + style Deploy fill:#fff3e0,stroke:#f57c00 +``` + +## Service Analyzer + +The `ServiceAnalyzer` class performs detailed analysis of individual services or packages. + +### Analysis Flow + +```mermaid +flowchart TB + subgraph Phase1["Phase 1: Core Detection"] + Lang[Detect Language] + Framework[Detect Framework] + Type[Detect Service Type] + end + + subgraph Phase2["Phase 2: Structure"] + KeyDirs[Find Key Directories] + EntryPoints[Find Entry Points] + Deps[Detect Dependencies] + Testing[Detect Testing] + end + + subgraph Phase3["Phase 3: Deep Analysis"] + EnvVars[Environment Variables] + Routes[API Routes] + Models[Database Models] + ExtServices[External Services] + end + + subgraph Phase4["Phase 4: Additional Context"] + Auth[Auth Patterns] + Migrations[Migrations] + Jobs[Background Jobs] + APIDocs[API Documentation] + Monitoring[Monitoring] + end + + Phase1 --> Phase2 + Phase2 --> Phase3 + Phase3 --> Phase4 + + style Phase1 fill:#e3f2fd,stroke:#1976d2 + style Phase2 fill:#e8f5e9,stroke:#4caf50 + style Phase3 fill:#fff3e0,stroke:#f57c00 + style Phase4 fill:#fce4ec,stroke:#e91e63 +``` + +### Service Type Detection + +```mermaid +flowchart TB + Start[Service Name] + + CheckFrontend{Contains frontend, client, web, ui, app?} + CheckBackend{Contains backend, api, server, service?} + CheckWorker{Contains worker, job, queue, task?} + CheckScraper{Contains scraper, crawler, spider?} + CheckLib{Contains lib, shared, common, core?} + + FrontendType[Type: frontend] + BackendType[Type: backend] + WorkerType[Type: worker] + ScraperType[Type: scraper] + LibraryType[Type: library] + Unknown[Type: unknown] + + Start --> CheckFrontend + CheckFrontend -->|Yes| FrontendType + CheckFrontend -->|No| CheckBackend + CheckBackend -->|Yes| BackendType + CheckBackend -->|No| CheckWorker + CheckWorker -->|Yes| WorkerType + CheckWorker -->|No| CheckScraper + CheckScraper -->|Yes| ScraperType + CheckScraper -->|No| CheckLib + CheckLib -->|Yes| LibraryType + CheckLib -->|No| Unknown + + style FrontendType fill:#e3f2fd,stroke:#1976d2 + style BackendType fill:#e8f5e9,stroke:#4caf50 + style WorkerType fill:#fff3e0,stroke:#f57c00 +``` + +### Integrated Analyzers + +```mermaid +classDiagram + class ServiceAnalyzer { + +analyze() dict + } + + class FrameworkAnalyzer { + +detect_language_and_framework() + -_detect_python_framework() + -_detect_js_framework() + -_detect_rust_framework() + } + + class RouteDetector { + +detect_all_routes() list + -_detect_fastapi_routes() + -_detect_flask_routes() + -_detect_express_routes() + } + + class DatabaseDetector { + +detect_all_models() dict + -_detect_sqlalchemy_models() + -_detect_prisma_models() + -_detect_django_models() + } + + class ContextAnalyzer { + +detect_environment_variables() + +detect_external_services() + +detect_auth_patterns() + +detect_migrations() + +detect_background_jobs() + } + + ServiceAnalyzer --> FrameworkAnalyzer : uses + ServiceAnalyzer --> RouteDetector : uses + ServiceAnalyzer --> DatabaseDetector : uses + ServiceAnalyzer --> ContextAnalyzer : uses +``` + +## Risk Classifier + +The `RiskClassifier` reads AI-generated complexity assessments and provides programmatic access to risk classification and validation recommendations. + +### Data Model + +```mermaid +classDiagram + class RiskAssessment { + +complexity: str + +workflow_type: str + +confidence: float + +reasoning: str + +analysis: ComplexityAnalysis + +recommended_phases: list + +flags: AssessmentFlags + +validation: ValidationRecommendations + } + + class ComplexityAnalysis { + +scope: ScopeAnalysis + +integrations: IntegrationAnalysis + +infrastructure: InfrastructureAnalysis + +knowledge: KnowledgeAnalysis + +risk: RiskAnalysis + } + + class ValidationRecommendations { + +risk_level: str + +skip_validation: bool + +minimal_mode: bool + +test_types_required: list + +security_scan_required: bool + +staging_deployment_required: bool + } + + class ScopeAnalysis { + +estimated_files: int + +estimated_services: int + +is_cross_cutting: bool + } + + class AssessmentFlags { + +needs_research: bool + +needs_self_critique: bool + +needs_infrastructure_setup: bool + } + + RiskAssessment --> ComplexityAnalysis + RiskAssessment --> AssessmentFlags + RiskAssessment --> ValidationRecommendations + ComplexityAnalysis --> ScopeAnalysis +``` + +### Risk Assessment Flow + +```mermaid +flowchart TB + Start[Load Assessment] + LoadJSON[Read complexity_assessment.json] + Parse[Parse Assessment Data] + + subgraph Classification + CheckRisk{Risk Level?} + Trivial[trivial - Skip validation] + Low[low - Unit tests only] + Medium[medium - Unit + Integration] + High[high - Full test suite] + Critical[critical - Manual review required] + end + + subgraph Recommendations + TestTypes[Determine Test Types] + SecurityScan[Check Security Scan Required] + Staging[Check Staging Required] + end + + Start --> LoadJSON + LoadJSON --> Parse + Parse --> CheckRisk + CheckRisk -->|trivial| Trivial + CheckRisk -->|low| Low + CheckRisk -->|medium| Medium + CheckRisk -->|high| High + CheckRisk -->|critical| Critical + + Trivial --> Recommendations + Low --> Recommendations + Medium --> Recommendations + High --> Recommendations + Critical --> Recommendations + + style Classification fill:#fff3e0,stroke:#f57c00 + style Recommendations fill:#e8f5e9,stroke:#4caf50 +``` + +### Key Methods + +| Method | Purpose | +|--------|---------| +| `load_assessment(spec_dir)` | Load and parse complexity_assessment.json | +| `should_skip_validation(spec_dir)` | Check if validation can be skipped | +| `get_required_test_types(spec_dir)` | Get list of required test types | +| `requires_security_scan(spec_dir)` | Check if security scanning is needed | +| `get_risk_level(spec_dir)` | Get the task risk level | +| `get_validation_summary(spec_dir)` | Get complete validation summary | + +### Validation Inference + +When explicit validation recommendations aren't provided, the classifier infers them from the complexity analysis: + +```mermaid +flowchart LR + RiskLevel[Risk Level] + + subgraph TestMapping["Test Type Mapping"] + LowRisk[low: unit only] + MediumRisk[medium: unit + integration] + HighRisk[high: unit + integration + e2e] + end + + subgraph SecurityCheck["Security Scan Check"] + HighLevel{High Risk?} + SecurityKeywords{Security Keywords?} + RequireScan[Require Security Scan] + end + + subgraph StagingCheck["Staging Check"] + DBChanges{Database Changes?} + MedOrHigh{Medium+ Risk?} + RequireStaging[Require Staging] + end + + RiskLevel --> TestMapping + RiskLevel --> SecurityCheck + HighLevel -->|Yes| RequireScan + SecurityKeywords -->|Yes| RequireScan + DBChanges -->|Yes| MedOrHigh + MedOrHigh -->|Yes| RequireStaging +``` + +## Security Scanner + +The `SecurityScanner` consolidates all security scanning operations including secrets detection and SAST tools. + +### Scanner Architecture + +```mermaid +flowchart TB + Start[Security Scan Request] + + subgraph Secrets["Secrets Detection"] + ScanSecrets[scan_secrets.py] + PatternMatch[Pattern Matching] + SecretMatches[Secret Matches] + end + + subgraph SAST["Static Analysis"] + CheckPython{Python Project?} + RunBandit[Run Bandit] + BanditResults[Bandit Results] + end + + subgraph DependencyAudit["Dependency Audit"] + CheckNode{Node Project?} + RunNPMAudit[npm audit] + CheckPyDeps{Python Project?} + RunPipAudit[pip-audit] + end + + subgraph Results + Aggregate[Aggregate Results] + DetermineCritical{Critical Issues?} + BlockQA[Block QA: True] + AllowQA[Block QA: False] + end + + Start --> Secrets + Start --> SAST + Start --> DependencyAudit + + Secrets --> Aggregate + SAST --> Aggregate + DependencyAudit --> Aggregate + + Aggregate --> DetermineCritical + DetermineCritical -->|Yes| BlockQA + DetermineCritical -->|No| AllowQA + + style Secrets fill:#ffebee,stroke:#f44336 + style SAST fill:#fff3e0,stroke:#f57c00 + style DependencyAudit fill:#e3f2fd,stroke:#1976d2 +``` + +### Security Scan Result + +```mermaid +classDiagram + class SecurityScanResult { + +secrets: list + +vulnerabilities: list~SecurityVulnerability~ + +scan_errors: list + +has_critical_issues: bool + +should_block_qa: bool + } + + class SecurityVulnerability { + +severity: str + +source: str + +title: str + +description: str + +file: str + +line: int + +cwe: str + } + + SecurityScanResult --> SecurityVulnerability +``` + +### Severity Levels + +| Severity | QA Impact | Examples | +|----------|-----------|----------| +| **critical** | Blocks QA | Exposed secrets, critical CVEs | +| **high** | Warning, review needed | High-severity vulnerabilities | +| **medium** | Noted in report | Moderate security issues | +| **low** | Informational | Minor concerns | +| **info** | Logged only | Informational findings | + +### Integrated Scanners + +```mermaid +flowchart LR + subgraph Secrets["Secrets Scanner"] + ScanSecrets[scan_secrets.py] + Patterns[Regex Patterns] + end + + subgraph Python["Python SAST"] + Bandit[Bandit] + PipAudit[pip-audit] + end + + subgraph JavaScript["JavaScript Security"] + NPMAudit[npm audit] + end + + Secrets --> SecurityScanner + Python --> SecurityScanner + JavaScript --> SecurityScanner + SecurityScanner --> Results[SecurityScanResult] + + style Secrets fill:#ffebee,stroke:#f44336 + style Python fill:#fff3e0,stroke:#f57c00 + style JavaScript fill:#e3f2fd,stroke:#1976d2 +``` + +## Insight Extractor + +The insight extractor automatically extracts structured insights from completed coding sessions for the Graphiti memory system. + +### Extraction Flow + +```mermaid +sequenceDiagram + participant Session as Coding Session + participant Extractor as InsightExtractor + participant Git as Git Repository + participant Claude as Claude SDK + participant Memory as Memory System + + Session->>Extractor: extract_session_insights() + Extractor->>Extractor: Check if extraction enabled + + alt Extraction Enabled + Extractor->>Git: Get session diff + Git-->>Extractor: Diff content + Extractor->>Git: Get changed files + Git-->>Extractor: File list + Extractor->>Git: Get commit messages + Git-->>Extractor: Commit history + + Extractor->>Extractor: Gather inputs + Extractor->>Claude: Build extraction prompt + Extractor->>Claude: Run extraction + Claude-->>Extractor: JSON insights + + Extractor->>Extractor: Parse insights + Extractor-->>Memory: Structured insights + else Extraction Disabled + Extractor-->>Memory: Generic insights + end +``` + +### Insights Structure + +```mermaid +classDiagram + class SessionInsights { + +file_insights: list~FileInsight~ + +patterns_discovered: list + +gotchas_discovered: list + +approach_outcome: ApproachOutcome + +recommendations: list + +subtask_id: str + +session_num: int + +success: bool + +changed_files: list + } + + class FileInsight { + +file_path: str + +description: str + +category: str + } + + class ApproachOutcome { + +success: bool + +approach_used: str + +why_it_worked: str + +why_it_failed: str + +alternatives_tried: list + } + + SessionInsights --> FileInsight + SessionInsights --> ApproachOutcome +``` + +### Configuration + +| Environment Variable | Default | Description | +|---------------------|---------|-------------| +| `INSIGHT_EXTRACTION_ENABLED` | `true` | Enable/disable extraction | +| `INSIGHT_EXTRACTOR_MODEL` | `claude-3-5-haiku-latest` | Model for extraction | + +### Extraction Limits + +| Limit | Value | Purpose | +|-------|-------|---------| +| `MAX_DIFF_CHARS` | 15000 | Avoid context limits | +| `MAX_ATTEMPTS_TO_INCLUDE` | 3 | Limit history size | + +## CI Discovery + +The `CIDiscovery` module parses CI/CD configuration files to extract test commands and workflows. + +### Supported CI Systems + +```mermaid +flowchart TB + subgraph GitHub["GitHub Actions"] + GHWorkflows[.github/workflows/*.yml] + end + + subgraph GitLab["GitLab CI"] + GLConfig[.gitlab-ci.yml] + end + + subgraph CircleCI["CircleCI"] + CCConfig[.circleci/config.yml] + end + + subgraph Jenkins["Jenkins"] + JFile[Jenkinsfile] + end + + GitHub --> CIDiscovery + GitLab --> CIDiscovery + CircleCI --> CIDiscovery + Jenkins --> CIDiscovery + CIDiscovery --> CIConfig[CIConfig Result] + + style GitHub fill:#24292e,stroke:#fff,color:#fff + style GitLab fill:#fc6d26,stroke:#fff,color:#fff + style CircleCI fill:#343434,stroke:#fff,color:#fff + style Jenkins fill:#d33833,stroke:#fff,color:#fff +``` + +### CI Configuration Model + +```mermaid +classDiagram + class CIConfig { + +ci_system: str + +config_files: list + +test_commands: dict + +coverage_command: str + +workflows: list~CIWorkflow~ + +environment_variables: list + } + + class CIWorkflow { + +name: str + +trigger: list + +steps: list + +test_related: bool + } + + CIConfig --> CIWorkflow +``` + +### Test Command Extraction + +```mermaid +flowchart LR + subgraph Commands["Recognized Test Commands"] + Pytest[pytest] + Jest[jest / vitest] + Mocha[mocha] + Playwright[playwright] + Cypress[cypress] + GoTest[go test] + CargoTest[cargo test] + end + + subgraph Types["Test Types"] + Unit[unit] + Integration[integration] + E2E[e2e] + end + + Commands --> Extraction[Command Extraction] + Extraction --> Types + + style Commands fill:#e3f2fd,stroke:#1976d2 + style Types fill:#e8f5e9,stroke:#4caf50 +``` + +## Test Discovery + +The `TestDiscovery` module detects test frameworks, commands, and directories in a project. + +### Framework Detection + +```mermaid +flowchart TB + subgraph JavaScript["JavaScript/TypeScript"] + Jest[Jest] + Vitest[Vitest] + Mocha[Mocha] + Playwright[Playwright] + Cypress[Cypress] + end + + subgraph Python["Python"] + Pytest[pytest] + Unittest[unittest] + end + + subgraph Other["Other Languages"] + CargoTest[cargo test] + GoTest[go test] + RSpec[RSpec] + Minitest[Minitest] + end + + JavaScript --> TestDiscovery + Python --> TestDiscovery + Other --> TestDiscovery + TestDiscovery --> Result[TestDiscoveryResult] + + style JavaScript fill:#f7df1e,stroke:#000 + style Python fill:#3776ab,stroke:#fff,color:#fff +``` + +### Discovery Process + +```mermaid +flowchart TB + Start[Start Discovery] + + subgraph PackageManager["Package Manager Detection"] + CheckPnpm{pnpm-lock.yaml?} + CheckYarn{yarn.lock?} + CheckNpm{package-lock.json?} + CheckPoetry{poetry.lock?} + CheckCargo{Cargo.lock?} + end + + subgraph Frameworks["Framework Detection"] + CheckPackageJSON{package.json?} + CheckPyProject{pyproject.toml?} + CheckCargoToml{Cargo.toml?} + CheckGoMod{go.mod?} + end + + subgraph TestDirs["Test Directory Discovery"] + Tests[tests/] + Test[test/] + Spec[spec/] + UnderTests[__tests__/] + end + + Start --> PackageManager + PackageManager --> Frameworks + Frameworks --> TestDirs + TestDirs --> Result[TestDiscoveryResult] + + style PackageManager fill:#e3f2fd,stroke:#1976d2 + style Frameworks fill:#fff3e0,stroke:#f57c00 + style TestDirs fill:#e8f5e9,stroke:#4caf50 +``` + +### Test Discovery Result + +```mermaid +classDiagram + class TestDiscoveryResult { + +frameworks: list~TestFramework~ + +test_command: str + +test_directories: list + +package_manager: str + +has_tests: bool + +coverage_command: str + } + + class TestFramework { + +name: str + +type: str + +command: str + +config_file: str + +version: str + +coverage_command: str + } + + TestDiscoveryResult --> TestFramework +``` + +## Context Detectors + +The `analyzers/context/` subpackage contains specialized detectors for extracting specific project context. + +### Detector Overview + +```mermaid +flowchart TB + subgraph Detectors + EnvDetector[env_detector.py] + AuthDetector[auth_detector.py] + ServicesDetector[services_detector.py] + MigrationsDetector[migrations_detector.py] + JobsDetector[jobs_detector.py] + APIDocsDetector[api_docs_detector.py] + MonitoringDetector[monitoring_detector.py] + end + + subgraph Outputs + EnvVars[Environment Variables] + AuthPatterns[Authentication Patterns] + ExtServices[External Services] + Migrations[Database Migrations] + BackgroundJobs[Background Jobs] + APIDocs[API Documentation] + Monitoring[Monitoring Config] + end + + EnvDetector --> EnvVars + AuthDetector --> AuthPatterns + ServicesDetector --> ExtServices + MigrationsDetector --> Migrations + JobsDetector --> BackgroundJobs + APIDocsDetector --> APIDocs + MonitoringDetector --> Monitoring + + style Detectors fill:#e3f2fd,stroke:#1976d2 + style Outputs fill:#e8f5e9,stroke:#4caf50 +``` + +### Detection Patterns + +| Detector | What It Finds | +|----------|---------------| +| **env_detector** | `.env` files, environment variable usage | +| **auth_detector** | JWT, OAuth, session auth patterns | +| **services_detector** | AWS, GCP, Redis, Elasticsearch, etc. | +| **migrations_detector** | Alembic, Django, Prisma migrations | +| **jobs_detector** | Celery, Bull, Sidekiq background jobs | +| **api_docs_detector** | OpenAPI, Swagger, GraphQL schemas | +| **monitoring_detector** | Prometheus, DataDog, Sentry config | + +## Base Analyzer + +The `BaseAnalyzer` class provides common utilities for all analyzers. + +### Skip Directories + +Directories automatically excluded from analysis: + +```python +SKIP_DIRS = { + "node_modules", ".git", "__pycache__", ".venv", "venv", + "dist", "build", ".next", ".nuxt", "target", "vendor", + ".idea", ".vscode", ".pytest_cache", ".mypy_cache", + "coverage", ".turbo", ".cache", ".worktrees", ".auto-claude" +} +``` + +### Service Indicators + +Common service directory names: + +```python +SERVICE_INDICATORS = { + "backend", "frontend", "api", "web", "app", "server", + "client", "worker", "workers", "services", "packages", + "apps", "libs", "scraper", "crawler", "proxy", "gateway", + "admin", "dashboard", "mobile", "desktop", "cli", "sdk" +} +``` + +## Usage Examples + +### Analyze a Project + +```python +from analysis.analyzers import analyze_project +from pathlib import Path + +# Analyze entire project +results = analyze_project(Path("/path/to/project")) + +print(f"Project Type: {results['project_type']}") +print(f"Services: {list(results['services'].keys())}") +print(f"CI System: {results['infrastructure'].get('ci')}") +``` + +### Run Security Scan + +```python +from analysis import SecurityScanner + +scanner = SecurityScanner() +result = scanner.scan( + project_dir=Path("/path/to/project"), + spec_dir=Path("/path/to/spec"), + run_secrets=True, + run_sast=True, +) + +if result.should_block_qa: + print("Security issues found - blocking QA") + for vuln in result.vulnerabilities: + print(f" [{vuln.severity}] {vuln.title}") +``` + +### Classify Risk + +```python +from analysis import RiskClassifier + +classifier = RiskClassifier() +summary = classifier.get_validation_summary(spec_dir) + +print(f"Risk Level: {summary['risk_level']}") +print(f"Test Types: {summary['test_types']}") +print(f"Skip Validation: {summary['skip_validation']}") +``` + +### Discover Tests + +```python +from analysis.test_discovery import discover_tests + +result = discover_tests(Path("/path/to/project")) + +print(f"Frameworks: {[f.name for f in result.frameworks]}") +print(f"Test Command: {result.test_command}") +print(f"Has Tests: {result.has_tests}") +``` + +## Integration Points + +```mermaid +flowchart LR + Analysis[Analysis Module] + + subgraph Consumers["Module Consumers"] + Planner[Planner Agent] + QA[QA Agent] + Coder[Coder Agent] + CLI[CLI Commands] + end + + subgraph External["External Tools"] + Git[Git] + Bandit[Bandit] + NPM[npm audit] + Claude[Claude SDK] + end + + Analysis --> Consumers + External --> Analysis + + style Consumers fill:#e8f5e9,stroke:#4caf50 + style External fill:#fce4ec,stroke:#e91e63 +``` + +### Key Dependencies + +| Module | Purpose | +|--------|---------| +| `scan_secrets.py` | Secrets detection patterns | +| `claude_agent_sdk` | AI-powered insight extraction | +| `bandit` | Python static analysis (optional) | +| `npm` | JavaScript dependency audit (optional) | + +## Error Handling + +### Graceful Degradation + +All analyzers implement graceful degradation: + +```mermaid +flowchart TB + Start[Analyzer Call] + Try[Try Primary Analysis] + Error{Error Occurred?} + Cache[Use Cached Result] + Default[Return Default/Empty] + Success[Return Analysis] + + Start --> Try + Try --> Error + Error -->|No| Success + Error -->|Yes| Cache + Cache -->|Available| Success + Cache -->|Not Available| Default + + style Success fill:#e8f5e9,stroke:#4caf50 + style Default fill:#fff3e0,stroke:#f57c00 +``` + +### Caching Strategy + +| Analyzer | Cache Key | Invalidation | +|----------|-----------|--------------| +| `RiskClassifier` | `spec_dir` path | `clear_cache()` | +| `CIDiscovery` | `project_dir` path | `clear_cache()` | +| `TestDiscovery` | `project_dir` path | `clear_cache()` | + +## Next Steps + +- [Core Module](./core.md) - Core infrastructure and authentication +- [CLI Module](./cli.md) - Command-line interface +- [Agents Module](./agents.md) - Agent system architecture +- [Planning Module](./planning.md) - Implementation planning From 9419c2a44332bac546655c290d3fb6473fc54b2f Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 21:54:30 +0200 Subject: [PATCH 11/27] auto-claude: subtask-3-3 - Create CLI module documentation covering batch, build, qa, and followup commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Created comprehensive CLI module documentation at docs/components/backend/cli.md covering: - Module overview with architecture diagram - Build commands (handle_build_command, workspace modes, interrupt handling) - QA commands (qa validation, status checks, review status) - Followup commands (collecting followup tasks, running planner) - Batch commands (create, status, cleanup operations) - Workspace commands (merge, review, discard, preview) - Spec commands (listing, discovery) - Input handlers (file reading, multiline input) - Utilities (environment setup, spec finding, validation) Includes 15+ Mermaid diagrams: flowcharts, sequence diagrams, and class diagrams. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/components/backend/cli.md | 1133 ++++++++++++++++++++++++++++++++ 1 file changed, 1133 insertions(+) create mode 100644 docs/components/backend/cli.md diff --git a/docs/components/backend/cli.md b/docs/components/backend/cli.md new file mode 100644 index 0000000000..c919ea43a8 --- /dev/null +++ b/docs/components/backend/cli.md @@ -0,0 +1,1133 @@ +# CLI Module + +The CLI module provides the command-line interface for Auto-Claude, enabling autonomous multi-session coding agent operations. It handles task execution, workspace management, QA validation, and batch operations. + +## Module Overview + +The CLI module is organized into focused command modules with clear responsibilities: + +```mermaid +flowchart TB + subgraph Entry["Entry Point"] + Main[main.py] + end + + subgraph Commands["Command Modules"] + Build[build_commands.py] + QA[qa_commands.py] + Followup[followup_commands.py] + Batch[batch_commands.py] + Spec[spec_commands.py] + Workspace[workspace_commands.py] + end + + subgraph Support["Support Modules"] + Utils[utils.py] + InputHandlers[input_handlers.py] + end + + Main --> Commands + Commands --> Support + + style Entry fill:#e3f2fd,stroke:#1976d2 + style Commands fill:#fff3e0,stroke:#f57c00 + style Support fill:#e8f5e9,stroke:#4caf50 +``` + +## Module Structure + +``` +apps/backend/cli/ +├── __init__.py # Package exports (main) +├── main.py # Argument parsing and command routing +├── build_commands.py # Build execution and workspace setup +├── qa_commands.py # QA validation commands +├── followup_commands.py # Follow-up task management +├── batch_commands.py # Batch task creation and status +├── spec_commands.py # Spec listing and discovery +├── workspace_commands.py # Merge, review, discard operations +├── input_handlers.py # User input collection utilities +└── utils.py # Shared utilities and configuration +``` + +## Command Flow Architecture + +```mermaid +flowchart TB + User[User Input] + ParseArgs[Parse Arguments] + + subgraph Routing["Command Routing"] + ListCheck{--list?} + SpecCheck{--spec?} + BatchCheck{Batch cmd?} + BuildCheck{Build cmd?} + QACheck{QA cmd?} + end + + subgraph Commands["Command Handlers"] + PrintSpecs[print_specs_list] + BuildCmd[handle_build_command] + QACmd[handle_qa_command] + FollowupCmd[handle_followup_command] + MergeCmd[handle_merge_command] + BatchCmd[handle_batch_*] + end + + User --> ParseArgs + ParseArgs --> Routing + ListCheck -->|Yes| PrintSpecs + ListCheck -->|No| SpecCheck + SpecCheck -->|No| BatchCheck + BatchCheck -->|Yes| BatchCmd + SpecCheck -->|Yes| BuildCheck + BuildCheck -->|Yes| BuildCmd + BuildCheck -->|No| QACheck + QACheck -->|Yes| QACmd + + style Routing fill:#e3f2fd,stroke:#1976d2 + style Commands fill:#e8f5e9,stroke:#4caf50 +``` + +## Build Commands + +The `build_commands.py` module handles the main build execution flow, workspace management, and agent orchestration. + +### Build Flow + +```mermaid +sequenceDiagram + participant User + participant CLI as handle_build_command + participant Review as ReviewState + participant Workspace as WorkspaceManager + participant Agent as run_autonomous_agent + participant QA as QA Validation + + User->>CLI: --spec 001 + CLI->>CLI: Print banner + CLI->>CLI: Validate environment + CLI->>Review: Check approval status + + alt Not Approved + Review-->>CLI: Blocked + CLI-->>User: Review required + else Approved + Review-->>CLI: Valid + CLI->>Workspace: Check existing build + + alt Has Existing Build + CLI->>User: Continue existing? + end + + CLI->>Workspace: Choose workspace mode + + alt Isolated Mode + Workspace->>Workspace: Setup worktree + end + + CLI->>Agent: Start autonomous agent + Agent-->>CLI: Subtasks complete + + alt QA Enabled + CLI->>QA: Run validation loop + QA-->>CLI: Approved/Issues + end + + CLI->>Workspace: Finalize workspace + CLI-->>User: Build complete + end +``` + +### Workspace Modes + +```mermaid +flowchart LR + subgraph Modes["Workspace Modes"] + Direct[Direct Mode] + Isolated[Isolated Mode] + end + + subgraph Direct["Direct Mode"] + DirectDesc[Build in project directory] + DirectRisk[Higher risk - affects main project] + end + + subgraph Isolated["Isolated Mode (Default)"] + IsolatedDesc[Build in git worktree] + IsolatedSafe[Safer - isolated from main] + IsolatedMerge[Merge when ready] + end + + CLI[CLI] -->|--direct| Direct + CLI -->|--isolated| Isolated + CLI -->|default| Isolated + + style Isolated fill:#e8f5e9,stroke:#4caf50 + style Direct fill:#fff3e0,stroke:#f57c00 +``` + +### Build Interrupt Handling + +```mermaid +flowchart TB + Interrupt[Ctrl+C Interrupt] + PrintBanner[Print paused banner] + UpdateStatus[Update status to PAUSED] + + subgraph Options["User Options"] + Type[Type instructions] + Paste[Paste from clipboard] + File[Read from file] + Skip[Continue without input] + Quit[Quit] + end + + subgraph Actions + SaveInput[Save to HUMAN_INPUT.md] + Resume[Resume build] + Exit[Exit] + end + + Interrupt --> PrintBanner + PrintBanner --> UpdateStatus + UpdateStatus --> Options + + Type --> SaveInput + Paste --> SaveInput + File --> SaveInput + Skip --> Resume + Quit --> Exit + SaveInput --> Exit + + style Options fill:#e3f2fd,stroke:#1976d2 + style Actions fill:#e8f5e9,stroke:#4caf50 +``` + +### Key Functions + +| Function | Purpose | +|----------|---------| +| `handle_build_command()` | Main build orchestration | +| `_handle_build_interrupt()` | Handle Ctrl+C during build | + +### Command Line Options + +| Option | Description | +|--------|-------------| +| `--spec ` | Spec to run (required) | +| `--model ` | Claude model to use | +| `--max-iterations ` | Max agent sessions | +| `--isolated` | Force isolated workspace | +| `--direct` | Force direct mode | +| `--auto-continue` | Non-interactive mode | +| `--skip-qa` | Skip QA validation | +| `--force` | Bypass approval check | +| `--base-branch ` | Base branch for worktree | + +## QA Commands + +The `qa_commands.py` module provides QA validation operations for completed builds. + +### QA Flow + +```mermaid +sequenceDiagram + participant User + participant CLI as handle_qa_command + participant Validator as QA Validator + participant Agent as QA Agent + participant Report as QA Report + + User->>CLI: --qa + CLI->>CLI: Print banner + CLI->>CLI: Validate environment + CLI->>Validator: Check if should run QA + + alt Build Not Complete + Validator-->>CLI: Not ready + CLI-->>User: Complete subtasks first + else Build Complete + CLI->>CLI: Check for human feedback + + alt Has Fix Request + CLI->>Agent: Process fix request + end + + CLI->>Agent: Run QA validation loop + + loop Until Approved or Max Iterations + Agent->>Agent: Run verification tests + Agent->>Agent: Check acceptance criteria + + alt Issues Found + Agent->>Report: Create QA_FIX_REQUEST.md + end + end + + Agent-->>CLI: Approved/Incomplete + CLI-->>User: QA result + end +``` + +### QA Status Commands + +```mermaid +flowchart TB + subgraph Commands["QA Status Commands"] + QAStatus[--qa-status] + ReviewStatus[--review-status] + end + + subgraph QAStatusFlow["QA Status Flow"] + PrintQA[Print QA status] + ShowProgress[Show verification progress] + end + + subgraph ReviewStatusFlow["Review Status Flow"] + PrintReview[Print review status] + CheckApproval{Approval Valid?} + Ready[Ready to build] + Changed[Spec changed - re-review] + NeedsReview[Review required] + end + + QAStatus --> QAStatusFlow + ReviewStatus --> ReviewStatusFlow + ReviewStatusFlow --> CheckApproval + CheckApproval -->|Valid| Ready + CheckApproval -->|Changed| Changed + CheckApproval -->|Not Approved| NeedsReview + + style Commands fill:#e3f2fd,stroke:#1976d2 +``` + +### Key Functions + +| Function | Purpose | +|----------|---------| +| `handle_qa_command()` | Run QA validation loop | +| `handle_qa_status_command()` | Display QA status | +| `handle_review_status_command()` | Display review/approval status | + +## Followup Commands + +The `followup_commands.py` module enables adding follow-up tasks to completed specs. + +### Followup Flow + +```mermaid +sequenceDiagram + participant User + participant CLI as handle_followup_command + participant Collector as collect_followup_task + participant Planner as run_followup_planner + participant Plan as Implementation Plan + + User->>CLI: --followup + CLI->>CLI: Print banner + CLI->>CLI: Check implementation plan exists + + alt No Plan + CLI-->>User: Build first + else Has Plan + CLI->>CLI: Check build complete + + alt Build Incomplete + CLI-->>User: Complete current build + else Build Complete + CLI->>Collector: Collect followup task + + alt User Cancels + Collector-->>CLI: None + CLI-->>User: Cancelled + else Task Provided + Collector->>Collector: Save to FOLLOWUP_REQUEST.md + Collector-->>CLI: Task description + + CLI->>Planner: Run followup planner + Planner->>Plan: Add new subtasks + Plan-->>Planner: Updated + Planner-->>CLI: Success + CLI-->>User: New subtasks added + end + end + end +``` + +### Input Collection Methods + +```mermaid +flowchart TB + subgraph Methods["Input Methods"] + Type[Type follow-up task] + Paste[Paste from clipboard] + File[Read from file] + Cancel[Cancel] + end + + subgraph Validation["Input Validation"] + CheckEmpty{Empty Input?} + Retry[Retry prompt] + MaxRetries{Max retries?} + Failed[Follow-up cancelled] + end + + subgraph Output + Save[Save FOLLOWUP_REQUEST.md] + Return[Return task] + end + + Methods --> CheckEmpty + CheckEmpty -->|Yes| Retry + Retry --> MaxRetries + MaxRetries -->|No| Methods + MaxRetries -->|Yes| Failed + CheckEmpty -->|No| Save + Save --> Return + + style Methods fill:#e3f2fd,stroke:#1976d2 + style Validation fill:#fff3e0,stroke:#f57c00 +``` + +### Key Functions + +| Function | Purpose | +|----------|---------| +| `handle_followup_command()` | Orchestrate follow-up workflow | +| `collect_followup_task()` | Collect user input for follow-up | + +## Batch Commands + +The `batch_commands.py` module provides batch task management for creating and managing multiple tasks. + +### Batch Create Flow + +```mermaid +sequenceDiagram + participant User + participant CLI as handle_batch_create_command + participant JSON as Batch JSON File + participant Specs as Specs Directory + + User->>CLI: --batch-create file.json + CLI->>JSON: Load batch file + + alt Invalid JSON + JSON-->>CLI: Error + CLI-->>User: Invalid JSON + else Valid JSON + JSON-->>CLI: Task list + + loop For Each Task + CLI->>CLI: Generate spec ID + CLI->>Specs: Create spec directory + CLI->>Specs: Write requirements.json + CLI-->>User: Created spec + end + + CLI-->>User: Summary + Next steps + end +``` + +### Batch JSON Format + +```json +{ + "tasks": [ + { + "title": "Task Title", + "description": "Detailed description", + "workflow_type": "feature", + "services": ["frontend", "backend"], + "priority": 5, + "complexity": "standard", + "estimated_hours": 4.0, + "estimated_days": 0.5 + } + ] +} +``` + +### Batch Status Display + +```mermaid +flowchart TB + subgraph Status["Status Icons"] + Pending["⏳ pending_spec"] + Created["📋 spec_created"] + Building["⚙️ building"] + Approved["✅ qa_approved"] + Unknown["❓ unknown"] + end + + subgraph Determination["Status Determination"] + HasSpec{Has spec.md?} + HasPlan{Has implementation_plan.json?} + HasQA{Has qa_report.md?} + end + + HasSpec -->|No| Pending + HasSpec -->|Yes| Created + HasPlan -->|Yes| Building + HasQA -->|Yes| Approved + + style Status fill:#e8f5e9,stroke:#4caf50 +``` + +### Key Functions + +| Function | Purpose | +|----------|---------| +| `handle_batch_create_command()` | Create specs from batch JSON | +| `handle_batch_status_command()` | Show status of all specs | +| `handle_batch_cleanup_command()` | Clean up completed specs | + +### Batch Commands + +| Command | Description | +|---------|-------------| +| `--batch-create ` | Create specs from JSON | +| `--batch-status` | Show all spec statuses | +| `--batch-cleanup` | Clean up completed specs | +| `--no-dry-run` | Actually delete in cleanup | + +## Workspace Commands + +The `workspace_commands.py` module provides workspace management operations for isolated builds. + +### Merge Flow + +```mermaid +sequenceDiagram + participant User + participant CLI as handle_merge_command + participant Worktree as Worktree + participant Git as Git + participant Main as Main Project + + User->>CLI: --merge + CLI->>Worktree: Get worktree path + + alt No Worktree + CLI-->>User: No build found + else Has Worktree + CLI->>Git: Check for conflicts + + alt Has Conflicts + CLI->>User: Show conflict info + end + + CLI->>Git: Merge changes + + alt No Commit Mode + Git->>Main: Stage changes only + CLI->>CLI: Generate commit message + else Commit Mode + Git->>Main: Merge and commit + end + + CLI-->>User: Merge complete + end +``` + +### Merge Preview + +```mermaid +flowchart TB + Start[Merge Preview Request] + + subgraph GitCheck["Git Conflict Check"] + MergeTree[git merge-tree] + FindConflicts[Find conflicting files] + CheckDivergence[Check branch divergence] + end + + subgraph SemanticCheck["Semantic Conflict Check"] + Orchestrator[MergeOrchestrator] + EvolutionTracker[Evolution Tracker] + PreviewMerge[Preview merge] + end + + subgraph Result["Preview Result"] + Files[Changed files list] + Conflicts[Conflict list] + Summary[Summary stats] + end + + Start --> GitCheck + Start --> SemanticCheck + GitCheck --> Result + SemanticCheck --> Result + + style GitCheck fill:#e3f2fd,stroke:#1976d2 + style SemanticCheck fill:#fff3e0,stroke:#f57c00 + style Result fill:#e8f5e9,stroke:#4caf50 +``` + +### Worktree Operations + +```mermaid +flowchart LR + subgraph Operations["Workspace Operations"] + Merge[--merge] + Review[--review] + Discard[--discard] + List[--list-worktrees] + Cleanup[--cleanup-worktrees] + end + + subgraph Actions + MergeAction[Merge to main project] + ReviewAction[Show diff summary] + DiscardAction[Delete worktree] + ListAction[List all worktrees] + CleanupAction[Remove all worktrees] + end + + Merge --> MergeAction + Review --> ReviewAction + Discard --> DiscardAction + List --> ListAction + Cleanup --> CleanupAction + + style Operations fill:#e3f2fd,stroke:#1976d2 + style Actions fill:#e8f5e9,stroke:#4caf50 +``` + +### Key Functions + +| Function | Purpose | +|----------|---------| +| `handle_merge_command()` | Merge worktree to main | +| `handle_merge_preview_command()` | Preview merge conflicts | +| `handle_review_command()` | Review worktree contents | +| `handle_discard_command()` | Discard worktree | +| `handle_list_worktrees_command()` | List all worktrees | +| `handle_cleanup_worktrees_command()` | Cleanup all worktrees | + +## Spec Commands + +The `spec_commands.py` module provides spec listing and discovery operations. + +### Spec Discovery + +```mermaid +flowchart TB + Start[list_specs] + + subgraph Discovery["Spec Discovery"] + ScanDir[Scan specs directory] + ParseName[Parse folder name] + CheckSpec{Has spec.md?} + CheckBuild[Check for worktree build] + CheckProgress[Check implementation_plan.json] + end + + subgraph Status["Status Determination"] + Complete[complete] + InProgress[in_progress] + Initialized[initialized] + Pending[pending] + end + + subgraph Output + SpecList[List of spec info dicts] + end + + Start --> ScanDir + ScanDir --> ParseName + ParseName --> CheckSpec + CheckSpec -->|Yes| CheckBuild + CheckBuild --> CheckProgress + CheckProgress --> Status + Status --> SpecList + + style Discovery fill:#e3f2fd,stroke:#1976d2 + style Status fill:#fff3e0,stroke:#f57c00 +``` + +### Auto-Create Workflow + +```mermaid +flowchart TB + List[--list command] + NoSpecs{Any specs found?} + + subgraph AutoCreate["Auto-Create Flow"] + Prompt[Quick start prompt] + GetTask[Get task description] + HasTask{Task provided?} + Direct[Direct mode with spec_runner] + Interactive[Interactive mode] + end + + subgraph Display + PrintSpecs[Print formatted spec list] + end + + List --> NoSpecs + NoSpecs -->|No| AutoCreate + NoSpecs -->|Yes| Display + Prompt --> GetTask + GetTask --> HasTask + HasTask -->|Yes| Direct + HasTask -->|No| Interactive + + style AutoCreate fill:#e8f5e9,stroke:#4caf50 +``` + +### Key Functions + +| Function | Purpose | +|----------|---------| +| `list_specs()` | Get all specs with status | +| `print_specs_list()` | Display formatted spec list | + +## Input Handlers + +The `input_handlers.py` module provides reusable user input collection utilities. + +### Input Flow + +```mermaid +flowchart TB + subgraph Methods["Input Methods"] + Type[Type instructions] + Paste[Paste from clipboard] + File[Read from file] + Skip[Continue without input] + Quit[Quit] + end + + subgraph FileInput["File Input"] + GetPath[Get file path] + Expand[Expand ~ and resolve] + CheckExists{File exists?} + ReadContent[Read content] + CheckEmpty{Content empty?} + end + + subgraph MultilineInput["Multiline Input"] + ShowPrompt[Show input box] + ReadLines[Read lines] + EmptyLine{Empty line?} + StopReading[Stop reading] + end + + Methods -->|file| FileInput + Methods -->|type/paste| MultilineInput + CheckExists -->|No| Error[Error: File not found] + CheckEmpty -->|Yes| Error2[Error: File empty] + + style Methods fill:#e3f2fd,stroke:#1976d2 + style FileInput fill:#fff3e0,stroke:#f57c00 + style MultilineInput fill:#e8f5e9,stroke:#4caf50 +``` + +### Key Functions + +| Function | Purpose | +|----------|---------| +| `collect_user_input_interactive()` | Interactive input collection | +| `read_from_file()` | Read from user-provided file path | +| `read_multiline_input()` | Read multi-line text input | + +## Utilities + +The `utils.py` module provides shared utilities and configuration for all CLI commands. + +### Configuration + +```mermaid +classDiagram + class CLIConfig { + <> + +DEFAULT_MODEL: str + } + + class Environment { + +setup_environment() Path + +validate_environment(spec_dir) bool + +get_project_dir(provided_dir) Path + } + + class SpecFinder { + +find_spec(project_dir, identifier) Path + +get_specs_dir(project_dir) Path + } + + class UIHelpers { + +print_banner() void + } +``` + +### Environment Validation + +```mermaid +flowchart TB + Start[validate_environment] + + subgraph Auth["Authentication Check"] + CheckToken{OAuth token?} + ShowSource[Show auth source] + ShowURL[Show custom base URL] + end + + subgraph Spec["Spec Check"] + CheckSpecMd{spec.md exists?} + end + + subgraph Integrations["Integration Status"] + LinearCheck[Linear integration] + GraphitiCheck[Graphiti memory] + end + + subgraph Result + Valid[Return True] + Invalid[Return False] + end + + Start --> Auth + Auth --> Spec + Spec --> Integrations + CheckToken -->|No| Invalid + CheckSpecMd -->|No| Invalid + Integrations --> Valid + + style Auth fill:#e3f2fd,stroke:#1976d2 + style Integrations fill:#e8f5e9,stroke:#4caf50 +``` + +### Spec Finding + +```mermaid +flowchart TB + Start[find_spec] + Input[Spec identifier: '001' or '001-feature'] + + subgraph Main["Main Project Search"] + ExactMatch[Try exact match] + PrefixMatch[Try prefix match] + end + + subgraph Worktree["Worktree Search"] + WTExact[Try worktree exact] + WTPrefix[Try worktree prefix] + end + + Found[Return spec path] + NotFound[Return None] + + Input --> Main + Main -->|Not found| Worktree + Main -->|Found| Found + Worktree -->|Found| Found + Worktree -->|Not found| NotFound + + style Main fill:#e3f2fd,stroke:#1976d2 + style Worktree fill:#fff3e0,stroke:#f57c00 +``` + +### Key Functions + +| Function | Purpose | +|----------|---------| +| `setup_environment()` | Initialize environment, load .env | +| `find_spec()` | Find spec by number or name | +| `validate_environment()` | Validate auth and spec | +| `print_banner()` | Print CLI banner | +| `get_project_dir()` | Determine project directory | + +## Class Diagram + +```mermaid +classDiagram + class CLIModule { + <> + +main() + +parse_args() + } + + class BuildCommands { + +handle_build_command() + -_handle_build_interrupt() + } + + class QACommands { + +handle_qa_command() + +handle_qa_status_command() + +handle_review_status_command() + } + + class FollowupCommands { + +handle_followup_command() + +collect_followup_task() + } + + class BatchCommands { + +handle_batch_create_command() + +handle_batch_status_command() + +handle_batch_cleanup_command() + } + + class SpecCommands { + +list_specs() + +print_specs_list() + } + + class WorkspaceCommands { + +handle_merge_command() + +handle_merge_preview_command() + +handle_review_command() + +handle_discard_command() + +handle_list_worktrees_command() + +handle_cleanup_worktrees_command() + } + + class InputHandlers { + +collect_user_input_interactive() + +read_from_file() + +read_multiline_input() + } + + class Utils { + +setup_environment() + +find_spec() + +validate_environment() + +print_banner() + +get_project_dir() + } + + CLIModule --> BuildCommands : uses + CLIModule --> QACommands : uses + CLIModule --> FollowupCommands : uses + CLIModule --> BatchCommands : uses + CLIModule --> SpecCommands : uses + CLIModule --> WorkspaceCommands : uses + BuildCommands --> InputHandlers : uses + BuildCommands --> Utils : uses + FollowupCommands --> InputHandlers : uses + QACommands --> Utils : uses +``` + +## Complete Command Reference + +### Main Commands + +| Command | Description | +|---------|-------------| +| `--list` | List all specs and their status | +| `--spec ` | Run/manage a specific spec | + +### Build Commands + +| Command | Description | +|---------|-------------| +| `--isolated` | Force isolated workspace mode | +| `--direct` | Build directly in project | +| `--auto-continue` | Non-interactive mode | +| `--skip-qa` | Skip QA validation | +| `--force` | Bypass approval check | +| `--max-iterations ` | Limit agent sessions | +| `--model ` | Specify Claude model | +| `--base-branch ` | Base for worktree | +| `--verbose` | Enable verbose output | + +### Workspace Commands + +| Command | Description | +|---------|-------------| +| `--merge` | Merge build to project | +| `--review` | Review build contents | +| `--discard` | Discard build | +| `--no-commit` | Stage only, don't commit | +| `--merge-preview` | Preview merge conflicts (JSON) | +| `--list-worktrees` | List all worktrees | +| `--cleanup-worktrees` | Remove all worktrees | + +### QA Commands + +| Command | Description | +|---------|-------------| +| `--qa` | Run QA validation loop | +| `--qa-status` | Show QA status | +| `--review-status` | Show approval status | + +### Followup Commands + +| Command | Description | +|---------|-------------| +| `--followup` | Add follow-up tasks | + +### Batch Commands + +| Command | Description | +|---------|-------------| +| `--batch-create ` | Create specs from JSON | +| `--batch-status` | Show all spec statuses | +| `--batch-cleanup` | Clean up completed specs | +| `--no-dry-run` | Actually delete files | + +## Usage Examples + +### Run a Build + +```bash +# Run a spec +python auto-claude/run.py --spec 001 + +# Run with specific model +python auto-claude/run.py --spec 001 --model claude-sonnet-4-20250514 + +# Run in direct mode (no isolation) +python auto-claude/run.py --spec 001 --direct + +# Non-interactive mode +python auto-claude/run.py --spec 001 --auto-continue +``` + +### Manage Workspaces + +```bash +# List all worktrees +python auto-claude/run.py --list-worktrees + +# Merge completed build +python auto-claude/run.py --spec 001 --merge + +# Stage changes without committing +python auto-claude/run.py --spec 001 --merge --no-commit + +# Review what was built +python auto-claude/run.py --spec 001 --review + +# Discard a build +python auto-claude/run.py --spec 001 --discard +``` + +### QA Operations + +```bash +# Run QA validation +python auto-claude/run.py --spec 001 --qa + +# Check QA status +python auto-claude/run.py --spec 001 --qa-status + +# Check review status +python auto-claude/run.py --spec 001 --review-status +``` + +### Batch Operations + +```bash +# Create specs from batch file +python auto-claude/run.py --batch-create tasks.json + +# Check all spec statuses +python auto-claude/run.py --batch-status + +# Clean up completed specs (dry run) +python auto-claude/run.py --batch-cleanup + +# Actually clean up +python auto-claude/run.py --batch-cleanup --no-dry-run +``` + +### Followup Tasks + +```bash +# Add follow-up to completed spec +python auto-claude/run.py --spec 001 --followup +``` + +## Integration Points + +```mermaid +flowchart LR + CLI[CLI Module] + + subgraph Internal["Internal Dependencies"] + Agent[Agent Module] + QALoop[QA Loop] + Workspace[Workspace Module] + Review[Review Module] + Progress[Progress Module] + end + + subgraph External["External Tools"] + Git[Git] + Claude[Claude SDK] + end + + subgraph UI["User Interface"] + Terminal[Terminal] + MenuSystem[Menu System] + end + + CLI --> Internal + CLI --> External + CLI --> UI + + style Internal fill:#e8f5e9,stroke:#4caf50 + style External fill:#e3f2fd,stroke:#1976d2 + style UI fill:#fff3e0,stroke:#f57c00 +``` + +### Key Dependencies + +| Module | Purpose | +|--------|---------| +| `agent` | Agent execution (`run_autonomous_agent`) | +| `qa_loop` | QA validation loop | +| `workspace` | Worktree management | +| `review` | Approval state management | +| `progress` | Subtask counting | +| `ui` | Terminal UI components | + +## Error Handling + +### Graceful Exit Handling + +```mermaid +flowchart TB + Error[Error Condition] + + subgraph Handlers["Error Handlers"] + KeyboardInt[KeyboardInterrupt] + EOFError[EOFError] + Exception[General Exception] + end + + subgraph Actions["Recovery Actions"] + SaveState[Save state to disk] + PrintHelp[Print resume command] + UpdateStatus[Update status file] + Exit[Exit with code] + end + + Error --> Handlers + KeyboardInt --> SaveState + SaveState --> PrintHelp + PrintHelp --> UpdateStatus + UpdateStatus --> Exit + Exception --> Exit + + style Handlers fill:#ffebee,stroke:#f44336 + style Actions fill:#e8f5e9,stroke:#4caf50 +``` + +### Exit Codes + +| Code | Meaning | +|------|---------| +| 0 | Success | +| 1 | Error (validation, missing spec, etc.) | + +## Next Steps + +- [Build Commands](./build_commands.md) - Detailed build execution +- [Agents Module](./agents.md) - Agent system architecture +- [Core Module](./core.md) - Core infrastructure +- [Analysis Module](./analysis.md) - Project analysis From ac03c57863750b81d210e2fb2fdf93c33020e6a2 Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 22:01:25 +0200 Subject: [PATCH 12/27] auto-claude: subtask-3-4 - Create core and context modules documentation cove --- docs/components/backend/core.md | 970 ++++++++++++++++++++++++++++++++ 1 file changed, 970 insertions(+) create mode 100644 docs/components/backend/core.md diff --git a/docs/components/backend/core.md b/docs/components/backend/core.md new file mode 100644 index 0000000000..0b7ed5d667 --- /dev/null +++ b/docs/components/backend/core.md @@ -0,0 +1,970 @@ +# Core and Context Modules + +The core and context modules provide the foundational infrastructure for Auto-Claude's autonomous coding system. The core module handles authentication, client creation, workspace management, and progress tracking, while the context module builds task-specific context by searching the codebase. + +## Module Overview + +```mermaid +flowchart TB + subgraph Core["Core Module"] + Agent[agent.py
Agent Facade] + Auth[auth.py
Authentication] + Client[client.py
Claude SDK Client] + Progress[progress.py
Progress Tracking] + Workspace[workspace.py
Workspace Management] + Worktree[worktree.py
Git Worktrees] + end + + subgraph Context["Context Module"] + Builder[builder.py
Context Builder] + Search[search.py
Code Search] + Categorizer[categorizer.py
File Categorization] + Keywords[keyword_extractor.py
Keyword Extraction] + ServiceMatcher[service_matcher.py
Service Matching] + Models[models.py
Data Models] + end + + Agent --> Client + Client --> Auth + Workspace --> Worktree + Builder --> Search + Builder --> Categorizer + Builder --> Keywords + Builder --> ServiceMatcher + + style Core fill:#e3f2fd,stroke:#1976d2 + style Context fill:#e8f5e9,stroke:#4caf50 +``` + +## Core Module Structure + +``` +apps/backend/core/ +├── __init__.py # Public API with lazy imports +├── agent.py # Agent session facade (re-exports from agents/) +├── auth.py # Authentication helpers +├── client.py # Claude SDK client configuration +├── debug.py # Debug utilities +├── phase_event.py # Phase event definitions +├── progress.py # Progress tracking utilities +├── workspace.py # Workspace management +├── worktree.py # Git worktree manager +└── workspace/ # Refactored workspace submodules + ├── __init__.py # Package exports + ├── display.py # UI display functions + ├── finalization.py # User interaction flows + ├── git_utils.py # Git operation utilities + ├── models.py # Data models and enums + └── setup.py # Workspace setup functions +``` + +## Context Module Structure + +``` +apps/backend/context/ +├── __init__.py # Public API exports +├── builder.py # Main context builder class +├── categorizer.py # File categorization logic +├── constants.py # Shared constants +├── graphiti_integration.py # Graphiti memory integration +├── keyword_extractor.py # Keyword extraction from tasks +├── main.py # CLI entry point +├── models.py # Data models (FileMatch, TaskContext) +├── pattern_discovery.py # Pattern discovery in files +├── search.py # Code search functionality +├── serialization.py # Context serialization +└── service_matcher.py # Service suggestion logic +``` + +## Core Class Diagram + +```mermaid +classDiagram + class CoreModule { + <> + +run_autonomous_agent() + +run_followup_planner() + +WorkspaceManager + +WorktreeManager + +ProgressTracker + +create_claude_client() + } + + class AuthModule { + <> + +get_auth_token() str|None + +get_auth_token_source() str|None + +require_auth_token() str + +get_sdk_env_vars() dict + +get_token_from_keychain() str|None + +ensure_claude_code_oauth_token() void + } + + class ClaudeClientFactory { + <> + +create_client(project_dir, spec_dir, model, agent_type) ClaudeSDKClient + +is_graphiti_mcp_enabled() bool + +is_electron_mcp_enabled() bool + +get_electron_debug_port() int + } + + class WorkspaceManager { + +project_dir: Path + +worktrees_dir: Path + +base_branch: str + +merge_existing_build() bool + +setup() void + +get_worktree_path(spec_name) Path + +get_branch_name(spec_name) str + } + + class WorktreeManager { + +project_dir: Path + +base_branch: str + +worktrees_dir: Path + +create_worktree(spec_name) WorktreeInfo + +get_or_create_worktree(spec_name) WorktreeInfo + +remove_worktree(spec_name, delete_branch) void + +merge_worktree(spec_name, delete_after, no_commit) bool + +list_all_worktrees() list[WorktreeInfo] + } + + class ProgressTracker { + <> + +count_subtasks(spec_dir) tuple[int,int] + +is_build_complete(spec_dir) bool + +get_progress_percentage(spec_dir) float + +get_next_subtask(spec_dir) dict|None + +get_plan_summary(spec_dir) dict + } + + CoreModule --> AuthModule : uses + CoreModule --> ClaudeClientFactory : uses + CoreModule --> WorkspaceManager : exports + CoreModule --> WorktreeManager : exports + CoreModule --> ProgressTracker : exports + ClaudeClientFactory --> AuthModule : authenticates + WorkspaceManager --> WorktreeManager : delegates to +``` + +## Context Class Diagram + +```mermaid +classDiagram + class ContextModule { + <> + +ContextBuilder + +CodeSearcher + +ServiceMatcher + +KeywordExtractor + +FileCategorizer + +PatternDiscoverer + } + + class ContextBuilder { + +project_dir: Path + +project_index: dict + +searcher: CodeSearcher + +service_matcher: ServiceMatcher + +keyword_extractor: KeywordExtractor + +categorizer: FileCategorizer + +pattern_discoverer: PatternDiscoverer + +build_context(task, services, keywords) TaskContext + +build_context_async(task, services, keywords) TaskContext + } + + class TaskContext { + +task_description: str + +scoped_services: list[str] + +files_to_modify: list[dict] + +files_to_reference: list[dict] + +patterns_discovered: dict[str,str] + +service_contexts: dict[str,dict] + +graph_hints: list[dict] + } + + class FileMatch { + +path: str + +service: str + +reason: str + +relevance_score: float + +matching_lines: list[tuple] + } + + class CodeSearcher { + +project_dir: Path + +search_service(service_path, service_name, keywords) list[FileMatch] + -_iter_code_files(directory) Iterator[Path] + } + + class ServiceMatcher { + +project_index: dict + +suggest_services(task) list[str] + } + + class KeywordExtractor { + +STOPWORDS: set[str] + +extract_keywords(task, max_keywords) list[str] + } + + class FileCategorizer { + +MODIFY_KEYWORDS: list[str] + +categorize_matches(matches, task) tuple[list,list] + } + + ContextBuilder --> TaskContext : creates + ContextBuilder --> FileMatch : produces + ContextBuilder --> CodeSearcher : uses + ContextBuilder --> ServiceMatcher : uses + ContextBuilder --> KeywordExtractor : uses + ContextBuilder --> FileCategorizer : uses +``` + +## Authentication System + +The `auth.py` module provides centralized authentication token resolution with fallback support. + +### Token Resolution Priority + +```mermaid +flowchart TB + Start[Get Auth Token] + + subgraph EnvVars["Environment Variables"] + Check1{CLAUDE_CODE_OAUTH_TOKEN?} + Check2{ANTHROPIC_AUTH_TOKEN?} + end + + subgraph Keychain["macOS Keychain"] + CheckOS{macOS?} + QueryKeychain[Query Keychain] + ParseJSON[Parse Credentials] + ExtractToken[Extract OAuth Token] + end + + Start --> Check1 + Check1 -->|Yes| ReturnToken[Return Token] + Check1 -->|No| Check2 + Check2 -->|Yes| ReturnToken + Check2 -->|No| CheckOS + CheckOS -->|Yes| QueryKeychain + CheckOS -->|No| ReturnNone[Return None] + QueryKeychain --> ParseJSON + ParseJSON --> ExtractToken + ExtractToken --> ReturnToken + + style EnvVars fill:#e3f2fd,stroke:#1976d2 + style Keychain fill:#fff3e0,stroke:#f57c00 +``` + +### Authentication Functions + +| Function | Description | Returns | +|----------|-------------|---------| +| `get_auth_token()` | Get token from env vars or Keychain | `str \| None` | +| `get_auth_token_source()` | Get name of token source | `str \| None` | +| `require_auth_token()` | Get token or raise ValueError | `str` | +| `get_sdk_env_vars()` | Get env vars to pass to SDK | `dict[str, str]` | +| `ensure_claude_code_oauth_token()` | Ensure token is set in env | `None` | + +### Security Note + +```mermaid +flowchart LR + subgraph Supported["✓ Supported"] + OAuth[CLAUDE_CODE_OAUTH_TOKEN] + CCR[ANTHROPIC_AUTH_TOKEN] + Keychain[macOS Keychain] + end + + subgraph NotSupported["✗ Not Supported"] + API[ANTHROPIC_API_KEY] + end + + style Supported fill:#e8f5e9,stroke:#4caf50 + style NotSupported fill:#ffebee,stroke:#f44336 +``` + +> **Important**: `ANTHROPIC_API_KEY` is intentionally NOT supported to prevent silent billing to user's API credits when OAuth is misconfigured. + +## Claude SDK Client Creation + +The `client.py` module creates configured Claude Agent SDK clients with multi-layered security. + +### Client Creation Flow + +```mermaid +sequenceDiagram + participant Caller + participant ClientFactory as create_client() + participant Auth as AuthModule + participant SDK as ClaudeSDKClient + participant MCP as MCP Servers + + Caller->>ClientFactory: project_dir, spec_dir, model, agent_type + ClientFactory->>Auth: require_auth_token() + Auth-->>ClientFactory: OAuth token + ClientFactory->>ClientFactory: Get SDK env vars + ClientFactory->>ClientFactory: Detect project capabilities + ClientFactory->>ClientFactory: Build allowed tools list + ClientFactory->>ClientFactory: Configure MCP servers + ClientFactory->>ClientFactory: Write security settings + ClientFactory->>SDK: Create client with options + SDK->>MCP: Initialize MCP connections + SDK-->>ClientFactory: Configured client + ClientFactory-->>Caller: ClaudeSDKClient +``` + +### Security Layers + +```mermaid +flowchart TB + subgraph Layer1["Layer 1: Sandbox"] + Sandbox[OS-level bash isolation] + end + + subgraph Layer2["Layer 2: Permissions"] + Perms[File operations restricted to project_dir] + end + + subgraph Layer3["Layer 3: Security Hooks"] + Hooks[Bash commands validated against allowlist] + end + + subgraph Layer4["Layer 4: Tool Filtering"] + Tools[Agent type determines available tools] + end + + Command[User Command] --> Layer1 + Layer1 --> Layer2 + Layer2 --> Layer3 + Layer3 --> Layer4 + Layer4 --> Execution[Execute] + + style Layer1 fill:#ffebee,stroke:#f44336 + style Layer2 fill:#fff3e0,stroke:#f57c00 + style Layer3 fill:#fff9c4,stroke:#fbc02d + style Layer4 fill:#e8f5e9,stroke:#4caf50 +``` + +### MCP Server Configuration + +```mermaid +flowchart LR + subgraph Always["Always Enabled"] + Context7[context7
Documentation] + end + + subgraph Conditional["Conditional"] + Linear[linear
Project Management] + Graphiti[graphiti-memory
Knowledge Graph] + AutoClaude[auto-claude
Custom Tools] + end + + subgraph QAOnly["QA Agents Only"] + Electron[electron
Desktop Automation] + Puppeteer[puppeteer
Browser Automation] + end + + style Always fill:#e8f5e9,stroke:#4caf50 + style Conditional fill:#e3f2fd,stroke:#1976d2 + style QAOnly fill:#fff3e0,stroke:#f57c00 +``` + +### Agent Types and Tools + +| Agent Type | Base Tools | Custom Tools | MCP Tools | +|------------|------------|--------------|-----------| +| `planner` | Read, Glob, Grep | Plan-specific | Context7 | +| `coder` | All built-in | Coder-specific | Context7, Linear | +| `qa_reviewer` | All built-in | QA-specific | + Electron/Puppeteer | +| `qa_fixer` | All built-in | QA-specific | + Electron/Puppeteer | + +## Workspace Management + +The workspace module provides Git worktree isolation for each spec. + +### Worktree Architecture + +```mermaid +flowchart TB + subgraph MainRepo["Main Repository"] + Main[main branch] + Feature[feature branches] + end + + subgraph Worktrees[".worktrees/"] + WT1[001-feature/
auto-claude/001-feature] + WT2[002-bugfix/
auto-claude/002-bugfix] + WT3[003-refactor/
auto-claude/003-refactor] + end + + Main -->|fork| WT1 + Main -->|fork| WT2 + Main -->|fork| WT3 + + WT1 -.->|merge| Main + WT2 -.->|merge| Main + WT3 -.->|merge| Main + + style MainRepo fill:#e3f2fd,stroke:#1976d2 + style Worktrees fill:#e8f5e9,stroke:#4caf50 +``` + +### WorktreeManager Class + +```python +class WorktreeManager: + """ + Manages per-spec Git worktrees. + + Each spec gets its own worktree in .worktrees/{spec-name}/ with + a corresponding branch auto-claude/{spec-name}. + """ + + def __init__(self, project_dir: Path, base_branch: str | None = None): + self.project_dir = project_dir + self.base_branch = base_branch or self._detect_base_branch() + self.worktrees_dir = project_dir / ".worktrees" +``` + +### WorktreeInfo Data Class + +```mermaid +classDiagram + class WorktreeInfo { + +path: Path + +branch: str + +spec_name: str + +base_branch: str + +is_active: bool + +commit_count: int + +files_changed: int + +additions: int + +deletions: int + } +``` + +### Worktree Lifecycle + +```mermaid +stateDiagram-v2 + [*] --> Created: create_worktree() + Created --> Active: Start coding + Active --> Active: commit_in_worktree() + Active --> Merged: merge_worktree() + Active --> Removed: remove_worktree() + Merged --> [*] + Removed --> [*] +``` + +### Key Methods + +| Method | Description | Returns | +|--------|-------------|---------| +| `create_worktree(spec_name)` | Create new worktree for spec | `WorktreeInfo` | +| `get_or_create_worktree(spec_name)` | Get existing or create new | `WorktreeInfo` | +| `merge_worktree(spec_name, ...)` | Merge worktree back to base | `bool` | +| `remove_worktree(spec_name, delete_branch)` | Remove worktree | `None` | +| `list_all_worktrees()` | List all spec worktrees | `list[WorktreeInfo]` | +| `get_changed_files(spec_name)` | Get changed files in worktree | `list[tuple]` | + +## AI-Powered Merge System + +The workspace module includes an AI-powered merge system for resolving conflicts. + +### Merge Flow + +```mermaid +flowchart TB + Start[merge_existing_build] + CheckWorktree{Worktree exists?} + SmartMerge[Try Smart Merge] + + subgraph Analysis["Conflict Analysis"] + GitConflicts{Git conflicts?} + SemanticAnalysis[Semantic Analysis] + AIResolve[AI Conflict Resolution] + end + + subgraph Resolution["Resolution"] + Simple3Way[Simple 3-way merge] + AIPrompt[Build AI prompt] + CallClaude[Call Claude Haiku] + ValidateSyntax[Validate syntax] + end + + GitMerge[Standard Git Merge] + Success[Merge Complete] + Failure[Manual Resolution] + + Start --> CheckWorktree + CheckWorktree -->|No| Failure + CheckWorktree -->|Yes| SmartMerge + SmartMerge --> GitConflicts + GitConflicts -->|Yes| AIResolve + GitConflicts -->|No| SemanticAnalysis + AIResolve --> Simple3Way + Simple3Way -->|Success| Success + Simple3Way -->|Fail| AIPrompt + AIPrompt --> CallClaude + CallClaude --> ValidateSyntax + ValidateSyntax -->|Valid| Success + ValidateSyntax -->|Invalid| Failure + SemanticAnalysis --> GitMerge + GitMerge --> Success + + style Analysis fill:#e3f2fd,stroke:#1976d2 + style Resolution fill:#e8f5e9,stroke:#4caf50 +``` + +### Parallel Merge Processing + +```mermaid +flowchart LR + subgraph Input["Conflicting Files"] + F1[file1.py] + F2[file2.ts] + F3[file3.tsx] + F4[file4.py] + end + + subgraph Parallel["Parallel AI Merges"] + Sem[Semaphore
max=5] + AI1[Claude Haiku] + AI2[Claude Haiku] + AI3[Claude Haiku] + end + + subgraph Output["Merged Results"] + R1[✓ file1.py] + R2[✓ file2.ts] + R3[✓ file3.tsx] + R4[✓ file4.py] + end + + F1 --> Sem + F2 --> Sem + F3 --> Sem + F4 --> Sem + Sem --> AI1 + Sem --> AI2 + Sem --> AI3 + AI1 --> R1 + AI2 --> R2 + AI3 --> R3 + AI1 --> R4 + + style Parallel fill:#fff3e0,stroke:#f57c00 +``` + +## Progress Tracking + +The `progress.py` module tracks implementation plan progress. + +### Progress Functions + +| Function | Description | Returns | +|----------|-------------|---------| +| `count_subtasks(spec_dir)` | Count completed/total subtasks | `tuple[int, int]` | +| `is_build_complete(spec_dir)` | Check if all subtasks done | `bool` | +| `get_progress_percentage(spec_dir)` | Get progress as percentage | `float` | +| `get_next_subtask(spec_dir)` | Find next subtask to work on | `dict \| None` | +| `get_plan_summary(spec_dir)` | Get detailed plan summary | `dict` | +| `get_current_phase(spec_dir)` | Get current phase info | `dict \| None` | + +### Progress Display + +```mermaid +flowchart TB + subgraph Display["Progress Display"] + Header[print_session_header] + Summary[print_progress_summary] + Banner[print_build_complete_banner] + Paused[print_paused_banner] + end + + subgraph Data["Progress Data"] + Count[count_subtasks] + Detailed[count_subtasks_detailed] + Phase[get_current_phase] + Next[get_next_subtask] + end + + Data --> Display + + style Display fill:#e3f2fd,stroke:#1976d2 + style Data fill:#e8f5e9,stroke:#4caf50 +``` + +## Context Building + +The context module builds task-specific context by searching the codebase. + +### Context Building Flow + +```mermaid +sequenceDiagram + participant Caller + participant Builder as ContextBuilder + participant Matcher as ServiceMatcher + participant Keywords as KeywordExtractor + participant Searcher as CodeSearcher + participant Categorizer as FileCategorizer + participant Patterns as PatternDiscoverer + participant Graphiti + + Caller->>Builder: build_context(task) + Builder->>Matcher: suggest_services(task) + Matcher-->>Builder: [service1, service2] + Builder->>Keywords: extract_keywords(task) + Keywords-->>Builder: [kw1, kw2, kw3] + + loop For each service + Builder->>Searcher: search_service(path, name, keywords) + Searcher-->>Builder: FileMatch[] + end + + Builder->>Categorizer: categorize_matches(matches, task) + Categorizer-->>Builder: (to_modify, to_reference) + Builder->>Patterns: discover_patterns(references, keywords) + Patterns-->>Builder: patterns{} + Builder->>Graphiti: fetch_graph_hints(task) + Graphiti-->>Builder: hints[] + Builder-->>Caller: TaskContext +``` + +### ContextBuilder Class + +```python +class ContextBuilder: + """Builds task-specific context by searching the codebase.""" + + def __init__(self, project_dir: Path, project_index: dict | None = None): + self.project_dir = project_dir.resolve() + self.project_index = project_index or self._load_project_index() + + # Initialize components + self.searcher = CodeSearcher(self.project_dir) + self.service_matcher = ServiceMatcher(self.project_index) + self.keyword_extractor = KeywordExtractor() + self.categorizer = FileCategorizer() + self.pattern_discoverer = PatternDiscoverer(self.project_dir) +``` + +### TaskContext Structure + +```mermaid +classDiagram + class TaskContext { + +task_description: str + +scoped_services: list[str] + +files_to_modify: list[dict] + +files_to_reference: list[dict] + +patterns_discovered: dict[str,str] + +service_contexts: dict[str,dict] + +graph_hints: list[dict] + } + + class FileMatch { + +path: str + +service: str + +reason: str + +relevance_score: float + +matching_lines: list[tuple[int,str]] + } + + TaskContext --> FileMatch : contains +``` + +## Code Search + +The `search.py` module searches code files for relevant matches. + +### Search Algorithm + +```mermaid +flowchart TB + subgraph Input + Keywords[Keywords List] + ServicePath[Service Path] + end + + subgraph Search["Search Process"] + IterFiles[Iterate Code Files] + SkipDirs[Skip node_modules, .git, etc.] + ReadContent[Read File Content] + ScoreFile[Score by Keyword Matches] + FindLines[Find Matching Lines] + end + + subgraph Output + Matches[FileMatch Objects] + Sort[Sort by Relevance] + Limit[Top 20 per Service] + end + + Input --> IterFiles + IterFiles --> SkipDirs + SkipDirs --> ReadContent + ReadContent --> ScoreFile + ScoreFile --> FindLines + FindLines --> Matches + Matches --> Sort + Sort --> Limit + + style Search fill:#e3f2fd,stroke:#1976d2 +``` + +### Scoring System + +| Factor | Score Impact | +|--------|--------------| +| Keyword occurrence | +1-10 per keyword (capped) | +| Multiple keywords | Additive | +| Line matches | Stored for context | + +## File Categorization + +The `categorizer.py` module categorizes files into modification vs reference targets. + +### Categorization Logic + +```mermaid +flowchart TB + Input[FileMatch] + + subgraph Checks["File Type Checks"] + IsTest{Test file?} + IsExample{Example file?} + IsConfig{Low-score config?} + HighScore{Score >= 5?} + IsModTask{Modification task?} + end + + subgraph Output["Categories"] + ToModify[Files to Modify] + ToReference[Files to Reference] + end + + Input --> IsTest + IsTest -->|Yes| ToReference + IsTest -->|No| IsExample + IsExample -->|Yes| ToReference + IsExample -->|No| IsConfig + IsConfig -->|Yes| ToReference + IsConfig -->|No| HighScore + HighScore -->|Yes| IsModTask + HighScore -->|No| ToReference + IsModTask -->|Yes| ToModify + IsModTask -->|No| ToReference + + style ToModify fill:#e8f5e9,stroke:#4caf50 + style ToReference fill:#e3f2fd,stroke:#1976d2 +``` + +### Modification Keywords + +The categorizer uses these keywords to detect modification tasks: + +| Keyword | Action Type | +|---------|-------------| +| `add`, `create`, `new` | Creation | +| `implement`, `build` | Implementation | +| `fix`, `update`, `change`, `modify` | Modification | + +## Service Matching + +The `service_matcher.py` module suggests relevant services based on task description. + +### Service Scoring + +```mermaid +flowchart LR + subgraph Input + Task[Task Description] + Index[Project Index] + end + + subgraph Scoring["Score Calculation"] + NameMatch[Service Name in Task: +10] + TypeMatch[Service Type Match: +5] + FrameworkMatch[Framework in Task: +3] + end + + subgraph Output + Top3[Top 3 Services] + Default[Default: 1 backend + 1 frontend] + end + + Task --> NameMatch + Task --> TypeMatch + Task --> FrameworkMatch + NameMatch --> Top3 + TypeMatch --> Top3 + FrameworkMatch --> Top3 + + style Scoring fill:#e3f2fd,stroke:#1976d2 +``` + +### Service Type Mapping + +| Service Type | Trigger Keywords | +|--------------|------------------| +| `backend` | api, endpoint, route, database, model | +| `frontend` | ui, component, page, button, form | +| `worker` | job, task, queue, background, async | +| `scraper` | scrape, crawl, fetch, parse | + +## Keyword Extraction + +The `keyword_extractor.py` module extracts meaningful keywords from task descriptions. + +### Extraction Process + +```mermaid +flowchart LR + subgraph Input + Task[Task Description] + end + + subgraph Process["Extraction"] + Tokenize[Tokenize with Regex] + Filter[Filter Stopwords] + LenCheck[Remove short words] + Dedupe[Deduplicate] + Limit[Limit to max] + end + + subgraph Output + Keywords[Keyword List] + end + + Task --> Tokenize + Tokenize --> Filter + Filter --> LenCheck + LenCheck --> Dedupe + Dedupe --> Limit + Limit --> Keywords + + style Process fill:#e3f2fd,stroke:#1976d2 +``` + +### Stopwords + +Common words filtered out include: +- Articles: a, an, the +- Prepositions: to, for, of, in, on, at, by, with +- Verbs: is, are, was, were, be, have, has, do, does +- Action words: add, create, make, implement, build, fix, update + +## Lazy Import Pattern + +Both modules use Python's `__getattr__` for lazy imports: + +```mermaid +flowchart TB + Import[Import core.function] + GetAttr["__getattr__(name)"] + + subgraph Routes["Name Routing"] + CheckAgent{Agent functions?} + CheckWorkspace{Workspace?} + CheckWorktree{Worktree?} + CheckProgress{Progress?} + CheckClient{Client?} + end + + subgraph Imports["Lazy Imports"] + ImportAgent[from .agent import ...] + ImportWorkspace[from .workspace import ...] + ImportWorktree[from .worktree import ...] + ImportProgress[from .progress import ...] + ImportClient[from .client import ...] + end + + Import --> GetAttr + GetAttr --> Routes + CheckAgent -->|Yes| ImportAgent + CheckWorkspace -->|Yes| ImportWorkspace + CheckWorktree -->|Yes| ImportWorktree + CheckProgress -->|Yes| ImportProgress + CheckClient -->|Yes| ImportClient + + style Routes fill:#e3f2fd,stroke:#1976d2 + style Imports fill:#e8f5e9,stroke:#4caf50 +``` + +## Integration Points + +### External Dependencies + +```mermaid +flowchart LR + Core[Core Module] + Context[Context Module] + + subgraph External["External Services"] + Claude[Claude Agent SDK] + Git[Git] + Graphiti[Graphiti Memory] + end + + subgraph Internal["Internal Modules"] + Agents[agents/] + Analysis[analysis/] + UI[ui/] + Security[security/] + end + + Core <-->|Execute| Claude + Core <-->|Manage| Git + Context <-->|Hints| Graphiti + Core --> Agents + Context --> Analysis + Core --> UI + Core --> Security + + style External fill:#fce4ec,stroke:#e91e63 + style Internal fill:#e8f5e9,stroke:#4caf50 +``` + +### Key Dependencies + +| Module | Dependency | Purpose | +|--------|------------|---------| +| `core.client` | `claude_agent_sdk` | AI agent execution | +| `core.auth` | `subprocess`, `json` | Keychain access | +| `core.workspace` | `subprocess`, `git` | Git operations | +| `context.builder` | `analysis` | Project index loading | +| `context.graphiti_integration` | `graphiti_memory` | Cross-session memory | + +## Error Handling + +### Authentication Errors + +```mermaid +flowchart TB + Check{Token found?} + Check -->|No| BuildError[Build Error Message] + BuildError --> CheckOS{macOS?} + CheckOS -->|Yes| MacHelp[Keychain + .env instructions] + CheckOS -->|No| WinHelp[.env instructions only] + MacHelp --> Raise[Raise ValueError] + WinHelp --> Raise +``` + +### Worktree Errors + +| Error | Cause | Resolution | +|-------|-------|------------| +| `WorktreeError` | Branch namespace conflict | Rename conflicting branch | +| Merge conflict | Diverged branches | AI resolution or manual | +| Missing worktree | Deleted or corrupted | Recreate from spec | + +## Next Steps + +- [Agents Module](./agents.md) - Agent execution system +- [Analysis Module](./analysis.md) - Project analysis system +- [CLI Module](./cli.md) - Command-line interface +- [Integration Points](../architecture/integration.md) - System integration From fa1ba8440eab363f4478b66c215b62949f320447 Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 22:05:38 +0200 Subject: [PATCH 13/27] auto-claude: subtask-3-5 - Create implementation plan and integrations documentation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Create docs/components/backend/planning.md with comprehensive documentation - Document ImplementationPlan, Phase, Subtask, and Verification models - Document WorkflowType, PhaseType, SubtaskStatus, and VerificationType enums - Document factory functions for creating different plan types - Document Graphiti memory integration with multi-provider support - Document Linear task tracking integration with status flow - Include extensive Mermaid diagrams for architecture and data flow - Add usage examples and API references 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/components/backend/planning.md | 1038 +++++++++++++++++++++++++++ 1 file changed, 1038 insertions(+) create mode 100644 docs/components/backend/planning.md diff --git a/docs/components/backend/planning.md b/docs/components/backend/planning.md new file mode 100644 index 0000000000..d5cd4823ce --- /dev/null +++ b/docs/components/backend/planning.md @@ -0,0 +1,1038 @@ +# Implementation Plan & Integrations + +The implementation plan module provides the data structures and logic for managing task execution plans, while integrations connect Auto-Claude to external services like Graphiti (memory) and Linear (task tracking). + +## Module Overview + +The planning system organizes work into hierarchical structures: Plans contain Phases, which contain Subtasks. This enables complex features to be broken down into manageable, trackable units of work. + +```mermaid +flowchart TB + subgraph Plan["Implementation Plan"] + Feature[Feature Name] + Workflow[Workflow Type] + Services[Services Involved] + Phases[Phases List] + end + + subgraph PhaseGroup["Phase"] + PhaseNum[Phase Number] + PhaseName[Phase Name] + PhaseType[Phase Type] + Dependencies[depends_on] + Subtasks[Subtasks List] + end + + subgraph SubtaskGroup["Subtask"] + SubtaskId[ID] + Description[Description] + Status[Status] + Files[Files to Modify/Create] + Verify[Verification] + end + + Plan --> PhaseGroup + PhaseGroup --> SubtaskGroup + + style Plan fill:#e3f2fd,stroke:#1976d2 + style PhaseGroup fill:#fff3e0,stroke:#f57c00 + style SubtaskGroup fill:#e8f5e9,stroke:#4caf50 +``` + +## Directory Structure + +``` +apps/backend/ +├── implementation_plan/ +│ ├── __init__.py # Public API exports +│ ├── enums.py # Workflow, Phase, Status, Verification enums +│ ├── factories.py # Plan creation factory functions +│ ├── phase.py # Phase model +│ ├── plan.py # ImplementationPlan model +│ ├── subtask.py # Subtask model +│ └── verification.py # Verification model +└── integrations/ + ├── __init__.py + ├── graphiti/ # Memory integration + │ ├── __init__.py + │ ├── config.py # GraphitiConfig, providers + │ ├── memory.py # GraphitiMemory facade + │ └── providers_pkg/ # LLM & embedder providers + └── linear/ # Task tracking integration + ├── __init__.py + ├── config.py # LinearConfig, status mappings + ├── integration.py # LinearManager + └── updater.py # Linear update operations +``` + +## Implementation Plan Module + +### Class Diagram + +```mermaid +classDiagram + class ImplementationPlan { + +feature: str + +workflow_type: WorkflowType + +services_involved: list~str~ + +phases: list~Phase~ + +final_acceptance: list~str~ + +status: str + +planStatus: str + +qa_signoff: dict + +to_dict() dict + +from_dict(data) ImplementationPlan + +save(path) void + +load(path) ImplementationPlan + +get_available_phases() list~Phase~ + +get_next_subtask() tuple~Phase,Subtask~ + +get_progress() dict + +add_followup_phase() Phase + } + + class Phase { + +phase: int + +name: str + +type: PhaseType + +subtasks: list~Subtask~ + +depends_on: list~int~ + +parallel_safe: bool + +is_complete() bool + +get_pending_subtasks() list~Subtask~ + +get_progress() tuple~int,int~ + } + + class Subtask { + +id: str + +description: str + +status: SubtaskStatus + +service: str + +files_to_modify: list~str~ + +files_to_create: list~str~ + +patterns_from: list~str~ + +verification: Verification + +start(session_id) void + +complete(output) void + +fail(reason) void + } + + class Verification { + +type: VerificationType + +run: str + +url: str + +expect_status: int + +expect_contains: str + +scenario: str + } + + ImplementationPlan "1" --> "*" Phase + Phase "1" --> "*" Subtask + Subtask "1" --> "0..1" Verification +``` + +### Enumerations + +The `enums.py` module defines all status and type constants: + +```mermaid +classDiagram + class WorkflowType { + <> + FEATURE + REFACTOR + INVESTIGATION + MIGRATION + SIMPLE + DEVELOPMENT + ENHANCEMENT + } + + class PhaseType { + <> + SETUP + IMPLEMENTATION + INVESTIGATION + INTEGRATION + CLEANUP + } + + class SubtaskStatus { + <> + PENDING + IN_PROGRESS + COMPLETED + BLOCKED + FAILED + } + + class VerificationType { + <> + COMMAND + API + BROWSER + COMPONENT + MANUAL + NONE + } +``` + +#### Workflow Types + +| Type | Description | Use Case | +|------|-------------|----------| +| `FEATURE` | Multi-service feature | New functionality spanning services | +| `REFACTOR` | Stage-based migration | Add new → migrate → remove old | +| `INVESTIGATION` | Bug hunting | Reproduce → investigate → fix | +| `MIGRATION` | Data migration | Prepare → test → execute → cleanup | +| `SIMPLE` | Single-service | Minimal overhead tasks | +| `DEVELOPMENT` | General dev work | Standard development | +| `ENHANCEMENT` | Improving existing | Updates to existing features | + +#### Phase Types + +| Type | Description | +|------|-------------| +| `SETUP` | Project scaffolding, environment setup | +| `IMPLEMENTATION` | Writing code | +| `INVESTIGATION` | Research, debugging, analysis | +| `INTEGRATION` | Wiring services together | +| `CLEANUP` | Removing old code, polish | + +#### Subtask Status Flow + +```mermaid +stateDiagram-v2 + [*] --> PENDING: Created + PENDING --> IN_PROGRESS: start() + IN_PROGRESS --> COMPLETED: complete() + IN_PROGRESS --> FAILED: fail() + FAILED --> IN_PROGRESS: retry + PENDING --> BLOCKED: dependency unmet + BLOCKED --> PENDING: dependency satisfied + COMPLETED --> [*] +``` + +### ImplementationPlan Model + +The main entry point for plan management. + +#### Key Methods + +```python +class ImplementationPlan: + def get_available_phases(self) -> list[Phase]: + """Get phases whose dependencies are satisfied.""" + + def get_next_subtask(self) -> tuple[Phase, Subtask] | None: + """Get the next subtask to work on, respecting dependencies.""" + + def get_progress(self) -> dict: + """Get overall progress statistics.""" + + def add_followup_phase( + self, + name: str, + subtasks: list[Subtask], + phase_type: PhaseType = PhaseType.IMPLEMENTATION, + parallel_safe: bool = False, + ) -> Phase: + """Add a new follow-up phase to an existing plan.""" + + def reset_for_followup(self) -> bool: + """Reset plan status from completed back to in_progress.""" +``` + +#### Progress Tracking + +```mermaid +flowchart TB + subgraph Progress["get_progress()"] + Total[Total Subtasks] + Done[Completed Subtasks] + Failed[Failed Subtasks] + Percent[Percent Complete] + IsComplete[Is Complete?] + end + + subgraph StatusSync["update_status_from_subtasks()"] + AllDone{All Done?} + AnyFailed{Any Failed?} + AnyInProgress{Any In Progress?} + AllPending{All Pending?} + end + + StatusSync --> AllDone + AllDone -->|Yes + QA| HumanReview[human_review] + AllDone -->|Yes| AIReview[ai_review] + AnyFailed -->|Yes| InProgress[in_progress] + AnyInProgress -->|Yes| InProgress + AllPending -->|Yes| Backlog[backlog] + + style Progress fill:#e3f2fd,stroke:#1976d2 + style StatusSync fill:#fff3e0,stroke:#f57c00 +``` + +#### Status Fields + +| Field | Values | Description | +|-------|--------|-------------| +| `status` | backlog, in_progress, ai_review, human_review, done | Overall task status | +| `planStatus` | pending, in_progress, review, completed | Plan execution status | + +### Phase Model + +Groups subtasks with dependency management. + +```python +@dataclass +class Phase: + phase: int # Phase number (1-indexed) + name: str # Human-readable name + type: PhaseType # Phase type + subtasks: list[Subtask] # Work items + depends_on: list[int] # Phase numbers that must complete first + parallel_safe: bool = False # Can subtasks run in parallel? +``` + +#### Dependency Resolution + +```mermaid +flowchart LR + subgraph Phases + P1[Phase 1: Setup] + P2[Phase 2: Backend] + P3[Phase 3: Frontend] + P4[Phase 4: Integration] + end + + P1 -->|depends_on| P2 + P1 -->|depends_on| P3 + P2 -->|depends_on| P4 + P3 -->|depends_on| P4 + + style P1 fill:#e8f5e9,stroke:#4caf50 + style P4 fill:#ffebee,stroke:#f44336 +``` + +### Subtask Model + +Represents a single unit of work. + +```python +@dataclass +class Subtask: + id: str # Unique identifier (e.g., "subtask-1-1") + description: str # What needs to be done + status: SubtaskStatus # Current status + service: str | None # Target service (backend, frontend, etc.) + all_services: bool = False # True for integration subtasks + files_to_modify: list[str] # Existing files to change + files_to_create: list[str] # New files to create + patterns_from: list[str] # Reference files for patterns + verification: Verification | None # How to verify completion + expected_output: str | None # For investigation subtasks + actual_output: str | None # What was discovered/done + session_id: int | None # Which session completed this +``` + +#### Subtask Lifecycle + +```mermaid +sequenceDiagram + participant Agent + participant Subtask + participant Plan + participant Recovery + + Agent->>Subtask: start(session_id) + Note over Subtask: status = IN_PROGRESS
started_at = now() + + alt Success + Agent->>Subtask: complete(output) + Note over Subtask: status = COMPLETED
completed_at = now() + Subtask->>Recovery: Record good commit + else Failure + Agent->>Subtask: fail(reason) + Note over Subtask: status = FAILED
actual_output = error + Subtask->>Recovery: Record failed attempt + end + + Agent->>Plan: save(path) +``` + +### Verification Model + +Defines how to verify subtask completion. + +```python +@dataclass +class Verification: + type: VerificationType # How to verify + run: str | None # Command to run + url: str | None # URL for API/browser tests + method: str | None # HTTP method + expect_status: int | None # Expected HTTP status + expect_contains: str | None # Expected content + scenario: str | None # Description for manual tests +``` + +#### Verification Types + +| Type | Usage | Example | +|------|-------|---------| +| `COMMAND` | Shell command | `npm test`, `pytest` | +| `API` | HTTP request | Health check endpoint | +| `BROWSER` | Browser automation | Playwright test | +| `COMPONENT` | Component render test | React component test | +| `MANUAL` | Human verification | Visual inspection | +| `NONE` | Investigation tasks | No verification needed | + +### Factory Functions + +The `factories.py` module provides helpers for creating plans: + +```python +def create_feature_plan( + feature: str, + services: list[str], + phases_config: list[dict], +) -> ImplementationPlan: + """Create a standard feature implementation plan.""" + +def create_investigation_plan( + bug_description: str, + services: list[str], +) -> ImplementationPlan: + """Create an investigation plan with structured debugging phases.""" + +def create_refactor_plan( + refactor_description: str, + services: list[str], + stages: list[dict], +) -> ImplementationPlan: + """Create a refactor plan with stage-based phases.""" +``` + +#### Investigation Plan Structure + +```mermaid +flowchart TB + subgraph Phase1["Phase 1: Reproduce & Instrument"] + AddLogging[Add detailed logging] + CreateRepro[Create reproduction steps] + end + + subgraph Phase2["Phase 2: Identify Root Cause"] + Analyze[Analyze logs and behavior] + end + + subgraph Phase3["Phase 3: Implement Fix"] + Fix[Apply fix] + RegressionTest[Add regression test] + end + + Phase1 --> Phase2 + Phase2 --> Phase3 + + style Phase1 fill:#fff3e0,stroke:#f57c00 + style Phase2 fill:#e3f2fd,stroke:#1976d2 + style Phase3 fill:#e8f5e9,stroke:#4caf50 +``` + +--- + +## Graphiti Integration + +Graphiti provides persistent cross-session memory using a knowledge graph database (LadybugDB). + +### Architecture + +```mermaid +flowchart TB + subgraph Agent["Agent Session"] + Coder[Coder Agent] + Memory[Memory Manager] + end + + subgraph Graphiti["Graphiti System"] + Config[GraphitiConfig] + Client[GraphitiMemory] + Search[Semantic Search] + Store[Episode Storage] + end + + subgraph Providers["Multi-Provider Support"] + LLM[LLM Provider] + Embedder[Embedder Provider] + end + + subgraph Storage["LadybugDB"] + Graph[Knowledge Graph] + Vectors[Vector Embeddings] + end + + Coder --> Memory + Memory --> Client + Client --> Config + Client --> Search + Client --> Store + Config --> Providers + Search --> Storage + Store --> Storage + + style Agent fill:#e3f2fd,stroke:#1976d2 + style Graphiti fill:#fff3e0,stroke:#f57c00 + style Storage fill:#e8f5e9,stroke:#4caf50 +``` + +### GraphitiConfig + +Configuration for multi-provider memory integration: + +```python +@dataclass +class GraphitiConfig: + # Core settings + enabled: bool = False + llm_provider: str = "openai" + embedder_provider: str = "openai" + + # Database settings (LadybugDB - embedded, no Docker required) + database: str = "auto_claude_memory" + db_path: str = "~/.auto-claude/memories" + + # Provider-specific settings + openai_api_key: str = "" + anthropic_api_key: str = "" + voyage_api_key: str = "" + google_api_key: str = "" + ollama_base_url: str = "http://localhost:11434" + + @classmethod + def from_env(cls) -> "GraphitiConfig": + """Create config from environment variables.""" + + def is_valid(self) -> bool: + """Check if config has minimum required values.""" + + def get_embedding_dimension(self) -> int: + """Get the embedding dimension for current provider.""" +``` + +### Supported Providers + +```mermaid +flowchart LR + subgraph LLMProviders["LLM Providers"] + OpenAI[OpenAI] + Anthropic[Anthropic] + AzureOAI[Azure OpenAI] + Google[Google AI] + Ollama[Ollama] + OpenRouter[OpenRouter] + end + + subgraph EmbedderProviders["Embedder Providers"] + OpenAIEmb[OpenAI] + Voyage[Voyage AI] + AzureEmb[Azure OpenAI] + GoogleEmb[Google AI] + OllamaEmb[Ollama] + OpenRouterEmb[OpenRouter] + end + + GraphitiConfig --> LLMProviders + GraphitiConfig --> EmbedderProviders + + style LLMProviders fill:#e3f2fd,stroke:#1976d2 + style EmbedderProviders fill:#fff3e0,stroke:#f57c00 +``` + +### Environment Variables + +| Variable | Description | Default | +|----------|-------------|---------| +| `GRAPHITI_ENABLED` | Enable Graphiti integration | false | +| `GRAPHITI_LLM_PROVIDER` | LLM provider | openai | +| `GRAPHITI_EMBEDDER_PROVIDER` | Embedder provider | openai | +| `GRAPHITI_DATABASE` | Database name | auto_claude_memory | +| `GRAPHITI_DB_PATH` | Database storage path | ~/.auto-claude/memories | +| `OPENAI_API_KEY` | OpenAI API key | - | +| `VOYAGE_API_KEY` | Voyage AI API key | - | +| `OLLAMA_EMBEDDING_MODEL` | Ollama embedding model | - | + +### Episode Types + +Memory is stored as episodes with semantic categorization: + +| Type | Description | +|------|-------------| +| `session_insight` | Session learnings and outcomes | +| `codebase_discovery` | File and pattern discoveries | +| `pattern` | Code patterns and conventions | +| `gotcha` | Pitfalls and warnings | +| `task_outcome` | Task completion results | +| `qa_result` | QA validation results | +| `historical_context` | Historical project context | + +### Memory Flow + +```mermaid +sequenceDiagram + participant Session as Agent Session + participant MemMgr as Memory Manager + participant Graphiti as GraphitiMemory + participant DB as LadybugDB + + Note over Session: Session Start + Session->>MemMgr: get_graphiti_context(subtask) + MemMgr->>Graphiti: Create instance + MemMgr->>Graphiti: get_relevant_context(query) + Graphiti->>DB: Semantic search + DB-->>Graphiti: Matching episodes + MemMgr->>Graphiti: get_session_history(limit=3) + Graphiti-->>MemMgr: Context items + MemMgr-->>Session: Formatted context + + Note over Session: Session End + Session->>MemMgr: save_session_memory(...) + MemMgr->>Graphiti: save_episode(insights) + Graphiti->>DB: Store with embeddings + DB-->>Graphiti: Saved + MemMgr-->>Session: (storage_type, success) +``` + +### GraphitiMemory API + +```python +class GraphitiMemory: + def __init__( + self, + spec_dir: Path, + project_dir: Path, + group_id_mode: str = "spec", + ): + """Initialize memory for a spec.""" + + async def get_relevant_context( + self, + query: str, + limit: int = 10, + ) -> list[dict]: + """Search for relevant context using semantic search.""" + + async def get_session_history( + self, + limit: int = 5, + ) -> list[dict]: + """Get recent session history.""" + + async def save_episode( + self, + content: str, + episode_type: str, + metadata: dict | None = None, + ) -> bool: + """Save a new episode to the knowledge graph.""" + + async def close(self) -> None: + """Close connections and cleanup.""" +``` + +### Group ID Modes + +| Mode | Description | Use Case | +|------|-------------|----------| +| `spec` | Isolated memory per spec | Default - each build has own context | +| `project` | Shared across project | Cross-build knowledge sharing | + +--- + +## Linear Integration + +Linear integration provides real-time task tracking visibility through Linear's project management system. + +### Architecture + +```mermaid +flowchart TB + subgraph AutoClaude["Auto-Claude"] + Orchestrator[Python Orchestrator] + Agent[Agent Session] + Plan[Implementation Plan] + end + + subgraph LinearInt["Linear Integration"] + Manager[LinearManager] + Updater[LinearUpdater] + Config[LinearConfig] + end + + subgraph LinearAPI["Linear (MCP)"] + Teams[Teams] + Projects[Projects] + Issues[Issues] + Comments[Comments] + end + + Orchestrator --> Manager + Orchestrator --> Updater + Agent --> Plan + Manager --> Config + Updater --> LinearAPI + Manager --> LinearAPI + + style AutoClaude fill:#e3f2fd,stroke:#1976d2 + style LinearInt fill:#fff3e0,stroke:#f57c00 + style LinearAPI fill:#e8f5e9,stroke:#4caf50 +``` + +### Design Principles + +1. **ONE task per spec** - Not one issue per subtask +2. **Python orchestrator controls** - Updates happen at key transitions +3. **Small focused prompts** - Can't lose context +4. **Graceful degradation** - Build continues if Linear unavailable + +### Status Flow + +```mermaid +stateDiagram-v2 + [*] --> Todo: Task created + Todo --> InProgress: Planner/Coder starts + InProgress --> InReview: All subtasks done + InReview --> Done: Human approves + InProgress --> InProgress: Subtask progress + + state InProgress { + [*] --> Planning + Planning --> Coding + Coding --> Coding: Next subtask + } +``` + +### LinearConfig + +```python +@dataclass +class LinearConfig: + api_key: str + team_id: str | None = None + project_id: str | None = None + project_name: str | None = None + meta_issue_id: str | None = None + enabled: bool = True + + @classmethod + def from_env(cls) -> "LinearConfig": + """Create config from environment variables.""" + + def is_valid(self) -> bool: + """Check if config has minimum required values.""" +``` + +### LinearManager + +High-level interface for Linear operations: + +```python +class LinearManager: + def __init__(self, spec_dir: Path, project_dir: Path): + """Initialize Linear manager.""" + + @property + def is_enabled(self) -> bool: + """Check if Linear integration is enabled.""" + + @property + def is_initialized(self) -> bool: + """Check if Linear project has been initialized.""" + + def get_issue_id(self, subtask_id: str) -> str | None: + """Get the Linear issue ID for a subtask.""" + + def set_issue_id(self, subtask_id: str, issue_id: str) -> None: + """Store subtask to issue mapping.""" + + def initialize_project(self, team_id: str, project_name: str) -> bool: + """Initialize a Linear project for this spec.""" + + def record_session_result( + self, + subtask_id: str, + session_num: int, + success: bool, + approach: str = "", + error: str = "", + git_commit: str = "", + ) -> str: + """Record a session result as a Linear comment.""" + + def prepare_stuck_escalation( + self, + subtask_id: str, + attempt_count: int, + attempts: list[dict], + reason: str = "", + ) -> dict: + """Prepare data for escalating a stuck subtask.""" +``` + +### LinearUpdater + +Python-orchestrated Linear updates via mini-agent calls: + +```python +async def create_linear_task( + spec_dir: Path, + title: str, + description: str | None = None, +) -> LinearTaskState | None: + """Create a new Linear task for a spec.""" + +async def update_linear_status( + spec_dir: Path, + new_status: str, +) -> bool: + """Update the Linear task status.""" + +async def add_linear_comment( + spec_dir: Path, + comment: str, +) -> bool: + """Add a comment to the Linear task.""" +``` + +### Convenience Functions + +| Function | Trigger | Description | +|----------|---------|-------------| +| `linear_task_started()` | Planner begins | Mark task In Progress | +| `linear_subtask_completed()` | Coder succeeds | Record completion comment | +| `linear_subtask_failed()` | Coder fails | Record failure comment | +| `linear_build_complete()` | All done | Record completion | +| `linear_qa_started()` | QA begins | Mark In Review | +| `linear_qa_approved()` | QA passes | Record approval | +| `linear_qa_rejected()` | QA fails | Record issues found | +| `linear_task_stuck()` | Max retries | Record stuck status | + +### Linear MCP Tools + +| Tool | Description | +|------|-------------| +| `mcp__linear-server__list_teams` | List available teams | +| `mcp__linear-server__create_issue` | Create a new issue | +| `mcp__linear-server__update_issue` | Update issue status | +| `mcp__linear-server__create_comment` | Add comment to issue | +| `mcp__linear-server__list_issue_statuses` | Get workflow states | + +### Status Mappings + +| Subtask Status | Linear Status | +|----------------|---------------| +| `pending` | Todo | +| `in_progress` | In Progress | +| `completed` | Done | +| `blocked` | Blocked | +| `failed` | Blocked | +| `stuck` | Blocked | + +### Priority Mapping + +Priority is based on phase position: + +| Position | Priority | Value | +|----------|----------|-------| +| First 25% | Urgent | 1 | +| 25-50% | High | 2 | +| 50-75% | Medium | 3 | +| Last 25% | Low | 4 | + +--- + +## Integration Points + +### Plan + Graphiti Flow + +```mermaid +sequenceDiagram + participant Plan as Implementation Plan + participant Agent as Coder Agent + participant Graphiti as Graphiti Memory + + Agent->>Plan: get_next_subtask() + Plan-->>Agent: (phase, subtask) + Agent->>Graphiti: get_relevant_context(subtask.description) + Graphiti-->>Agent: Historical context + + Note over Agent: Execute subtask with context + + Agent->>Plan: subtask.complete() + Agent->>Graphiti: save_episode(insights) + Agent->>Plan: save() +``` + +### Plan + Linear Flow + +```mermaid +sequenceDiagram + participant Orchestrator + participant Plan as Implementation Plan + participant Linear as Linear Updater + + Note over Orchestrator: Build starts + Orchestrator->>Linear: create_linear_task() + Orchestrator->>Linear: linear_task_started() + + loop For each subtask + Orchestrator->>Plan: get_next_subtask() + Note over Orchestrator: Execute subtask + alt Success + Orchestrator->>Linear: linear_subtask_completed() + else Failure + Orchestrator->>Linear: linear_subtask_failed() + end + end + + Note over Orchestrator: All done + Orchestrator->>Linear: linear_build_complete() + Orchestrator->>Linear: linear_qa_started() +``` + +## Error Handling + +### Graceful Degradation + +Both integrations are designed to fail gracefully: + +```mermaid +flowchart TB + subgraph Graphiti["Graphiti Fallback"] + TryG[Try Graphiti] + GraphitiOK{Success?} + FallbackFile[Fallback to File Storage] + end + + subgraph Linear["Linear Fallback"] + TryL[Try Linear Update] + LinearOK{Success?} + LocalOnly[Continue with Local Tracking] + end + + TryG --> GraphitiOK + GraphitiOK -->|Yes| Done1[Memory Saved] + GraphitiOK -->|No| FallbackFile + + TryL --> LinearOK + LinearOK -->|Yes| Done2[Updated] + LinearOK -->|No| LocalOnly + + style FallbackFile fill:#fff3e0,stroke:#f57c00 + style LocalOnly fill:#fff3e0,stroke:#f57c00 +``` + +### Key Error Behaviors + +| Scenario | Graphiti | Linear | +|----------|----------|--------| +| Not enabled | Skip silently | Skip silently | +| Connection failed | Fallback to file | Log warning, continue | +| API error | Fallback to file | Log error, continue | +| Invalid config | Return None | Return False | + +## Usage Examples + +### Creating a Plan + +```python +from implementation_plan import ImplementationPlan, create_feature_plan + +# Create from factory +plan = create_feature_plan( + feature="Add user authentication", + services=["backend", "frontend"], + phases_config=[ + { + "name": "Backend Setup", + "type": "implementation", + "subtasks": [ + { + "id": "subtask-1-1", + "description": "Add auth middleware", + "service": "backend", + "files_to_create": ["apps/backend/auth/middleware.py"], + } + ], + }, + { + "name": "Frontend Integration", + "type": "implementation", + "depends_on": [1], + "subtasks": [...], + }, + ], +) + +# Save plan +plan.save(spec_dir / "implementation_plan.json") +``` + +### Using Graphiti Memory + +```python +from integrations.graphiti import GraphitiMemory, is_graphiti_enabled + +if is_graphiti_enabled(): + memory = GraphitiMemory(spec_dir, project_dir) + + # Get context for a subtask + context = await memory.get_relevant_context( + "implement authentication middleware" + ) + + # Save session insights + await memory.save_episode( + content="Discovered auth pattern in existing code", + episode_type="codebase_discovery", + metadata={"file": "apps/backend/auth/existing.py"}, + ) + + await memory.close() +``` + +### Using Linear Integration + +```python +from integrations.linear import ( + is_linear_enabled, + create_linear_task, + linear_task_started, + linear_subtask_completed, +) + +if is_linear_enabled(): + # Create task at build start + state = await create_linear_task( + spec_dir, + title="Add user authentication", + description="Implement OAuth2 login flow", + ) + + # Mark as started + await linear_task_started(spec_dir) + + # Record subtask completion + await linear_subtask_completed( + spec_dir, + subtask_id="subtask-1-1", + completed_count=1, + total_count=5, + ) +``` + +## Next Steps + +- [Agents Module](./agents.md) - Agent system documentation +- [Context Module](./context.md) - Context building and search +- [CLI Module](./cli.md) - Command-line interface +- [Recovery Module](./recovery.md) - Error recovery and rollback From 4d52d4a4cd44ec5ab6d47143182adcfe6ce81b74 Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 22:09:46 +0200 Subject: [PATCH 14/27] auto-claude: subtask-4-1 - Create main process documentation covering AgentManager, IPC, terminal, and Python integration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/components/frontend/main-process.md | 830 +++++++++++++++++++++++ 1 file changed, 830 insertions(+) create mode 100644 docs/components/frontend/main-process.md diff --git a/docs/components/frontend/main-process.md b/docs/components/frontend/main-process.md new file mode 100644 index 0000000000..68cfe51904 --- /dev/null +++ b/docs/components/frontend/main-process.md @@ -0,0 +1,830 @@ +# Main Process Architecture + +The Electron main process serves as the backend of the Auto-Claude desktop application, orchestrating agent processes, managing terminals, handling IPC communication with the renderer, and integrating with Python backend scripts. It provides the core infrastructure that bridges the user interface with the autonomous coding system. + +## Module Overview + +```mermaid +flowchart TB + subgraph MainProcess["Main Process"] + Entry[index.ts
App Entry Point] + AgentMgr[AgentManager
Agent Orchestration] + TermMgr[TerminalManager
PTY Management] + IpcSetup[IPC Setup
Handler Registration] + PythonEnv[PythonEnvManager
Venv Management] + end + + subgraph AgentSubsystem["Agent Subsystem"] + AgentState[AgentState
Process Tracking] + AgentEvents[AgentEvents
Event Parsing] + AgentProcess[AgentProcessManager
Process Spawning] + AgentQueue[AgentQueueManager
Task Queuing] + end + + subgraph IpcHandlers["IPC Handlers"] + Project[project-handlers] + Task[task-handlers] + Terminal[terminal-handlers] + Settings[settings-handlers] + GitHub[github-handlers] + Linear[linear-handlers] + Context[context-handlers] + end + + subgraph TerminalSubsystem["Terminal Subsystem"] + PtyMgr[PTY Manager] + SessionHandler[Session Handler] + ClaudeInteg[Claude Integration] + EventHandler[Event Handler] + end + + Entry --> AgentMgr + Entry --> TermMgr + Entry --> IpcSetup + Entry --> PythonEnv + + AgentMgr --> AgentState + AgentMgr --> AgentEvents + AgentMgr --> AgentProcess + AgentMgr --> AgentQueue + + IpcSetup --> IpcHandlers + TermMgr --> TerminalSubsystem + + style MainProcess fill:#e3f2fd,stroke:#1976d2 + style AgentSubsystem fill:#e8f5e9,stroke:#4caf50 + style IpcHandlers fill:#fff3e0,stroke:#f57c00 + style TerminalSubsystem fill:#fce4ec,stroke:#e91e63 +``` + +## Directory Structure + +``` +apps/frontend/src/main/ +├── index.ts # Application entry point +├── ipc-setup.ts # IPC handler setup facade +├── agent-manager.ts # Legacy facade (re-exports) +├── terminal-manager.ts # Legacy facade (re-exports) +├── python-env-manager.ts # Python venv management +├── python-detector.ts # Python path detection +├── agent/ # Agent orchestration +│ ├── agent-manager.ts # Main orchestrator +│ ├── agent-state.ts # Process state tracking +│ ├── agent-events.ts # Event parsing +│ ├── agent-process.ts # Process spawning +│ ├── agent-queue.ts # Task queue management +│ ├── phase-event-parser.ts # Phase event parsing +│ └── types.ts # Type definitions +├── terminal/ # Terminal management +│ ├── terminal-manager.ts # Main terminal orchestrator +│ ├── pty-manager.ts # PTY process handling +│ ├── session-handler.ts # Session persistence +│ ├── terminal-lifecycle.ts # Create/destroy lifecycle +│ ├── claude-integration.ts # Claude Code integration +│ └── types.ts # Type definitions +├── ipc-handlers/ # IPC handler modules +│ ├── index.ts # Handler registration +│ ├── project-handlers.ts # Project CRUD +│ ├── task-handlers.ts # Task execution +│ ├── terminal-handlers.ts # Terminal operations +│ ├── settings-handlers.ts # App settings +│ ├── github-handlers.ts # GitHub integration +│ ├── linear-handlers.ts # Linear integration +│ ├── context-handlers.ts # Project context +│ └── ... # Other handlers +└── claude-profile/ # Claude profile management + ├── profile-storage.ts # Profile persistence + ├── usage-monitor.ts # Usage tracking + └── rate-limit-manager.ts # Rate limit handling +``` + +## Application Lifecycle + +```mermaid +sequenceDiagram + participant App as Electron App + participant Main as Main Process + participant Agent as AgentManager + participant Terminal as TerminalManager + participant IPC as IPC Handlers + participant Window as BrowserWindow + participant Python as PythonEnvManager + + App->>Main: app.whenReady() + Main->>Main: setAppUserModelId() + Main->>Agent: new AgentManager() + Main->>Agent: configure(pythonPath, autoBuildPath) + Main->>Terminal: new TerminalManager() + Main->>IPC: setupIpcHandlers() + Main->>Window: createWindow() + Main->>Main: initializeUsageMonitor() + Main->>Main: initializeAppUpdater() + + Note over App,Python: Runtime Operations + + App->>Main: window-all-closed + Main->>Main: Check platform + alt Not macOS + Main->>App: app.quit() + end + + App->>Main: before-quit + Main->>Main: Stop usage monitor + Main->>Agent: killAll() + Main->>Terminal: killAll() +``` + +## AgentManager + +The `AgentManager` is the central orchestrator for all agent-related operations, including spec creation, task execution, roadmap generation, and ideation. + +### Class Diagram + +```mermaid +classDiagram + class AgentManager { + -state: AgentState + -events: AgentEvents + -processManager: AgentProcessManager + -queueManager: AgentQueueManager + -taskExecutionContext: Map + +configure(pythonPath, autoBuildPath) + +startSpecCreation(taskId, projectPath, taskDescription, specDir, metadata) + +startTaskExecution(taskId, projectPath, specId, options) + +startQAProcess(taskId, projectPath, specId) + +startRoadmapGeneration(projectId, projectPath, refresh, enableCompetitor) + +startIdeationGeneration(projectId, projectPath, config, refresh) + +killTask(taskId): boolean + +killAll(): Promise + +isRunning(taskId): boolean + +getRunningTasks(): string[] + +restartTask(taskId, newProfileId): boolean + } + + class AgentState { + -processes: Map~string, AgentProcessInfo~ + -killedSpawns: Set~number~ + +addProcess(taskId, info) + +getProcess(taskId): AgentProcessInfo + +deleteProcess(taskId) + +hasProcess(taskId): boolean + +getRunningTaskIds(): string[] + +generateSpawnId(): number + +markSpawnAsKilled(spawnId) + +wasSpawnKilled(spawnId): boolean + } + + class AgentEvents { + +parseExecutionPhase(line, currentPhase, isSpecRunner): PhaseUpdate + +calculateOverallProgress(phase, phaseProgress): number + } + + class AgentProcessManager { + -state: AgentState + -events: AgentEvents + -_pythonPath: string + -autoBuildSourcePath: string + +configure(pythonPath, autoBuildPath) + +spawnProcess(taskId, cwd, args, env, processType) + +killProcess(taskId): boolean + +killAllProcesses(): Promise + +getPythonPath(): string + +getAutoBuildSourcePath(): string + +getCombinedEnv(projectPath): Record + } + + class AgentQueueManager { + -state: AgentState + -events: AgentEvents + -processManager: AgentProcessManager + +startRoadmapGeneration(...) + +startIdeationGeneration(...) + +stopRoadmap(projectId): boolean + +stopIdeation(projectId): boolean + +isRoadmapRunning(projectId): boolean + +isIdeationRunning(projectId): boolean + } + + AgentManager --> AgentState + AgentManager --> AgentEvents + AgentManager --> AgentProcessManager + AgentManager --> AgentQueueManager + AgentProcessManager --> AgentState + AgentProcessManager --> AgentEvents + AgentQueueManager --> AgentState + AgentQueueManager --> AgentProcessManager +``` + +### Task Execution Flow + +```mermaid +flowchart TB + Start[Start Task] + AuthCheck{Auth Valid?} + PathCheck{Auto-build
Path Found?} + ScriptCheck{Script
Exists?} + GetEnv[Get Combined Env] + StoreContext[Store Task Context] + SpawnProcess[Spawn Python Process] + + subgraph ProcessLifecycle["Process Lifecycle"] + Running[Running] + ParseOutput[Parse Output] + EmitProgress[Emit Progress Events] + HandleExit[Handle Exit] + end + + subgraph ErrorHandling["Error Handling"] + CheckRateLimit{Rate Limited?} + CheckAuth{Auth Failed?} + AutoSwap{Auto-Swap
Enabled?} + ManualModal[Show Manual Modal] + SwapProfile[Swap Profile] + RestartTask[Restart Task] + end + + Start --> AuthCheck + AuthCheck -->|No| EmitError[Emit Error] + AuthCheck -->|Yes| PathCheck + PathCheck -->|No| EmitError + PathCheck -->|Yes| ScriptCheck + ScriptCheck -->|No| EmitError + ScriptCheck -->|Yes| GetEnv + GetEnv --> StoreContext + StoreContext --> SpawnProcess + SpawnProcess --> Running + Running --> ParseOutput + ParseOutput --> EmitProgress + EmitProgress --> Running + Running -->|Exit| HandleExit + + HandleExit -->|Code != 0| CheckRateLimit + CheckRateLimit -->|Yes| AutoSwap + CheckRateLimit -->|No| CheckAuth + AutoSwap -->|Yes| SwapProfile + AutoSwap -->|No| ManualModal + SwapProfile --> RestartTask + CheckAuth -->|Yes| EmitAuthFailure[Emit Auth Failure] + CheckAuth -->|No| EmitExit[Emit Exit] + + style ProcessLifecycle fill:#e8f5e9,stroke:#4caf50 + style ErrorHandling fill:#ffebee,stroke:#f44336 +``` + +### Event Emissions + +| Event | Description | Payload | +|-------|-------------|---------| +| `execution-progress` | Phase progress update | `{ phase, phaseProgress, overallProgress, message }` | +| `log` | Process output line | `taskId, line` | +| `exit` | Process exited | `taskId, code, processType` | +| `error` | Error occurred | `taskId, message` | +| `sdk-rate-limit` | Rate limit detected | `{ source, resetTime, profileId, ... }` | +| `auth-failure` | Authentication failed | `taskId, { profileId, failureType, message }` | +| `auto-swap-restart-task` | Auto-swap triggered restart | `taskId, newProfileId` | + +### Execution Phases + +```mermaid +stateDiagram-v2 + [*] --> planning: Start + planning --> coding: Plan approved + coding --> qa: Code complete + qa --> complete: QA passed + qa --> coding: QA failed + coding --> failed: Error + planning --> failed: Error + complete --> [*] + failed --> [*] +``` + +## IPC Handler System + +The IPC system bridges the renderer process (UI) with the main process, organized into domain-specific handler modules. + +### Handler Registration Flow + +```mermaid +flowchart LR + subgraph Setup["setupIpcHandlers()"] + Init[Initialize Services] + RegisterAll[Register All Handlers] + end + + subgraph Handlers["Handler Modules"] + Project[Project
CRUD, init] + Task[Task
Execution] + Terminal[Terminal
PTY, Claude] + Settings[Settings
Config, dialogs] + GitHub[GitHub
PRs, issues] + Linear[Linear
Integration] + Context[Context
Memory] + File[File
Explorer] + Roadmap[Roadmap
Generation] + Ideation[Ideation
Ideas] + Changelog[Changelog
Generation] + Insights[Insights
AI chat] + Memory[Memory
Graphiti] + AppUpdate[Updates
Auto-update] + end + + Init --> RegisterAll + RegisterAll --> Handlers + + style Setup fill:#e3f2fd,stroke:#1976d2 +``` + +### IPC Communication Pattern + +```mermaid +sequenceDiagram + participant Renderer + participant Preload + participant Main + participant Handler + + Renderer->>Preload: window.api.invoke('channel', args) + Preload->>Main: ipcMain.handle('channel') + Main->>Handler: handleFunction(args) + Handler-->>Main: result + Main-->>Preload: result + Preload-->>Renderer: Promise resolution + + Note over Main,Handler: Event Forwarding + + Handler->>Main: mainWindow.webContents.send('event') + Main->>Preload: ipcRenderer.on('event') + Preload->>Renderer: callback(data) +``` + +### Key IPC Channels + +| Domain | Invoke Channels | Send Channels | +|--------|----------------|---------------| +| Project | `project:list`, `project:create`, `project:delete` | `project:updated` | +| Task | `task:start`, `task:stop`, `task:status` | `task:progress`, `task:complete` | +| Terminal | `terminal:create`, `terminal:write`, `terminal:resize` | `terminal:data`, `terminal:exit` | +| Agent | `agent:start-spec`, `agent:start-task`, `agent:kill` | `agent:log`, `agent:progress`, `agent:exit` | +| Settings | `settings:get`, `settings:save`, `dialog:open-folder` | `settings:changed` | +| GitHub | `github:get-prs`, `github:create-pr`, `github:import-repo` | `github:oauth-success` | + +## Terminal Management + +The `TerminalManager` handles PTY (pseudo-terminal) processes, integrating with Claude Code for AI-powered terminal sessions. + +### Architecture + +```mermaid +flowchart TB + subgraph TerminalManager["TerminalManager"] + Main[Main Orchestrator] + Terminals[terminals: Map] + end + + subgraph Modules["Modular Components"] + PtyMgr[pty-manager.ts
PTY Operations] + Session[session-handler.ts
Persistence] + Lifecycle[terminal-lifecycle.ts
Create/Destroy] + Events[terminal-event-handler.ts
Output Parsing] + Claude[claude-integration.ts
Claude Code] + end + + subgraph External["External"] + NodePty[node-pty
PTY Library] + ClaudeCode[Claude Code CLI] + SessionStore[Session Store
File System] + end + + Main --> PtyMgr + Main --> Session + Main --> Lifecycle + Main --> Events + Main --> Claude + + PtyMgr --> NodePty + Claude --> ClaudeCode + Session --> SessionStore + + style TerminalManager fill:#e3f2fd,stroke:#1976d2 + style Modules fill:#e8f5e9,stroke:#4caf50 + style External fill:#fff3e0,stroke:#f57c00 +``` + +### Terminal Lifecycle + +```mermaid +stateDiagram-v2 + [*] --> Created: create() + Created --> Active: PTY spawned + Active --> ClaudeMode: invokeClaude() + ClaudeMode --> Active: Claude exits + Active --> Active: write(), resize() + Active --> Destroyed: destroy() + ClaudeMode --> Destroyed: destroy() + + state ClaudeMode { + [*] --> Running + Running --> RateLimited: Rate limit detected + RateLimited --> ProfileSwitch: Auto-swap + ProfileSwitch --> Running: New profile + Running --> Exited: Session ends + } + + Destroyed --> [*] +``` + +### TerminalProcess Interface + +```mermaid +classDiagram + class TerminalProcess { + +id: string + +pty: IPty + +shell: string + +cwd: string + +title: string + +isClaudeMode: boolean + +claudeSessionId?: string + +claudeProfileId?: string + +projectPath?: string + +createdAt: Date + +scrollbackBuffer: string + } + + class TerminalManager { + -terminals: Map~string, TerminalProcess~ + -getWindow: WindowGetter + +create(options): Promise~Result~ + +restore(session): Promise~Result~ + +destroy(id): Promise~Result~ + +killAll(): Promise + +write(id, data): void + +resize(id, cols, rows): void + +invokeClaude(id, cwd, profileId): void + +switchClaudeProfile(id, profileId): Promise~Result~ + +resumeClaude(id, sessionId): void + +getSavedSessions(projectPath): Session[] + +isClaudeMode(id): boolean + } + + TerminalManager --> TerminalProcess +``` + +### Session Persistence + +```mermaid +flowchart LR + subgraph Runtime["Active Sessions"] + T1[Terminal 1] + T2[Terminal 2] + T3[Terminal 3] + end + + subgraph Persistence["Session Storage"] + Timer[30s Timer] + Store[SessionStore] + Files[JSON Files] + end + + subgraph Restore["Session Restore"] + Load[Load Sessions] + Recreate[Recreate PTYs] + Resume[Resume Claude] + end + + Runtime -->|Periodic Save| Timer + Timer --> Store + Store --> Files + + Files -->|App Restart| Load + Load --> Recreate + Recreate --> Resume + Resume --> Runtime + + style Runtime fill:#e8f5e9,stroke:#4caf50 + style Persistence fill:#e3f2fd,stroke:#1976d2 + style Restore fill:#fff3e0,stroke:#f57c00 +``` + +## Python Integration + +The `PythonEnvManager` manages the Python virtual environment required for running Auto-Claude backend scripts. + +### Environment Setup Flow + +```mermaid +flowchart TB + Start[initialize()] + CheckProgress{Already
initializing?} + WaitExisting[Wait for existing] + CheckReady{Already
ready?} + ReturnCached[Return cached status] + + subgraph Setup["Environment Setup"] + CheckVenv{Venv exists?} + CreateVenv[Create venv] + CheckDeps{Deps installed?} + InstallDeps[Install requirements.txt] + end + + Ready[Ready] + Error[Error] + + Start --> CheckProgress + CheckProgress -->|Yes| WaitExisting + CheckProgress -->|No| CheckReady + CheckReady -->|Yes| ReturnCached + CheckReady -->|No| CheckVenv + + CheckVenv -->|No| CreateVenv + CheckVenv -->|Yes| CheckDeps + CreateVenv -->|Success| CheckDeps + CreateVenv -->|Fail| Error + + CheckDeps -->|No| InstallDeps + CheckDeps -->|Yes| Ready + InstallDeps -->|Success| Ready + InstallDeps -->|Fail| Error + + style Setup fill:#e8f5e9,stroke:#4caf50 +``` + +### Python Path Resolution + +```mermaid +flowchart TB + subgraph Resolution["Python Path Resolution"] + VenvReady{Venv ready?} + VenvPath[Return venv Python] + FindPython[findPythonCommand()] + BundledExists{Bundled
Python?} + BundledPath[Return bundled] + SystemPython[Find system Python] + ValidVersion{Python 3.10+?} + ReturnSystem[Return system Python] + Fallback[Return 'python'] + end + + VenvReady -->|Yes| VenvPath + VenvReady -->|No| FindPython + FindPython --> BundledExists + BundledExists -->|Yes| BundledPath + BundledExists -->|No| SystemPython + SystemPython --> ValidVersion + ValidVersion -->|Yes| ReturnSystem + ValidVersion -->|No| Fallback + + style Resolution fill:#e3f2fd,stroke:#1976d2 +``` + +### Venv Location Strategy + +| Environment | Venv Path | Reason | +|-------------|-----------|--------| +| Development | `{source}/.venv` | Standard location in source | +| Packaged (Windows/Mac) | `{source}/.venv` | Writable app resources | +| Packaged (Linux AppImage) | `{userData}/python-venv` | AppImage resources are read-only | + +### PythonEnvManager Class + +```mermaid +classDiagram + class PythonEnvManager { + -autoBuildSourcePath: string + -pythonPath: string + -isInitializing: boolean + -isReady: boolean + -initializationPromise: Promise + +initialize(autoBuildSourcePath): Promise~Status~ + +getPythonPath(): string + +isEnvReady(): boolean + +getStatus(): Promise~Status~ + -getVenvBasePath(): string + -getVenvPythonPath(): string + -venvExists(): boolean + -checkDepsInstalled(): Promise~boolean~ + -createVenv(): Promise~boolean~ + -bootstrapPip(): Promise~boolean~ + -installDeps(): Promise~boolean~ + -findSystemPython(): string + } + + class PythonEnvStatus { + +ready: boolean + +pythonPath: string + +venvExists: boolean + +depsInstalled: boolean + +error?: string + } + + PythonEnvManager --> PythonEnvStatus : returns +``` + +## Rate Limit Handling + +The main process includes sophisticated rate limit detection and automatic profile switching. + +### Rate Limit Detection Flow + +```mermaid +flowchart TB + Output[Process Output] + Detect[detectRateLimit()] + + subgraph Detection["Pattern Detection"] + SDKPattern[SDK Rate Limit Pattern] + APIPattern[API Rate Limit Pattern] + ParseReset[Parse Reset Time] + ParseProfile[Parse Profile ID] + end + + subgraph Response["Response Handling"] + AutoSwapEnabled{Auto-swap
enabled?} + FindProfile[Find best profile] + ProfileAvailable{Profile
available?} + SwapProfile[Swap to new profile] + RestartTask[Restart task] + ShowModal[Show manual modal] + end + + Output --> Detect + Detect --> Detection + Detection --> AutoSwapEnabled + + AutoSwapEnabled -->|Yes| FindProfile + AutoSwapEnabled -->|No| ShowModal + FindProfile --> ProfileAvailable + ProfileAvailable -->|Yes| SwapProfile + ProfileAvailable -->|No| ShowModal + SwapProfile --> RestartTask + + style Detection fill:#e3f2fd,stroke:#1976d2 + style Response fill:#e8f5e9,stroke:#4caf50 +``` + +### Auto-Swap Mechanism + +```mermaid +sequenceDiagram + participant Process as Agent Process + participant Detector as Rate Limit Detector + participant ProfileMgr as Profile Manager + participant AgentMgr as Agent Manager + + Process->>Detector: Output with rate limit + Detector->>Detector: Parse rate limit info + Detector->>ProfileMgr: getAutoSwitchSettings() + + alt Auto-switch enabled + Detector->>ProfileMgr: getBestAvailableProfile() + ProfileMgr-->>Detector: Best profile + + alt Profile available + Detector->>ProfileMgr: setActiveProfile(newProfile) + Detector->>AgentMgr: emit('auto-swap-restart-task') + AgentMgr->>AgentMgr: restartTask() + else No profile + Detector->>Process: emit('sdk-rate-limit') [manual] + end + else Auto-switch disabled + Detector->>Process: emit('sdk-rate-limit') [manual] + end +``` + +## Window Management + +### BrowserWindow Configuration + +```mermaid +flowchart LR + subgraph Config["Window Configuration"] + Size[1400x900
min: 1000x700] + TitleBar[Hidden Title Bar
macOS inset] + WebPrefs[Web Preferences] + end + + subgraph WebPreferences["Security Settings"] + Preload[Preload Script] + Sandbox[sandbox: false] + Context[contextIsolation: true] + NodeInt[nodeIntegration: false] + Background[backgroundThrottling: false] + end + + subgraph DevMode["Development Mode"] + DevTools[Open DevTools] + HMR[Hot Module Reload] + RendererURL[Load from URL] + end + + subgraph ProdMode["Production Mode"] + LoadFile[Load index.html] + AutoUpdate[Auto-updater] + end + + Config --> WebPreferences + WebPreferences --> DevMode + WebPreferences --> ProdMode + + style Config fill:#e3f2fd,stroke:#1976d2 + style WebPreferences fill:#ffebee,stroke:#f44336 +``` + +### Platform-Specific Behavior + +| Platform | Behavior | +|----------|----------| +| macOS | Hidden title bar with traffic lights, dock icon, re-create window on activate | +| Windows | App user model ID for taskbar grouping, auto-hide menu bar | +| Linux | AppImage-compatible venv path, standard window controls | + +## Error Handling + +### Global Error Handlers + +```typescript +// Uncaught exceptions +process.on('uncaughtException', (error) => { + console.error('Uncaught exception:', error); +}); + +// Unhandled promise rejections +process.on('unhandledRejection', (reason) => { + console.error('Unhandled rejection:', reason); +}); +``` + +### Cleanup on Quit + +```mermaid +flowchart LR + BeforeQuit[before-quit event] + StopMonitor[Stop usage monitor] + KillAgents[Kill all agent processes] + KillTerminals[Kill all terminal processes] + Exit[App exits] + + BeforeQuit --> StopMonitor + StopMonitor --> KillAgents + KillAgents --> KillTerminals + KillTerminals --> Exit +``` + +## Integration Points + +### External Dependencies + +```mermaid +flowchart TB + subgraph Main["Main Process"] + AgentMgr[AgentManager] + TermMgr[TerminalManager] + PythonMgr[PythonEnvManager] + end + + subgraph Backend["Python Backend"] + SpecRunner[spec_runner.py] + RunPy[run.py] + Roadmap[roadmap_runner.py] + Ideation[ideation_runner.py] + end + + subgraph External["External Services"] + ClaudeSDK[Claude Agent SDK] + NodePty[node-pty] + Git[Git CLI] + end + + subgraph Renderer["Renderer Process"] + UI[React UI] + Store[Zustand Store] + end + + AgentMgr -->|Spawn| Backend + Backend -->|via| ClaudeSDK + TermMgr -->|via| NodePty + PythonMgr -->|Detect| Python[Python 3.10+] + Main <-->|IPC| Renderer + + style Main fill:#e3f2fd,stroke:#1976d2 + style Backend fill:#e8f5e9,stroke:#4caf50 + style External fill:#fff3e0,stroke:#f57c00 +``` + +### Key Dependencies + +| Module | Dependency | Purpose | +|--------|------------|---------| +| AgentManager | `child_process` | Spawn Python processes | +| AgentManager | `claude-profile-manager` | Profile authentication | +| TerminalManager | `node-pty` | PTY process management | +| TerminalManager | Claude Code CLI | AI-powered terminals | +| PythonEnvManager | `child_process` | Venv creation, pip install | +| IPC Handlers | `electron.ipcMain` | Process communication | + +## Next Steps + +- [Renderer Process](./renderer-process.md) - React UI architecture +- [Preload Bridge](./preload-bridge.md) - IPC bridge and API exposure +- [State Management](./state-management.md) - Zustand stores +- [Backend Integration](../architecture/integration.md) - Python backend connection From 81917d766f89179737020856cec7ef79361212e0 Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 22:15:42 +0200 Subject: [PATCH 15/27] auto-claude: subtask-4-2 - Create IPC handlers documentation covering all han MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add comprehensive IPC handlers documentation with 25+ Mermaid diagrams covering: - Module overview and structure - IPC communication architecture (request/response and event patterns) - Handler registration flow - Core handlers: Project, Task, Terminal, Agent Events, Settings, File - Feature handlers: Roadmap, Changelog, Ideation, Insights, Context, Env - Integration handlers: Linear, GitHub, Memory (Graphiti/Ollama) - System handlers: Auto-Build Source, App Updates - IPCResult pattern, error handling, and security considerations 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/components/frontend/ipc-handlers.md | 1294 ++++++++++++++++++++++ 1 file changed, 1294 insertions(+) create mode 100644 docs/components/frontend/ipc-handlers.md diff --git a/docs/components/frontend/ipc-handlers.md b/docs/components/frontend/ipc-handlers.md new file mode 100644 index 0000000000..a1cabe100f --- /dev/null +++ b/docs/components/frontend/ipc-handlers.md @@ -0,0 +1,1294 @@ +# IPC Handlers + +The IPC (Inter-Process Communication) handlers module provides the communication layer between Electron's main process and renderer process. It organizes all IPC handlers by domain into separate modules for maintainability and clear separation of concerns. + +## Module Overview + +The IPC handlers are organized into domain-specific modules, each handling a specific area of functionality: + +```mermaid +flowchart TB + subgraph Setup["setupIpcHandlers()"] + Init[Initialize Services] + end + + subgraph Core["Core Handlers"] + Project[Project Handlers] + Task[Task Handlers] + Terminal[Terminal Handlers] + AgentEvents[Agent Events] + Settings[Settings Handlers] + File[File Handlers] + end + + subgraph Features["Feature Handlers"] + Roadmap[Roadmap Handlers] + Context[Context Handlers] + Env[Environment Handlers] + Changelog[Changelog Handlers] + Ideation[Ideation Handlers] + Insights[Insights Handlers] + end + + subgraph Integrations["Integration Handlers"] + Linear[Linear Handlers] + GitHub[GitHub Handlers] + Memory[Memory Handlers] + end + + subgraph System["System Handlers"] + AutoBuild[Auto-Build Source] + AppUpdate[App Update Handlers] + end + + Setup --> Core + Setup --> Features + Setup --> Integrations + Setup --> System + + style Setup fill:#e3f2fd,stroke:#1976d2 + style Core fill:#e8f5e9,stroke:#4caf50 + style Features fill:#fff3e0,stroke:#f57c00 + style Integrations fill:#fce4ec,stroke:#e91e63 + style System fill:#f3e5f5,stroke:#9c27b0 +``` + +## Module Structure + +``` +apps/frontend/src/main/ipc-handlers/ +├── index.ts # Main setup function, exports all handlers +├── project-handlers.ts # Project CRUD, Git operations, Python env +├── task-handlers.ts # Task entry point (delegates to task/) +├── task/ # Task module subdirectory +│ ├── index.ts # Task handler registration +│ ├── crud-handlers.ts # Create, Read, Update, Delete +│ ├── execution-handlers.ts # Start, Stop, Review, Status +│ ├── worktree-handlers.ts # Git worktree operations +│ ├── logs-handlers.ts # Task log management +│ └── shared.ts # Shared utilities +├── terminal-handlers.ts # Terminal/PTY management, Claude profiles +├── agent-events-handlers.ts # Event forwarding to renderer +├── settings-handlers.ts # App settings, dialogs +├── file-handlers.ts # File explorer operations +├── roadmap-handlers.ts # Roadmap generation/management +├── context-handlers.ts # Context entry point (delegates to context/) +├── context/ # Context module subdirectory +│ ├── index.ts # Context handler registration +│ ├── memory-status-handlers.ts +│ ├── memory-data-handlers.ts +│ └── project-context-handlers.ts +├── env-handlers.ts # Environment configuration +├── linear-handlers.ts # Linear integration +├── github-handlers.ts # GitHub entry point (delegates to github/) +├── github/ # GitHub module subdirectory +│ ├── index.ts # GitHub handler registration +│ ├── repository-handlers.ts +│ ├── issue-handlers.ts +│ ├── investigation-handlers.ts +│ ├── import-handlers.ts +│ ├── release-handlers.ts +│ ├── utils.ts +│ ├── spec-utils.ts +│ └── types.ts +├── ideation-handlers.ts # Ideation entry point (delegates to ideation/) +├── ideation/ # Ideation module subdirectory +├── changelog-handlers.ts # Changelog generation +├── insights-handlers.ts # AI insights/chat +├── memory-handlers.ts # Memory infrastructure (Graphiti/LadybugDB) +├── autobuild-source-handlers.ts # Source updates +├── app-update-handlers.ts # Electron auto-updates +└── utils.ts # Shared utility functions +``` + +## Communication Architecture + +### IPC Communication Flow + +```mermaid +sequenceDiagram + participant R as Renderer Process + participant P as Preload Script + participant M as Main Process + participant H as IPC Handlers + participant S as Services + + R->>P: window.api.invoke(channel, data) + P->>M: ipcRenderer.invoke(channel, data) + M->>H: ipcMain.handle(channel, handler) + H->>S: Call service methods + S-->>H: Service result + H-->>M: IPCResult + M-->>P: Response + P-->>R: Resolved promise + + Note over R,S: Request/Response Pattern (ipcMain.handle) +``` + +### Event-Based Communication + +```mermaid +sequenceDiagram + participant S as Services/Managers + participant H as IPC Handlers + participant M as Main Process + participant R as Renderer Process + + S->>H: Emit event (e.g., 'log', 'progress') + H->>M: mainWindow.webContents.send(channel, data) + M->>R: ipcRenderer.on(channel, callback) + R->>R: Update UI state + + Note over S,R: Push Pattern (webContents.send) +``` + +## Handler Registration Flow + +```mermaid +flowchart TB + subgraph Main["Main Process Startup"] + CreateWindow[Create BrowserWindow] + GetManagers[Get AgentManager, TerminalManager] + GetPythonEnv[Get PythonEnvManager] + end + + subgraph Setup["setupIpcHandlers()"] + InitNotify[Initialize Notification Service] + RegProject[Register Project Handlers] + RegTask[Register Task Handlers] + RegTerminal[Register Terminal Handlers] + RegAgent[Register Agent Events] + RegSettings[Register Settings Handlers] + RegFile[Register File Handlers] + RegRoadmap[Register Roadmap Handlers] + RegContext[Register Context Handlers] + RegEnv[Register Env Handlers] + RegLinear[Register Linear Handlers] + RegGithub[Register GitHub Handlers] + RegAutoBuild[Register AutoBuild Handlers] + RegIdeation[Register Ideation Handlers] + RegChangelog[Register Changelog Handlers] + RegInsights[Register Insights Handlers] + RegMemory[Register Memory Handlers] + RegAppUpdate[Register App Update Handlers] + end + + Main --> Setup + CreateWindow --> InitNotify + GetManagers --> RegProject + RegProject --> RegTask + RegTask --> RegTerminal + RegTerminal --> RegAgent + RegAgent --> RegSettings + RegSettings --> RegFile + RegFile --> RegRoadmap + RegRoadmap --> RegContext + RegContext --> RegEnv + RegEnv --> RegLinear + RegLinear --> RegGithub + RegGithub --> RegAutoBuild + RegAutoBuild --> RegIdeation + RegIdeation --> RegChangelog + RegChangelog --> RegInsights + RegInsights --> RegMemory + RegMemory --> RegAppUpdate + + style Main fill:#e3f2fd,stroke:#1976d2 + style Setup fill:#e8f5e9,stroke:#4caf50 +``` + +## Core Handlers + +### Project Handlers + +Manages project lifecycle, Git operations, and Python environment initialization. + +```mermaid +flowchart TB + subgraph ProjectOps["Project Operations"] + Add[PROJECT_ADD] + Remove[PROJECT_REMOVE] + List[PROJECT_LIST] + UpdateSettings[PROJECT_UPDATE_SETTINGS] + Initialize[PROJECT_INITIALIZE] + CheckVersion[PROJECT_CHECK_VERSION] + HasLocalSource[project:has-local-source] + end + + subgraph TabState["Tab State"] + TabGet[TAB_STATE_GET] + TabSave[TAB_STATE_SAVE] + end + + subgraph GitOps["Git Operations"] + GetBranches[GIT_GET_BRANCHES] + GetCurrentBranch[GIT_GET_CURRENT_BRANCH] + DetectMain[GIT_DETECT_MAIN_BRANCH] + CheckStatus[GIT_CHECK_STATUS] + GitInit[GIT_INITIALIZE] + end + + subgraph PythonEnv["Python Environment"] + GetStatus[python-env:get-status] + Reinit[python-env:reinitialize] + StatusEvent[python-env:status] + ErrorEvent[python-env:error] + ReadyEvent[python-env:ready] + end + + ProjectStore[(Project Store)] + PythonManager[Python Env Manager] + + ProjectOps --> ProjectStore + TabState --> ProjectStore + GitOps --> Git[Git Commands] + PythonEnv --> PythonManager + + style ProjectOps fill:#e3f2fd,stroke:#1976d2 + style TabState fill:#fff3e0,stroke:#f57c00 + style GitOps fill:#e8f5e9,stroke:#4caf50 + style PythonEnv fill:#fce4ec,stroke:#e91e63 +``` + +#### Key IPC Channels + +| Channel | Type | Description | +|---------|------|-------------| +| `PROJECT_ADD` | handle | Add a new project to the workspace | +| `PROJECT_REMOVE` | handle | Remove a project from the workspace | +| `PROJECT_LIST` | handle | Get all projects with validation | +| `PROJECT_UPDATE_SETTINGS` | handle | Update project-specific settings | +| `PROJECT_INITIALIZE` | handle | Initialize .auto-claude in project | +| `GIT_GET_BRANCHES` | handle | List all git branches | +| `GIT_DETECT_MAIN_BRANCH` | handle | Auto-detect main/master branch | +| `python-env:get-status` | handle | Get Python environment status | +| `python-env:reinitialize` | handle | Reinitialize Python venv | + +### Task Handlers + +Organized into focused submodules for task management, execution, and worktree operations. + +```mermaid +flowchart TB + subgraph Entry["task-handlers.ts"] + Register[registerTaskHandlers] + end + + subgraph CRUD["crud-handlers.ts"] + TaskGet[TASK_GET] + TaskGetAll[TASK_GET_ALL] + TaskCreate[TASK_CREATE] + TaskDelete[TASK_DELETE] + TaskUpdateMeta[TASK_UPDATE_METADATA] + end + + subgraph Execution["execution-handlers.ts"] + TaskStart[TASK_START] + TaskStop[TASK_STOP] + TaskReview[TASK_REVIEW] + TaskRestart[TASK_RESTART] + TaskRecovery[TASK_RECOVERY_INFO] + end + + subgraph Worktree["worktree-handlers.ts"] + WorktreeStatus[WORKTREE_STATUS] + WorktreeDiff[WORKTREE_DIFF] + WorktreeMerge[WORKTREE_MERGE] + WorktreeDiscard[WORKTREE_DISCARD] + WorktreeList[WORKTREE_LIST] + end + + subgraph Logs["logs-handlers.ts"] + LogsGet[TASK_LOGS_GET] + LogsWatch[TASK_LOGS_WATCH] + LogsUnwatch[TASK_LOGS_UNWATCH] + end + + Entry --> CRUD + Entry --> Execution + Entry --> Worktree + Entry --> Logs + + style Entry fill:#e3f2fd,stroke:#1976d2 + style CRUD fill:#e8f5e9,stroke:#4caf50 + style Execution fill:#fff3e0,stroke:#f57c00 + style Worktree fill:#fce4ec,stroke:#e91e63 + style Logs fill:#f3e5f5,stroke:#9c27b0 +``` + +#### Task Execution Sequence + +```mermaid +sequenceDiagram + participant UI as Renderer + participant IPC as Task Handlers + participant AM as Agent Manager + participant Py as Python Runner + participant FS as File System + + UI->>IPC: TASK_START(taskId, projectId) + IPC->>FS: Create worktree (if needed) + IPC->>AM: startExecution(specId, projectPath) + AM->>Py: spawn(spec_runner.py) + AM-->>IPC: Process started + IPC-->>UI: { success: true } + + loop Execution Loop + Py->>FS: Update implementation_plan.json + AM->>IPC: emit('log', taskId, log) + IPC->>UI: TASK_LOG event + AM->>IPC: emit('execution-progress', taskId, progress) + IPC->>UI: TASK_EXECUTION_PROGRESS event + end + + Py->>AM: Process exit (code) + AM->>IPC: emit('exit', taskId, code) + IPC->>UI: TASK_STATUS_CHANGE event +``` + +### Terminal Handlers + +Manages PTY terminals and Claude profile multi-account support. + +```mermaid +flowchart TB + subgraph TerminalOps["Terminal Operations"] + Create[TERMINAL_CREATE] + Destroy[TERMINAL_DESTROY] + Input[TERMINAL_INPUT] + Resize[TERMINAL_RESIZE] + InvokeClaude[TERMINAL_INVOKE_CLAUDE] + ResumeClaude[TERMINAL_RESUME_CLAUDE] + GenerateName[TERMINAL_GENERATE_NAME] + CheckAlive[TERMINAL_CHECK_PTY_ALIVE] + end + + subgraph ProfileOps["Claude Profile Management"] + ProfilesGet[CLAUDE_PROFILES_GET] + ProfileSave[CLAUDE_PROFILE_SAVE] + ProfileDelete[CLAUDE_PROFILE_DELETE] + ProfileRename[CLAUDE_PROFILE_RENAME] + ProfileSetActive[CLAUDE_PROFILE_SET_ACTIVE] + ProfileSwitch[CLAUDE_PROFILE_SWITCH] + ProfileInit[CLAUDE_PROFILE_INITIALIZE] + ProfileSetToken[CLAUDE_PROFILE_SET_TOKEN] + end + + subgraph AutoSwitch["Auto-Switch Settings"] + AutoSwitchGet[CLAUDE_PROFILE_AUTO_SWITCH_SETTINGS] + AutoSwitchUpdate[CLAUDE_PROFILE_UPDATE_AUTO_SWITCH] + FetchUsage[CLAUDE_PROFILE_FETCH_USAGE] + GetBestProfile[CLAUDE_PROFILE_GET_BEST_PROFILE] + RetryWithProfile[CLAUDE_RETRY_WITH_PROFILE] + end + + subgraph Sessions["Session Management"] + GetSessions[TERMINAL_GET_SESSIONS] + RestoreSession[TERMINAL_RESTORE_SESSION] + ClearSessions[TERMINAL_CLEAR_SESSIONS] + GetDates[TERMINAL_GET_SESSION_DATES] + GetForDate[TERMINAL_GET_SESSIONS_FOR_DATE] + RestoreFromDate[TERMINAL_RESTORE_FROM_DATE] + end + + subgraph Usage["Usage Monitoring"] + UsageRequest[USAGE_REQUEST] + UsageUpdated[USAGE_UPDATED] + ProactiveSwap[PROACTIVE_SWAP_NOTIFICATION] + end + + TerminalManager[Terminal Manager] + ProfileManager[Claude Profile Manager] + UsageMonitor[Usage Monitor] + + TerminalOps --> TerminalManager + ProfileOps --> ProfileManager + AutoSwitch --> ProfileManager + Sessions --> TerminalManager + Usage --> UsageMonitor + + style TerminalOps fill:#e3f2fd,stroke:#1976d2 + style ProfileOps fill:#e8f5e9,stroke:#4caf50 + style AutoSwitch fill:#fff3e0,stroke:#f57c00 + style Sessions fill:#fce4ec,stroke:#e91e63 + style Usage fill:#f3e5f5,stroke:#9c27b0 +``` + +#### Claude Profile Switch Flow + +```mermaid +sequenceDiagram + participant UI as Renderer + participant IPC as Terminal Handlers + participant PM as Profile Manager + participant TM as Terminal Manager + participant PTY as PTY Process + + UI->>IPC: CLAUDE_PROFILE_SET_ACTIVE(profileId) + IPC->>PM: getActiveProfile() + PM-->>IPC: Previous profile + IPC->>PM: setActiveProfile(profileId) + PM-->>IPC: Success + + IPC->>TM: getActiveTerminalIds() + TM-->>IPC: [terminalId1, terminalId2, ...] + + loop For each terminal in Claude mode + IPC->>TM: isClaudeMode(terminalId) + TM-->>IPC: true + IPC->>TM: switchClaudeProfile(terminalId, profileId) + TM->>PTY: Send SIGINT / restart Claude + TM-->>IPC: Switch complete + end + + IPC-->>UI: { success: true } +``` + +### Agent Events Handlers + +Forwards events from the Agent Manager to the renderer process. + +```mermaid +flowchart TB + subgraph Sources["Event Sources"] + AM[Agent Manager] + TG[Title Generator] + FW[File Watcher] + end + + subgraph Events["Forwarded Events"] + Log[TASK_LOG] + Error[TASK_ERROR] + RateLimit[CLAUDE_SDK_RATE_LIMIT] + Exit[Task Exit] + Progress[TASK_EXECUTION_PROGRESS] + StatusChange[TASK_STATUS_CHANGE] + FileProgress[TASK_PROGRESS] + end + + subgraph Renderer["Renderer Process"] + UI[React UI] + Store[State Store] + end + + AM -->|log| Log + AM -->|error| Error + AM -->|sdk-rate-limit| RateLimit + AM -->|exit| Exit + AM -->|execution-progress| Progress + TG -->|sdk-rate-limit| RateLimit + FW -->|progress| FileProgress + FW -->|error| Error + + Log --> UI + Error --> UI + RateLimit --> UI + Exit --> StatusChange + Progress --> StatusChange + StatusChange --> Store + FileProgress --> UI + + style Sources fill:#e3f2fd,stroke:#1976d2 + style Events fill:#fff3e0,stroke:#f57c00 + style Renderer fill:#e8f5e9,stroke:#4caf50 +``` + +#### Event Flow for Task Execution + +```mermaid +sequenceDiagram + participant AM as Agent Manager + participant AE as Agent Events Handler + participant MW as Main Window + participant R as Renderer + + AM->>AE: emit('log', taskId, log) + AE->>MW: webContents.send(TASK_LOG, taskId, log) + MW->>R: IPC message + + AM->>AE: emit('execution-progress', taskId, progress) + AE->>AE: Map phase to TaskStatus + AE->>MW: webContents.send(TASK_EXECUTION_PROGRESS) + AE->>MW: webContents.send(TASK_STATUS_CHANGE) + MW->>R: IPC messages + + AM->>AE: emit('exit', taskId, code, processType) + AE->>AE: Find task in project store + alt Exit code 0 + AE->>AE: notificationService.notifyReviewNeeded() + else Non-zero exit + AE->>AE: notificationService.notifyTaskFailed() + AE->>MW: webContents.send(TASK_STATUS_CHANGE, 'human_review') + end +``` + +### Settings Handlers + +Manages application settings, dialog operations, and shell commands. + +```mermaid +flowchart TB + subgraph SettingsOps["Settings Operations"] + Get[SETTINGS_GET] + Save[SETTINGS_SAVE] + GetCLITools[SETTINGS_GET_CLI_TOOLS_INFO] + end + + subgraph Dialogs["Dialog Operations"] + SelectDir[DIALOG_SELECT_DIRECTORY] + CreateProject[DIALOG_CREATE_PROJECT_FOLDER] + GetDefaultLoc[DIALOG_GET_DEFAULT_PROJECT_LOCATION] + end + + subgraph AppInfo["App Information"] + Version[APP_VERSION] + end + + subgraph Shell["Shell Operations"] + OpenExternal[SHELL_OPEN_EXTERNAL] + OpenTerminal[SHELL_OPEN_TERMINAL] + end + + SettingsFile[(settings.json)] + ConfigureTools[Configure CLI Tools] + + SettingsOps --> SettingsFile + Get --> ConfigureTools + Save --> ConfigureTools + Dialogs --> Electron[Electron Dialog API] + Shell --> ShellAPI[Electron Shell API] + + style SettingsOps fill:#e3f2fd,stroke:#1976d2 + style Dialogs fill:#e8f5e9,stroke:#4caf50 + style AppInfo fill:#fff3e0,stroke:#f57c00 + style Shell fill:#fce4ec,stroke:#e91e63 +``` + +### File Handlers + +Provides file explorer functionality with smart filtering. + +```mermaid +flowchart LR + subgraph Request + List[FILE_EXPLORER_LIST] + DirPath[Directory Path] + end + + subgraph Processing + ReadDir[readdir with types] + Filter[Filter Ignored] + Sort[Sort Results] + end + + subgraph Ignored["Ignored Directories"] + NodeModules[node_modules] + Git[.git] + PyCache[__pycache__] + Dist[dist/build] + VEnv[.venv/venv] + Worktrees[.worktrees] + end + + subgraph Output + FileNodes[FileNode[]] + end + + List --> DirPath + DirPath --> ReadDir + ReadDir --> Filter + Filter -.->|Skip| Ignored + Filter --> Sort + Sort --> FileNodes + + style Request fill:#e3f2fd,stroke:#1976d2 + style Processing fill:#e8f5e9,stroke:#4caf50 + style Ignored fill:#ffebee,stroke:#f44336 + style Output fill:#fff3e0,stroke:#f57c00 +``` + +## Feature Handlers + +### Roadmap Handlers + +Manages AI-powered roadmap generation and feature management. + +```mermaid +flowchart TB + subgraph RoadmapOps["Roadmap Operations"] + Get[ROADMAP_GET] + GetStatus[ROADMAP_GET_STATUS] + Generate[ROADMAP_GENERATE] + Refresh[ROADMAP_REFRESH] + Stop[ROADMAP_STOP] + Save[ROADMAP_SAVE] + UpdateFeature[ROADMAP_UPDATE_FEATURE] + ConvertToSpec[ROADMAP_CONVERT_TO_SPEC] + end + + subgraph Events["Roadmap Events"] + Progress[ROADMAP_PROGRESS] + Complete[ROADMAP_COMPLETE] + Error[ROADMAP_ERROR] + Stopped[ROADMAP_STOPPED] + end + + subgraph AgentManager["Agent Manager"] + StartGen[startRoadmapGeneration] + StopGen[stopRoadmap] + IsRunning[isRoadmapRunning] + end + + RoadmapOps -->|Generate| StartGen + RoadmapOps -->|Stop| StopGen + RoadmapOps -->|Status| IsRunning + AgentManager -->|Emit| Events + + style RoadmapOps fill:#e3f2fd,stroke:#1976d2 + style Events fill:#e8f5e9,stroke:#4caf50 + style AgentManager fill:#fff3e0,stroke:#f57c00 +``` + +#### Roadmap Generation Sequence + +```mermaid +sequenceDiagram + participant UI as Renderer + participant IPC as Roadmap Handlers + participant AM as Agent Manager + participant Py as Python Runner + + UI->>IPC: ROADMAP_GENERATE(projectId, enableCompetitor) + IPC->>IPC: Get feature settings (model, thinking) + IPC->>AM: startRoadmapGeneration(...) + IPC->>UI: ROADMAP_PROGRESS (analyzing) + + AM->>Py: spawn(roadmap_runner.py) + loop Generation Loop + Py->>AM: emit progress + AM->>IPC: emit('roadmap-progress') + IPC->>UI: ROADMAP_PROGRESS + end + + alt Success + Py->>AM: Write roadmap.json + AM->>IPC: emit('roadmap-complete', roadmap) + IPC->>UI: ROADMAP_COMPLETE + else Error + AM->>IPC: emit('roadmap-error', error) + IPC->>UI: ROADMAP_ERROR + end +``` + +### Changelog Handlers + +Generates changelogs from completed tasks or git history. + +```mermaid +flowchart TB + subgraph TaskSource["Task-Based Source"] + GetDoneTasks[CHANGELOG_GET_DONE_TASKS] + LoadSpecs[CHANGELOG_LOAD_TASK_SPECS] + SuggestVersion[CHANGELOG_SUGGEST_VERSION] + end + + subgraph GitSource["Git-Based Source"] + GetBranches[CHANGELOG_GET_BRANCHES] + GetTags[CHANGELOG_GET_TAGS] + GetCommits[CHANGELOG_GET_COMMITS_PREVIEW] + SuggestFromCommits[CHANGELOG_SUGGEST_VERSION_FROM_COMMITS] + end + + subgraph Generation["Generation"] + Generate[CHANGELOG_GENERATE] + Progress[CHANGELOG_GENERATION_PROGRESS] + Complete[CHANGELOG_GENERATION_COMPLETE] + Error[CHANGELOG_GENERATION_ERROR] + end + + subgraph Output["Output Operations"] + Save[CHANGELOG_SAVE] + ReadExisting[CHANGELOG_READ_EXISTING] + SaveImage[CHANGELOG_SAVE_IMAGE] + ReadImage[CHANGELOG_READ_LOCAL_IMAGE] + end + + ChangelogService[Changelog Service] + + TaskSource --> ChangelogService + GitSource --> ChangelogService + Generation --> ChangelogService + Output --> ChangelogService + + style TaskSource fill:#e3f2fd,stroke:#1976d2 + style GitSource fill:#e8f5e9,stroke:#4caf50 + style Generation fill:#fff3e0,stroke:#f57c00 + style Output fill:#fce4ec,stroke:#e91e63 +``` + +### Ideation Handlers + +Manages AI-powered idea generation sessions. + +```mermaid +flowchart TB + subgraph SessionMgmt["Session Management"] + Get[IDEATION_GET] + end + + subgraph IdeaOps["Idea Operations"] + UpdateIdea[IDEATION_UPDATE_IDEA] + Dismiss[IDEATION_DISMISS] + DismissAll[IDEATION_DISMISS_ALL] + Archive[IDEATION_ARCHIVE] + Delete[IDEATION_DELETE] + DeleteMultiple[IDEATION_DELETE_MULTIPLE] + end + + subgraph Generation["Generation"] + Generate[IDEATION_GENERATE] + Refresh[IDEATION_REFRESH] + Stop[IDEATION_STOP] + end + + subgraph Conversion["Task Conversion"] + ConvertToTask[IDEATION_CONVERT_TO_TASK] + end + + subgraph Events["Ideation Events"] + Progress[IDEATION_PROGRESS] + Log[IDEATION_LOG] + TypeComplete[IDEATION_TYPE_COMPLETE] + TypeFailed[IDEATION_TYPE_FAILED] + Complete[IDEATION_COMPLETE] + Error[IDEATION_ERROR] + Stopped[IDEATION_STOPPED] + end + + IdeationModule[./ideation/ Module] + AgentManager[Agent Manager] + + SessionMgmt --> IdeationModule + IdeaOps --> IdeationModule + Generation --> AgentManager + Conversion --> IdeationModule + AgentManager --> Events + + style SessionMgmt fill:#e3f2fd,stroke:#1976d2 + style IdeaOps fill:#e8f5e9,stroke:#4caf50 + style Generation fill:#fff3e0,stroke:#f57c00 + style Conversion fill:#fce4ec,stroke:#e91e63 + style Events fill:#f3e5f5,stroke:#9c27b0 +``` + +### Insights Handlers + +Provides AI-powered codebase chat/analysis. + +```mermaid +flowchart TB + subgraph Session["Session Management"] + GetSession[INSIGHTS_GET_SESSION] + ListSessions[INSIGHTS_LIST_SESSIONS] + NewSession[INSIGHTS_NEW_SESSION] + SwitchSession[INSIGHTS_SWITCH_SESSION] + DeleteSession[INSIGHTS_DELETE_SESSION] + RenameSession[INSIGHTS_RENAME_SESSION] + UpdateModel[INSIGHTS_UPDATE_MODEL_CONFIG] + end + + subgraph Chat["Chat Operations"] + SendMessage[INSIGHTS_SEND_MESSAGE] + ClearSession[INSIGHTS_CLEAR_SESSION] + CreateTask[INSIGHTS_CREATE_TASK] + end + + subgraph Events["Stream Events"] + StreamChunk[INSIGHTS_STREAM_CHUNK] + Status[INSIGHTS_STATUS] + Error[INSIGHTS_ERROR] + RateLimit[CLAUDE_SDK_RATE_LIMIT] + end + + InsightsService[Insights Service] + + Session --> InsightsService + Chat --> InsightsService + InsightsService --> Events + + style Session fill:#e3f2fd,stroke:#1976d2 + style Chat fill:#e8f5e9,stroke:#4caf50 + style Events fill:#fff3e0,stroke:#f57c00 +``` + +### Context Handlers + +Manages project context and memory operations. + +```mermaid +flowchart TB + subgraph Entry["context-handlers.ts"] + Register[registerContextHandlers] + end + + subgraph Modules["Submodules"] + MemStatus[memory-status-handlers.ts] + MemData[memory-data-handlers.ts] + ProjContext[project-context-handlers.ts] + end + + subgraph Operations["Context Operations"] + CheckGraphiti[Check Graphiti Status] + GetMemories[Get Memories] + SearchMemories[Search Memories] + BuildContext[Build Project Context] + UpdateIndex[Update Context Index] + end + + Entry --> Modules + Modules --> Operations + + style Entry fill:#e3f2fd,stroke:#1976d2 + style Modules fill:#e8f5e9,stroke:#4caf50 + style Operations fill:#fff3e0,stroke:#f57c00 +``` + +### Environment Handlers + +Manages project-specific .env configuration. + +```mermaid +flowchart TB + subgraph EnvOps["Environment Operations"] + Get[ENV_GET] + Update[ENV_UPDATE] + end + + subgraph ClaudeAuth["Claude Authentication"] + CheckAuth[ENV_CHECK_CLAUDE_AUTH] + InvokeSetup[ENV_INVOKE_CLAUDE_SETUP] + end + + subgraph EnvVars["Managed Variables"] + Token[CLAUDE_CODE_OAUTH_TOKEN] + Model[AUTO_BUILD_MODEL] + Linear[LINEAR_API_KEY / LINEAR_*] + GitHub[GITHUB_TOKEN / GITHUB_*] + Branch[DEFAULT_BRANCH] + Graphiti[GRAPHITI_* / Embedding Config] + UI[ENABLE_FANCY_UI] + end + + EnvFile[.auto-claude/.env] + GlobalSettings[Global Settings] + + EnvOps --> EnvFile + EnvOps --> GlobalSettings + ClaudeAuth --> ClaudeCLI[Claude CLI] + + style EnvOps fill:#e3f2fd,stroke:#1976d2 + style ClaudeAuth fill:#e8f5e9,stroke:#4caf50 + style EnvVars fill:#fff3e0,stroke:#f57c00 +``` + +## Integration Handlers + +### Linear Handlers + +Integrates with Linear issue tracking. + +```mermaid +flowchart TB + subgraph Connection["Connection"] + CheckConnection[LINEAR_CHECK_CONNECTION] + end + + subgraph Queries["Queries"] + GetTeams[LINEAR_GET_TEAMS] + GetProjects[LINEAR_GET_PROJECTS] + GetIssues[LINEAR_GET_ISSUES] + end + + subgraph Import["Import"] + ImportIssues[LINEAR_IMPORT_ISSUES] + end + + subgraph Flow["Import Flow"] + SelectIssues[Select Issues] + FetchDetails[Fetch Issue Details] + CreateSpec[Create Spec Directory] + StartAgent[Start Spec Creation] + end + + LinearAPI[Linear GraphQL API] + ProjectStore[Project Store] + AgentManager[Agent Manager] + + Connection --> LinearAPI + Queries --> LinearAPI + Import --> LinearAPI + Import --> ProjectStore + Import --> AgentManager + + style Connection fill:#e3f2fd,stroke:#1976d2 + style Queries fill:#e8f5e9,stroke:#4caf50 + style Import fill:#fff3e0,stroke:#f57c00 + style Flow fill:#fce4ec,stroke:#e91e63 +``` + +#### Linear Import Sequence + +```mermaid +sequenceDiagram + participant UI as Renderer + participant IPC as Linear Handlers + participant API as Linear GraphQL + participant FS as File System + participant AM as Agent Manager + + UI->>IPC: LINEAR_IMPORT_ISSUES(projectId, issueIds) + IPC->>API: Fetch issue details (GraphQL) + API-->>IPC: Issue data + + loop For each issue + IPC->>FS: Create spec directory + IPC->>FS: Write implementation_plan.json + IPC->>FS: Write requirements.json + IPC->>FS: Write task_metadata.json + IPC->>AM: startSpecCreation(specId, ...) + end + + IPC-->>UI: { imported: N, failed: M } +``` + +### GitHub Handlers + +Organized into modular subhandlers for GitHub integration. + +```mermaid +flowchart TB + subgraph Entry["github-handlers.ts"] + Register[registerGithubHandlers] + end + + subgraph Modules["Submodules"] + Repo[repository-handlers.ts] + Issues[issue-handlers.ts] + Investigation[investigation-handlers.ts] + Import[import-handlers.ts] + Release[release-handlers.ts] + end + + subgraph Operations["Operations"] + CheckConnection[Check GitHub Connection] + GetIssues[Get Issues] + InvestigateIssue[AI Investigation] + ImportIssues[Import to Tasks] + CreateRelease[Create Release] + end + + subgraph Utils["Utilities"] + GitHubUtils[utils.ts] + SpecUtils[spec-utils.ts] + Types[types.ts] + end + + Entry --> Modules + Modules --> Operations + Modules --> Utils + + style Entry fill:#e3f2fd,stroke:#1976d2 + style Modules fill:#e8f5e9,stroke:#4caf50 + style Operations fill:#fff3e0,stroke:#f57c00 + style Utils fill:#fce4ec,stroke:#e91e63 +``` + +### Memory Handlers + +Manages memory infrastructure (Graphiti/LadybugDB) and Ollama integration. + +```mermaid +flowchart TB + subgraph MemoryInfra["Memory Infrastructure"] + Status[MEMORY_STATUS] + ListDB[MEMORY_LIST_DATABASES] + TestConnection[MEMORY_TEST_CONNECTION] + end + + subgraph Validation["Graphiti Validation"] + ValidateLLM[GRAPHITI_VALIDATE_LLM] + TestGraphiti[GRAPHITI_TEST_CONNECTION] + end + + subgraph Ollama["Ollama Operations"] + CheckStatus[OLLAMA_CHECK_STATUS] + ListModels[OLLAMA_LIST_MODELS] + ListEmbedding[OLLAMA_LIST_EMBEDDING_MODELS] + PullModel[OLLAMA_PULL_MODEL] + PullProgress[OLLAMA_PULL_PROGRESS] + end + + subgraph Services["Services"] + MemService[Memory Service] + OllamaDetector[ollama_model_detector.py] + APIValidation[API Validation Service] + end + + MemoryInfra --> MemService + Validation --> APIValidation + Ollama --> OllamaDetector + + style MemoryInfra fill:#e3f2fd,stroke:#1976d2 + style Validation fill:#e8f5e9,stroke:#4caf50 + style Ollama fill:#fff3e0,stroke:#f57c00 + style Services fill:#fce4ec,stroke:#e91e63 +``` + +#### Ollama Model Pull Sequence + +```mermaid +sequenceDiagram + participant UI as Renderer + participant IPC as Memory Handlers + participant Py as ollama_model_detector.py + participant Ollama as Ollama Service + + UI->>IPC: OLLAMA_PULL_MODEL(modelName) + IPC->>Py: spawn(['pull-model', modelName]) + Py->>Ollama: ollama pull modelName + + loop Download Progress + Ollama->>Py: NDJSON progress + Py->>IPC: stderr with progress JSON + IPC->>IPC: Parse NDJSON + IPC->>UI: OLLAMA_PULL_PROGRESS event + end + + Py->>IPC: Exit code + final status + IPC-->>UI: { model, status: completed } +``` + +## System Handlers + +### Auto-Build Source Handlers + +Manages Auto-Claude source code updates. + +```mermaid +flowchart TB + subgraph Updates["Update Operations"] + Check[AUTOBUILD_SOURCE_CHECK] + Download[AUTOBUILD_SOURCE_DOWNLOAD] + Version[AUTOBUILD_SOURCE_VERSION] + end + + subgraph Progress["Update Progress Events"] + Checking[Stage: checking] + Downloading[Stage: downloading] + Extracting[Stage: extracting] + Complete[Stage: complete] + Error[Stage: error] + end + + subgraph Env["Source Environment"] + EnvGet[AUTOBUILD_SOURCE_ENV_GET] + EnvUpdate[AUTOBUILD_SOURCE_ENV_UPDATE] + EnvCheckToken[AUTOBUILD_SOURCE_ENV_CHECK_TOKEN] + end + + Updater[auto-claude-updater] + + Updates --> Updater + Download --> Progress + Env --> SourcePath[Effective Source Path] + + style Updates fill:#e3f2fd,stroke:#1976d2 + style Progress fill:#fff3e0,stroke:#f57c00 + style Env fill:#e8f5e9,stroke:#4caf50 +``` + +### App Update Handlers + +Handles Electron app auto-updates. + +```mermaid +flowchart LR + subgraph Handlers["App Update Handlers"] + Check[APP_UPDATE_CHECK] + Download[APP_UPDATE_DOWNLOAD] + Install[APP_UPDATE_INSTALL] + GetVersion[APP_UPDATE_GET_VERSION] + end + + subgraph Updater["App Updater"] + CheckFn[checkForUpdates] + DownloadFn[downloadUpdate] + InstallFn[quitAndInstall] + VersionFn[getCurrentVersion] + end + + Check --> CheckFn + Download --> DownloadFn + Install --> InstallFn + GetVersion --> VersionFn + + style Handlers fill:#e3f2fd,stroke:#1976d2 + style Updater fill:#e8f5e9,stroke:#4caf50 +``` + +## IPCResult Pattern + +All IPC handlers return a consistent `IPCResult` type: + +```mermaid +classDiagram + class IPCResult~T~ { + +success: boolean + +data?: T + +error?: string + } + + class SuccessResult~T~ { + +success: true + +data: T + } + + class ErrorResult { + +success: false + +error: string + } + + IPCResult <|-- SuccessResult + IPCResult <|-- ErrorResult +``` + +### Usage Pattern + +```typescript +// Handler implementation +ipcMain.handle( + IPC_CHANNELS.EXAMPLE_CHANNEL, + async (_, param: string): Promise> => { + try { + const result = await someOperation(param); + return { success: true, data: result }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error.message : 'Unknown error' + }; + } + } +); + +// Renderer usage +const result = await window.api.invoke('example:channel', param); +if (result.success) { + console.log(result.data); +} else { + console.error(result.error); +} +``` + +## Handler Types + +### ipcMain.handle vs ipcMain.on + +```mermaid +flowchart TB + subgraph Handle["ipcMain.handle (Request/Response)"] + HandleReq[Renderer invokes] + HandleProc[Handler processes] + HandleRes[Returns Promise] + HandleReq --> HandleProc --> HandleRes + end + + subgraph On["ipcMain.on (Fire-and-Forget)"] + OnReq[Renderer sends] + OnProc[Handler processes] + OnEvent[Sends events back via webContents.send] + OnReq --> OnProc --> OnEvent + end + + style Handle fill:#e3f2fd,stroke:#1976d2 + style On fill:#fff3e0,stroke:#f57c00 +``` + +| Method | Use Case | Return | +|--------|----------|--------| +| `ipcMain.handle` | Request/response pattern | `Promise>` | +| `ipcMain.on` | Long-running operations, streaming | Events via `webContents.send` | + +## Error Handling Strategy + +```mermaid +flowchart TB + Handler[IPC Handler] + TryCatch{Try/Catch Block} + + subgraph Success["Success Path"] + Process[Process Request] + Return[Return { success: true, data }] + end + + subgraph Error["Error Path"] + Catch[Catch Exception] + Format[Format Error Message] + ReturnError[Return { success: false, error }] + end + + Handler --> TryCatch + TryCatch -->|try| Process + Process --> Return + TryCatch -->|catch| Catch + Catch --> Format + Format --> ReturnError + + style Success fill:#e8f5e9,stroke:#4caf50 + style Error fill:#ffebee,stroke:#f44336 +``` + +## Security Considerations + +### Input Validation + +All handlers validate inputs before processing: + +```mermaid +flowchart LR + Input[User Input] + Validate{Validate} + Process[Process Request] + Error[Return Error] + + Input --> Validate + Validate -->|Valid| Process + Validate -->|Invalid| Error + + style Validate fill:#fff3e0,stroke:#f57c00 + style Process fill:#e8f5e9,stroke:#4caf50 + style Error fill:#ffebee,stroke:#f44336 +``` + +### Path Security + +- Project paths validated for existence +- File operations restricted to project directories +- Shell commands use `execFileSync` with argument arrays (no shell injection) + +## Performance Considerations + +| Aspect | Implementation | +|--------|----------------| +| **Lazy Loading** | Handler modules loaded on demand | +| **Event Batching** | Progress events throttled where appropriate | +| **Streaming** | Long-running operations stream updates | +| **Connection Pooling** | Linear/GitHub API connections reused | +| **Caching** | Settings and environment configs cached | + +## Next Steps + +- [Preload API](./preload-api.md) - Preload script documentation +- [Agent Manager](./agent-manager.md) - Agent Manager documentation +- [Terminal Manager](./terminal-manager.md) - Terminal Manager documentation +- [Services](./services.md) - Backend services documentation From 66b247de0651a16009300bdfeb8f1b497a188f75 Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 22:20:20 +0200 Subject: [PATCH 16/27] auto-claude: subtask-4-3 - Create renderer components documentation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add comprehensive documentation for React renderer components covering: - Component hierarchy overview with Mermaid diagram - Directory structure and organization - App.tsx root component state flow - UI primitives (Radix UI/shadcn) library reference - Navigation components (Sidebar, ProjectTabBar) - View components (KanbanBoard, TerminalGrid, Context, etc.) - Dialog components (TaskCreationWizard, TaskDetailModal, AppSettings, Onboarding) - Card components (TaskCard, SortableTaskCard) - Feature module breakdowns (Changelog, GitHub Issues, Ideation, Settings) - Component patterns (Props, State Management, Styling, IPC) - Accessibility and internationalization guidelines Includes 21 Mermaid diagrams covering: - Component hierarchy flowchart - App state flow - View navigation - UI component class diagrams - Sidebar navigation structure - KanbanBoard DnD architecture - Terminal grid layout - Context view structure - Dialog component flows - Card component anatomy - Feature module breakdowns 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/components/frontend/renderer.md | 1001 ++++++++++++++++++++++++++ 1 file changed, 1001 insertions(+) create mode 100644 docs/components/frontend/renderer.md diff --git a/docs/components/frontend/renderer.md b/docs/components/frontend/renderer.md new file mode 100644 index 0000000000..cd36dcb9ed --- /dev/null +++ b/docs/components/frontend/renderer.md @@ -0,0 +1,1001 @@ +# Renderer Components + +The React renderer process provides the user interface for Auto-Claude, built on React 19, Radix UI primitives, Tailwind CSS, and Zustand for state management. Components are organized hierarchically from foundational UI primitives to complex feature components. + +## Component Hierarchy Overview + +```mermaid +flowchart TB + subgraph App["App.tsx - Root Component"] + Providers[Context Providers
TooltipProvider, DndContext] + Layout[Layout Container] + end + + subgraph Navigation["Navigation Layer"] + Sidebar[Sidebar
View Navigation] + TabBar[ProjectTabBar
Project Tabs] + end + + subgraph Views["Main View Components"] + Kanban[KanbanBoard
Task Management] + Terminals[TerminalGrid
Agent Terminals] + Roadmap[Roadmap
Feature Planning] + Context[Context
Project Index] + Ideation[Ideation
Feature Ideas] + Insights[Insights
AI Chat] + GitHubIssues[GitHubIssues
Issue Triage] + GitHubPRs[GitHubPRs
PR Reviews] + Changelog[Changelog
Release Notes] + Worktrees[Worktrees
Git Branches] + end + + subgraph Dialogs["Dialog Components"] + TaskCreation[TaskCreationWizard] + TaskDetail[TaskDetailModal] + AppSettings[AppSettingsDialog] + Onboarding[OnboardingWizard] + RateLimitModal[RateLimitModal] + end + + subgraph Cards["Card Components"] + TaskCard[TaskCard
Task Display] + FeatureCard[SortableFeatureCard] + IdeaCard[IdeaCard] + MemoryCard[MemoryCard] + end + + subgraph UILib["UI Primitives (Radix)"] + Dialog[Dialog] + Button[Button] + Card[Card] + Badge[Badge] + Select[Select] + Tabs[Tabs] + Tooltip[Tooltip] + ScrollArea[ScrollArea] + end + + App --> Navigation + App --> Views + App --> Dialogs + + Navigation --> Sidebar + Navigation --> TabBar + + Views --> Cards + Kanban --> TaskCard + Ideation --> IdeaCard + + Dialogs --> UILib + Cards --> UILib + Views --> UILib + + style App fill:#e3f2fd,stroke:#1976d2 + style Navigation fill:#f3e5f5,stroke:#9c27b0 + style Views fill:#e8f5e9,stroke:#4caf50 + style Dialogs fill:#fff3e0,stroke:#f57c00 + style Cards fill:#fce4ec,stroke:#e91e63 + style UILib fill:#f5f5f5,stroke:#9e9e9e +``` + +## Directory Structure + +``` +apps/frontend/src/renderer/ +├── App.tsx # Root application component +├── components/ # All React components +│ ├── ui/ # Radix UI primitives (shadcn/ui) +│ │ ├── alert-dialog.tsx +│ │ ├── badge.tsx +│ │ ├── button.tsx +│ │ ├── card.tsx +│ │ ├── checkbox.tsx +│ │ ├── dialog.tsx +│ │ ├── dropdown-menu.tsx +│ │ ├── full-screen-dialog.tsx +│ │ ├── input.tsx +│ │ ├── label.tsx +│ │ ├── progress.tsx +│ │ ├── scroll-area.tsx +│ │ ├── select.tsx +│ │ ├── separator.tsx +│ │ ├── switch.tsx +│ │ ├── tabs.tsx +│ │ ├── textarea.tsx +│ │ └── tooltip.tsx +│ ├── Sidebar.tsx # Navigation sidebar +│ ├── ProjectTabBar.tsx # Project tab management +│ ├── KanbanBoard.tsx # Task kanban view +│ ├── TaskCard.tsx # Task display card +│ ├── TaskCreationWizard.tsx # New task wizard +│ ├── TaskEditDialog.tsx # Edit task dialog +│ ├── TerminalGrid.tsx # Terminal container +│ ├── Terminal.tsx # Individual terminal +│ ├── Roadmap.tsx # Roadmap view +│ ├── Context.tsx # Project context view +│ ├── Ideation.tsx # Ideation view +│ ├── Insights.tsx # AI insights view +│ ├── GitHubIssues.tsx # GitHub issues view +│ ├── Changelog.tsx # Changelog view +│ ├── Worktrees.tsx # Git worktrees view +│ ├── WelcomeScreen.tsx # New user welcome +│ │ +│ ├── changelog/ # Changelog feature +│ ├── context/ # Context visualization +│ ├── github-issues/ # GitHub issues feature +│ ├── github-prs/ # GitHub PRs feature +│ ├── ideation/ # Ideation feature +│ ├── linear-import/ # Linear import feature +│ ├── onboarding/ # Onboarding wizard +│ ├── project-settings/ # Project settings +│ ├── roadmap/ # Roadmap feature +│ ├── settings/ # App settings +│ └── task-detail/ # Task detail modal +├── hooks/ # Custom React hooks +├── stores/ # Zustand state stores +└── lib/ # Utility functions +``` + +## Root Component: App.tsx + +The `App` component serves as the application entry point, orchestrating global state, routing between views, and managing modals. + +### Component State Flow + +```mermaid +stateDiagram-v2 + [*] --> LoadingState: App mounts + LoadingState --> ProjectsLoaded: loadProjects() + LoadingState --> SettingsLoaded: loadSettings() + + ProjectsLoaded --> ProjectSelected: Has active project + ProjectsLoaded --> WelcomeScreen: No projects + + SettingsLoaded --> OnboardingCheck: Check onboarding + OnboardingCheck --> OnboardingWizard: Not completed + OnboardingCheck --> NormalView: Completed + + ProjectSelected --> KanbanView: Default view + KanbanView --> TerminalView: User navigates + KanbanView --> RoadmapView: User navigates + KanbanView --> ContextView: User navigates + KanbanView --> IdeationView: User navigates + KanbanView --> InsightsView: User navigates + + state NormalView { + [*] --> ViewActive + ViewActive --> DialogOpen: Open modal + DialogOpen --> ViewActive: Close modal + } +``` + +### Key Responsibilities + +| Responsibility | Implementation | +|---------------|----------------| +| State Initialization | Loads projects, tasks, settings on mount | +| View Routing | Manages `activeView` state for navigation | +| Modal Management | Controls dialogs (settings, task creation, etc.) | +| Project Tab Management | Handles multi-project tab bar with DnD | +| Keyboard Shortcuts | Global keyboard navigation | +| IPC Listeners | Real-time updates via `useIpcListeners` | + +### View Navigation Flow + +```mermaid +flowchart LR + subgraph SidebarNav["Sidebar Navigation"] + K[Kanban K] + A[Terminals A] + N[Insights N] + D[Roadmap D] + I[Ideation I] + L[Changelog L] + C[Context C] + G[GitHub Issues G] + P[GitHub PRs P] + W[Worktrees W] + end + + subgraph ViewState["activeView State"] + KanbanBoard + TerminalGrid + InsightsView + RoadmapView + IdeationView + ChangelogView + ContextView + GitHubIssues + GitHubPRs + WorktreesView + end + + K --> KanbanBoard + A --> TerminalGrid + N --> InsightsView + D --> RoadmapView + I --> IdeationView + L --> ChangelogView + C --> ContextView + G --> GitHubIssues + P --> GitHubPRs + W --> WorktreesView + + style SidebarNav fill:#e3f2fd,stroke:#1976d2 + style ViewState fill:#e8f5e9,stroke:#4caf50 +``` + +## UI Primitives (Radix UI) + +The `/ui` directory contains foundational components built on [Radix UI](https://www.radix-ui.com/) primitives with Tailwind CSS styling, following the shadcn/ui pattern. + +### Component Library + +```mermaid +classDiagram + class Dialog { + +DialogTrigger + +DialogContent + +DialogHeader + +DialogTitle + +DialogDescription + +DialogFooter + } + + class AlertDialog { + +AlertDialogTrigger + +AlertDialogContent + +AlertDialogHeader + +AlertDialogTitle + +AlertDialogDescription + +AlertDialogFooter + +AlertDialogAction + +AlertDialogCancel + } + + class FullScreenDialog { + +FullScreenDialogContent + +FullScreenDialogHeader + +FullScreenDialogBody + +FullScreenDialogFooter + +FullScreenDialogTitle + +FullScreenDialogDescription + } + + class Button { + +variant: default|destructive|outline|ghost|link|warning + +size: default|sm|lg|icon + } + + class Badge { + +variant: default|secondary|destructive|outline|success|warning|info|purple + } + + class Card { + +CardHeader + +CardTitle + +CardDescription + +CardContent + +CardFooter + } + + class Select { + +SelectTrigger + +SelectValue + +SelectContent + +SelectItem + +SelectGroup + +SelectLabel + } + + class Tabs { + +TabsList + +TabsTrigger + +TabsContent + } +``` + +### UI Component Usage Patterns + +| Component | Purpose | Key Props | +|-----------|---------|-----------| +| `Dialog` | Modal overlays for focused interactions | `open`, `onOpenChange` | +| `FullScreenDialog` | Full-screen modals (settings, onboarding) | `open`, `onOpenChange` | +| `AlertDialog` | Confirmation dialogs | `open`, `onOpenChange` | +| `Button` | Actions and interactions | `variant`, `size`, `disabled` | +| `Badge` | Status indicators and labels | `variant` | +| `Card` | Content containers | Uses CardContent, CardHeader | +| `Select` | Dropdown selection | `value`, `onValueChange` | +| `Tabs` | Tabbed content navigation | `value`, `onValueChange` | +| `ScrollArea` | Scrollable containers | Custom scrollbar styling | +| `Tooltip` | Contextual hints | Requires `TooltipProvider` | + +## Navigation Components + +### Sidebar + +The `Sidebar` component provides primary navigation between views and project actions. + +```mermaid +flowchart TB + subgraph Sidebar["Sidebar Component"] + Header[App Header
electron-drag] + + subgraph ProjectNav["Project Section"] + Kanban[Kanban K] + Terminals[Terminals A] + Insights[Insights N] + Roadmap[Roadmap D] + Ideation[Ideation I] + Changelog[Changelog L] + Context[Context C] + end + + subgraph ToolsNav["Tools Section"] + GitHubIssues[GitHub Issues G] + GitHubPRs[GitHub PRs P] + Worktrees[Worktrees W] + end + + RateLimitIndicator[Rate Limit Indicator] + + subgraph Footer["Footer Actions"] + Settings[Settings Button] + Help[Help Button] + NewTask[New Task Button] + end + end + + Header --> ProjectNav + ProjectNav --> ToolsNav + ToolsNav --> RateLimitIndicator + RateLimitIndicator --> Footer + + style Sidebar fill:#f3e5f5,stroke:#9c27b0 + style ProjectNav fill:#e8f5e9,stroke:#4caf50 + style ToolsNav fill:#fff3e0,stroke:#f57c00 + style Footer fill:#e3f2fd,stroke:#1976d2 +``` + +### ProjectTabBar + +Manages multiple open projects with drag-and-drop tab reordering. + +```mermaid +sequenceDiagram + participant User + participant TabBar as ProjectTabBar + participant Store as projectStore + participant DnD as DndContext + + User->>TabBar: Click tab + TabBar->>Store: setActiveProject(id) + Store-->>TabBar: Re-render with new active + + User->>TabBar: Start drag + TabBar->>DnD: DragStart event + DnD->>TabBar: Show DragOverlay + + User->>TabBar: Drop on new position + DnD->>Store: reorderTabs(activeId, overId) + Store-->>TabBar: Re-render with new order + + User->>TabBar: Click close (X) + TabBar->>Store: closeProjectTab(id) + Store-->>TabBar: Re-render without tab +``` + +## View Components + +### KanbanBoard + +The task management view with drag-and-drop columns for workflow visualization. + +```mermaid +flowchart TB + subgraph KanbanBoard["KanbanBoard Component"] + Header[Filter Header
Show Archived Toggle] + + subgraph DndContext["DnD Context"] + subgraph Columns["Droppable Columns"] + Backlog[Backlog
+ Add Task] + InProgress[In Progress] + AIReview[AI Review] + HumanReview[Human Review] + Done[Done
Archive All] + end + + DragOverlay[DragOverlay
Dragged Card Preview] + end + end + + subgraph TaskCards["Task Cards"] + SC1[SortableTaskCard] + SC2[SortableTaskCard] + SC3[SortableTaskCard] + end + + Backlog --> SC1 + InProgress --> SC2 + Done --> SC3 + + style KanbanBoard fill:#e3f2fd,stroke:#1976d2 + style Columns fill:#e8f5e9,stroke:#4caf50 + style TaskCards fill:#fce4ec,stroke:#e91e63 +``` + +### TerminalGrid + +Container for multiple PTY terminal instances. + +```mermaid +flowchart TB + subgraph TerminalGrid["TerminalGrid Component"] + GridLayout[Grid Layout Container] + + subgraph Terminals["Terminal Instances"] + T1[Terminal 1
xterm.js] + T2[Terminal 2
xterm.js] + T3[Terminal 3
xterm.js] + end + + AddButton[Add Terminal Button] + end + + GridLayout --> Terminals + GridLayout --> AddButton + + subgraph Terminal["Terminal Component"] + XTermCore[xterm.js Core] + FitAddon[Fit Addon] + WebLinksAddon[WebLinks Addon] + WebglRenderer[WebGL Renderer] + end + + T1 --> Terminal + + style TerminalGrid fill:#1a1a2e,stroke:#16213e + style Terminals fill:#0f0f23,stroke:#1a1a2e +``` + +### Context View + +Displays analyzed project context including services, dependencies, and memories. + +```mermaid +flowchart TB + subgraph Context["Context Component"] + Tabs[TabsList] + + subgraph ProjectIndexTab["Project Index Tab"] + ProjectOverview[Project Overview Card] + ServiceCards[Service Cards] + end + + subgraph MemoriesTab["Memories Tab"] + MemoryList[Memory Card List] + MemorySearch[Search/Filter] + end + end + + subgraph ServiceCard["ServiceCard Component"] + ServiceHeader[Service Name + Type] + + subgraph Sections["Service Sections"] + API[APIRoutesSection] + DB[DatabaseSection] + Deps[DependenciesSection] + Env[EnvironmentSection] + Ext[ExternalServicesSection] + Mon[MonitoringSection] + end + end + + Tabs --> ProjectIndexTab + Tabs --> MemoriesTab + ServiceCards --> ServiceCard + + style Context fill:#e8f5e9,stroke:#4caf50 + style ServiceCard fill:#fff3e0,stroke:#f57c00 +``` + +## Dialog Components + +### TaskCreationWizard + +Multi-step wizard for creating new tasks with metadata, images, and file references. + +```mermaid +stateDiagram-v2 + [*] --> FormInput: Dialog opens + + FormInput --> ValidateTitle: Enter title + ValidateTitle --> FormInput: Title required + ValidateTitle --> OptionalFields: Title valid + + state OptionalFields { + [*] --> Description + Description --> Metadata: Show advanced + Metadata --> AgentProfile: Select profile + AgentProfile --> Images: Add images + Images --> FileRefs: Reference files + FileRefs --> GitOptions: Configure branch + } + + OptionalFields --> DraftSaved: Auto-save draft + DraftSaved --> OptionalFields: Continue editing + + OptionalFields --> Creating: Submit + Creating --> Success: Task created + Creating --> Error: Creation failed + + Success --> [*]: Close dialog + Error --> OptionalFields: Show error +``` + +### TaskDetailModal + +Full-screen modal for viewing and managing task details. + +```mermaid +flowchart TB + subgraph TaskDetailModal["TaskDetailModal Component"] + Header[Task Header
Title, Status, Actions] + + subgraph TabContent["Tab Navigation"] + OverviewTab[Overview
Metadata, Warnings] + SubtasksTab[Subtasks
Progress List] + LogsTab[Logs
Execution Output] + ReviewTab[Review
Feedback Form] + end + + Footer[Action Buttons
Start/Stop, Edit, Delete] + end + + subgraph SubComponents["Child Components"] + TaskMetadata[TaskMetadata] + TaskWarnings[TaskWarnings] + TaskSubtasks[TaskSubtasks] + TaskLogs[TaskLogs] + TaskReview[TaskReview] + PhaseProgress[PhaseProgressIndicator] + end + + OverviewTab --> TaskMetadata + OverviewTab --> TaskWarnings + SubtasksTab --> TaskSubtasks + LogsTab --> TaskLogs + ReviewTab --> TaskReview + Header --> PhaseProgress + + style TaskDetailModal fill:#fff3e0,stroke:#f57c00 + style SubComponents fill:#e8f5e9,stroke:#4caf50 +``` + +### AppSettingsDialog + +Full-screen settings dialog with app and project configuration sections. + +```mermaid +flowchart TB + subgraph AppSettings["AppSettingsDialog Component"] + subgraph NavSidebar["Navigation Sidebar"] + AppHeader[App Settings Header] + AppNav[App Navigation] + ProjectHeader[Project Settings Header] + ProjectNav[Project Navigation] + end + + subgraph ContentArea["Content Area"] + subgraph AppSections["App Sections"] + Appearance[ThemeSettings] + Display[DisplaySettings] + Language[LanguageSettings] + Agent[GeneralSettings] + Paths[PathSettings] + Integrations[IntegrationSettings] + Updates[UpdateSettings] + Notifications[NotificationSettings] + end + + subgraph ProjectSections["Project Sections"] + General[GeneralProjectSettings] + Claude[ClaudeSettings] + Linear[LinearSettings] + GitHub[GitHubSettings] + Memory[MemorySettings] + end + end + end + + NavSidebar --> ContentArea + + style AppSettings fill:#e3f2fd,stroke:#1976d2 + style AppSections fill:#e8f5e9,stroke:#4caf50 + style ProjectSections fill:#fff3e0,stroke:#f57c00 +``` + +### OnboardingWizard + +First-run wizard for new user setup. + +```mermaid +stateDiagram-v2 + [*] --> Welcome: First launch + Welcome --> OAuth: Next + OAuth --> Memory: Next/Skip + Memory --> Completion: Next + Completion --> [*]: Finish + + state Welcome { + WelcomeContent: Feature overview + } + + state OAuth { + OAuthContent: Claude authentication + } + + state Memory { + MemoryContent: Memory system setup + } + + state Completion { + CompletionContent: Success + next steps + } +``` + +## Card Components + +### TaskCard + +Displays task information in the kanban board with status, metadata, and actions. + +```mermaid +flowchart TB + subgraph TaskCard["TaskCard Component"] + Header[Title + Status Badges] + Description[Description Preview] + + subgraph MetadataBadges["Metadata Badges"] + Category[Category Badge
+ Icon] + Impact[Impact Badge] + Complexity[Complexity Badge] + Priority[Priority Badge] + end + + Progress[PhaseProgressIndicator] + + subgraph Footer["Footer"] + Timestamp[Updated At] + Actions[Start/Stop/Recover/Archive] + end + end + + Header --> Description + Description --> MetadataBadges + MetadataBadges --> Progress + Progress --> Footer + + style TaskCard fill:#fce4ec,stroke:#e91e63 + style MetadataBadges fill:#f5f5f5,stroke:#9e9e9e +``` + +### SortableTaskCard + +Wrapper around TaskCard providing drag-and-drop functionality via @dnd-kit. + +```mermaid +sequenceDiagram + participant User + participant Sortable as SortableTaskCard + participant DnD as useSortable hook + participant Card as TaskCard + + User->>Sortable: Mouse down (8px threshold) + DnD->>Sortable: isDragging = true + Sortable->>Sortable: Apply drag styles + Sortable->>DnD: Provide transform/transition + + User->>Sortable: Move to new position + DnD->>DnD: Calculate new position + + User->>Sortable: Release + DnD->>Sortable: isDragging = false + DnD-->>DnD: Emit DragEnd event +``` + +## Feature Module Components + +### Changelog Module + +```mermaid +flowchart TB + subgraph Changelog["Changelog Module"] + ChangelogMain[Changelog.tsx] + + subgraph Components["Sub-Components"] + Header[ChangelogHeader] + Filters[ChangelogFilters] + List[ChangelogList] + Entry[ChangelogEntry] + Details[ChangelogDetails] + Config[ConfigurationPanel] + Preview[PreviewPanel] + Release[GitHubReleaseCard] + Archive[ArchiveTasksCard] + Success[Step3SuccessScreen] + end + + subgraph Hooks["Custom Hooks"] + UseChangelog[useChangelog] + UseImageUpload[useImageUpload] + end + end + + ChangelogMain --> Header + ChangelogMain --> Filters + ChangelogMain --> List + List --> Entry + Entry --> Details + ChangelogMain --> Config + Config --> Preview + Config --> Release + Config --> Archive + Config --> Success + + ChangelogMain --> UseChangelog + Config --> UseImageUpload + + style Changelog fill:#e8f5e9,stroke:#4caf50 +``` + +### GitHub Issues Module + +```mermaid +flowchart TB + subgraph GitHubIssues["GitHub Issues Module"] + Main[GitHubIssues.tsx] + + subgraph Components["Sub-Components"] + IssueList[IssueList] + IssueListHeader[IssueListHeader] + IssueListItem[IssueListItem] + IssueDetail[IssueDetail] + InvestigationDialog[InvestigationDialog] + BatchReviewWizard[BatchReviewWizard] + AutoFixButton[AutoFixButton] + EmptyStates[EmptyStates] + end + + subgraph Hooks["Custom Hooks"] + UseIssues[useIssues] + UseInvestigation[useInvestigation] + end + end + + Main --> IssueList + IssueList --> IssueListHeader + IssueList --> IssueListItem + Main --> IssueDetail + Main --> InvestigationDialog + Main --> BatchReviewWizard + IssueDetail --> AutoFixButton + + Main --> Hooks + + style GitHubIssues fill:#fff3e0,stroke:#f57c00 +``` + +### Ideation Module + +```mermaid +flowchart TB + subgraph Ideation["Ideation Module"] + Main[Ideation.tsx] + + subgraph Components["Sub-Components"] + Header[IdeationHeader] + Filters[IdeationFilters] + EmptyState[IdeationEmptyState] + IdeaCard[IdeaCard] + SkeletonCard[IdeaSkeletonCard] + DetailPanel[IdeaDetailPanel] + Dialogs[IdeationDialogs] + GenProgress[GenerationProgressScreen] + TypeIcon[TypeIcon] + end + + subgraph DetailsModule["details/"] + Overview[OverviewTab] + Technical[TechnicalTab] + Implementation[ImplementationTab] + end + + subgraph Hooks["Custom Hooks"] + UseIdeation[useIdeation] + UseIdeaDetails[useIdeaDetails] + end + end + + Main --> Header + Main --> Filters + Main --> IdeaCard + Main --> DetailPanel + DetailPanel --> DetailsModule + + Main --> Hooks + + style Ideation fill:#fce4ec,stroke:#e91e63 +``` + +### Settings Module + +```mermaid +flowchart TB + subgraph Settings["Settings Module"] + AppSettings[AppSettings.tsx] + + subgraph Sections["Settings Sections"] + Theme[ThemeSettings] + Display[DisplaySettings] + Language[LanguageSettings] + General[GeneralSettings] + Advanced[AdvancedSettings] + Integration[IntegrationSettings] + end + + subgraph IntegrationsSub["integrations/"] + ClaudeAPI[ClaudeAPISettings] + GitHub[GitHubSettings] + Linear[LinearSettings] + end + + subgraph Hooks["Custom Hooks"] + UseSettings[useSettings] + end + + subgraph Common["common/"] + SettingRow[SettingRow] + PathInput[PathInput] + end + end + + AppSettings --> Sections + Integration --> IntegrationsSub + Sections --> Common + AppSettings --> Hooks + + style Settings fill:#f3e5f5,stroke:#9c27b0 +``` + +## Component Patterns + +### Props Interface Pattern + +All components follow a consistent props interface pattern: + +```typescript +interface ComponentProps { + // Required props first + data: DataType; + onAction: (value: ValueType) => void; + + // Optional props with defaults + variant?: 'default' | 'secondary'; + disabled?: boolean; + className?: string; +} + +export function Component({ + data, + onAction, + variant = 'default', + disabled = false, + className +}: ComponentProps) { + // Implementation +} +``` + +### State Management Pattern + +Components use Zustand stores for global state and local React state for UI concerns: + +```mermaid +flowchart TB + subgraph GlobalState["Zustand Stores"] + ProjectStore[projectStore] + TaskStore[taskStore] + SettingsStore[settingsStore] + TerminalStore[terminalStore] + end + + subgraph LocalState["Local Component State"] + DialogOpen[isDialogOpen] + FormData[formData] + UIFlags[isLoading, isError] + end + + subgraph Component["React Component"] + UseStore[useStore hooks] + UseState[useState hooks] + Render[Render UI] + end + + GlobalState --> UseStore + UseStore --> Render + LocalState --> UseState + UseState --> Render + + style GlobalState fill:#e3f2fd,stroke:#1976d2 + style LocalState fill:#e8f5e9,stroke:#4caf50 +``` + +### Styling Pattern + +Components use Tailwind CSS with the `cn()` utility for conditional classes: + +```typescript +import { cn } from '../lib/utils'; + +
+``` + +### IPC Communication Pattern + +Components interact with the main process via the `window.electronAPI` bridge: + +```mermaid +sequenceDiagram + participant Component + participant Store as Zustand Store + participant API as window.electronAPI + participant Main as Main Process + + Component->>Store: dispatch action + Store->>API: invoke IPC method + API->>Main: ipcRenderer.invoke() + Main-->>API: IPCResult + API-->>Store: result + Store-->>Component: state update + Component->>Component: re-render +``` + +## Accessibility + +Components follow accessibility best practices: + +| Pattern | Implementation | +|---------|----------------| +| Keyboard Navigation | Focus management, keyboard shortcuts | +| ARIA Labels | Descriptive labels for screen readers | +| Focus Trapping | Modals trap focus within content | +| Color Contrast | Tailwind color palette meets WCAG | +| Motion Reduction | Respects `prefers-reduced-motion` | + +## Internationalization + +Components support i18n via react-i18next: + +```typescript +import { useTranslation } from 'react-i18next'; + +function Component() { + const { t } = useTranslation('namespace'); + return {t('key.path')}; +} +``` + +Translation namespaces: `common`, `tasks`, `settings`, `dialogs`, `navigation`, `onboarding` + +## Related Documentation + +- [State Management](./state.md) - Zustand stores and React hooks +- [IPC Handlers](./ipc-handlers.md) - Main process communication +- [Main Process](./main-process.md) - Electron main process architecture +- [Frontend Architecture](../architecture/frontend.md) - Overall frontend design From c6d51a6b45755e1a5d8cf1b96f7fd5065e7136b3 Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 22:26:51 +0200 Subject: [PATCH 17/27] auto-claude: subtask-4-4 - Create state management documentation covering Zustand stores and React hooks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Document all Zustand stores (task, project, settings, terminal, context, ideation, roadmap, etc.) - Document GitHub store module architecture - Add extensive Mermaid diagrams for data flow and state machines - Document useIpcListeners and useVirtualizedTree hooks - Include store relationships and IPC integration patterns - Add performance considerations section 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/components/frontend/state.md | 855 ++++++++++++++++++++++++++++++ 1 file changed, 855 insertions(+) create mode 100644 docs/components/frontend/state.md diff --git a/docs/components/frontend/state.md b/docs/components/frontend/state.md new file mode 100644 index 0000000000..0bbece6552 --- /dev/null +++ b/docs/components/frontend/state.md @@ -0,0 +1,855 @@ +# State Management + +The Auto-Claude frontend uses [Zustand](https://github.com/pmndrs/zustand) for state management, providing a lightweight, performant alternative to Redux. Stores are organized by domain and follow consistent patterns for actions, selectors, and IPC integration. + +## State Management Architecture + +```mermaid +flowchart TB + subgraph ZustandStores["Zustand Store Layer"] + direction TB + ProjectStore[projectStore
Projects & Tabs] + TaskStore[taskStore
Tasks & Subtasks] + SettingsStore[settingsStore
App Settings] + TerminalStore[terminalStore
Terminal Sessions] + ContextStore[contextStore
Project Context] + IdeationStore[ideationStore
AI Ideas] + RoadmapStore[roadmapStore
Feature Roadmap] + RateLimitStore[rateLimitStore
Rate Limits] + ChangelogStore[changelogStore
Changelogs] + InsightsStore[insightsStore
AI Chat] + + subgraph GitHubStores["GitHub Store Module"] + IssuesStore[issuesStore] + PRReviewStore[prReviewStore] + InvestigationStore[investigationStore] + SyncStatusStore[syncStatusStore] + end + end + + subgraph ReactLayer["React Component Layer"] + Components[React Components] + Hooks[Custom Hooks] + end + + subgraph ElectronLayer["Electron IPC Layer"] + ElectronAPI[window.electronAPI] + MainProcess[Main Process] + end + + Components -->|useStore hooks| ZustandStores + Hooks -->|useStore hooks| ZustandStores + ZustandStores -->|IPC calls| ElectronAPI + ElectronAPI -->|ipcRenderer| MainProcess + MainProcess -->|IPC events| ElectronAPI + ElectronAPI -->|event listeners| Hooks + + style ZustandStores fill:#e3f2fd,stroke:#1976d2 + style GitHubStores fill:#e8f5e9,stroke:#4caf50 + style ReactLayer fill:#fff3e0,stroke:#f57c00 + style ElectronLayer fill:#f3e5f5,stroke:#9c27b0 +``` + +## Store Inventory + +| Store | Purpose | Key State | Key Actions | +|-------|---------|-----------|-------------| +| `projectStore` | Project and tab management | `projects`, `openProjectIds`, `activeProjectId` | `openProjectTab`, `closeProjectTab`, `setActiveProject` | +| `taskStore` | Task lifecycle management | `tasks`, `selectedTaskId`, `isLoading` | `addTask`, `updateTask`, `updateTaskStatus` | +| `settingsStore` | Application settings | `settings`, `isLoading` | `setSettings`, `updateSettings` | +| `terminalStore` | Terminal session management | `terminals`, `activeTerminalId` | `addTerminal`, `removeTerminal`, `setClaudeMode` | +| `contextStore` | Project context and memory | `projectIndex`, `memoryStatus`, `searchResults` | `setProjectIndex`, `setSearchResults` | +| `ideationStore` | AI-powered ideation | `session`, `generationStatus`, `typeStates` | `setSession`, `addIdeasForType`, `dismissIdea` | +| `roadmapStore` | Feature roadmap | `roadmap`, `generationStatus` | `setRoadmap`, `updateFeatureStatus`, `reorderFeatures` | +| `rateLimitStore` | Rate limit modals | `isModalOpen`, `rateLimitInfo` | `showRateLimitModal`, `hideRateLimitModal` | +| `changelogStore` | Release changelogs | `changelog`, `generationStatus` | `setChangelog`, `setGenerationStatus` | +| `insightsStore` | AI chat sessions | `messages`, `isLoading` | `addMessage`, `clearMessages` | +| `fileExplorerStore` | File tree browser | `files`, `expandedFolders` | `loadDirectory`, `toggleFolder` | +| `claudeProfileStore` | Claude API profile | `profile`, `rateLimit` | `setProfile`, `setRateLimit` | + +### GitHub Store Module + +The GitHub integration uses a modular store architecture: + +```mermaid +flowchart LR + subgraph GitHubModule["github/ Store Module"] + Index[index.ts
Module Export] + Issues[issues-store
Issue Data & Filters] + PRReview[pr-review-store
PR Review State] + Investigation[investigation-store
Issue Investigation] + SyncStatus[sync-status-store
Connection Status] + end + + subgraph Exports["Module Exports"] + useIssuesStore[useIssuesStore] + usePRReviewStore[usePRReviewStore] + useInvestigationStore[useInvestigationStore] + useSyncStatusStore[useSyncStatusStore] + initializeGitHubListeners[initializeGitHubListeners] + end + + Index --> Issues + Index --> PRReview + Index --> Investigation + Index --> SyncStatus + + Issues --> useIssuesStore + PRReview --> usePRReviewStore + Investigation --> useInvestigationStore + SyncStatus --> useSyncStatusStore + Index --> initializeGitHubListeners + + style GitHubModule fill:#e8f5e9,stroke:#4caf50 + style Exports fill:#fff3e0,stroke:#f57c00 +``` + +## Core Data Flow Patterns + +### Component-Store-IPC Data Flow + +```mermaid +sequenceDiagram + participant C as React Component + participant S as Zustand Store + participant API as window.electronAPI + participant M as Main Process + participant FS as File System + + Note over C,FS: Read Operation + C->>S: dispatch loadTasks(projectId) + S->>S: setLoading(true) + S->>API: getTasks(projectId) + API->>M: ipcMain.handle('get-tasks') + M->>FS: Read spec files + FS-->>M: Task data + M-->>API: IPCResult + API-->>S: result + S->>S: setTasks(tasks) + S->>S: setLoading(false) + S-->>C: Re-render with tasks + + Note over C,FS: Write Operation + C->>S: dispatch createTask(...) + S->>API: createTask(projectId, title, desc) + API->>M: ipcMain.handle('create-task') + M->>FS: Write spec file + FS-->>M: success + M-->>API: IPCResult + API-->>S: result + S->>S: addTask(task) + S-->>C: Re-render with new task +``` + +### Real-Time Event Updates + +```mermaid +sequenceDiagram + participant M as Main Process + participant API as window.electronAPI + participant H as useIpcListeners Hook + participant S as Zustand Store + participant C as React Component + + Note over M,C: Event-Driven Updates + M->>API: webContents.send('task-progress', taskId, plan) + API->>H: onTaskProgress callback + H->>S: updateTaskFromPlan(taskId, plan) + S->>S: Update state immutably + S-->>C: Re-render with updates + + M->>API: webContents.send('task-status-change', taskId, status) + API->>H: onTaskStatusChange callback + H->>S: updateTaskStatus(taskId, status) + S->>S: Update state immutably + S-->>C: Re-render with new status +``` + +## Store Patterns + +### Standard Store Structure + +All stores follow a consistent pattern: + +```mermaid +classDiagram + class ZustandStore { + +State data fields + +isLoading: boolean + +error: string | null + +setData(data) void + +updateData(updates) void + +setLoading(loading) void + +setError(error) void + +clearAll() void + } + + class AsyncAction { + +loadData(id) Promise~void~ + +saveData(data) Promise~boolean~ + +deleteData(id) Promise~boolean~ + } + + class Selector { + +getById(id) T | undefined + +getFiltered(predicate) T[] + +getStats() Stats + } + + ZustandStore <|-- AsyncAction : exports + ZustandStore <|-- Selector : exports +``` + +### State Immutability Pattern + +```typescript +// Store definition with immutable updates +export const useTaskStore = create((set, get) => ({ + tasks: [], + + // Immutable array update + updateTask: (taskId, updates) => + set((state) => ({ + tasks: state.tasks.map((t) => + t.id === taskId ? { ...t, ...updates } : t + ) + })), + + // Selector using get() + getSelectedTask: () => { + const state = get(); + return state.tasks.find((t) => t.id === state.selectedTaskId); + } +})); +``` + +## Task Store Deep Dive + +The task store manages the complete task lifecycle: + +```mermaid +stateDiagram-v2 + [*] --> backlog: createTask() + + backlog --> in_progress: startTask() + in_progress --> backlog: stopTask() + + in_progress --> ai_review: All subtasks complete + in_progress --> human_review: Subtask failed + + ai_review --> done: QA passes + ai_review --> human_review: QA fails + + human_review --> done: User approves + human_review --> in_progress: User requests changes + + done --> [*]: archiveTasks() + + state in_progress { + [*] --> planning + planning --> coding + coding --> qa_review + qa_review --> qa_fixing + qa_fixing --> qa_review + qa_review --> [*] + } +``` + +### Task Store State + +```mermaid +flowchart TB + subgraph TaskState["Task Store State"] + Tasks[tasks: Task[]] + SelectedId[selectedTaskId: string | null] + Loading[isLoading: boolean] + Error[error: string | null] + end + + subgraph TaskActions["Actions"] + SetTasks[setTasks] + AddTask[addTask] + UpdateTask[updateTask] + UpdateStatus[updateTaskStatus] + UpdateFromPlan[updateTaskFromPlan] + UpdateProgress[updateExecutionProgress] + AppendLog[appendLog] + SelectTask[selectTask] + ClearTasks[clearTasks] + end + + subgraph Selectors["Selectors"] + GetSelected[getSelectedTask] + GetByStatus[getTasksByStatus] + end + + subgraph AsyncActions["Async Actions (exported)"] + LoadTasks[loadTasks] + CreateTask[createTask] + StartTask[startTask] + StopTask[stopTask] + SubmitReview[submitReview] + PersistStatus[persistTaskStatus] + DeleteTask[deleteTask] + ArchiveTasks[archiveTasks] + RecoverStuck[recoverStuckTask] + end + + TaskActions --> TaskState + Selectors --> TaskState + AsyncActions --> TaskActions + AsyncActions --> ElectronAPI[window.electronAPI] + + style TaskState fill:#e3f2fd,stroke:#1976d2 + style TaskActions fill:#e8f5e9,stroke:#4caf50 + style Selectors fill:#fff3e0,stroke:#f57c00 + style AsyncActions fill:#f3e5f5,stroke:#9c27b0 +``` + +## Project Store Deep Dive + +The project store manages multi-project tabs: + +```mermaid +flowchart TB + subgraph ProjectState["Project Store State"] + Projects[projects: Project[]] + SelectedId[selectedProjectId: string | null] + + subgraph TabState["Tab State"] + OpenIds[openProjectIds: string[]] + ActiveId[activeProjectId: string | null] + TabOrder[tabOrder: string[]] + end + end + + subgraph TabActions["Tab Management"] + OpenTab[openProjectTab] + CloseTab[closeProjectTab] + SetActive[setActiveProject] + Reorder[reorderTabs] + Restore[restoreTabState] + end + + subgraph Persistence["Persistence"] + SaveToMain[saveTabStateToMain
Debounced IPC] + LoadFromMain[getTabState IPC] + end + + TabActions --> TabState + TabActions --> Persistence + Persistence --> MainProcess[Main Process Storage] + + style ProjectState fill:#e3f2fd,stroke:#1976d2 + style TabState fill:#fff3e0,stroke:#f57c00 + style Persistence fill:#f3e5f5,stroke:#9c27b0 +``` + +### Tab State Persistence Flow + +```mermaid +sequenceDiagram + participant U as User + participant C as Component + participant S as projectStore + participant D as Debounce Timer + participant API as electronAPI + participant M as Main Process + + U->>C: Click project tab + C->>S: openProjectTab(id) + S->>S: Update openProjectIds, tabOrder + S->>D: saveTabStateToMain() + Note over D: 100ms debounce + D->>API: saveTabState(state) + API->>M: ipcMain.handle('save-tab-state') + M->>M: Write to storage file + + Note over U,M: App Restart + M->>API: getTabState() + API->>S: Restore tab state + S->>S: setState(openProjectIds, tabOrder, activeProjectId) + S-->>C: Re-render with tabs +``` + +## Terminal Store Deep Dive + +The terminal store manages PTY terminal sessions: + +```mermaid +flowchart TB + subgraph TerminalState["Terminal Store State"] + Terminals[terminals: Terminal[]] + ActiveId[activeTerminalId: string | null] + MaxTerminals[maxTerminals: 12] + HasRestored[hasRestoredSessions: boolean] + end + + subgraph TerminalFields["Terminal Object"] + Id[id: string] + Title[title: string] + Status[status: TerminalStatus] + CWD[cwd: string] + ClaudeMode[isClaudeMode: boolean] + ClaudeSession[claudeSessionId: string] + TaskId[associatedTaskId: string] + ProjectPath[projectPath: string] + end + + subgraph Actions["Actions"] + Add[addTerminal] + AddRestored[addRestoredTerminal] + Remove[removeTerminal] + SetStatus[setTerminalStatus] + SetClaude[setClaudeMode] + Clear[clearAllTerminals] + end + + subgraph BufferMgr["Buffer Manager"] + BufferMgr_Singleton[terminalBufferManager
Singleton] + Get[get(id)] + Set[set(id, data)] + Dispose[dispose(id)] + end + + TerminalFields --> Terminals + Actions --> TerminalState + Add --> BufferMgr_Singleton + Remove --> BufferMgr_Singleton + + style TerminalState fill:#e3f2fd,stroke:#1976d2 + style TerminalFields fill:#f5f5f5,stroke:#9e9e9e + style BufferMgr fill:#e8f5e9,stroke:#4caf50 +``` + +### Terminal Status State Machine + +```mermaid +stateDiagram-v2 + [*] --> idle: addTerminal() + idle --> running: PTY spawned + running --> claude_active: setClaudeMode(true) + claude_active --> running: setClaudeMode(false) + running --> exited: PTY exit + claude_active --> exited: PTY exit + exited --> [*]: removeTerminal() +``` + +## Ideation Store Deep Dive + +The ideation store manages AI-powered feature suggestions: + +```mermaid +flowchart TB + subgraph IdeationState["Ideation Store State"] + Session[session: IdeationSession | null] + Status[generationStatus: IdeationGenerationStatus] + Config[config: IdeationConfig] + TypeStates[typeStates: Record<IdeationType, IdeationTypeState>] + IsGenerating[isGenerating: boolean] + Logs[logs: string[]] + Selected[selectedIds: Set<string>] + end + + subgraph IdeationTypes["Ideation Types"] + CodeImp[code_improvements] + UIUX[ui_ux_improvements] + Docs[documentation_gaps] + Security[security_hardening] + Perf[performance_optimizations] + Quality[code_quality] + end + + subgraph TypeStateFlow["Type State Machine"] + Pending[pending] + Generating[generating] + Completed[completed] + Failed[failed] + end + + Pending --> Generating: initializeTypeStates + Generating --> Completed: addIdeasForType + Generating --> Failed: onIdeationTypeFailed + + IdeationTypes --> TypeStates + + style IdeationState fill:#e3f2fd,stroke:#1976d2 + style IdeationTypes fill:#e8f5e9,stroke:#4caf50 + style TypeStateFlow fill:#fff3e0,stroke:#f57c00 +``` + +### Parallel Ideation Generation + +```mermaid +sequenceDiagram + participant U as User + participant S as ideationStore + participant API as electronAPI + participant B as Backend Agent + + U->>S: generateIdeation(projectId) + S->>S: clearSession, initializeTypeStates + S->>API: generateIdeation(projectId, config) + API->>B: Start parallel generation + + par Parallel Type Generation + B->>API: onIdeationTypeComplete('code_improvements', ideas) + API->>S: addIdeasForType('code_improvements', ideas) + and + B->>API: onIdeationTypeComplete('ui_ux_improvements', ideas) + API->>S: addIdeasForType('ui_ux_improvements', ideas) + and + B->>API: onIdeationTypeComplete('security_hardening', ideas) + API->>S: addIdeasForType('security_hardening', ideas) + end + + B->>API: onIdeationComplete(session) + API->>S: setSession(session), setIsGenerating(false) +``` + +## Roadmap Store Deep Dive + +The roadmap store manages feature planning: + +```mermaid +flowchart TB + subgraph RoadmapState["Roadmap Store State"] + Roadmap[roadmap: Roadmap | null] + CompetitorAnalysis[competitorAnalysis: CompetitorAnalysis | null] + GenStatus[generationStatus: RoadmapGenerationStatus] + CurrentProject[currentProjectId: string | null] + end + + subgraph Features["Feature Management"] + FeatureList[features: RoadmapFeature[]] + Phases[phases: RoadmapPhase[]] + end + + subgraph DragDrop["Drag & Drop Actions"] + ReorderFeatures[reorderFeatures
Within Phase] + UpdatePhase[updateFeaturePhase
Between Phases] + AddFeature[addFeature
New Feature] + end + + subgraph StatusFlow["Feature Status Flow"] + UnderReview[under_review] + Planned[planned] + InProgress[in_progress] + Done[done] + end + + Features --> Roadmap + DragDrop --> FeatureList + UnderReview --> Planned --> InProgress --> Done + + style RoadmapState fill:#e3f2fd,stroke:#1976d2 + style DragDrop fill:#e8f5e9,stroke:#4caf50 + style StatusFlow fill:#fff3e0,stroke:#f57c00 +``` + +## React Hooks + +### useIpcListeners Hook + +The primary hook for setting up IPC event listeners: + +```mermaid +flowchart TB + subgraph useIpcListeners["useIpcListeners Hook"] + SetupEffect[useEffect Setup] + + subgraph TaskListeners["Task Listeners"] + OnProgress[onTaskProgress] + OnError[onTaskError] + OnLog[onTaskLog] + OnStatus[onTaskStatusChange] + OnExecProgress[onTaskExecutionProgress] + end + + subgraph RoadmapListeners["Roadmap Listeners"] + OnRoadmapProgress[onRoadmapProgress] + OnRoadmapComplete[onRoadmapComplete] + OnRoadmapError[onRoadmapError] + OnRoadmapStopped[onRoadmapStopped] + end + + subgraph RateLimitListeners["Rate Limit Listeners"] + OnTerminalRateLimit[onTerminalRateLimit] + OnSDKRateLimit[onSDKRateLimit] + end + + CleanupFn[Cleanup Function] + end + + subgraph Stores["Target Stores"] + TaskStore[taskStore] + RoadmapStore[roadmapStore] + RateLimitStore[rateLimitStore] + end + + SetupEffect --> TaskListeners + SetupEffect --> RoadmapListeners + SetupEffect --> RateLimitListeners + + TaskListeners --> TaskStore + RoadmapListeners --> RoadmapStore + RateLimitListeners --> RateLimitStore + + SetupEffect --> CleanupFn + + style useIpcListeners fill:#e3f2fd,stroke:#1976d2 + style TaskListeners fill:#e8f5e9,stroke:#4caf50 + style RoadmapListeners fill:#fff3e0,stroke:#f57c00 + style RateLimitListeners fill:#fce4ec,stroke:#e91e63 +``` + +### useVirtualizedTree Hook + +Hook for virtualized file tree rendering: + +```mermaid +flowchart TB + subgraph useVirtualizedTree["useVirtualizedTree Hook"] + Input[rootPath: string] + + subgraph StoreAccess["Store Access"] + ExpandedFolders[expandedFolders: Set] + Files[files: Map] + IsLoading[isLoading: Map] + ToggleFolder[toggleFolder action] + LoadDirectory[loadDirectory action] + end + + subgraph Computation["Memoized Computation"] + FlattenTree[flattenTree function] + FlattenedNodes[flattenedNodes: FlattenedNode[]] + end + + subgraph Output["Return Value"] + Nodes[flattenedNodes array] + Count[count: number] + HandleToggle[handleToggle function] + IsRootLoading[isRootLoading: boolean] + HasRootFiles[hasRootFiles: boolean] + end + end + + subgraph FlattenedNode["FlattenedNode Type"] + Node[node: FileNode] + Depth[depth: number] + IsExpanded[isExpanded: boolean] + NodeIsLoading[isLoading: boolean] + Key[key: string] + end + + Input --> StoreAccess + StoreAccess --> Computation + Computation --> Output + FlattenedNodes --> FlattenedNode + + style useVirtualizedTree fill:#e3f2fd,stroke:#1976d2 + style Computation fill:#e8f5e9,stroke:#4caf50 + style Output fill:#fff3e0,stroke:#f57c00 +``` + +### Hook Index Exports + +```mermaid +flowchart LR + subgraph HooksModule["hooks/index.ts"] + Index[index.ts] + end + + subgraph Hooks["Exported Hooks"] + useIpcListeners[useIpcListeners
IPC event listeners] + useVirtualizedTree[useVirtualizedTree
File tree virtualization] + end + + subgraph useIpcHooks["useIpc.ts Additional Exports"] + useAppSettings[useAppSettings
Settings management] + useAppVersion[useAppVersion
App version] + end + + Index --> Hooks + useIpcListeners --> useIpcHooks + + style HooksModule fill:#e3f2fd,stroke:#1976d2 + style Hooks fill:#e8f5e9,stroke:#4caf50 + style useIpcHooks fill:#fff3e0,stroke:#f57c00 +``` + +## Store Relationships + +```mermaid +flowchart TB + subgraph CoreStores["Core Stores"] + ProjectStore[projectStore
Project Selection] + TaskStore[taskStore
Task Management] + SettingsStore[settingsStore
App Config] + end + + subgraph FeatureStores["Feature Stores"] + ContextStore[contextStore] + IdeationStore[ideationStore] + RoadmapStore[roadmapStore] + ChangelogStore[changelogStore] + InsightsStore[insightsStore] + end + + subgraph UIStores["UI State Stores"] + TerminalStore[terminalStore] + RateLimitStore[rateLimitStore] + FileExplorerStore[fileExplorerStore] + end + + subgraph IntegrationStores["Integration Stores"] + GitHubStores[GitHub Stores] + ClaudeProfileStore[claudeProfileStore] + end + + ProjectStore -->|selectedProjectId| TaskStore + ProjectStore -->|selectedProjectId| ContextStore + ProjectStore -->|selectedProjectId| IdeationStore + ProjectStore -->|selectedProjectId| RoadmapStore + ProjectStore -->|selectedProjectId| TerminalStore + + TaskStore -->|task execution| TerminalStore + IdeationStore -->|create task| TaskStore + RoadmapStore -->|linkedSpecId| TaskStore + + SettingsStore -->|globalClaudeOAuthToken| ClaudeProfileStore + SettingsStore -->|theme| UIStores + + style CoreStores fill:#e3f2fd,stroke:#1976d2 + style FeatureStores fill:#e8f5e9,stroke:#4caf50 + style UIStores fill:#fff3e0,stroke:#f57c00 + style IntegrationStores fill:#f3e5f5,stroke:#9c27b0 +``` + +## IPC Integration Pattern + +### Store-IPC Contract + +```mermaid +classDiagram + class StoreAsyncAction { + <> + +getState() StoreState + +setState(partial) void + +subscribe(listener) Unsubscribe + } + + class IPCResult~T~ { + +success: boolean + +data?: T + +error?: string + } + + class ElectronAPI { + +getProjects() Promise~IPCResult~Project[]~~ + +getTasks(projectId) Promise~IPCResult~Task[]~~ + +createTask(args) Promise~IPCResult~Task~~ + +onTaskProgress(callback) Cleanup + +onTaskStatusChange(callback) Cleanup + } + + class AsyncActionPattern { + <> + +store.setLoading(true) + +result = await electronAPI.method() + +if result.success then store.setData() + +else store.setError() + +store.setLoading(false) + } + + StoreAsyncAction --> IPCResult : returns + StoreAsyncAction --> ElectronAPI : calls + AsyncActionPattern --> StoreAsyncAction : implements +``` + +### Event Listener Setup Pattern + +```mermaid +sequenceDiagram + participant App as App.tsx + participant Hook as useIpcListeners + participant API as electronAPI + participant Store as Zustand Store + + App->>Hook: Call hook on mount + Hook->>API: onTaskProgress(callback) + API-->>Hook: cleanup function + Hook->>API: onTaskError(callback) + API-->>Hook: cleanup function + Hook->>API: onTaskStatusChange(callback) + API-->>Hook: cleanup function + + Note over Hook: Store cleanup functions + + loop Event Reception + API->>Hook: Invoke callback with data + Hook->>Store: dispatch action + Store-->>App: Re-render + end + + App->>Hook: Component unmount + Hook->>API: Call all cleanup functions +``` + +## Performance Considerations + +### Selector Optimization + +```mermaid +flowchart TB + subgraph BadPattern["Anti-Pattern: Inline Selector"] + Component1[Component] + Store1[Store] + FullState[Full State Object] + Rerender1[Re-render on ANY change] + + Component1 -->|useStore state => state| Store1 + Store1 --> FullState + FullState --> Rerender1 + end + + subgraph GoodPattern["Best Practice: Specific Selector"] + Component2[Component] + Store2[Store] + SpecificField[Specific Field Only] + Rerender2[Re-render only when field changes] + + Component2 -->|useStore state => state.tasks| Store2 + Store2 --> SpecificField + SpecificField --> Rerender2 + end + + style BadPattern fill:#ffebee,stroke:#c62828 + style GoodPattern fill:#e8f5e9,stroke:#2e7d32 +``` + +### Debounced Persistence + +```mermaid +sequenceDiagram + participant U as User Action + participant S as Store + participant D as Debounce Timer + participant API as IPC + + U->>S: Tab change 1 + S->>D: Schedule save (100ms) + U->>S: Tab change 2 (within 100ms) + D->>D: Reset timer + U->>S: Tab change 3 (within 100ms) + D->>D: Reset timer + Note over D: 100ms elapsed + D->>API: saveTabState(finalState) +``` + +## Related Documentation + +- [Renderer Components](./renderer.md) - React component architecture +- [IPC Handlers](./ipc-handlers.md) - Main process IPC handlers +- [Main Process](./main-process.md) - Electron main process +- [Frontend Architecture](../architecture/frontend.md) - Overall frontend design From 1fae4b1aba1bac4da28cbccbe78700dd64c75687 Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Mon, 29 Dec 2025 22:30:17 +0200 Subject: [PATCH 18/27] auto-claude: subtask-5-1 - Create use case diagrams page showing actor intera MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Create comprehensive use case diagrams documentation at docs/diagrams/use-cases.md: - Actor overview diagram with Developer, Claude AI, Git, Linear, Graphiti - Task creation use cases: new task, spec writing, parameter config, Linear/GitHub import - Build execution use cases: lifecycle, agent execution phases, monitoring, batch builds - Review workflow use cases: code review, QA process, merge & deploy operations - Context & memory use cases: project context, memory management, insights - Integration use cases: GitHub, Linear, external tools - Settings & configuration use cases: API keys, project config, preferences Includes 17 Mermaid flowchart diagrams showing actor interactions and system workflows for task creation, build execution, and review processes. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/diagrams/use-cases.md | 695 +++++++++++++++++++++++++++++++++++++ 1 file changed, 695 insertions(+) create mode 100644 docs/diagrams/use-cases.md diff --git a/docs/diagrams/use-cases.md b/docs/diagrams/use-cases.md new file mode 100644 index 0000000000..6dcea3dc64 --- /dev/null +++ b/docs/diagrams/use-cases.md @@ -0,0 +1,695 @@ +# Use Case Diagrams + +This document provides comprehensive use case diagrams for Auto-Claude, illustrating how different actors interact with the system to accomplish tasks. Use case diagrams help visualize the functional requirements and user-system interactions. + +## Actor Overview + +Auto-Claude involves several key actors that interact with the system: + +```mermaid +flowchart LR + subgraph Actors["System Actors"] + Developer["Developer
👤 Primary User"] + Claude["Claude AI
🤖 Agent"] + Git["Git/GitHub
📦 VCS"] + Linear["Linear
📋 Issue Tracker"] + Graphiti["Graphiti
🧠 Memory Store"] + end + + subgraph System["Auto-Claude System"] + Frontend["Frontend
(Electron)"] + Backend["Backend
(Python)"] + end + + Developer --> Frontend + Frontend --> Backend + Backend --> Claude + Backend --> Git + Backend --> Linear + Backend --> Graphiti + + style Developer fill:#e1f5fe,stroke:#0288d1 + style Claude fill:#fff3e0,stroke:#f57c00 + style System fill:#f3e5f5,stroke:#7b1fa2 +``` + +| Actor | Description | Primary Interactions | +|-------|-------------|---------------------| +| **Developer** | Human user operating the application | Task creation, build triggering, code review | +| **Claude AI** | Anthropic's AI assistant executing tasks | Code generation, analysis, testing | +| **Git/GitHub** | Version control and collaboration | Commits, branches, PRs | +| **Linear** | Project management integration | Issue sync, status updates | +| **Graphiti** | Memory and context persistence | Learning, cross-session context | + +--- + +## Task Creation Use Cases + +### Primary Task Creation Flow + +The main use case for creating and configuring a new task: + +```mermaid +flowchart LR + subgraph Developer["Developer"] + D[👤] + end + + subgraph "Task Creation Use Cases" + UC1[Create New Task] + UC2[Write Spec File] + UC3[Configure Task Parameters] + UC4[Set Priority/Labels] + UC5[Import from Linear] + UC6[Import from GitHub Issue] + end + + D --> UC1 + D --> UC2 + D --> UC3 + D --> UC4 + D --> UC5 + D --> UC6 + + UC5 -.->|extends| UC1 + UC6 -.->|extends| UC1 + UC2 -.->|includes| UC1 + UC3 -.->|includes| UC1 + + style UC1 fill:#c8e6c9,stroke:#388e3c + style UC5 fill:#fff9c4,stroke:#fbc02d + style UC6 fill:#fff9c4,stroke:#fbc02d +``` + +### Task Creation Detailed Flow + +```mermaid +flowchart TB + subgraph "Create New Task" + Start((Start)) + OpenWizard[Open Task Creation Wizard] + EnterTitle[Enter Task Title] + WriteSpec[Write/Paste Specification] + SelectPriority[Select Priority] + AddLabels[Add Labels/Tags] + ChooseWorkflow[Choose Workflow Type] + Review[Review Task Details] + Create[Create Task] + End((End)) + end + + Start --> OpenWizard + OpenWizard --> EnterTitle + EnterTitle --> WriteSpec + WriteSpec --> SelectPriority + SelectPriority --> AddLabels + AddLabels --> ChooseWorkflow + ChooseWorkflow --> Review + Review --> Create + Create --> End + + subgraph "Workflow Types" + Feature[feature - New functionality] + Bug[bugfix - Fix existing issue] + Refactor[refactor - Code improvement] + Docs[docs - Documentation] + end + + ChooseWorkflow -.-> Feature + ChooseWorkflow -.-> Bug + ChooseWorkflow -.-> Refactor + ChooseWorkflow -.-> Docs +``` + +### Linear Import Use Case + +```mermaid +flowchart LR + subgraph Developer["Developer"] + D[👤] + end + + subgraph "Linear Integration" + UC1[Browse Linear Issues] + UC2[Search Issues] + UC3[Filter by Status] + UC4[Select Issue] + UC5[Import to Auto-Claude] + UC6[Map Fields] + end + + subgraph Linear["Linear API"] + L[📋] + end + + D --> UC1 + D --> UC2 + D --> UC3 + UC1 --> UC4 + UC2 --> UC4 + UC3 --> UC4 + UC4 --> UC5 + UC5 --> UC6 + + Linear -.->|provides data| UC1 + Linear -.->|provides data| UC2 + + style UC5 fill:#c8e6c9,stroke:#388e3c +``` + +--- + +## Build Execution Use Cases + +### Build Lifecycle Overview + +```mermaid +flowchart LR + subgraph Developer["Developer"] + D[👤] + end + + subgraph "Build Execution Use Cases" + UC1[Start Build] + UC2[Monitor Progress] + UC3[View Live Output] + UC4[Pause/Resume Build] + UC5[Cancel Build] + UC6[Retry Failed Build] + UC7[View Build History] + end + + D --> UC1 + D --> UC2 + D --> UC3 + D --> UC4 + D --> UC5 + D --> UC6 + D --> UC7 + + UC2 -.->|includes| UC1 + UC3 -.->|includes| UC2 + UC6 -.->|extends| UC5 + + style UC1 fill:#c8e6c9,stroke:#388e3c + style UC5 fill:#ffcdd2,stroke:#d32f2f +``` + +### Agent Execution Use Case + +When a build is started, the agent system executes multiple sub-use cases: + +```mermaid +flowchart TB + subgraph "Agent Execution" + Start((Start Build)) + + subgraph Planning["Planning Phase"] + LoadSpec[Load Specification] + AnalyzeProject[Analyze Project Context] + CreatePlan[Create Implementation Plan] + ValidatePlan[Validate Plan Feasibility] + end + + subgraph Coding["Coding Phase"] + SelectSubtask[Select Next Subtask] + GenerateCode[Generate Code] + RunTests[Run Tests] + CommitChanges[Commit Changes] + UpdateProgress[Update Progress] + end + + subgraph QA["QA Phase"] + ReviewChanges[Review All Changes] + RunQATests[Run QA Tests] + ValidateOutput[Validate Output] + SignOff[QA Sign-off] + end + + Complete((Build Complete)) + end + + Start --> LoadSpec + LoadSpec --> AnalyzeProject + AnalyzeProject --> CreatePlan + CreatePlan --> ValidatePlan + ValidatePlan --> SelectSubtask + SelectSubtask --> GenerateCode + GenerateCode --> RunTests + RunTests -->|pass| CommitChanges + RunTests -->|fail| GenerateCode + CommitChanges --> UpdateProgress + UpdateProgress -->|more subtasks| SelectSubtask + UpdateProgress -->|all done| ReviewChanges + ReviewChanges --> RunQATests + RunQATests --> ValidateOutput + ValidateOutput --> SignOff + SignOff --> Complete + + style Start fill:#c8e6c9,stroke:#388e3c + style Complete fill:#c8e6c9,stroke:#388e3c +``` + +### Real-time Monitoring Use Case + +```mermaid +flowchart LR + subgraph Developer["Developer"] + D[👤] + end + + subgraph "Monitoring Use Cases" + UC1[View Terminal Output] + UC2[Track Phase Progress] + UC3[View File Changes] + UC4[Monitor Rate Limits] + UC5[View Agent Logs] + UC6[Check Commit History] + end + + subgraph System["Auto-Claude"] + Terminal[Terminal Panel] + Progress[Progress Indicators] + Diff[File Diff View] + Stats[Rate Limit Stats] + end + + D --> UC1 + D --> UC2 + D --> UC3 + D --> UC4 + D --> UC5 + D --> UC6 + + UC1 --> Terminal + UC2 --> Progress + UC3 --> Diff + UC4 --> Stats + + style Terminal fill:#e3f2fd,stroke:#1976d2 + style Progress fill:#e3f2fd,stroke:#1976d2 +``` + +### Batch Build Use Cases + +```mermaid +flowchart LR + subgraph Developer["Developer"] + D[👤] + end + + subgraph "Batch Operations" + UC1[Queue Multiple Tasks] + UC2[Set Execution Order] + UC3[Run Batch Build] + UC4[Monitor All Builds] + UC5[View Aggregate Results] + UC6[Handle Batch Failures] + end + + D --> UC1 + D --> UC2 + D --> UC3 + D --> UC4 + D --> UC5 + D --> UC6 + + UC1 --> UC2 + UC2 --> UC3 + UC3 --> UC4 + UC4 --> UC5 + UC6 -.->|extends| UC4 + + style UC3 fill:#c8e6c9,stroke:#388e3c +``` + +--- + +## Review Workflow Use Cases + +### Code Review Overview + +```mermaid +flowchart LR + subgraph Developer["Developer"] + D[👤] + end + + subgraph "Review Use Cases" + UC1[View Generated Code] + UC2[Compare Diffs] + UC3[Review Commit Messages] + UC4[Accept Changes] + UC5[Request Revisions] + UC6[Reject Changes] + UC7[Create Pull Request] + end + + D --> UC1 + D --> UC2 + D --> UC3 + D --> UC4 + D --> UC5 + D --> UC6 + D --> UC7 + + UC1 --> UC2 + UC2 --> UC3 + UC3 --> UC4 + UC3 --> UC5 + UC3 --> UC6 + UC4 --> UC7 + + style UC4 fill:#c8e6c9,stroke:#388e3c + style UC5 fill:#fff9c4,stroke:#fbc02d + style UC6 fill:#ffcdd2,stroke:#d32f2f +``` + +### QA Review Process + +```mermaid +flowchart TB + subgraph "QA Review Use Cases" + Start((Start Review)) + + subgraph Automated["Automated Checks"] + RunTests[Run Test Suite] + CheckLint[Run Linters] + CheckTypes[Type Checking] + SecurityScan[Security Scan] + end + + subgraph Manual["Manual Review"] + ReviewCode[Review Code Quality] + CheckLogic[Verify Business Logic] + TestUI[Test UI Changes] + CheckDocs[Verify Documentation] + end + + subgraph Decision["Decision"] + Approve{All Checks Pass?} + Accept[Accept & Sign-off] + Revise[Request Revisions] + end + + Complete((Review Complete)) + end + + Start --> RunTests + RunTests --> CheckLint + CheckLint --> CheckTypes + CheckTypes --> SecurityScan + SecurityScan --> ReviewCode + ReviewCode --> CheckLogic + CheckLogic --> TestUI + TestUI --> CheckDocs + CheckDocs --> Approve + + Approve -->|Yes| Accept + Approve -->|No| Revise + Accept --> Complete + Revise --> Start + + style Accept fill:#c8e6c9,stroke:#388e3c + style Revise fill:#fff9c4,stroke:#fbc02d +``` + +### Merge & Deploy Use Cases + +```mermaid +flowchart LR + subgraph Developer["Developer"] + D[👤] + end + + subgraph "Merge Operations" + UC1[View Worktree Branches] + UC2[Preview Merge] + UC3[Resolve Conflicts] + UC4[Execute Merge] + UC5[Push to Remote] + UC6[Create Release] + end + + subgraph Git["Git/GitHub"] + G[📦] + end + + D --> UC1 + D --> UC2 + D --> UC3 + D --> UC4 + D --> UC5 + D --> UC6 + + UC2 --> UC3 + UC3 --> UC4 + UC4 --> UC5 + UC5 --> UC6 + + UC4 -.->|uses| Git + UC5 -.->|uses| Git + UC6 -.->|uses| Git + + style UC4 fill:#c8e6c9,stroke:#388e3c +``` + +--- + +## Context & Memory Use Cases + +### Context Building + +```mermaid +flowchart LR + subgraph Developer["Developer"] + D[👤] + end + + subgraph "Context Use Cases" + UC1[View Project Context] + UC2[Explore File Tree] + UC3[Search Codebase] + UC4[View Dependencies] + UC5[Analyze Tech Stack] + UC6[Review Security Risks] + end + + subgraph Analysis["Analysis Engine"] + A[🔍] + end + + D --> UC1 + D --> UC2 + D --> UC3 + D --> UC4 + D --> UC5 + D --> UC6 + + Analysis -.->|provides| UC1 + Analysis -.->|provides| UC5 + Analysis -.->|provides| UC6 + + style UC1 fill:#e3f2fd,stroke:#1976d2 +``` + +### Memory & Learning + +```mermaid +flowchart LR + subgraph Developer["Developer"] + D[👤] + end + + subgraph "Memory Use Cases" + UC1[View Session History] + UC2[Access Insights] + UC3[Export Memory] + UC4[Clear History] + UC5[Share Context] + UC6[Configure Memory Settings] + end + + subgraph Graphiti["Graphiti Store"] + G[🧠] + end + + D --> UC1 + D --> UC2 + D --> UC3 + D --> UC4 + D --> UC5 + D --> UC6 + + Graphiti -.->|provides| UC1 + Graphiti -.->|provides| UC2 + UC3 -.->|uses| Graphiti + UC4 -.->|modifies| Graphiti + + style Graphiti fill:#fff3e0,stroke:#f57c00 +``` + +--- + +## Integration Use Cases + +### GitHub Integration + +```mermaid +flowchart LR + subgraph Developer["Developer"] + D[👤] + end + + subgraph "GitHub Use Cases" + UC1[Browse GitHub Issues] + UC2[Create Issue from Task] + UC3[Link PR to Task] + UC4[Sync Issue Status] + UC5[View PR Reviews] + UC6[Merge via GitHub] + end + + subgraph GitHub["GitHub API"] + GH[🐙] + end + + D --> UC1 + D --> UC2 + D --> UC3 + D --> UC4 + D --> UC5 + D --> UC6 + + GitHub -.->|syncs with| UC1 + GitHub -.->|syncs with| UC4 + UC2 -.->|creates in| GitHub + UC3 -.->|links to| GitHub + + style GitHub fill:#f3e5f5,stroke:#7b1fa2 +``` + +### External Tool Integration + +```mermaid +flowchart TB + subgraph Developer["Developer"] + D[👤] + end + + subgraph "Tool Integration Use Cases" + subgraph IDE["IDE Integration"] + UC1[Open in VS Code] + UC2[View in External Editor] + end + + subgraph Terminal["Terminal Tools"] + UC3[Run Custom Commands] + UC4[Execute Scripts] + UC5[Access System Shell] + end + + subgraph Services["External Services"] + UC6[Connect to Linear] + UC7[Configure GitHub] + UC8[Setup Graphiti] + end + end + + D --> UC1 + D --> UC2 + D --> UC3 + D --> UC4 + D --> UC5 + D --> UC6 + D --> UC7 + D --> UC8 + + style IDE fill:#e3f2fd,stroke:#1976d2 + style Terminal fill:#e8f5e9,stroke:#388e3c + style Services fill:#fff3e0,stroke:#f57c00 +``` + +--- + +## Settings & Configuration Use Cases + +### Application Settings + +```mermaid +flowchart LR + subgraph Developer["Developer"] + D[👤] + end + + subgraph "Settings Use Cases" + UC1[Configure API Keys] + UC2[Set Default Paths] + UC3[Customize UI Theme] + UC4[Configure Rate Limits] + UC5[Set Agent Preferences] + UC6[Manage Allowed Commands] + end + + D --> UC1 + D --> UC2 + D --> UC3 + D --> UC4 + D --> UC5 + D --> UC6 + + style UC1 fill:#ffcdd2,stroke:#d32f2f +``` + +### Project Configuration + +```mermaid +flowchart LR + subgraph Developer["Developer"] + D[👤] + end + + subgraph "Project Config Use Cases" + UC1[Select Project Directory] + UC2[Configure Worktree Settings] + UC3[Set Build Commands] + UC4[Configure Test Commands] + UC5[Define File Patterns] + UC6[Setup Pre-commit Hooks] + end + + D --> UC1 + D --> UC2 + D --> UC3 + D --> UC4 + D --> UC5 + D --> UC6 + + UC1 --> UC2 + UC2 --> UC3 + UC3 --> UC4 + + style UC1 fill:#c8e6c9,stroke:#388e3c +``` + +--- + +## Use Case Summary Matrix + +| Category | Primary Use Cases | Actors Involved | +|----------|-------------------|-----------------| +| **Task Creation** | Create task, write spec, import issues | Developer, Linear | +| **Build Execution** | Start build, monitor, pause/cancel | Developer, Claude AI | +| **Review Workflow** | View diffs, approve/reject, create PR | Developer, Git | +| **Context & Memory** | View context, search code, access history | Developer, Graphiti | +| **Integration** | GitHub sync, Linear import, tool config | Developer, External Services | +| **Configuration** | API keys, paths, preferences | Developer | + +--- + +## Related Documentation + +- [Architecture Overview](../architecture/overview.md) - System architecture details +- [Sequence Diagrams](./sequences.md) - Detailed interaction flows +- [Class Diagrams](./classes.md) - Type and interface structures +- [Integration Guide](../architecture/integration.md) - Frontend-backend communication From 9d78a726186ef52314ea7eddf636263ce18ccbac Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Tue, 30 Dec 2025 11:06:55 +0200 Subject: [PATCH 19/27] auto-claude: subtask-5-2 - Create sequence diagrams page showing task executi MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Created comprehensive sequence diagrams documentation at docs/diagrams/sequences.md with 18 mermaid sequence diagrams covering: - Task Execution Sequences: Complete task flow, creation, cancellation - IPC Communication Sequences: Renderer-to-Main, event streaming, handler registration, context bridge security - Agent Lifecycle Sequences: Initialization, phase transitions, error recovery, memory integration - Terminal Integration Sequences: Session creation, Claude Code invocation, session detection - File Watcher Sequences: Implementation plan watching, spec change detection - Integration Sequences: Linear import, GitHub PR creation Also includes reference tables for participant types, message types, and sequence patterns. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/diagrams/sequences.md | 920 +++++++++++++++++++++++++++++++++++++ 1 file changed, 920 insertions(+) create mode 100644 docs/diagrams/sequences.md diff --git a/docs/diagrams/sequences.md b/docs/diagrams/sequences.md new file mode 100644 index 0000000000..4755b57728 --- /dev/null +++ b/docs/diagrams/sequences.md @@ -0,0 +1,920 @@ +# Sequence Diagrams + +This document provides comprehensive sequence diagrams for Auto-Claude, illustrating the temporal flow of operations, inter-process communication, and component interactions. Sequence diagrams help visualize the exact order of events and message passing between system components. + +## Overview + +Sequence diagrams in Auto-Claude document critical flows across three main domains: + +| Domain | Description | Key Participants | +|--------|-------------|------------------| +| **Task Execution** | Full lifecycle from task creation to completion | UI, Store, AgentManager, Python Backend | +| **IPC Communication** | Message passing between Electron processes | Renderer, Preload, Main, IPC Handlers | +| **Agent Lifecycle** | Python agent phases and state transitions | AgentManager, ProcessManager, Claude API | + +--- + +## Task Execution Sequences + +### Complete Task Execution Flow + +The complete flow from user clicking "Start Task" to task completion: + +```mermaid +sequenceDiagram + autonumber + participant User as Developer + participant UI as React UI + participant Store as Zustand Store + participant API as electronAPI + participant IPC as IPC Handler + participant AM as AgentManager + participant PM as ProcessManager + participant Py as Python Backend + participant Claude as Claude API + + User->>UI: Click "Start Task" + UI->>Store: dispatch(setTaskStatus('in_progress')) + UI->>API: task.start(taskId, options) + API->>IPC: ipcRenderer.send('task:start', taskId) + + rect rgb(232, 245, 233) + Note over IPC,AM: Validation Phase + IPC->>IPC: Validate project path + IPC->>IPC: Check git repository + IPC->>IPC: Verify authentication + end + + IPC->>AM: startTaskExecution(taskId, specPath) + AM->>AM: Resolve auth profile + AM->>AM: Build environment vars + AM->>PM: spawnProcess(taskId, args, env) + + rect rgb(227, 242, 253) + Note over PM,Py: Process Spawning + PM->>PM: Setup environment (PYTHONUNBUFFERED, etc.) + PM->>Py: spawn(python, ['run.py', ...args]) + PM->>PM: Attach stdout/stderr handlers + end + + Py->>Claude: Create agent with SDK + + rect rgb(255, 243, 224) + Note over Py,Claude: Planning Phase + Py->>Claude: Analyze specification + Claude-->>Py: Implementation plan + Py-->>PM: __EXEC_PHASE__:planning:... + PM-->>AM: emit('execution-progress') + AM-->>IPC: Forward phase event + IPC-->>Store: Update task phase + end + + rect rgb(232, 245, 233) + Note over Py,Claude: Coding Phase + loop For each subtask + Py->>Claude: Execute subtask + Claude-->>Py: Code changes + Py->>Py: Run verification + Py->>Py: Commit changes + Py-->>PM: __EXEC_PHASE__:coding:subtask-N + PM-->>AM: emit('execution-progress') + AM-->>Store: Update subtask status + end + end + + rect rgb(252, 228, 236) + Note over Py,Claude: QA Phase + Py->>Claude: Review all changes + Claude-->>Py: QA feedback + Py-->>PM: __EXEC_PHASE__:qa_review:... + end + + Py-->>PM: Process exit (code 0) + PM-->>AM: emit('exit', 0) + AM-->>IPC: Forward completion + IPC-->>Store: setTaskStatus('completed') + Store-->>UI: Re-render with completion + UI-->>User: Show success notification +``` + +### Task Creation Sequence + +Creating a new task through the UI wizard: + +```mermaid +sequenceDiagram + autonumber + participant User as Developer + participant Wizard as TaskCreationWizard + participant Store as TaskStore + participant API as electronAPI + participant IPC as IPC Handler + participant FS as File System + participant Git as Git Repository + + User->>Wizard: Open task creation + Wizard->>Wizard: Initialize form state + Wizard->>Store: Get project settings + + User->>Wizard: Enter task details + User->>Wizard: Select workflow type + User->>Wizard: Write specification + + User->>Wizard: Click "Create Task" + + Wizard->>API: task.create(taskData) + API->>IPC: invoke('task:create', taskData) + + rect rgb(227, 242, 253) + Note over IPC,FS: Task File Creation + IPC->>IPC: Generate task ID (NNN-slug) + IPC->>IPC: Create spec directory path + IPC->>FS: mkdir(.auto-claude/specs/taskId) + IPC->>FS: writeFile(spec.md, specification) + end + + rect rgb(232, 245, 233) + Note over IPC,Git: Git Worktree Setup + IPC->>Git: git worktree add --detach + IPC->>Git: Create task branch + end + + IPC-->>API: { success: true, task: newTask } + API-->>Wizard: Task created response + Wizard->>Store: addTask(newTask) + Store-->>Wizard: State updated + Wizard-->>User: Navigate to task view +``` + +### Task Cancellation Sequence + +Cancelling a running task gracefully: + +```mermaid +sequenceDiagram + autonumber + participant User as Developer + participant UI as React UI + participant Store as TaskStore + participant API as electronAPI + participant IPC as IPC Handler + participant AM as AgentManager + participant PM as ProcessManager + participant Py as Python Process + + User->>UI: Click "Cancel Task" + UI->>UI: Show confirmation dialog + User->>UI: Confirm cancellation + + UI->>API: task.cancel(taskId) + API->>IPC: send('task:cancel', taskId) + + IPC->>AM: cancelTask(taskId) + AM->>PM: killProcess(taskId) + + rect rgb(252, 228, 236) + Note over PM,Py: Graceful Shutdown + PM->>Py: SIGTERM signal + PM->>PM: Start kill timeout (5s) + + alt Process responds + Py-->>PM: Exit gracefully + else Timeout exceeded + PM->>Py: SIGKILL signal + Py-->>PM: Forced exit + end + end + + PM-->>AM: emit('exit', -1) + AM->>AM: Cleanup task state + AM-->>IPC: Forward cancellation + IPC-->>Store: setTaskStatus('cancelled') + Store-->>UI: Update task display + UI-->>User: Show cancelled notification +``` + +--- + +## IPC Communication Sequences + +### Renderer to Main Communication + +Standard request-response pattern for IPC: + +```mermaid +sequenceDiagram + autonumber + participant React as React Component + participant Hook as useTaskData Hook + participant API as electronAPI + participant Preload as Preload Script + participant Bridge as contextBridge + participant Main as ipcMain.handle + participant Handler as Task Handler + participant Store as Data Store + + React->>Hook: useTaskData(projectId) + Hook->>API: task.list(projectId) + API->>Preload: ipcRenderer.invoke('task:list') + Preload->>Bridge: Forward through context bridge + Bridge->>Main: IPC message to main process + + Main->>Handler: Route to task handler + Handler->>Store: Query tasks for project + Store-->>Handler: Task data array + Handler->>Handler: Transform and validate + Handler-->>Main: { success: true, data: tasks } + + Main-->>Bridge: IPC response + Bridge-->>Preload: Forward response + Preload-->>API: Promise resolved + API-->>Hook: Tasks array + Hook-->>React: Update component state +``` + +### Event Streaming (Main to Renderer) + +Real-time event streaming for task progress: + +```mermaid +sequenceDiagram + autonumber + participant Py as Python Backend + participant PM as ProcessManager + participant AM as AgentManager + participant IPC as IPC Bridge + participant Win as BrowserWindow + participant Preload as Preload Script + participant Store as Zustand Store + participant React as React Component + + loop Continuous Output + Py->>PM: stdout data chunk + PM->>PM: Buffer and split lines + + alt Phase marker detected + PM->>PM: Parse __EXEC_PHASE__ + PM->>AM: emit('execution-progress', phase) + AM->>IPC: Forward phase event + IPC->>Win: webContents.send('task:executionProgress') + Win->>Preload: IPC event received + Preload->>Store: Trigger registered callback + Store->>Store: Update task phase state + Store->>React: Selector triggers re-render + end + + PM->>AM: emit('log', line) + AM->>IPC: Forward log line + IPC->>Win: webContents.send('task:log') + Win->>Preload: Log event received + Preload->>Store: Append to log buffer + end +``` + +### Multi-Handler IPC Registration + +How IPC handlers are registered at app startup: + +```mermaid +sequenceDiagram + autonumber + participant Main as main.ts + participant Setup as setupIpcHandlers + participant Project as projectHandlers + participant Task as taskHandlers + participant Terminal as terminalHandlers + participant Agent as agentEventsHandlers + participant More as ... 13 more modules + + Main->>Main: Create managers (AM, TM, PM) + Main->>Setup: setupIpcHandlers(managers) + + par Parallel Registration + Setup->>Project: registerProjectHandlers(AM, getWin) + Project->>Project: ipcMain.handle('project:*') + Project->>Project: ipcMain.on('project:*') + and + Setup->>Task: registerTaskHandlers(AM, TM, getWin) + Task->>Task: ipcMain.handle('task:*') + Task->>Task: ipcMain.on('task:*') + and + Setup->>Terminal: registerTerminalHandlers(TM, getWin) + Terminal->>Terminal: ipcMain.handle('terminal:*') + Terminal->>Terminal: ipcMain.on('terminal:*') + and + Setup->>Agent: registerAgentEventsHandlers(AM, getWin) + Agent->>Agent: Subscribe to AM events + Agent->>Agent: Forward to renderer + and + Setup->>More: Register remaining handlers + end + + Setup-->>Main: All handlers registered + Main->>Main: Create main window + Main->>Main: Load renderer +``` + +### Secure Context Bridge + +Security layer for IPC communication: + +```mermaid +sequenceDiagram + autonumber + participant Renderer as Renderer Process + participant Window as window object + participant API as electronAPI + participant Bridge as contextBridge + participant Expose as exposeInMainWorld + participant Preload as Preload Script + participant IPC as ipcRenderer + + Note over Renderer,IPC: App Initialization + + Preload->>Bridge: Create API object + Bridge->>Expose: exposeInMainWorld('electronAPI', api) + Expose->>Window: Attach to window + + Note over Renderer,IPC: Runtime Usage + + Renderer->>Window: Access window.electronAPI + Window->>API: Get exposed API + API->>API: Validate method exists + + rect rgb(252, 228, 236) + Note over API,IPC: Security Boundary + API->>Bridge: Invoke through bridge + Bridge->>Bridge: Sanitize input + Bridge->>IPC: Forward to main process + end + + Note over Renderer,IPC: Direct Node.js Access Blocked + Renderer--xIPC: Cannot access ipcRenderer directly + Renderer--xPreload: Cannot access preload globals +``` + +--- + +## Agent Lifecycle Sequences + +### Agent Initialization + +Starting the Python agent process: + +```mermaid +sequenceDiagram + autonumber + participant AM as AgentManager + participant PM as AgentProcessManager + participant Env as Environment Builder + participant Spawn as child_process.spawn + participant Py as Python Process + participant Agent as CoderAgent + + AM->>PM: spawnProcess(taskId, args) + + rect rgb(232, 245, 233) + Note over PM,Env: Environment Setup + PM->>Env: getCombinedEnv() + Env->>Env: Merge process.env + Env->>Env: Add PYTHONUNBUFFERED=1 + Env->>Env: Add PYTHONIOENCODING=utf-8 + Env->>Env: Add Claude profile vars + Env-->>PM: Complete environment + end + + PM->>PM: Resolve Python path + PM->>PM: Build command arguments + PM->>Spawn: spawn(pythonPath, args, options) + Spawn->>Py: Start Python interpreter + + Py->>Py: Import agent modules + Py->>Py: Load specification + Py->>Agent: Initialize CoderAgent + Agent->>Agent: Setup Claude SDK client + Agent->>Agent: Load tools and prompts + + Agent-->>Py: Agent ready + Py-->>PM: First output (startup) + PM->>PM: Track process in state + PM-->>AM: Process started successfully +``` + +### Agent Phase Transitions + +State machine for agent execution phases: + +```mermaid +sequenceDiagram + autonumber + participant AM as AgentManager + participant Py as Python Agent + participant Claude as Claude API + participant Plan as Implementation Plan + participant FS as File System + + rect rgb(255, 249, 196) + Note over Py,Claude: IDLE -> PLANNING + Py->>Py: __EXEC_PHASE__:planning:Starting... + Py->>Claude: Analyze spec and codebase + Claude-->>Py: Analysis results + Py->>Plan: Create implementation_plan.json + Py->>FS: Write plan to disk + end + + rect rgb(232, 245, 233) + Note over Py,Claude: PLANNING -> CODING + Py->>Py: __EXEC_PHASE__:coding:Starting... + + loop Each Subtask + Py->>Plan: Get next pending subtask + Plan-->>Py: Subtask details + Py->>Py: __EXEC_PHASE__:coding:subtask-N-M + Py->>Claude: Execute subtask + Claude-->>Py: Code changes + Py->>FS: Write files + Py->>Py: Run verification command + Py->>Plan: Update subtask status + Py->>FS: Git commit changes + end + end + + rect rgb(252, 228, 236) + Note over Py,Claude: CODING -> QA_REVIEW + Py->>Py: __EXEC_PHASE__:qa_review:Starting... + Py->>Claude: Review all changes + Claude-->>Py: QA feedback + + alt Issues Found + Py->>Py: __EXEC_PHASE__:qa_fixing:... + Py->>Claude: Fix issues + Claude-->>Py: Fixes applied + Py->>Py: __EXEC_PHASE__:qa_review:Re-reviewing... + end + end + + rect rgb(227, 242, 253) + Note over Py,Claude: QA_REVIEW -> COMPLETE + Py->>Plan: Set QA sign-off + Py->>FS: Final commit + Py->>Py: __EXEC_PHASE__:complete:Build finished + end +``` + +### Agent Error Recovery + +Handling errors and recovery scenarios: + +```mermaid +sequenceDiagram + autonumber + participant PM as ProcessManager + participant Py as Python Agent + participant Claude as Claude API + participant Detect as Error Detector + participant AM as AgentManager + participant UI as React UI + + Py->>Claude: API request + + alt Rate Limit Error + Claude-->>Py: 429 Rate Limit + Py-->>PM: Exit with error output + PM->>Detect: detectRateLimit(output) + Detect-->>AM: Rate limit confirmed + AM->>AM: Check auto-swap setting + + alt Auto-swap enabled + AM->>AM: getBestAvailableProfile() + AM->>AM: setActiveProfile(newProfile) + AM->>PM: Restart with new profile + PM->>Py: New process started + else Manual intervention + AM->>UI: Show rate limit modal + UI->>UI: Display profile options + end + end + + alt Authentication Error + Claude-->>Py: 401 Unauthorized + Py-->>PM: Exit with auth error + PM->>Detect: detectAuthFailure(output) + Detect-->>AM: Auth failure confirmed + AM->>UI: Show auth modal + UI->>UI: Prompt for re-authentication + end + + alt Process Crash + Py-->>PM: Unexpected exit (code != 0) + PM->>PM: Capture exit code + PM-->>AM: emit('exit', errorCode) + AM->>AM: Log error details + AM->>UI: Show error notification + UI->>UI: Display error message + end + + alt Verification Failure + Py->>Py: Run verification command + Py->>Py: Command returns non-zero + Py->>Py: Retry up to 3 times + + alt Retry succeeds + Py->>Py: Continue execution + else All retries fail + Py->>Py: Mark subtask as blocked + Py-->>PM: Continue with next subtask + end + end +``` + +### Agent Memory Integration + +How the agent interacts with Graphiti memory: + +```mermaid +sequenceDiagram + autonumber + participant Agent as CoderAgent + participant Memory as MemoryManager + participant MCP as MCP Server + participant Graphiti as Graphiti API + participant Claude as Claude SDK + + Agent->>Agent: Initialize with Graphiti enabled + Agent->>Memory: Setup MemoryManager + Memory->>MCP: Connect to MCP server + MCP->>Graphiti: Establish connection + + rect rgb(232, 245, 233) + Note over Agent,Graphiti: Context Loading + Agent->>Claude: Start conversation + Claude->>Memory: Query relevant memories + Memory->>MCP: search_memories(query) + MCP->>Graphiti: Graph search + Graphiti-->>MCP: Matching nodes/edges + MCP-->>Memory: Memory results + Memory-->>Claude: Inject as context + end + + rect rgb(227, 242, 253) + Note over Agent,Graphiti: Learning from Session + Agent->>Claude: Complete task + Claude->>Memory: Record discoveries + Memory->>Memory: Extract insights + Memory->>MCP: add_memory(insight) + MCP->>Graphiti: Store in graph + end + + rect rgb(255, 243, 224) + Note over Agent,Graphiti: Cross-Session Recall + Agent->>Claude: New task with similar context + Claude->>Memory: Recall past solutions + Memory->>MCP: search_by_project(projectId) + MCP->>Graphiti: Project-scoped query + Graphiti-->>MCP: Historical patterns + MCP-->>Memory: Past discoveries + Memory-->>Claude: Augment with history + end +``` + +--- + +## Terminal Integration Sequences + +### Terminal Session Creation + +Creating a new PTY session: + +```mermaid +sequenceDiagram + autonumber + participant UI as Terminal UI + participant Store as TerminalStore + participant API as electronAPI + participant IPC as IPC Handler + participant TM as TerminalManager + participant PTY as node-pty + participant Shell as System Shell + + UI->>Store: Request new terminal + Store->>API: terminal.create(options) + API->>IPC: invoke('terminal:create', options) + + IPC->>TM: createTerminal(options) + TM->>TM: Generate session ID + TM->>TM: Resolve shell path + + TM->>PTY: spawn(shell, args, ptyOptions) + PTY->>Shell: Start shell process + + PTY->>TM: onData callback registered + PTY->>TM: onExit callback registered + + TM->>TM: Store session in Map + TM-->>IPC: { sessionId, cols, rows } + IPC-->>API: Session created + API-->>Store: Store session info + Store-->>UI: Render xterm.js terminal +``` + +### Claude Code Invocation + +Invoking Claude Code within a terminal: + +```mermaid +sequenceDiagram + autonumber + participant UI as Terminal Component + participant Store as TerminalStore + participant API as electronAPI + participant TM as TerminalManager + participant PTY as node-pty + participant Shell as Shell Process + participant Claude as Claude Code CLI + + UI->>Store: User clicks "Invoke Claude" + Store->>API: terminal.invokeClaude(sessionId, options) + API->>TM: invokeClaude(sessionId) + + TM->>TM: Build claude command + TM->>TM: Add flags (--continue, etc.) + TM->>PTY: write(claudeCommand + '\r') + + PTY->>Shell: Execute command + Shell->>Claude: Start Claude Code + + Claude-->>Shell: Startup output + Shell-->>PTY: Output data + PTY-->>TM: onData(output) + TM-->>UI: webContents.send('terminal:output') + + UI->>UI: Render Claude output + + loop Interactive Session + UI->>API: terminal.input(userInput) + API->>TM: Forward input + TM->>PTY: write(input) + PTY->>Claude: User input + Claude-->>PTY: Response + PTY-->>TM: onData(response) + TM-->>UI: Send output + end +``` + +### Terminal Session Detection + +Detecting Claude session states: + +```mermaid +sequenceDiagram + autonumber + participant PTY as node-pty + participant TM as TerminalManager + participant Detect as Session Detector + participant Store as TerminalStore + participant UI as Terminal UI + + PTY->>TM: onData(outputChunk) + TM->>Detect: analyzeOutput(chunk) + + alt OAuth Token Detected + Detect->>Detect: Match OAuth pattern + Detect-->>TM: { type: 'oauth', token: '...' } + TM->>Store: storeOAuthToken(token) + TM-->>UI: send('terminal:oauthToken') + end + + alt Claude Session Started + Detect->>Detect: Match session ID pattern + Detect-->>TM: { type: 'session', id: '...' } + TM-->>UI: send('terminal:claudeSession') + UI->>UI: Enable session controls + end + + alt Rate Limit Detected + Detect->>Detect: Match rate limit pattern + Detect-->>TM: { type: 'rateLimit', ... } + TM-->>UI: send('terminal:rateLimit') + UI->>UI: Show rate limit warning + end + + alt Session Ended + Detect->>Detect: Match exit pattern + Detect-->>TM: { type: 'sessionEnd' } + TM-->>UI: send('terminal:sessionEnd') + UI->>UI: Reset session state + end +``` + +--- + +## File Watcher Sequences + +### Implementation Plan Watching + +Monitoring plan file changes during execution: + +```mermaid +sequenceDiagram + autonumber + participant Task as Task Execution + participant IPC as IPC Handler + participant FW as FileWatcher + participant Chok as chokidar + participant FS as File System + participant Store as TaskStore + participant UI as React UI + + Task->>IPC: Task started + IPC->>FW: startWatching(taskId, specDir) + FW->>FW: Build plan file path + FW->>Chok: watch(planPath, options) + + loop File Changes + FS->>Chok: File changed event + Chok->>FW: 'change' event + FW->>FW: Debounce (300ms) + FW->>FS: readFile(planPath) + FS-->>FW: File contents + FW->>FW: JSON.parse(contents) + FW->>FW: Validate plan structure + + alt Valid plan + FW-->>IPC: emit('progress', plan) + IPC->>Store: Update task subtasks + Store->>UI: Re-render subtask list + else Parse error + FW->>FW: Log warning + FW->>FW: Skip update + end + end + + Task->>IPC: Task completed/cancelled + IPC->>FW: stopWatching(taskId) + FW->>Chok: close() +``` + +### Spec File Change Detection + +Detecting changes to specification files: + +```mermaid +sequenceDiagram + autonumber + participant Editor as External Editor + participant FS as File System + participant Chok as chokidar + participant Handler as File Handler + participant IPC as IPC Bridge + participant Store as TaskStore + participant UI as Task Detail View + + Note over Editor,UI: User edits spec in external editor + + Editor->>FS: Save spec.md + FS->>Chok: 'change' event + Chok->>Handler: File changed + + Handler->>FS: Read new content + FS-->>Handler: Updated spec + Handler->>Handler: Compute diff + Handler->>Handler: Check if task running + + alt Task not running + Handler->>IPC: send('task:specUpdated') + IPC->>Store: Update spec content + Store->>UI: Re-render spec display + else Task is running + Handler->>Handler: Queue update + Handler->>IPC: send('task:specPendingUpdate') + IPC->>UI: Show pending indicator + end +``` + +--- + +## Integration Sequences + +### Linear Issue Import + +Importing issues from Linear: + +```mermaid +sequenceDiagram + autonumber + participant User as Developer + participant UI as Linear Panel + participant API as electronAPI + participant IPC as IPC Handler + participant Linear as Linear API + participant Task as Task Creator + participant FS as File System + + User->>UI: Open Linear integration + UI->>API: linear.getIssues(filters) + API->>IPC: invoke('linear:getIssues') + IPC->>Linear: GraphQL query + Linear-->>IPC: Issue list + IPC-->>UI: Display issues + + User->>UI: Select issue to import + UI->>API: linear.importIssue(issueId) + API->>IPC: invoke('linear:importIssue') + + IPC->>Linear: Fetch full issue details + Linear-->>IPC: Issue with description + IPC->>Task: Create task from issue + Task->>FS: Create spec directory + Task->>FS: Write spec.md from issue + Task->>Task: Create task metadata + Task-->>IPC: New task created + + IPC->>Linear: Update issue status + Linear-->>IPC: Status updated + IPC-->>UI: Import complete + UI->>UI: Navigate to new task +``` + +### GitHub PR Creation + +Creating a pull request after task completion: + +```mermaid +sequenceDiagram + autonumber + participant User as Developer + participant UI as Task View + participant API as electronAPI + participant IPC as IPC Handler + participant Git as Git CLI + participant GH as GitHub API + + User->>UI: Click "Create PR" + UI->>API: github.createPR(taskId, options) + API->>IPC: invoke('github:createPR') + + IPC->>Git: Get current branch + Git-->>IPC: Branch name + IPC->>Git: Get commit history + Git-->>IPC: Commits since base + + IPC->>IPC: Generate PR title + IPC->>IPC: Generate PR body + + IPC->>Git: Push branch to remote + Git-->>IPC: Push complete + + IPC->>GH: Create pull request + GH-->>IPC: PR created with URL + + IPC->>IPC: Link PR to task + IPC-->>API: { success: true, prUrl } + API-->>UI: Display PR link + UI->>UI: Show success notification +``` + +--- + +## Sequence Diagram Reference + +### Participant Types + +| Participant | Color | Description | +|-------------|-------|-------------| +| **User/Developer** | Default | Human actor initiating actions | +| **UI Components** | Blue | React components and views | +| **Stores** | Green | Zustand state stores | +| **IPC Layer** | Orange | Electron IPC handlers | +| **Backend** | Pink | Python processes | +| **External APIs** | Purple | Third-party services | + +### Message Types + +| Arrow Style | Meaning | +|-------------|---------| +| `->` | Synchronous call | +| `-->` | Async response | +| `->>` | Async message (no response) | +| `-->>` | Return value | +| `-x` | Blocked/failed | + +### Sequence Patterns + +| Pattern | Use Case | +|---------|----------| +| **Request-Response** | IPC invoke/handle | +| **Fire-and-Forget** | Event emission | +| **Streaming** | Real-time output | +| **Loop** | Repeated operations | +| **Alt** | Conditional branching | +| **Par** | Parallel execution | +| **Rect** | Logical grouping | + +--- + +## Related Documentation + +- [Use Case Diagrams](./use-cases.md) - Actor interactions and workflows +- [Class Diagrams](./classes.md) - Type and interface structures +- [Architecture Overview](../architecture/overview.md) - System architecture +- [Integration Guide](../architecture/integration.md) - IPC communication details From 6ca2f40da1326dbad1561f9fb5d0121a0b75d289 Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Tue, 30 Dec 2025 11:11:20 +0200 Subject: [PATCH 20/27] auto-claude: subtask-5-3 - Create class structure diagrams page showing key interfaces MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added comprehensive class structure diagrams documentation at docs/diagrams/classes.md: - 18 Mermaid classDiagram blocks covering all major interfaces - Backend Agent Classes: Agent hierarchy, tools, state machines - Backend Analysis Classes: Analyzers, context builders, implementation plan - Backend Integration Classes: Graphiti, Linear, MCP interfaces - Frontend Service Classes: AgentManager, TerminalManager, ProfileManager - Frontend IPC Handler Classes: Handler architecture, message types - Frontend State Store Classes: Zustand stores, domain types - Cross-domain relationships and data flow diagrams - Reference tables for UML notation and stereotypes 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/diagrams/classes.md | 1051 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 1051 insertions(+) create mode 100644 docs/diagrams/classes.md diff --git a/docs/diagrams/classes.md b/docs/diagrams/classes.md new file mode 100644 index 0000000000..cfa40e60d4 --- /dev/null +++ b/docs/diagrams/classes.md @@ -0,0 +1,1051 @@ +# Class Structure Diagrams + +This document provides comprehensive class diagrams for Auto-Claude, illustrating the key interfaces, class hierarchies, and relationships for agents, stores, and services. Class diagrams help understand the type system, inheritance patterns, and component interfaces. + +## Overview + +Class diagrams in Auto-Claude document the type structures across three main domains: + +| Domain | Description | Key Classes | +|--------|-------------|-------------| +| **Backend Agents** | Python agent system for task execution | CoderAgent, PlannerAgent, MemoryManager | +| **Backend Services** | Core services for analysis, context, and integrations | Analyzers, ContextBuilder, Graphiti | +| **Frontend Services** | TypeScript services in Electron main process | AgentManager, TerminalManager, ProfileManager | +| **Frontend Stores** | Zustand state stores for React renderer | TaskStore, ProjectStore, SettingsStore | + +--- + +## Backend Agent Classes + +### Agent Class Hierarchy + +The agent system is built on a modular architecture with specialized agents for different phases: + +```mermaid +classDiagram + direction TB + + class BaseAgent { + <> + +project_dir: Path + +spec_dir: Path + +model: str + +logger: Logger + +initialize() + +run() + } + + class CoderAgent { + +recovery_manager: RecoveryManager + +status_manager: StatusManager + +task_logger: TaskLogger + +run_autonomous_agent() + +execute_subtask() + +handle_verification() + } + + class PlannerAgent { + +spec_content: str + +context: dict + +generate_implementation_plan() + +create_phases() + +create_subtasks() + } + + class MemoryManager { + -graphiti_enabled: bool + -mcp_config: dict + +get_graphiti_context() + +save_session_memory() + +debug_memory_system_status() + +query_memories() + } + + class SessionManager { + +spec_dir: Path + +project_dir: Path + +run_agent_session() + +post_session_processing() + +extract_session_insights() + } + + class RecoveryManager { + -memory_path: Path + -attempts: list + -good_commits: list + +record_attempt() + +record_good_commit() + +get_recovery_context() + +should_skip_subtask() + } + + BaseAgent <|-- CoderAgent + BaseAgent <|-- PlannerAgent + CoderAgent --> MemoryManager : uses + CoderAgent --> SessionManager : delegates + CoderAgent --> RecoveryManager : uses + SessionManager --> RecoveryManager : updates +``` + +### Agent Tool Interfaces + +The agent uses Claude SDK tools for various operations: + +```mermaid +classDiagram + direction LR + + class ClaudeSDKClient { + <> + +create_client() + +run_conversation() + +add_tool() + } + + class ProgressTool { + +update_subtask_status() + +record_discovery() + +record_gotcha() + +get_build_progress() + } + + class QATool { + +update_qa_status() + +run_verification() + +check_test_results() + } + + class MemoryTool { + +search_memories() + +add_memory() + +get_session_context() + } + + class SubtaskTool { + +mark_complete() + +mark_failed() + +add_notes() + } + + ClaudeSDKClient --> ProgressTool : registers + ClaudeSDKClient --> QATool : registers + ClaudeSDKClient --> MemoryTool : registers + ClaudeSDKClient --> SubtaskTool : registers +``` + +### Agent State Machine + +```mermaid +classDiagram + class ExecutionPhase { + <> + IDLE + PLANNING + CODING + QA_REVIEW + QA_FIXING + COMPLETE + ERROR + } + + class BuildState { + <> + IDLE + PLANNING + BUILDING + QA + COMPLETE + ERROR + } + + class SubtaskStatus { + <> + pending + in_progress + completed + failed + skipped + } + + class StatusManager { + -project_dir: Path + -active_spec: str + -state: BuildState + +set_active() + +update() + +update_subtasks() + +clear() + } + + StatusManager --> BuildState : tracks + StatusManager --> ExecutionPhase : emits +``` + +--- + +## Backend Analysis Classes + +### Analyzer Class Hierarchy + +```mermaid +classDiagram + direction TB + + class BaseAnalyzer { + <> + +project_dir: Path + +analyze()* dict + +get_name()* str + } + + class ProjectAnalyzer { + +tech_stack: dict + +services: list + +analyze_project() + +detect_frameworks() + +scan_dependencies() + } + + class ServiceAnalyzer { + +service_path: Path + +analyze_service() + +detect_entry_points() + +scan_routes() + } + + class RiskClassifier { + +rules: list + +classify_file() + +assess_change_risk() + +get_risk_score() + } + + class SecurityScanner { + +patterns: list + +scan_secrets() + +check_vulnerabilities() + +audit_dependencies() + } + + class InsightExtractor { + +extract_session_insights() + +extract_code_patterns() + +summarize_changes() + } + + BaseAnalyzer <|-- ProjectAnalyzer + BaseAnalyzer <|-- ServiceAnalyzer + ProjectAnalyzer --> RiskClassifier : uses + ProjectAnalyzer --> SecurityScanner : uses + ServiceAnalyzer --> InsightExtractor : uses +``` + +### Context Detection Classes + +```mermaid +classDiagram + direction LR + + class ContextBuilder { + +project_dir: Path + +spec_dir: Path + +build_context() + +search_codebase() + +categorize_files() + } + + class CodeSearcher { + -index: dict + +search() + +rank_results() + +extract_snippets() + } + + class FileCategorizer { + +categories: dict + +categorize() + +match_patterns() + +get_priority() + } + + class ServiceMatcher { + +services: list + +match_file_to_service() + +get_service_context() + } + + class KeywordExtractor { + +extract_keywords() + +weight_by_importance() + +filter_common_terms() + } + + ContextBuilder --> CodeSearcher : uses + ContextBuilder --> FileCategorizer : uses + ContextBuilder --> ServiceMatcher : uses + CodeSearcher --> KeywordExtractor : uses +``` + +### Implementation Plan Classes + +```mermaid +classDiagram + class ImplementationPlan { + +feature: str + +workflow_type: str + +phases: list~Phase~ + +summary: dict + +verification_strategy: dict + +qa_acceptance: dict + +qa_signoff: dict + +status: str + } + + class Phase { + +id: str + +name: str + +type: PhaseType + +description: str + +depends_on: list~str~ + +parallel_safe: bool + +subtasks: list~Subtask~ + } + + class Subtask { + +id: str + +description: str + +service: str + +files_to_modify: list~str~ + +files_to_create: list~str~ + +patterns_from: list~str~ + +verification: Verification + +status: SubtaskStatus + +notes: str + } + + class Verification { + +type: str + +command: str + +expected: str + } + + class PhaseType { + <> + setup + implementation + testing + integration + documentation + } + + ImplementationPlan *-- Phase : contains + Phase *-- Subtask : contains + Subtask *-- Verification : has + Phase --> PhaseType : typed +``` + +--- + +## Backend Integration Classes + +### External Integration Interfaces + +```mermaid +classDiagram + direction TB + + class GraphitiClient { + <> + +url: str + +api_key: str + +search_memories() + +add_memory() + +get_graph() + } + + class LinearClient { + +api_key: str + +team_id: str + +get_issues() + +create_issue() + +update_status() + +add_comment() + } + + class LinearTaskState { + +task_id: str + +status: str + +spec_dir: Path + +load() + +save() + +update_status() + } + + class MCPServer { + +tools: list + +register_tool() + +handle_request() + +get_capabilities() + } + + class MCPTool { + <> + +name: str + +description: str + +input_schema: dict + +execute() + } + + GraphitiClient --> MCPServer : exposed via + MCPServer --> MCPTool : registers + LinearClient --> LinearTaskState : manages +``` + +--- + +## Frontend Service Classes + +### Main Process Service Architecture + +```mermaid +classDiagram + direction TB + + class AgentManager { + -state: AgentState + -events: AgentEvents + -processManager: AgentProcessManager + -queueManager: AgentQueueManager + +configure() + +startSpecCreation() + +startTaskExecution() + +startQAProcess() + +killTask() + +isRunning() + +getRunningTasks() + } + + class AgentState { + -processes: Map~string, ChildProcess~ + -taskStatus: Map~string, TaskStatus~ + +hasProcess() + +getProcess() + +setProcess() + +removeProcess() + +getRunningTaskIds() + } + + class AgentEvents { + +emitter: EventEmitter + +on() + +off() + +emit() + +once() + } + + class AgentProcessManager { + -pythonPath: string + -autoBuildSourcePath: string + +configure() + +spawnProcess() + +killProcess() + +killAllProcesses() + +getCombinedEnv() + } + + class AgentQueueManager { + -roadmapQueue: Map + -ideationQueue: Map + +startRoadmapGeneration() + +startIdeationGeneration() + +stopRoadmap() + +stopIdeation() + } + + AgentManager --> AgentState : owns + AgentManager --> AgentEvents : owns + AgentManager --> AgentProcessManager : owns + AgentManager --> AgentQueueManager : owns +``` + +### Terminal Management Classes + +```mermaid +classDiagram + direction LR + + class TerminalManager { + -sessions: Map~string, PTYSession~ + -maxSessions: number + +createTerminal() + +destroyTerminal() + +writeToTerminal() + +resizeTerminal() + +getAllSessions() + } + + class PTYSession { + +id: string + +pty: IPty + +shell: string + +cwd: string + +cols: number + +rows: number + +onData() + +onExit() + +write() + +resize() + +kill() + } + + class SessionDetector { + +detectClaudeSession() + +detectOAuthToken() + +detectRateLimit() + +parseOutput() + } + + class IPty { + <> + +pid: number + +cols: number + +rows: number + +write() + +resize() + +kill() + +onData() + +onExit() + } + + TerminalManager *-- PTYSession : manages + PTYSession --> IPty : wraps + TerminalManager --> SessionDetector : uses +``` + +### Profile Management Classes + +```mermaid +classDiagram + class ClaudeProfileManager { + -profiles: ClaudeProfile[] + -activeProfileId: string + -configPath: string + +loadProfiles() + +saveProfiles() + +getActiveProfile() + +setActiveProfile() + +createProfile() + +deleteProfile() + +hasValidAuth() + } + + class ClaudeProfile { + +id: string + +name: string + +authType: AuthType + +oauthToken: string + +apiKey: string + +model: string + +thinkingLevel: ThinkingLevel + +isDefault: boolean + +isAuto: boolean + } + + class AuthType { + <> + oauth + api_key + } + + class ThinkingLevel { + <> + none + low + medium + high + } + + class RateLimitTracker { + -profiles: Map~string, RateLimitInfo~ + +recordRateLimit() + +getRateLimitInfo() + +isRateLimited() + +clearRateLimit() + } + + ClaudeProfileManager *-- ClaudeProfile : manages + ClaudeProfile --> AuthType : has + ClaudeProfile --> ThinkingLevel : has + ClaudeProfileManager --> RateLimitTracker : uses +``` + +--- + +## Frontend IPC Handler Classes + +### IPC Handler Architecture + +```mermaid +classDiagram + direction TB + + class IpcHandler { + <> + +channel: string + +handle() + } + + class ProjectHandlers { + +registerHandlers() + +handleGetProjects() + +handleCreateProject() + +handleDeleteProject() + +handleUpdateProject() + } + + class TaskHandlers { + +registerHandlers() + +handleGetTasks() + +handleCreateTask() + +handleStartTask() + +handleStopTask() + +handleUpdateTaskStatus() + } + + class TerminalHandlers { + +registerHandlers() + +handleCreate() + +handleDestroy() + +handleInput() + +handleResize() + } + + class FileHandlers { + +registerHandlers() + +handleReadFile() + +handleWriteFile() + +handleWatchFile() + +handleOpenInEditor() + } + + class SettingsHandlers { + +registerHandlers() + +handleGetSettings() + +handleSaveSettings() + +handleResetSettings() + } + + IpcHandler <|.. ProjectHandlers + IpcHandler <|.. TaskHandlers + IpcHandler <|.. TerminalHandlers + IpcHandler <|.. FileHandlers + IpcHandler <|.. SettingsHandlers +``` + +### IPC Message Types + +```mermaid +classDiagram + class IpcResult~T~ { + +success: boolean + +data: T + +error: string + } + + class TaskEvent { + +taskId: string + +type: EventType + +payload: any + +timestamp: Date + } + + class ExecutionProgress { + +phase: ExecutionPhase + +phaseProgress: number + +overallProgress: number + +currentSubtask: string + +message: string + +sequenceNumber: number + } + + class EventType { + <> + started + progress + log + error + completed + cancelled + } + + TaskEvent --> EventType : has + TaskEvent --> ExecutionProgress : contains +``` + +--- + +## Frontend State Store Classes + +### Zustand Store Architecture + +```mermaid +classDiagram + direction TB + + class StoreState~T~ { + <> + +state: T + +actions: Actions + } + + class TaskStore { + +tasks: Task[] + +selectedTaskId: string + +isLoading: boolean + +error: string + +setTasks() + +addTask() + +updateTask() + +updateTaskStatus() + +selectTask() + +getSelectedTask() + +getTasksByStatus() + } + + class ProjectStore { + +projects: Project[] + +selectedProjectId: string + +isLoading: boolean + +setProjects() + +addProject() + +selectProject() + +getSelectedProject() + } + + class SettingsStore { + +settings: AppSettings + +isLoading: boolean + +loadSettings() + +updateSettings() + +resetSettings() + } + + class TerminalStore { + +sessions: TerminalSession[] + +activeSessionId: string + +createSession() + +destroySession() + +setActiveSession() + +appendOutput() + } + + StoreState <|.. TaskStore + StoreState <|.. ProjectStore + StoreState <|.. SettingsStore + StoreState <|.. TerminalStore +``` + +### Task Domain Types + +```mermaid +classDiagram + class Task { + +id: string + +specId: string + +title: string + +description: string + +status: TaskStatus + +subtasks: Subtask[] + +metadata: TaskMetadata + +executionProgress: ExecutionProgress + +logs: string[] + +createdAt: Date + +updatedAt: Date + } + + class TaskStatus { + <> + backlog + ready + in_progress + ai_review + human_review + done + cancelled + } + + class TaskMetadata { + +priority: Priority + +category: string + +labels: string[] + +linearIssueId: string + +githubIssueNumber: number + +archivedAt: Date + } + + class Subtask { + +id: string + +title: string + +description: string + +status: SubtaskStatus + +files: string[] + +verification: Verification + } + + Task --> TaskStatus : has + Task *-- TaskMetadata : contains + Task *-- Subtask : contains +``` + +### Context Store Classes + +```mermaid +classDiagram + class ContextStore { + +context: ProjectContext + +isLoading: boolean + +error: string + +loadContext() + +refreshContext() + +clearContext() + } + + class ProjectContext { + +projectId: string + +techStack: TechStack + +services: Service[] + +fileTree: FileNode[] + +securityRisks: Risk[] + +analyzedAt: Date + } + + class TechStack { + +languages: string[] + +frameworks: string[] + +buildTools: string[] + +databases: string[] + +testFrameworks: string[] + } + + class Service { + +name: string + +path: string + +type: ServiceType + +entryPoint: string + +dependencies: string[] + } + + class FileNode { + +path: string + +name: string + +type: FileType + +children: FileNode[] + +metadata: FileMetadata + } + + ContextStore --> ProjectContext : holds + ProjectContext *-- TechStack : has + ProjectContext *-- Service : contains + ProjectContext *-- FileNode : contains +``` + +### Additional Store Interfaces + +```mermaid +classDiagram + class IdeationStore { + +ideas: Idea[] + +filters: IdeationFilters + +isGenerating: boolean + +loadIdeas() + +generateIdeas() + +updateIdeaStatus() + +filterIdeas() + } + + class RoadmapStore { + +roadmap: RoadmapData + +isGenerating: boolean + +loadRoadmap() + +generateRoadmap() + +updateProgress() + } + + class ChangelogStore { + +entries: ChangelogEntry[] + +isGenerating: boolean + +generateChangelog() + +loadHistory() + } + + class RateLimitStore { + +profiles: Map~string, RateLimitInfo~ + +updateRateLimit() + +clearRateLimit() + +isProfileRateLimited() + } + + class InsightsStore { + +insights: Insight[] + +isRunning: boolean + +loadInsights() + +runInsightsSession() + +stopInsights() + } +``` + +--- + +## Cross-Domain Relationships + +### System Integration Overview + +```mermaid +classDiagram + direction TB + + class ElectronMain { + <> + AgentManager + TerminalManager + ProfileManager + IPC Handlers + } + + class ElectronRenderer { + <> + React Components + Zustand Stores + electronAPI + } + + class PythonBackend { + <> + CoderAgent + PlannerAgent + Analyzers + Integrations + } + + class ClaudeAPI { + <> + Claude SDK + Anthropic API + } + + class ExternalServices { + <> + GitHub + Linear + Graphiti + } + + ElectronMain <--> ElectronRenderer : IPC + ElectronMain --> PythonBackend : spawns + PythonBackend --> ClaudeAPI : calls + PythonBackend --> ExternalServices : integrates + ElectronMain --> ExternalServices : optional +``` + +### Data Flow Diagram + +```mermaid +classDiagram + direction LR + + class UserAction { + <> + Click/Input + } + + class ReactComponent { + Props + State + Handlers + } + + class ZustandStore { + State + Actions + Selectors + } + + class ElectronAPI { + invoke() + send() + on() + } + + class IPCHandler { + handle() + emit() + } + + class ServiceManager { + Process + State + Events + } + + class PythonProcess { + Agent + Output + Exit Code + } + + UserAction --> ReactComponent : triggers + ReactComponent --> ZustandStore : updates + ReactComponent --> ElectronAPI : calls + ElectronAPI --> IPCHandler : routes + IPCHandler --> ServiceManager : delegates + ServiceManager --> PythonProcess : manages + PythonProcess --> ServiceManager : emits + ServiceManager --> IPCHandler : forwards + IPCHandler --> ZustandStore : updates + ZustandStore --> ReactComponent : re-renders +``` + +--- + +## Class Diagram Reference + +### Relationship Types + +| Symbol | Meaning | Description | +|--------|---------|-------------| +| `<\|--` | Inheritance | Class extends another class | +| `*--` | Composition | Strong ownership (lifecycle tied) | +| `o--` | Aggregation | Weak ownership (independent lifecycle) | +| `-->` | Association | Uses or references | +| `..>` | Dependency | Temporary usage | +| `<\|..` | Realization | Implements interface | + +### Visibility Modifiers + +| Symbol | Meaning | +|--------|---------| +| `+` | Public | +| `-` | Private | +| `#` | Protected | +| `~` | Package/Internal | + +### Stereotypes Used + +| Stereotype | Meaning | +|------------|---------| +| `<>` | Interface definition | +| `<>` | Abstract class | +| `<>` | Enum type | +| `<>` | Third-party dependency | +| `<>` | Runtime process | +| `<>` | Event type | + +--- + +## Related Documentation + +- [Use Case Diagrams](./use-cases.md) - Actor interactions and workflows +- [Sequence Diagrams](./sequences.md) - Temporal flow of operations +- [Architecture Overview](../architecture/overview.md) - System architecture +- [Backend Components](../components/backend/agents.md) - Detailed agent documentation +- [Frontend Components](../components/frontend/state.md) - State management details From 835d3f979e4984f9e5950c969def8837f6c53810 Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Tue, 30 Dec 2025 14:18:10 +0200 Subject: [PATCH 21/27] docs: Add dark mode theme and local server instructions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Switch to docsify-themeable dark theme - Add comprehensive Mermaid dark mode styling with CSS overrides - Configure Mermaid themeVariables for dark backgrounds and light text - Add file:// protocol detection with helpful server instructions - Style tables, code blocks, and all UI elements for dark mode 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/index.html | 314 ++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 289 insertions(+), 25 deletions(-) diff --git a/docs/index.html b/docs/index.html index 9b56cc8720..1b9579228e 100644 --- a/docs/index.html +++ b/docs/index.html @@ -5,36 +5,306 @@ Auto-Claude Documentation - + +
Loading documentation...
+ + + + + + + + + - + - - - - From 0f77ae8ea862d1b55a7e9e36073ef7bd06909f7c Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Tue, 30 Dec 2025 14:20:59 +0200 Subject: [PATCH 22/27] scripts: Add cross-platform documentation server scripts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - serve-docs.bat for Windows - serve-docs.sh for macOS/Linux (auto-detects OS for browser opening) - Both start npx serve on port 3000 and open browser automatically Usage: Windows: scripts\serve-docs.bat macOS/Linux: ./scripts/serve-docs.sh 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- scripts/serve-docs.bat | 22 +++++++++++++++++++ scripts/serve-docs.sh | 49 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 scripts/serve-docs.bat create mode 100644 scripts/serve-docs.sh diff --git a/scripts/serve-docs.bat b/scripts/serve-docs.bat new file mode 100644 index 0000000000..dd1723b5c6 --- /dev/null +++ b/scripts/serve-docs.bat @@ -0,0 +1,22 @@ +@echo off +REM serve-docs.bat - Start documentation server and open browser (Windows) +REM Usage: scripts\serve-docs.bat + +echo Starting Auto-Claude documentation server... + +REM Check if we're in the right directory +if not exist "docs\index.html" ( + echo Error: docs\index.html not found. + echo Please run this script from the project root directory. + exit /b 1 +) + +REM Start browser after a short delay (in background) +start /b cmd /c "timeout /t 2 /nobreak >nul && start http://localhost:3000" + +REM Start the server (this will block) +echo. +echo Documentation will open in your browser at http://localhost:3000 +echo Press Ctrl+C to stop the server. +echo. +npx serve docs -p 3000 diff --git a/scripts/serve-docs.sh b/scripts/serve-docs.sh new file mode 100644 index 0000000000..93bb84f658 --- /dev/null +++ b/scripts/serve-docs.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# serve-docs.sh - Start documentation server and open browser (macOS/Linux) +# Usage: ./scripts/serve-docs.sh + +set -e + +echo "Starting Auto-Claude documentation server..." + +# Check if we're in the right directory +if [ ! -f "docs/index.html" ]; then + echo "Error: docs/index.html not found." + echo "Please run this script from the project root directory." + exit 1 +fi + +# Detect OS and set browser command +open_browser() { + local url="$1" + if [[ "$OSTYPE" == "darwin"* ]]; then + # macOS + open "$url" + elif [[ "$OSTYPE" == "linux-gnu"* ]]; then + # Linux + if command -v xdg-open &> /dev/null; then + xdg-open "$url" + elif command -v gnome-open &> /dev/null; then + gnome-open "$url" + elif command -v kde-open &> /dev/null; then + kde-open "$url" + else + echo "Could not detect browser. Please open $url manually." + fi + elif [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then + # Windows (Git Bash, Cygwin) + start "$url" + else + echo "Unknown OS. Please open $url manually." + fi +} + +# Open browser after delay (in background) +(sleep 2 && open_browser "http://localhost:3000") & + +# Start the server +echo "" +echo "Documentation will open in your browser at http://localhost:3000" +echo "Press Ctrl+C to stop the server." +echo "" +npx serve docs -p 3000 From 2d46282b9250f2c5943f62eff0fe8bd11a5b330d Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Tue, 30 Dec 2025 14:27:49 +0200 Subject: [PATCH 23/27] ci: Add GitHub Action for automated documentation updates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Workflow triggers on push to develop branch when source files change. Uses GitHub Copilot to: - Analyze recent commits and changed files - Determine if documentation updates are needed - Update relevant docs following existing style - Use Mermaid diagrams for visualizations - Create a PR with the changes for review Only triggers on backend Python and frontend TypeScript changes. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- .github/workflows/update-docs.yml | 134 ++++++++++++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 .github/workflows/update-docs.yml diff --git a/.github/workflows/update-docs.yml b/.github/workflows/update-docs.yml new file mode 100644 index 0000000000..f49e3d4014 --- /dev/null +++ b/.github/workflows/update-docs.yml @@ -0,0 +1,134 @@ +name: Update Documentation + +on: + push: + branches: + - develop + paths: + # Only trigger on source code changes, not docs themselves + - 'apps/backend/**/*.py' + - 'apps/frontend/src/**/*.ts' + - 'apps/frontend/src/**/*.tsx' + +jobs: + update-docs: + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 10 # Fetch recent commits for analysis + + - name: Get recent commits + id: commits + run: | + # Get commits from the last push + COMMITS=$(git log --oneline -10 --no-merges) + echo "commits<> $GITHUB_OUTPUT + echo "$COMMITS" >> $GITHUB_OUTPUT + echo "EOF" >> $GITHUB_OUTPUT + + # Get changed files + CHANGED_FILES=$(git diff --name-only HEAD~5 HEAD 2>/dev/null || git diff --name-only HEAD) + echo "changed_files<> $GITHUB_OUTPUT + echo "$CHANGED_FILES" >> $GITHUB_OUTPUT + echo "EOF" >> $GITHUB_OUTPUT + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + + - name: Use GitHub Copilot to update docs + uses: github/copilot-action@v1 + with: + prompt: | + You are a technical documentation writer for the Auto-Claude project. Your task is to analyze recent code changes and update the documentation if the changes are relevant to the technical overview. + + ## Recent Commits + ${{ steps.commits.outputs.commits }} + + ## Changed Files + ${{ steps.commits.outputs.changed_files }} + + ## Instructions + + 1. **Analyze the changes**: Review the recent commits and changed files to understand what was modified in the codebase. + + 2. **Determine relevance**: Only update documentation if changes affect: + - Architecture or system design + - New components, modules, or services + - API changes or new endpoints + - Agent behavior or workflow changes + - IPC communication patterns + - State management changes + - Integration points between frontend and backend + + 3. **Read existing documentation**: Before making changes, read these example documentation pages to understand the style and format: + - `docs/README.md` - Overview and structure + - `docs/architecture/overview.md` - Architecture documentation style + - `docs/components/backend/agents.md` - Component documentation style + - `docs/diagrams/sequences.md` - How to use Mermaid diagrams + + 4. **Documentation style guidelines**: + - Use Mermaid diagrams for visualizing: + - Flowcharts for processes and workflows + - Sequence diagrams for component interactions + - Class diagrams for type structures + - Keep explanations concise and technical + - Use tables for listing properties, methods, or configurations + - Include code examples where helpful + - Follow the existing heading hierarchy (h2 for main sections, h3 for subsections) + + 5. **Update the appropriate documentation file(s)**: + - Architecture changes → `docs/architecture/` + - Backend component changes → `docs/components/backend/` + - Frontend component changes → `docs/components/frontend/` + - New diagrams → `docs/diagrams/` + - Update `docs/_sidebar.md` if adding new pages + + 6. **If no documentation updates are needed**: Simply respond with "No documentation updates required" and explain why the changes don't warrant documentation updates. + + ## Mermaid Diagram Examples + + ```mermaid + flowchart TB + A[Component] --> B[Process] + B --> C{Decision} + C -->|Yes| D[Action] + C -->|No| E[Alternative] + ``` + + ```mermaid + sequenceDiagram + participant A as Component A + participant B as Component B + A->>B: Request + B-->>A: Response + ``` + + Please analyze the changes and provide any necessary documentation updates. + + - name: Create Pull Request + if: success() + uses: peter-evans/create-pull-request@v5 + with: + token: ${{ secrets.GITHUB_TOKEN }} + commit-message: "docs: Auto-update documentation based on recent changes" + title: "docs: Auto-update documentation" + body: | + This PR contains automated documentation updates based on recent code changes. + + ## Changes analyzed + ``` + ${{ steps.commits.outputs.commits }} + ``` + + Please review the documentation changes to ensure accuracy. + branch: docs/auto-update + base: develop + labels: documentation, automated From 1eb86fb6f6978ab442be69f729fa41afd37d976e Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Tue, 30 Dec 2025 14:31:11 +0200 Subject: [PATCH 24/27] ci: Update docs workflow - technical overview focus, direct commits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Emphasize docs are a technical overview, not a changelog - Add clear list of what NOT to document (bug fixes, refactors, etc.) - Commit directly to develop branch instead of creating PRs - Only update when changes affect fundamental system understanding 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- .github/workflows/update-docs.yml | 80 ++++++++++++++++++------------- 1 file changed, 46 insertions(+), 34 deletions(-) diff --git a/.github/workflows/update-docs.yml b/.github/workflows/update-docs.yml index f49e3d4014..abcf0ef71e 100644 --- a/.github/workflows/update-docs.yml +++ b/.github/workflows/update-docs.yml @@ -47,7 +47,18 @@ jobs: uses: github/copilot-action@v1 with: prompt: | - You are a technical documentation writer for the Auto-Claude project. Your task is to analyze recent code changes and update the documentation if the changes are relevant to the technical overview. + You are a technical documentation writer for the Auto-Claude project. Your task is to analyze recent code changes and update the documentation ONLY if changes are relevant to the technical overview. + + ## IMPORTANT: Documentation Purpose + + This documentation is a **technical overview** of how the Auto-Claude system works. It explains architecture, component relationships, data flows, and system design. + + **This is NOT:** + - A changelog or commit log + - API reference documentation + - A place to document every code change + + **Only update documentation when changes affect the fundamental understanding of how the system works.** Most code changes (bug fixes, refactors, minor features) do NOT require documentation updates. ## Recent Commits ${{ steps.commits.outputs.commits }} @@ -57,41 +68,46 @@ jobs: ## Instructions - 1. **Analyze the changes**: Review the recent commits and changed files to understand what was modified in the codebase. + 1. **Analyze the changes**: Review the recent commits and changed files to understand what was modified. 2. **Determine relevance**: Only update documentation if changes affect: - - Architecture or system design - - New components, modules, or services - - API changes or new endpoints - - Agent behavior or workflow changes - - IPC communication patterns - - State management changes - - Integration points between frontend and backend - - 3. **Read existing documentation**: Before making changes, read these example documentation pages to understand the style and format: + - Architecture or system design patterns + - New major components, modules, or services + - Significant workflow or process changes + - New integration points between systems + - Changes to how agents, IPC, or core systems work + + 3. **Skip documentation updates for**: + - Bug fixes + - Code refactoring without architectural changes + - Minor feature additions + - Performance improvements + - Dependency updates + - Test changes + + 4. **Read existing documentation**: Before making changes, read these example documentation pages to understand the style and format: - `docs/README.md` - Overview and structure - `docs/architecture/overview.md` - Architecture documentation style - `docs/components/backend/agents.md` - Component documentation style - `docs/diagrams/sequences.md` - How to use Mermaid diagrams - 4. **Documentation style guidelines**: + 5. **Documentation style guidelines**: - Use Mermaid diagrams for visualizing: - Flowcharts for processes and workflows - Sequence diagrams for component interactions - Class diagrams for type structures - Keep explanations concise and technical - Use tables for listing properties, methods, or configurations - - Include code examples where helpful - Follow the existing heading hierarchy (h2 for main sections, h3 for subsections) - 5. **Update the appropriate documentation file(s)**: + 6. **Update the appropriate documentation file(s)**: - Architecture changes → `docs/architecture/` - Backend component changes → `docs/components/backend/` - Frontend component changes → `docs/components/frontend/` - New diagrams → `docs/diagrams/` - Update `docs/_sidebar.md` if adding new pages - 6. **If no documentation updates are needed**: Simply respond with "No documentation updates required" and explain why the changes don't warrant documentation updates. + 7. **If no documentation updates are needed**: Simply respond with "No documentation updates required" and briefly explain why. ## Mermaid Diagram Examples @@ -113,22 +129,18 @@ jobs: Please analyze the changes and provide any necessary documentation updates. - - name: Create Pull Request - if: success() - uses: peter-evans/create-pull-request@v5 - with: - token: ${{ secrets.GITHUB_TOKEN }} - commit-message: "docs: Auto-update documentation based on recent changes" - title: "docs: Auto-update documentation" - body: | - This PR contains automated documentation updates based on recent code changes. - - ## Changes analyzed - ``` - ${{ steps.commits.outputs.commits }} - ``` - - Please review the documentation changes to ensure accuracy. - branch: docs/auto-update - base: develop - labels: documentation, automated + - name: Commit documentation changes + run: | + git config --local user.email "github-actions[bot]@users.noreply.github.com" + git config --local user.name "github-actions[bot]" + git add docs/ + if git diff --staged --quiet; then + echo "No documentation changes to commit" + else + git commit -m "docs: Auto-update technical documentation + + Based on recent commits to develop branch. + + 🤖 Generated with GitHub Copilot" + git push + fi From e5eb2f0e0025817e4db8226a48c8d5359fa63f0f Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Tue, 30 Dec 2025 14:32:14 +0200 Subject: [PATCH 25/27] fix: Use absolute paths in sidebar to prevent path duplication MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Change all sidebar links to absolute paths (starting with /) - Remove .md extensions (Docsify handles automatically) - Remove relativePath config option - Fixes 404 errors from duplicated paths like /components/frontend/components/frontend/... 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- docs/_sidebar.md | 34 +++++++++++++++++----------------- docs/index.html | 1 - 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/docs/_sidebar.md b/docs/_sidebar.md index 7414b7530d..39333695c2 100644 --- a/docs/_sidebar.md +++ b/docs/_sidebar.md @@ -1,34 +1,34 @@ - [Home](/) -- [Getting Started](getting-started.md) +- [Getting Started](/getting-started) --- - **Architecture** - - [Overview](architecture/overview.md) - - [Backend Architecture](architecture/backend.md) - - [Frontend Architecture](architecture/frontend.md) - - [Integration](architecture/integration.md) + - [Overview](/architecture/overview) + - [Backend Architecture](/architecture/backend) + - [Frontend Architecture](/architecture/frontend) + - [Integration](/architecture/integration) --- - **Components** - **Backend** - - [Agents System](components/backend/agents.md) - - [Analysis Module](components/backend/analysis.md) - - [CLI Commands](components/backend/cli.md) - - [Core Services](components/backend/core.md) - - [Planning & Integrations](components/backend/planning.md) + - [Agents System](/components/backend/agents) + - [Analysis Module](/components/backend/analysis) + - [CLI Commands](/components/backend/cli) + - [Core Services](/components/backend/core) + - [Planning & Integrations](/components/backend/planning) - **Frontend** - - [Main Process](components/frontend/main-process.md) - - [IPC Handlers](components/frontend/ipc-handlers.md) - - [Renderer Components](components/frontend/renderer.md) - - [State Management](components/frontend/state.md) + - [Main Process](/components/frontend/main-process) + - [IPC Handlers](/components/frontend/ipc-handlers) + - [Renderer Components](/components/frontend/renderer) + - [State Management](/components/frontend/state) --- - **Diagrams** - - [Use Cases](diagrams/use-cases.md) - - [Sequence Diagrams](diagrams/sequences.md) - - [Class Diagrams](diagrams/classes.md) + - [Use Cases](/diagrams/use-cases) + - [Sequence Diagrams](/diagrams/sequences) + - [Class Diagrams](/diagrams/classes) diff --git a/docs/index.html b/docs/index.html index 1b9579228e..07da7c2c5b 100644 --- a/docs/index.html +++ b/docs/index.html @@ -314,7 +314,6 @@

Quick Start:

auto2top: true, coverpage: false, maxLevel: 4, - relativePath: true, search: { placeholder: 'Search documentation', noData: 'No results found', From 5632eec73833b4757e3e371b03ac6643d8ecced9 Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Tue, 30 Dec 2025 14:42:15 +0200 Subject: [PATCH 26/27] fix: Fix Mermaid diagram syntax errors in documentation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Remove
from decision node labels (causes Mermaid parse errors) - Simplify decision node labels in main-process.md flowcharts - Add Mermaid syntax validation guidelines to GitHub Action prompt - Decision nodes {Label} don't support
, rectangular nodes [Label] do 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- .github/workflows/update-docs.yml | 7 +++ docs/components/frontend/main-process.md | 54 +++++++++--------------- 2 files changed, 28 insertions(+), 33 deletions(-) diff --git a/.github/workflows/update-docs.yml b/.github/workflows/update-docs.yml index abcf0ef71e..8be7254430 100644 --- a/.github/workflows/update-docs.yml +++ b/.github/workflows/update-docs.yml @@ -109,6 +109,13 @@ jobs: 7. **If no documentation updates are needed**: Simply respond with "No documentation updates required" and briefly explain why. + 8. **Double-check Mermaid diagrams for syntax errors**: + - Decision nodes (diamond shapes) use `{Label}` syntax - do NOT include `
` inside curly braces + - Rectangular nodes use `[Label]` or `[Label
Subtitle]` - `
` is allowed here + - Keep decision node labels short (e.g., `{Valid?}` not `{Is the value
valid?}`) + - Verify all node connections are valid (source and target nodes exist) + - Test complex diagrams by removing subgraphs if they cause rendering issues + ## Mermaid Diagram Examples ```mermaid diff --git a/docs/components/frontend/main-process.md b/docs/components/frontend/main-process.md index 68cfe51904..7ac3f87e8f 100644 --- a/docs/components/frontend/main-process.md +++ b/docs/components/frontend/main-process.md @@ -221,8 +221,8 @@ classDiagram flowchart TB Start[Start Task] AuthCheck{Auth Valid?} - PathCheck{Auto-build
Path Found?} - ScriptCheck{Script
Exists?} + PathCheck{Path Found?} + ScriptCheck{Script Exists?} GetEnv[Get Combined Env] StoreContext[Store Task Context] SpawnProcess[Spawn Python Process] @@ -237,7 +237,7 @@ flowchart TB subgraph ErrorHandling["Error Handling"] CheckRateLimit{Rate Limited?} CheckAuth{Auth Failed?} - AutoSwap{Auto-Swap
Enabled?} + AutoSwap{Auto-Swap?} ManualModal[Show Manual Modal] SwapProfile[Swap Profile] RestartTask[Restart Task] @@ -514,19 +514,15 @@ The `PythonEnvManager` manages the Python virtual environment required for runni ```mermaid flowchart TB - Start[initialize()] - CheckProgress{Already
initializing?} + Start[initialize] + CheckProgress{Already initializing?} WaitExisting[Wait for existing] - CheckReady{Already
ready?} + CheckReady{Already ready?} ReturnCached[Return cached status] - - subgraph Setup["Environment Setup"] - CheckVenv{Venv exists?} - CreateVenv[Create venv] - CheckDeps{Deps installed?} - InstallDeps[Install requirements.txt] - end - + CheckVenv{Venv exists?} + CreateVenv[Create venv] + CheckDeps{Deps installed?} + InstallDeps[Install requirements.txt] Ready[Ready] Error[Error] @@ -535,35 +531,29 @@ flowchart TB CheckProgress -->|No| CheckReady CheckReady -->|Yes| ReturnCached CheckReady -->|No| CheckVenv - CheckVenv -->|No| CreateVenv CheckVenv -->|Yes| CheckDeps CreateVenv -->|Success| CheckDeps CreateVenv -->|Fail| Error - CheckDeps -->|No| InstallDeps CheckDeps -->|Yes| Ready InstallDeps -->|Success| Ready InstallDeps -->|Fail| Error - - style Setup fill:#e8f5e9,stroke:#4caf50 ``` ### Python Path Resolution ```mermaid flowchart TB - subgraph Resolution["Python Path Resolution"] - VenvReady{Venv ready?} - VenvPath[Return venv Python] - FindPython[findPythonCommand()] - BundledExists{Bundled
Python?} - BundledPath[Return bundled] - SystemPython[Find system Python] - ValidVersion{Python 3.10+?} - ReturnSystem[Return system Python] - Fallback[Return 'python'] - end + VenvReady{Venv ready?} + VenvPath[Return venv Python] + FindPython[findPythonCommand] + BundledExists{Bundled Python?} + BundledPath[Return bundled] + SystemPython[Find system Python] + ValidVersion{Python 3.10+?} + ReturnSystem[Return system Python] + Fallback[Return python] VenvReady -->|Yes| VenvPath VenvReady -->|No| FindPython @@ -573,8 +563,6 @@ flowchart TB SystemPython --> ValidVersion ValidVersion -->|Yes| ReturnSystem ValidVersion -->|No| Fallback - - style Resolution fill:#e3f2fd,stroke:#1976d2 ``` ### Venv Location Strategy @@ -639,9 +627,9 @@ flowchart TB end subgraph Response["Response Handling"] - AutoSwapEnabled{Auto-swap
enabled?} + AutoSwapEnabled{Auto-swap?} FindProfile[Find best profile] - ProfileAvailable{Profile
available?} + ProfileAvailable{Profile OK?} SwapProfile[Swap to new profile] RestartTask[Restart task] ShowModal[Show manual modal] From c6d353358fa02a6ea6dde759a7dcb350289e36cc Mon Sep 17 00:00:00 2001 From: Vinicius Santos Date: Tue, 30 Dec 2025 14:45:54 +0200 Subject: [PATCH 27/27] ci: Use last updated date to track commits for doc updates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Extract "Last updated" date from docs/README.md home page - Get commits only since last documentation update (not arbitrary 10) - Filter commits to only source code changes (py, ts, tsx) - Update the date in README.md on every workflow run - Include last update date in commit message for traceability 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- .github/workflows/update-docs.yml | 42 ++++++++++++++++++++++++------- docs/README.md | 2 +- 2 files changed, 34 insertions(+), 10 deletions(-) diff --git a/.github/workflows/update-docs.yml b/.github/workflows/update-docs.yml index 8be7254430..51fc89536c 100644 --- a/.github/workflows/update-docs.yml +++ b/.github/workflows/update-docs.yml @@ -23,21 +23,35 @@ jobs: with: fetch-depth: 10 # Fetch recent commits for analysis - - name: Get recent commits + - name: Get commits since last doc update id: commits run: | - # Get commits from the last push - COMMITS=$(git log --oneline -10 --no-merges) + # Extract last updated date from docs/README.md (format: > Last updated: YYYY-MM-DD) + LAST_UPDATE=$(grep -oP '(?<=Last updated: )\d{4}-\d{2}-\d{2}' docs/README.md || echo "") + echo "last_update=$LAST_UPDATE" >> $GITHUB_OUTPUT + + if [ -n "$LAST_UPDATE" ]; then + echo "Documentation was last updated on: $LAST_UPDATE" + # Get commits since the last documentation update + COMMITS=$(git log --oneline --since="$LAST_UPDATE" --no-merges -- 'apps/backend/**/*.py' 'apps/frontend/src/**/*.ts' 'apps/frontend/src/**/*.tsx') + CHANGED_FILES=$(git diff --name-only $(git rev-list -1 --before="$LAST_UPDATE" HEAD) HEAD -- 'apps/backend/**/*.py' 'apps/frontend/src/**/*.ts' 'apps/frontend/src/**/*.tsx' 2>/dev/null || echo "") + else + echo "No last update date found, using recent commits" + COMMITS=$(git log --oneline -10 --no-merges) + CHANGED_FILES=$(git diff --name-only HEAD~5 HEAD 2>/dev/null || git diff --name-only HEAD) + fi + echo "commits<> $GITHUB_OUTPUT echo "$COMMITS" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT - # Get changed files - CHANGED_FILES=$(git diff --name-only HEAD~5 HEAD 2>/dev/null || git diff --name-only HEAD) echo "changed_files<> $GITHUB_OUTPUT echo "$CHANGED_FILES" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT + # Store today's date for updating README + echo "today=$(date +%Y-%m-%d)" >> $GITHUB_OUTPUT + - name: Setup Node.js uses: actions/setup-node@v4 with: @@ -60,10 +74,15 @@ jobs: **Only update documentation when changes affect the fundamental understanding of how the system works.** Most code changes (bug fixes, refactors, minor features) do NOT require documentation updates. - ## Recent Commits + ## Documentation Last Updated + The documentation home page (`docs/README.md`) contains a "Last updated" date at the top. + Last update: ${{ steps.commits.outputs.last_update }} + + ## Commits Since Last Documentation Update + These are the source code commits since the documentation was last updated: ${{ steps.commits.outputs.commits }} - ## Changed Files + ## Changed Files Since Last Update ${{ steps.commits.outputs.changed_files }} ## Instructions @@ -136,17 +155,22 @@ jobs: Please analyze the changes and provide any necessary documentation updates. - - name: Commit documentation changes + - name: Update documentation date and commit run: | git config --local user.email "github-actions[bot]@users.noreply.github.com" git config --local user.name "github-actions[bot]" + + # Always update the "Last updated" date in README.md + TODAY="${{ steps.commits.outputs.today }}" + sed -i "s/> Last updated: [0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}/> Last updated: $TODAY/" docs/README.md + git add docs/ if git diff --staged --quiet; then echo "No documentation changes to commit" else git commit -m "docs: Auto-update technical documentation - Based on recent commits to develop branch. + Based on commits since ${{ steps.commits.outputs.last_update }}. 🤖 Generated with GitHub Copilot" git push diff --git a/docs/README.md b/docs/README.md index a6c4aaaa4c..fec8889d59 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2,7 +2,7 @@ **Comprehensive technical documentation for developers working with the Auto-Claude codebase.** -> Last updated: 2025-06-29 +> Last updated: 2025-12-30 ---