An AI agent built to do Ralph loops - plan mode for planning and ralph mode for implementing.
1# Rustagent
2
3**It's a pun on rustacean.**
4
5Rustagent is an AI agent framework for autonomous task execution in Rust. It uses a two-phase approach: a Planning Agent that breaks down high-level goals into executable tasks, and the Ralph Loop that executes those tasks iteratively with tool access.
6
7The canonical [repository](https://tangled.org/dathagerty.com/rustagent) for this project is on [tangled.org](https://tangled.org).
8It is [mirrored](https://github.com/dathagerty/rustagent) on [GitHub](https://github.com) for discoverability.
9
10## Features
11
12- **Interactive TUI**: Terminal user interface built with ratatui for managing specs and monitoring agent execution
13- **Planning Agent**: Converts high-level specifications into structured execution plans
14- **Ralph Loop**: Autonomous execution agent with Read-Act-Learn-Plan-Help cycle
15- **Multiple LLM Support**: Works with Anthropic (Claude), OpenAI (GPT), and Ollama (local models)
16- **Tool System**: Extensible tools for file operations and shell commands with security validation
17- **Permission System**: CLI prompts for sensitive operations with path and command validation
18- **Structured Specs**: JSON-based specification format with tasks, acceptance criteria, and learnings
19
20## Installation
21
22### Prerequisites
23
24- Rust 1.85.0 or later (for Rust edition 2024 support)
25- An API key for your chosen LLM provider (or Ollama running locally)
26
27### Build from Source
28
29```bash
30# Clone the repository
31git clone https://github.com/yourusername/rustagent.git
32cd rustagent
33
34# Build the project
35cargo build --release
36
37# The binary will be available at target/release/rustagent
38```
39
40### Install Locally
41
42```bash
43cargo install --path .
44```
45
46## Configuration
47
48Rustagent looks for configuration files in the following locations (in order):
49
501. `./rustagent.toml` (current directory)
512. `~/.config/rustagent/config.toml` (XDG config directory)
523. `~/.rustagent/config.toml` (home directory)
53
54### Create Configuration File
55
56Copy the example configuration and customize it:
57
58```bash
59cp rustagent.toml.example rustagent.toml
60```
61
62### Configuration Format
63
64```toml
65# LLM Configuration (required)
66[llm]
67provider = "anthropic" # Options: "anthropic", "openai", "ollama"
68model = "claude-sonnet-4-20250514"
69max_tokens = 8192 # Maximum tokens per response
70
71# Provider-specific configuration
72[anthropic]
73api_key = "${ANTHROPIC_API_KEY}" # Environment variable substitution
74
75# Agent settings (required)
76[rustagent]
77spec_dir = "specs" # Directory for specification files
78max_iterations = 100 # Optional: limit execution iterations
79
80# Security settings (optional, has safe defaults)
81[security]
82shell_policy = "allowlist" # "allowlist", "blocklist", or "unrestricted"
83allowed_commands = ["git", "cargo", "npm", "ls", "cat", "grep", "find"]
84max_file_size_mb = 10
85allowed_paths = ["."]
86```
87
88### Environment Variables
89
90The config system supports environment variable substitution using `${VAR_NAME}` syntax:
91
92```bash
93# Set your API key
94export ANTHROPIC_API_KEY="your-api-key-here"
95
96# Or for OpenAI
97export OPENAI_API_KEY="your-api-key-here"
98```
99
100### Provider Options
101
102**Anthropic (Claude)**
103```toml
104[llm]
105provider = "anthropic"
106model = "claude-sonnet-4-20250514"
107
108[anthropic]
109api_key = "${ANTHROPIC_API_KEY}"
110```
111
112**OpenAI (GPT)**
113```toml
114[llm]
115provider = "openai"
116model = "gpt-4"
117
118[openai]
119api_key = "${OPENAI_API_KEY}"
120```
121
122**Ollama (Local)**
123```toml
124[llm]
125provider = "ollama"
126model = "llama2"
127
128[ollama]
129base_url = "http://localhost:11434"
130```
131
132### Mode-Specific LLM Overrides
133
134Use different models for planning vs execution:
135
136```toml
137# Default LLM
138[llm]
139provider = "anthropic"
140model = "claude-sonnet-4-20250514"
141
142# Use a more capable model for planning
143[planning.llm]
144provider = "anthropic"
145model = "claude-opus-4-20250514"
146max_tokens = 16384
147
148# Use a faster model for Ralph execution
149[ralph.llm]
150provider = "anthropic"
151model = "claude-sonnet-4-20250514"
152max_tokens = 4096
153```
154
155### Security Configuration
156
157Control what operations the agent can perform:
158
159```toml
160[security]
161# Shell policy options:
162# "allowlist" - Only listed commands can run (default, safest)
163# "blocklist" - All except blocked patterns can run
164# "unrestricted" - All commands can run
165shell_policy = "allowlist"
166
167# Commands allowed when using allowlist policy
168allowed_commands = ["git", "cargo", "npm", "ls", "cat", "grep", "find", "echo", "pwd", "mkdir", "touch"]
169
170# Regex patterns to block when using blocklist policy
171blocked_patterns = ["rm\\s+-rf", "sudo"]
172
173# Maximum file size the agent can write (MB)
174max_file_size_mb = 10
175
176# Paths the agent can access (relative or absolute)
177allowed_paths = ["."]
178```
179
180## Usage
181
182Rustagent provides four commands: `init`, `plan`, `run`, and `tui`. Running `rustagent` without a command launches the TUI by default.
183
184### Interactive TUI
185
186Launch the terminal user interface:
187
188```bash
189rustagent tui
190# or simply
191rustagent
192```
193
194The TUI provides:
195- Spec browsing and management
196- Real-time agent execution monitoring
197- Interactive spec creation and editing
198
199### 1. Initialize a Specification
200
201Create a new agent specification interactively:
202
203```bash
204rustagent init --spec-dir ./specs
205```
206
207This command (when implemented) will help you create the initial spec structure.
208
209### 2. Plan: Generate Execution Tasks
210
211Convert your specification into an execution plan using the Planning Agent:
212
213```bash
214rustagent plan --spec-dir ./specs
215```
216
217The Planning Agent will:
218- Read your high-level specification
219- Break it down into concrete, executable tasks
220- Add acceptance criteria for each task
221- Save the plan as `spec.json` in your spec directory
222
223### 3. Run: Execute the Plan
224
225Execute the generated plan using the Ralph Loop:
226
227```bash
228rustagent run specs/spec.json
229```
230
231With iteration limit:
232
233```bash
234rustagent run specs/spec.json --max-iterations 10
235```
236
237The Ralph Loop will:
238- Read the next pending task
239- Act using available tools to complete the task
240- Learn from the results and update the spec
241- Plan the next action based on learnings
242- Ask for help if blocked (human intervention required)
243- Continue until all tasks are complete or max iterations reached
244
245## How It Works
246
247### Planning Agent
248
249The Planning Agent transforms high-level goals into structured execution plans:
250
2511. **Input**: A specification directory containing your requirements
2522. **Process**: LLM-powered analysis and task decomposition
2533. **Output**: A `spec.json` file with structured tasks
254
255Example flow:
256```
257User Spec → Planning Agent → Structured Tasks → spec.json
258```
259
260### Ralph Loop (Read-Act-Learn-Plan-Help)
261
262The Ralph Loop is the core execution engine:
263
2641. **Read**: Load the spec and find the next pending task
2652. **Act**: Use tools (file operations, shell commands) to work on the task
2663. **Learn**: Analyze results and update learnings in the spec
2674. **Plan**: Determine the next action based on context
2685. **Help**: Ask for human intervention when blocked
269
270The loop continues until:
271- All tasks are complete
272- A task is blocked (requires human help)
273- Maximum iterations reached (if configured)
274
275## Specification Format
276
277Rustagent uses a JSON-based specification format:
278
279```json
280{
281 "name": "implement-user-auth",
282 "description": "Implement user authentication system with JWT",
283 "branch_name": "feature/user-auth",
284 "created_at": "2026-01-20T10:30:00Z",
285 "tasks": [
286 {
287 "id": "task-1",
288 "title": "Create User model",
289 "description": "Define User struct with fields for authentication",
290 "acceptance_criteria": [
291 "User struct has email, password_hash, and created_at fields",
292 "Implements proper serialization/deserialization",
293 "Includes validation for email format"
294 ],
295 "status": "pending",
296 "blocked_reason": null,
297 "completed_at": null
298 }
299 ],
300 "learnings": []
301}
302```
303
304### Task Statuses
305
306- `pending`: Task is ready to be worked on
307- `in_progress`: Task is currently being executed
308- `complete`: Task has been successfully completed
309- `blocked`: Task cannot proceed without human intervention
310
311## Available Tools
312
313Rustagent provides the following tools to agents:
314
315### File Operations
316
317- **read_file**: Read contents of a file
318 ```json
319 {
320 "name": "read_file",
321 "arguments": {
322 "path": "src/main.rs"
323 }
324 }
325 ```
326
327- **write_file**: Write or overwrite file contents
328 ```json
329 {
330 "name": "write_file",
331 "arguments": {
332 "path": "src/config.rs",
333 "content": "// File contents here"
334 }
335 }
336 ```
337
338- **list_files**: List files in a directory
339 ```json
340 {
341 "name": "list_files",
342 "arguments": {
343 "path": "src",
344 "recursive": false
345 }
346 }
347 ```
348
349### Shell Commands
350
351- **run_command**: Execute shell commands
352 ```json
353 {
354 "name": "run_command",
355 "arguments": {
356 "command": "cargo test",
357 "working_dir": "."
358 }
359 }
360 ```
361
362### Task Completion
363
364- **signal_completion**: Signal task completion or blocked status
365 ```json
366 {
367 "name": "signal_completion",
368 "arguments": {
369 "signal": "complete",
370 "message": "Task finished successfully"
371 }
372 }
373 ```
374
375 Or to signal blocked:
376 ```json
377 {
378 "name": "signal_completion",
379 "arguments": {
380 "signal": "blocked",
381 "reason": "Missing required dependency"
382 }
383 }
384 ```
385
386## Development
387
388### Building
389
390```bash
391# Debug build
392cargo build
393
394# Release build with optimizations
395cargo build --release
396
397# Quick compile check
398cargo check
399```
400
401### Code Quality
402
403```bash
404# Format code
405cargo fmt
406
407# Run linter
408cargo clippy
409```
410
411### Testing
412
413```bash
414# Run all tests
415cargo test
416
417# Run with logging
418RUST_LOG=debug cargo test
419
420# Run specific test
421cargo test test_name
422```
423
424### Logging
425
426Rustagent uses `tracing` for file-based logging. Logs are stored in:
427
428- `$XDG_STATE_HOME/rustagent/logs/` (if XDG_STATE_HOME is set)
429- `~/.local/share/rustagent/logs/` (macOS/Linux)
430- `~/.local/state/rustagent/logs/` (fallback)
431
432Logs are rotated daily. To adjust the log level, set the `RUST_LOG` environment variable:
433
434```bash
435RUST_LOG=rustagent=debug cargo run -- plan
436```
437
438### Documentation
439
440```bash
441# Generate and view documentation
442cargo doc --open
443```
444
445### Project Structure
446
447```
448rustagent/
449├── src/
450│ ├── main.rs # CLI entry point with init/plan/run/tui commands
451│ ├── lib.rs # Library exports
452│ ├── config.rs # Configuration loading with env var substitution
453│ ├── logging.rs # File-based tracing with daily rotation
454│ ├── spec.rs # Specification data structures
455│ ├── llm/
456│ │ ├── mod.rs # LlmClient trait and Message types
457│ │ ├── anthropic.rs # Anthropic (Claude) client
458│ │ ├── openai.rs # OpenAI (GPT) client
459│ │ ├── ollama.rs # Ollama (local models) client
460│ │ ├── mock.rs # Mock client for testing
461│ │ └── factory.rs # Client factory based on config
462│ ├── planning/
463│ │ └── mod.rs # Planning Agent implementation
464│ ├── ralph/
465│ │ └── mod.rs # Ralph Loop execution engine
466│ ├── security/
467│ │ ├── mod.rs # Security validator for paths/commands
468│ │ └── permission.rs # Permission handling (CLI prompts)
469│ ├── tools/
470│ │ ├── mod.rs # Tool trait and registry
471│ │ ├── file.rs # read_file, write_file, list_files tools
472│ │ ├── shell.rs # run_command tool
473│ │ ├── signal.rs # signal_completion tool
474│ │ ├── factory.rs # Tool registry factory
475│ │ └── permission_check.rs # File permission checking
476│ └── tui/
477│ ├── mod.rs # TUI module exports and terminal setup
478│ ├── app.rs # Application state and event handling
479│ ├── ui.rs # UI rendering logic
480│ ├── messages.rs # Agent-TUI message channel
481│ ├── views/ # View components (spec list, detail, etc.)
482│ └── widgets/ # Reusable TUI widgets
483├── specs/ # Default directory for specifications
484├── tests/ # Integration tests
485├── Cargo.toml # Package manifest
486└── rustagent.toml # Configuration file (create from example)
487```
488
489## Architecture
490
491Rustagent follows a modular architecture:
492
493- **Config System**: Multi-provider LLM configuration with environment variable support
494- **LLM Clients**: Abstracted clients for different LLM providers (streaming support)
495- **Tool System**: Trait-based tool implementation with dynamic registry (`Arc<RwLock>` for thread safety)
496- **Security Layer**: Path and command validation with interactive permission prompts
497- **Spec Management**: JSON persistence layer for task tracking and learning
498- **TUI**: ratatui-based terminal interface with async agent communication via channels
499- **Agents**: Planning Agent and Ralph Loop for two-phase execution
500
501## Examples
502
503### Example 1: Create a New Feature
504
5051. Create a specification:
506```bash
507mkdir -p specs/add-logging
508echo '{"description": "Add structured logging to the application"}' > specs/add-logging/description.txt
509```
510
5112. Generate execution plan:
512```bash
513rustagent plan --spec-dir specs/add-logging
514```
515
5163. Execute the plan:
517```bash
518rustagent run specs/add-logging/spec.json
519```
520
521### Example 2: Limited Iteration Run
522
523Run with a safety limit on iterations:
524
525```bash
526rustagent run specs/spec.json --max-iterations 5
527```
528
529This will stop after 5 iterations, even if tasks remain pending.
530
531## References
532
533- **Rust Edition 2024**: This project uses Rust edition 2024, stable since Rust 1.85.0
534- **Version Control**: Compatible with both Git and Jujutsu
535- **Anthropic API**: https://docs.anthropic.com/
536- **OpenAI API**: https://platform.openai.com/docs/
537- **Ollama**: https://ollama.ai/
538
539## Contributing
540
541Contributions are welcome! This is an exploration project for implementing AI agents in Rust.
542
543## License
544
545See LICENSE file for details.