Skip to main content

takopi-ralph

Autonomous coding loop plugin for takopi

Ship features while you sleep. Ralph runs AI agents in a loop until all tasks are complete, with built-in safeguards to prevent runaway execution.


Requirements

Dependency Version Purpose
Python 3.14+ Runtime
takopi >= 0.15 Telegram bot framework
Claude Code CLI Latest AI agent backend
Git Any File change detection

Quick Start

1. Install

uv tool install takopi-ralph

Or from source:

git clone https://github.com/l3wi/takopi-ralph
cd takopi-ralph
uv pip install -e .

2. Configure

Add to ~/.takopi/takopi.toml:

[ralph]
max_loops = 100

3. Initialize

Start takopi and send:

/ralph init

Answer the interactive questions to generate your prd.json.

4. Start

/ralph start

Ralph will autonomously implement each user story until complete.


Lifecycle

┌─────────────────────────────────────────────────────────────────────────┐
│                              LIFECYCLE                                   │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                          │
│  INIT                         LOOP                         EXIT          │
│  ────                         ────                         ────          │
│                                                                          │
│  /ralph init                  /ralph start                 Automatic     │
│       │                            │                            │        │
│       ▼                            ▼                            │        │
│  ┌─────────┐                 ┌───────────┐                      │        │
│  │ Answer  │                 │ Load PRD  │◄─────────────────────┤        │
│  │questions│                 │ next_story│                      │        │
│  └────┬────┘                 └─────┬─────┘                      │        │
│       │                            │                            │        │
│       ▼                            ▼                            │        │
│  ┌─────────┐                 ┌───────────┐                      │        │
│  │ Generate│                 │  Augment  │                      │        │
│  │ prd.json│                 │  prompt   │                      │        │
│  └─────────┘                 └─────┬─────┘                      │        │
│                                    │                            │        │
│                                    ▼                            │        │
│                              ┌───────────┐                      │        │
│                              │ Run Claude│                      │        │
│                              │    CLI    │                      │        │
│                              └─────┬─────┘                      │        │
│                                    │                            │        │
│                                    ▼                            │        │
│                              ┌───────────┐     ┌────────────┐   │        │
│                              │  Analyze  │────►│  Update    │   │        │
│                              │ response  │     │circuit brkr│   │        │
│                              └─────┬─────┘     └────────────┘   │        │
│                                    │                            │        │
│                                    ▼                            │        │
│                              ┌───────────┐                      │        │
│                              │Exit signal│──────────────────────┘        │
│                              │  check    │                               │
│                              └─────┬─────┘                               │
│                                    │ no                                  │
│                                    ▼                                     │
│                               Loop again                                 │
│                                                                          │
└─────────────────────────────────────────────────────────────────────────┘

Init Phase

  1. /ralph init starts an interactive session
  2. Questions cover: core requirements, target users, integrations, edge cases, quality level
  3. Answers are used to generate prd.json with user stories

Loop Phase

  1. Load prd.json and find the next incomplete story
  2. Augment the prompt with Ralph instructions and RALPH_STATUS block requirements
  3. Run Claude CLI with the augmented prompt
  4. Parse the ---RALPH_STATUS--- block from Claude's response
  5. Update circuit breaker state based on file changes and errors
  6. Check exit conditions

Exit Conditions

  • EXIT_SIGNAL: true in status block
  • All stories have passes: true
  • Circuit breaker is OPEN
  • Max loops reached
  • 3+ consecutive test-only loops (test saturation)

Context Targeting

Ralph supports targeting different projects and branches:

/ralph [project] [@branch] <command>

Examples

Command Description
/ralph start Current directory
/ralph myproject start Specific project
/ralph @feature start Current project, feature worktree
/ralph myproject @feature prd Project on feature branch

How It Works

  1. Project resolution: Takopi resolves project aliases from your takopi.toml
  2. Branch resolution: @branch targets git worktrees managed by takopi
  3. Fallback: Without project/branch, uses current working directory

Project Configuration

Projects are defined in your takopi config:

[projects.myproject]
path = "/path/to/myproject"

Commands

Command Description
/ralph init Interactive project setup
/ralph prd Show PRD status and progress
/ralph prd init <desc> Create PRD from description
/ralph prd clarify [focus] Analyze and improve PRD
/ralph start Start the autonomous loop
/ralph status Show loop progress and circuit state
/ralph stop Gracefully stop the loop
/ralph reset Reset circuit breaker
/ralph reset --all Reset circuit breaker and clear state
/ralph help Show command help

Monitoring Status

Check Progress

/ralph status

Returns:

  • Current loop number
  • Stories completed / total
  • Circuit breaker state (CLOSED/HALF_OPEN/OPEN)
  • Last work type (IMPLEMENTATION/TESTING/etc.)
  • Recent file changes

State Files

Ralph creates a .ralph/ directory in your project:

File Purpose
state.json Loop state, history, exit reason
session.json Claude session ID for continuations
circuit_breaker.json Circuit state and thresholds
clarify_sessions.json Active clarify sessions

Debugging Stuck Loops

  1. Check /ralph status for circuit breaker state
  2. Review .ralph/state.json for loop history
  3. Look at recent RALPH_STATUS blocks in conversation
  4. If circuit breaker is OPEN, run /ralph reset

Configuration

Add to ~/.takopi/takopi.toml:

[ralph]
# Maximum loop iterations before forced exit
max_loops = 100

# Path to prd.json relative to project root
prd_path = "prd.json"

# Directory for Ralph state files
state_dir = ".ralph"

# Inner engine to use (only "claude" supported currently)
engine = "claude"

All options have sensible defaults. Minimal config:

[ralph]
max_loops = 100

PRD Format

The Product Requirements Document (prd.json) tracks user stories:

{
  "project_name": "My App",
  "description": "A task management application",
  "created_at": "2026-01-10T12:00:00Z",
  "branch_name": null,
  "quality_level": "production",
  "feedback_commands": {
    "typecheck": "bun run typecheck",
    "test": "bun run test",
    "lint": "bun run lint"
  },
  "stories": [
    {
      "id": 1,
      "title": "Project Setup",
      "description": "Initialize project with basic structure",
      "acceptance_criteria": [
        "Project structure created",
        "Dependencies installed"
      ],
      "passes": false,
      "priority": 1,
      "notes": ""
    }
  ]
}

Story Fields

Field Type Description
id int Unique story identifier
title string Short story title
description string Detailed description
acceptance_criteria string[] Conditions for completion
passes bool Whether story is complete
priority int Execution order (lower = higher priority)
notes string Optional notes from implementation

Quality Levels

Level Description
prototype Quick implementation, minimal tests
production Full implementation with tests
library Library-grade with comprehensive tests and docs

Feedback Commands

Customize validation commands for your stack:

{
  "feedback_commands": {
    "typecheck": "bun run typecheck",
    "test": "pytest -q",
    "lint": "ruff check ."
  }
}

RALPH_STATUS Block

Claude must include this block at the end of each response:

---RALPH_STATUS---
STATUS: IN_PROGRESS | COMPLETE | BLOCKED
TASKS_COMPLETED_THIS_LOOP: <number>
FILES_MODIFIED: <number>
TESTS_STATUS: PASSING | FAILING | NOT_RUN
WORK_TYPE: IMPLEMENTATION | TESTING | DOCUMENTATION | REFACTORING
EXIT_SIGNAL: false | true
RECOMMENDATION: <one-line summary of what to do next>
---END_RALPH_STATUS---

Exit Signal Conditions

Set EXIT_SIGNAL: true when:

  • All stories in prd.json have passes: true
  • All tests are passing
  • No errors in the last execution
  • Nothing meaningful left to implement

Circuit Breaker

Prevents runaway token consumption using a state machine:

CLOSED ──(2 loops no progress)──► HALF_OPEN ──(threshold)──► OPEN
   ▲                                    │
   └────(progress detected)─────────────┘

States

State Description
CLOSED Normal operation, loop continues
HALF_OPEN Warning state, monitoring for progress
OPEN Loop halted, requires manual reset

Thresholds

Threshold Default Description
No progress 3 Opens after N loops with no file changes
Same error 5 Opens after N loops with repeated errors

Reset

/ralph reset         # Reset circuit breaker only
/ralph reset --all   # Reset circuit breaker and clear all state

File Structure

After running Ralph, your project will have:

my-project/
├── prd.json                    # User stories (from /ralph init)
├── .ralph/
│   ├── state.json              # Loop state and history
│   ├── session.json            # Claude session ID
│   ├── circuit_breaker.json    # Circuit breaker state
│   └── clarify_sessions.json   # Active clarify sessions
└── ... your project files

Troubleshooting

Circuit Breaker is OPEN

The circuit breaker opens when:

  • No file changes for 3+ consecutive loops
  • Same error repeated 5+ times

Fix:

/ralph reset

No RALPH_STATUS Block

If Claude doesn't include the status block, the analyzer falls back to text analysis. Check:

  1. The prompt template includes status block instructions
  2. Claude isn't truncating the response

Loop Exits Immediately

Check:

  1. prd.json exists and has stories with passes: false
  2. Circuit breaker is CLOSED (/ralph status)
  3. No syntax errors in prd.json

Clarify Session Expired

Clarify sessions are stored temporarily. Start a new one:

/ralph init

Development

Setup

git clone https://github.com/l3wi/takopi-ralph
cd takopi-ralph
uv sync --dev

Commands

uv run pytest              # Run tests with coverage
uv run ruff check .        # Lint
uv run ruff format .       # Format

Package Structure

src/takopi_ralph/
├── engine/              # Engine backend (RalphRunner)
├── command/             # Command backend (/ralph)
│   └── handlers/        # Subcommand handlers
├── prd/                 # prd.json management
├── state/               # Loop state persistence
├── circuit_breaker/     # Runaway protection
├── analysis/            # Response parsing
├── clarify/             # Interactive requirements
│   └── templates/       # Prompt templates
└── init/                # Initialization flow

License

MIT


Credits

Metadata

Release files for takopi-ralph 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for takopi-ralph 0.3.0
File Size Uploaded
takopi_ralph-0.3.0.tar.gz 42.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for takopi-ralph 0.3.0
File Interpreter ABI Platform
takopi_ralph-0.3.0-py3-none-any.whl Python 3 none any Details

Total release size: 99.1 kB

Release files / takopi_ralph-0.3.0.tar.gz

Download URL takopi_ralph-0.3.0.tar.gz
Size 42.1 kB
Tags Source
SHA-256 checksum
How to use checksums
2578146aa10b561142bdbd64a2ee7c0a7f6c293419cabaa472c955ba4ad3fae3
BLAKE2b-256 checksum
How to use checksums
38e1f1c47c6b866dc1374ef802f65d49f9ffbc25a00650ab06bbe256e6c1a3e4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jan 11, 2026.

Transparency log

Release files / takopi_ralph-0.3.0-py3-none-any.whl

Download URL takopi_ralph-0.3.0-py3-none-any.whl
Size 57.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
72834b4a1ab095c0db90c749b7bfa084f4bf8942308de3f499e712cb175f947d
BLAKE2b-256 checksum
How to use checksums
bbebe7fd47f2a4c8458137a32814a43862c1a234c30c79cd61dc940b89a0cd20
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jan 11, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.3.0 This release

2 release files

0.2.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page