rev-agentic 2.0.1
Rev - Autonomous AI Development System with Multi-Agent Orchestration
License: MIT
Requires Python: >=3.8
Keywords: ai, agent, ollama, autonomous, development, orchestration, ci-cd, testing, automation

# rev — Production-Grade Agentic Development System

A **robust, pattern-based autonomous development system** powered by [Ollama](https://ollama.ai) for local LLM inference. Built on **21 Agentic Design Patterns** for production-grade code generation, testing, and validation.

## 🌟 What Makes Rev Different

Rev isn't just another AI coding assistant — it's a **complete agentic development system** implementing industry-proven design patterns:

- **🧠 Agentic Design Patterns** — Built on 21 patterns from research (Goal Setting, Routing, RAG, Recovery, Resource Budgets, etc.)
- **🔍 Hybrid Search** — Combines symbolic (regex) + semantic (RAG/TF-IDF) code search for superior context gathering
- **📊 Resource-Aware** — Tracks steps, tokens, and time budgets to prevent runaway execution
- **🎯 Goal-Oriented** — Derives measurable goals from requests and validates they're met
- **🛡️ Production-Ready** — Multi-layer validation, security scanning, auto-recovery, and rollback planning
- **⚡ Intelligent** — Self-routing, priority scheduling, and adaptive agent configuration

## Key Features

### Agentic Design Patterns (NEW!)
- **🎯 Goal Setting & Monitoring** — Automatic goal derivation with measurable success metrics
- **🔀 Intelligent Routing** — Analyzes requests and configures optimal agent pipeline
- **🔍 RAG (Retrieval-Augmented Generation)** — Semantic code search using TF-IDF for better context
- **📊 Resource Budgets** — Tracks and enforces limits on steps, tokens, and execution time
- **🔄 Exception Recovery** — Automatic rollback plans and recovery strategies
- **📡 Inter-Agent Communication** — Message bus for coordinated multi-agent workflows
- **⚙️ Coding Workflows** — Multi-stage chains (analyze → design → plan → implement → test → refine)

### Core Capabilities
- **🤖 6-Agent System** — Planning, Research, Review, Execution, Validation, and Learning agents
- **🎭 Orchestrator Mode** — Meta-agent coordinates all agents with resource tracking
- **🔍 Research Agent** — Pre-planning codebase exploration (symbolic + semantic search)
- **📚 Learning Agent** — Project memory that learns from past executions
- **✅ Validation Agent** — Post-execution verification with goal evaluation
- **🛡️ Intelligent Review** — Automatic validation with security vulnerability detection
- **🔬 Advanced Analysis** (NEW!) — Test coverage, code context, symbol usage, dependencies, semantic diffs
- **📚 Complex Task Handling** — Recursive breakdown of large features
- **🔓 Smart Automation** — Autonomous execution with review-based approval
- **📋 Planning Mode** — Comprehensive task checklists with recursive decomposition
- **⚡ Execution Mode** — Iterative completion with optional action-level review
- **🚀 Parallel Execution** — Run 2+ tasks concurrently for 2-4x faster completion
- **🧪 Automatic Testing** — Runs tests after each change to validate correctness
- **🔧 Full Code Operations** — Review, edit, add, delete, rename files
- **🏠 Local LLM** — Uses Ollama (no API keys, fully private)
- **🎯 Advanced Planning** — Dependency analysis, impact assessment, risk evaluation
- **🛠️ Built-in Utilities** — File conversion, code refactoring, dependency management
- **⚡ Intelligent Caching** — File content, LLM responses, repo context, dependency trees

## Architecture

**Multi-Agent Orchestration System (v2.0)**

```
┌─────────────────────────────────────────────────────┐
│                   USER REQUEST                      │
└─────────────────┬───────────────────────────────────┘
                  │
         ┌────────┴────────┐
         │  ORCHESTRATOR   │  (Optional - coordinates all agents)
         └────────┬────────┘
                  │
                  ▼
┌─────────────────────────────────────────────────────┐
│           1. LEARNING AGENT (NEW!)                  │
│  • Recall similar past tasks                       │
│  • Provide success patterns                        │
│  • Estimate execution time                         │
│  • Warn about past failures                        │
└─────────────────┬───────────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────────────┐
│           2. RESEARCH AGENT (NEW!)                  │
│  • Explore codebase before planning               │
│  • Find relevant files and patterns               │
│  • Identify similar implementations               │
│  • Suggest approach based on codebase style       │
└─────────────────┬───────────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────────────┐
│           3. PLANNING AGENT                         │
│  • Break down request into atomic tasks            │
│  • Recursive breakdown for complex features        │
│  • Generate ordered execution checklist            │
│  • Assess dependencies, risks, and impact          │
└─────────────────┬───────────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────────────┐
│           4. REVIEW AGENT                           │
│  • Validate plan completeness                      │
│  • Identify security vulnerabilities               │
│  • Check for missing or unnecessary tasks          │
│  • Decision: Approved / Suggestions / Rejected     │
└─────────────────┬───────────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────────────┐
│           5. EXECUTION AGENT                        │
│  • Execute tasks sequentially or in parallel       │
│  • [Optional] Review Agent validates each action   │
│  • Make changes, run tests, validate               │
└─────────────────┬───────────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────────────┐
│           6. VALIDATION AGENT (NEW!)                │
│  • Run test suite                                  │
│  • Check syntax errors                             │
│  • Run linter                                      │
│  • Semantic validation (did changes match request?)│
│  • Auto-fix minor issues (optional)               │
└─────────────────┬───────────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────────────┐
│           LEARNING AGENT (POST)                     │
│  • Store successful patterns                       │
│  • Update project context                          │
│  • Record for future reference                     │
└─────────────────────────────────────────────────────┘
```

## Agentic Design Patterns

Rev implements **21 Agentic Design Patterns** from cutting-edge AI agent research, making it a production-grade development system rather than a simple code assistant.

### Pattern Implementations

**Phase 1: Foundational Patterns** ✅
- **Goal Setting & Monitoring** — Automatic derivation of measurable goals from user requests
- **Prompt Chaining (Coding Workflows)** — Multi-stage workflows: analyze → design → plan → implement → test → refine
- **Routing** — Intelligent request analysis that selects optimal agent configuration
- **Inter-Agent Communication** — Message bus with pub/sub for coordinated workflows
- **RAG (Retrieval-Augmented Generation)** — Semantic code search using TF-IDF alongside symbolic search
- **Exception Handling & Recovery** — Automatic rollback plans and recovery strategies
- **Resource-Aware Optimization** — Budget tracking for steps, tokens, and execution time

**Phase 2: Core Integrations** ✅
- **TaskRouter Integration** — Routes every request to determine coding mode and agent configuration
- **Goal Integration** — Goals automatically derived and validated post-execution
- **Priority Scheduling** — Higher-priority tasks execute first for critical path optimization
- **Metrics Emission** — JSONL metrics for evaluation and monitoring (`.rev-metrics/`)

**Phase 3: Advanced Integration** ✅
- **RAG Integration** — Research Agent uses hybrid symbolic + semantic search (enabled by default)
- **Resource Budget Tracking** — Orchestrator tracks and enforces budgets across all phases
- **Goal Validation** — Validation Agent evaluates whether goals were met

### Pattern Benefits

**🎯 Superior Context Gathering**
```bash
# Research Agent uses both approaches:
# Symbolic: Finds exact matches for "authenticate", "login", "jwt"
# Semantic: Finds conceptually related code even without keywords
rev "Add OAuth2 authentication"
```

**📊 Controlled Execution**
```bash
# Resource budgets prevent runaway execution:
# - Max steps: 200 (configurable via REV_MAX_STEPS)
# - Max tokens: 100,000 (REV_MAX_TOKENS)
# - Max time: 1800s / 30min (REV_MAX_SECONDS)
rev "Refactor entire authentication system"
# Output: "📊 Resource Usage: Steps: 45/200 | Tokens: 12000/100000 | Time: 120s/1800s"
```

**🎯 Goal-Oriented Validation**
```bash
# Goals automatically derived and validated:
rev "Fix all failing tests"
# Derives goal: "All tests must pass"
# Validation checks: Tests passed? ✅
# Goal met? ✅
```

**🔀 Adaptive Configuration**
```bash
# Router analyzes request and optimizes:
rev "Quick typo fix in README"
# → Route: quick_edit (skips research, minimal review)

rev "Implement payment processing system"
# → Route: full_feature (enables all agents, strict review)
```

### Pattern Usage

Most patterns are **enabled by default** with graceful degradation:

- **RAG Search**: Enabled (falls back to symbolic if unavailable)
- **Resource Budgets**: Always tracking (configurable limits)
- **Goal Validation**: Runs if goals exist (auto-derived for most tasks)
- **Routing**: Always active (optimizes agent pipeline)

**Configuration:**
```bash
# Disable RAG for faster execution
rev --research-depth shallow "Quick task"

# Adjust resource budgets
export REV_MAX_STEPS=500
export REV_MAX_TOKENS=200000
export REV_MAX_SECONDS=3600  # 1 hour

# Control routing behavior via strictness
rev --review-strictness strict "Critical production change"
```

**See [IMPLEMENTATION_SUMMARY.md](IMPLEMENTATION_SUMMARY.md) for complete pattern documentation and usage examples.**

## Installation

### Quick Install (Recommended)

```bash
# Install via pip (coming soon to PyPI)
pip install rev-agentic

# Or install from source
git clone https://github.com/redsand/rev
cd rev
pip install -e .
```

### 1. Install Ollama

```bash
# macOS
brew install ollama

# Linux
curl -fsSL https://ollama.ai/install.sh | sh

# Windows - Download from https://ollama.ai
```

### 2. Pull a Code Model

**⚠️ Important:** rev requires a model with **function/tool calling support** for full functionality.

**Recommended models with tool support:**
```bash
# Best for code tasks
ollama pull llama3.1:latest        # Best overall (tool support)
ollama pull qwen2.5:7b              # Good for code (tool support)
ollama pull mistral-nemo:latest     # Fast with tools

# Legacy (no tool support - limited functionality)
ollama pull gpt-oss:120b-cloud        # ⚠️ No tool support
ollama pull deepseek-coder:latest   # ⚠️ Check version for tool support
```

**🌐 Ollama Cloud Models (NEW!):**
```bash
# Ensure Ollama is running (cloud models proxy through local Ollama)
ollama serve

# Use powerful cloud-hosted models (requires authentication)
rev --model qwen3-coder:480b-cloud "Your task"
rev --model llama3.3:90b-cloud "Complex refactoring task"
```

**Important:** Cloud models require your local Ollama instance to be running. The local instance automatically proxies requests to Ollama's cloud service.

On first use, you'll be prompted to authenticate:
1. A browser URL will be displayed
2. Visit the URL and sign in with your Ollama account
3. Authorize your device
4. Press Enter to continue

**Verify tool support:**
```bash
# List models
ollama list

# Check model info
ollama show llama3.1:latest
```

### 3. Install Dependencies

```bash
pip install -r requirements.txt
```

## Usage

### One-Shot Mode

Execute a single task with **fully autonomous** operation:

```bash
rev "Add error handling to all API endpoints"
```

The agent will:
1. Analyze your repository
2. Generate an execution plan
3. **Execute autonomously** (no approval needed)
4. Prompt ONLY for destructive operations (delete, force push, etc.)
5. Show final summary

**New in v2: Autonomous by default!** No more repeated approval prompts. The agent only asks permission for potentially destructive operations.

### Interactive REPL

For iterative development with **session memory**:

```bash
rev --repl
```

The REPL now maintains context across multiple prompts:

```
agent> Review all documentation files
  ℹ️  Running in autonomous mode - destructive operations will prompt
  ... reviews README.md, COVERAGE.md, etc ...

agent> Now create a project overview document based on what you reviewed
  ... uses knowledge from previous reviews to create comprehensive overview ...

agent> /status
Session Summary:
  - Tasks completed: 15
  - Files reviewed: 8
  - Files modified: 1
```

**New REPL Commands:**
- `/status` - Show what's been done in this session
- `/clear` - Clear session memory
- `/help` - Show all commands
- `/exit` - Exit with session summary
- **`/mode`** - Control execution depth and thinking level (NEW in v2.0!)

### Execution Modes (NEW!)

Rev v2.0 introduces flexible execution modes that control the depth of analysis, research, and validation. Use `/mode` in REPL or configure via command-line:

```bash
# In REPL
rev> /mode thorough
Mode: thorough
  ✓ Orchestrator mode enabled
  Research:        Enabled (deep)
  Learning:        Enabled
  Review:          Enabled (strict)
  Validation:      Enabled + auto-fix
  Parallel Workers: 3

rev> Implement user authentication
# Executes with thorough mode settings...
```

**Available Modes:**

#### Mode Feature Matrix

| Feature | simple | standard | thorough | max |
|---------|--------|----------|----------|-----|
| **Orchestration** | ❌ | ✅ | ✅ | ✅ |
| **Research** | ❌ | Medium | Deep | Deep |
| **Learning** | ❌ | ❌ | ✅ | ✅ |
| **Review** | Lenient | Moderate | Strict | Strict |
| **Validation** | ❌ | ✅ | ✅ + auto-fix | ✅ + auto-fix |
| **Action Review** | ❌ | ❌ | ❌ | ✅ |
| **Parallel Workers** | 1 | 2 | 3 | 4 |
| **Best For** | Quick fixes | Daily development | Complex features | Critical changes |

**Mode Descriptions:**

- **`simple`** - Fast execution with minimal overhead. No research or learning. Sequential execution. Perfect for quick fixes and testing.

- **`standard`** - Balanced approach (DEFAULT). Medium research depth, moderate review, validation enabled, 2 parallel workers. Ideal for daily development.

- **`thorough`** - Comprehensive analysis. Deep research + learning, strict review, full validation with auto-fix, 3 parallel workers. Use for complex features and refactoring.

- **`max`** - Maximum capabilities. Full orchestration with all agents, deep research + learning, strict review with action-level validation, auto-fix, 4 parallel workers. For critical architectural changes.

**Command-Line Mode Control:**

```bash
# Standard mode (default)
rev "Add feature X"

# Simple mode for quick tasks
rev --no-orchestrate "Fix typo in README"

# Thorough mode for complex tasks
rev --orchestrate --research-depth deep --learn --auto-fix "Refactor auth system"
```

### Manual Approval Mode

If you want to manually approve the execution plan (old behavior):

```bash
rev --prompt "Run all tests and fix any failures"
```

With `--prompt`, the agent will ask for approval before starting execution.
**Default behavior: Runs autonomously without prompting** (except for scary operations).

### What Operations Require Confirmation?

Even in autonomous mode, the agent will **always prompt** for potentially destructive operations:

**Scary Operations (will prompt):**
- File deletion or removal
- Git operations: `reset --hard`, `clean -f`, `push --force`
- Commands containing: delete, remove, rm, clean, reset, force, destroy, drop, truncate
- Applying patches without dry-run first
- Tasks with "delete" action type

**Safe Operations (no prompt):**
- Reading files
- Searching code
- Running tests
- Creating/modifying files
- Git diff/log/status
- Running linters/formatters

## Configuration

### Environment Variables

```bash
# Ollama configuration
export OLLAMA_BASE_URL="http://localhost:11434"  # Default
export OLLAMA_MODEL="gpt-oss:120b-cloud"           # Default

# Reliability tuning (optional)
export OLLAMA_MAX_RETRIES=6                     # Retries for transient 5xx errors
export OLLAMA_RETRY_BACKOFF_SECONDS=2           # Base backoff between retries
export OLLAMA_RETRY_BACKOFF_MAX_SECONDS=30      # Cap for backoff delay
export OLLAMA_TIMEOUT_MAX_MULTIPLIER=3          # Cap timeout growth (10m -> 30m)

# Then run agent
rev "Your task here"
```

### Command-Line Options

```bash
rev [OPTIONS] "task description"

Options:
  --repl                       Interactive REPL mode
  --model MODEL                Ollama model to use (default: gpt-oss:120b-cloud)
  --base-url URL               Ollama API URL (default: http://localhost:11434)
  --prompt                     Prompt for approval before execution (default: auto-approve)
  -j N, --parallel N           Number of concurrent tasks (default: 2, use 1 for sequential)

  # Agent Control
  --orchestrate                Enable orchestrator mode (full multi-agent coordination)
  --learn                      Enable learning agent for project memory
  --research                   Enable research agent for pre-planning exploration
  --research-depth LEVEL       Research depth: shallow, medium, deep (default: medium)
  --review / --no-review       Enable/disable review agent (default: enabled)
  --review-strictness LEVEL    Review strictness: lenient, moderate, strict (default: moderate)
  --action-review              Enable action-level review during execution
  --validate / --no-validate   Enable/disable validation agent (default: enabled)
  --auto-fix                   Enable auto-fix for minor validation issues

  -h, --help                   Show help message
```

### Parallel Execution

**New in v2.0:** Concurrent task execution for faster completion!

By default, rev now runs **2 tasks in parallel** when they don't have dependencies on each other. This dramatically speeds up execution for complex tasks.

**Examples:**

```bash
# Use default (2 concurrent tasks)
rev "Review all API endpoints and add tests"

# Run 4 tasks in parallel for maximum speed
rev -j 4 "Refactor all components and update tests"

# Run sequentially (old behavior) for debugging
rev -j 1 "Complex refactoring that needs careful sequencing"

# Run 8 tasks in parallel for large codebases
rev -j 8 "Update all imports across the project"
```

**How it works:**
- The agent automatically tracks task dependencies
- Independent tasks (like reviewing different files) run in parallel
- Dependent tasks (like "run tests" after "fix bug") wait for prerequisites
- Thread-safe execution ensures no conflicts

**Performance benefits:**
- 2x-4x faster execution for typical tasks
- Scales well with more workers for large codebases
- No manual intervention needed - dependencies are automatic

## Examples

### Example 1: Add Feature

```bash
rev "Add rate limiting middleware to Express app"
```

**Generated Plan:**
1. [REVIEW] Analyze current Express middleware structure
2. [ADD] Create rate-limiting middleware module
3. [EDIT] Integrate rate limiter into main app
4. [ADD] Add tests for rate limiting
5. [TEST] Run test suite to validate

### Example 2: Fix Bugs

```bash
rev "Fix all ESLint errors in src/ directory"
```

**Generated Plan:**
1. [REVIEW] Run ESLint to identify all errors
2. [EDIT] Fix import order issues
3. [EDIT] Fix unused variable warnings
4. [EDIT] Fix indentation errors
5. [TEST] Run ESLint again to verify fixes

### Example 3: Refactoring

```bash
rev "Refactor authentication logic into separate service"
```

**Generated Plan:**
1. [REVIEW] Analyze current authentication code
2. [ADD] Create AuthService class
3. [EDIT] Extract auth logic to service
4. [EDIT] Update controllers to use AuthService
5. [EDIT] Update dependency injection
6. [TEST] Run integration tests

## How It Works

### Planning Phase

The agent uses Ollama to:
1. Analyze repository context (git status, file structure, recent commits)
2. Understand your request
3. Break it into atomic, ordered tasks
4. Classify each task by type (review, edit, add, delete, test)

### Execution Phase

For each task, the agent:
1. **Gathers context** using tools like `read_file`, `search_code`, `list_dir`
2. **Makes changes** using `write_file` or `apply_patch` (unified diffs)
3. **Validates changes** by running `run_tests`
4. **Reports completion** and moves to next task

### Available Tools

The agent has access to **41 powerful tools** across multiple categories:

**New in v2.0.1:** SSH remote execution! Connect to remote hosts, execute commands, and transfer files for managing your infrastructure.

**New in v2.0.1:** Cross-platform OS detection! The agent automatically detects your operating system (Windows, Linux, macOS) and adapts tool usage accordingly - choosing bash vs PowerShell, correct path separators, and platform-specific commands.

#### Core File Operations
| Tool | Description |
|------|-------------|
| `read_file` | Read file contents |
| `write_file` | Create or overwrite files |
| `delete_file` | Delete a file |
| `move_file` | Move or rename files |
| `copy_file` | Copy a file to a new location |
| `append_to_file` | Append content to a file |
| `replace_in_file` | Find and replace text within a file (supports regex) |
| `create_directory` | Create directories |
| `get_file_info` | Get file metadata (size, modified time, etc.) |
| `file_exists` | Check if a file or directory exists |
| `read_file_lines` | Read specific line range from a file |
| `tree_view` | Generate a tree view of directory structure |

#### Code Discovery & Search
| Tool | Description |
|------|-------------|
| `list_dir` | List files matching glob pattern |
| `search_code` | Search code with regex (symbolic search) |
| `rag_search` | Semantic code search using RAG/TF-IDF (NEW!) |

#### Git Operations
| Tool | Description |
|------|-------------|
| `git_diff` | View current uncommitted changes |
| `git_status` | Get detailed git status |
| `git_log` | Get git commit history |
| `git_commit` | Commit changes with a message |
| `git_branch` | Git branch operations (list, create, switch, current) |
| `apply_patch` | Apply unified diff patches |
| `get_repo_context` | Get git status and repo structure |

#### Command Execution
| Tool | Description |
|------|-------------|
| `run_cmd` | Execute shell commands |
| `run_tests` | Run test suite (pytest, npm test, etc.) |

#### Utility Tools
| Tool | Description |
|------|-------------|
| `install_package` | Install Python packages using pip |
| `web_fetch` | Fetch content from URLs |
| `execute_python` | Execute Python code snippets |
| `get_system_info` | Get system info (OS, version, architecture, shell type) |

#### SSH Remote Execution
| Tool | Description |
|------|-------------|
| `ssh_connect` | Connect to a remote host via SSH |
| `ssh_exec` | Execute commands on a remote host |
| `ssh_copy_to` | Copy a file to a remote host |
| `ssh_copy_from` | Copy a file from a remote host |
| `ssh_disconnect` | Disconnect from a remote host |
| `ssh_list_connections` | List all active SSH connections |

#### MCP (Model Context Protocol) Support
| Tool | Description |
|------|-------------|
| `mcp_add_server` | Add an MCP server for extended capabilities |
| `mcp_list_servers` | List configured MCP servers |
| `mcp_call_tool` | Call tools on MCP servers |

**New in v2.0.1:** MCP support allows the agent to connect to external tools and data sources through the Model Context Protocol, enabling integration with databases, APIs, and other development tools.

**New in v2.0.1:** Rev now includes **9 default MCP servers** for enhanced coding capabilities:
- 🧠 **Core**: memory, sequential-thinking, fetch
- 🚀 **Coding & CI/CD**: DeepWiki (GitHub search), Exa Search (code search), Semgrep (static analysis)
- 📚 **Docs**: Cloudflare Docs, Astro Docs
- 🤖 **AI/ML**: Hugging Face

**🔒 Private Mode:** Use `/private on` to disable all public MCP servers when working with secure/unsharable code. See [MCP_SERVERS.md](docs/MCP_SERVERS.md) for details.

#### Advanced Code Analysis Tools (NEW!)

**New in v2.0.1:** Five powerful analysis tools for improved development accuracy, review, and bug fixing:

| Tool | Description | Use Case |
|------|-------------|----------|
| `analyze_test_coverage` | Test coverage analysis using coverage.py/Istanbul | Check coverage before modifying code |
| `analyze_code_context` | Git history, bug fixes, code churn analysis | Understand why code exists before refactoring |
| `find_symbol_usages` | Find all references to functions/classes/variables | Assess impact before renaming/deleting |
| `analyze_dependencies` | Dependency graph with impact radius | Understand ripple effects before changes |
| `analyze_semantic_diff` | Detect breaking changes beyond line diffs | Verify backward compatibility |

**How Agents Use These Tools:**

```bash
# Before refactoring, agents automatically:
rev "Refactor UserService.authenticate method"

# 1. analyze_test_coverage() → Ensures 85% coverage exists
# 2. analyze_code_context() → Discovers recent bug fix for race condition
# 3. find_symbol_usages() → Finds 47 usages across 12 files
# 4. analyze_dependencies() → Calculates HIGH impact radius
# 5. Makes changes with full awareness
# 6. analyze_semantic_diff() → Verifies no breaking changes
```

**Benefits:**
- **🛡️ Prevents bugs:** Understands historical context to avoid re-introducing bugs
- **🎯 Impact awareness:** Knows exactly what will break before making changes
- **✅ Coverage validation:** Ensures adequate tests exist before modifications
- **🔍 Dependency tracking:** Maps full impact radius of changes
- **⚡ Breaking change detection:** Automatic backward compatibility checks

These tools transform Rev from "code modifier" to "intelligent code surgeon" with full awareness of consequences.

## Troubleshooting

### "Ollama API error: Connection refused"

Ensure Ollama is running:

```bash
ollama serve
```

### "Model not found"

Pull the model first:

```bash
ollama pull gpt-oss:120b-cloud
```

### "401 Unauthorized" for Cloud Models

Cloud models (ending with `-cloud`) require authentication. The agent will:
1. Detect the 401 error automatically
2. Display a signin URL
3. Wait for you to authenticate

**Steps to authenticate:**
```bash
# When you see the authentication prompt:
# 1. Visit the displayed URL in your browser
# 2. Sign in with your Ollama account
# 3. Authorize the device
# 4. Press Enter to continue

# The authentication persists, so you only need to do this once per device
```

**Example:**
```bash
rev --model qwen3-coder:480b-cloud "Review code"

# Output:
# ============================================================
# OLLAMA CLOUD AUTHENTICATION REQUIRED
# ============================================================
# Model 'qwen3-coder:480b-cloud' requires authentication.
#
# To authenticate:
# 1. Visit this URL in your browser:
#    https://ollama.com/connect?name=YOUR-DEVICE&key=...
#
# 2. Sign in with your Ollama account
# 3. Authorize this device
# ============================================================
#
# Press Enter after completing authentication...
```

### "400 Bad Request" or "Model not using tools"

Some Ollama models don't support function/tool calling. This is normal for older or smaller models.

**Models with tool support (recommended):**
- `llama3.1` (8B, 70B, 405B)
- `mistral-nemo`
- `mistral-large`
- `qwen2.5` (7B and up)
- `phi3.5`

**How to fix:**
1. Use a model with tool support:
   ```bash
   ollama pull llama3.1:latest
   rev --model llama3.1:latest "Your task"
   ```

2. Or enable debug mode to see what's happening:
   ```bash
   OLLAMA_DEBUG=1 rev "Your task"
   ```

The agent will automatically retry without tools if it detects the model doesn't support them, but tool support is highly recommended for best results.

### "Path escapes repo"

rev only operates within the current repository for safety. Use relative paths.

### Tasks not completing

Try a more specific request or use a larger model:

```bash
rev --model deepseek-coder:33b "Your task"
```

## Testing & Coverage

**Test Coverage: 80%** - Production Ready ✅

- **136 tests passing** (100% pass rate)
- **800+ statements** in the rev package
- **Cross-platform tested** (Linux, macOS, Windows detection)
- **SSH remote execution tested** (connection management, file transfer)
- **99% test code coverage** (tests are well-tested themselves)

### What's Tested
- ✅ File operations (read, write, delete, move, copy, append, replace)
- ✅ Advanced file operations (file_exists, read_file_lines, tree_view)
- ✅ Git operations (diff, patch, commit, status, log, branch)
- ✅ Command execution and validation
- ✅ Utility tools (install_package, web_fetch, execute_python, get_system_info)
- ✅ System information detection (OS, version, shell type, caching)
- ✅ SSH remote execution (connect, execute, file transfer, disconnect)
- ✅ MCP (Model Context Protocol) integration
- ✅ Task management (Task, ExecutionPlan)
- ✅ Tool execution routing
- ✅ Ollama integration (mocked)
- ✅ Planning and execution modes
- ✅ Security validations
- ✅ REPL mode commands and session tracking
- ✅ CLI argument parsing
- ✅ Scary operation detection and prompting
- ✅ Edge cases and error handling

### Code Quality Initiatives
- ✅ Static code analysis with automated linting
- ✅ Type hinting for improved code clarity
- ✅ Comprehensive documentation coverage
- ✅ Security scanning and vulnerability assessment
- ✅ Performance benchmarking and optimization
- ✅ Cross-platform compatibility verification
- ✅ Dependency security scanning

### Running Tests

```bash
# Run all tests
python -m pytest tests -v

# Run with coverage report
python -m pytest tests --cov=rev --cov-report=term-missing

# Generate HTML coverage report
python -m pytest tests --cov=rev --cov-report=html
```

For detailed coverage information, see [COVERAGE.md](COVERAGE.md).

For future testing, quality, documentation, and security improvements, see [RECOMMENDATIONS.md](RECOMMENDATIONS.md).

## Advanced Planning

rev includes sophisticated planning capabilities that analyze your tasks before execution:

### Features

**🔍 Dependency Analysis**
- Automatically determines optimal task ordering
- Identifies parallelization opportunities
- Calculates critical path through task dependencies

**📊 Impact Assessment**
- Predicts scope of changes before making them
- Identifies affected files and modules
- Estimates change magnitude

**⚠️ Risk Evaluation**
- Evaluates risk level for each task (🟢 LOW, 🟡 MEDIUM, 🟠 HIGH, 🔴 CRITICAL)
- Identifies potentially breaking changes
- Flags dangerous operations (database, security, delete, etc.)

**🔄 Rollback Planning**
- Automatically generates recovery procedures
- Action-specific rollback steps
- Database and production rollback guidance

**Example Output:**
```
============================================================
EXECUTION PLAN
============================================================
1. [REVIEW] Analyze current authentication module
   Risk: 🟢 LOW

2. [EDIT] Refactor auth to use dependency injection
   Risk: 🟡 MEDIUM (Destructive/modifying action: edit)
   Depends on: #1

3. [DELETE] Remove deprecated auth helpers
   Risk: 🔴 CRITICAL (Destructive/modifying action: delete)
   Depends on: #2
   ⚠️  Warning: Potentially breaking change

============================================================
PLANNING ANALYSIS SUMMARY
============================================================
Total tasks: 5
Risk distribution:
  🟢 LOW: 2
  🟡 MEDIUM: 2
  🔴 CRITICAL: 1

⚡ Parallelization potential: 3 tasks can run concurrently
   Critical path length: 4 steps

🔴 CRITICAL: 1 high-risk task(s) require extra caution
   - Task #3: Remove deprecated auth helpers...
     Rollback plan available
============================================================
```

**Learn More:** See [ADVANCED_PLANNING.md](ADVANCED_PLANNING.md) for complete documentation.

## Multi-Agent Quorum System

**New in v2.0.1:** rev now uses a **3-agent quorum system** that provides intelligent review and validation at multiple stages for more accurate and secure code changes.

### The Three Agents

```
┌──────────────────────────────────────────────────────────┐
│  1. PLANNING AGENT                                       │
│  • Breaks down complex requests into atomic tasks       │
│  • Analyzes dependencies and risks                      │
│  • Performs recursive breakdown for complex features    │
│  • Creates comprehensive execution plans                │
└───────────────────┬──────────────────────────────────────┘
                    ↓
┌──────────────────────────────────────────────────────────┐
│  2. REVIEW AGENT (NEW!)                                  │
│  • Validates execution plans before execution           │
│  • Reviews individual actions during execution          │
│  • Identifies security vulnerabilities                  │
│  • Suggests improvements and alternatives               │
│  • Checks for missing tasks or unnecessary steps        │
└───────────────────┬──────────────────────────────────────┘
                    ↓
┌──────────────────────────────────────────────────────────┐
│  3. EXECUTION AGENT                                      │
│  • Executes approved tasks sequentially or in parallel  │
│  • Calls tools and makes code changes                   │
│  • Validates results                                    │
│  • Applies recommendations from Review Agent            │
└──────────────────────────────────────────────────────────┘
```

### How It Works

**1. Planning Phase** - The Planning Agent analyzes your request
```bash
rev "Add user authentication with JWT"
```

The Planning Agent will:
- Analyze your repository structure
- Break down the request into specific tasks
- Identify dependencies between tasks
- Assess risks for each task
- **Handle recursive breakdown** for complex features

**End-to-end flow (Planning ➜ Review ➜ Execution)**

1. `rev "<task>"` kicks off the **planning phase** to draft a full execution plan.
2. The **review phase** evaluates completeness, safety, and risk before any edits occur.
3. The **execution phase** applies the approved steps with validations and tests, stopping on failures and surfacing actionable errors.

This flow runs automatically for every request, ensuring the plan, review, and execution steps all complete instead of stopping after planning.

For example, a high-level task like "Implement authentication system" will be automatically broken down into:
- Design authentication architecture
- Create user model and database schema
- Implement JWT token generation
- Add authentication middleware
- Create login/register endpoints
- Write authentication tests

**2. Review Phase** - The Review Agent validates the plan
```
============================================================
REVIEW AGENT - PLAN REVIEW
============================================================
→ Analyzing plan with review agent...

============================================================
REVIEW RESULTS
============================================================

Decision: ✅ APPROVED WITH SUGGESTIONS
Confidence: 85%

Plan is generally sound but could be improved

💡 Suggestions (3):
  - Add rate limiting to prevent brute force attacks
  - Include password reset func