minni 0.1.0

Local memory, task, and codebase indexing tool for AI agents
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
use super::languages::SupportedLanguage;
use crate::db::CodeChunk;
use anyhow::Result;
use chrono::Utc;
use tree_sitter::{Parser, Tree};
use uuid::Uuid;

/// Chunking options.
#[derive(Clone)]
pub struct ChunkConfig {
    pub min_chunk_lines: usize,
    pub max_chunk_lines: usize,
    pub overlap_lines: usize,
    pub include_file_chunks: bool,
}

impl Default for ChunkConfig {
    fn default() -> Self {
        Self {
            min_chunk_lines: 5,
            max_chunk_lines: 100,
            overlap_lines: 2,
            include_file_chunks: true,
        }
    }
}

/// Derive a dotted module path from a file path.
fn derive_module_path(file_path: &str) -> String {
    // Normalise path separators to '/'
    let normalised = file_path.replace('\\', "/");

    // Strip a leading `src/` or `lib/` prefix (only at the very start)
    let stripped = normalised
        .strip_prefix("src/")
        .or_else(|| normalised.strip_prefix("lib/"))
        .unwrap_or(&normalised);

    // Strip file extension
    let no_ext = if let Some(pos) = stripped.rfind('.') {
        // Make sure the dot isn't part of a directory component
        let after_last_slash = stripped.rfind('/').map(|i| i + 1).unwrap_or(0);
        if pos > after_last_slash {
            &stripped[..pos]
        } else {
            stripped
        }
    } else {
        stripped
    };

    // Handle `mod`, `__init__`, `index` as "directory-level" modules
    let parts: Vec<&str> = no_ext.split('/').collect();
    let trim_last = parts
        .last()
        .map(|last| *last == "mod" || *last == "__init__" || *last == "index")
        .unwrap_or(false);
    let final_parts = if trim_last {
        &parts[..parts.len().saturating_sub(1)]
    } else {
        parts.as_slice()
    };

    let result = final_parts.join(".");
    // Return the path as-is if we ended up with an empty string (edge case)
    if result.is_empty() {
        no_ext.replace('/', ".")
    } else {
        result
    }
}

pub fn chunk_file(
    content: &str,
    file_path: &str,
    language: SupportedLanguage,
    config: &ChunkConfig,
) -> Result<(Vec<CodeChunk>, Tree)> {
    let mut chunks = Vec::new();
    let lines: Vec<&str> = content.lines().collect();
    let timestamp = Utc::now().to_rfc3339();

    // Derive module_path once for the whole file
    let module_path = Some(derive_module_path(file_path));

    // Parse with tree-sitter
    let mut parser = Parser::new();
    parser
        .set_language(&language.tree_sitter_language())
        .map_err(|e| anyhow::anyhow!("Failed to set language: {}", e))?;

    let tree = parser
        .parse(content, None)
        .ok_or_else(|| anyhow::anyhow!("Failed to parse file"))?;

    // Extract semantic chunks (functions, classes, etc.)
    extract_semantic_chunks(
        &tree,
        content,
        file_path,
        language,
        config.min_chunk_lines,
        &mut chunks,
        &timestamp,
        module_path.as_deref(),
    );

    // If no semantic chunks found or file is small, create a file-level chunk
    if chunks.is_empty() || (config.include_file_chunks && lines.len() <= config.max_chunk_lines) {
        let file_chunk = CodeChunk {
            id: Uuid::new_v4().to_string(),
            file_path: file_path.to_string(),
            content: content.to_string(),
            start_line: 1,
            end_line: lines.len() as u32,
            chunk_type: "file".to_string(),
            language: language.name().to_string(),
            symbol_name: None,
            content_hash: compute_content_hash(content),
            indexed_at: timestamp.clone(),
            parent_symbol: None,
            signature: None,
            doc_comment: None,
            module_path: module_path.clone(),
        };
        chunks.push(file_chunk);
    }

    // For large files without semantic structure, create overlapping chunks
    if chunks.is_empty() && lines.len() > config.max_chunk_lines {
        let mut start = 0;
        while start < lines.len() {
            let end = (start + config.max_chunk_lines).min(lines.len());
            let chunk_content = lines[start..end].join("\n");

            let chunk = CodeChunk {
                id: Uuid::new_v4().to_string(),
                file_path: file_path.to_string(),
                content: chunk_content.clone(),
                start_line: (start + 1) as u32,
                end_line: end as u32,
                chunk_type: "block".to_string(),
                language: language.name().to_string(),
                symbol_name: None,
                content_hash: compute_content_hash(&chunk_content),
                indexed_at: timestamp.clone(),
                parent_symbol: None,
                signature: None,
                doc_comment: None,
                module_path: module_path.clone(),
            };
            chunks.push(chunk);

            if end >= lines.len() {
                break;
            }
            start = end - config.overlap_lines;
        }
    }

    Ok((chunks, tree))
}

/// Chunk a non-code file.
pub fn chunk_plain_text(
    content: &str,
    file_path: &str,
    language_label: &str,
    config: &ChunkConfig,
) -> Result<Vec<CodeChunk>> {
    let lines: Vec<&str> = content.lines().collect();
    let timestamp = Utc::now().to_rfc3339();
    let module_path = Some(derive_module_path(file_path));

    if lines.is_empty() {
        return Ok(Vec::new());
    }

    let chunks = if language_label == "markdown" {
        chunk_markdown(
            &lines,
            file_path,
            language_label,
            config,
            &timestamp,
            module_path.as_deref(),
        )
    } else {
        chunk_lines_overlap(
            &lines,
            file_path,
            language_label,
            config,
            &timestamp,
            module_path.as_deref(),
        )
    };

    Ok(chunks)
}

/// Split a markdown file on heading boundaries (lines starting with `#`).
/// Each section's `symbol_name` is the heading text (stripped of `#` prefix).
/// `chunk_type` is `"section"`. Over-large sections fall through to overlapping line chunks.
/// If no headings are found, falls back to `chunk_lines_overlap`.
fn chunk_markdown(
    lines: &[&str],
    file_path: &str,
    language_label: &str,
    config: &ChunkConfig,
    timestamp: &str,
    module_path: Option<&str>,
) -> Vec<CodeChunk> {
    let mut chunks = Vec::new();
    let mut section_start = 0;
    let mut section_heading: Option<String> = None;
    let mut found_heading = false;

    for (i, line) in lines.iter().enumerate() {
        let is_heading = line.starts_with('#');
        let is_last = i == lines.len() - 1;

        if is_heading || is_last {
            // Determine the end of the accumulated section
            let section_end = if is_last && !is_heading { i + 1 } else { i };

            if section_end > section_start {
                let section_content = lines[section_start..section_end].join("\n");
                if !section_content.trim().is_empty() {
                    if section_end - section_start > config.max_chunk_lines {
                        // Section too large — break into overlapping sub-chunks
                        let sub_lines = &lines[section_start..section_end];
                        let sub_chunks = chunk_lines_overlap_with_offset(
                            sub_lines,
                            file_path,
                            language_label,
                            config,
                            timestamp,
                            module_path,
                            section_start,
                            section_heading.as_deref(),
                        );
                        chunks.extend(sub_chunks);
                    } else {
                        chunks.push(CodeChunk {
                            id: Uuid::new_v4().to_string(),
                            file_path: file_path.to_string(),
                            content: section_content.clone(),
                            start_line: (section_start + 1) as u32,
                            end_line: section_end as u32,
                            chunk_type: "section".to_string(),
                            language: language_label.to_string(),
                            symbol_name: section_heading.clone(),
                            content_hash: compute_content_hash(&section_content),
                            indexed_at: timestamp.to_string(),
                            parent_symbol: None,
                            signature: None,
                            doc_comment: None,
                            module_path: module_path.map(|s| s.to_string()),
                        });
                    }
                }
            }

            if is_heading {
                found_heading = true;
                section_start = i;
                section_heading = Some(line.trim_start_matches('#').trim().to_string());

                // Handle the edge case where the heading is the very last line
                if is_last {
                    let section_content = lines[i..=i].join("\n");
                    chunks.push(CodeChunk {
                        id: Uuid::new_v4().to_string(),
                        file_path: file_path.to_string(),
                        content: section_content.clone(),
                        start_line: (i + 1) as u32,
                        end_line: (i + 1) as u32,
                        chunk_type: "section".to_string(),
                        language: language_label.to_string(),
                        symbol_name: section_heading.clone(),
                        content_hash: compute_content_hash(&section_content),
                        indexed_at: timestamp.to_string(),
                        parent_symbol: None,
                        signature: None,
                        doc_comment: None,
                        module_path: module_path.map(|s| s.to_string()),
                    });
                }
            }
        }
    }

    // No headings found → fall back to line-based chunking
    if !found_heading {
        return chunk_lines_overlap(
            lines,
            file_path,
            language_label,
            config,
            timestamp,
            module_path,
        );
    }

    chunks
}

/// Fixed-size overlapping line chunks with no offset.
fn chunk_lines_overlap(
    lines: &[&str],
    file_path: &str,
    language_label: &str,
    config: &ChunkConfig,
    timestamp: &str,
    module_path: Option<&str>,
) -> Vec<CodeChunk> {
    chunk_lines_overlap_with_offset(
        lines,
        file_path,
        language_label,
        config,
        timestamp,
        module_path,
        0,
        None,
    )
}

/// Fixed-size overlapping line chunks, with a `line_offset` for correct absolute line numbers
/// and an optional `symbol_name` to attach to every produced chunk.
fn chunk_lines_overlap_with_offset(
    lines: &[&str],
    file_path: &str,
    language_label: &str,
    config: &ChunkConfig,
    timestamp: &str,
    module_path: Option<&str>,
    line_offset: usize,
    symbol_name: Option<&str>,
) -> Vec<CodeChunk> {
    let mut chunks = Vec::new();

    // If file/section fits in one chunk, emit it as a single block
    if lines.len() <= config.max_chunk_lines {
        let content = lines.join("\n");
        if !content.trim().is_empty() {
            chunks.push(CodeChunk {
                id: Uuid::new_v4().to_string(),
                file_path: file_path.to_string(),
                content: content.clone(),
                start_line: (line_offset + 1) as u32,
                end_line: (line_offset + lines.len()) as u32,
                chunk_type: "block".to_string(),
                language: language_label.to_string(),
                symbol_name: symbol_name.map(|s| s.to_string()),
                content_hash: compute_content_hash(&content),
                indexed_at: timestamp.to_string(),
                parent_symbol: None,
                signature: None,
                doc_comment: None,
                module_path: module_path.map(|s| s.to_string()),
            });
        }
        return chunks;
    }

    // Overlapping window over the lines
    let mut start = 0;
    while start < lines.len() {
        let end = (start + config.max_chunk_lines).min(lines.len());
        let chunk_content = lines[start..end].join("\n");

        chunks.push(CodeChunk {
            id: Uuid::new_v4().to_string(),
            file_path: file_path.to_string(),
            content: chunk_content.clone(),
            start_line: (line_offset + start + 1) as u32,
            end_line: (line_offset + end) as u32,
            chunk_type: "block".to_string(),
            language: language_label.to_string(),
            symbol_name: symbol_name.map(|s| s.to_string()),
            content_hash: compute_content_hash(&chunk_content),
            indexed_at: timestamp.to_string(),
            parent_symbol: None,
            signature: None,
            doc_comment: None,
            module_path: module_path.map(|s| s.to_string()),
        });

        if end >= lines.len() {
            break;
        }
        start = end - config.overlap_lines;
    }

    chunks
}

fn extract_semantic_chunks(
    tree: &Tree,
    content: &str,
    file_path: &str,
    language: SupportedLanguage,
    min_chunk_lines: usize,
    chunks: &mut Vec<CodeChunk>,
    timestamp: &str,
    module_path: Option<&str>,
) {
    let root = tree.root_node();
    let mut cursor = root.walk();
    let lines: Vec<&str> = content.lines().collect();

    let function_types = language.function_node_types();
    let class_types = language.class_node_types();

    fn visit_node(
        cursor: &mut tree_sitter::TreeCursor,
        content: &str,
        lines: &[&str],
        file_path: &str,
        language: SupportedLanguage,
        min_chunk_lines: usize,
        function_types: &[&str],
        class_types: &[&str],
        chunks: &mut Vec<CodeChunk>,
        timestamp: &str,
        module_path: Option<&str>,
    ) {
        let node = cursor.node();
        let node_type = node.kind();

        let chunk_type = if function_types.contains(&node_type) {
            Some("function")
        } else if class_types.contains(&node_type) {
            Some("class")
        } else {
            None
        };

        if let Some(chunk_type) = chunk_type {
            let start_line = node.start_position().row;
            let end_line = node.end_position().row;
            let line_count = end_line.saturating_sub(start_line) + 1;

            // Skip nodes below configured minimum size.
            if line_count >= min_chunk_lines {
                let chunk_content = lines[start_line..=end_line.min(lines.len() - 1)].join("\n");

                // Try to extract the symbol name
                let symbol_name = node
                    .child_by_field_name(language.name_field())
                    .map(|n| n.utf8_text(content.as_bytes()).unwrap_or("").to_string())
                    .filter(|s| !s.is_empty());

                // Extract parent_symbol: walk up to the nearest enclosing class/struct/impl
                let parent_symbol = extract_parent_symbol(&node, content, class_types, language);

                // Extract signature: text from node start up to (not including) the body
                let signature = if chunk_type == "function" {
                    extract_signature(&node, content)
                } else {
                    None
                };

                // Extract doc_comment: look at the preceding sibling for a comment node
                let doc_comment = extract_doc_comment(&node, content, language);

                let chunk = CodeChunk {
                    id: Uuid::new_v4().to_string(),
                    file_path: file_path.to_string(),
                    content: chunk_content.clone(),
                    start_line: (start_line + 1) as u32,
                    end_line: (end_line + 1) as u32,
                    chunk_type: chunk_type.to_string(),
                    language: language.name().to_string(),
                    symbol_name,
                    content_hash: compute_content_hash(&chunk_content),
                    indexed_at: timestamp.to_string(),
                    parent_symbol,
                    signature,
                    doc_comment,
                    module_path: module_path.map(|s| s.to_string()),
                };
                chunks.push(chunk);
            }
        }

        // Visit children
        if cursor.goto_first_child() {
            loop {
                visit_node(
                    cursor,
                    content,
                    lines,
                    file_path,
                    language,
                    min_chunk_lines,
                    function_types,
                    class_types,
                    chunks,
                    timestamp,
                    module_path,
                );
                if !cursor.goto_next_sibling() {
                    break;
                }
            }
            cursor.goto_parent();
        }
    }

    visit_node(
        &mut cursor,
        content,
        &lines,
        file_path,
        language,
        min_chunk_lines,
        function_types,
        class_types,
        chunks,
        timestamp,
        module_path,
    );
}

/// Walk up the node's parent chain to find the nearest enclosing class/struct/impl.
fn extract_parent_symbol(
    node: &tree_sitter::Node,
    content: &str,
    class_types: &[&str],
    language: SupportedLanguage,
) -> Option<String> {
    let mut current = node.parent()?;
    loop {
        if class_types.contains(&current.kind()) {
            // Try to get the name field from the parent class/struct/impl
            let name = current
                .child_by_field_name(language.name_field())
                .and_then(|n| n.utf8_text(content.as_bytes()).ok())
                .map(|s| s.to_string())
                .filter(|s| !s.is_empty());
            if name.is_some() {
                return name;
            }
        }
        match current.parent() {
            Some(p) => current = p,
            None => break,
        }
    }
    None
}

/// Extract the signature of a function node: text from the node start up to (but not
/// including) the body child node. Falls back to the first line of the node.
fn extract_signature(node: &tree_sitter::Node, content: &str) -> Option<String> {
    let content_bytes = content.as_bytes();

    // Primary: use the named "body" field that most tree-sitter grammars provide.
    // Fallback: scan children for well-known body-like node kinds.
    let body_start = node
        .child_by_field_name("body")
        .map(|b| b.start_byte())
        .or_else(|| {
            (0..node.child_count())
                .filter_map(|i| node.child(i))
                .find(|child| {
                    matches!(
                        child.kind(),
                        "body"
                            | "block"
                            | "declaration_list"
                            | "field_declaration_list"
                            | "class_body"
                            | "statement_block"
                            | "compound_statement"
                            | "function_body"
                    )
                })
                .map(|body_node| body_node.start_byte())
        });

    let sig_bytes = if let Some(body_start_byte) = body_start {
        let node_start = node.start_byte();
        if body_start_byte > node_start {
            &content_bytes[node_start..body_start_byte]
        } else {
            return None;
        }
    } else {
        // No body child found — take the first line of the node
        let start = node.start_byte();
        let end = node.end_byte().min(content_bytes.len());
        let text = std::str::from_utf8(&content_bytes[start..end]).unwrap_or("");
        let first_line = text.lines().next().unwrap_or("").trim();
        return if first_line.is_empty() {
            None
        } else {
            Some(first_line.to_string())
        };
    };

    let sig_str = std::str::from_utf8(sig_bytes).unwrap_or("").trim();
    if sig_str.is_empty() {
        None
    } else {
        Some(sig_str.to_string())
    }
}

/// Look at the node's preceding sibling for a comment node or Python docstring.
/// For Python, also check the first statement in the function body for a string expression.
fn extract_doc_comment(
    node: &tree_sitter::Node,
    content: &str,
    language: SupportedLanguage,
) -> Option<String> {
    let content_bytes = content.as_bytes();

    // Check the immediately preceding named sibling for a comment or doc node.
    // Also handle `expression_statement > string` for Python docstrings that appear
    // as a preceding sibling in some tree-sitter grammar versions.
    if let Some(prev) = node.prev_sibling() {
        let kind = prev.kind();
        if kind.contains("comment") || kind.contains("doc") {
            let text = prev
                .utf8_text(content_bytes)
                .unwrap_or("")
                .trim()
                .to_string();
            if !text.is_empty() {
                return Some(text);
            }
        }
        // Python only: preceding sibling may be an expression_statement wrapping a string literal
        if matches!(language, SupportedLanguage::Python)
            && (kind == "expression_statement" || kind == "string")
        {
            let string_node = if kind == "expression_statement" {
                // find the first named child of kind "string"
                (0..prev.child_count())
                    .filter_map(|i| prev.child(i))
                    .find(|c| c.kind() == "string")
            } else {
                Some(prev)
            };
            if let Some(s) = string_node {
                let text = s.utf8_text(content_bytes).unwrap_or("").trim().to_string();
                if !text.is_empty() {
                    return Some(text);
                }
            }
        }
    }

    // For Python: check first named statement in the function body for a string (docstring).
    if matches!(language, SupportedLanguage::Python) {
        if let Some(body) = node.child_by_field_name("body") {
            // Walk named children only; stop after the first one.
            for i in 0..body.child_count() {
                if let Some(child) = body.child(i) {
                    if !child.is_named() {
                        continue;
                    }
                    let kind = child.kind();
                    // The docstring may appear directly as a `string` node or wrapped in
                    // `expression_statement`.
                    if kind == "string" {
                        let text = child
                            .utf8_text(content_bytes)
                            .unwrap_or("")
                            .trim()
                            .to_string();
                        if !text.is_empty() {
                            return Some(text);
                        }
                    } else if kind == "expression_statement" {
                        // find first child of kind "string"
                        let string_node = (0..child.child_count())
                            .filter_map(|i| child.child(i))
                            .find(|c| c.kind() == "string");
                        if let Some(s) = string_node {
                            let text = s.utf8_text(content_bytes).unwrap_or("").trim().to_string();
                            if !text.is_empty() {
                                return Some(text);
                            }
                        }
                    }
                    break; // Only inspect the very first named child
                }
            }
        }
    }

    None
}

fn compute_content_hash(content: &str) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(content.as_bytes());
    hex::encode(hasher.finalize())
}

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

    #[test]
    fn test_derive_module_path_rust() {
        assert_eq!(derive_module_path("src/search/bm25.rs"), "search.bm25");
        assert_eq!(derive_module_path("src/indexer/mod.rs"), "indexer");
        assert_eq!(derive_module_path("src/lib.rs"), "lib");
        assert_eq!(derive_module_path("src/db/mod.rs"), "db");
        assert_eq!(derive_module_path("src/cli/search.rs"), "cli.search");
    }

    #[test]
    fn test_derive_module_path_python() {
        assert_eq!(derive_module_path("app/utils/__init__.py"), "app.utils");
        assert_eq!(
            derive_module_path("app/utils/helpers.py"),
            "app.utils.helpers"
        );
    }

    #[test]
    fn test_derive_module_path_no_prefix() {
        assert_eq!(derive_module_path("main.rs"), "main");
        assert_eq!(derive_module_path("utils/helpers.ts"), "utils.helpers");
    }

    #[test]
    fn test_derive_module_path_windows_separators() {
        assert_eq!(derive_module_path("src\\search\\bm25.rs"), "search.bm25");
    }

    // ── chunk_plain_text tests ──────────────────────────────────────────────

    fn default_config() -> ChunkConfig {
        ChunkConfig {
            min_chunk_lines: 1,
            max_chunk_lines: 10,
            overlap_lines: 2,
            include_file_chunks: true,
        }
    }

    #[test]
    fn test_chunk_plain_text_empty_file() {
        let cfg = default_config();
        let result = chunk_plain_text("", "README.md", "markdown", &cfg).unwrap();
        assert!(result.is_empty(), "empty file should produce no chunks");
    }

    #[test]
    fn test_chunk_plain_text_whitespace_only() {
        let cfg = default_config();
        let result = chunk_plain_text("   \n\n  ", "README.md", "markdown", &cfg).unwrap();
        assert!(
            result.is_empty(),
            "whitespace-only file should produce no chunks"
        );
    }

    #[test]
    fn test_chunk_markdown_sections() {
        let cfg = default_config();
        let content = "# Introduction\nHello world.\n\n# Usage\nRun `cargo build`.\n";
        let chunks = chunk_plain_text(content, "README.md", "markdown", &cfg).unwrap();

        // Should produce two sections: "Introduction" and "Usage"
        assert_eq!(chunks.len(), 2);

        let intro = &chunks[0];
        assert_eq!(intro.chunk_type, "section");
        assert_eq!(intro.symbol_name.as_deref(), Some("Introduction"));
        assert_eq!(intro.language, "markdown");

        let usage = &chunks[1];
        assert_eq!(usage.chunk_type, "section");
        assert_eq!(usage.symbol_name.as_deref(), Some("Usage"));
    }

    #[test]
    fn test_chunk_markdown_no_headings_falls_back_to_blocks() {
        let cfg = default_config();
        let content = "Just some prose\nwith multiple lines\nbut no headings at all.\n";
        let chunks = chunk_plain_text(content, "notes.md", "markdown", &cfg).unwrap();

        assert!(!chunks.is_empty(), "should produce at least one chunk");
        // Without headings every chunk must be a "block", not a "section"
        for chunk in &chunks {
            assert_eq!(chunk.chunk_type, "block");
            assert_eq!(chunk.language, "markdown");
        }
    }

    #[test]
    fn test_chunk_plain_text_yaml_produces_blocks() {
        let cfg = default_config();
        let content = "name: my-app\nversion: 1.0\nenv: production\n";
        let chunks = chunk_plain_text(content, ".github/workflows/ci.yml", "yaml", &cfg).unwrap();

        assert!(!chunks.is_empty());
        for chunk in &chunks {
            assert_eq!(chunk.chunk_type, "block");
            assert_eq!(chunk.language, "yaml");
        }
    }

    #[test]
    fn test_chunk_plain_text_overlapping_large_file() {
        let cfg = ChunkConfig {
            max_chunk_lines: 5,
            overlap_lines: 2,
            ..default_config()
        };
        // 12-line file: should be split into overlapping chunks
        let lines: Vec<String> = (1..=12).map(|i| format!("line {i}")).collect();
        let content = lines.join("\n");
        let chunks = chunk_plain_text(&content, "big.sql", "sql", &cfg).unwrap();

        assert!(
            chunks.len() > 1,
            "large file should split into multiple chunks"
        );

        // All chunks should be "block"
        for chunk in &chunks {
            assert_eq!(chunk.chunk_type, "block");
        }

        // First chunk starts at line 1
        assert_eq!(chunks[0].start_line, 1);

        // Last chunk's end_line should be 12
        let last = chunks.last().unwrap();
        assert_eq!(last.end_line, 12);
    }

    #[test]
    fn test_chunk_markdown_heading_only_last_line() {
        let cfg = default_config();
        // Heading is the very last line — should still produce a section chunk
        let content = "Some intro text.\n# Trailing Heading";
        let chunks = chunk_plain_text(content, "README.md", "markdown", &cfg).unwrap();

        let trailing = chunks
            .iter()
            .find(|c| c.symbol_name.as_deref() == Some("Trailing Heading"));
        assert!(
            trailing.is_some(),
            "heading on last line should create a section chunk"
        );
    }
}