semantex-core 1.1.0

Core library for semantex semantic code search (indexing, embeddings, search)
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
use crate::server::protocol::{
    DeepSearchResponse, DisambigSuggestion, GraphWalkResponse, SearchResponse, SearchResultItem,
};
use std::fmt::Write as _;

/// Default response budget in bytes (~3K tokens).
pub const DEFAULT_BUDGET: usize = 12_000;

/// Max items per graph section.
const MAX_GRAPH_SECTION: usize = 10;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FormatStyle {
    Default,
    Grep,
}

/// Format a single result item as a compact reference string: `file:start-end[ name][ [kind]]`.
pub(crate) fn format_ref(item: &SearchResultItem) -> String {
    let mut s = format!("{}:{}-{}", item.file, item.start_line, item.end_line);
    if let Some(name) = &item.name {
        s.push(' ');
        s.push_str(name);
    }
    if let Some(kind) = &item.kind {
        let _ = write!(s, " [{kind}]");
    }
    s
}

/// Format search results as a human-readable string.
pub fn format_search_results(
    response: &SearchResponse,
    style: FormatStyle,
    budget: usize,
) -> String {
    if response.results.is_empty() {
        return "No results.".to_string();
    }

    match style {
        FormatStyle::Grep => format_grep(response),
        FormatStyle::Default => format_default(response, budget),
    }
}

fn format_grep(response: &SearchResponse) -> String {
    let mut lines = Vec::new();
    for item in &response.results {
        let first_line = item
            .content
            .as_deref()
            .unwrap_or("")
            .lines()
            .find(|l| !l.trim().is_empty())
            .unwrap_or("");
        lines.push(format!("{}:{}: {}", item.file, item.start_line, first_line));
    }
    let count = lines.len();
    lines.push(String::new());
    lines.push(format!("[{} matches, {}ms]", count, response.duration_ms));
    lines.join("\n")
}

fn format_default(response: &SearchResponse, budget: usize) -> String {
    let mut parts: Vec<String> = Vec::new();
    let mut total_bytes = 0usize;
    let total_count = response.results.len();
    let mut written = 0usize;

    for item in &response.results {
        // Skip items with no name AND no content AND no summary
        if item.name.is_none() && item.content.is_none() && item.summary.is_none() {
            continue;
        }

        let mut block = String::new();

        let _ = write!(block, "{}:{}-{}", item.file, item.start_line, item.end_line);
        if let Some(name) = &item.name {
            block.push(' ');
            block.push_str(name);
        }
        if let Some(kind) = &item.kind {
            let _ = write!(block, " [{kind}]");
        }
        let _ = write!(block, " ({:.2})", item.score);
        block.push('\n');

        // Line 2: summary or content (first 200 chars, newlines replaced with spaces)
        let preview = item
            .summary
            .as_deref()
            .filter(|s| !s.is_empty())
            .or_else(|| item.content.as_deref().filter(|s| !s.is_empty()));
        if let Some(text) = preview {
            let text_normalized = text.replace('\n', " ");
            let truncated = if text_normalized.len() > 200 {
                // Walk back from byte 200 to find a valid char boundary
                let end = (0..=200.min(text_normalized.len()))
                    .rev()
                    .find(|&i| text_normalized.is_char_boundary(i))
                    .unwrap_or(0);
                &text_normalized[..end]
            } else {
                &text_normalized
            };
            block.push_str("  ");
            block.push_str(truncated);
            block.push('\n');
        }

        let block_len = block.len();

        // Budget check: stop if over budget and at least one result written
        if written > 0 && total_bytes + block_len > budget {
            let remaining = total_count - written;
            parts.push(format!("... and {remaining} more results"));
            break;
        }

        total_bytes += block_len;
        written += 1;
        parts.push(block);
    }

    let confidence = response.confidence.as_deref().unwrap_or("unknown");
    let footer = format!(
        "[{} results, {}ms, confidence: {}]",
        total_count, response.duration_ms, confidence
    );

    let mut output = parts.join("\n");
    output.push('\n');
    output.push('\n');
    output.push_str(&footer);
    output
}

/// Format deep search results.
pub fn format_deep_results(response: &DeepSearchResponse, budget: usize) -> String {
    if response.answer.is_empty() && response.sources.is_empty() {
        return "No results.".to_string();
    }

    let mut out = String::new();

    // Answer — truncate at sentence boundary if over budget
    if !response.answer.is_empty() {
        if response.answer.len() > budget {
            // Find last '.' before the limit
            let truncate_at = response.answer[..budget]
                .rfind('.')
                .map_or(budget, |i| i + 1);
            out.push_str(&response.answer[..truncate_at]);
            out.push_str("\n\n[answer truncated]");
        } else {
            out.push_str(&response.answer);
        }
    }

    // Sources section
    if !response.sources.is_empty() {
        if !out.is_empty() {
            out.push_str("\n\n");
        }
        out.push_str("Sources:\n");
        for src in &response.sources {
            let _ = write!(out, "  {}:{}-{}", src.file, src.start_line, src.end_line);
            if let Some(name) = &src.name {
                out.push(' ');
                out.push_str(name);
            }
            if let Some(kind) = &src.kind {
                let _ = write!(out, " [{kind}]");
            }
            out.push('\n');
        }
    }

    // Metrics footer
    let m = &response.metrics;
    let footer = format!(
        "\n[searched: {} chunks, read: {}, {}ms]",
        m.chunks_searched, m.chunks_read, m.total_ms
    );
    out.push_str(&footer);

    out
}

/// Format graph walk results.
fn format_section(out: &mut String, title: &str, items: &[SearchResultItem]) {
    if items.is_empty() {
        return;
    }
    if !out.is_empty() {
        out.push('\n');
    }
    let _ = writeln!(out, "{} ({}):", title, items.len());
    let shown = items.len().min(MAX_GRAPH_SECTION);
    for item in &items[..shown] {
        let _ = writeln!(out, "  {}", format_ref(item));
    }
    if items.len() > MAX_GRAPH_SECTION {
        let _ = writeln!(out, "  ... and {} more", items.len() - MAX_GRAPH_SECTION);
    }
}

pub fn format_graph_results(response: &GraphWalkResponse) -> String {
    let all_empty = response.target.is_empty()
        && response.callers.is_empty()
        && response.callees.is_empty()
        && response.type_refs.is_empty()
        && response.hierarchy.is_empty();

    if all_empty {
        return "No graph data found.".to_string();
    }

    let mut out = String::new();

    // Target section (no count suffix if it's just the target)
    if !response.target.is_empty() {
        out.push_str("Target:\n");
        let shown = response.target.len().min(MAX_GRAPH_SECTION);
        for item in &response.target[..shown] {
            let _ = writeln!(out, "  {}", format_ref(item));
        }
    }

    format_section(&mut out, "Callers", &response.callers);
    format_section(&mut out, "Callees", &response.callees);
    format_section(&mut out, "Type References", &response.type_refs);
    format_section(&mut out, "Type Hierarchy", &response.hierarchy);

    out
}

/// Format code blocks with line numbers.
pub fn format_code_blocks(
    results: &[SearchResultItem],
    code_contents: &[String],
    budget: usize,
) -> String {
    let mut out = String::new();
    let mut total_chars = 0usize;
    let mut blocks_written = 0usize;

    for (item, code) in results.iter().zip(code_contents.iter()) {
        if code.is_empty() {
            continue;
        }

        let lang = item.language.as_deref().unwrap_or("");

        let mut block = String::new();
        // Header
        let _ = write!(
            block,
            "### {}:{}-{}",
            item.file, item.start_line, item.end_line
        );
        if let Some(name) = &item.name {
            let _ = write!(block, "{name}");
        }
        if let Some(kind) = &item.kind {
            let _ = write!(block, " [{kind}]");
        }
        block.push('\n');

        // Fenced code block with line numbers
        let _ = writeln!(block, "```{lang}");
        for (line_num, line) in (item.start_line..).zip(code.lines()) {
            let _ = writeln!(block, "{line_num:4} | {line}");
        }
        block.push_str("```\n");

        let block_len = block.len();

        // Budget check: stop if adding this block would exceed budget
        // But always include at least the first block
        if blocks_written > 0 && total_chars + block_len > budget {
            break;
        }

        if !out.is_empty() {
            out.push('\n');
        }
        out.push_str(&block);
        total_chars += block_len;
        blocks_written += 1;
    }

    if blocks_written == 0 {
        return "No code blocks to display.".to_string();
    }
    out
}

/// v0.5 Item 6: append a disambiguation block to an already-rendered
/// agent / search response.
///
/// Per spec §5 Item 6, the block lists up to 3 runner-up suggestions and
/// references the actual number of candidates surfaced (the spec's "4
/// distinct concepts" phrasing is illustrative — we substitute the real
/// `suggestions.len()`). Format:
///
/// ```text
/// [uncertainty: this query matches N distinct concepts. Refine with:]
/// - "userAuthHandler" (auth/users.rs:42)
/// - "tokenAuthHandler" (auth/tokens.rs:18)
/// - "sessionAuth" (sessions/handler.rs:107)
/// ```
///
/// Renders to the end of `out` separated by a blank line. No-ops on an
/// empty `suggestions` slice (the caller is expected to gate on
/// `disambiguation.is_some()`, but the no-op safety is cheap).
///
/// New helper introduced by W-Delta per spec §10 / §11 — does NOT touch
/// `format_search_results` / `format_deep_results` / `format_graph_results`
/// (those are W-Gamma territory).
pub fn append_disambiguation_block(out: &mut String, suggestions: &[DisambigSuggestion]) {
    if suggestions.is_empty() {
        return;
    }
    if !out.is_empty() && !out.ends_with('\n') {
        out.push('\n');
    }
    if !out.is_empty() {
        out.push('\n');
    }
    let _ = writeln!(
        out,
        "[uncertainty: this query matches {} distinct concepts. Refine with:]",
        suggestions.len()
    );
    for s in suggestions {
        let _ = writeln!(out, "- \"{}\" ({}:{})", s.name, s.path, s.line);
    }
}

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

    fn make_result(
        file: &str,
        start: u32,
        end: u32,
        name: Option<&str>,
        kind: Option<&str>,
        score: f32,
    ) -> SearchResultItem {
        SearchResultItem {
            file: file.into(),
            start_line: start,
            end_line: end,
            score,
            source: "Dense".into(),
            chunk_type: "AstNode".into(),
            name: name.map(Into::into),
            language: Some("rust".into()),
            content: Some("fn example() {}".into()),
            kind: kind.map(Into::into),
            summary: None,
        }
    }

    #[test]
    fn test_format_default_single_result() {
        let resp = SearchResponse {
            results: vec![make_result(
                "src/auth.rs",
                10,
                20,
                Some("Auth"),
                Some("struct"),
                0.85,
            )],
            duration_ms: 17,
            dense_count: 5,
            sparse_count: 8,
            fused_count: 10,
            metrics: None,
            confidence: Some("high".into()),
            disambiguation: None,
        };
        let out = format_search_results(&resp, FormatStyle::Default, DEFAULT_BUDGET);
        assert!(out.contains("src/auth.rs:10-20"));
        assert!(out.contains("Auth"));
        assert!(out.contains("[struct]"));
        assert!(out.contains("(0.85)"));
        assert!(out.contains("[1 results, 17ms"));
    }

    #[test]
    fn test_format_grep_style() {
        let resp = SearchResponse {
            results: vec![make_result("src/auth.rs", 42, 42, None, None, 0.5)],
            duration_ms: 3,
            dense_count: 0,
            sparse_count: 1,
            fused_count: 1,
            metrics: None,
            confidence: Some("medium".into()),
            disambiguation: None,
        };
        let out = format_search_results(&resp, FormatStyle::Grep, DEFAULT_BUDGET);
        assert!(out.contains("src/auth.rs:42:"));
        assert!(out.contains("[1 matches, 3ms]"));
    }

    #[test]
    fn test_format_empty() {
        let resp = SearchResponse {
            results: vec![],
            duration_ms: 1,
            dense_count: 0,
            sparse_count: 0,
            fused_count: 0,
            metrics: None,
            confidence: Some("none".into()),
            disambiguation: None,
        };
        assert_eq!(
            format_search_results(&resp, FormatStyle::Default, DEFAULT_BUDGET),
            "No results."
        );
    }

    #[test]
    fn test_format_deep_with_sources() {
        let resp = DeepSearchResponse {
            answer: "Auth uses JWT tokens.".into(),
            sources: vec![DeepSearchSource {
                file: "src/auth.rs".into(),
                start_line: 10,
                end_line: 50,
                name: Some("Auth".into()),
                kind: Some("struct".into()),
            }],
            metrics: DeepResponseMetrics {
                search_ms: 10,
                triage_ms: 2,
                graph_ms: 3,
                read_ms: 5,
                summarize_ms: 8,
                total_ms: 28,
                chunks_searched: 20,
                chunks_read: 8,
                confidence_zone: String::new(),
            },
            confidence: 0.9,
        };
        let out = format_deep_results(&resp, DEFAULT_BUDGET);
        assert!(out.contains("Auth uses JWT tokens."));
        assert!(out.contains("Sources:"));
        assert!(out.contains("src/auth.rs:10-50 Auth [struct]"));
        assert!(out.contains("[searched: 20 chunks, read: 8, 28ms]"));
    }

    #[test]
    fn test_format_graph_omits_empty_sections() {
        let resp = GraphWalkResponse {
            target: vec![make_result(
                "src/auth.rs",
                10,
                50,
                Some("Auth"),
                Some("struct"),
                1.0,
            )],
            callers: vec![make_result(
                "src/mid.rs",
                5,
                20,
                Some("check"),
                Some("fn"),
                0.9,
            )],
            callees: vec![],
            type_refs: vec![],
            hierarchy: vec![],
        };
        let out = format_graph_results(&resp);
        assert!(out.contains("Target:"));
        assert!(out.contains("Callers (1):"));
        assert!(!out.contains("Callees"));
        assert!(!out.contains("Type References"));
    }

    #[test]
    fn test_format_search_budget_truncates() {
        let results: Vec<SearchResultItem> = (0..20)
            .map(|i| {
                make_result(
                    &format!("file{i}.rs"),
                    1,
                    50,
                    Some(&format!("Func{i}")),
                    Some("fn"),
                    0.9,
                )
            })
            .collect();
        let resp = SearchResponse {
            results,
            duration_ms: 10,
            dense_count: 10,
            sparse_count: 10,
            fused_count: 20,
            metrics: None,
            confidence: Some("high".into()),
            disambiguation: None,
        };
        let out = format_search_results(&resp, FormatStyle::Default, 500);
        assert!(out.contains("more results"));
        assert!(out.contains("[20 results,"));
    }

    #[test]
    fn test_format_deep_budget_truncates() {
        let long_answer = "x".repeat(15000);
        let resp = DeepSearchResponse {
            answer: long_answer,
            sources: vec![],
            metrics: DeepResponseMetrics {
                search_ms: 10,
                triage_ms: 2,
                graph_ms: 3,
                read_ms: 5,
                summarize_ms: 8,
                total_ms: 28,
                chunks_searched: 20,
                chunks_read: 8,
                confidence_zone: String::new(),
            },
            confidence: 0.5,
        };
        let out = format_deep_results(&resp, 5000);
        assert!(out.len() < 6000);
        assert!(out.contains("[answer truncated]"));
    }

    #[test]
    fn test_code_blocks_no_content() {
        // All items have empty content → should return the sentinel string
        let results: Vec<SearchResultItem> = (0..3)
            .map(|i| {
                let mut item = make_result(&format!("file{i}.rs"), 1, 10, None, None, 0.5);
                item.content = Some(String::new());
                item
            })
            .collect();
        let code: Vec<String> = vec![String::new(); 3];
        assert_eq!(
            format_code_blocks(&results, &code, DEFAULT_BUDGET),
            "No code blocks to display."
        );
    }

    #[test]
    fn test_format_graph_all_empty() {
        let resp = GraphWalkResponse {
            target: vec![],
            callers: vec![],
            callees: vec![],
            type_refs: vec![],
            hierarchy: vec![],
        };
        assert_eq!(format_graph_results(&resp), "No graph data found.");
    }

    #[test]
    fn test_code_blocks_budget() {
        let results: Vec<SearchResultItem> = (0..10)
            .map(|i| {
                make_result(
                    &format!("file{i}.rs"),
                    1,
                    100,
                    Some(&format!("Fn{i}")),
                    Some("fn"),
                    0.5,
                )
            })
            .collect();
        let code: Vec<String> = (0..10).map(|_| "x".repeat(2000)).collect();
        let out = format_code_blocks(&results, &code, 6000);
        let block_count = out.matches("###").count();
        assert!((1..=4).contains(&block_count));
    }

    // --- v0.5 Item 6 ----------------------------------------------------

    /// Spec §5 Item 6: rendered block contains the header with actual
    /// count, and one bullet per suggestion in the spec-required format.
    #[test]
    fn append_disambiguation_block_renders_three_entries() {
        let mut out = String::from("preceding output");
        let suggestions = vec![
            DisambigSuggestion {
                name: "userAuthHandler".into(),
                path: "auth/users.rs".into(),
                line: 42,
            },
            DisambigSuggestion {
                name: "tokenAuthHandler".into(),
                path: "auth/tokens.rs".into(),
                line: 18,
            },
            DisambigSuggestion {
                name: "sessionAuth".into(),
                path: "sessions/handler.rs".into(),
                line: 107,
            },
        ];
        append_disambiguation_block(&mut out, &suggestions);
        // Header substitutes the actual count.
        assert!(
            out.contains("[uncertainty: this query matches 3 distinct concepts. Refine with:]"),
            "out: {out}"
        );
        // One bullet per entry in the spec format.
        assert!(
            out.contains("- \"userAuthHandler\" (auth/users.rs:42)"),
            "out: {out}"
        );
        assert!(
            out.contains("- \"tokenAuthHandler\" (auth/tokens.rs:18)"),
            "out: {out}"
        );
        assert!(
            out.contains("- \"sessionAuth\" (sessions/handler.rs:107)"),
            "out: {out}"
        );
        // Preceding content preserved.
        assert!(out.starts_with("preceding output"), "out: {out}");
    }

    /// Empty suggestions → no-op (formatter never emits a stray header).
    #[test]
    fn append_disambiguation_block_noop_on_empty_input() {
        let mut out = String::from("existing");
        append_disambiguation_block(&mut out, &[]);
        assert_eq!(out, "existing");
    }

    /// Single suggestion renders with count "1" and one bullet.
    #[test]
    fn append_disambiguation_block_handles_single_entry() {
        let mut out = String::new();
        append_disambiguation_block(
            &mut out,
            &[DisambigSuggestion {
                name: "only".into(),
                path: "p.rs".into(),
                line: 1,
            }],
        );
        assert!(out.contains("matches 1 distinct concepts"), "out: {out}");
        assert!(out.contains("- \"only\" (p.rs:1)"), "out: {out}");
    }
}