grapha 0.1.0

Blazingly fast code intelligence CLI and MCP server for Swift and Rust
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
mod assets;
mod changes;
mod classify;
mod compress;
mod config;
mod delta;
mod extract;
mod fields;
mod filter;
mod localization;
mod mcp;
mod progress;
mod query;
mod recall;
mod render;
mod rust_plugin;
mod search;
mod serve;
mod snippet;
mod store;
mod watch;

use std::path::{Path, PathBuf};
use std::time::Instant;

use anyhow::{Context, anyhow};
use clap::{Parser, Subcommand, ValueEnum};
use serde::Serialize;

use store::Store;

#[derive(Parser)]
#[command(
    name = "grapha",
    version,
    about = "Structural code graph for LLM consumption"
)]
struct Cli {
    /// ANSI color mode for tree output
    #[arg(long, global = true, value_enum, default_value_t = ColorMode::Auto)]
    color: ColorMode,
    #[command(subcommand)]
    command: Commands,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum ColorMode {
    Auto,
    Always,
    Never,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum QueryOutputFormat {
    Json,
    Tree,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum TraceDirection {
    Forward,
    Reverse,
}

#[derive(Subcommand)]
enum Commands {
    /// Analyze source files and output graph
    Analyze {
        /// File or directory to analyze
        path: PathBuf,
        /// Output file (default: stdout)
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Filter node kinds (comma-separated: fn,struct,enum,trait,impl,mod,field,variant)
        #[arg(long)]
        filter: Option<String>,
        /// Output in compact grouped format (optimized for LLM consumption)
        #[arg(long)]
        compact: bool,
    },
    /// Index a project into persistent storage
    Index {
        /// Project directory to index
        path: PathBuf,
        /// Storage format: "json" or "sqlite" (default: sqlite)
        #[arg(long, default_value = "sqlite")]
        format: String,
        /// Storage directory (default: .grapha/ in project root)
        #[arg(long)]
        store_dir: Option<PathBuf>,
        /// Force a full store/search rebuild instead of using incremental sync
        #[arg(long)]
        full_rebuild: bool,
        /// Show per-phase timing breakdown for performance profiling
        #[arg(long)]
        timing: bool,
    },
    /// Launch web UI for interactive graph exploration
    Serve {
        /// Project directory
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
        /// Port to listen on
        #[arg(long, default_value = "8080")]
        port: u16,
        /// Run as MCP server over stdio (instead of HTTP)
        #[arg(long)]
        mcp: bool,
        /// Watch for file changes and auto-update the graph
        #[arg(long)]
        watch: bool,
    },
    /// Query symbol relationships and search indexed symbols
    Symbol {
        #[command(subcommand)]
        command: SymbolCommands,
    },
    /// Inspect dataflow between symbols, entries, and effects
    Flow {
        #[command(subcommand)]
        command: FlowCommands,
    },
    /// Inspect localization references and usage sites
    #[command(name = "l10n")]
    L10n {
        #[command(subcommand)]
        command: L10nCommands,
    },
    /// Inspect image asset catalogs and usage sites
    Asset {
        #[command(subcommand)]
        command: AssetCommands,
    },
    /// Run repository-scoped analysis over the indexed graph
    Repo {
        #[command(subcommand)]
        command: RepoCommands,
    },
}

#[derive(Subcommand)]
enum SymbolCommands {
    /// Search symbols by name or file
    Search {
        /// Search query
        query: String,
        /// Max results
        #[arg(long, default_value = "20")]
        limit: usize,
        /// Project directory
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
        /// Filter by symbol kind (function, struct, enum, trait, etc.)
        #[arg(long)]
        kind: Option<String>,
        /// Filter by module name
        #[arg(long)]
        module: Option<String>,
        /// Filter by file path glob
        #[arg(long)]
        file: Option<String>,
        /// Filter by role (entry_point, terminal, internal)
        #[arg(long)]
        role: Option<String>,
        /// Enable fuzzy matching (tolerates typos)
        #[arg(long)]
        fuzzy: bool,
        /// Include source snippet and relationships in results
        #[arg(long)]
        context: bool,
        /// Fields to display (comma-separated: file,id,module,span,snippet,visibility,signature,role; or "all"/"none")
        #[arg(long)]
        fields: Option<String>,
    },
    /// Query symbol context (callers, callees, implementors)
    Context {
        /// Symbol name or ID
        symbol: String,
        /// Project directory (reads from .grapha/)
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
        /// Output format
        #[arg(long, value_enum, default_value_t = QueryOutputFormat::Json)]
        format: QueryOutputFormat,
        /// Fields to display (comma-separated: file,id,module,span,snippet,visibility,signature,role; or "all"/"none")
        #[arg(long)]
        fields: Option<String>,
    },
    /// Analyze blast radius of changing a symbol
    Impact {
        /// Symbol name or ID
        symbol: String,
        /// Maximum traversal depth
        #[arg(long, default_value = "3")]
        depth: usize,
        /// Project directory
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
        /// Output format
        #[arg(long, value_enum, default_value_t = QueryOutputFormat::Json)]
        format: QueryOutputFormat,
        /// Fields to display (comma-separated: file,id,module,span,snippet,visibility,signature,role; or "all"/"none")
        #[arg(long)]
        fields: Option<String>,
    },
    /// Analyze structural complexity of a type (properties, dependencies, invalidation surface)
    Complexity {
        /// Type name or ID to analyze
        symbol: String,
        /// Project directory
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
    },
    /// List all declarations in a file, ordered by source position
    File {
        /// File name or path suffix (e.g. "RoomPage.swift" or "src/main.rs")
        file: String,
        /// Project directory
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
    },
}

#[derive(Subcommand)]
enum FlowCommands {
    /// Trace dataflow forward to terminals or backward to entry points
    Trace {
        /// Symbol name or ID
        symbol: String,
        /// Trace direction
        #[arg(long, value_enum, default_value_t = TraceDirection::Forward)]
        direction: TraceDirection,
        /// Maximum traversal depth
        #[arg(long)]
        depth: Option<usize>,
        /// Project directory
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
        /// Output format
        #[arg(long, value_enum, default_value_t = QueryOutputFormat::Json)]
        format: QueryOutputFormat,
    },
    /// Derive a semantic effect graph from a symbol
    Graph {
        /// Symbol name or ID
        symbol: String,
        /// Maximum traversal depth
        #[arg(long, default_value = "10")]
        depth: usize,
        /// Project directory
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
        /// Output format
        #[arg(long, value_enum, default_value_t = QueryOutputFormat::Json)]
        format: QueryOutputFormat,
    },
    /// List auto-detected entry points
    Entries {
        /// Project directory
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
        /// Output format
        #[arg(long, value_enum, default_value_t = QueryOutputFormat::Json)]
        format: QueryOutputFormat,
    },
}

#[derive(Subcommand)]
enum L10nCommands {
    /// Resolve localization records reachable from a SwiftUI symbol subtree
    Symbol {
        /// Symbol name or ID
        symbol: String,
        /// Project directory
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
        /// Output format
        #[arg(long, value_enum, default_value_t = QueryOutputFormat::Json)]
        format: QueryOutputFormat,
    },
    /// Find SwiftUI usage sites for a localization key
    Usages {
        /// Localization key
        key: String,
        /// Optional table/catalog name
        #[arg(long)]
        table: Option<String>,
        /// Project directory
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
        /// Output format
        #[arg(long, value_enum, default_value_t = QueryOutputFormat::Json)]
        format: QueryOutputFormat,
    },
}

#[derive(Subcommand)]
enum AssetCommands {
    /// List image assets from indexed catalogs
    List {
        /// Only show assets with no references in source code
        #[arg(long)]
        unused: bool,
        /// Project directory
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
    },
    /// Find source code usage sites for an image asset
    Usages {
        /// Asset name (e.g., "icon_gift" or "Room/voiceWave")
        name: String,
        /// Project directory
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
        /// Output format
        #[arg(long, value_enum, default_value_t = QueryOutputFormat::Json)]
        format: QueryOutputFormat,
    },
}

#[derive(Subcommand)]
enum RepoCommands {
    /// Detect code changes and analyze their impact
    Changes {
        /// Scope: "unstaged", "staged", "all", or a git ref (e.g., "main")
        #[arg(default_value = "all")]
        scope: String,
        /// Project directory
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
    },
    /// Show file/symbol map for orientation in large projects
    Map {
        /// Filter by module name
        #[arg(long)]
        module: Option<String>,
        /// Project directory
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
    },
    /// Detect code smells across the graph (god types, deep nesting, wide invalidation, etc.)
    Smells {
        /// Filter to a specific module
        #[arg(long)]
        module: Option<String>,
        /// Project directory
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
    },
    /// Show per-module metrics (symbol counts, coupling, entry points)
    Modules {
        /// Project directory
        #[arg(short, long, default_value = ".")]
        path: PathBuf,
    },
}

fn builtin_registry() -> anyhow::Result<grapha_core::LanguageRegistry> {
    let mut registry = grapha_core::LanguageRegistry::new();
    rust_plugin::register_builtin(&mut registry)?;
    grapha_swift::register_builtin(&mut registry)?;
    Ok(registry)
}

/// Run the extraction pipeline on a path, returning a merged graph.
fn run_pipeline(
    path: &Path,
    verbose: bool,
    timing: bool,
) -> anyhow::Result<grapha_core::graph::Graph> {
    let t = Instant::now();
    let registry = builtin_registry()?;
    let project_context = grapha_core::project_context(path);

    let cfg = config::load_config(path);

    // Signal the Swift plugin to skip index store loading when disabled
    if !cfg.swift.index_store {
        // SAFETY: called before spawning threads; no concurrent readers yet.
        unsafe { std::env::set_var("GRAPHA_SKIP_INDEX_STORE", "1") };
    }

    // Run file discovery and plugin init concurrently
    let (files, _) = std::thread::scope(|scope| {
        let files_handle = scope.spawn(|| {
            grapha_core::pipeline::discover_files(path, &registry)
                .context("failed to discover files")
        });
        let plugin_handle =
            scope.spawn(|| grapha_core::prepare_plugins(&registry, &project_context));
        let files = files_handle.join().expect("discover thread panicked")?;
        plugin_handle.join().expect("plugin thread panicked")?;
        Ok::<_, anyhow::Error>((files, ()))
    })?;

    // Discover external repo files
    let mut external_files: Vec<PathBuf> = Vec::new();
    let mut external_repo_count = 0usize;
    for ext in &cfg.external {
        let ext_path = Path::new(&ext.path);
        if !ext_path.exists() {
            if verbose {
                eprintln!(
                    "  \x1b[33m!\x1b[0m external repo '{}' not found at {}, skipping",
                    ext.name, ext.path
                );
            }
            continue;
        }
        match grapha_core::pipeline::discover_files(ext_path, &registry) {
            Ok(ext_discovered) => {
                external_files.extend(ext_discovered);
                external_repo_count += 1;
            }
            Err(e) => {
                if verbose {
                    eprintln!(
                        "  \x1b[33m!\x1b[0m failed to discover files in '{}': {e}",
                        ext.name
                    );
                }
            }
        }
    }

    let external_file_count = external_files.len();
    let all_files: Vec<PathBuf> = files.into_iter().chain(external_files).collect();

    if verbose {
        let msg = if external_file_count > 0 {
            format!(
                "discovered {} files + {} external ({} repos)",
                all_files.len() - external_file_count,
                external_file_count,
                external_repo_count
            )
        } else {
            format!("discovered {} files", all_files.len())
        };
        progress::done(&msg, t);
        if let Some(store) = grapha_swift::index_store_path(&project_context.project_root) {
            progress::done(&format!("index store: {}", store.display()), t);
        }
    }

    let mut module_map = grapha_core::discover_modules(&registry, &project_context)?;
    for ext in &cfg.external {
        let ext_path = Path::new(&ext.path);
        if !ext_path.exists() {
            continue;
        }
        let ext_context = grapha_core::project_context(ext_path);
        if let Ok(ext_modules) = grapha_core::discover_modules(&registry, &ext_context) {
            module_map.merge(ext_modules);
        }
    }

    let t = Instant::now();
    let pb = if verbose && all_files.len() > 1 {
        Some(progress::bar(all_files.len() as u64, "extracting"))
    } else {
        None
    };

    use rayon::prelude::*;
    use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};

    let skipped = AtomicUsize::new(0);

    // Per-phase timing accumulators (nanoseconds, summed across all threads)
    let t_read_ns = AtomicU64::new(0);
    let t_extract_ns = AtomicU64::new(0);
    let t_snippet_ns = AtomicU64::new(0);

    let results: Vec<_> = all_files
        .par_iter()
        .filter_map(|file| {
            let t0 = Instant::now();
            let source = match std::fs::read(file) {
                Ok(s) => s,
                Err(_) => {
                    skipped.fetch_add(1, Ordering::Relaxed);
                    if let Some(ref pb) = pb {
                        pb.inc(1);
                    }
                    return None;
                }
            };
            t_read_ns.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed);

            let t1 = Instant::now();
            let file_context = grapha_core::file_context(&project_context, &module_map, file);
            let extraction_result =
                grapha_core::extract_with_registry(&registry, &source, &file_context);
            t_extract_ns.fetch_add(t1.elapsed().as_nanos() as u64, Ordering::Relaxed);

            if let Some(ref pb) = pb {
                pb.inc(1);
            }

            match extraction_result {
                Ok(mut result) => {
                    let t2 = Instant::now();
                    if result
                        .nodes
                        .iter()
                        .any(|n| snippet::should_extract_snippet(n.kind))
                    {
                        // Avoid allocation: try zero-copy first, fall back to lossy
                        let source_str: std::borrow::Cow<'_, str> =
                            match std::str::from_utf8(&source) {
                                Ok(s) => std::borrow::Cow::Borrowed(s),
                                Err(_) => String::from_utf8_lossy(&source),
                            };
                        let line_idx = snippet::LineIndex::new(&source_str);
                        for node in &mut result.nodes {
                            if snippet::should_extract_snippet(node.kind) {
                                node.snippet = line_idx.extract_snippet(&node.span, 600);
                            }
                        }
                    }
                    t_snippet_ns.fetch_add(t2.elapsed().as_nanos() as u64, Ordering::Relaxed);
                    Some(result)
                }
                Err(e) => {
                    skipped.fetch_add(1, Ordering::Relaxed);
                    if verbose && let Some(ref pb) = pb {
                        pb.suspend(|| {
                            eprintln!("  \x1b[33m!\x1b[0m skipping {}: {e}", file.display())
                        });
                    }
                    None
                }
            }
        })
        .collect();

    let skipped = skipped.load(Ordering::Relaxed);

    if let Some(pb) = pb {
        pb.finish_and_clear();
    }

    if timing {
        let read_ms = t_read_ns.load(Ordering::Relaxed) as f64 / 1_000_000.0;
        let extract_ms = t_extract_ns.load(Ordering::Relaxed) as f64 / 1_000_000.0;
        let snippet_ms = t_snippet_ns.load(Ordering::Relaxed) as f64 / 1_000_000.0;
        let is_ms = grapha_swift::TIMING_INDEXSTORE_NS.load(std::sync::atomic::Ordering::Relaxed)
            as f64
            / 1_000_000.0;
        let ts_parse_ms = grapha_swift::TIMING_TS_PARSE_NS
            .load(std::sync::atomic::Ordering::Relaxed) as f64
            / 1_000_000.0;
        let doc_ms = grapha_swift::TIMING_TS_DOC_NS.load(std::sync::atomic::Ordering::Relaxed)
            as f64
            / 1_000_000.0;
        let swiftui_ms = grapha_swift::TIMING_TS_SWIFTUI_NS
            .load(std::sync::atomic::Ordering::Relaxed) as f64
            / 1_000_000.0;
        let l10n_ms = grapha_swift::TIMING_TS_L10N_NS.load(std::sync::atomic::Ordering::Relaxed)
            as f64
            / 1_000_000.0;
        let asset_ms = grapha_swift::TIMING_TS_ASSET_NS.load(std::sync::atomic::Ordering::Relaxed)
            as f64
            / 1_000_000.0;
        let ss_ms = grapha_swift::TIMING_SWIFTSYNTAX_NS.load(std::sync::atomic::Ordering::Relaxed)
            as f64
            / 1_000_000.0;
        let ts_fb_ms = grapha_swift::TIMING_TS_FALLBACK_NS
            .load(std::sync::atomic::Ordering::Relaxed) as f64
            / 1_000_000.0;
        eprintln!(
            "    thread-summed: read {:.0}ms, extract {:.0}ms, snippet {:.0}ms",
            read_ms, extract_ms, snippet_ms
        );
        eprintln!(
            "    swift: indexstore {:.0}ms, ts-parse {:.0}ms, doc {:.0}ms, swiftui {:.0}ms, l10n {:.0}ms, asset {:.0}ms, swiftsyntax {:.0}ms, ts-fallback {:.0}ms",
            is_ms, ts_parse_ms, doc_ms, swiftui_ms, l10n_ms, asset_ms, ss_ms, ts_fb_ms
        );
    }
    if verbose {
        let msg = if skipped > 0 {
            format!("extracted {} files ({} skipped)", results.len(), skipped)
        } else {
            format!("extracted {} files", results.len())
        };
        progress::done(&msg, t);
    }

    let mut classifiers = registry.collect_classifiers();
    classifiers.insert(
        0,
        Box::new(classify::toml_rules::TomlRulesClassifier::new(
            &cfg.classifiers,
        )),
    );
    let composite = grapha_core::CompositeClassifier::new(classifiers);
    let preclassified_results: Vec<_> = results
        .into_iter()
        .map(|result| grapha_core::classify_extraction_result(result, &composite))
        .collect();

    let t = Instant::now();
    let merged = grapha_core::merge(preclassified_results);
    if verbose {
        progress::done(
            &format!(
                "merged → {} nodes, {} edges",
                merged.nodes.len(),
                merged.edges.len()
            ),
            t,
        );
    }

    let t = Instant::now();
    let mut graph = grapha_core::classify_graph(&merged, &composite);
    for pass in registry.collect_graph_passes() {
        graph = pass.apply(graph);
    }
    let graph = grapha_core::normalize_graph(graph);
    if verbose {
        let terminal_count = graph
            .nodes
            .iter()
            .filter(|n| matches!(n.role, Some(grapha_core::graph::NodeRole::Terminal { .. })))
            .count();
        let entry_count = graph
            .nodes
            .iter()
            .filter(|n| matches!(n.role, Some(grapha_core::graph::NodeRole::EntryPoint)))
            .count();
        progress::done(
            &format!(
                "classified → {} entries, {} terminals",
                entry_count, terminal_count
            ),
            t,
        );
    }

    Ok(graph)
}

fn load_graph(path: &Path) -> anyhow::Result<grapha_core::graph::Graph> {
    let db_path = path.join(".grapha/grapha.db");
    let s = store::sqlite::SqliteStore::new(db_path);
    s.load()
        .context("no index found — run `grapha index` first")
}

fn store_file_path(format: &str, store_path: &Path) -> anyhow::Result<PathBuf> {
    match format {
        "json" => Ok(store_path.join("graph.json")),
        "sqlite" => Ok(store_path.join("grapha.db")),
        other => Err(anyhow!("unknown store format: {other}")),
    }
}

fn build_store(format: &str, store_path: &Path) -> anyhow::Result<Box<dyn store::Store + Send>> {
    Ok(match format {
        "json" => Box::new(store::json::JsonStore::new(store_path.join("graph.json"))),
        "sqlite" => Box::new(store::sqlite::SqliteStore::new(
            store_path.join("grapha.db"),
        )),
        other => anyhow::bail!("unknown store format: {other}"),
    })
}

fn load_existing_graph(
    format: &str,
    store_path: &Path,
) -> anyhow::Result<Option<grapha_core::graph::Graph>> {
    let store_file = store_file_path(format, store_path)?;
    if !store_file.exists() {
        return Ok(None);
    }

    let store = build_store(format, store_path)?;
    match store.load() {
        Ok(graph) => Ok(Some(graph)),
        Err(error) => {
            eprintln!(
                "  \x1b[33m!\x1b[0m failed to load existing store, falling back to full rebuild: {error}"
            );
            Ok(None)
        }
    }
}

fn kind_label(kind: grapha_core::graph::NodeKind) -> String {
    serde_json::to_string(&kind)
        .unwrap_or_else(|_| format!("{kind:?}"))
        .trim_matches('"')
        .to_string()
}

fn format_ambiguity_error(query: &str, candidates: &[query::QueryCandidate]) -> String {
    let mut message = format!("ambiguous query: {query}\n");
    for candidate in candidates {
        message.push_str(&format!(
            "  - {} [{}] in {} ({})\n",
            candidate.name,
            kind_label(candidate.kind),
            candidate.file,
            candidate.id
        ));
    }
    message.push_str(&format!("hint: {}", query::ambiguity_hint()));
    message
}

fn resolve_query_result<T>(
    result: Result<T, query::QueryResolveError>,
    missing_label: &str,
) -> anyhow::Result<T> {
    match result {
        Ok(value) => Ok(value),
        Err(query::QueryResolveError::NotFound { query }) => {
            Err(anyhow!("{missing_label} not found: {query}"))
        }
        Err(query::QueryResolveError::Ambiguous { query, candidates }) => {
            Err(anyhow!(format_ambiguity_error(&query, &candidates)))
        }
        Err(query::QueryResolveError::NotFunction { hint }) => Err(anyhow!(hint)),
    }
}

fn resolve_field_set(fields_flag: &Option<String>, path: &Path) -> fields::FieldSet {
    match fields_flag {
        Some(f) => fields::FieldSet::parse(f),
        None => {
            let cfg = config::load_config(path);
            if cfg.output.default_fields.is_empty() {
                fields::FieldSet::default()
            } else {
                fields::FieldSet::from_config(&cfg.output.default_fields)
            }
        }
    }
}

fn tree_render_options(color: ColorMode) -> render::RenderOptions {
    use std::io::IsTerminal;

    match color {
        ColorMode::Always => render::RenderOptions::color(),
        ColorMode::Never => render::RenderOptions::plain(),
        ColorMode::Auto => {
            if std::io::stdout().is_terminal() {
                render::RenderOptions::color()
            } else {
                render::RenderOptions::plain()
            }
        }
    }
}

fn print_json<T: Serialize>(value: &T) -> anyhow::Result<()> {
    println!("{}", serde_json::to_string_pretty(value)?);
    Ok(())
}

fn print_query_result<T, R>(
    result: &T,
    format: QueryOutputFormat,
    render_options: render::RenderOptions,
    tree_renderer: R,
) -> anyhow::Result<()>
where
    T: Serialize,
    R: FnOnce(&T, render::RenderOptions) -> String,
{
    match format {
        QueryOutputFormat::Json => print_json(result),
        QueryOutputFormat::Tree => {
            println!("{}", tree_renderer(result, render_options));
            Ok(())
        }
    }
}

fn handle_resolved_graph_query<T, Q, R>(
    path: &Path,
    format: QueryOutputFormat,
    render_options: render::RenderOptions,
    missing_label: &str,
    query_fn: Q,
    tree_renderer: R,
) -> anyhow::Result<()>
where
    T: Serialize,
    Q: FnOnce(&grapha_core::graph::Graph) -> Result<T, query::QueryResolveError>,
    R: FnOnce(&T, render::RenderOptions) -> String,
{
    let graph = load_graph(path)?;
    let result = resolve_query_result(query_fn(&graph), missing_label)?;
    print_query_result(&result, format, render_options, tree_renderer)
}

fn handle_graph_query<T, Q, R>(
    path: &Path,
    format: QueryOutputFormat,
    render_options: render::RenderOptions,
    query_fn: Q,
    tree_renderer: R,
) -> anyhow::Result<()>
where
    T: Serialize,
    Q: FnOnce(&grapha_core::graph::Graph) -> T,
    R: FnOnce(&T, render::RenderOptions) -> String,
{
    let graph = load_graph(path)?;
    let result = query_fn(&graph);
    print_query_result(&result, format, render_options, tree_renderer)
}

fn open_search_index(path: &Path) -> anyhow::Result<tantivy::Index> {
    let search_index_path = path.join(".grapha/search_index");
    if search_index_path.exists() {
        Ok(tantivy::Index::open_in_dir(&search_index_path)?)
    } else {
        let graph = load_graph(path)?;
        eprintln!("  building search index...");
        Ok(search::build_index(&graph, &search_index_path)?)
    }
}

fn handle_analyze(
    path: PathBuf,
    output: Option<PathBuf>,
    filter: Option<String>,
    compact: bool,
) -> anyhow::Result<()> {
    let verbose = output.is_some();
    let mut graph = run_pipeline(&path, verbose, false)?;

    if let Some(ref filter_str) = filter {
        let kinds = filter::parse_filter(filter_str)?;
        graph = filter::filter_graph(graph, &kinds);
    }

    let json = if compact {
        let pruned = compress::prune::prune(graph, false);
        let grouped = compress::group::group(&pruned);
        match &output {
            Some(_) => serde_json::to_string(&grouped)?,
            None => serde_json::to_string_pretty(&grouped)?,
        }
    } else {
        match &output {
            Some(_) => serde_json::to_string(&graph)?,
            None => serde_json::to_string_pretty(&graph)?,
        }
    };

    match output {
        Some(p) => {
            std::fs::write(&p, &json)
                .with_context(|| format!("failed to write {}", p.display()))?;
            eprintln!("  \x1b[32m✓\x1b[0m wrote {}", p.display());
        }
        None => println!("{json}"),
    }

    Ok(())
}

fn handle_index(
    path: PathBuf,
    format: String,
    store_dir: Option<PathBuf>,
    full_rebuild: bool,
    timing: bool,
) -> anyhow::Result<()> {
    let total_start = Instant::now();
    let store_path = store_dir.unwrap_or_else(|| path.join(".grapha"));
    let graph = run_pipeline(&path, true, timing)?;

    std::fs::create_dir_all(&store_path)
        .with_context(|| format!("failed to create store dir {}", store_path.display()))?;

    let previous_graph = if full_rebuild {
        None
    } else {
        load_existing_graph(&format, &store_path)?
    };

    let delta = if full_rebuild {
        None
    } else {
        previous_graph
            .as_ref()
            .map(|prev| delta::GraphDelta::between(prev, &graph))
    };

    let search_index_path = store_path.join("search_index");
    let index_root = path.clone();
    let save_result = std::thread::scope(|scope| {
        let save_handle = scope.spawn(|| {
            let t = Instant::now();
            let s = build_store(&format, &store_path)?;
            let stats = if full_rebuild {
                let stats = store::StoreWriteStats::from_graphs(
                    previous_graph.as_ref(),
                    &graph,
                    delta::SyncMode::FullRebuild,
                );
                s.save(&graph)?;
                stats
            } else {
                s.save_incremental(previous_graph.as_ref(), &graph)?
            };
            Ok::<_, anyhow::Error>((t.elapsed(), stats))
        });

        let search_handle = scope.spawn(|| {
            let t = Instant::now();
            let stats = search::sync_index(
                previous_graph.as_ref(),
                &graph,
                &search_index_path,
                full_rebuild,
                delta.as_ref(),
            )?;
            Ok::<_, anyhow::Error>((t.elapsed(), stats))
        });

        let localization_handle = scope.spawn(|| {
            let t = Instant::now();
            let stats = localization::build_and_save_catalog_snapshot(&index_root, &store_path)?;
            Ok::<_, anyhow::Error>((t.elapsed(), stats))
        });

        let assets_handle = scope.spawn(|| {
            let t = Instant::now();
            let stats = assets::build_and_save_snapshot(&index_root, &store_path)?;
            Ok::<_, anyhow::Error>((t.elapsed(), stats))
        });

        let save = save_handle.join().expect("save thread panicked")?;
        let search = search_handle.join().expect("search thread panicked")?;
        let localization = localization_handle
            .join()
            .expect("localization thread panicked")?;
        let assets = assets_handle.join().expect("assets thread panicked")?;
        Ok::<_, anyhow::Error>((save, search, localization, assets))
    });
    let (
        (save_elapsed, save_stats),
        (search_elapsed, search_stats),
        (localize_elapsed, localize_stats),
        (assets_elapsed, assets_stats),
    ) = save_result?;
    progress::done_elapsed(
        &format!(
            "saved to {} ({}; {})",
            store_path.display(),
            format,
            save_stats.summary()
        ),
        save_elapsed,
    );
    progress::done_elapsed(
        &format!("built search index ({})", search_stats.summary()),
        search_elapsed,
    );
    progress::done_elapsed(
        &format!(
            "saved localization snapshot ({} records)",
            localize_stats.record_count
        ),
        localize_elapsed,
    );
    for warning in &localize_stats.warnings {
        eprintln!(
            "  \x1b[33m!\x1b[0m skipped invalid localization catalog {}: {}",
            warning.catalog_file, warning.reason
        );
    }
    progress::done_elapsed(
        &format!(
            "saved asset snapshot ({} images)",
            assets_stats.record_count
        ),
        assets_elapsed,
    );
    for warning in &assets_stats.warnings {
        eprintln!(
            "  \x1b[33m!\x1b[0m skipped invalid asset catalog {}: {}",
            warning.catalog_path, warning.reason
        );
    }

    progress::summary(&format!(
        "\n  {} nodes, {} edges indexed in {:.1}s",
        graph.nodes.len(),
        graph.edges.len(),
        total_start.elapsed().as_secs_f64(),
    ));

    Ok(())
}

fn handle_symbol_command(
    command: SymbolCommands,
    render_options: render::RenderOptions,
) -> anyhow::Result<()> {
    match command {
        SymbolCommands::Search {
            query,
            limit,
            path,
            kind,
            module,
            file,
            role,
            fuzzy,
            context,
            fields,
        } => {
            let field_set = resolve_field_set(&fields, &path);
            let _render_options = render_options.with_fields(field_set);
            let index = open_search_index(&path)?;
            let options = search::SearchOptions {
                kind,
                module,
                file_glob: file,
                role,
                fuzzy,
            };
            let t = Instant::now();
            let results = search::search_filtered(&index, &query, limit, &options)?;
            let elapsed = t.elapsed();

            if context {
                let graph = load_graph(&path)?;
                let enriched = search::enrich_with_context(&results, &graph);
                print_json(&enriched)?;
            } else {
                print_json(&results)?;
            }

            eprintln!(
                "\n  {} results in {:.1}ms",
                results.len(),
                elapsed.as_secs_f64() * 1000.0,
            );
            Ok(())
        }
        SymbolCommands::Context {
            symbol,
            path,
            format,
            fields,
        } => {
            let field_set = resolve_field_set(&fields, &path);
            let render_options = render_options.with_fields(field_set);
            handle_resolved_graph_query(
                &path,
                format,
                render_options,
                "symbol",
                |graph| query::context::query_context(graph, &symbol),
                render::render_context_with_options,
            )
        }
        SymbolCommands::Impact {
            symbol,
            depth,
            path,
            format,
            fields,
        } => {
            let field_set = resolve_field_set(&fields, &path);
            let render_options = render_options.with_fields(field_set);
            handle_resolved_graph_query(
                &path,
                format,
                render_options,
                "symbol",
                |graph| query::impact::query_impact(graph, &symbol, depth),
                render::render_impact_with_options,
            )
        }
        SymbolCommands::Complexity { symbol, path } => {
            let graph = load_graph(&path)?;
            let result =
                query::complexity::query_complexity(&graph, &symbol).map_err(|e| anyhow!("{e}"))?;
            print_json(&result)
        }
        SymbolCommands::File { file, path } => {
            let graph = load_graph(&path)?;
            let result = query::file_symbols::query_file_symbols(&graph, &file);
            if result.total == 0 {
                anyhow::bail!("no symbols found in file matching: {file}");
            }
            print_json(&result)
        }
    }
}

fn handle_flow_command(
    command: FlowCommands,
    render_options: render::RenderOptions,
) -> anyhow::Result<()> {
    match command {
        FlowCommands::Trace {
            symbol,
            direction,
            depth,
            path,
            format,
        } => match direction {
            TraceDirection::Forward => handle_resolved_graph_query(
                &path,
                format,
                render_options,
                "symbol",
                |graph| query::trace::query_trace(graph, &symbol, depth.unwrap_or(10)),
                render::render_trace_with_options,
            ),
            TraceDirection::Reverse => handle_resolved_graph_query(
                &path,
                format,
                render_options,
                "symbol",
                |graph| query::reverse::query_reverse(graph, &symbol, depth),
                render::render_reverse_with_options,
            ),
        },
        FlowCommands::Graph {
            symbol,
            depth,
            path,
            format,
        } => handle_resolved_graph_query(
            &path,
            format,
            render_options,
            "symbol",
            |graph| query::dataflow::query_dataflow(graph, &symbol, depth),
            render::render_dataflow_with_options,
        ),
        FlowCommands::Entries { path, format } => handle_graph_query(
            &path,
            format,
            render_options,
            query::entries::query_entries,
            render::render_entries_with_options,
        ),
    }
}

fn handle_l10n_command(
    command: L10nCommands,
    render_options: render::RenderOptions,
) -> anyhow::Result<()> {
    match command {
        L10nCommands::Symbol {
            symbol,
            path,
            format,
        } => {
            let graph = load_graph(&path)?;
            let catalogs = localization::load_catalog_index(&path)?;
            let result = resolve_query_result(
                query::localize::query_localize(&graph, &catalogs, &symbol),
                "symbol",
            )?;
            print_query_result(
                &result,
                format,
                render_options,
                render::render_localize_with_options,
            )
        }
        L10nCommands::Usages {
            key,
            table,
            path,
            format,
        } => {
            let graph = load_graph(&path)?;
            let catalogs = localization::load_catalog_index(&path)?;
            let result = query::usages::query_usages(&graph, &catalogs, &key, table.as_deref());
            print_query_result(
                &result,
                format,
                render_options,
                render::render_usages_with_options,
            )
        }
    }
}

fn handle_asset_command(command: AssetCommands) -> anyhow::Result<()> {
    match command {
        AssetCommands::List { unused, path } => {
            if unused {
                let graph = load_graph(&path)?;
                let index = assets::load_asset_index(&path)?;
                let unused = assets::find_unused(&index, &graph);
                print_json(&unused)
            } else {
                let index = assets::load_asset_index(&path)?;
                let records = index.all_records().to_vec();
                print_json(&records)
            }
        }
        AssetCommands::Usages { name, path, format } => {
            let graph = load_graph(&path)?;
            let usages = assets::find_usages(&graph, &name);
            match format {
                QueryOutputFormat::Json => print_json(&usages),
                QueryOutputFormat::Tree => {
                    if usages.is_empty() {
                        eprintln!("  no usages found for asset '{name}'");
                    } else {
                        for usage in &usages {
                            println!(
                                "  {} ({}) — {}",
                                usage.node_name, usage.file, usage.asset_name
                            );
                        }
                    }
                    Ok(())
                }
            }
        }
    }
}

fn handle_repo_command(command: RepoCommands) -> anyhow::Result<()> {
    match command {
        RepoCommands::Changes { scope, path } => {
            let graph = load_graph(&path)?;
            let report = changes::detect_changes(&path, &graph, &scope)?;
            print_json(&report)
        }
        RepoCommands::Map { module, path } => {
            let graph = load_graph(&path)?;
            let map = query::map::file_map(&graph, module.as_deref());
            print_json(&map)
        }
        RepoCommands::Smells { module, path } => {
            let graph = load_graph(&path)?;
            let mut result = query::smells::detect_smells(&graph);

            if let Some(ref module_name) = module {
                let module_lower = module_name.to_lowercase();
                result.smells.retain(|smell| {
                    graph.nodes.iter().any(|n| {
                        n.id == smell.symbol.id
                            && n.module
                                .as_ref()
                                .is_some_and(|m| m.to_lowercase() == module_lower)
                    })
                });
                result.total = result.smells.len();
                result.by_severity.clear();
                for smell in &result.smells {
                    *result
                        .by_severity
                        .entry(smell.severity.clone())
                        .or_default() += 1;
                }
            }

            print_json(&result)
        }
        RepoCommands::Modules { path } => {
            let graph = load_graph(&path)?;
            let result = query::module_summary::query_module_summary(&graph);
            print_json(&result)
        }
    }
}

fn handle_serve(path: PathBuf, port: u16, mcp_mode: bool, watch_mode: bool) -> anyhow::Result<()> {
    let graph = load_graph(&path)?;
    let search_index = open_search_index(&path)?;

    if mcp_mode {
        let state = mcp::handler::McpState {
            graph,
            search_index,
            store_path: path.join(".grapha"),
            recall: recall::Recall::new(),
        };

        // Start watcher if requested — runs on a background thread
        let _watcher_guard = if watch_mode {
            let (rx, _guard) =
                watch::start_watcher(&path, &["swift", "rs", "ts", "tsx", "js", "jsx", "vue"])?;
            let store_path = path.join(".grapha");
            let project_path = path.clone();

            // Spawn a thread that processes watch events and updates the MCP state
            // We use a channel to send updated state back to the main MCP loop
            let (state_tx, state_rx) =
                std::sync::mpsc::channel::<(grapha_core::graph::Graph, tantivy::Index)>();

            std::thread::Builder::new()
                .name("grapha-watch-reindex".into())
                .spawn(move || {
                    for event in rx {
                        match event {
                            watch::WatchEvent::FilesChanged(files) => {
                                eprintln!("watch: {} file(s) changed, re-indexing...", files.len());
                                // Run full pipeline and persist
                                match run_pipeline(&project_path, false, false) {
                                    Ok(graph) => {
                                        // Persist to SQLite
                                        let store_file = store_path.join("grapha.db");
                                        let store = store::sqlite::SqliteStore::new(store_file);
                                        if let Err(e) = store.save(&graph) {
                                            eprintln!("watch: failed to save graph: {e}");
                                            continue;
                                        }

                                        // Rebuild search index
                                        let search_path = store_path.join("search_index");
                                        match search::build_index(&graph, &search_path) {
                                            Ok(index) => {
                                                if state_tx.send((graph, index)).is_err() {
                                                    break;
                                                }
                                                eprintln!("watch: re-index complete");
                                            }
                                            Err(e) => {
                                                eprintln!(
                                                    "watch: failed to build search index: {e}"
                                                );
                                            }
                                        }
                                    }
                                    Err(e) => {
                                        eprintln!("watch: re-index failed: {e}");
                                    }
                                }
                            }
                        }
                    }
                })?;

            // The MCP server loop will check for state updates between requests
            // We integrate this by passing the receiver into run_mcp_server
            mcp::run_mcp_server_with_watch(state, state_rx)?;
            return Ok(());
        } else {
            None::<watch::WatcherGuard>
        };

        mcp::run_mcp_server(state)
    } else {
        let rt = tokio::runtime::Runtime::new()?;
        rt.block_on(serve::run(graph, search_index, port))?;
        Ok(())
    }
}

fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();
    let render_options = tree_render_options(cli.color);

    match cli.command {
        Commands::Analyze {
            path,
            output,
            filter,
            compact,
        } => handle_analyze(path, output, filter, compact)?,
        Commands::Index {
            path,
            format,
            store_dir,
            full_rebuild,
            timing,
        } => handle_index(path, format, store_dir, full_rebuild, timing)?,
        Commands::Serve {
            path,
            port,
            mcp,
            watch,
        } => handle_serve(path, port, mcp, watch)?,
        Commands::Symbol { command } => handle_symbol_command(command, render_options)?,
        Commands::Flow { command } => handle_flow_command(command, render_options)?,
        Commands::L10n { command } => handle_l10n_command(command, render_options)?,
        Commands::Asset { command } => handle_asset_command(command)?,
        Commands::Repo { command } => handle_repo_command(command)?,
    }

    Ok(())
}