cxpak 0.13.0

Spends CPU cycles so you don't spend tokens. The LLM gets a briefing packet instead of a flashlight in a dark room.
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
use crate::index::CodebaseIndex;
use crate::parser::language::{SymbolKind, Visibility};
use regex::Regex;
use serde::Serialize;

#[derive(Debug, Serialize)]
pub struct ApiSurface {
    pub symbols: SymbolSection,
    pub routes: RouteSection,
    pub grpc_services: Vec<GrpcService>,
    pub graphql_types: Vec<GraphqlType>,
    pub token_count: usize,
}

#[derive(Debug, Serialize)]
pub struct SymbolSection {
    pub total: usize,
    pub by_file: Vec<FileSymbols>,
}

#[derive(Debug, Serialize)]
pub struct FileSymbols {
    pub path: String,
    pub pagerank: f64,
    pub symbols: Vec<ApiSymbol>,
}

#[derive(Debug, Serialize)]
pub struct ApiSymbol {
    pub name: String,
    pub kind: String,
    pub signature: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub doc: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct RouteSection {
    pub total: usize,
    pub endpoints: Vec<RouteEndpoint>,
}

#[derive(Debug, Clone, Serialize)]
pub struct RouteEndpoint {
    pub method: String,
    pub path: String,
    pub handler: String,
    pub file: String,
    pub line: usize,
}

#[derive(Debug, Serialize)]
pub struct GrpcService {
    pub name: String,
    pub file: String,
    pub methods: Vec<String>,
}

#[derive(Debug, Serialize)]
pub struct GraphqlType {
    pub name: String,
    pub kind: String,
    pub file: String,
}

fn symbol_kind_str(kind: &SymbolKind) -> &'static str {
    match kind {
        SymbolKind::Function => "function",
        SymbolKind::Struct => "struct",
        SymbolKind::Enum => "enum",
        SymbolKind::Trait => "trait",
        SymbolKind::Interface => "interface",
        SymbolKind::Class => "class",
        SymbolKind::Method => "method",
        SymbolKind::Constant => "constant",
        SymbolKind::TypeAlias => "type_alias",
        SymbolKind::Selector => "selector",
        SymbolKind::Mixin => "mixin",
        SymbolKind::Variable => "variable",
        SymbolKind::Heading => "heading",
        SymbolKind::Section => "section",
        SymbolKind::Key => "key",
        SymbolKind::Table => "table",
        SymbolKind::Block => "block",
        SymbolKind::Target => "target",
        SymbolKind::Rule => "rule",
        SymbolKind::Element => "element",
        SymbolKind::Message => "message",
        SymbolKind::Service => "service",
        SymbolKind::Query => "query",
        SymbolKind::Mutation => "mutation",
        SymbolKind::Type => "type",
        SymbolKind::Instruction => "instruction",
    }
}

/// Extract the public API surface: public symbols sorted by PageRank, filtered by focus.
pub fn extract_public_symbols(
    index: &CodebaseIndex,
    focus: Option<&str>,
) -> (SymbolSection, usize) {
    let mut file_entries: Vec<FileSymbols> = vec![];
    let mut total_symbols = 0usize;
    let mut token_count = 0usize;

    // Collect files with public symbols, sorted by pagerank descending.
    let mut files_with_symbols: Vec<(&crate::index::IndexedFile, f64)> = index
        .files
        .iter()
        .filter(|f| {
            // Apply focus filter.
            if let Some(prefix) = focus {
                if !f.relative_path.starts_with(prefix) {
                    return false;
                }
            }
            // Must have at least one public symbol.
            f.parse_result
                .as_ref()
                .map(|pr| {
                    pr.symbols
                        .iter()
                        .any(|s| s.visibility == Visibility::Public)
                })
                .unwrap_or(false)
        })
        .map(|f| {
            let pr = index.pagerank.get(&f.relative_path).copied().unwrap_or(0.0);
            (f, pr)
        })
        .collect();

    files_with_symbols.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

    for (file, pagerank) in files_with_symbols {
        let pr = file.parse_result.as_ref().unwrap();
        let symbols: Vec<ApiSymbol> = pr
            .symbols
            .iter()
            .filter(|s| s.visibility == Visibility::Public)
            .map(|s| ApiSymbol {
                name: s.name.clone(),
                kind: symbol_kind_str(&s.kind).to_string(),
                signature: s.signature.clone(),
                doc: None,
            })
            .collect();

        total_symbols += symbols.len();
        // Rough token estimate: 5 tokens per symbol (name + kind + signature words).
        token_count += symbols
            .iter()
            .map(|s| s.signature.split_whitespace().count() + 2)
            .sum::<usize>();

        file_entries.push(FileSymbols {
            path: file.relative_path.clone(),
            pagerank,
            symbols,
        });
    }

    (
        SymbolSection {
            total: total_symbols,
            by_file: file_entries,
        },
        token_count,
    )
}

/// Detect HTTP route endpoints from file content using 12 framework patterns.
pub fn detect_routes(content: &str, file_path: &str) -> Vec<RouteEndpoint> {
    let mut routes = vec![];

    // Helper to compute 1-based line number from a byte offset.
    let line_of =
        |offset: usize| -> usize { content[..offset].chars().filter(|&c| c == '\n').count() + 1 };

    // 1. Express/Koa: (app|router).(get|post|put|delete|patch)("/<path>")
    if let Ok(re) =
        Regex::new(r#"(?i)(app|router)\.(get|post|put|delete|patch)\s*\(\s*["'](/[^"']*)"#)
    {
        for cap in re.captures_iter(content) {
            let method = cap[2].to_uppercase();
            let path = cap[3].to_string();
            let line = line_of(cap.get(0).unwrap().start());
            routes.push(RouteEndpoint {
                method,
                path,
                handler: "handler".to_string(),
                file: file_path.to_string(),
                line,
            });
        }
    }

    // 2. Flask: @(app|blueprint).(route|get|post|put|delete)("/<path>")
    if let Ok(re) =
        Regex::new(r#"(?i)@(app|blueprint)\.(route|get|post|put|delete)\s*\(\s*["'](/[^"']*)"#)
    {
        for cap in re.captures_iter(content) {
            let method_or_route = cap[2].to_lowercase();
            let method = if method_or_route == "route" {
                "GET".to_string()
            } else {
                method_or_route.to_uppercase()
            };
            let path = cap[3].to_string();
            let line = line_of(cap.get(0).unwrap().start());
            routes.push(RouteEndpoint {
                method,
                path,
                handler: "handler".to_string(),
                file: file_path.to_string(),
                line,
            });
        }
    }

    // 3. Django: path("/<path>") — only in files containing "urls" in the path
    if file_path.contains("urls") {
        if let Ok(re) = Regex::new(r#"(?i)path\s*\(\s*["']([^"']*)"#) {
            for cap in re.captures_iter(content) {
                let path_val = cap[1].to_string();
                let line = line_of(cap.get(0).unwrap().start());
                routes.push(RouteEndpoint {
                    method: "GET".to_string(),
                    path: format!("/{}", path_val.trim_start_matches('/')),
                    handler: "handler".to_string(),
                    file: file_path.to_string(),
                    line,
                });
            }
        }
    }

    // 4. FastAPI: @(app|router).(get|post|put|delete|patch)("/<path>")
    if let Ok(re) =
        Regex::new(r#"(?i)@(app|router)\.(get|post|put|delete|patch)\s*\(\s*["'](/[^"']*)"#)
    {
        for cap in re.captures_iter(content) {
            let method = cap[2].to_uppercase();
            let path = cap[3].to_string();
            let line = line_of(cap.get(0).unwrap().start());
            routes.push(RouteEndpoint {
                method,
                path,
                handler: "handler".to_string(),
                file: file_path.to_string(),
                line,
            });
        }
    }

    // 5. Spring: @(Get|Post|Put|Delete|Patch|Request)Mapping("/<path>")
    if let Ok(re) =
        Regex::new(r#"@(Get|Post|Put|Delete|Patch|Request)Mapping\s*\(\s*["'](/[^"']*)"#)
    {
        for cap in re.captures_iter(content) {
            let verb = cap[1].to_lowercase();
            let method = if verb == "request" {
                "GET".to_string()
            } else {
                verb.to_uppercase()
            };
            let path = cap[2].to_string();
            let line = line_of(cap.get(0).unwrap().start());
            routes.push(RouteEndpoint {
                method,
                path,
                handler: "handler".to_string(),
                file: file_path.to_string(),
                line,
            });
        }
    }

    // 6. actix-web: #[get("/path")]
    if let Ok(re) = Regex::new(r#"#\[(get|post|put|delete|patch)\s*\(\s*["'](/[^"']*)"#) {
        for cap in re.captures_iter(content) {
            let method = cap[1].to_uppercase();
            let path = cap[2].to_string();
            let line = line_of(cap.get(0).unwrap().start());
            routes.push(RouteEndpoint {
                method,
                path,
                handler: "handler".to_string(),
                file: file_path.to_string(),
                line,
            });
        }
    }

    // 7. axum: .route("/path")
    if let Ok(re) = Regex::new(r#"\.route\s*\(\s*["'](/[^"']*)"#) {
        for cap in re.captures_iter(content) {
            let path = cap[1].to_string();
            let line = line_of(cap.get(0).unwrap().start());
            routes.push(RouteEndpoint {
                method: "GET".to_string(),
                path,
                handler: "handler".to_string(),
                file: file_path.to_string(),
                line,
            });
        }
    }

    // 8. Gin: (r|router|group).(GET|POST|PUT|DELETE|PATCH)("/path")
    if let Ok(re) =
        Regex::new(r#"(?i)(r|router|group)\.(GET|POST|PUT|DELETE|PATCH)\s*\(\s*["'](/[^"']*)"#)
    {
        for cap in re.captures_iter(content) {
            let method = cap[2].to_uppercase();
            let path = cap[3].to_string();
            let line = line_of(cap.get(0).unwrap().start());
            routes.push(RouteEndpoint {
                method,
                path,
                handler: "handler".to_string(),
                file: file_path.to_string(),
                line,
            });
        }
    }

    // 9. Echo: (e|g|echo|group).(GET|POST|PUT|DELETE|PATCH)("/path")
    if let Ok(re) =
        Regex::new(r#"(?i)(e|g|echo|group)\.(GET|POST|PUT|DELETE|PATCH)\s*\(\s*["'](/[^"']*)"#)
    {
        for cap in re.captures_iter(content) {
            let method = cap[2].to_uppercase();
            let path = cap[3].to_string();
            let line = line_of(cap.get(0).unwrap().start());
            routes.push(RouteEndpoint {
                method,
                path,
                handler: "handler".to_string(),
                file: file_path.to_string(),
                line,
            });
        }
    }

    // 10. Rails: (get|post|put|patch|delete) "/path" — only in files containing "routes"
    if file_path.contains("routes") {
        if let Ok(re) = Regex::new(r#"(?i)(get|post|put|patch|delete)\s+["'](/[^"']*)"#) {
            for cap in re.captures_iter(content) {
                let method = cap[1].to_uppercase();
                let path = cap[2].to_string();
                let line = line_of(cap.get(0).unwrap().start());
                routes.push(RouteEndpoint {
                    method,
                    path,
                    handler: "handler".to_string(),
                    file: file_path.to_string(),
                    line,
                });
            }
        }
    }

    // 11. ASP.NET: [(HttpGet|HttpPost|HttpPut|HttpDelete|HttpPatch|Route)("/path")]
    if let Ok(re) = Regex::new(r#"\[(Http(Get|Post|Put|Delete|Patch)|Route)\s*\(\s*["'](/[^"']*)"#)
    {
        for cap in re.captures_iter(content) {
            let verb_raw = if cap.get(2).is_some() {
                cap[2].to_lowercase()
            } else {
                "get".to_string()
            };
            let method = verb_raw.to_uppercase();
            let path = cap[3].to_string();
            let line = line_of(cap.get(0).unwrap().start());
            routes.push(RouteEndpoint {
                method,
                path,
                handler: "handler".to_string(),
                file: file_path.to_string(),
                line,
            });
        }
    }

    // 12. Phoenix: (get|post|put|patch|delete) "/path" — only in files containing "router"
    if file_path.contains("router") {
        if let Ok(re) = Regex::new(r#"(?i)(get|post|put|patch|delete)\s+["'](/[^"']*)"#) {
            for cap in re.captures_iter(content) {
                let method = cap[1].to_uppercase();
                let path = cap[2].to_string();
                let line = line_of(cap.get(0).unwrap().start());
                routes.push(RouteEndpoint {
                    method,
                    path,
                    handler: "handler".to_string(),
                    file: file_path.to_string(),
                    line,
                });
            }
        }
    }

    // Deduplicate routes: multiple framework patterns may match the same route.
    // Dedup by (line, method, path) and sort by line number for stable, predictable output.
    let mut seen: std::collections::HashSet<(usize, String, String)> =
        std::collections::HashSet::new();
    routes.retain(|r| seen.insert((r.line, r.method.clone(), r.path.clone())));
    routes.sort_by_key(|r| r.line);

    routes
}

/// Extract gRPC services from proto file parse results.
fn extract_grpc_services(index: &CodebaseIndex, focus: Option<&str>) -> Vec<GrpcService> {
    let mut services: std::collections::HashMap<String, GrpcService> =
        std::collections::HashMap::new();

    for file in &index.files {
        if let Some(prefix) = focus {
            if !file.relative_path.starts_with(prefix) {
                continue;
            }
        }
        let is_proto = file
            .language
            .as_deref()
            .map(|l| l == "protobuf")
            .unwrap_or(false)
            || file.relative_path.ends_with(".proto");

        if !is_proto {
            continue;
        }

        if let Some(pr) = &file.parse_result {
            let mut current_service: Option<String> = None;

            for symbol in &pr.symbols {
                let kind_str = symbol_kind_str(&symbol.kind);
                if kind_str == "service" {
                    let entry = services.entry(symbol.name.clone()).or_insert(GrpcService {
                        name: symbol.name.clone(),
                        file: file.relative_path.clone(),
                        methods: vec![],
                    });
                    current_service = Some(symbol.name.clone());
                    // Suppress unused assignment warning for entry when no methods added yet.
                    let _ = entry;
                } else if kind_str == "method" {
                    if let Some(ref svc_name) = current_service {
                        if let Some(svc) = services.get_mut(svc_name) {
                            svc.methods.push(symbol.name.clone());
                        }
                    }
                }
            }
        }
    }

    services.into_values().collect()
}

/// Extract GraphQL types from GraphQL file parse results.
fn extract_graphql_types(index: &CodebaseIndex, focus: Option<&str>) -> Vec<GraphqlType> {
    let mut types = vec![];

    for file in &index.files {
        if let Some(prefix) = focus {
            if !file.relative_path.starts_with(prefix) {
                continue;
            }
        }
        let is_graphql = file
            .language
            .as_deref()
            .map(|l| l == "graphql")
            .unwrap_or(false)
            || file.relative_path.ends_with(".graphql")
            || file.relative_path.ends_with(".gql");

        if !is_graphql {
            continue;
        }

        if let Some(pr) = &file.parse_result {
            for symbol in &pr.symbols {
                let kind_str = symbol_kind_str(&symbol.kind);
                if matches!(kind_str, "type" | "query" | "mutation") {
                    types.push(GraphqlType {
                        name: symbol.name.clone(),
                        kind: kind_str.to_string(),
                        file: file.relative_path.clone(),
                    });
                }
            }
        }
    }

    types
}

/// Orchestrator: combine public symbols + routes + gRPC + GraphQL within a token budget.
pub fn extract_api_surface(
    index: &CodebaseIndex,
    focus: Option<&str>,
    include: &str,
    token_budget: usize,
) -> ApiSurface {
    let (symbols_section, sym_tokens) = if include == "all" || include == "symbols" {
        extract_public_symbols(index, focus)
    } else {
        (
            SymbolSection {
                total: 0,
                by_file: vec![],
            },
            0,
        )
    };

    let mut route_endpoints: Vec<RouteEndpoint> = vec![];
    if include == "all" || include == "routes" {
        for file in &index.files {
            if let Some(prefix) = focus {
                if !file.relative_path.starts_with(prefix) {
                    continue;
                }
            }
            let found = detect_routes(&file.content, &file.relative_path);
            route_endpoints.extend(found);
        }
    }

    let grpc_services = if include == "all" {
        extract_grpc_services(index, focus)
    } else {
        vec![]
    };

    let graphql_types = if include == "all" {
        extract_graphql_types(index, focus)
    } else {
        vec![]
    };

    let route_tokens = route_endpoints.len() * 8;
    let grpc_tokens = grpc_services
        .iter()
        .map(|s| s.methods.len() * 4 + 4)
        .sum::<usize>();
    let graphql_tokens = graphql_types.len() * 4;
    let raw_total = sym_tokens + route_tokens + grpc_tokens + graphql_tokens;

    // Apply token budget: trim symbol section if over budget.
    let (final_symbols, final_token_count) = if raw_total > token_budget && token_budget > 0 {
        let available_for_symbols =
            token_budget.saturating_sub(route_tokens + grpc_tokens + graphql_tokens);
        let mut trimmed_by_file = vec![];
        let mut remaining = available_for_symbols;
        let mut total_kept = 0usize;
        for file_syms in symbols_section.by_file {
            let file_tokens: usize = file_syms
                .symbols
                .iter()
                .map(|s| s.signature.split_whitespace().count() + 2)
                .sum();
            if file_tokens <= remaining {
                remaining = remaining.saturating_sub(file_tokens);
                total_kept += file_syms.symbols.len();
                trimmed_by_file.push(file_syms);
            }
        }
        (
            SymbolSection {
                total: total_kept,
                by_file: trimmed_by_file,
            },
            available_for_symbols - remaining + route_tokens + grpc_tokens + graphql_tokens,
        )
    } else {
        (symbols_section, raw_total)
    };

    let route_total = route_endpoints.len();
    ApiSurface {
        symbols: final_symbols,
        routes: RouteSection {
            total: route_total,
            endpoints: route_endpoints,
        },
        grpc_services,
        graphql_types,
        token_count: final_token_count,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::budget::counter::TokenCounter;
    use crate::index::CodebaseIndex;
    use crate::parser::language::{ParseResult, Symbol, SymbolKind, Visibility};
    use crate::scanner::ScannedFile;
    use std::collections::HashMap;

    fn make_index_with_symbols() -> CodebaseIndex {
        let counter = TokenCounter::new();
        let dir = tempfile::TempDir::new().unwrap();

        let fp1 = dir.path().join("src/api.rs");
        std::fs::create_dir_all(fp1.parent().unwrap()).unwrap();
        std::fs::write(&fp1, "pub fn get_users() {} pub fn internal() {}").unwrap();

        let fp2 = dir.path().join("src/internal.rs");
        std::fs::write(&fp2, "fn private_helper() {}").unwrap();

        let files = vec![
            ScannedFile {
                relative_path: "src/api.rs".into(),
                absolute_path: fp1,
                language: Some("rust".into()),
                size_bytes: 40,
            },
            ScannedFile {
                relative_path: "src/internal.rs".into(),
                absolute_path: fp2,
                language: Some("rust".into()),
                size_bytes: 20,
            },
        ];

        let mut parse_results = HashMap::new();
        parse_results.insert(
            "src/api.rs".to_string(),
            ParseResult {
                symbols: vec![
                    Symbol {
                        name: "get_users".to_string(),
                        kind: SymbolKind::Function,
                        visibility: Visibility::Public,
                        signature: "pub fn get_users()".to_string(),
                        body: "{}".to_string(),
                        start_line: 1,
                        end_line: 1,
                    },
                    Symbol {
                        name: "internal".to_string(),
                        kind: SymbolKind::Function,
                        visibility: Visibility::Private,
                        signature: "fn internal()".to_string(),
                        body: "{}".to_string(),
                        start_line: 1,
                        end_line: 1,
                    },
                ],
                imports: vec![],
                exports: vec![],
            },
        );
        parse_results.insert(
            "src/internal.rs".to_string(),
            ParseResult {
                symbols: vec![Symbol {
                    name: "private_helper".to_string(),
                    kind: SymbolKind::Function,
                    visibility: Visibility::Private,
                    signature: "fn private_helper()".to_string(),
                    body: "{}".to_string(),
                    start_line: 1,
                    end_line: 1,
                }],
                imports: vec![],
                exports: vec![],
            },
        );

        CodebaseIndex::build(files, parse_results, &counter)
    }

    #[test]
    fn test_extract_public_symbols_only() {
        let index = make_index_with_symbols();
        let (section, _tokens) = extract_public_symbols(&index, None);
        // Only one public symbol: get_users
        assert_eq!(section.total, 1);
        assert_eq!(section.by_file.len(), 1);
        assert_eq!(section.by_file[0].path, "src/api.rs");
        assert_eq!(section.by_file[0].symbols[0].name, "get_users");
    }

    #[test]
    fn test_private_symbols_excluded() {
        let index = make_index_with_symbols();
        let (section, _tokens) = extract_public_symbols(&index, None);
        // private_helper and internal must not appear
        for file_syms in &section.by_file {
            for sym in &file_syms.symbols {
                assert_ne!(sym.name, "private_helper");
                assert_ne!(sym.name, "internal");
            }
        }
    }

    #[test]
    fn test_sorted_by_pagerank() {
        let counter = TokenCounter::new();
        let dir = tempfile::TempDir::new().unwrap();

        let fp_a = dir.path().join("a.rs");
        let fp_b = dir.path().join("b.rs");
        std::fs::write(&fp_a, "pub fn alpha() {}").unwrap();
        std::fs::write(&fp_b, "pub fn beta() {}").unwrap();

        let files = vec![
            ScannedFile {
                relative_path: "a.rs".into(),
                absolute_path: fp_a,
                language: Some("rust".into()),
                size_bytes: 18,
            },
            ScannedFile {
                relative_path: "b.rs".into(),
                absolute_path: fp_b,
                language: Some("rust".into()),
                size_bytes: 16,
            },
        ];

        let mut parse_results = HashMap::new();
        parse_results.insert(
            "a.rs".to_string(),
            ParseResult {
                symbols: vec![Symbol {
                    name: "alpha".to_string(),
                    kind: SymbolKind::Function,
                    visibility: Visibility::Public,
                    signature: "pub fn alpha()".to_string(),
                    body: "{}".to_string(),
                    start_line: 1,
                    end_line: 1,
                }],
                imports: vec![],
                exports: vec![],
            },
        );
        parse_results.insert(
            "b.rs".to_string(),
            ParseResult {
                symbols: vec![Symbol {
                    name: "beta".to_string(),
                    kind: SymbolKind::Function,
                    visibility: Visibility::Public,
                    signature: "pub fn beta()".to_string(),
                    body: "{}".to_string(),
                    start_line: 1,
                    end_line: 1,
                }],
                imports: vec![],
                exports: vec![],
            },
        );

        let index = CodebaseIndex::build(files, parse_results, &counter);
        let (section, _tokens) = extract_public_symbols(&index, None);

        // Verify sorted order: higher pagerank first (or at least stable order is maintained).
        let pageranks: Vec<f64> = section.by_file.iter().map(|f| f.pagerank).collect();
        for i in 1..pageranks.len() {
            assert!(
                pageranks[i - 1] >= pageranks[i],
                "files should be sorted by pagerank descending"
            );
        }
    }

    #[test]
    fn test_focus_filter() {
        let index = make_index_with_symbols();
        // With focus "src/api", only api.rs should be included.
        let (section, _tokens) = extract_public_symbols(&index, Some("src/api"));
        assert_eq!(section.by_file.len(), 1);
        assert!(section.by_file[0].path.starts_with("src/api"));

        // With a non-matching focus, no files.
        let (section_empty, _) = extract_public_symbols(&index, Some("lib/"));
        assert_eq!(section_empty.total, 0);
        assert!(section_empty.by_file.is_empty());
    }

    // --- Route detection tests ---

    #[test]
    fn test_detect_routes_express() {
        let content = r#"app.get('/users', handler); router.post("/items", create);"#;
        let routes = detect_routes(content, "routes/index.js");
        assert_eq!(routes.len(), 2);
        assert_eq!(routes[0].method, "GET");
        assert_eq!(routes[0].path, "/users");
        assert_eq!(routes[1].method, "POST");
        assert_eq!(routes[1].path, "/items");
    }

    #[test]
    fn test_detect_routes_flask() {
        let content = r#"@app.route('/home')
@blueprint.get('/api/data')"#;
        let routes = detect_routes(content, "app.py");
        assert_eq!(routes.len(), 2);
        assert_eq!(routes[0].method, "GET");
        assert_eq!(routes[0].path, "/home");
        assert_eq!(routes[1].method, "GET");
        assert_eq!(routes[1].path, "/api/data");
    }

    #[test]
    fn test_detect_routes_django() {
        let content = r#"path('users/', views.user_list)"#;
        // Only matches when file_path contains "urls"
        let routes_no_match = detect_routes(content, "app/views.py");
        assert_eq!(routes_no_match.len(), 0);

        let routes = detect_routes(content, "app/urls.py");
        assert_eq!(routes.len(), 1);
        assert_eq!(routes[0].path, "/users/");
    }

    #[test]
    fn test_detect_routes_fastapi() {
        let content = r#"@app.get("/users")
@router.post("/items")"#;
        let routes = detect_routes(content, "main.py");
        assert_eq!(routes.len(), 2);
        assert_eq!(routes[0].method, "GET");
        assert_eq!(routes[0].path, "/users");
        assert_eq!(routes[1].method, "POST");
        assert_eq!(routes[1].path, "/items");
    }

    #[test]
    fn test_detect_routes_spring() {
        let content = r#"@GetMapping("/users")
@PostMapping("/users")
@RequestMapping("/api")"#;
        let routes = detect_routes(content, "UserController.java");
        assert_eq!(routes.len(), 3);
        assert_eq!(routes[0].method, "GET");
        assert_eq!(routes[0].path, "/users");
        assert_eq!(routes[1].method, "POST");
        assert_eq!(routes[1].path, "/users");
        assert_eq!(routes[2].method, "GET");
        assert_eq!(routes[2].path, "/api");
    }

    #[test]
    fn test_detect_routes_actix() {
        let content = r#"#[get("/health")]
#[post("/login")]"#;
        let routes = detect_routes(content, "src/main.rs");
        assert_eq!(routes.len(), 2);
        assert_eq!(routes[0].method, "GET");
        assert_eq!(routes[0].path, "/health");
        assert_eq!(routes[1].method, "POST");
        assert_eq!(routes[1].path, "/login");
    }

    #[test]
    fn test_detect_routes_axum() {
        let content = r#"Router::new().route("/users", get(list_users)).route("/users/:id", post(create_user))"#;
        let routes = detect_routes(content, "src/server.rs");
        assert_eq!(routes.len(), 2);
        assert_eq!(routes[0].path, "/users");
        assert_eq!(routes[1].path, "/users/:id");
    }

    #[test]
    fn test_detect_routes_gin() {
        let content = r#"r.GET("/ping", pingHandler)
router.POST("/users", createUser)"#;
        let routes = detect_routes(content, "main.go");
        assert_eq!(routes.len(), 2);
        assert_eq!(routes[0].method, "GET");
        assert_eq!(routes[0].path, "/ping");
        assert_eq!(routes[1].method, "POST");
        assert_eq!(routes[1].path, "/users");
    }

    #[test]
    fn test_detect_routes_echo() {
        let content = r#"e.GET("/users", getUsers)
g.POST("/items", createItem)
echo.DELETE("/users/:id", deleteUser)"#;
        let routes = detect_routes(content, "server.go");
        assert_eq!(routes.len(), 3);
        assert_eq!(routes[0].method, "GET");
        assert_eq!(routes[0].path, "/users");
        assert_eq!(routes[1].method, "POST");
        assert_eq!(routes[1].path, "/items");
        assert_eq!(routes[2].method, "DELETE");
        assert_eq!(routes[2].path, "/users/:id");
    }

    #[test]
    fn test_detect_routes_rails() {
        let content = r#"get '/users', to: 'users#index'
post "/items", to: 'items#create'"#;
        // Only matches when file_path contains "routes"
        let routes_no = detect_routes(content, "app/controllers/users_controller.rb");
        assert_eq!(routes_no.len(), 0);

        let routes = detect_routes(content, "config/routes.rb");
        assert_eq!(routes.len(), 2);
        assert_eq!(routes[0].method, "GET");
        assert_eq!(routes[0].path, "/users");
        assert_eq!(routes[1].method, "POST");
        assert_eq!(routes[1].path, "/items");
    }

    #[test]
    fn test_detect_routes_aspnet() {
        let content = r#"[HttpGet("/api/users")]
[HttpPost("/api/items")]
[Route("/api/health")]"#;
        let routes = detect_routes(content, "Controllers/UsersController.cs");
        assert_eq!(routes.len(), 3);
        assert_eq!(routes[0].method, "GET");
        assert_eq!(routes[0].path, "/api/users");
        assert_eq!(routes[1].method, "POST");
        assert_eq!(routes[1].path, "/api/items");
    }

    #[test]
    fn test_detect_routes_phoenix() {
        let content = r#"get "/users", UserController, :index
post "/items", ItemController, :create"#;
        // Only matches when file_path contains "router"
        let routes_no = detect_routes(content, "lib/my_app/controllers/user_controller.ex");
        assert_eq!(routes_no.len(), 0);

        let routes = detect_routes(content, "lib/my_app_web/router.ex");
        assert_eq!(routes.len(), 2);
        assert_eq!(routes[0].method, "GET");
        assert_eq!(routes[0].path, "/users");
        assert_eq!(routes[1].method, "POST");
        assert_eq!(routes[1].path, "/items");
    }

    #[test]
    fn test_detect_routes_no_match() {
        let content = r#"// This is a comment
fn regular_function() {}
let x = 42;
"#;
        let routes = detect_routes(content, "src/util.rs");
        assert_eq!(
            routes.len(),
            0,
            "non-route strings should produce no results"
        );
    }
}