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
//! Doctor command - Diagnose common Magellan issues
//!
//! Checks for common problems and provides actionable recommendations.
use anyhow::Result;
use magellan::output::generate_execution_id;
use magellan::CodeGraph;
use magellan::OutputFormat;
use serde::Serialize;
use std::fs;
use std::path::PathBuf;
/// A single diagnostic check result
#[derive(Debug, Clone, Serialize)]
struct CheckResult {
name: String,
status: String,
message: Option<String>,
fix_hint: Option<String>,
}
/// Complete doctor diagnostic report
#[derive(Debug, Serialize)]
struct DoctorReport {
status: String,
issues_found: usize,
issues_fixed: usize,
checks: Vec<CheckResult>,
}
/// Run the doctor command
///
/// Diagnoses common issues with Magellan installation and database.
pub fn run_doctor(db_path: PathBuf, fix: bool, output_format: OutputFormat) -> Result<()> {
let mut checks = Vec::new();
let mut issues_found = 0;
let mut issues_fixed = 0;
// Check 1: Database file exists
if db_path.exists() {
checks.push(CheckResult {
name: "Database file".to_string(),
status: "ok".to_string(),
message: None,
fix_hint: None,
});
} else {
checks.push(CheckResult {
name: "Database file".to_string(),
status: "missing".to_string(),
message: Some(format!("Database not found at: {:?}", db_path)),
fix_hint: Some(format!(
"Run 'magellan watch --root . --db {:?} --scan-initial'",
db_path
)),
});
issues_found += 1;
}
// Check 2: Database is readable
match CodeGraph::open(&db_path) {
Ok(mut graph) => {
checks.push(CheckResult {
name: "Database readability".to_string(),
status: "ok".to_string(),
message: None,
fix_hint: None,
});
// Check 3: Schema version via status
match graph.count_files() {
Ok(_) => {
checks.push(CheckResult {
name: "Schema version".to_string(),
status: "ok".to_string(),
message: None,
fix_hint: None,
});
}
Err(e) => {
checks.push(CheckResult {
name: "Schema version".to_string(),
status: "warning".to_string(),
message: Some(format!("Schema error: {}", e)),
fix_hint: Some("Re-open database to trigger migration".to_string()),
});
issues_found += 1;
}
}
// Check 4: Symbol count
match graph.count_symbols() {
Ok(count) => {
if count > 0 {
checks.push(CheckResult {
name: "Symbol index".to_string(),
status: "ok".to_string(),
message: Some(format!("{} symbols", count)),
fix_hint: None,
});
} else {
checks.push(CheckResult {
name: "Symbol index".to_string(),
status: "empty".to_string(),
message: Some("No symbols indexed".to_string()),
fix_hint: Some(format!(
"Run 'magellan watch --root . --db {:?} --scan-initial'",
db_path
)),
});
issues_found += 1;
}
}
Err(e) => {
checks.push(CheckResult {
name: "Symbol index".to_string(),
status: "error".to_string(),
message: Some(e.to_string()),
fix_hint: None,
});
issues_found += 1;
}
}
// Check 5: File count
match graph.count_files() {
Ok(count) => {
if count > 0 {
checks.push(CheckResult {
name: "File index".to_string(),
status: "ok".to_string(),
message: Some(format!("{} files", count)),
fix_hint: None,
});
} else {
checks.push(CheckResult {
name: "File index".to_string(),
status: "empty".to_string(),
message: Some("No files indexed".to_string()),
fix_hint: Some(format!(
"Run 'magellan watch --root . --db {:?} --scan-initial'",
db_path
)),
});
issues_found += 1;
}
}
Err(e) => {
checks.push(CheckResult {
name: "File index".to_string(),
status: "error".to_string(),
message: Some(e.to_string()),
fix_hint: None,
});
issues_found += 1;
}
}
// Check 6: Call graph
match graph.count_calls() {
Ok(count) => {
if count > 0 {
checks.push(CheckResult {
name: "Call graph".to_string(),
status: "ok".to_string(),
message: Some(format!("{} calls", count)),
fix_hint: None,
});
} else {
checks.push(CheckResult {
name: "Call graph".to_string(),
status: "empty".to_string(),
message: Some("No call relationships indexed".to_string()),
fix_hint: Some("Index files with function calls".to_string()),
});
issues_found += 1;
}
}
Err(e) => {
checks.push(CheckResult {
name: "Call graph".to_string(),
status: "error".to_string(),
message: Some(e.to_string()),
fix_hint: None,
});
issues_found += 1;
}
}
// Check 7: Database file size
if let Ok(metadata) = fs::metadata(&db_path) {
let size_mb = metadata.len() as f64 / (1024.0 * 1024.0);
if size_mb > 1000.0 {
checks.push(CheckResult {
name: "Database size".to_string(),
status: "warning".to_string(),
message: Some(format!("Large database: {:.1} MB", size_mb)),
fix_hint: Some("Consider exporting and starting fresh".to_string()),
});
issues_found += 1;
} else {
checks.push(CheckResult {
name: "Database size".to_string(),
status: "ok".to_string(),
message: Some(format!("{:.1} MB", size_mb)),
fix_hint: None,
});
}
}
// Check 8: WAL file
let wal_path = db_path.with_extension("db-wal");
if wal_path.exists() {
if let Ok(metadata) = fs::metadata(&wal_path) {
let wal_size_mb = metadata.len() as f64 / (1024.0 * 1024.0);
if wal_size_mb > 100.0 {
checks.push(CheckResult {
name: "WAL file".to_string(),
status: "warning".to_string(),
message: Some(format!("Large WAL: {:.1} MB", wal_size_mb)),
fix_hint: Some("Run 'magellan status' to checkpoint".to_string()),
});
if fix {
let _ = CodeGraph::open(&db_path);
issues_fixed += 1;
}
issues_found += 1;
} else {
checks.push(CheckResult {
name: "WAL file".to_string(),
status: "ok".to_string(),
message: Some(format!("{:.1} MB", wal_size_mb)),
fix_hint: None,
});
}
}
} else {
checks.push(CheckResult {
name: "WAL file".to_string(),
status: "ok".to_string(),
message: Some("No WAL file (good)".to_string()),
fix_hint: None,
});
}
// Check 9: Context index
let context_path = db_path
.parent()
.map(|p| p.join(db_path.file_name().unwrap_or_default()))
.unwrap_or_else(|| db_path.clone())
.with_extension("context.json");
if context_path.exists() {
checks.push(CheckResult {
name: "Context index".to_string(),
status: "ok".to_string(),
message: None,
fix_hint: None,
});
} else {
checks.push(CheckResult {
name: "Context index".to_string(),
status: "missing".to_string(),
message: Some("Context index not built".to_string()),
fix_hint: Some(format!("Run 'magellan context build --db {:?}'", db_path)),
});
if fix {
use magellan::context::build_context_index;
match build_context_index(&mut graph, &db_path) {
Ok(_) => issues_fixed += 1,
Err(e) => eprintln!("Warning: Failed to build context index: {}", e),
}
}
issues_found += 1;
}
// Check 10: Connection health
let start = std::time::Instant::now();
let conn_ok = graph.count_files().map(|_| true).unwrap_or(false);
let elapsed_ms = start.elapsed().as_millis();
if conn_ok {
if elapsed_ms > 500 {
checks.push(CheckResult {
name: "Connection health".to_string(),
status: "warning".to_string(),
message: Some(format!("Slow query response: {}ms", elapsed_ms)),
fix_hint: Some(
"Database may be under contention; restart watcher or reduce concurrent access"
.to_string(),
),
});
issues_found += 1;
} else {
checks.push(CheckResult {
name: "Connection health".to_string(),
status: "ok".to_string(),
message: Some(format!("{}ms", elapsed_ms)),
fix_hint: None,
});
}
} else {
checks.push(CheckResult {
name: "Connection health".to_string(),
status: "error".to_string(),
message: Some("Failed to query database".to_string()),
fix_hint: None,
});
issues_found += 1;
}
// Check 11: Duplicate file nodes
let mut dupes_found = Vec::new();
{
use std::collections::HashMap;
let mut path_counts: HashMap<String, usize> = HashMap::new();
let backend = graph.backend();
if let Ok(ids) = backend.entity_ids() {
let snapshot = sqlitegraph::SnapshotId::current();
for id in ids {
if let Ok(node) = backend.get_node(snapshot, id) {
if node.kind == "File" {
if let Ok(file_node) = serde_json::from_value::<
magellan::graph::schema::FileNode,
>(node.data)
{
*path_counts.entry(file_node.path).or_insert(0) += 1;
}
}
}
}
}
for (path, count) in path_counts {
if count > 1 {
dupes_found.push((path, count));
}
}
}
if dupes_found.is_empty() {
checks.push(CheckResult {
name: "Duplicate file nodes".to_string(),
status: "ok".to_string(),
message: None,
fix_hint: None,
});
} else {
let total_dupes: usize = dupes_found.iter().map(|(_, c)| c - 1).sum();
checks.push(CheckResult {
name: "Duplicate file nodes".to_string(),
status: "warning".to_string(),
message: Some(format!(
"{} file(s) with {} extra nodes",
dupes_found.len(),
total_dupes
)),
fix_hint: Some(
"Re-index to clean up: magellan watch --root . --scan-initial".to_string(),
),
});
if fix {
let mut fixed = 0;
for (path, _) in &dupes_found {
match graph.delete_file(path) {
Ok(_) => fixed += 1,
Err(_e) => {}
}
}
if fixed == dupes_found.len() {
issues_fixed += 1;
}
}
issues_found += 1;
}
// Check 12: Coverage schema
match graph.check_coverage_schema() {
Ok(true) => {
checks.push(CheckResult {
name: "Coverage schema".to_string(),
status: "ok".to_string(),
message: None,
fix_hint: None,
});
}
Ok(false) => {
checks.push(CheckResult {
name: "Coverage schema".to_string(),
status: "missing".to_string(),
message: Some("Coverage tables not found".to_string()),
fix_hint: Some("Re-open database to trigger schema migration".to_string()),
});
if fix {
drop(graph);
match CodeGraph::open(&db_path) {
Ok(_) => issues_fixed += 1,
Err(e) => eprintln!("Warning: Failed to re-open database: {}", e),
}
}
issues_found += 1;
}
Err(e) => {
checks.push(CheckResult {
name: "Coverage schema".to_string(),
status: "error".to_string(),
message: Some(e.to_string()),
fix_hint: None,
});
issues_found += 1;
}
}
}
Err(e) => {
checks.push(CheckResult {
name: "Database readability".to_string(),
status: "error".to_string(),
message: Some(format!("Cannot open database: {}", e)),
fix_hint: Some(format!(
"Delete and rebuild: rm {:?} && magellan watch --root . --db {:?} --scan-initial",
db_path, db_path
)),
});
issues_found += 1;
}
}
let report = DoctorReport {
status: if issues_found == 0 {
"healthy".to_string()
} else {
"issues_found".to_string()
},
issues_found,
issues_fixed,
checks,
};
match output_format {
OutputFormat::Json => {
println!("{}", serde_json::to_string(&report)?);
}
OutputFormat::Pretty => {
println!("{}", serde_json::to_string_pretty(&report)?);
}
OutputFormat::Human => {
println!("🔍 Magellan Doctor - Diagnosing issues...\n");
for check in &report.checks {
let icon = match check.status.as_str() {
"ok" => "✅",
"warning" | "large" => "⚠️",
"missing" | "empty" => "⚠️",
"error" => "❌",
_ => "❓",
};
print!("{} {}... ", icon, check.name);
if let Some(ref msg) = check.message {
println!("{}", msg);
} else {
println!("OK");
}
if let Some(ref hint) = check.fix_hint {
println!(" Fix: {}", hint);
}
}
println!("\n{}", "=".repeat(50));
if issues_found == 0 {
println!("✅ No issues found! Your Magellan installation is healthy.");
} else {
println!(
"⚠️ Found {} issue(s), {} fixed",
issues_found, issues_fixed
);
println!();
println!("Quick fixes:");
println!(
" - Rebuild database: magellan watch --root . --db {:?} --scan-initial",
db_path
);
println!(
" - Build context: magellan context build --db {:?}",
db_path
);
println!(" - Check status: magellan status --db {:?}", db_path);
println!();
println!("Run with --fix to auto-fix some issues");
}
}
}
// Track execution
let _exec_id = generate_execution_id();
Ok(())
}