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

use super::OutputConfig;
use crate::commands::{self, CommandDef};

#[derive(Args)]
pub struct RunArgs {
    /// Name of the command to execute
    name: Option<String>,

    /// List all defined commands
    #[arg(long, short = 'l')]
    list: bool,

    /// Save a new command (usage: --save NAME -- COMMAND [ARGS...])
    #[arg(long)]
    save: Option<String>,

    /// Remove a command definition
    #[arg(long)]
    remove: Option<String>,

    /// Show a command definition
    #[arg(long)]
    show: Option<String>,

    /// Initialize default search commands (intent-search, find-code, etc.)
    #[arg(long)]
    init: bool,

    /// Description for the command being saved (use with --save)
    #[arg(long, short = 'd')]
    description: Option<String>,

    /// Directory containing the bobbin repo (defaults to current directory)
    #[arg(long, default_value = ".")]
    path: std::path::PathBuf,

    /// Additional arguments appended to the saved command args.
    /// Use `--` to separate from run flags (e.g. `bobbin run my-cmd -- --limit 5`)
    #[arg(last = true)]
    extra_args: Vec<String>,
}

/// JSON output for listing commands
#[derive(Serialize)]
struct CommandListOutput {
    count: usize,
    commands: Vec<CommandListEntry>,
}

#[derive(Serialize)]
struct CommandListEntry {
    name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    command: String,
    args: Vec<String>,
    /// The full command line as a string
    expands_to: String,
}

/// Result of resolving a `bobbin run` invocation.
/// `Execute` means we need to re-dispatch through `Cli::run()` with new args.
/// `Done` means the management operation was completed (list, save, remove, show).
pub enum RunResult {
    /// Re-dispatch: the resolved CLI should be run by the caller
    Execute(Vec<String>),
    /// Management operation completed, nothing more to do
    Done,
}

/// Resolve a `bobbin run` invocation. Returns either resolved CLI args for
/// re-dispatch, or signals that a management operation was already completed.
/// This avoids async recursion between `run::run` and `Cli::run`.
pub fn resolve(args: RunArgs, output: &OutputConfig) -> Result<RunResult> {
    let repo_root = args
        .path
        .canonicalize()
        .unwrap_or_else(|_| args.path.clone());

    // Dispatch to the appropriate suboperation
    if args.list {
        list_commands(&repo_root, output)?;
        return Ok(RunResult::Done);
    }

    if args.init {
        init_defaults(&repo_root, output)?;
        return Ok(RunResult::Done);
    }

    if let Some(name) = &args.show {
        show_command(&repo_root, name, output)?;
        return Ok(RunResult::Done);
    }

    if let Some(name) = &args.remove {
        remove_command(&repo_root, name, output)?;
        return Ok(RunResult::Done);
    }

    if let Some(name) = &args.save {
        save_command(
            &repo_root,
            name,
            args.description.as_deref(),
            &args.extra_args,
            output,
        )?;
        return Ok(RunResult::Done);
    }

    // Execute a named command — return args for re-dispatch
    if let Some(name) = &args.name {
        let full_args = build_command_args(name, &repo_root, &args.extra_args, output)?;
        return Ok(RunResult::Execute(full_args));
    }

    // No action specified — show help
    bail!(
        "No command specified. Usage:\n  \
         bobbin run <name>              Execute a saved command\n  \
         bobbin run --list              List all saved commands\n  \
         bobbin run --init              Initialize default commands\n  \
         bobbin run --save NAME -- CMD  Save a new command\n  \
         bobbin run --show NAME         Show command definition\n  \
         bobbin run --remove NAME       Remove a command"
    );
}

fn list_commands(repo_root: &std::path::Path, output: &OutputConfig) -> Result<()> {
    let commands = commands::load_commands(repo_root)?;

    if output.json {
        let entries: Vec<CommandListEntry> = commands
            .iter()
            .map(|(name, def)| CommandListEntry {
                name: name.clone(),
                description: def.description.clone(),
                command: def.command.clone(),
                args: def.args.clone(),
                expands_to: expand_command(def),
            })
            .collect();

        let list_output = CommandListOutput {
            count: entries.len(),
            commands: entries,
        };
        println!("{}", serde_json::to_string_pretty(&list_output)?);
        return Ok(());
    }

    if commands.is_empty() {
        if !output.quiet {
            println!(
                "{} No commands defined. Save one with: bobbin run --save NAME -- COMMAND [ARGS...]",
                "!".yellow()
            );
        }
        return Ok(());
    }

    if !output.quiet {
        println!(
            "{} {} saved command{}:",
            "✓".green(),
            commands.len(),
            if commands.len() == 1 { "" } else { "s" }
        );
        println!();

        for (name, def) in &commands {
            let desc = def
                .description
                .as_deref()
                .map(|d| format!(" — {}", d.dimmed()))
                .unwrap_or_default();

            println!("  {}{}", name.bold(), desc);
            println!("    {}", expand_command(def).dimmed());
            println!();
        }
    }

    Ok(())
}

fn show_command(repo_root: &std::path::Path, name: &str, output: &OutputConfig) -> Result<()> {
    let commands = commands::load_commands(repo_root)?;

    let Some(def) = commands.get(name) else {
        bail!(
            "Command '{}' not found. Run `bobbin run --list` to see available commands.",
            name
        );
    };

    if output.json {
        let entry = CommandListEntry {
            name: name.to_string(),
            description: def.description.clone(),
            command: def.command.clone(),
            args: def.args.clone(),
            expands_to: expand_command(def),
        };
        println!("{}", serde_json::to_string_pretty(&entry)?);
        return Ok(());
    }

    if !output.quiet {
        let desc = def
            .description
            .as_deref()
            .map(|d| format!(" — {}", d))
            .unwrap_or_default();

        println!("{}{}", name.bold(), desc);
        println!("  Expands to: {}", expand_command(def).cyan());
    }

    Ok(())
}

fn save_command(
    repo_root: &std::path::Path,
    name: &str,
    description: Option<&str>,
    extra_args: &[String],
    output: &OutputConfig,
) -> Result<()> {
    if extra_args.is_empty() {
        bail!(
            "No command specified. Usage: bobbin run --save {} -- COMMAND [ARGS...]\n\
             Example: bobbin run --save find-tests -- search --type function test",
            name
        );
    }

    // Validate name: alphanumeric, hyphens, underscores only
    if !name
        .chars()
        .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
    {
        bail!("Command name must contain only alphanumeric characters, hyphens, and underscores");
    }

    // The first extra arg is the bobbin subcommand, the rest are its args
    let command = extra_args[0].clone();
    let args = extra_args[1..].to_vec();

    // Prevent saving "run" as the underlying command (would cause recursion)
    if command == "run" {
        bail!("Cannot save 'run' as the underlying command (would cause recursion)");
    }

    // Validate that the command is a known bobbin subcommand
    validate_subcommand(&command)?;

    let mut commands = commands::load_commands(repo_root)?;

    let is_update = commands.contains_key(name);

    commands.insert(
        name.to_string(),
        CommandDef {
            description: description.map(|s| s.to_string()),
            command,
            args,
        },
    );

    commands::save_commands(repo_root, &commands)?;

    if output.json {
        let entry = &commands[name];
        let json_entry = CommandListEntry {
            name: name.to_string(),
            description: entry.description.clone(),
            command: entry.command.clone(),
            args: entry.args.clone(),
            expands_to: expand_command(entry),
        };
        println!("{}", serde_json::to_string_pretty(&json_entry)?);
    } else if !output.quiet {
        let verb = if is_update { "Updated" } else { "Saved" };
        println!(
            "{} {} command '{}': {}",
            "✓".green(),
            verb,
            name.bold(),
            expand_command(&commands[name]).cyan()
        );
    }

    Ok(())
}

fn remove_command(repo_root: &std::path::Path, name: &str, output: &OutputConfig) -> Result<()> {
    let mut commands = commands::load_commands(repo_root)?;

    if commands.remove(name).is_none() {
        bail!(
            "Command '{}' not found. Run `bobbin run --list` to see available commands.",
            name
        );
    }

    commands::save_commands(repo_root, &commands)?;

    if output.json {
        println!(r#"{{"removed": "{}"}}"#, name);
    } else if !output.quiet {
        println!("{} Removed command '{}'", "✓".green(), name.bold());
    }

    Ok(())
}

/// Initialize default search commands in `.bobbin/commands.toml`.
/// Only adds commands that don't already exist (won't overwrite user customizations).
pub fn init_defaults(repo_root: &std::path::Path, output: &OutputConfig) -> Result<()> {
    let mut commands = commands::load_commands(repo_root)?;
    let mut added = 0;

    let defaults: Vec<(&str, CommandDef)> = vec![
        (
            "find-code",
            CommandDef {
                description: Some("Search for code (functions, structs, classes)".into()),
                command: "search".into(),
                args: vec!["--type".into(), "function".into()],
            },
        ),
        (
            "find-config",
            CommandDef {
                description: Some("Search config files (toml, yaml, json)".into()),
                command: "grep".into(),
                args: vec!["--type".into(), "other".into()],
            },
        ),
        (
            "find-docs",
            CommandDef {
                description: Some("Search documentation sections".into()),
                command: "search".into(),
                args: vec!["--type".into(), "section".into()],
            },
        ),
        (
            "find-structs",
            CommandDef {
                description: Some("Search for struct/type definitions".into()),
                command: "search".into(),
                args: vec!["--type".into(), "struct".into()],
            },
        ),
        (
            "recent-changes",
            CommandDef {
                description: Some("Show most-changed files (hotspots)".into()),
                command: "hotspots".into(),
                args: vec!["--limit".into(), "15".into()],
            },
        ),
        (
            "what-changed",
            CommandDef {
                description: Some("Search commit history semantically".into()),
                command: "log".into(),
                args: vec![],
            },
        ),
    ];

    for (name, def) in defaults {
        if !commands.contains_key(name) {
            commands.insert(name.to_string(), def);
            added += 1;
        }
    }

    if added > 0 {
        commands::save_commands(repo_root, &commands)?;
    }

    if output.json {
        let entries: Vec<CommandListEntry> = commands
            .iter()
            .map(|(name, def)| CommandListEntry {
                name: name.clone(),
                description: def.description.clone(),
                command: def.command.clone(),
                args: def.args.clone(),
                expands_to: expand_command(def),
            })
            .collect();

        let list_output = CommandListOutput {
            count: entries.len(),
            commands: entries,
        };
        println!("{}", serde_json::to_string_pretty(&list_output)?);
    } else if !output.quiet {
        if added > 0 {
            println!(
                "{} Initialized {} default command{} ({} total)",
                "✓".green(),
                added,
                if added == 1 { "" } else { "s" },
                commands.len()
            );
            println!();
            for (name, def) in &commands {
                let desc = def
                    .description
                    .as_deref()
                    .map(|d| format!(" — {}", d.dimmed()))
                    .unwrap_or_default();
                println!("  {}{}", name.bold(), desc);
                println!("    {}", expand_command(def).dimmed());
                println!();
            }
            println!("{}", "Run any command: bobbin <name> <query>".dimmed());
        } else {
            println!(
                "{} All default commands already exist ({} total)",
                "✓".green(),
                commands.len()
            );
        }
    }

    Ok(())
}

/// Build the full CLI argument vector for a saved command, suitable for
/// re-parsing through `Cli::try_parse_from`.
fn build_command_args(
    name: &str,
    repo_root: &std::path::Path,
    extra_args: &[String],
    output: &OutputConfig,
) -> Result<Vec<String>> {
    let commands = commands::load_commands(repo_root)?;

    let Some(def) = commands.get(name) else {
        bail!(
            "Command '{}' not found. Run `bobbin run --list` to see available commands.",
            name
        );
    };

    let mut full_args = vec!["bobbin".to_string()];

    // Forward current global flags
    if output.json {
        full_args.push("--json".to_string());
    }
    if output.quiet {
        full_args.push("--quiet".to_string());
    }
    if output.verbose {
        full_args.push("--verbose".to_string());
    }
    if let Some(ref server) = output.server {
        full_args.push("--server".to_string());
        full_args.push(server.clone());
    }

    // Add the stored subcommand and args
    full_args.push(def.command.clone());
    full_args.extend(def.args.iter().cloned());

    // Add any extra args from the user
    full_args.extend(extra_args.iter().cloned());

    Ok(full_args)
}

/// Expand a command definition into the equivalent CLI invocation string.
fn expand_command(def: &CommandDef) -> String {
    let mut parts = vec![format!("bobbin {}", def.command)];
    for arg in &def.args {
        if arg.contains(' ') {
            parts.push(format!("\"{}\"", arg));
        } else {
            parts.push(arg.clone());
        }
    }
    parts.join(" ")
}

/// Validate that a command name is a known bobbin subcommand.
fn validate_subcommand(name: &str) -> Result<()> {
    const VALID_COMMANDS: &[&str] = &[
        "init",
        "index",
        "search",
        "context",
        "deps",
        "grep",
        "refs",
        "related",
        "history",
        "log",
        "hotspots",
        "impact",
        "review",
        "similar",
        "status",
        "serve",
        "benchmark",
        "watch",
        "completions",
        "hook",
        "tour",
        "prime",
        "feedback",
    ];

    if VALID_COMMANDS.contains(&name) {
        Ok(())
    } else {
        bail!(
            "Unknown bobbin command '{}'. Valid commands: {}",
            name,
            VALID_COMMANDS.join(", ")
        );
    }
}

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

    #[test]
    fn test_expand_command_basic() {
        let def = CommandDef {
            description: None,
            command: "search".into(),
            args: vec!["--type".into(), "function".into(), "test".into()],
        };
        assert_eq!(expand_command(&def), "bobbin search --type function test");
    }

    #[test]
    fn test_expand_command_no_args() {
        let def = CommandDef {
            description: None,
            command: "status".into(),
            args: vec![],
        };
        assert_eq!(expand_command(&def), "bobbin status");
    }

    #[test]
    fn test_expand_command_quoted_args() {
        let def = CommandDef {
            description: None,
            command: "search".into(),
            args: vec!["hello world".into()],
        };
        assert_eq!(expand_command(&def), "bobbin search \"hello world\"");
    }

    #[test]
    fn test_validate_subcommand_valid() {
        assert!(validate_subcommand("search").is_ok());
        assert!(validate_subcommand("hotspots").is_ok());
        assert!(validate_subcommand("context").is_ok());
        assert!(validate_subcommand("status").is_ok());
    }

    #[test]
    fn test_validate_subcommand_invalid() {
        assert!(validate_subcommand("unknown").is_err());
        assert!(validate_subcommand("run").is_err());
        assert!(validate_subcommand("").is_err());
    }

    #[test]
    fn test_validate_subcommand_rejects_run() {
        // "run" is not in VALID_COMMANDS, preventing recursion
        assert!(validate_subcommand("run").is_err());
    }

    #[test]
    fn test_list_commands_empty_json() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join(".bobbin")).unwrap();

        let output = OutputConfig {
            json: true,
            quiet: false,
            verbose: false,
            server: None,
            role: "default".to_string(),
        };

        // Should succeed with empty list
        let result = list_commands(tmp.path(), &output);
        assert!(result.is_ok());
    }

    #[test]
    fn test_save_and_show_roundtrip() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join(".bobbin")).unwrap();

        let output = OutputConfig {
            json: false,
            quiet: true,
            verbose: false,
            server: None,
            role: "default".to_string(),
        };

        // Save a command
        let extra = vec![
            "search".into(),
            "--type".into(),
            "function".into(),
            "test".into(),
        ];
        save_command(
            tmp.path(),
            "find-tests",
            Some("Find tests"),
            &extra,
            &output,
        )
        .unwrap();

        // Verify it was saved
        let commands = commands::load_commands(tmp.path()).unwrap();
        assert_eq!(commands.len(), 1);
        assert_eq!(commands["find-tests"].command, "search");
        assert_eq!(
            commands["find-tests"].args,
            vec!["--type", "function", "test"]
        );
        assert_eq!(
            commands["find-tests"].description.as_deref(),
            Some("Find tests")
        );
    }

    #[test]
    fn test_save_rejects_invalid_name() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join(".bobbin")).unwrap();

        let output = OutputConfig {
            json: false,
            quiet: true,
            verbose: false,
            server: None,
            role: "default".to_string(),
        };

        let extra = vec!["search".into(), "test".into()];
        let result = save_command(tmp.path(), "bad name!", None, &extra, &output);
        assert!(result.is_err());
    }

    #[test]
    fn test_save_rejects_run_command() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join(".bobbin")).unwrap();

        let output = OutputConfig {
            json: false,
            quiet: true,
            verbose: false,
            server: None,
            role: "default".to_string(),
        };

        let extra = vec!["run".into(), "other".into()];
        let result = save_command(tmp.path(), "recursive", None, &extra, &output);
        assert!(result.is_err());
    }

    #[test]
    fn test_save_rejects_unknown_command() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join(".bobbin")).unwrap();

        let output = OutputConfig {
            json: false,
            quiet: true,
            verbose: false,
            server: None,
            role: "default".to_string(),
        };

        let extra = vec!["nonexistent".into(), "arg".into()];
        let result = save_command(tmp.path(), "bad-cmd", None, &extra, &output);
        assert!(result.is_err());
    }

    #[test]
    fn test_remove_nonexistent() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join(".bobbin")).unwrap();

        let output = OutputConfig {
            json: false,
            quiet: true,
            verbose: false,
            server: None,
            role: "default".to_string(),
        };

        let result = remove_command(tmp.path(), "nonexistent", &output);
        assert!(result.is_err());
    }

    #[test]
    fn test_remove_existing() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join(".bobbin")).unwrap();

        let output = OutputConfig {
            json: false,
            quiet: true,
            verbose: false,
            server: None,
            role: "default".to_string(),
        };

        // Save then remove
        let extra = vec!["search".into(), "test".into()];
        save_command(tmp.path(), "my-cmd", None, &extra, &output).unwrap();
        remove_command(tmp.path(), "my-cmd", &output).unwrap();

        let commands = commands::load_commands(tmp.path()).unwrap();
        assert!(commands.is_empty());
    }
}