ripvec-core 4.1.0

Semantic code + document search engine. Cacheless static-embedding + cross-encoder rerank by default; optional ModernBERT/BGE transformer engines with GPU backends. Tree-sitter chunking, hybrid BM25 + PageRank, composable ranking layers.
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
//! Per-language entry-point detection for the `find_dead_code` MCP tool
//! (4.1.0).
//!
//! The trait [`EntryPointDetector`] and its per-language implementors
//! ([`RustEntryDetector`], [`PythonEntryDetector`], [`GoEntryDetector`])
//! identify the syntactic shapes that act as roots of the call graph: the
//! BFS reachability walk for dead-code detection seeds from the union of
//! all [`EntryPoint`]s emitted across the indexed corpus.
//!
//! This module is X1 of the 4.1.0 series; the actual reachability walk and
//! cluster discovery (`RepoGraph::compute_dead_code`) lands in X2. The MCP
//! tool wrapper lands in X3. The remaining language detectors land in X4.
//! See `docs/FIND_DEAD_CODE_DESIGN.md` Section 2 for the per-language
//! entry-point survey and Section 3 for the algorithm that consumes this
//! output.
//!
//! ## Type B (Wired-Stub) self-audit note
//!
//! Until X2 lands, every public item in this module is consumed only from
//! the integration tests under `crates/ripvec-core/tests/entry_points.rs`.
//! `scripts/check_wiring_gaps.sh` will report these as Type B findings.
//! The findings are **explicitly deferred** to X2 — see the Section 9
//! PLAN.md entry — not silently dangling. Do not annotate with
//! `#[doc(hidden)]`: the doc-visibility surface is part of the X2 contract
//! and is the intended public API of the dead-code module.

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

use streaming_iterator::StreamingIterator;
use tree_sitter::{Node, Parser, Query, QueryCursor};

/// Classification of why a [`Definition`](crate::repo_map::Definition)-shaped
/// item is treated as an entry point for the dead-code reachability walk.
///
/// Categories follow Section 2 of `docs/FIND_DEAD_CODE_DESIGN.md`. The
/// classification is per-detection, not per-definition: the same
/// `pub fn` can appear as both [`EntryPointKind::Main`] (for binaries) and
/// [`EntryPointKind::LibraryExport`] (for libraries) depending on how the
/// containing crate is structured. Downstream consumers (X2) treat each
/// detection independently.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EntryPointKind {
    /// A binary-crate `main`-shaped entry: `fn main()` in Rust, `func main()`
    /// in Go, the `if __name__ == "__main__"` block in Python.
    Main,

    /// A public-API surface item: `pub` re-exports in Rust libraries,
    /// `__all__` exports in Python, capitalised names in Go libraries.
    LibraryExport,

    /// A test entry: `#[test]` / `#[bench]` in Rust, `def test_*` /
    /// `*_test.py` in Python, `func TestX` / `BenchmarkX` / `ExampleX` /
    /// `FuzzX` in Go.
    Test,

    /// A foreign-function-interface entry: `#[no_mangle]` /
    /// `extern "C"` in Rust, cgo `//export` in Go.
    Ffi,

    /// A procedural-macro entry: `#[proc_macro]`, `#[proc_macro_derive]`,
    /// `#[proc_macro_attribute]` in Rust.
    ProcMacro,

    /// A package-initialisation entry: `func init()` in Go.
    Init,

    /// A build-script entry: Cargo's `build.rs`.
    BuildScript,
}

/// A single entry-point detection in one source file.
///
/// Per-detection, not per-definition — the same `pub fn` can produce
/// multiple `EntryPoint` instances (one for each matching predicate).
/// Downstream consumers should treat each detection as an independent
/// reachability seed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EntryPoint {
    /// The symbol name of the entry point. For Rust this is the function
    /// item identifier; for Python it is the function or module-level
    /// expression name; for Go it is the function declaration identifier.
    pub name: String,

    /// Why this item was treated as an entry point.
    pub kind: EntryPointKind,

    /// The source file the entry point was detected in.
    pub file_path: PathBuf,

    /// 1-based line number of the entry point declaration. Matches the
    /// `start_line` field of [`crate::repo_map::Definition`].
    pub line: u32,
}

/// Per-language entry-point detector.
///
/// Designed for consumption by `RepoGraph::compute_dead_code` in
/// 4.1.0-X2. Until X2 lands, the only consumers are the integration tests
/// under `crates/ripvec-core/tests/entry_points.rs` — see the
/// module-level docstring for the Type B (Wired-Stub) self-audit note.
///
/// Implementations parse the source once per call. The parsing cost is
/// trivial (tree-sitter is O(n) and the source is already in memory at
/// detection time), and stateless parsers compose more cleanly than a
/// shared parser cache across the three (and eventually eleven) language
/// detectors. X2's `RepoGraph::compute_dead_code` already iterates
/// per-file, so the per-file parse adds no additional walk cost.
pub trait EntryPointDetector {
    /// Return every entry point declared in this source file.
    ///
    /// `source` is the full UTF-8 contents of `file_path`. The path is
    /// passed alongside `source` so detectors that consider filename
    /// patterns (e.g. Python's `test_*.py` and `*_test.py`,
    /// Rust's `build.rs`) can use both signals.
    ///
    /// If parsing fails, returns an empty vector — entry-point detection
    /// is best-effort and should never abort the dead-code walk.
    fn detect(&self, source: &str, file_path: &Path) -> Vec<EntryPoint>;
}

// ---------------------------------------------------------------------------
// Rust detector
// ---------------------------------------------------------------------------

/// Rust entry-point detector.
///
/// Detects (per `docs/FIND_DEAD_CODE_DESIGN.md` Section 2):
/// - `pub fn main()` and bare `fn main()` (Main)
/// - `pub fn` items in `lib.rs` / `mod.rs` (LibraryExport)
/// - Items annotated with `#[test]` or `#[bench]` (Test)
/// - Items annotated with `#[no_mangle]` or marked `extern "C"` (Ffi)
/// - Items annotated with `#[proc_macro]`, `#[proc_macro_derive]`, or
///   `#[proc_macro_attribute]` (ProcMacro)
/// - The entire `build.rs` file is treated as a single BuildScript entry
///   point (the build script's `main` is the cargo-known entry).
#[derive(Debug, Default, Clone, Copy)]
pub struct RustEntryDetector;

impl EntryPointDetector for RustEntryDetector {
    fn detect(&self, source: &str, file_path: &Path) -> Vec<EntryPoint> {
        let mut entries = Vec::new();
        let Some(tree) = parse_with(source, &tree_sitter_rust::LANGUAGE.into()) else {
            return entries;
        };
        let root = tree.root_node();
        let bytes = source.as_bytes();

        // Treat the entire build.rs file as a single BuildScript entry.
        // The crate's main may be named anything inside build.rs (cargo
        // calls the file's main), so we emit one entry at line 1.
        if file_path.file_name().and_then(|s| s.to_str()) == Some("build.rs") {
            entries.push(EntryPoint {
                name: "build.rs".to_string(),
                kind: EntryPointKind::BuildScript,
                file_path: file_path.to_path_buf(),
                line: 1,
            });
        }

        let is_lib_or_mod_rs = matches!(
            file_path.file_name().and_then(|s| s.to_str()),
            Some("lib.rs" | "mod.rs")
        );

        // Walk every function_item declaration recursively. For each item:
        //   - inspect its preceding attribute_item siblings for #[test],
        //     #[bench], #[no_mangle], #[proc_macro*]
        //   - inspect the function_item's own modifiers for `extern "C"`
        //   - inspect the name for `main`
        //   - if file is lib.rs/mod.rs and the item is `pub`, emit
        //     LibraryExport
        visit_rust_node(&root, bytes, file_path, is_lib_or_mod_rs, &mut entries);
        entries
    }
}

fn visit_rust_node(
    node: &Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    is_lib_or_mod_rs: bool,
    out: &mut Vec<EntryPoint>,
) {
    if node.kind() == "function_item" {
        rust_classify_function(node, bytes, file_path, is_lib_or_mod_rs, out);
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        visit_rust_node(&child, bytes, file_path, is_lib_or_mod_rs, out);
    }
}

fn rust_classify_function(
    node: &Node<'_>,
    bytes: &[u8],
    file_path: &Path,
    is_lib_or_mod_rs: bool,
    out: &mut Vec<EntryPoint>,
) {
    // Find the function name. function_item has a `name` field whose
    // value is an identifier child.
    let name_node = node.child_by_field_name("name");
    let Some(name_node) = name_node else { return };
    let Ok(name) = std::str::from_utf8(&bytes[name_node.start_byte()..name_node.end_byte()]) else {
        return;
    };
    let line = u32::try_from(node.start_position().row + 1).unwrap_or(u32::MAX);

    // Gather attributes that immediately precede this function. In
    // tree-sitter-rust the attributes are SIBLING attribute_item nodes,
    // not children of the function_item, so we walk previous siblings.
    let attrs = collect_preceding_rust_attrs(node, bytes);

    // A single function item may match multiple predicates (e.g. a
    // `#[no_mangle] pub extern "C" fn main` in `lib.rs` is both Ffi
    // and Main and LibraryExport). Emit one EntryPoint per matching
    // predicate; the BFS in X2 treats each detection as a distinct
    // reachability seed.

    // #[proc_macro], #[proc_macro_derive], #[proc_macro_attribute].
    if attrs.iter().any(|a| {
        a.starts_with("proc_macro_derive")
            || a.starts_with("proc_macro_attribute")
            || a == "proc_macro"
            || a.starts_with("proc_macro(")
    }) {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::ProcMacro,
            file_path: file_path.to_path_buf(),
            line,
        });
    }

    // #[test] / #[bench].
    if attrs.iter().any(|a| a == "test" || a == "bench") {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Test,
            file_path: file_path.to_path_buf(),
            line,
        });
    }

    // FFI: #[no_mangle] OR `extern "C"` in the function declaration.
    let function_text =
        std::str::from_utf8(&bytes[node.start_byte()..node.end_byte()]).unwrap_or("");
    let has_extern_c =
        rust_function_has_extern_c(node, bytes) || function_text.contains("extern \"C\"");
    if attrs.iter().any(|a| a == "no_mangle") || has_extern_c {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Ffi,
            file_path: file_path.to_path_buf(),
            line,
        });
    }

    // Main: `fn main` (with or without `pub`).
    if name == "main" {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Main,
            file_path: file_path.to_path_buf(),
            line,
        });
    }

    // LibraryExport: `pub fn` in lib.rs / mod.rs.
    if is_lib_or_mod_rs && rust_function_is_pub(node, bytes) {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::LibraryExport,
            file_path: file_path.to_path_buf(),
            line,
        });
    }
}

/// Collect the text of every `#[...]` attribute node that immediately
/// precedes this function_item in source order. The returned strings are
/// the attribute path/identifier (e.g. `"test"`, `"no_mangle"`,
/// `"proc_macro_derive(Foo)"`), with the leading `#[` and trailing `]`
/// stripped, and any leading `outer_attribute_item` `#[` punctuation
/// removed.
fn collect_preceding_rust_attrs(node: &Node<'_>, bytes: &[u8]) -> Vec<String> {
    let mut attrs = Vec::new();
    let mut prev = node.prev_sibling();
    while let Some(p) = prev {
        if p.kind() == "attribute_item" || p.kind() == "inner_attribute_item" {
            // The attribute_item child structure is `# [ attribute ]`;
            // pull the `attribute` child and use its text.
            let mut cursor = p.walk();
            let mut attr_text: Option<String> = None;
            for child in p.children(&mut cursor) {
                if child.kind() == "attribute"
                    && let Ok(text) =
                        std::str::from_utf8(&bytes[child.start_byte()..child.end_byte()])
                {
                    attr_text = Some(text.to_string());
                }
            }
            if let Some(t) = attr_text {
                attrs.push(t);
            }
            prev = p.prev_sibling();
        } else if p.kind().starts_with("line_comment") || p.kind().starts_with("block_comment") {
            prev = p.prev_sibling();
        } else {
            break;
        }
    }
    attrs
}

/// Return true if the function_item node has a `pub` visibility modifier.
fn rust_function_is_pub(node: &Node<'_>, bytes: &[u8]) -> bool {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "visibility_modifier"
            && let Ok(text) = std::str::from_utf8(&bytes[child.start_byte()..child.end_byte()])
        {
            return text.starts_with("pub");
        }
    }
    false
}

/// Return true if the function_item has an `extern "C"` ABI declaration
/// as a function-modifier child (e.g. `pub extern "C" fn bar()`).
fn rust_function_has_extern_c(node: &Node<'_>, bytes: &[u8]) -> bool {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        // tree-sitter-rust uses `function_modifiers` containing
        // `extern_modifier`; the latter's child is a `string_literal`
        // with the ABI name.
        if child.kind() != "function_modifiers" {
            continue;
        }
        let mut inner = child.walk();
        for grandchild in child.children(&mut inner) {
            if grandchild.kind() == "extern_modifier"
                && let Ok(text) =
                    std::str::from_utf8(&bytes[grandchild.start_byte()..grandchild.end_byte()])
                && text.contains("\"C\"")
            {
                return true;
            }
        }
    }
    false
}

// ---------------------------------------------------------------------------
// Python detector
// ---------------------------------------------------------------------------

/// Python entry-point detector.
///
/// Detects (per `docs/FIND_DEAD_CODE_DESIGN.md` Section 2):
/// - `if __name__ == "__main__":` blocks at module top level (Main)
/// - Top-level functions named in `__all__` (LibraryExport)
/// - Functions starting with `test_` in files matching `test_*.py` /
///   `*_test.py` or under a `tests/` directory (Test)
///
/// Framework decorators (`@click.command`, `@app.route`,
/// `@pytest.fixture`) are not yet captured — see X4 for the framework
/// pass.
#[derive(Debug, Default, Clone, Copy)]
pub struct PythonEntryDetector;

impl EntryPointDetector for PythonEntryDetector {
    fn detect(&self, source: &str, file_path: &Path) -> Vec<EntryPoint> {
        let mut entries = Vec::new();
        let Some(tree) = parse_with(source, &tree_sitter_python::LANGUAGE.into()) else {
            return entries;
        };
        let root = tree.root_node();
        let bytes = source.as_bytes();

        let is_test_file = python_is_test_file(file_path);

        // Module top-level statements.
        let mut cursor = root.walk();
        for child in root.children(&mut cursor) {
            match child.kind() {
                "if_statement" if python_is_dunder_main_block(&child, bytes) => {
                    let line = u32::try_from(child.start_position().row + 1).unwrap_or(u32::MAX);
                    entries.push(EntryPoint {
                        name: "__main__".to_string(),
                        kind: EntryPointKind::Main,
                        file_path: file_path.to_path_buf(),
                        line,
                    });
                }
                "expression_statement" => {
                    // `__all__ = [...]` is an expression_statement
                    // containing an assignment.
                    if let Some(names) = python_extract_dunder_all(&child, bytes) {
                        let line =
                            u32::try_from(child.start_position().row + 1).unwrap_or(u32::MAX);
                        for n in names {
                            entries.push(EntryPoint {
                                name: n,
                                kind: EntryPointKind::LibraryExport,
                                file_path: file_path.to_path_buf(),
                                line,
                            });
                        }
                    }
                }
                "function_definition" | "decorated_definition" => {
                    let fn_node = if child.kind() == "decorated_definition" {
                        child.child_by_field_name("definition")
                    } else {
                        Some(child)
                    };
                    if let Some(fn_node) = fn_node
                        && fn_node.kind() == "function_definition"
                        && let Some(name_node) = fn_node.child_by_field_name("name")
                        && let Ok(name) = std::str::from_utf8(
                            &bytes[name_node.start_byte()..name_node.end_byte()],
                        )
                        && is_test_file
                        && name.starts_with("test_")
                    {
                        let line =
                            u32::try_from(fn_node.start_position().row + 1).unwrap_or(u32::MAX);
                        entries.push(EntryPoint {
                            name: name.to_string(),
                            kind: EntryPointKind::Test,
                            file_path: file_path.to_path_buf(),
                            line,
                        });
                    }
                }
                _ => {}
            }
        }

        entries
    }
}

fn python_is_test_file(file_path: &Path) -> bool {
    let Some(file_name) = file_path.file_name().and_then(|s| s.to_str()) else {
        return false;
    };
    let is_py = Path::new(file_name)
        .extension()
        .is_some_and(|ext| ext.eq_ignore_ascii_case("py"));
    if !is_py {
        return false;
    }
    let stem = Path::new(file_name)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("");
    if stem.starts_with("test_") || stem.ends_with("_test") {
        return true;
    }
    // Any component named `tests` in the parent directory chain.
    file_path
        .components()
        .any(|c| c.as_os_str() == std::ffi::OsStr::new("tests"))
}

fn python_is_dunder_main_block(node: &Node<'_>, bytes: &[u8]) -> bool {
    // if condition: comparison `__name__ == "__main__"`.
    let cond = node.child_by_field_name("condition");
    let Some(cond) = cond else { return false };
    let Ok(text) = std::str::from_utf8(&bytes[cond.start_byte()..cond.end_byte()]) else {
        return false;
    };
    // Tolerate single or double quotes around `__main__`.
    let normalized = text.replace(' ', "");
    normalized.contains("__name__==\"__main__\"")
        || normalized.contains("__name__=='__main__'")
        || normalized.contains("\"__main__\"==__name__")
        || normalized.contains("'__main__'==__name__")
}

/// Extract the string literals from a top-level `__all__ = [...]`
/// assignment. Returns `None` if the statement is not such an assignment.
fn python_extract_dunder_all(node: &Node<'_>, bytes: &[u8]) -> Option<Vec<String>> {
    // expression_statement -> assignment (left, right)
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "assignment" {
            let left = child.child_by_field_name("left")?;
            let right = child.child_by_field_name("right")?;
            let left_text = std::str::from_utf8(&bytes[left.start_byte()..left.end_byte()]).ok()?;
            if left_text.trim() != "__all__" {
                return None;
            }
            // right is typically a `list` or `tuple` node containing
            // `string` children.
            let mut names = Vec::new();
            let mut inner = right.walk();
            for grandchild in right.children(&mut inner) {
                if grandchild.kind() != "string" {
                    continue;
                }
                // Walk the string node to find string_content child.
                let mut sc = grandchild.walk();
                let mut content_text: Option<String> = None;
                for sg in grandchild.children(&mut sc) {
                    if sg.kind() == "string_content"
                        && let Ok(t) = std::str::from_utf8(&bytes[sg.start_byte()..sg.end_byte()])
                    {
                        content_text = Some(t.to_string());
                    }
                }
                if let Some(t) = content_text {
                    names.push(t);
                } else if let Ok(raw) =
                    std::str::from_utf8(&bytes[grandchild.start_byte()..grandchild.end_byte()])
                {
                    // Fallback: strip the outer quotes from the raw
                    // string text.
                    let trimmed = raw.trim_matches(|c| c == '"' || c == '\'');
                    names.push(trimmed.to_string());
                }
            }
            return Some(names);
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Go detector
// ---------------------------------------------------------------------------

/// Go entry-point detector.
///
/// Detects (per `docs/FIND_DEAD_CODE_DESIGN.md` Section 2):
/// - `func main()` in `package main` (Main)
/// - `func init()` (Init) — runs automatically at package load
/// - Functions starting with `Test`, `Benchmark`, `Example`, `Fuzz` (Test)
/// - Exported names (starting with uppercase) in library packages
///   (LibraryExport)
#[derive(Debug, Default, Clone, Copy)]
pub struct GoEntryDetector;

impl EntryPointDetector for GoEntryDetector {
    fn detect(&self, source: &str, file_path: &Path) -> Vec<EntryPoint> {
        let mut entries = Vec::new();
        let Some(tree) = parse_with(source, &tree_sitter_go::LANGUAGE.into()) else {
            return entries;
        };
        let root = tree.root_node();
        let bytes = source.as_bytes();

        // Determine the package name. `package main` enables `main` as
        // the binary entry; non-main packages are libraries whose
        // exported names are library entries.
        let package_name = go_package_name(&root, bytes).unwrap_or_default();
        let is_main_package = package_name == "main";

        // Walk top-level function_declaration / method_declaration nodes.
        let mut cursor = root.walk();
        for child in root.children(&mut cursor) {
            match child.kind() {
                "function_declaration" => {
                    if let Some(name_node) = child.child_by_field_name("name")
                        && let Ok(name) = std::str::from_utf8(
                            &bytes[name_node.start_byte()..name_node.end_byte()],
                        )
                    {
                        let line =
                            u32::try_from(child.start_position().row + 1).unwrap_or(u32::MAX);
                        go_classify(name, line, is_main_package, file_path, &mut entries);
                    }
                }
                "method_declaration" => {
                    // Methods participate in LibraryExport only — main / init
                    // / Test* are exclusively free functions.
                    if let Some(name_node) = child.child_by_field_name("name")
                        && let Ok(name) = std::str::from_utf8(
                            &bytes[name_node.start_byte()..name_node.end_byte()],
                        )
                        && !is_main_package
                        && go_is_exported(name)
                    {
                        let line =
                            u32::try_from(child.start_position().row + 1).unwrap_or(u32::MAX);
                        entries.push(EntryPoint {
                            name: name.to_string(),
                            kind: EntryPointKind::LibraryExport,
                            file_path: file_path.to_path_buf(),
                            line,
                        });
                    }
                }
                _ => {}
            }
        }

        entries
    }
}

fn go_package_name(root: &Node<'_>, bytes: &[u8]) -> Option<String> {
    let mut cursor = root.walk();
    for child in root.children(&mut cursor) {
        if child.kind() != "package_clause" {
            continue;
        }
        let mut inner = child.walk();
        for grandchild in child.children(&mut inner) {
            if grandchild.kind() == "package_identifier"
                && let Ok(text) =
                    std::str::from_utf8(&bytes[grandchild.start_byte()..grandchild.end_byte()])
            {
                return Some(text.to_string());
            }
        }
    }
    None
}

fn go_classify(
    name: &str,
    line: u32,
    is_main_package: bool,
    file_path: &Path,
    out: &mut Vec<EntryPoint>,
) {
    if name == "main" && is_main_package {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Main,
            file_path: file_path.to_path_buf(),
            line,
        });
        return;
    }
    if name == "init" {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Init,
            file_path: file_path.to_path_buf(),
            line,
        });
        return;
    }
    if name.starts_with("Test")
        || name.starts_with("Benchmark")
        || name.starts_with("Example")
        || name.starts_with("Fuzz")
    {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::Test,
            file_path: file_path.to_path_buf(),
            line,
        });
        return;
    }
    if !is_main_package && go_is_exported(name) {
        out.push(EntryPoint {
            name: name.to_string(),
            kind: EntryPointKind::LibraryExport,
            file_path: file_path.to_path_buf(),
            line,
        });
    }
}

/// Return true if `name` starts with an ASCII uppercase letter, which is
/// Go's syntactic rule for an exported (package-public) identifier.
fn go_is_exported(name: &str) -> bool {
    name.chars().next().is_some_and(|c| c.is_ascii_uppercase())
}

// ---------------------------------------------------------------------------
// Dispatch
// ---------------------------------------------------------------------------

/// Return the entry-point detector for a language identifier.
///
/// `language` is the lowercased language name as used in
/// `crate::languages` (`"rust"`, `"python"`, `"go"`). Returns `None` for
/// any language not yet covered by this wave; X4 will extend coverage to
/// JS/TS, Java, C/C++, Ruby, Scala, Kotlin, Swift, and Bash.
///
/// File-extension dispatch (`"rs"`, `"py"`, `"pyi"`, `"go"`) is also
/// accepted for caller convenience — the BFS walk in X2 carries
/// extensions, not language names, through its per-file loop.
#[must_use]
pub fn detector_for(language: &str) -> Option<Box<dyn EntryPointDetector>> {
    match language {
        "rust" | "rs" => Some(Box::new(RustEntryDetector)),
        "python" | "py" | "pyi" => Some(Box::new(PythonEntryDetector)),
        "go" => Some(Box::new(GoEntryDetector)),
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Parse `source` with the given tree-sitter `Language`. Returns `None`
/// if the parser cannot be configured or the parse fails.
fn parse_with(source: &str, language: &tree_sitter::Language) -> Option<tree_sitter::Tree> {
    let mut parser = Parser::new();
    parser.set_language(language).ok()?;
    parser.parse(source, None)
}

// Unused-but-keep-for-X2 helpers. These ride alongside the detector
// implementations so X2 has a single import point for the BFS-time
// helpers.
//
// `query_match_lines` returns the 1-based line of every match of a
// compiled tree-sitter query against `source`. X2 will use this to
// post-process the raw RepoGraph definitions when an entry-point
// predicate fires on something that is not itself a Definition (e.g.
// the Python `if __name__ == "__main__"` block isn't a Definition —
// it's a top-level statement that anchors any function it calls).
//
// We expose it as `pub(crate)` so X2 can consume without it widening
// the public surface.

#[allow(dead_code)]
pub(crate) fn query_match_lines(
    source: &str,
    language: &tree_sitter::Language,
    query: &Query,
) -> Vec<u32> {
    let mut lines = Vec::new();
    let Some(tree) = parse_with(source, language) else {
        return lines;
    };
    let mut cursor = QueryCursor::new();
    let mut matches = cursor.matches(query, tree.root_node(), source.as_bytes());
    while let Some(m) = matches.next() {
        for cap in m.captures {
            let line = u32::try_from(cap.node.start_position().row + 1).unwrap_or(u32::MAX);
            lines.push(line);
        }
    }
    lines
}