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                    story_timeout_secs: 300,
152                    conflict_timeout_secs: 120,
153                };
154
155                let mut ralph = RalphLoop::new(
156                    prd_path.clone(),
157                    Arc::clone(provider),
158                    self.model.clone(),
159                    config,
160                )
161                .await
162                .context("Failed to initialize Ralph")?;
163
164                let state = ralph.run().await.context("Ralph loop failed")?;
165
166                let passed_count = state.prd.passed_count();
167                let total_count = state.prd.user_stories.len();
168                let feature_branch = state.prd.branch_name.clone();
169                let all_passed = passed_count == total_count;
170
171                // Clean up orphaned worktrees/branches
172                let cleanup_count = if let Ok(mgr) = WorktreeManager::new(&cwd) {
173                    mgr.cleanup_all().unwrap_or(0)
174                } else {
175                    0
176                };
177
178                // Return to starting branch if different
179                let returned_to_original = if let Some(ref start) = starting_branch {
180                    if !feature_branch.is_empty() && start != &feature_branch {
181                        let _ = Command::new("git")
182                            .args(["checkout", start])
183                            .current_dir(&cwd)
184                            .output();
185                        true
186                    } else {
187                        false
188                    }
189                } else {
190                    false
191                };
192
193                // Build the output with next steps guidance
194                let next_steps = if all_passed {
195                    format!(
196                        "\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   ```",
197                        feature_branch, feature_branch
198                    )
199                } else {
200                    let failed_stories: Vec<_> = state
201                        .prd
202                        .user_stories
203                        .iter()
204                        .filter(|s| !s.passes)
205                        .map(|s| format!("- {}: {}", s.id, s.title))
206                        .collect();
207                    format!(
208                        "\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`",
209                        failed_stories.join("\n"),
210                        prd_path.display(),
211                        feature_branch,
212                        prd_path.display()
213                    )
214                };
215
216                let cleanup_note = if cleanup_count > 0 {
217                    format!(
218                        "\n\n*(Cleaned up {} orphaned worktree(s)/branch(es))*",
219                        cleanup_count
220                    )
221                } else {
222                    String::new()
223                };
224
225                let branch_note = if returned_to_original {
226                    format!(
227                        "\n*(Returned to branch: {})*",
228                        starting_branch.as_deref().unwrap_or("main")
229                    )
230                } else {
231                    String::new()
232                };
233
234                let output = format!(
235                    "# Ralph {:?}\n\n**Project:** {}\n**Feature:** {}\n**Progress:** {}/{} stories\n**Iterations:** {}/{}\n**Feature Branch:** {}\n\n## Stories\n{}{}{}\n{}",
236                    state.status,
237                    state.prd.project,
238                    state.prd.feature,
239                    passed_count,
240                    total_count,
241                    state.current_iteration,
242                    state.max_iterations,
243                    feature_branch,
244                    state
245                        .prd
246                        .user_stories
247                        .iter()
248                        .map(|s| format!(
249                            "- [{}] {}: {}",
250                            if s.passes { "x" } else { " " },
251                            s.id,
252                            s.title
253                        ))
254                        .collect::<Vec<_>>()
255                        .join("\n"),
256                    cleanup_note,
257                    branch_note,
258                    next_steps
259                );
260
261                if all_passed {
262                    Ok(ToolResult::success(output)
263                        .with_metadata("status", json!(format!("{:?}", state.status)))
264                        .with_metadata("passed", json!(passed_count))
265                        .with_metadata("total", json!(total_count))
266                        .with_metadata("feature_branch", json!(feature_branch))
267                        .with_metadata("all_passed", json!(true))
268                        .with_metadata("ready_to_merge", json!(true)))
269                } else {
270                    Ok(ToolResult::error(output)
271                        .with_metadata("status", json!(format!("{:?}", state.status)))
272                        .with_metadata("passed", json!(passed_count))
273                        .with_metadata("total", json!(total_count))
274                        .with_metadata("feature_branch", json!(feature_branch))
275                        .with_metadata("all_passed", json!(false))
276                        .with_metadata("ready_to_merge", json!(false)))
277                }
278            }
279
280            "status" => match Prd::load(&prd_path).await {
281                Ok(prd) => {
282                    let passed_count = prd.passed_count();
283                    let output = format!(
284                        "# Ralph Status\n\n**Project:** {}\n**Feature:** {}\n**Progress:** {}/{} stories\n\n## Stories\n{}",
285                        prd.project,
286                        prd.feature,
287                        passed_count,
288                        prd.user_stories.len(),
289                        prd.user_stories
290                            .iter()
291                            .map(|s| format!(
292                                "- [{}] {}: {}",
293                                if s.passes { "x" } else { " " },
294                                s.id,
295                                s.title
296                            ))
297                            .collect::<Vec<_>>()
298                            .join("\n")
299                    );
300                    Ok(ToolResult::success(output))
301                }
302                Err(_) => Ok(ToolResult::error(format!(
303                    "No PRD found at {}. Create one with: ralph({{action: 'create-prd', project: '...', feature: '...'}})",
304                    prd_path.display()
305                ))),
306            },
307
308            "create-prd" => {
309                let project = p.project.unwrap_or_else(|| "MyProject".to_string());
310                let feature = p.feature.unwrap_or_else(|| "New Feature".to_string());
311
312                let prd = create_prd_template(&project, &feature);
313
314                prd.save(&prd_path).await.context("Failed to save PRD")?;
315
316                let output = format!(
317                    "# 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```",
318                    prd_path.display(),
319                    prd.project,
320                    prd.feature,
321                    prd.branch_name
322                );
323
324                Ok(ToolResult::success(output))
325            }
326
327            _ => Ok(ToolResult::error(format!(
328                "Unknown action: {}. Valid actions: run, status, create-prd",
329                p.action
330            ))),
331        }
332    }
333}
334
335/// Get the current git branch name
336fn get_current_branch(dir: &std::path::Path) -> Option<String> {
337    Command::new("git")
338        .args(["rev-parse", "--abbrev-ref", "HEAD"])
339        .current_dir(dir)
340        .output()
341        .ok()
342        .and_then(|o| {
343            if o.status.success() {
344                Some(String::from_utf8_lossy(&o.stdout).trim().to_string())
345            } else {
346                None
347            }
348        })
349}