gobby-code 0.9.9

Fast Rust CLI for Gobby's code index — AST-aware search, symbol navigation, and dependency graph
Documentation
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
use clap::{ArgAction, ArgGroup, Parser, Subcommand, ValueEnum};
use gobby_code::output;
use gobby_core::config::AiRouting;

#[derive(Parser)]
#[command(
    name = "gcode",
    version,
    about = "Fast code index CLI for Gobby",
    after_help = "Examples:
  find call sites:   gcode grep \"spawn_ui_server(\" [PATH...] -m 50
  read function:    gcode search-symbol \"spawn_ui_server\" --kind function
                    gcode symbol <id>
  find config key:  gcode grep \"config.ui.mode\" -F [PATH...] -m 50"
)]
pub(crate) struct Cli {
    /// Override project root (default: detect from cwd)
    #[arg(long, global = true)]
    pub(crate) project: Option<String>,

    /// Output format
    #[arg(long, global = true)]
    pub(crate) format: Option<output::Format>,

    /// Suppress warnings
    #[arg(long, global = true)]
    pub(crate) quiet: bool,

    /// Enable verbose output
    #[arg(long, global = true)]
    pub(crate) verbose: bool,

    /// Skip read-time freshness checks
    #[arg(long, global = true)]
    pub(crate) no_freshness: bool,

    #[command(subcommand)]
    pub(crate) command: Command,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
pub(crate) enum AiRouteArg {
    Auto,
    Daemon,
    Direct,
    Off,
}

impl From<AiRouteArg> for AiRouting {
    fn from(value: AiRouteArg) -> Self {
        match value {
            AiRouteArg::Auto => AiRouting::Auto,
            AiRouteArg::Daemon => AiRouting::Daemon,
            AiRouteArg::Direct => AiRouting::Direct,
            AiRouteArg::Off => AiRouting::Off,
        }
    }
}

#[derive(Subcommand)]
pub(crate) enum Command {
    /// Emit the CLI contract for daemon conformance tests
    Contract,

    // ── Project Setup ────────────────────────────────────────────────
    /// Initialize project context (.gobby/gcode.json)
    Init,
    /// Explicitly create gcode-owned standalone database objects
    Setup {
        /// Required opt-in for setup writes in v1
        #[arg(long, required = true)]
        standalone: bool,
        /// PostgreSQL database URL to set up
        #[arg(long)]
        database_url: Option<String>,
        /// Skip Docker service provisioning
        #[arg(long)]
        no_services: bool,
        /// Drop/recreate gcode-owned code-index state and clear code-index projections
        #[arg(long)]
        overwrite_code_index: bool,
        /// PostgreSQL schema namespace for gcode-owned objects
        #[arg(long, default_value = "public")]
        schema: String,
        /// Embedding provider to store in gcore.yaml
        #[arg(long)]
        embedding_provider: Option<String>,
        /// OpenAI-compatible embedding API base URL
        #[arg(long)]
        embedding_api_base: Option<String>,
        /// Embedding model name
        #[arg(long)]
        embedding_model: Option<String>,
        /// Query prefix to prepend before embedding search queries
        #[arg(long)]
        embedding_query_prefix: Option<String>,
        /// Embedding vector dimension
        #[arg(long)]
        embedding_vector_dim: Option<usize>,
        /// Embedding API key to store in local gcore.yaml
        #[arg(long)]
        embedding_api_key: Option<String>,
        /// FalkorDB host to store in gcore.yaml
        #[arg(long)]
        falkordb_host: Option<String>,
        /// FalkorDB port to store in gcore.yaml
        #[arg(long)]
        falkordb_port: Option<u16>,
        /// FalkorDB password for Docker provisioning or external config
        #[arg(long)]
        falkordb_password: Option<String>,
        /// Qdrant URL to store in gcore.yaml when services are not provisioned
        #[arg(long)]
        qdrant_url: Option<String>,
    },
    /// Index a directory (full or incremental). Writes symbols, files, and chunks to PostgreSQL hub
    Index {
        /// Path to index (default: project root)
        path: Option<String>,
        /// Index only specific files
        #[arg(long, num_args = 1..)]
        files: Option<Vec<String>>,
        /// Force full reindex (skip incremental hash check)
        #[arg(long)]
        full: bool,
        /// Fail C/C++ indexing when clangd or compile_commands.json semantics are unavailable
        #[arg(long)]
        require_cpp_semantics: bool,
        /// Synchronously update graph and vector projections after PostgreSQL indexing
        #[arg(long)]
        sync_projections: bool,
    },
    /// Show project index status
    Status,
    /// Clear index and force re-index
    Invalidate {
        /// Skip confirmation prompt
        #[arg(long)]
        force: bool,
    },
    /// Manage and inspect the code-index graph projection [requires FalkorDB]
    Graph {
        #[command(subcommand)]
        command: GraphCommand,
    },
    /// Manage the code-symbol vector projection [requires Qdrant and embeddings]
    Vector {
        #[command(subcommand)]
        command: VectorCommand,
    },
    /// Inspect embedding configuration consistency
    Embeddings {
        #[command(subcommand)]
        command: EmbeddingsCommand,
    },

    // ── Search (works in all modes) ──────────────────────────────────
    /// Hybrid search: pg_search BM25 + optional semantic (Qdrant) + optional graph boost (FalkorDB)
    #[command(
        after_help = "`gcode search` is hybrid/fuzzy concept search. Use `gcode grep \"pattern\" [PATH...] -m 50` for exact literals, call sites, dotted config keys, quoted strings, and paths. Use `gcode search-content \"query\" [PATH...]` for ranked file-content matches."
    )]
    Search {
        query: String,
        /// Optional file paths or globs to filter results
        #[arg(value_name = "PATH")]
        paths: Vec<String>,
        #[arg(long, default_value = "10")]
        limit: usize,
        /// Skip first N results (for pagination)
        #[arg(long, default_value = "0")]
        offset: usize,
        /// Filter by symbol kind
        #[arg(long)]
        kind: Option<String>,
        /// Filter by source language (e.g. rust, python, css)
        #[arg(long)]
        language: Option<String>,
    },
    /// Exact-first symbol/name search with deterministic ranking
    SearchSymbol {
        query: String,
        /// Optional file paths or globs to filter results
        #[arg(value_name = "PATH")]
        paths: Vec<String>,
        #[arg(long, default_value = "10")]
        limit: usize,
        /// Skip first N results (for pagination)
        #[arg(long, default_value = "0")]
        offset: usize,
        /// Filter by symbol kind
        #[arg(long)]
        kind: Option<String>,
        /// Filter by source language (e.g. rust, python, css)
        #[arg(long)]
        language: Option<String>,
        /// Include FalkorDB graph neighbors in the exact-first ranking [requires graph backend]
        #[arg(long)]
        with_graph: bool,
    },
    /// pg_search BM25 search on symbol metadata (names, signatures, docstrings)
    SearchText {
        query: String,
        /// Optional file paths or globs to filter results
        #[arg(value_name = "PATH")]
        paths: Vec<String>,
        #[arg(long, default_value = "10")]
        limit: usize,
        /// Skip first N results (for pagination)
        #[arg(long, default_value = "0")]
        offset: usize,
        /// Filter by source language (e.g. rust, python, css)
        #[arg(long)]
        language: Option<String>,
    },
    /// pg_search BM25 search on file content chunks
    SearchContent {
        query: String,
        /// Optional file paths or globs to filter results
        #[arg(value_name = "PATH")]
        paths: Vec<String>,
        #[arg(long, default_value = "10")]
        limit: usize,
        /// Skip first N results (for pagination)
        #[arg(long, default_value = "0")]
        offset: usize,
        /// Filter by source language (e.g. rust, python, css)
        #[arg(long)]
        language: Option<String>,
    },
    /// Indexed grep: exact pattern search on content chunks
    #[command(
        after_help = "gcode grep is indexed search over code_content_chunks. Unsupported grep/rg flags are intentionally rejected; use raw `rg` for filesystem grep."
    )]
    Grep {
        /// Pattern to search for (regex or fixed string)
        #[arg(value_parser = non_empty_grep_pattern)]
        pattern: String,
        /// Optional file paths or globs to filter results
        #[arg(value_name = "PATH")]
        paths: Vec<String>,
        /// Treat pattern as fixed string, not regex
        #[arg(short = 'F', long)]
        fixed_strings: bool,
        /// Match case-insensitively
        #[arg(short = 'i', long)]
        ignore_case: bool,
        /// Show N context lines before match
        #[arg(short = 'B', long)]
        before_context: Option<usize>,
        /// Show N context lines after match
        #[arg(short = 'A', long)]
        after_context: Option<usize>,
        /// Show N context lines before and after match
        #[arg(short = 'C', long)]
        context: Option<usize>,
        /// Glob pattern to filter files, ANDed with PATH filters when both are present
        /// (bare globs match basenames; slash globs match paths)
        #[arg(short = 'g', long)]
        glob: Vec<String>,
        /// Maximum matching lines to include
        #[arg(short = 'm', long)]
        max_count: Option<usize>,
        /// Show line numbers (always shown, deprecated flag for compatibility)
        #[arg(short = 'n', long)]
        line_number: bool,
        /// Unsupported: use -m/--max-count for indexed grep caps
        #[arg(long = "limit", hide = true, action = ArgAction::SetTrue)]
        unsupported_limit: bool,
        /// Unsupported: use raw rg for filesystem grep
        #[arg(short = 'l', long = "files-with-matches", hide = true, action = ArgAction::SetTrue)]
        unsupported_files_with_matches: bool,
        /// Unsupported: use raw rg for filesystem grep
        #[arg(short = 'L', long = "files-without-match", hide = true, action = ArgAction::SetTrue)]
        unsupported_files_without_match: bool,
        /// Unsupported: use raw rg for filesystem grep
        #[arg(short = 'c', long = "count", hide = true, action = ArgAction::SetTrue)]
        unsupported_count: bool,
        /// Unsupported: use raw rg for filesystem grep
        #[arg(short = 'o', long = "only-matching", hide = true, action = ArgAction::SetTrue)]
        unsupported_only_matching: bool,
        /// Unsupported: use raw rg for filesystem grep
        #[arg(short = 'v', long = "invert-match", hide = true, action = ArgAction::SetTrue)]
        unsupported_invert_match: bool,
        /// Unsupported: use raw rg for filesystem grep
        #[arg(short = 'w', long = "word-regexp", hide = true, action = ArgAction::SetTrue)]
        unsupported_word_regexp: bool,
        /// Unsupported: use raw rg for filesystem grep
        #[arg(short = 'e', long = "regexp", hide = true)]
        unsupported_regexp: Option<String>,
        /// Unsupported: use raw rg for filesystem grep
        #[arg(short = 'r', long = "recursive", hide = true, action = ArgAction::SetTrue)]
        unsupported_recursive: bool,
        /// Unsupported: use raw rg for filesystem grep
        #[arg(short = 't', long = "type", hide = true)]
        unsupported_type: Option<String>,
        /// Unsupported: use raw rg for filesystem grep
        #[arg(short = 'T', long = "type-not", hide = true)]
        unsupported_type_not: Option<String>,
        /// Unsupported: use raw rg for filesystem grep
        #[arg(short = 'P', long = "pcre2", hide = true, action = ArgAction::SetTrue)]
        unsupported_pcre2: bool,
        /// Unsupported: use raw rg for filesystem grep
        #[arg(short = 'U', long = "multiline", hide = true, action = ArgAction::SetTrue)]
        unsupported_multiline: bool,
        /// Unsupported: use --format json for structured indexed grep output
        #[arg(long = "json", hide = true, action = ArgAction::SetTrue)]
        unsupported_json: bool,
    },

    // ── Symbol Retrieval (works in all modes) ────────────────────────
    /// Hierarchical symbol tree for a file
    Outline {
        /// Use text generation to produce a natural-language outline when configured
        #[arg(long)]
        summarize: bool,
        file: String,
    },
    /// Fetch symbol source code by ID (byte-offset read)
    Symbol { id: String },
    /// Batch retrieve symbols by ID
    Symbols { ids: Vec<String> },
    /// List distinct symbol kinds in the index
    Kinds,
    /// File tree with symbol counts
    Tree,
    /// Generate vault-ready hierarchical code documentation
    Codewiki {
        /// Output directory for generated Markdown docs
        #[arg(long)]
        out: Option<String>,
        /// Limit docs to indexed files under one or more paths
        #[arg(long, num_args = 1.., value_name = "PATH")]
        scope: Vec<String>,
        /// Override AI routing for generated summaries
        #[arg(long, value_enum)]
        ai: Option<AiRouteArg>,
    },

    // ── Dependency Graph (requires graph backend) ──────────────────────
    /// Find callers of a symbol query, resolved to a canonical symbol ID [requires graph backend]
    Callers {
        symbol_name: String,
        #[arg(long, default_value = "10")]
        limit: usize,
        /// Skip first N results (for pagination)
        #[arg(long, default_value = "0")]
        offset: usize,
    },
    /// Find incoming call usages of a symbol query, resolved to a canonical symbol ID [requires graph backend]
    Usages {
        symbol_name: String,
        #[arg(long, default_value = "10")]
        limit: usize,
        /// Skip first N results (for pagination)
        #[arg(long, default_value = "0")]
        offset: usize,
    },
    /// Show import graph for a file [requires graph backend]
    Imports { file: String },
    /// Transitive impact analysis for a symbol query, resolved to a canonical symbol ID [requires graph backend]
    BlastRadius {
        /// Symbol query
        target: String,
        #[arg(long, default_value = "3")]
        depth: usize,
    },

    // ── Project Management ───────────────────────────────────────────
    /// Directory-grouped project stats
    RepoOutline,
    /// List indexed projects
    Projects,
    /// Remove stale projects (dead paths, invalid entries)
    Prune {
        /// Skip confirmation prompt
        #[arg(long)]
        force: bool,
    },
}

#[derive(Subcommand)]
pub(crate) enum GraphCommand {
    /// Sync one indexed file into the code-index graph projection
    SyncFile {
        /// Indexed file path to sync
        #[arg(long)]
        file: String,
        /// Skip sync if indexed file not found (daemon/background-worker only)
        #[arg(long)]
        allow_missing_indexed_file: bool,
    },
    /// Clear the current project's code-index graph projection
    Clear {
        /// Clear graph projection for this project id without resolving cwd project context
        #[arg(long)]
        project_id: Option<String>,
    },
    /// Rebuild the current project's code-index graph projection from PostgreSQL facts
    Rebuild,
    /// Generate a project graph report
    Report {
        /// Number of top hotspot and target rows to include
        #[arg(long, default_value = "10")]
        top_n: usize,
    },
    /// Show an overview graph for the current project
    Overview {
        /// Maximum files to include
        #[arg(long, default_value = "100")]
        limit: usize,
    },
    /// Show graph nodes and links for one indexed file
    File {
        /// Indexed file path to inspect
        #[arg(long)]
        file: String,
    },
    /// Show graph neighbors for one symbol ID
    Neighbors {
        /// Symbol ID to inspect
        #[arg(long)]
        symbol_id: String,
        #[arg(long, default_value = "100")]
        limit: usize,
    },
    /// Show transitive graph impact for a symbol ID or file path
    #[command(group(
        ArgGroup::new("target")
            .required(true)
            .args(["symbol_id", "file"])
    ))]
    BlastRadius {
        /// Symbol ID to inspect
        #[arg(long)]
        symbol_id: Option<String>,
        /// Indexed file path to inspect
        #[arg(long)]
        file: Option<String>,
        #[arg(long, default_value = "3")]
        depth: usize,
        #[arg(long, default_value = "100")]
        limit: usize,
    },
}

#[derive(Subcommand)]
pub(crate) enum VectorCommand {
    /// Sync one indexed file into the code-symbol vector projection
    SyncFile {
        /// Indexed file path to sync
        #[arg(long)]
        file: String,
    },
    /// Clear the current project's code-symbol vector projection
    Clear,
    /// Rebuild the current project's code-symbol vector projection from PostgreSQL facts
    Rebuild,
}

#[derive(Subcommand)]
pub(crate) enum EmbeddingsCommand {
    /// Emit embedding configuration doctor JSON
    Doctor,
}

fn non_empty_grep_pattern(value: &str) -> Result<String, String> {
    if value.is_empty() {
        Err("gcode grep pattern cannot be empty".to_string())
    } else {
        Ok(value.to_string())
    }
}

pub(crate) fn effective_format(
    explicit_format: Option<output::Format>,
    command: &Command,
) -> output::Format {
    explicit_format.unwrap_or(match command {
        Command::Grep { .. } => output::Format::Text,
        _ => output::Format::Json,
    })
}

pub(crate) fn reject_unsupported_grep_flags(command: &Command) -> anyhow::Result<()> {
    let Command::Grep {
        unsupported_limit,
        unsupported_files_with_matches,
        unsupported_files_without_match,
        unsupported_count,
        unsupported_only_matching,
        unsupported_invert_match,
        unsupported_word_regexp,
        unsupported_regexp,
        unsupported_recursive,
        unsupported_type,
        unsupported_type_not,
        unsupported_pcre2,
        unsupported_multiline,
        unsupported_json,
        ..
    } = command
    else {
        return Ok(());
    };

    let flag = first_set_flag(&[
        ("--limit", *unsupported_limit),
        ("--files-with-matches", *unsupported_files_with_matches),
        ("--files-without-match", *unsupported_files_without_match),
        ("--count", *unsupported_count),
        ("--only-matching", *unsupported_only_matching),
        ("--invert-match", *unsupported_invert_match),
        ("--word-regexp", *unsupported_word_regexp),
        ("--regexp", unsupported_regexp.is_some()),
        ("--recursive", *unsupported_recursive),
        ("--type", unsupported_type.is_some()),
        ("--type-not", unsupported_type_not.is_some()),
        ("--pcre2", *unsupported_pcre2),
        ("--multiline", *unsupported_multiline),
        ("--json", *unsupported_json),
    ]);

    if let Some(flag) = flag {
        anyhow::bail!(
            "gcode grep is indexed search; unsupported grep/rg flag `{flag}`. Use -m/--max-count for match caps or raw `rg` for filesystem grep."
        );
    }

    Ok(())
}

fn first_set_flag(flags: &[(&'static str, bool)]) -> Option<&'static str> {
    flags
        .iter()
        .find_map(|(flag, is_set)| is_set.then_some(*flag))
}

#[cfg(test)]
mod tests;