> ## Documentation Index
> Fetch the complete documentation index at: https://panopticon-cli.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Cloister

> AI lifecycle manager with intelligent model routing

export const ThemedImage = ({light, dark, alt = ""}) => <>
    <img src={light} alt={alt} className="block dark:hidden" />
    <img src={dark ?? light} alt={alt} className="hidden dark:block" />
  </>;

# Cloister: AI Lifecycle Manager

Cloister is Overdeck's intelligent agent lifecycle manager. It monitors all running agents and automatically handles:

* **Model Routing** - Routes tasks to appropriate models based on complexity, across multiple providers
* **Stuck Detection** - Identifies agents that have stopped making progress
* **Automatic Handoffs** - Escalates to specialists when needed
* **Specialist Coordination** - Manages review-agent, test-agent, inspect-agent, uat-agent, and merge-agent

## How Cloister Works

```
┌─────────────────────────────────────────────────────────────┐
│                     CLOISTER SERVICE                         │
│                                                              │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐     │
│  │  Heartbeat  │───▶│   Trigger   │───▶│   Handoff   │     │
│  │   Monitor   │    │   Detector  │    │   Manager   │     │
│  └─────────────┘    └─────────────┘    └─────────────┘     │
│         │                  │                  │             │
│         ▼                  ▼                  ▼             │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐     │
│  │   Agent     │    │  Complexity │    │ Specialists │     │
│  │   Health    │    │   Analysis  │    │  (5 types)  │     │
│  └─────────────┘    └─────────────┘    └─────────────┘     │
└─────────────────────────────────────────────────────────────┘
```

## Starting Cloister

```bash theme={null}
# Via dashboard - click "Start" in the Cloister status bar
# Or via CLI:
pan cloister start

# Check status
pan cloister status

# Stop monitoring
pan cloister stop
```

## Specialists

Cloister manages five specialized agents that handle specific phases of the development lifecycle:

| Specialist        | Purpose                                     | Trigger                    |
| ----------------- | ------------------------------------------- | -------------------------- |
| **review-agent**  | Code review before merge                    | Human clicks "Review"      |
| **test-agent**    | Runs test suite after review                | After review passes        |
| **inspect-agent** | Per-step verification during implementation | After each bead completion |
| **uat-agent**     | Browser-based requirement verification      | After tests pass           |
| **merge-agent**   | Handles git merge and conflict resolution   | "Approve & Merge" button   |

See the [Specialists feature guide](/features/specialists) for detailed information on specialist agents.

### Review Pipeline Flow

The review pipeline is a sequential handoff between specialists:

```
Human clicks "Review"
        │
        ▼
┌───────────────────┐
│   review-agent    │ Reviews code, checks for issues
└─────────┬─────────┘
          │ If PASSED: queues test-agent
          │ If BLOCKED: sends feedback to work-agent
          ▼
┌───────────────────┐
│    test-agent     │ Runs test suite, analyzes failures
└─────────┬─────────┘
          │ If PASSED: queues uat-agent
          │ If FAILED: sends feedback to work-agent
          ▼
┌───────────────────┐
│    uat-agent      │ Browser-based requirement verification
└─────────┬─────────┘
          │ If PASSED: marks ready for merge
          │ If FAILED: sends feedback to work-agent
          ▼
┌───────────────────┐
│  (Human clicks    │ Human approval required
│  "Approve & Merge"│ before merge
└─────────┬─────────┘
          ▼
┌───────────────────┐
│   merge-agent     │ Performs merge, resolves conflicts
└───────────────────┘
```

Additionally, **inspect-agent** runs during implementation (between beads), not as part of this post-implementation pipeline.

**Key Points:**

* **Human-initiated start** - A human must click "Review" to start the pipeline
* **Automatic handoffs** - review-agent → test-agent → uat-agent happens automatically
* **Human approval for merge** - Merge is NOT automatic; human clicks "Approve & Merge"
* **Feedback loops** - Failed reviews/tests/UAT send feedback back to the work-agent

### Queue Processing

Each specialist has a task queue (`~/.overdeck/specialists/{name}/hook.json`) managed via the FPP (Fixed Point Principle):

```
1. Task arrives (via API or handoff)
        │
        ▼
2. wakeSpecialistOrQueue() checks if specialist is busy
        │
        ├── If IDLE: Wake specialist immediately with task
        │
        └── If BUSY: Add task to queue (hook.json)
                │
                ▼
3. When specialist completes current task:
        │
        ├── Updates status via API (passed/failed/skipped)
        │
        └── Dashboard automatically wakes specialist for next queued task
```

**Queue priority order:** `urgent` > `high` > `normal` > `low`

**Completion triggers:** When a specialist reports status (`passed`, `failed`, or `skipped`), the dashboard:

1. Sets the specialist state to `idle`
2. Checks the specialist's queue for pending work
3. If work exists, immediately wakes the specialist with the next task

### Agent Self-Requeue (Circuit Breaker)

After a human initiates the first review, work-agents can request re-review up to 3 times automatically:

```bash theme={null}
# Work-agent requests re-review after fixing issues
pan work request-review MIN-123 -m "Fixed: added tests for edge cases"
```

**Circuit breaker behavior:**

* First human click resets the counter to 0
* Each `pan work request-review` increments the counter
* After 3 automatic re-requests, returns HTTP 429
* Human must click "Review" in dashboard to continue

This prevents infinite loops where an agent repeatedly fails review.

**API endpoint:** `POST /api/workspaces/:issueId/request-review`

### Specialist Auto-Initialization

When Cloister starts, it automatically initializes specialists that don't exist yet. This ensures all five specialists are ready to receive wake signals without manual setup.

## Automatic Handoffs

Cloister detects situations that require intervention:

| Trigger                      | Condition                                | Action                         |
| ---------------------------- | ---------------------------------------- | ------------------------------ |
| **stuck\_escalation**        | No activity for 30+ minutes              | Escalate to more capable model |
| **complexity\_upgrade**      | Task complexity exceeds model capability | Route to Opus                  |
| **implementation\_complete** | Agent signals work is done               | Wake review-agent              |
| **test\_failure**            | Tests fail repeatedly                    | Escalate model or request help |
| **planning\_complete**       | Planning session finishes                | Transition to implementation   |
| **merge\_requested**         | User clicks "Approve & Merge"            | Wake merge-agent               |

<Note>
  The same lifecycle signals that drive these handoffs also feed the **Fix-All
  Flywheel** orchestrator, which keeps the pipeline turning autonomously —
  prioritizing what to work on next, launching planning and work agents, and
  escalating where Cloister flags a problem. Cloister is the per-agent lifecycle
  layer; the Flywheel is the cross-issue orchestrator built on top of it.
</Note>

<ThemedImage light="/images/dashboard/flywheel-light.png" dark="/images/dashboard/flywheel-dark.png" alt="Fix-All Flywheel orchestrator view, the autonomous loop that prioritizes work and launches planning and work agents across the pipeline" />

### Handoff Methods

Cloister supports two handoff methods, automatically selected based on agent type:

| Method              | When Used                                             | How It Works                                                                                                                                                                          |
| ------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Kill & Spawn**    | General agents (agent-min-123, etc.)                  | 1. Captures full context (STATE.md, beads, git state)<br />2. Kills tmux session<br />3. Spawns new agent with handoff prompt<br />4. New agent continues work with preserved context |
| **Specialist Wake** | Permanent specialists (merge-agent, test-agent, etc.) | 1. Captures handoff context<br />2. Sends wake message to existing session<br />3. Specialist resumes with context injection                                                          |

**Kill & Spawn** is used for temporary agents that work on specific issues. It creates a clean handoff by:

* Capturing the agent's current understanding (from STATE.md)
* Preserving beads task progress and open items
* Including relevant git diff and file context
* Building a comprehensive handoff prompt for the new model

**Specialist Wake** is used for permanent specialists that persist across multiple issues. It avoids the overhead of killing/respawning by injecting context into the existing session.

### Handoff Context Capture

When a handoff occurs, Cloister captures:

```json theme={null}
{
  "agentId": "agent-min-123",
  "issueId": "MIN-123",
  "currentModel": "kimi-k2.5",
  "targetModel": "opus",
  "reason": "stuck_escalation",
  "handoffCount": 1,
  "state": {
    "phase": "implementation",
    "complexity": "complex",
    "lastActivity": "2024-01-22T10:30:00-08:00"
  },
  "beadsTasks": [...],
  "gitContext": {
    "branch": "feature/min-123",
    "uncommittedChanges": ["src/auth.ts", "src/tests/auth.test.ts"],
    "recentCommits": [...]
  }
}
```

Handoff prompts are saved to `~/.overdeck/agents/{agent-id}/handoffs/` for debugging.

## Heartbeat Monitoring

Agents send heartbeats via Claude Code hooks. Cloister tracks:

* Last tool use and timestamp
* Current task being worked on
* Git branch and workspace
* Process health

What Cloister tracks per agent surfaces directly on the dashboard's Agents page,
which rolls the live heartbeat data up into a fleet view: each card shows the
agent's model, runtime, and last activity, topped by a metric strip (Running,
Stuck, Cost 24h, Tokens 24h, runtime, Queue). This is where the stuck-detection
and process-health signals described below become operator-visible.

<ThemedImage light="/images/dashboard/agents-light.png" dark="/images/dashboard/agents-dark.png" alt="Agents page: a metric strip showing Running, Stuck, Cost 24h, Tokens 24h, runtime, and Queue over agent cards listing each agent's model, runtime, and last activity" />

Heartbeat files are stored in `~/.overdeck/heartbeats/`:

```json theme={null}
{
  "timestamp": "2024-01-22T10:30:00-08:00",
  "agent_id": "agent-min-123",
  "tool_name": "Edit",
  "last_action": "{\"file_path\":\"/path/to/file.ts\"...}",
  "git_branch": "feature/min-123",
  "workspace": "/home/user/projects/myapp/workspaces/feature-min-123"
}
```

### Heartbeat Hook Installation

The heartbeat hook is automatically synced to `~/.overdeck/bin/heartbeat-hook` via `pan sync`. It's also installed automatically when you install or upgrade Overdeck via npm.

**Manual installation:**

```bash theme={null}
pan sync  # Syncs all skills, agents, AND hooks
```

**Hook configuration in `~/.claude/settings.json`:**

```json theme={null}
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "~/.overdeck/bin/heartbeat-hook"
          }
        ]
      }
    ]
  }
}
```

**Hook resilience:** The heartbeat hook is designed to fail silently if:

* The heartbeats directory doesn't exist
* Write permissions are missing
* The hook script has errors

This prevents hook failures from interrupting agent work.

If heartbeats stop arriving — or any other part of the lifecycle plumbing drifts
— the dashboard's Health page surfaces it. Its system health checks and
diagnostics cover the same hooks, sockets, and services Cloister depends on, so
you can confirm the monitoring stack itself is sound before trusting the
stuck-detection signals it produces.

<ThemedImage light="/images/dashboard/health-light.png" dark="/images/dashboard/health-dark.png" alt="Health page showing system health checks and diagnostics for Overdeck's services and agent monitoring plumbing" />

## Configuration

Cloister configuration lives in `~/.overdeck/cloister/config.json`:

```json theme={null}
{
  "monitoring": {
    "heartbeat_interval_ms": 5000,
    "stuck_threshold_minutes": 30,
    "health_check_interval_ms": 30000
  },
  "specialists": {
    "review_agent": { "enabled": true, "auto_wake": false },
    "test_agent": { "enabled": true, "auto_wake": true },
    "inspect_agent": { "enabled": true },
    "uat_agent": { "enabled": true },
    "merge_agent": { "enabled": true, "auto_wake": false }
  },
  "triggers": {
    "stuck_escalation": { "enabled": true },
    "complexity_upgrade": { "enabled": true }
  }
}
```

## Model Routing & Complexity Detection

Cloister automatically routes tasks to the appropriate model based on detected complexity, optimizing for cost while ensuring quality. Model routing supports multiple providers: Anthropic, OpenAI, Google, Kimi, and Zhipu.

### Complexity Levels

| Level       | Default Model | Use Case                                         |
| ----------- | ------------- | ------------------------------------------------ |
| **trivial** | Haiku         | Typos, comments, documentation updates           |
| **simple**  | Haiku         | Small fixes, test additions, minor changes       |
| **medium**  | Kimi          | Features, components, integrations               |
| **complex** | Kimi          | Refactors, migrations, redesigns                 |
| **expert**  | Opus          | Architecture, security, performance optimization |

The default implementation model is configurable per-project. Kimi is the current default for medium/complex tasks, providing a cost-effective alternative to Sonnet with strong coding performance.

### Complexity Detection Signals

Complexity is detected from multiple signals (in priority order):

1. **Explicit field** - Task has a `complexity` field set (e.g., in beads)
2. **Labels/tags** - Issue labels like `architecture`, `security`, `refactor`
3. **Keywords** - Title/description contains keywords like "migration", "overhaul"
4. **File count** - Number of files changed (>20 files = complex)
5. **Time estimate** - If estimate exceeds thresholds

**Keyword patterns:**

```javascript theme={null}
{
  trivial: ['typo', 'rename', 'comment', 'documentation', 'readme'],
  simple: ['add comment', 'update docs', 'fix typo', 'small fix'],
  medium: ['feature', 'endpoint', 'component', 'service'],
  complex: ['refactor', 'migration', 'redesign', 'overhaul'],
  expert: ['architecture', 'security', 'performance optimization']
}
```

### Configuring Model Routing

Model routing is configured via the dashboard Settings page or `~/.overdeck/cloister/config.json`:

```json theme={null}
{
  "model_selection": {
    "default_model": "kimi-k2.5",
    "complexity_routing": {
      "trivial": "haiku",
      "simple": "haiku",
      "medium": "kimi-k2.5",
      "complex": "kimi-k2.5",
      "expert": "opus"
    }
  }
}
```

### Supported Providers

| Provider      | Models              | Use Case                                |
| ------------- | ------------------- | --------------------------------------- |
| **Anthropic** | Opus, Sonnet, Haiku | Planning (Opus), review, general        |
| **OpenAI**    | GPT-4o, o1          | Alternative implementation              |
| **Google**    | Gemini              | Alternative implementation              |
| **Kimi**      | Kimi K2.5           | Cost-effective implementation (default) |
| **Zhipu**     | GLM-4               | Alternative implementation              |

### Cost Optimization

Model routing helps optimize costs:

| Model  | Relative Cost | Best For                               |
| ------ | ------------- | -------------------------------------- |
| Haiku  | 1x (cheapest) | Simple tasks, bulk operations          |
| Kimi   | \~2x          | Most implementation work (default)     |
| Sonnet | 3x            | Review, complex implementation         |
| Opus   | 15x           | Planning, architecture, critical fixes |

A typical agent run might:

1. Plan with Opus (high-quality strategic decisions)
2. Implement with Kimi (cost-effective coding)
3. Escalate to Opus only if stuck or complexity detected

## Related Guides

* [Specialists](/features/specialists) - Detailed specialist agent documentation
* [Convoys](/features/convoys) - Multi-agent orchestration
* [Core Commands](/cli/core-commands) - Cloister CLI commands
