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
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
//! Configuration resolution for gcode.
//!
//! Reads bootstrap.yaml → PostgreSQL hub → config_store → service configs.
//! Resolves $secret:NAME and ${VAR} patterns.
//!
//! Source: src/gobby/config/bootstrap.py, src/gobby/config/persistence.py

use std::fmt;
use std::path::{Path, PathBuf};

use anyhow::Context as _;
use gobby_core::project::{find_project_root, read_project_id};
use postgres::Client;
use uuid::Uuid;

use super::services::{
    read_standalone_config_optional, resolve_code_vector_settings, resolve_embedding_config,
    resolve_falkordb_config, resolve_indexing_settings, resolve_qdrant_config,
};
use crate::db;
use crate::git::{self, WorktreeKind};
use crate::utils::short_id;

/// FalkorDB connection configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FalkorConfig {
    pub host: String,
    pub port: u16,
    pub password: Option<String>,
    pub graph_name: String,
}

/// Qdrant connection configuration.
pub type QdrantConfig = gobby_core::config::QdrantConfig;

/// Embedding API configuration (OpenAI-compatible endpoint).
pub type EmbeddingConfig = gobby_core::config::EmbeddingConfig;

pub const FALKORDB_GRAPH_NAME: &str = gobby_core::config::CODE_GRAPH_NAME;
pub const CODE_SYMBOL_COLLECTION_PREFIX: &str = "code_symbols_";

pub const GOBBY_FALKORDB_HOST_ENV: &str = "GOBBY_FALKORDB_HOST";
pub const GOBBY_FALKORDB_PORT_ENV: &str = "GOBBY_FALKORDB_PORT";
pub const GOBBY_FALKORDB_PASSWORD_ENV: &str = "GOBBY_FALKORDB_PASSWORD";

pub const FALKORDB_HOST_CONFIG_KEY: &str = "databases.falkordb.host";
pub const FALKORDB_PORT_CONFIG_KEY: &str = "databases.falkordb.port";
pub const FALKORDB_PASSWORD_CONFIG_KEY: &str = "databases.falkordb.password";

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CodeVectorSettings {
    pub vector_dim: Option<usize>,
}

pub type IndexingSettings = gobby_core::config::IndexingConfig;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ServiceConfigSelection {
    pub falkordb: bool,
    pub qdrant: bool,
    pub embedding: bool,
    pub code_vectors: bool,
}

impl ServiceConfigSelection {
    pub const fn all() -> Self {
        Self {
            falkordb: true,
            qdrant: true,
            embedding: true,
            code_vectors: true,
        }
    }

    pub const fn database_only() -> Self {
        Self {
            falkordb: false,
            qdrant: false,
            embedding: false,
            code_vectors: false,
        }
    }

    pub const fn falkordb_only() -> Self {
        Self {
            falkordb: true,
            qdrant: false,
            embedding: false,
            code_vectors: false,
        }
    }

    pub const fn qdrant_only() -> Self {
        Self {
            falkordb: false,
            qdrant: true,
            embedding: false,
            code_vectors: false,
        }
    }

    pub const fn projection_cleanup() -> Self {
        Self {
            falkordb: true,
            qdrant: true,
            embedding: false,
            code_vectors: false,
        }
    }

    pub const fn vectors() -> Self {
        Self {
            falkordb: false,
            qdrant: true,
            embedding: true,
            code_vectors: true,
        }
    }

    pub const fn hybrid_search() -> Self {
        Self {
            falkordb: true,
            qdrant: true,
            embedding: true,
            code_vectors: false,
        }
    }
}

impl Default for ServiceConfigSelection {
    fn default() -> Self {
        Self::all()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CodeVectorConfigError {
    InvalidVectorDim { source: &'static str, value: String },
    Read { source: String },
}

impl fmt::Display for CodeVectorConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidVectorDim { source, value } => write!(
                f,
                "invalid code vector dimension from {source}: `{value}` must be a positive integer"
            ),
            Self::Read { source } => write!(f, "failed to read code vector config: {source}"),
        }
    }
}

impl std::error::Error for CodeVectorConfigError {}

impl FalkorConfig {
    pub fn connection_config(&self) -> gobby_core::config::FalkorConfig {
        gobby_core::config::FalkorConfig {
            host: self.host.clone(),
            port: self.port,
            password: self.password.clone(),
        }
    }
}

/// Resolved runtime context for gcode commands.
#[derive(Debug, Clone)]
pub struct Context {
    /// PostgreSQL hub DSN
    pub database_url: String,
    /// Project root directory
    pub project_root: PathBuf,
    /// Project ID (from .gobby/project.json or DB lookup)
    pub project_id: String,
    /// Suppress warnings
    pub quiet: bool,
    /// FalkorDB config (None if unavailable)
    pub falkordb: Option<FalkorConfig>,
    /// Qdrant config (None if unavailable)
    pub qdrant: Option<QdrantConfig>,
    /// Embedding API config (None if unavailable → no semantic search)
    pub embedding: Option<EmbeddingConfig>,
    /// Code-symbol vector projection settings owned by gcode.
    pub code_vectors: CodeVectorSettings,
    /// Shared indexing behavior.
    pub indexing: IndexingSettings,
    /// Gobby daemon base URL (e.g. http://localhost:60887)
    pub daemon_url: Option<String>,
    /// Project read/index scope.
    pub index_scope: ProjectIndexScope,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum ProjectIndexScope {
    #[default]
    Single,
    Overlay {
        overlay_project_id: String,
        overlay_root: PathBuf,
        parent_project_id: String,
        parent_root: PathBuf,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissingIdentity {
    Error,
    Generate,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProjectIdentitySource {
    ProjectJson,
    GcodeJson,
    IsolatedRoot,
    IsolatedOverlay,
    LinkedWorktree,
    Generated,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectIdentity {
    pub project_id: String,
    pub root: PathBuf,
    pub source: ProjectIdentitySource,
    pub warning: Option<String>,
    pub should_write_gcode_json: bool,
    pub index_scope: ProjectIndexScope,
}

impl Context {
    /// Resolve context from CLI args and filesystem state.
    pub fn resolve(project_override: Option<&str>, quiet: bool) -> anyhow::Result<Self> {
        Self::resolve_with_services(project_override, quiet, ServiceConfigSelection::all())
    }

    pub fn resolve_with_services(
        project_override: Option<&str>,
        quiet: bool,
        services: ServiceConfigSelection,
    ) -> anyhow::Result<Self> {
        let database_url = db::resolve_database_url()?;
        let project_root = match project_override {
            Some(p) => {
                let path = PathBuf::from(p);
                if path.is_dir() {
                    path.canonicalize()?
                } else {
                    // Not a directory — try name lookup in the PostgreSQL hub.
                    resolve_project_by_name(p, &database_url)?
                }
            }
            None => detect_project_root()?,
        };

        let identity = resolve_project_identity(&project_root, MissingIdentity::Error)?;
        warn_project_identity(&identity, quiet);
        let project_id = identity.project_id;
        let index_scope = identity.index_scope;

        // Resolve service configs from config_store (best-effort).
        let standalone_config = read_standalone_config_optional();
        let mut conn = db::connect_readonly(&database_url)?;
        validate_parent_code_index(&mut conn, &index_scope)?;
        let falkordb = if services.falkordb {
            resolve_falkordb_config(&mut conn, standalone_config.clone(), quiet)?
        } else {
            None
        };
        let qdrant = if services.qdrant {
            resolve_qdrant_config(&mut conn, standalone_config.clone(), quiet)?
        } else {
            None
        };
        let embedding = if services.embedding {
            resolve_embedding_config(&mut conn, standalone_config.clone(), quiet)?
        } else {
            None
        };
        let indexing = resolve_indexing_settings(&mut conn, standalone_config.clone())?;
        let code_vectors = if services.code_vectors {
            resolve_code_vector_settings(&mut conn, standalone_config)?
        } else {
            CodeVectorSettings::default()
        };

        let daemon_url = Some(gobby_core::daemon_url::daemon_url());

        Ok(Self {
            database_url,
            project_root,
            project_id,
            quiet,
            falkordb,
            qdrant,
            embedding,
            code_vectors,
            indexing,
            daemon_url,
            index_scope,
        })
    }

    /// Resolve selected service configs for a caller-supplied project id without touching cwd identity.
    pub fn resolve_for_project_id_with_services(
        project_id: &str,
        quiet: bool,
        services: ServiceConfigSelection,
    ) -> anyhow::Result<Self> {
        let project_id = normalize_project_id(project_id)?;
        let database_url = db::resolve_database_url()?;

        let standalone_config = read_standalone_config_optional();
        let mut conn = db::connect_readonly(&database_url)?;
        let falkordb = if services.falkordb {
            resolve_falkordb_config(&mut conn, standalone_config.clone(), quiet)?
        } else {
            None
        };
        let qdrant = if services.qdrant {
            resolve_qdrant_config(&mut conn, standalone_config.clone(), quiet)?
        } else {
            None
        };
        let embedding = if services.embedding {
            resolve_embedding_config(&mut conn, standalone_config.clone(), quiet)?
        } else {
            None
        };
        let indexing = resolve_indexing_settings(&mut conn, standalone_config.clone())?;
        let code_vectors = if services.code_vectors {
            resolve_code_vector_settings(&mut conn, standalone_config)?
        } else {
            CodeVectorSettings::default()
        };

        let daemon_url = Some(gobby_core::daemon_url::daemon_url());

        Ok(Self {
            database_url,
            project_root: PathBuf::new(),
            project_id,
            quiet,
            falkordb,
            qdrant,
            embedding,
            code_vectors,
            indexing,
            daemon_url,
            index_scope: ProjectIndexScope::Single,
        })
    }
}

pub fn resolve_project_identity(
    project_root: &Path,
    missing: MissingIdentity,
) -> anyhow::Result<ProjectIdentity> {
    let root = project_root
        .canonicalize()
        .unwrap_or_else(|_| absolute_fallback(project_root));

    if let Some(marker) = crate::project::read_isolation_marker(&root) {
        if marker.parent_project_path.is_some() ^ marker.parent_project_id.is_some() {
            anyhow::bail!(
                "invalid isolation marker in {}: parent_project_path and parent_project_id must be set together",
                root.join(".gobby").join("project.json").display()
            );
        }

        if is_self_referential_isolation_marker(&marker, &root) {
            return resolve_non_isolated_project_identity(root, missing);
        }

        if let (Some(parent_project_path), Some(parent_project_id)) = (
            marker.parent_project_path.as_deref(),
            marker.parent_project_id.as_deref(),
        ) {
            let overlay_project_id = crate::project::code_index_id_for_root(&root);
            let parent_root = resolve_parent_project_root(&root, parent_project_path);
            let parent_project_id = normalize_project_id(parent_project_id)?;
            return Ok(ProjectIdentity {
                project_id: overlay_project_id.clone(),
                root: root.clone(),
                source: ProjectIdentitySource::IsolatedOverlay,
                warning: None,
                should_write_gcode_json: false,
                index_scope: ProjectIndexScope::Overlay {
                    overlay_project_id,
                    overlay_root: root,
                    parent_project_id,
                    parent_root,
                },
            });
        }

        return Ok(ProjectIdentity {
            project_id: crate::project::code_index_id_for_root(&root),
            root,
            source: ProjectIdentitySource::IsolatedRoot,
            warning: None,
            should_write_gcode_json: false,
            index_scope: ProjectIndexScope::Single,
        });
    }

    resolve_non_isolated_project_identity(root, missing)
}

fn resolve_non_isolated_project_identity(
    root: PathBuf,
    missing: MissingIdentity,
) -> anyhow::Result<ProjectIdentity> {
    let worktree = git::worktree_info(&root)?;
    if worktree.kind == WorktreeKind::Linked {
        let project_id = crate::project::code_index_id_for_root(&worktree.top_level);

        return Ok(ProjectIdentity {
            project_id,
            root: worktree.top_level,
            source: ProjectIdentitySource::LinkedWorktree,
            warning: None,
            should_write_gcode_json: false,
            index_scope: ProjectIndexScope::Single,
        });
    }

    let gobby_dir = root.join(".gobby");
    if gobby_dir.join("project.json").exists() {
        return Ok(ProjectIdentity {
            project_id: read_project_id(&root)?,
            root,
            source: ProjectIdentitySource::ProjectJson,
            warning: None,
            should_write_gcode_json: false,
            index_scope: ProjectIndexScope::Single,
        });
    }
    if gobby_dir.join("gcode.json").exists() {
        return Ok(ProjectIdentity {
            project_id: crate::project::read_gcode_json(&root)?,
            root,
            source: ProjectIdentitySource::GcodeJson,
            warning: None,
            should_write_gcode_json: false,
            index_scope: ProjectIndexScope::Single,
        });
    }

    match missing {
        MissingIdentity::Generate => Ok(ProjectIdentity {
            project_id: crate::project::code_index_id_for_root(&root),
            root,
            source: ProjectIdentitySource::Generated,
            warning: None,
            should_write_gcode_json: true,
            index_scope: ProjectIndexScope::Single,
        }),
        MissingIdentity::Error => anyhow::bail!(
            "No gcode project found. Run `gcode init` to initialize, \
             or use `--project <path>` to specify a project directory."
        ),
    }
}

fn is_self_referential_isolation_marker(
    marker: &crate::project::IsolationMarker,
    root: &Path,
) -> bool {
    let Some(parent_project_path) = marker.parent_project_path.as_deref() else {
        return false;
    };
    resolve_parent_project_root(root, parent_project_path) == root
}

fn resolve_parent_project_root(root: &Path, parent_project_path: &str) -> PathBuf {
    let parent = PathBuf::from(parent_project_path);
    let parent = if parent.is_absolute() {
        parent
    } else {
        root.join(parent)
    };
    parent.canonicalize().unwrap_or(parent)
}

fn normalize_project_id(project_id: &str) -> anyhow::Result<String> {
    let project_id = project_id.trim();
    if project_id.is_empty() {
        anyhow::bail!("--project-id must not be empty");
    }
    Uuid::parse_str(project_id)
        .map(|id| id.to_string())
        .with_context(|| format!("--project-id must be a UUID, got `{project_id}`"))
}

pub(crate) fn validate_parent_code_index(
    conn: &mut Client,
    scope: &ProjectIndexScope,
) -> anyhow::Result<()> {
    let ProjectIndexScope::Overlay {
        parent_project_id,
        parent_root,
        ..
    } = scope
    else {
        return Ok(());
    };

    let exists = conn
        .query_one(
            "SELECT EXISTS(
                SELECT 1 FROM code_indexed_files WHERE project_id = $1
            )",
            &[parent_project_id],
        )
        .and_then(|row| row.try_get::<_, bool>(0))?;

    if !exists {
        anyhow::bail!(
            "parent code index missing for {} ({})",
            parent_root.display(),
            short_id(parent_project_id)
        );
    }

    Ok(())
}

pub fn warn_project_identity(identity: &ProjectIdentity, quiet: bool) {
    if quiet {
        return;
    }
    if let Some(warning) = &identity.warning {
        eprintln!("Warning: {warning}");
    }
}

/// Resolve a `--project` name to a project root by looking up `code_indexed_projects`.
///
/// Matches against the basename of `root_path` in the PostgreSQL hub.
fn resolve_project_by_name(name: &str, database_url: &str) -> anyhow::Result<PathBuf> {
    let mut conn = db::connect_readonly(database_url)?;
    let (slash_suffix, backslash_suffix) = project_name_suffixes(name);
    let rows = conn.query(
        "SELECT root_path FROM code_indexed_projects
         WHERE root_path = $1
            OR right(root_path, length($2)) = $2
            OR right(root_path, length($3)) = $3
         ORDER BY last_indexed_at DESC NULLS LAST",
        &[&name, &slash_suffix, &backslash_suffix],
    )?;

    for row in rows {
        let root_path: String = row.try_get("root_path")?;
        let path = PathBuf::from(&root_path);
        if path.is_dir() {
            return Ok(path);
        }
    }

    anyhow::bail!(
        "Project '{}' not found. Run `gcode projects` to see indexed projects.",
        name
    )
}

pub(super) fn project_name_suffixes(name: &str) -> (String, String) {
    (format!("/{name}"), format!("\\{name}"))
}

/// Detect project root by walking up the directory tree.
///
/// Resolution order:
/// 1. `.gobby/project.json` or `.gobby/gcode.json` (identity file)
/// 2. VCS root (`.git` or `.hg`)
/// 3. Current working directory
pub fn detect_project_root() -> anyhow::Result<PathBuf> {
    let cwd = std::env::current_dir()?;
    detect_project_root_from(&cwd)
}

pub fn detect_project_root_from(start: &Path) -> anyhow::Result<PathBuf> {
    let start = start
        .canonicalize()
        .unwrap_or_else(|_| absolute_fallback(start));
    let start = if start.is_file() {
        start
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| start.clone())
    } else {
        start
    };

    // First: look for an identity file (.gobby/project.json or .gobby/gcode.json)
    if let Some(root) = find_project_root(&start) {
        return Ok(root.canonicalize().unwrap_or(root));
    }

    // Second: prefer the Git worktree top-level, including linked worktrees.
    if let Ok(info) = git::worktree_info(&start)
        && info.kind != WorktreeKind::NotGit
    {
        return Ok(info.top_level);
    }

    // Third: fall back to VCS root
    let mut dir = start.as_path();
    loop {
        if dir.join(".git").exists() || dir.join(".hg").exists() {
            return Ok(dir.to_path_buf());
        }
        match dir.parent() {
            Some(parent) => dir = parent,
            None => return Ok(start), // Last resort: start
        }
    }
}

/// Resolve project ID from identity files or generate deterministically.
///
/// Resolution order:
/// 1. `.gobby/project.json` — gobby's file (reads `"id"`, falls back to `"project_id"`)
/// 2. `.gobby/gcode.json` — gcode's standalone identity
/// 3. Generate deterministic UUID5 from canonical path (no filesystem writes)
#[cfg(test)]
pub(super) fn resolve_project_id(project_root: &Path) -> anyhow::Result<String> {
    Ok(resolve_project_identity(project_root, MissingIdentity::Error)?.project_id)
}

fn absolute_fallback(path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .unwrap_or_else(|_| std::env::temp_dir())
            .join(path)
    }
}