cflx 0.6.153

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
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
//! Hook execution module for OpenSpec Orchestrator.
//!
//! Provides a system for executing user-defined commands at various stages
//! of the orchestration process.

use crate::config::expand;
use crate::error::{OrchestratorError, Result};
use crate::events::{ExecutionEvent, LogEntry};
use crate::orchestration::output::OutputHandler;
use serde::{Deserialize, Deserializer, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::AsyncReadExt;
use tokio::sync::mpsc;
use tokio::time::timeout;
use tracing::{debug, error, info, warn};

/// Default timeout for hook execution in seconds
pub const DEFAULT_HOOK_TIMEOUT: u64 = 60;

/// Environment variable that tells hook children whether downstream git commits should use
/// `--no-verify`.
pub const OPENSPEC_GIT_COMMIT_NO_VERIFY_ENV: &str = "OPENSPEC_GIT_COMMIT_NO_VERIFY";

/// Maximum bytes of hook output to display before truncating
pub const HOOK_OUTPUT_TRUNCATE_BYTES: usize = 1024;

/// Types of hooks that can be executed
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(dead_code)]
pub enum HookType {
    // === Run lifecycle ===
    /// Triggered when the orchestrator starts (once per run)
    OnStart,
    /// Triggered when the orchestrator finishes (once per run)
    OnFinish,
    /// Triggered on error
    OnError,

    // === Change lifecycle ===
    /// Triggered when starting to process a new change (once per change)
    OnChangeStart,
    /// Triggered before each apply execution
    PreApply,
    /// Triggered after each successful apply
    PostApply,
    /// Triggered when a change reaches 100% task completion
    OnChangeComplete,
    /// Triggered before each archive execution
    PreArchive,
    /// Triggered after each successful archive
    PostArchive,
    /// Triggered when change processing ends (once per change, after archive)
    OnChangeEnd,
    /// Triggered when a change is merged to base branch
    OnMerged,

    // === User interaction (TUI only) ===
    /// Triggered when user adds a change to queue (Space key)
    OnQueueAdd,
    /// Triggered when user removes a change from queue (Space key)
    OnQueueRemove,
}

impl HookType {
    pub fn config_key(&self) -> &'static str {
        match self {
            HookType::OnStart => "on_start",
            HookType::OnFinish => "on_finish",
            HookType::OnError => "on_error",
            HookType::OnChangeStart => "on_change_start",
            HookType::PreApply => "pre_apply",
            HookType::PostApply => "post_apply",
            HookType::OnChangeComplete => "on_change_complete",
            HookType::PreArchive => "pre_archive",
            HookType::PostArchive => "post_archive",
            HookType::OnChangeEnd => "on_change_end",
            HookType::OnMerged => "on_merged",
            HookType::OnQueueAdd => "on_queue_add",
            HookType::OnQueueRemove => "on_queue_remove",
        }
    }
}

impl std::fmt::Display for HookType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.config_key())
    }
}

/// Default number of retries for a hook (0 means no retry)
pub const DEFAULT_HOOK_MAX_RETRIES: u32 = 0;

/// Default delay between hook retries in seconds
pub const DEFAULT_HOOK_RETRY_DELAY_SECS: u64 = 3;

/// Configuration for a single hook
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct HookConfig {
    /// The command to execute
    pub command: String,
    /// Whether to continue if the hook fails (default: true)
    #[serde(default = "default_continue_on_failure")]
    pub continue_on_failure: bool,
    /// Timeout in seconds (default: 60)
    #[serde(default = "default_timeout")]
    pub timeout: u64,
    /// Whether downstream git commits should skip verification hooks (default: false)
    #[serde(default)]
    pub git_commit_no_verify: bool,
    /// Number of retries on non-zero exit before applying continue_on_failure logic (default: 0)
    #[serde(default)]
    pub max_retries: u32,
    /// Delay in seconds between retries (default: 3)
    #[serde(default = "default_retry_delay_secs")]
    pub retry_delay_secs: u64,
}

fn default_continue_on_failure() -> bool {
    true
}

fn default_timeout() -> u64 {
    DEFAULT_HOOK_TIMEOUT
}

fn default_retry_delay_secs() -> u64 {
    DEFAULT_HOOK_RETRY_DELAY_SECS
}

fn default_index_lock_wait_secs() -> u64 {
    DEFAULT_INDEX_LOCK_WAIT_SECS
}

impl HookConfig {
    /// Create a new HookConfig with just a command (using defaults)
    pub fn from_command(command: String) -> Self {
        Self {
            command,
            continue_on_failure: true,
            timeout: DEFAULT_HOOK_TIMEOUT,
            git_commit_no_verify: false,
            max_retries: DEFAULT_HOOK_MAX_RETRIES,
            retry_delay_secs: DEFAULT_HOOK_RETRY_DELAY_SECS,
        }
    }
}

/// Wrapper type that can deserialize from either a string or a HookConfig object
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum HookConfigValue {
    /// Simple string command (uses defaults)
    Simple(String),
    /// Full configuration object
    Full(HookConfig),
}

impl<'de> Deserialize<'de> for HookConfigValue {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::{self, MapAccess, Visitor};
        use std::fmt;

        struct HookConfigValueVisitor;

        impl<'de> Visitor<'de> for HookConfigValueVisitor {
            type Value = HookConfigValue;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a string or a hook configuration object")
            }

            fn visit_str<E>(self, value: &str) -> std::result::Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(HookConfigValue::Simple(value.to_string()))
            }

            fn visit_string<E>(self, value: String) -> std::result::Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(HookConfigValue::Simple(value))
            }

            fn visit_map<M>(self, map: M) -> std::result::Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                let config = HookConfig::deserialize(de::value::MapAccessDeserializer::new(map))?;
                Ok(HookConfigValue::Full(config))
            }
        }

        deserializer.deserialize_any(HookConfigValueVisitor)
    }
}

impl HookConfigValue {
    /// Convert to a HookConfig, applying defaults for simple string form
    pub fn into_hook_config(self) -> HookConfig {
        match self {
            HookConfigValue::Simple(cmd) => HookConfig::from_command(cmd),
            HookConfigValue::Full(config) => config,
        }
    }
}

/// Configuration for all hooks
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct HooksConfig {
    /// Maximum seconds to wait for .git/index.lock release before on_merged hook (default: 10)
    #[serde(default = "default_index_lock_wait_secs")]
    pub index_lock_wait_secs: u64,

    // === Run lifecycle ===
    #[serde(default)]
    pub on_start: Option<HookConfigValue>,
    #[serde(default)]
    pub on_finish: Option<HookConfigValue>,
    #[serde(default)]
    pub on_error: Option<HookConfigValue>,

    // === Change lifecycle ===
    #[serde(default)]
    pub on_change_start: Option<HookConfigValue>,
    #[serde(default)]
    pub pre_apply: Option<HookConfigValue>,
    #[serde(default)]
    pub post_apply: Option<HookConfigValue>,
    #[serde(default)]
    pub on_change_complete: Option<HookConfigValue>,
    #[serde(default)]
    pub pre_archive: Option<HookConfigValue>,
    #[serde(default)]
    pub post_archive: Option<HookConfigValue>,
    #[serde(default)]
    pub on_change_end: Option<HookConfigValue>,
    #[serde(default)]
    pub on_merged: Option<HookConfigValue>,

    // === User interaction (TUI only) ===
    #[serde(default)]
    pub on_queue_add: Option<HookConfigValue>,
    #[serde(default)]
    pub on_queue_remove: Option<HookConfigValue>,
}

impl HooksConfig {
    /// Merge another HooksConfig into this one, with the other config taking priority
    /// for fields that are `Some`. This enables deep merging of hook configurations.
    pub fn merge(&mut self, other: Self) {
        // Macro to reduce repetition
        macro_rules! merge_hook {
            ($field:ident) => {
                if other.$field.is_some() {
                    self.$field = other.$field;
                }
            };
        }

        // Run lifecycle
        merge_hook!(on_start);
        merge_hook!(on_finish);
        merge_hook!(on_error);

        // Change lifecycle
        merge_hook!(on_change_start);
        merge_hook!(pre_apply);
        merge_hook!(post_apply);
        merge_hook!(on_change_complete);
        merge_hook!(pre_archive);
        merge_hook!(post_archive);
        merge_hook!(on_change_end);
        merge_hook!(on_merged);

        // User interaction (TUI only)
        merge_hook!(on_queue_add);
        merge_hook!(on_queue_remove);
    }

    /// Get the hook configuration for a specific hook type
    pub fn get(&self, hook_type: HookType) -> Option<HookConfig> {
        let value = match hook_type {
            // Run lifecycle
            HookType::OnStart => self.on_start.clone(),
            HookType::OnFinish => self.on_finish.clone(),
            HookType::OnError => self.on_error.clone(),
            // Change lifecycle
            HookType::OnChangeStart => self.on_change_start.clone(),
            HookType::PreApply => self.pre_apply.clone(),
            HookType::PostApply => self.post_apply.clone(),
            HookType::OnChangeComplete => self.on_change_complete.clone(),
            HookType::PreArchive => self.pre_archive.clone(),
            HookType::PostArchive => self.post_archive.clone(),
            HookType::OnChangeEnd => self.on_change_end.clone(),
            HookType::OnMerged => self.on_merged.clone(),
            // User interaction (TUI only)
            HookType::OnQueueAdd => self.on_queue_add.clone(),
            HookType::OnQueueRemove => self.on_queue_remove.clone(),
        };
        value.map(|v| v.into_hook_config())
    }

    /// Check if any hooks are configured
    #[allow(dead_code)]
    pub fn has_any_hooks(&self) -> bool {
        self.on_start.is_some()
            || self.on_finish.is_some()
            || self.on_error.is_some()
            || self.on_change_start.is_some()
            || self.pre_apply.is_some()
            || self.post_apply.is_some()
            || self.on_change_complete.is_some()
            || self.pre_archive.is_some()
            || self.post_archive.is_some()
            || self.on_change_end.is_some()
            || self.on_merged.is_some()
            || self.on_queue_add.is_some()
            || self.on_queue_remove.is_some()
    }
}

/// Context information passed to hooks
#[derive(Debug, Clone, Default)]
pub struct HookContext {
    /// Current change ID (always set except for on_start/on_finish)
    pub change_id: Option<String>,
    /// Number of changes processed so far (completed + archived)
    pub changes_processed: usize,
    /// Total number of changes in initial queue
    pub total_changes: usize,
    /// Remaining changes in queue
    pub remaining_changes: usize,
    /// Completed tasks for current change
    pub completed_tasks: Option<u32>,
    /// Total tasks for current change
    pub total_tasks: Option<u32>,
    /// Apply count for current change (how many times applied)
    pub apply_count: u32,
    /// Finish status (for on_finish: "completed", "iteration_limit", "cancelled")
    pub status: Option<String>,
    /// Error message (for on_error hook)
    pub error: Option<String>,
    /// Whether running in dry-run mode
    pub dry_run: bool,
    /// Workspace path (for parallel mode)
    pub workspace_path: Option<String>,
    /// Group index (for parallel mode)
    pub group_index: Option<u32>,
}

impl HookContext {
    /// Create a new HookContext with basic run-level info
    pub fn new(
        changes_processed: usize,
        total_changes: usize,
        remaining_changes: usize,
        dry_run: bool,
    ) -> Self {
        Self {
            changes_processed,
            total_changes,
            remaining_changes,
            dry_run,
            ..Default::default()
        }
    }

    /// Set the change-related fields
    pub fn with_change(mut self, change_id: &str, completed_tasks: u32, total_tasks: u32) -> Self {
        self.change_id = Some(change_id.to_string());
        self.completed_tasks = Some(completed_tasks);
        self.total_tasks = Some(total_tasks);
        self
    }

    /// Set the apply count for the current change
    pub fn with_apply_count(mut self, apply_count: u32) -> Self {
        self.apply_count = apply_count;
        self
    }

    /// Set the status field (for on_finish)
    pub fn with_status(mut self, status: &str) -> Self {
        self.status = Some(status.to_string());
        self
    }

    /// Set the error field (for on_error)
    pub fn with_error(mut self, error: &str) -> Self {
        self.error = Some(error.to_string());
        self
    }

    /// Set parallel execution context (workspace path and group index)
    pub fn with_parallel_context(mut self, workspace_path: &str, group_index: Option<u32>) -> Self {
        self.workspace_path = Some(workspace_path.to_string());
        self.group_index = group_index;
        self
    }

    /// Convert context to environment variables
    pub fn to_env_vars(&self) -> HashMap<String, String> {
        let mut vars = HashMap::new();

        if let Some(ref change_id) = self.change_id {
            vars.insert("OPENSPEC_CHANGE_ID".to_string(), change_id.clone());
        }
        vars.insert(
            "OPENSPEC_CHANGES_PROCESSED".to_string(),
            self.changes_processed.to_string(),
        );
        vars.insert(
            "OPENSPEC_TOTAL_CHANGES".to_string(),
            self.total_changes.to_string(),
        );
        vars.insert(
            "OPENSPEC_REMAINING_CHANGES".to_string(),
            self.remaining_changes.to_string(),
        );
        if let Some(completed) = self.completed_tasks {
            vars.insert(
                "OPENSPEC_COMPLETED_TASKS".to_string(),
                completed.to_string(),
            );
        }
        if let Some(total) = self.total_tasks {
            vars.insert("OPENSPEC_TOTAL_TASKS".to_string(), total.to_string());
        }
        vars.insert(
            "OPENSPEC_APPLY_COUNT".to_string(),
            self.apply_count.to_string(),
        );
        if let Some(ref status) = self.status {
            vars.insert("OPENSPEC_STATUS".to_string(), status.clone());
        }
        if let Some(ref error) = self.error {
            vars.insert("OPENSPEC_ERROR".to_string(), error.clone());
        }
        vars.insert("OPENSPEC_DRY_RUN".to_string(), self.dry_run.to_string());

        // Parallel mode specific variables
        if let Some(ref workspace_path) = self.workspace_path {
            vars.insert(
                "OPENSPEC_WORKSPACE_PATH".to_string(),
                workspace_path.clone(),
            );
        }
        if let Some(group_index) = self.group_index {
            vars.insert("OPENSPEC_GROUP_INDEX".to_string(), group_index.to_string());
        }

        vars
    }

    /// Expand placeholders in a command string.
    ///
    /// Placeholder values are shell-escaped consistently with config command expansion.
    pub fn expand_placeholders(&self, template: &str) -> String {
        let mut result = template.to_string();

        if let Some(ref change_id) = self.change_id {
            result = expand::expand_placeholder(&result, "{change_id}", change_id);
        }
        result = expand::expand_placeholder(
            &result,
            "{changes_processed}",
            &self.changes_processed.to_string(),
        );
        result =
            expand::expand_placeholder(&result, "{total_changes}", &self.total_changes.to_string());
        result = expand::expand_placeholder(
            &result,
            "{remaining_changes}",
            &self.remaining_changes.to_string(),
        );
        if let Some(completed) = self.completed_tasks {
            result =
                expand::expand_placeholder(&result, "{completed_tasks}", &completed.to_string());
        }
        if let Some(total) = self.total_tasks {
            result = expand::expand_placeholder(&result, "{total_tasks}", &total.to_string());
        }
        result =
            expand::expand_placeholder(&result, "{apply_count}", &self.apply_count.to_string());
        if let Some(ref status) = self.status {
            result = expand::expand_placeholder(&result, "{status}", status);
        }
        if let Some(ref error) = self.error {
            result = expand::expand_placeholder(&result, "{error}", error);
        }

        result
    }
}

/// Truncate hook output to `limit` bytes, respecting UTF-8 char boundaries.
///
/// Returns `(display_slice, was_truncated)`.
fn truncate_hook_output(s: &str, limit: usize) -> (&str, bool) {
    if s.len() <= limit {
        return (s, false);
    }
    // Walk back from `limit` to find a valid char boundary
    let mut boundary = limit;
    while boundary > 0 && !s.is_char_boundary(boundary) {
        boundary -= 1;
    }
    (&s[..boundary], true)
}

/// Default maximum wait time for .git/index.lock release (seconds)
pub const DEFAULT_INDEX_LOCK_WAIT_SECS: u64 = 10;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HookRunnerLogLevel {
    Info,
    Warn,
    Error,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum IndexLockWaitOutcome {
    NotPresent,
    Released,
    TimedOut,
}

/// Hook runner that executes hooks based on configuration
#[derive(Clone)]
pub struct HookRunner {
    config: HooksConfig,
    /// Repository root directory for hook execution (working directory for commands)
    repo_root: PathBuf,
    /// Optional event sender for hook logs (TUI/parallel mode)
    event_tx: Option<mpsc::Sender<ExecutionEvent>>,
    /// Optional output handler for CLI-visible hook logs
    output_handler: Option<Arc<dyn OutputHandler>>,
}

impl std::fmt::Debug for HookRunner {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HookRunner")
            .field("config", &self.config)
            .field("repo_root", &self.repo_root)
            .field("event_tx", &self.event_tx.is_some())
            .field("output_handler", &self.output_handler.is_some())
            .finish()
    }
}

impl HookRunner {
    /// Create a new HookRunner with the given configuration
    pub fn new(config: HooksConfig, repo_root: impl Into<PathBuf>) -> Self {
        Self {
            config,
            repo_root: repo_root.into(),
            event_tx: None,
            output_handler: None,
        }
    }

    /// Create a HookRunner with the given configuration and output handler for CLI-visible logs.
    ///
    /// Use this in CLI (`cflx run`) mode so hook command invocations and captured output
    /// are surfaced in the user-visible log stream.
    pub fn with_output_handler(
        config: HooksConfig,
        repo_root: impl Into<PathBuf>,
        output_handler: Arc<dyn OutputHandler>,
    ) -> Self {
        Self {
            config,
            repo_root: repo_root.into(),
            event_tx: None,
            output_handler: Some(output_handler),
        }
    }

    /// Create a HookRunner with the given configuration and event sender
    pub fn with_event_tx(
        config: HooksConfig,
        repo_root: impl Into<PathBuf>,
        event_tx: mpsc::Sender<ExecutionEvent>,
    ) -> Self {
        Self {
            config,
            repo_root: repo_root.into(),
            event_tx: Some(event_tx),
            output_handler: None,
        }
    }

    /// Create a HookRunner with no hooks configured
    #[allow(dead_code)]
    pub fn empty() -> Self {
        Self {
            config: HooksConfig::default(),
            repo_root: PathBuf::from("."),
            event_tx: None,
            output_handler: None,
        }
    }

    /// Check if a specific hook is configured
    #[allow(dead_code)]
    pub fn has_hook(&self, hook_type: HookType) -> bool {
        self.config.get(hook_type).is_some()
    }

    async fn emit_runner_log(&self, level: HookRunnerLogLevel, message: String) {
        match level {
            HookRunnerLogLevel::Info => info!("{}", message),
            HookRunnerLogLevel::Warn => warn!("{}", message),
            HookRunnerLogLevel::Error => error!("{}", message),
        }

        if let Some(ref tx) = self.event_tx {
            let entry = match level {
                HookRunnerLogLevel::Info => LogEntry::info(message.clone()),
                HookRunnerLogLevel::Warn => LogEntry::warn(message.clone()),
                HookRunnerLogLevel::Error => LogEntry::error(message.clone()),
            };
            let _ = tx.send(ExecutionEvent::Log(entry)).await;
        }

        if let Some(ref handler) = self.output_handler {
            match level {
                HookRunnerLogLevel::Info => handler.on_info(&message),
                HookRunnerLogLevel::Warn => handler.on_warn(&message),
                HookRunnerLogLevel::Error => handler.on_error(&message),
            }
        }
    }

    /// Wait for `.git/index.lock` to be released, polling every 500ms.
    ///
    /// Returns the observed lock outcome so callers/tests can distinguish no-lock,
    /// released, and timeout cases without depending on hidden state.
    async fn wait_for_index_lock_release(&self, max_wait_secs: u64) -> IndexLockWaitOutcome {
        let lock_path = self.repo_root.join(".git/index.lock");
        if !lock_path.exists() {
            self.emit_runner_log(
                HookRunnerLogLevel::Info,
                format!(
                    "on_merged root lock preflight: {} was not present before hook execution",
                    lock_path.display()
                ),
            )
            .await;
            return IndexLockWaitOutcome::NotPresent;
        }

        self.emit_runner_log(
            HookRunnerLogLevel::Warn,
            format!(
                "on_merged root lock preflight: {} was already present; waiting up to {}s for release",
                lock_path.display(), max_wait_secs
            ),
        )
        .await;
        let poll_interval = Duration::from_millis(500);
        let max_wait = Duration::from_secs(max_wait_secs);
        let start = tokio::time::Instant::now();

        loop {
            tokio::time::sleep(poll_interval).await;
            if !lock_path.exists() {
                self.emit_runner_log(
                    HookRunnerLogLevel::Info,
                    format!(
                        "on_merged root lock preflight: {} released after {:.1}s; proceeding with hook execution",
                        lock_path.display(),
                        start.elapsed().as_secs_f64()
                    ),
                )
                .await;
                return IndexLockWaitOutcome::Released;
            }
            if start.elapsed() >= max_wait {
                self.emit_runner_log(
                    HookRunnerLogLevel::Warn,
                    format!(
                        "on_merged root lock preflight: {} still present after {}s; proceeding with hook execution after timeout",
                        lock_path.display(), max_wait_secs
                    ),
                )
                .await;
                return IndexLockWaitOutcome::TimedOut;
            }
        }
    }

    /// Emit captured output (stdout/stderr) to configured log sinks.
    async fn emit_hook_output(
        &self,
        hook_type: HookType,
        stdout: &str,
        stderr: &str,
        hook_succeeded: bool,
    ) {
        if !stdout.is_empty() {
            let (display, was_truncated) = truncate_hook_output(stdout, HOOK_OUTPUT_TRUNCATE_BYTES);
            let mut msg = format!("{} hook stdout: {}", hook_type, display);
            if was_truncated {
                msg.push_str(&format!(
                    "\n[... {} bytes truncated]",
                    stdout.len() - HOOK_OUTPUT_TRUNCATE_BYTES
                ));
            }
            if let Some(ref tx) = self.event_tx {
                let _ = tx
                    .send(ExecutionEvent::Log(LogEntry::info(msg.clone())))
                    .await;
            }
            if let Some(ref handler) = self.output_handler {
                handler.on_stdout(&msg);
            }
        }

        if !stderr.is_empty() {
            let (display, was_truncated) = truncate_hook_output(stderr, HOOK_OUTPUT_TRUNCATE_BYTES);
            let mut msg = format!("{} hook stderr: {}", hook_type, display);
            if was_truncated {
                msg.push_str(&format!(
                    "\n[... {} bytes truncated]",
                    stderr.len() - HOOK_OUTPUT_TRUNCATE_BYTES
                ));
            }

            if hook_succeeded {
                if let Some(ref tx) = self.event_tx {
                    let _ = tx
                        .send(ExecutionEvent::Log(LogEntry::info(msg.clone())))
                        .await;
                }
                if let Some(ref handler) = self.output_handler {
                    handler.on_info(&msg);
                }
            } else {
                if let Some(ref tx) = self.event_tx {
                    let _ = tx
                        .send(ExecutionEvent::Log(LogEntry::warn(msg.clone())))
                        .await;
                }
                if let Some(ref handler) = self.output_handler {
                    handler.on_stderr(&msg);
                }
            }
        }
    }

    /// Run a hook if configured
    ///
    /// Returns Ok(()) if:
    /// - Hook is not configured
    /// - Hook executed successfully
    /// - Hook failed but continue_on_failure is true
    ///
    /// Returns Err if hook failed and continue_on_failure is false
    ///
    /// For `on_merged` hooks, waits for `.git/index.lock` release before execution.
    /// If `max_retries > 0`, retries on non-zero exit with `retry_delay_secs` delay.
    pub async fn run_hook(&self, hook_type: HookType, context: &HookContext) -> Result<()> {
        let Some(hook_config) = self.config.get(hook_type) else {
            debug!("No hook configured for {}", hook_type);
            return Ok(());
        };

        let command = context.expand_placeholders(&hook_config.command);
        let mut env_vars = context.to_env_vars();
        env_vars.insert(
            OPENSPEC_GIT_COMMIT_NO_VERIFY_ENV.to_string(),
            hook_config.git_commit_no_verify.to_string(),
        );
        let timeout_duration = Duration::from_secs(hook_config.timeout);

        info!(
            module = module_path!(),
            "Running {} hook: {}", hook_type, command
        );
        debug!("Hook timeout: {}s", hook_config.timeout);

        // Emit hook command to all configured log sinks (event channel and/or output handler)
        let cmd_msg = format!("Running {} hook: {}", hook_type, command);
        if let Some(ref tx) = self.event_tx {
            let _ = tx
                .send(ExecutionEvent::Log(LogEntry::info(cmd_msg.clone())))
                .await;
        }
        if let Some(ref handler) = self.output_handler {
            handler.on_info(&cmd_msg);
        }

        let index_lock_outcome = if hook_type == HookType::OnMerged {
            Some(
                self.wait_for_index_lock_release(self.config.index_lock_wait_secs)
                    .await,
            )
        } else {
            None
        };

        // Execute with retry loop
        let max_attempts = 1 + hook_config.max_retries;
        let mut last_result: Result<()> = Ok(());

        for attempt in 1..=max_attempts {
            match self
                .execute_hook(hook_type, &command, &env_vars, timeout_duration)
                .await
            {
                Ok((success, stdout, stderr)) => {
                    self.emit_hook_output(hook_type, &stdout, &stderr, success)
                        .await;

                    if success {
                        info!("{} hook completed successfully", hook_type);
                        return Ok(());
                    }

                    if hook_type == HookType::OnMerged {
                        if let Some(outcome) = index_lock_outcome {
                            self.emit_runner_log(
                                HookRunnerLogLevel::Error,
                                format!(
                                    "on_merged hook execution failed after root lock preflight outcome {:?}: non-zero exit; stdout_bytes={}, stderr_bytes={}",
                                    outcome,
                                    stdout.len(),
                                    stderr.len()
                                ),
                            )
                            .await;
                        }
                    }

                    // Non-zero exit: check if we should retry
                    if attempt < max_attempts {
                        warn!(
                            "{} hook failed (attempt {}/{}), retrying in {}s...",
                            hook_type, attempt, max_attempts, hook_config.retry_delay_secs
                        );
                        tokio::time::sleep(Duration::from_secs(hook_config.retry_delay_secs)).await;
                        last_result = Err(OrchestratorError::HookFailed {
                            hook_type: hook_type.to_string(),
                            message: "Hook command returned non-zero exit code".to_string(),
                        });
                        continue;
                    }

                    // All attempts exhausted: apply continue_on_failure logic
                    if hook_config.continue_on_failure {
                        warn!(
                            "{} hook failed after {} attempt(s), continuing due to continue_on_failure=true",
                            hook_type, max_attempts
                        );
                        return Ok(());
                    } else {
                        self.emit_runner_log(
                            HookRunnerLogLevel::Error,
                            format!(
                                "{} hook failed after {} attempt(s)",
                                hook_type, max_attempts
                            ),
                        )
                        .await;
                        return Err(OrchestratorError::HookFailed {
                            hook_type: hook_type.to_string(),
                            message: format!(
                                "Hook command returned non-zero exit code after {} attempt(s)",
                                max_attempts
                            ),
                        });
                    }
                }
                Err(e) => {
                    if hook_type == HookType::OnMerged {
                        if let Some(outcome) = index_lock_outcome {
                            self.emit_runner_log(
                                HookRunnerLogLevel::Error,
                                format!(
                                    "on_merged hook execution error after root lock preflight outcome {:?}: {}",
                                    outcome, e
                                ),
                            )
                            .await;
                        }
                    }

                    // Execution error (spawn failure, timeout, etc.): check retry
                    if attempt < max_attempts {
                        warn!(
                            "{} hook error (attempt {}/{}): {}, retrying in {}s...",
                            hook_type, attempt, max_attempts, e, hook_config.retry_delay_secs
                        );
                        tokio::time::sleep(Duration::from_secs(hook_config.retry_delay_secs)).await;
                        last_result = Err(e);
                        continue;
                    }

                    // All attempts exhausted
                    if hook_config.continue_on_failure {
                        warn!(
                            "{} hook failed after {} attempt(s): {} (continuing due to continue_on_failure=true)",
                            hook_type, max_attempts, e
                        );
                        return Ok(());
                    } else {
                        self.emit_runner_log(
                            HookRunnerLogLevel::Error,
                            format!(
                                "{} hook failed after {} attempt(s): {}",
                                hook_type, max_attempts, e
                            ),
                        )
                        .await;
                        return Err(e);
                    }
                }
            }
        }

        last_result
    }

    /// Execute a hook command with the given environment variables and timeout.
    ///
    /// Returns `(success, stdout, stderr)` with stdout and stderr captured separately
    /// so callers can emit them with appropriate labels and log levels.
    async fn execute_hook(
        &self,
        hook_type: HookType,
        command: &str,
        env_vars: &HashMap<String, String>,
        timeout_duration: Duration,
    ) -> Result<(bool, String, String)> {
        // Use login shell ($SHELL -l -c) so user's PATH from .zprofile/.profile
        // is available, even when cflx is started from launchd/systemd/cron.
        let mut cmd = crate::shell_command::build_login_shell_command(command);

        // Set working directory to repo root so hooks always run from a consistent location
        cmd.current_dir(&self.repo_root);

        debug!(
            module = module_path!(),
            "Executing {} hook command via login shell in {:?}: {}",
            hook_type,
            self.repo_root,
            command
        );
        for (key, value) in env_vars {
            cmd.env(key, value);
        }

        // Capture stdout and stderr for logging
        cmd.stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        let mut child = cmd.spawn().map_err(|e| OrchestratorError::HookFailed {
            hook_type: hook_type.to_string(),
            message: format!("Failed to spawn hook process: {}", e),
        })?;

        // Capture output asynchronously
        let stdout = child.stdout.take();
        let stderr = child.stderr.take();

        // Wait with timeout
        match timeout(timeout_duration, child.wait()).await {
            Ok(result) => {
                let status = result.map_err(|e| OrchestratorError::HookFailed {
                    hook_type: hook_type.to_string(),
                    message: format!("Failed to wait for hook process: {}", e),
                })?;

                // Read stdout and stderr separately to preserve stream identity
                let mut stdout_output = String::new();
                if let Some(mut stdout_pipe) = stdout {
                    let mut buf = Vec::new();
                    if (stdout_pipe.read_to_end(&mut buf).await).is_ok() {
                        if let Ok(s) = String::from_utf8(buf) {
                            stdout_output = s;
                        }
                    }
                }
                let mut stderr_output = String::new();
                if let Some(mut stderr_pipe) = stderr {
                    let mut buf = Vec::new();
                    if (stderr_pipe.read_to_end(&mut buf).await).is_ok() {
                        if let Ok(s) = String::from_utf8(buf) {
                            stderr_output = s;
                        }
                    }
                }

                Ok((status.success(), stdout_output, stderr_output))
            }
            Err(_) => Err(OrchestratorError::HookTimeout {
                hook_type: hook_type.to_string(),
                timeout_secs: timeout_duration.as_secs(),
            }),
        }
    }

    /// Get the underlying configuration (for testing)
    #[cfg(test)]
    #[allow(dead_code)]
    pub fn config(&self) -> &HooksConfig {
        &self.config
    }
}

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

    #[test]
    fn test_hook_type_display() {
        assert_eq!(HookType::OnStart.to_string(), "on_start");
        assert_eq!(HookType::PreApply.to_string(), "pre_apply");
        assert_eq!(HookType::OnFinish.to_string(), "on_finish");
    }

    #[test]
    fn test_hook_config_from_command() {
        let config = HookConfig::from_command("echo test".to_string());
        assert_eq!(config.command, "echo test");
        assert!(config.continue_on_failure);
        assert_eq!(config.timeout, DEFAULT_HOOK_TIMEOUT);
        assert!(!config.git_commit_no_verify);
    }

    #[test]
    fn test_hook_context_expand_placeholders() {
        let context = HookContext::new(2, 5, 3, false)
            .with_change("test-change", 3, 10)
            .with_apply_count(1)
            .with_status("completed");

        let template = "Change {change_id} processed {changes_processed} of {total_changes} remaining {remaining_changes} apply {apply_count}";
        let result = context.expand_placeholders(template);
        assert_eq!(
            result,
            "Change test-change processed 2 of 5 remaining 3 apply 1"
        );
    }

    #[test]
    fn test_hook_context_to_env_vars() {
        let context = HookContext::new(1, 5, 3, true)
            .with_change("my-change", 2, 10)
            .with_apply_count(2);

        let vars = context.to_env_vars();
        assert_eq!(
            vars.get("OPENSPEC_CHANGE_ID"),
            Some(&"my-change".to_string())
        );
        assert_eq!(
            vars.get("OPENSPEC_CHANGES_PROCESSED"),
            Some(&"1".to_string())
        );
        assert_eq!(vars.get("OPENSPEC_TOTAL_CHANGES"), Some(&"5".to_string()));
        assert_eq!(
            vars.get("OPENSPEC_REMAINING_CHANGES"),
            Some(&"3".to_string())
        );
        assert_eq!(vars.get("OPENSPEC_COMPLETED_TASKS"), Some(&"2".to_string()));
        assert_eq!(vars.get("OPENSPEC_TOTAL_TASKS"), Some(&"10".to_string()));
        assert_eq!(vars.get("OPENSPEC_APPLY_COUNT"), Some(&"2".to_string()));
        assert_eq!(vars.get("OPENSPEC_DRY_RUN"), Some(&"true".to_string()));
        assert!(!vars.contains_key(OPENSPEC_GIT_COMMIT_NO_VERIFY_ENV));
    }

    #[test]
    fn test_hooks_config_deserialize_simple_string() {
        let json = r#"{"on_start": "echo hello"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let hook = config.get(HookType::OnStart).unwrap();
        assert_eq!(hook.command, "echo hello");
        assert!(hook.continue_on_failure);
        assert_eq!(hook.timeout, DEFAULT_HOOK_TIMEOUT);
    }

    #[test]
    fn test_hooks_config_deserialize_full_object() {
        let json = r#"{
            "on_start": {
                "command": "echo hello",
                "continue_on_failure": false,
                "timeout": 120
            }
        }"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let hook = config.get(HookType::OnStart).unwrap();
        assert_eq!(hook.command, "echo hello");
        assert!(!hook.continue_on_failure);
        assert_eq!(hook.timeout, 120);
        assert!(!hook.git_commit_no_verify);
    }

    #[test]
    fn test_hooks_config_deserialize_git_commit_no_verify() {
        let json = r#"{
            "on_merged": {
                "command": "make bump-patch",
                "git_commit_no_verify": true
            }
        }"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let hook = config.get(HookType::OnMerged).unwrap();
        assert_eq!(hook.command, "make bump-patch");
        assert!(hook.git_commit_no_verify);
        assert!(hook.continue_on_failure);
        assert_eq!(hook.timeout, DEFAULT_HOOK_TIMEOUT);
    }

    #[test]
    fn test_hooks_config_deserialize_mixed() {
        let json = r#"{
            "on_start": "echo start",
            "post_apply": {
                "command": "cargo test",
                "continue_on_failure": false,
                "timeout": 300
            }
        }"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();

        let on_start = config.get(HookType::OnStart).unwrap();
        assert_eq!(on_start.command, "echo start");
        assert!(on_start.continue_on_failure);

        let post_apply = config.get(HookType::PostApply).unwrap();
        assert_eq!(post_apply.command, "cargo test");
        assert!(!post_apply.continue_on_failure);
        assert_eq!(post_apply.timeout, 300);
    }

    #[test]
    fn test_hooks_config_has_any_hooks() {
        let empty = HooksConfig::default();
        assert!(!empty.has_any_hooks());

        let json = r#"{"on_start": "echo hello"}"#;
        let with_hook: HooksConfig = serde_json::from_str(json).unwrap();
        assert!(with_hook.has_any_hooks());
    }

    #[test]
    fn test_hook_runner_has_hook() {
        let json = r#"{"on_start": "echo hello"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, ".");

        assert!(runner.has_hook(HookType::OnStart));
        assert!(!runner.has_hook(HookType::PreApply));
    }

    #[tokio::test]
    async fn test_hook_runner_run_hook_not_configured() {
        let runner = HookRunner::empty();
        let context = HookContext::default();

        // Should succeed even when hook is not configured
        let result = runner.run_hook(HookType::OnStart, &context).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_hook_runner_run_hook_success() {
        let json = r#"{"on_start": "echo hello"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, ".");
        let context = HookContext::default();

        let result = runner.run_hook(HookType::OnStart, &context).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_hook_runner_run_hook_failure_with_continue() {
        let json = r#"{"on_start": {"command": "exit 1", "continue_on_failure": true}}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, ".");
        let context = HookContext::default();

        // Should succeed because continue_on_failure is true
        let result = runner.run_hook(HookType::OnStart, &context).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_hook_runner_run_hook_failure_without_continue() {
        let json = r#"{"on_start": {"command": "exit 1", "continue_on_failure": false}}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, ".");
        let context = HookContext::default();

        // Should fail because continue_on_failure is false
        let result = runner.run_hook(HookType::OnStart, &context).await;
        assert!(result.is_err());
    }

    #[cfg(feature = "heavy-tests")]
    #[tokio::test]
    async fn test_hook_runner_timeout() {
        let json =
            r#"{"on_start": {"command": "sleep 10", "timeout": 1, "continue_on_failure": false}}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, ".");
        let context = HookContext::default();

        // Should fail due to timeout
        let result = runner.run_hook(HookType::OnStart, &context).await;
        assert!(result.is_err());
        if let Err(OrchestratorError::HookTimeout { timeout_secs, .. }) = result {
            assert_eq!(timeout_secs, 1);
        } else {
            panic!("Expected HookTimeout error");
        }
    }

    #[tokio::test]
    async fn test_hook_runner_with_env_vars() {
        let json = r#"{"on_start": "echo $OPENSPEC_CHANGE_ID"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, ".");
        let context = HookContext::new(1, 5, 3, false).with_change("test-id", 2, 10);

        let result = runner.run_hook(HookType::OnStart, &context).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_hook_runner_exposes_git_commit_no_verify_true() {
        let json = r#"{
            "on_merged": {
                "command": "test \"$OPENSPEC_GIT_COMMIT_NO_VERIFY\" = \"true\"",
                "continue_on_failure": false,
                "git_commit_no_verify": true
            }
        }"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, ".");

        let result = runner
            .run_hook(HookType::OnMerged, &HookContext::default())
            .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_hook_runner_exposes_git_commit_no_verify_false_by_default() {
        let json = r#"{
            "on_merged": {
                "command": "test \"$OPENSPEC_GIT_COMMIT_NO_VERIFY\" = \"false\"",
                "continue_on_failure": false
            }
        }"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, ".");

        let result = runner
            .run_hook(HookType::OnMerged, &HookContext::default())
            .await;
        assert!(result.is_ok());
    }

    // === Tests for on_queue_add hook (hooks spec 2.1) ===

    #[test]
    fn test_hooks_config_on_queue_add() {
        let json = r#"{"on_queue_add": "echo 'Added {change_id}'"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let hook = config.get(HookType::OnQueueAdd).unwrap();
        assert_eq!(hook.command, "echo 'Added {change_id}'");
    }

    #[tokio::test]
    async fn test_on_queue_add_hook_execution() {
        let json = r#"{"on_queue_add": "echo added"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, ".");
        let context = HookContext::new(0, 5, 5, false).with_change("test-change", 0, 3);

        let result = runner.run_hook(HookType::OnQueueAdd, &context).await;
        assert!(result.is_ok());
    }

    // === Tests for on_queue_remove hook (hooks spec 2.2) ===

    #[test]
    fn test_hooks_config_on_queue_remove() {
        let json = r#"{"on_queue_remove": "echo 'Removed {change_id}'"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let hook = config.get(HookType::OnQueueRemove).unwrap();
        assert_eq!(hook.command, "echo 'Removed {change_id}'");
    }

    #[tokio::test]
    async fn test_on_queue_remove_hook_execution() {
        let json = r#"{"on_queue_remove": "echo removed"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, ".");
        let context = HookContext::new(0, 5, 5, false).with_change("test-change", 0, 3);

        let result = runner.run_hook(HookType::OnQueueRemove, &context).await;
        assert!(result.is_ok());
    }

    // === Tests for on_change_start hook (hooks spec 2.5) ===

    #[test]
    fn test_hooks_config_on_change_start() {
        let json = r#"{"on_change_start": "echo 'Starting {change_id}'"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let hook = config.get(HookType::OnChangeStart).unwrap();
        assert_eq!(hook.command, "echo 'Starting {change_id}'");
    }

    #[tokio::test]
    async fn test_on_change_start_hook_receives_change_id() {
        let json = r#"{"on_change_start": "echo test"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, ".");
        let context = HookContext::new(0, 3, 3, false).with_change("add-feature", 0, 5);

        let result = runner.run_hook(HookType::OnChangeStart, &context).await;
        assert!(result.is_ok());

        // Verify change_id is available in context
        let vars = context.to_env_vars();
        assert_eq!(
            vars.get("OPENSPEC_CHANGE_ID"),
            Some(&"add-feature".to_string())
        );
    }

    #[test]
    fn test_on_change_start_placeholder_expansion() {
        let context = HookContext::new(0, 3, 3, false).with_change("my-change", 0, 5);
        let template = "git commit -m 'changeset: {change_id}'";
        let result = context.expand_placeholders(template);
        assert_eq!(result, "git commit -m 'changeset: my-change'");
    }

    // === Tests for on_change_end hook (hooks spec 2.6) ===

    #[test]
    fn test_hooks_config_on_change_end() {
        let json = r#"{"on_change_end": "echo 'Finished {change_id}'"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let hook = config.get(HookType::OnChangeEnd).unwrap();
        assert_eq!(hook.command, "echo 'Finished {change_id}'");
    }

    #[tokio::test]
    async fn test_on_change_end_hook_execution() {
        let json = r#"{"on_change_end": "echo finished"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, ".");
        // After first change is archived: changes_processed=1, remaining=2
        let context = HookContext::new(1, 3, 2, false).with_change("change-a", 5, 5);

        let result = runner.run_hook(HookType::OnChangeEnd, &context).await;
        assert!(result.is_ok());
    }

    #[test]
    fn test_on_change_end_tracks_progress() {
        // Test that changes_processed/total_changes are correctly available
        let context = HookContext::new(1, 3, 2, false).with_change("change-a", 5, 5);
        let template = "echo '{changes_processed}/{total_changes}'";
        let result = context.expand_placeholders(template);
        assert_eq!(result, "echo '1/3'");
    }

    // === Tests for hook execution order (hooks spec 2.7) ===

    #[test]
    fn test_hook_types_config_key_order() {
        // Verify that hook config keys are correctly mapped
        assert_eq!(HookType::OnStart.config_key(), "on_start");
        assert_eq!(HookType::OnChangeStart.config_key(), "on_change_start");
        assert_eq!(HookType::PreApply.config_key(), "pre_apply");
        assert_eq!(HookType::PostApply.config_key(), "post_apply");
        assert_eq!(
            HookType::OnChangeComplete.config_key(),
            "on_change_complete"
        );
        assert_eq!(HookType::PreArchive.config_key(), "pre_archive");
        assert_eq!(HookType::PostArchive.config_key(), "post_archive");
        assert_eq!(HookType::OnChangeEnd.config_key(), "on_change_end");
        assert_eq!(HookType::OnMerged.config_key(), "on_merged");
        assert_eq!(HookType::OnFinish.config_key(), "on_finish");
    }

    // === Tests for TUI/CLI hook parity (hooks spec 2.8) ===
    // Note: Full parity testing requires integration tests.
    // These unit tests verify the same hook infrastructure is usable.

    #[test]
    fn test_hook_runner_is_reusable_for_tui_and_cli() {
        // Same HookRunner can be used in both modes
        let json = r#"{
            "on_change_start": "echo start",
            "on_change_end": "echo end"
        }"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config.clone(), ".");

        // TUI mode context
        let tui_context = HookContext::new(0, 3, 3, false).with_change("change-a", 0, 5);
        // CLI mode context (same structure)
        let cli_context = HookContext::new(0, 3, 3, false).with_change("change-a", 0, 5);

        // Both contexts produce identical environment variables
        assert_eq!(tui_context.to_env_vars(), cli_context.to_env_vars());
        assert!(runner.has_hook(HookType::OnChangeStart));
        assert!(runner.has_hook(HookType::OnChangeEnd));
    }

    // === Tests for apply_count increment (hooks spec context) ===

    #[test]
    fn test_apply_count_increments() {
        // Test apply_count is correctly tracked across multiple applies
        let context1 = HookContext::new(0, 1, 1, false)
            .with_change("my-change", 1, 3)
            .with_apply_count(1);
        let context2 = HookContext::new(0, 1, 1, false)
            .with_change("my-change", 2, 3)
            .with_apply_count(2);
        let context3 = HookContext::new(0, 1, 1, false)
            .with_change("my-change", 3, 3)
            .with_apply_count(3);

        let template = "echo 'Apply #{apply_count}'";
        assert_eq!(context1.expand_placeholders(template), "echo 'Apply #1'");
        assert_eq!(context2.expand_placeholders(template), "echo 'Apply #2'");
        assert_eq!(context3.expand_placeholders(template), "echo 'Apply #3'");
    }

    // === Tests for on_finish hook with status ===

    #[test]
    fn test_on_finish_with_status_placeholder() {
        let context = HookContext::new(3, 3, 0, false).with_status("completed");
        let template = "echo 'Status: {status}, Changes: {changes_processed}/{total_changes}'";
        let result = context.expand_placeholders(template);
        assert_eq!(result, "echo 'Status: completed, Changes: 3/3'");
    }

    #[test]
    fn test_on_finish_with_iteration_limit_status() {
        let context = HookContext::new(2, 3, 1, false).with_status("iteration_limit");
        let vars = context.to_env_vars();
        assert_eq!(
            vars.get("OPENSPEC_STATUS"),
            Some(&"iteration_limit".to_string())
        );
    }

    // === Tests for on_error hook with error message ===

    #[test]
    fn test_on_error_with_error_placeholder() {
        let context = HookContext::new(1, 3, 2, false)
            .with_change("failing-change", 2, 5)
            .with_error("LLM API timeout");
        let template = "echo '[on_error] change={change_id} error={error}'";
        let result = context.expand_placeholders(template);
        assert_eq!(
            result,
            "echo '[on_error] change=failing-change error=LLM API timeout'"
        );
    }

    #[test]
    fn test_on_error_env_vars() {
        let context = HookContext::new(1, 3, 2, false)
            .with_change("failing-change", 2, 5)
            .with_error("Connection refused");
        let vars = context.to_env_vars();
        assert_eq!(
            vars.get("OPENSPEC_ERROR"),
            Some(&"Connection refused".to_string())
        );
        assert_eq!(
            vars.get("OPENSPEC_CHANGE_ID"),
            Some(&"failing-change".to_string())
        );
    }

    // === Tests for on_start without change_id ===

    #[test]
    fn test_on_start_has_no_change_id() {
        // on_start should NOT have change_id available
        let context = HookContext::new(0, 3, 3, false);
        // No with_change() call
        let template = "echo '{change_id}'";
        let result = context.expand_placeholders(template);
        // change_id is not expanded (remains as placeholder)
        assert_eq!(result, "echo '{change_id}'");

        // But total_changes is available
        let template2 = "echo 'total={total_changes}'";
        let result2 = context.expand_placeholders(template2);
        assert_eq!(result2, "echo 'total=3'");
    }

    // === Tests for all hook types registered ===

    #[test]
    fn test_all_hook_types_can_be_configured() {
        let json = r#"{
            "on_start": "echo start",
            "on_finish": "echo finish",
            "on_error": "echo error",
            "on_change_start": "echo change_start",
            "pre_apply": "echo pre_apply",
            "post_apply": "echo post_apply",
            "on_change_complete": "echo change_complete",
            "pre_archive": "echo pre_archive",
            "post_archive": "echo post_archive",
            "on_change_end": "echo change_end",
            "on_merged": "echo merged",
            "on_queue_add": "echo queue_add",
            "on_queue_remove": "echo queue_remove"
        }"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, ".");

        // All hook types should be configured
        assert!(runner.has_hook(HookType::OnStart));
        assert!(runner.has_hook(HookType::OnFinish));
        assert!(runner.has_hook(HookType::OnError));
        assert!(runner.has_hook(HookType::OnChangeStart));
        assert!(runner.has_hook(HookType::PreApply));
        assert!(runner.has_hook(HookType::PostApply));
        assert!(runner.has_hook(HookType::OnChangeComplete));
        assert!(runner.has_hook(HookType::PreArchive));
        assert!(runner.has_hook(HookType::PostArchive));
        assert!(runner.has_hook(HookType::OnChangeEnd));
        assert!(runner.has_hook(HookType::OnMerged));
        assert!(runner.has_hook(HookType::OnQueueAdd));
        assert!(runner.has_hook(HookType::OnQueueRemove));
    }

    // === Tests for parallel mode context (add-parallel-hooks spec) ===

    #[test]
    fn test_hook_context_with_parallel_context() {
        let context = HookContext::new(1, 5, 4, false)
            .with_change("test-change", 3, 10)
            .with_parallel_context("/tmp/workspace-test", Some(2));

        assert_eq!(
            context.workspace_path,
            Some("/tmp/workspace-test".to_string())
        );
        assert_eq!(context.group_index, Some(2));
    }

    #[test]
    fn test_hook_context_parallel_env_vars() {
        let context = HookContext::new(2, 8, 6, false)
            .with_change("parallel-change", 5, 10)
            .with_parallel_context("/workspace/change-1", Some(3));

        let vars = context.to_env_vars();

        // Verify parallel-mode specific env vars
        assert_eq!(
            vars.get("OPENSPEC_WORKSPACE_PATH"),
            Some(&"/workspace/change-1".to_string())
        );
        assert_eq!(vars.get("OPENSPEC_GROUP_INDEX"), Some(&"3".to_string()));

        // Verify standard env vars are still present
        assert_eq!(
            vars.get("OPENSPEC_CHANGE_ID"),
            Some(&"parallel-change".to_string())
        );
        assert_eq!(
            vars.get("OPENSPEC_CHANGES_PROCESSED"),
            Some(&"2".to_string())
        );
    }

    #[test]
    fn test_hook_context_parallel_env_vars_without_group_index() {
        let context = HookContext::new(0, 3, 3, false)
            .with_change("single-change", 0, 5)
            .with_parallel_context("/workspace/single", None);

        let vars = context.to_env_vars();

        assert_eq!(
            vars.get("OPENSPEC_WORKSPACE_PATH"),
            Some(&"/workspace/single".to_string())
        );
        // group_index is None, so no OPENSPEC_GROUP_INDEX
        assert!(!vars.contains_key("OPENSPEC_GROUP_INDEX"));
    }

    #[test]
    fn test_hook_context_no_parallel_context() {
        let context = HookContext::new(0, 1, 1, false).with_change("sequential-change", 0, 3);

        let vars = context.to_env_vars();

        // Neither workspace_path nor group_index should be set
        assert!(!vars.contains_key("OPENSPEC_WORKSPACE_PATH"));
        assert!(!vars.contains_key("OPENSPEC_GROUP_INDEX"));

        // Standard env vars should still work
        assert_eq!(
            vars.get("OPENSPEC_CHANGE_ID"),
            Some(&"sequential-change".to_string())
        );
    }

    // === Tests for hook output logging (add-hook-logs-view-output spec) ===

    #[tokio::test]
    async fn test_hook_output_captured_and_logged() {
        let json = r#"{"on_start": "echo 'Hello from hook'"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();

        let (tx, mut rx) = mpsc::channel(10);
        let runner = HookRunner::with_event_tx(config, ".", tx);
        let context = HookContext::default();

        let result = runner.run_hook(HookType::OnStart, &context).await;
        assert!(result.is_ok());

        // Collect log events
        let mut log_messages = Vec::new();
        while let Ok(event) = rx.try_recv() {
            if let ExecutionEvent::Log(entry) = event {
                log_messages.push(entry.message);
            }
        }

        // Should have at least 2 logs: command execution + output
        assert!(!log_messages.is_empty(), "Expected at least 1 log message");

        // First log should be the command
        assert!(
            log_messages[0].contains("Running on_start hook"),
            "Expected command log, got: {}",
            log_messages[0]
        );

        // If there's output, it should be logged with the "stdout" label
        if log_messages.len() > 1 {
            assert!(
                log_messages[1].contains("Hello from hook")
                    || log_messages[1].contains("on_start hook stdout"),
                "Expected stdout output log, got: {}",
                log_messages[1]
            );
        }
    }

    #[tokio::test]
    async fn test_hook_without_event_tx_still_works() {
        let json = r#"{"on_start": "echo test"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, ".");
        let context = HookContext::default();

        // Should work without event_tx (no logs sent)
        let result = runner.run_hook(HookType::OnStart, &context).await;
        assert!(result.is_ok());
    }

    // === Regression tests for CLI hook output visibility ===

    use std::sync::{Arc, Mutex};

    /// Minimal OutputHandler that records all messages for test assertions.
    #[derive(Default, Clone)]
    struct RecordingOutputHandler {
        messages: Arc<Mutex<Vec<(String, String)>>>,
    }

    impl RecordingOutputHandler {
        fn new() -> Self {
            Self {
                messages: Arc::new(Mutex::new(Vec::new())),
            }
        }

        fn all(&self) -> Vec<(String, String)> {
            self.messages.lock().unwrap().clone()
        }

        fn content(&self) -> Vec<String> {
            self.all().into_iter().map(|(_, v)| v).collect()
        }
    }

    impl crate::orchestration::output::OutputHandler for RecordingOutputHandler {
        fn on_stdout(&self, line: &str) {
            self.messages
                .lock()
                .unwrap()
                .push(("stdout".into(), line.to_string()));
        }

        fn on_stderr(&self, line: &str) {
            self.messages
                .lock()
                .unwrap()
                .push(("stderr".into(), line.to_string()));
        }

        fn on_agent_stderr(&self, line: &str) {
            self.messages
                .lock()
                .unwrap()
                .push(("agent_stderr".into(), line.to_string()));
        }

        fn on_info(&self, message: &str) {
            self.messages
                .lock()
                .unwrap()
                .push(("info".into(), message.to_string()));
        }

        fn on_warn(&self, message: &str) {
            self.messages
                .lock()
                .unwrap()
                .push(("warn".into(), message.to_string()));
        }

        fn on_error(&self, message: &str) {
            self.messages
                .lock()
                .unwrap()
                .push(("error".into(), message.to_string()));
        }

        fn on_success(&self, message: &str) {
            self.messages
                .lock()
                .unwrap()
                .push(("success".into(), message.to_string()));
        }
    }

    #[tokio::test]
    async fn test_cli_hook_stdout_visible_via_output_handler() {
        // Hook that writes to stdout; output must appear in the output_handler stream.
        let json = r#"{"on_start": "echo 'hello stdout'"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let handler = RecordingOutputHandler::new();
        let runner = HookRunner::with_output_handler(config, ".", Arc::new(handler.clone()));

        let result = runner
            .run_hook(HookType::OnStart, &HookContext::default())
            .await;
        assert!(result.is_ok());

        let content = handler.content();
        // Command log must appear first
        assert!(
            content.iter().any(|m| m.contains("Running on_start hook")),
            "Command log not found: {:?}",
            content
        );
        // stdout output must appear
        assert!(
            content
                .iter()
                .any(|m| m.contains("on_start hook stdout") && m.contains("hello stdout")),
            "stdout output not found: {:?}",
            content
        );
    }

    #[tokio::test]
    async fn test_cli_hook_stderr_visible_via_output_handler() {
        // Hook that writes only to stderr; output must appear in the output_handler stream.
        let json = r#"{"on_start": "echo 'hello stderr' >&2"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let handler = RecordingOutputHandler::new();
        let runner = HookRunner::with_output_handler(config, ".", Arc::new(handler.clone()));

        let result = runner
            .run_hook(HookType::OnStart, &HookContext::default())
            .await;
        assert!(result.is_ok());

        let messages = handler.all();
        assert!(
            messages
                .iter()
                .any(|(_, m)| { m.contains("on_start hook stderr") && m.contains("hello stderr") }),
            "stderr output not found: {:?}",
            messages
        );
        assert!(
            messages.iter().any(|(level, m)| {
                level == "info" && m.contains("on_start hook stderr") && m.contains("hello stderr")
            }),
            "successful hook stderr should be informational: {:?}",
            messages
        );
        assert!(
            !messages.iter().any(|(level, m)| {
                level == "stderr"
                    && m.contains("on_start hook stderr")
                    && m.contains("hello stderr")
            }),
            "successful hook stderr must not be emitted as warning stderr: {:?}",
            messages
        );
    }

    #[tokio::test]
    async fn test_hook_successful_stderr_event_log_is_info_not_warn() {
        let json = r#"{"pre_apply": "echo 'hook diagnostic' >&2"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let (tx, mut rx) = mpsc::channel(8);
        let runner = HookRunner::with_event_tx(config, ".", tx);

        let result = runner
            .run_hook(HookType::PreApply, &HookContext::default())
            .await;
        assert!(result.is_ok());

        let mut entries = Vec::new();
        while let Ok(event) = rx.try_recv() {
            if let ExecutionEvent::Log(entry) = event {
                entries.push(entry);
            }
        }

        let stderr_entries: Vec<_> = entries
            .iter()
            .filter(|entry| entry.message.contains("pre_apply hook stderr"))
            .collect();
        assert_eq!(
            stderr_entries.len(),
            1,
            "expected exactly one stderr log entry: {:?}",
            entries
        );
        assert_eq!(stderr_entries[0].level, crate::events::LogLevel::Info);
        assert!(stderr_entries[0].message.contains("hook diagnostic"));
    }

    #[tokio::test]
    async fn test_hook_failure_stderr_event_log_remains_warn_before_error() {
        let json = r#"{
            "post_apply": {
                "command": "echo 'failure diagnostic' >&2; exit 1",
                "continue_on_failure": false
            }
        }"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let (tx, mut rx) = mpsc::channel(8);
        let runner = HookRunner::with_event_tx(config, ".", tx);

        let result = runner
            .run_hook(HookType::PostApply, &HookContext::default())
            .await;
        assert!(result.is_err());

        let mut entries = Vec::new();
        while let Ok(event) = rx.try_recv() {
            if let ExecutionEvent::Log(entry) = event {
                entries.push(entry);
            }
        }

        let stderr_index = entries
            .iter()
            .position(|entry| entry.message.contains("post_apply hook stderr"))
            .expect("expected captured stderr log entry");
        assert_eq!(entries[stderr_index].level, crate::events::LogLevel::Warn);
        assert!(entries[stderr_index].message.contains("failure diagnostic"));
        assert!(
            entries
                .iter()
                .skip(stderr_index + 1)
                .any(|entry| entry.level == crate::events::LogLevel::Error
                    && entry.message.contains("post_apply hook failed")),
            "expected hook failure error after stderr warning: {:?}",
            entries
        );
    }

    #[tokio::test]
    async fn test_cli_hook_output_visible_even_on_failure() {
        // Hook exits non-zero but output must still be shown before the failure.
        let json = r#"{"on_start": {"command": "echo 'output before fail'; exit 1", "continue_on_failure": true}}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let handler = RecordingOutputHandler::new();
        let runner = HookRunner::with_output_handler(config, ".", Arc::new(handler.clone()));

        // continue_on_failure=true so run_hook returns Ok
        let result = runner
            .run_hook(HookType::OnStart, &HookContext::default())
            .await;
        assert!(result.is_ok(), "expected Ok with continue_on_failure=true");

        let content = handler.content();
        assert!(
            content.iter().any(|m| m.contains("output before fail")),
            "output before failure not shown: {:?}",
            content
        );
    }

    #[tokio::test]
    async fn test_cli_hook_global_hooks_no_change_id() {
        // on_start / on_finish have no change_id; output must still surface.
        let json = r#"{"on_finish": "echo 'run finished'"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let handler = RecordingOutputHandler::new();
        let runner = HookRunner::with_output_handler(config, ".", Arc::new(handler.clone()));

        // Build a context with no change_id (as on_start/on_finish use)
        let ctx = HookContext::new(3, 3, 0, false).with_status("completed");

        let result = runner.run_hook(HookType::OnFinish, &ctx).await;
        assert!(result.is_ok());

        let content = handler.content();
        assert!(
            content.iter().any(|m| m.contains("Running on_finish hook")),
            "on_finish command log not shown: {:?}",
            content
        );
        assert!(
            content.iter().any(|m| m.contains("run finished")),
            "on_finish stdout not shown: {:?}",
            content
        );
    }

    #[tokio::test]
    async fn test_cli_hook_truncated_output_marked_explicitly() {
        // Generate output that exceeds HOOK_OUTPUT_TRUNCATE_BYTES to verify the explicit marker.
        let big_output = "x".repeat(HOOK_OUTPUT_TRUNCATE_BYTES + 100);
        let json = format!(r#"{{"on_start": "printf '{}'" }}"#, big_output);
        let config: HooksConfig = serde_json::from_str(&json).unwrap();
        let handler = RecordingOutputHandler::new();
        let runner = HookRunner::with_output_handler(config, ".", Arc::new(handler.clone()));

        let result = runner
            .run_hook(HookType::OnStart, &HookContext::default())
            .await;
        assert!(result.is_ok());

        let content = handler.content();
        let has_truncation_marker = content.iter().any(|m| m.contains("bytes truncated"));
        assert!(
            has_truncation_marker,
            "Expected explicit truncation marker in output: {:?}",
            content
        );
    }

    #[test]
    fn test_truncate_hook_output_below_limit() {
        let s = "hello";
        let (result, truncated) = truncate_hook_output(s, 1024);
        assert_eq!(result, "hello");
        assert!(!truncated);
    }

    #[test]
    fn test_truncate_hook_output_at_limit() {
        let s = "a".repeat(1024);
        let (result, truncated) = truncate_hook_output(&s, 1024);
        assert_eq!(result.len(), 1024);
        assert!(!truncated);
    }

    #[test]
    fn test_truncate_hook_output_above_limit() {
        let s = "b".repeat(2000);
        let (result, truncated) = truncate_hook_output(&s, 1024);
        assert_eq!(result.len(), 1024);
        assert!(truncated);
    }

    #[test]
    fn test_truncate_hook_output_multibyte_boundary() {
        // "日" is 3 bytes; 1025 bytes of "日" repeated would split a multi-byte char
        let s = "".repeat(400); // 1200 bytes total
        let (result, truncated) = truncate_hook_output(&s, 1024);
        // Result must be valid UTF-8 (no partial multi-byte chars)
        assert!(std::str::from_utf8(result.as_bytes()).is_ok());
        assert!(truncated);
        // Should be at most 1024 bytes and a valid char boundary
        assert!(result.len() <= 1024);
    }

    // === Tests for max_retries and retry_delay_secs (fix-on-merged-hook-reliability) ===

    #[test]
    fn test_hook_config_deserialize_with_max_retries() {
        let json = r#"{
            "on_merged": {
                "command": "make bump-patch",
                "max_retries": 3,
                "retry_delay_secs": 5
            }
        }"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let hook = config.get(HookType::OnMerged).unwrap();
        assert_eq!(hook.command, "make bump-patch");
        assert_eq!(hook.max_retries, 3);
        assert_eq!(hook.retry_delay_secs, 5);
        // Other fields should have defaults
        assert!(hook.continue_on_failure);
        assert_eq!(hook.timeout, DEFAULT_HOOK_TIMEOUT);
        assert!(!hook.git_commit_no_verify);
    }

    #[test]
    fn test_hook_config_default_retry_values() {
        let json = r#"{
            "on_merged": {
                "command": "make bump-patch"
            }
        }"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let hook = config.get(HookType::OnMerged).unwrap();
        assert_eq!(hook.max_retries, DEFAULT_HOOK_MAX_RETRIES);
        assert_eq!(hook.retry_delay_secs, DEFAULT_HOOK_RETRY_DELAY_SECS);
    }

    #[test]
    fn test_hook_config_simple_string_has_default_retry_values() {
        let json = r#"{"on_start": "echo hello"}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let hook = config.get(HookType::OnStart).unwrap();
        assert_eq!(hook.max_retries, DEFAULT_HOOK_MAX_RETRIES);
        assert_eq!(hook.retry_delay_secs, DEFAULT_HOOK_RETRY_DELAY_SECS);
    }

    #[test]
    fn test_hooks_config_backward_compat_no_new_fields() {
        // Existing configs without max_retries/retry_delay_secs/index_lock_wait_secs parse fine
        let json = r#"{
            "on_start": "echo start",
            "on_merged": {
                "command": "make bump-patch",
                "continue_on_failure": false,
                "timeout": 120,
                "git_commit_no_verify": true
            }
        }"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();

        let on_start = config.get(HookType::OnStart).unwrap();
        assert_eq!(on_start.command, "echo start");
        assert_eq!(on_start.max_retries, 0);
        assert_eq!(on_start.retry_delay_secs, 3);

        let on_merged = config.get(HookType::OnMerged).unwrap();
        assert_eq!(on_merged.command, "make bump-patch");
        assert!(!on_merged.continue_on_failure);
        assert_eq!(on_merged.timeout, 120);
        assert!(on_merged.git_commit_no_verify);
        assert_eq!(on_merged.max_retries, 0);
        assert_eq!(on_merged.retry_delay_secs, 3);

        // index_lock_wait_secs defaults
        assert_eq!(config.index_lock_wait_secs, DEFAULT_INDEX_LOCK_WAIT_SECS);
    }

    #[test]
    fn test_hooks_config_index_lock_wait_secs() {
        let json = r#"{"index_lock_wait_secs": 30}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.index_lock_wait_secs, 30);
    }

    #[test]
    fn test_hooks_config_index_lock_wait_secs_default() {
        let json = r#"{}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.index_lock_wait_secs, DEFAULT_INDEX_LOCK_WAIT_SECS);
    }

    #[tokio::test]
    async fn test_hook_retry_success_after_failure() {
        // Hook fails on first attempt, succeeds on second
        // We use a shell script that creates a marker file on first run,
        // and succeeds when the marker exists
        let tmp_dir = tempfile::tempdir().unwrap();
        let marker = tmp_dir.path().join("attempt_marker");
        let marker_str = marker.to_str().unwrap();
        let cmd = format!(
            "if [ -f '{}' ]; then echo ok; else touch '{}' && exit 1; fi",
            marker_str, marker_str
        );
        let json = serde_json::json!({
            "on_merged": {
                "command": cmd,
                "max_retries": 1,
                "retry_delay_secs": 0,
                "continue_on_failure": false
            }
        });
        let config: HooksConfig = serde_json::from_str(&json.to_string()).unwrap();
        let runner = HookRunner::new(config, tmp_dir.path());
        let context = HookContext::default();

        let result = runner.run_hook(HookType::OnMerged, &context).await;
        assert!(result.is_ok(), "Expected retry to succeed: {:?}", result);
    }

    #[tokio::test]
    async fn test_hook_retry_all_fail_continue_on_failure() {
        // Hook always fails, but continue_on_failure=true
        let json = r#"{
            "on_start": {
                "command": "exit 1",
                "max_retries": 2,
                "retry_delay_secs": 0,
                "continue_on_failure": true
            }
        }"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, ".");
        let context = HookContext::default();

        let result = runner.run_hook(HookType::OnStart, &context).await;
        assert!(result.is_ok(), "Expected Ok with continue_on_failure=true");
    }

    #[tokio::test]
    async fn test_hook_retry_all_fail_no_continue() {
        // Hook always fails, continue_on_failure=false
        let json = r#"{
            "on_start": {
                "command": "exit 1",
                "max_retries": 1,
                "retry_delay_secs": 0,
                "continue_on_failure": false
            }
        }"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, ".");
        let context = HookContext::default();

        let result = runner.run_hook(HookType::OnStart, &context).await;
        assert!(result.is_err(), "Expected error with all retries exhausted");
    }

    #[tokio::test]
    async fn test_hook_no_retry_by_default() {
        // Default max_retries=0 means no retry, immediately apply continue_on_failure
        let json = r#"{
            "on_start": {
                "command": "exit 1",
                "continue_on_failure": false
            }
        }"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, ".");
        let context = HookContext::default();

        let result = runner.run_hook(HookType::OnStart, &context).await;
        assert!(
            result.is_err(),
            "Expected immediate failure with max_retries=0"
        );
    }

    #[tokio::test]
    async fn test_hook_runner_cwd_is_repo_root() {
        // Verify that hook commands execute in the repo_root directory
        let tmp_dir = tempfile::tempdir().unwrap();
        let json = r#"{"on_start": {"command": "pwd", "continue_on_failure": false}}"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let runner = HookRunner::new(config, tmp_dir.path());
        let context = HookContext::default();

        let result = runner.run_hook(HookType::OnStart, &context).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_project_release_hook_config_skips_git_commit_verification() {
        let config = HooksConfig {
            on_merged: Some(HookConfigValue::Full(HookConfig {
                command: "make bump-patch".to_string(),
                continue_on_failure: false,
                timeout: 600,
                git_commit_no_verify: true,
                max_retries: 0,
                retry_delay_secs: 5,
            })),
            ..Default::default()
        };

        let hook = config.get(HookType::OnMerged).unwrap();
        assert_eq!(hook.command, "make bump-patch");
        assert_eq!(hook.timeout, 600);
        assert!(hook.git_commit_no_verify);
        assert_eq!(hook.max_retries, 0);
    }

    #[cfg(feature = "heavy-tests")]
    #[tokio::test]
    async fn test_on_merged_lock_preflight_logs_not_present_to_event_sink() {
        // When no .git/index.lock exists, wait returns immediately
        let tmp_dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp_dir.path().join(".git")).unwrap();
        let (tx, mut rx) = mpsc::channel(4);
        let runner = HookRunner::with_event_tx(HooksConfig::default(), tmp_dir.path(), tx);

        let outcome = runner.wait_for_index_lock_release(1).await;
        assert_eq!(
            outcome,
            IndexLockWaitOutcome::NotPresent,
            "Expected immediate return when no lock file"
        );
        let log = rx.try_recv().expect("expected no-lock preflight log");
        match log {
            ExecutionEvent::Log(entry) => assert!(entry
                .message
                .contains("was not present before hook execution")),
            other => panic!("expected log event, got {other:?}"),
        }
    }

    #[cfg(feature = "heavy-tests")]
    #[tokio::test]
    async fn test_on_merged_lock_preflight_logs_release_to_event_sink() {
        // Lock file is released within wait period
        let tmp_dir = tempfile::tempdir().unwrap();
        let git_dir = tmp_dir.path().join(".git");
        std::fs::create_dir_all(&git_dir).unwrap();
        let lock_file = git_dir.join("index.lock");
        std::fs::write(&lock_file, "lock").unwrap();

        let (tx, mut rx) = mpsc::channel(4);
        let runner = HookRunner::with_event_tx(HooksConfig::default(), tmp_dir.path(), tx);

        // Remove lock after a short delay
        let lock_clone = lock_file.clone();
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(200)).await;
            let _ = std::fs::remove_file(lock_clone);
        });

        let outcome = runner.wait_for_index_lock_release(5).await;
        assert_eq!(
            outcome,
            IndexLockWaitOutcome::Released,
            "Expected lock to be released"
        );
        let logs: Vec<String> = (0..2)
            .filter_map(|_| match rx.try_recv().ok()? {
                ExecutionEvent::Log(entry) => Some(entry.message),
                _ => None,
            })
            .collect();
        assert!(
            logs.iter()
                .any(|message| message.contains("was already present")),
            "expected pre-existing lock log, got {logs:?}"
        );
        assert!(
            logs.iter()
                .any(|message| message.contains("released after")),
            "expected lock release log, got {logs:?}"
        );
    }

    #[cfg(feature = "heavy-tests")]
    #[tokio::test]
    async fn test_on_merged_lock_preflight_logs_timeout_to_event_sink() {
        // Lock file persists beyond timeout
        let tmp_dir = tempfile::tempdir().unwrap();
        let git_dir = tmp_dir.path().join(".git");
        std::fs::create_dir_all(&git_dir).unwrap();
        let lock_file = git_dir.join("index.lock");
        std::fs::write(&lock_file, "lock").unwrap();

        let (tx, mut rx) = mpsc::channel(4);
        let runner = HookRunner::with_event_tx(HooksConfig::default(), tmp_dir.path(), tx);

        let outcome = runner.wait_for_index_lock_release(0).await;
        assert_eq!(
            outcome,
            IndexLockWaitOutcome::TimedOut,
            "Expected timeout when lock persists"
        );
        let logs: Vec<String> = (0..2)
            .filter_map(|_| match rx.try_recv().ok()? {
                ExecutionEvent::Log(entry) => Some(entry.message),
                _ => None,
            })
            .collect();
        assert!(
            logs.iter()
                .any(|message| message.contains("was already present")),
            "expected pre-existing lock log, got {logs:?}"
        );
        assert!(
            logs.iter()
                .any(|message| message.contains("proceeding with hook execution after timeout")),
            "expected timeout/proceeding log, got {logs:?}"
        );
    }

    #[tokio::test]
    async fn test_on_merged_failure_logs_preflight_outcome() {
        let tmp_dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp_dir.path().join(".git")).unwrap();
        let json = r#"{
            "on_merged": {
                "command": "echo lock-failure >&2; exit 1",
                "continue_on_failure": false
            }
        }"#;
        let config: HooksConfig = serde_json::from_str(json).unwrap();
        let (tx, mut rx) = mpsc::channel(8);
        let runner = HookRunner::with_event_tx(config, tmp_dir.path(), tx);

        let result = runner
            .run_hook(HookType::OnMerged, &HookContext::default())
            .await;
        assert!(
            result.is_err(),
            "non-continuable on_merged failure must propagate"
        );

        let mut logs = Vec::new();
        while let Ok(event) = rx.try_recv() {
            if let ExecutionEvent::Log(entry) = event {
                logs.push(entry.message);
            }
        }
        assert!(
            logs.iter()
                .any(|message| message.contains("root lock preflight outcome NotPresent")),
            "expected hook failure log with preflight outcome, got {logs:?}"
        );
        assert!(
            logs.iter()
                .any(|message| message.contains("on_merged hook stderr")),
            "expected captured stderr log, got {logs:?}"
        );
    }
}