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
use anyhow::{bail, Context, Result};
use clap::{Args, Subcommand};
use colored::Colorize;
use serde::Serialize;
use std::path::PathBuf;

use super::OutputConfig;
use crate::analysis::refs::RefAnalyzer;
use crate::config::Config;
use crate::storage::VectorStore;

#[derive(Args)]
pub struct RefsArgs {
    #[command(subcommand)]
    command: RefsCommand,

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

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

#[derive(Subcommand)]
enum RefsCommand {
    /// Find references to a symbol (definition + usages)
    Find(FindArgs),

    /// List all symbols defined in a file
    Symbols(SymbolsArgs),

    /// Find functions called by a symbol (callees / dependency chain)
    Callees(CalleesArgs),
}

#[derive(Args)]
struct FindArgs {
    /// Symbol name to find references for
    symbol: String,

    /// Filter by symbol type (function, struct, trait, etc.)
    #[arg(long, short = 't')]
    r#type: Option<String>,

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

#[derive(Args)]
struct SymbolsArgs {
    /// File path to list symbols for
    file: PathBuf,
}

#[derive(Args)]
struct CalleesArgs {
    /// Symbol name to find callees for
    symbol: String,

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

#[derive(Serialize)]
struct FindOutput {
    symbol: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    r#type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    definition: Option<DefinitionOutput>,
    usage_count: usize,
    usages: Vec<UsageOutput>,
}

#[derive(Serialize)]
struct DefinitionOutput {
    name: String,
    chunk_type: String,
    file_path: String,
    start_line: u32,
    end_line: u32,
    signature: String,
}

#[derive(Serialize)]
struct UsageOutput {
    file_path: String,
    line: u32,
    context: String,
}

#[derive(Serialize)]
struct CalleesOutput {
    symbol: String,
    callee_count: usize,
    callees: Vec<CalleeOutput>,
}

#[derive(Serialize)]
struct CalleeOutput {
    name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    definition_file: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    definition_line: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    signature: Option<String>,
}

#[derive(Serialize)]
struct SymbolsOutput {
    file: String,
    count: usize,
    symbols: Vec<SymbolOutput>,
}

#[derive(Serialize)]
struct SymbolOutput {
    name: String,
    chunk_type: String,
    start_line: u32,
    end_line: u32,
    signature: String,
}

pub async fn run(args: RefsArgs, output: OutputConfig) -> Result<()> {
    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 lance_path = Config::lance_path(&repo_root);
    let mut vector_store = VectorStore::open(&lance_path)
        .await
        .context("Failed to open vector store")?;

    let stats = vector_store.get_stats(None).await?;
    if stats.total_chunks == 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(());
    }

    match args.command {
        RefsCommand::Find(find_args) => {
            run_find(&mut vector_store, find_args, args.repo.as_deref(), &output).await
        }
        RefsCommand::Symbols(sym_args) => {
            run_symbols(
                &mut vector_store,
                sym_args,
                &repo_root,
                args.repo.as_deref(),
                &output,
            )
            .await
        }
        RefsCommand::Callees(callees_args) => {
            run_callees(
                &mut vector_store,
                callees_args,
                args.repo.as_deref(),
                &output,
            )
            .await
        }
    }
}

async fn run_find(
    vector_store: &mut VectorStore,
    args: FindArgs,
    repo: Option<&str>,
    output: &OutputConfig,
) -> Result<()> {
    let type_filter = args.r#type.as_deref();

    let mut analyzer = RefAnalyzer::new(vector_store);
    let refs = analyzer
        .find_refs(&args.symbol, type_filter, args.limit, repo)
        .await?;

    if output.json {
        let json_output = FindOutput {
            symbol: args.symbol.clone(),
            r#type: args.r#type.clone(),
            definition: refs.definition.map(|d| DefinitionOutput {
                name: d.name,
                chunk_type: d.chunk_type.to_string(),
                file_path: d.file_path,
                start_line: d.start_line,
                end_line: d.end_line,
                signature: d.signature,
            }),
            usage_count: refs.usages.len(),
            usages: refs
                .usages
                .iter()
                .map(|u| UsageOutput {
                    file_path: u.file_path.clone(),
                    line: u.line,
                    context: u.context.clone(),
                })
                .collect(),
        };
        println!("{}", serde_json::to_string_pretty(&json_output)?);
    } else if !output.quiet {
        // Definition
        if let Some(ref def) = refs.definition {
            println!(
                "{} {} {} defined at {}:{}",
                "✓".green(),
                def.chunk_type.to_string().magenta(),
                def.name.cyan().bold(),
                def.file_path.blue(),
                def.start_line,
            );
            println!("  {}", def.signature.dimmed());
        } else {
            println!(
                "{} No definition found for: {}",
                "!".yellow(),
                args.symbol.cyan()
            );
        }

        // Usages
        if refs.usages.is_empty() {
            println!("\n  No usages found.");
        } else {
            println!(
                "\n{} {} usage{}:",
                "→".blue(),
                refs.usages.len(),
                if refs.usages.len() == 1 { "" } else { "s" }
            );
            for usage in &refs.usages {
                println!(
                    "  {}:{} {}",
                    usage.file_path.blue(),
                    usage.line.to_string().dimmed(),
                    usage.context
                );
            }
        }
    }

    Ok(())
}

async fn run_symbols(
    vector_store: &mut VectorStore,
    args: SymbolsArgs,
    repo_root: &std::path::Path,
    repo: Option<&str>,
    output: &OutputConfig,
) -> Result<()> {
    // Resolve file path relative to repo root
    let file_path = args
        .file
        .canonicalize()
        .with_context(|| format!("File not found: {}", args.file.display()))?;

    let rel_path = file_path
        .strip_prefix(repo_root)
        .context("File is not inside the repository")?
        .to_string_lossy()
        .to_string();

    let analyzer = RefAnalyzer::new(vector_store);
    let file_symbols = analyzer.list_symbols(&rel_path, repo).await?;

    if output.json {
        let json_output = SymbolsOutput {
            file: file_symbols.path,
            count: file_symbols.symbols.len(),
            symbols: file_symbols
                .symbols
                .iter()
                .map(|s| SymbolOutput {
                    name: s.name.clone(),
                    chunk_type: s.chunk_type.to_string(),
                    start_line: s.start_line,
                    end_line: s.end_line,
                    signature: s.signature.clone(),
                })
                .collect(),
        };
        println!("{}", serde_json::to_string_pretty(&json_output)?);
    } else if !output.quiet {
        if file_symbols.symbols.is_empty() {
            println!("{} No symbols found in: {}", "!".yellow(), rel_path.cyan());
        } else {
            println!("Symbols in {}:", rel_path.cyan());
            for symbol in &file_symbols.symbols {
                println!(
                    "  {} {} (lines {}-{})",
                    symbol.chunk_type.to_string().magenta(),
                    symbol.name.bold(),
                    symbol.start_line,
                    symbol.end_line,
                );
                if output.verbose {
                    println!("    {}", symbol.signature.dimmed());
                }
            }
            println!(
                "\n{} {} symbol{}",
                "✓".green(),
                file_symbols.symbols.len(),
                if file_symbols.symbols.len() == 1 {
                    ""
                } else {
                    "s"
                }
            );
        }
    }

    Ok(())
}

async fn run_callees(
    vector_store: &mut VectorStore,
    args: CalleesArgs,
    repo: Option<&str>,
    output: &OutputConfig,
) -> Result<()> {
    // First, find the definition to get its content
    let chunks = vector_store.get_chunks_by_name(&args.symbol, repo).await?;
    let chunk = match chunks.into_iter().next() {
        Some(c) => c,
        None => {
            if output.json {
                println!(
                    r#"{{"error": "not_found", "message": "Symbol '{}' not found in index"}}"#,
                    args.symbol
                );
            } else if !output.quiet {
                println!("{} Symbol not found: {}", "!".yellow(), args.symbol.cyan());
            }
            return Ok(());
        }
    };

    let analyzer = RefAnalyzer::new(vector_store);
    let callees = analyzer
        .find_callees(&chunk.content, chunk.name.as_deref(), args.limit, repo)
        .await?;

    if output.json {
        let json_output = CalleesOutput {
            symbol: args.symbol.clone(),
            callee_count: callees.len(),
            callees: callees
                .iter()
                .map(|c| CalleeOutput {
                    name: c.name.clone(),
                    definition_file: c.definition.as_ref().map(|d| d.file_path.clone()),
                    definition_line: c.definition.as_ref().map(|d| d.start_line),
                    signature: c.definition.as_ref().map(|d| d.signature.clone()),
                })
                .collect(),
        };
        println!("{}", serde_json::to_string_pretty(&json_output)?);
    } else if !output.quiet {
        println!(
            "{} Callees of {} {}:",
            "→".blue(),
            chunk.chunk_type.to_string().magenta(),
            args.symbol.cyan().bold(),
        );

        if callees.is_empty() {
            println!("  No resolved callees found.");
        } else {
            for callee in &callees {
                if let Some(ref def) = callee.definition {
                    println!(
                        "  {} {} ({}:{})",
                        "→".green(),
                        callee.name.bold(),
                        def.file_path.blue(),
                        def.start_line,
                    );
                    if output.verbose {
                        println!("    {}", def.signature.dimmed());
                    }
                } else {
                    println!(
                        "  {} {} {}",
                        "?".yellow(),
                        callee.name,
                        "(unresolved)".dimmed()
                    );
                }
            }
            println!(
                "\n{} {} callee{}",
                "✓".green(),
                callees.len(),
                if callees.len() == 1 { "" } else { "s" }
            );
        }
    }

    Ok(())
}