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
//! State management for hook execution tracking

use crate::types::{ExecutionStatus, Hook, HookResult};
use crate::{Error, Result};
use chrono::{DateTime, Utc};
#[allow(unused_imports)] // Used by load_state_sync for file locking
use fs4::fs_std::FileExt as SyncFileExt;
use fs4::tokio::AsyncFileExt;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::Read;
use std::path::{Path, PathBuf};
use tokio::fs;
use tokio::fs::OpenOptions;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tracing::{debug, error, info, warn};

/// Manages persistent state for hook execution sessions
#[derive(Debug, Clone)]
pub struct StateManager {
    state_dir: PathBuf,
}

impl StateManager {
    /// Create a new state manager with the specified state directory
    #[must_use]
    pub fn new(state_dir: PathBuf) -> Self {
        Self { state_dir }
    }

    /// Get the default state directory.
    ///
    /// Uses platform-appropriate paths:
    /// - Linux: `~/.local/state/cuenv/hooks`
    /// - macOS: `~/Library/Application Support/cuenv/hooks`
    /// - Windows: `%APPDATA%\cuenv\hooks`
    pub fn default_state_dir() -> Result<PathBuf> {
        let base = dirs::state_dir()
            .or_else(dirs::data_dir)
            .ok_or_else(|| Error::configuration("Could not determine state directory"))?;
        Ok(base.join("cuenv").join("hooks"))
    }

    /// Create a state manager using the default state directory
    pub fn with_default_dir() -> Result<Self> {
        Ok(Self::new(Self::default_state_dir()?))
    }

    /// Get the state directory path
    #[must_use]
    pub fn get_state_dir(&self) -> &Path {
        &self.state_dir
    }

    /// Ensure the state directory exists
    pub async fn ensure_state_dir(&self) -> Result<()> {
        if !self.state_dir.exists() {
            fs::create_dir_all(&self.state_dir)
                .await
                .map_err(|e| Error::Io {
                    source: e,
                    path: Some(self.state_dir.clone().into_boxed_path()),
                    operation: "create_dir_all".to_string(),
                })?;
            debug!("Created state directory: {}", self.state_dir.display());
        }
        Ok(())
    }

    /// Generate a state file path for a given directory hash
    fn state_file_path(&self, instance_hash: &str) -> PathBuf {
        self.state_dir.join(format!("{}.json", instance_hash))
    }

    /// Get the state file path for a given directory hash (public for PID files)
    #[must_use]
    pub fn get_state_file_path(&self, instance_hash: &str) -> PathBuf {
        self.state_dir.join(format!("{}.json", instance_hash))
    }

    /// Save execution state to disk with atomic write and locking
    pub async fn save_state(&self, state: &HookExecutionState) -> Result<()> {
        self.ensure_state_dir().await?;

        let state_file = self.state_file_path(&state.instance_hash);
        let json = serde_json::to_string_pretty(state)
            .map_err(|e| Error::serialization(format!("Failed to serialize state: {e}")))?;

        // Write to a temporary file first, then rename atomically
        let temp_path = state_file.with_extension("tmp");

        // Open temp file with exclusive lock for writing
        let mut file = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&temp_path)
            .await
            .map_err(|e| Error::Io {
                source: e,
                path: Some(temp_path.clone().into_boxed_path()),
                operation: "open".to_string(),
            })?;

        // Acquire exclusive lock (only one writer allowed)
        file.lock_exclusive().map_err(|e| {
            Error::configuration(format!(
                "Failed to acquire exclusive lock on state temp file: {}",
                e
            ))
        })?;

        file.write_all(json.as_bytes())
            .await
            .map_err(|e| Error::Io {
                source: e,
                path: Some(temp_path.clone().into_boxed_path()),
                operation: "write_all".to_string(),
            })?;

        file.sync_all().await.map_err(|e| Error::Io {
            source: e,
            path: Some(temp_path.clone().into_boxed_path()),
            operation: "sync_all".to_string(),
        })?;

        // Unlock happens automatically when file is dropped
        drop(file);

        // Atomically rename temp file to final location
        fs::rename(&temp_path, &state_file)
            .await
            .map_err(|e| Error::Io {
                source: e,
                path: Some(state_file.clone().into_boxed_path()),
                operation: "rename".to_string(),
            })?;

        debug!(
            "Saved execution state for directory hash: {}",
            state.instance_hash
        );
        Ok(())
    }

    /// Load execution state from disk with shared locking
    pub async fn load_state(&self, instance_hash: &str) -> Result<Option<HookExecutionState>> {
        let state_file = self.state_file_path(instance_hash);

        if !state_file.exists() {
            return Ok(None);
        }

        // Open file with shared lock for reading
        let mut file = match OpenOptions::new().read(true).open(&state_file).await {
            Ok(f) => f,
            Err(e) => {
                // File might have been deleted between exists check and open
                if e.kind() == std::io::ErrorKind::NotFound {
                    return Ok(None);
                }
                return Err(Error::Io {
                    source: e,
                    path: Some(state_file.clone().into_boxed_path()),
                    operation: "open".to_string(),
                });
            }
        };

        // Acquire shared lock (multiple readers allowed)
        file.lock_shared().map_err(|e| {
            Error::configuration(format!(
                "Failed to acquire shared lock on state file: {}",
                e
            ))
        })?;

        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .await
            .map_err(|e| Error::Io {
                source: e,
                path: Some(state_file.clone().into_boxed_path()),
                operation: "read_to_string".to_string(),
            })?;

        // Unlock happens automatically when file is dropped
        drop(file);

        let state: HookExecutionState = serde_json::from_str(&contents)
            .map_err(|e| Error::serialization(format!("Failed to deserialize state: {e}")))?;

        debug!(
            "Loaded execution state for directory hash: {}",
            instance_hash
        );
        Ok(Some(state))
    }

    /// Remove state file for a directory
    pub async fn remove_state(&self, instance_hash: &str) -> Result<()> {
        let state_file = self.state_file_path(instance_hash);

        if state_file.exists() {
            fs::remove_file(&state_file).await.map_err(|e| Error::Io {
                source: e,
                path: Some(state_file.into_boxed_path()),
                operation: "remove_file".to_string(),
            })?;
            debug!(
                "Removed execution state for directory hash: {}",
                instance_hash
            );
        }

        Ok(())
    }

    /// List all active execution states
    pub async fn list_active_states(&self) -> Result<Vec<HookExecutionState>> {
        if !self.state_dir.exists() {
            return Ok(Vec::new());
        }

        let mut states = Vec::new();
        let mut dir = fs::read_dir(&self.state_dir).await.map_err(|e| Error::Io {
            source: e,
            path: Some(self.state_dir.clone().into_boxed_path()),
            operation: "read_dir".to_string(),
        })?;

        while let Some(entry) = dir.next_entry().await.map_err(|e| Error::Io {
            source: e,
            path: Some(self.state_dir.clone().into_boxed_path()),
            operation: "next_entry".to_string(),
        })? {
            let path = entry.path();
            if path.extension().and_then(|s| s.to_str()) == Some("json")
                && let Some(stem) = path.file_stem().and_then(|s| s.to_str())
                && let Ok(Some(state)) = self.load_state(stem).await
            {
                states.push(state);
            }
        }

        Ok(states)
    }

    // ========================================================================
    // Directory Marker System - Fast status lookups without config hash
    // ========================================================================

    /// Compute a key for directory-only lookups (used for fast status checks).
    /// This hashes just the canonicalized directory path, without config hash.
    #[must_use]
    pub fn compute_directory_key(path: &Path) -> String {
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
        hasher.update(canonical.to_string_lossy().as_bytes());
        format!("{:x}", hasher.finalize())[..16].to_string()
    }

    /// Get the path for a directory marker file
    fn directory_marker_path(&self, directory_key: &str) -> PathBuf {
        self.state_dir.join(format!("{}.marker", directory_key))
    }

    /// Create a marker file linking directory to instance hash.
    /// Called when hooks start to enable fast status lookups.
    pub async fn create_directory_marker(
        &self,
        directory_path: &Path,
        instance_hash: &str,
    ) -> Result<()> {
        self.ensure_state_dir().await?;
        let dir_key = Self::compute_directory_key(directory_path);
        let marker_path = self.directory_marker_path(&dir_key);

        fs::write(&marker_path, instance_hash)
            .await
            .map_err(|e| Error::Io {
                source: e,
                path: Some(marker_path.into_boxed_path()),
                operation: "write_marker".to_string(),
            })?;

        debug!(
            "Created directory marker for {} -> {}",
            directory_path.display(),
            instance_hash
        );
        Ok(())
    }

    /// Remove marker file for a directory.
    /// Called when hooks complete/fail and display timeout expires.
    pub async fn remove_directory_marker(&self, directory_path: &Path) -> Result<()> {
        let dir_key = Self::compute_directory_key(directory_path);
        let marker_path = self.directory_marker_path(&dir_key);

        if marker_path.exists() {
            fs::remove_file(&marker_path).await.ok(); // Ignore errors
            debug!("Removed directory marker for {}", directory_path.display());
        }
        Ok(())
    }

    /// Fast synchronous check: does a marker exist for this directory?
    /// This is the hot path for Starship - just a single stat() syscall.
    #[must_use]
    pub fn has_active_marker(&self, directory_path: &Path) -> bool {
        let dir_key = Self::compute_directory_key(directory_path);
        self.directory_marker_path(&dir_key).exists()
    }

    /// Read the instance hash from a marker file (if it exists).
    pub async fn get_marker_instance_hash(&self, directory_path: &Path) -> Option<String> {
        let dir_key = Self::compute_directory_key(directory_path);
        let marker_path = self.directory_marker_path(&dir_key);
        fs::read_to_string(&marker_path)
            .await
            .ok()
            .map(|s| s.trim().to_string())
    }

    // ========================================================================
    // Synchronous Methods (for fast path - no tokio runtime required)
    // ========================================================================

    /// Read the instance hash from a marker file synchronously.
    /// This is the sync equivalent of `get_marker_instance_hash` for the fast path.
    #[must_use]
    pub fn get_marker_instance_hash_sync(&self, directory_path: &Path) -> Option<String> {
        let dir_key = Self::compute_directory_key(directory_path);
        let marker_path = self.directory_marker_path(&dir_key);
        std::fs::read_to_string(&marker_path)
            .ok()
            .map(|s| s.trim().to_string())
    }

    /// Load execution state from disk synchronously with shared locking.
    /// This is the sync equivalent of `load_state` for the fast path.
    pub fn load_state_sync(&self, instance_hash: &str) -> Result<Option<HookExecutionState>> {
        let state_file = self.state_file_path(instance_hash);

        if !state_file.exists() {
            return Ok(None);
        }

        // Open file with shared lock for reading
        let mut file = match std::fs::File::open(&state_file) {
            Ok(f) => f,
            Err(e) => {
                // File might have been deleted between exists check and open
                if e.kind() == std::io::ErrorKind::NotFound {
                    return Ok(None);
                }
                return Err(Error::Io {
                    source: e,
                    path: Some(state_file.clone().into_boxed_path()),
                    operation: "open".to_string(),
                });
            }
        };

        // Acquire shared lock (multiple readers allowed)
        file.lock_shared().map_err(|e| {
            Error::configuration(format!(
                "Failed to acquire shared lock on state file: {}",
                e
            ))
        })?;

        let mut contents = String::new();
        file.read_to_string(&mut contents).map_err(|e| Error::Io {
            source: e,
            path: Some(state_file.clone().into_boxed_path()),
            operation: "read_to_string".to_string(),
        })?;

        // Unlock happens automatically when file is dropped
        drop(file);

        let state: HookExecutionState = serde_json::from_str(&contents)
            .map_err(|e| Error::serialization(format!("Failed to deserialize state: {e}")))?;

        Ok(Some(state))
    }

    // ========================================================================
    // Cleanup Methods
    // ========================================================================

    /// Clean up the entire state directory
    pub async fn cleanup_state_directory(&self) -> Result<usize> {
        if !self.state_dir.exists() {
            return Ok(0);
        }

        let mut cleaned_count = 0;
        let mut dir = fs::read_dir(&self.state_dir).await.map_err(|e| Error::Io {
            source: e,
            path: Some(self.state_dir.clone().into_boxed_path()),
            operation: "read_dir".to_string(),
        })?;

        while let Some(entry) = dir.next_entry().await.map_err(|e| Error::Io {
            source: e,
            path: Some(self.state_dir.clone().into_boxed_path()),
            operation: "next_entry".to_string(),
        })? {
            let path = entry.path();

            let extension = path.extension().and_then(|s| s.to_str());

            // Clean up JSON state files
            if extension == Some("json") {
                if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                    match self.load_state(stem).await {
                        Ok(Some(state)) if state.is_complete() => {
                            // Remove completed states and their markers
                            if let Err(e) = fs::remove_file(&path).await {
                                warn!("Failed to remove state file {}: {}", path.display(), e);
                            } else {
                                cleaned_count += 1;
                                debug!("Cleaned up state file: {}", path.display());
                                // Also remove the directory marker
                                self.remove_directory_marker(&state.directory_path)
                                    .await
                                    .ok();
                            }
                        }
                        Ok(Some(_)) => {
                            // Keep running states
                            debug!("Keeping active state file: {}", path.display());
                        }
                        Ok(None) => {}
                        Err(e) => {
                            // If we can't parse it, it might be corrupted - remove it
                            warn!("Failed to parse state file {}: {}", path.display(), e);
                            if let Err(rm_err) = fs::remove_file(&path).await {
                                error!(
                                    "Failed to remove corrupted state file {}: {}",
                                    path.display(),
                                    rm_err
                                );
                            } else {
                                cleaned_count += 1;
                                info!("Removed corrupted state file: {}", path.display());
                            }
                        }
                    }
                }
            }
            // Clean up orphaned marker files (markers without corresponding state)
            else if extension == Some("marker")
                && let Ok(instance_hash) = fs::read_to_string(&path).await
            {
                let instance_hash = instance_hash.trim();
                // Check if corresponding state exists
                match self.load_state(instance_hash).await {
                    Ok(None) => {
                        // State doesn't exist, remove orphaned marker
                        if fs::remove_file(&path).await.is_ok() {
                            cleaned_count += 1;
                            debug!("Cleaned up orphaned marker: {}", path.display());
                        }
                    }
                    Ok(Some(state)) if state.is_complete() && !state.should_display_completed() => {
                        // State is complete and expired, remove marker
                        if fs::remove_file(&path).await.is_ok() {
                            cleaned_count += 1;
                            debug!("Cleaned up expired marker: {}", path.display());
                        }
                    }
                    _ => {} // Keep marker
                }
            }
        }

        if cleaned_count > 0 {
            info!(
                "Cleaned up {} state/marker files from directory",
                cleaned_count
            );
        }

        Ok(cleaned_count)
    }

    /// Clean up orphaned state files (states without corresponding processes)
    pub async fn cleanup_orphaned_states(&self, max_age: chrono::Duration) -> Result<usize> {
        let cutoff = Utc::now() - max_age;
        let mut cleaned_count = 0;

        for state in self.list_active_states().await? {
            // Remove states that are stuck in running but are too old
            if state.status == ExecutionStatus::Running && state.started_at < cutoff {
                warn!(
                    "Found orphaned running state for {} (started {}), removing",
                    state.directory_path.display(),
                    state.started_at
                );
                self.remove_state(&state.instance_hash).await?;
                // Also remove the directory marker
                self.remove_directory_marker(&state.directory_path)
                    .await
                    .ok();
                cleaned_count += 1;
            }
        }

        if cleaned_count > 0 {
            info!("Cleaned up {} orphaned state files", cleaned_count);
        }

        Ok(cleaned_count)
    }
}

/// Represents the state of hook execution for a specific directory
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HookExecutionState {
    /// Hash combining directory path and config (instance identifier)
    pub instance_hash: String,
    /// Path to the directory being processed
    pub directory_path: PathBuf,
    /// Hash of the configuration that was approved
    pub config_hash: String,
    /// Current status of execution
    pub status: ExecutionStatus,
    /// Total number of hooks to execute
    pub total_hooks: usize,
    /// Number of hooks completed so far
    pub completed_hooks: usize,
    /// Index of currently executing hook (if any)
    pub current_hook_index: Option<usize>,
    /// The list of hooks being executed (for display purposes)
    #[serde(default)]
    pub hooks: Vec<Hook>,
    /// Results of completed hooks
    pub hook_results: HashMap<usize, HookResult>,
    /// Timestamp when execution started
    pub started_at: DateTime<Utc>,
    /// Timestamp when execution finished (if completed)
    pub finished_at: Option<DateTime<Utc>>,
    /// Timestamp when the current hook started (if running)
    pub current_hook_started_at: Option<DateTime<Utc>>,
    /// Timestamp until which completed state should be displayed
    pub completed_display_until: Option<DateTime<Utc>>,
    /// Error message if execution failed
    pub error_message: Option<String>,
    /// Environment variables captured from source hooks
    pub environment_vars: HashMap<String, String>,
    /// Previous environment variables (for diff/unset support)
    pub previous_env: Option<HashMap<String, String>>,
}

impl HookExecutionState {
    /// Create a new execution state
    #[must_use]
    pub fn new(
        directory_path: PathBuf,
        instance_hash: String,
        config_hash: String,
        hooks: Vec<Hook>,
    ) -> Self {
        let total_hooks = hooks.len();
        Self {
            instance_hash,
            directory_path,
            config_hash,
            status: ExecutionStatus::Running,
            total_hooks,
            completed_hooks: 0,
            current_hook_index: None,
            hooks,
            hook_results: HashMap::new(),
            started_at: Utc::now(),
            finished_at: None,
            current_hook_started_at: None,
            completed_display_until: None,
            error_message: None,
            environment_vars: HashMap::new(),
            previous_env: None,
        }
    }

    /// Mark a hook as currently executing
    pub fn mark_hook_running(&mut self, hook_index: usize) {
        self.current_hook_index = Some(hook_index);
        self.current_hook_started_at = Some(Utc::now());
        info!(
            "Started executing hook {} of {}",
            hook_index + 1,
            self.total_hooks
        );
    }

    /// Record the result of a hook execution
    #[expect(
        clippy::needless_pass_by_value,
        reason = "Takes ownership for API clarity, cloning is intentional"
    )]
    pub fn record_hook_result(&mut self, hook_index: usize, result: HookResult) {
        self.hook_results.insert(hook_index, result.clone());
        self.completed_hooks += 1;
        self.current_hook_index = None;
        self.current_hook_started_at = None;

        if result.success {
            info!(
                "Hook {} of {} completed successfully",
                hook_index + 1,
                self.total_hooks
            );
        } else {
            error!(
                "Hook {} of {} failed: {:?}",
                hook_index + 1,
                self.total_hooks,
                result.error
            );
            self.status = ExecutionStatus::Failed;
            self.error_message.clone_from(&result.error);
            self.finished_at = Some(Utc::now());
            // Keep failed state visible for 2 seconds (enough for at least one starship poll)
            self.completed_display_until = Some(Utc::now() + chrono::Duration::seconds(2));
            return;
        }

        // Check if all hooks are complete
        if self.completed_hooks == self.total_hooks {
            self.status = ExecutionStatus::Completed;
            let now = Utc::now();
            self.finished_at = Some(now);
            // Keep completed state visible for 2 seconds (enough for at least one starship poll)
            self.completed_display_until = Some(now + chrono::Duration::seconds(2));
            info!("All {} hooks completed successfully", self.total_hooks);
        }
    }

    /// Mark execution as cancelled
    pub fn mark_cancelled(&mut self, reason: Option<String>) {
        self.status = ExecutionStatus::Cancelled;
        self.finished_at = Some(Utc::now());
        self.error_message = reason;
        self.current_hook_index = None;
    }

    /// Check if execution is complete (success, failure, or cancelled)
    #[must_use]
    pub fn is_complete(&self) -> bool {
        matches!(
            self.status,
            ExecutionStatus::Completed | ExecutionStatus::Failed | ExecutionStatus::Cancelled
        )
    }

    /// Get a human-readable progress display
    #[must_use]
    pub fn progress_display(&self) -> String {
        match &self.status {
            ExecutionStatus::Running => {
                if let Some(current) = self.current_hook_index {
                    format!(
                        "Executing hook {} of {} ({})",
                        current + 1,
                        self.total_hooks,
                        self.status
                    )
                } else {
                    format!(
                        "{} of {} hooks completed",
                        self.completed_hooks, self.total_hooks
                    )
                }
            }
            ExecutionStatus::Completed => "All hooks completed successfully".to_string(),
            ExecutionStatus::Failed => {
                if let Some(error) = &self.error_message {
                    format!("Hook execution failed: {}", error)
                } else {
                    "Hook execution failed".to_string()
                }
            }
            ExecutionStatus::Cancelled => {
                if let Some(reason) = &self.error_message {
                    format!("Hook execution cancelled: {}", reason)
                } else {
                    "Hook execution cancelled".to_string()
                }
            }
        }
    }

    /// Get execution duration
    pub fn duration(&self) -> chrono::Duration {
        let end = self.finished_at.unwrap_or_else(Utc::now);
        end - self.started_at
    }

    /// Get current hook duration (if a hook is currently running)
    #[must_use]
    pub fn current_hook_duration(&self) -> Option<chrono::Duration> {
        self.current_hook_started_at
            .map(|started| Utc::now() - started)
    }

    /// Get the currently executing hook
    #[must_use]
    pub fn current_hook(&self) -> Option<&Hook> {
        self.current_hook_index.and_then(|idx| self.hooks.get(idx))
    }

    /// Format duration in human-readable format (e.g., "2.3s", "1m 15s", "2h 5m")
    #[must_use]
    pub fn format_duration(duration: chrono::Duration) -> String {
        let total_secs = duration.num_seconds();

        if total_secs < 60 {
            // Less than 1 minute: show as decimal seconds
            let millis = duration.num_milliseconds();
            // Precision loss is acceptable for display purposes
            #[expect(
                clippy::cast_precision_loss,
                reason = "Display formatting, precision loss is acceptable"
            )]
            let secs = millis as f64 / 1000.0;
            format!("{secs:.1}s")
        } else if total_secs < 3600 {
            // Less than 1 hour: show minutes and seconds
            let mins = total_secs / 60;
            let secs = total_secs % 60;
            if secs == 0 {
                format!("{}m", mins)
            } else {
                format!("{}m {}s", mins, secs)
            }
        } else {
            // 1 hour or more: show hours and minutes
            let hours = total_secs / 3600;
            let mins = (total_secs % 3600) / 60;
            if mins == 0 {
                format!("{}h", hours)
            } else {
                format!("{}h {}m", hours, mins)
            }
        }
    }

    /// Get a short description of the current or next hook for display
    #[must_use]
    pub fn current_hook_display(&self) -> Option<String> {
        // If there's a current hook index, use that
        let hook = if let Some(hook) = self.current_hook() {
            Some(hook)
        } else if self.status == ExecutionStatus::Running && self.completed_hooks < self.total_hooks
        {
            // If we're running but no current hook index yet, show the next hook to execute
            self.hooks.get(self.completed_hooks)
        } else {
            None
        };

        hook.map(|h| {
            // Extract just the command name (first part before any path separators)
            let cmd_name = h.command.split('/').next_back().unwrap_or(&h.command);

            // Format: just the command name (no args, to keep it concise)
            format!("`{}`", cmd_name)
        })
    }

    /// Check if the completed state should still be displayed
    #[must_use]
    pub fn should_display_completed(&self) -> bool {
        if let Some(display_until) = self.completed_display_until {
            Utc::now() < display_until
        } else {
            false
        }
    }
}

/// Compute a hash for a unique execution instance (directory + config)
#[must_use]
pub fn compute_instance_hash(path: &Path, config_hash: &str) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(path.to_string_lossy().as_bytes());
    hasher.update(b":");
    hasher.update(config_hash.as_bytes());
    // Include cuenv version in hash to invalidate cache on upgrades
    // This is important when internal logic (like environment capturing) changes
    hasher.update(b":");
    hasher.update(env!("CARGO_PKG_VERSION").as_bytes());
    format!("{:x}", hasher.finalize())[..16].to_string()
}

/// Compute a hash for hook execution that includes input file contents.
///
/// This is separate from the approval hash - approval only cares about the hook
/// definition, but execution cache needs to invalidate when input files change.
pub fn compute_execution_hash(hooks: &[Hook], base_dir: &Path) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();

    // Hash the hook definitions
    if let Ok(hooks_json) = serde_json::to_string(hooks) {
        hasher.update(hooks_json.as_bytes());
    }

    // Hash the contents of input files from each hook
    for hook in hooks {
        // Determine the working directory for this hook
        let hook_dir = hook
            .dir
            .as_ref()
            .map_or_else(|| base_dir.to_path_buf(), PathBuf::from);

        for input in &hook.inputs {
            let input_path = hook_dir.join(input);
            if let Ok(content) = std::fs::read(&input_path) {
                hasher.update(b"file:");
                hasher.update(input.as_bytes());
                hasher.update(b":");
                hasher.update(&content);
            }
        }
    }

    // Include cuenv version
    hasher.update(b":version:");
    hasher.update(env!("CARGO_PKG_VERSION").as_bytes());

    format!("{:x}", hasher.finalize())[..16].to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{Hook, HookResult};
    use std::collections::HashMap;
    use std::os::unix::process::ExitStatusExt;
    use std::sync::Arc;
    use std::time::Duration;
    use tempfile::TempDir;

    #[test]
    fn test_compute_instance_hash() {
        let path = Path::new("/test/path");
        let config_hash = "test_config";
        let hash = compute_instance_hash(path, config_hash);
        assert_eq!(hash.len(), 16);

        // Same path and config should produce same hash
        let hash2 = compute_instance_hash(path, config_hash);
        assert_eq!(hash, hash2);

        // Different path should produce different hash
        let different_path = Path::new("/other/path");
        let different_hash = compute_instance_hash(different_path, config_hash);
        assert_ne!(hash, different_hash);

        // Same path but different config should produce different hash
        let different_config_hash = compute_instance_hash(path, "different_config");
        assert_ne!(hash, different_config_hash);
    }

    #[tokio::test]
    async fn test_state_manager_operations() {
        let temp_dir = TempDir::new().unwrap();
        let state_manager = StateManager::new(temp_dir.path().to_path_buf());

        let directory_path = PathBuf::from("/test/dir");
        let config_hash = "test_config_hash".to_string();
        let instance_hash = compute_instance_hash(&directory_path, &config_hash);

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

        let mut state =
            HookExecutionState::new(directory_path, instance_hash.clone(), config_hash, hooks);

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

        // Load state back
        let loaded_state = state_manager
            .load_state(&instance_hash)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(loaded_state.instance_hash, state.instance_hash);
        assert_eq!(loaded_state.total_hooks, 2);
        assert_eq!(loaded_state.status, ExecutionStatus::Running);

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

        let result = HookResult::success(
            hook,
            std::process::ExitStatus::from_raw(0),
            "test\n".to_string(),
            String::new(),
            100,
        );

        state.record_hook_result(0, result);
        state_manager.save_state(&state).await.unwrap();

        // Load updated state
        let updated_state = state_manager
            .load_state(&instance_hash)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(updated_state.completed_hooks, 1);
        assert_eq!(updated_state.hook_results.len(), 1);

        // Remove state
        state_manager.remove_state(&instance_hash).await.unwrap();
        let removed_state = state_manager.load_state(&instance_hash).await.unwrap();
        assert!(removed_state.is_none());
    }

    #[test]
    fn test_hook_execution_state() {
        let directory_path = PathBuf::from("/test/dir");
        let instance_hash = "test_hash".to_string();
        let config_hash = "config_hash".to_string();
        let hooks = vec![
            Hook {
                order: 100,
                propagate: false,
                command: "echo".to_string(),
                args: vec!["test1".to_string()],
                dir: None,
                inputs: vec![],
                source: None,
            },
            Hook {
                order: 100,
                propagate: false,
                command: "echo".to_string(),
                args: vec!["test2".to_string()],
                dir: None,
                inputs: vec![],
                source: None,
            },
            Hook {
                order: 100,
                propagate: false,
                command: "echo".to_string(),
                args: vec!["test3".to_string()],
                dir: None,
                inputs: vec![],
                source: None,
            },
        ];
        let mut state = HookExecutionState::new(directory_path, instance_hash, config_hash, hooks);

        // Initial state
        assert_eq!(state.status, ExecutionStatus::Running);
        assert_eq!(state.total_hooks, 3);
        assert_eq!(state.completed_hooks, 0);
        assert!(!state.is_complete());

        // Mark hook as running
        state.mark_hook_running(0);
        assert_eq!(state.current_hook_index, Some(0));

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

        let result = HookResult::success(
            hook.clone(),
            std::process::ExitStatus::from_raw(0),
            String::new(),
            String::new(),
            100,
        );

        state.record_hook_result(0, result);
        assert_eq!(state.completed_hooks, 1);
        assert_eq!(state.current_hook_index, None);
        assert_eq!(state.status, ExecutionStatus::Running);
        assert!(!state.is_complete());

        // Record failed hook result
        let failed_result = HookResult::failure(
            hook,
            Some(std::process::ExitStatus::from_raw(256)),
            String::new(),
            "error".to_string(),
            50,
            "Command failed".to_string(),
        );

        state.record_hook_result(1, failed_result);
        assert_eq!(state.completed_hooks, 2);
        assert_eq!(state.status, ExecutionStatus::Failed);
        assert!(state.is_complete());
        assert!(state.error_message.is_some());

        // Test cancellation
        let mut cancelled_state = HookExecutionState::new(
            PathBuf::from("/test"),
            "hash".to_string(),
            "config".to_string(),
            vec![Hook {
                order: 100,
                propagate: false,
                command: "echo".to_string(),
                args: vec![],
                dir: None,
                inputs: vec![],
                source: None,
            }],
        );
        cancelled_state.mark_cancelled(Some("User cancelled".to_string()));
        assert_eq!(cancelled_state.status, ExecutionStatus::Cancelled);
        assert!(cancelled_state.is_complete());
    }

    #[test]
    fn test_progress_display() {
        let directory_path = PathBuf::from("/test/dir");
        let instance_hash = "test_hash".to_string();
        let config_hash = "config_hash".to_string();
        let hooks = vec![
            Hook {
                order: 100,
                propagate: false,
                command: "echo".to_string(),
                args: vec!["test1".to_string()],
                dir: None,
                inputs: vec![],
                source: None,
            },
            Hook {
                order: 100,
                propagate: false,
                command: "echo".to_string(),
                args: vec!["test2".to_string()],
                dir: None,
                inputs: vec![],
                source: None,
            },
        ];
        let mut state = HookExecutionState::new(directory_path, instance_hash, config_hash, hooks);

        // Running state
        let display = state.progress_display();
        assert!(display.contains("0 of 2"));

        // Running with current hook
        state.mark_hook_running(0);
        let display = state.progress_display();
        assert!(display.contains("Executing hook 1 of 2"));

        // Completed state
        state.status = ExecutionStatus::Completed;
        state.current_hook_index = None;
        let display = state.progress_display();
        assert_eq!(display, "All hooks completed successfully");

        // Failed state
        state.status = ExecutionStatus::Failed;
        state.error_message = Some("Test error".to_string());
        let display = state.progress_display();
        assert!(display.contains("Hook execution failed: Test error"));
    }

    #[tokio::test]
    async fn test_state_directory_cleanup() {
        let temp_dir = TempDir::new().unwrap();
        let state_manager = StateManager::new(temp_dir.path().to_path_buf());

        // Create multiple states with different statuses
        let completed_state = HookExecutionState {
            instance_hash: "completed_hash".to_string(),
            directory_path: PathBuf::from("/completed"),
            config_hash: "config1".to_string(),
            status: ExecutionStatus::Completed,
            total_hooks: 1,
            completed_hooks: 1,
            current_hook_index: None,
            hooks: vec![],
            hook_results: HashMap::new(),
            environment_vars: HashMap::new(),
            started_at: Utc::now() - chrono::Duration::hours(1),
            finished_at: Some(Utc::now() - chrono::Duration::minutes(30)),
            current_hook_started_at: None,
            completed_display_until: None,
            error_message: None,
            previous_env: None,
        };

        let running_state = HookExecutionState {
            instance_hash: "running_hash".to_string(),
            directory_path: PathBuf::from("/running"),
            config_hash: "config2".to_string(),
            status: ExecutionStatus::Running,
            total_hooks: 2,
            completed_hooks: 1,
            current_hook_index: Some(1),
            hooks: vec![],
            hook_results: HashMap::new(),
            environment_vars: HashMap::new(),
            started_at: Utc::now() - chrono::Duration::minutes(5),
            finished_at: None,
            current_hook_started_at: None,
            completed_display_until: None,
            error_message: None,
            previous_env: None,
        };

        let failed_state = HookExecutionState {
            instance_hash: "failed_hash".to_string(),
            directory_path: PathBuf::from("/failed"),
            config_hash: "config3".to_string(),
            status: ExecutionStatus::Failed,
            total_hooks: 1,
            completed_hooks: 0,
            current_hook_index: None,
            hooks: vec![],
            hook_results: HashMap::new(),
            environment_vars: HashMap::new(),
            started_at: Utc::now() - chrono::Duration::hours(2),
            finished_at: Some(Utc::now() - chrono::Duration::hours(1)),
            current_hook_started_at: None,
            completed_display_until: None,
            error_message: Some("Test failure".to_string()),
            previous_env: None,
        };

        // Save all states
        state_manager.save_state(&completed_state).await.unwrap();
        state_manager.save_state(&running_state).await.unwrap();
        state_manager.save_state(&failed_state).await.unwrap();

        // Verify all states exist
        let states = state_manager.list_active_states().await.unwrap();
        assert_eq!(states.len(), 3);

        // Clean up completed states
        let cleaned = state_manager.cleanup_state_directory().await.unwrap();
        assert_eq!(cleaned, 2); // Should clean up completed and failed states

        // Verify only running state remains
        let remaining_states = state_manager.list_active_states().await.unwrap();
        assert_eq!(remaining_states.len(), 1);
        assert_eq!(remaining_states[0].instance_hash, "running_hash");
    }

    #[tokio::test]
    async fn test_cleanup_orphaned_states() {
        let temp_dir = TempDir::new().unwrap();
        let state_manager = StateManager::new(temp_dir.path().to_path_buf());

        // Create an old running state (orphaned)
        let orphaned_state = HookExecutionState {
            instance_hash: "orphaned_hash".to_string(),
            directory_path: PathBuf::from("/orphaned"),
            config_hash: "config".to_string(),
            status: ExecutionStatus::Running,
            total_hooks: 1,
            completed_hooks: 0,
            current_hook_index: Some(0),
            hooks: vec![],
            hook_results: HashMap::new(),
            environment_vars: HashMap::new(),
            started_at: Utc::now() - chrono::Duration::hours(3),
            finished_at: None,
            current_hook_started_at: None,
            completed_display_until: None,
            error_message: None,
            previous_env: None,
        };

        // Create a recent running state (not orphaned)
        let recent_state = HookExecutionState {
            instance_hash: "recent_hash".to_string(),
            directory_path: PathBuf::from("/recent"),
            config_hash: "config".to_string(),
            status: ExecutionStatus::Running,
            total_hooks: 1,
            completed_hooks: 0,
            current_hook_index: Some(0),
            hooks: vec![],
            hook_results: HashMap::new(),
            environment_vars: HashMap::new(),
            started_at: Utc::now() - chrono::Duration::minutes(5),
            finished_at: None,
            current_hook_started_at: None,
            completed_display_until: None,
            error_message: None,
            previous_env: None,
        };

        // Save both states
        state_manager.save_state(&orphaned_state).await.unwrap();
        state_manager.save_state(&recent_state).await.unwrap();

        // Clean up orphaned states older than 1 hour
        let cleaned = state_manager
            .cleanup_orphaned_states(chrono::Duration::hours(1))
            .await
            .unwrap();
        assert_eq!(cleaned, 1); // Should clean up only the orphaned state

        // Verify only recent state remains
        let remaining_states = state_manager.list_active_states().await.unwrap();
        assert_eq!(remaining_states.len(), 1);
        assert_eq!(remaining_states[0].instance_hash, "recent_hash");
    }

    #[tokio::test]
    async fn test_corrupted_state_file_handling() {
        let temp_dir = TempDir::new().unwrap();
        let state_dir = temp_dir.path().join("state");
        let state_manager = StateManager::new(state_dir.clone());

        // Ensure state directory exists
        state_manager.ensure_state_dir().await.unwrap();

        // Write corrupted JSON to a state file
        let corrupted_file = state_dir.join("corrupted.json");
        tokio::fs::write(&corrupted_file, "{invalid json}")
            .await
            .unwrap();

        // List active states should handle the corrupted file gracefully
        let states = state_manager.list_active_states().await.unwrap();
        assert_eq!(states.len(), 0); // Corrupted file should be skipped

        // Cleanup should remove the corrupted file
        let cleaned = state_manager.cleanup_state_directory().await.unwrap();
        assert_eq!(cleaned, 1);

        // Verify the corrupted file is gone
        assert!(!corrupted_file.exists());
    }

    #[tokio::test]
    async fn test_concurrent_state_modifications() {
        use tokio::task;

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

        // Create initial state
        let initial_state = HookExecutionState {
            instance_hash: "concurrent_hash".to_string(),
            directory_path: PathBuf::from("/concurrent"),
            config_hash: "config".to_string(),
            status: ExecutionStatus::Running,
            total_hooks: 10,
            completed_hooks: 0,
            current_hook_index: Some(0),
            hooks: vec![],
            hook_results: HashMap::new(),
            environment_vars: HashMap::new(),
            started_at: Utc::now(),
            finished_at: None,
            current_hook_started_at: None,
            completed_display_until: None,
            error_message: None,
            previous_env: None,
        };

        state_manager.save_state(&initial_state).await.unwrap();

        // Spawn multiple tasks that concurrently modify the state
        let mut handles = vec![];

        for i in 0..5 {
            let sm = state_manager.clone();
            let path = initial_state.directory_path.clone();

            let handle = task::spawn(async move {
                // Load state - it might have been modified by another task
                let instance_hash = compute_instance_hash(&path, "concurrent_config");

                // Simulate some work
                tokio::time::sleep(Duration::from_millis(10)).await;

                // Load state, modify, and save (handle potential concurrent modifications)
                if let Ok(Some(mut state)) = sm.load_state(&instance_hash).await {
                    state.completed_hooks += 1;
                    state.current_hook_index = Some(i + 1);

                    // Save state - ignore errors from concurrent saves
                    let _ = sm.save_state(&state).await;
                }
            });

            handles.push(handle);
        }

        // Wait for all tasks to complete
        for handle in handles {
            handle.await.unwrap();
        }

        // Verify final state - due to concurrent writes, the exact values may vary
        // but the state should be loadable and valid
        let final_state = state_manager
            .load_state(&initial_state.instance_hash)
            .await
            .unwrap();

        // The state might exist or not depending on timing of concurrent operations
        if let Some(state) = final_state {
            assert_eq!(state.instance_hash, "concurrent_hash");
            // Completed hooks will be 0 if all concurrent writes failed, or > 0 if some succeeded
        }
    }

    #[tokio::test]
    async fn test_state_with_unicode_and_special_chars() {
        let temp_dir = TempDir::new().unwrap();
        let state_manager = StateManager::new(temp_dir.path().to_path_buf());

        // Create state with unicode and special characters
        let mut unicode_state = HookExecutionState {
            instance_hash: "unicode_hash".to_string(),
            directory_path: PathBuf::from("/測試/目錄/🚀"),
            config_hash: "config_ñ_é_ü".to_string(),
            status: ExecutionStatus::Failed,
            total_hooks: 1,
            completed_hooks: 1,
            current_hook_index: None,
            hooks: vec![],
            hook_results: HashMap::new(),
            environment_vars: HashMap::new(),
            started_at: Utc::now(),
            finished_at: Some(Utc::now()),
            current_hook_started_at: None,
            completed_display_until: None,
            error_message: Some("Error: 錯誤信息 with émojis 🔥💥".to_string()),
            previous_env: None,
        };

        // Add hook result with unicode output
        let unicode_hook = Hook {
            order: 100,
            propagate: false,
            command: "echo".to_string(),
            args: vec![],
            dir: None,
            inputs: vec![],
            source: None,
        };
        let unicode_result = HookResult {
            hook: unicode_hook,
            success: false,
            exit_status: Some(1),
            stdout: "輸出: Hello 世界! 🌍".to_string(),
            stderr: "錯誤: ñoño error ⚠️".to_string(),
            duration_ms: 100,
            error: Some("失敗了 😢".to_string()),
        };
        unicode_state.hook_results.insert(0, unicode_result);

        // Save and load the state
        state_manager.save_state(&unicode_state).await.unwrap();

        let loaded = state_manager
            .load_state(&unicode_state.instance_hash)
            .await
            .unwrap()
            .unwrap();

        // Verify all unicode content is preserved
        assert_eq!(loaded.config_hash, "config_ñ_é_ü");
        assert_eq!(
            loaded.error_message,
            Some("Error: 錯誤信息 with émojis 🔥💥".to_string())
        );

        let hook_result = loaded.hook_results.get(&0).unwrap();
        assert_eq!(hook_result.stdout, "輸出: Hello 世界! 🌍");
        assert_eq!(hook_result.stderr, "錯誤: ñoño error ⚠️");
        assert_eq!(hook_result.error, Some("失敗了 😢".to_string()));
    }

    #[tokio::test]
    async fn test_state_directory_with_many_states() {
        let temp_dir = TempDir::new().unwrap();
        let state_manager = StateManager::new(temp_dir.path().to_path_buf());

        // Create many states to test scalability
        for i in 0..50 {
            let state = HookExecutionState {
                instance_hash: format!("hash_{}", i),
                directory_path: PathBuf::from(format!("/dir/{}", i)),
                config_hash: format!("config_{}", i),
                status: if i % 3 == 0 {
                    ExecutionStatus::Completed
                } else if i % 3 == 1 {
                    ExecutionStatus::Running
                } else {
                    ExecutionStatus::Failed
                },
                total_hooks: 1,
                completed_hooks: usize::from(i % 3 == 0),
                current_hook_index: if i % 3 == 1 { Some(0) } else { None },
                hooks: vec![],
                hook_results: HashMap::new(),
                environment_vars: HashMap::new(),
                started_at: Utc::now() - chrono::Duration::hours(i64::from(i)),
                finished_at: if i % 3 == 1 {
                    None
                } else {
                    Some(Utc::now() - chrono::Duration::hours(i64::from(i) - 1))
                },
                current_hook_started_at: None,
                completed_display_until: None,
                error_message: if i % 3 == 2 {
                    Some(format!("Error {}", i))
                } else {
                    None
                },
                previous_env: None,
            };
            state_manager.save_state(&state).await.unwrap();
        }

        // List all states
        let listed = state_manager.list_active_states().await.unwrap();
        assert_eq!(listed.len(), 50);

        // Clean up old completed states (older than 24 hours)
        let cleaned = state_manager
            .cleanup_orphaned_states(chrono::Duration::hours(24))
            .await
            .unwrap();

        // Should clean up states older than 24 hours
        assert!(cleaned > 0);
    }
}