tldr-cli 0.1.3

CLI binary for TLDR code analysis tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
//! Core daemon state machine and runtime
//!
//! This module contains the `TLDRDaemon` struct which manages:
//! - Daemon lifecycle state (Initializing -> Ready -> ShuttingDown)
//! - Salsa-style query cache
//! - Session statistics tracking
//! - Hook activity tracking
//! - Dirty file tracking for incremental re-indexing
//!
//! # Security Mitigations
//!
//! - TIGER-P2-02: Socket cleanup on abnormal exit via signal handlers

use std::collections::hash_map::DefaultHasher;
use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Instant;

use dashmap::DashMap;
use tokio::sync::{watch, RwLock};

use super::error::{DaemonError, DaemonResult};
use super::ipc::{read_command, send_response, IpcListener, IpcStream};
use super::salsa::{QueryCache, QueryKey};
use super::types::{
    AllSessionsSummary, DaemonCommand, DaemonConfig, DaemonResponse, DaemonStatus, HookStats,
    SalsaCacheStats, SessionStats, HOOK_FLUSH_THRESHOLD,
};

use tldr_core::{
    architecture_analysis, build_project_call_graph, change_impact, collect_all_functions,
    dead_code_analysis, detect_or_parse_language, extract_file, find_importers, get_cfg_context,
    get_code_structure, get_dfg_context, get_file_tree, get_imports, get_relevant_context,
    get_slice, impact_analysis, search as tldr_search, FileTree, Language, NodeType, SliceDirection,
};
#[cfg(feature = "semantic")]
use tldr_core::semantic::{BuildOptions, CacheConfig, IndexSearchOptions, SemanticIndex};
#[cfg(test)]
use super::types::DEFAULT_REINDEX_THRESHOLD;

// =============================================================================
// Helper Functions
// =============================================================================

/// Hash a slice of string arguments into a u64 for cache key generation.
fn hash_str_args(parts: &[&str]) -> u64 {
    let mut hasher = DefaultHasher::new();
    for part in parts {
        part.hash(&mut hasher);
    }
    hasher.finish()
}

/// Count the number of file nodes in a FileTree recursively.
fn count_tree_files(tree: &FileTree) -> usize {
    match tree.node_type {
        NodeType::File => 1,
        NodeType::Dir => tree.children.iter().map(count_tree_files).sum(),
    }
}

// =============================================================================
// TLDRDaemon - Main Daemon Process
// =============================================================================

/// Main daemon process that handles client connections and manages state.
///
/// The daemon runs an event loop that:
/// 1. Accepts incoming IPC connections
/// 2. Reads commands from clients
/// 3. Dispatches commands to handlers
/// 4. Sends responses back to clients
/// 5. Handles shutdown signals gracefully
pub struct TLDRDaemon {
    /// Project root directory
    project: PathBuf,
    /// Daemon configuration
    config: DaemonConfig,
    /// When the daemon was started
    start_time: Instant,
    /// Current daemon status
    status: Arc<RwLock<DaemonStatus>>,
    /// Salsa-style query cache
    cache: QueryCache,
    /// Per-session statistics
    sessions: DashMap<String, SessionStats>,
    /// Per-hook activity statistics
    hooks: DashMap<String, HookStats>,
    /// Set of dirty files awaiting reindex
    dirty_files: Arc<RwLock<HashSet<PathBuf>>>,
    /// Shutdown signal sender
    shutdown_tx: watch::Sender<bool>,
    /// Flag to track if we've been signaled to stop
    stopping: AtomicBool,
    /// Last time a client command was handled (for idle timeout)
    last_activity: Arc<RwLock<Instant>>,
    /// Number of indexed files (for status reporting)
    indexed_files: Arc<RwLock<usize>>,
    /// Persistent semantic index (built lazily on first query, invalidated on Notify)
    #[cfg(feature = "semantic")]
    semantic_index: Arc<RwLock<Option<SemanticIndex>>>,
}

impl TLDRDaemon {
    /// Create a new daemon instance.
    ///
    /// The daemon starts in `Initializing` status and must have `run()` called
    /// to begin accepting connections.
    pub fn new(project: PathBuf, config: DaemonConfig) -> Self {
        let (shutdown_tx, _shutdown_rx) = watch::channel(false);

        Self {
            project,
            config,
            start_time: Instant::now(),
            status: Arc::new(RwLock::new(DaemonStatus::Initializing)),
            cache: QueryCache::with_defaults(),
            sessions: DashMap::new(),
            hooks: DashMap::new(),
            dirty_files: Arc::new(RwLock::new(HashSet::new())),
            shutdown_tx,
            stopping: AtomicBool::new(false),
            last_activity: Arc::new(RwLock::new(Instant::now())),
            indexed_files: Arc::new(RwLock::new(0)),
            #[cfg(feature = "semantic")]
            semantic_index: Arc::new(RwLock::new(None)),
        }
    }

    /// Get the daemon's current status.
    pub async fn status(&self) -> DaemonStatus {
        *self.status.read().await
    }

    /// Get the daemon's uptime in seconds.
    pub fn uptime(&self) -> f64 {
        self.start_time.elapsed().as_secs_f64()
    }

    /// Get the daemon's uptime formatted as a human-readable string.
    pub fn uptime_human(&self) -> String {
        let secs = self.start_time.elapsed().as_secs();
        let hours = secs / 3600;
        let minutes = (secs % 3600) / 60;
        let seconds = secs % 60;
        format!("{}h {}m {}s", hours, minutes, seconds)
    }

    /// Get cache statistics.
    pub fn cache_stats(&self) -> SalsaCacheStats {
        self.cache.stats()
    }

    /// Get the project path.
    pub fn project(&self) -> &PathBuf {
        &self.project
    }

    /// Get the number of indexed files.
    pub async fn indexed_files(&self) -> usize {
        *self.indexed_files.read().await
    }

    /// Get a summary of all sessions.
    pub fn all_sessions_summary(&self) -> AllSessionsSummary {
        let mut summary = AllSessionsSummary {
            active_sessions: self.sessions.len(),
            ..AllSessionsSummary::default()
        };

        for entry in self.sessions.iter() {
            let stats = entry.value();
            summary.total_raw_tokens += stats.raw_tokens;
            summary.total_tldr_tokens += stats.tldr_tokens;
            summary.total_requests += stats.requests;
        }

        summary
    }

    /// Get all hook statistics.
    pub fn hook_stats(&self) -> HashMap<String, HookStats> {
        self.hooks
            .iter()
            .map(|e| (e.key().clone(), e.value().clone()))
            .collect()
    }

    /// Signal the daemon to shut down gracefully.
    pub fn shutdown(&self) {
        self.stopping.store(true, Ordering::SeqCst);
        let _ = self.shutdown_tx.send(true);
    }

    /// Run the daemon main loop.
    ///
    /// This function blocks until the daemon is shut down via:
    /// - A `Shutdown` command from a client
    /// - A SIGTERM/SIGINT signal
    /// - An error in the listener
    pub async fn run(self: Arc<Self>, listener: IpcListener) -> DaemonResult<()> {
        // Set status to Ready
        {
            let mut status = self.status.write().await;
            *status = DaemonStatus::Ready;
        }

        // Set up signal handlers for graceful shutdown
        #[cfg(unix)]
        {
            let daemon = Arc::clone(&self);
            tokio::spawn(async move {
                let mut sigterm =
                    tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
                        .expect("Failed to register SIGTERM handler");
                let mut sigint =
                    tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt())
                        .expect("Failed to register SIGINT handler");

                tokio::select! {
                    _ = sigterm.recv() => {
                        daemon.shutdown();
                    }
                    _ = sigint.recv() => {
                        daemon.shutdown();
                    }
                }
            });
        }

        // Main event loop
        let idle_timeout = std::time::Duration::from_secs(self.config.idle_timeout_secs);

        loop {
            // Check for shutdown signal
            if self.stopping.load(Ordering::SeqCst) {
                break;
            }

            // Safety net: self-terminate if project directory no longer exists
            if !self.project.exists() {
                eprintln!(
                    "Project directory {} no longer exists, shutting down",
                    self.project.display()
                );
                break;
            }

            // Self-terminate after idle timeout with no client activity
            {
                let last = self.last_activity.read().await;
                if last.elapsed() > idle_timeout {
                    eprintln!(
                        "No client activity for {}s, shutting down",
                        self.config.idle_timeout_secs
                    );
                    break;
                }
            }

            // Accept connection with timeout
            let accept_future = listener.accept();
            let timeout = tokio::time::Duration::from_millis(100);

            match tokio::time::timeout(timeout, accept_future).await {
                Ok(Ok(mut stream)) => {
                    // Update activity timestamp
                    *self.last_activity.write().await = Instant::now();

                    // Handle the connection
                    let daemon = Arc::clone(&self);
                    tokio::spawn(async move {
                        if let Err(e) = daemon.handle_connection(&mut stream).await {
                            eprintln!("Connection error: {}", e);
                        }
                    });
                }
                Ok(Err(e)) => {
                    // Accept error - log and continue
                    eprintln!("Accept error: {}", e);
                }
                Err(_) => {
                    // Timeout - check shutdown and continue
                    continue;
                }
            }
        }

        // Set status to ShuttingDown
        {
            let mut status = self.status.write().await;
            *status = DaemonStatus::ShuttingDown;
        }

        // Persist stats before exit
        self.persist_stats().await?;

        // Set status to Stopped
        {
            let mut status = self.status.write().await;
            *status = DaemonStatus::Stopped;
        }

        Ok(())
    }

    /// Handle a single client connection.
    async fn handle_connection(self: &Arc<Self>, stream: &mut IpcStream) -> DaemonResult<()> {
        // Read command
        let cmd = read_command(stream).await?;

        // Handle command
        let response = self.handle_command(cmd).await;

        // Send response
        send_response(stream, &response).await?;

        Ok(())
    }

    /// Handle a daemon command and return the response.
    pub async fn handle_command(&self, cmd: DaemonCommand) -> DaemonResponse {
        match cmd {
            DaemonCommand::Ping => DaemonResponse::Status {
                status: "ok".to_string(),
                message: Some("pong".to_string()),
            },

            DaemonCommand::Status { session } => self.handle_status(session).await,

            DaemonCommand::Shutdown => {
                self.shutdown();
                DaemonResponse::Status {
                    status: "shutting_down".to_string(),
                    message: Some("Daemon is shutting down".to_string()),
                }
            }

            DaemonCommand::Notify { file } => self.handle_notify(file).await,

            DaemonCommand::Track {
                hook,
                success,
                metrics,
            } => self.handle_track(hook, success, metrics).await,

            DaemonCommand::Warm { language } => {
                let lang = language
                    .as_deref()
                    .and_then(|l| l.parse::<Language>().ok())
                    .unwrap_or(Language::Python);

                let mut warmed = Vec::new();
                let mut errors = Vec::new();

                // 1. Warm call graph
                let calls_key = QueryKey::new(
                    "calls",
                    hash_str_args(&[&self.project.to_string_lossy()]),
                );
                if self.cache.get::<serde_json::Value>(&calls_key).is_some() {
                    warmed.push("call_graph (cached)");
                } else {
                    match build_project_call_graph(&self.project, lang, None, true) {
                        Ok(result) => {
                            let val = serde_json::to_value(&result).unwrap_or_default();
                            self.cache.insert(calls_key, &val, vec![]);
                            warmed.push("call_graph");
                        }
                        Err(e) => errors.push(format!("call_graph: {}", e)),
                    }
                }

                // 2. Warm code structure
                let struct_key = QueryKey::new(
                    "structure",
                    hash_str_args(&[&self.project.to_string_lossy(), ""]),
                );
                if self.cache.get::<serde_json::Value>(&struct_key).is_some() {
                    warmed.push("structure (cached)");
                } else {
                    match get_code_structure(&self.project, lang, 0, None) {
                        Ok(result) => {
                            let val = serde_json::to_value(&result).unwrap_or_default();
                            self.cache.insert(struct_key, &val, vec![]);
                            warmed.push("structure");
                        }
                        Err(e) => errors.push(format!("structure: {}", e)),
                    }
                }

                // 3. Warm file tree
                let tree_key = QueryKey::new(
                    "tree",
                    hash_str_args(&[&self.project.to_string_lossy()]),
                );
                if self.cache.get::<serde_json::Value>(&tree_key).is_some() {
                    warmed.push("file_tree (cached)");
                } else {
                    match get_file_tree(&self.project, None, true, None) {
                        Ok(result) => {
                            let file_count = count_tree_files(&result);
                            let val = serde_json::to_value(&result).unwrap_or_default();
                            self.cache.insert(tree_key, &val, vec![]);
                            *self.indexed_files.write().await = file_count;
                            warmed.push("file_tree");
                        }
                        Err(e) => errors.push(format!("file_tree: {}", e)),
                    }
                }

                // 4. Warm semantic index
                #[cfg(feature = "semantic")]
                {
                    let mut index_guard = self.semantic_index.write().await;
                    if index_guard.is_some() {
                        warmed.push("semantic_index (cached)");
                    } else {
                        let build_opts = BuildOptions {
                            show_progress: false,
                            use_cache: true,
                            ..Default::default()
                        };
                        match SemanticIndex::build(
                            &self.project,
                            build_opts,
                            Some(CacheConfig::default()),
                        ) {
                            Ok(idx) => {
                                *index_guard = Some(idx);
                                warmed.push("semantic_index");
                            }
                            Err(e) => errors.push(format!("semantic_index: {}", e)),
                        }
                    }
                }

                let message = if errors.is_empty() {
                    format!("Warmed: {}", warmed.join(", "))
                } else {
                    format!(
                        "Warmed: {}. Errors: {}",
                        warmed.join(", "),
                        errors.join("; ")
                    )
                };

                DaemonResponse::Status {
                    status: "ok".to_string(),
                    message: Some(message),
                }
            }

            #[cfg(feature = "semantic")]
            DaemonCommand::Semantic { query, top_k } => {
                // Semantic search with persistent index
                let mut index_guard = self.semantic_index.write().await;

                // Build index lazily on first query
                if index_guard.is_none() {
                    let build_opts = BuildOptions {
                        show_progress: false,
                        use_cache: true,
                        ..Default::default()
                    };
                    let cache_config = Some(CacheConfig::default());

                    match SemanticIndex::build(&self.project, build_opts, cache_config) {
                        Ok(idx) => {
                            *index_guard = Some(idx);
                        }
                        Err(e) => {
                            return DaemonResponse::Error {
                                status: "error".to_string(),
                                error: format!("Failed to build semantic index: {}", e),
                            };
                        }
                    }
                }

                // Search the index
                let index = index_guard.as_mut().unwrap();
                let search_opts = IndexSearchOptions {
                    top_k,
                    threshold: 0.5,
                    include_snippet: true,
                    snippet_lines: 5,
                };

                match index.search(&query, &search_opts) {
                    Ok(report) => match serde_json::to_value(&report) {
                        Ok(value) => DaemonResponse::Result(value),
                        Err(e) => DaemonResponse::Error {
                            status: "error".to_string(),
                            error: format!("Serialization error: {}", e),
                        },
                    },
                    Err(e) => DaemonResponse::Error {
                        status: "error".to_string(),
                        error: format!("Semantic search failed: {}", e),
                    },
                }
            }

            #[cfg(not(feature = "semantic"))]
            DaemonCommand::Semantic { .. } => DaemonResponse::Error {
                status: "error".to_string(),
                error: "Semantic search requires the 'semantic' feature".to_string(),
            },

            // Pass-through analysis commands with Salsa cache integration
            DaemonCommand::Search {
                pattern,
                max_results,
            } => {
                let max = max_results.unwrap_or(100);
                let key = QueryKey::new(
                    "search",
                    hash_str_args(&[&pattern, &max.to_string()]),
                );
                if let Some(cached) = self.cache.get::<serde_json::Value>(&key) {
                    return DaemonResponse::Result(cached);
                }
                match tldr_search(
                    &pattern,
                    &self.project,
                    None,
                    2,
                    max,
                    1000,
                    None,
                ) {
                    Ok(result) => {
                        let val = serde_json::to_value(&result).unwrap_or_default();
                        self.cache.insert(key, &val, vec![]);
                        DaemonResponse::Result(val)
                    }
                    Err(e) => DaemonResponse::Error {
                        status: "error".to_string(),
                        error: e.to_string(),
                    },
                }
            }

            DaemonCommand::Extract { file, session: _ } => {
                let file_str = file.to_string_lossy().to_string();
                let key = QueryKey::new("extract", hash_str_args(&[&file_str]));
                if let Some(cached) = self.cache.get::<serde_json::Value>(&key) {
                    return DaemonResponse::Result(cached);
                }
                let file_hash = super::salsa::hash_path(&file);
                match extract_file(&file, Some(&self.project)) {
                    Ok(result) => {
                        let val = serde_json::to_value(&result).unwrap_or_default();
                        self.cache.insert(key, &val, vec![file_hash]);
                        DaemonResponse::Result(val)
                    }
                    Err(e) => DaemonResponse::Error {
                        status: "error".to_string(),
                        error: e.to_string(),
                    },
                }
            }

            DaemonCommand::Tree { path } => {
                let root = path.unwrap_or_else(|| self.project.clone());
                let root_str = root.to_string_lossy().to_string();
                let key = QueryKey::new("tree", hash_str_args(&[&root_str]));
                if let Some(cached) = self.cache.get::<serde_json::Value>(&key) {
                    return DaemonResponse::Result(cached);
                }
                match get_file_tree(&root, None, true, None) {
                    Ok(result) => {
                        let val = serde_json::to_value(&result).unwrap_or_default();
                        self.cache.insert(key, &val, vec![]);
                        DaemonResponse::Result(val)
                    }
                    Err(e) => DaemonResponse::Error {
                        status: "error".to_string(),
                        error: e.to_string(),
                    },
                }
            }

            DaemonCommand::Structure { path, lang } => {
                let path_str = path.to_string_lossy().to_string();
                let lang_str = lang.as_deref().unwrap_or("");
                let key = QueryKey::new(
                    "structure",
                    hash_str_args(&[&path_str, lang_str]),
                );
                if let Some(cached) = self.cache.get::<serde_json::Value>(&key) {
                    return DaemonResponse::Result(cached);
                }
                let language = match detect_or_parse_language(lang.as_deref(), &path) {
                    Ok(l) => l,
                    Err(e) => {
                        return DaemonResponse::Error {
                            status: "error".to_string(),
                            error: e.to_string(),
                        }
                    }
                };
                match get_code_structure(&path, language, 0, None) {
                    Ok(result) => {
                        let val = serde_json::to_value(&result).unwrap_or_default();
                        self.cache.insert(key, &val, vec![]);
                        DaemonResponse::Result(val)
                    }
                    Err(e) => DaemonResponse::Error {
                        status: "error".to_string(),
                        error: e.to_string(),
                    },
                }
            }

            DaemonCommand::Context { entry, depth } => {
                let d = depth.unwrap_or(2);
                let key = QueryKey::new(
                    "context",
                    hash_str_args(&[&entry, &d.to_string()]),
                );
                if let Some(cached) = self.cache.get::<serde_json::Value>(&key) {
                    return DaemonResponse::Result(cached);
                }
                match get_relevant_context(
                    &self.project,
                    &entry,
                    d,
                    Language::Python,
                    true,
                    None,
                ) {
                    Ok(result) => {
                        let val = serde_json::to_value(&result).unwrap_or_default();
                        self.cache.insert(key, &val, vec![]);
                        DaemonResponse::Result(val)
                    }
                    Err(e) => DaemonResponse::Error {
                        status: "error".to_string(),
                        error: e.to_string(),
                    },
                }
            }

            DaemonCommand::Cfg { file, function } => {
                let file_str = file.to_string_lossy().to_string();
                let key = QueryKey::new(
                    "cfg",
                    hash_str_args(&[&file_str, &function]),
                );
                if let Some(cached) = self.cache.get::<serde_json::Value>(&key) {
                    return DaemonResponse::Result(cached);
                }
                let language = match detect_or_parse_language(None, &file) {
                    Ok(l) => l,
                    Err(e) => {
                        return DaemonResponse::Error {
                            status: "error".to_string(),
                            error: e.to_string(),
                        }
                    }
                };
                let file_hash = super::salsa::hash_path(&file);
                match get_cfg_context(&file_str, &function, language) {
                    Ok(result) => {
                        let val = serde_json::to_value(&result).unwrap_or_default();
                        self.cache.insert(key, &val, vec![file_hash]);
                        DaemonResponse::Result(val)
                    }
                    Err(e) => DaemonResponse::Error {
                        status: "error".to_string(),
                        error: e.to_string(),
                    },
                }
            }

            DaemonCommand::Dfg { file, function } => {
                let file_str = file.to_string_lossy().to_string();
                let key = QueryKey::new(
                    "dfg",
                    hash_str_args(&[&file_str, &function]),
                );
                if let Some(cached) = self.cache.get::<serde_json::Value>(&key) {
                    return DaemonResponse::Result(cached);
                }
                let language = match detect_or_parse_language(None, &file) {
                    Ok(l) => l,
                    Err(e) => {
                        return DaemonResponse::Error {
                            status: "error".to_string(),
                            error: e.to_string(),
                        }
                    }
                };
                let file_hash = super::salsa::hash_path(&file);
                match get_dfg_context(&file_str, &function, language) {
                    Ok(result) => {
                        let val = serde_json::to_value(&result).unwrap_or_default();
                        self.cache.insert(key, &val, vec![file_hash]);
                        DaemonResponse::Result(val)
                    }
                    Err(e) => DaemonResponse::Error {
                        status: "error".to_string(),
                        error: e.to_string(),
                    },
                }
            }

            DaemonCommand::Slice {
                file,
                function,
                line,
            } => {
                let file_str = file.to_string_lossy().to_string();
                let key = QueryKey::new(
                    "slice",
                    hash_str_args(&[&file_str, &function, &line.to_string()]),
                );
                if let Some(cached) = self.cache.get::<serde_json::Value>(&key) {
                    return DaemonResponse::Result(cached);
                }
                let language = match detect_or_parse_language(None, &file) {
                    Ok(l) => l,
                    Err(e) => {
                        return DaemonResponse::Error {
                            status: "error".to_string(),
                            error: e.to_string(),
                        }
                    }
                };
                let file_hash = super::salsa::hash_path(&file);
                match get_slice(
                    &file_str,
                    &function,
                    line as u32,
                    SliceDirection::Backward,
                    None,
                    language,
                ) {
                    Ok(result) => {
                        let val = serde_json::to_value(&result).unwrap_or_default();
                        self.cache.insert(key, &val, vec![file_hash]);
                        DaemonResponse::Result(val)
                    }
                    Err(e) => DaemonResponse::Error {
                        status: "error".to_string(),
                        error: e.to_string(),
                    },
                }
            }

            DaemonCommand::Calls { path } => {
                let root = path.unwrap_or_else(|| self.project.clone());
                let root_str = root.to_string_lossy().to_string();
                let key = QueryKey::new("calls", hash_str_args(&[&root_str]));
                if let Some(cached) = self.cache.get::<serde_json::Value>(&key) {
                    return DaemonResponse::Result(cached);
                }
                match build_project_call_graph(&root, Language::Python, None, true) {
                    Ok(result) => {
                        let val = serde_json::to_value(&result).unwrap_or_default();
                        self.cache.insert(key, &val, vec![]);
                        DaemonResponse::Result(val)
                    }
                    Err(e) => DaemonResponse::Error {
                        status: "error".to_string(),
                        error: e.to_string(),
                    },
                }
            }

            DaemonCommand::Impact { func, depth } => {
                let d = depth.unwrap_or(3);
                let key = QueryKey::new(
                    "impact",
                    hash_str_args(&[&func, &d.to_string()]),
                );
                if let Some(cached) = self.cache.get::<serde_json::Value>(&key) {
                    return DaemonResponse::Result(cached);
                }
                let graph =
                    match build_project_call_graph(&self.project, Language::Python, None, true) {
                        Ok(g) => g,
                        Err(e) => {
                            return DaemonResponse::Error {
                                status: "error".to_string(),
                                error: e.to_string(),
                            }
                        }
                    };
                match impact_analysis(&graph, &func, d, None) {
                    Ok(result) => {
                        let val = serde_json::to_value(&result).unwrap_or_default();
                        self.cache.insert(key, &val, vec![]);
                        DaemonResponse::Result(val)
                    }
                    Err(e) => DaemonResponse::Error {
                        status: "error".to_string(),
                        error: e.to_string(),
                    },
                }
            }

            DaemonCommand::Dead { path, entry } => {
                let root = path.unwrap_or_else(|| self.project.clone());
                let root_str = root.to_string_lossy().to_string();
                let entry_str = entry
                    .as_ref()
                    .map(|v| v.join(","))
                    .unwrap_or_default();
                let key = QueryKey::new(
                    "dead",
                    hash_str_args(&[&root_str, &entry_str]),
                );
                if let Some(cached) = self.cache.get::<serde_json::Value>(&key) {
                    return DaemonResponse::Result(cached);
                }
                let graph =
                    match build_project_call_graph(&root, Language::Python, None, true) {
                        Ok(g) => g,
                        Err(e) => {
                            return DaemonResponse::Error {
                                status: "error".to_string(),
                                error: e.to_string(),
                            }
                        }
                    };
                // Collect all functions from the project by extracting each file
                let extensions: HashSet<String> =
                    Language::Python.extensions().iter().map(|s| s.to_string()).collect();
                let file_tree = match get_file_tree(&root, Some(&extensions), true, None) {
                    Ok(t) => t,
                    Err(e) => {
                        return DaemonResponse::Error {
                            status: "error".to_string(),
                            error: e.to_string(),
                        }
                    }
                };
                let files = tldr_core::fs::tree::collect_files(&file_tree, &root);
                let mut module_infos = Vec::new();
                for file_path in files {
                    if let Ok(info) = extract_file(&file_path, Some(&root)) {
                        module_infos.push((file_path, info));
                    }
                }
                let all_functions = collect_all_functions(&module_infos);
                let entry_strings: Option<Vec<String>> = entry;
                let entry_refs: Option<&[String]> = entry_strings.as_deref();
                match dead_code_analysis(&graph, &all_functions, entry_refs) {
                    Ok(result) => {
                        let val = serde_json::to_value(&result).unwrap_or_default();
                        self.cache.insert(key, &val, vec![]);
                        DaemonResponse::Result(val)
                    }
                    Err(e) => DaemonResponse::Error {
                        status: "error".to_string(),
                        error: e.to_string(),
                    },
                }
            }

            DaemonCommand::Arch { path } => {
                let root = path.unwrap_or_else(|| self.project.clone());
                let root_str = root.to_string_lossy().to_string();
                let key = QueryKey::new("arch", hash_str_args(&[&root_str]));
                if let Some(cached) = self.cache.get::<serde_json::Value>(&key) {
                    return DaemonResponse::Result(cached);
                }
                let graph =
                    match build_project_call_graph(&root, Language::Python, None, true) {
                        Ok(g) => g,
                        Err(e) => {
                            return DaemonResponse::Error {
                                status: "error".to_string(),
                                error: e.to_string(),
                            }
                        }
                    };
                match architecture_analysis(&graph) {
                    Ok(result) => {
                        let val = serde_json::to_value(&result).unwrap_or_default();
                        self.cache.insert(key, &val, vec![]);
                        DaemonResponse::Result(val)
                    }
                    Err(e) => DaemonResponse::Error {
                        status: "error".to_string(),
                        error: e.to_string(),
                    },
                }
            }

            DaemonCommand::Imports { file } => {
                let file_str = file.to_string_lossy().to_string();
                let key = QueryKey::new("imports", hash_str_args(&[&file_str]));
                if let Some(cached) = self.cache.get::<serde_json::Value>(&key) {
                    return DaemonResponse::Result(cached);
                }
                let language = match detect_or_parse_language(None, &file) {
                    Ok(l) => l,
                    Err(e) => {
                        return DaemonResponse::Error {
                            status: "error".to_string(),
                            error: e.to_string(),
                        }
                    }
                };
                let file_hash = super::salsa::hash_path(&file);
                match get_imports(&file, language) {
                    Ok(result) => {
                        let val = serde_json::to_value(&result).unwrap_or_default();
                        self.cache.insert(key, &val, vec![file_hash]);
                        DaemonResponse::Result(val)
                    }
                    Err(e) => DaemonResponse::Error {
                        status: "error".to_string(),
                        error: e.to_string(),
                    },
                }
            }

            DaemonCommand::Importers { module, path } => {
                let root = path.unwrap_or_else(|| self.project.clone());
                let root_str = root.to_string_lossy().to_string();
                let key = QueryKey::new(
                    "importers",
                    hash_str_args(&[&module, &root_str]),
                );
                if let Some(cached) = self.cache.get::<serde_json::Value>(&key) {
                    return DaemonResponse::Result(cached);
                }
                match find_importers(&root, &module, Language::Python) {
                    Ok(result) => {
                        let val = serde_json::to_value(&result).unwrap_or_default();
                        self.cache.insert(key, &val, vec![]);
                        DaemonResponse::Result(val)
                    }
                    Err(e) => DaemonResponse::Error {
                        status: "error".to_string(),
                        error: e.to_string(),
                    },
                }
            }

            DaemonCommand::Diagnostics { path, project: _ } => {
                DaemonResponse::Error {
                    status: "error".to_string(),
                    error: format!(
                        "Diagnostics requires external tool orchestration; \
                         use CLI directly: tldr diagnostics {}",
                        path.display()
                    ),
                }
            }

            DaemonCommand::ChangeImpact {
                files,
                session: _,
                git: _,
            } => {
                let files_str = files
                    .as_ref()
                    .map(|v| {
                        v.iter()
                            .map(|p| p.to_string_lossy().to_string())
                            .collect::<Vec<_>>()
                            .join(",")
                    })
                    .unwrap_or_default();
                let key = QueryKey::new(
                    "change_impact",
                    hash_str_args(&[&files_str]),
                );
                if let Some(cached) = self.cache.get::<serde_json::Value>(&key) {
                    return DaemonResponse::Result(cached);
                }
                let changed: Option<Vec<PathBuf>> = files;
                match change_impact(
                    &self.project,
                    changed.as_deref(),
                    Language::Python,
                ) {
                    Ok(result) => {
                        let val = serde_json::to_value(&result).unwrap_or_default();
                        self.cache.insert(key, &val, vec![]);
                        DaemonResponse::Result(val)
                    }
                    Err(e) => DaemonResponse::Error {
                        status: "error".to_string(),
                        error: e.to_string(),
                    },
                }
            }
        }
    }

    /// Handle the Status command.
    async fn handle_status(&self, session: Option<String>) -> DaemonResponse {
        let status = self.status().await;
        let uptime = self.uptime();
        let files = self.indexed_files().await;
        let salsa_stats = self.cache_stats();
        let all_sessions = Some(self.all_sessions_summary());
        let hook_stats = Some(self.hook_stats());

        // Get session-specific stats if requested
        let session_stats =
            session.and_then(|id| self.sessions.get(&id).map(|entry| entry.value().clone()));

        DaemonResponse::FullStatus {
            status,
            uptime,
            files,
            project: self.project.clone(),
            salsa_stats,
            dedup_stats: None,
            session_stats,
            all_sessions,
            hook_stats,
        }
    }

    /// Handle the Notify command (file change notification).
    async fn handle_notify(&self, file: PathBuf) -> DaemonResponse {
        // Add file to dirty set
        let dirty_count = {
            let mut dirty = self.dirty_files.write().await;
            dirty.insert(file.clone());
            dirty.len()
        };

        // Invalidate cache entries for this file
        let file_hash = super::salsa::hash_path(&file);
        self.cache.invalidate_by_input(file_hash);

        // Invalidate semantic index so it rebuilds on next query
        #[cfg(feature = "semantic")]
        {
            let mut idx = self.semantic_index.write().await;
            *idx = None;
        }

        let threshold = self.config.auto_reindex_threshold;
        let reindex_triggered = dirty_count >= threshold;

        // Trigger reindex if threshold reached
        if reindex_triggered {
            // Clear dirty set
            let mut dirty = self.dirty_files.write().await;
            dirty.clear();

            // In full implementation, would spawn background reindex task
            // For now, just clear the dirty set
        }

        DaemonResponse::NotifyResponse {
            status: "ok".to_string(),
            dirty_count,
            threshold,
            reindex_triggered,
        }
    }

    /// Handle the Track command (hook activity tracking).
    async fn handle_track(
        &self,
        hook: String,
        success: bool,
        metrics: HashMap<String, f64>,
    ) -> DaemonResponse {
        // Get or create hook stats
        let mut entry = self
            .hooks
            .entry(hook.clone())
            .or_insert_with(|| HookStats::new(hook.clone()));

        // Record invocation
        let metrics_opt = if metrics.is_empty() {
            None
        } else {
            Some(metrics)
        };
        entry.record_invocation(success, metrics_opt);

        let total_invocations = entry.invocations;
        let flushed = total_invocations.is_multiple_of(HOOK_FLUSH_THRESHOLD as u64);

        // Flush stats periodically
        if flushed {
            // In full implementation, would persist stats to disk
            // For now, just mark as flushed
        }

        DaemonResponse::TrackResponse {
            status: "ok".to_string(),
            hook,
            total_invocations,
            flushed,
        }
    }

    /// Persist statistics to disk.
    async fn persist_stats(&self) -> DaemonResult<()> {
        // Create cache directory if it doesn't exist
        let cache_dir = self.project.join(".tldr/cache");
        if !cache_dir.exists() {
            std::fs::create_dir_all(&cache_dir)?;
        }

        // Save Salsa cache stats
        let salsa_stats_path = cache_dir.join("salsa_stats.json");
        let stats = self.cache_stats();
        let json = serde_json::to_string_pretty(&stats)?;
        std::fs::write(salsa_stats_path, json)?;

        // Save full query cache
        let cache_path = cache_dir.join("query_cache.bin");
        self.cache.save_to_file(&cache_path)?;

        Ok(())
    }
}

// =============================================================================
// Daemon Control Functions
// =============================================================================

/// Start a daemon in the background for the given project.
///
/// Returns the PID of the daemon process.
pub async fn start_daemon_background(project: &std::path::Path) -> DaemonResult<u32> {
    use std::process::Command;

    // Get the current executable path
    let exe_path = std::env::current_exe().map_err(DaemonError::Io)?;

    // Spawn the daemon process
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;

        let child = unsafe {
            Command::new(&exe_path)
                .args(["daemon", "start", "--project"])
                .arg(project.as_os_str())
                .arg("--foreground")
                .stdin(std::process::Stdio::null())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .pre_exec(|| {
                    // Create new session (detach from terminal)
                    libc::setsid();
                    Ok(())
                })
                .spawn()
                .map_err(DaemonError::Io)?
        };

        Ok(child.id())
    }

    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        const DETACHED_PROCESS: u32 = 0x00000008;
        const CREATE_NO_WINDOW: u32 = 0x08000000;

        let child = Command::new(&exe_path)
            .args(["daemon", "start", "--project"])
            .arg(project.as_os_str())
            .arg("--foreground")
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .creation_flags(DETACHED_PROCESS | CREATE_NO_WINDOW)
            .spawn()
            .map_err(DaemonError::Io)?;

        Ok(child.id())
    }
}

/// Wait for a daemon to become ready by polling the socket.
///
/// Returns `Ok(())` if the daemon becomes available within the timeout.
pub async fn wait_for_daemon(project: &std::path::Path, timeout_secs: u64) -> DaemonResult<()> {
    let start = Instant::now();
    let timeout = std::time::Duration::from_secs(timeout_secs);

    while start.elapsed() < timeout {
        // Try to connect
        if super::ipc::check_socket_alive(project).await {
            return Ok(());
        }

        // Wait a bit before retrying
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    }

    Err(DaemonError::ConnectionTimeout { timeout_secs })
}

// =============================================================================
// Tests
// =============================================================================

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

    #[test]
    fn test_daemon_new() {
        let temp = TempDir::new().unwrap();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        assert_eq!(daemon.project(), temp.path());
        assert!(daemon.uptime() < 1.0);
    }

    #[tokio::test]
    async fn test_daemon_status_initial() {
        let temp = TempDir::new().unwrap();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        assert_eq!(daemon.status().await, DaemonStatus::Initializing);
    }

    #[tokio::test]
    async fn test_daemon_uptime_human() {
        let temp = TempDir::new().unwrap();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let uptime = daemon.uptime_human();
        assert!(uptime.contains("h"));
        assert!(uptime.contains("m"));
        assert!(uptime.contains("s"));
    }

    #[tokio::test]
    async fn test_daemon_handle_ping() {
        let temp = TempDir::new().unwrap();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon.handle_command(DaemonCommand::Ping).await;

        match response {
            DaemonResponse::Status { status, message } => {
                assert_eq!(status, "ok");
                assert_eq!(message, Some("pong".to_string()));
            }
            _ => panic!("Expected Status response"),
        }
    }

    #[tokio::test]
    async fn test_daemon_handle_shutdown() {
        let temp = TempDir::new().unwrap();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon.handle_command(DaemonCommand::Shutdown).await;

        match response {
            DaemonResponse::Status { status, .. } => {
                assert_eq!(status, "shutting_down");
            }
            _ => panic!("Expected Status response"),
        }

        // Verify daemon is stopping
        assert!(daemon.stopping.load(Ordering::SeqCst));
    }

    #[tokio::test]
    async fn test_daemon_handle_notify() {
        let temp = TempDir::new().unwrap();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let file = temp.path().join("test.rs");
        let response = daemon.handle_command(DaemonCommand::Notify { file }).await;

        match response {
            DaemonResponse::NotifyResponse {
                dirty_count,
                threshold,
                reindex_triggered,
                ..
            } => {
                assert_eq!(dirty_count, 1);
                assert_eq!(threshold, DEFAULT_REINDEX_THRESHOLD);
                assert!(!reindex_triggered);
            }
            _ => panic!("Expected NotifyResponse"),
        }
    }

    #[tokio::test]
    async fn test_daemon_handle_notify_threshold() {
        let temp = TempDir::new().unwrap();
        let config = DaemonConfig {
            auto_reindex_threshold: 3, // Lower threshold for testing
            ..DaemonConfig::default()
        };
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        // Add files up to threshold
        for i in 0..3 {
            let file = temp.path().join(format!("test{}.rs", i));
            daemon.handle_command(DaemonCommand::Notify { file }).await;
        }

        // The third notification should trigger reindex
        let file = temp.path().join("test3.rs");
        let response = daemon.handle_command(DaemonCommand::Notify { file }).await;

        match response {
            DaemonResponse::NotifyResponse {
                reindex_triggered: _, ..
            } => {
                // After threshold is hit, dirty set is cleared
                // So reindex_triggered would have been true, but dirty_count is now 1
            }
            _ => panic!("Expected NotifyResponse"),
        }
    }

    #[tokio::test]
    async fn test_daemon_handle_track() {
        let temp = TempDir::new().unwrap();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon
            .handle_command(DaemonCommand::Track {
                hook: "test-hook".to_string(),
                success: true,
                metrics: HashMap::new(),
            })
            .await;

        match response {
            DaemonResponse::TrackResponse {
                hook,
                total_invocations,
                ..
            } => {
                assert_eq!(hook, "test-hook");
                assert_eq!(total_invocations, 1);
            }
            _ => panic!("Expected TrackResponse"),
        }
    }

    #[tokio::test]
    async fn test_daemon_all_sessions_summary() {
        let temp = TempDir::new().unwrap();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        // Add a session
        daemon.sessions.insert(
            "test-session".to_string(),
            SessionStats {
                session_id: "test-session".to_string(),
                raw_tokens: 1000,
                tldr_tokens: 100,
                requests: 10,
                started_at: None,
            },
        );

        let summary = daemon.all_sessions_summary();
        assert_eq!(summary.active_sessions, 1);
        assert_eq!(summary.total_raw_tokens, 1000);
        assert_eq!(summary.total_tldr_tokens, 100);
        assert_eq!(summary.total_requests, 10);
    }

    // =========================================================================
    // Pass-through handler tests
    // =========================================================================

    /// Helper to create a temp dir with a Python file for testing
    fn create_test_project() -> TempDir {
        let temp = TempDir::new().unwrap();
        let py_file = temp.path().join("main.py");
        std::fs::write(
            &py_file,
            "def hello():\n    \"\"\"Say hello.\"\"\"\n    return 'hello'\n\ndef main():\n    hello()\n",
        )
        .unwrap();
        temp
    }

    #[test]
    fn test_hash_str_args_deterministic() {
        let h1 = hash_str_args(&["search", "pattern", "100"]);
        let h2 = hash_str_args(&["search", "pattern", "100"]);
        assert_eq!(h1, h2);
    }

    #[test]
    fn test_hash_str_args_different_inputs() {
        let h1 = hash_str_args(&["search", "pattern_a"]);
        let h2 = hash_str_args(&["search", "pattern_b"]);
        assert_ne!(h1, h2);
    }

    #[tokio::test]
    async fn test_daemon_search_returns_result() {
        let temp = create_test_project();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon
            .handle_command(DaemonCommand::Search {
                pattern: "def hello".to_string(),
                max_results: Some(10),
            })
            .await;

        match response {
            DaemonResponse::Result(val) => {
                assert!(val.is_array(), "Search should return an array of matches");
                let arr = val.as_array().unwrap();
                assert!(!arr.is_empty(), "Should find at least one match for 'def hello'");
            }
            DaemonResponse::Error { error, .. } => {
                panic!("Search returned error: {}", error);
            }
            other => panic!("Expected Result response, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_daemon_search_caches_result() {
        let temp = create_test_project();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        // First call populates cache
        let _r1 = daemon
            .handle_command(DaemonCommand::Search {
                pattern: "def hello".to_string(),
                max_results: Some(10),
            })
            .await;

        // Second call should hit cache
        let _r2 = daemon
            .handle_command(DaemonCommand::Search {
                pattern: "def hello".to_string(),
                max_results: Some(10),
            })
            .await;

        let stats = daemon.cache_stats();
        assert!(stats.hits >= 1, "Second call should hit cache");
    }

    #[tokio::test]
    async fn test_daemon_extract_returns_result() {
        let temp = create_test_project();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon
            .handle_command(DaemonCommand::Extract {
                file: temp.path().join("main.py"),
                session: None,
            })
            .await;

        match response {
            DaemonResponse::Result(val) => {
                assert!(val.is_object(), "Extract should return a module info object");
                // Should contain functions field
                assert!(val.get("functions").is_some(), "Should have 'functions' field");
            }
            DaemonResponse::Error { error, .. } => {
                panic!("Extract returned error: {}", error);
            }
            other => panic!("Expected Result response, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_daemon_extract_nonexistent_file() {
        let temp = TempDir::new().unwrap();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon
            .handle_command(DaemonCommand::Extract {
                file: temp.path().join("nonexistent.py"),
                session: None,
            })
            .await;

        match response {
            DaemonResponse::Error { error, .. } => {
                assert!(
                    !error.is_empty(),
                    "Should return an error for nonexistent file"
                );
            }
            _ => panic!("Expected Error response for nonexistent file"),
        }
    }

    #[tokio::test]
    async fn test_daemon_tree_returns_result() {
        let temp = create_test_project();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon
            .handle_command(DaemonCommand::Tree { path: None })
            .await;

        match response {
            DaemonResponse::Result(val) => {
                assert!(val.is_object(), "Tree should return a FileTree object");
            }
            DaemonResponse::Error { error, .. } => {
                panic!("Tree returned error: {}", error);
            }
            other => panic!("Expected Result response, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_daemon_structure_returns_result() {
        let temp = create_test_project();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon
            .handle_command(DaemonCommand::Structure {
                path: temp.path().to_path_buf(),
                lang: Some("python".to_string()),
            })
            .await;

        match response {
            DaemonResponse::Result(val) => {
                assert!(val.is_object(), "Structure should return a CodeStructure object");
            }
            DaemonResponse::Error { error, .. } => {
                panic!("Structure returned error: {}", error);
            }
            other => panic!("Expected Result response, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_daemon_imports_returns_result() {
        let temp = create_test_project();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon
            .handle_command(DaemonCommand::Imports {
                file: temp.path().join("main.py"),
            })
            .await;

        match response {
            DaemonResponse::Result(val) => {
                assert!(val.is_array(), "Imports should return an array");
            }
            DaemonResponse::Error { error, .. } => {
                panic!("Imports returned error: {}", error);
            }
            other => panic!("Expected Result response, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_daemon_cfg_returns_result() {
        let temp = create_test_project();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let file = temp.path().join("main.py");
        let response = daemon
            .handle_command(DaemonCommand::Cfg {
                file,
                function: "hello".to_string(),
            })
            .await;

        match response {
            DaemonResponse::Result(val) => {
                assert!(val.is_object(), "Cfg should return a CfgInfo object");
                assert!(val.get("function").is_some(), "Should have 'function' field");
            }
            DaemonResponse::Error { error, .. } => {
                panic!("Cfg returned error: {}", error);
            }
            other => panic!("Expected Result response, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_daemon_dfg_returns_result() {
        let temp = create_test_project();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let file = temp.path().join("main.py");
        let response = daemon
            .handle_command(DaemonCommand::Dfg {
                file,
                function: "hello".to_string(),
            })
            .await;

        match response {
            DaemonResponse::Result(val) => {
                assert!(val.is_object(), "Dfg should return a DfgInfo object");
                assert!(val.get("function").is_some(), "Should have 'function' field");
            }
            DaemonResponse::Error { error, .. } => {
                panic!("Dfg returned error: {}", error);
            }
            other => panic!("Expected Result response, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_daemon_calls_returns_result() {
        let temp = create_test_project();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon
            .handle_command(DaemonCommand::Calls { path: None })
            .await;

        match response {
            DaemonResponse::Result(val) => {
                assert!(val.is_object(), "Calls should return a ProjectCallGraph object");
            }
            DaemonResponse::Error { error, .. } => {
                panic!("Calls returned error: {}", error);
            }
            other => panic!("Expected Result response, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_daemon_arch_returns_result() {
        let temp = create_test_project();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon
            .handle_command(DaemonCommand::Arch { path: None })
            .await;

        match response {
            DaemonResponse::Result(val) => {
                assert!(val.is_object(), "Arch should return an ArchitectureReport object");
            }
            DaemonResponse::Error { error, .. } => {
                panic!("Arch returned error: {}", error);
            }
            other => panic!("Expected Result response, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_daemon_diagnostics_returns_error_with_guidance() {
        let temp = TempDir::new().unwrap();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let path = temp.path().join("src");
        let response = daemon
            .handle_command(DaemonCommand::Diagnostics {
                path: path.clone(),
                project: None,
            })
            .await;

        match response {
            DaemonResponse::Error { error, .. } => {
                assert!(
                    error.contains("Diagnostics requires external tool orchestration"),
                    "Error should explain that diagnostics needs CLI: {}",
                    error
                );
                assert!(
                    error.contains("tldr diagnostics"),
                    "Error should suggest CLI usage"
                );
            }
            other => panic!("Expected Error response, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_daemon_importers_returns_result() {
        let temp = create_test_project();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon
            .handle_command(DaemonCommand::Importers {
                module: "os".to_string(),
                path: None,
            })
            .await;

        match response {
            DaemonResponse::Result(val) => {
                assert!(val.is_object(), "Importers should return an ImportersReport object");
            }
            DaemonResponse::Error { error, .. } => {
                panic!("Importers returned error: {}", error);
            }
            other => panic!("Expected Result response, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_daemon_dead_returns_result() {
        let temp = create_test_project();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon
            .handle_command(DaemonCommand::Dead {
                path: None,
                entry: None,
            })
            .await;

        match response {
            DaemonResponse::Result(val) => {
                assert!(val.is_object(), "Dead should return a DeadCodeReport object");
            }
            DaemonResponse::Error { error, .. } => {
                panic!("Dead returned error: {}", error);
            }
            other => panic!("Expected Result response, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_daemon_change_impact_returns_result() {
        let temp = create_test_project();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon
            .handle_command(DaemonCommand::ChangeImpact {
                files: Some(vec![temp.path().join("main.py")]),
                session: None,
                git: None,
            })
            .await;

        match response {
            DaemonResponse::Result(val) => {
                assert!(
                    val.is_object(),
                    "ChangeImpact should return a ChangeImpactReport object"
                );
            }
            DaemonResponse::Error { error, .. } => {
                panic!("ChangeImpact returned error: {}", error);
            }
            other => panic!("Expected Result response, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_daemon_extract_cache_invalidation() {
        let temp = create_test_project();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let file = temp.path().join("main.py");

        // First extract populates cache
        let r1 = daemon
            .handle_command(DaemonCommand::Extract {
                file: file.clone(),
                session: None,
            })
            .await;
        assert!(matches!(r1, DaemonResponse::Result(_)));

        // Notify file change - should invalidate the cache entry
        daemon
            .handle_command(DaemonCommand::Notify { file: file.clone() })
            .await;

        // After invalidation, next extract should be a cache miss
        let _r2 = daemon
            .handle_command(DaemonCommand::Extract {
                file,
                session: None,
            })
            .await;

        let stats = daemon.cache_stats();
        // Should have: 1 miss (first), 1 invalidation, 1 miss (after invalidation)
        assert!(
            stats.invalidations >= 1,
            "File notify should have caused invalidation"
        );
    }

    #[tokio::test]
    async fn test_daemon_slice_returns_result() {
        let temp = create_test_project();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let file = temp.path().join("main.py");
        let response = daemon
            .handle_command(DaemonCommand::Slice {
                file,
                function: "hello".to_string(),
                line: 3,
            })
            .await;

        match response {
            DaemonResponse::Result(val) => {
                assert!(val.is_array(), "Slice should return an array of line numbers");
            }
            DaemonResponse::Error { error, .. } => {
                panic!("Slice returned error: {}", error);
            }
            other => panic!("Expected Result response, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_daemon_context_returns_result_or_error() {
        let temp = create_test_project();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon
            .handle_command(DaemonCommand::Context {
                entry: "main".to_string(),
                depth: Some(1),
            })
            .await;

        // Context may return Result or Error depending on whether 'main' is found
        // in the call graph. Both are valid outcomes for this test.
        match response {
            DaemonResponse::Result(val) => {
                assert!(val.is_object(), "Context should return a RelevantContext object");
            }
            DaemonResponse::Error { .. } => {
                // Function not found in call graph is acceptable
            }
            other => panic!("Expected Result or Error response, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_daemon_impact_returns_result_or_error() {
        let temp = create_test_project();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon
            .handle_command(DaemonCommand::Impact {
                func: "hello".to_string(),
                depth: Some(2),
            })
            .await;

        // Impact may return Result or Error depending on call graph contents
        match response {
            DaemonResponse::Result(val) => {
                assert!(val.is_object(), "Impact should return an ImpactReport object");
            }
            DaemonResponse::Error { .. } => {
                // Function not found in call graph is acceptable for small test projects
            }
            other => panic!("Expected Result or Error response, got {:?}", other),
        }
    }

    #[cfg(feature = "semantic")]
    #[tokio::test]
    async fn test_semantic_search_builds_index() {
        // Create a temp dir with a simple Python file
        let temp = tempfile::tempdir().unwrap();
        let py_file = temp.path().join("hello.py");
        std::fs::write(
            &py_file,
            "def greet(name):\n    return f'Hello, {name}!'\n\ndef farewell(name):\n    return f'Goodbye, {name}!'\n",
        )
        .unwrap();

        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon
            .handle_command(DaemonCommand::Semantic {
                query: "greeting function".to_string(),
                top_k: 5,
            })
            .await;

        // Should return a Result with search results, not an error
        match &response {
            DaemonResponse::Result(value) => {
                assert!(value.get("query").is_some());
                assert!(value.get("results").is_some());
            }
            DaemonResponse::Error { error, .. } => {
                // May fail in CI without ONNX model - that's acceptable
                // but it should NOT say "not yet implemented"
                assert!(
                    !error.contains("not yet implemented"),
                    "Semantic search should be wired, got: {}",
                    error
                );
            }
            other => panic!("Unexpected response: {:?}", other),
        }
    }

    #[cfg(feature = "semantic")]
    #[tokio::test]
    async fn test_semantic_index_invalidated_on_notify() {
        let temp = tempfile::tempdir().unwrap();
        let py_file = temp.path().join("example.py");
        std::fs::write(&py_file, "def compute(x):\n    return x * 2\n").unwrap();

        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        // First semantic search - builds index
        let _ = daemon
            .handle_command(DaemonCommand::Semantic {
                query: "computation".to_string(),
                top_k: 5,
            })
            .await;

        // Verify index is populated
        {
            let idx = daemon.semantic_index.read().await;
            // Index may be Some (if ONNX model available) or None (if build failed)
            // We just verify the field exists and is accessible
            let _ = idx.is_some();
        }

        // Notify a file change - should invalidate the index
        let _ = daemon
            .handle_command(DaemonCommand::Notify {
                file: py_file.clone(),
            })
            .await;

        // Verify index was cleared
        {
            let idx = daemon.semantic_index.read().await;
            assert!(
                idx.is_none(),
                "Semantic index should be invalidated after Notify"
            );
        }
    }

    #[tokio::test]
    async fn test_daemon_warm_wires_caches() {
        let temp = tempfile::tempdir().unwrap();
        let py_file = temp.path().join("example.py");
        std::fs::write(
            &py_file,
            "def add(a, b):\n    return a + b\n\ndef multiply(x, y):\n    return x * y\n",
        )
        .unwrap();

        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon
            .handle_command(DaemonCommand::Warm { language: None })
            .await;

        match &response {
            DaemonResponse::Status { status, message } => {
                assert_eq!(status, "ok");
                let msg = message.as_deref().unwrap_or("");
                // Should mention what was warmed, not just "Warm completed"
                assert!(
                    msg.contains("Warmed"),
                    "Expected warm details, got: {}",
                    msg
                );
            }
            other => panic!("Expected Status response, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_daemon_warm_with_language() {
        let temp = tempfile::tempdir().unwrap();
        let rs_file = temp.path().join("lib.rs");
        std::fs::write(
            &rs_file,
            "pub fn hello() -> String {\n    \"hello\".to_string()\n}\n",
        )
        .unwrap();

        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        let response = daemon
            .handle_command(DaemonCommand::Warm {
                language: Some("rust".to_string()),
            })
            .await;

        match &response {
            DaemonResponse::Status { status, .. } => {
                assert_eq!(status, "ok");
            }
            other => panic!("Expected Status response, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_daemon_last_activity_updated_on_command() {
        let temp = tempfile::tempdir().unwrap();
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(temp.path().to_path_buf(), config);

        // Record initial activity time
        let before = *daemon.last_activity.read().await;

        // Small delay to ensure time difference
        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;

        // Any command should NOT update last_activity (only connections do),
        // but handle_command is what we can test. Verify the field exists and is accessible.
        let _ = daemon
            .handle_command(DaemonCommand::Ping)
            .await;

        // last_activity is set at connection accept, not command handling,
        // so it should still be the initial value
        let after = *daemon.last_activity.read().await;
        assert_eq!(before, after);
    }

    #[tokio::test]
    async fn test_daemon_created_with_nonexistent_project() {
        // Daemon should be constructable with any path — the exists() check
        // happens in the run loop, not in new()
        let fake_path = PathBuf::from("/tmp/nonexistent-project-dir-12345");
        let config = DaemonConfig::default();
        let daemon = TLDRDaemon::new(fake_path.clone(), config);

        assert_eq!(daemon.project(), &fake_path);
        // The project doesn't exist, but daemon construction succeeds.
        // The run() loop would detect this and self-terminate.
        assert!(!fake_path.exists());
    }
}