matrixcode-core 0.4.27

MatrixCode Agent Core - Pure logic, no UI
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
//! CodeGraph tool for semantic code analysis.
//!
//! Integrates CodeGraph (https://github.com/colbymchenry/codegraph) for:
//! - Symbol search across the codebase
//! - Call graph analysis (callers/callees)
//! - Impact analysis for code changes
//! - Task context building for AI agents
//!
//! Uses SQLite direct access for fast queries, and CLI for index building.
//!
//! # Auto-sync
//!
//! CodeGraphWatcher provides automatic file watching and index synchronization.
//! When source files change, it automatically runs `codegraph sync` to keep
//! the index up-to-date.

use anyhow::Result;
use async_trait::async_trait;
use notify::{Config, Event, RecommendedWatcher, RecursiveMode, Watcher};
use rusqlite::{Connection, params};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use tokio::process::Command;
use tokio::sync::{broadcast, mpsc, RwLock};
use tokio::time::{sleep, timeout};

use super::{Tool, ToolDefinition};
use crate::approval::RiskLevel;
use crate::cancel::CancellationToken;
use crate::constants::{CODEGRAPH_CLI_TIMEOUT_SECS, CODEGRAPH_SYNC_INTERVAL_SECS};
use crate::memory::ProjectStructureAnalyzer;

// ============================================================================
// Data Structures
// ============================================================================

/// Code symbol node from CodeGraph index.
#[derive(Debug, Serialize, Deserialize)]
pub struct Node {
    pub id: String,
    pub kind: String,
    pub name: String,
    pub qualified_name: String,
    pub file_path: String,
    pub language: String,
    pub start_line: u32,
    pub end_line: u32,
    pub start_column: u32,
    pub end_column: u32,
    pub signature: Option<String>,
    pub docstring: Option<String>,
    pub visibility: Option<String>,
    pub is_exported: bool,
    pub is_async: bool,
}

/// Edge representing relationship between nodes.
#[derive(Debug, Serialize, Deserialize)]
pub struct Edge {
    pub source: String,
    pub target: String,
    pub kind: String,
    pub line: Option<u32>,
}

/// Index status information.
#[derive(Debug, Serialize, Deserialize)]
pub struct IndexStatus {
    pub initialized: bool,
    pub file_count: u32,
    pub node_count: u32,
    pub edge_count: u32,
    pub languages: Vec<String>,
    pub pending_changes: PendingChanges,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PendingChanges {
    pub added: u32,
    pub modified: u32,
    pub removed: u32,
}

// ============================================================================
// CodeGraph CLI Detection and Installation
// ============================================================================

/// Get CodeGraph installation directory (platform-specific).
fn get_codegraph_install_dir() -> Option<PathBuf> {
    // Use dirs crate to get platform-appropriate local data directory
    dirs::data_local_dir()
        .map(|p| p.join("codegraph").join("current").join("bin"))
}

/// Get CodeGraph CLI executable name (platform-specific).
fn get_codegraph_exe_name() -> String {
    if cfg!(windows) {
        "codegraph.cmd".to_string()
    } else {
        "codegraph".to_string()
    }
}

/// Check if CodeGraph CLI is installed.
pub fn is_codegraph_installed() -> bool {
    // Try direct command (in PATH)
    if std::process::Command::new("codegraph")
        .arg("--version")
        .output()
        .is_ok() {
        return true;
    }

    // Try platform-specific installation path
    if let Some(install_dir) = get_codegraph_install_dir() {
        let exe_name = get_codegraph_exe_name();
        let exe_path = install_dir.join(&exe_name);
        if exe_path.exists()
            && std::process::Command::new(&exe_path)
                .arg("--version")
                .output()
                .is_ok() {
                return true;
            }
    }

    false
}

/// Get CodeGraph CLI path (returns the executable path or command name).
pub fn get_codegraph_path() -> Option<String> {
    // Try direct command first (in PATH)
    if std::process::Command::new("codegraph")
        .arg("--version")
        .output()
        .is_ok() {
        return Some("codegraph".to_string());
    }

    // Try platform-specific installation path
    if let Some(install_dir) = get_codegraph_install_dir() {
        let exe_name = get_codegraph_exe_name();
        let exe_path = install_dir.join(&exe_name);
        if exe_path.exists() {
            return Some(exe_path.to_string_lossy().to_string());
        }
    }

    None
}

/// Auto-install CodeGraph CLI (Windows).
pub async fn install_codegraph() -> Result<()> {
    log::info!("Installing CodeGraph CLI...");

    // Windows PowerShell installer
    let result = Command::new("powershell")
        .args([
            "-NoProfile",
            "-Command",
            "irm https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.ps1 | iex"
        ])
        .output()
        .await?;

    if result.status.success() {
        log::info!("CodeGraph CLI installed successfully");
        Ok(())
    } else {
        let stderr = String::from_utf8_lossy(&result.stderr);
        Err(anyhow::anyhow!("CodeGraph installation failed: {}", stderr))
    }
}

/// CodeGraph installation status.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CodeGraphInstallStatus {
    /// Already installed and available.
    Installed(String),
    /// Not installed, needs user approval to install.
    NotInstalled,
}

/// Check CodeGraph installation status (no auto-install).
pub fn check_codegraph_status() -> CodeGraphInstallStatus {
    match get_codegraph_path() {
        Some(path) => CodeGraphInstallStatus::Installed(path),
        None => CodeGraphInstallStatus::NotInstalled,
    }
}

/// Ensure CodeGraph is available with optional auto-install.
pub async fn ensure_codegraph() -> Result<String> {
    if let Some(path) = get_codegraph_path() {
        return Ok(path);
    }

    // Auto-install
    install_codegraph().await?;

    // Check again after installation
    get_codegraph_path()
        .ok_or_else(|| anyhow::anyhow!("CodeGraph installation failed - please install manually"))
}

/// Ensure CodeGraph with user prompt support.
/// Returns None if not installed and user declined installation.
pub async fn ensure_codegraph_with_prompt(prompt_fn: impl FnOnce() -> bool) -> Result<Option<String>> {
    match get_codegraph_path() {
        Some(path) => Ok(Some(path)),
        None => {
            // Prompt user for installation
            if prompt_fn() {
                install_codegraph().await?;
                get_codegraph_path()
                    .ok_or_else(|| anyhow::anyhow!("CodeGraph installation failed - please install manually"))
                    .map(Some)
            } else {
                Ok(None)
            }
        }
    }
}

// ============================================================================
// CodeGraph Manager
// ============================================================================

/// Manages CodeGraph index for a project.
pub struct CodeGraphManager {
    project_path: PathBuf,
    db_path: PathBuf,
}

impl CodeGraphManager {
    /// Create manager for a project path.
    pub fn new(project_path: &Path) -> Self {
        let db_path = project_path.join(".codegraph").join("codegraph.db");
        Self {
            project_path: project_path.to_path_buf(),
            db_path,
        }
    }

    /// Create manager with automatic project root detection.
    /// Uses find_project_root() to locate the correct directory.
    pub fn with_auto_detect(start_path: &Path) -> Self {
        let project_path = find_project_root(start_path);
        Self::new(&project_path)
    }

    /// Check if CodeGraph is initialized for this project.
    pub fn is_initialized(&self) -> bool {
        self.db_path.exists()
    }

    /// Get SQLite connection (read-only for safety).
    pub fn connect(&self) -> Result<Connection> {
        let conn = Connection::open(&self.db_path)?;
        // Enable read-only mode
        conn.execute_batch("PRAGMA query_only = ON;")?;
        Ok(conn)
    }

    /// Initialize CodeGraph index via CLI.
    pub async fn init(&self) -> Result<()> {
        self.run_cli_command(&["init", "-i"]).await?;
        Ok(())
    }

    /// Reinitialize CodeGraph - delete old index, matrix.md and rebuild.
    /// Returns error if CodeGraph CLI is not installed.
    pub async fn reinit(&self) -> Result<()> {
        // Check if CodeGraph CLI is available
        if get_codegraph_path().is_none() {
            return Err(anyhow::anyhow!(
                "CodeGraph CLI not installed. Please install first or use init with --install flag."
            ));
        }

        // Delete old .codegraph directory
        let codegraph_dir = self.project_path.join(".codegraph");
        if codegraph_dir.exists() {
            log::info!("CodeGraph: deleting old index at {}", codegraph_dir.display());
            std::fs::remove_dir_all(&codegraph_dir)?;
        }

        // Delete matrix.md overview file (if exists)
        let matrix_md_path = self.project_path.join(".matrix").join("matrix.md");
        if matrix_md_path.exists() {
            log::info!("CodeGraph: deleting old matrix.md at {}", matrix_md_path.display());
            std::fs::remove_file(&matrix_md_path)?;
        }

        // Rebuild fresh index
        log::info!("CodeGraph: rebuilding index for {}", self.project_path.display());
        self.init().await?;

        // Sync to ensure everything is up to date
        self.sync().await?;

        // Save version after reinit
        update_version_after_sync(&self.project_path);

        Ok(())
    }

    /// Sync index with latest file changes.
    pub async fn sync(&self) -> Result<()> {
        self.run_cli_command(&["sync"]).await?;
        Ok(())
    }

    /// Run codegraph CLI command.
    async fn run_cli_command(&self, args: &[&str]) -> Result<()> {
        let codegraph_path = get_codegraph_path()
            .ok_or_else(|| anyhow::anyhow!("CodeGraph CLI not installed. Run 'codegraph install' or use matrixcode to auto-install."))?;

        timeout(Duration::from_secs(CODEGRAPH_CLI_TIMEOUT_SECS), async {
            // Create command with hidden window on Windows
            #[cfg(target_os = "windows")]
            {
                use std::os::windows::process::CommandExt;
                const CREATE_NO_WINDOW: u32 = 0x08000000;

                let mut std_cmd = std::process::Command::new(&codegraph_path);
                std_cmd.args(args)
                    .current_dir(&self.project_path)
                    .creation_flags(CREATE_NO_WINDOW);

                let result = std_cmd.output()?;
                if !result.status.success() {
                    let stderr = String::from_utf8_lossy(&result.stderr);
                    return Err(anyhow::anyhow!("CodeGraph command failed: {}", stderr));
                }
                Ok::<_, anyhow::Error>(())
            }

            #[cfg(not(target_os = "windows"))]
            {
                let result = Command::new(&codegraph_path)
                    .args(args)
                    .current_dir(&self.project_path)
                    .output()
                    .await?;

                if !result.status.success() {
                    let stderr = String::from_utf8_lossy(&result.stderr);
                    return Err(anyhow::anyhow!("CodeGraph command failed: {}", stderr));
                }
                Ok::<_, anyhow::Error>(())
            }
        })
        .await
        .map_err(|_| anyhow::anyhow!(format!("CodeGraph CLI timeout ({})s", CODEGRAPH_CLI_TIMEOUT_SECS)))?
    }

    /// Initialize CodeGraph for this project (check CLI and auto-install if needed).
    pub async fn ensure_initialized(&self) -> Result<()> {
        // Ensure CLI is installed
        ensure_codegraph().await?;

        // Check if this is a code project
        let analyzer = ProjectStructureAnalyzer::new(self.project_path.clone());
        if analyzer.detect_project_type().is_none() {
            return Err(anyhow::anyhow!(
                "Not a code project directory: {}. CodeGraph requires a project with Cargo.toml, package.json, go.mod, etc.",
                self.project_path.display()
            ));
        }

        // Initialize if not already
        if !self.is_initialized() {
            log::info!("Initializing CodeGraph for: {}", self.project_path.display());
            self.init().await?;
        }

        Ok(())
    }

    // ========================================================================
    // Query Methods
    // ========================================================================

    /// Search symbols by name pattern.
    pub fn search(&self, pattern: &str, limit: usize) -> Result<Vec<Node>> {
        let conn = self.connect()?;
        let mut stmt = conn.prepare(
            "SELECT id, kind, name, qualified_name, file_path, language,
                    start_line, end_line, start_column, end_column,
                    signature, docstring, visibility, is_exported, is_async
             FROM nodes
             WHERE name LIKE ? OR qualified_name LIKE ?
             ORDER BY name
             LIMIT ?"
        )?;

        let pattern = format!("%{}%", pattern);
        let nodes = stmt.query_map(params![&pattern, &pattern, limit], |row| {
            Ok(Node {
                id: row.get(0)?,
                kind: row.get(1)?,
                name: row.get(2)?,
                qualified_name: row.get(3)?,
                file_path: row.get(4)?,
                language: row.get(5)?,
                start_line: row.get(6)?,
                end_line: row.get(7)?,
                start_column: row.get(8)?,
                end_column: row.get(9)?,
                signature: row.get(10)?,
                docstring: row.get(11)?,
                visibility: row.get(12)?,
                is_exported: row.get::<_, i32>(13)? != 0,
                is_async: row.get::<_, i32>(14)? != 0,
            })
        })?
        .collect::<Result<Vec<_>, _>>()?;

        Ok(nodes)
    }

    /// Find callers of a symbol (what calls this function).
    pub fn callers(&self, symbol_id: &str, limit: usize) -> Result<Vec<Node>> {
        let conn = self.connect()?;
        let mut stmt = conn.prepare(
            "SELECT n.id, n.kind, n.name, n.qualified_name, n.file_path, n.language,
                    n.start_line, n.end_line, n.start_column, n.end_column,
                    n.signature, n.docstring, n.visibility, n.is_exported, n.is_async
             FROM nodes n
             INNER JOIN edges e ON n.id = e.source
             WHERE e.target = ? AND e.kind = 'calls'
             LIMIT ?"
        )?;

        let nodes = stmt.query_map(params![symbol_id, limit], |row| {
            Ok(Node {
                id: row.get(0)?,
                kind: row.get(1)?,
                name: row.get(2)?,
                qualified_name: row.get(3)?,
                file_path: row.get(4)?,
                language: row.get(5)?,
                start_line: row.get(6)?,
                end_line: row.get(7)?,
                start_column: row.get(8)?,
                end_column: row.get(9)?,
                signature: row.get(10)?,
                docstring: row.get(11)?,
                visibility: row.get(12)?,
                is_exported: row.get::<_, i32>(13)? != 0,
                is_async: row.get::<_, i32>(14)? != 0,
            })
        })?
        .collect::<Result<Vec<_>, _>>()?;

        Ok(nodes)
    }

    /// Find callees of a symbol (what this function calls).
    pub fn callees(&self, symbol_id: &str, limit: usize) -> Result<Vec<Node>> {
        let conn = self.connect()?;
        let mut stmt = conn.prepare(
            "SELECT n.id, n.kind, n.name, n.qualified_name, n.file_path, n.language,
                    n.start_line, n.end_line, n.start_column, n.end_column,
                    n.signature, n.docstring, n.visibility, n.is_exported, n.is_async
             FROM nodes n
             INNER JOIN edges e ON n.id = e.target
             WHERE e.source = ? AND e.kind = 'calls'
             LIMIT ?"
        )?;

        let nodes = stmt.query_map(params![symbol_id, limit], |row| {
            Ok(Node {
                id: row.get(0)?,
                kind: row.get(1)?,
                name: row.get(2)?,
                qualified_name: row.get(3)?,
                file_path: row.get(4)?,
                language: row.get(5)?,
                start_line: row.get(6)?,
                end_line: row.get(7)?,
                start_column: row.get(8)?,
                end_column: row.get(9)?,
                signature: row.get(10)?,
                docstring: row.get(11)?,
                visibility: row.get(12)?,
                is_exported: row.get::<_, i32>(13)? != 0,
                is_async: row.get::<_, i32>(14)? != 0,
            })
        })?
        .collect::<Result<Vec<_>, _>>()?;

        Ok(nodes)
    }

    /// Get index status.
    pub fn status(&self) -> Result<IndexStatus> {
        if !self.is_initialized() {
            return Ok(IndexStatus {
                initialized: false,
                file_count: 0,
                node_count: 0,
                edge_count: 0,
                languages: vec![],
                pending_changes: PendingChanges {
                    added: 0,
                    modified: 0,
                    removed: 0,
                },
            });
        }

        let conn = self.connect()?;

        let file_count: u32 = conn.query_row("SELECT COUNT(*) FROM files", [], |r| r.get(0))?;
        let node_count: u32 = conn.query_row("SELECT COUNT(*) FROM nodes", [], |r| r.get(0))?;
        let edge_count: u32 = conn.query_row("SELECT COUNT(*) FROM edges", [], |r| r.get(0))?;

        // Get unique languages
        let mut stmt = conn.prepare("SELECT DISTINCT language FROM nodes")?;
        let languages: Vec<String> = stmt.query_map([], |r| r.get(0))?
            .collect::<Result<Vec<_>, _>>()?;

        Ok(IndexStatus {
            initialized: true,
            file_count,
            node_count,
            edge_count,
            languages,
            pending_changes: PendingChanges {
                added: 0,
                modified: 0,
                removed: 0,
            },
        })
    }

    /// Get files by language.
    pub fn files(&self, language: Option<&str>) -> Result<Vec<FileInfo>> {
        let conn = self.connect()?;
        let mut stmt = if let Some(_lang) = language {
            conn.prepare(
                "SELECT path, language, node_count FROM files WHERE language = ?"
            )?
        } else {
            conn.prepare("SELECT path, language, node_count FROM files")?
        };

        let files = if let Some(lang) = language {
            stmt.query_map(params![lang], |row| {
                Ok(FileInfo {
                    path: row.get(0)?,
                    language: row.get(1)?,
                    node_count: row.get(2)?,
                })
            })?
            .collect::<Result<Vec<_>, _>>()?
        } else {
            stmt.query_map([], |row| {
                Ok(FileInfo {
                    path: row.get(0)?,
                    language: row.get(1)?,
                    node_count: row.get(2)?,
                })
            })?
            .collect::<Result<Vec<_>, _>>()?
        };

        Ok(files)
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FileInfo {
    pub path: String,
    pub language: String,
    pub node_count: u32,
}

// ============================================================================
// File Watcher with Smart Filtering
// ============================================================================

/// Patterns to ignore for file watching (similar to CodeGraph defaults).
const DEFAULT_IGNORE_PATTERNS: &[&str] = &[
    // Build outputs
    "target", "dist", "build", "out", "bin", "obj", ".output",
    // Dependencies
    "node_modules", "vendor", "Pods", ".venv", "venv", "__pycache__",
    // Cache and temp
    ".cache", ".tmp", ".temp", "tmp", "temp",
    // IDE and tools
    ".idea", ".vscode", ".eclipse", ".project", ".classpath",
    // Generated files
    ".generated", "generated", ".codegraph",
    // Lock files
    "package-lock.json", "yarn.lock", "Cargo.lock", "pnpm-lock.yaml",
    // Test outputs
    "coverage", ".nyc_output", "test-results",
    // Logs
    "logs",
];

/// Extensions to watch (source files only).
const WATCH_EXTENSIONS: &[&str] = &[
    "rs", "ts", "tsx", "js", "jsx", "mjs", "py", "go",
    "java", "kt", "kts", "c", "cpp", "cc", "h", "hpp",
    "rb", "php", "swift", "cs", "scala", "lua", "sh",
];

/// Git status polling interval (for non-fsmonitor fallback)
const GIT_STATUS_POLL_INTERVAL_SECS: u64 = 2;

// ============================================================================
// Git Environment Detection & Helpers
// ============================================================================

/// Check if directory is inside a Git work tree.
fn is_git_repository(project_path: &Path) -> bool {
    std::process::Command::new("git")
        .args(["rev-parse", "--is-inside-work-tree"])
        .current_dir(project_path)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Get current Git HEAD commit SHA.
fn get_git_head_sha(project_path: &Path) -> Option<String> {
    std::process::Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(project_path)
        .output()
        .ok()
        .and_then(|o| {
            if o.status.success() {
                Some(String::from_utf8_lossy(&o.stdout).trim().to_string())
            } else {
                None
            }
        })
}

/// Get all Git tracked files (for efficient init).
#[allow(dead_code)]
fn get_git_tracked_files(project_path: &Path) -> Vec<PathBuf> {
    std::process::Command::new("git")
        .args(["ls-files"])
        .current_dir(project_path)
        .output()
        .ok()
        .and_then(|o| {
            if o.status.success() {
                Some(
                    String::from_utf8_lossy(&o.stdout)
                        .lines()
                        .filter_map(|line| {
                            let path = project_path.join(line);
                            if is_source_file(&path) {
                                Some(path)
                            } else {
                                None
                            }
                        })
                        .collect(),
                )
            } else {
                None
            }
        })
        .unwrap_or_default()
}

/// Get changed files via git status --porcelain.
/// Returns (modified, added, deleted) file lists.
fn get_git_status_changes(project_path: &Path) -> GitStatusChanges {
    let output = std::process::Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(project_path)
        .output();

    let mut changes = GitStatusChanges::default();

    if let Ok(o) = output
        && o.status.success() {
        for line in String::from_utf8_lossy(&o.stdout).lines() {
            if line.len() < 2 {
                continue;
            }
            let status = &line[..2];
            let path = line[3..].trim();

            // Handle rename format: "R100 old -> new"
            let file_path = if path.contains(" -> ") {
                path.split(" -> ").nth(1).unwrap_or(path)
            } else {
                path
            };

            let full_path = project_path.join(file_path);

            // Check if it's a source file
            if !is_source_file(&full_path) {
                continue;
            }

            // Categorize by status code
            match status.trim() {
                "M" | "MM" | "AM" => changes.modified.push(full_path),
                "A" | "??" => changes.added.push(full_path),
                "D" | "AD" | "MD" => changes.deleted.push(full_path),
                "R" => {
                    // Rename: treat as delete old + add new
                    if let Some(old_path) = path.split(" -> ").next() {
                        changes.deleted.push(project_path.join(old_path));
                    }
                    changes.added.push(full_path);
                }
                _ => {}
            }
        }
    }

    changes
}

/// Start Git fsmonitor daemon (if available).
fn start_git_fsmonitor(project_path: &Path) -> bool {
    std::process::Command::new("git")
        .args(["fsmonitor--daemon", "start"])
        .current_dir(project_path)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Check if Git fsmonitor daemon is running.
fn is_git_fsmonitor_running(project_path: &Path) -> bool {
    std::process::Command::new("git")
        .args(["fsmonitor--daemon", "status"])
        .current_dir(project_path)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Git status changes result.
#[derive(Debug, Default)]
struct GitStatusChanges {
    modified: Vec<PathBuf>,
    added: Vec<PathBuf>,
    deleted: Vec<PathBuf>,
}

impl GitStatusChanges {
    fn has_changes(&self) -> bool {
        !self.modified.is_empty() || !self.added.is_empty() || !self.deleted.is_empty()
    }

    #[allow(dead_code)]
    fn total_count(&self) -> usize {
        self.modified.len() + self.added.len() + self.deleted.len()
    }
}

// ============================================================================
// Project Root Detection
// ============================================================================

/// Project root marker files (used to detect project root).
const PROJECT_ROOT_MARKERS: &[&str] = &[
    // Git
    ".git",
    // Rust
    "Cargo.toml",
    // Node.js
    "package.json",
    // TypeScript
    "tsconfig.json",
    // Go
    "go.mod",
    // Python
    "pyproject.toml",
    "setup.py",
    "requirements.txt",
    // Java
    "pom.xml",
    "build.gradle",
    // PHP
    "composer.json",
    // Ruby
    "Gemfile",
];

/// Find project root directory from a given starting path.
/// Priority:
/// 1. .git directory (Git root)
/// 2. Project marker files (Cargo.toml, package.json, etc.)
/// 3. Fallback to starting path
pub fn find_project_root(start_path: &Path) -> PathBuf {
    // First, try to find Git root (highest priority)
    if let Some(git_root) = find_git_root(start_path) {
        return git_root;
    }

    // Then, look for project marker files going up the directory tree
    if let Some(project_root) = find_by_markers(start_path) {
        return project_root;
    }

    // Fallback to starting path
    start_path.to_path_buf()
}

/// Find Git repository root by traversing up.
fn find_git_root(start_path: &Path) -> Option<PathBuf> {
    let mut current = start_path;

    while let Some(parent) = current.parent() {
        if current.join(".git").exists() {
            return Some(current.to_path_buf());
        }
        current = parent;
    }

    // Check start_path itself
    if start_path.join(".git").exists() {
        return Some(start_path.to_path_buf());
    }

    None
}

/// Find project root by looking for marker files.
fn find_by_markers(start_path: &Path) -> Option<PathBuf> {
    let mut current = start_path;

    loop {
        // Check if any marker exists in current directory
        for marker in PROJECT_ROOT_MARKERS {
            if current.join(marker).exists() {
                return Some(current.to_path_buf());
            }
        }

        // Go up one level
        if let Some(parent) = current.parent() {
            current = parent;
        } else {
            break;
        }
    }

    None
}

// ============================================================================
// Multi-Instance Lock (防止多实例冲突)
// ============================================================================

/// Lock file name for preventing multiple watcher instances.
const WATCHER_LOCK_FILE: &str = "watcher.lock";

/// Sync lock file name for preventing concurrent syncs.
const SYNC_LOCK_FILE: &str = "sync.lock";

/// Lock timeout in seconds (auto-release if process dies).
const LOCK_TIMEOUT_SECS: u64 = 30;

/// Instance ID (unique per process).
fn get_instance_id() -> String {
    use std::process;
    format!("{}-{}", process::id(), chrono::Utc::now().timestamp())
}

/// Watcher lock information.
#[derive(Debug, Clone)]
struct WatcherLock {
    instance_id: String,
    acquired_at: i64,
    pid: u32,
}

impl WatcherLock {
    fn new() -> Self {
        Self {
            instance_id: get_instance_id(),
            acquired_at: chrono::Utc::now().timestamp(),
            pid: std::process::id(),
        }
    }

    fn encode(&self) -> String {
        format!("{}:{}:{}",
            self.instance_id,
            self.acquired_at,
            self.pid
        )
    }

    fn decode(s: &str) -> Option<Self> {
        let parts: Vec<&str> = s.split(':').collect();
        if parts.len() >= 3 {
            Some(Self {
                instance_id: parts[0].to_string(),
                acquired_at: parts[1].parse().ok()?,
                pid: parts[2].parse().ok()?,
            })
        } else {
            None
        }
    }

    /// Check if lock is stale (process died or timeout).
    fn is_stale(&self) -> bool {
        let now = chrono::Utc::now().timestamp();
        // Lock is stale if timeout exceeded
        if now - self.acquired_at > LOCK_TIMEOUT_SECS as i64 {
            return true;
        }
        false
    }
}

/// Try to acquire watcher lock.
/// Returns true if lock acquired (either fresh or stolen from stale holder).
pub fn try_acquire_watcher_lock(project_path: &Path) -> bool {
    let lock_path = project_path.join(".codegraph").join(WATCHER_LOCK_FILE);

    // Ensure directory exists
    if let Some(parent) = lock_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }

    // Check existing lock
    if lock_path.exists() {
        let content = std::fs::read_to_string(&lock_path).ok();
        if let Some(s) = content
            && let Some(lock) = WatcherLock::decode(&s) {
            // Check if lock is stale
            if !lock.is_stale() {
                log::info!(
                    "CodeGraph: watcher lock held by instance {} (PID {}), skipping",
                    lock.instance_id,
                    lock.pid
                );
                return false;
            }
            // Lock is stale, we can steal it
            log::info!(
                "CodeGraph: stealing stale watcher lock from instance {} (PID {})",
                lock.instance_id,
                lock.pid
            );
        }
    }

    // Acquire lock
    let lock = WatcherLock::new();
    let _ = std::fs::write(&lock_path, lock.encode());
    log::info!("CodeGraph: acquired watcher lock (instance {})", lock.instance_id);
    true
}

/// Release watcher lock.
pub fn release_watcher_lock(project_path: &Path) {
    let lock_path = project_path.join(".codegraph").join(WATCHER_LOCK_FILE);
    if lock_path.exists() {
        let _ = std::fs::remove_file(&lock_path);
        log::info!("CodeGraph: released watcher lock");
    }
}

/// Update watcher lock heartbeat (keep alive).
fn update_watcher_heartbeat(project_path: &Path) {
    let lock_path = project_path.join(".codegraph").join(WATCHER_LOCK_FILE);
    if lock_path.exists() {
        let lock = WatcherLock::new();
        let _ = std::fs::write(&lock_path, lock.encode());
    }
}

/// Try to acquire sync lock (short-lived, for preventing concurrent syncs).
fn try_acquire_sync_lock(project_path: &Path) -> bool {
    let lock_path = project_path.join(".codegraph").join(SYNC_LOCK_FILE);

    if lock_path.exists() {
        let content = std::fs::read_to_string(&lock_path).ok();
        if let Some(s) = content {
            let timestamp: i64 = s.parse().ok().unwrap_or(0);
            let now = chrono::Utc::now().timestamp();
            // Sync lock timeout is shorter (5 seconds)
            if now - timestamp < 5 {
                log::debug!("CodeGraph: sync in progress by another instance, skipping");
                return false;
            }
        }
    }

    // Acquire sync lock
    let timestamp = chrono::Utc::now().timestamp().to_string();
    let _ = std::fs::write(&lock_path, timestamp);
    true
}

/// Release sync lock.
fn release_sync_lock(project_path: &Path) {
    let lock_path = project_path.join(".codegraph").join(SYNC_LOCK_FILE);
    if lock_path.exists() {
        let _ = std::fs::remove_file(&lock_path);
    }
}

/// Version file name for storing Git HEAD SHA.
const VERSION_FILE: &str = "version.txt";

/// Save current Git HEAD SHA to version file.
fn save_version_sha(project_path: &Path, sha: &str) {
    let version_path = project_path.join(".codegraph").join(VERSION_FILE);
    if let Some(parent) = version_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let _ = std::fs::write(&version_path, sha);
}

/// Load stored Git HEAD SHA from version file.
fn load_version_sha(project_path: &Path) -> Option<String> {
    let version_path = project_path.join(".codegraph").join(VERSION_FILE);
    std::fs::read_to_string(&version_path)
        .ok()
        .map(|s| s.trim().to_string())
}

/// Check if version has changed (current SHA != stored SHA).
fn has_version_changed(project_path: &Path) -> bool {
    let current_sha = get_git_head_sha(project_path);
    let stored_sha = load_version_sha(project_path);
    current_sha != stored_sha
}

/// Update version after successful sync.
fn update_version_after_sync(project_path: &Path) {
    if let Some(sha) = get_git_head_sha(project_path) {
        save_version_sha(project_path, &sha);
        log::debug!("CodeGraph: version updated to SHA {}", sha);
    }
}

/// Environment type for CodeGraph.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CodeGraphEnv {
    Git,
    NonGit,
}

/// Detect environment type at startup.
fn detect_env_type(project_path: &Path) -> CodeGraphEnv {
    if is_git_repository(project_path) {
        CodeGraphEnv::Git
    } else {
        CodeGraphEnv::NonGit
    }
}

/// Gitignore patterns loaded from file.
pub struct IgnoreMatcher {
    patterns: Vec<String>,
    negation_patterns: Vec<String>,
}

impl IgnoreMatcher {
    /// Load ignore patterns from .gitignore and defaults.
    pub fn load(project_path: &Path) -> Self {
        let mut patterns = Vec::new();
        let mut negation_patterns = Vec::new();

        // Add default patterns
        for p in DEFAULT_IGNORE_PATTERNS {
            patterns.push(p.to_string());
        }

        // Load .gitignore
        let gitignore_path = project_path.join(".gitignore");
        if gitignore_path.exists()
            && let Ok(content) = std::fs::read_to_string(&gitignore_path) {
                for line in content.lines() {
                    let line = line.trim();
                    if line.is_empty() || line.starts_with('#') {
                        continue;
                    }
                    if let Some(stripped) = line.strip_prefix('!') {
                        // Negation pattern (include this)
                        negation_patterns.push(stripped.to_string());
                    } else {
                        patterns.push(line.to_string());
                    }
                }
            }

        Self { patterns, negation_patterns }
    }

    /// Check if a path should be ignored.
    pub fn should_ignore(&self, path: &Path, project_path: &Path) -> bool {
        let path_str = path.to_string_lossy();
        let relative_path = path.strip_prefix(project_path)
            .unwrap_or(path)
            .to_string_lossy();

        // Check negation patterns first (explicit inclusion)
        for pattern in &self.negation_patterns {
            if Self::matches_pattern(&relative_path, pattern) {
                return false; // Explicitly included
            }
        }

        // Check ignore patterns
        for pattern in &self.patterns {
            if Self::matches_pattern(&relative_path, pattern)
                || path_str.contains(pattern) {
                return true;
            }
        }

        // Check hidden files (but allow .codegraph)
        for component in path.components() {
            if let std::path::Component::Normal(name) = component {
                let name_str = name.to_string_lossy();
                if name_str.starts_with('.')
                    && name_str != ".codegraph"
                    && !WATCH_EXTENSIONS.contains(&name_str.split('.').next_back().unwrap_or("")) {
                    return true;
                }
            }
        }

        false
    }

    /// Check if path matches a gitignore pattern.
    fn matches_pattern(path: &str, pattern: &str) -> bool {
        // Simple pattern matching (handles common gitignore patterns)
        let pattern = pattern.trim_start_matches('/');

        // Directory match (pattern ends with /)
        if let Some(dir_pattern) = pattern.strip_suffix('/') {
            return path.contains(dir_pattern) || path.starts_with(dir_pattern);
        }

        // Wildcard match
        if pattern.contains('*') {
            let parts = pattern.split('*').collect::<Vec<_>>();
            if parts.len() == 2 {
                let prefix = parts[0];
                let suffix = parts[1];
                return (prefix.is_empty() || path.starts_with(prefix))
                    && (suffix.is_empty() || path.ends_with(suffix));
            }
        }

        // Exact match or contains
        path == pattern || path.contains(pattern) || path.starts_with(&format!("{}/", pattern))
    }
}

/// Check if a path is a source file worth watching.
fn is_source_file(path: &Path) -> bool {
    // Check extension
    if let Some(ext) = path.extension() {
        let ext_str = ext.to_string_lossy().to_lowercase();
        return WATCH_EXTENSIONS.contains(&ext_str.as_str());
    }
    false
}

/// CodeGraph file watcher for auto-sync.
pub struct CodeGraphWatcher {
    project_path: PathBuf,
    stop_tx: broadcast::Sender<()>,
    sync_interval: Duration,
}

impl CodeGraphWatcher {
    /// Create a new watcher for the project.
    pub fn new(project_path: &Path) -> Self {
        let (stop_tx, _) = broadcast::channel(1);
        Self {
            project_path: project_path.to_path_buf(),
            stop_tx,
            sync_interval: Duration::from_secs(CODEGRAPH_SYNC_INTERVAL_SECS), // Debounce interval
        }
    }

    /// Create watcher with automatic project root detection.
    /// Uses find_project_root() to locate the correct directory.
    pub fn with_auto_detect(start_path: &Path) -> Self {
        let project_path = find_project_root(start_path);
        log::info!("CodeGraph: detected project root at {}", project_path.display());
        Self::new(&project_path)
    }

    /// Start watching for file changes.
    /// Returns a JoinHandle that can be used to wait for or abort the watcher.
    pub fn start(&self, cancel_token: CancellationToken) -> tokio::task::JoinHandle<()> {
        let project_path = self.project_path.clone();
        let sync_interval = self.sync_interval;

        // Spawn watcher task and return handle for proper cleanup
        tokio::spawn(async move {
            Self::run_watcher_loop(project_path, sync_interval, cancel_token).await;
        })
    }

    /// Stop the watcher via broadcast signal.
    pub fn stop(&self) {
        let _ = self.stop_tx.send(());
    }

    /// Run the watcher loop with dual-path monitoring.
    async fn run_watcher_loop(
        project_path: PathBuf,
        _sync_interval: Duration,
        cancel_token: CancellationToken,
    ) {
        // Check if CodeGraph CLI is available (no auto-install)
        if get_codegraph_path().is_none() {
            log::warn!("CodeGraph CLI not found, watcher disabled. Please install CodeGraph manually.");
            return;
        }

        // Try to acquire watcher lock (prevent multiple instances)
        if !try_acquire_watcher_lock(&project_path) {
            log::info!("CodeGraph: another instance is watching this project, exiting");
            return;
        }

        // Check if this is a code project
        let analyzer = ProjectStructureAnalyzer::new(project_path.clone());
        if analyzer.detect_project_type().is_none() {
            log::info!(
                "CodeGraph: skipping non-code directory: {}",
                project_path.display()
            );
            return;
        }

        // Check if CodeGraph is initialized - DO NOT auto-initialize
        // User must manually run `codegraph init -i` or `/init` to create the index
        let manager = CodeGraphManager::new(&project_path);
        if !manager.is_initialized() {
            log::info!(
                "CodeGraph: not initialized for {}, skipping watcher. Run 'codegraph init -i' to create index.",
                project_path.display()
            );
            release_watcher_lock(&project_path);
            return;
        }

        // Detect environment type
        let env_type = detect_env_type(&project_path);
        log::info!(
            "CodeGraph: environment detected as {} for: {}",
            match env_type {
                CodeGraphEnv::Git => "Git repository",
                CodeGraphEnv::NonGit => "non-Git directory",
            },
            project_path.display()
        );

        // Check version consistency before starting
        if env_type == CodeGraphEnv::Git && has_version_changed(&project_path) {
            log::info!("CodeGraph: version changed, performing sync before starting watcher");
            if let Err(e) = manager.sync().await {
                log::warn!("CodeGraph version sync failed: {}", e);
            }
            update_version_after_sync(&project_path);
        }

        // Initial sync on startup
        log::info!("CodeGraph: performing initial sync on startup");
        if let Err(e) = manager.sync().await {
            log::warn!("CodeGraph initial sync failed: {}", e);
        }
        update_version_after_sync(&project_path);

        // Channel for file change events (from notify)
        let (change_tx, mut change_rx) = mpsc::channel::<PathBuf>(100);

        // Create notify file watcher (always running as fallback)
        let watcher_result = Self::create_file_watcher(&project_path, change_tx.clone());
        if watcher_result.is_err() {
            log::warn!("CodeGraph notify watcher failed to start: {}", watcher_result.err().unwrap());
            release_watcher_lock(&project_path);
            return;
        }
        let _watcher = watcher_result.unwrap();

        // Load ignore matcher
        let ignore_matcher = IgnoreMatcher::load(&project_path);

        // Track sync state with deduplication (async-safe)
        let syncing = Arc::new(AtomicBool::new(false));
        let syncing_clone = syncing.clone();
        let changed_files = Arc::new(RwLock::new(std::collections::HashSet::<PathBuf>::new()));
        let last_change = Arc::new(std::sync::Mutex::new(Instant::now()));

        // Debounce settings
        let debounce_delay = Duration::from_secs(CODEGRAPH_SYNC_INTERVAL_SECS);
        let git_poll_interval = Duration::from_secs(GIT_STATUS_POLL_INTERVAL_SECS);

        // Start Git monitoring if in Git environment
        let git_monitoring = if env_type == CodeGraphEnv::Git {
            // Try to start Git fsmonitor daemon
            if start_git_fsmonitor(&project_path) {
                log::info!("CodeGraph: Git fsmonitor daemon started");
                true
            } else if is_git_fsmonitor_running(&project_path) {
                log::info!("CodeGraph: Git fsmonitor daemon already running");
                true
            } else {
                log::info!("CodeGraph: Git fsmonitor not available, using git status polling");
                false
            }
        } else {
            false
        };

        log::info!(
            "CodeGraph watcher started (Git monitoring: {}, notify fallback: always)",
            git_monitoring
        );

        // Check interval
        let check_interval = Duration::from_secs(1);

        loop {
            if cancel_token.is_cancelled() {
                // Final sync before exit
                let pending_count = changed_files.read().await.len();
                if pending_count > 0 {
                    log::info!(
                        "CodeGraph: final sync before exit ({} unique files)",
                        pending_count
                    );
                    let manager = CodeGraphManager::new(&project_path);
                    if manager.is_initialized() {
                        let _ = manager.sync().await;
                        update_version_after_sync(&project_path);
                    }
                }
                // Release lock before exit
                release_watcher_lock(&project_path);
                log::info!("CodeGraph watcher stopped");
                break;
            }

            // Update heartbeat periodically (keep lock alive)
            update_watcher_heartbeat(&project_path);

            tokio::select! {
                // Notify file changes (fallback path - always running)
                Some(path) = change_rx.recv() => {
                    if cancel_token.is_cancelled() {
                        break;
                    }
                    if is_source_file(&path)
                        && !ignore_matcher.should_ignore(&path, &project_path) {
                        // Add to set (deduplicated, async-safe)
                        {
                            let mut files = changed_files.write().await;
                            if files.insert(path.clone()) {
                                *last_change.lock().unwrap() = Instant::now();
                                log::debug!(
                                    "CodeGraph [notify]: new file {} (total unique: {})",
                                    path.display(),
                                    files.len()
                                );
                            }
                        }
                    }
                }

                // Git status polling (Git environment only)
                _ = sleep(git_poll_interval), if git_monitoring => {
                    if cancel_token.is_cancelled() {
                        break;
                    }
                    // Check Git status for changes
                    let changes = get_git_status_changes(&project_path);
                    if changes.has_changes() {
                        let mut new_count = 0;
                        {
                            let mut files = changed_files.write().await;
                            // Add all changed files to set (deduplicated)
                            for path in changes.modified.iter().chain(&changes.added).chain(&changes.deleted) {
                                if files.insert(path.clone()) {
                                    new_count += 1;
                                }
                            }
                            if new_count > 0 {
                                log::debug!(
                                    "CodeGraph [git]: {} new changes (modified: {}, added: {}, deleted: {}, total unique: {})",
                                    new_count,
                                    changes.modified.len(),
                                    changes.added.len(),
                                    changes.deleted.len(),
                                    files.len()
                                );
                            }
                        }
                        if new_count > 0 {
                            *last_change.lock().unwrap() = Instant::now();
                        }
                    }
                }

                // Periodic sync check (debounced)
                _ = sleep(check_interval) => {
                    if cancel_token.is_cancelled() {
                        break;
                    }

                    let files_count = changed_files.read().await.len();
                    let elapsed = last_change.lock().unwrap().elapsed();

                    // Sync when: not syncing + have pending + debounce elapsed
                    if !syncing_clone.load(Ordering::SeqCst)
                        && files_count > 0
                        && elapsed >= debounce_delay {
                        syncing_clone.store(true, Ordering::SeqCst);
                        log::info!("CodeGraph: auto-sync triggered ({} unique files changed)", files_count);

                        // Try to acquire sync lock (prevent concurrent syncs)
                        if try_acquire_sync_lock(&project_path) {
                            let manager = CodeGraphManager::new(&project_path);
                            if manager.is_initialized() {
                                if let Err(e) = manager.sync().await {
                                    log::warn!("CodeGraph sync failed: {}", e);
                                } else {
                                    update_version_after_sync(&project_path);
                                }
                                // Clear the set after sync (async-safe)
                                changed_files.write().await.clear();
                            }
                            // Release sync lock
                            release_sync_lock(&project_path);
                        } else {
                            // Another instance is syncing, skip but keep pending changes
                            log::debug!("CodeGraph: skipping sync, another instance is syncing");
                        }
                        syncing_clone.store(false, Ordering::SeqCst);
                    }
                }
            }
        }
    }

    /// Create the underlying file watcher with optimized config.
    fn create_file_watcher(
        project_path: &Path,
        change_tx: mpsc::Sender<PathBuf>,
    ) -> Result<RecommendedWatcher> {
        let tx = change_tx.clone();

        let handler = move |event: Result<Event, notify::Error>| {
            if let Ok(event) = event {
                // Only process create/modify/remove events, ignore access/other
                if !event.kind.is_access() && !event.kind.is_other() {
                    for path in event.paths {
                        // Send change event (non-blocking to avoid stalls)
                        let _ = tx.try_send(path);
                    }
                }
            }
        };

        // Use optimized config to reduce event noise
        let config = Config::default()
            .with_poll_interval(Duration::from_secs(2)) // Reduce poll frequency
            .with_compare_contents(false); // Don't compare file contents

        let mut watcher = RecommendedWatcher::new(handler, config)?;
        watcher.watch(project_path, RecursiveMode::Recursive)?;

        Ok(watcher)
    }
}

// ============================================================================
// Tool Definitions
// ============================================================================

/// Tool for searching symbols in CodeGraph index.
pub struct CodeGraphSearchTool {
    manager: Arc<CodeGraphManager>,
}

impl CodeGraphSearchTool {
    pub fn new(project_path: &Path) -> Self {
        Self {
            manager: Arc::new(CodeGraphManager::new(project_path)),
        }
    }
}

#[async_trait]
impl Tool for CodeGraphSearchTool {
    fn definition(&self) -> ToolDefinition {
        ToolDefinition {
            name: "code_search".to_string(),
            description: "[优先工具] 搜索代码符号(函数、类、方法、变量)。

适用场景:
- 找函数定义(如 'handle_request'、'User::new')
- 查类定义、结构体、接口
- 定位变量声明、常量定义
- 查找方法签名、文档注释

不适用场景:
- ❌ 搜错误信息 → 用 grep(如 'failed to'、'panic')
- ❌ 搜注释内容 → 用 grep(如 'TODO')
- ❌ 搜字符串常量 → 用 grep

优先级:[高] 比grep快10-100倍,语义搜索首选".to_string(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "pattern": {
                        "type": "string",
                        "description": "符号名称搜索模式(支持模糊匹配)"
                    },
                    "limit": {
                        "type": "integer",
                        "description": "返回结果数量限制(默认 20)",
                        "default": 20
                    }
                },
                "required": ["pattern"]
            }),
            is_priority: true,
        }
    }

    async fn execute(&self, params: Value) -> Result<String> {
        if !self.manager.is_initialized() {
            return Ok("CodeGraph 未初始化。请先运行 codegraph init -i 来构建索引。".to_string());
        }

        let pattern = params["pattern"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("missing 'pattern'"))?;
        let limit = params["limit"].as_u64().unwrap_or(20) as usize;

        let nodes = self.manager.search(pattern, limit)?;

        if nodes.is_empty() {
            return Ok(format!("未找到匹配 '{}' 的符号。", pattern));
        }

        let mut results = Vec::new();
        for node in nodes {
            let sig = node.signature.as_deref().unwrap_or("");
            results.push(format!(
                "{} {} ({})\n  {}:{}\n  {}",
                node.kind, node.name, node.language,
                node.file_path, node.start_line,
                sig
            ));
        }

        Ok(results.join("\n\n"))
    }

    fn risk_level(&self) -> RiskLevel {
        RiskLevel::Safe
    }
}

/// Tool for finding callers of a symbol.
pub struct CodeGraphCallersTool {
    manager: Arc<CodeGraphManager>,
}

impl CodeGraphCallersTool {
    pub fn new(project_path: &Path) -> Self {
        Self {
            manager: Arc::new(CodeGraphManager::new(project_path)),
        }
    }
}

#[async_trait]
impl Tool for CodeGraphCallersTool {
    fn definition(&self) -> ToolDefinition {
        ToolDefinition {
            name: "code_callers".to_string(),
            description: "[优先工具] 查找调用指定符号的所有函数/方法(向上追溯)。

适用场景:
- 查谁调用了 'handle_error'?
- 哪些地方使用了 'User::new'?
- 分析函数被哪些模块引用

不适用场景:
- ❌ 查某函数调用了谁 → 用 code_callees
- ❌ 搜字符串内容 → 用 grep

优先级:[高] 分析调用关系首选".to_string(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "symbol": {
                        "type": "string",
                        "description": "符号 ID 或名称"
                    },
                    "limit": {
                        "type": "integer",
                        "description": "返回结果数量限制(默认 10)",
                        "default": 10
                    }
                },
                "required": ["symbol"]
            }),
            is_priority: true,
        }
    }

    async fn execute(&self, params: Value) -> Result<String> {
        if !self.manager.is_initialized() {
            return Ok("CodeGraph 未初始化。请先运行 codegraph init -i 来构建索引。".to_string());
        }

        let symbol = params["symbol"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("missing 'symbol'"))?;
        let limit = params["limit"].as_u64().unwrap_or(10) as usize;

        // First try to find the symbol ID
        let symbol_id = if symbol.contains(":") {
            symbol.to_string()
        } else {
            let nodes = self.manager.search(symbol, 1)?;
            if nodes.is_empty() {
                return Ok(format!("未找到符号 '{}'。", symbol));
            }
            nodes[0].id.clone()
        };

        let callers = self.manager.callers(&symbol_id, limit)?;

        if callers.is_empty() {
            return Ok(format!("符号 '{}' 没有调用者。", symbol));
        }

        let mut results = Vec::new();
        for node in callers {
            results.push(format!(
                "{} {} ({})\n  {}:{}",
                node.kind, node.name, node.language,
                node.file_path, node.start_line
            ));
        }

        Ok(format!("调用 '{}' 的符号:\n\n{}", symbol, results.join("\n")))
    }

    fn risk_level(&self) -> RiskLevel {
        RiskLevel::Safe
    }
}

/// Tool for finding callees of a symbol.
pub struct CodeGraphCalleesTool {
    manager: Arc<CodeGraphManager>,
}

impl CodeGraphCalleesTool {
    pub fn new(project_path: &Path) -> Self {
        Self {
            manager: Arc::new(CodeGraphManager::new(project_path)),
        }
    }
}

#[async_trait]
impl Tool for CodeGraphCalleesTool {
    fn definition(&self) -> ToolDefinition {
        ToolDefinition {
            name: "code_callees".to_string(),
            description: "[优先工具] 查找指定符号调用的所有函数/方法(向下追踪)。

适用场景:
- 查 'handle_request' 调用了哪些函数?
- 分析函数内部的执行流程
- 追踪代码依赖关系

不适用场景:
- ❌ 查谁调用了某函数 → 用 code_callers
- ❌ 搜字符串内容 → 用 grep

优先级:[高] 分析执行流程首选".to_string(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "symbol": {
                        "type": "string",
                        "description": "符号 ID 或名称"
                    },
                    "limit": {
                        "type": "integer",
                        "description": "返回结果数量限制(默认 10)",
                        "default": 10
                    }
                },
                "required": ["symbol"]
            }),
            is_priority: true,
        }
    }

    async fn execute(&self, params: Value) -> Result<String> {
        if !self.manager.is_initialized() {
            return Ok("CodeGraph 未初始化。请先运行 codegraph init -i 来构建索引。".to_string());
        }

        let symbol = params["symbol"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("missing 'symbol'"))?;
        let limit = params["limit"].as_u64().unwrap_or(10) as usize;

        let symbol_id = if symbol.contains(":") {
            symbol.to_string()
        } else {
            let nodes = self.manager.search(symbol, 1)?;
            if nodes.is_empty() {
                return Ok(format!("未找到符号 '{}'。", symbol));
            }
            nodes[0].id.clone()
        };

        let callees = self.manager.callees(&symbol_id, limit)?;

        if callees.is_empty() {
            return Ok(format!("符号 '{}' 不调用其他符号。", symbol));
        }

        let mut results = Vec::new();
        for node in callees {
            results.push(format!(
                "{} {} ({})\n  {}:{}",
                node.kind, node.name, node.language,
                node.file_path, node.start_line
            ));
        }

        Ok(format!("'{}' 调用的符号:\n\n{}", symbol, results.join("\n")))
    }

    fn risk_level(&self) -> RiskLevel {
        RiskLevel::Safe
    }
}

/// Tool for checking CodeGraph index status.
pub struct CodeGraphStatusTool {
    manager: Arc<CodeGraphManager>,
}

impl CodeGraphStatusTool {
    pub fn new(project_path: &Path) -> Self {
        Self {
            manager: Arc::new(CodeGraphManager::new(project_path)),
        }
    }
}

#[async_trait]
impl Tool for CodeGraphStatusTool {
    fn definition(&self) -> ToolDefinition {
        ToolDefinition {
            name: "code_status".to_string(),
            description: "检查 CodeGraph 索引状态。返回文件数、节点数、边数、支持的语言等信息。".to_string(),
            parameters: json!({
                "type": "object",
                "properties": {}
            }),
            is_priority: false,
        }
    }

    async fn execute(&self, _params: Value) -> Result<String> {
        // Check if CodeGraph CLI is installed first
        if get_codegraph_path().is_none() {
            return Ok("CodeGraph CLI 未安装。\n\n请先安装 CodeGraph CLI:\n- Windows: 运行 PowerShell 安装脚本\n- Linux/Mac: 运行安装脚本\n\n安装后运行 'codegraph init -i' 来构建代码索引。".to_string());
        }

        let status = self.manager.status()?;

        if !status.initialized {
            return Ok("CodeGraph 未初始化。\n\n运行 'codegraph init -i' 来构建代码索引,或在 matrixcode 中使用 /init 命令。".to_string());
        }

        Ok(format!(
            "CodeGraph 状态:\n\n文件数: {}\n节点数: {}\n边数: {}\n语言: {}",
            status.file_count,
            status.node_count,
            status.edge_count,
            status.languages.join(", ")
        ))
    }

    fn risk_level(&self) -> RiskLevel {
        RiskLevel::Safe
    }
}

/// Tool for manually syncing CodeGraph index.
pub struct CodeGraphSyncTool {
    manager: Arc<CodeGraphManager>,
}

impl CodeGraphSyncTool {
    pub fn new(project_path: &Path) -> Self {
        Self {
            manager: Arc::new(CodeGraphManager::new(project_path)),
        }
    }
}

#[async_trait]
impl Tool for CodeGraphSyncTool {
    fn definition(&self) -> ToolDefinition {
        ToolDefinition {
            name: "code_sync".to_string(),
            description: "手动同步 CodeGraph 索引。当代码库有变化但自动同步未触发时使用,确保搜索结果是最新的。".to_string(),
            parameters: json!({
                "type": "object",
                "properties": {}
            }),
            is_priority: false,
        }
    }

    async fn execute(&self, _params: Value) -> Result<String> {
        if !self.manager.is_initialized() {
            return Ok("CodeGraph 未初始化。请先运行 codegraph init -i 来构建索引。".to_string());
        }

        log::info!("CodeGraph: manual sync triggered by AI");
        self.manager.sync().await?;

        let status = self.manager.status()?;
        Ok(format!(
            "CodeGraph 索引已同步。\n\n文件数: {}\n节点数: {}\n边数: {}\n语言: {}",
            status.file_count,
            status.node_count,
            status.edge_count,
            status.languages.join(", ")
        ))
    }

    fn risk_level(&self) -> RiskLevel {
        RiskLevel::Safe
    }
}

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

/// Create all CodeGraph tools for a project.
/// Create CodeGraph tools for a project path.
/// Always returns tools - they will show appropriate error messages
/// if CodeGraph is not installed or initialized.
pub fn codegraph_tools(project_path: &Path) -> Vec<Box<dyn Tool>> {
    vec![
        Box::new(CodeGraphSearchTool::new(project_path)),
        Box::new(CodeGraphCallersTool::new(project_path)),
        Box::new(CodeGraphCalleesTool::new(project_path)),
        Box::new(CodeGraphStatusTool::new(project_path)),
        Box::new(CodeGraphSyncTool::new(project_path)),
    ]
}

/// Create CodeGraph tools with automatic project root detection.
pub fn codegraph_tools_with_auto_detect(start_path: &Path) -> Vec<Box<dyn Tool>> {
    let project_root = find_project_root(start_path);
    codegraph_tools(&project_root)
}

/// Check if CodeGraph tools should be injected.
/// Returns true if:
/// 1. CodeGraph CLI is installed
/// 2. Project has .codegraph directory (initialized)
///
/// Uses automatic project root detection from start_path.
pub fn should_inject_codegraph_tools(start_path: &Path) -> bool {
    if get_codegraph_path().is_none() {
        return false;
    }

    // Find project root and check for .codegraph/codegraph.db file (actual index)
    let project_root = find_project_root(start_path);
    project_root.join(".codegraph").join("codegraph.db").exists()
}

/// Create CodeGraph tools only if initialized.
/// Returns empty vec if CodeGraph CLI is not available or project not initialized.
/// Uses automatic project root detection.
pub fn codegraph_tools_if_installed(start_path: &Path) -> Vec<Box<dyn Tool>> {
    if should_inject_codegraph_tools(start_path) {
        codegraph_tools_with_auto_detect(start_path)
    } else {
        vec![]
    }
}

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

    #[test]
    fn test_codegraph_manager_creation() {
        let path = PathBuf::from(".");
        let manager = CodeGraphManager::new(&path);
        assert!(manager.db_path.to_str().unwrap().contains(".codegraph"));
    }

    #[test]
    fn test_tool_definitions() {
        let path = PathBuf::from(".");
        let tools = codegraph_tools(&path);

        let names: Vec<String> = tools.iter().map(|t| t.definition().name).collect();
        assert!(names.contains(&"code_search".to_string()));
        assert!(names.contains(&"code_callers".to_string()));
        assert!(names.contains(&"code_callees".to_string()));
        assert!(names.contains(&"code_status".to_string()));
        assert!(names.contains(&"code_sync".to_string()));
    }

    #[test]
    fn test_search_tool_priority() {
        let path = PathBuf::from(".");
        let tools = codegraph_tools(&path);

        for tool in tools {
            let def = tool.definition();
            if def.name == "code_search" {
                assert!(def.is_priority);
            }
        }
    }

    #[test]
    fn test_find_project_root_current_dir() {
        // Current directory should find a project root (this repo has .git and Cargo.toml)
        let start_path = PathBuf::from(".");
        let root = find_project_root(&start_path);
        // Should find either .git or Cargo.toml
        assert!(root.join(".git").exists() || root.join("Cargo.toml").exists());
    }

    #[test]
    fn test_find_project_root_subdirectory() {
        // Starting from a subdirectory, should still find root
        let start_path = PathBuf::from("./src");
        let root = find_project_root(&start_path);
        // Should find root with .git or Cargo.toml
        assert!(root.join(".git").exists() || root.join("Cargo.toml").exists());
    }

    #[test]
    fn test_manager_with_auto_detect() {
        let start_path = PathBuf::from(".");
        let manager = CodeGraphManager::with_auto_detect(&start_path);
        // Should find a valid project root
        assert!(manager.project_path.join(".git").exists()
            || manager.project_path.join("Cargo.toml").exists()
            || manager.project_path.join("package.json").exists());
    }
}