cuenv-hooks 0.40.6

Hook execution system for cuenv environments
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
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
//! Hook execution engine with background processing and state management

use crate::state::{HookExecutionState, StateManager, compute_instance_hash};
use crate::types::{ExecutionStatus, Hook, HookExecutionConfig, HookResult};
use crate::{Error, Result};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::{Duration, Instant};
use tokio::process::Command;
use tokio::time::timeout;
use tracing::{debug, error, info, warn};

/// Manages hook execution with background processing and state persistence
#[derive(Debug)]
pub struct HookExecutor {
    config: HookExecutionConfig,
    state_manager: StateManager,
}

impl HookExecutor {
    /// Create a new hook executor with the specified configuration
    pub fn new(config: HookExecutionConfig) -> Result<Self> {
        let state_dir = if let Some(dir) = config.state_dir.clone() {
            dir
        } else {
            StateManager::default_state_dir()?
        };

        let state_manager = StateManager::new(state_dir);

        Ok(Self {
            config,
            state_manager,
        })
    }

    /// Create a hook executor with default configuration
    pub fn with_default_config() -> Result<Self> {
        let mut config = HookExecutionConfig::default();

        // Use CUENV_STATE_DIR if set
        if let Ok(state_dir) = std::env::var("CUENV_STATE_DIR") {
            config.state_dir = Some(PathBuf::from(state_dir));
        }

        Self::new(config)
    }

    /// Start executing hooks in the background for a directory
    pub async fn execute_hooks_background(
        &self,
        directory_path: PathBuf,
        config_hash: String,
        hooks: Vec<Hook>,
    ) -> Result<String> {
        use std::process::{Command, Stdio};

        if hooks.is_empty() {
            return Ok("No hooks to execute".to_string());
        }

        let instance_hash = compute_instance_hash(&directory_path, &config_hash);
        let total_hooks = hooks.len();

        // Check for existing state to preserve previous environment
        let previous_env =
            if let Ok(Some(existing_state)) = self.state_manager.load_state(&instance_hash).await {
                // If we have a completed state, save its environment as previous
                if existing_state.status == ExecutionStatus::Completed {
                    Some(existing_state.environment_vars.clone())
                } else {
                    existing_state.previous_env
                }
            } else {
                None
            };

        // Create initial execution state with previous environment
        let mut state = HookExecutionState::new(
            directory_path.clone(),
            instance_hash.clone(),
            config_hash.clone(),
            hooks.clone(),
        );
        state.previous_env = previous_env;

        // Save initial state
        self.state_manager.save_state(&state).await?;

        // Create directory marker for fast status lookups
        self.state_manager
            .create_directory_marker(&directory_path, &instance_hash)
            .await?;

        info!(
            "Starting background execution of {} hooks for directory: {}",
            total_hooks,
            directory_path.display()
        );

        // Check if a supervisor is already running for this instance
        let pid_file = self
            .state_manager
            .get_state_file_path(&instance_hash)
            .with_extension("pid");

        if pid_file.exists() {
            // Read the PID and check if process is still running
            if let Ok(pid_str) = std::fs::read_to_string(&pid_file)
                && let Ok(pid) = pid_str.trim().parse::<usize>()
            {
                // Check if process is still alive using sysinfo
                use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System};
                let mut system = System::new();
                let process_pid = Pid::from(pid);
                system.refresh_processes_specifics(
                    ProcessesToUpdate::Some(&[process_pid]),
                    false,
                    ProcessRefreshKind::nothing(),
                );

                if system.process(process_pid).is_some() {
                    info!("Supervisor already running for directory with PID {}", pid);
                    return Ok(format!(
                        "Supervisor already running for {} hooks (PID: {})",
                        total_hooks, pid
                    ));
                }
            }
            // If we get here, the PID file exists but process is dead
            std::fs::remove_file(&pid_file).ok();
        }

        // Write hooks and config to temp files to avoid argument size limits
        let state_dir = self.state_manager.get_state_dir();
        let hooks_file = state_dir.join(format!("{}_hooks.json", instance_hash));
        let config_file = state_dir.join(format!("{}_config.json", instance_hash));

        // Serialize and write hooks
        let hooks_json = serde_json::to_string(&hooks)
            .map_err(|e| Error::serialization(format!("Failed to serialize hooks: {}", e)))?;
        std::fs::write(&hooks_file, &hooks_json).map_err(|e| Error::Io {
            source: e,
            path: Some(hooks_file.clone().into_boxed_path()),
            operation: "write".to_string(),
        })?;

        // Serialize and write config
        let config_json = serde_json::to_string(&self.config)
            .map_err(|e| Error::serialization(format!("Failed to serialize config: {}", e)))?;
        std::fs::write(&config_file, &config_json).map_err(|e| Error::Io {
            source: e,
            path: Some(config_file.clone().into_boxed_path()),
            operation: "write".to_string(),
        })?;

        // Get the executable path to spawn as supervisor
        // Allow override via CUENV_EXECUTABLE for testing
        let current_exe = if let Ok(exe_path) = std::env::var("CUENV_EXECUTABLE") {
            PathBuf::from(exe_path)
        } else {
            std::env::current_exe()
                .map_err(|e| Error::process(format!("Failed to get current exe: {}", e)))?
        };

        // Spawn a detached supervisor process
        let mut cmd = Command::new(&current_exe);
        cmd.arg("__hook-supervisor") // Special hidden command
            .arg("--directory")
            .arg(directory_path.to_string_lossy().to_string())
            .arg("--instance-hash")
            .arg(&instance_hash)
            .arg("--config-hash")
            .arg(&config_hash)
            .arg("--hooks-file")
            .arg(hooks_file.to_string_lossy().to_string())
            .arg("--config-file")
            .arg(config_file.to_string_lossy().to_string())
            .stdin(Stdio::null());

        // Redirect output to log files for debugging
        let temp_dir = std::env::temp_dir();
        let log_file = std::fs::File::create(temp_dir.join("cuenv_supervisor.log")).ok();
        let err_file = std::fs::File::create(temp_dir.join("cuenv_supervisor_err.log")).ok();

        if let Some(log) = log_file {
            cmd.stdout(Stdio::from(log));
        } else {
            cmd.stdout(Stdio::null());
        }

        if let Some(err) = err_file {
            cmd.stderr(Stdio::from(err));
        } else {
            cmd.stderr(Stdio::null());
        }

        // Pass through CUENV_STATE_DIR if set
        if let Ok(state_dir) = std::env::var("CUENV_STATE_DIR") {
            cmd.env("CUENV_STATE_DIR", state_dir);
        }

        // Pass through CUENV_APPROVAL_FILE if set
        if let Ok(approval_file) = std::env::var("CUENV_APPROVAL_FILE") {
            cmd.env("CUENV_APPROVAL_FILE", approval_file);
        }

        // Pass through RUST_LOG for debugging
        if let Ok(rust_log) = std::env::var("RUST_LOG") {
            cmd.env("RUST_LOG", rust_log);
        }

        // Platform-specific detachment configuration
        #[cfg(windows)]
        {
            use std::os::windows::process::CommandExt;
            // Windows-specific flags for detached process
            const DETACHED_PROCESS: u32 = 0x00000008;
            const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
            cmd.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP);
        }

        let _child = cmd
            .spawn()
            .map_err(|e| Error::process(format!("Failed to spawn supervisor: {}", e)))?;

        // The child is now properly detached

        info!("Spawned supervisor process for hook execution");

        Ok(format!(
            "Started execution of {} hooks in background",
            total_hooks
        ))
    }

    /// Get the current execution status for a directory
    pub async fn get_execution_status(
        &self,
        directory_path: &Path,
    ) -> Result<Option<HookExecutionState>> {
        // List all active states and find one matching this directory
        let states = self.state_manager.list_active_states().await?;
        for state in states {
            if state.directory_path == directory_path {
                return Ok(Some(state));
            }
        }
        Ok(None)
    }

    /// Get execution status for a specific instance (directory + config)
    pub async fn get_execution_status_for_instance(
        &self,
        directory_path: &Path,
        config_hash: &str,
    ) -> Result<Option<HookExecutionState>> {
        let instance_hash = compute_instance_hash(directory_path, config_hash);
        self.state_manager.load_state(&instance_hash).await
    }

    /// Fast check if any hooks are active for a directory (no config hash needed).
    /// This is the hot path for Starship - skips config hash computation entirely.
    /// Returns None if no hooks running, Some(state) if hooks active.
    pub async fn get_fast_status(
        &self,
        directory_path: &Path,
    ) -> Result<Option<HookExecutionState>> {
        // First check: does marker exist? O(1) filesystem stat
        if !self.state_manager.has_active_marker(directory_path) {
            return Ok(None);
        }

        // Marker exists - get instance hash and load state
        if let Some(instance_hash) = self
            .state_manager
            .get_marker_instance_hash(directory_path)
            .await
        {
            let state = self.state_manager.load_state(&instance_hash).await?;

            match &state {
                Some(s) if s.is_complete() && !s.should_display_completed() => {
                    // State is complete and expired, clean up marker
                    self.state_manager
                        .remove_directory_marker(directory_path)
                        .await
                        .ok();
                    return Ok(None);
                }
                None => {
                    // State file was deleted but marker exists - clean up orphaned marker
                    self.state_manager
                        .remove_directory_marker(directory_path)
                        .await
                        .ok();
                    return Ok(None);
                }
                Some(_) => return Ok(state),
            }
        }

        Ok(None)
    }

    /// Get a reference to the state manager (for marker operations from execute_hooks)
    #[must_use]
    pub fn state_manager(&self) -> &StateManager {
        &self.state_manager
    }

    /// Synchronous fast status check - no tokio runtime required.
    /// This is the hot path for Starship/shell prompts when no async runtime is available.
    /// Returns None if no hooks running, Some(state) if hooks active.
    pub fn get_fast_status_sync(
        &self,
        directory_path: &Path,
    ) -> Result<Option<HookExecutionState>> {
        // First check: does marker exist? O(1) filesystem stat
        if !self.state_manager.has_active_marker(directory_path) {
            return Ok(None);
        }

        // Marker exists - get instance hash and load state synchronously
        if let Some(instance_hash) = self
            .state_manager
            .get_marker_instance_hash_sync(directory_path)
        {
            let state = self.state_manager.load_state_sync(&instance_hash)?;

            match &state {
                Some(s) if s.is_complete() && !s.should_display_completed() => {
                    // State is complete and expired - for sync path, just return None
                    // (async cleanup will happen on next async call)
                    return Ok(None);
                }
                None => {
                    // State file was deleted but marker exists - return None
                    // (async cleanup will happen on next async call)
                    return Ok(None);
                }
                Some(_) => return Ok(state),
            }
        }

        Ok(None)
    }

    /// Wait for hook execution to complete, with optional timeout in seconds
    pub async fn wait_for_completion(
        &self,
        directory_path: &Path,
        config_hash: &str,
        timeout_seconds: Option<u64>,
    ) -> Result<HookExecutionState> {
        let instance_hash = compute_instance_hash(directory_path, config_hash);
        let poll_interval = Duration::from_millis(500);
        let start_time = Instant::now();

        loop {
            if let Some(state) = self.state_manager.load_state(&instance_hash).await? {
                if state.is_complete() {
                    return Ok(state);
                }
            } else {
                return Err(Error::state_not_found(&instance_hash));
            }

            // Check timeout
            if let Some(timeout) = timeout_seconds
                && start_time.elapsed().as_secs() >= timeout
            {
                return Err(Error::Timeout { seconds: timeout });
            }

            tokio::time::sleep(poll_interval).await;
        }
    }

    /// Cancel execution for a directory
    pub async fn cancel_execution(
        &self,
        directory_path: &Path,
        config_hash: &str,
        reason: Option<String>,
    ) -> Result<bool> {
        let instance_hash = compute_instance_hash(directory_path, config_hash);

        // Try to kill the supervisor process if it exists
        let pid_file = self
            .state_manager
            .get_state_file_path(&instance_hash)
            .with_extension("pid");

        if pid_file.exists()
            && let Ok(pid_str) = std::fs::read_to_string(&pid_file)
            && let Ok(pid) = pid_str.trim().parse::<usize>()
        {
            use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, Signal, System};

            let mut system = System::new();
            let process_pid = Pid::from(pid);

            // Refresh the specific process
            system.refresh_processes_specifics(
                ProcessesToUpdate::Some(&[process_pid]),
                false,
                ProcessRefreshKind::nothing(),
            );

            // Check if process exists and kill it
            if let Some(process) = system.process(process_pid) {
                if process.kill_with(Signal::Term).is_some() {
                    info!("Sent SIGTERM to supervisor process PID {}", pid);
                } else {
                    warn!("Failed to send SIGTERM to supervisor process PID {}", pid);
                }
            } else {
                info!(
                    "Supervisor process PID {} not found (may have already exited)",
                    pid
                );
            }

            // Clean up PID file regardless
            std::fs::remove_file(&pid_file).ok();
        }

        // Then update the state
        if let Some(mut state) = self.state_manager.load_state(&instance_hash).await?
            && !state.is_complete()
        {
            state.mark_cancelled(reason);
            self.state_manager.save_state(&state).await?;
            info!(
                "Cancelled execution for directory: {}",
                directory_path.display()
            );
            return Ok(true);
        }

        Ok(false)
    }

    /// Clean up completed execution states older than the specified duration
    pub async fn cleanup_old_states(&self, older_than: chrono::Duration) -> Result<usize> {
        let states = self.state_manager.list_active_states().await?;
        let cutoff = chrono::Utc::now() - older_than;
        let mut cleaned_count = 0;

        for state in states {
            if state.is_complete()
                && let Some(finished_at) = state.finished_at
                && finished_at < cutoff
            {
                self.state_manager
                    .remove_state(&state.instance_hash)
                    .await?;
                cleaned_count += 1;
            }
        }

        if cleaned_count > 0 {
            info!("Cleaned up {} old execution states", cleaned_count);
        }

        Ok(cleaned_count)
    }

    /// Execute a single hook and return the result
    pub async fn execute_single_hook(&self, hook: Hook) -> Result<HookResult> {
        // Use the default timeout from config
        let timeout = self.config.default_timeout_seconds;

        // No validation - users approved this config with cuenv allow
        execute_hook_with_timeout(hook, &timeout).await
    }
}

/// Execute hooks sequentially
pub async fn execute_hooks(
    hooks: Vec<Hook>,
    _directory_path: &Path,
    config: &HookExecutionConfig,
    state_manager: &StateManager,
    state: &mut HookExecutionState,
) -> Result<()> {
    let hook_count = hooks.len();
    debug!("execute_hooks called with {} hooks", hook_count);
    if hook_count == 0 {
        debug!("No hooks to execute");
        return Ok(());
    }
    debug!("Starting to iterate over {} hooks", hook_count);
    for (index, hook) in hooks.into_iter().enumerate() {
        debug!(
            "Processing hook {}/{}: command={}",
            index + 1,
            state.total_hooks,
            hook.command
        );
        // Check if execution was cancelled
        debug!("Checking if execution was cancelled");
        if let Ok(Some(current_state)) = state_manager.load_state(&state.instance_hash).await {
            debug!("Loaded state: status = {:?}", current_state.status);
            if current_state.status == ExecutionStatus::Cancelled {
                debug!("Execution was cancelled, stopping");
                break;
            }
        }

        // No validation - users approved this config with cuenv allow

        let timeout_seconds = config.default_timeout_seconds;

        // Mark hook as running
        state.mark_hook_running(index);

        // Execute the hook and wait for it to complete
        let result = execute_hook_with_timeout(hook.clone(), &timeout_seconds).await;

        // Record the result
        match result {
            Ok(hook_result) => {
                // If this is a source hook, evaluate its output to capture environment variables.
                // We do this even if the hook failed (exit code != 0), because tools like devenv
                // might output valid environment exports before crashing or exiting with error.
                // We rely on our robust delimiter-based parsing to extract what we can.
                if hook.source.unwrap_or(false) {
                    if hook_result.stdout.is_empty() {
                        warn!(
                            "Source hook produced empty stdout. Stderr content:\n{}",
                            hook_result.stderr
                        );
                    } else {
                        debug!(
                            "Evaluating source hook output for environment variables (success={})",
                            hook_result.success
                        );
                        match evaluate_shell_environment(
                            &hook_result.stdout,
                            &state.environment_vars,
                        )
                        .await
                        {
                            Ok((env_vars, removed_keys)) => {
                                let count = env_vars.len();
                                debug!(
                                    "Captured {} environment variables from source hook ({} removed)",
                                    count,
                                    removed_keys.len()
                                );
                                // Merge captured environment variables into state
                                for (key, value) in env_vars {
                                    state.environment_vars.insert(key, value);
                                }
                                // Remove variables that were unset by the hook
                                for key in &removed_keys {
                                    state.environment_vars.remove(key);
                                }
                            }
                            Err(e) => {
                                warn!("Failed to evaluate source hook output: {}", e);
                                // Don't fail the hook execution further, just log the error
                            }
                        }
                    }
                }

                state.record_hook_result(index, hook_result.clone());
                if !hook_result.success && config.fail_fast {
                    warn!(
                        "Hook {} failed and fail_fast is enabled, stopping",
                        index + 1
                    );
                    break;
                }
            }
            Err(e) => {
                let error_msg = format!("Hook execution error: {}", e);
                state.record_hook_result(
                    index,
                    HookResult::failure(
                        hook.clone(),
                        None,
                        String::new(),
                        error_msg.clone(),
                        0,
                        error_msg,
                    ),
                );
                if config.fail_fast {
                    warn!("Hook {} failed with error, stopping", index + 1);
                    break;
                }
            }
        }

        // Save state after each hook completes
        state_manager.save_state(state).await?;
    }

    // Mark execution as completed if we got here without errors
    if state.status == ExecutionStatus::Running {
        state.status = ExecutionStatus::Completed;
        state.finished_at = Some(chrono::Utc::now());
        info!(
            "All hooks completed successfully for directory: {}",
            state.directory_path.display()
        );
    }

    // Save final state
    state_manager.save_state(state).await?;

    Ok(())
}

/// Execute a single source hook and return the resulting environment.
///
/// This bypasses hook approval and state persistence, making it suitable for
/// runtime-backed environment materialization where the manifest itself is the
/// source of truth.
pub async fn capture_source_environment(
    hook: Hook,
    prior_env: &HashMap<String, String>,
    timeout_seconds: u64,
) -> Result<HashMap<String, String>> {
    if !hook.source.unwrap_or(false) {
        return Err(Error::configuration(
            "capture_source_environment requires a source hook",
        ));
    }

    let hook_result = execute_hook_with_timeout(hook, &timeout_seconds).await?;
    let (env_delta, removed_keys) =
        evaluate_shell_environment(&hook_result.stdout, prior_env).await?;

    let mut environment = prior_env.clone();
    for (key, value) in env_delta {
        environment.insert(key, value);
    }
    for key in removed_keys {
        environment.remove(&key);
    }

    Ok(environment)
}

/// Resolve the absolute path to the `env` command by searching PATH.
/// Falls back to `/usr/bin/env` if not found (best-effort for non-Nix environments).
fn find_env_command() -> String {
    let path_var = std::env::var_os("PATH").unwrap_or_default();
    for dir in std::env::split_paths(&path_var) {
        let candidate = dir.join("env");
        if candidate.is_file() {
            return candidate.to_string_lossy().into_owned();
        }
    }
    "/usr/bin/env".to_string()
}

/// Detect which shell to use for environment evaluation
async fn detect_shell() -> String {
    // Try bash first
    if is_shell_capable("bash").await {
        return "bash".to_string();
    }

    // Try zsh (common on macOS where bash is old)
    if is_shell_capable("zsh").await {
        return "zsh".to_string();
    }

    // Fall back to sh (likely to fail for advanced scripts but better than nothing)
    "sh".to_string()
}

/// Check if a shell supports modern features like case fallthrough (;&)
async fn is_shell_capable(shell: &str) -> bool {
    let check_script = "case x in x) true ;& y) true ;; esac";
    match Command::new(shell)
        .arg("-c")
        .arg(check_script)
        .output()
        .await
    {
        Ok(output) => output.status.success(),
        Err(_) => false,
    }
}

/// Evaluate shell script and extract resulting environment variables
async fn evaluate_shell_environment(
    shell_script: &str,
    prior_env: &HashMap<String, String>,
) -> Result<(HashMap<String, String>, Vec<String>)> {
    const DELIMITER: &str = "__CUENV_ENV_START__";

    debug!(
        "Evaluating shell script to extract environment ({} bytes)",
        shell_script.len()
    );

    tracing::trace!("Raw shell script from hook:\n{}", shell_script);

    // Try to find the specific bash binary that produced this script (common in Nix/devenv)
    // This avoids compatibility issues with system bash (e.g. macOS bash 3.2 vs Nix bash 5.x)
    let mut shell = detect_shell().await;

    for line in shell_script.lines() {
        if let Some(path) = line.strip_prefix("BASH='")
            && let Some(end) = path.find('\'')
        {
            let bash_path = &path[..end];
            let path = PathBuf::from(bash_path);
            if path.exists() {
                debug!("Detected Nix bash in script: {}", bash_path);
                shell = bash_path.to_string();
                break;
            }
        }
    }

    debug!("Using shell: {}", shell);

    let env_cmd = find_env_command();

    // First, get the environment before running the script
    let mut cmd_before = Command::new(&shell);
    cmd_before.arg("-c");
    cmd_before.arg(format!("{env_cmd} -0"));
    cmd_before.stdout(Stdio::piped());
    cmd_before.stderr(Stdio::piped());
    // Inject prior hooks' environment so the baseline reflects accumulated state
    for (key, value) in prior_env {
        cmd_before.env(key, value);
    }

    let output_before = cmd_before
        .output()
        .await
        .map_err(|e| Error::configuration(format!("Failed to get initial environment: {}", e)))?;

    let env_before_output = String::from_utf8_lossy(&output_before.stdout);
    let mut env_before = HashMap::new();
    for line in env_before_output.split('\0') {
        if let Some((key, value)) = line.split_once('=') {
            env_before.insert(key.to_string(), value.to_string());
        }
    }

    // Filter out lines that are likely status messages or not shell assignments
    let filtered_lines: Vec<&str> = shell_script
        .lines()
        .filter(|line| {
            let trimmed = line.trim();
            if trimmed.is_empty() {
                return false;
            }

            // Filter out known status/error prefixes that might pollute stdout
            if trimmed.starts_with("")
                || trimmed.starts_with("sh:")
                || trimmed.starts_with("bash:")
            {
                return false;
            }

            // Otherwise keep it. We trust the tool to output valid shell code
            // (including multiline strings, comments, unsets, aliases, etc.)
            true
        })
        .collect();

    let filtered_script = filtered_lines.join("\n");
    tracing::trace!("Filtered shell script:\n{}", filtered_script);

    // Now execute the filtered script and capture the environment after
    let mut cmd = Command::new(shell);
    cmd.arg("-c");

    let script = format!(
        "{}\necho -ne '\\0{}\\0'; {env_cmd} -0",
        filtered_script, DELIMITER
    );
    cmd.arg(script);
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());
    // Inject prior hooks' environment so $PATH etc. expand correctly
    for (key, value) in prior_env {
        cmd.env(key, value);
    }

    let output = cmd.output().await.map_err(|e| {
        Error::configuration(format!("Failed to evaluate shell environment: {}", e))
    })?;

    // If the command failed, we still try to parse the output, in case env -0 ran.
    // But we should log the error.
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        warn!(
            "Shell script evaluation finished with error (exit code {:?}): {}",
            output.status.code(),
            stderr
        );
        // We continue to try to parse stdout.
    }

    // Parse the output. We expect: <script_output>\0<DELIMITER>\0<env_vars>\0...
    let stdout_bytes = &output.stdout;
    let delimiter_bytes = format!("\0{}\0", DELIMITER).into_bytes();

    // Find the delimiter in the output
    let env_start_index = stdout_bytes
        .windows(delimiter_bytes.len())
        .position(|window| window == delimiter_bytes);

    let env_output_bytes = if let Some(idx) = env_start_index {
        // We found the delimiter, everything after it is the environment
        &stdout_bytes[idx + delimiter_bytes.len()..]
    } else {
        debug!("Environment delimiter not found in hook output");
        // Log the tail of stdout to diagnose why delimiter is missing
        let len = stdout_bytes.len();
        let start = len.saturating_sub(1000);
        let tail = String::from_utf8_lossy(&stdout_bytes[start..]);
        warn!(
            "Delimiter missing. Tail of stdout (last 1000 bytes):\n{}",
            tail
        );

        // Fallback: return empty if delimiter missing
        &[]
    };

    let env_output = String::from_utf8_lossy(env_output_bytes);
    let mut env_delta = HashMap::new();
    let mut post_env_keys = std::collections::HashSet::new();

    let is_skip_key = |key: &str| -> bool {
        key.starts_with("BASH_FUNC_")
            || key == "PS1"
            || key == "PS2"
            || key == "_"
            || key == "PWD"
            || key == "OLDPWD"
            || key == "SHLVL"
            || key.starts_with("BASH")
    };

    for line in env_output.split('\0') {
        if line.is_empty() {
            continue;
        }

        if let Some((key, value)) = line.split_once('=') {
            if is_skip_key(key) {
                continue;
            }

            if !key.is_empty() {
                post_env_keys.insert(key.to_string());
            }

            // Only include variables that are new or changed
            // We also skip empty keys which can happen with malformed output
            if !key.is_empty() && env_before.get(key) != Some(&value.to_string()) {
                env_delta.insert(key.to_string(), value.to_string());
            }
        }
    }

    // Detect variables that were present in prior_env but removed by this hook
    let removed_keys: Vec<String> = prior_env
        .keys()
        .filter(|key| !is_skip_key(key) && !post_env_keys.contains(key.as_str()))
        .cloned()
        .collect();

    if env_delta.is_empty() && removed_keys.is_empty() && !output.status.success() {
        // If we failed AND got no variables, that's a real problem.
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(Error::configuration(format!(
            "Shell script evaluation failed and no environment captured. Error: {}",
            stderr
        )));
    }

    debug!(
        "Evaluated shell script and extracted {} new/changed environment variables ({} removed)",
        env_delta.len(),
        removed_keys.len()
    );
    Ok((env_delta, removed_keys))
}

/// Execute a single hook with timeout
async fn execute_hook_with_timeout(hook: Hook, timeout_seconds: &u64) -> Result<HookResult> {
    let start_time = Instant::now();

    debug!(
        "Executing hook: {} {} (source: {})",
        hook.command,
        hook.args.join(" "),
        hook.source.unwrap_or(false)
    );

    // Prepare the command
    let mut cmd = Command::new(&hook.command);
    cmd.args(&hook.args);
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());

    // Set working directory
    if let Some(dir) = &hook.dir {
        cmd.current_dir(dir);
    }

    // Force SHELL to match the evaluator shell for source hooks
    // This ensures tools like devenv output compatible syntax (e.g. avoid fish syntax)
    if hook.source.unwrap_or(false) {
        cmd.env("SHELL", detect_shell().await);
    }

    // Execute with timeout
    let execution_result = timeout(Duration::from_secs(*timeout_seconds), cmd.output()).await;

    // Truncation is fine here - a u64 can hold ~584M years in milliseconds
    #[expect(
        clippy::cast_possible_truncation,
        reason = "u128 to u64 truncation is acceptable for duration"
    )]
    let duration_ms = start_time.elapsed().as_millis() as u64;

    match execution_result {
        Ok(Ok(output)) => {
            let stdout = String::from_utf8_lossy(&output.stdout).to_string();
            let stderr = String::from_utf8_lossy(&output.stderr).to_string();

            if output.status.success() {
                debug!("Hook completed successfully in {}ms", duration_ms);
                Ok(HookResult::success(
                    hook,
                    output.status,
                    stdout,
                    stderr,
                    duration_ms,
                ))
            } else {
                warn!("Hook failed with exit code: {:?}", output.status.code());
                Ok(HookResult::failure(
                    hook,
                    Some(output.status),
                    stdout,
                    stderr,
                    duration_ms,
                    format!("Command exited with status: {}", output.status),
                ))
            }
        }
        Ok(Err(io_error)) => {
            error!("Failed to execute hook: {}", io_error);
            Ok(HookResult::failure(
                hook,
                None,
                String::new(),
                String::new(),
                duration_ms,
                format!("Failed to execute command: {}", io_error),
            ))
        }
        Err(_timeout_error) => {
            warn!("Hook timed out after {} seconds", timeout_seconds);
            Ok(HookResult::timeout(
                hook,
                String::new(),
                String::new(),
                *timeout_seconds,
            ))
        }
    }
}

#[cfg(test)]
#[expect(
    clippy::print_stderr,
    reason = "Tests may use eprintln! to report skip conditions"
)]
mod tests {
    use super::*;
    use crate::types::Hook;
    use tempfile::TempDir;

    /// Helper to set up CUENV_EXECUTABLE for tests that spawn the supervisor.
    /// The cuenv binary must already be built (via `cargo build --bin cuenv`).
    fn setup_cuenv_executable() -> Option<PathBuf> {
        // Check if already set
        if std::env::var("CUENV_EXECUTABLE").is_ok() {
            return Some(PathBuf::from(std::env::var("CUENV_EXECUTABLE").unwrap()));
        }

        // Try to find the cuenv binary in target/debug
        let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        let workspace_root = manifest_dir.parent()?.parent()?;
        let cuenv_binary = workspace_root.join("target/debug/cuenv");

        if cuenv_binary.exists() {
            // SAFETY: This is only called in tests where we control the environment.
            // No other threads should be accessing this environment variable.
            #[expect(
                unsafe_code,
                reason = "Test helper setting env var in controlled test environment"
            )]
            unsafe {
                std::env::set_var("CUENV_EXECUTABLE", &cuenv_binary);
            }
            Some(cuenv_binary)
        } else {
            None
        }
    }

    #[tokio::test]
    async fn test_hook_executor_creation() {
        let temp_dir = TempDir::new().unwrap();
        let config = HookExecutionConfig {
            default_timeout_seconds: 60,
            fail_fast: true,
            state_dir: Some(temp_dir.path().to_path_buf()),
        };

        let executor = HookExecutor::new(config).unwrap();
        assert_eq!(executor.config.default_timeout_seconds, 60);
    }

    #[tokio::test]
    async fn test_execute_single_hook_success() {
        let executor = HookExecutor::with_default_config().unwrap();

        let hook = Hook {
            order: 100,
            propagate: false,
            command: "echo".to_string(),
            args: vec!["hello".to_string()],
            dir: None,
            inputs: vec![],
            source: None,
        };

        let result = executor.execute_single_hook(hook).await.unwrap();
        assert!(result.success);
        assert!(result.stdout.contains("hello"));
    }

    #[tokio::test]
    async fn test_execute_single_hook_failure() {
        let executor = HookExecutor::with_default_config().unwrap();

        let hook = Hook {
            order: 100,
            propagate: false,
            command: "false".to_string(), // Command that always fails
            args: vec![],
            dir: None,
            inputs: Vec::new(),
            source: Some(false),
        };

        let result = executor.execute_single_hook(hook).await.unwrap();
        assert!(!result.success);
        assert!(result.exit_status.is_some());
        assert_ne!(result.exit_status.unwrap(), 0);
    }

    #[tokio::test]
    async fn test_execute_single_hook_timeout() {
        let temp_dir = TempDir::new().unwrap();
        let config = HookExecutionConfig {
            default_timeout_seconds: 1, // Set timeout to 1 second
            fail_fast: true,
            state_dir: Some(temp_dir.path().to_path_buf()),
        };
        let executor = HookExecutor::new(config).unwrap();

        let hook = Hook {
            order: 100,
            propagate: false,
            command: "sleep".to_string(),
            args: vec!["10".to_string()], // Sleep for 10 seconds
            dir: None,
            inputs: Vec::new(),
            source: Some(false),
        };

        let result = executor.execute_single_hook(hook).await.unwrap();
        assert!(!result.success);
        assert!(result.error.as_ref().unwrap().contains("timed out"));
    }

    #[tokio::test]
    async fn test_background_execution() {
        let temp_dir = TempDir::new().unwrap();
        let config = HookExecutionConfig {
            default_timeout_seconds: 30,
            fail_fast: true,
            state_dir: Some(temp_dir.path().to_path_buf()),
        };

        let executor = HookExecutor::new(config).unwrap();
        let directory_path = PathBuf::from("/test/directory");
        let config_hash = "test_hash".to_string();

        let hooks = vec![
            Hook {
                order: 100,
                propagate: false,
                command: "echo".to_string(),
                args: vec!["hook1".to_string()],
                dir: None,
                inputs: Vec::new(),
                source: Some(false),
            },
            Hook {
                order: 100,
                propagate: false,
                command: "echo".to_string(),
                args: vec!["hook2".to_string()],
                dir: None,
                inputs: Vec::new(),
                source: Some(false),
            },
        ];

        let result = executor
            .execute_hooks_background(directory_path.clone(), config_hash.clone(), hooks)
            .await
            .unwrap();

        assert!(result.contains("Started execution of 2 hooks"));

        // Wait a bit for background execution to start
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Check execution status
        let status = executor
            .get_execution_status_for_instance(&directory_path, &config_hash)
            .await
            .unwrap();
        assert!(status.is_some());

        let state = status.unwrap();
        assert_eq!(state.total_hooks, 2);
        assert_eq!(state.directory_path, directory_path);
    }

    #[tokio::test]
    async fn test_command_validation() {
        let executor = HookExecutor::with_default_config().unwrap();

        // Commands are no longer validated against a whitelist
        // The approval mechanism is the security boundary

        // Test that echo command works with any arguments
        let hook = Hook {
            order: 100,
            propagate: false,
            command: "echo".to_string(),
            args: vec!["test message".to_string()],
            dir: None,
            inputs: Vec::new(),
            source: Some(false),
        };

        let result = executor.execute_single_hook(hook).await;
        assert!(result.is_ok(), "Echo command should succeed");

        // Verify the output contains the expected message
        let hook_result = result.unwrap();
        assert!(hook_result.stdout.contains("test message"));
    }

    #[tokio::test]
    async fn test_cancellation() {
        // Skip if cuenv binary is not available
        if setup_cuenv_executable().is_none() {
            eprintln!("Skipping test_cancellation: cuenv binary not found");
            return;
        }

        let temp_dir = TempDir::new().unwrap();
        let config = HookExecutionConfig {
            default_timeout_seconds: 30,
            fail_fast: false,
            state_dir: Some(temp_dir.path().to_path_buf()),
        };

        let executor = HookExecutor::new(config).unwrap();
        let directory_path = PathBuf::from("/test/cancel");
        let config_hash = "cancel_test".to_string();

        // Create a long-running hook
        let hooks = vec![Hook {
            order: 100,
            propagate: false,
            command: "sleep".to_string(),
            args: vec!["10".to_string()],
            dir: None,
            inputs: Vec::new(),
            source: Some(false),
        }];

        executor
            .execute_hooks_background(directory_path.clone(), config_hash.clone(), hooks)
            .await
            .unwrap();

        // Wait for supervisor to actually start and create state
        // Poll until we see Running status or timeout
        let mut started = false;
        for _ in 0..20 {
            tokio::time::sleep(Duration::from_millis(100)).await;
            if let Ok(Some(state)) = executor
                .get_execution_status_for_instance(&directory_path, &config_hash)
                .await
                && state.status == ExecutionStatus::Running
            {
                started = true;
                break;
            }
        }

        if !started {
            eprintln!("Warning: Supervisor didn't start in time, skipping cancellation test");
            return;
        }

        // Cancel the execution
        let cancelled = executor
            .cancel_execution(
                &directory_path,
                &config_hash,
                Some("User cancelled".to_string()),
            )
            .await
            .unwrap();
        assert!(cancelled);

        // Check that state reflects cancellation
        let state = executor
            .get_execution_status_for_instance(&directory_path, &config_hash)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(state.status, ExecutionStatus::Cancelled);
    }

    #[tokio::test]
    async fn test_large_output_handling() {
        let executor = HookExecutor::with_default_config().unwrap();

        // Generate a large output using printf repeating a pattern
        // Create a large string in the environment variable instead
        let large_content = "x".repeat(1000); // 1KB per line
        let mut args = Vec::new();
        // Generate 100 lines of 1KB each = 100KB total
        for i in 0..100 {
            args.push(format!("Line {}: {}", i, large_content));
        }

        // Use echo with multiple arguments
        let hook = Hook {
            order: 100,
            propagate: false,
            command: "echo".to_string(),
            args,
            dir: None,
            inputs: Vec::new(),
            source: Some(false),
        };

        let result = executor.execute_single_hook(hook).await.unwrap();
        assert!(result.success);
        // Output should be captured without causing memory issues
        assert!(result.stdout.len() > 50_000); // At least 50KB of output
    }

    #[tokio::test]
    async fn test_state_cleanup() {
        // Skip if cuenv binary is not available
        if setup_cuenv_executable().is_none() {
            eprintln!("Skipping test_state_cleanup: cuenv binary not found");
            return;
        }

        let temp_dir = TempDir::new().unwrap();
        let config = HookExecutionConfig {
            default_timeout_seconds: 30,
            fail_fast: false,
            state_dir: Some(temp_dir.path().to_path_buf()),
        };

        let executor = HookExecutor::new(config).unwrap();
        let directory_path = PathBuf::from("/test/cleanup");
        let config_hash = "cleanup_test".to_string();

        // Execute some hooks
        let hooks = vec![Hook {
            order: 100,
            propagate: false,
            command: "echo".to_string(),
            args: vec!["test".to_string()],
            dir: None,
            inputs: Vec::new(),
            source: Some(false),
        }];

        executor
            .execute_hooks_background(directory_path.clone(), config_hash.clone(), hooks)
            .await
            .unwrap();

        // Poll until state exists before waiting for completion
        let mut state_exists = false;
        for _ in 0..20 {
            tokio::time::sleep(Duration::from_millis(100)).await;
            if executor
                .get_execution_status_for_instance(&directory_path, &config_hash)
                .await
                .unwrap()
                .is_some()
            {
                state_exists = true;
                break;
            }
        }

        if !state_exists {
            eprintln!("Warning: State never created, skipping cleanup test");
            return;
        }

        // Wait for completion
        if let Err(e) = executor
            .wait_for_completion(&directory_path, &config_hash, Some(15))
            .await
        {
            eprintln!(
                "Warning: wait_for_completion timed out: {}, skipping test",
                e
            );
            return;
        }

        // Clean up old states (should clean up the completed state)
        let cleaned = executor
            .cleanup_old_states(chrono::Duration::seconds(0))
            .await
            .unwrap();
        assert_eq!(cleaned, 1);

        // State should be gone
        let state = executor
            .get_execution_status_for_instance(&directory_path, &config_hash)
            .await
            .unwrap();
        assert!(state.is_none());
    }

    #[tokio::test]
    async fn test_execution_state_tracking() {
        let temp_dir = TempDir::new().unwrap();
        let config = HookExecutionConfig {
            default_timeout_seconds: 30,
            fail_fast: true,
            state_dir: Some(temp_dir.path().to_path_buf()),
        };

        let executor = HookExecutor::new(config).unwrap();
        let directory_path = PathBuf::from("/test/directory");
        let config_hash = "hash".to_string();

        // Initially no state
        let status = executor
            .get_execution_status_for_instance(&directory_path, &config_hash)
            .await
            .unwrap();
        assert!(status.is_none());

        // Start execution
        let hooks = vec![Hook {
            order: 100,
            propagate: false,
            command: "echo".to_string(),
            args: vec!["test".to_string()],
            dir: None,
            inputs: Vec::new(),
            source: Some(false),
        }];

        executor
            .execute_hooks_background(directory_path.clone(), config_hash.clone(), hooks)
            .await
            .unwrap();

        // Should now have state
        let status = executor
            .get_execution_status_for_instance(&directory_path, &config_hash)
            .await
            .unwrap();
        assert!(status.is_some());
    }

    #[tokio::test]
    async fn test_working_directory_handling() {
        let executor = HookExecutor::with_default_config().unwrap();
        let temp_dir = TempDir::new().unwrap();

        // Test with valid working directory
        let hook_with_valid_dir = Hook {
            order: 100,
            propagate: false,
            command: "pwd".to_string(),
            args: vec![],
            dir: Some(temp_dir.path().to_string_lossy().to_string()),
            inputs: vec![],
            source: None,
        };

        let result = executor
            .execute_single_hook(hook_with_valid_dir)
            .await
            .unwrap();
        assert!(result.success);
        assert!(result.stdout.contains(temp_dir.path().to_str().unwrap()));

        // Test with non-existent working directory
        let hook_with_invalid_dir = Hook {
            order: 100,
            propagate: false,
            command: "pwd".to_string(),
            args: vec![],
            dir: Some("/nonexistent/directory/that/does/not/exist".to_string()),
            inputs: vec![],
            source: None,
        };

        let result = executor.execute_single_hook(hook_with_invalid_dir).await;
        // This might succeed or fail depending on the implementation
        // The important part is it doesn't panic
        if let Ok(output) = result {
            // If it succeeds, the command might have handled the missing directory
            assert!(
                !output
                    .stdout
                    .contains("/nonexistent/directory/that/does/not/exist")
            );
        }
    }

    #[tokio::test]
    async fn test_hook_execution_with_complex_output() {
        let executor = HookExecutor::with_default_config().unwrap();

        // Test simple hooks without dangerous characters
        let hook = Hook {
            order: 100,
            propagate: false,
            command: "echo".to_string(),
            args: vec!["stdout output".to_string()],
            dir: None,
            inputs: vec![],
            source: None,
        };

        let result = executor.execute_single_hook(hook).await.unwrap();
        assert!(result.success);
        assert!(result.stdout.contains("stdout output"));

        // Test hook with non-zero exit code (using false command)
        let hook_with_exit_code = Hook {
            order: 100,
            propagate: false,
            command: "false".to_string(),
            args: vec![],
            dir: None,
            inputs: Vec::new(),
            source: Some(false),
        };

        let result = executor
            .execute_single_hook(hook_with_exit_code)
            .await
            .unwrap();
        assert!(!result.success);
        // Exit code should be non-zero
        assert!(result.exit_status.is_some());
    }

    #[tokio::test]
    async fn test_state_dir_getter() {
        use crate::state::StateManager;

        let temp_dir = TempDir::new().unwrap();
        let state_dir = temp_dir.path().to_path_buf();
        let state_manager = StateManager::new(state_dir.clone());

        assert_eq!(state_manager.get_state_dir(), state_dir.as_path());
    }

    /// Test timeout behavior edge cases:
    /// - Verify that hooks are terminated after timeout
    /// - Verify error message includes timeout duration
    /// - Verify partial output is not captured on timeout
    #[tokio::test]
    async fn test_hook_timeout_behavior() {
        let temp_dir = TempDir::new().unwrap();

        // Test with very short timeout (1 second)
        let config = HookExecutionConfig {
            default_timeout_seconds: 1,
            fail_fast: true,
            state_dir: Some(temp_dir.path().to_path_buf()),
        };
        let executor = HookExecutor::new(config).unwrap();

        // Hook that sleeps longer than timeout
        let slow_hook = Hook {
            order: 100,
            propagate: false,
            command: "sleep".to_string(),
            args: vec!["30".to_string()],
            dir: None,
            inputs: Vec::new(),
            source: Some(false),
        };

        let result = executor.execute_single_hook(slow_hook).await.unwrap();

        // Verify timeout behavior
        assert!(!result.success, "Hook should fail due to timeout");
        assert!(
            result.error.is_some(),
            "Should have error message on timeout"
        );
        let error_msg = result.error.as_ref().unwrap();
        assert!(
            error_msg.contains("timed out"),
            "Error should mention timeout: {}",
            error_msg
        );
        assert!(
            error_msg.contains('1'),
            "Error should mention timeout duration: {}",
            error_msg
        );

        // Verify exit_status is None for timeout (process was killed)
        assert!(
            result.exit_status.is_none(),
            "Exit status should be None for timed out process"
        );

        // Test that timeout duration is roughly correct
        assert!(
            result.duration_ms >= 1000,
            "Duration should be at least 1 second"
        );
        assert!(
            result.duration_ms < 5000,
            "Duration should not be much longer than timeout"
        );
    }

    /// Test timeout with a hook that produces output before timing out
    #[tokio::test]
    async fn test_hook_timeout_with_partial_output() {
        let temp_dir = TempDir::new().unwrap();

        let config = HookExecutionConfig {
            default_timeout_seconds: 1,
            fail_fast: true,
            state_dir: Some(temp_dir.path().to_path_buf()),
        };
        let executor = HookExecutor::new(config).unwrap();

        // Hook that outputs something then sleeps
        // Using bash -c to chain commands
        let hook = Hook {
            order: 100,
            propagate: false,
            command: "bash".to_string(),
            args: vec!["-c".to_string(), "echo 'started'; sleep 30".to_string()],
            dir: None,
            inputs: Vec::new(),
            source: Some(false),
        };

        let result = executor.execute_single_hook(hook).await.unwrap();

        assert!(!result.success, "Hook should timeout");
        assert!(
            result.error.as_ref().unwrap().contains("timed out"),
            "Should indicate timeout"
        );
    }

    /// Test concurrent hook isolation: multiple hooks executing in parallel
    /// should not interfere with each other's state or environment
    #[tokio::test]
    async fn test_concurrent_hook_isolation() {
        use std::sync::Arc;
        use tokio::task::JoinSet;

        let temp_dir = TempDir::new().unwrap();
        let config = HookExecutionConfig {
            default_timeout_seconds: 30,
            fail_fast: false,
            state_dir: Some(temp_dir.path().to_path_buf()),
        };
        let executor = Arc::new(HookExecutor::new(config).unwrap());

        let mut join_set = JoinSet::new();

        // Spawn multiple hooks concurrently with unique identifiers
        for i in 0..5 {
            let executor = executor.clone();
            let unique_id = format!("hook_{}", i);

            join_set.spawn(async move {
                let hook = Hook {
                    order: 100,
                    propagate: false,
                    command: "bash".to_string(),
                    args: vec![
                        "-c".to_string(),
                        format!(
                            "echo 'ID:{}'; sleep 0.1; echo 'DONE:{}'",
                            unique_id, unique_id
                        ),
                    ],
                    dir: None,
                    inputs: Vec::new(),
                    source: Some(false),
                };

                let result = executor.execute_single_hook(hook).await.unwrap();
                (i, result)
            });
        }

        // Collect all results
        let mut results = Vec::new();
        while let Some(result) = join_set.join_next().await {
            results.push(result.unwrap());
        }

        // Verify each hook completed successfully and output is isolated
        assert_eq!(results.len(), 5, "All 5 hooks should complete");

        for (i, result) in results {
            assert!(result.success, "Hook {} should succeed", i);

            let expected_id = format!("hook_{}", i);
            assert!(
                result.stdout.contains(&format!("ID:{}", expected_id)),
                "Hook {} output should contain its ID. Got: {}",
                i,
                result.stdout
            );
            assert!(
                result.stdout.contains(&format!("DONE:{}", expected_id)),
                "Hook {} output should contain its DONE marker. Got: {}",
                i,
                result.stdout
            );

            // Verify no cross-contamination: output should not contain other hook IDs
            for j in 0..5 {
                if j != i {
                    let other_id = format!("hook_{}", j);
                    assert!(
                        !result.stdout.contains(&format!("ID:{}", other_id)),
                        "Hook {} output should not contain hook {} ID",
                        i,
                        j
                    );
                }
            }
        }
    }

    /// Test environment variable capture with special characters including:
    /// - Multiline values
    /// - Unicode characters
    /// - Special shell characters (quotes, backslashes, etc.)
    #[tokio::test]
    async fn test_environment_capture_special_chars() {
        // Test multiline environment variable values
        let multiline_script = r"
export MULTILINE_VAR='line1
line2
line3'
";

        let result = evaluate_shell_environment(multiline_script, &HashMap::new()).await;
        assert!(result.is_ok(), "Should parse multiline env vars");

        let (env_vars, _removed) = result.unwrap();
        if let Some(value) = env_vars.get("MULTILINE_VAR") {
            assert!(
                value.contains("line1"),
                "Should contain first line: {}",
                value
            );
            assert!(
                value.contains("line2"),
                "Should contain second line: {}",
                value
            );
        }

        // Test Unicode characters
        let unicode_script = r"
export UNICODE_VAR='Hello 世界 🌍 émoji'
export CHINESE_VAR='中文测试'
export JAPANESE_VAR='日本語テスト'
";

        let result = evaluate_shell_environment(unicode_script, &HashMap::new()).await;
        assert!(result.is_ok(), "Should parse unicode env vars");

        let (env_vars, _removed) = result.unwrap();
        if let Some(value) = env_vars.get("UNICODE_VAR") {
            assert!(
                value.contains("世界"),
                "Should preserve Chinese characters: {}",
                value
            );
            assert!(value.contains("🌍"), "Should preserve emoji: {}", value);
        }

        // Test special shell characters
        let special_chars_script = r#"
export QUOTED_VAR="value with 'single' and \"double\" quotes"
export PATH_VAR="/usr/local/bin:/usr/bin:/bin"
export EQUALS_VAR="key=value=another"
"#;

        let result = evaluate_shell_environment(special_chars_script, &HashMap::new()).await;
        assert!(result.is_ok(), "Should parse special chars");

        let (env_vars, _removed) = result.unwrap();
        if let Some(value) = env_vars.get("EQUALS_VAR") {
            assert!(
                value.contains("key=value=another"),
                "Should preserve equals signs: {}",
                value
            );
        }
    }

    /// Test environment capture with empty and whitespace-only values
    #[tokio::test]
    async fn test_environment_capture_edge_cases() {
        // Test empty value
        let empty_script = r"
export EMPTY_VAR=''
export SPACE_VAR='   '
";

        let result = evaluate_shell_environment(empty_script, &HashMap::new()).await;
        assert!(result.is_ok(), "Should handle empty/whitespace values");
        let (_env_vars, _removed) = result.unwrap();

        // Test very long value
        let long_value = "x".repeat(10000);
        let long_script = format!("export LONG_VAR='{}'", long_value);

        let result = evaluate_shell_environment(&long_script, &HashMap::new()).await;
        assert!(result.is_ok(), "Should handle very long values");

        let (env_vars, _removed) = result.unwrap();
        if let Some(value) = env_vars.get("LONG_VAR") {
            assert_eq!(value.len(), 10000, "Should preserve full length");
        }
    }

    /// Test that prior_env is passed through to child shells and that unset propagation works
    #[tokio::test]
    async fn test_environment_prior_env_chaining() {
        // Test 1: prior_env variables are visible and can be extended
        let mut prior_env = HashMap::new();
        prior_env.insert("CUENV_TEST_PRIOR".to_string(), "original_value".to_string());

        let script = r#"export CUENV_TEST_PRIOR="extended_${CUENV_TEST_PRIOR}""#;
        let result = evaluate_shell_environment(script, &prior_env).await;
        assert!(
            result.is_ok(),
            "Should evaluate with prior_env: {:?}",
            result.as_ref().err()
        );

        let (env_vars, _removed) = result.unwrap();
        if let Some(value) = env_vars.get("CUENV_TEST_PRIOR") {
            assert!(
                value.contains("extended_"),
                "Value should contain extended_ prefix: {}",
                value
            );
            assert!(
                value.contains("original_value"),
                "Value should contain original_value from prior_env: {}",
                value
            );
        } else {
            panic!("CUENV_TEST_PRIOR should be in env_vars delta since it was modified");
        }

        // Test 2: unsetting a prior_env variable is reported in removed_keys
        let mut prior_env = HashMap::new();
        prior_env.insert("CUENV_TEST_REMOVE".to_string(), "bar".to_string());

        let script = "unset CUENV_TEST_REMOVE";
        let result = evaluate_shell_environment(script, &prior_env).await;
        assert!(result.is_ok(), "Should evaluate unset script");

        let (env_vars, removed) = result.unwrap();
        assert!(
            !env_vars.contains_key("CUENV_TEST_REMOVE"),
            "Unset variable should not appear in env_vars"
        );
        assert!(
            removed.contains(&"CUENV_TEST_REMOVE".to_string()),
            "Unset variable should appear in removed_keys: {:?}",
            removed
        );
    }

    /// Test that hooks with different working directories are isolated
    #[tokio::test]
    async fn test_working_directory_isolation() {
        let executor = HookExecutor::with_default_config().unwrap();

        // Create two temp directories
        let temp_dir1 = TempDir::new().unwrap();
        let temp_dir2 = TempDir::new().unwrap();

        // Write unique files to each directory
        std::fs::write(temp_dir1.path().join("marker.txt"), "dir1").unwrap();
        std::fs::write(temp_dir2.path().join("marker.txt"), "dir2").unwrap();

        // Hook that reads the marker file in its working directory
        let hook1 = Hook {
            order: 100,
            propagate: false,
            command: "cat".to_string(),
            args: vec!["marker.txt".to_string()],
            dir: Some(temp_dir1.path().to_string_lossy().to_string()),
            inputs: vec![],
            source: None,
        };

        let hook2 = Hook {
            order: 100,
            propagate: false,
            command: "cat".to_string(),
            args: vec!["marker.txt".to_string()],
            dir: Some(temp_dir2.path().to_string_lossy().to_string()),
            inputs: vec![],
            source: None,
        };

        let result1 = executor.execute_single_hook(hook1).await.unwrap();
        let result2 = executor.execute_single_hook(hook2).await.unwrap();

        assert!(result1.success, "Hook 1 should succeed");
        assert!(result2.success, "Hook 2 should succeed");

        assert!(
            result1.stdout.contains("dir1"),
            "Hook 1 should read from dir1: {}",
            result1.stdout
        );
        assert!(
            result2.stdout.contains("dir2"),
            "Hook 2 should read from dir2: {}",
            result2.stdout
        );
    }

    /// Test hook execution with stderr output
    #[tokio::test]
    async fn test_stderr_capture() {
        let executor = HookExecutor::with_default_config().unwrap();

        // Hook that writes to both stdout and stderr
        let hook = Hook {
            order: 100,
            propagate: false,
            command: "bash".to_string(),
            args: vec![
                "-c".to_string(),
                "echo 'to stdout'; echo 'to stderr' >&2".to_string(),
            ],
            dir: None,
            inputs: vec![],
            source: None,
        };

        let result = executor.execute_single_hook(hook).await.unwrap();

        assert!(result.success, "Hook should succeed");
        assert!(
            result.stdout.contains("to stdout"),
            "Should capture stdout: {}",
            result.stdout
        );
        assert!(
            result.stderr.contains("to stderr"),
            "Should capture stderr: {}",
            result.stderr
        );
    }

    /// Test that hooks handle binary output gracefully
    #[tokio::test]
    async fn test_binary_output_handling() {
        let executor = HookExecutor::with_default_config().unwrap();

        // Hook that outputs some binary-like data (null bytes will be lossy-converted)
        let hook = Hook {
            order: 100,
            propagate: false,
            command: "bash".to_string(),
            args: vec!["-c".to_string(), "printf 'hello\\x00world'".to_string()],
            dir: None,
            inputs: vec![],
            source: None,
        };

        let result = executor.execute_single_hook(hook).await.unwrap();

        // Should complete without panic even with binary output
        assert!(result.success, "Hook should succeed");
        // Output will contain replacement character for null byte
        assert!(
            result.stdout.contains("hello") && result.stdout.contains("world"),
            "Should contain text parts: {}",
            result.stdout
        );
    }

    #[tokio::test]
    async fn test_capture_source_environment_returns_resulting_env() {
        let hook = Hook {
            order: 100,
            propagate: false,
            command: "bash".to_string(),
            args: vec![
                "-c".to_string(),
                "printf '%s\n' 'export CUENV_RUNTIME_TEST=from_runtime'".to_string(),
            ],
            dir: None,
            inputs: vec![],
            source: Some(true),
        };

        let environment = capture_source_environment(hook, &HashMap::new(), 5)
            .await
            .unwrap();

        assert_eq!(
            environment.get("CUENV_RUNTIME_TEST"),
            Some(&"from_runtime".to_string())
        );
    }
}