cflx 0.6.189

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
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
//! Shared serial execution service for CLI and TUI modes.
//!
//! This module provides a unified service for running serial execution
//! that can be used by both CLI and TUI orchestrators, eliminating
//! code duplication between the two modes.
//!
//! The service provides helper functions for:
//! - Change selection based on progress and dependencies
//! - State tracking (apply counts, completed/stalled changes)
//! - Iteration limit checking
//! - Hook execution helpers
//!
//! The actual orchestration loop remains in the orchestrators for now,
//! as they have mode-specific concerns (WIP commits for CLI, DynamicQueue for TUI).

use crate::agent::{AgentRunner, OutputLine};
use crate::ai_command_runner::AiCommandRunner;
use crate::config::OrchestratorConfig;
use crate::error::Result;
use crate::execution::apply as common_apply;
use crate::hooks::{HookContext, HookRunner, HookType};
use crate::openspec::{self, Change};
use crate::orchestration::acceptance::{
    decide_acceptance_retry, missing_verdict_exhausted_error, normalize_findings,
    repository_findings, semantic_progress_fingerprint, AcceptanceRetryDecision,
    MissingVerdictRetryDriver, MissingVerdictRetryStep, MAX_MISSING_VERDICT_RETRIES,
};
use crate::orchestration::{
    acceptance_test_streaming, archive_change, AcceptanceResult, ArchiveContext, ArchiveResult,
    OutputHandler,
};
use crate::parallel::acceptance_state::{
    consume_resumable_acceptance_marker, parse_blocked_marker,
    write_acceptance_blocked_marker_with_context, AcceptanceRetryContext,
};
use crate::stall::{StallDetector, StallPhase};
use crate::task_parser;
use crate::task_parser::TaskProgress;
use crate::vcs::VcsBackend;

use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, warn};

/// Service for serial execution of changes.
///
/// This service encapsulates the shared logic between CLI and TUI
/// serial execution modes, including:
/// - Change selection
/// - Apply/archive flow
/// - Acceptance testing
/// - Hook execution
/// - Iteration tracking
/// - Stall detection
pub struct SerialRunService {
    /// Configuration for the orchestrator
    config: OrchestratorConfig,
    /// Repository root directory
    repo_root: PathBuf,
    /// Apply count per change
    apply_counts: HashMap<String, u32>,
    /// Currently processing change ID
    current_change_id: Option<String>,
    /// Completed change IDs
    completed_change_ids: HashSet<String>,
    /// Stalled change IDs
    stalled_change_ids: HashSet<String>,
    /// Stall detector for monitoring progress
    stall_detector: StallDetector,
    /// Changes processed count
    changes_processed: usize,
    /// Current iteration
    iteration: u32,
    /// In-memory acceptance retry context for the active run, keyed by change ID.
    ///
    /// This is deliberately not persisted: a restarted process starts a fresh
    /// acceptance sequence instead of trusting a generated checkpoint.
    acceptance_retry: HashMap<String, AcceptanceRetryContext>,
}

impl SerialRunService {
    /// Create a new serial run service
    pub fn new(repo_root: PathBuf, config: OrchestratorConfig) -> Self {
        let stall_config = config.get_stall_detection();
        Self {
            config,
            repo_root,
            apply_counts: HashMap::new(),
            current_change_id: None,
            completed_change_ids: HashSet::new(),
            stalled_change_ids: HashSet::new(),
            stall_detector: StallDetector::new(stall_config),
            changes_processed: 0,
            iteration: 0,
            acceptance_retry: HashMap::new(),
        }
    }

    /// Get the repository root path
    #[allow(dead_code)] // Reserved for future TUI integration
    pub fn repo_root(&self) -> &PathBuf {
        &self.repo_root
    }

    /// Get the current iteration number
    #[allow(dead_code)] // Reserved for future TUI integration
    pub fn iteration(&self) -> u32 {
        self.iteration
    }

    /// Get the number of changes processed
    #[allow(dead_code)] // Reserved for future TUI integration
    pub fn changes_processed(&self) -> usize {
        self.changes_processed
    }

    /// Get the current change ID being processed
    #[allow(dead_code)] // Reserved for future TUI integration
    pub fn current_change_id(&self) -> Option<&String> {
        self.current_change_id.as_ref()
    }

    /// Get apply count for a change
    pub fn apply_count(&self, change_id: &str) -> u32 {
        *self.apply_counts.get(change_id).unwrap_or(&0)
    }

    /// Increment apply count for a change
    fn increment_apply_count(&mut self, change_id: &str) {
        let count = self.apply_counts.entry(change_id.to_string()).or_insert(0);
        *count += 1;
    }

    /// Check if a change is stalled
    pub fn is_stalled(&self, change_id: &str) -> bool {
        self.stalled_change_ids.contains(change_id)
    }

    /// Check if a change is completed
    pub fn is_completed(&self, change_id: &str) -> bool {
        self.completed_change_ids.contains(change_id)
    }

    /// Select the next change to process.
    ///
    /// Prioritizes changes by highest progress percentage.
    /// Filters out stalled changes and their dependencies.
    pub fn select_next_change<'a>(&self, changes: &'a [Change]) -> Option<&'a Change> {
        // Filter out completed and stalled changes
        let eligible: Vec<_> = changes
            .iter()
            .filter(|c| !self.is_completed(&c.id) && !self.is_stalled(&c.id))
            .collect();

        // Further filter out changes that depend on stalled changes
        let filtered: Vec<_> = eligible
            .iter()
            .filter(|c| {
                !c.dependencies
                    .iter()
                    .any(|dep| self.stalled_change_ids.contains(dep))
            })
            .copied()
            .collect();

        if filtered.is_empty() {
            return None;
        }

        // Find incomplete changes and prioritize by progress
        let incomplete: Vec<_> = filtered.iter().filter(|c| !c.is_complete()).collect();

        if !incomplete.is_empty() {
            // Prioritize incomplete changes by highest progress percentage
            return incomplete
                .into_iter()
                .max_by(|a, b| {
                    let a_progress = if a.total_tasks > 0 {
                        a.completed_tasks as f32 / a.total_tasks as f32
                    } else {
                        0.0
                    };
                    let b_progress = if b.total_tasks > 0 {
                        b.completed_tasks as f32 / b.total_tasks as f32
                    } else {
                        0.0
                    };
                    a_progress
                        .partial_cmp(&b_progress)
                        .unwrap_or(std::cmp::Ordering::Equal)
                })
                .copied();
        }

        // If all are complete, select the first one for archiving
        filtered.first().copied()
    }

    /// Mark a change as stalled
    pub fn mark_stalled(&mut self, change_id: &str, reason: &str) {
        warn!("Marking {} as stalled: {}", change_id, reason);
        self.stalled_change_ids.insert(change_id.to_string());
    }

    /// Consume a resumable acceptance marker for an explicit serial retry.
    pub fn consume_explicit_acceptance_retry(&mut self, change_id: &str) -> Result<bool> {
        let consumed = consume_resumable_acceptance_marker(&self.repo_root, change_id)?;
        if consumed {
            self.stalled_change_ids.remove(change_id);
        }
        Ok(consumed)
    }

    /// Acceptance retry context accumulated during the active run.
    ///
    /// Returns `None` after a restart, which forces a fresh acceptance sequence.
    #[allow(dead_code)] // Consumed by active-run acceptance retry regression coverage.
    pub fn acceptance_retry_context(&self, change_id: &str) -> Option<&AcceptanceRetryContext> {
        self.acceptance_retry.get(change_id)
    }

    /// Record acceptance retry context for the active run only.
    pub fn set_acceptance_retry_context(
        &mut self,
        change_id: &str,
        context: AcceptanceRetryContext,
    ) {
        self.acceptance_retry.insert(change_id.to_string(), context);
    }

    /// Seed the agent with acceptance retry context gathered earlier in this run.
    ///
    /// Nothing is restored after a restart: the in-memory map is empty, so the
    /// next acceptance runs without a reconstructed baseline.
    fn seed_active_run_acceptance_history(&self, change_id: &str, agent: &mut AgentRunner) {
        let Some(context) = self.acceptance_retry.get(change_id) else {
            return;
        };
        if context.finding_identities.is_empty() {
            return;
        }

        let mut history = crate::history::AcceptanceHistory::new();
        history.set_checkpoint(
            change_id,
            context.cycle_count,
            context.finding_identities.clone(),
            context.semantic_fingerprint.clone(),
        );
        agent.seed_acceptance_history(history);
    }

    fn preflight_blocked_marker(&mut self, change_id: &str) -> Result<Option<ChangeProcessResult>> {
        if let Some(marker) = parse_blocked_marker(&self.repo_root, change_id)? {
            let error = format!("Blocked marker ({:?}): {}", marker.origin, marker.reason);
            self.mark_stalled(change_id, &error);
            return Ok(Some(ChangeProcessResult::Stalled { error }));
        }
        Ok(None)
    }

    /// Process a single iteration for a change.
    ///
    /// This includes:
    /// - Running hooks (on_change_start, pre_apply, post_apply, etc.)
    /// - Applying or archiving the change
    /// - Running acceptance tests
    /// - Stall detection
    ///
    /// Returns `Ok(ChangeProcessResult)` indicating the outcome.
    /// Callers should handle the result and decide whether to continue the loop.
    #[allow(clippy::too_many_arguments)]
    pub async fn process_change<O: OutputHandler, F, G>(
        &mut self,
        change: &Change,
        agent: &mut AgentRunner,
        ai_runner: &AiCommandRunner,
        hooks: &HookRunner,
        output: &O,
        total_changes: usize,
        remaining_changes: usize,
        cancel_check: F,
        is_single_change_stopped: G,
        operation_tracker: Option<std::sync::Arc<std::sync::RwLock<String>>>,
    ) -> Result<ChangeProcessResult>
    where
        F: Fn() -> bool + Clone + Send + 'static,
        G: Fn() -> bool + Clone,
    {
        self.iteration += 1;
        let change_id = &change.id;

        if let Some(result) = self.preflight_blocked_marker(change_id)? {
            return Ok(result);
        }

        // Check if this is a new change
        let is_new_change = self.current_change_id.as_ref() != Some(change_id);
        if is_new_change {
            // Run on_change_start hook
            let change_start_context = HookContext::new(
                self.changes_processed,
                total_changes,
                remaining_changes,
                false,
            )
            .with_change(change_id, change.completed_tasks, change.total_tasks)
            .with_apply_count(0);

            hooks
                .run_hook(HookType::OnChangeStart, &change_start_context)
                .await?;

            self.current_change_id = Some(change_id.clone());
        }

        let apply_count = self.apply_count(change_id);

        // Process the change
        if change.is_complete() {
            // Archive completed change
            self.archive_change_internal(
                change,
                agent,
                ai_runner,
                hooks,
                output,
                total_changes,
                remaining_changes,
                apply_count,
                operation_tracker,
            )
            .await
        } else {
            // Apply incomplete change
            self.apply_change_internal(
                change,
                agent,
                ai_runner,
                hooks,
                output,
                total_changes,
                remaining_changes,
                apply_count,
                &cancel_check,
                &is_single_change_stopped,
                operation_tracker,
            )
            .await
        }
    }

    /// Internal method to archive a change
    #[allow(clippy::too_many_arguments)]
    async fn archive_change_internal<O: OutputHandler>(
        &mut self,
        change: &Change,
        agent: &mut AgentRunner,
        ai_runner: &AiCommandRunner,
        hooks: &HookRunner,
        output: &O,
        total_changes: usize,
        remaining_changes: usize,
        apply_count: u32,
        operation_tracker: Option<std::sync::Arc<std::sync::RwLock<String>>>,
    ) -> Result<ChangeProcessResult> {
        info!("Change {} is complete, archiving...", change.id);

        // Update operation to "archive" before running archive
        Self::update_operation_tracker(&operation_tracker, "archive");

        let archive_ctx = ArchiveContext::new(
            self.changes_processed,
            total_changes,
            remaining_changes,
            apply_count,
        );

        let stall_config = self.config.get_stall_detection();

        match archive_change(
            change,
            agent,
            ai_runner,
            hooks,
            &archive_ctx,
            output,
            None,
            &stall_config,
        )
        .await
        {
            Ok(ArchiveResult::Success) => {
                // Update changes_processed count
                self.changes_processed += 1;

                // Clear acceptance history after successful archive
                agent.clear_acceptance_history(&change.id);

                // Run on_change_end hook (not included in shared archive_change)
                let new_remaining = remaining_changes.saturating_sub(1);
                let change_end_context =
                    HookContext::new(self.changes_processed, total_changes, new_remaining, false)
                        .with_change(&change.id, change.completed_tasks, change.total_tasks)
                        .with_apply_count(apply_count);
                hooks
                    .run_hook(HookType::OnChangeEnd, &change_end_context)
                    .await?;

                // Run on_merged hook after on_change_end (serial mode: archive success = merge complete equivalent)
                let merged_context =
                    HookContext::new(self.changes_processed, total_changes, new_remaining, false)
                        .with_change(&change.id, change.completed_tasks, change.total_tasks)
                        .with_apply_count(apply_count);
                hooks.run_hook(HookType::OnMerged, &merged_context).await?;

                // Mark change as completed and clear current
                self.completed_change_ids.insert(change.id.clone());
                self.current_change_id = None;
                self.apply_counts.remove(&change.id);
                self.stall_detector.clear_change(&change.id);

                Ok(ChangeProcessResult::Archived)
            }
            Ok(ArchiveResult::Stalled { error }) => {
                self.mark_stalled(&change.id, &error);
                Ok(ChangeProcessResult::Stalled { error })
            }
            Ok(ArchiveResult::Failed { error }) => Ok(ChangeProcessResult::Failed { error }),
            Ok(ArchiveResult::Cancelled) => Ok(ChangeProcessResult::Cancelled),
            Err(e) => Err(e),
        }
    }

    /// Internal method to apply a change
    #[allow(clippy::too_many_arguments)]
    async fn apply_change_internal<O: OutputHandler, F, G>(
        &mut self,
        change: &Change,
        agent: &mut AgentRunner,
        ai_runner: &AiCommandRunner,
        hooks: &HookRunner,
        output: &O,
        total_changes: usize,
        remaining_changes: usize,
        _apply_count: u32,
        cancel_check: &F,
        is_single_change_stopped: &G,
        operation_tracker: Option<std::sync::Arc<std::sync::RwLock<String>>>,
    ) -> Result<ChangeProcessResult>
    where
        F: Fn() -> bool + Clone + Send + 'static,
        G: Fn() -> bool + Clone,
    {
        info!("Applying change: {}", change.id);

        // Create event handler for apply loop
        let event_handler = SerialApplyEventHandler::new(output);

        // Create hook context for apply loop
        let hook_ctx = common_apply::ApplyLoopHookContext::serial(
            self.changes_processed,
            total_changes,
            remaining_changes,
        );

        // Create a cancellation token and spawn a background task to poll cancel_check
        // This allows us to bridge the cancel_check closure to CancellationToken
        let cancel_token = CancellationToken::new();
        let cancel_token_for_task = cancel_token.clone();
        let cancel_check_clone = cancel_check.clone();
        let cancel_task = tokio::spawn(async move {
            loop {
                if cancel_check_clone() {
                    cancel_token_for_task.cancel();
                    break;
                }
                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
            }
        });

        // Execute apply loop using common implementation
        let apply_result = match common_apply::execute_apply_loop(
            &change.id,
            &self.repo_root,
            &self.config,
            agent,
            VcsBackend::Git,
            None, // workspace_manager (None for serial mode)
            Some(hooks),
            &hook_ctx,
            &event_handler,
            Some(&cancel_token), // Pass cancel_token to enable apply loop cancellation
            ai_runner,
            |line| async move {
                match &line {
                    OutputLine::Stdout(s) => output.on_stdout(s),
                    OutputLine::Stderr(s) => output.on_agent_stderr(s),
                }
            },
        )
        .await
        {
            Ok(result) => result,
            Err(crate::error::OrchestratorError::PermissionBlocked {
                denied_path,
                guidance,
            }) => {
                // Abort the background cancel monitoring task
                cancel_task.abort();

                // Mark as stalled with permission guidance
                let error_message = format!(
                    "Permission auto-rejected for: {}\n{}",
                    denied_path, guidance
                );
                self.mark_stalled(&change.id, &error_message);
                return Ok(ChangeProcessResult::Stalled {
                    error: error_message,
                });
            }
            Err(e) => {
                // Abort the background cancel monitoring task
                cancel_task.abort();
                return Err(e);
            }
        };

        // Abort the background cancel monitoring task now that apply is complete
        cancel_task.abort();

        let apply_blocked_handoff = apply_result.blocked_handoff.clone();

        // Check if apply loop completed successfully or detected blocked handoff.
        if apply_result.completed || apply_blocked_handoff.is_some() {
            if apply_result.completed {
                info!(
                    "Apply loop completed for {} after {} iterations",
                    change.id, apply_result.iterations
                );
            } else if let Some(ref handoff) = apply_blocked_handoff {
                warn!(
                    change_id = %change.id,
                    blocker_path = %handoff.blocker_path.display(),
                    iterations = apply_result.iterations,
                    "Apply blocked handoff detected; keeping change blocked with preserved worktree context"
                );
            }

            // Increment apply count for this change
            self.increment_apply_count(&change.id);

            // Re-fetch change to get updated task counts after apply
            let (updated_change, is_complete) = self.refetch_change_after_apply(&change.id);

            if is_complete || apply_blocked_handoff.is_some() {
                let updated_change = updated_change.unwrap_or_else(|| change.clone());

                if let Some(ref handoff) = apply_blocked_handoff {
                    warn!(
                        change_id = %change.id,
                        blocker_path = %handoff.blocker_path.display(),
                        "Apply reported recoverable blocker; leaving change stalled for explicit unblock/resume"
                    );

                    Ok(ChangeProcessResult::Stalled {
                        error: format!(
                            "Apply blocked handoff recorded at {}",
                            handoff.blocker_path.display()
                        ),
                    })
                } else {
                    info!(
                        "Tasks complete for {}, running acceptance test...",
                        change.id
                    );

                    self.seed_active_run_acceptance_history(&change.id, agent);

                    // Update operation to "acceptance" before running acceptance test
                    Self::update_operation_tracker(&operation_tracker, "acceptance");

                    // Run acceptance test. A completed command with no canonical
                    // verdict is a protocol failure, so re-invoke the normal
                    // configured acceptance command with continuation context
                    // while the shared missing-verdict budget remains. That
                    // budget is active-run memory only and never touches the
                    // configured explicit-CONTINUE budget.
                    let mut protocol = MissingVerdictRetryDriver::default();
                    loop {
                        match acceptance_test_streaming(
                            &updated_change,
                            agent,
                            ai_runner,
                            &self.config,
                            output,
                            cancel_check,
                            protocol.take_protocol_retry(),
                        )
                        .await
                        {
                            Ok((
                                AcceptanceResult::MissingVerdict { findings },
                                _attempt_number,
                                _command,
                            )) => match protocol.observe_missing_verdict(&findings) {
                                MissingVerdictRetryStep::Retry { progress, .. } => {
                                    warn!("{} for {}", progress, change.id);
                                    output.on_warn(&progress);
                                    continue;
                                }
                                MissingVerdictRetryStep::Exhausted { error } => {
                                    error!("{} for {}", error, change.id);
                                    break Ok(ChangeProcessResult::AcceptanceCommandFailed {
                                        error,
                                    });
                                }
                            },
                            Ok((result, _attempt_number, _command)) => {
                                protocol.observe_canonical_verdict();
                                let repo_root = self.repo_root.clone();
                                break Ok(self.process_acceptance_result(
                                    &change.id,
                                    &repo_root,
                                    agent,
                                    result,
                                    is_single_change_stopped,
                                ));
                            }
                            Err(e) => {
                                error!("Acceptance error for {}: {}", change.id, e);
                                break Err(e);
                            }
                        }
                    }
                }
            } else {
                info!(
                    "Apply completed for {}, but tasks not yet complete",
                    change.id
                );
                Ok(ChangeProcessResult::ApplySuccessIncomplete)
            }
        } else {
            error!(
                "Apply loop did not complete for {} after {} iterations",
                change.id, apply_result.iterations
            );
            Ok(ChangeProcessResult::ApplyFailed {
                error: format!(
                    "Apply loop did not complete after {} iterations",
                    apply_result.iterations
                ),
            })
        }
    }

    /// Check stall detection after apply
    pub fn check_stall_after_apply(
        &mut self,
        change_id: &str,
        progress: &TaskProgress,
        is_empty_commit: Option<bool>,
    ) -> Option<String> {
        if let Some(is_empty) = is_empty_commit {
            if !is_progress_complete(progress)
                && self
                    .stall_detector
                    .register_commit(change_id, StallPhase::Apply, is_empty)
            {
                let count = self
                    .stall_detector
                    .current_count(change_id, StallPhase::Apply);
                let threshold = self.stall_detector.config().threshold;
                let message = format!(
                    "Stall detected for {} after {} empty WIP commits (apply)",
                    change_id, count
                );
                return Some(format!("{} (threshold {})", message, threshold));
            }
        }
        None
    }

    /// Re-fetch change to get updated task counts after apply.
    ///
    /// Returns the updated change and whether it's complete.
    fn refetch_change_after_apply(&self, change_id: &str) -> (Option<Change>, bool) {
        let updated_changes =
            openspec::list_changes_native_from(&self.repo_root).unwrap_or_default();
        let updated_change = updated_changes.iter().find(|c| c.id == change_id).cloned();
        let is_complete = updated_change.as_ref().is_some_and(|c| c.is_complete());
        (updated_change, is_complete)
    }

    /// Process acceptance test result and determine outcome.
    ///
    /// Handles Pass, Continue, Fail, CommandFailed, and Cancelled results,
    /// applying max_continues logic for Continue results.
    fn process_acceptance_result<F>(
        &mut self,
        change_id: &str,
        workspace_path: &std::path::Path,
        agent: &AgentRunner,
        acceptance_result: AcceptanceResult,
        is_single_change_stopped: F,
    ) -> ChangeProcessResult
    where
        F: Fn() -> bool,
    {
        match acceptance_result {
            AcceptanceResult::Pass => {
                // PASS is handed off to archive through active-run control flow
                // only; nothing durable records the verdict.
                self.acceptance_retry.remove(change_id);
                info!("Acceptance passed for {}, ready for archive", change_id);
                match task_parser::resolve_acceptance_follow_up_tasks_path_for_cleanup(
                    change_id,
                    workspace_path,
                ) {
                    Ok(Some(tasks_path)) => {
                        if let Err(err) = task_parser::clear_acceptance_follow_up(&tasks_path) {
                            return ChangeProcessResult::AcceptanceCommandFailed {
                                error: format!(
                                    "Acceptance passed but follow-up cleanup failed at {}: {}",
                                    tasks_path.display(),
                                    err
                                ),
                            };
                        }
                    }
                    Ok(None) => debug!("No acceptance follow-up to clear for {}", change_id),
                    Err(err) => {
                        return ChangeProcessResult::AcceptanceCommandFailed {
                            error: format!(
                                "Acceptance passed but follow-up path resolution failed: {}",
                                err
                            ),
                        };
                    }
                }
                ChangeProcessResult::AcceptancePassed
            }
            AcceptanceResult::Continue => {
                let continue_count = agent.count_consecutive_acceptance_continues(change_id);
                let max_continues = self.config.get_acceptance_max_continues();

                if continue_count >= max_continues {
                    let semantic_fingerprint = semantic_progress_fingerprint(workspace_path).ok();
                    self.set_acceptance_retry_context(
                        change_id,
                        AcceptanceRetryContext {
                            finding_identities: Vec::new(),
                            semantic_fingerprint,
                            cycle_count: continue_count,
                        },
                    );
                    warn!(
                        "Acceptance CONTINUE limit ({}) exceeded for {}, treating as FAIL",
                        max_continues, change_id
                    );
                    ChangeProcessResult::AcceptanceContinueExceeded
                } else {
                    info!(
                        "Acceptance requires continuation for {} (attempt {}/{}), retrying...",
                        change_id, continue_count, max_continues
                    );
                    ChangeProcessResult::AcceptanceContinue
                }
            }
            AcceptanceResult::Gated => {
                let retry = self
                    .acceptance_retry
                    .get(change_id)
                    .cloned()
                    .unwrap_or_default();
                if let Err(error) = write_acceptance_blocked_marker_with_context(
                    workspace_path,
                    change_id,
                    "acceptance_gated",
                    &["acceptance emitted gated compatibility token".to_string()],
                    &retry,
                    "no_semantic_progress",
                    &["recoverable acceptance gate".to_string()],
                    true,
                    "explicit retry",
                ) {
                    return ChangeProcessResult::AcceptanceCommandFailed {
                        error: format!("Failed to persist acceptance stalled evidence: {error}"),
                    };
                }
                warn!(
                    "Acceptance gated for {} - preserving change as stalled/resumable",
                    change_id
                );
                ChangeProcessResult::Stalled {
                    error: "Acceptance gated with recoverable blocker".to_string(),
                }
            }
            AcceptanceResult::Fail { findings } => {
                // Retry context comes from this run only. After a restart the
                // map is empty, so the next failure is treated as the first one
                // and acceptance is retried rather than skipped.
                let previous = self.acceptance_retry.get(change_id).cloned();
                let retry_count = previous.as_ref().map_or_else(
                    || {
                        agent
                            .get_last_acceptance_attempt(change_id)
                            .map(|attempt| attempt.attempt)
                            .unwrap_or(1)
                    },
                    |context| context.cycle_count.saturating_add(1),
                );
                let fingerprint = match semantic_progress_fingerprint(workspace_path) {
                    Ok(fingerprint) => fingerprint,
                    Err(error) => {
                        return ChangeProcessResult::AcceptanceCommandFailed {
                            error: format!("Failed to fingerprint acceptance progress: {error}"),
                        };
                    }
                };
                let normalized = normalize_findings(&findings);
                let identities = normalized
                    .iter()
                    .map(|finding| finding.identity.clone())
                    .collect::<Vec<_>>();
                let decision = decide_acceptance_retry(
                    previous.as_ref().map_or(
                        &[] as &[String],
                        AcceptanceRetryContext::previous_identities,
                    ),
                    previous
                        .as_ref()
                        .and_then(AcceptanceRetryContext::previous_fingerprint),
                    &normalized,
                    &fingerprint,
                    retry_count,
                );
                let retry = AcceptanceRetryContext {
                    finding_identities: identities.clone(),
                    semantic_fingerprint: Some(fingerprint),
                    cycle_count: retry_count,
                };
                self.set_acceptance_retry_context(change_id, retry.clone());
                if let AcceptanceRetryDecision::Stall {
                    reason,
                    external_blockers,
                } = decision
                {
                    if let Err(error) = write_acceptance_blocked_marker_with_context(
                        workspace_path,
                        change_id,
                        reason,
                        &identities,
                        &retry,
                        "no_semantic_progress",
                        &external_blockers,
                        true,
                        "explicit retry",
                    ) {
                        return ChangeProcessResult::AcceptanceCommandFailed {
                            error: format!(
                                "Failed to persist acceptance stalled evidence: {error}"
                            ),
                        };
                    }
                    return ChangeProcessResult::Stalled {
                        error: reason.to_string(),
                    };
                }
                let blocking_gate_context = findings
                    .first()
                    .cloned()
                    .unwrap_or_else(|| "no acceptance findings captured".to_string());
                warn!(
                    "Acceptance failed for {} ({} findings), blocking gate context: {}; will retry apply",
                    change_id,
                    findings.len(),
                    blocking_gate_context
                );
                let repository_findings = repository_findings(&findings);
                if !findings.is_empty() {
                    if let Ok(tasks_path) = task_parser::resolve_acceptance_follow_up_tasks_path(
                        change_id,
                        workspace_path,
                    ) {
                        if let Err(err) = task_parser::replace_acceptance_follow_up_from_latest_fail(
                            &tasks_path,
                            agent
                                .get_last_acceptance_attempt(change_id)
                                .map(|attempt| attempt.attempt)
                                .unwrap_or(1),
                            &findings,
                        ) {
                            warn!(
                                "Acceptance follow-up persistence degraded for {} at {}: {}",
                                change_id,
                                tasks_path.display(),
                                err
                            );
                        }
                    }
                }
                ChangeProcessResult::AcceptanceFailed {
                    findings: repository_findings,
                }
            }
            AcceptanceResult::CommandFailed {
                error,
                findings: _findings,
            } => {
                error!("Acceptance command failed for {}: {}", change_id, error);
                // Canonical owner note: runtime appends follow-up tasks for FAIL verdicts,
                // while command-level failures are surfaced without forcing local tasks.md updates.
                ChangeProcessResult::AcceptanceCommandFailed { error }
            }
            AcceptanceResult::MissingVerdict { findings } => {
                // A completed acceptance command with no canonical verdict is a
                // protocol failure, not an intentional CONTINUE. The acceptance
                // retry loop owns the dedicated protocol budget and only reaches
                // terminal routing after exhaustion, so this arm reports the
                // exhausted diagnostic with bounded output evidence.
                let error = missing_verdict_exhausted_error(
                    MAX_MISSING_VERDICT_RETRIES.saturating_add(1),
                    MAX_MISSING_VERDICT_RETRIES,
                    &findings,
                );
                error!("{} for {}", error, change_id);
                ChangeProcessResult::AcceptanceCommandFailed { error }
            }
            AcceptanceResult::PermissionStalled { blocker } => {
                let evidence = vec![blocker.summary()];
                let retry = self
                    .acceptance_retry
                    .get(change_id)
                    .cloned()
                    .unwrap_or_default();
                if let Err(error) = write_acceptance_blocked_marker_with_context(
                    workspace_path,
                    change_id,
                    "permission_stalled",
                    &evidence,
                    &retry,
                    "no_semantic_progress",
                    &evidence,
                    true,
                    &blocker.next_action,
                ) {
                    return ChangeProcessResult::AcceptanceCommandFailed {
                        error: format!("Failed to persist acceptance stalled evidence: {error}"),
                    };
                }
                warn!(
                    "Acceptance stalled for {} due to repeated unresolved permission/tool policy blocker: {}",
                    change_id, blocker.next_action
                );
                ChangeProcessResult::Stalled {
                    error: blocker.next_action,
                }
            }
            AcceptanceResult::Cancelled => {
                // Check if this is a single-change stop or global cancel
                if is_single_change_stopped() {
                    info!("Single change {} stopped during acceptance", change_id);
                    ChangeProcessResult::ChangeStopped
                } else {
                    info!("Acceptance cancelled for {} (global cancel)", change_id);
                    ChangeProcessResult::Cancelled
                }
            }
        }
    }

    /// Update operation tracker with the current operation name.
    ///
    /// This is a helper to centralize tracker updates for both apply and acceptance flows.
    fn update_operation_tracker(
        operation_tracker: &Option<std::sync::Arc<std::sync::RwLock<String>>>,
        operation: &str,
    ) {
        if let Some(ref tracker) = operation_tracker {
            *tracker.write().unwrap() = operation.to_string();
        }
    }
}

/// Result of processing a single change
#[derive(Debug, Clone)]
#[allow(dead_code)] // Some variants may not be used yet depending on mode
pub enum ChangeProcessResult {
    /// Change was successfully archived
    Archived,
    /// Change was stalled
    Stalled { error: String },
    /// Archive or apply failed
    Failed { error: String },
    /// Operation was cancelled (global stop)
    Cancelled,
    /// Single change was stopped (not a global cancel)
    ChangeStopped,
    /// Apply succeeded but tasks not yet complete
    ApplySuccessIncomplete,
    /// Apply failed
    ApplyFailed { error: String },
    /// Acceptance test passed
    AcceptancePassed,
    /// Acceptance test failed
    AcceptanceFailed { findings: Vec<String> },
    /// Acceptance test command failed
    AcceptanceCommandFailed { error: String },
    /// Acceptance test requires continuation
    AcceptanceContinue,
    /// Acceptance CONTINUE limit exceeded
    AcceptanceContinueExceeded,
    /// Acceptance gated and change was rejected
    Rejected { reason: String },
}

/// Helper function to check if progress is complete
fn is_progress_complete(progress: &TaskProgress) -> bool {
    progress.total > 0 && progress.completed >= progress.total
}

/// Event handler for serial apply loop that delegates to OutputHandler
struct SerialApplyEventHandler<'a, O: OutputHandler> {
    #[allow(dead_code)] // Kept for type safety but not used since output is handled via closure
    output: &'a O,
}

impl<'a, O: OutputHandler> SerialApplyEventHandler<'a, O> {
    fn new(output: &'a O) -> Self {
        Self { output }
    }
}

impl<'a, O: OutputHandler> common_apply::ApplyEventHandler for SerialApplyEventHandler<'a, O> {
    fn on_apply_started(&self, _change_id: &str, _command: &str) {
        // No-op for serial mode - output is handled via output_handler closure
    }

    fn on_progress_updated(&self, _change_id: &str, _completed: u32, _total: u32) {
        // No-op for serial mode - progress is logged in execute_apply_loop
    }

    fn on_hook_started(&self, _change_id: &str, _hook_type: &str) {
        // No-op for serial mode - hooks log themselves
    }

    fn on_hook_completed(&self, _change_id: &str, _hook_type: &str) {
        // No-op for serial mode - hooks log themselves
    }

    fn on_hook_failed(&self, _change_id: &str, _hook_type: &str, _error: &str) {
        // No-op for serial mode - hooks log themselves
    }

    fn on_apply_output(&self, _change_id: &str, _line: &OutputLine, _iteration: u32) {
        // No-op: Output is already handled by the output_handler closure passed to execute_apply_loop
        // (lines 398-403). Having both would cause duplicate output.
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::command_queue::CommandQueueConfig;
    use crate::config::defaults::default_retry_patterns;
    use crate::config::OrchestratorConfig;
    use crate::hooks::{HookRunner, HooksConfig};
    use crate::openspec::ProposalMetadata;
    use crate::orchestration::output::NullOutputHandler;
    use std::sync::Arc;
    use tempfile::TempDir;
    use tokio::sync::Mutex;

    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_select_next_change_prioritizes_progress() {
        let temp_dir = TempDir::new().unwrap();
        let service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());

        let changes = vec![
            create_test_change("a", 1, 10), // 10% progress
            create_test_change("b", 5, 10), // 50% progress
            create_test_change("c", 8, 10), // 80% progress (highest)
        ];

        let next = service.select_next_change(&changes);
        assert_eq!(next.map(|c| c.id.as_str()), Some("c"));
    }

    #[test]
    fn test_select_next_change_excludes_stalled() {
        let temp_dir = TempDir::new().unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());

        service.mark_stalled("b", "test");

        let changes = vec![
            create_test_change("a", 1, 10),
            create_test_change("b", 8, 10), // Highest progress but stalled
            create_test_change("c", 5, 10),
        ];

        let next = service.select_next_change(&changes);
        assert_eq!(next.map(|c| c.id.as_str()), Some("c")); // Should pick 'c', not 'b'
    }

    #[test]
    fn test_select_next_change_prioritizes_complete_for_archive() {
        let temp_dir = TempDir::new().unwrap();
        let service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());

        let changes = vec![
            create_test_change("a", 5, 10),  // 50% progress, incomplete
            create_test_change("b", 10, 10), // 100% complete
        ];

        let next = service.select_next_change(&changes);
        // Should select the incomplete one first (archive happens in a separate phase in practice,
        // but select_next_change returns the first match which would be 'b' if it's complete)
        // Actually, reading the implementation, it prioritizes incomplete first, so should be 'a'
        assert_eq!(next.map(|c| c.id.as_str()), Some("a"));
    }

    fn serial_test_ai_runner() -> AiCommandRunner {
        AiCommandRunner::new(
            CommandQueueConfig {
                stagger_delay_ms: 0,
                max_retries: 0,
                retry_delay_ms: 0,
                retry_error_patterns: default_retry_patterns(),
                retry_if_duration_under_secs: 0,
                inactivity_timeout_secs: 0,
                inactivity_kill_grace_secs: 0,
                inactivity_timeout_max_retries: 0,
                strict_process_cleanup: true,
            },
            Arc::new(Mutex::new(None)),
        )
    }

    fn init_serial_repo(root: &std::path::Path, change_id: &str) -> std::path::PathBuf {
        for args in [
            vec!["init", "-b", "main"],
            vec!["config", "user.email", "test@example.com"],
            vec!["config", "user.name", "Test User"],
        ] {
            std::process::Command::new("git")
                .args(args)
                .current_dir(root)
                .output()
                .unwrap();
        }
        let change_dir = root.join("openspec/changes").join(change_id);
        std::fs::create_dir_all(&change_dir).unwrap();
        std::fs::write(change_dir.join("proposal.md"), "# serial restart\n").unwrap();
        std::fs::write(change_dir.join("tasks.md"), "- [ ] pending\n").unwrap();
        std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(root)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "base"])
            .current_dir(root)
            .output()
            .unwrap();
        change_dir
    }

    fn serial_failing_acceptance_config(change_id: &str) -> OrchestratorConfig {
        OrchestratorConfig {
            // Apply checks off every open box, including acceptance follow-up
            // entries, so repeated cycles converge instead of exhausting the
            // apply iteration budget.
            apply_command: Some(format!(
                "sh -c \"sed 's/- \\[ \\]/- [x]/g' openspec/changes/{change_id}/tasks.md \
                 > openspec/changes/{change_id}/tasks.next \
                 && mv openspec/changes/{change_id}/tasks.next openspec/changes/{change_id}/tasks.md\""
            )),
            acceptance_command: Some(
                "sh -c 'echo ACCEPTANCE: FAIL; echo FINDINGS:; echo - repeated serial finding'"
                    .to_string(),
            ),
            ..Default::default()
        }
    }

    #[tokio::test]
    async fn serial_active_run_accumulates_acceptance_retry_context_without_a_checkpoint_file() {
        let temp_dir = TempDir::new().unwrap();
        let change_id = "serial-restart";
        init_serial_repo(temp_dir.path(), change_id);

        let config = serial_failing_acceptance_config(change_id);
        let mut service = SerialRunService::new(temp_dir.path().to_path_buf(), config.clone());
        let mut agent = AgentRunner::new(config.clone());
        let ai_runner = serial_test_ai_runner();

        // First failure of this run: retry context does not exist yet, so the
        // change returns to apply instead of stalling.
        assert!(service.acceptance_retry_context(change_id).is_none());
        let result = service
            .process_change(
                &create_test_change(change_id, 0, 1),
                &mut agent,
                &ai_runner,
                &HookRunner::new(HooksConfig::default(), temp_dir.path()),
                &NullOutputHandler::new(),
                1,
                1,
                || false,
                || false,
                None,
            )
            .await
            .unwrap();

        assert!(matches!(
            result,
            ChangeProcessResult::AcceptanceFailed { .. }
        ));
        let context = service.acceptance_retry_context(change_id).unwrap();
        assert_eq!(context.cycle_count, 1);
        assert_eq!(
            context.finding_identities,
            ["repository|repeated serial finding|implementation"]
        );
        assert!(!temp_dir.path().join(".cflx/acceptance-state.json").exists());

        // Second identical failure in the same run reuses the in-memory
        // baseline and stalls with a tracked marker.
        let result = service
            .process_change(
                &create_test_change(change_id, 0, 1),
                &mut agent,
                &ai_runner,
                &HookRunner::new(HooksConfig::default(), temp_dir.path()),
                &NullOutputHandler::new(),
                1,
                1,
                || false,
                || false,
                None,
            )
            .await
            .unwrap();

        assert!(matches!(
            result,
            ChangeProcessResult::Stalled { ref error }
            if error == "repeated_acceptance_findings"
        ));
        let marker =
            crate::parallel::acceptance_state::parse_blocked_marker(temp_dir.path(), change_id)
                .unwrap()
                .unwrap();
        assert_eq!(marker.reason, "repeated_acceptance_findings");
        assert_eq!(marker.retry_count, 2);
        assert!(!temp_dir.path().join(".cflx/acceptance-state.json").exists());
    }

    #[tokio::test]
    async fn serial_restart_reruns_acceptance_without_reconstructing_retry_context() {
        let temp_dir = TempDir::new().unwrap();
        let change_id = "serial-restart";
        init_serial_repo(temp_dir.path(), change_id);

        // A leftover checkpoint from an older Conflux version claims a nearly
        // exhausted retry budget. It must be ignored entirely.
        let stale_checkpoint = temp_dir.path().join(".cflx/acceptance-state.json");
        std::fs::create_dir_all(stale_checkpoint.parent().unwrap()).unwrap();
        std::fs::write(
            &stale_checkpoint,
            "{\"state\":\"failed\",\"revision\":\"old\",\"updated_at\":\"now\",             \"workspace_path\":\".\",\"change_id\":\"serial-restart\",             \"previous_finding_identities\":[\"repository|repeated serial finding|implementation\"],             \"semantic_fingerprint\":\"stale\",\"cycle_count\":9}",
        )
        .unwrap();

        let config = serial_failing_acceptance_config(change_id);
        let mut service = SerialRunService::new(temp_dir.path().to_path_buf(), config.clone());
        let mut agent = AgentRunner::new(config.clone());
        let ai_runner = serial_test_ai_runner();

        let result = service
            .process_change(
                &create_test_change(change_id, 0, 1),
                &mut agent,
                &ai_runner,
                &HookRunner::new(HooksConfig::default(), temp_dir.path()),
                &NullOutputHandler::new(),
                1,
                1,
                || false,
                || false,
                None,
            )
            .await
            .unwrap();

        // Acceptance actually ran and produced a first-failure verdict rather
        // than resuming the stale cycle count or inferring a prior PASS.
        assert!(matches!(
            result,
            ChangeProcessResult::AcceptanceFailed { .. }
        ));
        assert_eq!(
            service
                .acceptance_retry_context(change_id)
                .unwrap()
                .cycle_count,
            1
        );
        assert!(crate::parallel::acceptance_state::parse_blocked_marker(
            temp_dir.path(),
            change_id
        )
        .unwrap()
        .is_none());
    }

    /// Configure a stateful fake acceptance command that withholds a canonical
    /// verdict for its first `missing_attempts` invocations, then emits
    /// `ACCEPTANCE: PASS`. It is the ordinary configured acceptance command on
    /// every invocation — no harness session, resume flag, or job identifier.
    fn serial_missing_verdict_config(
        change_id: &str,
        state_dir: &std::path::Path,
        missing_attempts: u32,
    ) -> OrchestratorConfig {
        let counter = state_dir.join("attempts").display().to_string();
        let prompts = state_dir.join("prompts").display().to_string();
        std::fs::create_dir_all(state_dir.join("prompts")).unwrap();
        OrchestratorConfig {
            acceptance_command: Some(format!(
                "sh -c 'n=$(cat \"{counter}\" 2>/dev/null || echo 0); n=$((n+1)); \
                 echo $n > \"{counter}\"; printf \"%s\" \"$0\" > \"{prompts}/attempt-$n.txt\"; \
                 if [ $n -gt {missing_attempts} ]; then echo \"ACCEPTANCE: PASS\"; \
                 else echo \"Monitoring verification, waiting for the owned job to finish\"; fi' \
                 {{prompt}}"
            )),
            ..serial_failing_acceptance_config(change_id)
        }
    }

    fn serial_acceptance_invocations(state_dir: &std::path::Path) -> u32 {
        std::fs::read_to_string(state_dir.join("attempts"))
            .map(|text| text.trim().parse().unwrap_or(0))
            .unwrap_or(0)
    }

    fn serial_acceptance_prompt(state_dir: &std::path::Path, attempt: u32) -> String {
        std::fs::read_to_string(
            state_dir
                .join("prompts")
                .join(format!("attempt-{attempt}.txt")),
        )
        .unwrap_or_default()
    }

    async fn run_serial_missing_verdict_change(
        temp_dir: &std::path::Path,
        state_dir: &std::path::Path,
        change_id: &str,
        missing_attempts: u32,
    ) -> ChangeProcessResult {
        let config = serial_missing_verdict_config(change_id, state_dir, missing_attempts);
        let mut service = SerialRunService::new(temp_dir.to_path_buf(), config.clone());
        let mut agent = AgentRunner::new(config.clone());
        let ai_runner = serial_test_ai_runner();

        service
            .process_change(
                &create_test_change(change_id, 0, 1),
                &mut agent,
                &ai_runner,
                &HookRunner::new(HooksConfig::default(), temp_dir),
                &NullOutputHandler::new(),
                1,
                1,
                || false,
                || false,
                None,
            )
            .await
            .unwrap()
    }

    /// Serial parity with parallel: a status-only acceptance exit re-runs the
    /// normal configured acceptance command with continuation context, and a
    /// later canonical PASS keeps its existing routing.
    #[tokio::test]
    async fn serial_missing_verdict_retries_then_passes() {
        let temp_dir = TempDir::new().unwrap();
        let state_dir = TempDir::new().unwrap();
        let change_id = "serial-missing-verdict-pass";
        init_serial_repo(temp_dir.path(), change_id);

        let result =
            run_serial_missing_verdict_change(temp_dir.path(), state_dir.path(), change_id, 2)
                .await;

        assert!(
            matches!(result, ChangeProcessResult::AcceptancePassed),
            "a canonical PASS after protocol retries must route as AcceptancePassed, got {result:?}"
        );
        assert_eq!(
            serial_acceptance_invocations(state_dir.path()),
            3,
            "the initial attempt plus two protocol retries must run the acceptance command"
        );

        assert!(
            !serial_acceptance_prompt(state_dir.path(), 1).contains("<acceptance_protocol_retry>"),
            "the initial attempt must not receive corrective retry context"
        );
        for attempt in [2, 3] {
            let prompt = serial_acceptance_prompt(state_dir.path(), attempt);
            assert!(
                prompt.contains("<acceptance_protocol_retry>"),
                "retry {attempt} must carry the continuation context"
            );
            assert!(prompt.contains("emit exactly one canonical verdict"));
            assert!(
                prompt.contains("Monitoring verification"),
                "retry {attempt} must carry bounded prior acceptance output"
            );
            let lower = prompt.to_ascii_lowercase();
            for forbidden in ["session_id", "--resume", "job_id"] {
                assert!(
                    !lower.contains(forbidden),
                    "continuation must stay harness neutral, found `{forbidden}`"
                );
            }
        }

        assert!(
            !temp_dir.path().join("ACCEPTANCE_REPORT.json").exists(),
            "protocol retries must not create an acceptance report artifact"
        );
    }

    /// Three consecutive missing verdicts exhaust the dedicated budget and
    /// become the terminal protocol failure.
    #[tokio::test]
    async fn serial_missing_verdict_exhaustion_is_terminal() {
        let temp_dir = TempDir::new().unwrap();
        let state_dir = TempDir::new().unwrap();
        let change_id = "serial-missing-verdict-exhausted";
        init_serial_repo(temp_dir.path(), change_id);

        let result = run_serial_missing_verdict_change(
            temp_dir.path(),
            state_dir.path(),
            change_id,
            u32::MAX,
        )
        .await;

        match result {
            ChangeProcessResult::AcceptanceCommandFailed { error } => {
                assert!(error.contains("missing-verdict protocol failure"));
                assert!(error.contains("Exhausted 3 consecutive attempts after 2 protocol retries"));
                assert!(
                    error.contains("Monitoring verification"),
                    "terminal diagnostic must retain bounded evidence, got: {error}"
                );
            }
            other => panic!("exhausted protocol retries must be terminal, got {other:?}"),
        }
        assert_eq!(
            serial_acceptance_invocations(state_dir.path()),
            3,
            "no fourth protocol retry may start"
        );
        assert!(!temp_dir.path().join("ACCEPTANCE_REPORT.json").exists());
    }

    /// Constitutional restart behavior: the protocol counter is active-run
    /// memory, so a fresh run re-runs acceptance with a full budget and cannot
    /// infer PASS from the previous run's narrative output.
    #[tokio::test]
    async fn serial_restart_reruns_acceptance_after_missing_verdict_exhaustion() {
        let temp_dir = TempDir::new().unwrap();
        let change_id = "serial-missing-verdict-restart";
        init_serial_repo(temp_dir.path(), change_id);

        let first_state = TempDir::new().unwrap();
        let first = run_serial_missing_verdict_change(
            temp_dir.path(),
            first_state.path(),
            change_id,
            u32::MAX,
        )
        .await;
        assert!(matches!(
            first,
            ChangeProcessResult::AcceptanceCommandFailed { .. }
        ));
        assert_eq!(serial_acceptance_invocations(first_state.path()), 3);

        // A fresh service/agent owns no prior runtime state.
        let second_state = TempDir::new().unwrap();
        let second = run_serial_missing_verdict_change(
            temp_dir.path(),
            second_state.path(),
            change_id,
            u32::MAX,
        )
        .await;

        assert!(
            matches!(second, ChangeProcessResult::AcceptanceCommandFailed { .. }),
            "an unarchived change must not be treated as accepted from prior output, got {second:?}"
        );
        assert_eq!(
            serial_acceptance_invocations(second_state.path()),
            3,
            "a restarted run must re-run acceptance with a full, fresh protocol budget"
        );
        assert!(
            !temp_dir.path().join(".cflx/acceptance-state.json").exists(),
            "protocol retries must not create a durable acceptance checkpoint"
        );
    }

    #[test]
    fn serial_acceptance_pass_hands_off_in_memory_without_writing_a_checkpoint() {
        let temp_dir = TempDir::new().unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());
        let agent = AgentRunner::new(OrchestratorConfig::default());
        service.set_acceptance_retry_context(
            "test-change",
            AcceptanceRetryContext {
                finding_identities: vec!["repository|old finding|implementation".to_string()],
                semantic_fingerprint: Some("baseline".to_string()),
                cycle_count: 1,
            },
        );

        let result = service.process_acceptance_result(
            "test-change",
            temp_dir.path(),
            &agent,
            AcceptanceResult::Pass,
            || false,
        );

        assert!(matches!(result, ChangeProcessResult::AcceptancePassed));
        assert!(service.acceptance_retry_context("test-change").is_none());
        assert!(!temp_dir.path().join(".cflx/acceptance-state.json").exists());
    }

    #[test]
    fn serial_repeated_findings_without_progress_stall_before_another_apply() {
        use crate::orchestration::acceptance::normalize_findings;

        let temp_dir = TempDir::new().unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());
        let agent = AgentRunner::new(OrchestratorConfig::default());
        let findings = vec!["src/lib.rs:10 missing regression coverage".to_string()];
        let fingerprint = semantic_progress_fingerprint(temp_dir.path()).unwrap();
        service.set_acceptance_retry_context(
            "test-change",
            AcceptanceRetryContext {
                finding_identities: normalize_findings(&findings)
                    .into_iter()
                    .map(|finding| finding.identity)
                    .collect(),
                semantic_fingerprint: Some(fingerprint),
                cycle_count: 1,
            },
        );

        let result = service.process_acceptance_result(
            "test-change",
            temp_dir.path(),
            &agent,
            AcceptanceResult::Fail { findings },
            || false,
        );

        assert!(matches!(
            result,
            ChangeProcessResult::Stalled { ref error }
            if error == "repeated_acceptance_findings"
        ));
        assert_eq!(
            crate::parallel::acceptance_state::parse_blocked_marker(temp_dir.path(), "test-change")
                .unwrap()
                .unwrap()
                .reason,
            "repeated_acceptance_findings"
        );
    }

    #[test]
    fn serial_external_only_failure_stalls_without_apply_findings() {
        let temp_dir = TempDir::new().unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());
        let agent = AgentRunner::new(OrchestratorConfig::default());

        let result = service.process_acceptance_result(
            "test-change",
            temp_dir.path(),
            &agent,
            AcceptanceResult::Fail {
                findings: vec!["external non-mockable prerequisite unavailable".to_string()],
            },
            || false,
        );

        assert!(matches!(
            result,
            ChangeProcessResult::Stalled { ref error } if error == "external_acceptance_blocker"
        ));
        assert!(crate::parallel::acceptance_state::parse_blocked_marker(
            temp_dir.path(),
            "test-change"
        )
        .unwrap()
        .is_some());
    }

    #[test]
    fn serial_missing_verdict_routes_as_protocol_failure_not_continue() {
        // A completed acceptance command without a canonical verdict must be
        // surfaced as an explicit protocol/command failure with actionable
        // evidence — never as the intentional-CONTINUE retry path.
        let temp_dir = TempDir::new().unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());
        let agent = AgentRunner::new(OrchestratorConfig::default());

        let result = service.process_acceptance_result(
            "test-change",
            temp_dir.path(),
            &agent,
            AcceptanceResult::MissingVerdict {
                findings: vec!["Monitoring verification, will report when complete".to_string()],
            },
            || false,
        );

        match result {
            ChangeProcessResult::AcceptanceCommandFailed { error } => {
                assert!(
                    error.contains("missing-verdict protocol failure"),
                    "diagnostic must identify the missing verdict, got: {error}"
                );
                assert!(
                    error.contains("Exhausted 3 consecutive attempts after 2 protocol retries"),
                    "terminal routing must report the exhausted attempts, got: {error}"
                );
                assert!(
                    error.contains("Monitoring verification, will report when complete"),
                    "diagnostic must retain bounded output evidence, got: {error}"
                );
            }
            other => panic!(
                "missing verdict must route as acceptance command failure, got {:?}",
                other
            ),
        }
    }

    #[test]
    fn serial_explicit_continue_still_uses_continue_retry_path() {
        // Control: an explicit canonical CONTINUE keeps its intentional
        // continuation routing and configured retry policy.
        let temp_dir = TempDir::new().unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());
        let agent = AgentRunner::new(OrchestratorConfig::default());

        let result = service.process_acceptance_result(
            "test-change",
            temp_dir.path(),
            &agent,
            AcceptanceResult::Continue,
            || false,
        );

        assert!(
            matches!(result, ChangeProcessResult::AcceptanceContinue),
            "explicit CONTINUE below the retry limit must retry acceptance, got {:?}",
            result
        );
    }

    #[test]
    fn serial_cycle_limit_stalls_with_workspace_marker() {
        use crate::orchestration::acceptance::{normalize_findings, MAX_ACCEPTANCE_RETRY_CYCLES};

        let temp_dir = TempDir::new().unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());
        let agent = AgentRunner::new(OrchestratorConfig::default());
        let findings = vec!["new finding at ceiling".to_string()];
        service.set_acceptance_retry_context(
            "test-change",
            AcceptanceRetryContext {
                finding_identities: normalize_findings(&["older finding".to_string()])
                    .into_iter()
                    .map(|finding| finding.identity)
                    .collect(),
                semantic_fingerprint: Some("previous-progress".to_string()),
                cycle_count: MAX_ACCEPTANCE_RETRY_CYCLES - 1,
            },
        );

        let result = service.process_acceptance_result(
            "test-change",
            temp_dir.path(),
            &agent,
            AcceptanceResult::Fail { findings },
            || false,
        );

        assert!(matches!(
            result,
            ChangeProcessResult::Stalled { ref error }
            if error == "acceptance_cycle_limit_exhausted"
        ));
        let marker =
            crate::parallel::acceptance_state::parse_blocked_marker(temp_dir.path(), "test-change")
                .unwrap()
                .unwrap();
        assert_eq!(marker.reason, "acceptance_cycle_limit_exhausted");
        assert_eq!(marker.retry_count, MAX_ACCEPTANCE_RETRY_CYCLES);
    }

    #[test]
    fn test_process_acceptance_result_archive_readiness_fail_blocks_archive_progression() {
        use crate::agent::AgentRunner;
        use crate::orchestration::AcceptanceResult;

        let temp_dir = TempDir::new().unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());

        let agent = AgentRunner::new(OrchestratorConfig::default());
        let findings = vec![
            "blocking gate: cargo clippy -- -D warnings".to_string(),
            "src/orchestration/archive.rs:459".to_string(),
        ];
        let change_dir = temp_dir
            .path()
            .join("openspec")
            .join("changes")
            .join("test-change");
        std::fs::create_dir_all(&change_dir).unwrap();
        std::fs::write(
            change_dir.join("tasks.md"),
            "## Implementation Tasks\n- [x] done\n",
        )
        .unwrap();

        let result = service.process_acceptance_result(
            "test-change",
            temp_dir.path(),
            &agent,
            AcceptanceResult::Fail {
                findings: findings.clone(),
            },
            || false,
        );

        assert!(matches!(
            result,
            ChangeProcessResult::AcceptanceFailed { findings: returned }
            if returned == findings
        ));
    }

    #[test]
    fn serial_latest_fail_reconciles_completed_findings_with_parallel_parity() {
        let temp_dir = TempDir::new().unwrap();
        let change_id = "test-change";
        let change_dir = temp_dir
            .path()
            .join("openspec")
            .join("changes")
            .join(change_id);
        std::fs::create_dir_all(&change_dir).unwrap();
        let tasks_path = change_dir.join("tasks.md");
        std::fs::write(
            &tasks_path,
            "## Implementation Tasks\n- [x] done\n\n## Current Acceptance Follow-up\n- attempt: 1\n- [x] [SAME_FINDING] fixed wording\n- [x] [RETIRED_FINDING] fixed and not reported again\n- [x] [DIFFERENT_FINDING] unrelated completed defect\n",
        )
        .unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());
        let agent = AgentRunner::new(OrchestratorConfig::default());
        let findings = vec![
            "[SAME_FINDING] defect still present with new evidence".to_string(),
            "[NEW_FINDING] distinct newly reported defect".to_string(),
        ];

        let result = service.process_acceptance_result(
            change_id,
            temp_dir.path(),
            &agent,
            AcceptanceResult::Fail {
                findings: findings.clone(),
            },
            || false,
        );

        assert!(matches!(
            result,
            ChangeProcessResult::AcceptanceFailed { findings: returned }
            if returned == findings
        ));
        let content = std::fs::read_to_string(&tasks_path).unwrap();
        assert!(content.contains("- [ ] [SAME_FINDING] defect still present with new evidence"));
        assert!(content.contains("- [ ] [NEW_FINDING] distinct newly reported defect"));
        assert!(!content.contains("RETIRED_FINDING"));
        assert!(!content.contains("DIFFERENT_FINDING"));
        assert_eq!(
            crate::task_parser::parse_file(&tasks_path, None).unwrap(),
            TaskProgress::with_counts(1, 3)
        );
    }

    #[test]
    fn acceptance_fail_uses_recorded_attempt_number_for_follow_up() {
        use crate::agent::AgentRunner;
        use crate::history::AcceptanceAttempt;
        use crate::orchestration::AcceptanceResult;
        use std::time::Duration;

        let temp_dir = TempDir::new().unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());
        let mut agent = AgentRunner::new(OrchestratorConfig::default());
        agent.record_acceptance_attempt(
            "test-change",
            AcceptanceAttempt {
                attempt: 1,
                passed: false,
                duration: Duration::from_secs(1),
                findings: Some(vec!["first".to_string()]),
                exit_code: Some(0),
                stdout_tail: None,
                stderr_tail: None,
                commit_hash: None,
            },
        );
        agent.record_acceptance_attempt(
            "test-change",
            AcceptanceAttempt {
                attempt: 2,
                passed: false,
                duration: Duration::from_secs(1),
                findings: Some(vec!["second".to_string()]),
                exit_code: Some(0),
                stdout_tail: None,
                stderr_tail: None,
                commit_hash: None,
            },
        );
        let change_dir = temp_dir
            .path()
            .join("openspec")
            .join("changes")
            .join("test-change");
        std::fs::create_dir_all(&change_dir).unwrap();
        std::fs::write(change_dir.join("tasks.md"), "- [x] done\n").unwrap();

        service.process_acceptance_result(
            "test-change",
            temp_dir.path(),
            &agent,
            AcceptanceResult::Fail {
                findings: vec!["canonical second".to_string()],
            },
            || false,
        );

        let content = std::fs::read_to_string(change_dir.join("tasks.md")).unwrap();
        assert!(content.contains("## Current Acceptance Follow-up"));
        assert!(content.contains("- attempt: 2"));
        assert_eq!(
            content.matches("## Current Acceptance Follow-up").count(),
            1
        );
    }

    #[test]
    fn test_process_acceptance_result_fail_uses_archive_tasks_fallback_when_active_missing() {
        use crate::agent::AgentRunner;
        use crate::orchestration::AcceptanceResult;

        let temp_dir = TempDir::new().unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());
        let agent = AgentRunner::new(OrchestratorConfig::default());

        let archive_dir = temp_dir
            .path()
            .join("openspec")
            .join("changes")
            .join("archive")
            .join("test-change");
        std::fs::create_dir_all(&archive_dir).unwrap();
        std::fs::write(
            archive_dir.join("tasks.md"),
            "## Implementation Tasks\n- [x] done\n",
        )
        .unwrap();

        let findings = vec!["archive fallback finding".to_string()];
        let result = service.process_acceptance_result(
            "test-change",
            temp_dir.path(),
            &agent,
            AcceptanceResult::Fail {
                findings: findings.clone(),
            },
            || false,
        );

        assert!(matches!(
            result,
            ChangeProcessResult::AcceptanceFailed { findings: returned }
            if returned == findings
        ));

        let content = std::fs::read_to_string(archive_dir.join("tasks.md")).unwrap();
        assert!(content.contains("## Current Acceptance Follow-up"));
        assert!(content.contains("- attempt: 1"));
        assert!(content.contains("- [ ] archive fallback finding"));
    }

    #[test]
    fn test_process_acceptance_result_fail_degrades_when_no_tasks_path_available() {
        use crate::agent::AgentRunner;
        use crate::orchestration::AcceptanceResult;

        let temp_dir = TempDir::new().unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());
        let agent = AgentRunner::new(OrchestratorConfig::default());
        let findings = vec!["missing tasks path finding".to_string()];

        let result = service.process_acceptance_result(
            "test-change",
            temp_dir.path(),
            &agent,
            AcceptanceResult::Fail {
                findings: findings.clone(),
            },
            || false,
        );

        assert!(matches!(
            result,
            ChangeProcessResult::AcceptanceFailed { findings: returned }
            if returned == findings
        ));
    }

    #[test]
    fn acceptance_pass_clears_runtime_follow_up() {
        use crate::agent::AgentRunner;
        use crate::orchestration::AcceptanceResult;

        let temp_dir = TempDir::new().unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());
        let agent = AgentRunner::new(OrchestratorConfig::default());
        let change_dir = temp_dir
            .path()
            .join("openspec")
            .join("changes")
            .join("test-change");
        std::fs::create_dir_all(&change_dir).unwrap();
        std::fs::write(
            change_dir.join("tasks.md"),
            "## Implementation Tasks\n- [x] done\n\n## Acceptance #2 Failure Follow-up\n- [x] fixed\n",
        )
        .unwrap();

        let result = service.process_acceptance_result(
            "test-change",
            temp_dir.path(),
            &agent,
            AcceptanceResult::Pass,
            || false,
        );

        assert!(matches!(result, ChangeProcessResult::AcceptancePassed));
        let content = std::fs::read_to_string(change_dir.join("tasks.md")).unwrap();
        assert!(!content.contains("Failure Follow-up"));
        assert!(content.contains("## Implementation Tasks\n- [x] done"));
    }

    #[test]
    fn test_process_acceptance_result_archive_readiness_pass_allows_archive_progression() {
        use crate::agent::AgentRunner;
        use crate::orchestration::AcceptanceResult;

        let temp_dir = TempDir::new().unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());

        let agent = AgentRunner::new(OrchestratorConfig::default());

        let result = service.process_acceptance_result(
            "test-change",
            temp_dir.path(),
            &agent,
            AcceptanceResult::Pass,
            || false,
        );

        assert!(matches!(result, ChangeProcessResult::AcceptancePassed));
    }

    #[test]
    fn test_process_acceptance_result_gated_returns_stalled_result() {
        use crate::agent::AgentRunner;
        use crate::orchestration::AcceptanceResult;

        let temp_dir = TempDir::new().unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());

        let agent = AgentRunner::new(OrchestratorConfig::default());

        let result = service.process_acceptance_result(
            "test-change",
            temp_dir.path(),
            &agent,
            AcceptanceResult::Gated,
            || false, // Not a single-change stop
        );

        assert!(matches!(
            result,
            ChangeProcessResult::Stalled { ref error }
            if error == "Acceptance gated with recoverable blocker"
        ));
        let marker =
            crate::parallel::acceptance_state::parse_blocked_marker(temp_dir.path(), "test-change")
                .unwrap()
                .unwrap();
        assert_eq!(marker.reason, "acceptance_gated");
        assert_eq!(marker.semantic_progress, "no_semantic_progress");
        assert_eq!(marker.external_blockers, ["recoverable acceptance gate"]);
    }

    #[tokio::test]
    async fn serial_process_change_stops_at_workspace_marker_before_archive() {
        use crate::parallel::acceptance_state::write_acceptance_blocked_marker;

        let temp_dir = TempDir::new().unwrap();
        write_acceptance_blocked_marker(
            temp_dir.path(),
            "complete-change",
            "stalled",
            &[],
            true,
            "explicit retry",
        )
        .unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());
        let mut agent = AgentRunner::new(OrchestratorConfig::default());
        let ai_runner = AiCommandRunner::new(
            CommandQueueConfig {
                stagger_delay_ms: 0,
                max_retries: 0,
                retry_delay_ms: 0,
                retry_error_patterns: default_retry_patterns(),
                retry_if_duration_under_secs: 0,
                inactivity_timeout_secs: 0,
                inactivity_kill_grace_secs: 0,
                inactivity_timeout_max_retries: 0,
                strict_process_cleanup: true,
            },
            Arc::new(Mutex::new(None)),
        );
        let result = service
            .process_change(
                &create_test_change("complete-change", 1, 1),
                &mut agent,
                &ai_runner,
                &HookRunner::new(HooksConfig::default(), temp_dir.path()),
                &NullOutputHandler::new(),
                1,
                1,
                || false,
                || false,
                None,
            )
            .await
            .unwrap();

        assert!(matches!(result, ChangeProcessResult::Stalled { .. }));
        assert!(service.is_stalled("complete-change"));
        assert!(crate::parallel::acceptance_state::parse_blocked_marker(
            temp_dir.path(),
            "complete-change"
        )
        .unwrap()
        .is_some());
    }

    #[test]
    fn serial_preflight_suppresses_apply_and_archive_for_any_marker() {
        use crate::parallel::acceptance_state::write_acceptance_blocked_marker;

        let temp_dir = TempDir::new().unwrap();
        write_acceptance_blocked_marker(
            temp_dir.path(),
            "complete-change",
            "stalled",
            &[],
            true,
            "explicit retry",
        )
        .unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());

        let result = service.preflight_blocked_marker("complete-change").unwrap();

        assert!(matches!(result, Some(ChangeProcessResult::Stalled { .. })));
        assert!(service.is_stalled("complete-change"));
    }

    #[test]
    fn malformed_marker_stops_serial_preflight_and_is_preserved() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir
            .path()
            .join("openspec/changes/blocked/APPLY_BLOCKED/marker.md");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, "{ malformed").unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());

        assert!(service.preflight_blocked_marker("blocked").is_err());
        assert!(path.exists());
    }

    #[test]
    fn explicit_serial_retry_consumes_only_resumable_acceptance_marker() {
        use crate::parallel::acceptance_state::write_acceptance_blocked_marker;

        let temp_dir = TempDir::new().unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());
        write_acceptance_blocked_marker(
            temp_dir.path(),
            "acceptance",
            "stalled",
            &[],
            true,
            "explicit retry",
        )
        .unwrap();
        assert!(service
            .consume_explicit_acceptance_retry("acceptance")
            .unwrap());

        let apply_marker = temp_dir
            .path()
            .join("openspec/changes/apply/APPLY_BLOCKED/marker.md");
        std::fs::create_dir_all(apply_marker.parent().unwrap()).unwrap();
        std::fs::write(&apply_marker, "origin: apply\nreason: blocked\n").unwrap();
        assert!(!service.consume_explicit_acceptance_retry("apply").unwrap());
        assert!(apply_marker.exists());
    }

    #[test]
    fn test_mark_stalled_prevents_reselection() {
        let temp_dir = TempDir::new().unwrap();
        let mut service =
            SerialRunService::new(temp_dir.path().to_path_buf(), OrchestratorConfig::default());

        let changes = vec![
            create_test_change("a", 5, 10),
            create_test_change("b", 8, 10), // Highest progress
        ];

        // Initially, highest progress change should be selected
        let next = service.select_next_change(&changes);
        assert_eq!(next.map(|c| c.id.as_str()), Some("b"));

        // Mark 'b' as stalled (simulating GATED acceptance)
        service.mark_stalled("b", "Implementation blocker detected");

        // After marking as stalled, 'b' should not be selected
        let next = service.select_next_change(&changes);
        assert_eq!(next.map(|c| c.id.as_str()), Some("a"));

        // Verify 'b' is marked as stalled
        assert!(service.is_stalled("b"));
        assert!(!service.is_stalled("a"));
    }
}