Skip to main content

codetether_agent/tool/
ralph.rs

1//! Ralph Tool - Autonomous PRD-driven agent loop
2//!
3//! Exposes the Ralph loop as a tool for agents to invoke.
4
5use anyhow::{Context, Result};
6use async_trait::async_trait;
7use serde::Deserialize;
8use serde_json::{Value, json};
9use std::path::PathBuf;
10use std::process::Command;
11use std::sync::Arc;
12
13use super::{Tool, ToolResult};
14use crate::provider::Provider;
15use crate::ralph::{Prd, RalphConfig, RalphLoop, create_prd_template};
16use crate::worktree::WorktreeManager;
17
18/// Tool for running the Ralph autonomous agent loop
19pub struct RalphTool {
20    provider: Option<Arc<dyn Provider>>,
21    model: String,
22}
23
24impl RalphTool {
25    pub fn new() -> Self {
26        Self {
27            provider: None,
28            model: String::new(),
29        }
30    }
31
32    /// Create with a specific provider and model
33    pub fn with_provider(provider: Arc<dyn Provider>, model: String) -> Self {
34        Self {
35            provider: Some(provider),
36            model,
37        }
38    }
39
40    /// Set the provider after construction
41    #[allow(dead_code)]
42    pub fn set_provider(&mut self, provider: Arc<dyn Provider>, model: String) {
43        self.provider = Some(provider);
44        self.model = model;
45    }
46}
47
48#[derive(Deserialize)]
49struct Params {
50    action: String,
51    #[serde(default)]
52    prd_path: Option<String>,
53    #[serde(default)]
54    feature: Option<String>,
55    #[serde(default)]
56    project: Option<String>,
57    #[serde(default)]
58    max_iterations: Option<usize>,
59}
60
61#[async_trait]
62impl Tool for RalphTool {
63    fn id(&self) -> &str {
64        "ralph"
65    }
66    fn name(&self) -> &str {
67        "Ralph Agent"
68    }
69
70    fn description(&self) -> &str {
71        r#"Run the Ralph autonomous agent loop to implement user stories from a PRD.
72
73Ralph is an autonomous AI agent loop that runs repeatedly until all PRD items are complete.
74Each iteration is a fresh instance with clean context. Memory persists via:
75- Git history (commits from previous iterations)
76- progress.txt (learnings and context)
77- prd.json (which stories are done)
78
79After completion, Ralph:
80- Cleans up orphaned worktrees and branches
81- Returns to your original branch
82- Provides next steps (merge instructions or retry guidance)
83
84The calling agent should handle the final merge based on the result metadata.
85
86Actions:
87- run: Start the Ralph loop with a PRD file
88- status: Check progress of current Ralph run
89- create-prd: Create a new PRD template
90
91Returns metadata: {all_passed, ready_to_merge, feature_branch, passed, total}
92"#
93    }
94
95    fn parameters(&self) -> Value {
96        json!({
97            "type": "object",
98            "properties": {
99                "action": {
100                    "type": "string",
101                    "enum": ["run", "status", "create-prd"],
102                    "description": "Action to perform"
103                },
104                "prd_path": {
105                    "type": "string",
106                    "description": "Path to prd.json file (default: prd.json)"
107                },
108                "feature": {
109                    "type": "string",
110                    "description": "Feature name for create-prd action"
111                },
112                "project": {
113                    "type": "string",
114                    "description": "Project name for create-prd action"
115                },
116                "max_iterations": {
117                    "type": "integer",
118                    "description": "Maximum iterations for run action (default: 10)"
119                }
120            },
121            "required": ["action"]
122        })
123    }
124
125    async fn execute(&self, params: Value) -> Result<ToolResult> {
126        let p: Params = serde_json::from_value(params).context("Invalid params")?;
127        let prd_path = PathBuf::from(p.prd_path.unwrap_or_else(|| "prd.json".to_string()));
128
129        match p.action.as_str() {
130            "run" => {
131                let provider = self
132                    .provider
133                    .as_ref()
134                    .ok_or_else(|| anyhow::anyhow!("No provider configured for Ralph"))?;
135
136                // Remember the starting branch so we can return to it
137                let cwd = std::env::current_dir().unwrap_or_default();
138                let starting_branch = get_current_branch(&cwd);
139
140                let config = RalphConfig {
141                    prd_path: prd_path.to_string_lossy().to_string(),
142                    max_iterations: p.max_iterations.unwrap_or(10),
143                    progress_path: "progress.txt".to_string(),
144                    quality_checks_enabled: true,
145                    auto_commit: true,
146                    model: Some(self.model.clone()),
147                    use_rlm: false,
148                    parallel_enabled: true,
149                    max_concurrent_stories: 3,
150                    worktree_enabled: true,
151                };
152
153                let mut ralph = RalphLoop::new(
154                    prd_path.clone(),
155                    Arc::clone(provider),
156                    self.model.clone(),
157                    config,
158                )
159                .await
160                .context("Failed to initialize Ralph")?;
161
162                let state = ralph.run().await.context("Ralph loop failed")?;
163
164                let passed_count = state.prd.passed_count();
165                let total_count = state.prd.user_stories.len();
166                let feature_branch = state.prd.branch_name.clone();
167                let all_passed = passed_count == total_count;
168
169                // Clean up orphaned worktrees/branches
170                let cleanup_count = if let Ok(mgr) = WorktreeManager::new(&cwd) {
171                    mgr.cleanup_all().unwrap_or(0)
172                } else {
173                    0
174                };
175
176                // Return to starting branch if different
177                let returned_to_original = if let Some(ref start) = starting_branch {
178                    if !feature_branch.is_empty() && start != &feature_branch {
179                        let _ = Command::new("git")
180                            .args(["checkout", start])
181                            .current_dir(&cwd)
182                            .output();
183                        true
184                    } else {
185                        false
186                    }
187                } else {
188                    false
189                };
190
191                // Build the output with next steps guidance
192                let next_steps = if all_passed {
193                    format!(
194                        "\n## Next Steps\n\n1. Review the changes on branch `{}`\n2. Create a pull request or merge to main:\n   ```bash\n   git checkout main && git merge {} --no-ff\n   ```\n3. Push the changes:\n   ```bash\n   git push\n   ```",
195                        feature_branch, feature_branch
196                    )
197                } else {
198                    let failed_stories: Vec<_> = state
199                        .prd
200                        .user_stories
201                        .iter()
202                        .filter(|s| !s.passes)
203                        .map(|s| format!("- {}: {}", s.id, s.title))
204                        .collect();
205                    format!(
206                        "\n## Incomplete Stories\n\n{}\n\n## Next Steps\n\n1. Review progress.txt for learnings\n2. Either:\n   - Re-run Ralph: `ralph({{action: 'run', prd_path: '{}'}})`\n   - Fix manually on branch `{}`\n   - Reset PRD to retry: edit {} and set `passes: false`",
207                        failed_stories.join("\n"),
208                        prd_path.display(),
209                        feature_branch,
210                        prd_path.display()
211                    )
212                };
213
214                let cleanup_note = if cleanup_count > 0 {
215                    format!(
216                        "\n\n*(Cleaned up {} orphaned worktree(s)/branch(es))*",
217                        cleanup_count
218                    )
219                } else {
220                    String::new()
221                };
222
223                let branch_note = if returned_to_original {
224                    format!(
225                        "\n*(Returned to branch: {})*",
226                        starting_branch.as_deref().unwrap_or("main")
227                    )
228                } else {
229                    String::new()
230                };
231
232                let output = format!(
233                    "# Ralph {:?}\n\n**Project:** {}\n**Feature:** {}\n**Progress:** {}/{} stories\n**Iterations:** {}/{}\n**Feature Branch:** {}\n\n## Stories\n{}{}{}\n{}",
234                    state.status,
235                    state.prd.project,
236                    state.prd.feature,
237                    passed_count,
238                    total_count,
239                    state.current_iteration,
240                    state.max_iterations,
241                    feature_branch,
242                    state
243                        .prd
244                        .user_stories
245                        .iter()
246                        .map(|s| format!(
247                            "- [{}] {}: {}",
248                            if s.passes { "x" } else { " " },
249                            s.id,
250                            s.title
251                        ))
252                        .collect::<Vec<_>>()
253                        .join("\n"),
254                    cleanup_note,
255                    branch_note,
256                    next_steps
257                );
258
259                if all_passed {
260                    Ok(ToolResult::success(output)
261                        .with_metadata("status", json!(format!("{:?}", state.status)))
262                        .with_metadata("passed", json!(passed_count))
263                        .with_metadata("total", json!(total_count))
264                        .with_metadata("feature_branch", json!(feature_branch))
265                        .with_metadata("all_passed", json!(true))
266                        .with_metadata("ready_to_merge", json!(true)))
267                } else {
268                    Ok(ToolResult::error(output)
269                        .with_metadata("status", json!(format!("{:?}", state.status)))
270                        .with_metadata("passed", json!(passed_count))
271                        .with_metadata("total", json!(total_count))
272                        .with_metadata("feature_branch", json!(feature_branch))
273                        .with_metadata("all_passed", json!(false))
274                        .with_metadata("ready_to_merge", json!(false)))
275                }
276            }
277
278            "status" => match Prd::load(&prd_path).await {
279                Ok(prd) => {
280                    let passed_count = prd.passed_count();
281                    let output = format!(
282                        "# Ralph Status\n\n**Project:** {}\n**Feature:** {}\n**Progress:** {}/{} stories\n\n## Stories\n{}",
283                        prd.project,
284                        prd.feature,
285                        passed_count,
286                        prd.user_stories.len(),
287                        prd.user_stories
288                            .iter()
289                            .map(|s| format!(
290                                "- [{}] {}: {}",
291                                if s.passes { "x" } else { " " },
292                                s.id,
293                                s.title
294                            ))
295                            .collect::<Vec<_>>()
296                            .join("\n")
297                    );
298                    Ok(ToolResult::success(output))
299                }
300                Err(_) => Ok(ToolResult::error(format!(
301                    "No PRD found at {}. Create one with: ralph({{action: 'create-prd', project: '...', feature: '...'}})",
302                    prd_path.display()
303                ))),
304            },
305
306            "create-prd" => {
307                let project = p.project.unwrap_or_else(|| "MyProject".to_string());
308                let feature = p.feature.unwrap_or_else(|| "New Feature".to_string());
309
310                let prd = create_prd_template(&project, &feature);
311
312                prd.save(&prd_path).await.context("Failed to save PRD")?;
313
314                let output = format!(
315                    "# PRD Created\n\nSaved to: {}\n\n**Project:** {}\n**Feature:** {}\n**Branch:** {}\n\nEdit the file to add your user stories, then run:\n```\nralph({{action: 'run'}})\n```",
316                    prd_path.display(),
317                    prd.project,
318                    prd.feature,
319                    prd.branch_name
320                );
321
322                Ok(ToolResult::success(output))
323            }
324
325            _ => Ok(ToolResult::error(format!(
326                "Unknown action: {}. Valid actions: run, status, create-prd",
327                p.action
328            ))),
329        }
330    }
331}
332
333/// Get the current git branch name
334fn get_current_branch(dir: &std::path::Path) -> Option<String> {
335    Command::new("git")
336        .args(["rev-parse", "--abbrev-ref", "HEAD"])
337        .current_dir(dir)
338        .output()
339        .ok()
340        .and_then(|o| {
341            if o.status.success() {
342                Some(String::from_utf8_lossy(&o.stdout).trim().to_string())
343            } else {
344                None
345            }
346        })
347}