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
// NOTE: split from reducer/state_reduction/review.rs (fix attempt events).

use crate::agents::{AgentDrain, DrainMode};
use crate::reducer::event::{PipelinePhase, ReviewEvent};
use crate::reducer::state::{
    AgentChainState, CommitState, ContinuationState, FixStatus, FixValidatedOutcome, PipelineState,
};

fn clear_fix_drain_progress(state: PipelineState) -> PipelineState {
    PipelineState {
        review_issues_found: false,
        fix_prompt_prepared_pass: None,
        fix_required_files_cleaned_pass: None,
        fix_agent_invoked_pass: None,
        fix_analysis_agent_invoked_pass: None,
        fix_result_xml_extracted_pass: None,
        fix_validated_outcome: None,
        fix_result_xml_archived_pass: None,
        ..state
    }
}

fn transition_to_commit_after_fix(
    state: PipelineState,
    pass: u32,
    increment_review_passes_completed: bool,
) -> PipelineState {
    let state = clear_fix_drain_progress(state);

    PipelineState {
        phase: PipelinePhase::CommitMessage,
        previous_phase: Some(PipelinePhase::Review),
        reviewer_pass: pass,
        agent_chain: state.agent_chain.with_mode(DrainMode::Normal),
        commit: CommitState::NotStarted,
        commit_prompt_prepared: false,
        commit_diff_prepared: false,
        commit_diff_empty: false,
        commit_diff_content_id_sha256: None,
        commit_agent_invoked: false,
        commit_required_files_cleaned: false,
        commit_xml_extracted: false,
        commit_validated_outcome: None,
        commit_xml_archived: false,
        commit_selected_files: Vec::new(),
        commit_excluded_files: Vec::new(),
        commit_residual_retry_pass: 0,
        continuation: state.continuation.reset(),
        metrics: if increment_review_passes_completed {
            state.metrics.increment_review_passes_completed()
        } else {
            state.metrics
        },
        ..state
    }
}

/// Handles `ReviewEvent::FixAttemptStarted`.
///
/// Starts a new fix attempt by resetting the agent chain for the Fix drain
/// and clearing pending flags to prevent infinite loops.
///
/// Fix attempts use the Reviewer agent chain by design. The pipeline has three
/// agent roles: Developer, Reviewer, and Commit. Fixes are performed by the same
/// agent chain configured for review (there is no separate "Fixer" role), since
/// the fix phase is part of the review workflow.
pub(super) fn reduce_fix_attempt_started(state: PipelineState) -> PipelineState {
    PipelineState {
        agent_chain: AgentChainState::initial()
            .with_max_cycles(state.agent_chain.max_cycles)
            .with_backoff_policy(
                state.agent_chain.retry_delay_ms,
                state.agent_chain.backoff_multiplier,
                state.agent_chain.max_backoff_ms,
            )
            .reset_for_drain(AgentDrain::Fix),
        // Clear pending flags when fix attempt starts to prevent infinite loops.
        // xsd_retry_pending is cleared to ensure the XSD retry effect doesn't re-trigger
        // after the fix attempt starts a fresh agent invocation.
        continuation: ContinuationState {
            invalid_output_attempts: 0,
            fix_continue_pending: false,
            xsd_retry_pending: false,
            same_agent_retry_pending: false,
            same_agent_retry_reason: None,
            // Clear fix error when starting a new fix attempt
            last_fix_xsd_error: None,
            ..state.continuation
        },
        fix_prompt_prepared_pass: None,
        fix_required_files_cleaned_pass: None,
        fix_agent_invoked_pass: None,
        fix_analysis_agent_invoked_pass: None,
        fix_result_xml_extracted_pass: None,
        fix_validated_outcome: None,
        fix_result_xml_archived_pass: None,
        ..state
    }
}

/// Handles `ReviewEvent::FixPromptPrepared`.
///
/// Marks fix prompt as prepared for this pass.
/// Clears retry and continuation flags to prevent infinite loops.
pub(super) fn reduce_fix_prompt_prepared(state: PipelineState, pass: u32) -> PipelineState {
    PipelineState {
        agent_chain: state.agent_chain.with_drain(AgentDrain::Fix),
        fix_prompt_prepared_pass: Some(pass),
        continuation: ContinuationState {
            xsd_retry_pending: false,
            xsd_retry_session_reuse_pending: state.continuation.xsd_retry_session_reuse_pending,
            same_agent_retry_pending: false,
            same_agent_retry_reason: None,
            // Clear fix_continue_pending to prevent infinite loop.
            // Once the fix prompt is prepared, the fix continuation attempt has started,
            // so we should not re-derive PrepareFixPrompt.
            fix_continue_pending: false,
            ..state.continuation
        },
        ..state
    }
}

/// Handles `ReviewEvent::FixResultXmlCleaned`.
///
/// Marks fix result XML as cleaned for this pass (pre-invocation cleanup).
pub(super) fn reduce_fix_result_xml_cleaned(state: PipelineState, pass: u32) -> PipelineState {
    PipelineState {
        fix_required_files_cleaned_pass: Some(pass),
        ..state
    }
}

/// Handles `ReviewEvent::FixAgentInvoked`.
///
/// Marks fix agent as invoked for this pass and increments metrics.
/// Clears retry flags since agent invocation is a fresh attempt.
pub(super) fn reduce_fix_agent_invoked(state: PipelineState, pass: u32) -> PipelineState {
    PipelineState {
        agent_chain: state.agent_chain.with_drain(AgentDrain::Fix),
        fix_agent_invoked_pass: Some(pass),
        continuation: ContinuationState {
            xsd_retry_pending: false,
            xsd_retry_session_reuse_pending: false,
            same_agent_retry_pending: false,
            same_agent_retry_reason: None,
            ..state.continuation
        },
        metrics: state.metrics.increment_fix_runs_total(),
        ..state
    }
}

/// Handles `ReviewEvent::FixAnalysisAgentInvoked`.
///
/// Marks fix analysis agent as invoked for this pass and increments metrics.
/// This is the fix verification step that mirrors development analysis.
pub(super) fn reduce_fix_analysis_agent_invoked(state: PipelineState, pass: u32) -> PipelineState {
    PipelineState {
        agent_chain: state.agent_chain.with_drain(AgentDrain::Analysis),
        fix_analysis_agent_invoked_pass: Some(pass),
        continuation: ContinuationState {
            xsd_retry_pending: false,
            xsd_retry_session_reuse_pending: false,
            same_agent_retry_pending: false,
            same_agent_retry_reason: None,
            ..state.continuation
        },
        metrics: state.metrics.increment_fix_analysis_runs_total(),
        ..state
    }
}

/// Handles `ReviewEvent::FixResultXmlExtracted`.
///
/// Marks fix result XML as extracted for this pass.
pub(super) fn reduce_fix_result_xml_extracted(state: PipelineState, pass: u32) -> PipelineState {
    PipelineState {
        fix_result_xml_extracted_pass: Some(pass),
        ..state
    }
}

/// Handles `ReviewEvent::FixResultXmlValidated`.
///
/// Stores fix validation outcome and clears XSD error (validation succeeded).
pub(super) fn reduce_fix_result_xml_validated(
    state: PipelineState,
    pass: u32,
    status: FixStatus,
    summary: Option<String>,
) -> PipelineState {
    PipelineState {
        fix_validated_outcome: Some(FixValidatedOutcome {
            pass,
            status,
            summary,
        }),
        continuation: ContinuationState {
            // Clear error when validation succeeds
            last_fix_xsd_error: None,
            ..state.continuation
        },
        ..state
    }
}

/// Handles `ReviewEvent::FixResultXmlArchived`.
///
/// Marks fix result XML as archived for this pass.
pub(super) fn reduce_fix_result_xml_archived(state: PipelineState, pass: u32) -> PipelineState {
    PipelineState {
        fix_result_xml_archived_pass: Some(pass),
        ..state
    }
}

/// Handles `ReviewEvent::FixOutcomeApplied`.
///
/// Applies the fix outcome by checking if continuation is needed or fix is complete.
/// Recursively reduces the derived event (`FixContinuationTriggered`, `FixContinuationBudgetExhausted`, or `FixAttemptCompleted`).
pub(super) fn reduce_fix_outcome_applied(state: PipelineState, pass: u32) -> PipelineState {
    let Some(outcome) = state
        .fix_validated_outcome
        .as_ref()
        .filter(|o| o.pass == pass)
    else {
        return state;
    };

    let next_event = if outcome.status.needs_continuation() {
        let next_attempt = state.continuation.fix_continuation_attempt + 1;
        if next_attempt >= state.continuation.max_fix_continue_count {
            ReviewEvent::FixContinuationBudgetExhausted {
                pass,
                total_attempts: next_attempt,
                last_status: outcome.status,
            }
        } else {
            ReviewEvent::FixContinuationTriggered {
                pass,
                status: outcome.status,
                summary: outcome.summary.clone(),
            }
        }
    } else {
        let changes_made = matches!(outcome.status, FixStatus::AllIssuesAddressed);
        ReviewEvent::FixAttemptCompleted { pass, changes_made }
    };

    // Recursively reduce the derived event
    super::reduce_review_event(state, next_event)
}

/// Handles `ReviewEvent::FixAttemptCompleted`.
///
/// Completes fix attempt and transitions to `CommitMessage` phase.
/// Increments completed passes counter.
pub(super) fn reduce_fix_attempt_completed(
    state: PipelineState,
    pass: u32,
    _changes_made: bool,
) -> PipelineState {
    transition_to_commit_after_fix(state, pass, true)
}

/// Handles `ReviewEvent::FixContinuationTriggered`.
///
/// Triggers a fix continuation when fix output indicates work is incomplete.
/// Increments continuation metrics and sets `fix_continue_pending`.
pub(super) fn reduce_fix_continuation_triggered(
    state: PipelineState,
    pass: u32,
    status: FixStatus,
    summary: Option<String>,
) -> PipelineState {
    // Fix output is valid but indicates work is incomplete (issues_remain)
    PipelineState {
        agent_chain: state
            .agent_chain
            .with_drain(AgentDrain::Fix)
            .with_mode(DrainMode::Continuation),
        reviewer_pass: pass,
        fix_prompt_prepared_pass: None,
        fix_required_files_cleaned_pass: None,
        fix_agent_invoked_pass: None,
        fix_analysis_agent_invoked_pass: None,
        fix_result_xml_extracted_pass: None,
        fix_validated_outcome: None,
        fix_result_xml_archived_pass: None,
        continuation: state.continuation.trigger_fix_continuation(status, summary),
        metrics: state
            .metrics
            .increment_fix_continuations_total()
            .increment_fix_continuation_attempt(),
        ..state
    }
}

/// Handles `ReviewEvent::FixContinuationSucceeded`.
///
/// Completes fix continuation successfully and transitions to `CommitMessage`.
/// Increments completed passes counter.
pub(super) fn reduce_fix_continuation_succeeded(
    state: PipelineState,
    pass: u32,
    _total_attempts: u32,
) -> PipelineState {
    transition_to_commit_after_fix(state, pass, true)
}

/// Handles `ReviewEvent::FixContinuationBudgetExhausted`.
///
/// Fix continuation budget exhausted - proceed to commit with current state.
/// Policy: We accept partial fixes rather than blocking the pipeline.
pub(super) fn reduce_fix_continuation_budget_exhausted(
    state: PipelineState,
    pass: u32,
    _total_attempts: u32,
    _last_status: FixStatus,
) -> PipelineState {
    // Fix continuation budget exhausted - proceed to commit with current state.
    // Policy: We accept partial fixes rather than blocking the pipeline.
    transition_to_commit_after_fix(state, pass, false)
}

/// Handles `ReviewEvent::FixOutputValidationFailed` and `ReviewEvent::FixResultXmlMissing`.
///
/// Increments XSD retry count and either:
/// - Sets `xsd_retry_pending` for another attempt (if budget remains)
/// - Switches to next agent in chain (if XSD retries exhausted)
pub(super) fn reduce_fix_output_validation_failed(
    state: PipelineState,
    pass: u32,
    attempt: u32,
    error_detail: Option<String>,
) -> PipelineState {
    // Same policy as review output validation failure
    let new_xsd_count = state.continuation.xsd_retry_count + 1;

    // Only increment metrics if we're actually retrying (not exhausted)
    let will_retry = new_xsd_count < state.continuation.max_xsd_retry_count;

    if new_xsd_count >= state.continuation.max_xsd_retry_count {
        // XSD retries exhausted - switch to next agent
        // Reset orchestration flags to ensure prompt is prepared and new agent is invoked
        let new_agent_chain = state
            .agent_chain
            .with_drain(AgentDrain::Fix)
            .switch_to_next_agent()
            .clear_session_id();
        PipelineState {
            phase: PipelinePhase::Review,
            reviewer_pass: pass,
            agent_chain: new_agent_chain
                .with_drain(AgentDrain::Fix)
                .with_mode(DrainMode::Normal),
            continuation: ContinuationState {
                invalid_output_attempts: 0,
                xsd_retry_count: 0,
                xsd_retry_pending: false,
                xsd_retry_session_reuse_pending: false,
                // Clear error when switching agents
                last_fix_xsd_error: None,
                ..state.continuation
            },
            // Reset orchestration flags to ensure:
            // 1. Prompt is prepared for new agent
            // 2. New agent is invoked
            // 3. Cleanup runs before invocation
            fix_prompt_prepared_pass: None,
            fix_agent_invoked_pass: None,
            fix_analysis_agent_invoked_pass: None,
            fix_required_files_cleaned_pass: None,
            metrics: if will_retry {
                state.metrics.increment_xsd_retry_fix()
            } else {
                state.metrics
            },
            ..state
        }
    } else {
        // Stay in Review, increment attempt counters, set retry pending
        // Reset orchestration flags to ensure XSD retry prompt is prepared
        // and agent is re-invoked with the retry prompt.
        PipelineState {
            phase: PipelinePhase::Review,
            reviewer_pass: pass,
            agent_chain: state
                .agent_chain
                .with_drain(AgentDrain::Fix)
                .with_mode(DrainMode::XsdRetry),
            continuation: ContinuationState {
                invalid_output_attempts: attempt + 1,
                xsd_retry_count: new_xsd_count,
                xsd_retry_pending: true,
                // Reuse last session id for fix XSD retry when available.
                xsd_retry_session_reuse_pending: true,
                // Preserve error detail for XSD retry prompt
                last_fix_xsd_error: error_detail,
                ..state.continuation
            },
            // Reset orchestration flags to ensure:
            // 1. XSD retry prompt is prepared (fix_prompt_prepared_pass = None)
            // 2. Agent is re-invoked with the retry prompt (fix_agent_invoked_pass = None)
            // 3. Cleanup runs before re-invocation (fix_required_files_cleaned_pass = None)
            fix_prompt_prepared_pass: None,
            fix_agent_invoked_pass: None,
            fix_analysis_agent_invoked_pass: None,
            fix_required_files_cleaned_pass: None,
            metrics: if will_retry {
                state.metrics.increment_xsd_retry_fix()
            } else {
                state.metrics
            },
            ..state
        }
    }
}