ralph-workflow 0.7.18

PROMPT-driven multi-agent orchestrator for git repos
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
// Fix prompt generation functions for the review module.

/// Format the list of files to modify for the fix mode prompt.
///
/// This function takes a list of file paths and formats them into a string
/// suitable for display in the fix mode prompt templates.
///
/// # Arguments
///
/// * `files` - Slice of file paths that may be modified
///
/// # Returns
///
/// A formatted string listing the files, or a message indicating no specific files were found.
fn format_files_section_xml(files: &[String]) -> String {
    if files.is_empty() {
        "No specific files identified - you may modify any files needed to fix the issues."
            .to_string()
    } else {
        format!("Files identified in issues:\n{}\n\nNOTE: If the issue references a file that is not listed here, you may still modify it.",
            files.iter()
                .map(|f| format!("- {f}"))
                .collect::<Vec<_>>()
                .join("\n"))
    }
}

/// Generate fix prompt with substitution log.
///
/// This is the new log-based version that returns both content and substitution tracking.
/// Use this version in handlers to enable log-based validation.
pub fn prompt_fix_xml_with_log(
    context: &TemplateContext,
    prompt_content: &str,
    plan_content: &str,
    issues_content: &str,
    files_to_modify: &[String],
    workspace: &dyn Workspace,
    template_name: &str,
) -> RenderedTemplate {
    let partials = get_shared_partials();
    let template_content = context
        .registry()
        .get_template("fix_mode_xml")
        .unwrap_or_else(|_| include_str!("../templates/fix_mode_xml.txt").to_string());
    let variables = HashMap::from([
        ("PROMPT", prompt_content.to_string()),
        ("PLAN", plan_content.to_string()),
        ("ISSUES", issues_content.to_string()),
        ("FILES_TO_MODIFY", format_files_section_xml(files_to_modify)),
        (
            "FIX_RESULT_XML_PATH",
            workspace.absolute_str(".agent/tmp/fix_result.xml"),
        ),
        (
            "FIX_RESULT_XSD_PATH",
            workspace.absolute_str(".agent/tmp/fix_result.xsd"),
        ),
    ]);
    match Template::new(&template_content).render_with_log(template_name, &variables, &partials) {
        Ok(rendered) => rendered,
        Err(err) => {
            // Extract missing variable from error
            let unsubstituted = match &err {
                crate::prompts::template_engine::TemplateError::MissingVariable(name) => {
                    vec![name.clone()]
                }
                _ => vec![],
            };

            let prompt_content = format!(
                "FIX MODE\n\nFix the issues:\n\n{issues_content}\n\n\
                 Based on requirements:\n{prompt_content}\n\nPlan:\n{plan_content}\n\n\
                 Output format: <ralph-fix-result><ralph-summary>Summary</ralph-summary><ralph-fixes-applied>Changes made</ralph-fixes-applied></ralph-fix-result>\n"
            );
            RenderedTemplate {
                content: prompt_content,
                log: SubstitutionLog {
                    template_name: template_name.to_string(),
                    substituted: vec![
                        SubstitutionEntry {
                            name: "PROMPT".to_string(),
                            source: SubstitutionSource::Value,
                        },
                        SubstitutionEntry {
                            name: "PLAN".to_string(),
                            source: SubstitutionSource::Value,
                        },
                        SubstitutionEntry {
                            name: "ISSUES".to_string(),
                            source: SubstitutionSource::Value,
                        },
                    ],
                    unsubstituted,
                },
            }
        }
    }
}

/// Generate XSD validation retry prompt for fix with substitution log.
///
/// This is the log-based version that returns both content and substitution tracking.
/// Use this version in handlers to enable log-based validation.
pub fn prompt_fix_xsd_retry_with_log(
    context: &TemplateContext,
    xsd_error: &str,
    last_output: &str,
    workspace: &dyn Workspace,
    template_name: &str,
) -> RenderedTemplate {
    write_fix_xsd_retry_files(workspace, last_output);

    let schema_path = Path::new(".agent/tmp/fix_result.xsd");
    let last_output_path = Path::new(".agent/tmp/last_output.xml");

    let schema_exists = workspace.exists(schema_path);
    let last_output_exists = workspace.exists(last_output_path);

    let diagnostic_prefix = if !schema_exists || !last_output_exists {
        let parts: Vec<String> =
            std::iter::once("⚠️  WARNING: Required XSD retry files are missing:\n".to_string())
                .chain(
                    if !schema_exists {
                        Some(format!(
                            "  - Schema file: {} (workspace.root() = {})\n",
                            workspace.absolute_str(".agent/tmp/fix_result.xsd"),
                            workspace.root().display()
                        ))
                    } else {
                        None
                    },
                )
                .chain(if !last_output_exists {
                    Some(format!(
                        "  - Last output: {} (workspace.root() = {})\n",
                        workspace.absolute_str(".agent/tmp/last_output.xml"),
                        workspace.root().display()
                    ))
                } else {
                    None
                })
                .chain(std::iter::once(
                    "This likely indicates CWD != workspace.root() path mismatch.\n\n".to_string(),
                ))
                .collect();
        parts.concat()
    } else {
        String::new()
    };

    let build_manual_log = |template_name: &str, xsd_error: &str| {
        if xsd_error.is_empty() {
            SubstitutionLog {
                template_name: template_name.to_string(),
                substituted: Vec::new(),
                unsubstituted: vec!["XSD_ERROR".to_string()],
            }
        } else {
            SubstitutionLog {
                template_name: template_name.to_string(),
                substituted: vec![SubstitutionEntry {
                    name: "XSD_ERROR".to_string(),
                    source: SubstitutionSource::Value,
                }],
                unsubstituted: Vec::new(),
            }
        }
    };

    if !schema_exists && !last_output_exists {
        let prompt_content = format!(
            "{diagnostic_prefix}\
             XSD VALIDATION FAILED - FIX XML ONLY\n\n\
             **THIS IS A SUBMISSION-FIX-ONLY RETRY**\n\n\
             Error: {xsd_error}\n\n\
             The schema and previous output files could not be found.\n\n\
             PRIMARY OBJECTIVE: Fix malformed XML structure - fix root parse errors FIRST.\n\n\
             DO NOT DO:\n             - Do NOT write any new code\n             - Do NOT modify any source files\n             - Do NOT run any commands\n             - Do NOT do ANY fix/development work\n             - Do NOT change the content/meaning of your response\n\n\
             This is a PURE XML SYNTAX FIX. Your fix work is done. \
             The only problem is that your XML output doesn't conform to the schema. \
             Fix the XML structure, nothing else.\n\n\
             Output format: <ralph-fix-result><ralph-status>all_issues_addressed|issues_remain|no_issues_found</ralph-status><ralph-summary>Summary</ralph-summary></ralph-fix-result>\n"
        );
        return RenderedTemplate {
            content: prompt_content,
            log: build_manual_log(template_name, xsd_error),
        };
    }

    let partials = get_shared_partials();
    let template_content = context
        .registry()
        .get_template("fix_mode_xsd_retry")
        .unwrap_or_else(|_| include_str!("../templates/fix_mode_xsd_retry.txt").to_string());
    let variables = HashMap::from([
        ("XSD_ERROR", xsd_error.to_string()),
        (
            "FIX_RESULT_XML_PATH",
            workspace.absolute_str(".agent/tmp/fix_result.xml"),
        ),
        (
            "FIX_RESULT_XSD_PATH",
            workspace.absolute_str(".agent/tmp/fix_result.xsd"),
        ),
        (
            "LAST_OUTPUT_XML_PATH",
            workspace.absolute_str(".agent/tmp/last_output.xml"),
        ),
    ]);

    let template = Template::new(&template_content);
    template
        .render_with_log(template_name, &variables, &partials)
        .map(|mut rendered| {
            if !diagnostic_prefix.is_empty() {
                rendered.content = format!("{}\n{}", diagnostic_prefix, rendered.content);
            }
            rendered
        })
        .unwrap_or_else(|_| {
            let prompt_content = format!(
                "XSD VALIDATION FAILED - FIX XML ONLY\n\n\
                 **THIS IS A SUBMISSION-FIX-ONLY RETRY**\n\n\
                 Error: {xsd_error}\n\n\
                 REFERENCE ONLY: Read .agent/tmp/fix_result.xsd and .agent/tmp/last_output.xml.\n\
                 Do NOT redo fix/development work.\n\n\
                 PRIMARY OBJECTIVE: Fix malformed XML structure - fix root parse errors FIRST.\n\n\
                 DO NOT DO:\n\
                 - Do NOT write any new code\n\
                 - Do NOT modify any source files\n\
                 - Do NOT run any commands\n\
                 - Do NOT do ANY fix/development work\n\
                 - Do NOT change the content/meaning of your response\n\n\
                 This is a PURE XML SYNTAX FIX. Fix the XML structure to conform to the schema.\n\n\
                 Output format: <ralph-fix-result><ralph-status>all_issues_addressed|issues_remain|no_issues_found</ralph-status><ralph-summary>Summary</ralph-summary></ralph-fix-result>\n"
            );
            RenderedTemplate {
                content: prompt_content,
                log: build_manual_log(template_name, xsd_error),
            }
        })
}

/// Generate XML-based fix prompt using template registry.
///
/// This version uses XML output format with XSD validation for reliable parsing.
///
/// # Arguments
///
/// * `context` - Template context containing the template registry
/// * `prompt_content` - Content of PROMPT.md for context about the original request
/// * `plan_content` - Content of PLAN.md for context about the implementation plan
/// * `issues_content` - Content of ISSUES.md for context about issues to fix
/// * `files_to_modify` - List of files that may be modified
/// * `workspace` - Workspace for resolving absolute paths
pub fn prompt_fix_xml_with_context(
    context: &TemplateContext,
    prompt_content: &str,
    plan_content: &str,
    issues_content: &str,
    files_to_modify: &[String],
    workspace: &dyn Workspace,
) -> String {
    let partials = get_shared_partials();
    let template_content = context
        .registry()
        .get_template("fix_mode_xml")
        .unwrap_or_else(|_| include_str!("../templates/fix_mode_xml.txt").to_string());
    let variables = HashMap::from([
        ("PROMPT", prompt_content.to_string()),
        ("PLAN", plan_content.to_string()),
        ("ISSUES", issues_content.to_string()),
        ("FILES_TO_MODIFY", format_files_section_xml(files_to_modify)),
        (
            "FIX_RESULT_XML_PATH",
            workspace.absolute_str(".agent/tmp/fix_result.xml"),
        ),
        (
            "FIX_RESULT_XSD_PATH",
            workspace.absolute_str(".agent/tmp/fix_result.xsd"),
        ),
    ]);
    Template::new(&template_content)
        .render_with_partials(&variables, &partials)
        .unwrap_or_else(|_| {
            format!(
                "FIX MODE\n\nFix the issues:\n\n{issues_content}\n\n\
                 Based on requirements:\n{prompt_content}\n\nPlan:\n{plan_content}\n\n\
                 Output format: <ralph-fix-result><ralph-summary>Summary</ralph-summary><ralph-fixes-applied>Changes made</ralph-fixes-applied></ralph-fix-result>\n"
            )
        })
}

/// Generate XSD validation retry prompt for fix with error feedback.
///
/// This prompt is used when an AI agent produces fix result XML that fails XSD validation.
/// The XSD schema and last output are written to files at `.agent/tmp/` to avoid
/// bloating the prompt. The agent should read these files.
///
/// # Arguments
///
/// * `context` - Template context containing the template registry
/// * `_issues_content` - Content of ISSUES.md (unused - kept for API compatibility)
/// * `xsd_error` - The XSD validation error message to include in the prompt
/// * `last_output` - The invalid XML output that failed validation
/// * `workspace` - Workspace for writing XSD retry context files
pub fn prompt_fix_xsd_retry_with_context(
    context: &TemplateContext,
    _issues_content: &str,
    xsd_error: &str,
    last_output: &str,
    workspace: &dyn Workspace,
) -> String {
    // Write context files to .agent/tmp/ for the agent to read
    write_fix_xsd_retry_files(workspace, last_output);
    prompt_fix_xsd_retry_with_context_files(context, xsd_error, workspace)
}

/// Generate XSD validation retry prompt for fix with error feedback.
///
/// This variant assumes `.agent/tmp/last_output.xml` is already materialized.
///
/// Per acceptance criteria #5: Template rendering errors must never terminate the pipeline.
/// If required files are missing, a deterministic fallback prompt is produced that includes
/// diagnostic information but still provides valid instructions to the agent.
pub fn prompt_fix_xsd_retry_with_context_files(
    context: &TemplateContext,
    xsd_error: &str,
    workspace: &dyn Workspace,
) -> String {
    let partials = get_shared_partials();
    // Ensure schema file exists; last_output.xml is expected to already be present.
    write_fix_xsd_retry_schema_files(workspace);

    // Check that required files exist
    let schema_path = Path::new(".agent/tmp/fix_result.xsd");
    let last_output_path = Path::new(".agent/tmp/last_output.xml");

    let schema_exists = workspace.exists(schema_path);
    let last_output_exists = workspace.exists(last_output_path);

    // Build diagnostic prefix for missing files (per acceptance criteria #3)
    let diagnostic_prefix = if !schema_exists || !last_output_exists {
        let parts: Vec<String> =
            std::iter::once("⚠️  WARNING: Required XSD retry files are missing:\n".to_string())
                .chain(
                    if !schema_exists {
                        Some(format!(
                            "  - Schema file: {} (workspace.root() = {})\n",
                            workspace.absolute_str(".agent/tmp/fix_result.xsd"),
                            workspace.root().display()
                        ))
                    } else {
                        None
                    },
                )
                .chain(if !last_output_exists {
                    Some(format!(
                        "  - Last output: {} (workspace.root() = {})\n",
                        workspace.absolute_str(".agent/tmp/last_output.xml"),
                        workspace.root().display()
                    ))
                } else {
                    None
                })
                .chain(std::iter::once(
                    "This likely indicates CWD != workspace.root() path mismatch.\n\n".to_string(),
                ))
                .collect();
        parts.concat()
    } else {
        String::new()
    };

    // If both files are missing, return fallback prompt with diagnostics (per AC #5)
    if !schema_exists && !last_output_exists {
        return format!(
            "{diagnostic_prefix}\
             XSD VALIDATION FAILED - FIX XML ONLY\n\n\
             **THIS IS A SUBMISSION-FIX-ONLY RETRY**\n\n\
             Error: {xsd_error}\n\n\
             The schema and previous output files could not be found.\n\n\
             PRIMARY OBJECTIVE: Fix malformed XML structure - fix root parse errors FIRST.\n\n\
             DO NOT DO:\n             - Do NOT write any new code\n             - Do NOT modify any source files\n             - Do NOT run any commands\n             - Do NOT do ANY fix/development work\n             - Do NOT change the content/meaning of your response\n\n\
             This is a PURE XML SYNTAX FIX. Your fix work is done. \
             The only problem is that your XML output doesn't conform to the schema. \
             Fix the XML structure, nothing else.\n\n\
             Output format: <ralph-fix-result><ralph-status>all_issues_addressed|issues_remain|no_issues_found</ralph-status><ralph-summary>Summary</ralph-summary></ralph-fix-result>\n"
        );
    }

    // Proceed with normal XSD retry prompt generation if at least schema exists
    let template_content = context
        .registry()
        .get_template("fix_mode_xsd_retry")
        .unwrap_or_else(|_| include_str!("../templates/fix_mode_xsd_retry.txt").to_string());
    let variables = HashMap::from([
        ("XSD_ERROR", xsd_error.to_string()),
        (
            "FIX_RESULT_XML_PATH",
            workspace.absolute_str(".agent/tmp/fix_result.xml"),
        ),
        (
            "FIX_RESULT_XSD_PATH",
            workspace.absolute_str(".agent/tmp/fix_result.xsd"),
        ),
        (
            "LAST_OUTPUT_XML_PATH",
            workspace.absolute_str(".agent/tmp/last_output.xml"),
        ),
    ]);

    let rendered_prompt = Template::new(&template_content)
        .render_with_partials(&variables, &partials)
        .unwrap_or_else(|_| {
            format!(
                "XSD VALIDATION FAILED - FIX XML ONLY\n\n\
                 **THIS IS A SUBMISSION-FIX-ONLY RETRY**\n\n\
                 Error: {xsd_error}\n\n\
                 REFERENCE ONLY: Read .agent/tmp/fix_result.xsd and .agent/tmp/last_output.xml.\n\
                 Do NOT redo fix/development work.\n\n\
                 PRIMARY OBJECTIVE: Fix malformed XML structure - fix root parse errors FIRST.\n\n\
                 DO NOT DO:\n\
                 - Do NOT write any new code\n\
                 - Do NOT modify any source files\n\
                 - Do NOT run any commands\n\
                 - Do NOT do ANY fix/development work\n\
                 - Do NOT change the content/meaning of your response\n\n\
                 This is a PURE XML SYNTAX FIX. Fix the XML structure to conform to the schema.\n\n\
                 Output format: <ralph-fix-result><ralph-status>all_issues_addressed|issues_remain|no_issues_found</ralph-status><ralph-summary>Summary</ralph-summary></ralph-fix-result>\n"
            )
        });

    // Prepend diagnostic prefix if files were missing but we continued anyway
    if diagnostic_prefix.is_empty() {
        rendered_prompt
    } else {
        format!("{diagnostic_prefix}\n{rendered_prompt}")
    }
}