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
use anyhow::{Context, Result};
use serde_json;
use std::path::Path;
use std::time::Instant;
use tracing::info;
// Use public API instead of direct internal access
use crate::{
LoreGrep,
core::types::ScanResult as PublicScanResult,
internal::{
cli_types::{AnalyzeArgs, ExecToolArgs, ScanArgs, SearchArgs},
config::CliConfig,
},
loregrep::LoreGrepConfig,
};
/// Lightweight search result used for plain, machine-facing output.
#[derive(Debug, Clone)]
pub struct SearchResult {
pub result_type: String,
pub content: String,
pub file_path: String,
pub line: Option<u32>,
pub context: Option<String>,
}
impl SearchResult {
pub fn new(result_type: String, content: String, file_path: String, line: Option<u32>) -> Self {
Self {
result_type,
content,
file_path,
line,
context: None,
}
}
pub fn with_context(mut self, context: String) -> Self {
self.context = Some(context);
self
}
}
pub struct CliApp {
config: CliConfig,
loregrep: LoreGrep,
verbose: bool,
}
impl CliApp {
pub async fn new(config: CliConfig, verbose: bool, _colors_enabled: bool) -> Result<Self> {
info!("Initializing Loregrep CLI");
// Create LoreGrep instance using public API
let mut builder = LoreGrep::builder()
.with_all_analyzers() // Rust, Python, TypeScript/TSX
// One default file limit for the whole project (see the const's
// documentation for why 10,000).
.max_files(LoreGrepConfig::DEFAULT_MAX_FILES)
.include_patterns(config.file_scanning.include_patterns.clone())
.exclude_patterns(config.file_scanning.exclude_patterns.clone())
.max_file_size(config.file_scanning.max_file_size)
.follow_symlinks(config.file_scanning.follow_symlinks);
// Configure depth limit
if let Some(depth) = config.file_scanning.max_depth {
builder = builder.max_depth(depth);
} else {
builder = builder.unlimited_depth();
}
let loregrep = builder
.build()
.map_err(|e| anyhow::anyhow!("Failed to create LoreGrep instance: {}", e))?;
// Create the cache directory itself if it doesn't exist. (This used to
// create `config.cache.path.parent()` — the *parent* of the cache
// directory — which is not a directory anything ever writes to.)
if config.cache.enabled {
tokio::fs::create_dir_all(&config.cache.path)
.await
.context("Failed to create cache directory")?;
}
if verbose {
eprintln!("LoreGrep initialized with public API");
}
Ok(Self {
config,
loregrep,
verbose,
})
}
pub async fn scan(&mut self, args: ScanArgs) -> Result<()> {
let start_time = Instant::now();
// Show absolute path for clarity
let abs_path = args
.path
.canonicalize()
.unwrap_or_else(|_| args.path.clone());
if self.verbose {
eprintln!("Scanning directory: {}", abs_path.display());
eprintln!(
"Include patterns: {:?}",
self.config.file_scanning.include_patterns
);
eprintln!(
"Exclude patterns: {:?}",
self.config.file_scanning.exclude_patterns
);
}
// Use public API to scan the repository
let scan_result = self
.loregrep
.scan(&args.path.to_string_lossy())
.await
.map_err(|e| anyhow::anyhow!("Failed to scan repository: {}", e))?;
// Display scan results using public API data
self.print_public_scan_results(&scan_result);
// Cache results if enabled
if args.cache && self.config.cache.enabled {
self.save_cache(&args.path);
}
if self.verbose {
eprintln!("Total scan time: {:?}", start_time.elapsed());
}
Ok(())
}
/// The persisted index cache file for `root`, or `None` when caching is off.
///
/// The cache lives under the user's own cache directory
/// (`config.cache.path`), never inside the analysed tree: a query is a read,
/// and a read must not create files in someone else's repository (K11).
fn index_cache_path(&self, root: &Path) -> Option<std::path::PathBuf> {
if !self.config.cache.enabled {
return None;
}
match LoreGrep::cache_path_for(&self.config.cache.path, root) {
Ok(path) => Some(path),
Err(e) => {
eprintln!("Cache disabled for this run: {}", e);
None
}
}
}
/// Make sure an index for `root` is in memory: reuse a validated persisted
/// cache if there is one, otherwise scan and persist the result.
///
/// Both `exec-tool` and `search` need exactly this, and having them share
/// one method is what keeps them from drifting apart — `search` previously
/// had no load-or-scan step at all and so reported "Repository not scanned"
/// on every single invocation (K7).
///
/// Validation only runs when the cache file exists — on the first run there
/// is no cache, so we go straight to the single scan rather than walking the
/// tree twice.
///
/// `load_index_if_fresh` validates the cache against this build, this
/// configuration and the files actually on disk (path set + content hashes)
/// before installing it, and checks the recorded analysis root. Any mismatch
/// — an added file with a preserved old mtime, a deleted file, a changed
/// configuration, a cache belonging to a different tree — falls through to a
/// rescan.
async fn ensure_index(&mut self, root: &Path) -> Result<()> {
let cache_path = self.index_cache_path(root);
let loaded_from_cache = match &cache_path {
Some(path) => match self.loregrep.load_index_if_fresh(path, root) {
Ok(true) => {
eprintln!("Loaded index cache from {}", path.display());
true
}
Ok(false) => false,
Err(e) => {
eprintln!("Cache load failed ({}); rescanning", e);
false
}
},
None => false,
};
if !loaded_from_cache {
self.loregrep
.scan(&root.to_string_lossy())
.await
.map_err(|e| anyhow::anyhow!("Scan failed: {}", e))?;
// Persist the freshly built index so the next invocation can skip
// the scan. Uses the shared, non-fatal save path.
self.save_cache(root);
}
Ok(())
}
/// Execute a single analysis tool and print its `ToolResult` as JSON to stdout.
///
/// The index is obtained through [`CliApp::ensure_index`] (validated cache,
/// else scan). Cache use is opportunistic (no flag required) and honours
/// `config.cache.enabled`. All diagnostics go to stderr, so stdout carries
/// only the JSON result (for agent/tool consumption).
pub async fn exec_tool(&mut self, args: ExecToolArgs) -> Result<()> {
self.ensure_index(&args.path).await?;
let params: serde_json::Value = serde_json::from_str(&args.params)
.map_err(|e| anyhow::anyhow!("Invalid --params JSON: {}", e))?;
let result = self
.loregrep
.execute_tool(&args.tool, params)
.await
.map_err(|e| anyhow::anyhow!("Tool execution failed: {}", e))?;
println!("{}", serde_json::to_string_pretty(&result)?);
if !result.success {
std::process::exit(1);
}
Ok(())
}
/// Search the index for `args.query`.
///
/// This used to bail out with "Repository not scanned. Run 'scan' first" —
/// unconditionally, because every process starts with an empty index and
/// nothing here ever loaded the persisted one, so the advice was both
/// useless and impossible to follow (K7). It now obtains an index the same
/// way `exec-tool` does.
pub async fn search(&mut self, args: SearchArgs) -> Result<()> {
self.ensure_index(&args.path).await?;
let start_time = Instant::now();
if self.verbose {
eprintln!("Query: {}", args.query);
eprintln!("Search type: {}", args.r#type);
eprintln!(
"Fuzzy matching: {}",
if args.fuzzy { "enabled" } else { "disabled" }
);
}
// Perform search using public API tools
let results =
match args.r#type.as_str() {
"function" | "func" => {
let tool_result = self
.loregrep
.execute_tool(
"search_functions",
serde_json::json!({
"pattern": args.query,
"limit": args.limit
}),
)
.await
.map_err(|e| anyhow::anyhow!("Function search failed: {}", e))?;
if tool_result.success {
self.convert_tool_result_to_search_results(tool_result.data, "function")
} else {
eprintln!("Search failed: {:?}", tool_result.error);
Vec::new()
}
}
"struct" => {
let tool_result = self
.loregrep
.execute_tool(
"search_structs",
serde_json::json!({
"pattern": args.query,
"limit": args.limit
}),
)
.await
.map_err(|e| anyhow::anyhow!("Struct search failed: {}", e))?;
if tool_result.success {
self.convert_tool_result_to_search_results(tool_result.data, "struct")
} else {
eprintln!("Search failed: {:?}", tool_result.error);
Vec::new()
}
}
"all" => {
let mut all_results = Vec::new();
// Search functions
if let Ok(func_result) = self
.loregrep
.execute_tool(
"search_functions",
serde_json::json!({
"pattern": args.query,
"limit": args.limit / 2
}),
)
.await
{
if func_result.success {
all_results.extend(self.convert_tool_result_to_search_results(
func_result.data,
"function",
));
}
}
// Search structs
if let Ok(struct_result) = self
.loregrep
.execute_tool(
"search_structs",
serde_json::json!({
"pattern": args.query,
"limit": args.limit / 2
}),
)
.await
{
if struct_result.success {
all_results.extend(self.convert_tool_result_to_search_results(
struct_result.data,
"struct",
));
}
}
all_results
}
_ => {
eprintln!(
"Unknown search type: {}. Available types: function, struct, all",
args.r#type
);
return Ok(());
}
};
// Print results (data goes to stdout)
for result in &results {
match result.line {
Some(line) => println!("{}:{}: {}", result.file_path, line, result.content),
None => println!("{}: {}", result.file_path, result.content),
}
}
if self.verbose && !results.is_empty() {
eprintln!("Search completed in {:?}", start_time.elapsed());
}
Ok(())
}
pub async fn analyze(&mut self, args: AnalyzeArgs) -> Result<()> {
if !args.file.exists() {
eprintln!("Path not found: {}", args.file.display());
return Ok(());
}
let start_time = Instant::now();
if args.file.is_dir() {
// Directory analysis - analyze all files in the directory
if self.verbose {
eprintln!("Analyzing directory: {}", args.file.display());
eprintln!("Output format: {}", args.format);
}
// Scan the directory first to populate the in-memory RepoMap;
// `get_repository_tree` reads from that index, so without a scan a
// real run would print an empty tree.
self.loregrep
.scan(&args.file.to_string_lossy())
.await
.map_err(|e| anyhow::anyhow!("Directory scan failed: {}", e))?;
// There is no dedicated "analyze_directory" tool; the repository
// tree tool is the natural fit for a directory overview.
let tool_result = self
.loregrep
.execute_tool(
"get_repository_tree",
serde_json::json!({
"include_file_details": true,
"max_depth": 0
}),
)
.await
.map_err(|e| anyhow::anyhow!("Directory analysis failed: {}", e))?;
if !tool_result.success {
eprintln!("Analysis failed: {:?}", tool_result.error);
return Ok(());
}
// Display directory results
self.display_directory_analysis(&tool_result.data, &args);
if self.verbose {
eprintln!("Directory analysis completed in {:?}", start_time.elapsed());
}
} else {
// Single file analysis
if self.verbose {
eprintln!("Analyzing file: {}", args.file.display());
eprintln!("Output format: {}", args.format);
}
// A human naming a file on the command line IS the authorization, so
// the file's own directory becomes the analysis root for this
// invocation. The containment rule exists to stop AGENT-supplied
// parameters — which may be relaying untrusted text — from reaching
// arbitrary paths; it is not here to second-guess an explicit
// argument the user typed.
if let Some(parent) = args.file.parent() {
let root = if parent.as_os_str().is_empty() {
std::path::Path::new(".")
} else {
parent
};
self.loregrep.set_scan_root(&root.to_string_lossy());
}
// Use public API to analyze file
let tool_result = self
.loregrep
.execute_tool(
"analyze_file",
serde_json::json!({
"file_path": args.file.to_string_lossy(),
"include_content": true
}),
)
.await
.map_err(|e| anyhow::anyhow!("File analysis failed: {}", e))?;
if !tool_result.success {
eprintln!("Analysis failed: {:?}", tool_result.error);
return Ok(());
}
// Display results based on format
match args.format.as_str() {
"json" => {
let json = serde_json::to_string_pretty(&tool_result.data)
.context("Failed to serialize analysis to JSON")?;
println!("{}", json);
}
"text" => {
self.display_tool_analysis_text(&tool_result.data, &args);
}
"tree" => {
self.display_tool_analysis_tree(&tool_result.data);
}
_ => {
eprintln!("Unknown output format: {}", args.format);
return Ok(());
}
}
if self.verbose {
eprintln!("Analysis completed in {:?}", start_time.elapsed());
}
}
Ok(())
}
pub async fn show_config(&self) -> Result<()> {
let config_json = serde_json::to_string_pretty(&self.config)
.context("Failed to serialize configuration")?;
println!("{}", config_json);
Ok(())
}
// Helper methods for public API conversion
fn print_public_scan_results(&self, scan_result: &PublicScanResult) {
println!("Files scanned: {}", scan_result.files_scanned);
println!("Functions found: {}", scan_result.functions_found);
println!("Structs found: {}", scan_result.structs_found);
println!("Duration: {}ms", scan_result.duration_ms);
if !scan_result.languages.is_empty() {
println!("Languages: {:?}", scan_result.languages);
}
}
fn convert_tool_result_to_search_results(
&self,
data: serde_json::Value,
result_type: &str,
) -> Vec<SearchResult> {
let mut results = Vec::new();
// The search tools return an object of the shape
// `{ "status": .., "pattern": .., "results": [ ..items.. ], "count": N }`,
// so read the items out of the `results` array (not the top-level value).
if let Some(items) = data.get("results").and_then(|v| v.as_array()) {
for item in items {
if let Some(name) = item.get("name").and_then(|v| v.as_str()) {
let file_path = item
.get("file_path")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string();
// Items are serialized `FunctionSignature`/`StructSignature`,
// which expose `start_line`/`end_line` rather than `line_number`.
let line_number = item
.get("start_line")
.and_then(|v| v.as_u64())
.map(|n| n as u32);
let signature = match result_type {
"function" => {
let params = item
.get("parameters")
.and_then(|v| v.as_array())
.map(|arr| arr.len())
.unwrap_or(0);
let return_type = item
.get("return_type")
.and_then(|v| v.as_str())
.unwrap_or("");
if return_type.is_empty() {
format!("fn {}(...) [{}params]", name, params)
} else {
format!("fn {}(...) -> {} [{}params]", name, return_type, params)
}
}
"struct" => {
let fields = item
.get("fields")
.and_then(|v| v.as_array())
.map(|arr| arr.len())
.unwrap_or(0);
format!("struct {} {{ {}fields }}", name, fields)
}
_ => name.to_string(),
};
results.push(SearchResult::new(
result_type.to_string(),
signature,
file_path,
line_number,
));
}
}
}
results
}
/// The path to SHOW a human for a tool result.
///
/// Tool JSON is root-relative by contract (stable across machines, cheap in
/// tokens); a person reading a terminal wants the path they can paste, so the
/// display layer rejoins it with the `analysis_root` the response carries.
fn displayable_path(data: &serde_json::Value, file_path: &str) -> String {
match data.get("analysis_root").and_then(|v| v.as_str()) {
Some(root) if !root.is_empty() && !Path::new(file_path).is_absolute() => {
Path::new(root)
.join(file_path)
.to_string_lossy()
.to_string()
}
_ => file_path.to_string(),
}
}
fn display_tool_analysis_text(&self, data: &serde_json::Value, args: &AnalyzeArgs) {
if let Some(file_path) = data.get("file_path").and_then(|v| v.as_str()) {
println!("File: {}", Self::displayable_path(data, file_path));
}
if let Some(language) = data.get("language").and_then(|v| v.as_str()) {
println!("Language: {}", language);
}
// Display functions
if args.functions || (!args.structs && !args.imports) {
if let Some(functions) = data.get("functions").and_then(|v| v.as_array()) {
if !functions.is_empty() {
println!("Functions:");
for func in functions {
if let Some(name) = func.get("name").and_then(|v| v.as_str()) {
let params = func
.get("parameters")
.and_then(|v| v.as_array())
.map(|arr| arr.len())
.unwrap_or(0);
let return_type = func
.get("return_type")
.and_then(|v| v.as_str())
.unwrap_or("");
println!(
" fn {}({} params) -> {}",
name,
params,
if return_type.is_empty() {
"()"
} else {
return_type
}
);
}
}
}
}
}
// Display structs
if args.structs || (!args.functions && !args.imports) {
if let Some(structs) = data.get("structs").and_then(|v| v.as_array()) {
if !structs.is_empty() {
println!("Structs:");
for struct_item in structs {
if let Some(name) = struct_item.get("name").and_then(|v| v.as_str()) {
let fields = struct_item
.get("fields")
.and_then(|v| v.as_array())
.map(|arr| arr.len())
.unwrap_or(0);
println!(" struct {} {{ {} fields }}", name, fields);
}
}
}
}
}
}
fn display_tool_analysis_tree(&self, data: &serde_json::Value) {
if let Some(file_path) = data.get("file_path").and_then(|v| v.as_str()) {
println!("{}", Self::displayable_path(data, file_path));
if let Some(functions) = data.get("functions").and_then(|v| v.as_array()) {
for func in functions {
if let Some(name) = func.get("name").and_then(|v| v.as_str()) {
println!(" fn {}", name);
}
}
}
if let Some(structs) = data.get("structs").and_then(|v| v.as_array()) {
for struct_item in structs {
if let Some(name) = struct_item.get("name").and_then(|v| v.as_str()) {
println!(" struct {}", name);
}
}
}
}
}
/// Collect all `File` nodes from a `get_repository_tree` directory node,
/// walking directories recursively. Each returned value is the `FileNode`
/// JSON object (with a `skeleton` field).
fn collect_tree_files<'a>(node: &'a serde_json::Value, out: &mut Vec<&'a serde_json::Value>) {
if let Some(children) = node.get("children").and_then(|v| v.as_array()) {
for child in children {
match child.get("type").and_then(|v| v.as_str()) {
Some("File") => out.push(child),
Some("Directory") => Self::collect_tree_files(child, out),
_ => {}
}
}
}
}
fn display_directory_analysis(&self, data: &serde_json::Value, args: &AnalyzeArgs) {
match args.format.as_str() {
"json" => {
let json = serde_json::to_string_pretty(data).unwrap_or_else(|_| "{}".to_string());
println!("{}", json);
}
"text" => {
let tree = data
.get("repository_tree")
.unwrap_or(&serde_json::Value::Null);
let mut files = Vec::new();
Self::collect_tree_files(tree, &mut files);
let mut total_functions = 0;
let mut total_structs = 0;
for file_data in &files {
let skeleton = file_data
.get("skeleton")
.unwrap_or(&serde_json::Value::Null);
let file_path = skeleton
.get("path")
.and_then(|v| v.as_str())
.or_else(|| file_data.get("path").and_then(|v| v.as_str()))
.unwrap_or("unknown");
println!("File: {}", file_path);
if let Some(language) = skeleton.get("language").and_then(|v| v.as_str()) {
if !language.is_empty() {
println!("Language: {}", language);
}
}
// Display functions
if args.functions || (!args.structs && !args.imports) {
if let Some(functions) =
skeleton.get("functions").and_then(|v| v.as_array())
{
if !functions.is_empty() {
println!("Functions:");
for func in functions {
if let Some(name) = func.get("name").and_then(|v| v.as_str()) {
let params = func
.get("parameter_count")
.and_then(|v| v.as_u64())
.unwrap_or(0);
let return_type = func
.get("return_type")
.and_then(|v| v.as_str())
.unwrap_or("");
println!(
" fn {}({} params) -> {}",
name,
params,
if return_type.is_empty() {
"()"
} else {
return_type
}
);
total_functions += 1;
}
}
}
}
}
// Display structs
if args.structs || (!args.functions && !args.imports) {
if let Some(structs) = skeleton.get("structs").and_then(|v| v.as_array()) {
if !structs.is_empty() {
println!("Structs:");
for struct_item in structs {
if let Some(name) =
struct_item.get("name").and_then(|v| v.as_str())
{
let fields = struct_item
.get("field_count")
.and_then(|v| v.as_u64())
.unwrap_or(0);
println!(" struct {} {{ {} fields }}", name, fields);
total_structs += 1;
}
}
}
}
}
println!(); // Blank line between files
}
// Summary
println!(
"Summary: {} functions, {} structs across {} files",
total_functions,
total_structs,
files.len()
);
}
"tree" => {
let tree = data
.get("repository_tree")
.unwrap_or(&serde_json::Value::Null);
// The tree's own `root_path` is now the root-relative ".", which
// tells a human nothing; the absolute root travels alongside as
// `analysis_root`. Prefer it, and fall back for a response that
// predates it.
if let Some(root_path) = data
.get("analysis_root")
.and_then(|v| v.as_str())
.or_else(|| {
data.get("metadata")
.and_then(|m| m.get("root_path"))
.and_then(|v| v.as_str())
})
.or_else(|| tree.get("path").and_then(|v| v.as_str()))
{
println!("{}", root_path);
}
let mut files = Vec::new();
Self::collect_tree_files(tree, &mut files);
for file_data in &files {
let skeleton = file_data
.get("skeleton")
.unwrap_or(&serde_json::Value::Null);
let file_name = file_data
.get("name")
.and_then(|v| v.as_str())
.or_else(|| skeleton.get("path").and_then(|v| v.as_str()))
.unwrap_or("unknown");
println!(" {}", file_name);
if let Some(functions) = skeleton.get("functions").and_then(|v| v.as_array()) {
for func in functions {
if let Some(name) = func.get("name").and_then(|v| v.as_str()) {
println!(" fn {}", name);
}
}
}
if let Some(structs) = skeleton.get("structs").and_then(|v| v.as_array()) {
for struct_item in structs {
if let Some(name) = struct_item.get("name").and_then(|v| v.as_str()) {
println!(" struct {}", name);
}
}
}
}
}
_ => {
eprintln!("Unknown output format: {}", args.format);
}
}
}
// Helper methods
/// Persist the current in-memory index to this repository's entry in the
/// user's cache directory so later invocations can skip rescanning.
///
/// This is the single save path shared by `scan` and `ensure_index`: it owns
/// the cache-path computation and the error policy. Cache saving is a
/// best-effort optimization, so a failure is non-fatal — it warns on stderr
/// and returns rather than aborting the command. Diagnostics go to stderr
/// only; stdout is untouched (machine-first output).
/// A truncated index is deliberately not persisted: caching a partial view
/// of the repository would let the next run reload it as authoritative.
fn save_cache(&self, root_path: &Path) {
let Some(cache_path) = self.index_cache_path(root_path) else {
return; // caching disabled
};
let coverage = self.loregrep.index_coverage();
if coverage.truncated {
eprintln!(
"Not caching a truncated index ({} of {} files); raise max_files and rescan",
coverage.files_indexed, coverage.files_discovered
);
return;
}
match self.loregrep.save_index(&cache_path) {
Ok(()) => eprintln!("Saved index cache to {}", cache_path.display()),
Err(e) => eprintln!("Warning: failed to save index cache: {}", e),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::TempDir;
use tokio::test;
/// A config whose index cache lives somewhere disposable.
///
/// `CliConfig::default()` points at the *developer's real* cache directory,
/// so tests that ran a scan used to write there. Every test gets its own
/// root; tests that need two `CliApp`s to share a cache use
/// [`create_test_config_with_cache`] instead.
fn create_test_config() -> CliConfig {
let mut config = CliConfig::default();
config.cache.path = unique_temp_cache_root();
config
}
fn create_test_config_with_cache(cache_dir: &TempDir) -> CliConfig {
let mut config = CliConfig::default();
config.cache.path = cache_dir.path().to_path_buf();
config
}
fn unique_temp_cache_root() -> std::path::PathBuf {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
std::env::temp_dir().join(format!(
"loregrep-test-cache-{}-{}",
std::process::id(),
COUNTER.fetch_add(1, Ordering::Relaxed)
))
}
/// Snapshot of every path under `root` and the bytes of every file, used to
/// prove a command did not modify the tree it read.
fn tree_snapshot(root: &Path) -> Vec<(std::path::PathBuf, Option<Vec<u8>>)> {
fn walk(dir: &Path, out: &mut Vec<(std::path::PathBuf, Option<Vec<u8>>)>) {
let mut entries: Vec<_> = fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap().path())
.collect();
entries.sort();
for path in entries {
if path.is_dir() {
out.push((path.clone(), None));
walk(&path, out);
} else {
out.push((path.clone(), Some(fs::read(&path).unwrap())));
}
}
}
let mut out = Vec::new();
walk(root, &mut out);
out
}
fn create_test_rust_file(dir: &TempDir, name: &str, content: &str) -> std::path::PathBuf {
let file_path = dir.path().join(name);
fs::write(&file_path, content).unwrap();
file_path
}
#[test]
async fn test_cli_app_creation() {
let config = create_test_config();
let app = CliApp::new(config, false, true).await;
assert!(app.is_ok());
}
#[test]
async fn test_analyze_simple_rust_file() {
let temp_dir = TempDir::new().unwrap();
let rust_content = r#"
pub fn hello_world() -> String {
"Hello, World!".to_string()
}
pub struct TestStruct {
pub name: String,
pub value: i32,
}
use std::collections::HashMap;
"#;
let file_path = create_test_rust_file(&temp_dir, "test.rs", rust_content);
let config = create_test_config();
let mut app = CliApp::new(config, false, false).await.unwrap();
// Scan first, as every real invocation does: analyze_file resolves its
// parameter against the analysis root and refuses when none is known,
// rather than reading relative to the process cwd.
app.loregrep
.scan(temp_dir.path().to_str().unwrap())
.await
.unwrap();
// Use public API to analyze file
let result = app
.loregrep
.execute_tool(
"analyze_file",
serde_json::json!({
"file_path": file_path.to_string_lossy(),
"include_source": false
}),
)
.await;
assert!(result.is_ok());
let tool_result = result.unwrap();
assert!(tool_result.success);
// Check that we got analysis data
assert!(tool_result.data.get("language").is_some());
assert!(tool_result.data.get("functions").is_some());
assert!(tool_result.data.get("structs").is_some());
}
#[test]
async fn test_scan_directory() {
let temp_dir = TempDir::new().unwrap();
// Create multiple Rust files
create_test_rust_file(&temp_dir, "main.rs", "fn main() {}");
create_test_rust_file(&temp_dir, "lib.rs", "pub fn lib_func() {}");
create_test_rust_file(&temp_dir, "utils.rs", "pub struct Utils {}");
let config = create_test_config();
let mut app = CliApp::new(config, false, false).await.unwrap();
let scan_args = ScanArgs {
path: temp_dir.path().to_path_buf(),
cache: false,
};
let result = app.scan(scan_args).await;
assert!(result.is_ok());
// Check that repository was scanned using public API
assert!(app.loregrep.is_scanned());
let stats = app.loregrep.get_stats().unwrap();
assert!(stats.files_scanned > 0);
}
#[test]
async fn test_analyze_command() {
let temp_dir = TempDir::new().unwrap();
let rust_content = r#"
pub fn test_function(x: i32, y: String) -> bool {
x > 0 && !y.is_empty()
}
struct PrivateStruct {
field: String,
}
"#;
let file_path = create_test_rust_file(&temp_dir, "test.rs", rust_content);
let config = create_test_config();
let mut app = CliApp::new(config, false, false).await.unwrap();
let analyze_args = AnalyzeArgs {
file: file_path,
format: "text".to_string(),
functions: true,
structs: true,
imports: false,
};
let result = app.analyze(analyze_args).await;
assert!(result.is_ok());
}
#[test]
async fn test_search_empty_repo_map() {
// An empty directory, not "." — `search` now indexes the path it is
// given, and pointing a unit test at the process working directory
// would scan whatever tree the test runner happens to sit in.
let empty = TempDir::new().unwrap();
let config = create_test_config();
let mut app = CliApp::new(config, false, false).await.unwrap();
let search_args = SearchArgs {
query: "test".to_string(),
path: empty.path().to_path_buf(),
r#type: "function".to_string(),
limit: 10,
fuzzy: false,
};
let result = app.search(search_args).await;
assert!(result.is_ok());
}
#[test]
async fn test_config_display() {
let config = create_test_config();
let app = CliApp::new(config, false, false).await.unwrap();
let result = app.show_config().await;
assert!(result.is_ok());
}
#[test]
async fn test_convert_tool_result_reads_results_array() {
// Regression test: search tools return an OBJECT with a `results`
// array (not a bare array), and items carry `start_line` (not
// `line_number`). This test would fail against the old code that read
// `data.as_array()` / `line_number`.
let config = create_test_config();
let app = CliApp::new(config, false, false).await.unwrap();
let tool_data = serde_json::json!({
"status": "success",
"pattern": "foo",
"results": [
{
"name": "foo_bar",
"file_path": "/src/foo.rs",
"start_line": 42,
"end_line": 50,
"parameters": [{"name": "x"}, {"name": "y"}],
"return_type": "bool"
}
],
"count": 1
});
let results = app.convert_tool_result_to_search_results(tool_data, "function");
assert_eq!(results.len(), 1, "should read items from the results array");
assert_eq!(results[0].file_path, "/src/foo.rs");
assert_eq!(
results[0].line,
Some(42),
"line should come from start_line"
);
assert!(results[0].content.contains("foo_bar"));
}
#[test]
async fn test_exec_tool_scans_and_executes() {
// exec-tool should scan the given path then run the named tool and succeed.
let temp_dir = TempDir::new().unwrap();
create_test_rust_file(
&temp_dir,
"sample.rs",
"pub fn exec_target() -> i32 { 1 }\n",
);
let config = create_test_config();
let mut app = CliApp::new(config, false, false).await.unwrap();
let args = ExecToolArgs {
tool: "search_functions".to_string(),
params: r#"{"pattern":"exec_target"}"#.to_string(),
path: temp_dir.path().to_path_buf(),
};
// Success path returns Ok (prints JSON to stdout; no process exit).
assert!(app.exec_tool(args).await.is_ok());
// The exec-tool scan populated the index; the tool found the function.
let result = app
.loregrep
.execute_tool(
"search_functions",
serde_json::json!({"pattern": "exec_target"}),
)
.await
.unwrap();
assert!(result.success);
let count = result
.data
.get("count")
.and_then(|v| v.as_u64())
.unwrap_or(0);
assert!(count >= 1, "expected exec-tool scan to index exec_target");
}
#[test]
async fn exec_tool_leaves_the_analysed_tree_byte_for_byte_unchanged() {
// K11: `exec-tool` is a read. It used to write
// `<path>/.loregrep/index.cache` unconditionally — creating a directory
// inside a repository the user only asked a question about, and
// ignoring `cache.enabled` entirely.
let repo = TempDir::new().unwrap();
create_test_rust_file(
&repo,
"read_only.rs",
"pub fn read_only_fn() -> i32 { 1 }\n",
);
let nested = repo.path().join("nested");
fs::create_dir(&nested).unwrap();
fs::write(nested.join("more.rs"), "pub fn more_fn() -> i32 { 2 }\n").unwrap();
let before = tree_snapshot(repo.path());
let cache_dir = TempDir::new().unwrap();
let mut app = CliApp::new(create_test_config_with_cache(&cache_dir), false, false)
.await
.unwrap();
let args = ExecToolArgs {
tool: "search_functions".to_string(),
params: r#"{"pattern":"read_only_fn"}"#.to_string(),
path: repo.path().to_path_buf(),
};
assert!(app.exec_tool(args).await.is_ok());
assert_eq!(
tree_snapshot(repo.path()),
before,
"exec-tool must not modify the repository it analyses"
);
assert!(
!repo.path().join(".loregrep").exists(),
"no .loregrep directory may appear in the analysed tree"
);
// The index went to the user's own cache directory instead.
assert!(
LoreGrep::cache_path_for(cache_dir.path(), repo.path())
.unwrap()
.exists(),
"the index cache belongs under the configured cache root"
);
}
#[test]
async fn exec_tool_honours_the_cache_disabled_setting() {
// With caching off, nothing is written anywhere — neither in the
// analysed tree nor in the cache root. `exec_tool` used to consult no
// setting at all.
let repo = TempDir::new().unwrap();
create_test_rust_file(&repo, "nocache.rs", "pub fn nocache_fn() -> i32 { 1 }\n");
let before = tree_snapshot(repo.path());
let cache_dir = TempDir::new().unwrap();
let mut config = create_test_config_with_cache(&cache_dir);
config.cache.enabled = false;
let mut app = CliApp::new(config, false, false).await.unwrap();
let args = ExecToolArgs {
tool: "search_functions".to_string(),
params: r#"{"pattern":"nocache_fn"}"#.to_string(),
path: repo.path().to_path_buf(),
};
assert!(app.exec_tool(args).await.is_ok());
assert_eq!(tree_snapshot(repo.path()), before);
assert!(
!LoreGrep::cache_path_for(cache_dir.path(), repo.path())
.unwrap()
.exists(),
"cache.enabled = false must mean no cache file"
);
}
#[test]
async fn search_works_without_a_prior_scan_in_the_same_process() {
// K7: `search` opened with `if !is_scanned() { "run scan first" }`, and
// since each process starts empty that branch was taken every time —
// advice that could not be followed. It must obtain an index itself.
let repo = TempDir::new().unwrap();
create_test_rust_file(
&repo,
"searchable.rs",
"pub fn searchable_fn() -> i32 { 5 }\n",
);
let cache_dir = TempDir::new().unwrap();
let mut app = CliApp::new(create_test_config_with_cache(&cache_dir), false, false)
.await
.unwrap();
assert!(!app.loregrep.is_scanned(), "a fresh process starts empty");
let args = SearchArgs {
query: "searchable_fn".to_string(),
path: repo.path().to_path_buf(),
r#type: "function".to_string(),
limit: 10,
fuzzy: false,
};
assert!(app.search(args).await.is_ok());
assert!(
app.loregrep.is_scanned(),
"search must populate the index instead of telling the user to scan"
);
let result = app
.loregrep
.execute_tool(
"search_functions",
serde_json::json!({"pattern": "searchable_fn"}),
)
.await
.unwrap();
let count = result
.data
.get("count")
.and_then(|v| v.as_u64())
.unwrap_or(0);
assert!(count >= 1, "search should find the function it indexed");
}
#[test]
async fn search_reuses_the_cache_exec_tool_wrote() {
// The two commands share one load-or-scan path, so an index built by
// either is usable by the other.
let repo = TempDir::new().unwrap();
create_test_rust_file(&repo, "shared.rs", "pub fn shared_fn() -> i32 { 3 }\n");
let cache_dir = TempDir::new().unwrap();
let cache_path = LoreGrep::cache_path_for(cache_dir.path(), repo.path()).unwrap();
{
let mut app = CliApp::new(create_test_config_with_cache(&cache_dir), false, false)
.await
.unwrap();
let args = ExecToolArgs {
tool: "search_functions".to_string(),
params: r#"{"pattern":"shared_fn"}"#.to_string(),
path: repo.path().to_path_buf(),
};
assert!(app.exec_tool(args).await.is_ok());
}
assert!(cache_path.exists());
let mut app2 = CliApp::new(create_test_config_with_cache(&cache_dir), false, false)
.await
.unwrap();
assert!(app2.loregrep.is_cache_fresh(&cache_path, repo.path()));
let args = SearchArgs {
query: "shared_fn".to_string(),
path: repo.path().to_path_buf(),
r#type: "all".to_string(),
limit: 10,
fuzzy: false,
};
assert!(app2.search(args).await.is_ok());
assert!(app2.loregrep.is_scanned());
}
#[test]
async fn test_exec_tool_persists_and_reuses_cache() {
// First exec-tool invocation scans and writes a per-repo index cache;
// a second, fresh CliApp on the same path finds that cache fresh and
// loads it (proving repeated use does not require a rescan).
let temp_dir = TempDir::new().unwrap();
create_test_rust_file(
&temp_dir,
"cached.rs",
"pub fn cached_target() -> i32 { 7 }\n",
);
let cache_dir = TempDir::new().unwrap();
let cache_path = LoreGrep::cache_path_for(cache_dir.path(), temp_dir.path()).unwrap();
assert!(
!cache_path.exists(),
"no cache should exist before first run"
);
// First invocation: scans, then persists the index.
{
let config = create_test_config_with_cache(&cache_dir);
let mut app = CliApp::new(config, false, false).await.unwrap();
let args = ExecToolArgs {
tool: "search_functions".to_string(),
params: r#"{"pattern":"cached_target"}"#.to_string(),
path: temp_dir.path().to_path_buf(),
};
assert!(app.exec_tool(args).await.is_ok());
}
assert!(
cache_path.exists(),
"first exec-tool run should have written the index cache"
);
// Second invocation with a brand-new app: the cache is fresh and used.
let config = create_test_config_with_cache(&cache_dir);
let mut app2 = CliApp::new(config, false, false).await.unwrap();
assert!(
app2.loregrep.is_cache_fresh(&cache_path, temp_dir.path()),
"the just-written cache should be considered fresh"
);
let args = ExecToolArgs {
tool: "search_functions".to_string(),
params: r#"{"pattern":"cached_target"}"#.to_string(),
path: temp_dir.path().to_path_buf(),
};
assert!(app2.exec_tool(args).await.is_ok());
// The cache-loaded index resolves the function (loaded, not empty).
assert!(app2.loregrep.is_scanned());
let result = app2
.loregrep
.execute_tool(
"search_functions",
serde_json::json!({"pattern": "cached_target"}),
)
.await
.unwrap();
assert!(result.success);
let count = result
.data
.get("count")
.and_then(|v| v.as_u64())
.unwrap_or(0);
assert!(
count >= 1,
"cache-loaded index should contain cached_target"
);
}
#[test]
async fn test_exec_tool_cache_invalidated_on_file_deletion() {
// Regression: mtime-based freshness cannot see a *deleted* source file
// (removing it makes no remaining file newer than the cache), so a naive
// cache would keep returning the deleted file's symbols. exec_tool must
// detect the missing indexed path, discard the cache, and rescan.
let temp_dir = TempDir::new().unwrap();
create_test_rust_file(&temp_dir, "keep.rs", "pub fn alpha_keep() -> i32 { 1 }\n");
let doomed = create_test_rust_file(
&temp_dir,
"doomed.rs",
"pub fn beta_doomed() -> i32 { 2 }\n",
);
let cache_dir = TempDir::new().unwrap();
let cache_path = LoreGrep::cache_path_for(cache_dir.path(), temp_dir.path()).unwrap();
// First run: scan both files and persist the cache.
{
let mut app = CliApp::new(create_test_config_with_cache(&cache_dir), false, false)
.await
.unwrap();
let args = ExecToolArgs {
tool: "search_functions".to_string(),
params: r#"{"pattern":"beta_doomed"}"#.to_string(),
path: temp_dir.path().to_path_buf(),
};
assert!(app.exec_tool(args).await.is_ok());
}
assert!(cache_path.exists(), "first run should write the cache");
// Delete one indexed file. Its removal does NOT make any surviving file
// newer than the cache, so the old max(mtime) gate reported "fresh"
// forever. Comparing the indexed path set against what is on disk sees
// it immediately.
fs::remove_file(&doomed).unwrap();
let mut app2 = CliApp::new(create_test_config_with_cache(&cache_dir), false, false)
.await
.unwrap();
assert!(
!app2.loregrep.is_cache_fresh(&cache_path, temp_dir.path()),
"a deleted indexed file MUST make the cache stale"
);
// Second run: the cache is rejected and the path rescanned, so the
// deleted file's symbols are gone.
let args = ExecToolArgs {
tool: "search_functions".to_string(),
params: r#"{"pattern":"beta_doomed"}"#.to_string(),
path: temp_dir.path().to_path_buf(),
};
assert!(app2.exec_tool(args).await.is_ok());
let beta = app2
.loregrep
.execute_tool(
"search_functions",
serde_json::json!({"pattern": "beta_doomed"}),
)
.await
.unwrap();
let beta_count = beta.data.get("count").and_then(|v| v.as_u64()).unwrap_or(0);
assert_eq!(
beta_count, 0,
"deleted file's symbols must not survive in the rescanned index"
);
// Sanity: the surviving file is still indexed.
let alpha = app2
.loregrep
.execute_tool(
"search_functions",
serde_json::json!({"pattern": "alpha_keep"}),
)
.await
.unwrap();
let alpha_count = alpha
.data
.get("count")
.and_then(|v| v.as_u64())
.unwrap_or(0);
assert!(alpha_count >= 1, "surviving file should remain indexed");
}
#[test]
async fn test_freshness_ignores_files_in_excluded_dirs() {
// Regression: the freshness check must consider the SAME files the
// scanner indexes. A regenerated file under an excluded directory must
// NOT mark the cache stale (otherwise the cache never helps), while a
// real edit to an indexed file MUST.
let temp_dir = TempDir::new().unwrap();
create_test_rust_file(&temp_dir, "main.rs", "pub fn indexed_fn() -> i32 { 1 }\n");
// A file inside an excluded directory: it is not indexed, so it must not
// influence freshness.
let excluded_dir = temp_dir.path().join("excluded");
fs::create_dir(&excluded_dir).unwrap();
let excluded_file = excluded_dir.join("generated.rs");
fs::write(&excluded_file, "pub fn excluded_fn() -> i32 { 2 }\n").unwrap();
// Configure the scanner to exclude that directory (mirrors how config
// exclude_patterns / gitignore drop build artifacts).
let cache_dir = TempDir::new().unwrap();
let mut config = create_test_config_with_cache(&cache_dir);
config
.file_scanning
.exclude_patterns
.push("**/excluded/**".to_string());
let cache_path = LoreGrep::cache_path_for(cache_dir.path(), temp_dir.path()).unwrap();
{
let mut app = CliApp::new(config.clone(), false, false).await.unwrap();
let args = ExecToolArgs {
tool: "search_functions".to_string(),
params: r#"{"pattern":"indexed_fn"}"#.to_string(),
path: temp_dir.path().to_path_buf(),
};
assert!(app.exec_tool(args).await.is_ok());
}
assert!(cache_path.exists(), "first run should write the cache");
let app2 = CliApp::new(config.clone(), false, false).await.unwrap();
// Touch the excluded file so it is strictly newer than the cache. Since
// it is excluded from indexing, the cache must still be considered fresh.
std::thread::sleep(std::time::Duration::from_millis(20));
fs::write(&excluded_file, "pub fn excluded_fn() -> i32 { 3 }\n").unwrap();
assert!(
app2.loregrep.is_cache_fresh(&cache_path, temp_dir.path()),
"a change under an excluded dir must NOT make the cache stale"
);
// Control: editing the indexed file MUST invalidate the cache.
std::thread::sleep(std::time::Duration::from_millis(20));
fs::write(
temp_dir.path().join("main.rs"),
"pub fn indexed_fn() -> i32 { 42 }\n",
)
.unwrap();
assert!(
!app2.loregrep.is_cache_fresh(&cache_path, temp_dir.path()),
"editing an indexed file MUST make the cache stale"
);
}
#[tokio::test]
async fn test_analyze_directory_produces_output() {
// Regression test for the `analyze <directory>` path, which used to call
// a nonexistent `analyze_directory` tool. It now routes to
// `get_repository_tree`; verify the whole path succeeds and that the
// returned tree contains the scanned file with its symbols.
let temp_dir = TempDir::new().unwrap();
let rust_content = r#"
pub fn dir_function() -> i32 {
7
}
pub struct DirStruct {
pub field: String,
}
"#;
create_test_rust_file(&temp_dir, "sample.rs", rust_content);
let config = create_test_config();
let mut app = CliApp::new(config, false, false).await.unwrap();
// Do NOT scan manually here: the `analyze <directory>` path must scan
// the directory itself before reading the repository tree. Without that,
// a real run would print an empty tree.
let analyze_args = AnalyzeArgs {
file: temp_dir.path().to_path_buf(),
format: "text".to_string(),
functions: true,
structs: true,
imports: false,
};
assert!(app.analyze(analyze_args).await.is_ok());
// The analyze path itself populated the index.
assert!(
app.loregrep.is_scanned(),
"analyze <directory> should have scanned the directory"
);
// Exercise the underlying tool call and assert non-empty output.
let tool_result = app
.loregrep
.execute_tool(
"get_repository_tree",
serde_json::json!({
"include_file_details": true,
"max_depth": 0
}),
)
.await
.unwrap();
assert!(tool_result.success);
let tree = tool_result
.data
.get("repository_tree")
.expect("repository_tree present");
let mut files = Vec::new();
CliApp::collect_tree_files(tree, &mut files);
assert!(
!files.is_empty(),
"directory analysis should surface at least one file"
);
// The scanned file should expose its function and struct.
let has_symbols = files.iter().any(|f| {
let skeleton = f.get("skeleton");
let funcs = skeleton
.and_then(|s| s.get("functions"))
.and_then(|v| v.as_array())
.map(|a| !a.is_empty())
.unwrap_or(false);
let structs = skeleton
.and_then(|s| s.get("structs"))
.and_then(|v| v.as_array())
.map(|a| !a.is_empty())
.unwrap_or(false);
funcs || structs
});
assert!(
has_symbols,
"scanned file should carry functions/structs in its skeleton"
);
}
#[test]
async fn test_analyze_nonexistent_file() {
let config = create_test_config();
let mut app = CliApp::new(config, false, false).await.unwrap();
let analyze_args = AnalyzeArgs {
file: std::path::PathBuf::from("nonexistent.rs"),
format: "text".to_string(),
functions: false,
structs: false,
imports: false,
};
let result = app.analyze(analyze_args).await;
assert!(result.is_ok()); // Should handle gracefully
}
#[test]
async fn test_analyze_json_format() {
let temp_dir = TempDir::new().unwrap();
let rust_content = "pub fn simple() {}";
let file_path = create_test_rust_file(&temp_dir, "simple.rs", rust_content);
let config = create_test_config();
let mut app = CliApp::new(config, false, false).await.unwrap();
let analyze_args = AnalyzeArgs {
file: file_path,
format: "json".to_string(),
functions: false,
structs: false,
imports: false,
};
let result = app.analyze(analyze_args).await;
assert!(result.is_ok());
}
#[test]
async fn test_analyze_file_json_includes_content() {
// Regression: the single-file analyze branch passed `include_source`,
// but the analyze_file tool reads `include_content`, so source was never
// included. Verify the corrected key surfaces `content`, and that the
// old (wrong) key does not.
let temp_dir = TempDir::new().unwrap();
let rust_content = "pub fn simple() -> i32 { 1 }";
let file_path = create_test_rust_file(&temp_dir, "simple.rs", rust_content);
let config = create_test_config();
let mut app = CliApp::new(config, false, false).await.unwrap();
// Scan first: analyze_file resolves against the analysis root.
app.loregrep
.scan(temp_dir.path().to_str().unwrap())
.await
.unwrap();
// Corrected key used by `analyze <file>` -> content present.
let with_content = app
.loregrep
.execute_tool(
"analyze_file",
serde_json::json!({
"file_path": file_path.to_string_lossy(),
"include_content": true
}),
)
.await
.unwrap();
assert!(with_content.success);
assert_eq!(
with_content.data.get("content").and_then(|v| v.as_str()),
Some(rust_content),
"include_content: true should surface the file content"
);
// Old/wrong key is ignored by the tool -> no content field.
let wrong_key = app
.loregrep
.execute_tool(
"analyze_file",
serde_json::json!({
"file_path": file_path.to_string_lossy(),
"include_source": true
}),
)
.await
.unwrap();
assert!(wrong_key.success);
assert!(
wrong_key.data.get("content").is_none(),
"the wrong key must not surface content"
);
}
#[test]
async fn test_analyze_tree_format() {
let temp_dir = TempDir::new().unwrap();
let rust_content = "pub fn simple() {}";
let file_path = create_test_rust_file(&temp_dir, "simple.rs", rust_content);
let config = create_test_config();
let mut app = CliApp::new(config, false, false).await.unwrap();
let analyze_args = AnalyzeArgs {
file: file_path,
format: "tree".to_string(),
functions: false,
structs: false,
imports: false,
};
let result = app.analyze(analyze_args).await;
assert!(result.is_ok());
}
}