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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
// Development phase tests.
//
// Tests for development phase effect determination, agent chain states,
// and iteration counting.

use super::*;

#[test]
fn test_determine_effect_development_phase_empty_chain() {
    let state = PipelineState {
        phase: PipelinePhase::Development,
        iteration: 2,
        total_iterations: 5,
        agent_chain: AgentChainState::initial(),
        ..create_test_state()
    };
    let effect = determine_next_effect(&state);
    assert!(matches!(
        effect,
        Effect::InitializeAgentChain {
            drain: crate::agents::AgentDrain::Development,
            ..
        }
    ));
}

#[test]
fn test_determine_effect_development_phase_exhausted_chain() {
    let mut chain = AgentChainState::initial()
        .with_agents(
            vec!["claude".to_string()],
            vec![vec![]],
            AgentRole::Developer,
        )
        .with_max_cycles(3);
    chain = chain.start_retry_cycle();
    chain = chain.start_retry_cycle();
    chain = chain.start_retry_cycle();

    let state = PipelineState {
        phase: PipelinePhase::Development,
        iteration: 2,
        total_iterations: 5,
        agent_chain: chain,
        ..create_test_state()
    };
    let effect = determine_next_effect(&state);
    assert!(matches!(effect, Effect::SaveCheckpoint { .. }));
}

#[test]
fn test_determine_effect_exhausted_chain_after_checkpoint_aborts() {
    let mut chain = AgentChainState::initial()
        .with_agents(
            vec!["claude".to_string()],
            vec![vec![]],
            AgentRole::Developer,
        )
        .with_max_cycles(3);
    chain = chain.start_retry_cycle();
    chain = chain.start_retry_cycle();
    chain = chain.start_retry_cycle();

    let state = PipelineState {
        phase: PipelinePhase::Development,
        iteration: 2,
        total_iterations: 5,
        checkpoint_saved_count: 1,
        agent_chain: chain,
        ..create_test_state()
    };
    let effect = determine_next_effect(&state);
    assert!(matches!(effect, Effect::ReportAgentChainExhausted { .. }));
}

#[test]
fn test_determine_effect_development_phase_with_chain() {
    let state = PipelineState {
        phase: PipelinePhase::Development,
        iteration: 2,
        total_iterations: 5,
        agent_chain: PipelineState::initial(5, 2).agent_chain.with_agents(
            vec!["claude".to_string()],
            vec![vec![]],
            AgentRole::Developer,
        ),
        ..create_test_state()
    };
    let effect = determine_next_effect(&state);
    assert!(matches!(effect, Effect::PrepareDevelopmentContext { .. }));
}

#[test]
fn test_same_agent_retry_in_development_retries_analysis_when_chain_role_is_analysis() {
    // Regression: analysis runs during Development phase. If the analysis agent times out or
    // otherwise fails in a same-agent-retryable way, orchestration must retry the analysis
    // invocation (not restart the developer prompt flow).
    let mut chain = AgentChainState::initial().with_agents(
        vec!["agent-a".to_string()],
        vec![vec![]],
        AgentRole::Analysis,
    );
    // Ensure chain is not considered exhausted.
    chain = chain.with_max_cycles(3);

    let state = PipelineState {
        phase: PipelinePhase::Development,
        iteration: 0,
        total_iterations: 1,
        agent_chain: chain,
        continuation: crate::reducer::state::ContinuationState {
            same_agent_retry_count: 1,
            same_agent_retry_pending: true,
            ..crate::reducer::state::ContinuationState::new()
        },
        ..create_test_state()
    };

    let effect = determine_next_effect(&state);
    assert!(matches!(
        effect,
        Effect::InvokeAnalysisAgent { iteration: 0 }
    ));
}

#[test]
fn test_development_initializes_analysis_chain_before_invoking_analysis() {
    // Regression: Analysis has its own fallback chain (FallbackConfig.analysis). The developer
    // chain must not be reused for analysis invocations.
    let chain = AgentChainState::initial().with_agents(
        vec!["dev-agent".to_string()],
        vec![vec![]],
        AgentRole::Developer,
    );

    let state = PipelineState {
        phase: PipelinePhase::Development,
        iteration: 1,
        total_iterations: 5,
        agent_chain: chain,
        development_context_prepared_iteration: Some(1),
        development_prompt_prepared_iteration: Some(1),
        development_required_files_cleaned_iteration: Some(1),
        development_agent_invoked_iteration: Some(1),
        analysis_agent_invoked_iteration: None,
        ..create_test_state()
    };

    let effect = determine_next_effect(&state);
    assert!(matches!(
        effect,
        Effect::InitializeAgentChain {
            drain: crate::agents::AgentDrain::Analysis,
            ..
        }
    ));
}

#[test]
fn test_determine_effect_development_complete() {
    let state = PipelineState {
        phase: PipelinePhase::Development,
        iteration: 6,
        total_iterations: 5,
        agent_chain: PipelineState::initial(5, 2).agent_chain.with_agents(
            vec!["claude".to_string()],
            vec![vec![]],
            AgentRole::Developer,
        ),
        ..create_test_state()
    };
    let effect = determine_next_effect(&state);
    assert!(matches!(effect, Effect::SaveCheckpoint { .. }));
}

#[test]
fn test_development_runs_exactly_n_iterations() {
    // When total_iterations=5, should run iterations 0,1,2,3,4 (5 total)
    let mut state = PipelineState::initial(5, 0);
    state.agent_chain = state.agent_chain.with_agents(
        vec!["claude".to_string()],
        vec![vec![]],
        AgentRole::Developer,
    );

    // Track which iterations actually run
    let mut iterations_run = Vec::new();

    // Simulate the development phase
    while state.phase == PipelinePhase::Planning
        || state.phase == PipelinePhase::Development
        || state.phase == PipelinePhase::CommitMessage
    {
        let effect = determine_next_effect(&state);

        match effect {
            Effect::EnsureGitignoreEntries => {
                state = reduce(
                    state,
                    PipelineEvent::gitignore_entries_ensured(
                        vec!["/PROMPT*".to_string(), ".agent/".to_string()],
                        vec![],
                        false,
                    ),
                );
            }
            Effect::CleanupContext => {
                // Context cleanup before planning
                state = reduce(state, PipelineEvent::ContextCleaned);
            }
            Effect::CleanupContinuationContext => {
                state = reduce(
                    state,
                    PipelineEvent::development_continuation_context_cleaned(),
                );
            }
            Effect::MaterializePlanningInputs { iteration } => {
                let sig = state.agent_chain.consumer_signature_sha256();
                state = reduce(
                    state,
                    PipelineEvent::planning_inputs_materialized(
                        iteration,
                        crate::reducer::state::MaterializedPromptInput {
                            kind: crate::reducer::state::PromptInputKind::Prompt,
                            content_id_sha256: "id".to_string(),
                            consumer_signature_sha256: sig,
                            original_bytes: 1,
                            final_bytes: 1,
                            model_budget_bytes: None,
                            inline_budget_bytes: None,
                            representation:
                                crate::reducer::state::PromptInputRepresentation::Inline,
                            reason:
                                crate::reducer::state::PromptMaterializationReason::WithinBudgets,
                        },
                    ),
                );
            }
            Effect::PreparePlanningPrompt { iteration, .. } => {
                state = reduce(state, PipelineEvent::planning_prompt_prepared(iteration));
            }
            Effect::CleanupRequiredFiles { files }
                if files.iter().any(|f| f.contains("plan.xml")) =>
            {
                let iteration = state.iteration;
                state = reduce(state, PipelineEvent::planning_xml_cleaned(iteration));
            }
            Effect::InvokePlanningAgent { iteration } => {
                state = reduce(state, PipelineEvent::planning_agent_invoked(iteration));
            }
            Effect::ExtractPlanningXml { iteration } => {
                state = reduce(state, PipelineEvent::planning_xml_extracted(iteration));
            }
            Effect::ValidatePlanningXml { iteration } => {
                state = reduce(
                    state,
                    PipelineEvent::planning_xml_validated(
                        iteration,
                        true,
                        Some("# Plan\n\n- step\n".to_string()),
                    ),
                );
            }
            Effect::WritePlanningMarkdown { iteration } => {
                state = reduce(state, PipelineEvent::planning_markdown_written(iteration));
            }
            Effect::ArchivePlanningXml { iteration } => {
                state = reduce(state, PipelineEvent::planning_xml_archived(iteration));
            }
            Effect::ApplyPlanningOutcome { iteration, valid } => {
                state = reduce(
                    state,
                    PipelineEvent::plan_generation_completed(iteration, valid),
                );
            }
            Effect::PrepareDevelopmentContext { iteration } => {
                state = reduce(
                    state,
                    PipelineEvent::development_context_prepared(iteration),
                );
            }
            Effect::MaterializeDevelopmentInputs { iteration } => {
                let sig = state.agent_chain.consumer_signature_sha256();
                let prompt = crate::reducer::state::MaterializedPromptInput {
                    kind: crate::reducer::state::PromptInputKind::Prompt,
                    content_id_sha256: "id".to_string(),
                    consumer_signature_sha256: sig.clone(),
                    original_bytes: 1,
                    final_bytes: 1,
                    model_budget_bytes: None,
                    inline_budget_bytes: None,
                    representation: crate::reducer::state::PromptInputRepresentation::Inline,
                    reason: crate::reducer::state::PromptMaterializationReason::WithinBudgets,
                };
                let plan = crate::reducer::state::MaterializedPromptInput {
                    kind: crate::reducer::state::PromptInputKind::Plan,
                    content_id_sha256: "id".to_string(),
                    consumer_signature_sha256: sig,
                    original_bytes: 1,
                    final_bytes: 1,
                    model_budget_bytes: None,
                    inline_budget_bytes: None,
                    representation: crate::reducer::state::PromptInputRepresentation::Inline,
                    reason: crate::reducer::state::PromptMaterializationReason::WithinBudgets,
                };
                state = reduce(
                    state,
                    PipelineEvent::development_inputs_materialized(iteration, prompt, plan),
                );
            }
            Effect::PrepareDevelopmentPrompt { iteration, .. } => {
                state = reduce(state, PipelineEvent::development_prompt_prepared(iteration));
            }
            Effect::CleanupRequiredFiles { files }
                if files.iter().any(|f| f.contains("development_result.xml")) =>
            {
                let iteration = state.iteration;
                state = reduce(state, PipelineEvent::development_xml_cleaned(iteration));
            }
            Effect::InvokeDevelopmentAgent { iteration } => {
                state = reduce(state, PipelineEvent::development_agent_invoked(iteration));
            }
            Effect::InvokeAnalysisAgent { iteration } => {
                state = reduce(
                    state,
                    PipelineEvent::Development(
                        crate::reducer::event::DevelopmentEvent::AnalysisAgentInvoked { iteration },
                    ),
                );
            }
            Effect::ExtractDevelopmentXml { iteration } => {
                state = reduce(state, PipelineEvent::development_xml_extracted(iteration));
            }
            Effect::ValidateDevelopmentXml { iteration } => {
                state = reduce(
                    state,
                    PipelineEvent::development_xml_validated(
                        iteration,
                        crate::reducer::state::DevelopmentStatus::Completed,
                        "done".to_string(),
                        None,
                        None,
                    ),
                );
            }
            Effect::ArchiveDevelopmentXml { iteration } => {
                state = reduce(state, PipelineEvent::development_xml_archived(iteration));
            }
            Effect::ApplyDevelopmentOutcome { iteration } => {
                iterations_run.push(iteration);
                state = reduce(
                    state,
                    PipelineEvent::development_iteration_completed(iteration, true),
                );
            }
            Effect::CheckCommitDiff => {
                state = reduce(
                    state,
                    PipelineEvent::commit_diff_prepared(false, "id".to_string()),
                );
            }
            Effect::MaterializeCommitInputs { attempt } => {
                let sig = state.agent_chain.consumer_signature_sha256();
                state = reduce(
                    state,
                    PipelineEvent::commit_inputs_materialized(
                        attempt,
                        crate::reducer::state::MaterializedPromptInput {
                            kind: crate::reducer::state::PromptInputKind::Diff,
                            content_id_sha256: "id".to_string(),
                            consumer_signature_sha256: sig,
                            original_bytes: 1,
                            final_bytes: 1,
                            model_budget_bytes: None,
                            inline_budget_bytes: None,
                            representation:
                                crate::reducer::state::PromptInputRepresentation::Inline,
                            reason:
                                crate::reducer::state::PromptMaterializationReason::WithinBudgets,
                        },
                    ),
                );
            }
            Effect::PrepareCommitPrompt { .. } => {
                state = reduce(state, PipelineEvent::commit_generation_started());
                state = reduce(state, PipelineEvent::commit_prompt_prepared(1));
            }
            Effect::CleanupRequiredFiles { files }
                if files.iter().any(|f| f.contains("commit_message.xml")) =>
            {
                state = reduce(state, PipelineEvent::commit_required_files_cleaned(1));
            }
            Effect::InvokeCommitAgent => {
                state = reduce(state, PipelineEvent::commit_agent_invoked(1));
            }
            Effect::ExtractCommitXml => {
                state = reduce(state, PipelineEvent::commit_xml_extracted(1));
            }
            Effect::ValidateCommitXml => {
                state = reduce(
                    state,
                    PipelineEvent::commit_xml_validated("test".to_string(), vec![], vec![], 1),
                );
            }
            Effect::ApplyCommitMessageOutcome => {
                state = reduce(
                    state,
                    PipelineEvent::commit_message_generated("test".to_string(), 1),
                );
            }
            Effect::ArchiveCommitXml => {
                state = reduce(state, PipelineEvent::commit_xml_archived(1));
            }
            Effect::CreateCommit { .. } => {
                state = reduce(
                    state,
                    PipelineEvent::commit_created(
                        format!("abc{}", iterations_run.len()),
                        "test".to_string(),
                    ),
                );
            }
            Effect::SaveCheckpoint { .. } => {
                // Phase complete
                break;
            }
            Effect::InitializeAgentChain { drain, .. } => {
                state = reduce(
                    state,
                    PipelineEvent::agent_chain_initialized(
                        drain,
                        vec![AgentName::from("claude")],
                        vec![],
                        3,
                        1000,
                        2.0,
                        60000,
                    ),
                );
            }
            Effect::LockPromptPermissions => {
                state = reduce(state, PipelineEvent::prompt_permissions_locked(None));
            }
            _ => panic!("Unexpected effect: {effect:?}"),
        }
    }

    // Should run exactly 5 iterations (0,1,2,3,4), not 6 (0,1,2,3,4,5)
    assert_eq!(
        iterations_run.len(),
        5,
        "Should run exactly 5 iterations, ran: {iterations_run:?}"
    );
    assert_eq!(
        iterations_run,
        vec![0, 1, 2, 3, 4],
        "Should run iterations 0-4"
    );
    // With total_reviewer_passes=0, we go to FinalValidation, not Review
    assert_eq!(
        state.phase,
        PipelinePhase::FinalValidation,
        "Should transition to FinalValidation after 5 iterations when reviewer_passes=0"
    );
}

#[test]
fn test_resume_at_final_iteration_should_run_development_not_skip() {
    // BUG REPRODUCTION: When checkpoint saved at iteration=1, total=1
    // and all progress flags are None (reset on resume),
    // orchestration should derive development work effects,
    // NOT SaveCheckpoint (which would skip to Review phase).

    let state = PipelineState {
        phase: PipelinePhase::Development,
        iteration: 1,
        total_iterations: 1,
        agent_chain: PipelineState::initial(1, 0).agent_chain.with_agents(
            vec!["claude".to_string()],
            vec![vec![]],
            AgentRole::Developer,
        ),
        // All progress flags None - simulating resume state
        development_context_prepared_iteration: None,
        development_prompt_prepared_iteration: None,
        development_required_files_cleaned_iteration: None,
        development_agent_invoked_iteration: None,
        analysis_agent_invoked_iteration: None,
        development_xml_extracted_iteration: None,
        development_validated_outcome: None,
        development_xml_archived_iteration: None,
        ..create_test_state()
    };

    let effect = determine_next_effect(&state);

    // CRITICAL: Should derive development work, NOT phase transition
    // This test verifies the fix: previously would fail, now passes
    assert!(
        matches!(effect, Effect::PrepareDevelopmentContext { .. }),
        "Expected PrepareDevelopmentContext, got {effect:?}"
    );
}

#[test]
fn test_resume_iteration_0_total_1_should_run_development() {
    // Edge case: iteration=0, total=1
    // 0 < 1 is true, so this case may already work
    // But include it to verify boundary behavior

    let state = PipelineState {
        phase: PipelinePhase::Development,
        iteration: 0,
        total_iterations: 1,
        agent_chain: PipelineState::initial(1, 0).agent_chain.with_agents(
            vec!["claude".to_string()],
            vec![vec![]],
            AgentRole::Developer,
        ),
        development_context_prepared_iteration: None,
        development_agent_invoked_iteration: None,
        ..create_test_state()
    };

    let effect = determine_next_effect(&state);

    assert!(
        matches!(effect, Effect::PrepareDevelopmentContext { .. }),
        "Expected PrepareDevelopmentContext for iteration 0, got {effect:?}"
    );
}

#[test]
fn test_timeout_context_write_derived_before_same_agent_retry() {
    // AC-1b: When a timeout with partial output occurs but the agent has no session ID,
    // orchestration must derive WriteTimeoutContext BEFORE the same-agent retry prompt.
    //
    // This test verifies the priority order:
    // 1. timeout_context_write_pending=true -> WriteTimeoutContext
    // 2. same_agent_retry_pending=true -> SameAgentRetry effect
    //
    // Without this ordering, the retry prompt would be prepared without the context file path,
    // and the agent would lose its partial progress.

    let mut chain = AgentChainState::initial().with_agents(
        vec!["agent-a".to_string()],
        vec![vec![]],
        AgentRole::Developer,
    );
    chain = chain.with_max_cycles(3);

    let state = PipelineState {
        phase: PipelinePhase::Development,
        iteration: 0,
        total_iterations: 1,
        agent_chain: chain,
        continuation: crate::reducer::state::ContinuationState {
            same_agent_retry_count: 1,
            same_agent_retry_pending: true,
            // CRITICAL: This flag must trigger WriteTimeoutContext, NOT SameAgentRetry
            timeout_context_write_pending: true,
            timeout_context_file_path: Some(".agent/logs/developer_1.log".to_string()),
            ..crate::reducer::state::ContinuationState::new()
        },
        ..create_test_state()
    };

    let effect = determine_next_effect(&state);

    // MUST derive WriteTimeoutContext, NOT PrepareDevelopmentPrompt with SameAgentRetry mode
    assert!(
        matches!(
            effect,
            Effect::WriteTimeoutContext {
                role: AgentRole::Developer,
                logfile_path: _,
                context_path: _,
            }
        ),
        "Expected WriteTimeoutContext when timeout_context_write_pending=true, got {effect:?}"
    );
}

#[test]
fn test_timeout_context_write_uses_correct_paths() {
    // Verify that WriteTimeoutContext effect uses:
    // - logfile_path from continuation.timeout_context_file_path (set by reducer)
    // - context_path generated based on retry attempt number

    let mut chain = AgentChainState::initial().with_agents(
        vec!["agent-a".to_string()],
        vec![vec![]],
        AgentRole::Developer,
    );
    chain = chain.with_max_cycles(3);

    let state = PipelineState {
        phase: PipelinePhase::Development,
        iteration: 0,
        total_iterations: 1,
        agent_chain: chain,
        continuation: crate::reducer::state::ContinuationState {
            same_agent_retry_count: 2,
            timeout_context_write_pending: true,
            timeout_context_file_path: Some(".agent/logs/developer_1_a1.log".to_string()),
            ..crate::reducer::state::ContinuationState::new()
        },
        ..create_test_state()
    };

    let effect = determine_next_effect(&state);

    if let Effect::WriteTimeoutContext {
        logfile_path,
        context_path,
        ..
    } = effect
    {
        // logfile_path must match what reducer stored
        assert_eq!(
            logfile_path, ".agent/logs/developer_1_a1.log",
            "logfile_path should match timeout_context_file_path from continuation state"
        );
        // context_path should be generated based on retry count
        assert!(
            context_path.contains("timeout_context_2"),
            "context_path should contain retry count, got: {context_path}"
        );
    } else {
        panic!("Expected WriteTimeoutContext effect, got {effect:?}");
    }
}

#[test]
fn test_completed_final_iteration_should_transition_not_rerun() {
    // Verify: When iteration=total AND work is actually done
    // (development_xml_archived_iteration is Some),
    // orchestration should transition to next phase, not re-run work.
    use crate::reducer::state::DevelopmentStatus;
    use crate::reducer::state::DevelopmentValidatedOutcome;

    let state = PipelineState {
        phase: PipelinePhase::Development,
        iteration: 1,
        total_iterations: 1,
        agent_chain: PipelineState::initial(1, 0).agent_chain.with_agents(
            vec!["claude".to_string()],
            vec![vec![]],
            AgentRole::Developer,
        ),
        // All progress flags set - work is DONE
        development_context_prepared_iteration: Some(1),
        development_prompt_prepared_iteration: Some(1),
        development_required_files_cleaned_iteration: Some(1),
        development_agent_invoked_iteration: Some(1),
        analysis_agent_invoked_iteration: Some(1),
        development_xml_extracted_iteration: Some(1),
        development_validated_outcome: Some(DevelopmentValidatedOutcome {
            iteration: 1,
            status: DevelopmentStatus::Completed,
            summary: "Test complete".to_string(),
            files_changed: None,
            next_steps: None,
        }),
        development_xml_archived_iteration: Some(1),
        ..create_test_state()
    };

    let effect = determine_next_effect(&state);

    // Should derive ApplyDevelopmentOutcome (next step after archiving)
    // NOT re-run development work
    assert!(
        matches!(effect, Effect::ApplyDevelopmentOutcome { .. }),
        "Expected ApplyDevelopmentOutcome for completed iteration, got {effect:?}"
    );
}

#[test]
fn test_resume_at_final_iteration_with_partial_progress_continues() {
    // Edge case: agent was invoked but iteration not fully archived
    // This simulates a crash after agent invocation but before XML archival

    let state = PipelineState {
        phase: PipelinePhase::Development,
        iteration: 1,
        total_iterations: 1,
        agent_chain: AgentChainState::initial().with_agents(
            vec!["claude".to_string()],
            vec![vec![]],
            AgentRole::Developer,
        ),
        development_agent_invoked_iteration: Some(1),
        development_xml_archived_iteration: None, // Not archived yet
        ..create_test_state()
    };

    let effect = determine_next_effect(&state);

    // Should NOT skip to SaveCheckpoint - should continue processing
    // The next effect should be InvokeAnalysisAgent or ExtractDevelopmentXml
    assert!(
        !matches!(effect, Effect::SaveCheckpoint { .. }),
        "Should not SaveCheckpoint with partial progress, got {effect:?}"
    );
}

#[test]
fn test_resume_at_iteration_zero_with_total_one_runs_work() {
    // Boundary case: iteration=0, total_iterations=1
    // This is the first (and only) iteration - should run

    let state = PipelineState {
        phase: PipelinePhase::Development,
        iteration: 0,
        total_iterations: 1,
        agent_chain: AgentChainState::initial().with_agents(
            vec!["claude".to_string()],
            vec![vec![]],
            AgentRole::Developer,
        ),
        development_agent_invoked_iteration: None,
        ..create_test_state()
    };

    let effect = determine_next_effect(&state);

    // iteration < total_iterations (0 < 1), so should run
    assert!(
        matches!(effect, Effect::PrepareDevelopmentContext { iteration: 0 }),
        "Expected PrepareDevelopmentContext but got {effect:?}"
    );
}