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
use anyhow::Context;
use anyhow::Result;
use chrono::Utc;
use clap::Args;
use colored::Colorize;
use serde::Serialize;
use std::path::PathBuf;

use super::calibrate::{
    self, capture_snapshot_from_index, CalibrationGuard, CalibrationResult, DefaultCalibrationGuard,
};
use super::OutputConfig;
use crate::config::Config;
use crate::index::git::GitAnalyzer;
use crate::storage::VectorStore;
use crate::types::IndexStats;

#[derive(Args)]
pub struct StatusArgs {
    /// Show detailed statistics
    #[arg(long)]
    detailed: bool,

    /// Show stats for a specific repository only
    #[arg(long, short = 'r')]
    repo: Option<String>,

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

#[derive(Serialize)]
struct StatusOutput {
    #[serde(skip_serializing_if = "Option::is_none")]
    gpu: Option<crate::gpu_runtime::Diagnostics>,
    status: String,
    path: String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    repos: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    stats: Option<IndexStats>,
    #[serde(skip_serializing_if = "Option::is_none")]
    calibration: Option<CalibrationStatus>,
    #[serde(skip_serializing_if = "Option::is_none")]
    git: Option<GitStatus>,
    #[serde(skip_serializing_if = "Option::is_none")]
    freshness: Option<Freshness>,
    /// Chunk-edge counts by type (next_chunk, part_of, implements, ...)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    chunk_edges: Vec<(String, u64)>,
}

/// Index freshness relative to git HEAD (bobbin #44).
#[derive(Serialize)]
struct Freshness {
    /// True when HEAD's commit is newer than the last index run (or the repo
    /// has commits but has never been indexed).
    stale: bool,
    /// Committer timestamp (unix seconds) of the current HEAD.
    head_commit_time: i64,
    /// Timestamp (unix seconds) of the most recent index run, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    last_indexed: Option<i64>,
}

impl Freshness {
    fn compute(head_commit_time: i64, last_indexed: Option<i64>) -> Self {
        let stale = match last_indexed {
            Some(ts) => head_commit_time > ts,
            None => true,
        };
        Freshness {
            stale,
            head_commit_time,
            last_indexed,
        }
    }
}

#[derive(Serialize)]
struct CalibrationStatus {
    calibrated: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    calibrated_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    config_summary: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    f1: Option<f32>,
    stale: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    chunk_delta_pct: Option<f32>,
}

#[derive(Serialize)]
struct GitStatus {
    repo_age_days: u32,
    recent_commit_rate: f32,
}

pub async fn run(args: StatusArgs, 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);
    let data_dir = Config::data_dir(&repo_root);

    if !config_path.exists() {
        if output.json {
            let json_output = StatusOutput {
                gpu: Some(crate::gpu_runtime::diagnostics()),
                status: "not_initialized".to_string(),
                path: repo_root.display().to_string(),
                repos: vec![],
                stats: None,
                calibration: None,
                git: None,
                freshness: None,
                chunk_edges: vec![],
            };
            println!("{}", serde_json::to_string_pretty(&json_output)?);
        } else if !output.quiet {
            crate::gpu_runtime::diagnostics().print();
            println!(
                "{} Bobbin not initialized in {}",
                "!".yellow(),
                repo_root.display()
            );
            println!("Run `bobbin init` to initialize.");
        }
        return Ok(());
    }

    // Get stats from LanceDB (primary storage)
    let lance_path = Config::lance_path(&repo_root);
    let vector_store = VectorStore::open(&lance_path)
        .await
        .context("Failed to open vector store")?;

    let repos = vector_store.get_all_repos().await?;
    let stats = vector_store.get_stats(args.repo.as_deref()).await?;

    // Calibration state
    let calibration_result = calibrate::load_calibration(&repo_root);
    let cal_status = build_calibration_status(&calibration_result, stats.total_chunks);

    // Git info + index freshness (bobbin #44): compare HEAD's commit time
    // against the last index run. If HEAD is newer, committed changes have not
    // been picked up — a watcher-drift signal that doesn't false-positive on
    // quiet repos (no new commits => HEAD not newer => not stale).
    let git = GitAnalyzer::new(&repo_root).ok();
    let git_status = git.as_ref().map(build_git_status);
    let freshness = git
        .as_ref()
        .and_then(|g| g.get_head_commit_time())
        .map(|head_ts| Freshness::compute(head_ts, stats.last_indexed));

    if output.json {
        let json_output = StatusOutput {
            gpu: Some(crate::gpu_runtime::diagnostics()),
            status: "ready".to_string(),
            path: data_dir.display().to_string(),
            repos,
            stats: Some(stats),
            calibration: Some(cal_status),
            git: git_status,
            freshness,
            chunk_edges: vector_store
                .get_chunk_edge_stats()
                .await
                .unwrap_or_default(),
        };
        println!("{}", serde_json::to_string_pretty(&json_output)?);
    } else if !output.quiet {
        println!("{} Bobbin status for {}", "✓".green(), repo_root.display());

        crate::gpu_runtime::diagnostics().print();

        // --- Index section ---
        println!("\n{}", "Index".bold());

        if repos.len() > 1 || (repos.len() == 1 && repos[0] != "default") {
            println!("  Repositories: {}", repos.join(", ").cyan());
        }
        if let Some(ref repo) = args.repo {
            println!("  Showing:      {}", repo.cyan());
        }

        println!("  Files:        {}", stats.total_files.to_string().cyan());
        println!("  Chunks:       {}", stats.total_chunks.to_string().cyan());

        // Language distribution
        if !stats.languages.is_empty() {
            let total_files: u64 = stats.languages.iter().map(|l| l.file_count).sum();
            let lang_parts: Vec<String> = stats
                .languages
                .iter()
                .take(5)
                .map(|l| {
                    let pct = if total_files > 0 {
                        (l.file_count as f32 / total_files as f32 * 100.0) as u32
                    } else {
                        0
                    };
                    format!("{} ({}%)", l.language, pct)
                })
                .collect();
            println!("  Languages:    {}", lang_parts.join(", "));
        }

        if let Some(ts) = stats.last_indexed {
            let dt = chrono::DateTime::from_timestamp(ts, 0)
                .map(|t| format_relative_time(t.timestamp()))
                .unwrap_or_else(|| "Unknown".to_string());
            println!("  Last indexed: {}", dt);
        }

        // Freshness signal (bobbin #44): warn when HEAD outpaces the index.
        if let Some(ref f) = freshness {
            if f.stale {
                let behind = f
                    .last_indexed
                    .map(|ts| {
                        format!(
                            " (HEAD is {} newer)",
                            format_duration(f.head_commit_time - ts)
                        )
                    })
                    .unwrap_or_else(|| " (never indexed)".to_string());
                println!(
                    "  Freshness:    {}{}",
                    "stale — run `bobbin index`".yellow(),
                    behind.dimmed()
                );
            } else {
                println!("  Freshness:    {}", "up to date".green());
            }
        }

        // Show dependency stats
        if let Ok((total_deps, resolved_deps)) = vector_store.get_dependency_stats().await {
            if total_deps > 0 {
                println!(
                    "  Dependencies: {} ({} resolved)",
                    total_deps.to_string().cyan(),
                    resolved_deps
                );
            }
        }

        // Show chunk edge stats
        if let Ok(edge_stats) = vector_store.get_chunk_edge_stats().await {
            if !edge_stats.is_empty() {
                let total: u64 = edge_stats.iter().map(|(_, c)| c).sum();
                let breakdown: Vec<String> = edge_stats
                    .iter()
                    .map(|(t, c)| format!("{} {}", c, t))
                    .collect();
                println!(
                    "  Chunk edges:  {} ({})",
                    total.to_string().cyan(),
                    breakdown.join(", ")
                );
            }
        }

        // --- Calibration section ---
        println!("\n{}", "Calibration".bold());
        print_calibration_status(&calibration_result, stats.total_chunks);

        // --- Git section ---
        if let Some(ref gs) = git_status {
            println!("\n{}", "Git".bold());
            let age_str = format_age_days(gs.repo_age_days);
            println!("  Repo age:     {}", age_str);
            println!("  Commit rate:  {:.1} commits/week", gs.recent_commit_rate);
        }

        // --- Detailed language breakdown ---
        if args.detailed && !stats.languages.is_empty() {
            println!("\n{}", "Language Details".bold());
            for lang in &stats.languages {
                println!(
                    "    {}: {} files, {} chunks",
                    lang.language.blue(),
                    lang.file_count,
                    lang.chunk_count
                );
            }
        }
    }

    Ok(())
}

// --- Helpers ---

fn build_calibration_status(
    cal: &Option<CalibrationResult>,
    current_chunks: u64,
) -> CalibrationStatus {
    let Some(cal) = cal else {
        return CalibrationStatus {
            calibrated: false,
            calibrated_at: None,
            config_summary: None,
            f1: None,
            stale: false,
            chunk_delta_pct: None,
        };
    };

    let prev_chunks = cal.snapshot.chunk_count;
    let delta_pct = if prev_chunks > 0 {
        ((current_chunks as f64 - prev_chunks as f64) / prev_chunks as f64 * 100.0) as f32
    } else {
        0.0
    };

    // Check staleness using the CalibrationGuard
    let snapshot = capture_snapshot_from_index(current_chunks as usize);
    let guard = DefaultCalibrationGuard;
    let stale = guard.should_recalibrate(&snapshot, Some(cal));

    let bc = &cal.best_config;
    let mut summary = format!(
        "sw={:.2} dd={:.2} k={:.0}",
        bc.semantic_weight, bc.doc_demotion, bc.rrf_k
    );
    if let Some(hl) = bc.recency_half_life_days {
        summary.push_str(&format!(" hl={:.0}", hl));
    }
    if let Some(rw) = bc.recency_weight {
        summary.push_str(&format!(" rw={:.2}", rw));
    }
    if let Some(cd) = bc.coupling_depth {
        summary.push_str(&format!(" cd={}", cd));
    }
    if let Some(b) = bc.budget_lines {
        if b != 300 {
            summary.push_str(&format!(" b={}", b));
        }
    }
    if let Some(sl) = bc.search_limit {
        if sl != 20 {
            summary.push_str(&format!(" sl={}", sl));
        }
    }

    let f1 = cal.top_results.first().map(|r| r.f1);

    CalibrationStatus {
        calibrated: true,
        calibrated_at: Some(cal.calibrated_at.clone()),
        config_summary: Some(summary),
        f1,
        stale,
        chunk_delta_pct: Some(delta_pct),
    }
}

fn print_calibration_status(cal: &Option<CalibrationResult>, current_chunks: u64) {
    let Some(cal) = cal else {
        println!("  Status:       {}", "not calibrated".yellow());
        println!("  Run `bobbin calibrate` to find optimal search parameters.");
        return;
    };

    // Date formatting
    let cal_date = chrono::DateTime::parse_from_rfc3339(&cal.calibrated_at)
        .map(|t| t.format("%Y-%m-%d").to_string())
        .unwrap_or_else(|_| "unknown".to_string());

    let bc = &cal.best_config;
    let mut config_str = format!(
        "sw={:.2} dd={:.2} k={:.0}",
        bc.semantic_weight, bc.doc_demotion, bc.rrf_k
    );
    if let Some(hl) = bc.recency_half_life_days {
        config_str.push_str(&format!(" hl={:.0}", hl));
    }
    if let Some(rw) = bc.recency_weight {
        config_str.push_str(&format!(" rw={:.2}", rw));
    }
    if let Some(cd) = bc.coupling_depth {
        config_str.push_str(&format!(" cd={}", cd));
    }
    if let Some(b) = bc.budget_lines {
        if b != 300 {
            config_str.push_str(&format!(" b={}", b));
        }
    }
    if let Some(sl) = bc.search_limit {
        if sl != 20 {
            config_str.push_str(&format!(" sl={}", sl));
        }
    }

    let f1 = cal.top_results.first().map(|r| r.f1).unwrap_or(0.0);

    println!("  Status:       {} ({})", "calibrated".green(), cal_date);
    println!("  Config:       {} (F1={:.3})", config_str.cyan(), f1);

    // Staleness check
    let prev_chunks = cal.snapshot.chunk_count;
    let delta_pct = if prev_chunks > 0 {
        ((current_chunks as f64 - prev_chunks as f64) / prev_chunks as f64 * 100.0) as f32
    } else {
        0.0
    };

    let snapshot = capture_snapshot_from_index(current_chunks as usize);
    let guard = DefaultCalibrationGuard;
    let stale = guard.should_recalibrate(&snapshot, Some(cal));

    if stale {
        println!(
            "  Stale:        {} (chunk delta: {:+.0}%)",
            "yes — recalibration recommended".yellow(),
            delta_pct
        );
    } else {
        println!(
            "  Stale:        {} (chunk delta: {:+.0}%)",
            "no".green(),
            delta_pct
        );
    }

    if cal.terse_warning {
        println!(
            "  {}",
            "⚠ Terse commit messages may reduce calibration accuracy".yellow()
        );
    }
}

fn build_git_status(git: &GitAnalyzer) -> GitStatus {
    let repo_age_days = git_repo_age_days(git).unwrap_or(0);
    let recent_commit_rate = git
        .get_commit_log(500, None)
        .ok()
        .map(|commits| {
            let thirty_days_ago = Utc::now().timestamp() - (30 * 86400);
            let count = commits
                .iter()
                .filter(|c| c.timestamp > thirty_days_ago)
                .count();
            count as f32 / 4.3
        })
        .unwrap_or(0.0);

    GitStatus {
        repo_age_days,
        recent_commit_rate,
    }
}

fn git_repo_age_days(git: &GitAnalyzer) -> Result<u32> {
    let output = std::process::Command::new("git")
        .args(["log", "--reverse", "--format=%ct", "-1"])
        .current_dir(git.repo_root())
        .output()
        .context("Failed to get repo age")?;
    let first_ts: i64 = String::from_utf8_lossy(&output.stdout)
        .trim()
        .parse()
        .unwrap_or(0);
    if first_ts == 0 {
        return Ok(0);
    }
    let now = Utc::now().timestamp();
    Ok(((now - first_ts) / 86400) as u32)
}

fn format_relative_time(ts: i64) -> String {
    let now = Utc::now().timestamp();
    let diff = now - ts;
    if diff < 60 {
        "just now".to_string()
    } else if diff < 3600 {
        format!("{} minutes ago", diff / 60)
    } else if diff < 86400 {
        format!("{} hours ago", diff / 3600)
    } else {
        format!("{} days ago", diff / 86400)
    }
}

/// Format a positive duration in seconds as a compact human string.
fn format_duration(secs: i64) -> String {
    let secs = secs.max(0);
    if secs < 60 {
        format!("{}s", secs)
    } else if secs < 3600 {
        format!("{}m", secs / 60)
    } else if secs < 86400 {
        format!("{}h", secs / 3600)
    } else {
        format!("{}d", secs / 86400)
    }
}

fn format_age_days(days: u32) -> String {
    if days < 30 {
        format!("{} days", days)
    } else if days < 365 {
        let months = days as f32 / 30.44;
        format!("{:.1} months", months)
    } else {
        let years = days as f32 / 365.25;
        format!("{:.1} years", years)
    }
}

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

    let client = Client::new(server_url);
    let resp = client.status().await?;

    if output.json {
        let json_output = StatusOutput {
            gpu: None,
            status: resp.status,
            path: server_url.to_string(),
            repos: vec![],
            calibration: None,   // Not available via remote
            git: None,           // Not available via remote
            freshness: None,     // Not available via remote
            chunk_edges: vec![], // Not available via remote
            stats: Some(IndexStats {
                total_files: resp.index.total_files,
                total_chunks: resp.index.total_chunks,
                total_embeddings: resp.index.total_embeddings,
                languages: resp
                    .index
                    .languages
                    .iter()
                    .map(|l| crate::types::LanguageStats {
                        language: l.language.clone(),
                        file_count: l.file_count,
                        chunk_count: l.chunk_count,
                    })
                    .collect(),
                last_indexed: resp.index.last_indexed,
                index_size_bytes: resp.index.index_size_bytes,
            }),
        };
        println!("{}", serde_json::to_string_pretty(&json_output)?);
    } else if !output.quiet {
        println!("{} Bobbin status via {}", "✓".green(), server_url);
        println!();
        println!("  Status:       {}", resp.status.green());
        println!(
            "  Total files:  {}",
            resp.index.total_files.to_string().cyan()
        );
        println!(
            "  Total chunks: {}",
            resp.index.total_chunks.to_string().cyan()
        );

        if let Some(ts) = resp.index.last_indexed {
            let dt = chrono::DateTime::from_timestamp(ts, 0)
                .map(|t| t.to_rfc3339())
                .unwrap_or_else(|| "Unknown".to_string());
            println!("  Last indexed: {}", dt);
        }

        if args.detailed {
            println!("\n  Languages:");
            for lang in &resp.index.languages {
                println!(
                    "    {}: {} files, {} chunks",
                    lang.language.blue(),
                    lang.file_count,
                    lang.chunk_count
                );
            }
        }
    }

    Ok(())
}

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