cflx 0.6.128

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
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
use crate::agent::AgentRunner;
use crate::ai_command_runner::{AiCommandRunner, SharedStaggerState};
use crate::command_queue::CommandQueueConfig;
use crate::config::defaults::*;
use crate::config::OrchestratorConfig;
use crate::error::{OrchestratorError, Result};
use crate::error_history::CircuitBreakerConfig;
use crate::events::{cli_event_sinks, dispatch_event, ExecutionEvent};
use crate::execution::apply::{check_task_progress, create_progress_commit};
use crate::hooks::{HookContext, HookRunner, HookType};
use crate::openspec::{self, Change};
use crate::orchestration::state::OrchestratorState;
use crate::orchestration::LogOutputHandler;
use crate::parallel_run_service::ParallelRunService;
use crate::progress::ProgressDisplay;
use crate::serial_run_service::SerialRunService;
use crate::stall::StallDetector;
use crate::task_parser::TaskProgress;
use crate::tui::log_deduplicator;
use crate::vcs::git::commands as git_commands;
use crate::vcs::{GitWorkspaceManager, VcsBackend, WorkspaceManager};
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::Mutex;
use tracing::{error, info, warn};

#[cfg(feature = "web-monitoring")]
use crate::web::WebState;
#[cfg(feature = "web-monitoring")]
use tokio::sync::mpsc;

struct SerialSnapshot {
    progress: crate::task_parser::TaskProgress,
    empty_commit: Option<bool>,
}

pub struct Orchestrator {
    agent: AgentRunner,
    ai_runner: AiCommandRunner,
    config: OrchestratorConfig,
    progress: Option<ProgressDisplay>,
    /// Target changes specified by --change option (comma-separated)
    target_changes: Option<Vec<String>>,
    /// Snapshot of change IDs captured at run start.
    /// Only changes present in this snapshot will be processed during the run.
    /// This prevents mid-run proposals from being processed before they are ready.
    initial_change_ids: Option<HashSet<String>>,
    /// Hook runner for executing hooks at various stages
    hooks: HookRunner,
    /// Stall detector for empty WIP commit tracking
    stall_detector: StallDetector,
    /// Maximum iterations limit (0 = no limit)
    max_iterations: u32,
    /// Enable parallel execution mode
    parallel: bool,
    /// Maximum concurrent workspaces for parallel execution
    max_concurrent: Option<usize>,
    /// Dry run mode (preview without execution)
    dry_run: bool,
    /// VCS backend for parallel execution
    #[allow(dead_code)] // Will be passed to ParallelRunService in future
    vcs_backend: VcsBackend,
    /// Disable automatic workspace resume (always create new workspaces)
    no_resume: bool,
    /// Shared orchestration state (single source of truth for state tracking)
    /// Wrapped in Arc<RwLock<>> to allow sharing with TUI/Web monitoring
    shared_state: std::sync::Arc<tokio::sync::RwLock<OrchestratorState>>,
    /// Web monitoring state (for broadcasting updates to WebSocket clients)
    #[cfg(feature = "web-monitoring")]
    web_state: Option<Arc<WebState>>,
    /// Current execution mode for web monitoring app_mode
    /// "select" | "running" | "stopped" | "stopping" | "error"
    #[cfg(feature = "web-monitoring")]
    execution_mode: String,
}

/// Control flow result indicating whether to continue or break the main loop
enum LoopControl {
    Continue,
    Break { finish_status: &'static str },
}

impl Orchestrator {
    /// Create a new orchestrator with optional custom config path and max iterations override
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        target_changes: Option<Vec<String>>,
        config_path: Option<PathBuf>,
        max_iterations_override: Option<u32>,
        parallel: bool,
        max_concurrent: Option<usize>,
        dry_run: bool,
        vcs_override: Option<VcsBackend>,
        no_resume: bool,
    ) -> Result<Self> {
        let config = OrchestratorConfig::load(config_path.as_deref())?;
        log_deduplicator::configure_logging(config.get_logging());
        let repo_root = std::env::current_dir()?;
        let hooks = HookRunner::with_output_handler(
            config.get_hooks(),
            &repo_root,
            Arc::new(LogOutputHandler::new()),
        );
        // CLI override takes precedence over config file value
        let max_iterations = max_iterations_override.unwrap_or_else(|| config.get_max_iterations());
        let agent = AgentRunner::new(config.clone());
        // VCS backend: CLI override takes precedence, then config, then auto
        let vcs_backend = vcs_override.unwrap_or_else(|| config.get_vcs_backend());
        let stall_detector = StallDetector::new(config.get_stall_detection());

        // Create AiCommandRunner for serial mode execution
        let shared_stagger_state: SharedStaggerState = Arc::new(Mutex::new(None));
        let queue_config = CommandQueueConfig {
            stagger_delay_ms: config
                .command_queue_stagger_delay_ms
                .unwrap_or(DEFAULT_STAGGER_DELAY_MS),
            max_retries: config
                .command_queue_max_retries
                .unwrap_or(DEFAULT_MAX_RETRIES),
            retry_delay_ms: config
                .command_queue_retry_delay_ms
                .unwrap_or(DEFAULT_RETRY_DELAY_MS),
            retry_error_patterns: config
                .command_queue_retry_patterns
                .clone()
                .unwrap_or_else(default_retry_patterns),
            retry_if_duration_under_secs: config
                .command_queue_retry_if_duration_under_secs
                .unwrap_or(DEFAULT_RETRY_IF_DURATION_UNDER_SECS),
            inactivity_timeout_secs: config.get_command_inactivity_timeout_secs(),
            inactivity_kill_grace_secs: config.get_command_inactivity_kill_grace_secs(),
            inactivity_timeout_max_retries: config.get_command_inactivity_timeout_max_retries(),
            strict_process_cleanup: config.get_command_strict_process_cleanup(),
        };
        let mut ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state);
        ai_runner.set_stream_json_textify(config.get_stream_json_textify());
        ai_runner.set_strict_process_cleanup(config.get_command_strict_process_cleanup());

        // Initialize shared state (will be populated when run() is called with actual changes)
        // Wrapped in Arc<RwLock<>> to allow sharing with TUI/Web monitoring
        let shared_state = std::sync::Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            Vec::new(),
            max_iterations,
        )));

        Ok(Self {
            agent,
            ai_runner,
            config,
            progress: None,
            target_changes,
            initial_change_ids: None,
            hooks,
            stall_detector,
            max_iterations,
            parallel,
            max_concurrent,
            dry_run,
            vcs_backend,
            no_resume,
            shared_state,
            #[cfg(feature = "web-monitoring")]
            web_state: None,
            #[cfg(feature = "web-monitoring")]
            execution_mode: "select".to_string(),
        })
    }

    /// Set web monitoring state for broadcasting updates to WebSocket clients.
    /// Also injects the shared orchestration state reference into WebState for unified tracking.
    #[cfg(feature = "web-monitoring")]
    pub async fn set_web_state(&mut self, web_state: Arc<WebState>) {
        // Inject shared state reference into WebState
        web_state.set_shared_state(self.shared_state.clone()).await;
        self.web_state = Some(web_state);
    }

    /// Broadcast state update to web monitoring clients
    #[cfg(feature = "web-monitoring")]
    async fn broadcast_state_update(&self, changes: &[Change]) {
        if let Some(ref web_state) = self.web_state {
            web_state
                .update_with_mode(changes, &self.execution_mode)
                .await;
        }
    }

    /// No-op when web monitoring is disabled
    #[cfg(not(feature = "web-monitoring"))]
    async fn broadcast_state_update(&self, _changes: &[Change]) {}

    /// Create a new orchestrator with explicit configuration (for testing)
    #[cfg(test)]
    pub fn with_config(
        target_changes: Option<Vec<String>>,
        config: OrchestratorConfig,
    ) -> Result<Self> {
        log_deduplicator::configure_logging(config.get_logging());
        let repo_root = std::env::current_dir()?;
        let hooks = HookRunner::with_output_handler(
            config.get_hooks(),
            &repo_root,
            Arc::new(LogOutputHandler::new()),
        );
        let max_iterations = config.get_max_iterations();
        let agent = AgentRunner::new(config.clone());
        let stall_detector = StallDetector::new(config.get_stall_detection());

        // Create AiCommandRunner for serial mode execution
        let shared_stagger_state: SharedStaggerState = Arc::new(Mutex::new(None));
        let queue_config = CommandQueueConfig {
            stagger_delay_ms: config
                .command_queue_stagger_delay_ms
                .unwrap_or(DEFAULT_STAGGER_DELAY_MS),
            max_retries: config
                .command_queue_max_retries
                .unwrap_or(DEFAULT_MAX_RETRIES),
            retry_delay_ms: config
                .command_queue_retry_delay_ms
                .unwrap_or(DEFAULT_RETRY_DELAY_MS),
            retry_error_patterns: config
                .command_queue_retry_patterns
                .clone()
                .unwrap_or_else(default_retry_patterns),
            retry_if_duration_under_secs: config
                .command_queue_retry_if_duration_under_secs
                .unwrap_or(DEFAULT_RETRY_IF_DURATION_UNDER_SECS),
            inactivity_timeout_secs: config.get_command_inactivity_timeout_secs(),
            inactivity_kill_grace_secs: config.get_command_inactivity_kill_grace_secs(),
            inactivity_timeout_max_retries: config.get_command_inactivity_timeout_max_retries(),
            strict_process_cleanup: config.get_command_strict_process_cleanup(),
        };
        let mut ai_runner = AiCommandRunner::new(queue_config, shared_stagger_state);
        ai_runner.set_stream_json_textify(config.get_stream_json_textify());
        ai_runner.set_strict_process_cleanup(config.get_command_strict_process_cleanup());

        // Initialize shared state (for testing, will use empty change list)
        // Wrapped in Arc<RwLock<>> to allow sharing with TUI/Web monitoring
        let shared_state = std::sync::Arc::new(tokio::sync::RwLock::new(OrchestratorState::new(
            Vec::new(),
            max_iterations,
        )));

        Ok(Self {
            agent,
            ai_runner,
            config,
            progress: None,
            target_changes,
            initial_change_ids: None,
            hooks,
            stall_detector,
            max_iterations,
            parallel: false,
            max_concurrent: None,
            dry_run: false,
            vcs_backend: VcsBackend::Auto,
            no_resume: false,
            shared_state,
            #[cfg(feature = "web-monitoring")]
            web_state: None,
            #[cfg(feature = "web-monitoring")]
            execution_mode: "select".to_string(),
        })
    }

    /// Update execution mode and broadcast state (helper for mode transitions)
    #[cfg(feature = "web-monitoring")]
    async fn update_execution_mode(&mut self, mode: &str) {
        self.execution_mode = mode.to_string();
        let current_changes = openspec::list_changes_native().unwrap_or_default();
        self.broadcast_state_update(&current_changes).await;
    }

    /// Check for graceful stop flag and update state accordingly
    /// Returns LoopControl indicating whether to continue or break
    async fn check_graceful_stop(
        &mut self,
        graceful_stop_flag: &Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
        previous_graceful_stop: &mut bool,
    ) -> LoopControl {
        if let Some(ref graceful_flag) = graceful_stop_flag {
            let current_graceful_stop = graceful_flag.load(std::sync::atomic::Ordering::SeqCst);

            // Detect transition from false to true (entering stopping state)
            if current_graceful_stop && !*previous_graceful_stop {
                info!("Graceful stop requested, entering stopping state");
                #[cfg(feature = "web-monitoring")]
                self.update_execution_mode("stopping").await;
            }

            // Detect transition from true to false (cancel stop - resume running)
            if !current_graceful_stop && *previous_graceful_stop {
                info!("Graceful stop cancelled, resuming running state");
                #[cfg(feature = "web-monitoring")]
                self.update_execution_mode("running").await;
            }

            *previous_graceful_stop = current_graceful_stop;

            // If stop is still requested, exit loop
            if current_graceful_stop {
                info!("Graceful stop: stopping after current change");
                #[cfg(feature = "web-monitoring")]
                self.update_execution_mode("stopped").await;
                if let Some(progress) = &mut self.progress {
                    progress.complete_all();
                }
                return LoopControl::Break {
                    finish_status: "graceful_stop",
                };
            }
        }
        LoopControl::Continue
    }

    /// Check for cancellation token
    /// Returns LoopControl indicating whether to continue or break
    async fn check_cancellation(
        &mut self,
        cancel_token: &tokio_util::sync::CancellationToken,
    ) -> LoopControl {
        if cancel_token.is_cancelled() {
            info!("Cancellation requested, stopping orchestration");
            #[cfg(feature = "web-monitoring")]
            self.update_execution_mode("stopped").await;
            if let Some(progress) = &mut self.progress {
                progress.complete_all();
            }
            return LoopControl::Break {
                finish_status: "cancelled",
            };
        }
        LoopControl::Continue
    }

    /// Check max iterations limit and increment counter
    /// Returns LoopControl indicating whether to continue or break
    async fn check_max_iterations(&mut self) -> LoopControl {
        let mut state = self.shared_state.write().await;
        state.increment_iteration();
        let iteration = state.iteration();
        let max_iterations = state.max_iterations();
        drop(state);

        if max_iterations > 0 {
            // Log warning when approaching limit (80%)
            let warning_threshold = (max_iterations as f32 * 0.8) as u32;
            if iteration == warning_threshold {
                warn!(
                    "Approaching max iterations: {}/{}",
                    iteration, max_iterations
                );
            }

            // Stop if max iterations reached
            if iteration > max_iterations {
                info!(
                    "Max iterations ({}) reached, stopping orchestration",
                    max_iterations
                );
                if let Some(progress) = &mut self.progress {
                    progress.complete_all();
                }
                return LoopControl::Break {
                    finish_status: "iteration_limit",
                };
            }
        }
        LoopControl::Continue
    }

    /// Check all loop control conditions (graceful stop, cancellation, max iterations).
    /// Returns LoopControl indicating whether to continue or break.
    async fn check_loop_controls(
        &mut self,
        graceful_stop_flag: &Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
        previous_graceful_stop: &mut bool,
        cancel_token: &tokio_util::sync::CancellationToken,
    ) -> LoopControl {
        // Check for graceful stop
        match self
            .check_graceful_stop(graceful_stop_flag, previous_graceful_stop)
            .await
        {
            LoopControl::Continue => {}
            break_control => return break_control,
        }

        // Check for cancellation
        match self.check_cancellation(cancel_token).await {
            LoopControl::Continue => {}
            break_control => return break_control,
        }

        // Check max iterations
        self.check_max_iterations().await
    }

    /// Update shared state with an execution event
    async fn update_shared_state(&self, event: ExecutionEvent) {
        let sinks: Vec<std::sync::Arc<dyn crate::events::EventSink>> = cli_event_sinks();
        dispatch_event(self.shared_state.as_ref(), &sinks, event).await;
    }

    /// Handle Archived result
    async fn handle_archived(&mut self, next: &Change) {
        self.update_shared_state(ExecutionEvent::ChangeArchived(next.id.clone()))
            .await;
        self.stall_detector.clear_change(&next.id);

        if let Some(progress) = &mut self.progress {
            progress.archive_change(&next.id);
        }
    }

    /// Handle Stalled result
    async fn handle_stalled(&mut self, next: &Change, error: &str) -> LoopControl {
        warn!("Change stalled: {} - {}", next.id, error);
        self.mark_change_stalled(&next.id, error).await;
        LoopControl::Continue
    }

    /// Handle Failed result
    async fn handle_failed(&mut self, next: &Change, error: &str) -> Result<()> {
        error!("Change failed: {} - {}", next.id, error);
        if let Some(progress) = &mut self.progress {
            progress.error(&format!("Failed: {}", next.id));
        }
        #[cfg(feature = "web-monitoring")]
        self.update_execution_mode("error").await;
        Err(OrchestratorError::AgentCommand(error.to_string()))
    }

    /// Handle ApplySuccessIncomplete result
    async fn handle_apply_success_incomplete(
        &mut self,
        next: &Change,
        serial_service: &mut SerialRunService,
    ) -> LoopControl {
        self.update_shared_state(ExecutionEvent::ApplyCompleted {
            change_id: next.id.clone(),
            revision: "serial".to_string(),
        })
        .await;

        // CLI-specific: Create WIP snapshot
        let apply_count = serial_service.apply_count(&next.id);
        let snapshot = match self.snapshot_serial_iteration(&next.id, apply_count).await {
            Ok(snapshot) => snapshot,
            Err(e) => {
                warn!("Failed to snapshot WIP commit for {}: {}", next.id, e);
                SerialSnapshot {
                    progress: crate::task_parser::TaskProgress::default(),
                    empty_commit: None,
                }
            }
        };

        // CLI-specific: Check for stall on empty commits
        if let Some(stall_reason) = serial_service.check_stall_after_apply(
            &next.id,
            &snapshot.progress,
            snapshot.empty_commit,
        ) {
            warn!("{}", stall_reason);
            self.mark_change_stalled(&next.id, &stall_reason).await;
            return LoopControl::Continue;
        }

        if let Some(progress) = &mut self.progress {
            progress.complete_change(&next.id);
        }
        LoopControl::Continue
    }

    /// Handle ApplyFailed result
    async fn handle_apply_failed(
        &mut self,
        next: &Change,
        error: &str,
        serial_service: &mut SerialRunService,
    ) -> Result<()> {
        self.update_shared_state(ExecutionEvent::ApplyStarted {
            change_id: next.id.clone(),
            command: "(placeholder)".to_string(),
        })
        .await;

        // CLI-specific: Create WIP snapshot even on failure
        let apply_count = serial_service.apply_count(&next.id);
        if let Err(e) = self.snapshot_serial_iteration(&next.id, apply_count).await {
            warn!("Failed to snapshot WIP commit for {}: {}", next.id, e);
        }

        // CLI-specific: Check circuit breaker
        if self
            .record_error_and_check_circuit_breaker(&next.id, error)
            .await
        {
            let message = format!(
                "Circuit breaker opened for '{}' due to repeated errors",
                next.id
            );
            warn!("{}", message);
            self.mark_change_stalled(&next.id, &message).await;
            serial_service.mark_stalled(&next.id, &message);
            return Ok(());
        }

        error!("Apply failed for {}: {}", next.id, error);
        if let Some(progress) = &mut self.progress {
            progress.error(&format!("Apply failed: {}", next.id));
        }
        #[cfg(feature = "web-monitoring")]
        self.update_execution_mode("error").await;
        Err(OrchestratorError::AgentCommand(error.to_string()))
    }

    /// Handle acceptance-related results (Passed, Continue, ContinueExceeded, Failed, CommandFailed, Blocked)
    async fn handle_acceptance_result(
        &mut self,
        next: &Change,
        serial_service: &mut SerialRunService,
        result: &crate::serial_run_service::ChangeProcessResult,
    ) {
        use crate::serial_run_service::ChangeProcessResult;

        // Common state update for all acceptance results
        self.update_shared_state(ExecutionEvent::ApplyCompleted {
            change_id: next.id.clone(),
            revision: "serial".to_string(),
        })
        .await;

        // Specific handling based on result type
        match result {
            ChangeProcessResult::AcceptancePassed => {
                // CLI-specific: Squash WIP commits after acceptance pass
                let apply_count = serial_service.apply_count(&next.id);
                let _ = self.squash_serial_wip_commits(&next.id, apply_count).await;
                info!("Acceptance passed for {}, ready for archive", next.id);
            }
            ChangeProcessResult::AcceptanceContinue => {
                info!(
                    "Acceptance requires continuation for {}, retrying...",
                    next.id
                );
            }
            ChangeProcessResult::AcceptanceContinueExceeded => {
                warn!(
                    "Acceptance CONTINUE limit exceeded for {}, treating as FAIL",
                    next.id
                );
            }
            ChangeProcessResult::Rejected { reason } => {
                info!(
                    "Acceptance gated for {} - rejected flow completed: {}",
                    next.id, reason
                );
                self.update_shared_state(ExecutionEvent::ChangeRejected {
                    change_id: next.id.clone(),
                    reason: reason.clone(),
                })
                .await;
            }
            ChangeProcessResult::AcceptanceFailed { .. } => {
                info!("Acceptance failed for {}, will retry apply", next.id);
            }
            ChangeProcessResult::AcceptanceCommandFailed { .. } => {
                info!(
                    "Acceptance command failed for {}, will retry apply",
                    next.id
                );
            }
            _ => {}
        }

        if let Some(progress) = &mut self.progress {
            progress.complete_change(&next.id);
        }
    }

    /// Initialize run loop state (shared state, progress display, serial service).
    /// Returns (filtered_initial_changes, serial_service, total_changes).
    async fn initialize_run_loop(
        &mut self,
        initial_changes: Vec<Change>,
    ) -> Result<(Vec<Change>, SerialRunService, usize)> {
        // Filter by target_changes if specified (early filtering)
        let filtered_initial = if let Some(targets) = &self.target_changes {
            // Explicit targets specified via --change option
            let mut found = Vec::new();
            for target in targets {
                let trimmed = target.trim();
                if let Some(change) = initial_changes.iter().find(|c| c.id == trimmed) {
                    found.push(change.clone());
                } else {
                    warn!("Specified change '{}' not found, skipping", trimmed);
                }
            }
            found
        } else {
            // No explicit target: return all changes
            initial_changes
        };

        if filtered_initial.is_empty() {
            // Return empty result - caller will handle early exit
            let repo_root = std::env::current_dir()?;
            let serial_service = SerialRunService::new(repo_root, self.config.clone());
            return Ok((filtered_initial, serial_service, 0));
        }

        // Store snapshot of change IDs (only the filtered ones)
        let snapshot_ids: HashSet<String> = filtered_initial.iter().map(|c| c.id.clone()).collect();
        info!(
            "Captured snapshot of {} changes: {:?}",
            snapshot_ids.len(),
            snapshot_ids
        );
        self.initial_change_ids = Some(snapshot_ids.clone());

        // Initialize shared orchestration state with filtered changes (serial mode)
        let change_ids: Vec<String> = filtered_initial.iter().map(|c| c.id.clone()).collect();
        *self.shared_state.write().await = OrchestratorState::new(change_ids, self.max_iterations);

        // Initialize progress display
        self.progress = Some(ProgressDisplay::new(filtered_initial.len()));

        let total_changes = filtered_initial.len();

        // Create serial run service for shared state and helpers
        let repo_root = std::env::current_dir()?;
        let serial_service = SerialRunService::new(repo_root, self.config.clone());

        Ok((filtered_initial, serial_service, total_changes))
    }

    /// Handle ChangeProcessResult and return LoopControl
    async fn handle_change_result(
        &mut self,
        result: crate::serial_run_service::ChangeProcessResult,
        next: &Change,
        serial_service: &mut SerialRunService,
    ) -> Result<LoopControl> {
        use crate::serial_run_service::ChangeProcessResult;

        match result {
            ChangeProcessResult::Archived => {
                self.handle_archived(next).await;
                Ok(LoopControl::Continue)
            }
            ChangeProcessResult::Stalled { error } => Ok(self.handle_stalled(next, &error).await),
            ChangeProcessResult::Failed { error } => {
                self.handle_failed(next, &error).await?;
                Ok(LoopControl::Continue)
            }
            ChangeProcessResult::Cancelled => {
                info!("Processing cancelled for {}", next.id);
                Ok(LoopControl::Break {
                    finish_status: "cancelled",
                })
            }
            ChangeProcessResult::ChangeStopped => {
                // In CLI mode, single-change stop is not applicable (no TUI queue)
                // Treat it as a global cancel
                info!("Change {} stopped", next.id);
                Ok(LoopControl::Break {
                    finish_status: "stopped",
                })
            }
            ChangeProcessResult::ApplySuccessIncomplete => Ok(self
                .handle_apply_success_incomplete(next, serial_service)
                .await),
            ChangeProcessResult::ApplyFailed { error } => {
                self.handle_apply_failed(next, &error, serial_service)
                    .await?;
                Ok(LoopControl::Continue)
            }
            ChangeProcessResult::AcceptancePassed
            | ChangeProcessResult::AcceptanceContinue
            | ChangeProcessResult::AcceptanceContinueExceeded
            | ChangeProcessResult::AcceptanceFailed { .. }
            | ChangeProcessResult::AcceptanceCommandFailed { .. }
            | ChangeProcessResult::Rejected { .. } => {
                self.handle_acceptance_result(next, serial_service, &result)
                    .await;
                Ok(LoopControl::Continue)
            }
        }
    }

    /// Run the orchestration loop with cancellation support
    pub async fn run(
        &mut self,
        cancel_token: tokio_util::sync::CancellationToken,
        graceful_stop_flag: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
    ) -> Result<()> {
        info!("Starting orchestration loop");

        // Set execution mode to running (for web monitoring)
        #[cfg(feature = "web-monitoring")]
        {
            self.execution_mode = "running".to_string();
        }

        // Capture initial snapshot of change IDs at run start.
        // Only changes present at this point will be processed during the run.
        // This prevents mid-run proposals from being processed before they are ready.
        let initial_changes = openspec::list_changes_native()?;

        // Handle parallel mode with dry_run
        if self.parallel && self.dry_run {
            return self.run_parallel_dry_run(&initial_changes).await;
        }

        // Handle parallel execution mode
        if self.parallel {
            return self
                .run_parallel(&initial_changes, cancel_token, graceful_stop_flag)
                .await;
        }

        if initial_changes.is_empty() {
            info!("No changes found");
            return Ok(());
        }

        // Initialize run loop state (shared state, progress display, serial service)
        let (filtered_initial, mut serial_service, total_changes) =
            self.initialize_run_loop(initial_changes).await?;

        if filtered_initial.is_empty() {
            info!("No changes found matching specified targets");
            return Ok(());
        }

        // Run on_start hook
        let start_context = HookContext::new(0, total_changes, total_changes, false);
        self.hooks
            .run_hook(HookType::OnStart, &start_context)
            .await?;

        let finish_status;

        // Track previous graceful stop state to detect transitions (false -> true)
        let mut previous_graceful_stop = false;

        loop {
            // Check all loop control conditions (graceful stop, cancellation, max iterations)
            match self
                .check_loop_controls(
                    &graceful_stop_flag,
                    &mut previous_graceful_stop,
                    &cancel_token,
                )
                .await
            {
                LoopControl::Continue => {}
                LoopControl::Break {
                    finish_status: status,
                } => {
                    finish_status = status;
                    break;
                }
            }

            // Refetch and select next change to process
            let (next, remaining_changes) =
                match self.refetch_and_select_change(&mut serial_service).await? {
                    Some(result) => result,
                    None => {
                        // All changes processed or stalled
                        finish_status = "completed";
                        break;
                    }
                };

            // Check if this is a new change (for state tracking)
            let is_new_change = {
                let state = self.shared_state.read().await;
                state.current_change_id() != Some(&next.id)
            };
            if is_new_change {
                // Update shared state: processing started
                self.update_shared_state(ExecutionEvent::ProcessingStarted(next.id.clone()))
                    .await;

                // Note: OnChangeStart hook is called by process_change() internally
            }

            // Process the change through SerialRunService
            let output = LogOutputHandler::new();
            let cancel_check = || false; // No cancellation in CLI mode
            let is_single_change_stopped = || false; // No single-change stop in CLI mode

            let result = serial_service
                .process_change(
                    &next,
                    &mut self.agent,
                    &self.ai_runner,
                    &self.hooks,
                    &output,
                    total_changes,
                    remaining_changes,
                    cancel_check,
                    is_single_change_stopped,
                    None, // No operation tracker in CLI mode
                )
                .await?;

            // Handle mode-specific concerns based on result
            match self
                .handle_change_result(result, &next, &mut serial_service)
                .await?
            {
                LoopControl::Continue => {}
                LoopControl::Break {
                    finish_status: status,
                } => {
                    finish_status = status;
                    break;
                }
            }
        }

        // Run on_finish hook
        let processed = self.shared_state.read().await.changes_processed();
        let finish_context =
            HookContext::new(processed, total_changes, 0, false).with_status(finish_status);
        self.hooks
            .run_hook(HookType::OnFinish, &finish_context)
            .await?;

        // Set execution mode to stopped (for web monitoring)
        #[cfg(feature = "web-monitoring")]
        self.update_execution_mode("stopped").await;

        info!("Orchestration completed");
        Ok(())
    }

    async fn snapshot_serial_iteration(
        &self,
        change_id: &str,
        iteration: u32,
    ) -> Result<SerialSnapshot> {
        let repo_root = std::env::current_dir()?;
        let progress =
            check_task_progress(&repo_root, change_id).unwrap_or_else(|_| TaskProgress::default());
        let mut empty_commit = None;

        if matches!(self.vcs_backend, VcsBackend::Git | VcsBackend::Auto) {
            let is_git_repo = match git_commands::check_git_repo(&repo_root).await {
                Ok(is_repo) => is_repo,
                Err(e) => {
                    warn!("Failed to check Git repository status: {}", e);
                    false
                }
            };

            if is_git_repo {
                let workspace_manager = GitWorkspaceManager::new(
                    repo_root.join(".openspec-worktrees"),
                    repo_root.clone(),
                    1,
                    self.config.clone(),
                );

                if let Err(e) = create_progress_commit(
                    &workspace_manager,
                    &repo_root,
                    change_id,
                    &progress,
                    iteration,
                )
                .await
                {
                    warn!(
                        "Failed to create WIP commit for {} (apply#{}): {}",
                        change_id, iteration, e
                    );
                } else {
                    match git_commands::is_head_empty_commit(&repo_root).await {
                        Ok(is_empty) => empty_commit = Some(is_empty),
                        Err(e) => {
                            warn!(
                                "Failed to check WIP commit contents for {} (apply#{}): {}",
                                change_id, iteration, e
                            );
                        }
                    }
                }
            }
        }

        Ok(SerialSnapshot {
            progress,
            empty_commit,
        })
    }

    async fn squash_serial_wip_commits(&self, change_id: &str, iteration: u32) -> Result<()> {
        if !matches!(self.vcs_backend, VcsBackend::Git | VcsBackend::Auto) {
            return Ok(());
        }

        let repo_root = std::env::current_dir()?;
        let is_git_repo = match git_commands::check_git_repo(&repo_root).await {
            Ok(is_repo) => is_repo,
            Err(e) => {
                warn!("Failed to check Git repository status: {}", e);
                false
            }
        };

        if !is_git_repo {
            return Ok(());
        }

        let workspace_manager = GitWorkspaceManager::new(
            repo_root.join(".openspec-worktrees"),
            repo_root.clone(),
            1,
            self.config.clone(),
        );

        if let Err(e) = workspace_manager
            .squash_wip_commits(&repo_root, change_id, iteration)
            .await
        {
            warn!(
                "Failed to squash WIP commits for {} (apply#{}): {}",
                change_id, iteration, e
            );
        }

        Ok(())
    }

    /// Filter changes to only include those present in the initial snapshot.
    /// Returns an empty vector if no snapshot was captured.
    fn filter_to_snapshot(&self, changes: &[Change]) -> Vec<Change> {
        match &self.initial_change_ids {
            Some(snapshot) => changes
                .iter()
                .filter(|c| snapshot.contains(&c.id))
                .cloned()
                .collect(),
            None => changes.to_vec(),
        }
    }

    /// Log any changes that were not present in the initial snapshot.
    /// These are new changes added after the run started and will be ignored.
    fn log_new_changes(&self, changes: &[Change]) {
        if let Some(snapshot) = &self.initial_change_ids {
            for change in changes {
                if !snapshot.contains(&change.id) {
                    warn!(
                        "New change '{}' detected after run started - will be ignored",
                        change.id
                    );
                }
            }
        }
    }

    /// Filter out stalled changes and those blocked by stalled dependencies.
    async fn filter_stalled_changes(&mut self, changes: &[Change]) -> Vec<Change> {
        let mut eligible = Vec::new();
        let mut state = self.shared_state.write().await;

        for change in changes {
            if state.stalled_change_ids().contains(&change.id) {
                continue;
            }

            if let Some(failed_dep) = change
                .dependencies
                .iter()
                .find(|dep| state.stalled_change_ids().contains(*dep))
            {
                if state.mark_skipped(change.id.clone()) {
                    warn!(
                        "Skipping '{}' because dependency '{}' stalled",
                        change.id, failed_dep
                    );
                }
                continue;
            }

            eligible.push(change.clone());
        }

        eligible
    }

    /// Refetch and filter changes for the current iteration.
    /// Returns None if loop should break (all changes processed or stalled).
    /// Returns Some((next_change, remaining_count)) if a change was selected.
    async fn refetch_and_select_change(
        &mut self,
        serial_service: &mut SerialRunService,
    ) -> Result<Option<(Change, usize)>> {
        // List all changes from openspec (to get updated progress)
        let changes = openspec::list_changes_native()?;

        // Broadcast state update to web monitoring clients
        self.broadcast_state_update(&changes).await;

        // Filter to only include changes from initial snapshot
        let snapshot_changes = self.filter_to_snapshot(&changes);

        // Log any new changes that appeared after run started
        self.log_new_changes(&changes);

        if snapshot_changes.is_empty() {
            info!("All changes from initial snapshot processed");
            if let Some(progress) = &mut self.progress {
                progress.complete_all();
            }
            return Ok(None);
        }

        let eligible_changes = self.filter_stalled_changes(&snapshot_changes).await;
        let remaining_changes = eligible_changes.len();

        if eligible_changes.is_empty() {
            info!("All remaining changes are blocked by stalled dependencies");
            if let Some(progress) = &mut self.progress {
                progress.complete_all();
            }
            return Ok(None);
        }

        // Select next change to process using serial service
        let next = serial_service
            .select_next_change(&eligible_changes)
            .ok_or_else(|| {
                OrchestratorError::AgentCommand("No eligible change found".to_string())
            })?;
        info!("Selected change: {}", next.id);

        if let Some(progress) = &mut self.progress {
            progress.update_change(next);
        }

        Ok(Some((next.clone(), remaining_changes)))
    }

    async fn mark_change_stalled(&mut self, change_id: &str, reason: &str) {
        {
            let mut state = self.shared_state.write().await;
            state.add_dynamic_change(change_id.to_string());
            state.mark_stalled(change_id.to_string());
            state.clear_stalled_change(change_id);
            state.clear_error_history(change_id);
            state.apply_execution_event(&ExecutionEvent::WorkspaceStatusUpdated {
                change_id: change_id.to_string(),
                workspace_name: "serial-stalled".to_string(),
                status: crate::vcs::WorkspaceStatus::Blocked,
            });
        }
        self.stall_detector.clear_change(change_id);

        if let Some(progress) = &mut self.progress {
            progress.error(reason);
        }
    }

    /// Record an error and check if circuit breaker should trip
    /// Returns true if the change should be skipped due to repeated errors
    async fn record_error_and_check_circuit_breaker(
        &mut self,
        change_id: &str,
        error: &str,
    ) -> bool {
        let cb_config = self.config.get_error_circuit_breaker();
        let circuit_breaker_config = CircuitBreakerConfig {
            enabled: cb_config.enabled,
            threshold: cb_config.threshold,
        };

        let mut state = self.shared_state.write().await;
        if state.record_error_and_check_circuit_breaker(
            change_id,
            error,
            circuit_breaker_config.clone(),
        ) {
            error!(
                "Circuit breaker triggered for '{}': same error occurred {} times consecutively",
                change_id, circuit_breaker_config.threshold
            );
            if let Some(last_err) = state.last_error(change_id) {
                error!("Last error pattern: {}", last_err);
            }
            true
        } else {
            false
        }
    }

    /// Set initial change IDs snapshot directly (for testing purposes)
    #[cfg(test)]
    pub fn set_initial_change_ids(&mut self, ids: HashSet<String>) {
        self.initial_change_ids = Some(ids);
    }

    /// Run parallel mode with dry run (preview parallelization groups)
    async fn run_parallel_dry_run(&self, changes: &[Change]) -> Result<()> {
        info!("Running parallel mode dry run (preview only)");

        if changes.is_empty() {
            println!("No changes found for parallel execution.");
            return Ok(());
        }

        // Use ParallelRunService to analyze groups (uses LLM if enabled)
        let repo_root = std::env::current_dir()?;
        let service = ParallelRunService::new(repo_root, self.config.clone());
        let groups = service.analyze_and_group_public(changes).await;

        // Display parallelization groups
        println!("\n=== Parallel Execution Plan (Dry Run) ===\n");
        println!("Total changes: {}", changes.len());
        println!("Parallelization groups: {}\n", groups.len());

        for group in &groups {
            println!("Group {} (can run in parallel):", group.id);
            for change_id in &group.changes {
                let change = changes.iter().find(|c| c.id == *change_id);
                if let Some(c) = change {
                    println!(
                        "  - {} ({}/{} tasks, {:.1}%)",
                        c.id,
                        c.completed_tasks,
                        c.total_tasks,
                        c.progress_percent()
                    );
                } else {
                    println!("  - {}", change_id);
                }
            }
            if !group.depends_on.is_empty() {
                println!("  (depends on group(s): {:?})", group.depends_on);
            }
            println!();
        }

        println!(
            "Max concurrent workspaces: {}",
            self.max_concurrent.unwrap_or(4)
        );
        println!("\nTo execute, run without --dry-run flag.");

        Ok(())
    }

    /// Run parallel execution mode
    async fn run_parallel(
        &mut self,
        changes: &[Change],
        cancel_token: tokio_util::sync::CancellationToken,
        graceful_stop_flag: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
    ) -> Result<()> {
        info!("Running parallel execution mode");

        if changes.is_empty() {
            info!("No changes found for parallel execution");
            return Ok(());
        }

        // Store snapshot of change IDs
        let snapshot_ids: HashSet<String> = changes.iter().map(|c| c.id.clone()).collect();
        self.initial_change_ids = Some(snapshot_ids);

        // Initialize shared orchestration state with parallel execution mode
        {
            let change_ids: Vec<String> = changes.iter().map(|c| c.id.clone()).collect();
            *self.shared_state.write().await = OrchestratorState::with_mode(
                change_ids,
                self.max_iterations,
                crate::orchestration::state::ExecutionMode::Parallel,
            );
        }

        // Use ParallelRunService for the common parallel execution flow
        let repo_root = std::env::current_dir()?;
        let mut service = ParallelRunService::new(repo_root.clone(), self.config.clone());
        service.set_no_resume(self.no_resume);
        service.set_shared_orchestrator_state(self.shared_state.clone());

        // Check if Git is available for true parallel execution
        service.check_vcs_available().await?;

        info!("Git available, executing changes in parallel using worktrees");

        #[cfg(feature = "web-monitoring")]
        let (web_event_tx, web_event_handle) = if let Some(web_state) = self.web_state.clone() {
            let (tx, mut rx) = mpsc::unbounded_channel();
            let handle = tokio::spawn(async move {
                while let Some(event) = rx.recv().await {
                    crate::web::WebState::apply_execution_event(&web_state, &event).await;
                    if matches!(
                        event,
                        crate::events::ExecutionEvent::AllCompleted
                            | crate::events::ExecutionEvent::Stopped
                    ) {
                        break;
                    }
                }
            });
            (Some(tx), Some(handle))
        } else {
            (None, None)
        };

        #[cfg(feature = "web-monitoring")]
        let web_event_sender = web_event_tx.clone();

        // Monitor graceful_stop_flag and trigger cancellation if set
        // This allows Web control Stop to work in parallel mode
        if let Some(ref stop_flag) = graceful_stop_flag {
            let monitor_token = cancel_token.clone();
            let monitor_flag = stop_flag.clone();
            tokio::spawn(async move {
                loop {
                    tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
                    if monitor_flag.load(std::sync::atomic::Ordering::SeqCst) {
                        info!("Graceful stop requested in parallel mode, cancelling execution");
                        monitor_token.cancel();
                        break;
                    }
                }
            });
        }

        // Track start-time rejections so we can report clearly when no work started.
        let total_requested = changes.len();
        let rejected_count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let track_rejected = rejected_count.clone();

        // Run with a simple logging event handler for CLI mode
        let result = service
            .run_parallel(changes.to_vec(), Some(cancel_token), move |event| {
                // Log events for CLI mode (no TUI)
                use crate::parallel::ParallelEvent;
                #[cfg(feature = "web-monitoring")]
                if let Some(tx) = &web_event_sender {
                    let _ = tx.send(event.clone());
                }
                match event {
                    ParallelEvent::ParallelStartRejected {
                        ref change_ids,
                        ref reason,
                    } => {
                        // Immediately surface the rejection so the user knows these changes
                        // will not run, even before the overall completion message.
                        eprintln!(
                            "WARNING: {} change(s) rejected at start-time ({}): {}",
                            change_ids.len(),
                            reason,
                            change_ids.join(", ")
                        );
                        track_rejected
                            .fetch_add(change_ids.len(), std::sync::atomic::Ordering::SeqCst);
                    }
                    ParallelEvent::ApplyStarted { change_id, command } => {
                        info!("Apply started for {}", change_id);
                        println!("[{} apply] {}", change_id, command);
                    }
                    ParallelEvent::ApplyOutput {
                        change_id,
                        output,
                        iteration,
                    } => {
                        let iter = iteration
                            .map(|n| format!("#{}", n))
                            .unwrap_or_else(|| "".to_string());
                        if iter.is_empty() {
                            println!("[{} apply] {}", change_id, output);
                        } else {
                            println!("[{} apply {}] {}", change_id, iter, output);
                        }
                    }
                    ParallelEvent::ProgressUpdated {
                        change_id,
                        completed,
                        total,
                    } if total > 0 => {
                        info!("Progress {}: {}/{}", change_id, completed, total);
                    }
                    ParallelEvent::ApplyCompleted { change_id, .. } => {
                        info!("Apply completed for {}", change_id);
                    }
                    ParallelEvent::ApplyFailed { change_id, error } => {
                        error!("Apply failed for {}: {}", change_id, error);
                    }
                    ParallelEvent::AcceptanceStarted { change_id, command } => {
                        info!("Acceptance started for {}", change_id);
                        println!("[{} acceptance] {}", change_id, command);
                    }
                    ParallelEvent::AcceptanceOutput {
                        change_id,
                        output,
                        iteration,
                    } => {
                        let iter = iteration
                            .map(|n| format!("#{}", n))
                            .unwrap_or_else(|| "".to_string());
                        if iter.is_empty() {
                            println!("[{} acceptance] {}", change_id, output);
                        } else {
                            println!("[{} acceptance {}] {}", change_id, iter, output);
                        }
                    }
                    ParallelEvent::AcceptanceCompleted { change_id } => {
                        info!("Acceptance completed for {}", change_id);
                    }
                    ParallelEvent::AcceptanceFailed { change_id, error } => {
                        error!("Acceptance failed for {}: {}", change_id, error);
                    }
                    ParallelEvent::ArchiveStarted { change_id, command } => {
                        info!("Archive started for {}", change_id);
                        println!("[{} archive] {}", change_id, command);
                    }
                    ParallelEvent::ArchiveResumed {
                        change_id,
                        reason,
                        summary,
                    } => {
                        info!(
                            "Archive resumed for {} (reason={:?}, summary={:?})",
                            change_id, reason, summary
                        );
                    }
                    ParallelEvent::ArchiveRetryScheduled {
                        change_id,
                        attempt,
                        max_attempts,
                        reason,
                        summary,
                    } => {
                        warn!(
                            "Archive retry scheduled for {} ({}/{}): reason={:?}, summary={:?}",
                            change_id, attempt, max_attempts, reason, summary
                        );
                    }
                    ParallelEvent::ArchiveOutput {
                        change_id,
                        output,
                        iteration,
                    } => {
                        println!("[{} archive #{}] {}", change_id, iteration, output);
                    }
                    ParallelEvent::ChangeArchived(change_id) => {
                        info!("Archived {}", change_id);
                    }
                    ParallelEvent::ArchiveFailed {
                        change_id,
                        error,
                        reason,
                        summary,
                    } => {
                        error!(
                            "Archive failed for {}: {} (reason={:?}, summary={:?})",
                            change_id, error, reason, summary
                        );
                    }
                    ParallelEvent::AllCompleted => {
                        info!("All parallel execution completed");
                    }
                    ParallelEvent::Error { message } => {
                        error!("Parallel execution error: {}", message);
                    }
                    ParallelEvent::Warning { message, .. } => {
                        eprintln!("{}", message);
                    }
                    ParallelEvent::Log(entry) => {
                        // Forward user-facing log entries in CLI mode as well.
                        println!("{}", entry.message);
                    }
                    _ => {}
                }
            })
            .await;

        #[cfg(feature = "web-monitoring")]
        if let Some(handle) = web_event_handle {
            drop(web_event_tx);
            let _ = handle.await;
        }

        result?;

        // Report clearly when all requested changes were rejected before any work started.
        let n_rejected = rejected_count.load(std::sync::atomic::Ordering::SeqCst);
        if n_rejected >= total_requested && total_requested > 0 {
            eprintln!(
                "ERROR: No changes started: all {} requested change(s) were rejected by \
                 start-time eligibility filter (uncommitted or not in HEAD). \
                 Commit your changes before running in parallel mode.",
                total_requested
            );
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::openspec::ProposalMetadata;

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

    #[test]
    fn test_filter_to_snapshot_filters_new_changes() {
        // Create orchestrator with mock config (won't be used in this test)
        let config = OrchestratorConfig::default();
        let mut orchestrator = Orchestrator::with_config(None, config).unwrap();

        // Set up snapshot with only change-a and change-b
        let snapshot: HashSet<String> = ["change-a", "change-b"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        orchestrator.set_initial_change_ids(snapshot);

        // Create changes list including new change-c
        let all_changes = vec![
            create_test_change("change-a", 2, 5),
            create_test_change("change-b", 3, 5),
            create_test_change("change-c", 0, 3), // New change, not in snapshot
        ];

        // Filter to snapshot
        let filtered = orchestrator.filter_to_snapshot(&all_changes);

        // Should only include change-a and change-b
        assert_eq!(filtered.len(), 2);
        assert!(filtered.iter().any(|c| c.id == "change-a"));
        assert!(filtered.iter().any(|c| c.id == "change-b"));
        assert!(!filtered.iter().any(|c| c.id == "change-c"));
    }

    #[test]
    fn test_filter_to_snapshot_returns_all_when_no_snapshot() {
        // Create orchestrator without setting snapshot
        let config = OrchestratorConfig::default();
        let orchestrator = Orchestrator::with_config(None, config).unwrap();

        let all_changes = vec![
            create_test_change("change-a", 2, 5),
            create_test_change("change-b", 3, 5),
        ];

        // Should return all changes when no snapshot is set
        let filtered = orchestrator.filter_to_snapshot(&all_changes);
        assert_eq!(filtered.len(), 2);
    }

    #[test]
    fn test_filter_to_snapshot_removes_archived_changes() {
        let config = OrchestratorConfig::default();
        let mut orchestrator = Orchestrator::with_config(None, config).unwrap();

        // Set up snapshot with change-a, change-b, change-c
        let snapshot: HashSet<String> = ["change-a", "change-b", "change-c"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        orchestrator.set_initial_change_ids(snapshot);

        // Simulate change-b being archived (no longer in list)
        let current_changes = vec![
            create_test_change("change-a", 2, 5),
            create_test_change("change-c", 1, 5),
        ];

        // Filter should only return change-a and change-c (both in snapshot and in current list)
        let filtered = orchestrator.filter_to_snapshot(&current_changes);
        assert_eq!(filtered.len(), 2);
        assert!(filtered.iter().any(|c| c.id == "change-a"));
        assert!(filtered.iter().any(|c| c.id == "change-c"));
    }

    #[test]
    fn test_filter_to_snapshot_handles_empty_changes() {
        let config = OrchestratorConfig::default();
        let mut orchestrator = Orchestrator::with_config(None, config).unwrap();

        let snapshot: HashSet<String> = ["change-a"].iter().map(|s| s.to_string()).collect();
        orchestrator.set_initial_change_ids(snapshot);

        // Empty changes list
        let current_changes: Vec<Change> = vec![];

        let filtered = orchestrator.filter_to_snapshot(&current_changes);
        assert!(filtered.is_empty());
    }

    #[test]
    fn test_snapshot_preserves_updated_progress() {
        let config = OrchestratorConfig::default();
        let mut orchestrator = Orchestrator::with_config(None, config).unwrap();

        // Set up snapshot with change-a
        let snapshot: HashSet<String> = ["change-a"].iter().map(|s| s.to_string()).collect();
        orchestrator.set_initial_change_ids(snapshot);

        // Create changes with updated progress for change-a
        let current_changes = vec![
            create_test_change("change-a", 4, 5), // Progress updated from 2/5 to 4/5
        ];

        let filtered = orchestrator.filter_to_snapshot(&current_changes);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].completed_tasks, 4); // Progress should be updated
    }

    #[tokio::test]
    async fn test_filter_stalled_changes_skips_dependencies() {
        let config = OrchestratorConfig::default();
        let mut orchestrator = Orchestrator::with_config(None, config).unwrap();
        orchestrator
            .shared_state
            .write()
            .await
            .mark_stalled("change-a".to_string());

        let changes = vec![
            Change {
                id: "change-a".to_string(),
                completed_tasks: 0,
                total_tasks: 3,
                last_modified: "now".to_string(),
                dependencies: Vec::new(),
                metadata: ProposalMetadata::default(),
            },
            Change {
                id: "change-b".to_string(),
                completed_tasks: 0,
                total_tasks: 3,
                last_modified: "now".to_string(),
                dependencies: vec!["change-a".to_string()],
                metadata: ProposalMetadata::default(),
            },
            Change {
                id: "change-c".to_string(),
                completed_tasks: 0,
                total_tasks: 3,
                last_modified: "now".to_string(),
                dependencies: Vec::new(),
                metadata: ProposalMetadata::default(),
            },
        ];

        let eligible = orchestrator.filter_stalled_changes(&changes).await;
        assert_eq!(eligible.len(), 1);
        assert_eq!(eligible[0].id, "change-c");
    }

    // Note: build_analysis_prompt tests moved to src/orchestration/selection.rs

    #[tokio::test]
    async fn test_orchestrator_creation() {
        let config = OrchestratorConfig::default();
        let orchestrator = Orchestrator::with_config(None, config).unwrap();

        assert!(orchestrator.target_changes.is_none());
        assert!(orchestrator.initial_change_ids.is_none());

        let state = orchestrator.shared_state.read().await;
        assert!(state.current_change_id().is_none());
        assert_eq!(state.changes_processed(), 0);
        assert_eq!(state.iteration(), 0);
    }

    #[test]
    fn test_orchestrator_with_single_target_change() {
        let config = OrchestratorConfig::default();
        let orchestrator =
            Orchestrator::with_config(Some(vec!["my-change".to_string()]), config).unwrap();

        assert_eq!(
            orchestrator.target_changes,
            Some(vec!["my-change".to_string()])
        );
    }

    #[test]
    fn test_orchestrator_with_multiple_target_changes() {
        let config = OrchestratorConfig::default();
        let orchestrator = Orchestrator::with_config(
            Some(vec![
                "change-a".to_string(),
                "change-b".to_string(),
                "change-c".to_string(),
            ]),
            config,
        )
        .unwrap();

        assert_eq!(
            orchestrator.target_changes,
            Some(vec![
                "change-a".to_string(),
                "change-b".to_string(),
                "change-c".to_string()
            ])
        );
    }

    #[tokio::test]
    async fn test_serial_shared_state_apply_count_and_iteration_increment() {
        let config = OrchestratorConfig::default();
        let mut orchestrator = Orchestrator::with_config(None, config).unwrap();

        {
            let mut state = orchestrator.shared_state.write().await;
            *state = crate::orchestration::state::OrchestratorState::new(
                vec!["change-a".to_string()],
                3,
            );
        }

        // check_max_iterations increments iteration in shared state
        match orchestrator.check_max_iterations().await {
            super::LoopControl::Continue => {}
            _ => panic!("iteration check should continue"),
        }

        {
            let state = orchestrator.shared_state.read().await;
            assert_eq!(state.iteration(), 1);
            assert_eq!(state.apply_count("change-a"), 0);
        }

        // ApplyCompleted increments per-change apply count in shared state
        orchestrator
            .update_shared_state(crate::events::ExecutionEvent::ApplyCompleted {
                change_id: "change-a".to_string(),
                revision: "serial".to_string(),
            })
            .await;

        let state = orchestrator.shared_state.read().await;
        assert_eq!(state.apply_count("change-a"), 1);
    }

    #[tokio::test]
    async fn test_stalled_result_marks_change_stalled_state() {
        use crate::serial_run_service::ChangeProcessResult;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config = OrchestratorConfig::default();
        let mut orchestrator = Orchestrator::with_config(None, config.clone()).unwrap();
        let mut serial_service = SerialRunService::new(temp_dir.path().to_path_buf(), config);

        let blocked_change = create_test_change("blocked-change", 3, 5);

        let result = ChangeProcessResult::Stalled {
            error: "Acceptance gated with recoverable blocker".to_string(),
        };

        orchestrator
            .handle_change_result(result, &blocked_change, &mut serial_service)
            .await
            .unwrap();

        let state = orchestrator.shared_state.read().await;
        assert_eq!(state.display_status(&blocked_change.id), "stalled");
    }

    /// Regression: when ALL requested changes are rejected by start-time eligibility filtering,
    /// the CLI event callback must count them as rejected so the orchestrator can report that
    /// zero changes started.  This test directly exercises the rejected_count accumulation
    /// logic used in `run_parallel_in_parallel_mode` to trigger the
    /// "ERROR: No changes started" message.
    #[test]
    fn test_cli_all_rejected_start_detection() {
        use crate::parallel::ParallelEvent;
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;

        let total_requested: usize = 2;
        let rejected_count = Arc::new(AtomicUsize::new(0));
        let track_rejected = rejected_count.clone();

        // Mirror the event-callback logic from run_parallel_in_parallel_mode.
        let handle_event = move |event: ParallelEvent| {
            if let ParallelEvent::ParallelStartRejected { change_ids, .. } = event {
                track_rejected.fetch_add(change_ids.len(), Ordering::SeqCst);
            }
        };

        // Simulate a single ParallelStartRejected event covering all requested changes.
        handle_event(ParallelEvent::ParallelStartRejected {
            change_ids: vec!["change-a".to_string(), "change-b".to_string()],
            reason: "uncommitted or not in HEAD".to_string(),
        });

        let n_rejected = rejected_count.load(Ordering::SeqCst);
        assert_eq!(
            n_rejected, total_requested,
            "rejected_count must equal total_requested when all changes are filtered out"
        );
        // Verify the guard condition used in the orchestrator to emit the error message.
        assert!(
            n_rejected >= total_requested && total_requested > 0,
            "orchestrator should detect the all-rejected condition and report no changes started"
        );
    }
}