cflx 0.6.327

Conflux – a spec-driven parallel coding orchestrator that runs AI agents on git worktrees
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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
use crate::parallel::dedup::DiagnosticDeduplicationKey;
use crate::tui::events::LogEntry;
#[cfg(test)]
use crate::tui::events::TuiCommand;

use crate::tui::state::AppState;

impl AppState {
    pub(crate) fn handle_processing_error(&mut self, id: String, error: String) {
        self.reset_analysis_log_dedupe();
        if let Some(change) = self.changes.iter_mut().find(|c| c.id == id) {
            change.set_error_message_cache(error.clone());
        }
        self.add_log(LogEntry::error(format!("Error in {}: {}", id, error)).with_change_id(&id));
        self.error_change_id = Some(id.clone());
        self.current_change = None;
    }

    pub(crate) fn handle_apply_failed(&mut self, change_id: String, error: String) {
        self.reset_analysis_log_dedupe();
        if let Some(change) = self.changes.iter_mut().find(|c| c.id == change_id) {
            change.set_error_message_cache(error.clone());
        }
        self.add_log(
            LogEntry::error(format!("Apply failed for {}: {}", change_id, error))
                .with_change_id(&change_id),
        );
    }

    pub(crate) fn handle_archive_failed(&mut self, change_id: String, error: String) {
        self.reset_analysis_log_dedupe();
        if let Some(change) = self.changes.iter_mut().find(|c| c.id == change_id) {
            change.set_error_message_cache(error.clone());
        }
        self.add_log(
            LogEntry::error(format!("Archive failed for {}: {}", change_id, error))
                .with_change_id(&change_id),
        );
    }

    /// Paint a change-scoped resolve failure without taking the screen.
    ///
    /// Bounded post-archive exhaustion is `ContinueWithErrors` at the scheduler:
    /// only this one change returns to manual `merge wait`, and every other change
    /// keeps running. A modal warning popup would own input until dismissed, so a
    /// change-local recoverable failure would read — and behave — like a whole-run
    /// stop. The structured error log entry plus the `merge wait` row carry the
    /// diagnostic instead; the process file log remains the durable full record
    /// once the bounded TUI log evicts the entry.
    pub(crate) fn handle_resolve_failed(&mut self, change_id: String, error: String) {
        self.reset_analysis_log_dedupe();
        self.clear_resolving();
        if let Some(change) = self.changes.iter_mut().find(|c| c.id == change_id) {
            if change.display_status_cache == "merged" {
                self.add_log(
                    LogEntry::info(format!(
                        "Ignoring ResolveFailed for '{}': already Merged",
                        change_id
                    ))
                    .with_change_id(&change_id),
                );
                return;
            }
            change.set_display_status_cache("merge wait");
        }
        let message = format!("Failed to resolve merge for '{}': {}", change_id, error);
        self.add_log(LogEntry::error(message).with_change_id(&change_id));

        self.try_transition_to_select();
    }

    pub(crate) fn handle_change_stop_failed(&mut self, change_id: String, error: String) {
        self.add_log(
            LogEntry::error(format!("Failed to stop {}: {}", change_id, error))
                .with_change_id(&change_id),
        );
    }

    pub(crate) fn handle_hook_failed(
        &mut self,
        change_id: String,
        hook_type: String,
        error: String,
    ) {
        self.reset_analysis_log_dedupe();
        if hook_type == "on_merged" {
            if let Some(change) = self.changes.iter_mut().find(|c| c.id == change_id) {
                if change.display_status_cache != "merged" {
                    change.set_display_status_cache("merge wait");
                }
            }
            let message = format!(
                "on_merged hook failed for '{}'; merged transition blocked: {}",
                change_id, error
            );
            self.show_warning_popup("on_merged hook failed", message.clone());
            self.add_log(LogEntry::error(message).with_change_id(&change_id));
            self.try_transition_to_select();
        } else {
            self.add_log(
                LogEntry::error(format!(
                    "Hook '{}' failed for {}: {}",
                    hook_type, change_id, error
                ))
                .with_change_id(&change_id),
            );
        }
    }

    fn add_merge_deferred_warning_log(
        &mut self,
        change_id: &str,
        reason: &str,
        auto_resumable: bool,
        message: String,
    ) {
        let key = DiagnosticDeduplicationKey::TuiMergeDeferred {
            change_id: change_id.to_string(),
            reason: reason.to_string(),
            auto_resumable,
        };

        if !self.diagnostic_dedup.should_emit(key) {
            tracing::debug!(
                change_id = %change_id,
                auto_resumable = auto_resumable,
                reason = %reason,
                "Suppressing repeated merge-deferred TUI diagnostic"
            );
            return;
        }

        self.add_log(LogEntry::warn(message).with_change_id(change_id));
    }

    /// True when a change other than `change_id` is actually inside the resolve
    /// lifecycle.
    ///
    /// `is_resolving` alone is not evidence of an active resolve: `resolve_merge()`
    /// reserves that project-scoped slot optimistically when `M` is pressed, before
    /// `ResolveStarted` arrives. Only the reducer-derived `resolving` display proves
    /// a resolve actually started.
    fn other_change_is_resolving(&self, change_id: &str) -> bool {
        self.changes
            .iter()
            .any(|c| c.id != change_id && c.display_status_cache == "resolving")
    }

    /// Apply a manual (non auto-resumable) merge deferral.
    ///
    /// The shared reducer has already demoted the change to `MergeWait` and cleared
    /// scheduler-owned `ResolveWait` membership, so any TUI-local resolve
    /// reservation/queue entry for it is stale. Keeping it would recreate a
    /// display-only `resolve pending` row that never drains, forcing a TUI restart
    /// before the row could be retried.
    fn apply_manual_merge_deferral(&mut self, change_id: &str, reason: &str) {
        self.remove_from_resolve_queue(change_id);
        if self.is_resolving() && !self.other_change_is_resolving(change_id) {
            self.clear_resolving();
        }
        if let Some(change) = self.changes.iter_mut().find(|c| c.id == change_id) {
            change.set_display_status_cache("merge wait");
        }
        self.add_merge_deferred_warning_log(
            change_id,
            reason,
            false,
            format!("Merge deferred for {}: {}", change_id, reason),
        );
    }

    /// Paint a deferred merge. Never dispatches: see
    /// [`AppState::handle_orchestrator_event`].
    pub(crate) fn handle_merge_deferred(
        &mut self,
        change_id: String,
        reason: String,
        auto_resumable: bool,
    ) {
        if !auto_resumable {
            self.apply_manual_merge_deferral(&change_id, &reason);
            return;
        }

        if self.is_resolving() {
            let is_current_resolving = self
                .changes
                .iter()
                .any(|c| c.id == change_id && c.display_status_cache == "resolving");

            if is_current_resolving {
                self.add_merge_deferred_warning_log(
                    &change_id,
                    &reason,
                    auto_resumable,
                    format!(
                        "Merge deferred for '{}' (currently resolving, not queued): {}",
                        change_id, reason
                    ),
                );
            } else {
                if let Some(change) = self.changes.iter_mut().find(|c| c.id == change_id) {
                    change.set_display_status_cache("resolve pending");
                }
                if self.add_to_resolve_queue(&change_id) {
                    self.add_merge_deferred_warning_log(
                        &change_id,
                        &reason,
                        auto_resumable,
                        format!(
                            "Merge deferred for '{}' (queued for resolve): {}",
                            change_id, reason
                        ),
                    );
                } else {
                    self.add_merge_deferred_warning_log(
                        &change_id,
                        &reason,
                        auto_resumable,
                        format!(
                            "Merge deferred for '{}' (already queued): {}",
                            change_id, reason
                        ),
                    );
                }
            }
        } else {
            if let Some(change) = self.changes.iter_mut().find(|c| c.id == change_id) {
                change.set_display_status_cache("resolve pending");
            }
            // Presentation only, and no command: the reducer already turned this
            // deferral into reducer-owned `ResolveWait` before the TUI saw the
            // event, and the emitting scheduler cannot exit while that intent
            // stands, so the resolve is dispatched on the reducer lane. Re-
            // submitting it here could only be refused — the row is no longer
            // `merge wait` — which reached the operator as a red warning for a
            // resolve that was in fact proceeding.
            self.add_merge_deferred_warning_log(
                &change_id,
                &reason,
                auto_resumable,
                format!(
                    "Merge deferred for '{}' (auto-resumable, awaiting scheduler retry): {}",
                    change_id, reason
                ),
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::openspec::{Change, ProposalMetadata};
    use crate::tui::events::OrchestratorEvent;
    use crate::tui::types::{AppExecutionMode, StopMode};
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    use std::collections::HashMap;

    fn create_test_change(id: &str, completed: u32, total: u32) -> Change {
        Change {
            id: id.to_string(),
            completed_tasks: completed,
            total_tasks: total,
            last_modified: "now".to_string(),
            dependencies: Vec::new(),
            metadata: ProposalMetadata::default(),
        }
    }

    /// Replay what the shared run-control service does when it accepts a resolve.
    ///
    /// These tests exercise `AppState` event handling, not the service, so its
    /// three effects — reducer retry intent, the single reservation, and the
    /// adapter's row advance — are applied directly here.
    fn accept_resolve(
        app: &mut AppState,
        shared: &std::sync::Arc<
            tokio::sync::RwLock<crate::orchestration::state::OrchestratorState>,
        >,
        change_id: &str,
    ) {
        shared.blocking_write().apply_command(
            crate::orchestration::state::ReducerCommand::ResolveMerge(change_id.to_string()),
        );
        app.set_resolving(change_id);
        if let Some(change) = app.changes.iter_mut().find(|c| c.id == change_id) {
            change.set_display_status_cache("resolve pending");
        }
    }

    fn change_ids_for_message(app: &AppState, needle: &str) -> Vec<Option<String>> {
        app.logs
            .iter()
            .filter(|entry| entry.message.contains(needle))
            .map(|entry| entry.change_id.clone())
            .collect()
    }

    #[test]
    fn proposal_error_logs_carry_structured_change_id() {
        let mut app = AppState::new(vec![create_test_change("change-a", 0, 1)]);

        app.handle_processing_error("change-a".to_string(), "boom".to_string());
        app.handle_apply_failed("change-a".to_string(), "boom".to_string());
        app.handle_archive_failed("change-a".to_string(), "boom".to_string());
        app.handle_resolve_failed("change-a".to_string(), "boom".to_string());
        app.handle_change_stop_failed("change-a".to_string(), "boom".to_string());
        app.handle_hook_failed(
            "change-a".to_string(),
            "on_applied".to_string(),
            "boom".to_string(),
        );

        for needle in [
            "Error in change-a: boom",
            "Apply failed for change-a: boom",
            "Archive failed for change-a: boom",
            "Failed to resolve merge for 'change-a': boom",
            "Failed to stop change-a: boom",
            "Hook 'on_applied' failed for change-a: boom",
        ] {
            assert_eq!(
                change_ids_for_message(&app, needle),
                vec![Some("change-a".to_string())],
                "expected structured change_id on {needle}"
            );
        }
    }

    #[test]
    fn on_merged_hook_failure_and_merge_deferred_logs_carry_structured_change_id() {
        let mut app = AppState::new(vec![create_test_change("change-a", 0, 1)]);

        app.handle_hook_failed(
            "change-a".to_string(),
            "on_merged".to_string(),
            "boom".to_string(),
        );
        app.handle_merge_deferred("change-a".to_string(), "conflict".to_string(), false);

        assert_eq!(
            change_ids_for_message(&app, "on_merged hook failed for 'change-a'"),
            vec![Some("change-a".to_string())]
        );
        assert_eq!(
            change_ids_for_message(&app, "Merge deferred for change-a: conflict"),
            vec![Some("change-a".to_string())]
        );
    }

    #[test]
    fn processing_error_keeps_app_mode() {
        let changes = vec![create_test_change("test-change", 0, 1)];
        let mut app = AppState::new(changes);

        app.execution_mode = AppExecutionMode::Running;
        app.current_change = Some("test-change".to_string());
        app.changes[0].selected = true;
        app.publish_execution_marks();

        // The authoritative dispatcher revokes the mark before this frontend
        // sees the event; the row follows the store rather than deciding for
        // itself.
        app.execution_marks().set("test-change", false);
        app.handle_orchestrator_event(OrchestratorEvent::ProcessingError {
            id: "test-change".to_string(),
            error: "Test error message".to_string(),
        });

        assert_eq!(app.execution_mode, AppExecutionMode::Running);
        let change = app.changes.iter().find(|c| c.id == "test-change").unwrap();
        assert_eq!(change.display_status_cache, "error");
        assert!(!change.selected);
        assert_eq!(app.error_change_id, Some("test-change".to_string()));
        assert_eq!(app.current_change, None);
    }

    #[test]
    fn processing_error_from_select_mode() {
        let changes = vec![create_test_change("test-change", 0, 1)];
        let mut app = AppState::new(changes);

        app.execution_mode = AppExecutionMode::Select;
        app.changes[0].selected = true;
        app.publish_execution_marks();

        app.execution_marks().set("test-change", false);
        app.handle_orchestrator_event(OrchestratorEvent::ProcessingError {
            id: "test-change".to_string(),
            error: "Test error message".to_string(),
        });

        assert_eq!(app.execution_mode, AppExecutionMode::Select);
        let change = app.changes.iter().find(|c| c.id == "test-change").unwrap();
        assert_eq!(change.display_status_cache, "error");
        assert!(!change.selected);
    }

    #[test]
    fn handle_on_merged_hook_failed_surfaces_merge_wait_not_merged() {
        let changes = vec![create_test_change("change-a", 1, 1)];
        let mut app = AppState::new(changes);

        app.changes[0].display_status_cache = "archived".to_string();
        let hook_error =
            "git index lock held\nstderr: fatal: unable to lock index\nstdout: retry later";
        app.handle_orchestrator_event(OrchestratorEvent::HookFailed {
            change_id: "change-a".to_string(),
            hook_type: "on_merged".to_string(),
            error: hook_error.to_string(),
        });

        assert_eq!(app.changes[0].display_status_cache, "merge wait");
        let popup = app.warning_popup.as_ref().expect("warning popup");
        assert!(popup.message.contains(hook_error));
        assert!(popup.message.contains("git index lock held\nstderr:"));
        let logged_message = app
            .logs
            .iter()
            .find(|log| log.message.contains("merged transition blocked"))
            .map(|log| log.message.as_str())
            .expect("on_merged log entry");
        assert!(logged_message.contains("git index lock held"));
        assert!(logged_message.contains("stderr: fatal: unable to lock index"));
        assert!(logged_message.contains("stdout: retry later"));
    }

    #[test]
    fn handle_resolve_failed_does_not_demote_merged() {
        let changes = vec![create_test_change("change-a", 1, 1)];
        let mut app = AppState::new(changes);

        app.changes[0].display_status_cache = "merged".to_string();

        app.handle_orchestrator_event(OrchestratorEvent::ResolveFailed {
            change_id: "change-a".to_string(),
            error: "archive check failed".to_string(),
        });

        assert_eq!(app.changes[0].display_status_cache, "merged");
        assert!(app
            .logs
            .iter()
            .any(|log| log.message.contains("already Merged")));
    }

    #[test]
    fn merge_deferred_transitions_to_resolve_wait_when_resolving() {
        let changes = vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ];
        let mut app = AppState::new(changes);

        app.changes[0].display_status_cache = "resolving".to_string();
        app.set_resolving("__active__");
        app.changes[1].display_status_cache = "archived".to_string();

        app.handle_merge_deferred(
            "change-b".to_string(),
            "Base branch has uncommitted changes".to_string(),
            true,
        );

        assert_eq!(app.changes[1].display_status_cache, "resolve pending");
        assert!(app.resolve_reservations().is_reserved("change-b"));
    }

    #[test]
    fn merge_deferred_does_not_queue_current_resolving_change() {
        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        app.changes[0].display_status_cache = "resolving".to_string();
        app.set_resolving("__active__");

        app.handle_merge_deferred(
            "change-a".to_string(),
            "Base branch has uncommitted changes".to_string(),
            true,
        );

        assert_eq!(app.changes[0].display_status_cache, "resolving");
        assert!(!app.resolve_reservations().is_reserved("change-a"));
    }

    #[test]
    fn merge_deferred_queues_other_change_while_resolving() {
        let changes = vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ];
        let mut app = AppState::new(changes);

        app.changes[0].display_status_cache = "resolving".to_string();
        app.set_resolving("__active__");
        app.changes[1].display_status_cache = "archived".to_string();

        app.handle_merge_deferred(
            "change-b".to_string(),
            "Base branch has uncommitted changes".to_string(),
            true,
        );

        assert_eq!(app.changes[1].display_status_cache, "resolve pending");
        assert!(app.resolve_reservations().is_reserved("change-b"));
    }

    #[test]
    fn merge_deferred_maintains_merge_wait_when_not_resolving() {
        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        app.clear_resolving();
        app.changes[0].display_status_cache = "archived".to_string();

        app.handle_merge_deferred(
            "change-a".to_string(),
            "Base branch has uncommitted changes".to_string(),
            false,
        );

        assert_eq!(app.changes[0].display_status_cache, "merge wait");
        assert!(!app.resolve_reservations().is_reserved("change-a"));
    }

    #[test]
    fn auto_resumable_merge_deferred_shows_resolve_wait_not_merge_wait() {
        let changes = vec![create_test_change("change-b", 0, 1)];
        let mut app = AppState::new(changes);

        app.clear_resolving();
        app.changes[0].display_status_cache = "archived".to_string();

        app.handle_merge_deferred(
            "change-b".to_string(),
            "Merge in progress (MERGE_HEAD exists)".to_string(),
            true,
        );

        assert_eq!(app.changes[0].display_status_cache, "resolve pending");
        assert!(
            app.warning_message.is_none(),
            "an auto-resumable deferral is not an operator-facing refusal"
        );
        assert!(
            !app.resolve_reservations().is_reserved("change-b"),
            "an idle deferral is painted only; the scheduler consumes the \
             reducer-owned ResolveWait the same event already recorded"
        );
    }

    #[test]
    fn auto_resumable_merge_deferred_paints_resolve_pending_when_idle() {
        let changes = vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ];
        let mut app = AppState::new(changes);

        app.clear_resolving();
        app.changes[0].display_status_cache = "merged".to_string();
        app.changes[1].display_status_cache = "archived".to_string();

        app.handle_merge_deferred(
            "change-b".to_string(),
            "Base is dirty: Merge in progress (MERGE_HEAD exists)".to_string(),
            true,
        );

        assert_eq!(app.changes[1].display_status_cache, "resolve pending");
        assert!(app.warning_message.is_none());
        assert!(
            !app.resolve_reservations().is_reserved("change-b"),
            "the scheduler, not this handler, drives the idle resolve"
        );
    }

    /// Reducer-first production ordering, which is what makes the idle branch
    /// silent rather than merely quiet: `src/tui/runner.rs` applies
    /// `MergeDeferred(auto_resumable = true)` to the shared reducer — recording
    /// reducer-owned `ResolveWait` and demoting the row to `resolve pending` —
    /// and syncs display caches *before* the TUI handles the event. Any command
    /// emitted from here would therefore carry a target that is no longer
    /// `merge wait`, and the shared run-control service refuses exactly that with
    /// `TargetIneligible`, which the adapter paints as a red status-bar warning
    /// for a resolve the scheduler is in fact about to run.
    #[test]
    fn auto_resumable_deferral_through_the_reducer_neither_commands_nor_warns() {
        use crate::orchestration::state::{OrchestratorState, WorkspaceObservation};
        use std::sync::Arc;

        let mut app = AppState::new(vec![create_test_change("change-a", 0, 1)]);
        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            0,
        )));
        {
            let mut guard = shared.blocking_write();
            guard.apply_observation("change-a", WorkspaceObservation::WorkspaceArchived);
        }
        app.set_shared_state(shared.clone());
        app.execution_mode = AppExecutionMode::Running;
        app.clear_resolving();

        let deferred = crate::events::ExecutionEvent::MergeDeferred {
            change_id: "change-a".to_string(),
            reason: "Base is dirty: Merge in progress (MERGE_HEAD exists)".to_string(),
            auto_resumable: true,
        };
        let display_map = {
            let mut guard = shared.blocking_write();
            guard.apply_execution_event(&deferred);
            guard.all_display_statuses()
        };
        app.apply_display_statuses_from_reducer(&display_map);
        assert_eq!(
            app.changes[0].display_status_cache, "resolve pending",
            "the reducer, not the TUI, has already demoted the row"
        );
        assert!(!app.is_resolving(), "the resolver ledger is idle");

        // Returns `()`: no command can leave this path for the service to refuse.
        app.handle_orchestrator_event(deferred);

        assert_eq!(
            app.warning_message, None,
            "an auto-resumable deferral must never reach the operator as a refusal"
        );
        assert_eq!(app.changes[0].display_status_cache, "resolve pending");
        assert_eq!(
            shared.blocking_read().resolve_wait_change_ids(),
            vec!["change-a".to_string()],
            "the reducer keeps the intent the scheduler dispatches from"
        );
        assert!(!app.resolve_reservations().is_reserved("change-a"));
    }

    #[test]
    fn auto_resumable_merge_deferred_queues_when_resolving() {
        let changes = vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ];
        let mut app = AppState::new(changes);

        app.set_resolving("__active__");
        app.changes[0].display_status_cache = "resolving".to_string();
        app.changes[1].display_status_cache = "archived".to_string();

        app.handle_merge_deferred(
            "change-b".to_string(),
            "Merge in progress (MERGE_HEAD exists)".to_string(),
            true,
        );

        assert_eq!(app.changes[1].display_status_cache, "resolve pending");
        assert!(app.resolve_reservations().is_reserved("change-b"));
    }

    #[test]
    fn duplicate_merge_deferred_warning_is_suppressed() {
        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        app.handle_merge_deferred(
            "change-a".to_string(),
            "stale workspace path".to_string(),
            false,
        );
        app.handle_merge_deferred(
            "change-a".to_string(),
            "stale workspace path".to_string(),
            false,
        );

        let matching_logs = app
            .logs
            .iter()
            .filter(|log| log.message.contains("stale workspace path"))
            .count();
        assert_eq!(matching_logs, 1);
    }

    #[test]
    fn distinct_merge_deferred_reason_is_logged_after_suppressed_duplicate() {
        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        app.handle_merge_deferred(
            "change-a".to_string(),
            "stale workspace path".to_string(),
            false,
        );
        app.handle_merge_deferred(
            "change-a".to_string(),
            "stale workspace path".to_string(),
            false,
        );
        app.handle_merge_deferred(
            "change-a".to_string(),
            "Working tree has uncommitted changes".to_string(),
            false,
        );

        assert!(app
            .logs
            .iter()
            .any(|log| log.message.contains("stale workspace path")));
        assert!(app
            .logs
            .iter()
            .any(|log| log.message.contains("Working tree has uncommitted changes")));
        assert_eq!(
            app.logs
                .iter()
                .filter(|log| log.message.contains("Merge deferred for change-a"))
                .count(),
            2
        );
    }

    #[test]
    fn manual_resolve_merge_in_progress_tui_shows_resolve_wait() {
        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        app.changes[0].display_status_cache = "merge wait".to_string();
        app.clear_resolving();

        app.handle_merge_deferred(
            "change-a".to_string(),
            "Base is dirty: Merge in progress (MERGE_HEAD exists)".to_string(),
            true,
        );

        assert_eq!(app.changes[0].display_status_cache, "resolve pending");
    }

    #[test]
    fn manual_resolve_uncommitted_changes_tui_shows_merge_wait() {
        let changes = vec![create_test_change("change-a", 0, 1)];
        let mut app = AppState::new(changes);

        app.changes[0].display_status_cache = "merge wait".to_string();
        app.clear_resolving();

        app.handle_resolve_failed(
            "change-a".to_string(),
            "Base is dirty: Working tree has uncommitted changes".to_string(),
        );

        assert_eq!(app.changes[0].display_status_cache, "merge wait");
    }

    /// Reducer-first production ordering: `M` reserves the local resolve slot, the
    /// reducer demotes the row to MergeWait, the runner syncs that display, and only
    /// then the TUI handles `MergeDeferred(auto_resumable=false)`. The stale
    /// reservation must not be mistaken for an active resolve.
    #[test]
    fn manual_deferral_before_resolve_started_clears_optimistic_reservation() {
        let mut app = AppState::new(vec![create_test_change("change-a", 0, 1)]);
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].display_status_cache = "merge wait".to_string();
        app.cursor_index = 0;
        app.clear_resolving();

        let first_cmd = app.resolve_merge();
        assert!(matches!(first_cmd, Some(TuiCommand::ResolveMerge(ref id)) if id == "change-a"));

        // What the shared service and the adapter do once the command is handled:
        // the reservation exists, but `ResolveStarted` has not arrived yet.
        app.set_resolving("change-a");
        app.changes[0].set_display_status_cache("resolve pending");
        assert!(app.is_resolving());

        app.apply_display_statuses_from_reducer(&HashMap::from([(
            "change-a".to_string(),
            "merge wait",
        )]));
        app.handle_merge_deferred(
            "change-a".to_string(),
            "Base is dirty: Working tree has uncommitted changes".to_string(),
            false,
        );

        assert_eq!(
            app.changes[0].display_status_cache, "merge wait",
            "manual deferral must preserve the reducer-derived merge wait row"
        );
        assert!(
            !app.is_resolving(),
            "stale optimistic reservation must be cleared"
        );
        assert!(!app.resolve_reservations().is_reserved("change-a"));
        assert!(app.queued_resolves().is_empty());
    }

    /// Even if the deferred change was already queued locally (for example by an
    /// earlier auto-resumable deferral), manual deferral must drain that entry while
    /// leaving unrelated FIFO entries untouched.
    #[test]
    fn manual_deferral_removes_only_its_own_local_queue_entry() {
        let mut app = AppState::new(vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
            create_test_change("change-c", 0, 1),
        ]);
        app.set_resolving("__active__");
        app.changes[0].display_status_cache = "resolving".to_string();
        app.changes[1].display_status_cache = "resolve pending".to_string();
        app.changes[2].display_status_cache = "resolve pending".to_string();
        app.add_to_resolve_queue("change-b");
        app.add_to_resolve_queue("change-c");

        app.handle_merge_deferred(
            "change-b".to_string(),
            "Base is dirty: Working tree has uncommitted changes".to_string(),
            false,
        );

        assert_eq!(app.changes[1].display_status_cache, "merge wait");
        assert!(!app.resolve_reservations().is_reserved("change-b"));
        assert_eq!(
            app.queued_resolves(),
            vec!["change-c".to_string()],
            "unrelated queued resolves must keep FIFO membership"
        );
    }

    /// A manual deferral for one change must not steal serialization from a different
    /// change that actually entered the resolve lifecycle.
    #[test]
    fn manual_deferral_preserves_serialization_for_other_resolving_change() {
        let mut app = AppState::new(vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ]);
        app.set_resolving("__active__");
        app.changes[0].display_status_cache = "resolving".to_string();
        app.changes[1].display_status_cache = "merge wait".to_string();

        app.handle_merge_deferred(
            "change-b".to_string(),
            "Base is dirty: Working tree has uncommitted changes".to_string(),
            false,
        );

        assert_eq!(app.changes[1].display_status_cache, "merge wait");
        assert!(!app.resolve_reservations().is_reserved("change-b"));
        assert!(
            app.is_resolving(),
            "serialization must remain owned by the actually resolving change"
        );
        assert_eq!(app.changes[0].display_status_cache, "resolving");
    }

    /// Auto-resumable deferrals keep queueing behind a reservation-only slot owner,
    /// so scheduler-owned retry work still shows as `resolve pending`.
    #[test]
    fn auto_resumable_merge_deferred_still_queues_behind_optimistic_reservation() {
        let mut app = AppState::new(vec![
            create_test_change("change-a", 0, 1),
            create_test_change("change-b", 0, 1),
        ]);
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].display_status_cache = "merge wait".to_string();
        app.changes[1].display_status_cache = "merge wait".to_string();
        app.cursor_index = 0;
        app.clear_resolving();
        assert!(app.resolve_merge().is_some());
        // The shared service took the reservation the emitted command asked for.
        app.set_resolving("change-a");

        app.handle_merge_deferred(
            "change-b".to_string(),
            "Merge in progress (MERGE_HEAD exists)".to_string(),
            true,
        );

        assert_eq!(
            app.changes[1].display_status_cache, "resolve pending",
            "queued retry must wait for the active slot"
        );
        assert!(app.resolve_reservations().is_reserved("change-b"));
        assert!(app.is_resolving());
    }

    /// Full local lifecycle: reservation, reducer demotion, TUI handling, then a
    /// second `M` on the same `AppState` must produce fresh scheduler-consumable
    /// retry intent without restarting the TUI.
    #[test]
    fn manual_deferral_keeps_second_m_actionable_without_restart() {
        use crate::orchestration::state::{OrchestratorState, WorkspaceObservation};
        use std::sync::Arc;

        let mut app = AppState::new(vec![create_test_change("change-a", 0, 1)]);
        let shared = Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            vec!["change-a".to_string()],
            0,
        )));
        {
            let mut guard = shared.blocking_write();
            guard.apply_observation("change-a", WorkspaceObservation::WorkspaceArchived);
        }
        app.set_shared_state(shared.clone());
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].display_status_cache = "merge wait".to_string();
        app.cursor_index = 0;
        app.clear_resolving();

        // 1st M press: the emitted command reaches the shared service, which
        // records the reducer retry intent and takes the single reservation.
        assert!(app.resolve_merge().is_some());
        accept_resolve(&mut app, &shared, "change-a");
        assert_eq!(
            shared.blocking_read().resolve_wait_change_ids(),
            vec!["change-a".to_string()]
        );

        // Scheduler retry evaluation finds a dirty base before ResolveStarted.
        let display_map = {
            let mut guard = shared.blocking_write();
            guard.apply_execution_event(&crate::events::ExecutionEvent::MergeDeferred {
                change_id: "change-a".to_string(),
                reason: "Base is dirty: Working tree has uncommitted changes".to_string(),
                auto_resumable: false,
            });
            guard.all_display_statuses()
        };
        app.apply_display_statuses_from_reducer(&display_map);
        app.handle_merge_deferred(
            "change-a".to_string(),
            "Base is dirty: Working tree has uncommitted changes".to_string(),
            false,
        );

        assert_eq!(app.changes[0].display_status_cache, "merge wait");
        assert!(!app.is_resolving());
        assert!(app.queued_resolves().is_empty());
        assert!(shared.blocking_read().resolve_wait_change_ids().is_empty());

        // 2nd M press after the user cleaned the base: fresh retry, same AppState.
        let second_cmd = app.resolve_merge();

        assert!(
            matches!(second_cmd, Some(TuiCommand::ResolveMerge(ref id)) if id == "change-a"),
            "clean second M must dispatch a fresh retry without a TUI restart"
        );
        accept_resolve(&mut app, &shared, "change-a");
        assert_eq!(app.changes[0].display_status_cache, "resolve pending");
        assert_eq!(
            shared.blocking_read().resolve_wait_change_ids(),
            vec!["change-a".to_string()],
            "second retry must be scheduler-consumable"
        );
        assert!(app.queued_resolves().is_empty());
    }

    #[test]
    fn resolve_failed_transitions_to_select_when_no_active() {
        let changes = vec![create_test_change("change-a", 3, 3)];
        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].display_status_cache = "resolving".to_string();
        app.set_resolving("__active__");

        app.handle_resolve_failed("change-a".to_string(), "conflict".to_string());

        assert_eq!(app.execution_mode, AppExecutionMode::Select);
    }

    /// The bounded-exhaustion diagnostic the conflict layer actually emits.
    ///
    /// Built from the producer's own helper rather than a hand-copied string, so
    /// these regressions cannot drift away from the real wording.
    fn exhaustion_detail() -> String {
        crate::parallel::resolve_failure_detail(
            3,
            crate::parallel::ResolveFailureClassification::UnresolvedConflict,
            "conflicts still present after merge resolution attempt: a.rs",
        )
    }

    /// The regression this whole change exists for.
    ///
    /// A bounded post-archive resolve exhaustion arrives as the real event
    /// sequence — presentation telemetry plus one change-scoped `ResolveFailed`.
    /// The change goes back to `merge wait` for explicit retry, the diagnostic
    /// keeps `alpha` as structured identity, and the run stays `Running` because
    /// other work is still active.
    #[test]
    fn exhausted_post_archive_resolve_stays_change_scoped_and_keeps_running() {
        let changes = vec![
            create_test_change("alpha", 3, 3),
            create_test_change("beta", 0, 1),
        ];
        let mut app = AppState::new(changes);
        app.execution_mode = AppExecutionMode::Running;
        // `beta` is the other active change that must keep the run alive.
        app.current_change = Some("beta".to_string());
        if let Some(change) = app.changes.iter_mut().find(|c| c.id == "beta") {
            change.set_display_status_cache("applying");
        }

        let detail = exhaustion_detail();
        app.handle_orchestrator_event(OrchestratorEvent::ConflictResolutionFailed {
            error: detail.clone(),
        });
        assert_eq!(
            app.execution_mode,
            AppExecutionMode::Running,
            "presentation telemetry must not change execution mode"
        );

        app.handle_orchestrator_event(OrchestratorEvent::ResolveFailed {
            change_id: "alpha".to_string(),
            error: detail,
        });

        let alpha = app
            .changes
            .iter()
            .find(|c| c.id == "alpha")
            .expect("alpha row");
        assert_eq!(alpha.display_status_cache, "merge wait");
        assert_ne!(
            app.execution_mode,
            AppExecutionMode::Error,
            "a change-local merge failure must never become a global TUI error"
        );
        assert_eq!(
            app.execution_mode,
            AppExecutionMode::Running,
            "the run stays Running while other work is active"
        );
        assert_eq!(
            change_ids_for_message(&app, "Failed to resolve merge for 'alpha'"),
            vec![Some("alpha".to_string())],
            "the failure diagnostic must retain structured change identity"
        );
    }

    /// Automatic bounded exhaustion must stay a change-local notification.
    ///
    /// The popup this asserts against owned input until dismissed, which made an
    /// explicitly `ContinueWithErrors` failure interrupt monitoring and control of
    /// every unrelated change that was still running.
    #[test]
    fn exhausted_post_archive_resolve_is_non_modal_and_leaves_other_work_operable() {
        let mut app = AppState::new(vec![
            create_test_change("alpha", 3, 3),
            create_test_change("beta", 0, 1),
        ]);
        app.execution_mode = AppExecutionMode::Running;
        app.current_change = Some("beta".to_string());
        app.changes[0].set_display_status_cache("resolving");
        app.changes[1].set_display_status_cache("applying");
        app.set_resolving("alpha");

        app.handle_orchestrator_event(OrchestratorEvent::ResolveFailed {
            change_id: "alpha".to_string(),
            error: exhaustion_detail(),
        });

        assert!(
            app.warning_popup.is_none(),
            "a change-scoped resolve failure must not open a blocking overlay"
        );
        assert!(
            !crate::tui::key_handlers::handle_warning_popup_key(
                &mut app,
                KeyEvent::new(KeyCode::Down, KeyModifiers::NONE),
            ),
            "no popup may claim operator input ahead of the underlying screen"
        );
        assert_eq!(
            app.stop_mode,
            StopMode::None,
            "a change-local failure must not request graceful or immediate global stop"
        );
        assert_eq!(
            app.execution_mode,
            AppExecutionMode::Running,
            "unrelated active work keeps the run alive"
        );
        assert_eq!(
            app.changes[0].display_status_cache, "merge wait",
            "the affected row stays retryable rather than terminal"
        );
        assert_eq!(app.changes[1].display_status_cache, "applying");
        assert_eq!(
            change_ids_for_message(&app, "Failed to resolve merge for 'alpha'"),
            vec![Some("alpha".to_string())],
            "the retained diagnostic must identify the affected change"
        );
    }

    /// The same failure with nothing else active: the pre-existing non-fatal
    /// `Select` transition still applies, and the row is still retryable.
    #[test]
    fn idle_change_scoped_resolve_failure_stays_retryable_without_a_popup() {
        let mut app = AppState::new(vec![create_test_change("alpha", 3, 3)]);
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].set_display_status_cache("resolving");
        app.cursor_index = 0;
        app.set_resolving("alpha");

        app.handle_orchestrator_event(OrchestratorEvent::ResolveFailed {
            change_id: "alpha".to_string(),
            error: exhaustion_detail(),
        });

        assert!(app.warning_popup.is_none());
        assert_eq!(
            app.execution_mode,
            AppExecutionMode::Select,
            "the existing no-active-work transition remains valid"
        );
        assert_ne!(app.execution_mode, AppExecutionMode::Error);
        assert_eq!(app.changes[0].display_status_cache, "merge wait");
        assert!(
            matches!(app.resolve_merge(), Some(TuiCommand::ResolveMerge(ref id)) if id == "alpha"),
            "the explicit merge retry action must remain available"
        );
    }

    /// Operator-initiated resolve takes the same handler, so `M` followed by a
    /// failure must not be modal either — and must leave `M` usable again.
    #[test]
    fn operator_initiated_resolve_failure_is_also_non_modal_and_retryable() {
        let mut app = AppState::new(vec![create_test_change("alpha", 3, 3)]);
        app.execution_mode = AppExecutionMode::Running;
        app.changes[0].set_display_status_cache("merge wait");
        app.cursor_index = 0;
        app.clear_resolving();

        assert!(
            matches!(app.resolve_merge(), Some(TuiCommand::ResolveMerge(ref id)) if id == "alpha")
        );
        // What the shared run-control service and the adapter do with that command.
        app.set_resolving("alpha");
        app.changes[0].set_display_status_cache("resolve pending");

        app.handle_orchestrator_event(OrchestratorEvent::ResolveFailed {
            change_id: "alpha".to_string(),
            error: exhaustion_detail(),
        });

        assert!(
            app.warning_popup.is_none(),
            "a manual resolve failure is still change-scoped, not a run stop"
        );
        assert_eq!(app.stop_mode, StopMode::None);
        assert_eq!(app.changes[0].display_status_cache, "merge wait");
        assert_eq!(
            change_ids_for_message(&app, "Failed to resolve merge for 'alpha'"),
            vec![Some("alpha".to_string())],
            "the bounded TUI log keeps the structured diagnostic"
        );
        assert!(
            matches!(app.resolve_merge(), Some(TuiCommand::ResolveMerge(ref id)) if id == "alpha"),
            "a second explicit retry must remain possible without a restart"
        );
    }

    /// Severity comes from the event type, not from the diagnostic text: the same
    /// wording is non-modal as `ResolveFailed` and still modal as an `on_merged`
    /// hook failure, which is specified separately and keeps its popup.
    #[test]
    fn unrelated_warning_class_keeps_its_popup_for_the_same_diagnostic_text() {
        let detail = exhaustion_detail();

        let mut app = AppState::new(vec![create_test_change("alpha", 3, 3)]);
        app.changes[0].set_display_status_cache("resolving");
        app.handle_orchestrator_event(OrchestratorEvent::ResolveFailed {
            change_id: "alpha".to_string(),
            error: detail.clone(),
        });
        assert!(app.warning_popup.is_none());

        let mut app = AppState::new(vec![create_test_change("alpha", 3, 3)]);
        app.changes[0].set_display_status_cache("archived");
        app.handle_orchestrator_event(OrchestratorEvent::HookFailed {
            change_id: "alpha".to_string(),
            hook_type: "on_merged".to_string(),
            error: detail,
        });

        let popup = app
            .warning_popup
            .as_ref()
            .expect("on_merged hook failure keeps its popup");
        assert!(popup.message.contains("merged transition blocked"));
    }

    /// A run-fatal global Error is still fatal. Change-local suppression must not
    /// downgrade the one event that means the run was actually invalidated.
    #[test]
    fn run_fatal_global_error_still_enters_error_mode() {
        let mut app = AppState::new(vec![create_test_change("alpha", 3, 3)]);
        app.execution_mode = AppExecutionMode::Running;

        app.handle_orchestrator_event(OrchestratorEvent::ResolveFailed {
            change_id: "alpha".to_string(),
            error: exhaustion_detail(),
        });
        assert_ne!(app.execution_mode, AppExecutionMode::Error);
        assert!(
            app.warning_popup.is_none(),
            "the non-modal change-scoped path must not leave an overlay behind"
        );

        app.handle_orchestrator_event(OrchestratorEvent::Error {
            message: "Background merge failed for 'alpha' (workspace 'ws-alpha'): base branch could not be identified".to_string(),
        });

        assert_eq!(
            app.execution_mode,
            AppExecutionMode::Error,
            "a run-fatal outcome must still stop the frontend"
        );
    }

    /// A finite `CompletedWithErrors` boundary report is a warning plus the
    /// existing terminal transition — never a success message and never Error.
    #[test]
    fn finite_completion_with_errors_is_not_fatal_and_keeps_retry_available() {
        let mut app = AppState::new(vec![create_test_change("alpha", 3, 3)]);
        app.execution_mode = AppExecutionMode::Running;

        app.handle_orchestrator_event(OrchestratorEvent::ResolveFailed {
            change_id: "alpha".to_string(),
            error: exhaustion_detail(),
        });
        app.handle_orchestrator_event(OrchestratorEvent::Log(LogEntry::warn(
            "Processing completed with errors".to_string(),
        )));
        app.handle_orchestrator_event(OrchestratorEvent::AllCompleted);

        assert_ne!(app.execution_mode, AppExecutionMode::Error);
        assert!(
            !app.logs
                .iter()
                .any(|entry| entry.message.contains("All parallel changes completed")),
            "no success completion message may accompany an unresolved change failure"
        );
        let alpha = app
            .changes
            .iter()
            .find(|c| c.id == "alpha")
            .expect("alpha row");
        assert_eq!(
            alpha.display_status_cache, "merge wait",
            "explicit merge retry must remain available after the run ends"
        );
    }
}