bobbin-ai 0.25.2

Local-first context injection engine for AI coding agents
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
use anyhow::{bail, Context, Result};
use clap::Args;
use colored::Colorize;
use serde::Serialize;
use std::path::PathBuf;

use super::OutputConfig;
use crate::access::RepoFilter;
use crate::config::Config;
use crate::index::Embedder;
use crate::search::{HybridSearch, SemanticSearch};
use crate::storage::{MetadataStore, VectorStore};
use crate::tags::{build_tag_exclude_filter, build_tag_include_filter};
use crate::types::{source_kind, ChunkType, MatchType, SearchResult};

#[derive(Args)]
pub struct SearchArgs {
    /// The search query
    query: String,

    /// Filter by chunk type: function, method, class, struct, enum, interface,
    /// module, impl, trait, doc, section, table, code_block, commit, issue
    /// (alias: bead), other.
    #[arg(long, short = 't')]
    r#type: Option<String>,

    /// Maximum number of results
    #[arg(long, short = 'n', default_value = "10")]
    limit: usize,

    /// Search mode: hybrid (default), semantic, or keyword
    #[arg(long, short = 'm', default_value = "hybrid")]
    mode: SearchMode,

    /// Filter results to a specific repository
    #[arg(long, short = 'r')]
    repo: Option<String>,

    /// Filter results to a named repo group (defined in config.toml)
    #[arg(long, short = 'g')]
    group: Option<String>,

    /// Include only chunks with this tag (can be repeated)
    #[arg(long = "tag")]
    tags: Vec<String>,

    /// Exclude chunks with this tag (can be repeated)
    #[arg(long = "exclude-tag")]
    exclude_tags: Vec<String>,

    /// Directory to search in (defaults to current directory)
    #[arg(default_value = ".")]
    path: PathBuf,
}

/// Search mode for the query
#[derive(Debug, Clone, Copy, Default, clap::ValueEnum)]
pub enum SearchMode {
    /// Combine semantic and keyword search using RRF
    #[default]
    Hybrid,
    /// Vector similarity search only
    Semantic,
    /// Full-text keyword search only
    Keyword,
}

/// JSON output format for search results
#[derive(Serialize)]
struct SearchOutput {
    query: String,
    mode: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    r#type: Option<String>,
    limit: usize,
    count: usize,
    results: Vec<SearchResultOutput>,
}

#[derive(Serialize)]
struct SearchResultOutput {
    file_path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<String>,
    chunk_type: String,
    /// Source kind: "code", "issue", or "commit"
    source: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    repo: Option<String>,
    start_line: u32,
    end_line: u32,
    score: f32,
    #[serde(skip_serializing_if = "Option::is_none")]
    match_type: Option<String>,
    language: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    content_preview: Option<String>,
}

// ---------------------------------------------------------------------------
// Query interpretation helpers (#50 item 1)
// ---------------------------------------------------------------------------

/// Resolve the repo filter: an inline `repo:` wins over `--repo`.
///
/// Inline is the more specific statement of intent and it is the precedence
/// the HTTP handler already applies, so the two surfaces agree. Only a single
/// non-negated value counts — `repo:a,b` and `-repo:x` are multi-value/negated
/// and stay in the SQL filter list where they can be expressed properly.
fn resolve_repo(parsed: &crate::search::query::ParsedQuery, flag: Option<&str>) -> Option<String> {
    parsed
        .filters
        .iter()
        .find(|f| {
            f.field == crate::search::query::FilterField::Repo && !f.negated && f.values.len() == 1
        })
        .map(|f| f.values[0].clone())
        .or_else(|| flag.map(str::to_string))
}

/// Resolve the group name: an inline `group:` wins over `--group`.
fn resolve_group(parsed: &crate::search::query::ParsedQuery, flag: Option<&str>) -> Option<String> {
    crate::search::query::extract_group_filters(&parsed.filters)
        .into_iter()
        .next()
        .or_else(|| flag.map(str::to_string))
}

/// The text actually sent to the index.
///
/// The parsed free text, NOT the raw argument: the filters have already become
/// SQL and must not also be matched as literal words — that is what made
/// `bobbin search 'repo:foo bar'` return nothing, since no chunk contains the
/// literal string "repo:foo". A filters-only query has no free text at all, so
/// it falls back to the raw string rather than searching for the empty string.
fn search_text_for(parsed: &crate::search::query::ParsedQuery, raw: &str) -> String {
    if parsed.text_query.is_empty() {
        raw.to_string()
    } else {
        parsed.text_query.clone()
    }
}

/// Everything one search execution needs, so an OR-branched query can run the
/// same code per branch as a plain one.
///
/// This mirrors `http::handlers::search_exec` rather than sharing it: that one
/// is bound to `AppState` (shared embedder cache, HTTP error type), and the
/// CLI has neither. The part that MUST NOT diverge is query interpretation,
/// and that is genuinely shared — `query::parse` and `query::retain_matching`.
struct SearchExec<'a> {
    lance_path: &'a std::path::Path,
    mode: SearchMode,
    limit: usize,
    repo_filter: Option<&'a str>,
    combined_filter: Option<&'a str>,
    embedding: &'a crate::config::EmbeddingConfig,
    model_dir: &'a std::path::Path,
    semantic_weight: f32,
    rrf_k: f32,
    reranker: Option<crate::search::rerank::RerankerConfig>,
}

impl SearchExec<'_> {
    /// Run one query against an already-open store, consuming it.
    async fn run_one(&self, query: &str, vector_store: VectorStore) -> Result<Vec<SearchResult>> {
        match self.mode {
            SearchMode::Keyword => vector_store
                .search_fts_filtered(query, self.limit, self.repo_filter, self.combined_filter)
                .await
                .context("Keyword search failed"),
            SearchMode::Semantic => {
                let embedder = Embedder::from_config(self.embedding, self.model_dir)
                    .context("Failed to load embedding model")?;
                let mut search = SemanticSearch::new(embedder, vector_store);
                search
                    .search_filtered(query, self.limit, self.repo_filter, self.combined_filter)
                    .await
                    .context("Semantic search failed")
            }
            SearchMode::Hybrid => {
                let embedder = Embedder::from_config(self.embedding, self.model_dir)
                    .context("Failed to load embedding model")?;
                let mut search = HybridSearch::new(embedder, vector_store, self.semantic_weight)
                    .with_rrf_k(self.rrf_k)
                    .with_reranker(self.reranker.clone());
                search
                    .search_filtered(query, self.limit, self.repo_filter, self.combined_filter)
                    .await
                    .context("Hybrid search failed")
            }
        }
    }

    /// Run each OR branch and merge by best score per chunk.
    ///
    /// Same merge rule as the HTTP path: a chunk found by two branches keeps
    /// its higher score rather than being counted twice, and the merged set is
    /// re-sorted because per-branch ordering says nothing about the union.
    async fn run_or_branches(&self, branches: &[String]) -> Result<Vec<SearchResult>> {
        use std::collections::HashMap;

        let mut best_by_id: HashMap<String, SearchResult> = HashMap::new();
        for branch in branches {
            let vector_store = VectorStore::open(self.lance_path)
                .await
                .context("Failed to open vector store")?;
            for result in self.run_one(branch, vector_store).await? {
                let id = result.chunk.id.clone();
                match best_by_id.get(&id) {
                    Some(existing) if existing.score >= result.score => {}
                    _ => {
                        best_by_id.insert(id, result);
                    }
                }
            }
        }

        let mut merged: Vec<SearchResult> = best_by_id.into_values().collect();
        merged.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        Ok(merged)
    }
}

pub async fn run(args: SearchArgs, output: OutputConfig) -> Result<()> {
    // Thin-client mode: proxy through remote server
    if let Some(ref server_url) = output.server {
        return run_remote(args, output.clone(), server_url).await;
    }

    let repo_root = args
        .path
        .canonicalize()
        .with_context(|| format!("Invalid path: {}", args.path.display()))?;

    let config_path = Config::config_path(&repo_root);
    if !config_path.exists() {
        bail!("{}", super::not_initialized_error(&repo_root));
    }

    let config = Config::load(&config_path).with_context(|| "Failed to load configuration")?;

    let type_filter = args
        .r#type
        .as_ref()
        .map(|t| parse_chunk_type(t))
        .transpose()?;

    let lance_path = Config::lance_path(&repo_root);
    let db_path = Config::db_path(&repo_root);
    let model_dir = Config::model_cache_dir()?;

    let vector_store = VectorStore::open(&lance_path)
        .await
        .context("Failed to open vector store")?;

    let count = vector_store.count().await?;
    if count == 0 {
        if output.json {
            println!(
                r#"{{"error": "empty_index", "message": "No indexed content. Run `bobbin index` first."}}"#
            );
        } else if !output.quiet {
            println!(
                "{} No indexed content. Run `bobbin index` first.",
                "!".yellow()
            );
        }
        return Ok(());
    }

    // MetadataStore only used for model check
    let metadata_store = MetadataStore::open(&db_path).context("Failed to open metadata store")?;

    let search_limit = if type_filter.is_some() {
        args.limit * 3
    } else {
        args.limit
    };

    // Advanced query syntax — the same parser the HTTP `/search` handler uses.
    // Until this call existed, `bobbin search 'repo:foo lang:rust "error
    // handling"'` sent the whole string to FTS as literal text, so inline
    // filters, phrases, OR/NOT and regex were inert on the CLI while working
    // over HTTP: one query, two answers, depending on how you asked (#50).
    let parsed = crate::search::query::parse(&args.query);

    let inline_repo = resolve_repo(&parsed, args.repo.as_deref());
    let repo_filter = inline_repo.as_deref();
    let group_arg = resolve_group(&parsed, args.group.as_deref());

    // Resolve group filter to SQL clause
    let group_sql = group_arg
        .as_deref()
        .map(|name| {
            config.group_filter(name).ok_or_else(|| {
                let available: Vec<&str> = config.groups.iter().map(|g| g.name.as_str()).collect();
                if available.is_empty() {
                    anyhow::anyhow!("Unknown group '{}'. No groups configured.", name)
                } else {
                    anyhow::anyhow!(
                        "Unknown group '{}'. Available: {}",
                        name,
                        available.join(", ")
                    )
                }
            })
        })
        .transpose()?;

    // Build tag filters and combine with group filter
    let mut extra_filters: Vec<String> = Vec::new();
    // Inline filters (repo:, lang:, type:, file:, path:, tag:) first — group:
    // is excluded by `filters_to_sql` and handled above.
    extra_filters.extend(crate::search::query::filters_to_sql(&parsed.filters));
    if let Some(ref g) = group_sql {
        extra_filters.push(g.clone());
    }
    if !args.tags.is_empty() {
        extra_filters.push(build_tag_include_filter(&args.tags));
    }
    if !args.exclude_tags.is_empty() {
        extra_filters.push(build_tag_exclude_filter(&args.exclude_tags));
    }
    let combined_filter = if extra_filters.is_empty() {
        None
    } else {
        Some(extra_filters.join(" AND "))
    };

    // Model/index agreement is checked once, before any branch runs — a
    // mismatch is a property of the store, not of one query.
    if matches!(args.mode, SearchMode::Semantic | SearchMode::Hybrid) {
        let current_model = config.embedding.model.as_str();
        if let Some(stored) = metadata_store.get_meta("embedding_model")? {
            if stored != current_model {
                bail!(
                    "Configured embedding model ({}) differs from indexed model ({}). Run `bobbin index` to re-index.",
                    current_model,
                    stored
                );
            }
        }
    }

    let search_text = search_text_for(&parsed, &args.query);

    // Config cascade: calibration.json > config.toml (hybrid only).
    let calibration = super::calibrate::load_calibration(&repo_root);
    let exec = SearchExec {
        lance_path: &lance_path,
        mode: args.mode,
        limit: search_limit,
        repo_filter,
        combined_filter: combined_filter.as_deref(),
        embedding: &config.embedding,
        model_dir: &model_dir,
        semantic_weight: calibration
            .as_ref()
            .map(|c| c.best_config.semantic_weight)
            .unwrap_or(config.search.semantic_weight),
        rrf_k: calibration
            .as_ref()
            .map(|c| c.best_config.rrf_k)
            .unwrap_or(config.search.rrf_k),
        reranker: config.search.reranker.clone(),
    };

    // The already-open store serves the single-query path; OR branches reopen
    // per branch, because each executor takes ownership of the store.
    let results = if parsed.has_or && parsed.or_branches.len() > 1 {
        drop(vector_store);
        exec.run_or_branches(&parsed.or_branches).await?
    } else {
        exec.run_one(&search_text, vector_store).await?
    };

    // Apply role-based access filtering
    let access_filter = RepoFilter::from_config(&config.access, &output.role);
    let mut results =
        access_filter.filter_vec(results, |r| RepoFilter::repo_from_path(&r.chunk.file_path));

    // +required / -negated / /regex/ — the same post-filter the HTTP handler
    // applies, called through the shared helper so the two cannot drift.
    crate::search::query::retain_matching(&mut results, &parsed, |r| r.chunk.content.as_str());
    let results = results;

    let filtered_results: Vec<SearchResult> = if let Some(ref chunk_type) = type_filter {
        results
            .into_iter()
            .filter(|r| &r.chunk.chunk_type == chunk_type)
            .take(args.limit)
            .collect()
    } else {
        results.into_iter().take(args.limit).collect()
    };

    if output.json {
        print_json_output(
            &args.query,
            args.mode,
            &args.r#type,
            args.limit,
            &filtered_results,
        )?;
    } else if !output.quiet {
        print_human_output(&args.query, args.mode, &filtered_results, output.verbose);
    }

    Ok(())
}

/// Run search via remote HTTP server (thin-client mode).
async fn run_remote(args: SearchArgs, output: OutputConfig, server_url: &str) -> Result<()> {
    use crate::http::client::Client;

    let client = Client::new(server_url);

    let mode_str = match args.mode {
        SearchMode::Hybrid => "hybrid",
        SearchMode::Semantic => "semantic",
        SearchMode::Keyword => "keyword",
    };

    // Use the already-resolved role (honors --role, then env). Previously this
    // re-resolved with None, so `bobbin search --role X` was ignored in
    // thin-client/server mode and always used the env role.
    let role = output.role.clone();
    let resp = client
        .search(
            &args.query,
            mode_str,
            args.r#type.as_deref(),
            args.limit,
            args.repo.as_deref(),
            Some(&role),
        )
        .await?;

    if output.json {
        let json_output = SearchOutput {
            query: resp.query,
            mode: resp.mode,
            r#type: args.r#type,
            limit: args.limit,
            count: resp.count,
            results: resp
                .results
                .iter()
                .map(|r| SearchResultOutput {
                    file_path: r.file_path.clone(),
                    name: r.name.clone(),
                    chunk_type: r.chunk_type.clone(),
                    source: r.source.clone().unwrap_or_else(|| "code".to_string()),
                    repo: r.repo.clone(),
                    start_line: r.start_line,
                    end_line: r.end_line,
                    score: r.score,
                    match_type: r.match_type.clone(),
                    language: r.language.clone(),
                    content_preview: Some(r.content_preview.clone()),
                })
                .collect(),
        };
        println!("{}", serde_json::to_string_pretty(&json_output)?);
    } else if !output.quiet {
        if resp.results.is_empty() {
            println!(
                "{} No results found for: {} (via {})",
                "!".yellow(),
                args.query.cyan(),
                server_url.dimmed()
            );
            return Ok(());
        }

        println!(
            "{} Found {} results for: {} ({}, via {})",
            "✓".green(),
            resp.results.len(),
            args.query.cyan(),
            resp.mode.dimmed(),
            server_url.dimmed()
        );
        println!();

        for (i, result) in resp.results.iter().enumerate() {
            let name_display = result
                .name
                .as_ref()
                .map(|n| format!(" ({})", n.cyan()))
                .unwrap_or_default();

            println!(
                "{}. {}:{}{}",
                (i + 1).to_string().bold(),
                result.file_path.blue(),
                result.start_line,
                name_display
            );

            let match_info = result
                .match_type
                .as_ref()
                .map(|mt| format!(" [{}]", mt).dimmed().to_string())
                .unwrap_or_default();

            let repo_tag = result
                .repo
                .as_ref()
                .map(|r| format!("[{}] ", r).green().to_string())
                .unwrap_or_default();

            println!(
                "   {}{} {} · lines {}-{} · score {:.4}{}",
                repo_tag,
                result.chunk_type.magenta(),
                result.language.dimmed(),
                result.start_line,
                result.end_line,
                result.score,
                match_info
            );

            if output.verbose {
                let preview = truncate_content(&result.content_preview, 300);
                for line in preview.lines().take(5) {
                    println!("   {}", line.dimmed());
                }
                if result.content_preview.lines().count() > 5 {
                    println!("   {}", "...".dimmed());
                }
            }

            println!();
        }
    }

    Ok(())
}

fn parse_chunk_type(s: &str) -> Result<ChunkType> {
    match s.to_lowercase().as_str() {
        "function" | "func" | "fn" => Ok(ChunkType::Function),
        "method" => Ok(ChunkType::Method),
        "class" => Ok(ChunkType::Class),
        "struct" => Ok(ChunkType::Struct),
        "enum" => Ok(ChunkType::Enum),
        "interface" => Ok(ChunkType::Interface),
        "module" | "mod" => Ok(ChunkType::Module),
        "impl" => Ok(ChunkType::Impl),
        "trait" => Ok(ChunkType::Trait),
        "doc" | "documentation" => Ok(ChunkType::Doc),
        "section" => Ok(ChunkType::Section),
        "table" => Ok(ChunkType::Table),
        "code_block" | "codeblock" => Ok(ChunkType::CodeBlock),
        "commit" => Ok(ChunkType::Commit),
        "issue" | "bead" => Ok(ChunkType::Issue),
        "other" => Ok(ChunkType::Other),
        _ => bail!(
            "Unknown chunk type '{}'. Valid types: function, method, class, struct, enum, interface, module, impl, trait, doc, section, table, code_block, commit, issue, other",
            s
        ),
    }
}

fn print_json_output(
    query: &str,
    mode: SearchMode,
    type_filter: &Option<String>,
    limit: usize,
    results: &[SearchResult],
) -> Result<()> {
    let mode_str = match mode {
        SearchMode::Hybrid => "hybrid",
        SearchMode::Semantic => "semantic",
        SearchMode::Keyword => "keyword",
    };

    let output = SearchOutput {
        query: query.to_string(),
        mode: mode_str.to_string(),
        r#type: type_filter.clone(),
        limit,
        count: results.len(),
        results: results
            .iter()
            .map(|r| SearchResultOutput {
                file_path: r.chunk.file_path.clone(),
                name: r.chunk.name.clone(),
                chunk_type: r.chunk.chunk_type.to_string(),
                source: source_kind(&r.chunk.chunk_type).to_string(),
                repo: r.repo.clone(),
                start_line: r.chunk.start_line,
                end_line: r.chunk.end_line,
                score: r.score,
                match_type: r.match_type.map(|mt| match mt {
                    MatchType::Semantic => "semantic".to_string(),
                    MatchType::Keyword => "keyword".to_string(),
                    MatchType::Hybrid => "hybrid".to_string(),
                }),
                language: r.chunk.language.clone(),
                content_preview: Some(truncate_content(&r.chunk.content, 200)),
            })
            .collect(),
    };

    println!("{}", serde_json::to_string_pretty(&output)?);
    Ok(())
}

fn print_human_output(query: &str, mode: SearchMode, results: &[SearchResult], verbose: bool) {
    if results.is_empty() {
        println!("{} No results found for: {}", "!".yellow(), query.cyan());
        return;
    }

    let mode_str = match mode {
        SearchMode::Hybrid => "hybrid",
        SearchMode::Semantic => "semantic",
        SearchMode::Keyword => "keyword",
    };

    println!(
        "{} Found {} results for: {} ({})",
        "✓".green(),
        results.len(),
        query.cyan(),
        mode_str.dimmed()
    );
    println!();

    for (i, result) in results.iter().enumerate() {
        let chunk = &result.chunk;

        let match_info = match (mode, result.match_type) {
            (SearchMode::Hybrid, Some(MatchType::Hybrid)) => " [hybrid]".yellow().to_string(),
            (SearchMode::Hybrid, Some(MatchType::Semantic)) => " [semantic]".dimmed().to_string(),
            (SearchMode::Hybrid, Some(MatchType::Keyword)) => " [keyword]".dimmed().to_string(),
            _ => String::new(),
        };

        // Show repo tag when available (distinguishes beads-issues from beads source code)
        let repo_tag = result
            .repo
            .as_ref()
            .map(|r| format!("[{}] ", r).green().to_string())
            .unwrap_or_default();

        if chunk.chunk_type == ChunkType::Commit {
            // Commit-specific display
            let name_display = chunk
                .name
                .as_ref()
                .map(|n| n.cyan().to_string())
                .unwrap_or_default();

            println!(
                "{}. {} {}",
                (i + 1).to_string().bold(),
                chunk.file_path.blue(),
                name_display,
            );

            println!(
                "   {}{} · score {:.4}{}",
                repo_tag,
                "commit".magenta(),
                result.score,
                match_info
            );
        } else if chunk.chunk_type == ChunkType::Issue {
            // Issue-specific display (beads from the configured store)
            let name_display = chunk
                .name
                .as_ref()
                .map(|n| n.cyan().to_string())
                .unwrap_or_default();

            println!(
                "{}. {} {}",
                (i + 1).to_string().bold(),
                chunk.file_path.blue(),
                name_display,
            );

            println!(
                "   {}{} · score {:.4}{}",
                repo_tag,
                "issue".magenta(),
                result.score,
                match_info
            );
        } else {
            // Standard code chunk display
            let name_display = chunk
                .name
                .as_ref()
                .map(|n| format!(" ({})", n.cyan()))
                .unwrap_or_default();

            println!(
                "{}. {}:{}{}",
                (i + 1).to_string().bold(),
                chunk.file_path.blue(),
                chunk.start_line,
                name_display
            );

            println!(
                "   {}{} {} · lines {}-{} · score {:.4}{}",
                repo_tag,
                chunk.chunk_type.to_string().magenta(),
                chunk.language.dimmed(),
                chunk.start_line,
                chunk.end_line,
                result.score,
                match_info
            );
        }

        if verbose {
            let preview = truncate_content(&chunk.content, 300);
            for line in preview.lines().take(5) {
                println!("   {}", line.dimmed());
            }
            if chunk.content.lines().count() > 5 {
                println!("   {}", "...".dimmed());
            }
        }

        println!();
    }
}

fn truncate_content(content: &str, max_len: usize) -> String {
    if content.len() <= max_len {
        content.to_string()
    } else {
        let truncated: String = content.chars().take(max_len).collect();
        format!("{}...", truncated.trim_end())
    }
}

#[cfg(test)]
#[path = "search_tests.rs"]
mod tests;