knot 1.6.1

Codebase Graph + Vector RAG Indexer for Java, TypeScript, JavaScript, Kotlin, Rust, Python, Groovy, C/C++, Build Systems, and HTML/CSS codebases
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
//! Stage 2 — Parse: AST extraction via Tree-sitter + Rayon.
//!
//! Each source file is parsed in parallel on the Rayon thread pool.
//! Tree-sitter queries extract class declarations, method/function declarations,
//! associated documentation comments, and call-site references.
//!
//! # Custom queries
//! Built-in queries are compiled into the binary at build time (see `queries/`
//! directory). When [`ParseConfig::custom_queries_path`] is set, the parser
//! will instead load `java.scm` and `typescript.scm` from that directory,
//! allowing callers to override extraction logic without recompiling.

use anyhow::{Context, Result};
use std::{
    fs,
    path::{Path, PathBuf},
};
use tracing::{debug, warn};

use crate::models::ParsedEntity;
use tokio::sync::mpsc;

mod comments;
mod context;
pub(crate) mod extractor;
pub mod languages;
mod orphans;
mod utils;

#[cfg(test)]
mod test_utils;

// Built-in query files compiled into the binary.
const DEFAULT_JAVA_QUERY: &str = include_str!("../../../queries/java.scm");
const DEFAULT_KOTLIN_QUERY: &str = include_str!("../../../queries/kotlin.scm");
const DEFAULT_TS_QUERY: &str = include_str!("../../../queries/typescript.scm");
const DEFAULT_TSX_QUERY: &str = include_str!("../../../queries/tsx.scm");
const DEFAULT_JS_QUERY: &str = include_str!("../../../queries/javascript.scm");
#[expect(dead_code, reason = "reserved for future query-based HTML parsing")]
const DEFAULT_HTML_QUERY: &str = include_str!("../../../queries/html.scm");
const DEFAULT_CSS_QUERY: &str = include_str!("../../../queries/css.scm");
const DEFAULT_SCSS_QUERY: &str = include_str!("../../../queries/scss.scm");
const DEFAULT_RUST_QUERY: &str = include_str!("../../../queries/rust.scm");
const DEFAULT_PYTHON_QUERY: &str = include_str!("../../../queries/python.scm");
const DEFAULT_C_QUERY: &str = include_str!("../../../queries/c.scm");
const DEFAULT_CPP_QUERY: &str = include_str!("../../../queries/cpp.scm");
const DEFAULT_MD_QUERY: &str = include_str!("../../../queries/markdown.scm");

/// Configuration for the parse stage.
#[derive(Clone)]
pub struct ParseConfig {
    pub repo_root: PathBuf,
    /// Optional filesystem path to a directory containing custom `.scm` query files.
    pub custom_queries_path: Option<String>,
    /// Logical repository name for multi-repository isolation.
    pub repo_name: String,
    /// Whether to index configuration files (YAML, JSON, .properties) and
    /// Kubernetes/Helm manifests. When `false`, these files produce no entities.
    pub include_config_files: bool,
    /// Filesystem root of the repository being indexed. Required by Rust
    /// post-processing to discover `Cargo.toml` files and compute crate
    /// qualified FQNs (e.g. `crate_a::config::Config`). When `None`, Rust
    /// FQNs fall back to their bare-name form.
    pub repo_path: Option<String>,
}

impl Default for ParseConfig {
    fn default() -> Self {
        Self {
            repo_root: PathBuf::from("."),
            custom_queries_path: None,
            repo_name: String::new(),
            include_config_files: false,
            repo_path: None,
        }
    }
}

/// Callback invoked exactly once per input file after the file has been
/// fully processed (all entities sent to the channel, or parse failed).
pub type FileParsedCallback = std::sync::Arc<dyn Fn() + Send + Sync>;

/// Parse a collection of source files in parallel and send results through a channel.
///
/// Uses `std::thread::scope` with raw OS threads (NOT Rayon) so that
/// `blocking_send` on the bounded channel only blocks the dedicated
/// parsing thread rather than a shared thread pool. This prevents
/// deadlocks with `fastembed` which requires Rayon for tokenization.
///
/// This function blocks until all files have been processed. It is
/// intended to be called from a `tokio::task::spawn_blocking` context.
pub fn parse_files_stream(
    files: &[PathBuf],
    parse_cfg: &ParseConfig,
    sender: mpsc::Sender<ParsedEntity>,
    max_concurrent: usize,
    on_file_parsed: Option<FileParsedCallback>,
) {
    use std::sync::{Arc, Condvar, Mutex};

    // Concurrency limiter: Condvar-based semaphore backed by a Mutex.
    let sem = Arc::new((Mutex::new(0usize), Condvar::new()));

    // Collect entities into a shared buffer so we can run a global post-parse
    // aggregation step (e.g. Varnish built-in sub aggregators) before sending
    // them down the pipeline.
    let buffer: Arc<Mutex<Vec<ParsedEntity>>> = Arc::new(Mutex::new(Vec::new()));

    std::thread::scope(|s| {
        for path in files {
            let path = path.clone();
            let parse_cfg = parse_cfg.clone();
            let sem = Arc::clone(&sem);
            let buffer = Arc::clone(&buffer);

            // Acquire: block until active < max_concurrent
            {
                let (lock, cvar) = &*sem;
                let mut active = lock.lock().unwrap();
                while *active >= max_concurrent {
                    active = cvar.wait(active).unwrap();
                }
                *active += 1;
            }

            let on_file_parsed = on_file_parsed.clone();

            s.spawn(move || {
                if let Ok(entities) = parse_single_file(&path, &parse_cfg) {
                    let mut buf = buffer.lock().unwrap();
                    buf.extend(entities);
                }

                if let Some(cb) = &on_file_parsed {
                    cb();
                }

                // Release: decrement active count and wake waiter
                let (lock, cvar) = &*sem;
                let mut active = lock.lock().unwrap();
                *active -= 1;
                cvar.notify_one();
            });
        }
    });
    // All threads joined here (std::thread::scope guarantees this).

    // Post-parse: aggregate Varnish built-in subs globally.
    let mut entities = Arc::try_unwrap(buffer)
        .map(|m| m.into_inner().unwrap_or_default())
        .unwrap_or_default();
    languages::varnish::aggregate_varnish_builtin_subs(&mut entities, &parse_cfg.repo_name);

    for entity in entities {
        if sender.blocking_send(entity).is_err() {
            warn!("Failed to send entity to channel");
            break;
        }
    }
}

/// Parse a collection of source files in parallel and return all extracted entities.
///
/// Uses `parse_files_stream` internally. This is a convenience wrapper for
/// callers that want the full Vec instead of streaming through a channel.
pub fn parse_files(files: &[PathBuf], parse_cfg: &ParseConfig) -> Vec<ParsedEntity> {
    let (tx, mut rx) = mpsc::channel(1024);
    let cpus = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(4);

    parse_files_stream(files, parse_cfg, tx, cpus, None);

    let mut entities = Vec::with_capacity(1024);
    while let Ok(entity) = rx.try_recv() {
        entities.push(entity);
    }

    // Post-process Varnish built-in sub aggregators globally.
    languages::varnish::aggregate_varnish_builtin_subs(&mut entities, &parse_cfg.repo_name);

    entities
}

/// Parse a single source file and return its extracted entities.
/// Heuristic: detect whether a `.h` header contains C++ syntax.
/// Scans for keywords exclusive to C++ that do not appear in valid C.
fn is_cpp_header(source: &str) -> bool {
    let cpp_indicators = [
        "class ",
        "namespace ",
        "template<",
        "template <",
        "virtual ",
        "public:",
        "private:",
        "protected:",
        "using namespace",
        "constexpr ",
        "noexcept",
        "nullptr",
        "override",
        " final",
        "::", // qualified calls like Print::write(...)
    ];
    cpp_indicators.iter().any(|kw| source.contains(kw))
}

#[expect(
    clippy::too_many_lines,
    reason = "function is verbose but correct — extraction deferred"
)]
#[expect(
    clippy::cognitive_complexity,
    reason = "function is verbose but correct — extraction deferred"
)]
fn parse_single_file(path: &Path, parse_cfg: &ParseConfig) -> Result<Vec<ParsedEntity>> {
    let source = {
        let bytes =
            fs::read(path).with_context(|| format!("Cannot read file: {}", path.display()))?;
        String::from_utf8_lossy(&bytes).into_owned()
    };

    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or_default();

    // Handle files identified by name (no extension), e.g. Jenkinsfile
    let filename = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or_default();

    let file_path = crate::pipeline::files::to_repo_relative(path, &parse_cfg.repo_root);

    // Dispatch by filename first for extensionless files
    if filename == "Jenkinsfile" {
        return Ok(languages::jenkins::extract_entities_jenkins(
            &source,
            &file_path,
            &parse_cfg.repo_name,
        ));
    }

    let entities = match ext {
        "java" => {
            let query_src = load_query_source("java.scm", DEFAULT_JAVA_QUERY, parse_cfg);
            extractor::extract_entities(
                &source,
                tree_sitter_java::LANGUAGE.into(),
                &query_src,
                "java",
                &file_path,
                &parse_cfg.repo_name,
            )?
        }
        "kt" | "kts" => {
            let query_src = load_query_source("kotlin.scm", DEFAULT_KOTLIN_QUERY, parse_cfg);
            extractor::extract_entities(
                &source,
                tree_sitter_kotlin_ng::LANGUAGE.into(),
                &query_src,
                "kotlin",
                &file_path,
                &parse_cfg.repo_name,
            )?
        }
        "ts" | "tsx" | "cts" => {
            let mut query_src = load_query_source("typescript.scm", DEFAULT_TS_QUERY, parse_cfg);
            let lang: tree_sitter::Language = if ext == "tsx" {
                // For TSX files, append TSX-specific rules (JSX component invocations)
                let tsx_rules = load_query_source("tsx.scm", DEFAULT_TSX_QUERY, parse_cfg);
                query_src.push('\n');
                query_src.push_str(&tsx_rules);
                tree_sitter_typescript::LANGUAGE_TSX.into()
            } else {
                tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()
            };
            extractor::extract_entities(
                &source,
                lang,
                &query_src,
                "typescript",
                &file_path,
                &parse_cfg.repo_name,
            )?
        }
        "js" | "mjs" | "cjs" | "jsx" => {
            let query_src = load_query_source("javascript.scm", DEFAULT_JS_QUERY, parse_cfg);
            let lang: tree_sitter::Language = tree_sitter_javascript::LANGUAGE.into();
            extractor::extract_entities(
                &source,
                lang,
                &query_src,
                "javascript",
                &file_path,
                &parse_cfg.repo_name,
            )?
        }
        "html" | "htm" => {
            let mut parser = tree_sitter::Parser::new();
            parser
                .set_language(&tree_sitter_html::LANGUAGE.into())
                .context("Failed to load HTML grammar")?;
            let tree = parser
                .parse(&source, None)
                .context("Failed to parse HTML")?;
            languages::html::extract_entities_html(
                tree.root_node(),
                source.as_bytes(),
                &file_path,
                &parse_cfg.repo_name,
            )
        }
        "yml" | "yaml" => {
            if !parse_cfg.include_config_files {
                Vec::new()
            } else {
                dispatch_yaml(&source, path, &file_path, &parse_cfg.repo_name)
            }
        }
        "json" => {
            if !parse_cfg.include_config_files
                && filename != "package.json"
                && filename != "tsconfig.json"
            {
                Vec::new()
            } else {
                languages::json_config::extract_entities_json_config(
                    &source,
                    &file_path,
                    &parse_cfg.repo_name,
                )
            }
        }
        "properties" => {
            if !parse_cfg.include_config_files {
                Vec::new()
            } else {
                languages::properties::extract_entities_properties(
                    &source,
                    &file_path,
                    &parse_cfg.repo_name,
                )
            }
        }
        "tpl" => {
            if !parse_cfg.include_config_files {
                Vec::new()
            } else {
                let chart_name = detect_chart_name(path, &parse_cfg.repo_root);
                languages::helm::extract_helm_template(
                    &source,
                    &file_path,
                    &parse_cfg.repo_name,
                    &chart_name,
                )
            }
        }
        "css" => {
            let query_src = load_query_source("css.scm", DEFAULT_CSS_QUERY, parse_cfg);
            extractor::extract_entities(
                &source,
                tree_sitter_css::LANGUAGE.into(),
                &query_src,
                "css",
                &file_path,
                &parse_cfg.repo_name,
            )?
        }
        "scss" | "sass" => {
            let query_src = load_query_source("scss.scm", DEFAULT_SCSS_QUERY, parse_cfg);
            extractor::extract_entities(
                &source,
                tree_sitter_scss::language(),
                &query_src,
                "scss",
                &file_path,
                &parse_cfg.repo_name,
            )?
        }
        "py" | "pyi" | "pyw" => {
            let query_src = load_query_source("python.scm", DEFAULT_PYTHON_QUERY, parse_cfg);
            extractor::extract_entities(
                &source,
                tree_sitter_python::LANGUAGE.into(),
                &query_src,
                "python",
                &file_path,
                &parse_cfg.repo_name,
            )?
        }
        "rs" => {
            let query_src = load_query_source("rust.scm", DEFAULT_RUST_QUERY, parse_cfg);
            let mut rust_entities = extractor::extract_entities(
                &source,
                tree_sitter_rust::LANGUAGE.into(),
                &query_src,
                "rust",
                &file_path,
                &parse_cfg.repo_name,
            )?;
            languages::rust::qualify_rust_fqns(
                &mut rust_entities,
                &file_path,
                parse_cfg.repo_path.as_deref(),
                Some(&source),
            );
            rust_entities
        }
        "c" => {
            let query_src = load_query_source("c.scm", DEFAULT_C_QUERY, parse_cfg);
            extractor::extract_entities(
                &source,
                tree_sitter_c::LANGUAGE.into(),
                &query_src,
                "c",
                &file_path,
                &parse_cfg.repo_name,
            )?
        }
        "h" => {
            if is_cpp_header(&source) {
                let query_src = load_query_source("cpp.scm", DEFAULT_CPP_QUERY, parse_cfg);
                extractor::extract_entities(
                    &source,
                    tree_sitter_cpp::LANGUAGE.into(),
                    &query_src,
                    "cpp",
                    &file_path,
                    &parse_cfg.repo_name,
                )?
            } else {
                let query_src = load_query_source("c.scm", DEFAULT_C_QUERY, parse_cfg);
                extractor::extract_entities(
                    &source,
                    tree_sitter_c::LANGUAGE.into(),
                    &query_src,
                    "c",
                    &file_path,
                    &parse_cfg.repo_name,
                )?
            }
        }
        "cpp" | "cxx" | "cc" | "hpp" | "hxx" | "hh" => {
            let query_src = load_query_source("cpp.scm", DEFAULT_CPP_QUERY, parse_cfg);
            extractor::extract_entities(
                &source,
                tree_sitter_cpp::LANGUAGE.into(),
                &query_src,
                "cpp",
                &file_path,
                &parse_cfg.repo_name,
            )?
        }
        "groovy" => {
            languages::groovy::extract_entities_groovy(&source, &file_path, &parse_cfg.repo_name)
        }
        "gradle" => {
            languages::gradle::extract_entities_gradle(&source, &file_path, &parse_cfg.repo_name)
        }
        "jenkinsfile" => {
            languages::jenkins::extract_entities_jenkins(&source, &file_path, &parse_cfg.repo_name)
        }
        "xml" => languages::xml::extract_entities_xml(&source, &file_path, &parse_cfg.repo_name),
        "toml" => languages::toml::extract_entities_toml(&source, &file_path, &parse_cfg.repo_name),
        "md" | "markdown" => {
            let query_src = load_query_source("markdown.scm", DEFAULT_MD_QUERY, parse_cfg);
            extractor::extract_entities(
                &source,
                tree_sitter_md::LANGUAGE.into(),
                &query_src,
                "markdown",
                &file_path,
                &parse_cfg.repo_name,
            )?
        }
        "vcl" => {
            languages::varnish::extract_entities_vcl(&source, &file_path, &parse_cfg.repo_name)
        }
        "vtc" => {
            languages::varnish::extract_entities_vtc(&source, &file_path, &parse_cfg.repo_name)
        }
        "vcc" => {
            languages::varnish::extract_entities_vcc(&source, &file_path, &parse_cfg.repo_name)
        }
        other => {
            warn!("Unsupported extension '{other}', skipping");
            vec![]
        }
    };

    debug!("Extracted {} entities from {}", entities.len(), file_path);
    Ok(entities)
}

/// Dispatch YAML files to the appropriate parser based on content.
fn dispatch_yaml(
    source: &str,
    absolute_path: &Path,
    relative_path: &str,
    repo_name: &str,
) -> Vec<ParsedEntity> {
    let filename = absolute_path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("");

    // 1. Is it Chart.yaml?
    if filename == "Chart.yaml" {
        return languages::helm::extract_chart_yaml(source, relative_path, repo_name);
    }

    // 2. Is it inside a Helm chart directory?
    if is_in_helm_chart_dir(absolute_path) {
        if filename == "values.yaml" || filename == "values.yml" {
            let chart_name = detect_chart_name(
                absolute_path,
                absolute_path.parent().unwrap_or(Path::new(".")),
            );
            return languages::helm::extract_values_yaml(
                source,
                relative_path,
                repo_name,
                &chart_name,
            );
        }
        if is_in_templates_dir(absolute_path) {
            let chart_name = detect_chart_name(
                absolute_path,
                absolute_path.parent().unwrap_or(Path::new(".")),
            );
            return languages::helm::extract_helm_template(
                source,
                relative_path,
                repo_name,
                &chart_name,
            );
        }
    }

    // 3. Is it a K8s manifest? (has apiVersion + kind at root level)
    if let Ok(yaml) = serde_yaml::from_str::<serde_yaml::Value>(source)
        && yaml.get("apiVersion").is_some()
        && yaml.get("kind").is_some()
    {
        return languages::kubernetes::extract_entities_k8s(source, relative_path, repo_name);
    }

    // 4. Default: generic configuration YAML
    languages::yaml::extract_entities_yaml(source, relative_path, repo_name)
}

/// Check if the file is inside a Helm chart directory by looking for Chart.yaml in parent dirs.
///
/// `absolute_path` must be an absolute filesystem path — the function uses
/// `.exists()` on each ancestor, which resolves against the **process CWD**
/// for relative inputs. Callers in the pipeline always have the absolute
/// path from `discover_files`; only the **persisted** entity `file_path`
/// is relative.
fn is_in_helm_chart_dir(absolute_path: &Path) -> bool {
    let mut current = absolute_path.parent();

    while let Some(dir) = current {
        if dir.join("Chart.yaml").exists() {
            return true;
        }
        current = dir.parent();
    }
    false
}

/// Check if the file is inside a templates directory (Helm convention).
fn is_in_templates_dir(absolute_path: &Path) -> bool {
    let mut current = Some(absolute_path);

    while let Some(p) = current {
        if p.file_name().and_then(|n| n.to_str()) == Some("templates") {
            return true;
        }
        current = p.parent();
    }
    false
}

/// Detect the Helm chart name from the nearest Chart.yaml or directory name.
///
/// `absolute_path` must be an absolute filesystem path (see
/// `is_in_helm_chart_dir`). The `repo_root` parameter is currently unused
/// but kept for future disambiguation if multiple Chart.yamls are reachable.
fn detect_chart_name(absolute_path: &Path, _repo_root: &Path) -> String {
    let mut current = absolute_path.parent();

    while let Some(dir) = current {
        let chart_yaml = dir.join("Chart.yaml");
        if chart_yaml.exists() {
            if let Ok(source) = fs::read_to_string(&chart_yaml)
                && let Ok(yaml) = serde_yaml::from_str::<serde_yaml::Value>(&source)
                && let Some(name) = yaml.get("name").and_then(|v| v.as_str())
            {
                return name.to_string();
            }
            break;
        }
        current = dir.parent();
    }

    // Fall back to parent directory name
    absolute_path
        .parent()
        .and_then(|p| p.file_name())
        .and_then(|n| n.to_str())
        .unwrap_or("unknown")
        .to_string()
}

/// Return the query source string, preferring a custom file when available.
#[expect(
    clippy::cognitive_complexity,
    reason = "function is verbose but correct — extraction deferred"
)]
fn load_query_source(filename: &str, default: &str, cfg: &ParseConfig) -> String {
    if let Some(dir) = &cfg.custom_queries_path {
        let custom_path = PathBuf::from(dir).join(filename);
        if custom_path.exists() {
            match fs::read_to_string(&custom_path) {
                Ok(src) => {
                    tracing::info!("Using custom query: {}", custom_path.display());
                    return src;
                }
                Err(e) => warn!(
                    "Failed to load custom query {}: {e} — using built-in",
                    custom_path.display()
                ),
            }
        }
    }
    default.to_owned()
}

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

    #[test]
    fn test_parse_config_creation() {
        let cfg = ParseConfig {
            custom_queries_path: None,
            repo_name: "test-repo".to_string(),
            include_config_files: true,
            repo_path: None,
            ..Default::default()
        };

        assert_eq!(cfg.repo_name, "test-repo");
        assert!(cfg.custom_queries_path.is_none());
    }

    #[test]
    fn test_parse_config_with_custom_queries() {
        let cfg = ParseConfig {
            custom_queries_path: Some("/custom/queries".to_string()),
            repo_name: "my-repo".to_string(),
            include_config_files: true,
            repo_path: None,
            ..Default::default()
        };

        assert_eq!(cfg.repo_name, "my-repo");
        assert_eq!(cfg.custom_queries_path, Some("/custom/queries".to_string()));
    }

    #[test]
    fn test_load_query_source_uses_default() {
        let cfg = ParseConfig {
            custom_queries_path: None,
            repo_name: "test-repo".to_string(),
            include_config_files: true,
            repo_path: None,
            ..Default::default()
        };

        let default_query = "MATCH (n) RETURN n";
        let result = load_query_source("test.scm", default_query, &cfg);

        assert_eq!(result, default_query);
    }

    #[test]
    fn test_load_query_source_nonexistent_custom_path() {
        let cfg = ParseConfig {
            custom_queries_path: None,
            repo_name: "test-repo".to_string(),
            include_config_files: true,
            repo_path: None,
            ..Default::default()
        };

        let default_query = "MATCH (n) RETURN n";
        let result = load_query_source("test.scm", default_query, &cfg);

        // Should fall back to default when custom path doesn't exist
        assert_eq!(result, default_query);
    }

    #[test]
    fn test_parse_files_empty_list() {
        let cfg = ParseConfig {
            custom_queries_path: None,
            repo_name: "test-repo".to_string(),
            include_config_files: true,
            repo_path: None,
            ..Default::default()
        };

        let files: Vec<PathBuf> = vec![];
        let (sender, mut receiver) = mpsc::channel::<ParsedEntity>(32);

        parse_files_stream(&files, &cfg, sender, 4, None);

        // No files to parse, channel should receive nothing
        assert!(receiver.try_recv().is_err());
    }

    #[test]
    fn test_parse_files_with_mock_channel() {
        let cfg = ParseConfig {
            custom_queries_path: None,
            repo_name: "test-repo".to_string(),
            include_config_files: true,
            repo_path: None,
            ..Default::default()
        };

        // Use an empty list since we can't create real files in unit tests
        let files: Vec<PathBuf> = vec![];
        let (sender, mut receiver) = mpsc::channel::<ParsedEntity>(32);

        parse_files_stream(&files, &cfg, sender, 4, None);

        // Verify channel can receive messages (simulated)
        assert!(receiver.try_recv().is_err()); // No data sent
    }

    #[test]
    fn test_is_cpp_header_detects_class() {
        assert!(is_cpp_header(
            "class Print {\npublic:\n    void write();\n};"
        ));
    }

    #[test]
    fn test_is_cpp_header_detects_namespace() {
        assert!(is_cpp_header("namespace Engine {\n    class Foo {};\n}"));
    }

    #[test]
    fn test_is_cpp_header_detects_virtual() {
        assert!(is_cpp_header("virtual size_t write(uint8_t) = 0;"));
    }

    #[test]
    fn test_is_cpp_header_detects_template() {
        assert!(is_cpp_header("template <typename T>\nclass Container {};"));
    }

    #[test]
    fn test_is_cpp_header_pure_c_returns_false() {
        let c_header = r#"
#ifndef FOO_H
#define FOO_H
typedef struct { int x; int y; } Point;
void foo(int n);
int bar(const char *s);
#endif
"#;
        assert!(!is_cpp_header(c_header));
    }

    #[test]
    fn test_is_cpp_header_empty_returns_false() {
        assert!(!is_cpp_header(""));
    }

    #[test]
    fn test_is_cpp_header_detects_qualified_call() {
        assert!(is_cpp_header(
            "size_t Print::write(const uint8_t *buf, size_t s) { return 0; }"
        ));
    }

    #[test]
    fn test_unsupported_file_extension_handling() {
        // Test extension detection logic
        let path = PathBuf::from("/test/file.unsupported");
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or_default();

        assert_eq!(ext, "unsupported");
        // File would be skipped (not java, ts, tsx, cts, js, mjs, cjs, jsx)
        assert!(
            ext != "java"
                && ext != "ts"
                && ext != "tsx"
                && ext != "cts"
                && ext != "js"
                && ext != "mjs"
                && ext != "cjs"
                && ext != "jsx"
        );
    }

    #[test]
    fn test_java_file_extension_detection() {
        let path = PathBuf::from("/test/Service.java");
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or_default();

        assert_eq!(ext, "java");
    }

    fn assert_extensions_detected(extensions: &[&str]) {
        for ext_name in extensions {
            let path = PathBuf::from(format!("/test/file.{}", ext_name));
            let ext = path
                .extension()
                .and_then(|e| e.to_str())
                .unwrap_or_default();
            assert_eq!(ext, *ext_name);
        }
    }

    #[test]
    fn test_kotlin_file_extension_detection() {
        assert_extensions_detected(&["kt", "kts"]);
    }

    #[test]
    fn test_typescript_file_extension_detection() {
        assert_extensions_detected(&["ts", "tsx", "cts"]);
    }

    #[test]
    fn test_javascript_file_extension_detection() {
        assert_extensions_detected(&["js", "mjs", "cjs", "jsx"]);
    }

    #[test]
    fn test_file_path_conversion() {
        let parse_cfg = ParseConfig {
            repo_root: PathBuf::from("/home/user/project"),
            ..Default::default()
        };
        let path = PathBuf::from("/home/user/project/src/Main.java");
        let file_path = crate::pipeline::files::to_repo_relative(&path, &parse_cfg.repo_root);

        assert!(file_path.contains("Main.java"));
        assert_eq!(file_path, "src/Main.java");
    }

    // ---- §10.1 parser tests for relative file_path in entities ----

    #[test]
    fn test_parsed_entity_file_path_is_relative() {
        use tempfile::tempdir;
        let dir = tempdir().unwrap();
        let repo_root = dir.path().canonicalize().unwrap();

        // Create a minimal Java source file so the parser returns entities.
        let src_dir = repo_root.join("src");
        fs::create_dir_all(&src_dir).unwrap();
        let java_file = src_dir.join("Foo.java");
        fs::write(&java_file, "public class Foo { public void bar() {} }").unwrap();

        let parse_cfg = ParseConfig {
            repo_root: repo_root.clone(),
            custom_queries_path: None,
            repo_name: "test-repo".to_string(),
            include_config_files: false,
            repo_path: Some(repo_root.to_string_lossy().into_owned()),
        };

        let entities = parse_files(&[java_file], &parse_cfg);
        assert!(
            !entities.is_empty(),
            "parser should produce at least one entity for Foo.java"
        );
        for entity in &entities {
            assert!(
                !entity.file_path.starts_with('/'),
                "file_path must be relative (no leading /), got {}",
                entity.file_path
            );
            assert!(
                !entity.file_path.contains('\\'),
                "file_path must use POSIX separators, got {}",
                entity.file_path
            );
        }
        // The class `Foo` should carry file_path = "src/Foo.java".
        let foo = entities.iter().find(|e| e.name == "Foo").expect("Foo");
        assert_eq!(foo.file_path, "src/Foo.java");
    }

    #[test]
    fn test_parsed_entity_file_path_verbatim_without_repo_root() {
        // When `repo_path` is None the parser falls back to its original
        // behavior (path verbatim), protecting existing parser unit tests
        // that don't set up a repo root.
        use tempfile::tempdir;
        let dir = tempdir().unwrap();
        let java_file = dir.path().join("Main.java");
        fs::write(&java_file, "public class Main {}").unwrap();

        let parse_cfg = ParseConfig {
            // No canonical repo_root set in production — default (".") used.
            repo_root: PathBuf::from("."),
            custom_queries_path: None,
            repo_name: "test-repo".to_string(),
            include_config_files: false,
            repo_path: None,
        };

        let entities = parse_files(std::slice::from_ref(&java_file), &parse_cfg);
        // Without a repo_root, the parser cannot strip a prefix — it falls
        // back to the absolute path (R5). Existing unit tests that don't
        // set up a repo root continue to see the path they passed in.
        assert!(!entities.is_empty(), "parser must still produce entities");
        let main = entities.iter().find(|e| e.name == "Main").expect("Main");
        assert!(
            main.file_path.contains("Main.java"),
            "verbatim path should still contain the filename, got {}",
            main.file_path
        );
    }

    #[test]
    fn test_parse_config_repo_name_assignment() {
        let cfg = ParseConfig {
            custom_queries_path: None,
            repo_name: "myproject".to_string(),
            include_config_files: true,
            repo_path: None,
            ..Default::default()
        };

        let path = PathBuf::from("/src/Main.java");
        let _entities = parse_files(&[path], &cfg);

        // With empty/invalid files, should return empty vector
        // But repo_name should be preserved in config
        assert_eq!(cfg.repo_name, "myproject");
    }

    #[test]
    fn test_parse_files_with_empty_input() {
        let cfg = ParseConfig {
            custom_queries_path: None,
            repo_name: "test-repo".to_string(),
            include_config_files: true,
            repo_path: None,
            ..Default::default()
        };

        let files: Vec<PathBuf> = vec![];
        let entities = parse_files(&files, &cfg);

        // No files to parse, should return empty vector
        assert!(entities.is_empty());
    }

    #[test]
    fn test_channel_sender_behavior_mock() {
        // Test that bounded channel sender doesn't fail on empty input
        let (sender, mut receiver) = mpsc::channel::<ParsedEntity>(32);

        // Dropping sender without sending should not error
        drop(sender);

        // Receiver should get no data
        assert!(receiver.try_recv().is_err());
    }

    #[test]
    fn test_bounded_channel_blocking_send() {
        // Test that blocking_send works correctly with a bounded channel
        let (sender, mut receiver) = mpsc::channel::<ParsedEntity>(2);

        // Create a minimal entity for testing
        let entity = ParsedEntity::new(
            "TestEntity",
            crate::models::EntityKind::Class,
            "com.test.TestEntity",
            None,
            None,
            "java",
            "/test/Test.java",
            1,
            5,
            None,
            "test-repo",
        );

        // Send via blocking_send (simulating what parse_files_stream does)
        assert!(sender.blocking_send(entity.clone()).is_ok());
        assert!(sender.blocking_send(entity).is_ok());

        // Verify receiver gets both entities
        assert!(receiver.try_recv().is_ok());
        assert!(receiver.try_recv().is_ok());
    }

    #[test]
    fn test_bounded_channel_capacity_backpressure() {
        // Test that bounded channel respects capacity
        let (sender, _receiver) = mpsc::channel::<ParsedEntity>(2);

        let entity = ParsedEntity::new(
            "TestEntity",
            crate::models::EntityKind::Class,
            "com.test.TestEntity",
            None,
            None,
            "java",
            "/test/Test.java",
            1,
            5,
            None,
            "test-repo",
        );

        // Fill the channel to capacity
        assert!(sender.try_send(entity.clone()).is_ok());
        assert!(sender.try_send(entity.clone()).is_ok());

        // Third send should fail with Full error (channel is at capacity)
        assert!(sender.try_send(entity).is_err());
    }

    #[test]
    fn test_bounded_channel_receives_after_blocking_send() {
        // Verify that after blocking_send, data is available on the receiver
        let (sender, mut receiver) = mpsc::channel::<ParsedEntity>(1);

        let entity = ParsedEntity::new(
            "TestClass",
            crate::models::EntityKind::Class,
            "com.example.TestClass",
            Some("public class TestClass".to_string()),
            Some("A test class".to_string()),
            "java",
            "/proj/TestClass.java",
            10,
            25,
            None,
            "test-repo",
        );

        sender.blocking_send(entity).unwrap();

        let received = receiver.try_recv().unwrap();
        assert_eq!(received.name, "TestClass");
        assert_eq!(received.fqn, "com.example.TestClass");
        assert_eq!(received.language, "java");
    }

    #[test]
    fn test_parse_files_stream_callback_once_per_file() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use tempfile::tempdir;

        let dir = tempdir().unwrap();
        for i in 0..3 {
            fs::write(dir.path().join(format!("file_{}.rs", i)), "fn foo() {}").unwrap();
        }

        let files: Vec<PathBuf> = (0..3)
            .map(|i| dir.path().join(format!("file_{}.rs", i)))
            .collect();

        let cfg = ParseConfig {
            custom_queries_path: None,
            repo_name: "test-repo".to_string(),
            include_config_files: true,
            repo_path: None,
            ..Default::default()
        };

        let (sender, mut receiver) = mpsc::channel::<ParsedEntity>(32);
        let counter = std::sync::Arc::new(AtomicUsize::new(0));
        let counter_clone = std::sync::Arc::clone(&counter);
        let cb: FileParsedCallback = std::sync::Arc::new(move || {
            counter_clone.fetch_add(1, Ordering::SeqCst);
        });

        parse_files_stream(&files, &cfg, sender, 4, Some(cb));

        let mut count = 0;
        while receiver.try_recv().is_ok() {
            count += 1;
        }
        assert!(count > 0, "Should have extracted some entities");
        assert_eq!(counter.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn test_parse_files_stream_callback_counts_unparseable() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use tempfile::tempdir;

        let dir = tempdir().unwrap();
        fs::write(dir.path().join("valid.rs"), "fn foo() {}").unwrap();
        fs::write(dir.path().join("valid2.rs"), "enum Color { Red }").unwrap();
        fs::write(dir.path().join("broken.rs"), "not valid rust @@@@!!").unwrap();

        let files: Vec<PathBuf> = ["valid.rs", "valid2.rs", "broken.rs"]
            .iter()
            .map(|f| dir.path().join(f))
            .collect();

        let cfg = ParseConfig {
            custom_queries_path: None,
            repo_name: "test-repo".to_string(),
            include_config_files: true,
            repo_path: None,
            ..Default::default()
        };

        let (sender, _receiver) = mpsc::channel::<ParsedEntity>(32);
        let counter = std::sync::Arc::new(AtomicUsize::new(0));
        let counter_clone = std::sync::Arc::clone(&counter);
        let cb: FileParsedCallback = std::sync::Arc::new(move || {
            counter_clone.fetch_add(1, Ordering::SeqCst);
        });

        parse_files_stream(&files, &cfg, sender, 4, Some(cb));

        assert_eq!(counter.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn test_parse_files_stream_none_callback() {
        use tempfile::tempdir;

        let dir = tempdir().unwrap();
        fs::write(dir.path().join("test.rs"), "fn foo() {}").unwrap();
        let files: Vec<PathBuf> = vec![dir.path().join("test.rs")];

        let cfg = ParseConfig {
            custom_queries_path: None,
            repo_name: "test-repo".to_string(),
            include_config_files: true,
            repo_path: None,
            ..Default::default()
        };

        let (sender, mut receiver) = mpsc::channel::<ParsedEntity>(32);
        parse_files_stream(&files, &cfg, sender, 4, None);

        let mut count = 0;
        while receiver.try_recv().is_ok() {
            count += 1;
        }
        assert!(count > 0, "Should parse entities with None callback");
    }

    #[test]
    fn test_multiple_file_extensions_in_batch() {
        let files = [
            PathBuf::from("file1.java"),
            PathBuf::from("file2.ts"),
            PathBuf::from("file3.tsx"),
            PathBuf::from("file4.kt"),
            PathBuf::from("file5.unsupported"),
        ];

        let expected_extensions = ["java", "ts", "tsx", "kt", "unsupported"];

        for (file, expected_ext) in files.iter().zip(expected_extensions.iter()) {
            let ext = file
                .extension()
                .and_then(|e| e.to_str())
                .unwrap_or_default();
            assert_eq!(ext, *expected_ext);
        }
    }
}