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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! Retry and continuation counter tests
//!
//! Tests for retry/continuation/fallback counters:
//! - XSD retry counters (total and phase-specific)
//! - Same-agent retry counters
//! - Continuation budget tracking
//! - Agent fallback counters

use super::*;
#[test]
fn test_phase_specific_xsd_retry_increments_review_metrics() {
    let mut state = PipelineState::initial(0, 3);
    state.phase = crate::reducer::event::PipelinePhase::Review;
    assert_eq!(state.metrics.xsd_retry_review, 0);
    assert_eq!(state.metrics.xsd_retry_attempts_total, 0);

    let event = PipelineEvent::Review(ReviewEvent::OutputValidationFailed {
        pass: 0,
        attempt: 0,
        error_detail: None,
    });
    let state = reduce(state, event);

    assert_eq!(state.metrics.xsd_retry_review, 1);
    assert_eq!(state.metrics.xsd_retry_attempts_total, 1);
}

#[test]
fn test_phase_specific_xsd_retry_increments_fix_metrics() {
    let mut state = PipelineState::initial(0, 3);
    state.phase = crate::reducer::event::PipelinePhase::Review;
    assert_eq!(state.metrics.xsd_retry_fix, 0);
    assert_eq!(state.metrics.xsd_retry_attempts_total, 0);

    let event = PipelineEvent::Review(ReviewEvent::FixOutputValidationFailed {
        pass: 0,
        attempt: 0,
        error_detail: None,
    });
    let state = reduce(state, event);

    assert_eq!(state.metrics.xsd_retry_fix, 1);
    assert_eq!(state.metrics.xsd_retry_attempts_total, 1);
}

#[test]
fn test_xsd_retry_does_not_increment_when_exhausted() {
    let mut state = PipelineState::initial(3, 0);
    state.phase = crate::reducer::event::PipelinePhase::Development;
    state.continuation.xsd_retry_count = 98; // One below max (default is 99)
    state.continuation.max_xsd_retry_count = 99;

    // This retry should NOT increment: (98 + 1 = 99) is treated as exhausted.
    let event = PipelineEvent::Development(DevelopmentEvent::OutputValidationFailed {
        iteration: 0,
        attempt: 0,
    });
    let state = reduce(state, event);

    // (98 + 1) hits exhaustion and switches agents, so metrics do not increment.
    assert_eq!(state.metrics.xsd_retry_development, 0);
    assert_eq!(state.metrics.xsd_retry_attempts_total, 0);

    // Try another validation failure. Because XSD retry count is reset when switching
    // agents, this one is a retry attempt and should increment.
    let event = PipelineEvent::Development(DevelopmentEvent::OutputValidationFailed {
        iteration: 0,
        attempt: 0,
    });
    let state = reduce(state, event);

    assert_eq!(state.metrics.xsd_retry_development, 1);
    assert_eq!(state.metrics.xsd_retry_attempts_total, 1);
}

#[test]
fn test_fix_continuation_triggered_increments_counter() {
    use crate::reducer::state::FixStatus;

    let state = PipelineState::initial(0, 3);
    let event = PipelineEvent::Review(ReviewEvent::FixContinuationTriggered {
        pass: 0,
        status: FixStatus::IssuesRemain,
        summary: Some("more work needed".to_string()),
    });
    let state = reduce(state, event);

    assert_eq!(state.metrics.fix_continuations_total, 1);
}

#[test]
fn test_review_pass_completed_clean_increments_counter() {
    let mut state = PipelineState::initial(0, 3);
    state = reduce(state, PipelineEvent::review_pass_started(1));
    assert_eq!(state.metrics.review_passes_completed, 0);

    // Simulate clean pass completion
    let event = PipelineEvent::Review(ReviewEvent::PassCompletedClean { pass: 1 });
    let state = reduce(state, event);

    assert_eq!(state.metrics.review_passes_completed, 1);
    assert_eq!(state.reviewer_pass, 2); // Advances to next pass
}

#[test]
fn test_multiple_review_passes_increment_completed() {
    let mut state = PipelineState::initial(0, 3);

    // Pass 1
    state = reduce(state, PipelineEvent::review_pass_started(1));
    state = reduce(
        state,
        PipelineEvent::Review(ReviewEvent::PassCompletedClean { pass: 1 }),
    );
    assert_eq!(state.metrics.review_passes_completed, 1);

    // Pass 2
    state = reduce(state, PipelineEvent::review_pass_started(2));
    state = reduce(
        state,
        PipelineEvent::Review(ReviewEvent::PassCompletedClean { pass: 2 }),
    );
    assert_eq!(state.metrics.review_passes_completed, 2);
}

#[test]
fn test_fix_attempt_completed_increments_review_passes_completed() {
    let mut state = PipelineState::initial(0, 3);
    state = reduce(state, PipelineEvent::review_pass_started(1));
    assert_eq!(state.metrics.review_passes_completed, 0);

    // Simulate fix completing the pass
    let event = PipelineEvent::Review(ReviewEvent::FixAttemptCompleted {
        pass: 1,
        changes_made: true,
    });
    let state = reduce(state, event);

    assert_eq!(state.metrics.review_passes_completed, 1);
}

#[test]
fn test_continuation_succeeded_increments_dev_completed() {
    let mut state = PipelineState::initial(3, 0);
    state = reduce(state, PipelineEvent::development_iteration_started(0));
    assert_eq!(state.metrics.dev_iterations_completed, 0);

    // Trigger continuation
    state = reduce(
        state,
        PipelineEvent::Development(DevelopmentEvent::ContinuationTriggered {
            iteration: 0,
            status: DevelopmentStatus::Partial,
            summary: "partial work".to_string(),
            files_changed: None,
            next_steps: None,
        }),
    );

    // Continuation succeeds
    let event = PipelineEvent::Development(DevelopmentEvent::ContinuationSucceeded {
        iteration: 0,
        total_continuation_attempts: 1,
    });
    let state = reduce(state, event);

    assert_eq!(state.metrics.dev_iterations_completed, 1);
}

#[test]
fn test_same_agent_retry_increments_counter() {
    let state = PipelineState::initial(3, 0);
    let event = PipelineEvent::agent_timed_out(
        AgentRole::Developer,
        AgentName::from("claude"),
        TimeoutOutputKind::PartialResult,
        Some(".agent/logs/developer_0.log".to_string()),
        None,
    );
    let state = reduce(state, event);

    assert_eq!(state.metrics.same_agent_retry_attempts_total, 1);
}

#[test]
fn test_model_fallback_increments_counter() {
    let state = PipelineState::initial(3, 0);
    let event = PipelineEvent::agent_model_fallback_triggered(
        AgentRole::Developer,
        AgentName::from("claude"),
        ModelName::from("claude-sonnet"),
        ModelName::from("gpt-4"),
    );
    let state = reduce(state, event);

    assert_eq!(state.metrics.model_fallbacks_total, 1);
}

#[test]
fn test_retry_cycle_started_increments_counter() {
    let state = PipelineState::initial(3, 0);
    let event = PipelineEvent::agent_retry_cycle_started(AgentRole::Developer, 1);
    let state = reduce(state, event);

    assert_eq!(state.metrics.retry_cycles_started_total, 1);
}

#[test]
fn test_metrics_survive_checkpoint_serialization() {
    let mut state = PipelineState::initial(5, 3);

    // Simulate some progress
    state.metrics.dev_iterations_started = 2;
    state.metrics.dev_iterations_completed = 1;
    state.metrics.dev_attempts_total = 3;
    state.metrics.analysis_attempts_total = 2;
    state.metrics.review_passes_started = 1;
    state.metrics.review_runs_total = 1;
    state.metrics.xsd_retry_attempts_total = 5;
    state.metrics.xsd_retry_development = 3;
    state.metrics.same_agent_retry_attempts_total = 2;
    state.metrics.commits_created_total = 1;

    // Serialize and deserialize
    let json = serde_json::to_string(&state).expect("serialization failed");
    let restored: PipelineState = serde_json::from_str(&json).expect("deserialization failed");

    // Verify all metrics are preserved
    assert_eq!(restored.metrics.dev_iterations_started, 2);
    assert_eq!(restored.metrics.dev_iterations_completed, 1);
    assert_eq!(restored.metrics.dev_attempts_total, 3);
    assert_eq!(restored.metrics.analysis_attempts_total, 2);
    assert_eq!(restored.metrics.review_passes_started, 1);
    assert_eq!(restored.metrics.review_runs_total, 1);
    assert_eq!(restored.metrics.xsd_retry_attempts_total, 5);
    assert_eq!(restored.metrics.xsd_retry_development, 3);
    assert_eq!(restored.metrics.same_agent_retry_attempts_total, 2);
    assert_eq!(restored.metrics.commits_created_total, 1);
}

#[test]
fn test_metrics_default_for_old_checkpoints() {
    // Simulate an old checkpoint without metrics field
    let json = r#"{
        "phase": "Development",
        "iteration": 1,
        "total_iterations": 5,
        "reviewer_pass": 0,
        "total_reviewer_passes": 2,
        "agent_chain": {
            "agents": [],
            "current_agent_index": 0,
            "models_per_agent": [],
            "current_model_index": 0,
            "retry_cycle": 0,
            "max_cycles": 1,
            "retry_delay_ms": 1000,
            "backoff_multiplier": 2.0,
            "max_backoff_ms": 60000,
            "backoff_pending_ms": null,
            "current_role": "Developer",
            "rate_limit_continuation_prompt": null,
            "last_session_id": null
        },
        "continuation": {
            "invalid_output_attempts": 0,
            "continuation_attempt": 0,
            "max_continue_count": 3,
            "continue_pending": false,
            "context_write_pending": false,
            "context_cleanup_pending": false,
            "xsd_retry_count": 0,
            "xsd_retry_pending": false,
            "xsd_retry_session_reuse_pending": false,
            "max_xsd_retry_count": 99,
            "same_agent_retry_count": 0,
            "same_agent_retry_pending": false,
            "same_agent_retry_reason": null,
            "max_same_agent_retry_count": 3,
            "fix_continuation_attempt": 0,
            "max_fix_continue_count": 3,
            "fix_continue_pending": false,
            "last_xsd_error": null,
            "last_review_xsd_error": null,
            "last_fix_xsd_error": null,
            "dev_continuation_context": null
        },
        "rebase": "NotStarted",
        "commit": "NotStarted",
        "execution_history": [],
        "prompt_inputs": {
            "development": null,
            "review": null,
            "commit": null
        },
        "review_issues_found": false,
        "commit_prompt_prepared": false,
        "commit_diff_prepared": false,
        "commit_diff_empty": false,
        "commit_diff_content_id_sha256": null,
        "commit_agent_invoked": false,
        "commit_required_files_cleaned": false,
        "commit_xml_extracted": false,
        "commit_validated_outcome": null,
        "commit_xml_archived": false,
        "context_cleaned": false,
        "dev_fix_triggered": false,
        "previous_phase": null,
        "planning_prompt_prepared_iteration": null,
        "planning_required_files_cleaned_iteration": null,
        "planning_agent_invoked_iteration": null,
        "planning_xml_extracted_iteration": null,
        "planning_validated_outcome": null,
        "planning_markdown_written_iteration": null,
        "planning_xml_archived_iteration": null,
        "development_context_prepared_iteration": null,
        "development_prompt_prepared_iteration": null,
        "development_required_files_cleaned_iteration": null,
        "development_agent_invoked_iteration": null,
        "analysis_agent_invoked_iteration": null,
        "development_xml_extracted_iteration": null,
        "development_validated_outcome": null,
        "development_xml_archived_iteration": null,
        "review_context_prepared_pass": null,
        "review_prompt_prepared_pass": null,
        "review_required_files_cleaned_pass": null,
        "review_agent_invoked_pass": null,
        "review_issues_xml_extracted_pass": null,
        "review_validated_outcome": null,
        "review_issues_markdown_written_pass": null,
        "review_issue_snippets_extracted_pass": null,
        "review_issues_xml_archived_pass": null,
        "fix_prompt_prepared_pass": null,
        "fix_required_files_cleaned_pass": null,
        "fix_agent_invoked_pass": null,
        "fix_result_xml_extracted_pass": null,
        "fix_validated_outcome": null,
        "fix_result_xml_archived_pass": null,
        "checkpoint_saved_count": 0
    }"#;

    let restored: PipelineState = serde_json::from_str(json).expect(
        "deserialization failed: legacy JSON in test must include required AgentChainState fields",
    );

    // Verify metrics field is present with defaults
    assert_eq!(restored.metrics.dev_iterations_started, 0);
    assert_eq!(restored.metrics.max_dev_iterations, 0); // Not initialized from config in this test
}

#[test]
fn test_new_metrics_backward_compatible() {
    // Simulate checkpoint from before review_passes_completed was added
    let mut state = PipelineState::initial(5, 3);
    state.metrics.review_passes_started = 2;
    state.metrics.review_runs_total = 2;
    // review_passes_completed field didn't exist in old checkpoint

    let json = serde_json::to_string(&state).unwrap();
    let mut json_obj: serde_json::Value = serde_json::from_str(&json).unwrap();

    // Remove the new field to simulate old checkpoint
    if let Some(metrics) = json_obj.get_mut("metrics") {
        if let Some(metrics_obj) = metrics.as_object_mut() {
            metrics_obj.remove("review_passes_completed");
        }
    }

    let restored: PipelineState =
        serde_json::from_value(json_obj).expect("should deserialize with defaults");

    // New field should default to 0
    assert_eq!(restored.metrics.review_passes_completed, 0);
    // Existing fields should be preserved
    assert_eq!(restored.metrics.review_passes_started, 2);
    assert_eq!(restored.metrics.review_runs_total, 2);
}

#[test]
fn test_same_agent_retry_exhausted_does_not_increment() {
    let mut state = PipelineState::initial(3, 0);
    state.continuation.max_same_agent_retry_count = 3;
    state.continuation.same_agent_retry_count = 2; // One below max

    // First retry (count becomes 3, which is >= max) should NOT increment because will_retry = false
    let event = PipelineEvent::agent_timed_out(
        AgentRole::Developer,
        AgentName::from("claude"),
        TimeoutOutputKind::PartialResult,
        Some(".agent/logs/developer_0.log".to_string()),
        None,
    );
    let state = reduce(state, event);

    // Should be 0 because new_retry_count (3) >= max (3), so we fall back without incrementing
    assert_eq!(state.metrics.same_agent_retry_attempts_total, 0);
    // Verify agent chain switched
    assert!(state.agent_chain.current_agent_index > 0 || state.agent_chain.retry_cycle > 0);
}

// ========================================================================
// Timeout output kind metric tests (AC-8)
// ========================================================================

#[test]
fn test_no_output_timeout_increments_timeout_no_output_agent_switches_total() {
    let state = PipelineState::initial(3, 0);
    let event = PipelineEvent::agent_timed_out(
        AgentRole::Developer,
        AgentName::from("claude"),
        TimeoutOutputKind::NoResult,
        None,
        None,
    );
    let state = reduce(state, event);

    assert_eq!(
        state.metrics.timeout_no_output_agent_switches_total, 1,
        "NoResult timeout should increment timeout_no_output_agent_switches_total"
    );
}

#[test]
fn test_partial_output_timeout_does_not_increment_timeout_no_output_agent_switches_total() {
    let state = PipelineState::initial(3, 0);
    let event = PipelineEvent::agent_timed_out(
        AgentRole::Developer,
        AgentName::from("claude"),
        TimeoutOutputKind::PartialResult,
        Some(".agent/logs/developer_0.log".to_string()),
        None,
    );
    let state = reduce(state, event);

    assert_eq!(
        state.metrics.timeout_no_output_agent_switches_total, 0,
        "PartialResult timeout should NOT increment timeout_no_output_agent_switches_total"
    );
    // But same_agent_retry_attempts_total should be incremented
    assert_eq!(
        state.metrics.same_agent_retry_attempts_total, 1,
        "PartialResult timeout should increment same_agent_retry_attempts_total"
    );
}

#[test]
fn test_no_output_timeout_does_not_increment_same_agent_retry_attempts_total() {
    let state = PipelineState::initial(3, 0);
    let event = PipelineEvent::agent_timed_out(
        AgentRole::Developer,
        AgentName::from("claude"),
        TimeoutOutputKind::NoResult,
        None,
        None,
    );
    let state = reduce(state, event);

    assert_eq!(
        state.metrics.same_agent_retry_attempts_total, 0,
        "NoResult timeout should NOT increment same_agent_retry_attempts_total"
    );
}