gobby-code 1.3.3

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
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
use clap::{ArgGroup, Parser, Subcommand, ValueEnum};
use gobby_code::output;
use gobby_core::config::AiRouting;

const DEFAULT_CODEWIKI_GRAPH_EDGE_LIMIT: usize = 5000;
const DEFAULT_SYMBOL_PATH_MAX_DEPTH: usize =
    gobby_code::graph::code_graph::DEFAULT_SYMBOL_PATH_MAX_DEPTH;
const MAX_POSITIVE_USIZE_ARG: usize = 1_000_000_000;
const MAX_GREP_MAX_COUNT: usize = 10_000;

#[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>
  locate by line:   gcode symbol-at src/auth.ts:42
  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(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
pub(crate) enum AiDepthArg {
    Sections,
    #[default]
    Files,
    Symbols,
}

impl From<AiDepthArg> for gobby_code::commands::codewiki::AiDepth {
    fn from(value: AiDepthArg) -> Self {
        match value {
            AiDepthArg::Sections => Self::Sections,
            AiDepthArg::Files => Self::Files,
            AiDepthArg::Symbols => Self::Symbols,
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
pub(crate) enum AiProseDepthArg {
    Brief,
    #[default]
    Standard,
    Deep,
}

impl From<AiProseDepthArg> for gobby_code::commands::codewiki::ProseDepth {
    fn from(value: AiProseDepthArg) -> Self {
        match value {
            AiProseDepthArg::Brief => Self::Brief,
            AiProseDepthArg::Standard => Self::Standard,
            AiProseDepthArg::Deep => Self::Deep,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
pub(crate) enum AiRegisterArg {
    Newcomer,
    Maintainer,
    Agent,
}

impl From<AiRegisterArg> for gobby_code::commands::codewiki::ProseRegister {
    fn from(value: AiRegisterArg) -> Self {
        match value {
            AiRegisterArg::Newcomer => Self::Newcomer,
            AiRegisterArg::Maintainer => Self::Maintainer,
            AiRegisterArg::Agent => Self::Agent,
        }
    }
}

#[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 + semantic (Qdrant) + 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>,
        /// Trim returned rows to an approximate token budget
        #[arg(long, value_parser = positive_usize)]
        token_budget: Option<usize>,
    },
    /// 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,
        /// Match only standalone ASCII identifier words
        #[arg(short = 'w', long)]
        word: 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, up to 10000
        #[arg(short = 'm', long, value_parser = grep_max_count)]
        max_count: Option<usize>,
    },

    // ── 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 },
    /// Fetch symbol source code at PATH:LINE or PATH:LINE:COLUMN
    SymbolAt {
        /// Location containing line information; conflicts with separate LINE
        #[arg(value_name = "PATH[:LINE[:COLUMN]]")]
        location: String,
        /// 1-based line number; do not pass when LOCATION already includes a line
        #[arg(value_name = "LINE", value_parser = positive_usize)]
        line: Option<usize>,
    },
    /// 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>,
        /// AI prose depth: sections (architecture/modules/repo), files (+ per-file
        /// summaries), symbols (+ one call per symbol — expensive on large repos)
        #[arg(long, value_enum, default_value_t = AiDepthArg::Files)]
        ai_depth: AiDepthArg,
        /// Daemon feature profile for aggregate docs (architecture/modules/repo)
        /// [default: opus-first writer chain — claude/opus@high, codex/gpt-5.5@xhigh]
        #[arg(long, value_name = "PROFILE")]
        ai_aggregate_profile: Option<String>,
        /// Daemon feature profile for grounded verification
        /// [default: feature_mid]
        #[arg(long, value_name = "PROFILE")]
        ai_verify_profile: Option<String>,
        /// Prose verbosity: brief (terser), standard (default), or deep (longer,
        /// richer). Orthogonal to --ai-depth; raises the per-page token budget.
        #[arg(long, value_enum, default_value_t = AiProseDepthArg::Standard)]
        ai_prose_depth: AiProseDepthArg,
        /// Audience register for generated prose: newcomer (ELI5, plain
        /// language), maintainer (why + trade-offs), or agent (terse build
        /// substrate). Omit to keep the base voice. Grounding holds in all.
        #[arg(long, value_enum)]
        ai_register: Option<AiRegisterArg>,
        /// Maximum graph edges to fetch from FalkorDB
        #[arg(long, default_value_t = DEFAULT_CODEWIKI_GRAPH_EDGE_LIMIT, value_parser = positive_usize)]
        edge_limit: usize,
        /// Also document content-only files (markdown, plain text). By default
        /// codewiki documents only code and structured config (json/yaml);
        /// narrative markdown belongs to gwiki.
        #[arg(long)]
        include_docs: bool,
        /// Incremental driver: regenerate only pages whose sources or cross-file
        /// neighbors changed since this git ref, plus aggregate pages whose model
        /// digest changed. `git diff --name-only <ref>` selects the change set;
        /// omitting it runs a full content-hash scan. Out-of-scope pages and
        /// `_meta` are preserved either way.
        #[arg(long, value_name = "GIT_REF")]
        since: Option<String>,
        /// Repair-only mode: re-anchor existing pages' `[file:line]` citations
        /// against the current index and exit. No generation, no AI/LLM calls.
        /// Ignores generation flags (`--ai`, `--scope`, `--ai-depth`, …); honors
        /// `--out`/`--format`.
        #[arg(long)]
        repair_citations: bool,
    },

    // ── 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,
        /// Trim returned rows to an approximate token budget
        #[arg(long, value_parser = positive_usize)]
        token_budget: Option<usize>,
    },
    /// Show import graph for a file [requires graph backend]
    Imports { file: String },
    /// Shortest CALLS path from one symbol query to another [requires graph backend]
    Path {
        /// Source symbol query
        #[arg(value_name = "SYMBOL_A")]
        symbol_a: String,
        /// Target symbol query
        #[arg(value_name = "SYMBOL_B")]
        symbol_b: String,
        /// Maximum CALLS hops to search
        #[arg(long, default_value_t = DEFAULT_SYMBOL_PATH_MAX_DEPTH, value_parser = positive_usize)]
        max_depth: usize,
    },
    /// 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,
        /// Trim returned rows to an approximate token budget
        #[arg(long, value_parser = positive_usize)]
        token_budget: Option<usize>,
    },

    // ── Project Management ───────────────────────────────────────────
    /// Directory-grouped project stats
    RepoOutline,
    /// List indexed projects
    Projects,
    /// Remove stale projects and reconcile orphaned graph + vector projection state across indexed projects
    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,
    /// Remove project-wide orphaned graph nodes (run periodically; not on every file sync)
    CleanupOrphans,
    /// 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,
        /// Skip sync if indexed file not found (daemon/background-worker only)
        #[arg(long)]
        allow_missing_indexed_file: bool,
    },
    /// Clear the current project's code-symbol vector projection
    Clear,
    /// Rebuild the current project's code-symbol vector projection from PostgreSQL facts
    Rebuild,
    /// Remove code-symbol vectors for files no longer indexed in PostgreSQL
    CleanupOrphans,
}

#[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())
    }
}

fn positive_usize(value: &str) -> Result<usize, String> {
    bounded_positive_usize(value, MAX_POSITIVE_USIZE_ARG, "value")
}

fn grep_max_count(value: &str) -> Result<usize, String> {
    bounded_positive_usize(value, MAX_GREP_MAX_COUNT, "--max-count")
}

fn bounded_positive_usize(value: &str, max: usize, name: &str) -> Result<usize, String> {
    let parsed = value
        .parse::<usize>()
        .map_err(|_| format!("{name} must be a positive integer"))?;
    if parsed == 0 {
        Err(format!("{name} must be a positive integer"))
    } else if parsed > max {
        Err(format!("{name} must be no more than {max}"))
    } else {
        Ok(parsed)
    }
}

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,
    })
}

#[cfg(test)]
mod tests;

#[cfg(test)]
mod symbol_at_tests;