Metadata-Version: 2.5
Name: codeanex
Version: 0.1.0
Summary: codeAnex — AI coding agent for production codebases (CLI)
Author: Dimitrie Tayon
License: MIT
Requires-Python: >=3.11
Requires-Dist: anthropic>=0.40.0
Requires-Dist: fastapi>=0.115.0
Requires-Dist: graphifyy>=0.9.9
Requires-Dist: httpx>=0.27.0
Requires-Dist: jedi>=0.19.0
Requires-Dist: langgraph>=0.2.0
Requires-Dist: mcp>=1.10.0
Requires-Dist: openai>=1.75.0
Requires-Dist: prompt-toolkit>=3.0.52
Requires-Dist: pyjwt>=2.8.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: stripe>=10.0.0
Requires-Dist: truststore>=0.10.0
Requires-Dist: uvicorn>=0.30.0
Provides-Extra: react
Requires-Dist: langchain-anthropic; extra == 'react'
Requires-Dist: langchain-google-genai; extra == 'react'
Requires-Dist: langchain-openai; extra == 'react'
Description-Content-Type: text/markdown

# 🤖 Code AI Agent

A powerful CLI coding assistant that runs in your terminal.  
Supports Claude, Gemini, DeepSeek, and OpenAI models.

## Features

- **Single agent mode** — one elite agent with 100+ tools, no orchestrator overhead
- **Multi-agent mode** — LLM decomposes tasks into subtasks, each run by the right specialist in parallel
- **12 specialists** — coder, debugger, tester, reviewer, designer, devops, database, documenter, researcher, git, playwright, planner
- **Plan checkpointing** — incomplete plans survive crashes; resume with `/replan`
- **Self-healing loop** — auto-injects a debugger subtask when tests fail mid-plan
- **Multi-provider** — Claude, Gemini, DeepSeek, OpenAI via `/model` switch
- **Framework scaffolding** — init tools for Next.js, React, Angular, Vue, NestJS, FastAPI, Django and more
- **Smart linting** — auto-detects ruff, eslint, biome (no npx)
- **Background processes** — dev servers start without blocking the agent
- **Undo / diff** — file-level undo stack and live diff preview before writes
- **Context compaction** — `/compact` summarizes conversation to free context window

## Installation

```bash
git clone https://github.com/dimitrie095/code-agent.git
cd code-agent
python -m venv .venv

# Windows:
.venv\Scripts\activate
# Mac/Linux:
source .venv/bin/activate

pip install -r requirements.txt
cp .env.example .env
# Add your API keys to .env
```

## Configuration

Edit `.env`:

```env
ANTHROPIC_API_KEY=sk-ant-...
GEMINI_API_KEY=AIza...
DEEPSEEK_API_KEY=sk-...
OPENAI_API_KEY=sk-...
NVIDIA_API_KEY=nvapi-...
GITHUB_TOKEN=ghp_...
DEFAULT_MODEL=claude-sonnet-4-20250514
```

### MCP (Model Context Protocol)

codeAnex plays **two roles**:

| Rolle | Status | Beschreibung |
|-------|--------|--------------|
| **MCP-Client** | ✅ shipped | Lädt externe MCP-Server aus `mcp.json` → 106+ Tools werden erweiterbar |
| **MCP-Server** | ✅ Phase 2 (Basis) | codeAnex-Tools für Cursor/Claude Code/Cline: `python main.py mcp serve` |

**Client config** (Cursor-kompatibel), merged: `~/.cursor/mcp.json` + `.codeAnex/mcp.json`.

**CLI marketplace:**

```bash
python main.py mcp presets              # Katalog
python main.py mcp starter              # Phase-1: GitHub, Playwright, Postgres, Slack, Brave
python main.py mcp coding-starter       # Context7, Memory, Sequential Thinking
python main.py mcp add playwright       # Einzelnes Preset
python main.py mcp refresh
python main.py mcp serve --dir .        # codeAnex als MCP-Server
```

**Cursor mcp.json — codeAnex als Server:**

```json
{
  "mcpServers": {
    "codeanex": {
      "command": "python",
      "args": ["-m", "codeanex_mcp"],
      "env": { "CODE_AGENT_WORKING_DIR": "/path/to/project" }
    }
  }
}
```

**Curated presets** (`config/mcp_presets.json`) — Kategorie A/B aus der Roadmap:

| Tier | Presets |
|------|---------|
| **Must-have** | `github`, `gitlab`, `playwright`, `postgres`, `sqlite`, `slack`, `brave-search`, `fetch`, `sentry`, `kubernetes`, `git` |
| **Differentiation** | `context7`, `memory`, `sequential-thinking` |

REPL: `/mcp`, `/mcp starter`, `/mcp starter-phase1`, `/mcp add <id>`

Extension: **Settings → MCP Servers** (Coding starter / Phase-1 pack / Preset chips)

Requires: `pip install "mcp>=1.10.0"`, Node.js (`npx`), optional [uv](https://docs.astral.sh/uv/) for Python MCP servers.

**Pitfalls:** MCP-Tools laufen als Subprocess — Keys in `env`, nicht committen. Remote-only Server (Linear hosted URL) brauchen noch HTTP/SSE-Transport.

## Usage

```bash
python main.py                              # Interactive mode
python main.py -p "Fix the bug in app.py"  # Single prompt
python main.py --model deepseek-chat        # Specific model
python main.py --dir /path/to/project       # Specific directory
python main.py --no-confirm --verbose       # Skip confirmations, verbose output
python main.py --ci -p "Run tests" --json  # CI mode: JSON output + exit code
```

## CLI Commands

| Command              | Description                                              |
| -------------------- | -------------------------------------------------------- |
| `/help`              | Show all commands                                        |
| `/agent [name]`      | Switch to a specialist (or list all)                     |
| `/mode single\|multi` | Single agent vs multi-agent orchestrator                 |
| `/plan <task>`       | Decompose task into subtasks and execute with specialists |
| `/model [name]`      | Switch LLM model                                         |
| `/dir <path>`        | Change working directory                                 |
| `/reset`             | Clear conversation history                               |
| `/compact`           | Summarize conversation and replace history with summary  |
| `/quick <task>`      | Fast mode: skip plan gate, go straight to the fix        |
| `/undo [N]`          | Undo last N file changes (default: 1)                    |
| `/undolist`          | Show all file changes made this session                  |
| `/diff`              | Show changes as unified diff                             |
| `/difflive`          | Toggle live diff preview (confirm before each write)     |
| `/rollback`          | Revert all changes from the last plan (git stash pop)    |
| `/replan`            | Resume an incomplete plan from checkpoint                |
| `/background <task>` | Run a task in the background (non-blocking)              |
| `/background`        | List running background tasks                            |
| `/sessions`          | List saved sessions                                      |
| `/resume <id>`       | Restore a previous session                               |
| `/history`           | Show message count and token estimate                    |
| `/verbose`           | Toggle verbose output                                    |
| `/mcp`               | MCP server config and loaded tools                       |
| `/mcp refresh`       | Reconnect MCP servers and reload tool catalog            |
| `/exit`              | Quit                                                     |

## Specialists

Switch to a focused expert — same tools, smarter system prompt:

```
/agent             → list all specialists
/agent coder       → 💻 end-to-end implementation
/agent reviewer    → 🔍 code review (bugs, security, quality)
/agent tester      → 🧪 unit/integration tests, coverage
/agent debugger    → 🐛 root-cause analysis, regression tests
/agent devops      → 🐳 Docker, CI/CD, deployments
/agent designer    → 🎨 UI/UX, Tailwind, shadcn, layouts
/agent playwright  → 🎭 browser E2E tests, snapshots
/agent database    → 🗄️  SQL, Prisma, migrations, seeds
/agent documenter  → 📝 README, docstrings, API docs
/agent researcher  → 🌐 web research, docs lookup
/agent git         → 🔀 commits, branches, PRs
/agent planner     → 📋 architecture-only breakdowns
/agent default     → back to default mode
```

## Multi-Agent Mode

```
/mode multi         → every message is decomposed into subtasks
/plan <task>        → one-shot: plan + execute for a single task
```

The orchestrator decomposes the task with an LLM call, routes each subtask to the best specialist, and runs independent steps in parallel. A self-healing loop automatically injects a debugger subtask if tests fail. Completed steps are checkpointed — use `/replan` to resume after a crash.

## Supported Models

**Anthropic:** `claude-sonnet-4-20250514`, `claude-opus-4-5`, `claude-haiku-4-5-20251001`  
**Gemini:** `gemini-2.5-pro`, `gemini-2.5-flash`, `gemini-2.0-flash`  
**DeepSeek:** `deepseek-chat`, `deepseek-reasoner`  
**OpenAI:** `gpt-4o`, `gpt-4.1`, `o3-mini`, `o4-mini`, and more

---

## Available Tools (106)

### 📁 File & Code

| Tool               | Description                                          |
| ------------------ | ---------------------------------------------------- |
| `read_file`        | Read file contents with optional line range          |
| `write_file`       | Write full content to a file, creates dirs if needed |
| `edit_file`        | Replace a unique string in a file (str_replace)      |
| `move_rename_file` | Move or rename a file or directory                   |
| `diff_files`       | Show unified diff between two files                  |
| `diff_apply`       | Apply a unified diff patch to a file                 |
| `find_replace_all` | Find and replace text across multiple files          |
| `archive`          | Create or extract a ZIP/TAR archive                  |
| `list_directory`   | List files and directories with sizes                |
| `delete_file`      | Delete a file or directory                           |
| `file_stats`       | File metadata: size, lines, modified date            |
| `readme_outline`   | Extract headings from a Markdown file                |
| `zip_inspect`      | List contents of a ZIP without extracting            |

### 🔍 Search & Analysis

| Tool                | Description                                          |
| ------------------- | ---------------------------------------------------- |
| `search_files`      | Search for text or regex patterns across files       |
| `glob_files`        | Find files by glob pattern                           |
| `ast_query`         | Query code structure via AST (functions, classes)    |
| `rename_symbol`     | Rename a symbol across all files                     |
| `analyze_codebase`  | High-level codebase summary and metrics              |
| `find_dead_code`    | Detect unused functions and variables                |
| `find_duplicates`   | Find duplicate code blocks                           |
| `measure_complexity`| Cyclomatic complexity per function                   |
| `scan_secrets`      | Detect leaked secrets and credentials                |
| `security_scan`     | Static security analysis (SAST)                     |
| `check_dependencies`| Audit outdated or vulnerable dependencies            |

### ⚙️ Shell & Processes

| Tool                       | Description                                              |
| -------------------------- | -------------------------------------------------------- |
| `run_command`              | Execute a shell command (install, build, test)           |
| `start_background_process` | Start a long-running process in background               |
| `process_manager`          | List running processes or kill one by PID/name           |
| `read_logs`                | Read and filter a log file                               |
| `parse_logs`               | Structured log parsing with pattern matching             |
| `which_executable`         | Locate an executable in PATH                             |
| `wait_seconds`             | Wait N seconds (for polling or timing)                   |
| `check_ports`              | Check which ports are open/listening                     |
| `port_forward`             | Forward a local port to a remote host                    |

### 🔀 Git & Worktrees

| Tool                 | Description                                               |
| -------------------- | --------------------------------------------------------- |
| `git_command`        | Run any git command                                       |
| `git_context`        | Get current branch, status, and recent log               |
| `git_worktree_list`  | List all git worktrees                                    |
| `git_worktree_add`   | Create a new isolated worktree                            |
| `git_worktree_remove`| Remove a worktree                                         |
| `git_worktree_enter` | Switch context into a worktree                            |
| `git_worktree_exit`  | Return to main worktree                                   |

### 🌐 Web & HTTP

| Tool            | Description                                       |
| --------------- | ------------------------------------------------- |
| `web_search`    | Search the web via DuckDuckGo (no API key needed) |
| `fetch_url`     | Fetch and read a web page, strips HTML            |
| `http_request`  | Make HTTP requests to any REST API                |
| `download_file` | Download a file from a URL                        |
| `openapi_call`  | Call an API endpoint described by an OpenAPI spec |
| `graphql_query` | Execute a GraphQL query                           |

### 🗄️ Database

| Tool                | Description                                           |
| ------------------- | ----------------------------------------------------- |
| `sqlite_query`      | Run SQL queries on a SQLite database                  |
| `inspect_db_schema` | Show tables, columns, and types of a SQLite database  |
| `database_migrate`  | Run database migrations (Alembic, Prisma, Flyway)     |
| `generate_migration`| Generate a migration file from schema changes         |
| `redis_command`     | Run Redis commands via CLI                            |

### 🐳 DevOps & Cloud

| Tool             | Description                                              |
| ---------------- | -------------------------------------------------------- |
| `docker_command` | Run Docker commands: ps, logs, start, stop, build, exec  |
| `ssh_command`    | Run a command on a remote server via SSH                 |
| `k8s_command`    | Run kubectl commands for Kubernetes                      |
| `validate_env`   | Check required environment variables are set             |
| `env_manage`     | Read, write, or merge .env files                         |

### 🧪 Testing & Quality

| Tool                   | Description                                              |
| ---------------------- | -------------------------------------------------------- |
| `run_tests`            | Run tests (pytest, jest, go test, etc.)                  |
| `lint_code`            | Lint — auto-selects ruff/flake8/eslint/biome (no npx)   |
| `format_code`          | Auto-format with black/prettier/gofmt/rustfmt            |
| `generate_tests`       | Generate unit tests for a file or function               |
| `test_file`            | Run tests for a single file                              |
| `watch_tests`          | Run tests in watch mode                                  |
| `coverage_report`      | Generate and show test coverage                          |
| `detect_test_framework`| Detect which test framework a project uses               |
| `test_report`          | Parse and summarize a test results file                  |
| `verification_sketch`  | Quick pre-flight check before implementation             |

### 📊 Data & Documents

| Tool               | Description                                          |
| ------------------ | ---------------------------------------------------- |
| `read_csv`         | Read and summarize a CSV file                        |
| `read_json`        | Read and query a JSON file (dot-notation paths)      |
| `convert_format`   | Convert between JSON, YAML, and TOML                 |
| `pdf_read`         | Extract text from a PDF file                         |
| `spreadsheet_read` | Read Excel/ODS spreadsheets                          |
| `image_info`       | Get metadata and dimensions from an image file       |
| `decode_encode`    | Base64 / hex / URL encode and decode                 |
| `regex_test`       | Test a regex pattern against sample input            |
| `template_render`  | Render a Jinja2 / Mustache template                  |

### 📝 Todo & Planning

| Tool          | Description                                             |
| ------------- | ------------------------------------------------------- |
| `todo_write`  | Create a structured step-by-step plan                   |
| `todo_update` | Mark a todo item as in_progress, done, or failed        |
| `todo_read`   | Read the current todo list                              |

### 🧠 Memory & Blackboard

| Tool              | Description                                              |
| ----------------- | -------------------------------------------------------- |
| `save_note`       | Save a persistent note for later retrieval               |
| `read_notes`      | Read saved notes — list all or filter by key/tag         |
| `memory_store`    | Store a fact in the agent's long-term memory             |
| `memory_search`   | Search long-term memory by keyword                       |
| `blackboard_write`| Write shared state to the inter-agent blackboard         |
| `blackboard_read` | Read shared state from the inter-agent blackboard        |

### 📈 Performance

| Tool                 | Description                                          |
| -------------------- | ---------------------------------------------------- |
| `benchmark`          | Benchmark a function or command                      |
| `profile_endpoint`   | Profile an HTTP endpoint for latency                 |
| `load_test`          | Simple load test against a URL                       |
| `performance_profile`| Profile a Python script with cProfile               |

### 📄 Documentation

| Tool              | Description                                          |
| ----------------- | ---------------------------------------------------- |
| `generate_docs`   | Generate docstrings or API docs for a module         |
| `generate_diagram`| Generate a Mermaid architecture or ER diagram        |

### 🕸️ Knowledge graph (Graphify, bundled)

Ships with codeAnex via `pip install -r requirements.txt` (`graphifyy`). No separate Graphify install for end users.

| Tool             | Description                                                                 |
| ---------------- | --------------------------------------------------------------------------- |
| `graphify_status`| Check whether a workspace knowledge graph exists (nodes, paths to outputs)  |
| `graphify_build` | Build/refresh graph (default: AST-only code graph, no API key)              |
| `graphify_query` | Natural-language query over the graph (BFS/DFS)                             |
| `graphify_path`  | Shortest path between two concepts in the graph                             |

Outputs live under `.codeAnex/graphify-out/` (`graph.json`, `graph.html`).

**Auto mode (opt-in):** `CODE_AGENT_GRAPHIFY_AUTO=1`, `--graphify-auto`, or VS Code setting `codeAgent.autoGraphify`. On startup the agent builds the AST graph if missing; each user message triggers a `graphify_query` whose results are injected into the system prompt; code file edits schedule a debounced rebuild (~30s).

### ⚛️ React Doctor (React/Next/Expo)

Uses [react-doctor](https://github.com/millionco/react-doctor) — installed **into each React project** as a devDependency (not globally). Setup checks `package.json` first and skips if already present. The agent runs it after `.tsx`/`.jsx` edits and during verify/audit workflows. `init_nextjs`, `init_react`, and `init_expo` trigger background setup automatically.

| Tool                  | Description                                                          |
| --------------------- | -------------------------------------------------------------------- |
| `react_doctor_status` | Detect React project + whether react-doctor is installed             |
| `react_doctor_install`| Add `react-doctor` devDependency + optional agent skill in the repo  |
| `react_doctor_audit`  | Full or incremental scan (state, perf, a11y, security)             |

Last report: `.codeAnex/react-doctor-last.json`. Disable auto-runs: `CODE_AGENT_REACT_DOCTOR_AUTO=0`.

### 🔬 Notebooks & LSP

| Tool                 | Description                                         |
| -------------------- | --------------------------------------------------- |
| `notebook_list_cells`| List cells in a Jupyter notebook                    |
| `notebook_edit`      | Edit a specific cell in a Jupyter notebook          |
| `lsp_query`          | Query an LSP server for hover info, references      |

### 🐙 GitHub

| Tool         | Description                                         |
| ------------ | --------------------------------------------------- |
| `github_api` | Interact with GitHub: issues, PRs, repos, comments  |

### 🖥️ System

| Tool                | Description                                               |
| ------------------- | --------------------------------------------------------- |
| `clipboard`         | Read from or write to the system clipboard                |
| `send_notification` | Send a desktop notification when a task finishes          |
| `think`             | Reason through a problem before acting                    |
| `tool_catalog`      | List all available tools with descriptions                |
| `mcp_refresh`       | Reload MCP server tool catalog                            |
| `list_mcp_resources`| List resources exposed by MCP servers                     |
| `read_mcp_resource` | Read a specific MCP resource                              |

### 🚀 Framework Init

| Tool           | Description                                            |
| -------------- | ------------------------------------------------------ |
| `init_nextjs`  | Scaffold Next.js project (TS, Tailwind, App Router)    |
| `init_react`   | Scaffold React + Vite project                          |
| `init_angular` | Scaffold Angular project                               |
| `init_vue`     | Scaffold Vue 3 with TS, Router, Pinia, Vitest          |
| `init_nestjs`  | Scaffold NestJS backend                                |
| `init_express` | Create Express + TypeScript backend (no CLI)           |
| `init_fastapi` | Create FastAPI Python backend (no CLI)                 |
| `init_django`  | Scaffold Django project                                |
| `init_nuxt`    | Scaffold Nuxt 3 project                                |
| `init_svelte`  | Scaffold Svelte + Vite project                         |

---

## Workflows

User workflows are YAML files in `.codeAnex/workflows/`. Each file defines a named workflow with
ordered steps that the agent executes automatically — no manual step-by-step guidance needed.

### Quick Start

1. Create `.codeAnex/workflows/<name>.yaml`
2. List workflows: `/workflow list` or `--list-workflows`
3. Run a workflow: `/workflow <name>` or `python main.py --workflow <name>`

### Built-in Workflows

| Workflow          | Steps | Description                                        |
|-------------------|-------|----------------------------------------------------|
| `verify`          | 3     | Lint → syntax check → run tests (with auto-fix)   |
| `daily-checks`    | 3     | Security scan → deps check → dead code finder     |
| `daily-full`      | 5     | Comprehensive health check (chains security-audit) |
| `security-audit`  | 4     | Secrets → deps → SAST → report (specialist routed) |
| `refactor`        | 4     | Analyze → test → refactor → validate               |
| `optimierung-wf`  | 4     | Analyze → research → implement → validate          |

### Enhanced Step Features

```yaml
steps:
  - name: Security scan
    specialist: reviewer          # Route to a specialist
    timeout: 120                  # Step timeout in seconds
    retry:                        # Auto-retry on failure
      max_attempts: 3
      delay_seconds: 5
      on_retry_prompt: "Fix issues and retry"
    prompt: "Run scan_secrets..."

  - name: Only on full scope
    if: "{{scope}} == full"       # Conditional execution
    specialist: tester
    run_workflow: sub-workflow    # Chain another workflow

  - name: Error handler
    on_error: error-handler       # Custom error recovery
    output_vars:                  # Pass results as variables
      report_path: path to the generated report
```

### Step Formats

| Format               | Example                                                    |
|----------------------|------------------------------------------------------------|
| `prompt: "..."`      | Natural language instruction for the agent                 |
| `run: "command"`     | Shell command (literal)                                    |
| `tool: "name"`       | Direct tool call with `input: {key: val}`                  |
| `run_workflow: "x"`  | Delegate to another workflow (sub-workflow chaining)       |
| `{{var}}`            | Variable substitution in all fields                        |

### Events & Scheduling

- **Hooks** (`.codeAnex/hooks.yaml`): Trigger workflows on `startup`, `git_commit`, `file_changed`
- **Schedule** (`.codeAnex/schedule.yaml`): Cron or interval (`30m`, `6h`, `1d`) — runs in background

```bash
/hooks list       # List active hooks
/schedule list    # List scheduled tasks
```

---

## Project Structure

```
code-agent/
├── main.py                      # Entry point, CLI args, interactive REPL loop
├── requirements.txt
├── .env.example
├── config/
│   └── settings.py              # Settings, provider detection, model registry
├── .codeAnex/
│   ├── workflows/                  # YAML workflow definitions (6 built-in)
│   ├── hooks.yaml                  # Event-triggered hooks
│   ├── schedule.yaml               # Cron/interval scheduled tasks
│   ├── macros.yaml                 # /macro prompt templates
│   └── integrations.json           # Jira, GitHub, GitLab configs
├── agent/
│   ├── agent_loop.py            # Main agent loop, all provider adapters
│   ├── agent_graph.py           # LangGraph execution graph, wave runner
│   ├── orchestrator.py          # Multi-agent orchestrator (/mode multi)
│   ├── task_planner.py          # LLM task decomposition
│   ├── specialist.py            # 12 specialist definitions and routing
│   ├── plan_gate.py             # Explore → plan → execute enforcement
│   ├── checkpoint_plan.py       # Plan state persistence and resume
│   ├── blackboard.py            # Shared inter-subtask state
│   ├── project_memory.py        # Cross-subtask project context
│   ├── todo_graph.py            # LangGraph-backed todo manager
│   ├── hitl.py                  # Human-in-the-loop confirmations
│   ├── mapreduce.py             # Parallel file analysis (map-reduce)
│   ├── react_agent.py           # ReAct execution mode
│   ├── workflow_engine.py       # Workflow engine with enhanced features
│   └── persistence.py           # Session save/load (SQLite)
├── tools/
│   ├── definitions.py           # 106 tool schemas
│   └── executor.py              # Tool implementations
└── ui/
    └── cli.py                   # Terminal UI, REPL, slash commands
```

## Requirements

- Python 3.11+
- API key for at least one provider (Anthropic recommended)
