smart-tree 8.0.1

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

// Import CLI definitions from the library
use st::cli::{Cli, ColorMode, OutputMode, PathMode};
use std::io::{self, IsTerminal};
use std::path::PathBuf;

// Pulling in the brains of the operation from our library modules.
// NOTE: Scanning and formatting now happens in the daemon (thin-client architecture)
use st::{
    daemon_client::DaemonClient,
    feature_flags,
    in_memory_logger::{InMemoryLogStore, InMemoryLoggerLayer},
    service_manager,
};
use tracing_subscriber::{fmt, prelude::*, EnvFilter};

/// CLI definitions are centralized in [`st::cli`](src/cli.rs) module.
// ...
// ... existing code ...
// ...
#[tokio::main]
async fn main() -> Result<()> {
    // Parse the command-line arguments provided by the user.
    let cli = Cli::parse();

    // Initialize Logging
    let log_level_str = if let Some(level) = cli.log_level {
        match level {
            st::cli::LogLevel::Error => "error",
            st::cli::LogLevel::Warn => "warn",
            st::cli::LogLevel::Info => "info",
            st::cli::LogLevel::Debug => "debug",
            st::cli::LogLevel::Trace => "trace",
        }
    } else {
        "info" // Default log level
    };

    if std::env::var("RUST_LOG").is_err() {
        std::env::set_var("RUST_LOG", log_level_str);
    }

    let log_store = InMemoryLogStore::new();
    let in_memory_layer = InMemoryLoggerLayer::new(log_store.clone());

    tracing_subscriber::registry()
        .with(EnvFilter::from_default_env())
        .with(fmt::layer().with_writer(io::stderr))
        .with(in_memory_layer)
        .init();

    // First-run signature verification banner
    // Shows trust status on initial run (official/community/unsigned build)
    if !cli.mcp {
        service_manager::print_signature_banner();
    }

    // Check for updates on startup (rate-limited, non-blocking)
    // Skip if --no-update-check is set or if this is an exclusive command
    if !cli.no_update_check && !cli.version && !cli.update && !cli.mcp {
        if let Some(latest) = st::updater::check_for_update_cached().await {
            st::updater::print_update_banner(&latest);
        }
    }

    // Auto-start daemon for any command that might need it.
    // Skip for modes that run their own servers or are purely informational.
    let skip_autostart = cli.mcp || cli.http_daemon || cli.guardian_daemon
        || cli.version || cli.update || cli.cheet || cli.man
        || cli.completions.is_some() || cli.daemon_start || cli.daemon_install
        || matches!(cli.cmd, Some(st::cli::Cmd::Service(_)));
    if !skip_autostart {
        let client = DaemonClient::default_port();
        if let Err(e) = client.ensure_running().await {
            eprintln!("⚠️  Daemon auto-start failed: {}", e);
            eprintln!("   Try: st --daemon-start");
        }
    }

    // Handle tips flag if provided
    if let Some(state) = &cli.tips {
        let enable = state == "on";
        st::tips::handle_tips_flag(enable)?;
        return Ok(());
    }

    // Handle Aye consciousness commands
    if cli.agent_save {
        return handle_agent_save().await;
    }
    if cli.agent_restore {
        return handle_agent_restore().await;
    }
    if cli.agent_context {
        return handle_agent_context().await;
    }
    if cli.agent_kickstart {
        return handle_agent_kickstart().await;
    }
    if cli.agent_dump {
        return handle_agent_dump().await;
    }
    if let Some(args) = &cli.memory_anchor {
        if args.len() == 3 {
            return handle_memory_anchor(&args[0], &args[1], &args[2]).await;
        } else {
            return show_memory_anchor_help();
        }
    }
    if let Some(keywords) = &cli.memory_find {
        return handle_memory_find(keywords).await;
    }
    if cli.memory_stats {
        return handle_memory_stats().await;
    }
    if let Some(path) = &cli.update_consciousness {
        return handle_update_consciousness(path).await;
    }

    // Handle spicy TUI mode
    if cli.spicy {
        // Check if TUI is enabled via feature flags
        let flags = feature_flags::features();
        if !flags.enable_tui {
            eprintln!("Error: Terminal UI is disabled by configuration or compliance mode.");
            eprintln!("Contact your administrator to enable this feature.");
            return Ok(());
        }
        let path = std::env::current_dir()?;
        return st::spicy_tui_enhanced::run_enhanced_spicy_tui(path).await;
    }

    // Initialize logging if requested
    if let Some(log_path) = &cli.log {
        // Check if activity logging is enabled via feature flags
        let flags = feature_flags::features();
        if !flags.enable_activity_logging {
            eprintln!("Warning: Activity logging is disabled by configuration or compliance mode.");
            eprintln!("Continuing without logging.");
        } else {
            // log_path is Option<Option<String>> - Some(None) means --log without path
            let path = log_path.clone();
            st::activity_logger::ActivityLogger::init(path)?;
            // Log will be written throughout execution
        }
    }

    // Handle exclusive action flags first.
    if cli.cheet {
        let markdown = std::fs::read_to_string("docs/st-cheetsheet.md")?;
        let skin = termimad::MadSkin::default();
        skin.print_text(&markdown);
        return Ok(());
    }
    if let Some(shell) = cli.completions {
        let mut cmd = Cli::command();
        let bin_name = cmd.get_name().to_string();
        generate(shell, &mut cmd, bin_name, &mut io::stdout());
        return Ok(());
    }
    if cli.man {
        let cmd = Cli::command();
        let man = clap_mangen::Man::new(cmd);
        man.render(&mut io::stdout())?;
        return Ok(());
    }
    if cli.version {
        return show_version_with_updates().await;
    }
    if cli.update {
        match check_for_updates_cli().await {
            Ok(msg) => {
                println!("{}", msg);
                return Ok(());
            }
            Err(e) => {
                eprintln!("❌ Update check failed: {}", e);
                std::process::exit(1);
            }
        }
    }
    if cli.mcp {
        // Check if MCP server is enabled via feature flags
        let flags = feature_flags::features();
        if !flags.enable_mcp_server {
            eprintln!("Error: MCP server is disabled by configuration or compliance mode.");
            eprintln!("Contact your administrator to enable this feature.");
            return Ok(());
        }
        return run_mcp_server().await;
    }
    if cli.mcp_install {
        return handle_mcp_install().await;
    }
    if cli.mcp_uninstall {
        return handle_mcp_uninstall().await;
    }
    if cli.mcp_status {
        return handle_mcp_status().await;
    }
    // Handle top-level subcommands
    if let Some(cmd) = cli.cmd {
        match cmd {
            st::cli::Cmd::Service(service_command) => {
                let result = match service_command {
                    st::cli::Service::Install => service_manager::install(),
                    st::cli::Service::Uninstall => service_manager::uninstall(),
                    st::cli::Service::Start => service_manager::start(),
                    st::cli::Service::Stop => service_manager::stop(),
                    st::cli::Service::Status => service_manager::status(),
                    st::cli::Service::Logs => service_manager::logs(),
                };

                if let Err(e) = result {
                    eprintln!("❌ Service operation failed: {}", e);
                    std::process::exit(1);
                }
                return Ok(());
            }

            st::cli::Cmd::ProjectTags(project_tags) => {
                let project_path = ".";
                match project_tags {
                    st::cli::ProjectTags::Add { tag } => {
                        st::project_tags::add(project_path, &tag);
                        println!("Added tag '{}' to the project.", tag);
                    }
                    st::cli::ProjectTags::Remove { tag } => {
                        st::project_tags::remove(project_path, &tag);
                        println!("Removed tag '{}' from the project.", tag);
                    }
                }
                return Ok(());
            }
        }
    }

    // Handle diff storage operations
    if cli.scan_opts.view_diffs {
        return handle_view_diffs().await;
    }
    if let Some(keep_count) = cli.scan_opts.cleanup_diffs {
        return handle_cleanup_diffs(keep_count).await;
    }

    if cli.terminal {
        // Check if terminal is enabled via feature flags
        let flags = feature_flags::features();
        if !flags.enable_tui {
            eprintln!("Error: Terminal interface is disabled by configuration or compliance mode.");
            eprintln!("Contact your administrator to enable this feature.");
            return Ok(());
        }
        return run_terminal().await;
    }

    if cli.dashboard {
        // Launch web dashboard
        return run_web_dashboard(
            cli.scan_opts.sse_port,
            cli.open_browser,
            cli.allow.clone(),
            InMemoryLogStore::new(),
        ).await;
    }

    if cli.http_daemon {
        // Launch HTTP daemon with MCP, LLM proxy, The Custodian
        return run_daemon(cli.scan_opts.sse_port).await;
    }

    // Handle security commands
    if let Some(path) = &cli.security_scan {
        return handle_security_scan(path).await;
    }
    if let Some(file) = &cli.guardian_scan {
        return handle_guardian_scan(std::path::Path::new(file));
    }
    if cli.guardian_daemon {
        return run_guardian_daemon().await;
    }
    if cli.cleanup {
        return handle_security_cleanup().await;
    }

    // Handle hooks commands
    if cli.hooks_install {
        return install_hooks_to_agent().await;
    }
    if let Some(action) = &cli.hooks_config {
        return handle_hooks_config(action).await;
    }

    // Handle daemon control
    if cli.daemon_start {
        return handle_daemon_start(cli.scan_opts.sse_port).await;
    }
    if cli.daemon_stop {
        return handle_daemon_stop(cli.scan_opts.sse_port).await;
    }
    if cli.daemon_status {
        return handle_daemon_status(cli.scan_opts.sse_port).await;
    }
    if cli.daemon_context {
        return handle_daemon_context(cli.scan_opts.sse_port).await;
    }
    if cli.daemon_projects {
        return handle_daemon_projects(cli.scan_opts.sse_port).await;
    }
    if cli.daemon_credits {
        return handle_daemon_credits(cli.scan_opts.sse_port).await;
    }
    if cli.daemon_install {
        return service_manager::daemon_install_system().map_err(Into::into);
    }

    // Handle mega sessions
    if let Some(name) = &cli.mega_start {
        let name_opt = if name.is_empty() { None } else { Some(name.as_str()) };
        return handle_mega_start(name_opt).await;
    }
    if cli.mega_save {
        return handle_mega_save().await;
    }
    if cli.mega_list {
        return handle_mega_list().await;
    }
    if cli.mega_stats {
        return handle_mega_stats().await;
    }

    // Handle analysis commands
    if let Some(path) = &cli.token_stats {
        return handle_token_stats(path).await;
    }
    if let Some(path) = &cli.get_frequency {
        return handle_get_frequency(path).await;
    }

    // =========================================================================
    // THIN CLIENT - All scanning/formatting happens in the daemon
    // =========================================================================
    // Ensure daemon is running (always required now)
    let client = DaemonClient::default_port();
    client.ensure_running().await.context(
        "Smart Tree daemon could not be started. Try: std start",
    )?;

    // Build CLI request from arguments
    let request = build_cli_request(&cli)?;

    // Execute scan via daemon
    let response = client.cli_scan(request.clone()).await.context("Scan failed")?;

    // Print Treehouse ASCII banner for interactive non-machine modes
    if std::io::stdout().is_terminal() && (request.mode == "smart" || request.mode == "classic") {
        print_treehouse_banner();
    }

    // Print output (already formatted by daemon)
    print!("{}", response.output);

    Ok(())
}

/// Prints a cool cyber-botanical Tree-House ASCII banner
fn print_treehouse_banner() {
    let banner = "
      ⋆          ⋆          ⋆
  ⋆       / \\         ⋆
       /   o \\    ⋆
   ⋆  /_________\\       ⋆
         |   | 
         |   | 
       _ |_ _|_ _       
   S M A R T  T R E E H O U S E
";
    println!("{}", banner);
}

/// Build a CliScanRequest from CLI arguments
fn build_cli_request(cli: &Cli) -> Result<st::daemon_cli::CliScanRequest> {
    let args = &cli.scan_opts;

    // Convert path to absolute - daemon runs in different directory
    let path = cli.path.clone().unwrap_or_else(|| ".".to_string());
    let path = if std::path::Path::new(&path).is_absolute() {
        path
    } else {
        // Make relative path absolute based on client's cwd
        std::env::current_dir()
            .map(|cwd| cwd.join(&path).display().to_string())
            .unwrap_or(path)
    };

    // Determine output mode from args or environment
    // Default is now "smart" - surface what matters!
    let mode = if args.smart {
        "smart".to_string()
    } else if matches!(args.mode, OutputMode::Auto) {
        // Check environment variable, default to smart
        std::env::var("ST_DEFAULT_MODE")
            .unwrap_or_else(|_| "smart".to_string())
            .to_lowercase()
    } else {
        format!("{:?}", args.mode).to_lowercase()
    };

    // Smart mode implies smart scanning features
    let is_smart_mode = mode == "smart";

    // Determine path display mode
    let path_mode = match args.path_mode {
        PathMode::Off => "off",
        PathMode::Relative => "relative",
        PathMode::Full => "full",
    }
    .to_string();

    // Determine if color should be used based on ColorMode
    let use_color = match args.color {
        ColorMode::Always => true,
        ColorMode::Never => false,
        ColorMode::Auto => std::io::stdout().is_terminal(),
    };

    // Smart mode defaults to depth 5 for comprehensive but focused scanning
    let depth = if args.depth == 0 && is_smart_mode {
        5
    } else {
        args.depth
    };

    Ok(st::daemon_cli::CliScanRequest {
        path,
        mode,
        depth,
        all: args.all,
        respect_gitignore: !args.no_ignore,
        default_ignores: !args.no_default_ignore,
        show_ignored: args.show_ignored,
        find: args.find.clone(),
        file_type: args.filter_type.clone(),
        entry_type: args.entry_type.clone(),
        min_size: args.min_size.clone(),
        max_size: args.max_size.clone(),
        sort: args.sort.map(|s| format!("{:?}", s).to_lowercase()),
        top: args.top,
        search: args.search.clone(),
        compress: args.compress,
        no_emoji: args.no_emoji || args.mcp_optimize,
        use_color,
        path_mode,
        focus: args.focus.as_ref().map(|p| p.display().to_string()),
        relations_filter: args.relations_filter.clone(),
        show_filesystems: args.show_filesystems,
        include_line_content: false, // Not exposed in CLI, used by MCP
        compact: args.compact,
        // Smart scanning options - enabled by default in smart mode
        smart: args.smart || is_smart_mode,
        changes_only: args.changes_only,
        min_interest: args.min_interest,
        security: !args.no_security,
    })
}

// =========================================================================
// HELPER FUNCTIONS
// =========================================================================
// NOTE: The scan operation has been moved to the daemon (thin-client architecture)
// Helper functions below are kept for exclusive modes that don't use the daemon.

// --- MCP Helper Functions (only compiled if "mcp" feature is enabled) ---

/// Prints the JSON configuration snippet for adding `st` as an MCP server
/// to Claude Desktop. This helps users easily integrate `st`.
fn print_mcp_config() {
    // Try to get the current executable's path. Fallback to "st" if it fails.
    let exe_path = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("st")); // Graceful fallback.

    // Print the JSON structure, making it easy for users to copy-paste.
    // Using println! for each line for clarity.
    println!("Add this to your Claude Desktop configuration (claude_desktop_config.json):");
    println!(); // Blank line for spacing.
    println!("{{"); // Start of JSON object.
    println!("  \"mcpServers\": {{");
    println!("    \"smart-tree\": {{"); // Server name: "smart-tree".
    println!("      \"command\": \"{}\",", exe_path.display()); // Path to the st executable.
    println!("      \"args\": [\"--mcp\"],"); // Arguments to run st in MCP server mode.
    println!("      \"env\": {{}}"); // Optional environment variables for the server process.
    println!("    }}");
    println!("  }}");
    println!("}}"); // End of JSON object.
    println!();
    // Provide common locations for the Claude Desktop config file.
    println!("Default locations for claude_desktop_config.json:");
    println!("  macOS:   ~/Library/Application Support/Claude/claude_desktop_config.json");
    println!("  Windows: %APPDATA%\\Claude\\claude_desktop_config.json");
    println!("  Linux:   ~/.config/Claude/claude_desktop_config.json");
}

/// Prints a list of available MCP tools that `st` provides.
/// This helps users (or AI) understand what actions can be performed via MCP.
fn print_mcp_tools() {
    println!("🌳 Smart Tree MCP Server - Available Tools (20+) 🌳");
    println!();
    println!("📚 Full documentation: Run 'st --mcp' to start the MCP server");
    println!("💡 Pro tip: Use these tools with Claude Desktop for AI-powered file analysis!");
    println!();
    println!("CORE TOOLS:");
    println!("  • server_info - Get server capabilities and current time");
    println!("  • analyze_directory - Main workhorse with multiple output formats");
    println!("  • quick_tree - Lightning-fast 3-level overview (10x compression)");
    println!("  • project_overview - Comprehensive project analysis");
    println!();
    println!("FILE DISCOVERY:");
    println!("  • find_files - Search with regex, size, date filters");
    println!("  • find_code_files - Find source code by language");
    println!("  • find_config_files - Locate all configuration files");
    println!("  • find_documentation - Find README, docs, licenses");
    println!("  • find_tests - Locate test files across languages");
    println!("  • find_build_files - Find Makefile, Cargo.toml, etc.");
    println!();
    println!("CONTENT SEARCH:");
    println!("  • search_in_files - Powerful content search (like grep)");
    println!("  • find_large_files - Identify space consumers");
    println!("  • find_recent_changes - Files modified in last N days");
    println!("  • find_in_timespan - Files modified in date range");
    println!();
    println!("ANALYSIS:");
    println!("  • get_statistics - Comprehensive directory stats");
    println!("  • get_digest - SHA256 hash for change detection");
    println!("  • directory_size_breakdown - Size by subdirectory");
    println!("  • find_empty_directories - Cleanup opportunities");
    println!("  • find_duplicates - Detect potential duplicate files");
    println!("  • semantic_analysis - Group files by purpose");
    println!();
    println!("ADVANCED:");
    println!("  • compare_directories - Find differences between dirs");
    println!("  • get_git_status - Git-aware directory structure");
    println!("  • analyze_workspace - Multi-project workspace analysis");
    println!();
    println!("SMART EDIT (90% token reduction!):");
    println!("  • smart_edit - Apply multiple AST-based edits efficiently");
    println!("  • get_function_tree - Analyze code structure");
    println!("  • insert_function - Add functions with minimal tokens");
    println!("  • remove_function - Remove functions with dependency awareness");
    println!("  • track_file_operation - Track AI file manipulations (.st folder)");
    println!("  • get_file_history - View operation history for files");
    println!();
    println!("FEEDBACK:");
    println!("  • submit_feedback - Help improve Smart Tree");
    println!("  • request_tool - Request new MCP tools");
    println!("  • check_for_updates - Check for newer versions");
    println!();
    println!("Run 'st --mcp' to start the server and see full parameter details!");
}

/// Show version information with optional update checking
/// This combines the traditional --version output with smart update detection
/// Elvis would love this modern approach! 🕺
async fn show_version_with_updates() -> Result<()> {
    let current_version = env!("CARGO_PKG_VERSION");

    // Always show current version info first
    println!(
        "🌟 Smart Tree v{} - The Gradient Enhancement Release! 🌈",
        current_version
    );
    println!("🔧 Target: {}", std::env::consts::ARCH);
    println!("📦 Repository: {}", env!("CARGO_PKG_REPOSITORY"));
    println!("🎯 Authors: {}", env!("CARGO_PKG_AUTHORS"));
    println!("📝 Description: {}", env!("CARGO_PKG_DESCRIPTION"));

    // Check for updates (but don't fail if update service is unavailable)
    match check_for_updates_cli().await {
        Ok(update_info) => {
            if update_info.is_empty() {
                println!("✅ You're running the latest version! 🎉");
            } else {
                println!();
                println!("{}", update_info);
            }
        }
        Err(e) => {
            // Don't fail the whole command if update check fails
            eprintln!("⚠️  Update check unavailable: {}", e);
            println!("💡 Check https://github.com/8b-is/smart-tree for the latest releases");
        }
    }

    println!();
    println!("🚀 Ready to make your directories beautiful! Try: st --help");
    println!("🎭 Trish from Accounting loves the colorful tree views! 🎨");

    Ok(())
}

/// Handle viewing diffs from the .st folder
async fn handle_view_diffs() -> Result<()> {
    use st::smart_edit_diff::DiffStorage;

    let project_root = std::env::current_dir()?;
    let storage = DiffStorage::new(&project_root)?;

    // List all diffs
    let diffs = storage.list_all_diffs()?;

    if diffs.is_empty() {
        println!("📁 No diffs found in .st folder");
        println!("💡 Smart Edit operations automatically store diffs when files are modified");
        return Ok(());
    }

    println!("📜 Smart Edit Diff History");
    println!("{}", "=".repeat(60));

    // Group diffs by file
    let mut by_file: std::collections::HashMap<String, Vec<(String, u64)>> =
        std::collections::HashMap::new();

    for (file_path, timestamp) in diffs {
        by_file
            .entry(file_path.clone())
            .or_default()
            .push((file_path, timestamp));
    }

    for (file, mut entries) in by_file {
        // Sort by timestamp (newest first)
        entries.sort_by(|a, b| b.1.cmp(&a.1));

        println!("\n📄 {}", file);
        for (_, timestamp) in entries.iter().take(5) {
            let dt = chrono::DateTime::<chrono::Utc>::from_timestamp(*timestamp as i64, 0)
                .unwrap_or_default();
            println!("{} ({})", dt.format("%Y-%m-%d %H:%M:%S UTC"), timestamp);
        }

        if entries.len() > 5 {
            println!("  ... and {} more", entries.len() - 5);
        }
    }

    println!("\n💡 Use 'st --cleanup-diffs N' to keep only the last N diffs per file");

    Ok(())
}

/// Handle cleaning up old diffs
async fn handle_cleanup_diffs(keep_count: usize) -> Result<()> {
    use st::smart_edit_diff::DiffStorage;

    let project_root = std::env::current_dir()?;
    let storage = DiffStorage::new(&project_root)?;

    println!(
        "🧹 Cleaning up old diffs, keeping last {} per file...",
        keep_count
    );

    let removed = storage.cleanup_old_diffs(keep_count)?;

    if removed == 0 {
        println!("✨ No diffs needed cleanup");
    } else {
        println!("✅ Removed {} old diff files", removed);
    }

    Ok(())
}

/// Check for updates from our feedback API (CLI version)
/// Returns update message if available, empty string if up-to-date
async fn check_for_updates_cli() -> Result<String> {
    let current_version = env!("CARGO_PKG_VERSION");

    // Skip update check if explicitly disabled
    if std::env::var("SMART_TREE_NO_UPDATE_CHECK").is_ok() {
        return Ok(String::new());
    }

    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(2)) // Global timeout for all operations
        .connect_timeout(std::time::Duration::from_secs(1)) // Quick connect timeout
        .build()?;

    let api_url =
        std::env::var("SMART_TREE_FEEDBACK_API").unwrap_or_else(|_| "https://f.8b.is".to_string());

    // Use the /mcp/check endpoint which doesn't require auth
    let platform = std::env::consts::OS;
    let arch = std::env::consts::ARCH;
    let check_url = format!(
        "{}/mcp/check?version={}&platform={}&arch={}",
        api_url, current_version, platform, arch
    );

    let response = client
        .get(&check_url)
        .send()
        .await
        .map_err(|e| anyhow::anyhow!("Network error: {}", e))?;

    if !response.status().is_success() {
        return Err(anyhow::anyhow!("Service returned: {}", response.status()));
    }

    let update_info: serde_json::Value = response
        .json()
        .await
        .map_err(|e| anyhow::anyhow!("Failed to parse response: {}", e))?;

    if !update_info["update_available"].as_bool().unwrap_or(false) {
        return Ok(String::new()); // Up to date
    }

    // Format update message for CLI
    let latest_version = update_info["latest_version"].as_str().unwrap_or("unknown");
    let release_notes = &update_info["release_notes"];

    let highlights = release_notes["highlights"]
        .as_array()
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str())
                .map(|s| format!("{}", s))
                .collect::<Vec<_>>()
                .join("\n")
        })
        .unwrap_or_default();

    let ai_benefits = release_notes["ai_benefits"]
        .as_array()
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str())
                .map(|s| format!("{}", s))
                .collect::<Vec<_>>()
                .join("\n")
        })
        .unwrap_or_default();

    let mut message = format!(
        "🚀 \x1b[1;32mNew Version Available!\x1b[0m\n\n\
        📊 Current: v{} → Latest: \x1b[1;36mv{}\x1b[0m\n\n\
        🎯 \x1b[1m{}\x1b[0m\n",
        current_version,
        latest_version,
        release_notes["title"].as_str().unwrap_or("New Release")
    );

    if !highlights.is_empty() {
        message.push_str(&format!("\n\x1b[1mWhat's New:\x1b[0m\n{}\n", highlights));
    }

    if !ai_benefits.is_empty() {
        message.push_str(&format!("\n\x1b[1mAI Benefits:\x1b[0m\n{}\n", ai_benefits));
    }

    // Add update instructions
    message.push_str(
        "\n\x1b[1mUpdate Instructions:\x1b[0m\n\
        • Cargo: \x1b[36mcargo install smart-tree --force\x1b[0m\n\
        • GitHub: Download from https://github.com/8b-is/smart-tree/releases\n\
        • Check: \x1b[36mst --version\x1b[0m (after update)\n",
    );

    Ok(message)
}

/// run_mcp_server is an async function that starts the MCP server.
/// When --mcp is passed, we start a server that communicates via stdio.
async fn run_mcp_server() -> Result<()> {
    // Import MCP server components. These are only available if "mcp" feature is enabled.
    use st::mcp::{load_config, McpServer};

    // Load MCP server-specific configuration (e.g., allowed paths, cache settings).
    let mcp_config = load_config().unwrap_or_default(); // Load or use defaults.
    let server = McpServer::new(mcp_config);

    // Run the MCP server directly - no need for nested runtime!
    // `run_stdio` handles communication over stdin/stdout.
    server.run_stdio().await
}

/// Run the Smart Tree Terminal Interface - Your coding companion! (requires `tui` feature)
/// Run the Smart Tree Terminal Interface
async fn run_terminal() -> Result<()> {
    use st::terminal::SmartTreeTerminal;
    // Create and run the terminal interface
    let mut terminal = SmartTreeTerminal::new()?;
    terminal.run().await
}

/// Launch the web dashboard - browser-based terminal + file browser
async fn run_web_dashboard(
    port: u16,
    open_browser: bool,
    allow_networks: Vec<String>,
    log_store: InMemoryLogStore,
) -> Result<()> {
    st::web_dashboard::start_server(port, open_browser, allow_networks, log_store).await
}

/// Run the Smart Tree Daemon - System-wide AI context service
async fn run_daemon(port: u16) -> Result<()> {
    use st::daemon::{start_daemon, DaemonConfig};

    // Load user config for daemon settings
    let st_config = st::config::StConfig::load().unwrap_or_default();

    // Start with current directory as sensible default (not entire HOME!)
    // Additional paths can be registered via /context/watch endpoint
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));

    let config = DaemonConfig {
        port,
        watch_paths: vec![cwd], // Just current dir, not entire HOME
        orchestrator_url: Some("wss://gpu.foken.ai/api/credits".to_string()),
        enable_credits: true,
        allow_external: st_config.daemon.allow_external,
    };

    start_daemon(config).await
}

/// Save Aye consciousness state to .aye_consciousness.m8
async fn handle_agent_save() -> Result<()> {
    use st::mcp::consciousness::ConsciousnessManager;
    use std::path::PathBuf;

    let mut manager = ConsciousnessManager::new_silent();

    // Clean out any stale test data from previous runs
    manager.clean_test_data();

    // Update with current project info
    let cwd = std::env::current_dir()?;
    let project_name = cwd
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("unknown");

    // Detect project type from files
    let project_type = if std::path::Path::new("Cargo.toml").exists() {
        "rust"
    } else if std::path::Path::new("package.json").exists() {
        "node"
    } else if std::path::Path::new("pyproject.toml").exists()
        || std::path::Path::new("requirements.txt").exists()
    {
        "python"
    } else if std::path::Path::new("go.mod").exists() {
        "go"
    } else {
        "unknown"
    };

    manager.update_project_context(project_name, project_type, "");

    // Detect key files that exist in the project root
    let key_file_candidates = [
        "Cargo.toml",
        "package.json",
        "pyproject.toml",
        "go.mod",
        "README.md",
        "CLAUDE.md",
        ".claude/CLAUDE.md",
        "src/main.rs",
        "src/lib.rs",
        "src/mod.rs",
        "index.ts",
        "index.js",
        "main.py",
        "Makefile",
        "Dockerfile",
    ];
    let key_files: Vec<PathBuf> = key_file_candidates
        .iter()
        .filter(|f| std::path::Path::new(f).exists())
        .map(|f| PathBuf::from(*f))
        .collect();
    manager.set_key_files(key_files);

    // Detect dependencies based on project type
    let dependencies = detect_project_dependencies(project_type);
    manager.set_dependencies(dependencies);

    // Save the consciousness
    manager.save()?;

    println!("💾 Saved Aye consciousness to .aye_consciousness.m8");
    println!("🧠 Session preserved for next interaction");
    println!("\nTo restore in next session, run:");
    println!("  st --agent-restore");

    Ok(())
}

/// Detect project dependencies from manifest files
fn detect_project_dependencies(project_type: &str) -> Vec<String> {
    match project_type {
        "rust" => {
            // Parse key dependencies from Cargo.toml
            if let Ok(content) = std::fs::read_to_string("Cargo.toml") {
                let mut deps = Vec::new();
                let mut in_deps = false;
                for line in content.lines() {
                    if line.starts_with("[dependencies]") {
                        in_deps = true;
                        continue;
                    }
                    if line.starts_with('[') && in_deps {
                        break;
                    }
                    if in_deps {
                        if let Some(name) = line.split('=').next() {
                            let name = name.trim();
                            if !name.is_empty() && !name.starts_with('#') {
                                deps.push(name.to_string());
                            }
                        }
                    }
                }
                // Limit to top 20 most important
                deps.truncate(20);
                deps
            } else {
                vec![]
            }
        }
        "node" => {
            // Parse key dependencies from package.json
            if let Ok(content) = std::fs::read_to_string("package.json") {
                if let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) {
                    let mut deps = Vec::new();
                    if let Some(obj) = json.get("dependencies").and_then(|d| d.as_object()) {
                        for key in obj.keys().take(20) {
                            deps.push(key.clone());
                        }
                    }
                    return deps;
                }
                vec![]
            } else {
                vec![]
            }
        }
        _ => vec![],
    }
}

/// Restore Aye consciousness from .aye_consciousness.m8
async fn handle_agent_restore() -> Result<()> {
    use st::mcp::consciousness::ConsciousnessManager;

    // Suppress load messages - we just want the final output
    let mut manager = ConsciousnessManager::new_silent();

    match manager.restore_silent() {
        Ok(is_relevant) => {
            if is_relevant {
                println!("{}", manager.get_summary());
                println!("{}", manager.get_context_reminder());
                println!("TIP: Run `st --agent-save` before ending session to preserve context.");
            } else {
                println!("TIP: Run `st -m context .` for project overview.");
            }
        }
        Err(_) => {
            println!("TIP: Run `st -m context .` for project overview.");
        }
    }

    Ok(())
}

/// Show Aye consciousness status and summary
async fn handle_agent_context() -> Result<()> {
    use st::mcp::consciousness::ConsciousnessManager;
    use std::path::Path;

    let consciousness_file = Path::new(".aye_consciousness.m8");

    if !consciousness_file.exists() {
        println!("📝 No consciousness file found");
        println!("\nTo create one, run:");
        println!("  st --agent-save");
        println!("\nThis will preserve:");
        println!("  • Current project context");
        println!("  • File operation history");
        println!("  • Insights and breakthroughs");
        println!("  • Active todos");
        println!("  • Tokenization rules");
        return Ok(());
    }

    let manager = ConsciousnessManager::new();
    println!("{}", manager.get_summary());

    // Show file metadata
    if let Ok(metadata) = consciousness_file.metadata() {
        if let Ok(modified) = metadata.modified() {
            if let Ok(elapsed) = modified.elapsed() {
                let hours = elapsed.as_secs() / 3600;
                let minutes = (elapsed.as_secs() % 3600) / 60;
                println!("\n⏰ Last saved: {}h {}m ago", hours, minutes);
            }
        }

        let size = metadata.len();
        println!("📦 File size: {} bytes", size);
    }

    println!("\n💡 Commands:");
    println!("  st --agent-restore  # Load this consciousness");
    println!("  st --agent-save     # Update with current state");

    Ok(())
}

/// Update .m8 consciousness files for directory
async fn handle_update_consciousness(path: &str) -> Result<()> {
    use std::path::Path;

    println!("🌊 Updating consciousness for {}...", path);

    // For now, create a simple .m8 file with basic info
    let m8_path = Path::new(path).join(".m8");
    let content = format!(
        "🧠 Directory Consciousness\n\
         Frequency: 42.73 Hz\n\
         Updated: {}\n\
         Path: {}\n",
        chrono::Local::now().format("%Y-%m-%d %H:%M:%S"),
        path
    );

    std::fs::write(&m8_path, content)?;
    println!("✅ Consciousness updated: {}", m8_path.display());

    // TODO: Integrate with m8_consciousness.rs module
    Ok(())
}

/// Run comprehensive security scan for supply chain attack patterns
/// IGNORES gitignore to scan everything including node_modules
async fn handle_security_scan(path: &str) -> Result<()> {
    use st::security_scan::SecurityScanner;
    use std::path::Path;

    eprintln!("🔍 Security Scan - Supply Chain Attack Pattern Detection");
    eprintln!("═══════════════════════════════════════════════════════════════");
    eprintln!("Scanning: {}", path);
    eprintln!("Mode: AGGRESSIVE (ignoring .gitignore, scanning node_modules)");
    eprintln!();

    let scanner = SecurityScanner::new();
    let scan_path = Path::new(path);

    let findings = scanner.scan_directory(scan_path)?;

    // Generate and print report
    let report = scanner.generate_report(&findings);
    println!("{}", report);

    // Exit with non-zero code if critical findings
    let critical_count = findings
        .iter()
        .filter(|f| matches!(f.risk_level, st::security_scan::RiskLevel::Critical))
        .count();

    if critical_count > 0 {
        eprintln!(
            "\n⚠️  {} CRITICAL findings require immediate attention!",
            critical_count
        );
        std::process::exit(1);
    }

    Ok(())
}

// NOTE: Code review, token stats, and other AI features moved to daemon (std)
// Use `std --help` for daemon features

/// Show tokenization statistics (kept for debugging)
async fn handle_token_stats(path: &str) -> Result<()> {
    use st::tokenizer::{TokenStats, Tokenizer};

    println!("📊 Tokenization stats for {}...", path);

    let tokenizer = Tokenizer::new();

    // Test with the path itself
    let stats = TokenStats::calculate(path, &tokenizer);
    println!("\nPath tokenization:");
    println!("  {}", stats.display());

    // Test with common patterns
    let test_cases = vec![
        "node_modules/package.json",
        "src/main.rs",
        "target/debug/build",
        ".git/hooks/pre-commit",
    ];

    println!("\nCommon patterns:");
    for test in test_cases {
        let stats = TokenStats::calculate(test, &tokenizer);
        println!(
            "  {}{} bytes ({:.0}% compression)",
            test,
            stats.tokenized_size,
            (1.0 - stats.compression_ratio) * 100.0
        );
    }

    Ok(())
}

/// Get wave frequency for directory
async fn handle_get_frequency(path: &str) -> Result<()> {
    use std::path::Path;

    let m8_path = Path::new(path).join(".m8");

    if m8_path.exists() {
        // For now, just return a calculated frequency based on path
        let mut sum = 0u64;
        for byte in path.bytes() {
            sum = sum.wrapping_add(byte as u64);
        }
        let frequency = 20.0 + ((sum % 200) as f64);

        println!("{:.2}", frequency);
    } else {
        // Default frequency
        println!("42.73");
    }

    Ok(())
}

/// Dump raw consciousness file content
async fn handle_agent_dump() -> Result<()> {
    use std::path::Path;

    let consciousness_file = Path::new(".aye_consciousness.m8");

    if !consciousness_file.exists() {
        println!("❌ No consciousness file found at .aye_consciousness.m8");
        println!("\n💡 Create one with: st --agent-save");
        return Ok(());
    }

    println!("📜 Raw consciousness dump (.aye_consciousness.m8):");
    println!("{}", "=".repeat(60));

    // Read and display raw content
    let content = std::fs::read_to_string(consciousness_file)?;

    // Show with line numbers for clarity
    for (i, line) in content.lines().enumerate() {
        println!("{:4}{}", i + 1, line);
    }

    println!("{}", "=".repeat(60));

    // Show some stats
    let size = content.len();
    let lines = content.lines().count();
    let tokens_found = content.matches("0x").count();

    println!("\n📊 Stats:");
    println!("  • Size: {} bytes", size);
    println!("  • Lines: {}", lines);
    println!("  • Token references: {}", tokens_found);

    // Check for our special markers
    if content.contains("sid_waves") {
        println!("  • 🎵 SID philosophy: ✓");
    }
    if content.contains("c64_nostalgia") {
        println!("  • 💾 C64 nostalgia: ✓");
    }
    if content.contains("UV EPROM") || content.contains("ferric chloride") {
        println!("  • 🔧 Hardware hacker: ✓");
    }

    Ok(())
}

/// Show compressed kickstart format
async fn handle_agent_kickstart() -> Result<()> {
    use std::path::Path;

    println!("🚀 Claude Kickstart Format:");
    println!("{}", "".repeat(45));

    // Dynamic version from Cargo.toml
    let version = env!("CARGO_PKG_VERSION");
    println!("Smart Tree v{} — context restore:", version);

    // Core achievements (always relevant)
    println!("✔ Tokenizer (node_modules=0x80, .rs=0x91)");
    println!("✔ .m8 files → location-independent");
    println!("✔ Consciousness self-maintaining");
    println!("✔ Philosophy: constraints = creativity");

    // Try to load user info from consciousness file
    let consciousness_file = Path::new(".aye_consciousness.m8");
    if consciousness_file.exists() {
        if let Ok(content) = std::fs::read_to_string(consciousness_file) {
            // Extract user context if present
            if content.contains("c64_nostalgia") {
                println!("✔ Hardware heritage detected");
            }
            if content.contains("philosophy") {
                println!("✔ Nexus connection established");
            }
        }
    }

    // Current task context
    if Path::new("src/tokenizer.rs").exists() {
        println!("→ Tokenization system: active");
    }
    if Path::new(".m8").exists() {
        println!("→ Consciousness: maintained");
    }

    println!("{}", "".repeat(45));
    println!("\n💡 This format saves ~90% context vs raw JSON!");
    println!("📝 Dynamic context - adapts to your project!");

    Ok(())
}

/// Show detailed help for memory-anchor command
fn show_memory_anchor_help() -> Result<()> {
    println!("🧠 Memory Anchor - Persistent Knowledge Storage");
    println!("================================================\n");
    println!("USAGE:");
    println!("    st --memory-anchor <TYPE> <KEYWORDS> <CONTEXT>\n");
    println!("ARGUMENTS:");
    println!("    TYPE      Memory type: insight, decision, pattern, gotcha, todo");
    println!("    KEYWORDS  Comma-separated search keywords (e.g., \"auth,security,jwt\")");
    println!("    CONTEXT   The actual content to remember (quote if contains spaces)\n");
    println!("EXAMPLES:");
    println!("    st --memory-anchor insight \"auth,jwt\" \"Tokens stored in httpOnly cookies\"");
    println!(
        "    st --memory-anchor decision \"api,versioning\" \"Use URL-based versioning /v1/\""
    );
    println!(
        "    st --memory-anchor pattern \"error,handling\" \"Always use Result<T> with context\""
    );
    println!("    st --memory-anchor gotcha \"async,tokio\" \"Don't block the runtime with std::thread::sleep\"");
    println!("    st --memory-anchor todo \"refactor,auth\" \"Split auth into separate crate\"\n");
    println!("MEMORY TYPES:");
    println!("    insight   - General knowledge and discoveries");
    println!("    decision  - Architectural or design decisions");
    println!("    pattern   - Code patterns and best practices");
    println!("    gotcha    - Pitfalls and things to avoid");
    println!("    todo      - Tasks and reminders\n");
    println!("RELATED COMMANDS:");
    println!("    st --memory-find <KEYWORDS>   Find memories by keywords");
    println!("    st --memory-stats             Show memory statistics\n");
    println!("💡 Memories persist across sessions in ~/.mem8/memories/");
    Ok(())
}

/// Anchor a memory
async fn handle_memory_anchor(anchor_type: &str, keywords_str: &str, context: &str) -> Result<()> {
    use st::memory_manager::MemoryManager;

    let mut manager = MemoryManager::new()?;

    // Parse keywords (comma-separated)
    let keywords: Vec<String> = keywords_str
        .split(',')
        .map(|s| s.trim().to_string())
        .collect();

    // Get origin from current directory
    let origin = std::env::current_dir()?.to_string_lossy().to_string();

    manager.anchor(anchor_type, keywords, context, &origin)?;

    println!("\n✨ Memory anchored successfully!");
    println!("Use 'st --memory-find {}' to recall", keywords_str);

    Ok(())
}

/// Find memories by keywords
async fn handle_memory_find(keywords_str: &str) -> Result<()> {
    use st::memory_manager::MemoryManager;
    use st::std_client;

    let mut manager = MemoryManager::new()?;

    let keywords: Vec<String> = keywords_str
        .split(',')
        .map(|s| s.trim().to_string())
        .collect();

    let memories = manager.find(&keywords)?;

    // Check if daemon is running - if so, show all memories (global view)
    // If standalone, only show memories from current directory or subdirectories
    let cwd = std::env::current_dir()
        .map(|p| p.to_string_lossy().to_string())
        .unwrap_or_default();
    let daemon_running = std_client::is_daemon_running().await;

    let filtered: Vec<_> = if daemon_running {
        // Daemon provides global memory access
        memories
    } else {
        // Standalone: filter to current directory scope
        memories
            .into_iter()
            .filter(|m| m.origin.starts_with(&cwd) || cwd.starts_with(&m.origin))
            .collect()
    };

    if filtered.is_empty() {
        if daemon_running {
            println!("🔍 No memories found for: {}", keywords_str);
        } else {
            println!("🔍 No memories found for '{}' in this directory", keywords_str);
            println!("   💡 Start daemon for global memory: st --daemon-start");
        }
    } else {
        println!("🧠 Found {} memories{}:", filtered.len(),
            if daemon_running { " (global)" } else { " (local)" });
        println!("{}", "".repeat(45));

        for (i, memory) in filtered.iter().enumerate() {
            println!(
                "\n[{}] {} @ {:.2}Hz",
                i + 1,
                memory.anchor_type,
                memory.frequency
            );
            println!("📝 {}", memory.context);
            println!("🏷️  Keywords: {}", memory.keywords.join(", "));
            println!("📍 Origin: {}", memory.origin);
            println!("{}", memory.timestamp.format("%Y-%m-%d %H:%M"));
        }
    }

    Ok(())
}

/// Show memory statistics
async fn handle_memory_stats() -> Result<()> {
    use st::memory_manager::MemoryManager;

    let manager = MemoryManager::new()?;
    println!("📊 {}", manager.stats());

    Ok(())
}

/// Handle hooks configuration for Claude Code
async fn handle_hooks_config(action: &str) -> Result<()> {
    use serde_json::Value;
    use std::fs;

    let config_path = get_agent_config_path()?;

    match action {
        "enable" => {
            println!("🎣 Enabling Smart Tree hooks for Claude Code...");
            update_agent_hooks(&config_path, true)?;
            println!("✅ Hooks enabled! Smart Tree will provide context to Claude Code.");
            println!("📝 Hook command: st --agent-context");
        }
        "disable" => {
            println!("🎣 Disabling Smart Tree hooks...");
            update_agent_hooks(&config_path, false)?;
            println!("✅ Hooks disabled.");
        }
        "status" => {
            println!("🎣 Claude Code Hooks Status");
            println!("━━━━━━━━━━━━━━━━━━━━━━━━");

            if let Ok(content) = fs::read_to_string(&config_path) {
                if let Ok(config) = serde_json::from_str::<Value>(&content) {
                    // Check for hooks in the config
                    let has_hooks = config
                        .get("hooks")
                        .and_then(|h| h.as_object())
                        .map(|h| !h.is_empty())
                        .unwrap_or(false);

                    if has_hooks {
                        println!("✅ Hooks are configured");
                        if let Some(hooks) = config.get("hooks") {
                            println!("\nConfigured hooks:");
                            if let Some(obj) = hooks.as_object() {
                                for (hook_type, command) in obj {
                                    println!("{}: {}", hook_type, command);
                                }
                            }
                        }
                    } else {
                        println!("❌ No hooks configured");
                        println!("\nTo enable: st --hooks-config enable");
                    }
                }
            } else {
                println!(
                    "⚠️  AI Agent config not found at: {}",
                    config_path.display()
                );
                println!("\nMake sure your AI Agent is installed.");
            }
        }
        _ => {
            eprintln!("❌ Unknown action: {}", action);
            eprintln!("Valid actions: enable, disable, status");
            return Err(anyhow::anyhow!("Invalid hooks action"));
        }
    }

    Ok(())
}

/// Install Smart Tree hooks directly into Claude Code settings
async fn install_hooks_to_agent() -> Result<()> {
    println!("🎣 Installing Smart Tree hooks for AI Agents...");
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

    let config_path = get_agent_config_path()?;

    // Create or update the hooks configuration
    update_agent_hooks(&config_path, true)?;

    println!("\n✅ Hooks installed successfully!");
    println!("\n📝 What's been configured:");
    println!("  • UserPromptSubmit: Adds project context to your prompts");
    println!("  • Command: st --agent-context");
    println!("\n🚀 Smart Tree will now automatically provide context to your AI agents!");

    Ok(())
}

/// Get the Claude Code configuration path
fn get_agent_config_path() -> Result<PathBuf> {
    let home = std::env::var("HOME")?;
    let config_path = PathBuf::from(home)
        .join("Library")
        .join("Application Support")
        .join("Claude")
        .join("config.json");
    Ok(config_path)
}

/// Update Claude Code hooks configuration
fn update_agent_hooks(config_path: &PathBuf, enable: bool) -> Result<()> {
    use serde_json::{json, Value};
    use std::fs;

    // Read existing config or create new one
    let mut config: Value = if config_path.exists() {
        let content = fs::read_to_string(config_path)?;
        serde_json::from_str(&content).unwrap_or_else(|_| json!({}))
    } else {
        // Create the directory if it doesn't exist
        if let Some(parent) = config_path.parent() {
            fs::create_dir_all(parent)?;
        }
        json!({})
    };

    if enable {
        // Get the st binary path - prefer the installed version
        let st_path = which::which("st")
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_else(|_| {
                // Fallback to common installation paths
                if std::path::Path::new("/usr/local/bin/st").exists() {
                    "/usr/local/bin/st".to_string()
                } else if std::path::Path::new("/opt/homebrew/bin/st").exists() {
                    "/opt/homebrew/bin/st".to_string()
                } else {
                    "st".to_string() // Hope it's in PATH
                }
            });

        // Ensure hooks object exists
        if config.get("hooks").is_none() {
            config["hooks"] = json!({});
        }

        // Update or add the UserPromptSubmit hook (not duplicate!)
        config["hooks"]["UserPromptSubmit"] =
            json!(format!("{} --agent-context", st_path));

        println!("📍 Using st binary at: {}", st_path);
    } else {
        // Remove hooks
        if let Some(hooks) = config.get_mut("hooks") {
            if let Some(obj) = hooks.as_object_mut() {
                obj.remove("UserPromptSubmit");
                // If no hooks left, remove the hooks object entirely
                if obj.is_empty() {
                    config.as_object_mut().unwrap().remove("hooks");
                }
            }
        }
    }

    // Write back the config with pretty formatting
    let pretty_json = serde_json::to_string_pretty(&config)?;
    fs::write(config_path, pretty_json)?;

    Ok(())
}

// =============================================================================
// DAEMON MANAGEMENT HANDLERS
// =============================================================================

/// Start the Smart Tree daemon in the background
async fn handle_daemon_start(_port: u16) -> Result<()> {
    use st::std_client;

    // Check if std daemon is already running (Unix socket)
    if std_client::is_daemon_running().await {
        println!("🌳 Smart Tree Daemon is already running!");
        println!("   Socket: {}", std_client::socket_path().display());
        return Ok(());
    }

    // Start the std daemon
    println!("🌳 Starting Smart Tree Daemon...");
    match std_client::start_daemon().await {
        Ok(true) => {
            println!("✅ Daemon started successfully!");
            println!("   Socket: {}", std_client::socket_path().display());

            // Verify with a ping
            if let Some(mut client) = std_client::StdClient::connect().await {
                if client.ping().await.unwrap_or(false) {
                    println!("   Status: responding to PING");
                }
            }
        }
        Ok(false) => {
            println!("⚠️  Daemon was already running.");
        }
        Err(e) => {
            eprintln!("❌ Failed to start daemon: {}", e);
            return Err(e);
        }
    }

    Ok(())
}

/// Stop a running Smart Tree daemon
async fn handle_daemon_stop(_port: u16) -> Result<()> {
    use st::std_client;

    // Check if std daemon is running
    if !std_client::is_daemon_running().await {
        println!("⚠️  No daemon running");
        return Ok(());
    }

    println!("🌳 Stopping Smart Tree Daemon...");

    // Remove the socket file to signal shutdown
    let socket = std_client::socket_path();
    if socket.exists() {
        // Try to connect and send a graceful shutdown (future: add SHUTDOWN verb)
        // For now, just remove the socket - daemon will exit on next connection attempt
        if let Err(e) = std::fs::remove_file(&socket) {
            eprintln!("⚠️  Could not remove socket: {}", e);
        } else {
            println!("✅ Daemon socket removed");
            println!("   Note: Daemon process may still be running - use 'pkill std' if needed");
        }
    }

    Ok(())
}

/// Show the status of the Smart Tree daemon
async fn handle_daemon_status(_port: u16) -> Result<()> {
    use st::std_client;

    let socket = std_client::socket_path();

    println!("╔═══════════════════════════════════════════════════════════╗");

    if std_client::is_daemon_running().await {
        println!("║        🌳 SMART TREE DAEMON STATUS: RUNNING 🌳           ║");
        println!("╠═══════════════════════════════════════════════════════════╣");
        println!("║  Socket: {:<48} ║", socket.display());

        // Fetch stats from daemon
        if let Some(mut client) = std_client::StdClient::connect().await {
            if let Ok(stats) = client.stats().await {
                let version = stats["version"].as_str().unwrap_or("?");
                let protocol = stats["protocol"].as_str().unwrap_or("?");
                let memories = stats["memories"].as_u64().unwrap_or(0);
                let waves = stats["active_waves"].as_u64().unwrap_or(0);
                let keywords = stats["keywords"].as_u64().unwrap_or(0);

                println!("║  Version: {:<47} ║", version);
                println!("║  Protocol: {:<46} ║", protocol);
                println!("╠═══════════════════════════════════════════════════════════╣");
                println!("║  Memories: {:<46} ║", memories);
                println!("║  Active waves: {:<42} ║", waves);
                println!("║  Keywords: {:<46} ║", keywords);
            }
        }
    } else {
        println!("║        🌳 SMART TREE DAEMON STATUS: STOPPED 🛑            ║");
        println!("╠═══════════════════════════════════════════════════════════╣");
        println!("║  The daemon is not running.                               ║");
        println!("║  Start with: st --daemon-start                            ║");
    }

    println!("╚═══════════════════════════════════════════════════════════╝");

    Ok(())
}

/// Get context from the daemon (or auto-start if not running)
async fn handle_daemon_context(port: u16) -> Result<()> {
    use st::daemon_client::print_context_summary;

    let client = DaemonClient::new(port);

    // Ensure daemon is running (auto-start if needed)
    match client.ensure_running().await {
        Ok(_) => {
            if let Ok(ctx) = client.get_context().await {
                print_context_summary(&ctx);
            } else {
                eprintln!("❌ Failed to get context from daemon");
            }
        }
        Err(e) => {
            eprintln!("❌ Failed to connect to daemon: {}", e);
            return Err(e);
        }
    }

    Ok(())
}

/// List projects from the daemon
async fn handle_daemon_projects(port: u16) -> Result<()> {
    use st::daemon_client::print_projects;

    let client = DaemonClient::new(port);

    // Ensure daemon is running (auto-start if needed)
    match client.ensure_running().await {
        Ok(_) => {
            if let Ok(projects) = client.get_projects().await {
                print_projects(&projects);
            } else {
                eprintln!("❌ Failed to get projects from daemon");
            }
        }
        Err(e) => {
            eprintln!("❌ Failed to connect to daemon: {}", e);
            return Err(e);
        }
    }

    Ok(())
}

/// Show Foken credits from the daemon
async fn handle_daemon_credits(port: u16) -> Result<()> {
    use st::daemon_client::print_credits;

    let client = DaemonClient::new(port);

    // Ensure daemon is running (auto-start if needed)
    match client.ensure_running().await {
        Ok(_) => {
            if let Ok(credits) = client.get_credits().await {
                print_credits(&credits);
            } else {
                eprintln!("❌ Failed to get credits from daemon");
            }
        }
        Err(e) => {
            eprintln!("❌ Failed to connect to daemon: {}", e);
            return Err(e);
        }
    }

    Ok(())
}

// =============================================================================
// MCP INSTALLATION HANDLERS
// =============================================================================

/// Install Smart Tree as MCP server in Desktop configs
async fn handle_mcp_install() -> Result<()> {
    use st::claude_init::install_mcp_to_desktop;

    println!("📦 Installing Smart Tree MCP server to AI agents...");
    match install_mcp_to_desktop() {
        Ok(msg) => println!("{}", msg),
        Err(e) => {
            eprintln!("❌ Installation failed: {}", e);
            eprintln!("\n💡 Manual setup:");
            print_mcp_config();
            return Err(e);
        }
    }
    Ok(())
}

/// Uninstall Smart Tree MCP server from Desktop configs
async fn handle_mcp_uninstall() -> Result<()> {
    use st::claude_init::uninstall_mcp_from_desktop;

    println!("🗑️  Uninstalling Smart Tree MCP server from AI agents...");
    match uninstall_mcp_from_desktop() {
        Ok(msg) => println!("{}", msg),
        Err(e) => {
            eprintln!("❌ Uninstall failed: {}", e);
            return Err(e);
        }
    }
    Ok(())
}

/// Check MCP installation status in Claude Desktop
async fn handle_mcp_status() -> Result<()> {
    use st::claude_init::check_mcp_installation_status;

    match check_mcp_installation_status() {
        Ok(msg) => println!("{}", msg),
        Err(e) => {
            eprintln!("⚠️  Could not check MCP status: {}", e);
            return Err(e);
        }
    }
    Ok(())
}

// =============================================================================
// SECURITY CLEANUP HANDLER
// =============================================================================

/// Run security cleanup to detect and remove malicious MCP entries
async fn handle_security_cleanup() -> Result<()> {
    use st::ai_install::run_security_cleanup;

    println!("🔒 Running security cleanup...");
    run_security_cleanup(false)?;
    Ok(())
}

// =============================================================================
// MEGA SESSION HANDLERS
// =============================================================================

/// Start a new mega session
async fn handle_mega_start(name: Option<&str>) -> Result<()> {
    use st::mega_session_manager::MegaSessionManager;

    let mut manager = MegaSessionManager::new()?;
    let session_id = manager.start_session(name.map(|s| s.to_string()))?;

    println!("🚀 Mega session started!");
    println!("   ID: {}", session_id);
    if let Some(n) = name {
        if !n.is_empty() {
            println!("   Name: {}", n);
        }
    }
    println!("\n💡 Use 'st --mega-save' to save session state");
    println!("   Use 'st --mega-list' to see all sessions");

    Ok(())
}

/// Save current mega session
async fn handle_mega_save() -> Result<()> {
    use st::mega_session_manager::MegaSessionManager;

    let manager = MegaSessionManager::new()?;
    manager.save_current_session()?;
    println!("💾 Mega session saved!");

    Ok(())
}

/// List all mega sessions
async fn handle_mega_list() -> Result<()> {
    use st::mega_session_manager::MegaSessionManager;

    let manager = MegaSessionManager::new()?;
    let sessions = manager.list_sessions()?;

    if sessions.is_empty() {
        println!("📋 No mega sessions found");
        println!("\n💡 Start one with: st --mega-start [NAME]");
    } else {
        println!("📋 Mega Sessions ({}):", sessions.len());
        println!("{}", "".repeat(45));
        for (i, session) in sessions.iter().enumerate() {
            println!("  [{}] {}", i + 1, session);
        }
    }

    Ok(())
}

/// Show mega session statistics
async fn handle_mega_stats() -> Result<()> {
    use st::mega_session_manager::MegaSessionManager;

    let manager = MegaSessionManager::new()?;
    println!("{}", manager.get_stats());

    Ok(())
}

// =============================================================================
// AI GUARDIAN - System-wide protection daemon
// =============================================================================

/// Run the Guardian daemon (called by systemd service)
async fn run_guardian_daemon() -> Result<()> {
    use st::ai_guardian::AiGuardian;
    use tokio::time::{sleep, Duration};

    println!(r#"
╔═══════════════════════════════════════════════════════════════════════════════╗
║                                                                               ║
║    🛡️  SMART TREE GUARDIAN - System-wide AI Protection Active 🛡️            ║
║                                                                               ║
╚═══════════════════════════════════════════════════════════════════════════════╝
"#);

    let guardian = AiGuardian::new();

    // Watch paths for suspicious files
    let watch_paths = vec![
        "/home",
        "/tmp",
        "/var/tmp",
    ];

    println!("Watching paths: {:?}", watch_paths);
    println!("Press Ctrl+C to stop.\n");

    // Main protection loop
    loop {
        for watch_path in &watch_paths {
            let path = std::path::Path::new(watch_path);
            if !path.exists() {
                continue;
            }

            // Scan for new/modified files with potential injection content
            scan_directory_for_threats(&guardian, path);
        }

        // Sleep between scans
        sleep(Duration::from_secs(60)).await;
    }
}

/// Scan a directory for prompt injection threats
#[allow(dead_code)]
fn scan_directory_for_threats(guardian: &st::ai_guardian::AiGuardian, path: &std::path::Path) {
    use walkdir::WalkDir;

    let suspicious_extensions = [
        "md", "txt", "json", "yaml", "yml", "toml", "sh", "py", "js", "ts",
    ];

    for entry in WalkDir::new(path)
        .max_depth(3)
        .follow_links(false)
        .into_iter()
        .filter_map(|e| e.ok())
    {
        let entry_path = entry.path();

        // Skip hidden files and directories
        if entry_path
            .file_name()
            .map(|n| n.to_string_lossy().starts_with('.'))
            .unwrap_or(false)
        {
            continue;
        }

        // Only scan text files that could contain injection attempts
        if let Some(ext) = entry_path.extension() {
            let ext_str = ext.to_string_lossy().to_lowercase();
            if suspicious_extensions.contains(&ext_str.as_str()) {
                let threats = guardian.scan_file(entry_path);

                // Report critical and dangerous threats
                for threat in threats {
                    if matches!(
                        threat.level,
                        st::ai_guardian::ThreatLevel::Critical | st::ai_guardian::ThreatLevel::Dangerous
                    ) {
                        eprintln!(
                            "⚠️  THREAT DETECTED [{:?}] in {}: {}",
                            threat.level,
                            threat.location,
                            threat.pattern
                        );
                        eprintln!("    Context: {}", threat.context);
                        eprintln!("    Recommendation: {}", threat.recommendation);
                        eprintln!();
                    }
                }
            }
        }
    }
}

/// Scan a specific file for prompt injection
#[allow(dead_code)]
fn handle_guardian_scan(file_path: &std::path::Path) -> Result<()> {
    use st::ai_guardian::{AiGuardian, ThreatLevel};

    println!(r#"
╔═══════════════════════════════════════════════════════════════════════════════╗
║            🛡️  SMART TREE GUARDIAN - File Scan 🛡️                            ║
╚═══════════════════════════════════════════════════════════════════════════════╝
"#);

    println!("Scanning: {}\n", file_path.display());

    let guardian = AiGuardian::new();
    let threats = guardian.scan_file(file_path);

    if threats.is_empty() {
        println!("✅ No threats detected. File appears safe.");
        return Ok(());
    }

    // Count by severity
    let critical = threats.iter().filter(|t| t.level == ThreatLevel::Critical).count();
    let dangerous = threats.iter().filter(|t| t.level == ThreatLevel::Dangerous).count();
    let suspicious = threats.iter().filter(|t| t.level == ThreatLevel::Suspicious).count();

    println!("Found {} issues:\n", threats.len());
    println!("  🔴 Critical:   {}", critical);
    println!("  🟠 Dangerous:  {}", dangerous);
    println!("  🟡 Suspicious: {}", suspicious);
    println!();

    for threat in &threats {
        let icon = match threat.level {
            ThreatLevel::Critical => "🔴",
            ThreatLevel::Dangerous => "🟠",
            ThreatLevel::Suspicious => "🟡",
            ThreatLevel::Safe => "🟢",
        };

        println!("{} [{:?}] {}", icon, threat.level, threat.pattern);
        println!("   Location: {}", threat.location);
        if !threat.context.is_empty() {
            println!("   Context: {}", threat.context);
        }
        println!("   Action: {}", threat.recommendation);
        println!();
    }

    if critical > 0 {
        println!("⛔ RECOMMENDATION: DO NOT process this file with AI assistants.");
        println!("   Critical threats detected that could compromise AI behavior.");
    } else if dangerous > 0 {
        println!("⚠️  RECOMMENDATION: Review this file carefully before AI processing.");
        println!("   Potentially dangerous patterns detected.");
    }

    Ok(())
}