magellan 4.12.3

Deterministic codebase mapping tool for local development
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
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
//! Refs command implementation
//!
//! Shows calls (incoming/outgoing) for a symbol.

use crate::service::registry::Registry;
use anyhow::Context;
use anyhow::Result;
use magellan::common::{detect_language_from_path, resolve_path};
use magellan::graph::query;
use magellan::graph::MultiDbContext;
use magellan::output::rich::{SpanChecksums, SpanContext};
use magellan::output::{
    output_json, JsonResponse, OutputFormat, ReferenceMatch, RefsResponse, Span,
};
use magellan::{CallFact, CodeGraph};
use std::path::{Path, PathBuf};

/// Represents a found symbol with its file path for refs lookup
struct RefsSymbol {
    file_path: String,
}

/// Find a symbol across all files by name
///
/// Returns all matching symbols with their file paths
fn find_symbol_all_files(graph: &mut CodeGraph, name: &str) -> Result<Vec<RefsSymbol>> {
    let mut results = Vec::new();

    // Get all indexed files
    let file_nodes = graph.all_file_nodes()?;

    // Search each file for the symbol
    for file_path in file_nodes.keys() {
        let entries = query::symbol_nodes_in_file_with_ids(graph, file_path)?;
        for (_node_id, symbol, _symbol_id) in entries {
            if let Some(symbol_name) = &symbol.name {
                if symbol_name == name {
                    results.push(RefsSymbol {
                        file_path: file_path.clone(),
                    });
                    break; // Found in this file, move to next
                }
            }
        }
    }

    Ok(results)
}

/// Run the refs command
///
/// # Arguments
/// * `db_path` - Path to the sqlitegraph database
/// * `name` - Symbol name to query
/// * `root` - Optional root directory for resolving relative paths
/// * `path` - Optional file path containing the symbol (if None, searches all files)
/// * `symbol_id` - Optional stable SymbolId for precise lookup
/// * `direction` - "in" for callers, "out" for calls
/// * `output_format` - Output format (Human or Json)
/// * `with_context` - Include context lines
/// * `with_semantics` - Include semantic information (kind, language)
/// * `with_checksums` - Include SHA-256 checksums
/// * `context_lines` - Number of context lines before/after (capped at 100)
///
/// # Displays
/// Human-readable list of calls or JSON output
#[allow(
    clippy::too_many_arguments,
    reason = "CLI command surface: each arg maps to a flag"
)]
pub fn run_refs(
    db_path: PathBuf,
    name: String,
    root: Option<PathBuf>,
    path: Option<PathBuf>,
    symbol_id: Option<String>,
    direction: String,
    output_format: OutputFormat,
    with_context: bool,
    with_semantics: bool,
    with_checksums: bool,
    context_lines: usize,
    all: bool,
    tokens: Option<usize>,
) -> Result<()> {
    if all {
        return run_refs_all(
            &name,
            &direction,
            output_format,
            with_context,
            with_semantics,
            with_checksums,
            context_lines,
        );
    }

    // Build args for execution tracking
    let mut args = vec!["refs".to_string()];
    args.push("--name".to_string());
    args.push(name.clone());
    if let Some(ref root_path) = root {
        args.push("--root".to_string());
        args.push(root_path.to_string_lossy().to_string());
    }
    if let Some(ref p) = path {
        args.push("--path".to_string());
        args.push(p.to_string_lossy().to_string());
    }
    if let Some(ref sid) = symbol_id {
        args.push("--symbol-id".to_string());
        args.push(sid.clone());
    }
    args.push("--direction".to_string());
    args.push(direction.clone());

    let graph = CodeGraph::open(&db_path)?;
    let exec_id = magellan::output::generate_execution_id();
    let root_str = root.as_ref().map(|p| p.to_string_lossy().to_string());
    let db_path_str = db_path.to_string_lossy().to_string();

    graph.execution_log().start_execution(
        &exec_id,
        env!("CARGO_PKG_VERSION"),
        &args,
        root_str.as_deref(),
        &db_path_str,
    )?;

    // Phase: resolve_target
    graph
        .telemetry()
        .record_phase_start(&exec_id, "resolve_target")?;

    // Handle --symbol-id alternative
    if let Some(sid) = symbol_id {
        let mut graph_mut = CodeGraph::open(&db_path)?;
        let target_symbol = query::find_by_symbol_id(&mut graph_mut, &sid)?;

        match target_symbol {
            Some(symbol) => {
                // Query references by SymbolId
                // Fall back to FQN-based if symbol has display_fqn
                if let Some(ref fqn) = symbol.display_fqn {
                    // Use existing FQN-based reference query via name/path
                    // For now, we use the name from the symbol
                    let symbol_name = symbol.name.clone().unwrap_or_else(|| fqn.clone());
                    // Use the provided path for FQN lookup (required when using --symbol-id)
                    let path_str = match path {
                        Some(p) => resolve_path(&p, &root),
                        None => {
                            graph.execution_log().finish_execution(
                                &exec_id,
                                "error",
                                Some("--path is required when using --symbol-id"),
                                0,
                                0,
                                0,
                            )?;
                            eprintln!("Error: --path is required when using --symbol-id");
                            return Ok(());
                        }
                    };

                    let calls: Vec<CallFact> = match direction.as_str() {
                        "in" | "incoming" => {
                            graph_mut.callers_of_symbol(&path_str, &symbol_name)?
                        }
                        "out" | "outgoing" => {
                            graph_mut.calls_from_symbol(&path_str, &symbol_name)?
                        }
                        _ => {
                            let err_msg =
                                format!("Invalid direction: '{}'. Use 'in' or 'out'", direction);
                            graph.execution_log().finish_execution(
                                &exec_id,
                                "error",
                                Some(err_msg.as_str()),
                                0,
                                0,
                                0,
                            )?;
                            anyhow::bail!(err_msg);
                        }
                    };

                    // Handle JSON output mode
                    if output_format == OutputFormat::Json || output_format == OutputFormat::Pretty
                    {
                        graph
                            .execution_log()
                            .finish_execution(&exec_id, "success", None, 0, 0, 0)?;
                        return output_json_mode(
                            &db_path,
                            &symbol_name,
                            &path_str,
                            &direction,
                            calls,
                            &exec_id,
                            output_format,
                            with_context,
                            with_semantics,
                            with_checksums,
                            context_lines,
                            tokens,
                        );
                    }

                    // Human mode
                    if direction == "in" || direction == "incoming" {
                        if calls.is_empty() {
                            println!("No incoming calls to \"{}\"", symbol_name);
                        } else {
                            println!("Calls TO \"{}\":", symbol_name);
                            for call in &calls {
                                println!(
                                    "  From: {} (Function) at {}:{}",
                                    call.caller,
                                    call.file_path.display(),
                                    call.start_line
                                );
                            }
                        }
                    } else if calls.is_empty() {
                        println!("No outgoing calls from \"{}\"", symbol_name);
                    } else {
                        println!("Calls FROM \"{}\":", symbol_name);
                        for call in &calls {
                            println!(
                                "  To: {} at {}:{}",
                                call.callee,
                                call.file_path.display(),
                                call.start_line
                            );
                        }
                    }

                    graph
                        .execution_log()
                        .finish_execution(&exec_id, "success", None, 0, 0, 0)?;
                    return Ok(());
                } else {
                    // Symbol has no display_fqn, cannot lookup references
                    graph.execution_log().finish_execution(
                        &exec_id,
                        "error",
                        Some("Symbol has no display FQN for reference lookup"),
                        0,
                        0,
                        0,
                    )?;
                    eprintln!(
                        "Symbol ID '{}' has no display FQN, cannot lookup references",
                        sid
                    );
                    return Ok(());
                }
            }
            None => {
                graph.execution_log().finish_execution(
                    &exec_id,
                    "error",
                    Some("Symbol ID not found"),
                    0,
                    0,
                    0,
                )?;
                eprintln!("Symbol ID '{}' not found", sid);
                return Ok(());
            }
        }
    }

    // Determine the file path to use for the symbol lookup
    let path_str = match path {
        Some(p) => {
            // User provided a specific path - use existing behavior
            resolve_path(&p, &root)
        }
        None => {
            // End resolve_target phase, start search phase
            graph
                .telemetry()
                .record_phase_end(&exec_id, "resolve_target")?;
            graph.telemetry().record_phase_start(&exec_id, "search")?;

            // No path provided - search all files for the symbol
            let mut graph_mut = CodeGraph::open(&db_path)?;
            let matches = find_symbol_all_files(&mut graph_mut, &name)?;

            match matches.len() {
                0 => {
                    graph.execution_log().finish_execution(
                        &exec_id,
                        "error",
                        Some("Symbol not found"),
                        0,
                        0,
                        0,
                    )?;
                    eprintln!("Symbol '{}' not found anywhere", name);
                    return Ok(());
                }
                1 => {
                    // Exactly one match - use it automatically
                    let matched_symbol = &matches[0];
                    if output_format == OutputFormat::Human {
                        println!("Found '{}' in {}", name, matched_symbol.file_path);
                    }
                    matched_symbol.file_path.clone()
                }
                _ => {
                    // Multiple matches - show ranked list
                    graph.execution_log().finish_execution(
                        &exec_id,
                        "error",
                        Some("Ambiguous symbol name"),
                        0,
                        0,
                        0,
                    )?;
                    eprintln!("Symbol '{}' found in multiple locations:", name);
                    for (i, matched_symbol) in matches.iter().enumerate() {
                        eprintln!("  [{}] {}", i + 1, matched_symbol.file_path);
                    }
                    eprintln!("\nUse --path <file> to specify which one to use");
                    return Ok(());
                }
            }
        }
    };

    let calls: Vec<CallFact> = match direction.as_str() {
        "in" | "incoming" => {
            // End resolve_target phase, start query phase
            graph
                .telemetry()
                .record_phase_end(&exec_id, "resolve_target")?;
            graph
                .telemetry()
                .record_phase_start(&exec_id, "query_refs")?;

            // Get callers of this symbol
            {
                let mut graph_mut = CodeGraph::open(&db_path)?;
                graph_mut.callers_of_symbol(&path_str, &name)?
            }
        }
        "out" | "outgoing" => {
            // End resolve_target phase, start query phase
            graph
                .telemetry()
                .record_phase_end(&exec_id, "resolve_target")?;
            graph
                .telemetry()
                .record_phase_start(&exec_id, "query_refs")?;

            // Get calls from this symbol
            {
                let mut graph_mut = CodeGraph::open(&db_path)?;
                graph_mut.calls_from_symbol(&path_str, &name)?
            }
        }
        _ => {
            let err_msg = format!("Invalid direction: '{}'. Use 'in' or 'out'", direction);
            graph.execution_log().finish_execution(
                &exec_id,
                "error",
                Some(err_msg.as_str()),
                0,
                0,
                0,
            )?;
            anyhow::bail!(err_msg);
        }
    };

    // Handle JSON output mode
    if output_format == OutputFormat::Json || output_format == OutputFormat::Pretty {
        // End query phase, start build_response phase
        graph.telemetry().record_phase_end(&exec_id, "query_refs")?;
        graph
            .telemetry()
            .record_phase_start(&exec_id, "build_response")?;

        graph
            .execution_log()
            .finish_execution(&exec_id, "success", None, 0, 0, 0)?;
        return output_json_mode(
            &db_path,
            &name,
            &path_str,
            &direction,
            calls,
            &exec_id,
            output_format,
            with_context,
            with_semantics,
            with_checksums,
            context_lines,
            tokens,
        );
    }

    // Human mode (existing behavior)
    if direction == "in" || direction == "incoming" {
        // End query phase for human output
        graph.telemetry().record_phase_end(&exec_id, "query_refs")?;
        if calls.is_empty() {
            println!("No incoming calls to \"{}\"", name);
        } else {
            println!("Calls TO \"{}\":", name);
            for call in &calls {
                println!(
                    "  From: {} (Function) at {}:{}",
                    call.caller,
                    call.file_path.display(),
                    call.start_line
                );
            }
        }
    } else if calls.is_empty() {
        println!("No outgoing calls from \"{}\"", name);
    } else {
        println!("Calls FROM \"{}\":", name);
        for call in &calls {
            println!(
                "  To: {} at {}:{}",
                call.callee,
                call.file_path.display(),
                call.start_line
            );
        }
    }

    graph
        .execution_log()
        .finish_execution(&exec_id, "success", None, 0, 0, 0)?;

    // Record output phase
    graph.telemetry().record_phase_start(&exec_id, "output")?;
    graph.telemetry().record_phase_end(&exec_id, "output")?;

    Ok(())
}

/// Output refs results in JSON format
#[allow(
    clippy::too_many_arguments,
    reason = "JSON output needs all query parameters"
)]
fn output_json_mode(
    _db_path: &Path,
    symbol_name: &str,
    file_path: &str,
    direction: &str,
    mut calls: Vec<CallFact>,
    exec_id: &str,
    output_format: OutputFormat,
    with_context: bool,
    with_semantics: bool,
    with_checksums: bool,
    context_lines: usize,
    tokens: Option<usize>,
) -> Result<()> {
    // Sort deterministically: by file_path, byte_start
    calls.sort_by(|a, b| {
        a.file_path
            .cmp(&b.file_path)
            .then_with(|| a.byte_start.cmp(&b.byte_start))
    });

    // Apply token budget if specified
    let (references, was_truncated) = if let Some(token_limit) = tokens {
        if token_limit > 0 {
            // Estimate current output size and truncate if needed
            let mut temp_calls = calls.clone();

            loop {
                // Convert temp_calls to ReferenceMatch to estimate size
                let temp_references: Vec<ReferenceMatch> = temp_calls
                    .iter()
                    .map(|call| {
                        let mut span = Span::new(
                            call.file_path.to_string_lossy().to_string(),
                            call.byte_start,
                            call.byte_end,
                            call.start_line,
                            call.start_col,
                            call.end_line,
                            call.end_col,
                        );

                        // Add context if requested
                        if with_context {
                            if let Some(context) = SpanContext::extract(
                                call.file_path.to_string_lossy().as_ref(),
                                call.start_line,
                                call.end_line,
                                context_lines,
                            ) {
                                span = span.with_context(context);
                            }
                        }

                        // Add semantics if requested
                        if with_semantics {
                            let kind = "call".to_string();
                            let language = detect_language_from_path(
                                call.file_path.to_string_lossy().as_ref(),
                            );
                            span = span.with_semantics_from(kind, language);
                        }

                        // Add checksums if requested
                        if with_checksums {
                            let checksums = SpanChecksums::compute(
                                call.file_path.to_string_lossy().as_ref(),
                                call.byte_start,
                                call.byte_end,
                            );
                            span = span.with_checksums(checksums);
                        }

                        let (referenced_symbol, target_symbol_id) =
                            if direction == "in" || direction == "incoming" {
                                (call.caller.clone(), call.caller_symbol_id.clone())
                            } else {
                                (call.callee.clone(), call.callee_symbol_id.clone())
                            };

                        ReferenceMatch::new(
                            span,
                            referenced_symbol,
                            Some("call".to_string()),
                            target_symbol_id,
                        )
                    })
                    .collect();

                // Create a test response to check token count
                let test_response = RefsResponse {
                    references: temp_references.clone(),
                    symbol_name: symbol_name.to_string(),
                    file_path: file_path.to_string(),
                    direction: direction.to_string(),
                };
                let test_json = serde_json::to_string(&test_response).unwrap_or_default();
                let tokens_est = test_json.len() / 4;

                if tokens_est <= token_limit {
                    break;
                } else {
                    // Need to truncate - try reducing calls
                    if temp_calls.len() > 1 {
                        temp_calls = temp_calls
                            .iter()
                            .take(temp_calls.len() / 2)
                            .cloned()
                            .collect();
                    } else {
                        temp_calls.clear();
                    }
                    if temp_calls.is_empty() {
                        break;
                    }
                }
            }

            // Convert final calls to ReferenceMatch
            let final_references: Vec<ReferenceMatch> = calls
                .into_iter()
                .take(temp_calls.len())
                .map(|call| {
                    let mut span = Span::new(
                        call.file_path.to_string_lossy().to_string(),
                        call.byte_start,
                        call.byte_end,
                        call.start_line,
                        call.start_col,
                        call.end_line,
                        call.end_col,
                    );

                    // Add context if requested
                    if with_context {
                        if let Some(context) = SpanContext::extract(
                            call.file_path.to_string_lossy().as_ref(),
                            call.start_line,
                            call.end_line,
                            context_lines,
                        ) {
                            span = span.with_context(context);
                        }
                    }

                    // Add semantics if requested
                    if with_semantics {
                        let kind = "call".to_string();
                        let language =
                            detect_language_from_path(call.file_path.to_string_lossy().as_ref());
                        span = span.with_semantics_from(kind, language);
                    }

                    // Add checksums if requested
                    if with_checksums {
                        let checksums = SpanChecksums::compute(
                            call.file_path.to_string_lossy().as_ref(),
                            call.byte_start,
                            call.byte_end,
                        );
                        span = span.with_checksums(checksums);
                    }

                    let (referenced_symbol, target_symbol_id) =
                        if direction == "in" || direction == "incoming" {
                            (call.caller.clone(), call.caller_symbol_id)
                        } else {
                            (call.callee.clone(), call.callee_symbol_id)
                        };

                    ReferenceMatch::new(
                        span,
                        referenced_symbol,
                        Some("call".to_string()),
                        target_symbol_id,
                    )
                })
                .collect();

            (final_references, true)
        } else {
            // token_limit is 0, no limit
            (
                calls
                    .into_iter()
                    .map(|call| {
                        let mut span = Span::new(
                            call.file_path.to_string_lossy().to_string(),
                            call.byte_start,
                            call.byte_end,
                            call.start_line,
                            call.start_col,
                            call.end_line,
                            call.end_col,
                        );

                        // Add context if requested
                        if with_context {
                            if let Some(context) = SpanContext::extract(
                                call.file_path.to_string_lossy().as_ref(),
                                call.start_line,
                                call.end_line,
                                context_lines,
                            ) {
                                span = span.with_context(context);
                            }
                        }

                        // Add semantics if requested
                        if with_semantics {
                            let kind = "call".to_string();
                            let language = detect_language_from_path(
                                call.file_path.to_string_lossy().as_ref(),
                            );
                            span = span.with_semantics_from(kind, language);
                        }

                        // Add checksums if requested
                        if with_checksums {
                            let checksums = SpanChecksums::compute(
                                call.file_path.to_string_lossy().as_ref(),
                                call.byte_start,
                                call.byte_end,
                            );
                            span = span.with_checksums(checksums);
                        }

                        let (referenced_symbol, target_symbol_id) =
                            if direction == "in" || direction == "incoming" {
                                (call.caller.clone(), call.caller_symbol_id)
                            } else {
                                (call.callee.clone(), call.callee_symbol_id)
                            };

                        ReferenceMatch::new(
                            span,
                            referenced_symbol,
                            Some("call".to_string()),
                            target_symbol_id,
                        )
                    })
                    .collect(),
                false,
            )
        }
    } else {
        // No token limit, use all calls
        (
            calls
                .into_iter()
                .map(|call| {
                    let mut span = Span::new(
                        call.file_path.to_string_lossy().to_string(),
                        call.byte_start,
                        call.byte_end,
                        call.start_line,
                        call.start_col,
                        call.end_line,
                        call.end_col,
                    );

                    // Add context if requested
                    if with_context {
                        if let Some(context) = SpanContext::extract(
                            call.file_path.to_string_lossy().as_ref(),
                            call.start_line,
                            call.end_line,
                            context_lines,
                        ) {
                            span = span.with_context(context);
                        }
                    }

                    // Add semantics if requested
                    if with_semantics {
                        let kind = "call".to_string();
                        let language =
                            detect_language_from_path(call.file_path.to_string_lossy().as_ref());
                        span = span.with_semantics_from(kind, language);
                    }

                    // Add checksums if requested
                    if with_checksums {
                        let checksums = SpanChecksums::compute(
                            call.file_path.to_string_lossy().as_ref(),
                            call.byte_start,
                            call.byte_end,
                        );
                        span = span.with_checksums(checksums);
                    }

                    let (referenced_symbol, target_symbol_id) =
                        if direction == "in" || direction == "incoming" {
                            (call.caller.clone(), call.caller_symbol_id)
                        } else {
                            (call.callee.clone(), call.callee_symbol_id)
                        };

                    ReferenceMatch::new(
                        span,
                        referenced_symbol,
                        Some("call".to_string()),
                        target_symbol_id,
                    )
                })
                .collect(),
            false,
        )
    };

    let response = RefsResponse {
        references,
        symbol_name: symbol_name.to_string(),
        file_path: file_path.to_string(),
        direction: direction.to_string(),
    };

    let tokens_estimated = if tokens.is_some() {
        let json = serde_json::to_string(&response).unwrap_or_default();
        Some(json.len() / 4)
    } else {
        None
    };

    let mut json_response = JsonResponse::new(response, exec_id);
    if let Some(est) = tokens_estimated {
        json_response = json_response.with_tokens(est);
    }
    if was_truncated {
        json_response = json_response.with_truncated(true);
    }
    output_json(&json_response, output_format)?;

    Ok(())
}

#[allow(
    clippy::too_many_arguments,
    reason = "registry fan-out path mirrors CLI flag surface"
)]
fn run_refs_all(
    _name: &str,
    direction: &str,
    output_format: OutputFormat,
    _with_context: bool,
    _with_semantics: bool,
    _with_checksums: bool,
    _context_lines: usize,
) -> Result<()> {
    let registry = Registry::load().with_context(|| "Failed to load project registry")?;
    let enabled: Vec<_> = registry.projects.iter().filter(|p| p.enabled).collect();

    if enabled.is_empty() {
        println!("No enabled projects in registry.");
        println!("Hint: use `magellan catalog` to list registered projects, then `magellan watch` to index one.");
        return Ok(());
    }

    let db_paths: Vec<PathBuf> = enabled.iter().map(|p| p.db.clone()).collect();
    let mut mdb = MultiDbContext::from_paths(&db_paths)?;

    let include_callers = direction == "in" || direction == "incoming";
    let include_callees = direction == "out" || direction == "outgoing";
    let matches = mdb.search_symbol(_name, None, Some(1), include_callers, include_callees);

    if matches.is_empty() {
        if include_callers {
            println!(
                "No incoming references to '{}' across {} project(s).",
                _name,
                enabled.len()
            );
        } else {
            println!(
                "No outgoing references from '{}' across {} project(s).",
                _name,
                enabled.len()
            );
        }
        return Ok(());
    }

    match output_format {
        OutputFormat::Json | OutputFormat::Pretty => {
            let exec_id = magellan::output::generate_execution_id();
            let response = JsonResponse::new(&matches, &exec_id);
            if output_format == OutputFormat::Pretty {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&response)
                        .expect("invariant: JsonResponse serialization is infallible")
                );
            } else {
                println!(
                    "{}",
                    serde_json::to_string(&response)
                        .expect("invariant: JsonResponse serialization is infallible")
                );
            }
        }
        OutputFormat::Human => {
            if include_callers {
                println!(
                    "Incoming references for '{}' across {} project(s):",
                    _name,
                    enabled.len()
                );
                for m in matches {
                    if let Some(ref callers) = m.callers {
                        for caller in callers {
                            println!(
                                "  called by {} in {}:{}",
                                caller.name, caller.file_path, caller.line
                            );
                        }
                    }
                }
            } else {
                println!(
                    "Outgoing references for '{}' across {} project(s):",
                    _name,
                    enabled.len()
                );
                for m in matches {
                    if let Some(ref callees) = m.callees {
                        for callee in callees {
                            println!(
                                "  calls {} in {}:{}",
                                callee.name, callee.file_path, callee.line
                            );
                        }
                    }
                }
            }
        }
    }

    Ok(())
}