agpm-cli 0.4.14

AGent Package Manager - A Git-based package manager for coding agents
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
//! Git repository cache management with worktree-based parallel operations.
//!
//! Provides caching for Git repositories with safe parallel resource installation via worktrees.
//!
//! # Architecture
//!
//! - [`Cache`]: Core repository management and worktree orchestration
//! - [`CacheLock`]: File-based locking for process-safe concurrent access
//! - SHA-based worktrees: One worktree per unique commit for maximum deduplication
//! - Notification-based coordination: `tokio::sync::Notify` eliminates polling
//!
//! # Cache Structure
//!
//! ```text
//! ~/.agpm/cache/
//! ├── sources/       # Bare repositories
//! ├── worktrees/     # SHA-based worktrees with .state.json registry
//! └── .locks/        # Per-repository and per-worktree locks
//! ```
//!
//! # Key Features
//!
//! - Fsync-based verification ensures files readable after worktree creation
//! - DashMap for lock-free concurrent worktree access
//! - Command-instance fetch caching (single fetch per repo per command)
//! - Cross-platform path handling and cache locations

use crate::constants::{default_lock_timeout, pending_state_timeout};
use crate::core::error::AgpmError;
use crate::core::file_error::{FileOperation, FileResultExt};
use crate::git::GitRepo;
use crate::git::command_builder::GitCommand;
use crate::utils::fs;
use crate::utils::security::validate_path_security;
use anyhow::{Context, Result};
use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::fs as async_fs;
use tokio::sync::{Mutex, MutexGuard, RwLock};

/// Acquire a tokio Mutex with timeout and diagnostic dump on failure.
/// Uses test-mode aware timeout from constants.
async fn acquire_mutex_with_timeout<'a, T>(
    mutex: &'a Mutex<T>,
    name: &str,
) -> Result<MutexGuard<'a, T>> {
    let timeout = default_lock_timeout();
    match tokio::time::timeout(timeout, mutex.lock()).await {
        Ok(guard) => Ok(guard),
        Err(_) => {
            eprintln!("[DEADLOCK] Timeout waiting for mutex '{}' after {:?}", name, timeout);
            anyhow::bail!(
                "Timeout waiting for mutex '{}' after {:?} - possible deadlock",
                name,
                timeout
            )
        }
    }
}

/// Acquire a tokio RwLock read guard with timeout and diagnostic dump on failure.
async fn acquire_rwlock_read_with_timeout<'a, T>(
    rwlock: &'a RwLock<T>,
    name: &str,
) -> Result<tokio::sync::RwLockReadGuard<'a, T>> {
    let timeout = default_lock_timeout();
    match tokio::time::timeout(timeout, rwlock.read()).await {
        Ok(guard) => Ok(guard),
        Err(_) => {
            eprintln!("[DEADLOCK] Timeout waiting for RwLock read '{}' after {:?}", name, timeout);
            anyhow::bail!(
                "Timeout waiting for RwLock read '{}' after {:?} - possible deadlock",
                name,
                timeout
            )
        }
    }
}

/// Acquire a tokio RwLock write guard with timeout and diagnostic dump on failure.
async fn acquire_rwlock_write_with_timeout<'a, T>(
    rwlock: &'a RwLock<T>,
    name: &str,
) -> Result<tokio::sync::RwLockWriteGuard<'a, T>> {
    let timeout = default_lock_timeout();
    match tokio::time::timeout(timeout, rwlock.write()).await {
        Ok(guard) => Ok(guard),
        Err(_) => {
            eprintln!("[DEADLOCK] Timeout waiting for RwLock write '{}' after {:?}", name, timeout);
            anyhow::bail!(
                "Timeout waiting for RwLock write '{}' after {:?} - possible deadlock",
                name,
                timeout
            )
        }
    }
}

// Concurrency Architecture:
// - Direct control approach: Command parallelism (--max-parallel) + per-worktree file locking
// - Instance-level caching: Worktrees and fetch operations cached per Cache instance
// - Command-level control: --max-parallel flag controls dependency processing parallelism
// - Fetch caching: Network operations cached for 5 minutes to reduce redundancy

/// Worktree lifecycle state for concurrent coordination.
///
/// State machine enabling safe concurrent access: Pending (creating) → Ready (available).
/// First thread creates with `Pending(notify)`, others wait on notification.
/// Key format: `"{cache_dir_hash}:{owner}_{repo}:{sha}"` for SHA-based deduplication.
#[derive(Debug, Clone)]
enum WorktreeState {
    /// Worktree being created. Notification triggered when complete.
    Pending(Arc<tokio::sync::Notify>),
    /// Worktree ready at path. Validate before use as may be externally deleted.
    Ready(PathBuf),
}

/// Extract notification handle from worktree cache entry to wake waiters.
fn extract_notify_handle(
    cache: &DashMap<String, WorktreeState>,
    key: &str,
) -> Option<Arc<tokio::sync::Notify>> {
    cache.get(key).and_then(|entry| {
        if let WorktreeState::Pending(n) = entry.value() {
            Some(n.clone())
        } else {
            None
        }
    })
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
struct WorktreeRegistry {
    entries: HashMap<String, WorktreeRecord>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct WorktreeRecord {
    source: String,
    version: String,
    path: PathBuf,
    last_used: u64,
}

impl WorktreeRegistry {
    fn load(path: &Path) -> Self {
        match std::fs::read(path) {
            Ok(data) => serde_json::from_slice(&data).unwrap_or_default(),
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Self::default(),
            Err(err) => {
                tracing::warn!("Failed to load worktree registry from {}: {}", path.display(), err);
                Self::default()
            }
        }
    }

    fn update(&mut self, key: String, source: String, version: String, path: PathBuf) {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_else(|_| Duration::from_secs(0))
            .as_secs();

        self.entries.insert(
            key,
            WorktreeRecord {
                source,
                version,
                path,
                last_used: timestamp,
            },
        );
    }

    fn remove_by_path(&mut self, target: &Path) -> bool {
        if let Some(key) = self.entries.iter().find_map(|(k, record)| {
            if record.path == target {
                Some(k.clone())
            } else {
                None
            }
        }) {
            self.entries.remove(&key);
            true
        } else {
            false
        }
    }

    /// Gets the source URL for a worktree by its path.
    ///
    /// Used to look up repository information without parsing the worktree directory name.
    fn get_source_by_path(&self, target: &Path) -> Option<String> {
        self.entries
            .values()
            .find(|record| record.path == target)
            .map(|record| record.source.clone())
    }

    async fn persist(&self, path: &Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            async_fs::create_dir_all(parent).await?;
        }

        let data = serde_json::to_vec_pretty(self)?;
        async_fs::write(path, data).await?;
        Ok(())
    }
}

/// File-based locking mechanism for cache operations
///
/// This module provides thread-safe and process-safe locking for cache
/// operations through OS-level file locks, ensuring data consistency
/// when multiple AGPM processes access the same cache directory.
pub mod lock;
pub use lock::CacheLock;

/// Git repository cache for efficient resource management.
///
/// Manages repository cloning, updating, version management, and resource copying.
/// Multiple instances can safely operate on same cache via [`CacheLock`].
pub struct Cache {
    /// Root directory for cached repositories
    dir: PathBuf,
    /// Instance-level worktree cache. Key: `"{cache_dir_hash}:{owner}_{repo}:{sha}"`.
    /// DashMap enables lock-free concurrent access.
    worktree_cache: Arc<DashMap<String, WorktreeState>>,
    /// Per-repository locks preventing redundant fetches
    fetch_locks: Arc<DashMap<PathBuf, Arc<Mutex<()>>>>,
    /// Tracks fetched repos in this command instance (single fetch per repo per command)
    fetched_repos: Arc<RwLock<HashSet<PathBuf>>>,
    /// Persistent worktree registry for reuse across runs
    worktree_registry: Arc<Mutex<WorktreeRegistry>>,
}

impl Clone for Cache {
    fn clone(&self) -> Self {
        Self {
            dir: self.dir.clone(),
            worktree_cache: Arc::clone(&self.worktree_cache),
            fetch_locks: Arc::clone(&self.fetch_locks),
            fetched_repos: Arc::clone(&self.fetched_repos),
            worktree_registry: Arc::clone(&self.worktree_registry),
        }
    }
}

impl Cache {
    fn registry_path_for(cache_dir: &Path) -> PathBuf {
        cache_dir.join("worktrees").join(".state.json")
    }

    fn registry_path(&self) -> PathBuf {
        Self::registry_path_for(&self.dir)
    }

    async fn record_worktree_usage(
        &self,
        registry_key: &str,
        source_name: &str,
        version_key: &str,
        worktree_path: &Path,
    ) -> Result<()> {
        let mut registry =
            acquire_mutex_with_timeout(&self.worktree_registry, "worktree_registry").await?;
        registry.update(
            registry_key.to_string(),
            source_name.to_string(),
            version_key.to_string(),
            worktree_path.to_path_buf(),
        );
        registry.persist(&self.registry_path()).await?;
        Ok(())
    }

    async fn remove_worktree_record_by_path(&self, worktree_path: &Path) -> Result<()> {
        let mut registry =
            acquire_mutex_with_timeout(&self.worktree_registry, "worktree_registry").await?;
        if registry.remove_by_path(worktree_path) {
            registry.persist(&self.registry_path()).await?;
        }
        Ok(())
    }

    async fn configure_connection_pooling(path: &Path) -> Result<()> {
        let commands = [
            ("http.version", "HTTP/2"),
            ("http.postBuffer", "524288000"),
            ("core.compression", "0"),
        ];

        for (key, value) in commands {
            GitCommand::new()
                .args(["config", key, value])
                .current_dir(path)
                .execute_success()
                .await
                .ok();
        }

        Ok(())
    }

    /// Creates cache instance with default platform-specific directory.
    ///
    /// Linux/macOS: `~/.agpm/cache/`, Windows: `%LOCALAPPDATA%\agpm\cache\`.
    /// Override with `AGPM_CACHE_DIR` environment variable.
    pub fn new() -> Result<Self> {
        let dir = crate::config::get_cache_dir()?;
        let registry_path = Self::registry_path_for(&dir);
        let registry = WorktreeRegistry::load(&registry_path);
        Ok(Self {
            dir,
            worktree_cache: Arc::new(DashMap::new()),
            fetch_locks: Arc::new(DashMap::new()),
            fetched_repos: Arc::new(RwLock::new(HashSet::new())),
            worktree_registry: Arc::new(Mutex::new(registry)),
        })
    }

    /// Creates cache instance with custom directory (useful for testing).
    pub fn with_dir(dir: PathBuf) -> Result<Self> {
        let registry_path = Self::registry_path_for(&dir);
        let registry = WorktreeRegistry::load(&registry_path);
        Ok(Self {
            dir,
            worktree_cache: Arc::new(DashMap::new()),
            fetch_locks: Arc::new(DashMap::new()),
            fetched_repos: Arc::new(RwLock::new(HashSet::new())),
            worktree_registry: Arc::new(Mutex::new(registry)),
        })
    }

    /// Ensures cache directory exists, creating if necessary. Safe to call multiple times.
    pub async fn ensure_cache_dir(&self) -> Result<()> {
        if !self.dir.exists() {
            async_fs::create_dir_all(&self.dir).await.with_file_context(
                FileOperation::CreateDir,
                &self.dir,
                "creating cache directory",
                "cache::ensure_cache_dir",
            )?;
        }
        Ok(())
    }

    /// Returns path to cache directory.
    #[must_use]
    pub fn cache_dir(&self) -> &Path {
        &self.dir
    }

    /// Constructs worktree path for URL and SHA (does not check existence or create).
    pub fn get_worktree_path(&self, url: &str, sha: &str) -> Result<PathBuf> {
        let (owner, repo) =
            crate::git::parse_git_url(url).map_err(|e| anyhow::anyhow!("Invalid Git URL: {e}"))?;
        let sha_short = &sha[..8.min(sha.len())];
        Ok(self.dir.join("worktrees").join(format!("{owner}_{repo}_{sha_short}")))
    }

    /// Gets or clones source repository to cache.
    ///
    /// Handles cloning new repos and updating existing ones with file-based locking.
    /// Concurrent calls with same `name` block; different names run in parallel.
    ///
    /// # Arguments
    ///
    /// * `name` - Source identifier for cache directory and locking
    /// * `url` - Git repository URL (HTTPS, SSH, or local)
    /// * `version` - Optional Git ref (tag, branch, commit, or None for default)
    pub async fn get_or_clone_source(
        &self,
        name: &str,
        url: &str,
        version: Option<&str>,
    ) -> Result<PathBuf> {
        self.get_or_clone_source_impl(name, url, version).await
    }

    /// Removes worktree using `git worktree remove` to properly clean up metadata.
    ///
    /// This ensures both the worktree directory AND the bare repo's metadata are cleaned up,
    /// preventing "missing but already registered worktree" errors on subsequent creation.
    pub async fn cleanup_worktree(&self, worktree_path: &Path) -> Result<()> {
        if !worktree_path.exists() {
            return Ok(());
        }

        // Look up source URL from registry instead of parsing the path
        // This avoids brittle path parsing that breaks with underscores in owner/repo names
        let source_url = {
            let registry =
                acquire_mutex_with_timeout(&self.worktree_registry, "worktree_registry").await?;
            registry.get_source_by_path(worktree_path)
        };

        if let Some(url) = source_url {
            // Use parse_git_url to get owner/repo from the URL
            if let Ok((owner, repo)) = crate::git::parse_git_url(&url) {
                let bare_repo_path = self.dir.join("sources").join(format!("{owner}_{repo}.git"));
                if bare_repo_path.exists() {
                    // Acquire bare-repo-level EXCLUSIVE lock for worktree removal.
                    // This blocks parallel worktree creation (which uses shared locks)
                    // to prevent race conditions when modifying .git/worktrees/ state.
                    let bare_repo_worktree_lock_name = format!("bare-worktree-{owner}_{repo}");
                    let _bare_worktree_lock =
                        CacheLock::acquire(&self.dir, &bare_repo_worktree_lock_name).await?;

                    // Use git worktree remove --force to properly clean up
                    let repo = GitRepo::new(&bare_repo_path);
                    let _ = repo.remove_worktree(worktree_path).await;
                }
            }
        }

        // Fallback: remove directory if git worktree remove didn't clean it up
        if worktree_path.exists() {
            tokio::fs::remove_dir_all(worktree_path).await.with_file_context(
                FileOperation::Write,
                worktree_path,
                "removing worktree directory",
                "cache::cleanup_worktree",
            )?;
        }

        self.remove_worktree_record_by_path(worktree_path).await?;
        Ok(())
    }

    /// Removes all worktrees from cache and prunes bare repo references.
    pub async fn cleanup_all_worktrees(&self) -> Result<()> {
        let worktrees_dir = self.dir.join("worktrees");

        if !worktrees_dir.exists() {
            return Ok(());
        }

        // Remove the entire worktrees directory
        tokio::fs::remove_dir_all(&worktrees_dir).await.with_file_context(
            FileOperation::Write,
            &worktrees_dir,
            "cleaning up worktrees directory",
            "cache_module",
        )?;

        // Also prune worktree references from all bare repos
        let sources_dir = self.dir.join("sources");
        if sources_dir.exists() {
            let mut entries = tokio::fs::read_dir(&sources_dir).await.with_file_context(
                FileOperation::Read,
                &sources_dir,
                "reading sources directory",
                "cache_module",
            )?;
            while let Some(entry) = entries.next_entry().await? {
                let path = entry.path();
                if path.extension().and_then(|s| s.to_str()) == Some("git") {
                    let bare_repo = GitRepo::new(&path);
                    bare_repo.prune_worktrees().await.ok();
                }
            }
        }

        {
            let mut registry =
                acquire_mutex_with_timeout(&self.worktree_registry, "worktree_registry").await?;
            if !registry.entries.is_empty() {
                registry.entries.clear();
                registry.persist(&self.registry_path()).await?;
            }
        }

        Ok(())
    }

    /// Gets or creates SHA-based worktree with notification coordination.
    ///
    /// First thread creates worktree, others wait on notification. SHA-based ensures
    /// maximum reuse and deterministic installations.
    ///
    /// # Arguments
    ///
    /// * `sha` - Full 40-character commit SHA (pre-resolved)
    #[allow(clippy::too_many_lines)]
    pub async fn get_or_create_worktree_for_sha(
        &self,
        name: &str,
        url: &str,
        sha: &str,
        context: Option<&str>,
    ) -> Result<PathBuf> {
        // Validate SHA format
        if sha.len() != 40 || !sha.chars().all(|c| c.is_ascii_hexdigit()) {
            return Err(anyhow::anyhow!(
                "Invalid SHA format: expected 40 hex characters, got '{sha}'"
            ));
        }

        // Check if this is a local path
        let is_local_path = crate::utils::is_local_path(url);
        if is_local_path {
            // Local paths don't use worktrees
            return self.get_or_clone_source(name, url, None).await;
        }

        self.ensure_cache_dir().await?;

        // Parse URL for cache structure
        let (owner, repo) =
            crate::git::parse_git_url(url).unwrap_or(("direct".to_string(), "repo".to_string()));

        // Define unified lock name and bare repo path for this repository
        let bare_repo_dir = self.dir.join("sources").join(format!("{owner}_{repo}.git"));
        let bare_repo_lock_name = format!("bare-repo-{owner}_{repo}");

        // Create SHA-based cache key
        // Using first 8 chars of SHA for directory name (like Git does)
        let sha_short = &sha[..8];
        let cache_dir_hash = {
            use std::collections::hash_map::DefaultHasher;
            use std::hash::{Hash, Hasher};
            let mut hasher = DefaultHasher::new();
            self.dir.hash(&mut hasher);
            format!("{:x}", hasher.finish())[..8].to_string()
        };
        let cache_key = format!("{cache_dir_hash}:{owner}_{repo}:{sha}");

        // Check if we already have a worktree for this SHA using DashMap's lock-free API
        // This eliminates lock contention and deadlocks from the previous RwLock implementation
        let pending_timeout = pending_state_timeout();

        loop {
            match self.worktree_cache.entry(cache_key.clone()) {
                dashmap::mapref::entry::Entry::Occupied(entry) => {
                    match entry.get() {
                        WorktreeState::Ready(cached_path) if cached_path.exists() => {
                            // Worktree already exists and is ready
                            let cached_path = cached_path.clone();
                            drop(entry);

                            self.record_worktree_usage(&cache_key, name, sha_short, &cached_path)
                                .await?;

                            if let Some(ctx) = context {
                                tracing::debug!(
                                    target: "git",
                                    "({}) Reusing SHA-based worktree for {} @ {}",
                                    ctx,
                                    url.split('/').next_back().unwrap_or(url),
                                    sha_short
                                );
                            }
                            return Ok(cached_path);
                        }
                        WorktreeState::Ready(_cached_path) => {
                            // Path exists in cache but not on filesystem - need to recreate
                            // Create fresh notify handle for this creation attempt
                            let notify = Arc::new(tokio::sync::Notify::new());
                            drop(entry);
                            // Insert Pending state and proceed to creation
                            self.worktree_cache
                                .insert(cache_key.clone(), WorktreeState::Pending(notify));
                            break;
                        }
                        WorktreeState::Pending(existing_notify) => {
                            // Another thread is creating this worktree - wait for notification
                            let existing_notify = existing_notify.clone();

                            // CRITICAL: Create the notified future BEFORE dropping entry
                            // This ensures we won't miss the notification if the other thread
                            // finishes between drop() and notified() - Notify only wakes
                            // futures that are ALREADY waiting
                            let notified_future = existing_notify.notified();
                            drop(entry);

                            if let Some(ctx) = context {
                                tracing::debug!(
                                    target: "git",
                                    "({}) Waiting for SHA worktree creation for {} @ {}",
                                    ctx,
                                    url.split('/').next_back().unwrap_or(url),
                                    sha_short
                                );
                            }

                            // Wait for notification with timeout
                            tokio::select! {
                                _ = notified_future => {
                                    // Worktree creation completed (success or failure) - retry from top
                                    continue;
                                }
                                _ = tokio::time::sleep(pending_timeout) => {
                                    // Timeout waiting - the other thread may have hung.
                                    // We need to take ownership by inserting our own Pending state.
                                    // This ensures proper coordination with any other waiting threads.
                                    let our_notify = Arc::new(tokio::sync::Notify::new());
                                    self.worktree_cache
                                        .insert(cache_key.clone(), WorktreeState::Pending(our_notify));

                                    // Notify existing waiters so they can re-evaluate the new state
                                    existing_notify.notify_waiters();
                                    tracing::warn!(
                                        target: "git",
                                        "Timeout waiting for worktree creation for {} @ {} - taking ownership",
                                        url.split('/').next_back().unwrap_or(url),
                                        sha_short
                                    );
                                    break;
                                }
                            }
                        }
                    }
                }
                dashmap::mapref::entry::Entry::Vacant(entry) => {
                    // No entry exists - create notify handle here to ensure
                    // it's only created when actually needed for a new entry
                    let notify = Arc::new(tokio::sync::Notify::new());
                    entry.insert(WorktreeState::Pending(notify));
                    break;
                }
            }
        }

        // All work wrapped in a result to handle cleanup explicitly on error
        let worktree_cache = self.worktree_cache.clone();
        let cache_key_for_cleanup = cache_key.clone();

        let result: Result<PathBuf> = async {
            tracing::debug!(
                target: "git::worktree",
                "Starting worktree creation for {} @ {} (cache_key={})",
                url.split('/').next_back().unwrap_or(url),
                sha_short,
                cache_key
            );

            // Check if bare repository already exists BEFORE acquiring lock
            // This avoids lock order violations when multiple worktrees are created concurrently
            if !bare_repo_dir.exists() {
                // Bare repo doesn't exist - acquire lock and clone
                tracing::debug!(
                    target: "git",
                    "Bare repo does not exist, acquiring lock to clone: {}",
                    bare_repo_dir.display()
                );

                let bare_repo_lock = CacheLock::acquire(&self.dir, &bare_repo_lock_name).await?;

                // Re-check after acquiring lock (another task may have cloned it)
                if !bare_repo_dir.exists() {
                    if let Some(parent) = bare_repo_dir.parent() {
                        tokio::fs::create_dir_all(parent).await.with_file_context(
                            FileOperation::CreateDir,
                            parent,
                            "creating cache parent directory",
                            "cache_module",
                        )?;
                    }

                    if let Some(ctx) = context {
                        tracing::debug!("📦 ({ctx}) Cloning repository {url}...");
                    } else {
                        tracing::debug!("📦 Cloning repository {url} to cache...");
                    }

                    // Add timeout to prevent hung clone operations
                    tokio::time::timeout(
                        crate::constants::GIT_CLONE_TIMEOUT,
                        GitRepo::clone_bare_with_context(url, &bare_repo_dir, context),
                    )
                    .await
                    .map_err(|_| {
                        anyhow::anyhow!(
                            "Git clone operation timed out after {:?} for {}",
                            crate::constants::GIT_CLONE_TIMEOUT,
                            url
                        )
                    })??;

                    Self::configure_connection_pooling(&bare_repo_dir).await.ok();

                    // Mark as fetched since clone_bare_with_context already fetches
                    acquire_rwlock_write_with_timeout(&self.fetched_repos, "fetched_repos")
                        .await?
                        .insert(bare_repo_dir.clone());
                }

                // Release bare repo lock before proceeding to worktree creation
                drop(bare_repo_lock);
            }
            // If bare_repo_dir already existed, we never acquired the lock

            let bare_repo = GitRepo::new(&bare_repo_dir);

            // Create worktree path using SHA
            let worktree_path =
                self.dir.join("worktrees").join(format!("{owner}_{repo}_{sha_short}"));

            // Acquire per-SHA worktree lock for caching/deduplication.
            let worktree_lock_name = format!("worktree-{owner}-{repo}-{sha_short}");
            let _worktree_lock = CacheLock::acquire(&self.dir, &worktree_lock_name).await?;

            // Re-check after lock
            if worktree_path.exists() {
                // Notify and update cache to Ready
                let notify_to_wake = extract_notify_handle(&self.worktree_cache, &cache_key);
                self.worktree_cache
                    .insert(cache_key.clone(), WorktreeState::Ready(worktree_path.clone()));
                if let Some(n) = notify_to_wake {
                    n.notify_waiters();
                }

                self.record_worktree_usage(&cache_key, name, sha_short, &worktree_path).await?;
                return Ok(worktree_path);
            }

            // NOTE: We intentionally do NOT call prune_worktrees() here.
            // The speculative prune caused race conditions when multiple threads created
            // worktrees from the same bare repo simultaneously (each had different SHA locks
            // but prune affects the entire .git/worktrees/ directory).
            // If stale worktree metadata exists, git worktree add will fail with
            // "missing but already registered worktree" and the error handling path
            // (create_worktree_with_context) will prune and retry.

            // Create worktree at specific SHA
            if let Some(ctx) = context {
                tracing::debug!(
                    target: "git",
                    "({}) Creating SHA-based worktree: {} @ {}",
                    ctx,
                    url.split('/').next_back().unwrap_or(url),
                    sha_short
                );
            }

            // Acquire bare-repo-level SHARED lock for worktree creation.
            // Shared locks allow parallel worktree creation for different SHAs (each writes
            // to its own subdirectory in .git/worktrees/). Exclusive locks are used only
            // for deletion/pruning operations that modify shared state.
            let bare_repo_worktree_lock_name = format!("bare-worktree-{owner}_{repo}");
            let _bare_worktree_lock =
                CacheLock::acquire_shared(&self.dir, &bare_repo_worktree_lock_name).await?;

            // Create worktree using SHA directly
            // Add timeout to prevent hung worktree creation
            let worktree_result = tokio::time::timeout(
                crate::constants::GIT_WORKTREE_TIMEOUT,
                bare_repo.create_worktree_with_context(&worktree_path, Some(sha), context),
            )
            .await
            .map_err(|_| {
                anyhow::anyhow!(
                    "Git worktree creation timed out after {:?} for {} @ {}",
                    crate::constants::GIT_WORKTREE_TIMEOUT,
                    url,
                    sha_short
                )
            })?;

            // Keep lock held until cache is updated to ensure git state is fully settled
            match worktree_result {
                Ok(_) => {
                    // Verify worktree is fully accessible before marking as Ready
                    // Using git status to ensure files are accessible, avoiding deadlocks from retry loops.
                    // Files verified here are guaranteed readable, eliminating need for retry logic later.
                    // This architectural choice enables better parallelism and prevents lock contention.
                    if !worktree_path.exists() {
                        return Err(anyhow::anyhow!(
                            "Worktree directory does not exist: {}",
                            worktree_path.display()
                        ));
                    }

                    let git_file = worktree_path.join(".git");
                    if !git_file.exists() {
                        return Err(anyhow::anyhow!(
                            "Worktree .git file does not exist: {}",
                            git_file.display()
                        ));
                    }

                    // Release bare repo lock - worktree creation is complete
                    drop(_bare_worktree_lock);

                    // Fsync both directories to ensure all file entries are visible.
                    // This fixes APFS/filesystem buffer cache issues where files aren't
                    // immediately readable after git worktree add completes.
                    //
                    // SKIP ON WINDOWS: Windows uses mandatory file locking which ensures
                    // file visibility after git operations complete. The fsync operation
                    // is expensive (100-500ms per call on NTFS) and unnecessary.
                    #[cfg(not(windows))]
                    {
                        let worktree_path_clone = worktree_path.clone();
                        let bare_worktrees_dir = bare_repo_dir.join("worktrees");
                        let bare_worktrees_exists = bare_worktrees_dir.exists();

                        let _ = tokio::task::spawn_blocking(move || {
                            // Fsync worktree directory
                            if let Ok(dir) = std::fs::File::open(&worktree_path_clone) {
                                let _ = dir.sync_all();
                            }

                            // Fsync bare repo's worktrees metadata directory
                            if bare_worktrees_exists {
                                if let Ok(dir) = std::fs::File::open(&bare_worktrees_dir) {
                                    let _ = dir.sync_all();
                                }
                            }
                        })
                        .await;

                        tracing::debug!(
                            target: "git::worktree",
                            "Worktree fsync completed for {} @ {}",
                            worktree_path.display(),
                            &sha[..8]
                        );
                    }

                    // Notify and update cache to Ready
                    let notify_to_wake = extract_notify_handle(&self.worktree_cache, &cache_key);
                    self.worktree_cache
                        .insert(cache_key.clone(), WorktreeState::Ready(worktree_path.clone()));
                    if let Some(n) = notify_to_wake {
                        n.notify_waiters();
                    }

                    self.record_worktree_usage(&cache_key, name, sha_short, &worktree_path).await?;
                    Ok(worktree_path)
                }
                Err(e) => Err(e),
            }
        }
        .await;

        // Handle result with explicit cleanup on error
        match result {
            Ok(path) => Ok(path),
            Err(e) => {
                // Cleanup: remove Pending entry and notify waiters
                let notify = extract_notify_handle(&worktree_cache, &cache_key_for_cleanup);
                worktree_cache.remove(&cache_key_for_cleanup);
                if let Some(n) = notify {
                    n.notify_waiters();
                }
                Err(e)
            }
        }
    }

    /// Get or clone a source repository with options to control cache behavior.
    ///
    /// This method provides the core functionality for repository access with
    /// additional control over cache behavior. Creates bare repositories that
    /// can be shared by all operations (resolution, installation, etc).
    ///
    /// # Parameters
    ///
    /// * `name` - The name of the source (used for cache directory naming)
    /// * `url` - The Git repository URL or local path
    /// * `version` - Optional specific version/tag/branch to checkout
    /// * `force_refresh` - If true, ignore cached version and clone/fetch fresh
    ///
    /// # Returns
    ///
    /// Returns the path to the cached bare repository directory
    async fn get_or_clone_source_impl(
        &self,
        name: &str,
        url: &str,
        version: Option<&str>,
    ) -> Result<PathBuf> {
        // Check if this is a local path (not a git repository URL)
        let is_local_path = crate::utils::is_local_path(url);

        if is_local_path {
            // For local paths (directories), validate and return the secure path
            // No cloning or version management needed

            // Resolve path securely with validation
            let resolved_path = crate::utils::platform::resolve_path(url)?;

            // Canonicalize to get the real path and prevent symlink attacks
            let canonical_path = crate::utils::safe_canonicalize(&resolved_path)
                .map_err(|_| anyhow::anyhow!("Local path is not accessible or does not exist"))?;

            // Security check: Validate path against blacklist and symlinks
            validate_path_security(&canonical_path, true)?;

            // For local paths, versions don't apply. Suppress warning for internal sentinel values.
            if let Some(ver) = version
                && ver != "local"
            {
                eprintln!("Warning: Version constraints are ignored for local paths");
            }

            return Ok(canonical_path);
        }

        self.ensure_cache_dir().await?;

        // Acquire lock for this source to prevent concurrent access
        let _lock = CacheLock::acquire(&self.dir, name)
            .await
            .with_context(|| format!("Failed to acquire lock for source: {name}"))?;

        // Use the same cache directory structure as worktrees - bare repos with .git suffix
        // This ensures we have ONE repository that's shared by all operations
        let (owner, repo) =
            crate::git::parse_git_url(url).unwrap_or(("direct".to_string(), "repo".to_string()));
        let source_dir = self.dir.join("sources").join(format!("{owner}_{repo}.git")); // Always use .git suffix for bare repos

        // Ensure parent directory exists
        if let Some(parent) = source_dir.parent() {
            tokio::fs::create_dir_all(parent).await.with_file_context(
                FileOperation::CreateDir,
                parent,
                "creating cache directory",
                "cache_module",
            )?;
        }

        if source_dir.exists() {
            // Use existing cache - fetch to ensure we have latest refs
            // Skip fetch for local paths as they don't have remotes
            // For Git URLs, always fetch to get the latest refs (especially important for branches)
            if crate::utils::is_git_url(url) {
                // Check if we've already fetched this repo in this command instance
                let already_fetched = {
                    let fetched =
                        acquire_rwlock_read_with_timeout(&self.fetched_repos, "fetched_repos")
                            .await?;
                    fetched.contains(&source_dir)
                };

                if already_fetched {
                    tracing::debug!(
                        target: "agpm::cache",
                        "Skipping fetch for {} (already fetched in this command)",
                        name
                    );
                } else {
                    tracing::debug!(
                        target: "agpm::cache",
                        "Fetching updates for {} from {}",
                        name,
                        url
                    );
                    let repo = crate::git::GitRepo::new(&source_dir);
                    if let Err(e) = repo.fetch(None).await {
                        tracing::warn!(
                            target: "agpm::cache",
                            "Failed to fetch updates for {}: {}",
                            name,
                            e
                        );
                    } else {
                        // Mark this repo as fetched for this command execution
                        let mut fetched =
                            acquire_rwlock_write_with_timeout(&self.fetched_repos, "fetched_repos")
                                .await?;
                        fetched.insert(source_dir.clone());
                        tracing::debug!(
                            target: "agpm::cache",
                            "Successfully fetched updates for {}",
                            name
                        );
                    }
                }
            } else {
                tracing::debug!(
                    target: "agpm::cache",
                    "Skipping fetch for local path: {}",
                    url
                );
            }
        } else {
            // Directory doesn't exist - clone fresh as bare repo
            self.clone_source(url, &source_dir).await?;
        }

        Ok(source_dir)
    }

    /// Clones a Git repository to the specified target directory as a bare repository.
    ///
    /// This internal method performs the initial clone operation for repositories
    /// that are not yet present in the cache. It creates a bare repository which
    /// is optimal for serving and allows multiple worktrees to be created from it.
    ///
    /// # Why Bare Repositories
    ///
    /// Bare repositories are used because:
    /// - **No working directory conflicts**: Multiple worktrees can be created safely
    /// - **Optimized for serving**: Like GitHub/GitLab, designed for fetch operations
    /// - **Space efficient**: No checkout of files in the main repository
    /// - **Thread-safe**: Multiple processes can fetch from it simultaneously
    ///
    /// # Authentication
    ///
    /// Repository authentication is handled through:
    /// - **SSH keys**: For `git@github.com:` URLs (user's SSH configuration)
    /// - **HTTPS tokens**: For private repositories (from global config)
    /// - **Public repos**: No authentication required
    ///
    /// # Parameters
    ///
    /// * `url` - Git repository URL to clone from
    /// * `target` - Local directory path where bare repository should be created
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Repository URL is invalid or unreachable
    /// - Authentication fails for private repositories
    /// - Target directory cannot be created or written to
    /// - Network connectivity issues
    /// - Git command is not available in PATH
    async fn clone_source(&self, url: &str, target: &Path) -> Result<()> {
        tracing::debug!("📦 Cloning {} to cache...", url);

        // Clone as a bare repository for better concurrency and worktree support
        GitRepo::clone_bare(url, target)
            .await
            .with_context(|| format!("Failed to clone repository from {url}"))?;

        // Debug: List what was cloned
        if cfg!(test)
            && let Ok(entries) = std::fs::read_dir(target)
        {
            tracing::debug!(
                target: "agpm::cache",
                "Cloned bare repo to {}, contents:",
                target.display()
            );
            for entry in entries.flatten() {
                tracing::debug!(
                    target: "agpm::cache",
                    "  - {}",
                    entry.path().display()
                );
            }
        }

        Ok(())
    }

    /// Copies resource file from cached repository to project (silent).
    ///
    /// Uses copy-based approach (not symlinks) for cross-platform compatibility
    /// and Git integration. Creates parent directories automatically.
    ///
    /// # Arguments
    ///
    /// * `source_dir` - Cached repository path
    /// * `source_path` - Relative path within repository
    /// * `target_path` - Absolute installation path
    pub async fn copy_resource(
        &self,
        source_dir: &Path,
        source_path: &str,
        target_path: &Path,
    ) -> Result<()> {
        self.copy_resource_with_output(source_dir, source_path, target_path, false).await
    }

    /// Copies resource file with optional installation output.
    ///
    /// Same as `copy_resource` but optionally displays "✅ Installed" messages.
    ///
    /// # Arguments
    ///
    /// * `show_output` - Whether to display installation progress
    pub async fn copy_resource_with_output(
        &self,
        source_dir: &Path,
        source_path: &str,
        target_path: &Path,
        show_output: bool,
    ) -> Result<()> {
        let source_file = source_dir.join(source_path);

        if !source_file.exists() {
            return Err(AgpmError::ResourceFileNotFound {
                path: source_path.to_string(),
                source_name: source_dir
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or("unknown")
                    .to_string(),
            }
            .into());
        }

        if let Some(parent) = target_path.parent() {
            async_fs::create_dir_all(parent)
                .await
                .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
        }

        async_fs::copy(&source_file, target_path).await.with_context(|| {
            format!("Failed to copy {} to {}", source_file.display(), target_path.display())
        })?;

        if show_output {
            println!("  ✅ Installed {}", target_path.display());
        }

        Ok(())
    }

    /// Removes cached repositories not in active sources list.
    ///
    /// Returns count of removed directories. Displays progress messages.
    ///
    /// # Arguments
    ///
    /// * `active_sources` - Source names to preserve
    pub async fn clean_unused(&self, active_sources: &[String]) -> Result<usize> {
        self.ensure_cache_dir().await?;

        let mut removed_count = 0;
        let mut entries = async_fs::read_dir(&self.dir)
            .await
            .with_context(|| "Failed to read cache directory")?;

        while let Some(entry) =
            entries.next_entry().await.with_context(|| "Failed to read directory entry")?
        {
            let path = entry.path();
            if path.is_dir() {
                let dir_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");

                if !active_sources.contains(&dir_name.to_string()) {
                    println!("🗑️  Removing unused cache: {dir_name}");
                    async_fs::remove_dir_all(&path).await.with_context(|| {
                        format!("Failed to remove cache directory: {}", path.display())
                    })?;
                    removed_count += 1;
                }
            }
        }

        Ok(removed_count)
    }

    /// Calculates total cache size in bytes (recursive, returns 0 if not exists).
    pub async fn get_cache_size(&self) -> Result<u64> {
        if !self.dir.exists() {
            return Ok(0);
        }

        let size = fs::get_directory_size(&self.dir).await?;
        Ok(size)
    }

    /// Returns cache directory path (may not exist, use `ensure_cache_dir` to create).
    #[must_use]
    pub fn get_cache_location(&self) -> &Path {
        &self.dir
    }

    /// Removes entire cache directory (destructive, requires re-cloning repos).
    pub async fn clear_all(&self) -> Result<()> {
        if self.dir.exists() {
            async_fs::remove_dir_all(&self.dir).await.with_context(|| "Failed to clear cache")?;
            println!("🗑️  Cleared all cache");
        }
        Ok(())
    }
}

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

    use tempfile::TempDir;

    #[tokio::test]
    async fn test_cache_dir_creation() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");

        let cache = Cache::with_dir(cache_dir.clone()).unwrap();
        cache.ensure_cache_dir().await.unwrap();

        assert!(cache_dir.exists());
    }

    #[tokio::test]
    async fn test_cache_location() {
        let temp_dir = TempDir::new().unwrap();
        let cache = Cache::with_dir(temp_dir.path().to_path_buf()).unwrap();
        let location = cache.get_cache_location();
        assert_eq!(location, temp_dir.path());
    }

    #[tokio::test]
    async fn test_cache_size_empty() {
        let temp_dir = TempDir::new().unwrap();
        let cache = Cache::with_dir(temp_dir.path().to_path_buf()).unwrap();

        cache.ensure_cache_dir().await.unwrap();
        let size = cache.get_cache_size().await.unwrap();
        assert_eq!(size, 0);
    }

    #[tokio::test]
    async fn test_cache_size_with_content() {
        let temp_dir = TempDir::new().unwrap();
        let cache = Cache::with_dir(temp_dir.path().to_path_buf()).unwrap();

        cache.ensure_cache_dir().await.unwrap();

        // Create some test content
        let test_file = temp_dir.path().join("test.txt");
        std::fs::write(&test_file, "test content").unwrap();

        let size = cache.get_cache_size().await.unwrap();
        assert!(size > 0);
        assert_eq!(size, 12); // "test content" is 12 bytes
    }

    #[tokio::test]
    async fn test_clean_unused_empty_cache() {
        let temp_dir = TempDir::new().unwrap();
        let cache = Cache::with_dir(temp_dir.path().to_path_buf()).unwrap();

        cache.ensure_cache_dir().await.unwrap();

        let removed = cache.clean_unused(&["active".to_string()]).await.unwrap();
        assert_eq!(removed, 0);
    }

    #[tokio::test]
    async fn test_clean_unused_removes_correct_dirs() {
        let temp_dir = TempDir::new().unwrap();
        let cache = Cache::with_dir(temp_dir.path().to_path_buf()).unwrap();

        cache.ensure_cache_dir().await.unwrap();

        // Create some test directories
        let active_dir = temp_dir.path().join("active");
        let unused_dir = temp_dir.path().join("unused");
        let another_unused = temp_dir.path().join("another_unused");

        std::fs::create_dir_all(&active_dir).unwrap();
        std::fs::create_dir_all(&unused_dir).unwrap();
        std::fs::create_dir_all(&another_unused).unwrap();

        // Add some content to verify directories are removed completely
        std::fs::write(active_dir.join("file.txt"), "keep").unwrap();
        std::fs::write(unused_dir.join("file.txt"), "remove").unwrap();
        std::fs::write(another_unused.join("file.txt"), "remove").unwrap();

        let removed = cache.clean_unused(&["active".to_string()]).await.unwrap();

        assert_eq!(removed, 2);
        assert!(active_dir.exists());
        assert!(!unused_dir.exists());
        assert!(!another_unused.exists());
    }

    #[tokio::test]
    async fn test_clear_all_removes_entire_cache() {
        let temp_dir = TempDir::new().unwrap();
        let cache = Cache::with_dir(temp_dir.path().to_path_buf()).unwrap();

        cache.ensure_cache_dir().await.unwrap();

        // Create some content
        let subdir = temp_dir.path().join("subdir");
        std::fs::create_dir_all(&subdir).unwrap();
        std::fs::write(subdir.join("file.txt"), "content").unwrap();

        assert!(temp_dir.path().exists());
        assert!(subdir.exists());

        cache.clear_all().await.unwrap();

        assert!(!temp_dir.path().exists());
    }

    #[tokio::test]
    async fn test_copy_resource() {
        let temp_dir = TempDir::new().unwrap();
        let cache = Cache::with_dir(temp_dir.path().join("cache")).unwrap();

        // Create source file
        let source_dir = temp_dir.path().join("source");
        std::fs::create_dir_all(&source_dir).unwrap();
        let source_file = source_dir.join("resource.md");
        std::fs::write(&source_file, "# Test Resource\nContent").unwrap();

        // Copy resource
        let dest = temp_dir.path().join("dest.md");
        cache.copy_resource(&source_dir, "resource.md", &dest).await.unwrap();

        assert!(dest.exists());
        let content = std::fs::read_to_string(&dest).unwrap();
        assert_eq!(content, "# Test Resource\nContent");
    }

    #[tokio::test]
    async fn test_copy_resource_nested_path() {
        let temp_dir = TempDir::new().unwrap();
        let cache = Cache::with_dir(temp_dir.path().join("cache")).unwrap();

        // Create source file in nested directory
        let source_dir = temp_dir.path().join("source");
        let nested_dir = source_dir.join("nested").join("path");
        std::fs::create_dir_all(&nested_dir).unwrap();
        let source_file = nested_dir.join("resource.md");
        std::fs::write(&source_file, "# Nested Resource").unwrap();

        // Copy resource using relative path from source_dir
        let dest = temp_dir.path().join("dest.md");
        cache.copy_resource(&source_dir, "nested/path/resource.md", &dest).await.unwrap();

        assert!(dest.exists());
        let content = std::fs::read_to_string(&dest).unwrap();
        assert_eq!(content, "# Nested Resource");
    }

    #[tokio::test]
    async fn test_copy_resource_invalid_path() {
        let temp_dir = TempDir::new().unwrap();
        let cache = Cache::with_dir(temp_dir.path().join("cache")).unwrap();

        let source_dir = temp_dir.path().join("source");
        std::fs::create_dir_all(&source_dir).unwrap();

        // Try to copy non-existent resource
        let dest = temp_dir.path().join("dest.md");
        let result = cache.copy_resource(&source_dir, "nonexistent.md", &dest).await;

        assert!(result.is_err());
        assert!(!dest.exists());
    }

    #[tokio::test]
    async fn test_ensure_cache_dir_idempotent() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let cache = Cache::with_dir(cache_dir.clone()).unwrap();

        // Call ensure_cache_dir multiple times
        cache.ensure_cache_dir().await.unwrap();
        assert!(cache_dir.exists());

        cache.ensure_cache_dir().await.unwrap();
        assert!(cache_dir.exists());

        // Add a file and ensure it's preserved
        std::fs::write(cache_dir.join("test.txt"), "content").unwrap();

        cache.ensure_cache_dir().await.unwrap();
        assert!(cache_dir.exists());
        assert!(cache_dir.join("test.txt").exists());
    }

    #[tokio::test]
    async fn test_copy_resource_creates_parent_directories() {
        let temp_dir = TempDir::new().unwrap();
        let cache = Cache::with_dir(temp_dir.path().join("cache")).unwrap();

        // Create source file
        let source_dir = temp_dir.path().join("source");
        std::fs::create_dir_all(&source_dir).unwrap();
        std::fs::write(source_dir.join("file.md"), "content").unwrap();

        // Copy to a destination with non-existent parent directories
        let dest = temp_dir.path().join("deep").join("nested").join("dest.md");
        cache.copy_resource(&source_dir, "file.md", &dest).await.unwrap();

        assert!(dest.exists());
        assert_eq!(std::fs::read_to_string(&dest).unwrap(), "content");
    }

    #[tokio::test]
    async fn test_copy_resource_with_output_flag() {
        let temp_dir = TempDir::new().unwrap();
        let cache = Cache::with_dir(temp_dir.path().join("cache")).unwrap();

        // Create source file
        let source_dir = temp_dir.path().join("source");
        std::fs::create_dir_all(&source_dir).unwrap();
        std::fs::write(source_dir.join("file.md"), "content").unwrap();

        // Test with output flag false
        let dest1 = temp_dir.path().join("dest1.md");
        cache.copy_resource_with_output(&source_dir, "file.md", &dest1, false).await.unwrap();
        assert!(dest1.exists());

        // Test with output flag true
        let dest2 = temp_dir.path().join("dest2.md");
        cache.copy_resource_with_output(&source_dir, "file.md", &dest2, true).await.unwrap();
        assert!(dest2.exists());
    }

    #[tokio::test]
    async fn test_cache_size_nonexistent_dir() {
        let temp_dir = TempDir::new().unwrap();
        let nonexistent = temp_dir.path().join("nonexistent");
        let cache = Cache::with_dir(nonexistent).unwrap();

        let size = cache.get_cache_size().await.unwrap();
        assert_eq!(size, 0);
    }

    #[tokio::test]
    async fn test_clear_all_nonexistent_cache() {
        let temp_dir = TempDir::new().unwrap();
        let nonexistent = temp_dir.path().join("nonexistent");
        let cache = Cache::with_dir(nonexistent).unwrap();

        // Should not error when clearing non-existent cache
        cache.clear_all().await.unwrap();
    }

    #[tokio::test]
    async fn test_clean_unused_with_files_and_dirs() {
        let temp_dir = TempDir::new().unwrap();
        let cache = Cache::with_dir(temp_dir.path().to_path_buf()).unwrap();

        cache.ensure_cache_dir().await.unwrap();

        // Create directories
        std::fs::create_dir_all(temp_dir.path().join("keep")).unwrap();
        std::fs::create_dir_all(temp_dir.path().join("remove")).unwrap();

        // Create a file (not a directory)
        std::fs::write(temp_dir.path().join("file.txt"), "content").unwrap();

        let removed = cache.clean_unused(&["keep".to_string()]).await.unwrap();

        // Should only remove the "remove" directory, not the file
        assert_eq!(removed, 1);
        assert!(temp_dir.path().join("keep").exists());
        assert!(!temp_dir.path().join("remove").exists());
        assert!(temp_dir.path().join("file.txt").exists());
    }

    #[tokio::test]
    async fn test_copy_resource_overwrites_existing() {
        let temp_dir = TempDir::new().unwrap();
        let cache = Cache::with_dir(temp_dir.path().join("cache")).unwrap();

        // Create source file
        let source_dir = temp_dir.path().join("source");
        std::fs::create_dir_all(&source_dir).unwrap();
        std::fs::write(source_dir.join("file.md"), "new content").unwrap();

        // Create existing destination file
        let dest = temp_dir.path().join("dest.md");
        std::fs::write(&dest, "old content").unwrap();

        // Copy should overwrite
        cache.copy_resource(&source_dir, "file.md", &dest).await.unwrap();

        assert_eq!(std::fs::read_to_string(&dest).unwrap(), "new content");
    }

    #[tokio::test]
    async fn test_copy_resource_special_characters() {
        let temp_dir = TempDir::new().unwrap();
        let cache = Cache::with_dir(temp_dir.path().join("cache")).unwrap();

        // Create source file with special characters
        let source_dir = temp_dir.path().join("source");
        std::fs::create_dir_all(&source_dir).unwrap();
        let special_name = "file with spaces & special-chars.md";
        std::fs::write(source_dir.join(special_name), "content").unwrap();

        // Copy resource
        let dest = temp_dir.path().join("dest.md");
        cache.copy_resource(&source_dir, special_name, &dest).await.unwrap();

        assert!(dest.exists());
        assert_eq!(std::fs::read_to_string(&dest).unwrap(), "content");
    }

    #[tokio::test]
    async fn test_cache_location_consistency() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("my_cache");
        let cache = Cache::with_dir(cache_dir.clone()).unwrap();

        // Get location multiple times
        let loc1 = cache.get_cache_location();
        let loc2 = cache.get_cache_location();

        assert_eq!(loc1, loc2);
        assert_eq!(loc1, cache_dir.as_path());
    }

    #[tokio::test]
    async fn test_clean_unused_empty_active_list() {
        let temp_dir = TempDir::new().unwrap();
        let cache = Cache::with_dir(temp_dir.path().to_path_buf()).unwrap();

        cache.ensure_cache_dir().await.unwrap();

        // Create some directories
        std::fs::create_dir_all(temp_dir.path().join("source1")).unwrap();
        std::fs::create_dir_all(temp_dir.path().join("source2")).unwrap();

        // Empty active list should remove all
        let removed = cache.clean_unused(&[]).await.unwrap();

        assert_eq!(removed, 2);
        assert!(!temp_dir.path().join("source1").exists());
        assert!(!temp_dir.path().join("source2").exists());
    }

    #[tokio::test]
    async fn test_copy_resource_with_relative_paths() {
        let temp_dir = TempDir::new().unwrap();
        let cache = Cache::with_dir(temp_dir.path().join("cache")).unwrap();

        // Create source with subdirectories
        let source_dir = temp_dir.path().join("source");
        let sub_dir = source_dir.join("agents");
        std::fs::create_dir_all(&sub_dir).unwrap();
        std::fs::write(sub_dir.join("helper.md"), "# Helper Agent").unwrap();

        // Copy using relative path
        let dest = temp_dir.path().join("my-agent.md");
        cache.copy_resource(&source_dir, "agents/helper.md", &dest).await.unwrap();

        assert!(dest.exists());
        assert_eq!(std::fs::read_to_string(&dest).unwrap(), "# Helper Agent");
    }

    #[tokio::test]
    async fn test_cache_size_with_subdirectories() {
        let temp_dir = TempDir::new().unwrap();
        let cache = Cache::with_dir(temp_dir.path().to_path_buf()).unwrap();

        cache.ensure_cache_dir().await.unwrap();

        // Create nested structure with files
        let sub1 = temp_dir.path().join("sub1");
        let sub2 = sub1.join("sub2");
        std::fs::create_dir_all(&sub2).unwrap();

        std::fs::write(temp_dir.path().join("file1.txt"), "12345").unwrap(); // 5 bytes
        std::fs::write(sub1.join("file2.txt"), "1234567890").unwrap(); // 10 bytes
        std::fs::write(sub2.join("file3.txt"), "abc").unwrap(); // 3 bytes

        let size = cache.get_cache_size().await.unwrap();
        assert_eq!(size, 18); // 5 + 10 + 3
    }
}