gobby-code 0.4.4

Fast Rust CLI for Gobby's code index — AST-aware search, symbol navigation, and dependency graph
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
//! Neo4j HTTP API client for graph queries and writes.
//!
//! Sends Cypher queries via POST /db/{database}/query/v2 with Basic Auth.
//!
//! Read helpers (wrapped by `with_neo4j`) degrade gracefully — returning
//! empty results on connection failure. Write functions (`write_defines`,
//! `write_calls`, `write_imports`, `delete_file_graph`) propagate errors
//! to callers via `Result<()>` so failures can be tracked.

use std::collections::HashMap;

use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use serde_json::Value;

use crate::config::{Context, Neo4jConfig};
use crate::models::{CallRelation, GraphResult, ImportRelation, Symbol};

/// Row from a Neo4j v2 query response.
pub type Row = HashMap<String, Value>;

/// Blocking HTTP client for the Neo4j Query API v2.
pub struct Neo4jClient {
    client: reqwest::blocking::Client,
    url: String,
    database: String,
    auth_header: Option<String>,
}

impl Neo4jClient {
    pub fn from_config(config: &Neo4jConfig) -> Self {
        let auth_header = config
            .auth
            .as_ref()
            .map(|a| format!("Basic {}", STANDARD.encode(a.as_bytes())));
        Self {
            client: reqwest::blocking::Client::builder()
                .timeout(std::time::Duration::from_secs(15))
                .build()
                .expect("failed to build HTTP client"),
            url: config.url.trim_end_matches('/').to_string(),
            database: config.database.clone(),
            auth_header,
        }
    }

    /// Execute a Cypher query and return parsed rows.
    pub fn query(&self, cypher: &str, params: Option<Value>) -> anyhow::Result<Vec<Row>> {
        let path = format!("{}/db/{}/query/v2", self.url, self.database);
        let mut body = serde_json::json!({"statement": cypher});
        if let Some(p) = params {
            body["parameters"] = p;
        }

        let mut req = self
            .client
            .post(&path)
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            .json(&body);

        if let Some(auth) = &self.auth_header {
            req = req.header("Authorization", auth);
        }

        let response = req.send()?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().unwrap_or_default();
            anyhow::bail!("Neo4j query error: HTTP {status}: {body}");
        }

        let data: Value = response.json()?;
        Ok(parse_v2_response(&data))
    }
}

/// Parse Neo4j HTTP API v2 response into flat row dicts.
/// Format: {"data": {"fields": [...], "values": [[...], ...]}}
fn parse_v2_response(data: &Value) -> Vec<Row> {
    let result_data = data.get("data").unwrap_or(&Value::Null);
    let fields: Vec<String> = result_data
        .get("fields")
        .and_then(|f| f.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();
    let values = result_data
        .get("values")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();

    values
        .into_iter()
        .filter_map(|row_val| {
            let row_arr = row_val.as_array()?;
            let mut row = HashMap::new();
            for (i, field) in fields.iter().enumerate() {
                let val = row_arr.get(i).cloned().unwrap_or(Value::Null);
                row.insert(field.clone(), val);
            }
            Some(row)
        })
        .collect()
}

// ── Helper: run graph query with graceful degradation ────────────────

fn with_neo4j<T>(
    ctx: &Context,
    default: T,
    f: impl FnOnce(&Neo4jClient) -> anyhow::Result<T>,
) -> anyhow::Result<T> {
    match &ctx.neo4j {
        Some(config) => {
            let client = Neo4jClient::from_config(config);
            match f(&client) {
                Ok(v) => Ok(v),
                Err(e) => {
                    if !ctx.quiet {
                        eprintln!("Warning: Neo4j query failed: {e}");
                    }
                    Ok(default)
                }
            }
        }
        None => Ok(default),
    }
}

fn row_to_graph_result(row: &Row) -> GraphResult {
    GraphResult {
        id: row
            .get("caller_id")
            .or_else(|| row.get("callee_id"))
            .or_else(|| row.get("source_id"))
            .or_else(|| row.get("symbol_id"))
            .or_else(|| row.get("id"))
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string(),
        name: row
            .get("caller_name")
            .or_else(|| row.get("callee_name"))
            .or_else(|| row.get("source_name"))
            .or_else(|| row.get("symbol_name"))
            .or_else(|| row.get("name"))
            .or_else(|| row.get("module_name"))
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string(),
        file_path: row
            .get("file")
            .or_else(|| row.get("file_path"))
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string(),
        line: row.get("line").and_then(|v| v.as_u64()).unwrap_or(0) as usize,
        relation: row
            .get("relation")
            .or_else(|| row.get("rel_type"))
            .and_then(|v| v.as_str())
            .map(String::from),
        distance: row
            .get("distance")
            .and_then(|v| v.as_u64())
            .map(|d| d as usize),
    }
}

// ── Graph query functions (read) ─────────────────────────────────────

/// Count callers of a symbol (server-side COUNT for accurate pagination total).
pub fn count_callers(ctx: &Context, symbol_name: &str) -> anyhow::Result<usize> {
    with_neo4j(ctx, 0, |client| {
        let rows = client.query(
            "MATCH (caller:CodeSymbol)-[:CALLS]->(callee:CodeSymbol {name: $name, project: $project}) \
             RETURN count(caller) AS cnt",
            Some(serde_json::json!({
                "name": symbol_name,
                "project": ctx.project_id,
            })),
        )?;
        let count = rows
            .first()
            .and_then(|r| r.get("cnt"))
            .and_then(|v| v.as_u64())
            .unwrap_or(0) as usize;
        Ok(count)
    })
}

/// Count usages of a symbol (server-side COUNT for accurate pagination total).
pub fn count_usages(ctx: &Context, symbol_name: &str) -> anyhow::Result<usize> {
    with_neo4j(ctx, 0, |client| {
        let rows = client.query(
            "MATCH (n)-[r]->(target:CodeSymbol {name: $name, project: $project}) \
             WHERE type(r) IN ['CALLS', 'IMPORTS'] \
             RETURN count(n) AS cnt",
            Some(serde_json::json!({
                "name": symbol_name,
                "project": ctx.project_id,
            })),
        )?;
        let count = rows
            .first()
            .and_then(|r| r.get("cnt"))
            .and_then(|v| v.as_u64())
            .unwrap_or(0) as usize;
        Ok(count)
    })
}

/// Find symbols that call the given symbol name.
pub fn find_callers(
    ctx: &Context,
    symbol_name: &str,
    offset: usize,
    limit: usize,
) -> anyhow::Result<Vec<GraphResult>> {
    with_neo4j(ctx, vec![], |client| {
        let rows = client.query(
            "MATCH (caller:CodeSymbol)-[r:CALLS]->(callee:CodeSymbol {name: $name, project: $project}) \
             RETURN caller.id AS caller_id, caller.name AS caller_name, \
                    r.file AS file, r.line AS line \
             SKIP $offset LIMIT $limit",
            Some(serde_json::json!({
                "name": symbol_name,
                "project": ctx.project_id,
                "offset": offset,
                "limit": limit,
            })),
        )?;
        Ok(rows.iter().map(row_to_graph_result).collect())
    })
}

/// Find all usages of a symbol (callers + imports).
pub fn find_usages(
    ctx: &Context,
    symbol_name: &str,
    offset: usize,
    limit: usize,
) -> anyhow::Result<Vec<GraphResult>> {
    with_neo4j(ctx, vec![], |client| {
        let rows = client.query(
            "MATCH (n)-[r]->(target:CodeSymbol {name: $name, project: $project}) \
             WHERE type(r) IN ['CALLS', 'IMPORTS'] \
             RETURN n.id AS source_id, n.name AS source_name, \
                    type(r) AS rel_type, r.file AS file, r.line AS line \
             SKIP $offset LIMIT $limit",
            Some(serde_json::json!({
                "name": symbol_name,
                "project": ctx.project_id,
                "offset": offset,
                "limit": limit,
            })),
        )?;
        Ok(rows.iter().map(row_to_graph_result).collect())
    })
}

/// Find symbols that call any of the given symbol names (batch).
/// Used by graph expansion to find callers of top search results.
pub fn find_callers_batch(
    ctx: &Context,
    names: &[String],
    limit: usize,
) -> anyhow::Result<Vec<GraphResult>> {
    if names.is_empty() {
        return Ok(vec![]);
    }
    with_neo4j(ctx, vec![], |client| {
        let rows = client.query(
            "MATCH (caller:CodeSymbol)-[r:CALLS]->(callee:CodeSymbol {project: $project}) \
             WHERE callee.name IN $names \
             RETURN caller.id AS caller_id, caller.name AS caller_name, \
                    r.file AS file, r.line AS line \
             LIMIT $limit",
            Some(serde_json::json!({
                "names": names,
                "project": ctx.project_id,
                "limit": limit,
            })),
        )?;
        Ok(rows.iter().map(row_to_graph_result).collect())
    })
}

/// Find symbols called by any of the given symbol names (batch).
/// Used by graph expansion to find callees of top search results.
pub fn find_callees_batch(
    ctx: &Context,
    names: &[String],
    limit: usize,
) -> anyhow::Result<Vec<GraphResult>> {
    if names.is_empty() {
        return Ok(vec![]);
    }
    with_neo4j(ctx, vec![], |client| {
        let rows = client.query(
            "MATCH (src:CodeSymbol {project: $project})-[r:CALLS]->(callee:CodeSymbol) \
             WHERE src.name IN $names \
             RETURN callee.id AS callee_id, callee.name AS callee_name, \
                    r.file AS file, r.line AS line \
             LIMIT $limit",
            Some(serde_json::json!({
                "names": names,
                "project": ctx.project_id,
                "limit": limit,
            })),
        )?;
        Ok(rows.iter().map(row_to_graph_result).collect())
    })
}

/// Get import graph for a file.
pub fn get_imports(ctx: &Context, file_path: &str) -> anyhow::Result<Vec<GraphResult>> {
    with_neo4j(ctx, vec![], |client| {
        let rows = client.query(
            "MATCH (f:CodeFile {path: $path, project: $project})-[:IMPORTS]->(m:CodeModule) \
             RETURN m.name AS module_name",
            Some(serde_json::json!({
                "path": file_path,
                "project": ctx.project_id,
            })),
        )?;
        Ok(rows.iter().map(row_to_graph_result).collect())
    })
}

/// Find transitive blast radius of changing a symbol.
pub fn blast_radius(ctx: &Context, target: &str, depth: usize) -> anyhow::Result<Vec<GraphResult>> {
    let depth = depth.clamp(1, 5);
    with_neo4j(ctx, vec![], |client| {
        // Neo4j doesn't support parameterized path length, so we interpolate depth
        // (it's clamped to 1-5, safe for interpolation)
        let cypher = format!(
            "MATCH path = (affected:CodeSymbol)-[:CALLS*1..{depth}]->(\
                target:CodeSymbol {{name: $name, project: $project}}) \
             WITH affected, min(length(path)) AS distance \
             OPTIONAL MATCH (file:CodeFile)-[:DEFINES]->(affected) \
             RETURN DISTINCT affected.id AS symbol_id, \
                    affected.name AS symbol_name, \
                    affected.kind AS kind, file.path AS file_path, \
                    distance \
             ORDER BY distance ASC, affected.name ASC \
             LIMIT $limit"
        );
        let rows = client.query(
            &cypher,
            Some(serde_json::json!({
                "name": target,
                "project": ctx.project_id,
                "limit": 100,
            })),
        )?;
        Ok(rows.iter().map(row_to_graph_result).collect())
    })
}

// ── Graph write functions (for indexing) ──────────────────────────────

/// Write DEFINES edges: file → symbol.
pub fn write_defines(
    client: &Neo4jClient,
    project_id: &str,
    file_path: &str,
    symbols: &[Symbol],
) -> anyhow::Result<()> {
    for sym in symbols {
        client.query(
            "MERGE (f:CodeFile {path: $file, project: $project}) \
             MERGE (s:CodeSymbol {id: $symbol_id, project: $project}) \
             SET s.name = $name, s.kind = $kind \
             MERGE (f)-[:DEFINES]->(s)",
            Some(serde_json::json!({
                "file": file_path,
                "project": project_id,
                "symbol_id": sym.id,
                "name": sym.name,
                "kind": sym.kind,
            })),
        )?;
    }
    Ok(())
}

/// Write CALLS edges: caller → callee.
pub fn write_calls(
    client: &Neo4jClient,
    project_id: &str,
    calls: &[CallRelation],
) -> anyhow::Result<()> {
    for call in calls {
        client.query(
            "MERGE (caller:CodeSymbol {id: $caller_id, project: $project}) \
             MERGE (callee:CodeSymbol {name: $callee_name, project: $project}) \
             MERGE (caller)-[:CALLS {file: $file, line: $line}]->(callee)",
            Some(serde_json::json!({
                "caller_id": call.caller_id,
                "callee_name": call.callee_name,
                "file": call.file_path,
                "line": call.line,
                "project": project_id,
            })),
        )?;
    }
    Ok(())
}

/// Write IMPORTS edges: file → module.
pub fn write_imports(
    client: &Neo4jClient,
    project_id: &str,
    imports: &[ImportRelation],
) -> anyhow::Result<()> {
    for imp in imports {
        client.query(
            "MERGE (f:CodeFile {path: $source, project: $project}) \
             MERGE (m:CodeModule {name: $target, project: $project}) \
             MERGE (f)-[:IMPORTS]->(m)",
            Some(serde_json::json!({
                "source": imp.file_path,
                "target": imp.module_name,
                "project": project_id,
            })),
        )?;
    }
    Ok(())
}

/// Delete graph data for a file before re-indexing.
///
/// Preserves incoming CALLS edges to symbol nodes (from other files).
/// Symbol nodes become orphaned but are re-merged by write_defines.
pub fn delete_file_graph(
    client: &Neo4jClient,
    project_id: &str,
    file_path: &str,
) -> anyhow::Result<()> {
    // 1. Delete outgoing relationships from symbols defined in this file
    // 2. Detach-delete the CodeFile node (removes DEFINES + IMPORTS edges)
    // Symbol nodes remain with incoming CALLS edges intact.
    client.query(
        "MATCH (f:CodeFile {path: $file_path, project: $project}) \
         OPTIONAL MATCH (f)-[:DEFINES]->(s:CodeSymbol) \
         OPTIONAL MATCH (s)-[r_out]->() \
         DELETE r_out \
         WITH f \
         DETACH DELETE f",
        Some(serde_json::json!({
            "file_path": file_path,
            "project": project_id,
        })),
    )?;
    // Clean up orphaned modules
    client.query(
        "MATCH (m:CodeModule {project: $project}) \
         WHERE NOT (m)<-[:IMPORTS]-() \
         DETACH DELETE m",
        Some(serde_json::json!({
            "project": project_id,
        })),
    )?;
    Ok(())
}

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

    #[test]
    fn test_parse_v2_response_basic() {
        let data = serde_json::json!({
            "data": {
                "fields": ["name", "age"],
                "values": [
                    ["Alice", 30],
                    ["Bob", 25]
                ]
            }
        });
        let rows = parse_v2_response(&data);
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0]["name"], "Alice");
        assert_eq!(rows[0]["age"], 30);
        assert_eq!(rows[1]["name"], "Bob");
    }

    #[test]
    fn test_parse_v2_response_empty() {
        let data = serde_json::json!({"data": {"fields": [], "values": []}});
        let rows = parse_v2_response(&data);
        assert!(rows.is_empty());
    }

    #[test]
    fn test_parse_v2_response_null_values() {
        let data = serde_json::json!({
            "data": {
                "fields": ["id", "name"],
                "values": [
                    ["abc", null]
                ]
            }
        });
        let rows = parse_v2_response(&data);
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0]["id"], "abc");
        assert!(rows[0]["name"].is_null());
    }

    #[test]
    fn test_parse_v2_response_mismatched_lengths() {
        let data = serde_json::json!({
            "data": {
                "fields": ["a", "b", "c"],
                "values": [
                    ["x"]
                ]
            }
        });
        let rows = parse_v2_response(&data);
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0]["a"], "x");
        assert!(rows[0]["b"].is_null());
        assert!(rows[0]["c"].is_null());
    }

    #[test]
    fn test_parse_v2_response_missing_data() {
        let data = serde_json::json!({});
        let rows = parse_v2_response(&data);
        assert!(rows.is_empty());
    }
}