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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
// Commit phase tests.
//
// Tests for commit phase effect determination, agent chain states,
// diff checking, and commit message generation.

use super::*;

#[test]
fn test_determine_effect_commit_message_empty_chain() {
    // When agent chain is empty, commit phase should request initialization
    let state = PipelineState {
        phase: PipelinePhase::CommitMessage,
        commit: CommitState::NotStarted,
        agent_chain: AgentChainState::initial(),
        ..create_test_state()
    };
    let effect = determine_next_effect(&state);
    assert!(matches!(
        effect,
        Effect::InitializeAgentChain {
            drain: crate::agents::AgentDrain::Commit,
            ..
        }
    ));
}

#[test]
fn test_determine_effect_commit_message_role_mismatch_reinitializes_chain() {
    // Regression: entering CommitMessage with a non-commit agent chain must still
    // initialize the commit chain so FallbackConfig.commit is honored.
    let chain = AgentChainState::initial().with_agents(
        vec!["dev-agent".to_string()],
        vec![vec![]],
        AgentRole::Developer,
    );
    let state = PipelineState {
        phase: PipelinePhase::CommitMessage,
        commit: CommitState::NotStarted,
        agent_chain: chain,
        ..create_test_state()
    };

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

#[test]
fn test_determine_effect_commit_message_not_started() {
    // With initialized agent chain and diff prepared, commit phase should prepare prompt
    let state = PipelineState {
        phase: PipelinePhase::CommitMessage,
        commit: CommitState::NotStarted,
        commit_diff_prepared: true, // Diff already done
        commit_diff_content_id_sha256: Some("id".to_string()),
        agent_chain: PipelineState::initial(5, 2).agent_chain.with_agents(
            vec!["commit-agent".to_string()],
            vec![vec![]],
            AgentRole::Commit,
        ),
        ..create_test_state()
    };
    let effect = determine_next_effect(&state);
    assert!(matches!(effect, Effect::MaterializeCommitInputs { .. }));
}

#[test]
fn test_commit_phase_uses_xsd_retry_prompt_when_pending() {
    // When XSD retry is pending, orchestration should select the XSD retry prompt mode
    // instead of the normal prompt mode. This ensures we converge on valid XML quickly.
    let state = PipelineState {
        phase: PipelinePhase::CommitMessage,
        commit: CommitState::Generating {
            attempt: 1,
            max_attempts: 3,
        },
        commit_diff_prepared: true,
        commit_diff_empty: false,
        commit_diff_content_id_sha256: Some("id".to_string()),
        commit_prompt_prepared: false,
        agent_chain: PipelineState::initial(5, 2).agent_chain.with_agents(
            vec!["commit-agent".to_string()],
            vec![vec![]],
            AgentRole::Commit,
        ),
        prompt_inputs: crate::reducer::state::PromptInputsState {
            commit: Some(crate::reducer::state::MaterializedCommitInputs {
                attempt: 1,
                diff: crate::reducer::state::MaterializedPromptInput {
                    kind: crate::reducer::state::PromptInputKind::Diff,
                    content_id_sha256: "id".to_string(),
                    consumer_signature_sha256: PipelineState::initial(5, 2)
                        .agent_chain
                        .with_agents(
                            vec!["commit-agent".to_string()],
                            vec![vec![]],
                            AgentRole::Commit,
                        )
                        .consumer_signature_sha256(),
                    original_bytes: 1,
                    final_bytes: 1,
                    model_budget_bytes: Some(200_000),
                    inline_budget_bytes: Some(100_000),
                    representation: crate::reducer::state::PromptInputRepresentation::Inline,
                    reason: crate::reducer::state::PromptMaterializationReason::WithinBudgets,
                },
            }),
            ..Default::default()
        },
        continuation: crate::reducer::state::ContinuationState {
            xsd_retry_pending: true,
            ..crate::reducer::state::ContinuationState::default()
        },
        ..create_test_state()
    };

    let effect = determine_next_effect(&state);
    assert!(
        matches!(
            effect,
            Effect::PrepareCommitPrompt {
                prompt_mode: PromptMode::XsdRetry
            }
        ),
        "Expected XSD retry prompt when xsd_retry_pending=true, got {effect:?}"
    );
}

#[test]
fn test_commit_phase_effects_uses_xsd_retry_prompt_mode_when_pending() {
    // Regression: phase-specific commit orchestration must also derive the XSD retry
    // prompt mode when the reducer marks xsd_retry_pending, so retry prompts remain
    // reachable even if retry routing is bypassed (e.g., during refactors or targeted
    // phase effect determination).
    let state = PipelineState {
        phase: PipelinePhase::CommitMessage,
        commit: CommitState::Generating {
            attempt: 1,
            max_attempts: 3,
        },
        commit_diff_prepared: true,
        commit_diff_empty: false,
        commit_diff_content_id_sha256: Some("id".to_string()),
        commit_prompt_prepared: false,
        agent_chain: PipelineState::initial(5, 2).agent_chain.with_agents(
            vec!["commit-agent".to_string()],
            vec![vec![]],
            AgentRole::Commit,
        ),
        prompt_inputs: crate::reducer::state::PromptInputsState {
            commit: Some(crate::reducer::state::MaterializedCommitInputs {
                attempt: 1,
                diff: crate::reducer::state::MaterializedPromptInput {
                    kind: crate::reducer::state::PromptInputKind::Diff,
                    content_id_sha256: "id".to_string(),
                    consumer_signature_sha256: PipelineState::initial(5, 2)
                        .agent_chain
                        .with_agents(
                            vec!["commit-agent".to_string()],
                            vec![vec![]],
                            AgentRole::Commit,
                        )
                        .consumer_signature_sha256(),
                    original_bytes: 1,
                    final_bytes: 1,
                    model_budget_bytes: Some(200_000),
                    inline_budget_bytes: Some(100_000),
                    representation: crate::reducer::state::PromptInputRepresentation::Inline,
                    reason: crate::reducer::state::PromptMaterializationReason::WithinBudgets,
                },
            }),
            ..Default::default()
        },
        continuation: crate::reducer::state::ContinuationState {
            xsd_retry_pending: true,
            xsd_retry_count: 1,
            max_xsd_retry_count: 10,
            ..crate::reducer::state::ContinuationState::default()
        },
        ..create_test_state()
    };

    let effect = determine_next_effect_for_phase(&state);
    assert!(
        matches!(
            effect,
            Effect::PrepareCommitPrompt {
                prompt_mode: PromptMode::XsdRetry
            }
        ),
        "Expected phase effect to use XSD retry prompt when xsd_retry_pending=true, got {effect:?}"
    );
}

#[test]
fn test_determine_effect_commit_message_ignores_stale_validated_outcome() {
    // Stale outcome (attempt 1) should be ignored when current attempt is 2
    // Should proceed to prepare prompt instead of applying stale outcome
    let state = PipelineState {
        phase: PipelinePhase::CommitMessage,
        commit: CommitState::Generating {
            attempt: 2,
            max_attempts: 5,
        },
        commit_diff_prepared: true, // Diff already done
        commit_diff_content_id_sha256: Some("id".to_string()),
        commit_prompt_prepared: false,
        commit_agent_invoked: false,
        commit_xml_extracted: false,
        commit_validated_outcome: Some(crate::reducer::state::CommitValidatedOutcome {
            attempt: 1, // Stale: from attempt 1, not current attempt 2
            message: Some("stale message".to_string()),
            reason: None,
        }),
        agent_chain: PipelineState::initial(5, 2).agent_chain.with_agents(
            vec!["commit-agent".to_string()],
            vec![vec![]],
            AgentRole::Commit,
        ),
        ..create_test_state()
    };

    let effect = determine_next_effect(&state);
    assert!(matches!(effect, Effect::MaterializeCommitInputs { .. }));
}

#[test]
fn test_determine_effect_commit_message_generated() {
    let state = PipelineState {
        phase: PipelinePhase::CommitMessage,
        commit: CommitState::Generated {
            message: "test commit message".to_string(),
        },
        commit_xml_archived: true,
        agent_chain: PipelineState::initial(5, 2).agent_chain.with_agents(
            vec!["commit-agent".to_string()],
            vec![vec![]],
            AgentRole::Commit,
        ),
        ..create_test_state()
    };
    let effect = determine_next_effect(&state);
    match effect {
        Effect::CreateCommit { message, .. } => {
            assert_eq!(message, "test commit message");
        }
        _ => panic!("Expected CreateCommit effect, got {effect:?}"),
    }
}

#[test]
fn test_determine_effect_commit_message_rematerializes_when_consumer_signature_changes() {
    // If the consumer set (agent chain + models + role) changes mid-attempt,
    // we must re-materialize commit inputs so model budget decisions stay safe.
    let mut state = PipelineState {
        phase: PipelinePhase::CommitMessage,
        commit: CommitState::Generating {
            attempt: 1,
            max_attempts: 3,
        },
        commit_diff_prepared: true,
        commit_diff_empty: false,
        commit_diff_content_id_sha256: Some("id".to_string()),
        commit_prompt_prepared: false,
        agent_chain: PipelineState::initial(5, 2).agent_chain.with_agents(
            vec!["commit-agent".to_string(), "fallback-agent".to_string()],
            vec![vec!["model-a".to_string()], vec!["model-b".to_string()]],
            AgentRole::Commit,
        ),
        prompt_inputs: crate::reducer::state::PromptInputsState {
            commit: Some(crate::reducer::state::MaterializedCommitInputs {
                attempt: 1,
                diff: crate::reducer::state::MaterializedPromptInput {
                    kind: crate::reducer::state::PromptInputKind::Diff,
                    content_id_sha256: "id".to_string(),
                    consumer_signature_sha256: "stale_sig".to_string(),
                    original_bytes: 1,
                    final_bytes: 1,
                    model_budget_bytes: Some(200_000),
                    inline_budget_bytes: Some(100_000),
                    representation: crate::reducer::state::PromptInputRepresentation::Inline,
                    reason: crate::reducer::state::PromptMaterializationReason::WithinBudgets,
                },
            }),
            ..Default::default()
        },
        ..create_test_state()
    };

    // Ensure the agent chain signature is different from the stored one.
    let expected_sig = state.agent_chain.consumer_signature_sha256();
    assert_ne!(
        expected_sig, "stale_sig",
        "test setup error: consumer signature should differ"
    );

    let effect = determine_next_effect(&state);
    assert!(
        matches!(effect, Effect::MaterializeCommitInputs { attempt: 1 }),
        "Expected re-materialization when consumer signature changes, got {effect:?}"
    );

    // Changing current agent/model indices should not change the signature and should not
    // force re-materialization once signatures match.
    state
        .prompt_inputs
        .commit
        .as_mut()
        .unwrap()
        .diff
        .consumer_signature_sha256 = expected_sig;
    state.agent_chain.current_agent_index = 1;
    let effect = determine_next_effect(&state);
    assert!(
        !matches!(effect, Effect::MaterializeCommitInputs { .. }),
        "Expected no re-materialization when only current agent index changes, got {effect:?}"
    );
}

#[test]
fn test_recovery_does_not_emit_success_before_create_commit() {
    // Regression: when recovering from a commit failure, we must NOT clear recovery
    // counters before the actually-failing operation (CreateCommit) succeeds.
    //
    // Previously, commit orchestration emitted EmitRecoverySuccess as soon as
    // commit_xml_archived=true, which can be true even though CreateCommit will fail.
    let state = PipelineState {
        phase: PipelinePhase::CommitMessage,
        previous_phase: Some(PipelinePhase::AwaitingDevFix),
        failed_phase_for_recovery: Some(PipelinePhase::CommitMessage),
        dev_fix_attempt_count: 2,
        recovery_escalation_level: 1,
        commit: CommitState::Generated {
            message: "msg".to_string(),
        },
        commit_xml_archived: true,
        agent_chain: PipelineState::initial(5, 2).agent_chain.with_agents(
            vec!["commit-agent".to_string()],
            vec![vec![]],
            AgentRole::Commit,
        ),
        ..create_test_state()
    };

    let effect = determine_next_effect(&state);

    assert!(
        matches!(effect, Effect::CreateCommit { .. }),
        "expected CreateCommit (do not clear recovery state yet), got: {effect:?}"
    );
}

#[test]
fn test_recovery_emits_success_after_commit_created() {
    // Once CreateCommit has succeeded (CommitState::Committed), recovery success
    // should be emitted to clear attempt counters before continuing.
    let state = PipelineState {
        phase: PipelinePhase::FinalValidation,
        failed_phase_for_recovery: Some(PipelinePhase::CommitMessage),
        dev_fix_attempt_count: 3,
        recovery_escalation_level: 2,
        commit: CommitState::Committed {
            hash: "abc123".to_string(),
        },
        ..create_test_state()
    };

    let effect = determine_next_effect(&state);

    assert!(
        matches!(effect, Effect::EmitRecoverySuccess { .. }),
        "expected EmitRecoverySuccess after commit created, got: {effect:?}"
    );
}

#[test]
fn test_committed_retry_pass_emits_matching_residual_check() {
    let mut state = create_test_state();
    state.phase = PipelinePhase::CommitMessage;
    state.commit = CommitState::Committed {
        hash: "abc123".to_string(),
    };
    state.agent_chain = AgentChainState::initial().with_agents(
        vec!["commit-agent".to_string()],
        vec![vec![]],
        AgentRole::Commit,
    );
    state.commit_residual_retry_pass = 3;

    let effect = determine_next_effect(&state);

    assert!(
        matches!(effect, Effect::CheckResidualFiles { pass: 3 }),
        "Committed retry pass must emit CheckResidualFiles for the same retry pass"
    );
}

#[test]
fn test_determine_effect_final_validation() {
    let mut state = PipelineState {
        phase: PipelinePhase::FinalValidation,
        ..create_test_state()
    };

    // First cycle: pre-termination safety check
    let effect = determine_next_effect(&state);
    assert!(
        matches!(effect, Effect::CheckUncommittedChangesBeforeTermination),
        "FinalValidation should first check for uncommitted changes"
    );

    // After safety check passes, should derive ValidateFinalState
    state.pre_termination_commit_checked = true;
    let effect = determine_next_effect(&state);
    assert!(
        matches!(effect, Effect::ValidateFinalState),
        "After safety check, FinalValidation should derive ValidateFinalState"
    );
}

#[test]
fn test_check_commit_diff_emitted_on_each_commit_phase_entry() {
    // Regression: in a multi-iteration pipeline (dev → commit → planning → dev → commit),
    // CheckCommitDiff must be emitted ONCE per commit-phase entry, not skipped on second entry.
    //
    // This test catches the bug where commit_diff_prepared survives across phase transitions
    // (via ..state spread) and causes the orchestrator guard to skip CheckCommitDiff on
    // the second commit phase entry.
    let mut state = PipelineState::initial(2, 0); // 2 dev iterations, 0 reviewer passes
    state.agent_chain = state.agent_chain.with_agents(
        vec!["commit-agent".to_string()],
        vec![vec![]],
        AgentRole::Commit,
    );

    let mut check_diff_count = 0usize;
    let max_steps = 200;

    for step in 0..max_steps {
        let effect = determine_next_effect(&state);

        match effect {
            Effect::CheckCommitDiff => {
                check_diff_count += 1;
                state = reduce(
                    state,
                    PipelineEvent::commit_diff_prepared(false, format!("hash-{check_diff_count}")),
                );
            }
            Effect::LockPromptPermissions => {
                state = reduce(state, PipelineEvent::prompt_permissions_locked(None));
            }
            Effect::RestorePromptPermissions => {
                state = reduce(state, PipelineEvent::prompt_permissions_restored());
            }
            Effect::EnsureGitignoreEntries => {
                state = reduce(
                    state,
                    PipelineEvent::gitignore_entries_ensured(
                        vec!["/PROMPT*".to_string(), ".agent/".to_string()],
                        vec![],
                        false,
                    ),
                );
            }
            Effect::CleanupContext => {
                state = reduce(state, PipelineEvent::ContextCleaned);
            }
            Effect::CleanupContinuationContext => {
                state = reduce(
                    state,
                    PipelineEvent::development_continuation_context_cleaned(),
                );
            }
            Effect::InitializeAgentChain { drain, .. } => {
                state = reduce(
                    state,
                    PipelineEvent::agent_chain_initialized(
                        drain,
                        vec![AgentName::from("commit-agent")],
                        vec![],
                        3,
                        1000,
                        2.0,
                        60000,
                    ),
                );
            }
            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::CleanupRequiredFiles { ref files }
                if files.iter().any(|f| f.contains("plan.xml")) =>
            {
                let iteration = state.iteration;
                state = reduce(state, PipelineEvent::planning_xml_cleaned(iteration));
            }
            Effect::PreparePlanningPrompt { iteration, .. } => {
                state = reduce(state, PipelineEvent::planning_prompt_prepared(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::CleanupRequiredFiles { ref files }
                if files.iter().any(|f| f.contains("development_result.xml")) =>
            {
                let iteration = state.iteration;
                state = reduce(state, PipelineEvent::development_xml_cleaned(iteration));
            }
            Effect::PrepareDevelopmentPrompt { iteration, .. } => {
                state = reduce(state, PipelineEvent::development_prompt_prepared(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 } => {
                state = reduce(
                    state,
                    PipelineEvent::development_iteration_completed(iteration, true),
                );
            }
            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: format!("hash-{check_diff_count}"),
                            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 { ref 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 commit".to_string(),
                        vec![],
                        vec![],
                        1,
                    ),
                );
            }
            Effect::ApplyCommitMessageOutcome => {
                state = reduce(
                    state,
                    PipelineEvent::commit_message_generated("test commit".to_string(), 1),
                );
            }
            Effect::ArchiveCommitXml => {
                state = reduce(state, PipelineEvent::commit_xml_archived(1));
            }
            Effect::CreateCommit { .. } => {
                state = reduce(
                    state,
                    PipelineEvent::commit_created(
                        format!("sha-{check_diff_count}"),
                        "test commit".to_string(),
                    ),
                );
            }
            Effect::CheckUncommittedChangesBeforeTermination => {
                state = reduce(state, PipelineEvent::pre_termination_safety_check_passed());
            }
            Effect::ValidateFinalState => {
                state = reduce(state, PipelineEvent::finalizing_started());
            }
            Effect::SaveCheckpoint { .. } => {
                if state.phase == PipelinePhase::Complete {
                    break;
                }
            }
            _ => panic!("Unexpected effect at step {step}: {effect:?}"),
        }

        if state.phase == PipelinePhase::Complete {
            break;
        }
    }

    assert_eq!(
        state.phase,
        PipelinePhase::Complete,
        "Pipeline should complete"
    );
    assert_eq!(
        check_diff_count, 2,
        "CheckCommitDiff must be emitted exactly once per commit phase entry \
         (2 dev iterations = 2 commit phases)"
    );
}

#[test]
fn test_determine_effect_complete() {
    let mut state = PipelineState {
        phase: PipelinePhase::Complete,
        ..create_test_state()
    };

    // First cycle: pre-termination safety check
    let effect = determine_next_effect(&state);
    assert!(matches!(
        effect,
        Effect::CheckUncommittedChangesBeforeTermination
    ));

    // After safety check passes, SaveCheckpoint is derived
    state.pre_termination_commit_checked = true;
    let effect = determine_next_effect(&state);
    assert!(matches!(effect, Effect::SaveCheckpoint { .. }));
}

#[test]
fn test_commit_orchestrator_never_derives_continuation_mode() {
    // Phase 4 policy violation fix: commit orchestrator must constrain prompt_mode
    // to admissible set {Normal, XsdRetry, SameAgentRetry} before deriving
    // Effect::PrepareCommitPrompt. Continuation mode is semantically invalid for
    // commit phase (commit is atomic, not incremental work).
    //
    // This test exhaustively checks all reducer state combinations that could
    // theoretically trigger PrepareCommitPrompt derivation and ensures none
    // derive Continuation mode.

    use crate::reducer::state::PromptMode;

    // Helper to build minimal state for prompt preparation
    let base_state = || PipelineState {
        phase: PipelinePhase::CommitMessage,
        commit: CommitState::Generating {
            attempt: 1,
            max_attempts: 3,
        },
        commit_diff_prepared: true,
        commit_diff_empty: false,
        commit_diff_content_id_sha256: Some("test_diff_id".to_string()),
        commit_prompt_prepared: false,
        agent_chain: PipelineState::initial(5, 2).agent_chain.with_agents(
            vec!["commit-agent".to_string()],
            vec![vec![]],
            AgentRole::Commit,
        ),
        prompt_inputs: crate::reducer::state::PromptInputsState {
            commit: Some(crate::reducer::state::MaterializedCommitInputs {
                attempt: 1,
                diff: crate::reducer::state::MaterializedPromptInput {
                    kind: crate::reducer::state::PromptInputKind::Diff,
                    content_id_sha256: "test_diff_id".to_string(),
                    consumer_signature_sha256: "test_consumer".to_string(),
                    original_bytes: 100,
                    final_bytes: 100,
                    model_budget_bytes: Some(1000),
                    inline_budget_bytes: Some(500),
                    representation: crate::reducer::state::PromptInputRepresentation::Inline,
                    reason: crate::reducer::state::PromptMaterializationReason::WithinBudgets,
                },
            }),
            ..Default::default()
        },
        ..create_test_state()
    };

    // Test case 1: Normal mode (no retries pending)
    let state = base_state();
    let effect = determine_next_effect(&state);
    if let Effect::PrepareCommitPrompt { prompt_mode } = effect {
        assert_eq!(
            prompt_mode,
            PromptMode::Normal,
            "Normal path should derive Normal mode"
        );
    }

    // Test case 2: Same-agent retry pending
    let mut state = base_state();
    state.continuation.same_agent_retry_pending = true;
    state.continuation.same_agent_retry_count = 0;
    let effect = determine_next_effect(&state);
    if let Effect::PrepareCommitPrompt { prompt_mode } = effect {
        assert_eq!(
            prompt_mode,
            PromptMode::SameAgentRetry,
            "Same-agent retry should derive SameAgentRetry mode"
        );
    }

    // Test case 3: XSD retry pending
    let mut state = base_state();
    state.continuation.xsd_retry_pending = true;
    state.continuation.xsd_retry_count = 0;
    let effect = determine_next_effect(&state);
    if let Effect::PrepareCommitPrompt { prompt_mode } = effect {
        assert_eq!(
            prompt_mode,
            PromptMode::XsdRetry,
            "XSD retry should derive XsdRetry mode"
        );
    }

    // Test case 4: Both retries pending (same-agent takes priority per orchestration logic)
    let mut state = base_state();
    state.continuation.same_agent_retry_pending = true;
    state.continuation.same_agent_retry_count = 0;
    state.continuation.xsd_retry_pending = true;
    state.continuation.xsd_retry_count = 0;
    let effect = determine_next_effect(&state);
    if let Effect::PrepareCommitPrompt { prompt_mode } = effect {
        assert_ne!(
            prompt_mode,
            PromptMode::Continuation,
            "Commit phase must never derive Continuation mode (even with both retries)"
        );
    }

    // Test case 5: Neither retry pending (clean state, should be Normal)
    let mut state = base_state();
    state.continuation.same_agent_retry_pending = false;
    state.continuation.xsd_retry_pending = false;
    let effect = determine_next_effect(&state);
    if let Effect::PrepareCommitPrompt { prompt_mode } = effect {
        assert_eq!(
            prompt_mode,
            PromptMode::Normal,
            "Clean continuation state should derive Normal mode, not Continuation"
        );
    }
}