# Technical Documentation: AndyMik90/Aperant

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/AndyMik90/Aperant)

### Overview (`README.md`)

# Aperant (formerly Auto Claude)

**Autonomous multi-agent coding framework that plans, builds, and validates software for you.**



[](./agpl-3.0.txt)
[](https://discord.gg/KCXaPBr4Dj)
[](https://www.youtube.com/@AndreMikalsen)
[](https://github.com/AndyMik90/Aperant/actions)
[](https://github.com/hesreallyhim/awesome-claude-code)

---

## 🚀 Status: Aperant 3.0 in active development

> **Aperant is alive and under active development — it is _not_ abandoned.**
>
> We're rebuilding the entire app **from the ground up** for **Aperant 3.0**, which adds **cloud features** on top of the local desktop experience. Aperant 3.0 will stay **fully open source under AGPL-3.0**.
>
> **Why this repo looks quiet:** most of the 3.0 work is happening in a separate development repository right now and will be merged back here once it's ready. So even though commits look sparse on the surface, the project is very much alive and moving fast behind the scenes.
>
> **What this means today:**
> - 🛠️ **The current 2.x desktop app is in maintenance mode** — it's stable and usable, but new development is going into 3.0.
> - 🚫 **Pull requests are paused.** Because the codebase is being rebuilt from scratch, code PRs against the current app can't be merged and will be closed. Please hold off on opening them for now.
> - 💬 **We still want your input.** [Open an issue](https://github.com/AndyMik90/Aperant/issues), [start a discussion](https://github.com/AndyMik90/Aperant/discussions), or [join our Discord](https://discord.gg/KCXaPBr4Dj) to report bugs and help shape what 3.0 becomes.
>
> _No public release date yet — ⭐ star and watch the repo (or join Discord) to follow progress._

---

## Download

> 🛠️ **These are 2.x maintenance builds.** They're stable and fully usable today, but active development has moved to Aperant 3.0 (see status above). Expect critical fixes here rather than new features.

### Stable Release


[](https://github.com/AndyMik90/Aperant/releases/tag/v2.7.6)



| Platform | Download |
|----------|----------|
| **Windows** | [Auto-Claude-2.7.6-win32-x64.exe](https://github.com/AndyMik90/Aperant/releases/download/v2.7.6/Auto-Claude-2.7.6-win32-x64.exe) |
| **macOS (Apple Silicon)** | [Auto-Claude-2.7.6-darwin-arm64.dmg](https://github.com/AndyMik90/Aperant/releases/download/v2.7.6/Auto-Claude-2.7.6-darwin-arm64.dmg) |
| **macOS (Intel)** | [Auto-Claude-2.7.6-darwin-x64.dmg](https://github.com/AndyMik90/Aperant/releases/download/v2.7.6/Auto-Claude-2.7.6-darwin-x64.dmg) |
| **Linux** | [Auto-Claude-2.7.6-linux-x86_64.AppImage](https://github.com/AndyMik90/Aperant/releases/download/v2.7.6/Auto-Claude-2.7.6-linux-x86_64.AppImage) |
| **Linux (Debian)** | [Auto-Claude-2.7.6-linux-amd64.deb](https://github.com/AndyMik90/Aperant/releases/download/v2.7.6/Auto-Claude-2.7.6-linux-amd64.deb) |
| **Linux (Flatpak)** | [Auto-Claude-2.7.6-linux-x86_64.flatpak](https://github.com/AndyMik90/Aperant/releases/download/v2.7.6/Auto-Claude-2.7.6-linux-x86_64.flatpak) |


### Beta Release

> ⚠️ Beta releases may contain bugs and breaking changes. [View all releases](https://github.com/AndyMik90/Aperant/releases)


[](https://github.com/AndyMik90/Aperant/releases/tag/v2.8.0-beta.6)



| Platform | Download |
|----------|----------|
| **Windows** | [Aperant-2.8.0-beta.5-win32-x64.exe](https://github.com/AndyMik90/Aperant/releases/download/v2.8.0-beta.5/Aperant-2.8.0-beta.5-win32-x64.exe) |
| **macOS (Apple Silicon)** | [Aperant-2.8.0-beta.5-darwin-arm64.dmg](https://github.com/AndyMik90/Aperant/releases/download/v2.8.0-beta.5/Aperant-2.8.0-beta.5-darwin-arm64.dmg) |
| **macOS (Intel)** | [Aperant-2.8.0-beta.5-darwin-x64.dmg](https://github.com/AndyMik90/Aperant/releases/download/v2.8.0-beta.5/Aperant-2.8.0-beta.5-darwin-x64.dmg) |
| **Linux** | [Aperant-2.8.0-beta.5-linux-x86_64.AppImage](https://github.com/AndyMik90/Aperant/releases/download/v2.8.0-beta.5/Aperant-2.8.0-beta.5-linux-x86_64.AppImage) |
| **Linux (Debian)** | [Aperant-2.8.0-beta.5-linux-amd64.deb](https://github.com/AndyMik90/Aperant/releases/download/v2.8.0-beta.5/Aperant-2.8.0-beta.5-linux-amd64.deb) |
| **Linux (Flatpak)** | [Aperant-2.8.0-beta.5-linux-x86_64.flatpak](https://github.com/AndyMik90/Aperant/releases/download/v2.8.0-beta.5/Aperant-2.8.0-beta.5-linux-x86_64.flatpak) |


> All releases include SHA256 checksums and VirusTotal scan results for security verification.

---

## Requirements

- **Claude Pro/Max subscription** - [Get one here](https://claude.ai/upgrade)
- **Claude Code CLI** - `npm install @anthropic-ai/claude-code`
- **Git repository** - Your project must be initialized as a git repo

---

## Quick Start

1. **Download and install** the app for your platform
2. **Open your project** - Select a git repository folder
3. **Connect Claude** - The app will guide you through OAuth setup
4. **Create a task** - Describe what you want to build
5. **Watch it work** - Agents plan, code, and validate autonomously

---

## Features

| Feature | Description |
|---------|-------------|
| **Autonomous Tasks** | Describe your goal; agents handle planning, implementation, and validation |
| **Parallel Execution** | Run multiple builds simultaneously with up to 12 agent terminals |
| **Isolated Workspaces** | All changes happen in git worktrees - your main branch stays safe |
| **Self-Validating QA** | Built-in quality assurance loop catches issues before you review |
| **AI-Powered Merge** | Automatic conflict resolution when integrating back to main |
| **Memory Layer** | Agents retain insights across sessions for smarter builds |
| **GitHub/GitLab Integration** | Import issues, investigate with AI, create merge requests |
| **Linear Integration** | Sync tasks with Linear for team progress tracking |
| **Cross-Platform** | Native desktop apps for Windows, macOS, and Linux |
| **Auto-Updates** | App updates automatically when new versions are released |

---

## Interface

### Kanban Board
Visual task management from planning through completion. Create tasks and monitor agent progress in real-time.

### Agent Terminals
AI-powered terminals with one-click task context injection. Spawn multiple agents for parallel work.



### Roadmap
AI-assisted feature planning with competitor analysis and audience targeting.



### Additional Features
- **Insights** - Chat interface for exploring your codebase
- **Ideation** - Discover improvements, performance issues, and vulnerabilities
- **Changelog** - Generate release notes from completed tasks

---

## Project Structure

```
Aperant/
├── apps/
│   └── desktop/     # Electron desktop application (TypeScript AI agent layer + UI)
├── guides/          # Additional documentation
└── scripts/         # Build utilities
```

---

## Development

Want to build and run from source? See [CONTRIBUTING.md](CONTRIBUTING.md) for complete development setup instructions. (Note: code contributions are paused during the 3.0 rebuild — see [Contributing](#contributing) below.)

For Linux-specific builds (Flatpak, AppImage), see [guides/linux.md](guides/linux.md).

---

## Security

Aperant uses a three-layer security model:

1. **OS Sandbox** - Bash commands run in isolation
2. **Filesystem Restrictions** - Operations limited to project directory
3. **Dynamic Command Allowlist** - Only approved commands based on detected project stack

All releases are:
- Scanned with VirusTotal before publishing
- Include SHA256 checksums for verification
- Code-signed where applicable (macOS)

---

## Available Scripts

| Command | Description |
|---------|-------------|
| `npm run install:all` | Install all dependencies |
| `npm start` | Build and run the desktop app |
| `npm run dev` | Run in development mode with hot reload |
| `npm run package` | Package for current platform |
| `npm run package:mac` | Package for macOS |
| `npm run package:win` | Package for Windows |
| `npm run package:linux` | Package for Linux |
| `npm run package:flatpak` | Package as Flatpak (see [guides/linux.md](guides/linux.md)) |
| `npm run lint` | Run linter |
| `npm test` | Run frontend tests |

---

## Contributing

> 🚫 **Pull requests are paused while we rebuild for Aperant 3.0.** The current codebase is being replaced from the ground up, so code PRs against it can't be merged and will be closed. This is temporary — contribution will reopen once the 3.0 foundation lands.

**You can still help shape Aperant right now:**
- 🐛 [Report bugs](https://github.com/AndyMik90/Aperant/issues) you hit in the current app
- 💡 [Share ideas and feature requests](https://github.com/AndyMik90/Aperant/discussions) for 3.0
- 💬 [Join the Discord](https://discord.gg/KCXaPBr4Dj) to follow development and influence the roadmap

When contributions reopen, [CONTRIBUTING.md](CONTRIBUTING.md) covers development setup, code style, testing, and the pull request process.

---

## Community

- **Discord** - [Join our community](https://discord.gg/KCXaPBr4Dj)
- **Issues** - [Report bugs or request features](https://github.com/AndyMik90/Aperant/issues)
- **Discussions** - [Ask questions](https://github.com/AndyMik90/Aperant/discussions)

---

## License

**AGPL-3.0** - GNU Affero General Public License v3.0

Aperant is free to use. If you modify and distribute it, or run it as a service, your code must also be open source under AGPL-3.0.

Commercial licensing available for closed-source use cases.

---

## Star History

[](https://github.com/AndyMik90/Aperant/stargazers)

[](https://star-history.com/#AndyMik90/Aperant&Date)

---

### Overview (`guides/README.md`)

# Auto Claude Guides

Detailed documentation for Auto Claude setup and usage.

## Available Guides

| Guide | Description |
|-------|-------------|
| **[CLI-USAGE.md](CLI-USAGE.md)** | Terminal-only usage for power users, headless servers, and CI/CD |
| **[windows-development.md](windows-development.md)** | Windows-specific development guide (file encoding, paths, line endings) |
| **[linux.md](linux.md)** | Linux-specific installation and build guide (Flatpak, AppImage) |

## Quick Links

- [Main README](../README.md) - Getting started (download and install)
- [Contributing](../CONTRIBUTING.md) - How to contribute and run from source
- [Changelog](../CHANGELOG.md) - Release history

---

### Overview (`apps/desktop/README.md`)

# Auto Claude UI - Frontend

A modern Electron + React desktop application for the Auto Claude autonomous coding framework.

## Prerequisites

### Node.js v24.12.0 LTS (Required)

This project requires **Node.js v24.12.0 LTS** (Latest LTS version as of December 2024).

**Download:** https://nodejs.org/en/download/

**Or install via command line:**

**Windows:**
```bash
winget install OpenJS.NodeJS.LTS
```

**macOS:**
```bash
brew install node@24
```

**Linux (Ubuntu/Debian):**
```bash
curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash -
sudo apt install -y nodejs
```

**Linux (Fedora):**
```bash
sudo dnf install nodejs npm
```

> **IMPORTANT:** When installing Node.js on Windows, make sure to check:
> - "Add to PATH"
> - "npm package manager"

**Verify installation:**
```bash
node --version  # Should output: v24.12.0
npm --version   # Should output: 11.x.x or higher
```

> **Note:** npm is included with Node.js. If `npm` is not found after installing Node.js, you need to reinstall Node.js properly.

## Quick Start

```bash
# Navigate to frontend directory
cd apps/desktop

# Install dependencies (includes native module rebuild)
npm install

# Start development server
npm run dev
```

## Security

This project maintains **0 vulnerabilities**. Run `npm audit` to verify.

```bash
npm audit
# Expected output: found 0 vulnerabilities
```

## Architecture

This project follows a **feature-based architecture** for better maintainability and scalability.

```
/* Detailed source-code truncated for AI context efficiency. */
```

## Scripts

| Command | Description |
|---------|-------------|
| `npm run dev` | Start development server with hot reload |
| `npm run build` | Build for production |
| `npm run package` | Build and package for current platform |
| `npm run package:win` | Package for Windows |
| `npm run package:mac` | Package for macOS |
| `npm run package:linux` | Package for Linux |
| `npm test` | Run unit tests |
| `npm run test:watch` | Run tests in watch mode |
| `npm run test:coverage` | Run tests with coverage |
| `npm run lint` | Check for lint errors |
| `npm run lint:fix` | Auto-fix lint errors |
| `npm run typecheck` | Type check TypeScript |
| `npm audit` | Check for security vulnerabilities |

## Development Guidelines

### Code Organization Principles

1. **Feature-based Architecture**: Group related code by feature, not by type
2. **Single Responsibility**: Each component/hook/store does one thing well
3. **DRY (Don't Repeat Yourself)**: Extract reusable logic into shared modules
4. **KISS (Keep It Simple)**: Prefer simple solutions over complex ones
5. **SOLID Principles**: Apply object-oriented design principles

### Naming Conventions

| Type | Convention | Example |
|------|------------|---------|
| Components | PascalCase | `TaskCard.tsx` |
| Hooks | camelCase with `use` prefix | `useTaskStore.ts` |
| Stores | kebab-case with `-store` suffix | `task-store.ts` |
| Types | PascalCase | `Task`, `TaskStatus` |
| Constants | SCREAMING_SNAKE_CASE | `MAX_RETRIES` |

### TypeScript Guidelines

- **No implicit `any`**: Always type your variables and parameters
- **Use `type` for simple objects**: Prefer `type` over `interface`
- **Export types separately**: Use `export type` for type-only exports

### Security Guidelines

- **Never expose secrets**: API keys, tokens should stay in main process
- **Validate IPC data**: Always validate data coming through IPC
- **Use contextBridge**: Never expose Node.js APIs directly to renderer

## Troubleshooting

### npm not found

If `npm` command is not recognized after installing Node.js:

1. **Windows**: Reinstall Node.js from https://nodejs.org and ensure you check "Add to PATH"
2. **macOS/Linux**: Add to your shell profile:
   ```bash
   export PATH="/usr/local/bin:$PATH"
   ```
3. Restart your terminal

### Native module errors

If you get errors about native modules (node-pty, etc.):

```bash
npm run rebuild
```

### Windows build tools required

If electron-rebuild fails on Windows, install Visual Studio Build Tools:

1. Download from https://visualstudio.microsoft.com/visual-cpp-build-tools/
2. Select "Desktop development with C++" workload
3. Restart terminal and run `npm install` again

## Git Hooks

This project uses Husky for Git hooks that run automatically:

### Pre-commit Hook

Runs before each commit:
- **lint-staged**: Lints staged `.ts`/`.tsx` files
- **typecheck**: TypeScript type checking
- **lint**: ESLint checks
- **npm audit**: Security vulnerability check (high severity)

### Commit Message Format

We use [Conventional Commits](https://www.conventionalcommits.org/). Your commit messages must follow this format:

```
type(scope): description
```

**Valid types:**
| Type | Description |
|------|-------------|
| `feat` | A new feature |
| `fix` | A bug fix |
| `docs` | Documentation changes |
| `style` | Code style (formatting, semicolons, etc.) |
| `refactor` | Code refactoring (no feature/fix) |
| `perf` | Performance improvements |
| `test` | Adding or updating tests |
| `build` | Build system or dependencies |
| `ci` | CI/CD configuration |
| `chore` | Maintenance tasks |
| `revert` | Reverting a previous commit |

**Examples:**
```bash
git commit -m "feat(tasks): add drag and drop support"
git commit -m "fix(terminal): resolve scroll position issue"
git commit -m "docs: update README with setup instructions"
git commit -m "chore: update dependencies"
```

## Package Manager

This project uses **npm** (not pnpm or yarn). The lock files for other package managers are ignored.

## License

AGPL-3.0

---

### Overview (`apps/desktop/src/main/changelog/README.md`)

# Changelog Module

This directory contains the refactored changelog generation system, split into focused, maintainable modules.

## Architecture

The changelog service has been decomposed from a monolithic 1,279-line file into specialized modules:

### Module Structure

```
changelog/
├── changelog-service.ts    # Main orchestrator (slim facade)
├── generator.ts            # AI-powered changelog generation
├── parser.ts               # Parsing and extraction logic
├── formatter.ts            # Prompt building and formatting
├── git-integration.ts      # Git operations (branches, tags, commits)
├── types.ts                # Module-specific type definitions
└── index.ts                # Clean module exports
```

### Responsibilities

#### `changelog-service.ts` (Main Facade)
- Orchestrates all changelog operations
- Manages configuration and environment setup
- Delegates to specialized modules
- Provides public API for IPC handlers
- ~465 lines (down from 1,279)

#### `generator.ts` (AI Generation)
- Handles Claude CLI subprocess spawning
- Manages generation lifecycle and progress
- Rate limit detection and error handling
- Environment configuration for subprocess
- ~340 lines

#### `parser.ts` (Parsing & Extraction)
- Extract spec overviews
- Extract changelog from AI output
- Parse existing changelog files
- Parse git log output into structured data
- ~160 lines

#### `formatter.ts` (Prompt Building)
- Build prompts for task-based changelogs
- Build prompts for git-based changelogs
- Format templates (keep-a-changelog, simple-list, github-release)
- Audience-specific instructions (technical, user-facing, marketing)
- Python script generation for Claude CLI
- ~190 lines

#### `git-integration.ts` (Git Operations)
- Get branches (local and remote)
- Get tags with metadata
- Get current and default branch
- Get commits for various scenarios (recent, since-date, tag-range)
- Get branch diff commits
- ~230 lines

#### `types.ts` (Type Definitions)
- Changelog-specific types
- Configuration interfaces
- Internal type definitions
- ~25 lines

## Usage

### Import the Service

```typescript
import { changelogService } from './changelog-service';
// or
import { changelogService } from './changelog';
```

### Backward Compatibility

The original `/src/main/changelog-service.ts` now serves as a re-export facade, maintaining full backward compatibility with existing code.

## Benefits of Refactoring

1. **Single Responsibility**: Each module has one clear purpose
2. **Easier Testing**: Smaller, focused modules are easier to test
3. **Better Maintainability**: Changes are isolated to relevant modules
4. **Reduced Complexity**: No single file exceeds 500 lines
5. **Improved Readability**: Clear separation of concerns
6. **Easier Navigation**: Developers can quickly find relevant code

## Design Patterns Used

- **Facade Pattern**: `changelog-service.ts` provides unified interface
- **Delegation**: Service delegates to specialized modules
- **Single Responsibility**: Each module has one clear concern
- **Event Emitter**: Generator emits progress and error events

## Migration Notes

No changes required for existing code - the refactoring maintains full API compatibility through the facade pattern.

---

### Overview (`apps/desktop/src/main/claude-profile/README.md`)

# Claude Profile Module

This directory contains the refactored Claude profile management system, broken down into logical, maintainable modules.

## Architecture

The profile management system is organized using separation of concerns, with each module handling a specific responsibility:

```
claude-profile/
├── index.ts                 # Central export point
├── types.ts                 # Type definitions
├── token-encryption.ts      # OAuth token encryption/decryption
├── usage-parser.ts          # Usage data parsing and reset time calculations
├── rate-limit-manager.ts    # Rate limit event tracking
├── profile-storage.ts       # Disk persistence
├── profile-scorer.ts        # Profile availability scoring and auto-switch logic
└── profile-utils.ts         # Helper utilities
```

## Modules

### 1. **token-encryption.ts**
Handles OAuth token encryption and decryption using the OS keychain (Electron's safeStorage API).

**Key Functions:**
- `encryptToken(token: string): string` - Encrypts a token using OS keychain
- `decryptToken(storedToken: string): string` - Decrypts a token, handles legacy plain tokens
- `isTokenEncrypted(storedToken: string): boolean` - Checks if token is encrypted

### 2. **usage-parser.ts**
Parses Claude `/usage` command output and calculates reset times.

**Key Functions:**
- `parseUsageOutput(usageOutput: string): ClaudeUsageData` - Parses full usage output
- `parseResetTime(resetTimeStr: string): Date` - Converts reset time strings to Date objects
- `classifyRateLimitType(resetTimeStr: string): 'session' | 'weekly'` - Determines rate limit type

### 3. **rate-limit-manager.ts**
Manages rate limit events and status tracking.

**Key Functions:**
- `recordRateLimitEvent(profile, resetTimeStr): ClaudeRateLimitEvent` - Records a rate limit hit
- `isProfileRateLimited(profile): {limited, type?, resetAt?}` - Checks current rate limit status
- `clearRateLimitEvents(profile): void` - Clears rate limit history

### 4. **profile-storage.ts**
Handles persistence of profile data to disk with version migration.

**Key Functions:**
- `loadProfileStore(storePath: string): ProfileStoreData | null` - Loads profiles from disk
- `saveProfileStore(storePath: string, data: ProfileStoreData): void` - Saves profiles to disk

**Constants:**
- `STORE_VERSION` - Current storage format version
- `DEFAULT_AUTO_SWITCH_SETTINGS` - Default auto-switch configuration

### 5. **profile-scorer.ts**
Implements intelligent profile scoring and auto-switch logic.

**Key Functions:**
- `getBestAvailableProfile(profiles, settings, excludeProfileId?): ClaudeProfile | null` - Finds best profile based on usage/limits
- `shouldProactivelySwitch(profile, allProfiles, settings): {shouldSwitch, reason?, suggestedProfile?}` - Determines if proactive switch is needed
- `getProfilesSortedByAvailability(profiles): ClaudeProfile[]` - Sorts profiles by availability

**Scoring Criteria:**
1. Not rate-limited (highest priority)
2. Lower weekly usage (more important than session)
3. Lower session usage
4. Authenticated profiles

### 6. **profile-utils.ts**
Helper utilities for profile operations.

**Key Functions:**
- `generateProfileId(name, existingProfiles): string` - Generates unique profile IDs
- `createProfileDirectory(profileName): Promise<string>` - Creates profile directory
- `isProfileAuthenticated(profile): boolean` - Checks if profile has valid auth
- `hasValidToken(profile): boolean` - Validates OAuth token (1 year expiry)
- `expandHomePath(path): string` - Expands ~ in paths

**Constants:**
- `DEFAULT_CLAUDE_CONFIG_DIR` - Default Claude config location (~/.claude)
- `CLAUDE_PROFILES_DIR` - Additional profiles directory (~/.claude-profiles)

### 7. **types.ts**
Re-exports shared types for convenience and future extensibility.

### 8. **index.ts**
Central export point providing a clean public API for all profile functionality.

## Main Manager

The `claude-profile-manager.ts` (parent directory) serves as the high-level coordinator that:
- Delegates to specialized modules
- Manages the overall profile lifecycle
- Coordinates between different subsystems
- Provides the singleton instance

**Original size:** 903 lines
**Refactored size:** 509 lines (44% reduction)
**Total with modules:** 1197 lines (organized and maintainable)

## Usage

### Using the Main Manager
```typescript
import { getClaudeProfileManager } from './claude-profile-manager';

const manager = getClaudeProfileManager();
const profile = manager.getActiveProfile();
const usage = manager.updateProfileUsage(profileId, usageOutput);
```

### Using Individual Modules (Advanced)
```typescript
import { parseUsageOutput, isProfileRateLimited } from './claude-profile';

const usage = parseUsageOutput(output);
const status = isProfileRateLimited(profile);
```

## Benefits of Refactoring

1. **Separation of Concerns** - Each module has a single, well-defined responsibility
2. **Testability** - Modules can be unit tested independently
3. **Maintainability** - Easier to understand and modify specific functionality
4. **Reusability** - Modules can be imported individually when needed
5. **Readability** - Smaller files are easier to navigate and understand
6. **Type Safety** - Clear module boundaries with explicit TypeScript types

## Backward Compatibility

All existing imports continue to work without modification:
```typescript
import { getClaudeProfileManager } from './claude-profile-manager';
```

The public API of `ClaudeProfileManager` remains unchanged, ensuring zero breaking changes for existing code.

## Future Enhancements

Potential areas for future improvement:
- Add comprehensive unit tests for each module
- Implement profile import/export functionality
- Add profile usage analytics and reporting
- Enhance auto-switch algorithms with machine learning
- Add profile backup and restore capabilities

---

### Overview (`apps/desktop/src/main/insights/README.md`)

# Insights Module

This directory contains the modular architecture for the AI-powered codebase insights feature.

## Architecture Overview

The insights module follows a clean separation of concerns with each module handling a specific responsibility:

```
insights-service.ts (186 lines)
├── config.ts (109 lines) - Configuration & Environment Management
├── paths.ts (46 lines) - Path Resolution Utilities
├── session-storage.ts (212 lines) - Filesystem Persistence
├── session-manager.ts (151 lines) - Session Lifecycle Management
└── insights-executor.ts (267 lines) - Python Process Execution
```

## Module Responsibilities

### InsightsConfig (`config.ts`)
- Manages Python and auto-claude source path configuration
- Detects auto-claude installation automatically
- Loads environment variables from auto-claude .env file
- Provides complete process environment with profile support

### InsightsPaths (`paths.ts`)
- Provides consistent path resolution for insights data
- Manages session directory structure
- Handles migration paths for old session format

### SessionStorage (`session-storage.ts`)
- Handles filesystem persistence of sessions
- Loads and saves session JSON files
- Manages session file operations (create, read, update, delete)
- Handles old session format migration
- Generates session titles from first user message

### SessionManager (`session-manager.ts`)
- Manages in-memory session cache
- Coordinates session lifecycle operations
- Provides high-level session operations (create, switch, delete, rename)
- Manages current session pointer

### InsightsExecutor (`insights-executor.ts`)
- Spawns and manages Python insights_runner.py process
- Handles streaming output parsing
- Detects and emits tool usage events
- Detects and handles rate limiting
- Emits status updates and stream chunks

## Usage

The main `InsightsService` class (in `insights-service.ts`) coordinates all these modules:

```typescript
import { InsightsService } from './insights-service';

const service = new InsightsService();

// Configure paths
service.configure(pythonPath, autoBuildSourcePath);

// Load session
const session = service.loadSession(projectId, projectPath);

// Send message
await service.sendMessage(projectId, projectPath, message);
```

## Event Flow

1. User sends message via `sendMessage()`
2. Service loads/creates session via `SessionManager`
3. Service executes query via `InsightsExecutor`
4. Executor emits streaming events (status, chunks, tools)
5. Service saves assistant response via `SessionManager`

## Benefits of This Architecture

- **Maintainability**: Each module has a single, clear responsibility
- **Testability**: Modules can be unit tested independently
- **Reusability**: Modules can be used independently if needed
- **Readability**: Much easier to understand and navigate
- **Extensibility**: Easy to add new features to specific modules

## Migration Notes

This refactoring maintains 100% backward compatibility. All functionality from the original 659-line file is preserved, just better organized across 5 focused modules.

---

### Overview (`apps/desktop/src/main/ipc-handlers/README.md`)

# IPC Handlers - Modular Architecture

This directory contains the refactored IPC (Inter-Process Communication) handlers for Auto Claude UI, organized into domain-specific modules for better maintainability and code organization.

## Overview

The original monolithic `ipc-handlers.ts` file (6,913 lines, 220KB) has been refactored into 16 focused modules, each handling a specific domain of the application.

## Module Structure

### Core Modules

#### `project-handlers.ts` (10KB)
Handles project lifecycle and Python environment management:
- `PROJECT_ADD` - Add new project to workspace
- `PROJECT_REMOVE` - Remove project
- `PROJECT_LIST` - List all projects
- `PROJECT_UPDATE_SETTINGS` - Update project settings
- `PROJECT_INITIALIZE` - Initialize .auto-claude directory
- `PROJECT_CHECK_VERSION` - Check initialization status
- `project:has-local-source` - Check if project has local auto-claude source
- Python environment initialization and status events

#### `task-handlers.ts` (52KB) - Largest module
Manages task lifecycle and execution:
- `TASK_LIST` - List tasks for project
- `TASK_CREATE` - Create new task with auto-generated title
- `TASK_DELETE` - Delete task
- `TASK_UPDATE` - Update task properties
- `TASK_START` - Start task execution
- `TASK_STOP` - Stop running task
- `TASK_REVIEW` - Review task results
- `TASK_UPDATE_STATUS` - Update task status
- `TASK_RECOVER_STUCK` - Recover stuck tasks
- `TASK_CHECK_RUNNING` - Check if task is running
- `TASK_ARCHIVE` / `TASK_UNARCHIVE` - Archive management
- Worktree operations (status, diff, merge, discard)
- Task logs (get, watch, unwatch)

#### `terminal-handlers.ts` (16KB)
Terminal and Claude profile management:
- `TERMINAL_CREATE` - Create terminal session
- `TERMINAL_DESTROY` - Destroy terminal
- `TERMINAL_INPUT` - Send input to terminal
- `TERMINAL_RESIZE` - Resize terminal
- `TERMINAL_INVOKE_CLAUDE` - Invoke Claude in terminal
- Claude profile management (CRUD operations)
- Profile auto-switching and usage tracking
- Terminal session persistence and restoration

#### `settings-handlers.ts` (6.3KB)
Application settings and dialogs:
- `SETTINGS_GET` - Get app settings
- `SETTINGS_SAVE` - Save app settings
- `DIALOG_SELECT_DIRECTORY` - Directory selection dialog
- `DIALOG_CREATE_PROJECT_FOLDER` - Create project folder
- `DIALOG_GET_DEFAULT_PROJECT_LOCATION` - Get default location
- `APP_VERSION` - Get application version

#### `file-handlers.ts` (2.0KB)
File system operations:
- `FILE_EXPLORER_LIST` - List directory contents with filtering

### Feature Modules

#### `roadmap-handlers.ts` (12KB)
Roadmap generation and management:
- `ROADMAP_GET` - Get project roadmap
- `ROADMAP_GENERATE` - Generate roadmap with AI
- `ROADMAP_REFRESH` - Refresh roadmap
- `ROADMAP_UPDATE_FEATURE` - Update feature status
- `ROADMAP_CONVERT_TO_SPEC` - Convert feature to task spec

#### `ideation-handlers.ts` (22KB)
AI-powered ideation system:
- `IDEATION_GET` - Get ideation session
- `IDEATION_GENERATE` - Generate ideas with AI
- `IDEATION_REFRESH` - Refresh ideas
- `IDEATION_STOP` - Stop generation
- `IDEATION_UPDATE_IDEA` - Update idea
- `IDEATION_CONVERT_TO_TASK` - Convert idea to task
- `IDEATION_DISMISS` / `IDEATION_DISMISS_ALL` - Dismiss ideas

#### `insights-handlers.ts` (9.4KB)
AI insights chat system:
- `INSIGHTS_GET_SESSION` - Get chat session
- `INSIGHTS_SEND_MESSAGE` - Send chat message
- `INSIGHTS_CLEAR_SESSION` - Clear session
- `INSIGHTS_CREATE_TASK` - Create task from insights
- Session management (list, new, switch, delete, rename)

#### `changelog-handlers.ts` (8.2KB)
Changelog generation:
- `CHANGELOG_GET_DONE_TASKS` - Get completed tasks
- `CHANGELOG_LOAD_TASK_SPECS` - Load task specifications
- `CHANGELOG_GENERATE` - Generate changelog with AI
- `CHANGELOG_SAVE` - Save changelog
- `CHANGELOG_READ_EXISTING` - Read existing changelog
- `CHANGELOG_SUGGEST_VERSION` - Suggest version number
- Git operations (branches, tags, commits)

#### `context-handlers.ts` (20KB)
Project context and memory:
- `CONTEXT_GET` - Get project context
- `CONTEXT_REFRESH_INDEX` - Refresh project index
- `CONTEXT_MEMORY_STATUS` - Get Graphiti memory status
- `CONTEXT_SEARCH_MEMORIES` - Search memory episodes
- `CONTEXT_GET_MEMORIES` - Get memory episodes

### Integration Modules

#### `github-handlers.ts` (23KB)
GitHub integration:
- `GITHUB_GET_REPOSITORIES` - List repositories
- `GITHUB_GET_ISSUES` - List issues
- `GITHUB_GET_ISSUE` - Get single issue
- `GITHUB_CHECK_CONNECTION` - Test connection
- `GITHUB_INVESTIGATE_ISSUE` - AI investigation
- `GITHUB_IMPORT_ISSUES` - Import issues as tasks
- `GITHUB_CREATE_RELEASE` - Create GitHub release

#### `linear-handlers.ts` (15KB)
Linear integration:
- `LINEAR_GET_TEAMS` - List teams
- `LINEAR_GET_PROJECTS` - List projects
- `LINEAR_GET_ISSUES` - List issues
- `LINEAR_IMPORT_ISSUES` - Import issues as tasks
- `LINEAR_CHECK_CONNECTION` - Test connection

#### `env-handlers.ts` (16KB)
Environment configuration:
- `ENV_GET` - Get project environment
- `ENV_UPDATE` - Update environment variables
- `ENV_CHECK_CLAUDE_AUTH` - Check Claude authentication
- `ENV_INVOKE_CLAUDE_SETUP` - Run Claude setup

#### `autobuild-source-handlers.ts` (8.9KB)
Auto-build source updates:
- `AUTOBUILD_SOURCE_CHECK` - Check for updates
- `AUTOBUILD_SOURCE_DOWNLOAD` - Download updates
- `AUTOBUILD_SOURCE_VERSION` - Get version info
- Source environment configuration

### Event Handlers

#### `agent-events-handlers.ts` (6.1KB)
Agent event forwarding to renderer:
- Agent log events
- Agent error events
- SDK rate limit events
- Agent exit events with status transitions
- Execution progress events
- File watcher events
- Implementation plan updates

## Entry Point

### `index.ts` (3.6KB)
Central registration point that:
- Imports all handler modules
- Exports `setupIpcHandlers()` function
- Configures services with dependencies
- Registers all handlers in organized sequence
- Re-exports individual registration functions

### Main IPC Handlers File
The refactored `ipc-handlers.ts` now:
- Imports `setupIpcHandlers` from `./ipc-handlers`
- Delegates all registration to modular handlers
- Provides clear documentation of module organization
- Reduced from 6,913 lines to ~50 lines

## Benefits of Modular Architecture

### Maintainability
- **Focused Modules**: Each module has a single responsibility
- **Clear Boundaries**: Domain separation makes code easier to understand
- **Reduced Complexity**: Smaller files are easier to navigate and modify
- **Better Organization**: Related handlers grouped together

### Testability
- **Isolated Testing**: Each module can be tested independently
- **Mock Dependencies**: Easier to mock services for unit tests
- **Focused Test Suites**: Test files can mirror module structure

### Developer Experience
- **Easier Navigation**: Find handlers by domain, not by scrolling
- **Reduced Conflicts**: Multiple developers can work on different modules
- **Clear Imports**: Each module declares its dependencies explicitly
- **Better IDE Support**: Faster intellisense and type checking

### Code Quality
- **Explicit Dependencies**: Each module imports only what it needs
- **Type Safety**: Proper TypeScript imports throughout
- **Consistent Patterns**: Uniform registration pattern across modules
- **Documentation**: Each module has clear purpose and scope

## Usage

To register all IPC handlers:

```typescript
import { setupIpcHandlers } from './ipc-handlers';
import { AgentManager } from './agent-manager';
import { TerminalManager } from './terminal-manager';
import { PythonEnvManager } from './python-env-manager';

// Initialize services
const agentManager = new AgentManager();
const terminalManager = new TerminalManager();
const pythonEnvManager = new PythonEnvManager();

// Register all handlers
setupIpcHandlers(
  agentManager,
  terminalManager,
  () => mainWindow,
  pythonEnvManager
);
```

To register individual modules:

```typescript
import { registerTaskHandlers } from './ipc-handlers/task-handlers';

registerTaskHandlers(agentManager, () => mainWindow);
```

## Migration Notes

The refactoring maintains 100% backward compatibility:
- All IPC channel names unchanged
- All handler signatures unchanged
- All service dependencies preserved
- Event forwarding logic unchanged

Original file backed up as `ipc-handlers.ts.backup`.

## Module Dependencies

Each module may depend on:
- **Services**: AgentManager, TerminalManager, ChangelogService, etc.
- **Stores**: projectStore
- **Utilities**: fileWatcher, titleGenerator
- **Constants**: IPC_CHANNELS, AUTO_BUILD_PATHS, getSpecsDir
- **Types**: Extensive TypeScript types from shared/types

All dependencies are explicitly imported at the module level.

---

### Overview (`apps/desktop/src/main/ipc-handlers/context/README.md`)

# Context Handlers Module

This directory contains the refactored context-related IPC handlers for the Auto Claude UI application. The handlers manage project context, memory systems (both file-based and Graphiti/LadybugDB), and project index operations.

## Architecture

The module is organized into focused, single-responsibility files:

### Core Modules

#### `utils.ts` (148 lines)
Shared utility functions for environment configuration and parsing.

**Exports:**
- `getAutoBuildSourcePath()` - Get auto-build source path from settings
- `parseEnvFile(content)` - Parse .env file content into key-value pairs
- `loadProjectEnvVars(projectPath, autoBuildPath)` - Load project-specific environment variables
- `loadGlobalSettings()` - Load global application settings
- `isGraphitiEnabled(projectEnvVars)` - Check if Graphiti memory system is enabled
- `hasOpenAIKey(projectEnvVars, globalSettings)` - Check if OpenAI API key is available
- `getGraphitiConnectionDetails(projectEnvVars)` - Get LadybugDB connection configuration

**Types:**
- `EnvironmentVars` - Environment variable dictionary
- `GlobalSettings` - Global application settings
- `GraphitiConnectionDetails` - LadybugDB connection details

#### `memory-status-handlers.ts` (130 lines)
Handlers for checking Graphiti/memory system configuration status.

**Exports:**
- `loadGraphitiStateFromSpecs(projectPath, autoBuildPath)` - Load Graphiti state from most recent spec
- `buildMemoryStatus(projectPath, autoBuildPath, memoryState)` - Build memory status from environment
- `registerMemoryStatusHandlers(getMainWindow)` - Register IPC handlers

**IPC Channels:**
- `CONTEXT_MEMORY_STATUS` - Get memory system status

#### `memory-data-handlers.ts` (242 lines)
Handlers for retrieving and searching memories (both file-based and LadybugDB).

**Exports:**
- `loadFileBasedMemories(specsDir, limit)` - Load memories from spec files
- `searchFileBasedMemories(specsDir, query, limit)` - Search file-based memories
- `registerMemoryDataHandlers(getMainWindow)` - Register IPC handlers

**IPC Channels:**
- `CONTEXT_GET_MEMORIES` - Get recent memories (with LadybugDB fallback)
- `CONTEXT_SEARCH_MEMORIES` - Search memories by query

**Features:**
- Dual-source memory loading (LadybugDB primary, file-based fallback)
- Session insights extraction from spec directories
- Codebase map integration
- Semantic search support (when Graphiti is available)

#### `project-context-handlers.ts` (199 lines)
Handlers for project context and index operations.

**Exports:**
- `registerProjectContextHandlers(getMainWindow)` - Register IPC handlers

**IPC Channels:**
- `CONTEXT_GET` - Get full project context (index, memory status, recent memories)
- `CONTEXT_REFRESH_INDEX` - Refresh project index by running analyzer

**Features:**
- Project index loading and caching
- Graphiti state detection from specs
- Memory status aggregation
- Analyzer script execution for index regeneration

#### `index.ts` (21 lines)
Main entry point that aggregates all context handlers.

**Exports:**
- `registerContextHandlers(getMainWindow)` - Register all context-related handlers
- Re-exports all utility functions and handler functions

## Refactoring Benefits

### Before (676 lines in single file)
- All context logic in one large file
- Difficult to navigate and maintain
- Repeated code for environment parsing
- Hard to test individual components
- No clear separation of concerns

### After (29 lines main + 740 lines in 5 focused modules)
- **Single Responsibility**: Each module has one clear purpose
- **Reusability**: Utility functions can be imported and tested independently
- **Maintainability**: Easier to find and fix issues in specific areas
- **Testability**: Each module can be unit tested in isolation
- **Readability**: Clear module boundaries with descriptive names
- **Scalability**: Easy to add new handlers without cluttering existing files

## Module Dependencies

```
context-handlers.ts (main entry)
    ↓
context/index.ts (aggregator)
    ↓
    ├── utils.ts (no dependencies, pure utilities)
    ├── memory-status-handlers.ts (depends on: utils)
    ├── memory-data-handlers.ts (depends on: utils, ladybug-service)
    └── project-context-handlers.ts (depends on: utils, memory-status-handlers, memory-data-handlers)
```

## Usage Example

```typescript
import { registerContextHandlers } from './ipc-handlers/context-handlers';

// In main process setup
const getMainWindow = () => mainWindow;
registerContextHandlers(getMainWindow);
```

## Testing Strategy

Each module can be tested independently:

```typescript
// Example: Testing utility functions
import { parseEnvFile, isGraphitiEnabled } from './utils';

test('parseEnvFile handles quotes correctly', () => {
  const content = 'API_KEY="test-key"\nDEBUG=true';
  const vars = parseEnvFile(content);
  expect(vars.API_KEY).toBe('test-key');
  expect(vars.DEBUG).toBe('true');
});

// Example: Testing memory status
import { buildMemoryStatus } from './memory-status-handlers';

test('buildMemoryStatus returns correct status', () => {
  const status = buildMemoryStatus('/path/to/project', 'auto-claude');
  expect(status).toHaveProperty('enabled');
  expect(status).toHaveProperty('available');
});
```

## Future Enhancements

- Add TypeScript interface documentation for all data structures
- Implement caching layer for frequently accessed context data
- Add telemetry for memory system performance
- Support additional memory providers beyond LadybugDB
- Implement memory compression for large session insights

## Related Documentation

- [Project Memory System](../../../../auto-claude/memory.py)
- [Graphiti Memory Integration](../../../../auto-claude/graphiti_memory.py)
- [LadybugDB Integration](../../ladybug-service.ts)
- [IPC Channels](../../../shared/constants.ts)

---

### Overview (`apps/desktop/src/main/ipc-handlers/github/README.md`)

# GitHub Handlers Module

This directory contains the modularized GitHub integration handlers, refactored from the original 742-line `github-handlers.ts` file for better maintainability and code organization.

## Module Structure

```
github/
├── README.md                      # This file
├── index.ts                       # Main entry point, registers all handlers
├── types.ts                       # TypeScript type definitions
├── utils.ts                       # Shared utility functions
├── spec-utils.ts                  # Spec creation and management utilities
├── repository-handlers.ts         # Repository and connection handlers
├── issue-handlers.ts              # Issue fetching and retrieval handlers
├── investigation-handlers.ts      # AI-powered issue investigation handlers
├── import-handlers.ts             # Bulk issue import handlers
└── release-handlers.ts            # GitHub release creation handlers
```

## File Descriptions

### Core Files

**index.ts** (37 lines)
- Main entry point that orchestrates all handler registrations
- Re-exports utilities for external use
- Clean interface for the parent module

**types.ts** (48 lines)
- Shared TypeScript interfaces and types
- GitHub API response types
- Configuration interfaces

**utils.ts** (60 lines)
- `getGitHubConfig()` - Extract GitHub configuration from project
- `githubFetch()` - Wrapper for GitHub API requests with authentication

**spec-utils.ts** (169 lines)
- `createSpecForIssue()` - Create spec directory and initial files
- `buildIssueContext()` - Build context string from issue data
- `buildInvestigationTask()` - Generate task description for AI
- Helper functions for spec numbering and slug generation

### Handler Modules

**repository-handlers.ts** (127 lines)
- `GITHUB_CHECK_CONNECTION` - Verify GitHub connection status
- `GITHUB_GET_REPOSITORIES` - Fetch user's repositories

**issue-handlers.ts** (125 lines)
- `GITHUB_GET_ISSUES` - Fetch issues with filtering
- `GITHUB_GET_ISSUE` - Fetch single issue details
- `transformIssue()` - Transform API response to app format

**investigation-handlers.ts** (211 lines)
- `GITHUB_INVESTIGATE_ISSUE` - AI-powered issue investigation
- Progress tracking and event emission
- Integration with AgentManager for task creation

**import-handlers.ts** (107 lines)
- `GITHUB_IMPORT_ISSUES` - Bulk import of multiple issues
- Error handling and progress tracking
- Task creation for each imported issue

**release-handlers.ts** (126 lines)
- `GITHUB_CREATE_RELEASE` - Create GitHub releases via gh CLI
- CLI availability and authentication checks
- Support for draft and prerelease options

## Benefits of This Structure

### 1. Improved Maintainability
- Each module has a single, clear responsibility
- Easy to locate and update specific functionality
- Reduced cognitive load when working on specific features

### 2. Better Code Organization
- Logical grouping of related handlers
- Shared utilities extracted to dedicated files
- Clear separation between data types, utilities, and handlers

### 3. Enhanced Testability
- Individual modules can be tested in isolation
- Mock dependencies at module boundaries
- Easier to write focused unit tests

### 4. Scalability
- Easy to add new handler types as separate modules
- Can extend functionality without modifying existing modules
- Clear patterns for new contributors to follow

### 5. Reduced Complexity
- Main entry file reduced from 742 to 33 lines (95.6% reduction)
- No single file exceeds 211 lines
- Each module is focused and comprehensible

## Usage

The module maintains the same public interface as the original file:

```typescript
import { registerGithubHandlers } from './github-handlers';
import { AgentManager } from '../agent';
import type { BrowserWindow } from 'electron';

const agentManager = new AgentManager();
const getMainWindow = () => mainWindow;

registerGithubHandlers(agentManager, getMainWindow);
```

## Dependencies

- `electron` - IPC communication
- `child_process` - For gh CLI operations
- `fs` - File system operations
- `path` - Path manipulation
- Project modules:
  - `../../shared/constants` - Constants and configuration
  - `../../shared/types` - Type definitions
  - `../project-store` - Project data access
  - `../agent` - Agent management

## Handler Registration Flow

```
registerGithubHandlers()
  ├── registerRepositoryHandlers()
  │   ├── registerCheckConnection()
  │   └── registerGetRepositories()
  ├── registerIssueHandlers()
  │   ├── registerGetIssues()
  │   └── registerGetIssue()
  ├── registerInvestigationHandlers()
  │   └── registerInvestigateIssue()
  ├── registerImportHandlers()
  │   └── registerImportIssues()
  └── registerReleaseHandlers()
      └── registerCreateRelease()
```

## IPC Channels

All handlers use channels defined in `IPC_CHANNELS`:

- `GITHUB_CHECK_CONNECTION`
- `GITHUB_GET_REPOSITORIES`
- `GITHUB_GET_ISSUES`
- `GITHUB_GET_ISSUE`
- `GITHUB_INVESTIGATE_ISSUE`
- `GITHUB_INVESTIGATION_PROGRESS`
- `GITHUB_INVESTIGATION_COMPLETE`
- `GITHUB_INVESTIGATION_ERROR`
- `GITHUB_IMPORT_ISSUES`
- `GITHUB_CREATE_RELEASE`

## Future Enhancements

Potential areas for further improvement:

1. **Error Handling** - Centralized error handling middleware
2. **Caching** - Add response caching for frequently accessed data
3. **Rate Limiting** - Implement GitHub API rate limit handling
4. **Testing** - Add comprehensive unit and integration tests
5. **Logging** - Enhanced logging and debugging capabilities
6. **Webhooks** - Support for GitHub webhook integration
7. **PR Handlers** - Separate module for pull request operations

---

### Overview (`apps/desktop/src/main/ipc-handlers/task/README.md`)

# Task Handlers Module

This directory contains the refactored task-related IPC handlers, previously consolidated in a single 1,873-line file. The code has been reorganized into smaller, focused modules for better maintainability.

## Module Structure

### Core Modules

| Module | Lines | Responsibility |
|--------|-------|----------------|
| `crud-handlers.ts` | ~428 | Task CRUD operations (Create, Read, Update, Delete, List) |
| `execution-handlers.ts` | ~553 | Task execution lifecycle (Start, Stop, Review, Status, Recovery) |
| `worktree-handlers.ts` | ~759 | Git worktree management (Status, Diff, Merge, Preview, Discard, List) |
| `logs-handlers.ts` | ~111 | Task logs operations (Get, Watch, Unwatch) |
| `shared.ts` | ~22 | Shared utilities and helper functions |
| `index.ts` | ~41 | Main module exports and registration |

### Main Entry Point

The main `task-handlers.ts` file (now 22 lines) serves as a simple re-export of the modular implementation.

## Module Responsibilities

### CRUD Handlers (`crud-handlers.ts`)
Handles basic task lifecycle operations:
- **TASK_LIST** - List all tasks for a project
- **TASK_CREATE** - Create new task with spec directory
- **TASK_DELETE** - Delete task and associated files
- **TASK_UPDATE** - Update task metadata, title, description

Features:
- Auto-generates task titles using Claude AI
- Manages attached images (save to disk, maintain references)
- Creates spec directories with proper structure
- Updates implementation plans and requirements

### Execution Handlers (`execution-handlers.ts`)
Manages task execution lifecycle:
- **TASK_START** - Start task execution (spec creation or implementation)
- **TASK_STOP** - Stop running task
- **TASK_REVIEW** - Approve or reject task results
- **TASK_UPDATE_STATUS** - Update task status manually
- **TASK_CHECK_RUNNING** - Check if task has active process
- **TASK_RECOVER_STUCK** - Recover tasks stuck in inconsistent state

Features:
- Handles spec creation phase vs implementation phase
- Auto-starts tasks when moved to in_progress
- Intelligent recovery with subtask analysis
- File watcher integration

### Worktree Handlers (`worktree-handlers.ts`)
Manages git worktree operations:
- **TASK_WORKTREE_STATUS** - Get worktree status and git info
- **TASK_WORKTREE_DIFF** - Get detailed file-level diff
- **TASK_WORKTREE_MERGE** - Merge worktree into main branch
- **TASK_WORKTREE_MERGE_PREVIEW** - Preview merge conflicts
- **TASK_WORKTREE_DISCARD** - Discard worktree and branch
- **TASK_LIST_WORKTREES** - List all project worktrees

Features:
- Per-spec worktree architecture (`.worktrees/{spec-name}/`)
- Smart merge with AI-powered conflict resolution
- Merge preview with conflict analysis
- Stage-only merge option (--no-commit)
- Comprehensive git statistics

### Logs Handlers (`logs-handlers.ts`)
Manages task logs and streaming:
- **TASK_LOGS_GET** - Get task logs organized by phase
- **TASK_LOGS_WATCH** - Start watching spec for log changes
- **TASK_LOGS_UNWATCH** - Stop watching spec

Features:
- Real-time log streaming to renderer
- Event forwarding for logs-changed and stream-chunk
- Phase-organized logs (planning, coding, validation)

### Shared Utilities (`shared.ts`)
Common helper functions:
- `findTaskAndProject()` - Locate task and project by ID

## Usage

Import the main registration function:

```typescript
import { registerTaskHandlers } from './ipc-handlers/task-handlers';

// Register all task handlers
registerTaskHandlers(agentManager, pythonEnvManager, getMainWindow);
```

## Benefits of Refactoring

### Code Quality
- **Single Responsibility**: Each module has one clear purpose
- **Readability**: Smaller files are easier to understand
- **Maintainability**: Changes are isolated to relevant modules
- **Testability**: Modules can be tested independently

### Developer Experience
- **Navigation**: Find specific handlers quickly
- **Context**: Related functionality grouped together
- **Documentation**: Clear module boundaries
- **Scalability**: Easy to add new handlers

### Metrics

| Metric | Before | After |
|--------|--------|-------|
| Main file size | 1,885 lines | 22 lines |
| Number of files | 1 | 7 (6 + index) |
| Largest module | 1,885 lines | 759 lines |
| Average module | 1,885 lines | ~314 lines |

## Dependencies

### External
- `electron` - IPC communication
- `fs` - File system operations
- `child_process` - Process management
- `path` - Path utilities

### Internal
- `../../shared/constants` - IPC channels, paths
- `../../shared/types` - TypeScript types
- `../../agent` - Agent management
- `../../project-store` - Project state
- `../../file-watcher` - File watching
- `../../task-log-service` - Log service
- `../../title-generator` - AI title generation
- `../../python-env-manager` - Python environment
- `../../auto-claude-updater` - Source paths
- `../../rate-limit-detector` - Profile environment

## Architecture Notes

### Worktree Architecture
Each task spec has its own isolated worktree at `.worktrees/{spec-name}/`:
- Enables safe parallel development
- Each spec has dedicated branch: `auto-claude/{spec-name}`
- Branches stay local until user explicitly pushes
- User reviews in worktree before merging to main

### Status Management
Tasks maintain status in `implementation_plan.json`:
- UI statuses: `backlog`, `in_progress`, `ai_review`, `human_review`, `done`
- Python statuses: `pending`, `in_progress`, `review`, `completed`
- Status mapping handled by project-store

### Recovery System
Intelligent stuck task recovery:
- Analyzes subtask completion status
- Resets interrupted subtasks to pending
- Preserves completed work for resumption
- Auto-restart option available

## Future Enhancements

Potential improvements:
- Extract more shared utilities
- Add comprehensive unit tests
- Create handler factory patterns
- Implement middleware for common operations
- Add detailed error handling utilities

---

### Overview (`apps/desktop/src/preload/api/modules/README.md`)

# Agent API Modules

This directory contains modularized agent API implementations, broken down by domain for better code organization and maintainability.

## Structure

The agent API has been refactored from a monolithic 677-line file into smaller, focused modules:

```
modules/
├── ipc-utils.ts          # Common IPC utilities and helper functions
├── roadmap-api.ts        # Roadmap generation and management
├── ideation-api.ts       # AI-powered ideation and idea management
├── insights-api.ts       # AI insights and chat functionality
├── changelog-api.ts      # Changelog generation and versioning
├── linear-api.ts         # Linear issue tracking integration
├── github-api.ts         # GitHub integration (issues, releases)
├── autobuild-api.ts      # Auto-build source update management
├── shell-api.ts          # Shell operations (e.g., opening URLs)
└── index.ts              # Barrel export for easy imports
```

## Module Organization

Each module follows a consistent pattern:

1. **Type Imports**: Import required types from shared types
2. **Interface Definition**: Define the module's API interface
3. **Implementation**: Create factory function that returns the API implementation
4. **IPC Communication**: Use utility functions from `ipc-utils.ts` for consistent IPC handling

### Example Module Structure

```typescript
// Import utilities and types
import { IPC_CHANNELS } from '../../../shared/constants';
import type { SomeType, IPCResult } from '../../../shared/types';
import { createIpcListener, invokeIpc, sendIpc } from './ipc-utils';

// Define API interface
export interface ModuleAPI {
  operation: (arg: string) => Promise<IPCResult<SomeType>>;
  onEvent: (callback: (data: SomeType) => void) => () => void;
}

// Create implementation
export const createModuleAPI = (): ModuleAPI => ({
  operation: (arg: string) => invokeIpc(IPC_CHANNELS.SOME_CHANNEL, arg),
  onEvent: (callback) => createIpcListener(IPC_CHANNELS.SOME_EVENT, callback)
});
```

## IPC Utilities

The `ipc-utils.ts` module provides common functionality:

- **`createIpcListener`**: Creates typed event listeners with automatic cleanup
- **`invokeIpc`**: Invokes IPC methods with typed return values
- **`sendIpc`**: Sends IPC messages without expecting responses
- **`IpcListenerCleanup`**: Type for cleanup functions

## Main Entry Point

The `agent-api.ts` file in the parent directory aggregates all modules:

```typescript
import { createRoadmapAPI } from './modules/roadmap-api';
import { createIdeationAPI } from './modules/ideation-api';
// ... other imports

export const createAgentAPI = (): AgentAPI => ({
  ...createRoadmapAPI(),
  ...createIdeationAPI(),
  // ... other modules
});
```

## Benefits of This Structure

1. **Separation of Concerns**: Each module handles a specific domain
2. **Easier Maintenance**: Changes to one domain don't affect others
3. **Better Code Navigation**: Developers can quickly find relevant code
4. **Improved Testability**: Modules can be tested independently
5. **Reduced Complexity**: Smaller files are easier to understand
6. **Type Safety**: Strong TypeScript typing throughout
7. **Reusability**: Common IPC patterns extracted to utilities

## Adding New Operations

To add new operations to an existing module:

1. Add the operation to the module's interface
2. Implement the operation using IPC utilities
3. Export is automatically handled by the main `agent-api.ts`

To create a new module:

1. Create a new file in `modules/` (e.g., `new-feature-api.ts`)
2. Follow the standard module pattern
3. Import and integrate in `agent-api.ts`
4. Add export to `modules/index.ts`

## Migration Notes

This refactoring maintains 100% backward compatibility. The `AgentAPI` interface remains unchanged, so no updates to consuming code are required.

### Before (677 lines)
```typescript
// Single large file with all operations
export const createAgentAPI = (): AgentAPI => ({
  // 50+ operations defined inline
});
```

### After (90 lines + 8 focused modules)
```typescript
// Clean aggregation of modular APIs
export const createAgentAPI = (): AgentAPI => ({
  ...createRoadmapAPI(),
  ...createIdeationAPI(),
  // ... etc
});
```

---

### Overview (`apps/desktop/src/renderer/components/context/README.md`)

# Context Component Refactoring

This directory contains the refactored Context component, broken down into logical, maintainable modules.

## Structure

```
context/
├── Context.tsx                 # Main component - entry point (2.3KB, down from 35KB)
├── types.ts                    # TypeScript type definitions
├── constants.ts                # Icon mappings and color schemes
├── hooks.ts                    # Custom React hooks for data fetching
├── utils.ts                    # Utility functions (date formatting, etc.)
├── InfoItem.tsx                # Reusable info display component
├── MemoryCard.tsx              # Memory episode card component
├── ServiceCard.tsx             # Service card component with all service details
├── ProjectIndexTab.tsx         # Project index tab content
├── MemoriesTab.tsx             # Memories tab content
├── service-sections/           # Collapsible service detail sections
│   ├── EnvironmentSection.tsx
│   ├── APIRoutesSection.tsx
│   ├── DatabaseSection.tsx
│   ├── ExternalServicesSection.tsx
│   ├── MonitoringSection.tsx
│   ├── DependenciesSection.tsx
│   └── index.ts
└── index.ts                    # Module exports

../Context.tsx                  # Re-export wrapper for backward compatibility
```

## Architecture

### Main Component (`Context.tsx`)
- Orchestrates the two main tabs (Project Index and Memories)
- Uses custom hooks for data fetching and state management
- Delegates rendering to specialized tab components
- Clean, readable entry point (~70 lines)

### Tab Components
- **ProjectIndexTab**: Displays project structure, services, infrastructure, and conventions
- **MemoriesTab**: Shows memory status, search interface, and recent memories

### Service Sections
Each service detail section (environment, API routes, database, etc.) is a separate component:
- Self-contained with its own expand/collapse state
- Consistent UI patterns
- Easy to test and modify independently

### Shared Components
- **ServiceCard**: Comprehensive service display with all collapsible sections
- **MemoryCard**: Memory episode display with expand/collapse
- **InfoItem**: Simple label/value pair display

### Utilities
- **hooks.ts**: Custom hooks for project context loading, refresh, and search
- **constants.ts**: Icon and color mappings for service types and memory types
- **utils.ts**: Date formatting and other utility functions

## Benefits

1. **Maintainability**: Each component has a single responsibility
2. **Testability**: Small, focused components are easier to test
3. **Reusability**: Components like InfoItem and section components can be reused
4. **Readability**: Clear file organization and naming conventions
5. **Type Safety**: Proper TypeScript types for all props and data
6. **Scalability**: Easy to add new service sections or features

## Backward Compatibility

The original `Context.tsx` file now acts as a re-export wrapper, ensuring all existing imports continue to work:

```typescript
import { Context } from './components/Context'; // Still works!
```

## File Size Reduction

- **Before**: 854 lines in a single file (35KB)
- **After**: Main component is 70 lines (2.3KB), with logic distributed across 14 focused modules
- **Reduction**: ~95% reduction in main file size

## Usage

```typescript
import { Context } from '@/components/context';
// or
import { Context } from '@/components/Context'; // Backward compatible

function App() {
  return <Context projectId="my-project-id" />;
}
```

---

### Overview (`apps/desktop/src/renderer/components/github-issues/README.md`)

# GitHub Issues Module

A well-structured, modular implementation of the GitHub Issues feature for the Auto Claude UI.

## Quick Stats

- **Main Component:** 131 lines (down from 623 lines - 79% reduction)
- **Total Modules:** 14 files organized in 4 directories
- **Custom Hooks:** 3 reusable hooks
- **UI Components:** 7 focused components
- **Type Definitions:** 11 TypeScript interfaces
- **Utility Functions:** 2 helper functions

## Directory Structure

```
github-issues/
├── components/           # UI Components (7 components, 507 lines)
├── hooks/                # Custom Hooks (3 hooks, 143 lines)
├── types/                # TypeScript Types (65 lines)
├── utils/                # Utilities (21 lines)
├── index.ts              # Module exports
├── README.md             # This file
├── REFACTORING_SUMMARY.md
└── ARCHITECTURE.md
```

## Usage

### Basic Import
```typescript
// Import the main component
import { GitHubIssues } from './components/github-issues';

// Use in your app
<GitHubIssues onOpenSettings={handleOpenSettings} />
```

### Advanced Usage
```typescript
// Import specific components for custom layouts
import {
  IssueList,
  IssueDetail,
  InvestigationDialog
} from './components/github-issues';

// Import hooks for custom implementations
import {
  useGitHubIssues,
  useGitHubInvestigation
} from './components/github-issues';

// Import types for type safety
import type {
  GitHubIssuesProps,
  FilterState
} from './components/github-issues';

// Import utilities
import { formatDate, filterIssuesBySearch } from './components/github-issues';
```

## Modules

### Components (`/components`)

| Component | Lines | Purpose |
|-----------|-------|---------|
| **IssueListItem** | 67 | Individual issue card with metadata and investigate button |
| **IssueList** | 53 | Container for issue list with loading/error/empty states |
| **IssueListHeader** | 80 | Header with search, filters, refresh controls |
| **IssueDetail** | 162 | Full issue detail view with description, labels, etc |
| **InvestigationDialog** | 107 | Modal for AI investigation with progress tracking |
| **EmptyStates** | 38 | Reusable empty state and not-connected state components |

### Hooks (`/hooks`)

| Hook | Lines | Purpose |
|------|-------|---------|
| **useGitHubIssues** | 53 | Manages issue loading, filtering, and state |
| **useGitHubInvestigation** | 70 | Handles AI investigation lifecycle and events |
| **useIssueFiltering** | 17 | Provides search functionality with memoization |

### Types (`/types`)

Centralized TypeScript definitions for:
- Component props interfaces
- FilterState type ('open' | 'closed' | 'all')
- Event handler signatures
- Investigation status types

### Utils (`/utils`)

| Function | Purpose |
|----------|---------|
| **formatDate** | Formats ISO date strings to readable format |
| **filterIssuesBySearch** | Filters issues by search query |

## Features

### Issue Management
- View GitHub issues synced from repository
- Filter by state (open/closed/all)
- Search issues by title and body
- Select issues to view details
- Refresh issue list

### AI Investigation
- Investigate issues with AI analysis
- Create tasks from GitHub issues
- Track investigation progress
- View investigation results
- Complexity estimation

### UI/UX
- Split-pane layout (list + detail)
- Loading and error states
- Empty states
- Responsive design
- Smooth transitions

## Architecture

The module follows a clean architecture with clear separation of concerns:

1. **Presentation Layer** (`/components`) - Pure UI components
2. **Business Logic Layer** (`/hooks`) - Reusable hooks with state management
3. **Type Layer** (`/types`) - TypeScript definitions
4. **Utility Layer** (`/utils`) - Pure helper functions

See [ARCHITECTURE.md](./ARCHITECTURE.md) for detailed architecture documentation.

## State Management

The module uses a hybrid state management approach:

- **Zustand Store** (`useGitHubStore`) - Shared state across the app
- **Custom Hooks** - Encapsulated business logic and side effects
- **Local State** - Component-specific UI state

## Dependencies

### Internal Dependencies
- `../stores/github-store` - GitHub state management
- `../stores/project-store` - Project state management
- `../../shared/types` - Shared TypeScript types
- `../../shared/constants` - Shared constants

### External Dependencies
- React (hooks: useState, useEffect, useCallback, useMemo)
- lucide-react (icons)
- UI components (button, input, badge, card, etc.)

## Development

### Adding a New Component

1. Create component file in `/components/ComponentName.tsx`
2. Define props interface in `/types/index.ts`
3. Export component from `/components/index.ts`
4. Import and use in main component

### Adding a New Hook

1. Create hook file in `/hooks/useHookName.ts`
2. Define types in `/types/index.ts` if needed
3. Export hook from `/hooks/index.ts`
4. Use in components

### Adding a New Utility

1. Create utility function in `/utils/index.ts`
2. Keep it pure (no side effects)
3. Add types for parameters and return values
4. Export from `/utils/index.ts`

## Testing Strategy

### Component Testing
```typescript
// Test components in isolation
import { render, screen } from '@testing-library/react';
import { IssueListItem } from './components';

test('renders issue title', () => {
  render(<IssueListItem issue={mockIssue} {...props} />);
  expect(screen.getByText('Issue Title')).toBeInTheDocument();
});
```

### Hook Testing
```typescript
// Test hooks with renderHook
import { renderHook } from '@testing-library/react-hooks';
import { useGitHubIssues } from './hooks';

test('loads issues on mount', () => {
  const { result } = renderHook(() => useGitHubIssues('project-id'));
  expect(result.current.isLoading).toBe(true);
});
```

### Util Testing
```typescript
// Test utilities as pure functions
import { formatDate } from './utils';

test('formats date correctly', () => {
  expect(formatDate('2024-01-01')).toBe('Jan 1, 2024');
});
```

## Performance Considerations

### Optimizations Implemented
- **Memoization** - useIssueFiltering uses useMemo for filtered results
- **Callback Memoization** - useCallback for event handlers
- **Virtual Scrolling** - ScrollArea component for long lists
- **Lazy Loading** - Components only render when needed

### Future Optimizations
- Implement React.memo for expensive components
- Add pagination for large issue lists
- Use React Query for better caching
- Add intersection observer for lazy image loading

## Troubleshooting

### Common Issues

**Issue: Components not rendering**
- Check that all required props are passed
- Verify that the GitHub store is properly initialized
- Check browser console for TypeScript errors

**Issue: Issues not loading**
- Verify GitHub token is configured
- Check project settings for repository URL
- Inspect network tab for API errors

**Issue: Investigation not working**
- Ensure project is selected
- Check that the investigation service is running
- Verify event listeners are properly set up

## Migration from Original Component

The refactored module maintains 100% backward compatibility:

```typescript
// Old import (still works)
import { GitHubIssues } from './components/GitHubIssues';

// New import (recommended)
import { GitHubIssues } from './components/github-issues';

// Both work exactly the same way
<GitHubIssues onOpenSettings={handler} />
```

## Documentation

- **README.md** (this file) - Module overview and usage
- **REFACTORING_SUMMARY.md** - Detailed refactoring metrics and benefits
- **ARCHITECTURE.md** - In-depth architecture documentation

## Contributing

When contributing to this module:

1. Follow the established file structure
2. Keep components small and focused (< 200 lines)
3. Use TypeScript strictly (no `any` types)
4. Add proper prop interfaces
5. Document complex logic with comments
6. Write tests for new features
7. Update documentation as needed

## License

Part of the Auto Claude project.

---

### Overview (`apps/desktop/src/renderer/components/linear-import/README.md`)

# Linear Task Import Module

This directory contains the refactored Linear task import functionality, structured for better code quality, maintainability, and reusability.

## Directory Structure

```
linear-import/
├── README.md                          # This file
├── index.ts                           # Central export point
├── types.ts                           # Type definitions and constants
├── LinearTaskImportModalRefactored.tsx # Main modal component
├── hooks/                             # Custom React hooks
│   ├── index.ts                      # Hook exports
│   ├── useLinearTeams.ts            # Load Linear teams
│   ├── useLinearProjects.ts         # Load Linear projects
│   ├── useLinearIssues.ts           # Load Linear issues
│   ├── useIssueFiltering.ts         # Filter and search issues
│   ├── useIssueSelection.ts         # Manage issue selection state
│   ├── useLinearImport.ts           # Handle import operation
│   └── useLinearImportModal.ts      # Main orchestration hook
└── components/                       # UI Components
    ├── index.ts                     # Component exports
    ├── ImportSuccessBanner.tsx      # Success message banner
    ├── ErrorBanner.tsx              # Error message banner
    ├── TeamProjectSelector.tsx      # Team/project dropdowns
    ├── SearchAndFilterBar.tsx       # Search and filter controls
    ├── SelectionControls.tsx        # Select all/deselect controls
    ├── IssueCard.tsx               # Individual issue display
    └── IssueList.tsx               # Issue list with states

```

## Architecture

### Separation of Concerns

The module is organized into three main layers:

1. **Hooks Layer** (`hooks/`)
   - Data fetching hooks for teams, projects, and issues
   - Business logic for filtering, selection, and import
   - Main orchestration hook that coordinates all functionality

2. **Components Layer** (`components/`)
   - Presentational components for UI elements
   - Each component has a single responsibility
   - Props-driven, easy to test and reuse

3. **Types Layer** (`types.ts`)
   - TypeScript interfaces and type definitions
   - Shared constants (colors, priority levels, etc.)
   - Props interfaces for components and hooks

### Main Orchestration Hook

`useLinearImportModal` is the central hook that:
- Combines all individual hooks
- Manages state coordination
- Provides a single interface for the main component
- Handles side effects and state updates

### Benefits of This Structure

1. **Maintainability**: Each file has a single, clear purpose
2. **Testability**: Hooks and components can be tested in isolation
3. **Reusability**: Components and hooks can be used independently
4. **Readability**: Clear file names and structure make navigation easy
5. **Type Safety**: Centralized types prevent duplication and errors

## Usage

### Main Component

```tsx
import { LinearTaskImportModal } from './linear-import';

<LinearTaskImportModal
  projectId="project-123"
  open={isOpen}
  onOpenChange={setIsOpen}
  onImportComplete={(result) => console.log('Imported:', result)}
/>
```

### Individual Hooks

You can also use individual hooks for custom implementations:

```tsx
import { useLinearTeams, useLinearIssues } from './linear-import/hooks';

function MyCustomComponent() {
  const { teams, isLoadingTeams } = useLinearTeams(projectId, true);
  const { issues, isLoadingIssues } = useLinearIssues(projectId, teamId, '');

  // Your custom logic here
}
```

### Individual Components

Components can be reused in different contexts:

```tsx
import { IssueCard, SearchAndFilterBar } from './linear-import/components';

function MyCustomView() {
  return (
    <>
      <SearchAndFilterBar
        searchQuery={query}
        filterState={filter}
        uniqueStateTypes={states}
        onSearchChange={setQuery}
        onFilterChange={setFilter}
      />
      {issues.map(issue => (
        <IssueCard
          key={issue.id}
          issue={issue}
          isSelected={selected.has(issue.id)}
          onToggle={toggleSelection}
        />
      ))}
    </>
  );
}
```

## File Size Reduction

The original `LinearTaskImportModal.tsx` was **611 lines**. After refactoring:
- Main modal component: ~150 lines (75% reduction)
- Functionality split across 15 focused files
- Each file is under 150 lines, easy to understand and maintain

## Type Safety

All components and hooks are fully typed with TypeScript:
- Props interfaces for all components
- Return type definitions for all hooks
- Shared types exported from `types.ts`
- No `any` types used

## Future Improvements

Possible enhancements to this structure:
1. Add unit tests for each hook and component
2. Extract additional utility functions as needed
3. Consider adding error boundary components
4. Add more granular loading states
5. Implement optimistic updates for better UX

---

### Overview (`apps/desktop/src/renderer/components/project-settings/README.md`)

# ProjectSettings Refactoring

This directory contains the refactored components from the original 1,445-line `ProjectSettings.tsx` file. The refactoring improves code maintainability, reusability, and testability by breaking down the monolithic component into smaller, focused modules.

## Architecture Overview

### Original Structure
- **Single file**: 1,445 lines
- **Multiple concerns**: State management, UI rendering, API calls, and business logic all mixed
- **Hard to maintain**: Complex component with many responsibilities
- **Difficult to test**: Tightly coupled logic

### New Structure
- **Modular approach**: Split into 17+ files
- **Separation of concerns**: Custom hooks, section components, and utility components
- **Easier to maintain**: Each file has a single, clear responsibility
- **Testable**: Individual components and hooks can be tested in isolation

## Directory Structure

```
project-settings/
├── README.md                         # This file
├── index.ts                          # Barrel export for all components
├── AutoBuildIntegration.tsx          # Auto-Build setup and status
├── LinearIntegrationSection.tsx      # Linear project management integration
├── GitHubIntegrationSection.tsx      # GitHub issues integration
├── MemoryBackendSection.tsx          # Graphiti/file-based memory configuration
├── AgentConfigSection.tsx            # Agent model selection
├── NotificationsSection.tsx          # Notification preferences
├── CollapsibleSection.tsx            # Reusable collapsible section wrapper
├── PasswordInput.tsx                 # Reusable password input with toggle
├── StatusBadge.tsx                   # Reusable status badge component
├── ConnectionStatus.tsx              # Reusable connection status display
└── InfrastructureStatus.tsx          # LadybugDB memory status display

hooks/
├── index.ts                          # Barrel export for all hooks
├── useProjectSettings.ts             # Project settings state management
├── useEnvironmentConfig.ts           # Environment configuration state
├── useClaudeAuth.ts                  # Claude authentication status
├── useLinearConnection.ts            # Linear connection status
├── useGitHubConnection.ts            # GitHub connection status
└── useInfrastructureStatus.ts        # LadybugDB memory status
```

## Component Breakdown

### Section Components (Feature-Specific)

#### AutoBuildIntegration.tsx
**Purpose**: Manages Auto-Build framework initialization and status.
**Props**:
- `autoBuildPath`: Current Auto-Build path
- `versionInfo`: Version and initialization status
- `isCheckingVersion`: Loading state
- `isUpdating`: Update in progress state
- `onInitialize`: Initialize Auto-Build handler
- `onUpdate`: Update Auto-Build handler

**Responsibilities**:
- Display initialization status
- Show Auto-Build version information
- Handle initialization and updates

#### LinearIntegrationSection.tsx
**Purpose**: Configures Linear project management integration.
**Props**:
- `isExpanded`: Section expand/collapse state
- `onToggle`: Toggle handler
- `envConfig`: Environment configuration
- `onUpdateConfig`: Configuration update handler
- `linearConnectionStatus`: Connection status
- `isCheckingLinear`: Connection check in progress
- `onOpenImportModal`: Import modal handler

**Responsibilities**:
- Enable/disable Linear integration
- Configure Linear API credentials
- Display connection status
- Manage real-time sync settings
- Handle task import from Linear

#### GitHubIntegrationSection.tsx
**Purpose**: Configures GitHub issues integration.
**Props**:
- `isExpanded`: Section expand/collapse state
- `onToggle`: Toggle handler
- `envConfig`: Environment configuration
- `onUpdateConfig`: Configuration update handler
- `gitHubConnectionStatus`: Connection status
- `isCheckingGitHub`: Connection check in progress

**Responsibilities**:
- Enable/disable GitHub integration
- Configure GitHub PAT and repository
- Display connection status
- Manage auto-sync settings

#### MemoryBackendSection.tsx
**Purpose**: Configures memory backend (Graphiti vs file-based).
**Props**:
- `isExpanded`: Section expand/collapse state
- `onToggle`: Toggle handler
- `envConfig`: Environment configuration
- `settings`: Project settings
- `onUpdateConfig`: Configuration update handler
- `onUpdateSettings`: Settings update handler
- `infrastructureStatus`: LadybugDB memory status
- Infrastructure management handlers

**Responsibilities**:
- Toggle between Graphiti and file-based memory
- Configure LLM and embedding providers
- Manage LadybugDB connection settings
- Display infrastructure status (LadybugDB)
- Handle infrastructure startup

#### AgentConfigSection.tsx
**Purpose**: Configures agent model selection.
**Props**:
- `settings`: Project settings
- `onUpdateSettings`: Settings update handler

**Responsibilities**:
- Display available models
- Handle model selection

#### NotificationsSection.tsx
**Purpose**: Configures notification preferences.
**Props**:
- `settings`: Project settings
- `onUpdateSettings`: Settings update handler

**Responsibilities**:
- Toggle task completion notifications
- Toggle task failure notifications
- Toggle review needed notifications
- Toggle sound notifications

### Utility Components (Reusable UI)

#### CollapsibleSection.tsx
**Purpose**: Reusable wrapper for collapsible sections.
**Props**:
- `title`: Section title
- `icon`: Section icon
- `isExpanded`: Expanded state
- `onToggle`: Toggle handler
- `badge`: Optional status badge
- `children`: Section content

**Usage**: Used by all integration sections for consistent expand/collapse behavior.

#### PasswordInput.tsx
**Purpose**: Reusable password input with show/hide toggle.
**Props**:
- `value`: Input value
- `onChange`: Change handler
- `placeholder`: Placeholder text
- `className`: Optional CSS class

**Usage**: Used for all sensitive credentials (OAuth tokens, API keys, passwords).

#### StatusBadge.tsx
**Purpose**: Reusable status badge component.
**Props**:
- `status`: 'success' | 'warning' | 'info'
- `label`: Badge text

**Usage**: Used to display connection status, enabled/disabled state, etc.

#### ConnectionStatus.tsx
**Purpose**: Reusable connection status display.
**Props**:
- `isChecking`: Loading state
- `isConnected`: Connection state
- `title`: Status title
- `successMessage`: Message when connected
- `errorMessage`: Message when not connected
- `additionalInfo`: Optional extra information

**Usage**: Used by Linear and GitHub sections to display connection status.

#### InfrastructureStatus.tsx
**Purpose**: Displays LadybugDB memory status for Graphiti.
**Props**:
- `infrastructureStatus`: Status object
- `isCheckingInfrastructure`: Loading state
- Infrastructure action handlers

**Usage**: Used by MemoryBackendSection to manage Graphiti infrastructure.

## Custom Hooks

### useProjectSettings.ts
**Purpose**: Manages project settings state and version checking.
**Returns**:
- `settings`: Current project settings
- `setSettings`: Settings updater
- `versionInfo`: Auto-Build version info
- `setVersionInfo`: Version info updater
- `isCheckingVersion`: Loading state

### useEnvironmentConfig.ts
**Purpose**: Manages environment configuration state and persistence.
**Returns**:
- `envConfig`: Current environment config
- `setEnvConfig`: Config updater
- `updateEnvConfig`: Partial update function (auto-saves to backend)
- `isLoadingEnv`: Loading state
- `envError`: Error state

### useLinearConnection.ts
**Purpose**: Monitors Linear connection status.
**Returns**:
- `linearConnectionStatus`: Connection status object
- `isCheckingLinear`: Loading state

### useGitHubConnection.ts
**Purpose**: Monitors GitHub connection status.
**Returns**:
- `gitHubConnectionStatus`: Connection status object
- `isCheckingGitHub`: Loading state

### useInfrastructureStatus.ts
**Purpose**: Monitors LadybugDB memory infrastructure status.
**Returns**:
- `infrastructureStatus`: Status object
- `isCheckingInfrastructure`: Loading state
- Infrastructure management functions

## Main Component (ProjectSettings.tsx)

The refactored main component is now only **~320 lines** (down from 1,445), focusing on:
- Orchestrating child components
- Managing dialog state
- Coordinating save operations
- Handling component composition

## Benefits of This Refactoring

1. **Maintainability**: Each file has a clear, single responsibility
2. **Reusability**: Utility components can be used in other parts of the app
3. **Testability**: Individual components and hooks can be tested in isolation
4. **Readability**: Smaller files are easier to understand
5. **Type Safety**: Explicit prop interfaces improve TypeScript coverage
6. **Performance**: Can optimize individual components without affecting others
7. **Collaboration**: Multiple developers can work on different sections simultaneously

## Migration Guide

The refactored component maintains the same external API:

```tsx
// Usage remains the same
<ProjectSettings
  project={project}
  open={isOpen}
  onOpenChange={setIsOpen}
/>
```

All functionality is preserved - this is a pure refactor with no breaking changes.

## Future Improvements

Potential enhancements for the future:
1. Add unit tests for each component and hook
2. Add Storybook stories for visual testing
3. Extract common patterns into additional shared components
4. Add error boundary components
5. Implement optimistic updates for better UX
6. Add analytics tracking for user interactions

---

### Overview (`apps/desktop/src/renderer/components/roadmap/README.md`)

# Roadmap Component Architecture

This directory contains the refactored Roadmap component, broken down into smaller, maintainable modules.

## Overview

The original `Roadmap.tsx` (764 lines) has been refactored into:
- **Main component**: `Roadmap.tsx` (123 lines) - 84% reduction
- **Modular sub-components**: 10 separate files organized by concern
- **Clear separation**: UI components, logic hooks, utilities, and types

## File Structure

```
roadmap/
├── README.md                    # This file
├── index.ts                     # Public exports (9 lines)
├── types.ts                     # TypeScript type definitions (50 lines)
├── utils.ts                     # Helper utility functions (30 lines)
├── hooks.ts                     # Custom React hooks (98 lines)
├── RoadmapEmptyState.tsx        # Empty state UI (23 lines)
├── RoadmapHeader.tsx            # Header with stats (87 lines)
├── FeatureCard.tsx              # Feature card component (86 lines)
├── PhaseCard.tsx                # Phase card with features (147 lines)
├── FeatureDetailPanel.tsx       # Side panel details (204 lines)
└── RoadmapTabs.tsx              # Tab navigation and views (130 lines)
```

## Component Breakdown

### Main Entry Point
- **`Roadmap.tsx`**: Orchestrates the entire roadmap view, manages state, and composes sub-components

### UI Components

#### `RoadmapHeader.tsx`
- Displays project name, vision, and status
- Shows target audience information
- Renders feature statistics and priority breakdown
- Action buttons (Add Feature, Refresh)

#### `RoadmapEmptyState.tsx`
- Initial state when no roadmap exists
- Single "Generate Roadmap" CTA

#### `RoadmapTabs.tsx`
- Tab navigation (Phases, All Features, By Priority, Kanban)
- Renders appropriate view based on active tab
- Delegates to PhaseCard, FeatureCard, and RoadmapKanbanView

#### `PhaseCard.tsx`
- Individual phase card with status indicator
- Progress bar showing completion
- Milestone list with status
- Feature preview (up to 5) with actions

#### `FeatureCard.tsx`
- Compact feature card display
- Priority, complexity, and impact badges
- Competitor insight indicator
- Build/View Task actions

#### `FeatureDetailPanel.tsx`
- Slide-in side panel for feature details
- Full description, rationale, and metrics
- User stories and acceptance criteria
- Dependencies and competitor insights
- Convert to task or view existing task actions

### Logic and State

#### `hooks.ts`
Three custom hooks for managing roadmap logic:

1. **`useRoadmapData(projectId)`**
   - Loads and provides roadmap data
   - Returns: `{ roadmap, competitorAnalysis, generationStatus }`

2. **`useFeatureActions()`**
   - Handles feature-related actions
   - Returns: `{ convertFeatureToSpec }`

3. **`useRoadmapGeneration(projectId)`**
   - Manages roadmap generation flow
   - Handles competitor analysis dialog
   - Returns generation handlers and dialog state

### Utilities

#### `utils.ts`
- **`getCompetitorInsightsForFeature()`**: Extracts competitor pain points for a feature
- **`hasCompetitorInsight()`**: Checks if a feature has competitor insights

#### `types.ts`
TypeScript interfaces for all component props:
- `RoadmapProps`
- `RoadmapHeaderProps`
- `RoadmapTabsProps`
- `PhaseCardProps`
- `FeatureCardProps`
- `FeatureDetailPanelProps`
- `RoadmapEmptyStateProps`

## Design Principles

### Separation of Concerns
- **UI Components**: Pure presentation logic
- **Custom Hooks**: State management and side effects
- **Utilities**: Reusable helper functions
- **Types**: Centralized type definitions

### Component Composition
The main `Roadmap.tsx` now serves as a thin orchestration layer:
```tsx
<Roadmap>
  <RoadmapHeader />
  <RoadmapTabs>
    <PhaseCard />
    <FeatureCard />
  </RoadmapTabs>
  <FeatureDetailPanel />
</Roadmap>
```

### Reusability
- Components can be used independently
- Hooks can be reused in other components
- Utilities are framework-agnostic
- Types ensure consistency

### Maintainability
- Single Responsibility Principle: Each file has one clear purpose
- Smaller files (23-204 lines) are easier to understand and modify
- Clear naming conventions
- Well-defined interfaces

## Usage

Import from the module:

```tsx
// Import the main component
import { Roadmap } from './components/Roadmap';

// Or import specific parts
import {
  RoadmapHeader,
  FeatureCard,
  useRoadmapData
} from './components/roadmap';
```

## Benefits of This Refactoring

1. **Improved Readability**: Each file focuses on a single concern
2. **Better Testability**: Smaller components and pure functions are easier to test
3. **Enhanced Reusability**: Components can be used in different contexts
4. **Easier Maintenance**: Changes to one aspect don't affect others
5. **Better Type Safety**: Centralized types with proper TypeScript support
6. **Reduced Cognitive Load**: Developers can focus on one piece at a time
7. **Scalability**: Easy to add new features or modify existing ones

## Migration Notes

- All functionality remains identical to the original implementation
- No breaking changes to the public API
- Import paths updated to use the new structure
- TypeScript compilation verified with no new errors

---

### Overview (`apps/desktop/src/renderer/components/settings/README.md`)

# Project Settings Components

Refactored and modular project settings system with clear separation of concerns.

## Directory Structure

```
settings/
├── ProjectSettingsContent.tsx       # Main entry point (170 lines)
├── common/                          # Common UI components
│   ├── EmptyProjectState.tsx        # Empty state when no project selected
│   ├── ErrorDisplay.tsx             # Error message display
│   ├── InitializationGuard.tsx      # Guards for Auto-Build requirement
│   └── index.ts                     # Exports
├── integrations/                    # Third-party integrations
│   ├── LinearIntegration.tsx        # Linear setup (241 lines)
│   ├── GitHubIntegration.tsx        # GitHub setup (215 lines)
│   └── index.ts                     # Exports
├── sections/                        # Section routing
│   ├── SectionRouter.tsx            # Routes between settings sections
│   └── index.ts                     # Exports
└── utils/                           # Utility functions
    ├── hookProxyFactory.ts          # Hook proxy generator
    └── index.ts                     # Exports
```

## Component Overview

### Main Component

**ProjectSettingsContent.tsx** (170 lines)
- Main entry point for project settings
- Handles project selection and empty states
- Orchestrates hook state and section rendering
- Manages Linear task import modal

### Common Components

**EmptyProjectState** (15 lines)
- Displays empty state with icon when no project selected
- Reusable across the application

**ErrorDisplay** (22 lines)
- Shows error messages in consistent format
- Handles both general and environment errors
- Returns null when no errors present

**InitializationGuard** (29 lines)
- Guards features requiring Auto-Build initialization
- Shows informative message when not initialized
- Renders children when guard passes

### Integration Components

**LinearIntegration** (241 lines)
- Complete Linear integration UI
- Features:
  - Enable/disable toggle
  - API key input with visibility control
  - Connection status display
  - Task import functionality
  - Real-time sync configuration
  - Team/Project ID settings
- Sub-components:
  - `ConnectionStatus` - Connection state indicator
  - `ImportTasksPrompt` - Import action card
  - `RealtimeSyncToggle` - Sync toggle with description
  - `RealtimeSyncWarning` - Warning about auto-import
  - `TeamProjectIds` - ID configuration grid

**GitHubIntegration** (215 lines)
- Complete GitHub integration UI
- Features:
  - Enable/disable toggle
  - Personal access token input
  - Repository configuration
  - Connection status display
  - Auto-sync on load toggle
- Sub-components:
  - `TokenInput` - Token input with visibility toggle
  - `RepositoryInput` - Repo name configuration
  - `ConnectionStatus` - Connection state indicator
  - `IssuesAvailableInfo` - Info card about issues
  - `AutoSyncToggle` - Auto-sync control

### Section Routing

**SectionRouter** (207 lines)
- Routes to appropriate settings section
- Sections: `general`, `claude`, `linear`, `github`, `memory`
- Wraps sections with `InitializationGuard` where needed
- Maintains consistent section structure
- Passes appropriate props to each section

### Utilities

**hookProxyFactory** (57 lines)
- Creates stable hook proxy to prevent infinite loops
- Uses getters to access latest ref values
- Reduces 47 lines of boilerplate in main component
- Type-safe with full TypeScript support

## Usage Examples

### Using Common Components

```tsx
import { EmptyProjectState, ErrorDisplay, InitializationGuard } from './common';

// Empty state
<EmptyProjectState />

// Error display
<ErrorDisplay error={error} envError={envError} />

// Guard with initialization check
<InitializationGuard
  initialized={!!project.autoBuildPath}
  title="Feature Name"
  description="Feature description"
>
  <YourComponent />
</InitializationGuard>
```

### Using Integration Components

```tsx
import { LinearIntegration, GitHubIntegration } from './integrations';

// Linear integration
<LinearIntegration
  envConfig={envConfig}
  updateEnvConfig={updateEnvConfig}
  showLinearKey={showLinearKey}
  setShowLinearKey={setShowLinearKey}
  linearConnectionStatus={status}
  isCheckingLinear={isChecking}
  onOpenLinearImport={handleOpen}
/>

// GitHub integration
<GitHubIntegration
  envConfig={envConfig}
  updateEnvConfig={updateEnvConfig}
  showGitHubToken={showToken}
  setShowGitHubToken={setShowToken}
  gitHubConnectionStatus={status}
  isCheckingGitHub={isChecking}
/>
```

### Using Section Router

```tsx
import { SectionRouter } from './sections';

<SectionRouter
  activeSection={activeSection}
  project={project}
  settings={settings}
  setSettings={setSettings}
  // ... other props
/>
```

### Using Utilities

```tsx
import { createHookProxy } from './utils';

const hookRef = useRef(hook);
hookRef.current = hook;

const hookProxy = createHookProxy(hookRef);
```

## Refactoring Results

### Metrics

| Metric | Before | After | Improvement |
|--------|--------|-------|-------------|
| Main file lines | 682 | 170 | 75% reduction |
| Number of files | 1 | 13 | Better organization |
| Largest component | 682 | 241 | More manageable |
| Code duplication | High | Low | DRY principle |

### Benefits

1. **Maintainability**: Each component has a single, clear responsibility
2. **Reusability**: Components can be used elsewhere in the application
3. **Testability**: Smaller components are easier to test in isolation
4. **Scalability**: Easy to add new sections or integrations
5. **Type Safety**: Explicit TypeScript interfaces throughout
6. **Readability**: Clear component names and structure

## Testing

### Recommended Test Coverage

1. **Unit Tests**
   - Each common component (EmptyProjectState, ErrorDisplay, InitializationGuard)
   - Each integration component (LinearIntegration, GitHubIntegration)
   - Hook proxy factory utility

2. **Integration Tests**
   - SectionRouter routing logic
   - Main ProjectSettingsContent orchestration

3. **Snapshot Tests**
   - All UI components for visual regression

4. **Hook Tests**
   - createHookProxy utility function

## Contributing

When adding new features:

1. **New Integration**: Add to `integrations/` following the pattern
2. **New Section**: Update `SectionRouter` with new case
3. **New Common Component**: Add to `common/` and export from index
4. **New Utility**: Add to `utils/` and export from index

## Migration from Old Code

The refactored code maintains 100% functional equivalence with the original implementation. No changes required in parent components.

### Import Changes

Old:
```tsx
// Everything was in one file
import { ProjectSettingsContent } from './ProjectSettingsContent';
```

New (if importing sub-components directly):
```tsx
// Can now import individual pieces
import { ProjectSettingsContent } from './ProjectSettingsContent';
import { LinearIntegration } from './integrations';
import { ErrorDisplay } from './common';
```

## Related Documentation

- See `REFACTORING_SUMMARY.md` for detailed refactoring analysis
- See individual component files for inline documentation
- See TypeScript interfaces for prop specifications

---

### Overview (`apps/desktop/src/renderer/components/task-detail/README.md`)

# TaskDetailPanel Refactoring

This directory contains the refactored TaskDetailPanel component, which was previously a single 1,767-line file.

## Structure

```
task-detail/
├── hooks/
│   └── useTaskDetail.ts         # Custom hook for state management and side effects
├── TaskDetailPanel.tsx           # Main container component (slim, orchestrates children)
├── TaskHeader.tsx                # Task title, status badges, and header actions
├── TaskProgress.tsx              # Execution phase indicator and progress bars
├── TaskMetadata.tsx              # Classification badges, description, and metadata
├── TaskActions.tsx               # Primary action buttons and delete dialog
├── TaskWarnings.tsx              # Stuck/incomplete task warning banners
├── TaskSubtasks.tsx              # Subtasks list view
├── TaskLogs.tsx                  # Phase-based log viewer with expandable entries
├── TaskReview.tsx                # Human review workflow (merge/discard/feedback)
├── index.ts                      # Re-exports for clean imports
└── README.md                     # This file
```

## Components

### `TaskDetailPanel` (Main Container)
- Orchestrates all child components
- Handles event handlers that interact with stores
- Uses `useTaskDetail` hook for state management
- Provides tab navigation (Overview, Subtasks, Logs)

### `TaskHeader`
- Task title with overflow tooltip
- Spec ID badge
- Status badges (Running, Stuck, Incomplete, etc.)
- Edit and close buttons

### `TaskProgress`
- Execution phase indicator (Planning, Coding, Validation)
- Progress bar with animation
- Phase progress segments visualization
- Subtask completion counter

### `TaskMetadata`
- Classification badges (Category, Priority, Complexity, Impact, etc.)
- Description with markdown sanitization
- Detailed metadata (Rationale, Problem Solved, Target Audience, etc.)
- Acceptance criteria and affected files
- Timeline (Created/Updated timestamps)

### `TaskActions`
- Primary action button (Start/Stop/Resume/Recover)
- Task completion indicator
- Delete button with confirmation dialog

### `TaskWarnings`
- Stuck task warning with recovery button
- Incomplete task warning with resume button

### `TaskSubtasks`
- List of implementation subtasks
- Status indicators for each subtask
- File associations
- Progress summary

### `TaskLogs`
- Phase-based collapsible log viewer
- Tool usage tracking (Read, Write, Edit, Bash, etc.)
- Expandable log entry details
- Auto-scroll with user control
- Interrupted phase detection

### `TaskReview`
- Workspace status (files changed, commits, additions/deletions)
- View changes dialog
- Stage-only option for IDE review
- Merge/Discard actions
- QA feedback textarea for requesting changes
- Confirmation dialogs for destructive actions

### `useTaskDetail` Hook
- Consolidates all component state
- Manages side effects (loading, watching, checking)
- Provides event handlers for scroll and phase toggling
- Abstracts complex state logic from UI components

## Benefits of Refactoring

1. **Maintainability**: Each component has a single responsibility and is easier to understand
2. **Testability**: Smaller components are easier to test in isolation
3. **Reusability**: Components can be reused or customized independently
4. **Performance**: Easier to optimize individual components with React.memo if needed
5. **Developer Experience**: Easier to navigate and modify specific features
6. **Code Organization**: Related functionality is grouped together

## Usage

The original `TaskDetailPanel.tsx` file at the parent level now re-exports the refactored component for backwards compatibility:

```typescript
// From parent components directory
import { TaskDetailPanel } from './TaskDetailPanel';

// Or from the new directory
import { TaskDetailPanel } from './task-detail';
```

All existing imports continue to work without changes.

## Migration Notes

- No breaking changes to the public API
- All props remain the same
- All functionality preserved
- Original file kept as re-export for backwards compatibility

---

### Overview (`apps/desktop/src/renderer/components/terminal/README.md`)

# Terminal Component Architecture

This directory contains the refactored Terminal component, broken down into smaller, maintainable modules with clear separation of concerns.

## Directory Structure

```
terminal/
├── README.md                    # This file
├── index.ts                     # Public exports
├── types.ts                     # TypeScript types and constants
├── TerminalHeader.tsx           # Terminal header with controls
├── TerminalTitle.tsx            # Editable title component
├── TaskSelector.tsx             # Task selection dropdown
├── useXterm.ts                  # Xterm.js initialization hook
├── usePtyProcess.ts             # PTY process management hook
├── useTerminalEvents.ts         # Terminal event listeners hook
└── useAutoNaming.ts             # Auto-naming functionality hook
```

## Component Hierarchy

```
Terminal (main component - 196 lines, down from 767)
├── TerminalHeader
│   ├── TerminalTitle (editable title with tooltip)
│   └── TaskSelector (task selection/status dropdown)
├── useXterm (xterm.js UI management)
├── usePtyProcess (PTY lifecycle management)
├── useTerminalEvents (event listeners)
└── useAutoNaming (command-based naming)
```

## Files Overview

### Main Component

**Terminal.tsx** (196 lines)
- Main entry point that composes all sub-components and hooks
- Handles drag-and-drop for file insertion
- Manages terminal activation and focus
- Coordinates task selection and context passing
- Reduced from 767 lines to 196 lines (74% reduction)

### UI Components

**TerminalHeader.tsx** (94 lines)
- Renders terminal header with status indicator
- Contains Claude invocation button
- Integrates title editing and task selection
- Handles terminal close action

**TerminalTitle.tsx** (111 lines)
- Inline editable title with double-click to edit
- Shows task description in tooltip when task is associated
- Handles keyboard shortcuts (Enter to save, Escape to cancel)
- Auto-sizes input field based on content

**TaskSelector.tsx** (168 lines)
- Dropdown for selecting tasks from backlog
- Shows current task status with phase indicator
- Animated loading states for active phases
- Supports task switching and clearing
- Integrates with task creation flow

### Type Definitions

**types.ts** (32 lines)
- `TerminalProps` interface
- `STATUS_COLORS` mapping for terminal status indicators
- `PHASE_CONFIG` for execution phase display configuration
- Centralized type definitions for the entire module

### Custom Hooks

**useXterm.ts** (166 lines)
- Initializes xterm.js terminal UI with theme configuration
- Manages FitAddon for responsive terminal sizing
- Handles input buffering and command tracking
- Provides write, writeln, focus, and dispose methods
- Manages output buffer replay for session persistence

**usePtyProcess.ts** (78 lines)
- Creates and manages PTY (pseudoterminal) processes
- Handles both new terminal creation and session restoration
- Manages process lifecycle (creation, running, exit)
- Provides error handling for PTY operations
- Prevents double-creation with ref guards

**useTerminalEvents.ts** (54 lines)
- Sets up IPC event listeners for terminal events
- Handles terminal output streaming
- Manages exit notifications
- Tracks title changes from shell
- Captures Claude session IDs

**useAutoNaming.ts** (62 lines)
- Generates intelligent terminal names based on commands
- Filters out common/short commands
- Debounces naming requests (1.5s delay)
- Only runs when auto-naming is enabled
- Respects Claude mode (no auto-naming during Claude sessions)

## Key Improvements

### Code Organization
- **Single Responsibility**: Each file has one clear purpose
- **Separation of Concerns**: UI, logic, and state management are separated
- **Reusability**: Hooks and components can be reused or tested independently
- **Type Safety**: Centralized types prevent inconsistencies

### Maintainability
- **Smaller Files**: Easier to understand and modify (largest file is 196 lines)
- **Clear Dependencies**: Import structure shows relationships clearly
- **Better Testing**: Isolated units are easier to test
- **Documentation**: Each file has a clear purpose

### Developer Experience
- **Easy Navigation**: Related code is grouped logically
- **Reduced Cognitive Load**: Can focus on one concern at a time
- **Clear Interfaces**: Hook APIs are well-defined with TypeScript
- **Composability**: Components can be mixed and matched

## Usage

### Importing the Main Component

```typescript
import { Terminal } from './components/Terminal';
// or
import { Terminal } from './components/terminal';
```

### Importing Sub-components or Hooks

```typescript
import { TerminalHeader, useXterm, useAutoNaming } from './components/terminal';
```

### Using Individual Hooks

```typescript
function CustomTerminal() {
  const { terminalRef, write, focus } = useXterm({
    terminalId: 'my-terminal',
    onCommandEnter: (cmd) => console.log('Command:', cmd),
    onResize: (cols, rows) => console.log('Resized:', cols, rows),
  });

  useTerminalEvents({
    terminalId: 'my-terminal',
    onOutput: (data) => write(data),
    onExit: (code) => console.log('Exited:', code),
  });

  return <div ref={terminalRef} />;
}
```

## Design Patterns

### Custom Hooks Pattern
All terminal functionality is encapsulated in custom hooks that:
- Accept configuration via options object
- Return methods and state via object destructuring
- Use refs to avoid unnecessary re-renders
- Provide cleanup functions where needed

### Component Composition
The main Terminal component uses composition over inheritance:
- Renders TerminalHeader which composes TerminalTitle and TaskSelector
- Uses hooks for all complex logic
- Keeps the component focused on coordination

### Event-Driven Architecture
Terminal events flow through a clear pipeline:
1. Main process emits event via IPC
2. useTerminalEvents hook catches event
3. Hook updates store and calls callback
4. Component reacts to state changes

## Future Enhancements

Potential improvements that are now easier to implement:

1. **Testing**: Each hook and component can be unit tested independently
2. **Theming**: Terminal theme configuration could be extracted to a separate hook
3. **Plugins**: New features can be added as additional hooks
4. **Performance**: Individual hooks can be optimized without affecting others
5. **Alternative UIs**: Components can be swapped for different terminal UIs

## Migration Guide

The refactored component maintains 100% API compatibility with the original:

```typescript
// Before and after - same props, same behavior
<Terminal
  id={terminalId}
  cwd={workingDir}
  projectPath={projectPath}
  isActive={activeId === terminalId}
  onClose={() => handleClose(terminalId)}
  onActivate={() => setActive(terminalId)}
  tasks={tasks}
  onNewTaskClick={openTaskDialog}
/>
```

No changes needed to existing code using the Terminal component!

---

### Overview (`apps/desktop/src/renderer/lib/mocks/README.md`)

# Browser Mock Modules

This directory contains modular mock implementations for the Electron API, enabling the app to run in a regular browser for UI development and testing.

## Architecture

The mock system is organized into separate modules by functional domain, making it easier to maintain and extend.

### Module Structure

```
mocks/
├── index.ts                    # Central export point
├── mock-data.ts               # Sample data (projects, tasks, sessions)
├── project-mock.ts            # Project CRUD and initialization
├── task-mock.ts               # Task operations and lifecycle
├── workspace-mock.ts          # Git worktree management
├── terminal-mock.ts           # Terminal and session management
├── claude-profile-mock.ts     # Claude profile and rate limiting
├── roadmap-mock.ts            # Roadmap generation and features
├── context-mock.ts            # Project context and memory
├── integration-mock.ts        # External integrations (Linear, GitHub)
├── changelog-mock.ts          # Changelog and release operations
├── insights-mock.ts           # AI insights and conversations
├── infrastructure-mock.ts     # LadybugDB, memory, ideation, updates
└── settings-mock.ts           # App settings and version info
```

## Usage

The main `browser-mock.ts` file aggregates all mocks:

```typescript
import {
  projectMock,
  taskMock,
  workspaceMock,
  // ... other mocks
} from './mocks';

const browserMockAPI: ElectronAPI = {
  ...projectMock,
  ...taskMock,
  ...workspaceMock,
  // ... other mocks
};
```

## Adding New Mocks

1. Create a new file in the `mocks/` directory following the naming pattern: `<domain>-mock.ts`
2. Export a const object with your mock implementations
3. Add the export to `index.ts`
4. Spread the mock into `browserMockAPI` in `browser-mock.ts`

Example:

```typescript
// mocks/new-feature-mock.ts
export const newFeatureMock = {
  getFeature: async () => ({ success: true, data: null }),
  updateFeature: async () => ({ success: true })
};

// mocks/index.ts
export { newFeatureMock } from './new-feature-mock';

// browser-mock.ts
import { newFeatureMock, /* ... */ } from './mocks';

const browserMockAPI: ElectronAPI = {
  // ... existing mocks
  ...newFeatureMock
};
```

## Mock Data

Sample data is centralized in `mock-data.ts` and includes:
- `mockProjects` - Sample project entries
- `mockTasks` - Sample tasks with various statuses
- `mockInsightsSessions` - Sample conversation sessions

This data can be imported and used by any mock module.

## Console Logging

Mock operations that involve side effects (e.g., terminal operations, external processes) log to the console with the `[Browser Mock]` prefix for debugging.

## Type Safety

All mocks conform to the `ElectronAPI` interface from `shared/types`, ensuring type safety and API compatibility.

---

### Overview (`apps/desktop/src/renderer/components/task-detail/task-review/README.md`)

# Task Review Module

This directory contains the refactored components for the TaskReview functionality. The original 681-line monolithic component has been broken down into smaller, focused, and reusable components.

## Refactoring Summary

**Before:**
- Single file: `TaskReview.tsx` (681 lines)
- All logic and UI mixed together
- Difficult to maintain and test

**After:**
- Main component: `TaskReview.tsx` (155 lines - 77% reduction)
- 10 specialized modules (864 lines total including documentation)
- Clear separation of concerns
- Improved testability and maintainability

## Module Structure

### Core Components

#### `WorkspaceStatus.tsx` (217 lines)
The most complex component handling the active workspace display including:
- Change summary statistics
- Merge preview integration
- Action buttons (View Changes, Refresh Conflicts, Open Terminal)
- Stage/Merge options
- Discard functionality

**Props:**
- `task`: Current task information
- `worktreeStatus`: Workspace status data
- `workspaceError`: Error message if workspace operation failed
- `stageOnly`: Whether to stage changes only
- `mergePreview`: Merge conflict preview data
- `isLoadingPreview`: Loading state for merge preview
- Various callback handlers

#### `MergePreviewSummary.tsx` (109 lines)
Displays merge conflict preview information:
- Conflict count and severity
- Git conflicts with AI resolution indicator
- Auto-mergeable vs manual review statistics
- Branch divergence information

**Props:**
- `mergePreview`: Object containing conflicts, summary, and git conflict info
- `onShowConflictDialog`: Callback to open conflict details dialog

### Dialog Components

#### `ConflictDetailsDialog.tsx` (123 lines)
Full-screen dialog showing detailed merge conflict information:
- List of all conflicts with severity indicators
- Auto-merge capability badges
- Location, reason, and strategy for each conflict
- Action buttons to proceed with merge or close

#### `DiffViewDialog.tsx` (90 lines)
Displays list of changed files:
- File status (added, modified, deleted, renamed)
- Color-coded indicators
- Line addition/deletion counts

#### `DiscardDialog.tsx` (93 lines)
Confirmation dialog for discarding workspace changes:
- Warning message
- Summary of changes to be lost
- Confirmation action

### Message Components

#### `StagedSuccessMessage.tsx` (54 lines)
Success message shown after changes are staged:
- Next steps instructions
- Git command examples
- Terminal shortcut button

#### `WorkspaceMessages.tsx` (68 lines)
Collection of simple status messages:
- `LoadingMessage`: Loading indicator
- `NoWorkspaceMessage`: No workspace found state
- `StagedInProjectMessage`: Already staged state

### Form Components

#### `QAFeedbackSection.tsx` (57 lines)
Feedback form for requesting changes:
- Textarea for feedback
- Submit button with loading state
- Validation (feedback required)

### Utilities

#### `utils.tsx` (37 lines)
Shared utility functions:
- `getSeverityIcon()`: Returns icon component for conflict severity
- `getSeverityVariant()`: Returns CSS classes for severity styling

#### `index.ts` (16 lines)
Central export point for all module components and utilities.

## Component Hierarchy

```
TaskReview (main entry point)
├── StagedSuccessMessage
├── LoadingMessage
├── WorkspaceStatus
│   ├── MergePreviewSummary
│   └── (action buttons)
├── StagedInProjectMessage
├── NoWorkspaceMessage
├── QAFeedbackSection
├── DiscardDialog
├── DiffViewDialog
└── ConflictDetailsDialog
    └── utils (getSeverityIcon, getSeverityVariant)
```

## Design Principles Applied

### 1. Single Responsibility Principle
Each component has one clear purpose:
- Dialogs handle user confirmations
- Messages display status information
- Forms collect user input
- Utilities provide shared functions

### 2. Composition Over Inheritance
The main `TaskReview` component composes smaller components rather than containing all logic inline.

### 3. Props Drilling Minimization
Each component receives only the props it needs, making dependencies explicit and reducing coupling.

### 4. Reusability
Components like `LoadingMessage` and utility functions can be easily reused in other parts of the application.

### 5. Maintainability
- Each file is under 220 lines
- Clear component naming
- JSDoc comments for each component
- Explicit prop interfaces

## Usage Example

```tsx
import { TaskReview } from './task-detail/TaskReview';

function MyComponent() {
  return (
    <TaskReview
      task={task}
      feedback={feedback}
      worktreeStatus={worktreeStatus}
      // ... other props
      onMerge={handleMerge}
      onDiscard={handleDiscard}
    />
  );
}
```

## Testing Strategy

The modular structure enables focused unit tests:

```tsx
// Test individual components
describe('MergePreviewSummary', () => {
  it('shows success state when no conflicts', () => {
    // Test logic
  });

  it('shows warning when conflicts exist', () => {
    // Test logic
  });
});

// Test utilities independently
describe('getSeverityIcon', () => {
  it('returns correct icon for each severity level', () => {
    // Test logic
  });
});
```

## Future Improvements

Potential enhancements to consider:

1. **Custom Hooks**: Extract state management logic into custom hooks
   - `useWorktreeStatus()`
   - `useMergePreview()`

2. **Context API**: If prop drilling becomes an issue, consider a `TaskReviewContext`

3. **Animation**: Add transitions between states using Framer Motion

4. **Accessibility**: Enhance ARIA labels and keyboard navigation

5. **Storybook**: Create stories for each component for visual testing

## Migration Notes

This refactoring maintains 100% backward compatibility. The `TaskReview` component's props interface remains unchanged, so no updates are required in parent components.

## Contributing

When adding new features to the TaskReview functionality:

1. Consider if it fits in an existing component or needs a new one
2. Keep components under 250 lines
3. Add JSDoc comments
4. Update this README with new components
5. Follow the established naming conventions

---

### Guides CLI USAGE (`guides/CLI-USAGE.md`)

# Auto Claude

Auto Claude is a desktop application. All functionality is accessed through the Electron desktop UI.

## Getting Started

1. Download the latest release for your platform from the [Releases page](https://github.com/AndyMik90/Auto-Claude/releases)
2. Install and launch the application
3. Open your project (a git repository folder)
4. Connect Claude via the OAuth setup guide in the app
5. Create a task and let the agents work

## Running the App from Source

```bash
# Install dependencies
npm run install:all

# Development mode (hot reload)
npm run dev

# Production build + run
npm start
```

## Configuration

All configuration is done through the app's Settings UI. You can:

- Connect Claude accounts (OAuth or API key)
- Configure multiple provider profiles (Anthropic, OpenAI, Google, etc.)
- Enable the Graphiti memory system
- Set default models and thinking budgets
- Configure Linear/GitHub/GitLab integrations

---

### Guides Cross Project Projectid Tracking (`guides/cross-project-projectid-tracking.md`)

# Cross-Project Task Contamination: Missing projectId in Agent Event Pipeline

## Description

When running multiple projects simultaneously, agent events from one project can corrupt the status, badges, and column placement of tasks in another project. The root cause is that the entire agent event pipeline (from process spawn through XState state machine to disk persistence) identifies tasks by `specId` alone, with no project scoping. Since specIds are derived from task descriptions and are not unique across projects, `findTaskAndProject(taskId)` returns the first match across all loaded projects, routing events to the wrong task.

## Severity

**High** - Silent data corruption. Affected tasks show wrong status, wrong badges, land in wrong Kanban columns, and persist corrupted state to disk. On refresh, the corrupted state is reloaded, making the damage permanent until manually fixed.

## Affected Versions

All versions using the XState task state machine (PR #1575 and later).

## Steps to Reproduce

1. Open Auto Claude and load two projects (e.g., "Project A" and "Project B")
2. In Project A, create a task with a specific name (e.g., "write wtf to text file") - this generates specId `016-write-wtf-to-text-file`
3. In Project B, create a task with the same name - this generates the same specId `016-write-wtf-to-text-file`
4. Start both tasks simultaneously (or start Project A's task first, let it reach QA, then start Project B's task)
5. Switch between projects and observe the Kanban board

## Expected Results

- Each project's task progresses independently through its own lifecycle
- Events from Project A's agent process only affect Project A's task card
- Events from Project B's agent process only affect Project B's task card
- Refreshing the app preserves the correct status for both tasks
- Switching between projects shows each task in its correct column with the correct badge

## Actual Results

- Tasks in the non-active project show wrong status badges (e.g., "Coding" badge on a task still in the Planning column)
- Tasks snap to the wrong Kanban column after refresh
- Tasks get stuck in states they should have transitioned out of (e.g., permanently stuck in "Planning")
- "Incomplete" badges appear on tasks that completed their phase successfully
- QA tasks appear in "In Progress" column instead of "AI Review" column after switching projects
- The corrupted state persists to `implementation_plan.json`, so the damage survives app restart

## Root Cause

### Task Identity Collision

Every task has two identifiers:

- **`task.id`** - A UUID, unique globally
- **`task.specId`** - The spec directory name (e.g., `016-write-wtf-to-text-file`), derived from the task description, **not unique across projects**

The backend process uses `specId` as the task identifier in stdout markers. All agent event handlers resolve this back to a Task object via `findTaskAndProject(taskId)`, which searches all projects and returns the first match.

### Missing projectId in Event Pipeline

The agent event pipeline has no project scoping:

```
Backend process (Python)
  -> stdout/stderr (phase markers, task events, logs)
    -> agent-process.ts (parses output, emits typed events)
      -> agent-manager.ts (EventEmitter relay)
        -> agent-events-handlers.ts (event handlers)
          -> findTaskAndProject(taskId)  <-- COLLISION POINT
            -> taskStateManager (XState actor)
              -> persistPlanStatusAndReasonSync (disk)
              -> safeSendToRenderer (IPC to UI)
```

None of the `AgentManagerEvents` carry a `projectId`:

```typescript
// BEFORE: no way to scope events to the correct project
interface AgentManagerEvents {
  log: (taskId: string, log: string) => void;
  error: (taskId: string, error: string) => void;
  exit: (taskId: string, code: number | null, processType: ProcessType) => void;
  'execution-progress': (taskId: string, progress: ExecutionProgressData) => void;
  'task-event': (taskId: string, event: TaskEventPayload) => void;
}
```

### Impact on XState

The `TaskStateManager` maintains one XState actor per taskId and drives column placement, badge display, disk persistence, and renderer notifications. When an event is routed to the wrong project's actor:

1. The actor receives an event invalid for its current state (e.g., `PLANNING_COMPLETE` sent to an actor in `qa_review`)
2. XState either drops the event or transitions to an unexpected state
3. The wrong project's `implementation_plan.json` is overwritten with incorrect status fields
4. On app refresh, the task loads from the corrupted plan file and appears in the wrong column
5. Subsequent legitimate events may be rejected because the actor is in a state that doesn't accept them

### Contamination Example

Given:
- **Project A**: task `016-write-wtf-to-text-file` in QA (`qa_review` state)
- **Project B**: task `016-write-wtf-to-text-file` just started (`planning` state)

When Project B's planner emits `PLANNING_COMPLETE`:
1. `agent-process.ts` emits `task-event` with `taskId = "016-write-wtf-to-text-file"` and no projectId
2. `findTaskAndProject("016-write-wtf-to-text-file")` returns **Project A's task** (first match)
3. `PLANNING_COMPLETE` is sent to **Project A's XState actor** (which is in `qa_review`)
4. Project A's plan file is corrupted; Project B's task never receives the event

## Observed Symptoms

| Symptom | Cause |
|---------|-------|
| "Coding" badge on a task in the Planning column | Project B's `CODING_STARTED` event hit Project A's planning task |
| Task snaps to backlog on refresh | Plan file overwritten without XState fields; wrong project looked up for re-stamp |
| "Incomplete" badge on a task that just finished planning | `PROCESS_EXITED` event from Project B's process hit Project A's `plan_review` actor |
| QA task in "In Progress" column with "AI Review" badge | Execution progress event wrote wrong status to plan file |
| Task stuck in "Planning" forever | Events meant for this task were consumed by the duplicate in another project |

## Fix

Thread `projectId` from the IPC handler that starts each agent process through the entire event pipeline to the lookup function.

### Propagation Chain

```
execution-handlers.ts
  agentManager.startSpecCreation(..., project.id)       <- Origin: project.id from IPC handler
  agentManager.startTaskExecution(..., project.id)
  agentManager.startQAProcess(..., project.id)

agent-manager.ts
  storeTaskContext(..., projectId)                       <- Stored in execution context
  processManager.spawnProcess(..., projectId)            <- Passed to process spawner

agent-process.ts
  this.emitter.emit('log', taskId, ..., projectId)      <- Attached to every emitted event
  this.emitter.emit('task-event', taskId, ..., projectId)
  this.emitter.emit('execution-progress', ..., projectId)
  this.emitter.emit('exit', taskId, ..., projectId)
  this.emitter.emit('error', taskId, ..., projectId)

agent-events-handlers.ts
  findTaskAndProject(taskId, projectId)                  <- Scoped lookup
  taskStateManager.handleTaskEvent(...)                  <- Correct actor receives event
  persistPlanStatusAndReasonSync(...)                    <- Correct plan file updated
  safeSendToRenderer(..., projectId)                     <- Renderer filters by project
```

### Scoped Lookup

`findTaskAndProject` now accepts an optional `projectId`. When provided, it searches only the target project. Falls back to searching all projects for backward compatibility (file watcher events, renderer-initiated actions).

## Files Changed

| File | Change |
|------|--------|
| `apps/desktop/src/main/agent/types.ts` | Added `projectId?: string` to all event signatures |
| `apps/desktop/src/main/agent/agent-manager.ts` | Added `projectId` to context storage, start methods, restart flow |
| `apps/desktop/src/main/agent/agent-process.ts` | Added `projectId` to `spawnProcess` and all `emitter.emit()` calls |
| `apps/desktop/src/main/ipc-handlers/task/shared.ts` | Scoped `findTaskAndProject` by projectId with fallback |
| `apps/desktop/src/main/ipc-handlers/agent-events-handlers.ts` | All event handlers receive and forward projectId |
| `apps/desktop/src/main/ipc-handlers/task/execution-handlers.ts` | All 9 `agentManager.start*` call sites pass `project.id` |
| `apps/desktop/src/__tests__/integration/subprocess-spawn.test.ts` | Updated test expectations for new projectId parameter |

## Verification

- [ ] Run two projects simultaneously with tasks that have the same specId
- [ ] Verify events from Project A only affect Project A's task cards
- [ ] Verify events from Project B only affect Project B's task cards
- [ ] Refresh the app during various lifecycle stages - tasks remain in correct columns
- [ ] Switch between projects during QA - task stays in AI Review column
- [ ] `npm run typecheck` passes
- [ ] `npm run test` passes (2639 tests, 0 failures)

---

### Guides Linux (`guides/linux.md`)

# Linux Installation & Building Guide

This guide covers Linux-specific installation options and building from source.

## Flatpak Installation

Flatpak packages are available for Linux users who prefer sandboxed applications.

### Download Flatpak

See the [main README](../README.md#beta-release) for Flatpak download links in the Beta Release section.

### Building Flatpak from Source

To build the Flatpak package yourself, you need additional dependencies:

```bash
# Fedora/RHEL
sudo dnf install flatpak-builder

# Ubuntu/Debian
sudo apt install flatpak-builder

# Install required Flatpak runtimes
flatpak install flathub org.freedesktop.Platform//25.08 org.freedesktop.Sdk//25.08
flatpak install flathub org.electronjs.Electron2.BaseApp//25.08

# Build the Flatpak
cd apps/desktop
npm run package:flatpak
```

The Flatpak will be created in `apps/desktop/dist/`.

### Installing the Built Flatpak

After building, install the Flatpak locally:

```bash
flatpak install --user apps/desktop/dist/Auto-Claude-*.flatpak
```

### Running from Flatpak

```bash
flatpak run com.autoclaude.AutoClaude
```

## Other Linux Packages

### AppImage

AppImage files are portable and don't require installation:

```bash
# Make executable
chmod +x Auto-Claude-*-linux-x86_64.AppImage

# Run
./Auto-Claude-*-linux-x86_64.AppImage
```

### Debian Package (.deb)

For Ubuntu/Debian systems:

```bash
sudo dpkg -i Auto-Claude-*-linux-amd64.deb
```

## Troubleshooting

### Flatpak Runtime Issues

If you encounter runtime issues with Flatpak:

```bash
# Update runtimes
flatpak update

# Check for missing runtimes
flatpak list --runtime
```

### AppImage Not Starting

If the AppImage doesn't start:

```bash
# Check for missing libraries
ldd ./Auto-Claude-*-linux-x86_64.AppImage

# Try running with debug output
./Auto-Claude-*-linux-x86_64.AppImage --verbose
```

---

### Guides Pr 1575 Fixes (`guides/pr-1575-fixes.md`)

# PR #1575 Follow-up: XState Status Lifecycle & Cross-Project Contamination Fixes

## Overview

After the XState task state machine migration (PR #1575), several interrelated bugs surfaced when running multiple projects simultaneously and during normal task lifecycle transitions. These bugs caused tasks to appear in wrong columns, display incorrect badges, and lose status on refresh.

## Bug 1: Cross-Project Task Contamination

### Problem
When two projects have tasks with the same specId (e.g., both have a task `016-write-wtf-to-text-file`), events from Project A's task would affect Project B's task card. Tasks in the secondary project would show wrong status badges (e.g., "Coding" badge on a task in the Planning column).

### Root Cause
`findTaskAndProject(taskId)` searches ALL projects by matching `t.id === taskId || t.specId === taskId`, returning the first match. When the backend emits events using the specId as the task identifier, the lookup could match a task in the wrong project.

Agent events (log, error, exit, execution-progress, task-event) did not carry a `projectId`, so there was no way to scope the lookup to the correct project.

### Fix
- Added `projectId` to all `AgentManagerEvents` type signatures
- Pass `project.id` from all 9 `agentManager.start*` call sites in `execution-handlers.ts`
- Thread `projectId` through `agent-manager.ts` → `agent-process.ts` → all `emitter.emit()` calls
- Updated `findTaskAndProject(taskId, projectId?)` to scope search to the target project when `projectId` is provided, with fallback to searching all projects for backward compatibility
- All event handlers in `agent-events-handlers.ts` now receive and use `projectId`

### Files Changed
- `apps/desktop/src/main/agent/types.ts`
- `apps/desktop/src/main/agent/agent-manager.ts`
- `apps/desktop/src/main/agent/agent-process.ts`
- `apps/desktop/src/main/ipc-handlers/task/shared.ts`
- `apps/desktop/src/main/ipc-handlers/agent-events-handlers.ts`
- `apps/desktop/src/main/ipc-handlers/task/execution-handlers.ts`
- `apps/desktop/src/__tests__/integration/subprocess-spawn.test.ts`

## Bug 2: "Incomplete" Badge on Plan Review Tasks

### Problem
Tasks with `requireReviewBeforeCoding=true` would complete planning, correctly transition to `plan_review` state, but then immediately show an "Incomplete" badge instead of "Planning" + "Approve Plan".

### Root Cause
Two issues combined:

1. **`PLANNING_COMPLETE` was not in the `TERMINAL_EVENTS` set.** When the spec creation process finished normally (exit code 0), `handleProcessExited` was called. Since `PLANNING_COMPLETE` wasn't terminal, the check didn't skip.

2. **`handleProcessExited` always sent `unexpected: true`**, even for exit code 0. This caused the XState guard `unexpectedExit` to pass, transitioning the task from `plan_review` → `error`, which overwrote the correct `plan_review` reviewReason.

### Fix
- Added `PLANNING_COMPLETE` to the `TERMINAL_EVENTS` set so process exit is skipped when planning has already completed
- Changed `handleProcessExited` to only set `unexpected: true` when `exitCode !== 0` — a code-0 exit is normal and should not trigger error transitions

### Files Changed
- `apps/desktop/src/main/task-state-manager.ts`

## Bug 3: Backend qa.py Racing with XState Status

### Problem
Tasks completing QA would sometimes show "Incomplete" instead of "Needs Review" because the `reviewReason` field was missing.

### Root Cause
The backend `qa.py` tool was writing `plan["status"] = "human_review"` directly to the plan file WITHOUT setting `reviewReason`. This raced with the frontend XState state machine's `persistPlanStatusAndReasonSync()` which writes both `status` and `reviewReason` together. When qa.py wrote last, it clobbered the `reviewReason`.

### Fix
Removed the backend's direct status writes from `qa.py`. The frontend XState state machine is now the sole owner of status transitions — the backend only updates `last_updated` timestamps and QA-specific fields.

### Files Changed
- `apps/backend/agents/tools_pkg/tools/qa.py` (now removed — backend deleted)

## Bug 4: Plan File Overwrite by Planner Agent

### Problem
After a task started, the frontend would persist XState status fields (`status`, `xstateState`, `executionPhase`) to `implementation_plan.json`. The planner agent would then create the full plan using the Write tool, completely replacing the file and stripping the frontend's status fields. On refresh, the task would snap back to backlog.

### Root Cause
The planner agent writes `implementation_plan.json` via Claude's Write tool, which replaces the entire file. The agent-generated plan does not include frontend status fields (`xstateState`, `executionPhase`), so they are lost.

### Fix
Added a re-stamp mechanism in the file watcher's `progress` event handler. When the file watcher detects a plan file change and the `xstateState` field is missing (indicating the backend overwrote the file), the handler re-persists the current XState state back to the file. This also covers the worktree copy.

### Files Changed
- `apps/desktop/src/main/ipc-handlers/agent-events-handlers.ts`

## Bug 5: QA Tasks in Wrong Column After Project Switch

### Problem
A task correctly in the "AI Review" column (status `ai_review`, phase `qa_review`) would snap to "In Progress" column after switching to another project and back. The "AI Review" badge would still show, but the card was in the wrong column.

### Root Cause
`persistPlanPhaseSync()` in `plan-file-utils.ts` mapped execution phases to TaskStatus for column placement. It incorrectly mapped `qa_review` and `qa_fixing` to `in_progress` instead of `ai_review`. Every execution-progress event during QA would overwrite the correct `ai_review` status (set by XState) with `in_progress`. On refresh (reading from disk), the task loaded with `status: 'in_progress'` + `executionPhase: 'qa_review'`, placing it in the In Progress column with an AI Review badge.

### Fix
Changed the phase-to-status mapping in `persistPlanPhaseSync`:
- `qa_review` → `ai_review` (was `in_progress`)
- `qa_fixing` → `ai_review` (was `in_progress`)

### Files Changed
- `apps/desktop/src/main/ipc-handlers/task/plan-file-utils.ts`

## Bug 6: updateTaskStatus Not Applying reviewReason

### Problem
Tasks completing planning with `requireReviewBeforeCoding=true` would show an "Incomplete" badge in the Human Review column instead of "Planning" + "Approve Plan". The persisted plan file had the correct `reviewReason: 'plan_review'`, so refreshing the app would fix it.

### Root Cause
`updateTaskStatus` in `task-store.ts` received `reviewReason` as a parameter but never applied it to the task object. The spread was `{ ...t, status, executionProgress }` — missing `reviewReason`. The skip condition also only checked `status`, not `reviewReason`, so transitions where only `reviewReason` changed (e.g., `human_review` with different reasons) were silently dropped.

### Fix
- Added `reviewReason` to the task spread: `{ ...t, status, reviewReason, executionProgress }`
- Updated skip condition to check both `status` AND `reviewReason`

### Files Changed
- `apps/desktop/src/renderer/stores/task-store.ts`

## Bug 7: Task Stuck in "In Progress" After Planning (requireReviewBeforeCoding)

### Problem
Tasks with `requireReviewBeforeCoding=true` would complete planning, XState would correctly transition to `plan_review`, but the task card would remain in the "In Progress" column with `status=in_progress, reviewReason=none, phase=planning`.

### Root Cause
When the process exits with code 1 (expected — the interactive review checkpoint fails in piped mode), `agent-process.ts` emits an `execution-progress` event with `phase: 'failed'` before the `exit` event. The `execution-progress` handler in `agent-events-handlers.ts`:

1. **Called `persistPlanPhaseSync` with `phase: 'failed'`**, which maps `failed` → `status: 'error'`, overwriting the `status: 'human_review'` that XState had already persisted to the plan file
2. **Sent `TASK_EXECUTION_PROGRESS` with `phase: 'failed'` to the renderer**, overwriting the `planning` phase that XState had already emitted via `emitPhaseFromState`

Both operations bypassed XState's authority as the source of truth for status.

### Fix
Added an XState "settled state" guard in the `execution-progress` handler. When XState has already transitioned to a settled state (`plan_review`, `human_review`, `error`, `creating_pr`, `pr_created`, `done`), the handler:
- Skips `persistPlanPhaseSync` to prevent overwriting XState's persisted status
- Skips sending `TASK_EXECUTION_PROGRESS` to the renderer to prevent overwriting XState's emitted phase

XState's own `persistStatus()` and `emitPhaseFromState()` already handle disk and renderer updates correctly when transitioning to these states.

### Files Changed
- `apps/desktop/src/main/ipc-handlers/agent-events-handlers.ts`

## Testing

All fixes pass:
- `npm run typecheck` — clean
- `npm run test` — 2649 tests passing, 0 failures
- Manual testing: multi-project with same specIds, review-required tasks, project switching during QA, refresh at all lifecycle stages

---

### Guides Windows Development (`guides/windows-development.md`)

# Windows Development Guide

This guide covers Windows-specific considerations when developing Auto Claude.

## Setup

Auto Claude downloads prebuilt native binaries for `node-pty` on Windows automatically. If prebuilts are not available for your Electron version, you will need Visual Studio Build Tools:

1. Download [Visual Studio Build Tools 2022](https://visualstudio.microsoft.com/visual-cpp-build-tools/)
2. Select the "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 inside `apps/desktop/`

## Line Endings

Windows uses CRLF (`\r\n`) line endings while macOS/Linux use LF (`\n`). This can cause git diffs to show every line changed.

Configure git to handle line endings:

```bash
git config --global core.autocrlf true
```

The project's `.gitattributes` handles this automatically for tracked files.

## Path Separators

TypeScript code should use `path.join()` or `path.posix.join()` rather than hardcoded forward or back slashes. The platform abstraction layer in `apps/desktop/src/main/platform/` provides cross-platform helpers — always use those instead of `process.platform` directly.

## Shell Commands

The Bash tool in the AI agent layer validates commands against the allowlist defined in `apps/desktop/src/main/ai/security/`. On Windows, `.cmd` and `.bat` files require `shell: true` — the platform module's `requiresShell()` helper handles this automatically.

## Testing Windows Compatibility

CI runs all three platforms (Ubuntu, Windows, macOS) on every PR. To test locally on Windows:

```bash
cd apps/desktop

# Run unit tests
npm test

# Run type checking
npm run typecheck

# Run linter
npm run lint
```

## Common Issues

### Permission errors when deleting files

Windows file locking is stricter than Unix. Ensure streams and file handles are properly closed before attempting to delete or overwrite files.

### Long path names

Windows has a 260-character path limit by default. Enable long paths:

1. Open Group Policy Editor (`gpedit.msc`)
2. Navigate to: Local Computer Policy > Computer Configuration > Administrative Templates > System > Filesystem
3. Enable "Enable Win32 long paths"

Or use WSL2 to avoid the issue entirely.

### Case-insensitive filesystem

Windows filesystems are case-insensitive. Be consistent with casing in import paths — a mismatch that works on Windows will fail on Linux CI.

## Resources

- [Node.js on Windows](https://nodejs.org/en/download/)
- [Git for Windows](https://gitforwindows.org/)
- [WSL2 Documentation](https://docs.microsoft.com/en-us/windows/wsl/)

## Related

- [CONTRIBUTING.md](../CONTRIBUTING.md) - General contribution guidelines

---

--- METRICS ---
- Files Extracted: 26
- Estimated Token Budget: ~35440 tokens
- Canonical Reference: https://codewiki.google/github.com/AndyMik90/Aperant
