Metadata-Version: 2.4
Name: ctrlcode
Version: 0.5.2
Summary: Adaptive coding harness that transforms AI slop into production-ready code
License-File: LICENSE
Requires-Python: >=3.12
Requires-Dist: aiohttp>=3.10.0
Requires-Dist: aiosqlite>=0.20.0
Requires-Dist: anthropic>=0.40.0
Requires-Dist: apscheduler>=3.11.2
Requires-Dist: harness-utils>=1.3.0
Requires-Dist: httpx>=0.28.1
Requires-Dist: mcp>=1.0.0
Requires-Dist: networkx>=3.6.1
Requires-Dist: openai>=1.54.0
Requires-Dist: platformdirs>=4.5.1
Requires-Dist: playwright>=1.58.0
Requires-Dist: pyperclip>=1.11.0
Requires-Dist: textual>=7.5.0
Requires-Dist: tiktoken>=0.12.0
Requires-Dist: tree-sitter-language-pack>=0.13.0
Requires-Dist: tree-sitter>=0.25.2
Requires-Dist: watchfiles>=1.0.0
Description-Content-Type: text/markdown

# ctrl+code

AI coding harness that transforms raw LLM output into production-ready code. Middleware-driven session management, pluggable backends, proactive context management, a composable skills system, and a multi-agent workflow engine.

**NOTE**: *This is **beta** software, there are rough edges. Please report anything you find*

## Installation

```bash
pip install ctrlcode
```

## Usage

Start the TUI (auto-launches server):
```bash
ctrlcode
```

Or start server separately:
```bash
ctrlcode-server
```

## Configuration

ctrl+code follows platform conventions for config and data storage:

| Platform | Config | Data | Cache |
|----------|--------|------|-------|
| **Linux** | `~/.config/ctrlcode/` | `~/.local/share/ctrlcode/` | `~/.cache/ctrlcode/` |
| **macOS** | `~/Library/Application Support/ctrlcode/` | `~/Library/Application Support/ctrlcode/` | `~/Library/Caches/ctrlcode/` |
| **Windows** | `%APPDATA%\ctrlcode\` | `%LOCALAPPDATA%\ctrlcode\` | `%LOCALAPPDATA%\ctrlcode\Cache\` |

### Environment Variables

Override default directories:
- `CTRLCODE_CONFIG_DIR`: Config file location
- `CTRLCODE_DATA_DIR`: Session logs and persistent data
- `CTRLCODE_CACHE_DIR`: Conversation storage and temp files

### Configuration File

Copy `config.example.toml` to your config directory as `config.toml` and fill in your API keys.

```toml
[providers.anthropic]
api_key = "sk-ant-..."
model = "claude-sonnet-4-6"

[context]
prune_protect = 40000

[agents]
max_delegation_depth = 2   # Max recursive sub-agent depth (0 = disable delegation)

[trajectories]
enabled = false            # Opt-in: record turns as training data
dir = ".ctrlcode/trajectories"

[permissions]
safe_commands = ["pytest", "ruff"]   # Commands that don't require approval
```

### Agent Instructions (AGENT.md)

Customize agent behavior with `AGENT.md` files, loaded hierarchically:

1. **Global** (`~/.config/ctrlcode/AGENT.md`) — Your personal defaults across all projects
2. **Project** (`<workspace>/AGENT.md`) — Project-specific instructions

Example project `AGENT.md`:
```markdown
# MyProject Instructions

## Architecture
- Frontend: React + TypeScript
- Backend: FastAPI + PostgreSQL

## Style
- Use async/await for all I/O
- Prefer functional components
```

Instructions are injected into the system prompt, giving the agent context about your preferences and project structure.

## Skills

Skills are reusable workflows invoked with `/name` in the TUI, or applied automatically when the agent recognizes the intent.

### Built-in Skills

| Skill | Description |
|-------|-------------|
| `/commit` | Create a semantic git commit (analyzes diff, stages, writes message) |
| `/refactor` | Refactor a function or module; provide the target as an argument |
| `/test` | Run test suite, analyze failures, suggest missing coverage |
| `/review` | Review current git diff for quality, bugs, and security issues |
| `/docs` | Document a class/function; provide the target as an argument |
| `/debug-session` | Structured debug workflow: reproduce → isolate → fix → verify |
| `/plan` | Write a tasks/todo.md plan with checkboxes before implementing |
| `/pr` | Create a GitHub pull request: summarize commits, push branch, open PR |

### Custom Skills

Create a folder with a `SKILL.md` file. Skills are discovered from multiple locations (later overrides earlier):

1. Built-in (`src/ctrlcode/skills/builtin/`) — lowest priority
2. Global (`~/.config/ctrlcode/skills/`)
3. Project-local (`.ctrlcode/skills/`) — auto-detected per workspace
4. Config override (`config.skills_directory`) — highest priority

**Example** `.ctrlcode/skills/deploy/SKILL.md`:
```markdown
---
name: deploy
description: Deploy to staging and run smoke tests
license: project
requires_args: false
---

# Deploy

## Instructions

1. Run `make build`
2. Push to staging with `./scripts/deploy.sh staging`
3. Run `./scripts/smoke_test.sh` and report results
```

## Context Management

ctrl+code manages the LLM context window automatically:

- **Proactive monitoring**: Checks usage before each turn; compacts automatically at 85% of the model's limit
- **Agent-triggered compaction**: The agent can call `compact_conversation` at phase boundaries — last 6 messages are always preserved verbatim, older messages are summarized
- **History archive**: All compacted messages are archived to `.ctrlcode/conversation_history/<session_id>.md`
- **Model limits**: Claude family = 200k tokens; GPT-4o = 128k tokens; fallback = 170k

## Multi-Agent Workflows

For complex tasks ctrl+code can decompose work across a team of specialized agents orchestrated by `WorkflowOrchestrator`:

| Agent | Role |
|-------|------|
| **planner** | Analyzes intent, produces a task graph with parallel groups and checkpoints |
| **coder** | Implements tasks; reads, writes, and runs code |
| **reviewer** | Reviews completed work and requests changes if needed |
| **executor** | Runs tests, fetches URLs, validates that changes work |

The workflow is: plan → execute (parallel where safe) → review → re-execute if needed → validate.

### Recursive Delegation

The `coder` agent can spawn sub-agents via the `spawn_agent` tool to parallelize independent subtasks. Depth is bounded by `max_delegation_depth` in config (default: 2). `reviewer` and `executor` agents cannot delegate.

### Session Tracing

Every spawned agent is recorded in `.ctrlcode/agents/spawn_index.jsonl` with its `agent_id`, `parent_agent_id`, `depth`, and `conv_id`. The parent session conversation records each `spawn_agent` call and result including the child `agent_id`, so the full delegation tree is reconstructable from the main session log.

Sub-agent conversations are stored at `.ctrlcode/agents/{agent_id}/`.

## Architecture Overview

```
┌─────────────────────────────────────────────────┐
│                    TUI Client                    │
│         (Textual-based terminal UI)             │
└────────────┬────────────────────────────────────┘
             │ JSON-RPC over HTTP
┌────────────▼────────────────────────────────────┐
│              Server (aiohttp)                   │
│  ┌──────────────────────────────────────────┐   │
│  │         Session Manager                  │   │
│  │  ┌───────────────────────────────────┐   │   │
│  │  │       Middleware Stack            │   │   │
│  │  │  Memory → Workspace → Skill →     │   │   │
│  │  │  Baseline → ContextAssembly →     │   │   │
│  │  │  Permission → Progress            │   │   │
│  │  └───────────────────────────────────┘   │   │
│  └──────────────────────────────────────────┘   │
│                                                  │
│  ┌───────────────┐  ┌──────────────────────────┐ │
│  │ AgentReActLoop│  │  Tool Registry &         │ │
│  │               │  │  Executor                │ │
│  └───────────────┘  └──────────────────────────┘ │
│                                                  │
│  ┌───────────────────────────────────────────┐   │
│  │  WorkflowOrchestrator                     │   │
│  │    AgentCoordinator                       │   │
│  │      planner / coder / reviewer /         │   │
│  │      executor  (each: AgentReActLoop)     │   │
│  └───────────────────────────────────────────┘   │
│                                                  │
│  ┌───────────────┐  ┌──────────────────────────┐ │
│  │ Backend Layer │  │  Rootset DB              │ │
│  │ (Pluggable)   │  │  (.ctrlcode/rootset.db)  │ │
│  └───────────────┘  └──────────────────────────┘ │
└──────────────────────────────────────────────────┘
```

Key subsystems:

- **Middleware Stack**: Composable `BaseMiddleware` objects with four hook points (`before_turn`, `pre_tool`, `after_tool_call`, `after_turn`). Schema migrations for `rootset.db` run automatically on startup.
- **Pluggable Backends**: `BackendProtocol` abstracts all tool-layer I/O — swap `FilesystemBackend` for `StateBackend` (in-memory) in tests, or use `CompositeBackend` to route by path prefix
- **Rootset DB**: SQLite artifact store at `.ctrlcode/rootset.db` with versioned schema migrations (auto-applied on startup)
- **Context Window Monitor**: Per-session 85%-threshold monitor with LLM-powered summarization
- **Multi-Agent Engine**: `WorkflowOrchestrator` drives a planner→coder→reviewer→executor pipeline with parallel task groups, checkpoints, and configurable recursive delegation

## Developer Docs

- [Architecture](docs/architectural-patterns.md) — system design and patterns
- [Features Guide](docs/user-guide/features.md) — complete feature reference
- [Getting Started](docs/user-guide/getting-started.md) — setup guide
- [Configuration](docs/user-guide/configuration.md) — all config options
- [Security](docs/user-guide/security.md) — security model
- [Agent Docs](docs/AGENTS.md) — documentation map for agents working in this codebase
