ralph_workflow/phases/commit/runner/
attempt.rs1use crate::phases::commit_logging::CommitAttemptLog;
3
4#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum CommitMessageOutcome {
9 Message(String),
11 Skipped { reason: String },
13}
14
15#[derive(Debug)]
17pub struct CommitMessageResult {
18 pub outcome: CommitMessageOutcome,
19}
20
21pub struct CommitAttemptResult {
23 pub had_error: bool,
24 pub output_valid: bool,
25 pub message: Option<String>,
26 pub skip_reason: Option<String>,
27 pub files: Vec<String>,
28 pub excluded_files: Vec<crate::reducer::state::pipeline::ExcludedFile>,
29 pub validation_detail: String,
30 pub auth_failure: bool,
31}
32
33pub fn run_commit_attempt(
52 ctx: &mut PhaseContext<'_>,
53 attempt: u32,
54 model_safe_diff: &str,
55 commit_agent: &str,
56) -> anyhow::Result<CommitAttemptResult> {
57 let (prompt, substitution_log) =
62 build_commit_prompt(ctx.template_context, model_safe_diff, ctx.workspace);
63
64 if !substitution_log.is_complete() {
67 return Err(anyhow::anyhow!(
68 "Commit prompt has unresolved placeholders: {:?}",
69 substitution_log.unsubstituted
70 ));
71 }
72
73 let log_dir = ctx
74 .run_log_context
75 .run_dir()
76 .join("debug")
77 .join("commit_generation");
78 let (session, attempt_number) =
79 crate::phases::commit::create_session_and_get_attempt_number(&log_dir, ctx.workspace);
80 let diff_was_truncated =
81 model_safe_diff.contains("[Truncated:") || model_safe_diff.contains("[truncated...]");
82 let attempt_log = CommitAttemptLog::with_basics(
83 attempt_number,
84 commit_agent,
85 "single",
86 prompt.len(),
87 model_safe_diff.len(),
88 diff_was_truncated,
89 );
90
91 let agent_config = ctx
92 .registry
93 .resolve_config(commit_agent)
94 .ok_or_else(|| anyhow::anyhow!("Agent not found: {commit_agent}"))?;
95 let cmd_str = agent_config.build_cmd_with_model(true, true, true, None);
96
97 let base_log_path = ctx.run_log_context.agent_log("commit", attempt, None);
99 let log_attempt = crate::pipeline::logfile::next_simplified_logfile_attempt_index(
100 &base_log_path,
101 ctx.workspace,
102 );
103 let logfile = if log_attempt == 0 {
104 base_log_path
105 .to_str()
106 .expect("Path contains invalid UTF-8 - all paths in this codebase should be UTF-8")
107 .to_string()
108 } else {
109 ctx.run_log_context
110 .agent_log("commit", attempt, Some(log_attempt))
111 .to_str()
112 .expect("Path contains invalid UTF-8 - all paths in this codebase should be UTF-8")
113 .to_string()
114 };
115
116 let log_header = format!(
119 "# Ralph Agent Invocation Log\n\
120 # Role: Commit\n\
121 # Agent: {}\n\
122 # Model Index: 0\n\
123 # Attempt: {}\n\
124 # Phase: CommitMessage\n\
125 # Timestamp: {}\n\n",
126 commit_agent,
127 log_attempt,
128 chrono::Utc::now().to_rfc3339()
129 );
130 ctx.workspace
131 .append_bytes(std::path::Path::new(&logfile), log_header.as_bytes())
132 .context("Failed to write agent log header - log would be incomplete without metadata")?;
133
134 let log_prefix = format!("commit_{attempt}"); let model_index = 0usize; let prompt_cmd = PromptCommand {
137 label: commit_agent,
138 display_name: commit_agent,
139 cmd_str: &cmd_str,
140 prompt: &prompt,
141 log_prefix: &log_prefix,
142 model_index: Some(model_index),
143 attempt: Some(log_attempt),
144 logfile: &logfile,
145 parser_type: agent_config.json_parser,
146 env_vars: &agent_config.env_vars,
147 };
148
149 let result = run_with_prompt(
150 &prompt_cmd,
151 &mut PipelineRuntime {
152 timer: ctx.timer,
153 logger: ctx.logger,
154 colors: ctx.colors,
155 config: ctx.config,
156 executor: ctx.executor,
157 executor_arc: std::sync::Arc::clone(&ctx.executor_arc),
158 workspace: ctx.workspace,
159 workspace_arc: std::sync::Arc::clone(&ctx.workspace_arc),
160 },
161 )?;
162 let had_error = result.exit_code != 0;
163 let auth_failure = had_error && stderr_contains_auth_error(&result.stderr);
164
165 if auth_failure {
166 let attempt_log = attempt_log.with_raw_output(&result.stderr);
167 if !session.is_noop() {
168 let _ = attempt_log.write_to_workspace(session.run_dir(), ctx.workspace);
169 let _ = session.write_summary(1, "AUTHENTICATION_FAILURE", ctx.workspace);
170 }
171 return Ok(CommitAttemptResult {
172 had_error,
173 output_valid: false,
174 message: None,
175 skip_reason: None,
176 files: vec![],
177 excluded_files: vec![],
178 validation_detail: "Authentication error detected".to_string(),
179 auth_failure: true,
180 });
181 }
182
183 let attempt_log = attempt_log.with_raw_output(&result.stderr);
184
185 let extraction = extract_commit_message_from_file_with_workspace(ctx.workspace);
186 let (outcome, detail, extraction_result, extraction_succeeded, skip_reason, files, excluded) =
187 match extraction {
188 CommitExtractionOutcome::Valid {
189 extracted: result,
190 files,
191 excluded_files,
192 } => (
193 AttemptOutcome::Success(result.clone().into_message()),
194 "Valid commit message extracted".to_string(),
195 Some(result),
196 true,
197 None,
198 files,
199 excluded_files,
200 ),
201 CommitExtractionOutcome::InvalidXml(detail) => (
202 AttemptOutcome::XsdValidationFailed(detail.clone()),
203 detail,
204 None,
205 false,
206 None,
207 vec![],
208 vec![],
209 ),
210 CommitExtractionOutcome::MissingFile(detail) => (
211 AttemptOutcome::ExtractionFailed(detail.clone()),
212 detail,
213 None,
214 false,
215 None,
216 vec![],
217 vec![],
218 ),
219 CommitExtractionOutcome::Skipped(reason) => (
220 AttemptOutcome::Success(format!("SKIPPED: {reason}")),
221 format!("Commit skipped: {reason}"),
222 None,
223 true,
224 Some(reason),
225 vec![],
226 vec![],
227 ),
228 };
229
230 let attempt_log = attempt_log
231 .add_extraction_attempt(if extraction_succeeded {
232 ExtractionAttempt::success("XML", detail.clone())
233 } else {
234 ExtractionAttempt::failure("XML", detail.clone())
235 })
236 .with_outcome(outcome.clone());
237
238 if !session.is_noop() {
239 let _ = attempt_log.write_to_workspace(session.run_dir(), ctx.workspace);
240 let final_outcome = format!("{outcome}");
241 let _ = session.write_summary(1, &final_outcome, ctx.workspace);
242 }
243
244 if let Some(result) = extraction_result {
245 let message = result.into_message();
246 return Ok(CommitAttemptResult {
247 had_error,
248 output_valid: true,
249 message: Some(message),
250 skip_reason: None,
251 files,
252 excluded_files: excluded,
253 validation_detail: detail,
254 auth_failure: false,
255 });
256 }
257
258 Ok(CommitAttemptResult {
259 had_error,
260 output_valid: extraction_succeeded,
261 message: None,
262 skip_reason,
263 files,
264 excluded_files: excluded,
265 validation_detail: detail,
266 auth_failure: false,
267 })
268}