repotoire 0.3.47

Graph-powered code analysis CLI. 81 detectors for security, architecture, and code quality.
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
//! MCP Tool handlers
//!
//! Implementation of each MCP tool's functionality.

use anyhow::{Context, Result};
use serde_json::{json, Value};
use std::path::PathBuf;
use std::sync::Arc;

use crate::ai::{AiClient, LlmBackend};
use crate::detectors::{default_detectors, DetectorEngineBuilder};
use crate::graph::GraphStore;
use crate::models::FindingsSummary;

/// State shared across tool calls
pub struct HandlerState {
    /// Path to the repository being analyzed
    pub repo_path: PathBuf,
    /// Graph client (lazily initialized)
    graph: Option<Arc<GraphStore>>,
    /// API key for cloud PRO features
    pub api_key: Option<String>,
    /// API base URL
    pub api_url: String,
    /// BYOK: User's own AI backend
    pub ai_backend: Option<LlmBackend>,
}

impl HandlerState {
    pub fn new(repo_path: PathBuf) -> Self {
        let api_key = std::env::var("REPOTOIRE_API_KEY").ok();
        let api_url = std::env::var("REPOTOIRE_API_URL")
            .unwrap_or_else(|_| "https://api.repotoire.io".to_string());

        // Check for BYOK keys (in order of preference)
        let ai_backend = if std::env::var("ANTHROPIC_API_KEY").is_ok() {
            Some(LlmBackend::Anthropic)
        } else if std::env::var("OPENAI_API_KEY").is_ok() {
            Some(LlmBackend::OpenAi)
        } else if std::env::var("DEEPINFRA_API_KEY").is_ok() {
            Some(LlmBackend::Deepinfra)
        } else if std::env::var("OPENROUTER_API_KEY").is_ok() {
            Some(LlmBackend::OpenRouter)
        } else if AiClient::ollama_available() {
            Some(LlmBackend::Ollama)
        } else {
            None
        };

        Self {
            repo_path,
            graph: None,
            api_key,
            api_url,
            ai_backend,
        }
    }

    pub fn is_pro(&self) -> bool {
        self.api_key.is_some()
    }

    /// Check if user has BYOK AI keys
    pub fn has_ai(&self) -> bool {
        self.ai_backend.is_some()
    }

    /// Get mode description
    pub fn mode_description(&self) -> &'static str {
        if self.is_pro() {
            "PRO (cloud)"
        } else if self.has_ai() {
            "BYOK (local AI)"
        } else {
            "FREE"
        }
    }

    /// Get or initialize the graph client
    pub fn get_graph(&mut self) -> Result<Arc<GraphStore>> {
        if let Some(ref client) = self.graph {
            return Ok(Arc::clone(client));
        }

        let db_path = self.repo_path.join(".repotoire").join("graph");
        let client = GraphStore::new(&db_path)
            .context("Failed to initialize graph database")?;
        let client = Arc::new(client);
        self.graph = Some(Arc::clone(&client));
        Ok(client)
    }
}

// =============================================================================
// FREE Tier Tool Handlers
// =============================================================================

/// Run code analysis on the repository
pub fn handle_analyze(state: &mut HandlerState, args: &Value) -> Result<Value> {
    let repo_path = args
        .get("repo_path")
        .and_then(|v| v.as_str())
        .map(PathBuf::from)
        .unwrap_or_else(|| state.repo_path.clone());

    let _incremental = args
        .get("incremental")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);

    // Get graph client
    let graph = state.get_graph()?;

    // Build detector engine
    let engine = DetectorEngineBuilder::new()
        .workers(4)
        .detectors(default_detectors(&repo_path))
        .build();

    // Run analysis - engine.run() returns Vec<Finding> directly
    let findings = engine.run(&graph)?;

    let summary = FindingsSummary::from_findings(&findings);

    Ok(json!({
        "status": "completed",
        "repo_path": repo_path.display().to_string(),
        "total_findings": summary.total,
        "by_severity": {
            "critical": summary.critical,
            "high": summary.high,
            "medium": summary.medium,
            "low": summary.low,
            "info": summary.info
        },
        "message": format!("Analysis complete. Found {} issues.", summary.total)
    }))
}

/// Execute a query on the code graph (limited - Cypher no longer supported)
pub fn handle_query_graph(state: &mut HandlerState, args: &Value) -> Result<Value> {
    let query_type = args
        .get("type")
        .and_then(|v| v.as_str())
        .unwrap_or("functions");

    let graph = state.get_graph()?;
    
    let results: Vec<serde_json::Value> = match query_type {
        "functions" => {
            graph.get_functions()
                .iter()
                .take(100)
                .map(|f| json!({
                    "qualified_name": f.qualified_name,
                    "name": f.name,
                    "file_path": f.file_path,
                    "line_start": f.line_start,
                    "complexity": f.complexity()
                }))
                .collect()
        }
        "classes" => {
            graph.get_classes()
                .iter()
                .take(100)
                .map(|c| json!({
                    "qualified_name": c.qualified_name,
                    "name": c.name,
                    "file_path": c.file_path,
                    "line_start": c.line_start
                }))
                .collect()
        }
        "files" => {
            graph.get_files()
                .iter()
                .take(100)
                .map(|f| json!({
                    "file_path": f.file_path,
                    "language": f.language
                }))
                .collect()
        }
        "stats" => {
            vec![json!(graph.stats())]
        }
        _ => {
            return Err(anyhow::anyhow!("Unknown query type: {}. Use: functions, classes, files, stats", query_type));
        }
    };

    Ok(json!({
        "results": results,
        "count": results.len()
    }))
}

/// Get findings from the last analysis
pub fn handle_get_findings(state: &mut HandlerState, args: &Value) -> Result<Value> {
    let severity = args.get("severity").and_then(|v| v.as_str());
    let detector = args.get("detector").and_then(|v| v.as_str());
    let limit = args
        .get("limit")
        .and_then(|v| v.as_u64())
        .unwrap_or(20) as usize;

    // Try to read from findings file first
    let findings_path = state.repo_path.join(".repotoire").join("last_findings.json");
    if findings_path.exists() {
        let content = std::fs::read_to_string(&findings_path)?;
        let parsed: Value = serde_json::from_str(&content)?;
        let mut findings: Vec<Value> = parsed
            .get("findings")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();

        // Apply filters
        if let Some(sev) = severity {
            findings.retain(|f| {
                f.get("severity")
                    .and_then(|v| v.as_str())
                    .map(|s| s == sev)
                    .unwrap_or(false)
            });
        }
        if let Some(det) = detector {
            findings.retain(|f| {
                f.get("detector")
                    .and_then(|v| v.as_str())
                    .map(|d| d == det)
                    .unwrap_or(false)
            });
        }

        let count = findings.len();
        findings.truncate(limit);

        return Ok(json!({
            "findings": findings,
            "count": count,
            "returned": findings.len()
        }));
    }

    // Fall back to running analysis
    let graph = state.get_graph()?;
    let engine = DetectorEngineBuilder::new()
        .workers(4)
        .detectors(default_detectors(&state.repo_path))
        .build();

    // engine.run() returns Vec<Finding> directly
    let mut findings = engine.run(&graph)?;

    // Apply filters
    if let Some(sev) = severity {
        findings.retain(|f| f.severity.to_string() == sev);
    }
    if let Some(det) = detector {
        findings.retain(|f| f.detector == det);
    }

    let count = findings.len();
    findings.truncate(limit);

    Ok(json!({
        "findings": findings,
        "count": count,
        "returned": findings.len()
    }))
}

/// Read file content
pub fn handle_get_file(state: &HandlerState, args: &Value) -> Result<Value> {
    let file_path = args
        .get("file_path")
        .and_then(|v| v.as_str())
        .context("Missing required argument: file_path")?;

    let start_line = args.get("start_line").and_then(|v| v.as_u64());
    let end_line = args.get("end_line").and_then(|v| v.as_u64());

    let full_path = state.repo_path.join(file_path);
    if !full_path.exists() {
        return Ok(json!({
            "error": format!("File not found: {}", file_path)
        }));
    }

    let content = std::fs::read_to_string(&full_path)?;
    let lines: Vec<&str> = content.lines().collect();
    let total_lines = lines.len();

    let (content, showing) = if start_line.is_some() || end_line.is_some() {
        let start = start_line.map(|n| (n as usize).saturating_sub(1)).unwrap_or(0);
        let end = end_line.map(|n| n as usize).unwrap_or(total_lines);
        let selected: Vec<&str> = lines.into_iter().skip(start).take(end - start).collect();
        let showing = format!("{}-{}", start + 1, start + selected.len());
        (selected.join("\n"), showing)
    } else {
        (content, format!("1-{}", total_lines))
    };

    Ok(json!({
        "path": file_path,
        "content": content,
        "total_lines": total_lines,
        "showing_lines": showing
    }))
}

/// Get codebase architecture overview
pub fn handle_get_architecture(state: &mut HandlerState, _args: &Value) -> Result<Value> {
    let graph = state.get_graph()?;

    // Get node counts
    let stats = graph.stats();

    // Get language distribution
    let files = graph.get_files();
    let mut lang_counts: std::collections::HashMap<String, i64> = std::collections::HashMap::new();
    for file in &files {
        let lang = file.language.clone().unwrap_or_else(|| "unknown".to_string());
        *lang_counts.entry(lang).or_insert(0) += 1;
    }
    let languages: Vec<serde_json::Value> = lang_counts
        .into_iter()
        .map(|(lang, count)| json!({"language": lang, "file_count": count}))
        .collect();

    // Get class overview with method counts
    let classes = graph.get_classes();
    let mut top_classes: Vec<serde_json::Value> = classes
        .iter()
        .map(|c| json!({
            "class_name": c.name,
            "file": c.file_path,
            "method_count": c.get_i64("methodCount").unwrap_or(0)
        }))
        .collect();
    top_classes.sort_by(|a, b| {
        let a_count = a.get("method_count").and_then(|v| v.as_i64()).unwrap_or(0);
        let b_count = b.get("method_count").and_then(|v| v.as_i64()).unwrap_or(0);
        b_count.cmp(&a_count)
    });
    top_classes.truncate(20);

    Ok(json!({
        "node_counts": stats,
        "languages": languages,
        "top_classes": top_classes
    }))
}

/// List available detectors
#[allow(unused_imports)]
pub fn handle_list_detectors(state: &HandlerState, _args: &Value) -> Result<Value> {
    use crate::detectors::Detector;

    let detectors = default_detectors(&state.repo_path);
    let detector_info: Vec<Value> = detectors
        .iter()
        .map(|d| {
            json!({
                "name": d.name(),
                "description": d.description(),
                "category": d.category()
            })
        })
        .collect();

    Ok(json!({
        "detectors": detector_info,
        "count": detector_info.len()
    }))
}

/// Get hotspot files (most issues)
pub fn handle_get_hotspots(state: &mut HandlerState, args: &Value) -> Result<Value> {
    let limit = args
        .get("limit")
        .and_then(|v| v.as_u64())
        .unwrap_or(10) as usize;

    // Try findings file first
    let findings_path = state.repo_path.join(".repotoire").join("last_findings.json");
    if findings_path.exists() {
        let content = std::fs::read_to_string(&findings_path)?;
        let parsed: Value = serde_json::from_str(&content)?;
        let findings: Vec<Value> = parsed
            .get("findings")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();

        // Count findings per file
        let mut file_counts: std::collections::HashMap<String, (usize, Vec<String>)> =
            std::collections::HashMap::new();

        for finding in &findings {
            if let Some(files) = finding.get("affected_files").and_then(|v| v.as_array()) {
                for file in files {
                    if let Some(path) = file.as_str() {
                        let entry = file_counts.entry(path.to_string()).or_insert((0, vec![]));
                        entry.0 += 1;
                        if let Some(sev) = finding.get("severity").and_then(|v| v.as_str()) {
                            entry.1.push(sev.to_string());
                        }
                    }
                }
            }
        }

        let mut hotspots: Vec<Value> = file_counts
            .into_iter()
            .map(|(path, (count, severities))| {
                json!({
                    "file_path": path,
                    "finding_count": count,
                    "severities": severities
                })
            })
            .collect();

        hotspots.sort_by(|a, b| {
            b.get("finding_count")
                .and_then(|v| v.as_u64())
                .unwrap_or(0)
                .cmp(&a.get("finding_count").and_then(|v| v.as_u64()).unwrap_or(0))
        });

        hotspots.truncate(limit);

        return Ok(json!({
            "hotspots": hotspots
        }));
    }

    // No findings file - run quick analysis
    Ok(json!({
        "error": "No findings available. Run 'analyze' first.",
        "hint": "Use the 'analyze' tool to generate findings"
    }))
}

// =============================================================================
// PRO Tier Tool Handlers
// =============================================================================

/// Search code semantically (PRO)
pub async fn handle_search_code(state: &HandlerState, args: &Value) -> Result<Value> {
    if !state.is_pro() {
        return Ok(json!({
            "error": "This feature requires a PRO subscription.",
            "upgrade_url": "https://repotoire.com/pricing"
        }));
    }

    let query = args
        .get("query")
        .and_then(|v| v.as_str())
        .context("Missing required argument: query")?;

    let top_k = args.get("top_k").and_then(|v| v.as_u64()).unwrap_or(10);
    let entity_types = args.get("entity_types");

    let client = reqwest::Client::new();
    let response = client
        .post(format!("{}/api/v1/code/search", state.api_url))
        .header("X-API-Key", state.api_key.as_ref().unwrap())
        .header("Content-Type", "application/json")
        .json(&json!({
            "query": query,
            "top_k": top_k,
            "entity_types": entity_types
        }))
        .send()
        .await?;

    handle_api_response(response).await
}

/// Ask about codebase (PRO)
pub async fn handle_ask(state: &HandlerState, args: &Value) -> Result<Value> {
    if !state.is_pro() {
        return Ok(json!({
            "error": "This feature requires a PRO subscription.",
            "upgrade_url": "https://repotoire.com/pricing"
        }));
    }

    let question = args
        .get("question")
        .and_then(|v| v.as_str())
        .context("Missing required argument: question")?;

    let top_k = args.get("top_k").and_then(|v| v.as_u64()).unwrap_or(10);

    let client = reqwest::Client::new();
    let response = client
        .post(format!("{}/api/v1/code/ask", state.api_url))
        .header("X-API-Key", state.api_key.as_ref().unwrap())
        .header("Content-Type", "application/json")
        .json(&json!({
            "question": question,
            "top_k": top_k
        }))
        .send()
        .await?;

    handle_api_response(response).await
}

/// Generate fix for a finding (PRO or BYOK)
pub async fn handle_generate_fix(state: &HandlerState, args: &Value) -> Result<Value> {
    // BYOK: Use local AI if user provided their own key
    if let Some(backend) = &state.ai_backend {
        return handle_generate_fix_local(state, args, backend.clone()).await;
    }

    // Cloud PRO fallback
    if !state.is_pro() {
        return Ok(json!({
            "error": "AI features require an API key.",
            "hint": "Set ANTHROPIC_API_KEY or OPENAI_API_KEY to enable AI fixes.",
            "docs": "https://github.com/Zach-hammad/repotoire#ai-powered-fixes-optional"
        }));
    }

    let finding_id = args
        .get("finding_id")
        .and_then(|v| v.as_str())
        .context("Missing required argument: finding_id")?;

    let client = reqwest::Client::new();
    let response = client
        .post(format!("{}/api/v1/fixes/generate", state.api_url))
        .header("X-API-Key", state.api_key.as_ref().unwrap())
        .header("Content-Type", "application/json")
        .json(&json!({
            "finding_id": finding_id
        }))
        .send()
        .await?;

    handle_api_response(response).await
}

/// Generate fix using local AI (BYOK)
async fn handle_generate_fix_local(state: &HandlerState, args: &Value, backend: LlmBackend) -> Result<Value> {
    use crate::ai::FixGenerator;
    use crate::models::Finding;

    let finding_index = args
        .get("finding_id")
        .and_then(|v| v.as_str())
        .or_else(|| args.get("finding_index").and_then(|v| v.as_str()))
        .context("Missing required argument: finding_id or finding_index")?;

    // Parse as 1-based index
    let index: usize = finding_index.parse().unwrap_or(0);
    if index == 0 {
        return Ok(json!({
            "error": "finding_id must be a number (1-based index from findings list)"
        }));
    }

    // Load findings
    let findings_path = state.repo_path.join(".repotoire/last_findings.json");
    if !findings_path.exists() {
        return Ok(json!({
            "error": "No findings available. Run 'analyze' first."
        }));
    }

    let findings_json = std::fs::read_to_string(&findings_path)?;
    let parsed: Value = serde_json::from_str(&findings_json)?;
    let findings: Vec<Finding> = serde_json::from_value(
        parsed.get("findings").cloned().unwrap_or(json!([]))
    )?;

    if index > findings.len() {
        return Ok(json!({
            "error": format!("Invalid finding index: {}. Valid range: 1-{}", index, findings.len())
        }));
    }

    let finding = &findings[index - 1];

    // Generate fix using local AI
    let client = AiClient::from_env(backend)?;
    let generator = FixGenerator::new(client);
    
    let file = finding.affected_files.first()
        .map(|p| p.display().to_string())
        .unwrap_or_default();
    
    match generator.generate_fix(finding, &state.repo_path).await {
        Ok(fix) => Ok(json!({
            "finding": {
                "title": finding.title,
                "severity": format!("{:?}", finding.severity),
                "file": file,
                "line": finding.line_start
            },
            "fix": {
                "description": fix.description,
                "changes": fix.changes,
                "diff": fix.diff(&state.repo_path)
            }
        })),
        Err(e) => Ok(json!({
            "error": format!("Failed to generate fix: {}", e)
        }))
    }
}

/// Handle API response with proper error mapping
async fn handle_api_response(response: reqwest::Response) -> Result<Value> {
    let status = response.status();

    if status == reqwest::StatusCode::UNAUTHORIZED {
        return Ok(json!({
            "error": "Invalid API key. Get your key at https://app.repotoire.io/settings/api-keys"
        }));
    }

    if status == reqwest::StatusCode::PAYMENT_REQUIRED {
        return Ok(json!({
            "error": "Feature requires PRO subscription. Upgrade at https://repotoire.com/pricing"
        }));
    }

    if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
        return Ok(json!({
            "error": "Rate limit exceeded. Please try again later."
        }));
    }

    if !status.is_success() {
        let error_text = response.text().await.unwrap_or_default();
        return Ok(json!({
            "error": format!("API error ({}): {}", status, error_text)
        }));
    }

    let body: Value = response.json().await?;
    Ok(body)
}

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

    #[test]
    fn test_handler_state_new() {
        let dir = tempdir().unwrap();
        let state = HandlerState::new(dir.path().to_path_buf());
        assert!(!state.is_pro()); // No API key in test env
    }

    #[test]
    fn test_get_file_not_found() {
        let dir = tempdir().unwrap();
        let state = HandlerState::new(dir.path().to_path_buf());
        let result = handle_get_file(&state, &json!({"file_path": "nonexistent.txt"})).unwrap();
        assert!(result.get("error").is_some());
    }

    #[test]
    fn test_get_file_success() {
        let dir = tempdir().unwrap();
        std::fs::write(dir.path().join("test.txt"), "line1\nline2\nline3").unwrap();
        
        let state = HandlerState::new(dir.path().to_path_buf());
        let result = handle_get_file(&state, &json!({"file_path": "test.txt"})).unwrap();
        
        assert_eq!(result.get("total_lines").and_then(|v| v.as_u64()), Some(3));
    }
}