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
//! Commit phase reducer tests.
//!
//! Tests for commit-related event handling in the state reduction layer.

use crate::reducer::event::*;
use crate::reducer::state::*;
use crate::reducer::state_reduction::reduce;

#[test]
fn test_diff_failed_event_is_noop_for_backward_compatibility() {
    // DiffFailed is deprecated and should not be emitted by current handler code.
    // If received (e.g., from old checkpoint), it should be a no-op to avoid termination.

    let mut state = PipelineState::initial(1, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.commit_diff_prepared = true;
    state.commit_diff_empty = false;
    state.commit_diff_content_id_sha256 = Some("abc123".to_string());

    let event = PipelineEvent::commit_diff_failed("git diff failed".to_string());
    let new_state = reduce(state.clone(), event);

    // Event should be no-op: state unchanged
    assert_eq!(new_state.phase, state.phase);
    assert_eq!(new_state.commit_diff_prepared, state.commit_diff_prepared);
    assert_eq!(new_state.commit_diff_empty, state.commit_diff_empty);
    assert_eq!(
        new_state.commit_diff_content_id_sha256,
        state.commit_diff_content_id_sha256
    );

    // Should NOT transition to Interrupted
    assert_ne!(new_state.phase, PipelinePhase::Interrupted);
}

#[test]
fn test_diff_prepared_event_sets_flags() {
    let mut state = PipelineState::initial(1, 0);
    state.phase = PipelinePhase::CommitMessage;

    let event = PipelineEvent::commit_diff_prepared(false, "content_hash".to_string());
    let new_state = reduce(state, event);

    assert!(new_state.commit_diff_prepared);
    assert!(!new_state.commit_diff_empty);
    assert_eq!(
        new_state.commit_diff_content_id_sha256,
        Some("content_hash".to_string())
    );
}

#[test]
fn test_diff_prepared_empty_sets_empty_flag() {
    let mut state = PipelineState::initial(1, 0);
    state.phase = PipelinePhase::CommitMessage;

    let event = PipelineEvent::commit_diff_prepared(true, "empty_hash".to_string());
    let new_state = reduce(state, event);

    assert!(new_state.commit_diff_prepared);
    assert!(new_state.commit_diff_empty);
    assert_eq!(
        new_state.commit_diff_content_id_sha256,
        Some("empty_hash".to_string())
    );
}

#[test]
fn test_diff_invalidated_clears_flags() {
    let mut state = PipelineState::initial(1, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.commit_diff_prepared = true;
    state.commit_diff_empty = false;
    state.commit_diff_content_id_sha256 = Some("old_hash".to_string());
    state.commit_prompt_prepared = true;

    let event = PipelineEvent::commit_diff_invalidated("Diff file missing".to_string());
    let new_state = reduce(state, event);

    assert!(!new_state.commit_diff_prepared);
    assert!(!new_state.commit_diff_empty);
    assert_eq!(new_state.commit_diff_content_id_sha256, None);
    assert!(!new_state.commit_prompt_prepared);
}

#[test]
fn test_pre_termination_uncommitted_changes_routes_back_to_commit_phase() {
    // When the pre-termination safety check finds uncommitted changes, the reducer must
    // route back through the commit phase (unattended-mode safety), recording the
    // phase we should resume after committing.
    let mut state = PipelineState::initial(0, 0);
    state.phase = PipelinePhase::Complete;
    state.pre_termination_commit_checked = false;
    state.termination_resume_phase = None;

    let event = PipelineEvent::pre_termination_uncommitted_changes_detected(3);
    let new_state = reduce(state, event);

    assert_eq!(new_state.phase, PipelinePhase::CommitMessage);
    assert_eq!(
        new_state.termination_resume_phase,
        Some(PipelinePhase::Complete)
    );
}

#[test]
fn test_post_commit_resumes_termination_phase_when_safety_commit_pending() {
    // If we routed into CommitMessage due to the pre-termination safety check,
    // a successful commit must resume the original termination phase and allow
    // termination to proceed.
    let mut state = PipelineState::initial(0, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.termination_resume_phase = Some(PipelinePhase::Complete);
    state.pre_termination_commit_checked = false;

    let new_state = reduce(
        state,
        PipelineEvent::commit_created("abc123".to_string(), "msg".to_string()),
    );

    assert_eq!(new_state.phase, PipelinePhase::Complete);
    assert_eq!(new_state.termination_resume_phase, None);
    assert!(
        !new_state.pre_termination_commit_checked,
        "Safety commit completion must NOT auto-unblock termination; the pre-termination \
         safety check must re-run to confirm the repo is clean"
    );
}

#[test]
fn test_skip_does_not_unblock_termination_when_safety_commit_pending() {
    // If the pre-termination safety check detected a dirty repo and routed into CommitMessage,
    // an AI-driven "skip" must NOT unblock termination.
    //
    // The pipeline must re-run CheckUncommittedChangesBeforeTermination after any skip and only
    // proceed once the repo is actually clean.
    let mut state = PipelineState::initial(0, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.termination_resume_phase = Some(PipelinePhase::Complete);
    state.pre_termination_commit_checked = false;

    let new_state = reduce(
        state,
        PipelineEvent::commit_skipped("no changes".to_string()),
    );

    assert_eq!(new_state.phase, PipelinePhase::Complete);
    assert_eq!(new_state.termination_resume_phase, None);
    assert!(
        !new_state.pre_termination_commit_checked,
        "Skip during safety-check commit must not unblock termination"
    );
}

#[test]
fn test_empty_diff_skip_unblocks_termination_when_safety_commit_pending() {
    // When the pre-termination safety check detected a dirty repo and routed into
    // CommitMessage, but the diff is empty (orchestration-initiated skip, not AI-driven),
    // the repo has nothing to commit. The skip MUST unblock termination to prevent an
    // infinite loop: safety check → commit phase → empty diff → skip → safety check → ...
    let mut state = PipelineState::initial(0, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.termination_resume_phase = Some(PipelinePhase::Complete);
    state.pre_termination_commit_checked = false;
    state.commit_diff_empty = true; // Orchestration detected empty diff

    let new_state = reduce(
        state,
        PipelineEvent::commit_skipped("No changes to commit (empty diff)".to_string()),
    );

    assert_eq!(new_state.phase, PipelinePhase::Complete);
    assert_eq!(new_state.termination_resume_phase, None);
    assert!(
        new_state.pre_termination_commit_checked,
        "Empty-diff skip during safety-check commit must unblock termination \
         to prevent infinite loop"
    );
}

#[test]
fn test_created_normal_resets_commit_diff_prepared() {
    // After a successful commit (normal path), commit_diff_prepared must be reset to false
    // so the next entry into the commit phase always re-checks the diff.
    let mut state = PipelineState::initial(2, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.previous_phase = Some(PipelinePhase::Development);
    state.iteration = 0;
    state.commit_diff_prepared = true;
    state.commit_diff_empty = false;
    state.commit_diff_content_id_sha256 = Some("hash-to-reset".to_string());
    // termination_resume_phase is None by default => normal path

    let new_state = reduce(
        state,
        PipelineEvent::commit_created("abc123".to_string(), "fix: something".to_string()),
    );

    assert!(
        !new_state.commit_diff_prepared,
        "commit_diff_prepared must be false after CommitEvent::Created (normal path)"
    );
    assert!(
        !new_state.commit_diff_empty,
        "commit_diff_empty must be false after CommitEvent::Created (normal path)"
    );
    assert_eq!(
        new_state.commit_diff_content_id_sha256, None,
        "commit_diff_content_id_sha256 must be None after CommitEvent::Created (normal path)"
    );
}

#[test]
fn test_created_pre_termination_resets_commit_diff_prepared() {
    // After a successful commit in the pre-termination safety path, commit_diff_prepared must
    // be reset to false so the next commit-phase entry always re-checks the diff.
    let mut state = PipelineState::initial(0, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.termination_resume_phase = Some(PipelinePhase::Complete);
    state.pre_termination_commit_checked = false;
    state.commit_diff_prepared = true;
    state.commit_diff_empty = false;
    state.commit_diff_content_id_sha256 = Some("hash-to-reset".to_string());

    let new_state = reduce(
        state,
        PipelineEvent::commit_created("abc123".to_string(), "fix: something".to_string()),
    );

    assert!(
        !new_state.commit_diff_prepared,
        "commit_diff_prepared must be false after CommitEvent::Created (pre-termination path)"
    );
    assert!(
        !new_state.commit_diff_empty,
        "commit_diff_empty must be false after CommitEvent::Created (pre-termination path)"
    );
    assert_eq!(
        new_state.commit_diff_content_id_sha256, None,
        "commit_diff_content_id_sha256 must be None after CommitEvent::Created (pre-termination path)"
    );
}

#[test]
fn test_skipped_normal_resets_commit_diff_prepared() {
    // After a skipped commit (normal path), commit_diff_prepared must be reset to false
    // so the next entry into the commit phase always re-checks the diff.
    let mut state = PipelineState::initial(2, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.previous_phase = Some(PipelinePhase::Development);
    state.iteration = 0;
    state.commit_diff_prepared = true;
    state.commit_diff_empty = false;
    state.commit_diff_content_id_sha256 = Some("hash-to-reset".to_string());
    // termination_resume_phase is None by default => normal path

    let new_state = reduce(
        state,
        PipelineEvent::commit_skipped("AI chose to skip".to_string()),
    );

    assert!(
        !new_state.commit_diff_prepared,
        "commit_diff_prepared must be false after CommitEvent::Skipped (normal path)"
    );
    assert!(
        !new_state.commit_diff_empty,
        "commit_diff_empty must be false after CommitEvent::Skipped (normal path)"
    );
    assert_eq!(
        new_state.commit_diff_content_id_sha256, None,
        "commit_diff_content_id_sha256 must be None after CommitEvent::Skipped (normal path)"
    );
}

#[test]
fn test_skipped_pre_termination_resets_commit_diff_prepared() {
    // After a skipped commit in the pre-termination safety path (AI-driven skip with
    // non-empty diff), commit_diff_prepared must be reset to false.
    let mut state = PipelineState::initial(0, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.termination_resume_phase = Some(PipelinePhase::Complete);
    state.pre_termination_commit_checked = false;
    state.commit_diff_prepared = true;
    state.commit_diff_empty = false; // non-empty => AI-driven skip, pre_termination_commit_checked stays false
    state.commit_diff_content_id_sha256 = Some("hash-to-reset".to_string());

    let new_state = reduce(
        state,
        PipelineEvent::commit_skipped("AI chose to skip".to_string()),
    );

    assert!(
        !new_state.commit_diff_prepared,
        "commit_diff_prepared must be false after CommitEvent::Skipped (pre-termination path)"
    );
    assert!(
        !new_state.commit_diff_empty,
        "commit_diff_empty must be false after CommitEvent::Skipped (pre-termination path)"
    );
    assert_eq!(
        new_state.commit_diff_content_id_sha256, None,
        "commit_diff_content_id_sha256 must be None after CommitEvent::Skipped (pre-termination path)"
    );
}

#[test]
fn test_created_normal_clears_prompt_inputs_commit() {
    // After a successful commit (normal path), prompt_inputs.commit must be cleared
    // to prevent stale materialized commit diff/context from surviving into the next iteration.
    let mut state = PipelineState::initial(2, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.previous_phase = Some(PipelinePhase::Development);
    state.iteration = 0;
    state.commit_diff_prepared = true;
    // Set stale commit inputs that must be cleared after commit
    state.prompt_inputs.commit = Some(MaterializedCommitInputs {
        attempt: 1,
        diff: MaterializedPromptInput {
            kind: PromptInputKind::Diff,
            content_id_sha256: "stale-hash".to_string(),
            consumer_signature_sha256: "stale-sig".to_string(),
            original_bytes: 100,
            final_bytes: 100,
            model_budget_bytes: None,
            inline_budget_bytes: None,
            representation: PromptInputRepresentation::Inline,
            reason: PromptMaterializationReason::WithinBudgets,
        },
    });
    // termination_resume_phase is None by default => normal path

    let new_state = reduce(
        state,
        PipelineEvent::commit_created("abc123".to_string(), "fix: something".to_string()),
    );

    assert!(
        new_state.prompt_inputs.commit.is_none(),
        "prompt_inputs.commit must be cleared after CommitEvent::Created (normal path) \
         to prevent stale commit context reuse in later iterations"
    );
}

#[test]
fn test_created_pre_termination_clears_prompt_inputs_commit() {
    // After a successful commit (pre-termination safety path), prompt_inputs.commit must be
    // cleared to prevent stale materialized commit context from surviving.
    let mut state = PipelineState::initial(0, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.termination_resume_phase = Some(PipelinePhase::Complete);
    state.pre_termination_commit_checked = false;
    state.commit_diff_prepared = true;
    state.prompt_inputs.commit = Some(MaterializedCommitInputs {
        attempt: 1,
        diff: MaterializedPromptInput {
            kind: PromptInputKind::Diff,
            content_id_sha256: "stale-hash".to_string(),
            consumer_signature_sha256: "stale-sig".to_string(),
            original_bytes: 100,
            final_bytes: 100,
            model_budget_bytes: None,
            inline_budget_bytes: None,
            representation: PromptInputRepresentation::Inline,
            reason: PromptMaterializationReason::WithinBudgets,
        },
    });

    let new_state = reduce(
        state,
        PipelineEvent::commit_created("abc123".to_string(), "fix: something".to_string()),
    );

    assert!(
        new_state.prompt_inputs.commit.is_none(),
        "prompt_inputs.commit must be cleared after CommitEvent::Created (pre-termination path)"
    );
}

#[test]
fn test_skipped_normal_clears_prompt_inputs_commit() {
    // After a skipped commit (normal path), prompt_inputs.commit must be cleared
    // to prevent stale materialized commit diff/context from surviving into the next iteration.
    let mut state = PipelineState::initial(2, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.previous_phase = Some(PipelinePhase::Development);
    state.iteration = 0;
    state.commit_diff_prepared = true;
    state.prompt_inputs.commit = Some(MaterializedCommitInputs {
        attempt: 1,
        diff: MaterializedPromptInput {
            kind: PromptInputKind::Diff,
            content_id_sha256: "stale-hash".to_string(),
            consumer_signature_sha256: "stale-sig".to_string(),
            original_bytes: 100,
            final_bytes: 100,
            model_budget_bytes: None,
            inline_budget_bytes: None,
            representation: PromptInputRepresentation::Inline,
            reason: PromptMaterializationReason::WithinBudgets,
        },
    });
    // termination_resume_phase is None by default => normal path

    let new_state = reduce(
        state,
        PipelineEvent::commit_skipped("AI chose to skip".to_string()),
    );

    assert!(
        new_state.prompt_inputs.commit.is_none(),
        "prompt_inputs.commit must be cleared after CommitEvent::Skipped (normal path) \
         to prevent stale commit context reuse in later iterations"
    );
}

#[test]
fn test_diff_prepared_clears_stale_prompt_inputs_surviving_generation_failed() {
    // When GenerationFailed fires, prompt_inputs.commit is NOT cleared (uses ..state spread).
    // The subsequent DiffPrepared event MUST clear it to force rematerialization before the
    // next commit prompt is prepared. This is the canonical safety net for diff freshness.
    let mut state = PipelineState::initial(2, 0);
    state.phase = PipelinePhase::CommitMessage;
    // Simulate stale commit inputs materialized during iteration 1
    state.prompt_inputs.commit = Some(MaterializedCommitInputs {
        attempt: 1,
        diff: MaterializedPromptInput {
            kind: PromptInputKind::Diff,
            content_id_sha256: "iter-1-hash".to_string(),
            consumer_signature_sha256: "iter-1-sig".to_string(),
            original_bytes: 100,
            final_bytes: 100,
            model_budget_bytes: None,
            inline_budget_bytes: None,
            representation: PromptInputRepresentation::Inline,
            reason: PromptMaterializationReason::WithinBudgets,
        },
    });

    // Step 1: GenerationFailed should NOT clear prompt_inputs.commit
    let after_failed = reduce(
        state,
        PipelineEvent::commit_generation_failed("agent timeout".to_string()),
    );
    assert!(
        after_failed.prompt_inputs.commit.is_some(),
        "GenerationFailed must NOT clear prompt_inputs.commit — DiffPrepared is the safety net"
    );

    // Step 2: DiffPrepared (from the re-triggered CheckCommitDiff) MUST clear stale inputs
    let after_diff_prepared = reduce(
        after_failed,
        PipelineEvent::commit_diff_prepared(false, "iter-2-hash".to_string()),
    );
    assert!(
        after_diff_prepared.prompt_inputs.commit.is_none(),
        "DiffPrepared must clear prompt_inputs.commit to prevent stale diff context reuse"
    );
}

#[test]
fn test_skipped_pre_termination_clears_prompt_inputs_commit() {
    // After a skipped commit (pre-termination safety path), prompt_inputs.commit must be
    // cleared to prevent stale materialized commit context from surviving.
    let mut state = PipelineState::initial(0, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.termination_resume_phase = Some(PipelinePhase::Complete);
    state.pre_termination_commit_checked = false;
    state.commit_diff_prepared = true;
    state.commit_diff_empty = false; // non-empty => AI-driven skip
    state.prompt_inputs.commit = Some(MaterializedCommitInputs {
        attempt: 1,
        diff: MaterializedPromptInput {
            kind: PromptInputKind::Diff,
            content_id_sha256: "stale-hash".to_string(),
            consumer_signature_sha256: "stale-sig".to_string(),
            original_bytes: 100,
            final_bytes: 100,
            model_budget_bytes: None,
            inline_budget_bytes: None,
            representation: PromptInputRepresentation::Inline,
            reason: PromptMaterializationReason::WithinBudgets,
        },
    });

    let new_state = reduce(
        state,
        PipelineEvent::commit_skipped("AI chose to skip".to_string()),
    );

    assert!(
        new_state.prompt_inputs.commit.is_none(),
        "prompt_inputs.commit must be cleared after CommitEvent::Skipped (pre-termination path)"
    );
}

// =========================================================================
// Tests for residual files and commit retry-pass logic
// =========================================================================

#[test]
fn test_commit_xml_validated_stores_excluded_files() {
    // CommitXmlValidated with excluded_files must store them in commit_excluded_files.
    use crate::reducer::state::pipeline::{ExcludedFile, ExcludedFileReason};

    let mut state = PipelineState::initial(1, 0);
    state.phase = PipelinePhase::CommitMessage;

    let excluded = vec![ExcludedFile {
        path: "src/sensitive.rs".to_string(),
        reason: ExcludedFileReason::Sensitive,
    }];

    let event = PipelineEvent::commit_xml_validated(
        "feat: add feature".to_string(),
        vec!["src/main.rs".to_string()],
        excluded.clone(),
        1,
    );
    let new_state = reduce(state, event);

    assert_eq!(
        new_state.commit_excluded_files, excluded,
        "CommitXmlValidated must store excluded_files in commit_excluded_files"
    );
}

#[test]
fn test_commit_xml_validated_empty_excluded_files() {
    // CommitXmlValidated with no excluded files stores empty vec.
    let mut state = PipelineState::initial(1, 0);
    state.phase = PipelinePhase::CommitMessage;

    let event =
        PipelineEvent::commit_xml_validated("feat: add feature".to_string(), vec![], vec![], 1);
    let new_state = reduce(state, event);

    assert!(
        new_state.commit_excluded_files.is_empty(),
        "Empty excluded_files must produce empty commit_excluded_files"
    );
}

#[test]
fn test_residual_files_found_pass1_sets_retry_pass_to_2() {
    // ResidualFilesFound pass=1: pipeline must enter commit retry pass 2.
    // commit_residual_retry_pass must be set to 2 and commit state must be reset
    // so orchestration can run a fresh retry cycle.
    let mut state = PipelineState::initial(1, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.commit_residual_retry_pass = 0;

    let event = PipelineEvent::residual_files_found(vec!["src/leftover.rs".to_string()], 1);
    let new_state = reduce(state, event);

    assert_eq!(
        new_state.commit_residual_retry_pass, 2,
        "ResidualFilesFound pass=1 must set commit_residual_retry_pass=2"
    );
    // commit state must be reset for the second pass
    assert!(
        !new_state.commit_diff_prepared,
        "commit_diff_prepared must be reset for second pass"
    );
    assert!(
        !new_state.commit_agent_invoked,
        "commit_agent_invoked must be reset for second pass"
    );
    assert!(
        !new_state.commit_prompt_prepared,
        "commit_prompt_prepared must be reset for second pass"
    );
    // residual files must NOT yet be moved to carry-forward
    assert!(
        new_state.commit_residual_files.is_empty(),
        "commit_residual_files must stay empty after pass=1 (not yet carry-forward)"
    );
}

#[test]
fn test_residual_files_found_pass2_enters_retry_pass3_when_budget_remains() {
    // ResidualFilesFound pass=2: with retry budget remaining, the pipeline must
    // enter commit retry pass 3 instead of carrying files forward immediately.
    let mut state = PipelineState::initial(1, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.commit_residual_retry_pass = 2;

    let residual = vec!["src/remaining.rs".to_string(), "tests/other.rs".to_string()];
    let event = PipelineEvent::residual_files_found(residual, 2);
    let new_state = reduce(state, event);

    assert_eq!(
        new_state.commit_residual_retry_pass, 3,
        "ResidualFilesFound pass=2 must advance to commit retry pass 3 while budget remains"
    );
    assert!(
        new_state.commit_residual_files.is_empty(),
        "ResidualFilesFound pass=2 must not carry files forward while retry budget remains"
    );
}

#[test]
fn test_residual_files_found_final_retry_carries_forward() {
    // ResidualFilesFound on the final configured retry pass must carry files forward
    // to the next cycle and clear commit retry tracking.
    let mut state = PipelineState::initial(1, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.commit_residual_retry_pass = 11;

    let residual = vec!["src/remaining.rs".to_string(), "tests/other.rs".to_string()];
    let event = PipelineEvent::residual_files_found(residual.clone(), 11);
    let new_state = reduce(state, event);

    assert_eq!(
        new_state.commit_residual_files, residual,
        "Final residual retry pass must store files in commit_residual_files"
    );
    assert_eq!(
        new_state.commit_residual_retry_pass, 0,
        "Final residual retry pass must clear commit_residual_retry_pass"
    );
}

#[test]
fn test_residual_files_found_uses_configured_retry_budget() {
    // With max_commit_residual_retries=1, pass 2 is the final residual check and must
    // carry files forward immediately instead of continuing toward the default pass 11.
    let mut state = PipelineState::initial(1, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.max_commit_residual_retries = 1;
    state.commit_residual_retry_pass = 2;

    let residual = vec!["src/remaining.rs".to_string()];
    let new_state = reduce(
        state,
        PipelineEvent::residual_files_found(residual.clone(), 2),
    );

    assert_eq!(new_state.commit_residual_files, residual);
    assert_eq!(new_state.commit_residual_retry_pass, 0);
}

#[test]
fn test_residual_files_none_clears_retry_pass_and_residual() {
    // ResidualFilesNone: working tree is clean after a commit pass.
    // commit_residual_retry_pass must be cleared and commit_residual_files must be cleared.
    let mut state = PipelineState::initial(1, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.commit_residual_retry_pass = 4;
    state.commit_residual_files = vec!["src/old.rs".to_string()];

    let event = PipelineEvent::residual_files_none();
    let new_state = reduce(state, event);

    assert_eq!(
        new_state.commit_residual_retry_pass, 0,
        "ResidualFilesNone must clear commit_residual_retry_pass"
    );
    assert!(
        new_state.commit_residual_files.is_empty(),
        "ResidualFilesNone must clear commit_residual_files"
    );
}

#[test]
fn test_residual_files_found_invalid_pass_routes_to_awaiting_dev_fix() {
    // ResidualFilesFound must only accept pass=1 or pass=2.
    // Any other value indicates an invariant violation; the reducer must route
    // through AwaitingDevFix so unattended remediation can proceed deterministically.
    let mut state = PipelineState::initial(1, 0);
    state.phase = PipelinePhase::CommitMessage;

    let event = PipelineEvent::residual_files_found(vec!["src/leftover.rs".to_string()], 0);
    let new_state = reduce(state, event);

    assert_eq!(new_state.phase, PipelinePhase::AwaitingDevFix);
    assert_eq!(
        new_state.failed_phase_for_recovery,
        Some(PipelinePhase::CommitMessage)
    );
    assert_eq!(new_state.previous_phase, Some(PipelinePhase::CommitMessage));
    assert_eq!(
        new_state.commit_residual_retry_pass, 0,
        "invalid pass must not trigger retry-pass behavior"
    );
    assert!(
        new_state.commit_residual_files.is_empty(),
        "invalid pass must not silently carry-forward residuals"
    );
}

#[test]
fn test_commit_residual_files_survives_generation_started() {
    // commit_residual_files is carry-forward state: it must NOT be cleared when
    // GenerationStarted resets the commit phase for a new cycle.
    let mut state = PipelineState::initial(2, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.commit_residual_files = vec!["src/leftover.rs".to_string()];

    let event = PipelineEvent::commit_generation_started();
    let new_state = reduce(state, event);

    assert_eq!(
        new_state.commit_residual_files,
        vec!["src/leftover.rs".to_string()],
        "commit_residual_files must survive GenerationStarted (carry-forward across cycles)"
    );
}

#[test]
fn test_commit_residual_files_cleared_after_commit_created() {
    // After a successful commit completes and transitions to the next phase,
    // commit_residual_files must be cleared (the files were presumably committed).
    let mut state = PipelineState::initial(2, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.previous_phase = Some(PipelinePhase::Development);
    state.iteration = 0;
    state.commit_residual_files = vec!["src/leftover.rs".to_string()];

    let new_state = reduce(
        state,
        PipelineEvent::commit_created("abc123".to_string(), "feat: done".to_string()),
    );

    assert!(
        new_state.commit_residual_files.is_empty(),
        "commit_residual_files must be cleared after CommitEvent::Created"
    );
}

#[test]
fn test_selective_commit_created_stays_in_commit_message_until_residual_check_completes() {
    // Regression: when the commit is selective (commit_selected_files is non-empty), the
    // pipeline must remain in CommitMessage after the commit is created so orchestration
    // can run CheckResidualFiles and (if needed) another commit retry pass.
    let mut state = PipelineState::initial(2, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.previous_phase = Some(PipelinePhase::Development);
    state.iteration = 0;
    state.commit_selected_files = vec!["src/one.rs".to_string()];

    let new_state = reduce(
        state,
        PipelineEvent::commit_created("abc123".to_string(), "msg".to_string()),
    );

    assert_eq!(
        new_state.phase,
        PipelinePhase::CommitMessage,
        "Selective commit must keep phase in CommitMessage until residual checking completes"
    );
    assert_eq!(
        new_state.previous_phase,
        Some(PipelinePhase::Development),
        "Selective commit must preserve previous_phase until post-commit transition occurs"
    );
}

#[test]
fn test_residual_files_none_transitions_after_selective_commit() {
    // ResidualFilesNone marks the end of residual handling; the pipeline must now perform
    // the normal post-commit transition (e.g., Development -> Planning for next iteration).
    let mut state = PipelineState::initial(2, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.previous_phase = Some(PipelinePhase::Development);
    state.iteration = 0;
    state.commit = CommitState::Committed {
        hash: "abc123".to_string(),
    };
    state.commit_selected_files = vec!["src/one.rs".to_string()];

    let new_state = reduce(state, PipelineEvent::residual_files_none());

    assert_eq!(
        new_state.phase,
        PipelinePhase::Planning,
        "After residuals are clean, pipeline should transition out of CommitMessage"
    );
    assert_eq!(
        new_state.iteration, 1,
        "Post-commit transition from Development should increment iteration"
    );
    assert!(
        new_state.previous_phase.is_none(),
        "Post-commit transition must clear previous_phase"
    );
}

#[test]
fn test_residual_files_found_pass2_transitions_and_carries_forward_after_second_pass() {
    // If the final residual retry pass still has leftovers, carry them forward and transition
    // out of CommitMessage.
    let mut state = PipelineState::initial(2, 0);
    state.phase = PipelinePhase::CommitMessage;
    state.previous_phase = Some(PipelinePhase::Development);
    state.iteration = 0;
    state.commit = CommitState::Committed {
        hash: "abc123".to_string(),
    };
    state.commit_residual_retry_pass = 11;
    state.commit_selected_files = vec!["src/one.rs".to_string()];

    let residual = vec!["src/remaining.rs".to_string()];
    let new_state = reduce(
        state,
        PipelineEvent::residual_files_found(residual.clone(), 11),
    );

    assert_eq!(new_state.commit_residual_files, residual);
    assert_eq!(
        new_state.phase,
        PipelinePhase::Planning,
        "After pass 2 residuals are recorded, pipeline should transition out of CommitMessage"
    );
    assert_eq!(new_state.iteration, 1);
}