pathfinder-mcp 0.20.1

Pathfinder — The Headless IDE MCP Server for AI Coding Agents
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
use super::super::test_helpers::{make_scope, make_server_with_lawyer, make_temp_workspace};
use crate::server::types::InspectParams;
use crate::server::PathfinderServer;
use pathfinder_common::config::PathfinderConfig;
use pathfinder_common::sandbox::Sandbox;
use pathfinder_common::types::{DegradedReason, WorkspaceRoot};
use pathfinder_lsp::types::{CallHierarchyCall, CallHierarchyItem};
use pathfinder_lsp::{DefinitionLocation, MockLawyer};
use pathfinder_search::MockScout;
use pathfinder_treesitter::mock::MockSurgeon;
use std::sync::Arc;

// ── read_with_deep_context ────────────────────────────────────────

#[tokio::test]
async fn test_read_with_deep_context_degrades_when_call_hierarchy_unsupported() {
    let surgeon = Arc::new(MockSurgeon::new());
    surgeon.read_symbol_scope_results.lock().unwrap().extend([
        Ok(make_scope()),
        Ok(make_scope()),
        Ok(make_scope()),
    ]);

    let lawyer = Arc::new(pathfinder_lsp::NoOpLawyer);
    let ws_dir = make_temp_workspace();
    let ws = WorkspaceRoot::new(ws_dir.path()).expect("valid root");
    let config = PathfinderConfig::default();
    let sandbox = Sandbox::new(ws.path(), &config.sandbox);
    let server = PathfinderServer::with_all_engines(
        ws,
        config,
        sandbox,
        Arc::new(MockScout::default()),
        surgeon,
        lawyer,
    );

    let params = InspectParams {
        semantic_path: "src/auth.rs::login".to_owned(),
        ..Default::default()
    };
    let result = server.read_with_deep_context_impl(params).await;
    let call_res = result.expect("should succeed");
    let text_content = match &call_res.content[0].raw {
        rmcp::model::RawContent::Text(t) => t.text.clone(),
        _ => panic!("expected text content"),
    };
    let val: crate::server::types::ReadWithDeepContextMetadata =
        serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

    assert!(
        text_content.starts_with("DEGRADED (grep_fallback_dependencies) — results are heuristic (grep-based), verify manually — fallback: use search for authoritative results\n\n0 dependencies loaded\n\nfn login() { }"),
        "text_content: {text_content}"
    );
    assert!(val.degraded);
    assert_eq!(
        val.degraded_reason,
        Some(DegradedReason::GrepFallbackDependencies)
    );
    assert!(val.dependencies.is_empty());
}

#[tokio::test]
async fn test_read_with_deep_context_lsp_populates_dependencies() {
    let surgeon = Arc::new(MockSurgeon::new());
    surgeon
        .read_symbol_scope_results
        .lock()
        .unwrap()
        .push(Ok(make_scope()));

    let lawyer = Arc::new(MockLawyer::default());

    let item = CallHierarchyItem {
        name: "login".into(),
        kind: "function".into(),
        detail: None,
        file: "src/auth.rs".into(),
        line: 9,
        column: 4,
        data: None,
    };
    lawyer.push_prepare_call_hierarchy_result(Ok(vec![item.clone()]));

    lawyer.push_outgoing_call_result(Ok(vec![CallHierarchyCall {
        item: CallHierarchyItem {
            name: "validate_token".into(),
            kind: "function".into(),
            detail: Some("fn validate_token() -> bool".into()),
            file: "src/token.rs".into(),
            line: 15,
            column: 4,
            data: None,
        },
        call_sites: vec![9],
    }]));

    let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

    let params = InspectParams {
        semantic_path: "src/auth.rs::login".to_owned(),
        ..Default::default()
    };
    let result = server.read_with_deep_context_impl(params).await;
    let call_res = result.expect("should succeed");
    let text_content = match &call_res.content[0].raw {
        rmcp::model::RawContent::Text(t) => t.text.clone(),
        _ => panic!("expected text content"),
    };
    let val: crate::server::types::ReadWithDeepContextMetadata =
        serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

    assert!(
        text_content.starts_with("1 dependencies loaded\n  fn validate_token() -> bool (src/token.rs:L15)\n\nfn login() { }"),
        "text_content: {text_content}"
    );
    assert!(!val.degraded);
    assert_eq!(val.degraded_reason, None);
    assert_eq!(val.dependencies.len(), 1);
    assert_eq!(
        val.dependencies[0].semantic_path,
        "src/token.rs::validate_token"
    );
    assert_eq!(val.dependencies[0].signature, "fn validate_token() -> bool");
    assert_eq!(val.dependencies[0].file, "src/token.rs");
    assert_eq!(val.dependencies[0].line, 15);
}

// ── read_with_deep_context with outgoing call error ───────────────────

#[tokio::test]
async fn test_read_with_deep_context_outgoing_error_degrades() {
    let surgeon = Arc::new(MockSurgeon::new());
    surgeon
        .read_symbol_scope_results
        .lock()
        .unwrap()
        .push(Ok(make_scope()));

    let lawyer = Arc::new(MockLawyer::default());

    let item = CallHierarchyItem {
        name: "login".into(),
        kind: "function".into(),
        detail: None,
        file: "src/auth.rs".into(),
        line: 9,
        column: 4,
        data: None,
    };
    // Prepare succeeds
    lawyer.push_prepare_call_hierarchy_result(Ok(vec![item]));
    // But outgoing call fails
    lawyer.push_outgoing_call_result(Err(pathfinder_lsp::LspError::Protocol(
        "outgoing failed".to_string(),
    )));

    let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

    let params = InspectParams {
        semantic_path: "src/auth.rs::login".to_owned(),
        ..Default::default()
    };
    let result = server.read_with_deep_context_impl(params).await;
    let call_res = result.expect("should succeed");
    let val: crate::server::types::ReadWithDeepContextMetadata =
        serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

    // Degraded because outgoing call failed
    assert!(val.degraded);
    assert_eq!(
        val.degraded_reason,
        Some(DegradedReason::LspErrorGrepFallback)
    );
    assert!(val.dependencies.is_empty());
}

// ── read_with_deep_context with empty hierarchy (confirmed zero deps) ──

#[tokio::test]
async fn test_read_with_deep_context_empty_hierarchy_zero_deps() {
    // call_hierarchy_prepare returns Ok([]) AND goto_definition probe returns Ok(Some(...))
    // → LSP is warm, confirmed zero deps. Must NOT be degraded.
    let surgeon = Arc::new(MockSurgeon::new());
    surgeon
        .read_symbol_scope_results
        .lock()
        .unwrap()
        .push(Ok(make_scope()));

    let lawyer = Arc::new(MockLawyer::default());
    // Empty call hierarchy — ambiguous on its own
    lawyer.push_prepare_call_hierarchy_result(Ok(vec![]));
    // Probe: goto_definition succeeds → LSP is warm → confirmed zero
    lawyer.set_goto_definition_result(Ok(Some(DefinitionLocation {
        file: "src/auth.rs".into(),
        line: 10,
        column: 4,
        preview: "fn login() {}".into(),
    })));

    let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

    let params = InspectParams {
        semantic_path: "src/auth.rs::login".to_owned(),
        ..Default::default()
    };
    let result = server.read_with_deep_context_impl(params).await;
    let call_res = result.expect("should succeed");
    let val: crate::server::types::ReadWithDeepContextMetadata =
        serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

    // NOT degraded — LSP warm, genuinely zero deps confirmed
    assert!(
        !val.degraded,
        "must not be degraded when probe confirms LSP is warm"
    );
    assert_eq!(val.degraded_reason, None);
    assert!(val.dependencies.is_empty(), "confirmed zero dependencies");
}

#[tokio::test]
async fn test_read_with_deep_context_empty_hierarchy_warmup_degrades() {
    // call_hierarchy_prepare returns Ok([]) AND goto_definition probe returns Ok(None)
    // → LSP is still warming up. Falls through to grep fallback (PATCH-005).
    let surgeon = Arc::new(MockSurgeon::new());
    surgeon.read_symbol_scope_results.lock().unwrap().extend([
        Ok(make_scope()),
        Ok(make_scope()),
        Ok(make_scope()),
    ]);

    let lawyer = Arc::new(MockLawyer::default());
    // Empty call hierarchy
    lawyer.push_prepare_call_hierarchy_result(Ok(vec![]));
    // Probe: goto_definition returns Ok(None) → LSP is still warming up
    // MockLawyer::default() already returns Ok(None) for goto_definition, so no extra setup needed.

    let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

    let params = InspectParams {
        semantic_path: "src/auth.rs::login".to_owned(),
        ..Default::default()
    };
    let result = server.read_with_deep_context_impl(params).await;
    let call_res = result.expect("should succeed");
    let val: crate::server::types::ReadWithDeepContextMetadata =
        serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

    // DEGRADED — grep fallback used because LSP warmup returns empty hierarchy
    assert!(
        val.degraded,
        "must be degraded when goto_definition probe also returns None"
    );
    assert_eq!(
        val.degraded_reason,
        Some(DegradedReason::GrepFallbackDependencies),
        "degraded_reason must indicate grep fallback was used"
    );
    assert!(val.dependencies.is_empty());
}

#[tokio::test]
async fn test_read_with_deep_context_closes_document_on_success() {
    let surgeon = Arc::new(MockSurgeon::new());
    surgeon
        .read_symbol_scope_results
        .lock()
        .unwrap()
        .push(Ok(make_scope()));

    let lawyer = Arc::new(MockLawyer::default());
    let item = CallHierarchyItem {
        name: "login".into(),
        kind: "function".into(),
        detail: None,
        file: "src/auth.rs".into(),
        line: 9,
        column: 4,
        data: None,
    };
    lawyer.push_prepare_call_hierarchy_result(Ok(vec![item]));

    let (server, _ws) = make_server_with_lawyer(surgeon, lawyer.clone());
    let params = InspectParams {
        semantic_path: "src/auth.rs::login".to_owned(),
        ..Default::default()
    };

    let _ = server.read_with_deep_context_impl(params).await;

    tokio::task::yield_now().await;

    assert_eq!(
        lawyer.did_open_call_count(),
        lawyer.did_close_call_count(),
        "DS-1: did_open and did_close must be symmetric in read_with_deep_context"
    );
}

// ── TASK-7: max_dependencies truncation ───────────────────────────────────

/// When outgoing dependencies exceed `max_dependencies`, the result must be
/// truncated and `dependencies_truncated = true`.
#[tokio::test]
async fn test_read_with_deep_context_max_dependencies_truncates_results() {
    let surgeon = Arc::new(MockSurgeon::new());
    surgeon
        .read_symbol_scope_results
        .lock()
        .unwrap()
        .push(Ok(make_scope()));

    let lawyer = Arc::new(MockLawyer::default());

    let item = CallHierarchyItem {
        name: "login".into(),
        kind: "function".into(),
        detail: None,
        file: "src/auth.rs".into(),
        line: 9,
        column: 4,
        data: None,
    };
    lawyer.push_prepare_call_hierarchy_result(Ok(vec![item.clone()]));

    // Push 5 outgoing callees (each on a distinct file)
    let outgoing_calls: Vec<CallHierarchyCall> = (1..=5)
        .map(|i| CallHierarchyCall {
            item: CallHierarchyItem {
                name: format!("dep_{i}"),
                kind: "function".into(),
                detail: Some(format!("fn dep_{i}()")),
                file: format!("src/dep_{i}.rs"),
                line: i * 5,
                column: 4,
                data: None,
            },
            call_sites: vec![i * 5],
        })
        .collect();
    lawyer.push_outgoing_call_result(Ok(outgoing_calls));

    let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

    let params = InspectParams {
        semantic_path: "src/auth.rs::login".to_owned(),
        max_dependencies: 2, // cap below the 5 available
        ..Default::default()
    };
    let result = server
        .read_with_deep_context_impl(params)
        .await
        .expect("should succeed");
    let val: crate::server::types::ReadWithDeepContextMetadata =
        serde_json::from_value(result.structured_content.unwrap()).unwrap();

    assert_eq!(
        val.dependencies.len(),
        2,
        "dependencies must be capped at max_dependencies=2"
    );
    assert!(
        val.dependencies_truncated,
        "dependencies_truncated must be true when budget is exhausted"
    );
}

/// Verify that the `default_max_dependencies()` constant is 50.
#[test]
fn test_read_with_deep_context_default_max_dependencies_is_50() {
    use crate::server::types::default_max_dependencies;
    assert_eq!(
        default_max_dependencies(),
        50,
        "default_max_dependencies must be 50 per the implementation"
    );
}

// ── attempt_grep_fallback with resolved candidates ───────────────

#[tokio::test]
async fn test_read_with_deep_context_grep_fallback_resolves_candidates() {
    // PATCH-005: When LSP is unavailable, grep fallback extracts call candidates
    // from the symbol body and resolves each via search.
    let surgeon = Arc::new(MockSurgeon::new());
    // First call: read_symbol_scope_enriched (for the main function)
    // Second call: read_symbol_scope (for grep fallback candidate extraction)
    // Use scope content that contains a function call to exercise candidate extraction.
    let mut scope = make_scope();
    scope.content = "fn login() -> bool { validate_token() }".to_string();
    surgeon
        .read_symbol_scope_results
        .lock()
        .unwrap()
        .extend([Ok(scope.clone()), Ok(scope)]);

    let ws_dir = make_temp_workspace();
    let ws = WorkspaceRoot::new(ws_dir.path()).expect("valid root");
    let config = PathfinderConfig::default();
    let sandbox = Sandbox::new(ws.path(), &config.sandbox);

    std::fs::create_dir_all(ws_dir.path().join("src")).unwrap();
    std::fs::write(
        ws_dir.path().join("src/auth.rs"),
        "fn login() -> bool { validate_token() }",
    )
    .unwrap();

    let scout = Arc::new(MockScout::default());
    // First search: resolve "validate_token" candidate
    scout.set_result(Ok(pathfinder_search::SearchResult {
        matches: vec![pathfinder_search::SearchMatch {
            file: "src/token.rs".to_string(),
            line: 5,
            column: 1,
            content: "fn validate_token() -> bool { true }".to_string(),
            context_before: vec![],
            context_after: vec![],
            enclosing_semantic_path: None,
            is_definition: None,
            version_hash: "sha256:abc".to_string(),
            known: Some(false),
        }],
        total_matches: 1,
        truncated: false,
        files_searched: 1,
        files_in_scope: 1,
        binary_skipped: 0,
        gitignored_skipped: 0,
        other_skipped: 0,
    }));

    let server = PathfinderServer::with_all_engines(
        ws,
        config,
        sandbox,
        scout,
        surgeon,
        Arc::new(pathfinder_lsp::NoOpLawyer),
    );

    let params = InspectParams {
        semantic_path: "src/auth.rs::login".to_owned(),
        ..Default::default()
    };
    let result = server.read_with_deep_context_impl(params).await;
    let call_res = result.expect("should succeed");
    let val: crate::server::types::ReadWithDeepContextMetadata =
        serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

    assert!(val.degraded);
    assert_eq!(
        val.degraded_reason,
        Some(DegradedReason::GrepFallbackDependencies)
    );
    // The grep fallback should have resolved "validate_token" from the scope body.
    assert!(
        !val.dependencies.is_empty(),
        "expected at least 1 resolved dependency, got {}",
        val.dependencies.len()
    );
}

// ── detail: None fallback ────────────────────────────────────────

#[tokio::test]
async fn test_read_with_deep_context_detail_none_falls_back_to_name() {
    // When callee.detail is None, the signature should fall back to callee.name.
    let surgeon = Arc::new(MockSurgeon::new());
    surgeon
        .read_symbol_scope_results
        .lock()
        .unwrap()
        .push(Ok(make_scope()));

    let lawyer = Arc::new(MockLawyer::default());

    let item = CallHierarchyItem {
        name: "login".into(),
        kind: "function".into(),
        detail: None,
        file: "src/auth.rs".into(),
        line: 9,
        column: 4,
        data: None,
    };
    lawyer.push_prepare_call_hierarchy_result(Ok(vec![item]));

    // Outgoing call with detail=None
    lawyer.push_outgoing_call_result(Ok(vec![CallHierarchyCall {
        item: CallHierarchyItem {
            name: "validate_token".into(),
            kind: "function".into(),
            detail: None, // No detail — should fall back to name
            file: "src/token.rs".into(),
            line: 15,
            column: 4,
            data: None,
        },
        call_sites: vec![9],
    }]));

    let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

    let params = InspectParams {
        semantic_path: "src/auth.rs::login".to_owned(),
        ..Default::default()
    };
    let result = server.read_with_deep_context_impl(params).await;
    let call_res = result.expect("should succeed");
    let val: crate::server::types::ReadWithDeepContextMetadata =
        serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

    assert!(!val.degraded);
    assert_eq!(val.dependencies.len(), 1);
    // Signature should be the name since detail is None
    assert_eq!(val.dependencies[0].signature, "validate_token");
    assert_eq!(
        val.dependencies[0].semantic_path,
        "src/token.rs::validate_token"
    );
}

// ── Warmup retry success ────────────────────────────────────────

#[tokio::test]
async fn test_read_with_deep_context_warmup_retry_success() {
    // LSP returns Ok([]) first (warmup), then Ok(items) on retry.
    let surgeon = Arc::new(MockSurgeon::new());
    surgeon
        .read_symbol_scope_results
        .lock()
        .unwrap()
        .push(Ok(make_scope()));

    let lawyer = Arc::new(MockLawyer::default());

    let item = CallHierarchyItem {
        name: "login".into(),
        kind: "function".into(),
        detail: None,
        file: "src/auth.rs".into(),
        line: 9,
        column: 4,
        data: None,
    };

    // First call: empty (warmup)
    lawyer.push_prepare_call_hierarchy_result(Ok(vec![]));
    // goto_definition probe: Ok(None) — confirms LSP warming up
    // (default MockLawyer returns Ok(None))
    // Retry call: succeeds with items
    lawyer.push_prepare_call_hierarchy_result(Ok(vec![item]));
    // Outgoing deps for retry
    lawyer.push_outgoing_call_result(Ok(vec![CallHierarchyCall {
        item: CallHierarchyItem {
            name: "validate_token".into(),
            kind: "function".into(),
            detail: Some("fn validate_token() -> bool".into()),
            file: "src/token.rs".into(),
            line: 15,
            column: 4,
            data: None,
        },
        call_sites: vec![9],
    }]));

    let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

    let params = InspectParams {
        semantic_path: "src/auth.rs::login".to_owned(),
        ..Default::default()
    };
    let result = server.read_with_deep_context_impl(params).await;
    let call_res = result.expect("should succeed on retry");
    let val: crate::server::types::ReadWithDeepContextMetadata =
        serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

    assert!(!val.degraded, "should NOT be degraded on retry success");
    assert_eq!(val.dependencies.len(), 1);
    assert_eq!(
        val.dependencies[0].semantic_path,
        "src/token.rs::validate_token"
    );
}

// ── project_only filtering in append_outgoing_deps ──────────────

#[tokio::test]
async fn test_read_with_deep_context_filters_non_workspace_deps() {
    // When project_only=true, callees from non-workspace files should be filtered.
    let surgeon = Arc::new(MockSurgeon::new());
    surgeon
        .read_symbol_scope_results
        .lock()
        .unwrap()
        .push(Ok(make_scope()));

    let lawyer = Arc::new(MockLawyer::default());

    let item = CallHierarchyItem {
        name: "login".into(),
        kind: "function".into(),
        detail: None,
        file: "src/auth.rs".into(),
        line: 9,
        column: 4,
        data: None,
    };
    lawyer.push_prepare_call_hierarchy_result(Ok(vec![item]));

    // Outgoing: one workspace dep + one non-workspace (absolute path = stdlib)
    lawyer.push_outgoing_call_result(Ok(vec![
        CallHierarchyCall {
            item: CallHierarchyItem {
                name: "validate_token".into(),
                kind: "function".into(),
                detail: Some("fn validate_token()".into()),
                file: "src/token.rs".into(),
                line: 15,
                column: 4,
                data: None,
            },
            call_sites: vec![9],
        },
        CallHierarchyCall {
            item: CallHierarchyItem {
                name: "println".into(),
                kind: "function".into(),
                detail: Some("macro println".into()),
                file: "/rust/library/std/src/io/stdio.rs".into(), // absolute = non-workspace
                line: 100,
                column: 1,
                data: None,
            },
            call_sites: vec![9],
        },
    ]));

    let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

    let params = InspectParams {
        semantic_path: "src/auth.rs::login".to_owned(),
        ..Default::default()
    };
    let result = server.read_with_deep_context_impl(params).await;
    let call_res = result.expect("should succeed");
    let val: crate::server::types::ReadWithDeepContextMetadata =
        serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

    assert!(!val.degraded);
    // Only the workspace dep should be included
    assert_eq!(val.dependencies.len(), 1);
    assert_eq!(
        val.dependencies[0].semantic_path,
        "src/token.rs::validate_token"
    );
}

// ── Dedup in append_outgoing_deps ────────────────────────────────

#[tokio::test]
async fn test_read_with_deep_context_deduplicates_deps() {
    // When LSP returns the same callee multiple times, dedup should prevent duplicates.
    let surgeon = Arc::new(MockSurgeon::new());
    surgeon
        .read_symbol_scope_results
        .lock()
        .unwrap()
        .push(Ok(make_scope()));

    let lawyer = Arc::new(MockLawyer::default());

    let item = CallHierarchyItem {
        name: "login".into(),
        kind: "function".into(),
        detail: None,
        file: "src/auth.rs".into(),
        line: 9,
        column: 4,
        data: None,
    };
    lawyer.push_prepare_call_hierarchy_result(Ok(vec![item]));

    // Outgoing: same callee returned twice (simulates LSP duplicate)
    lawyer.push_outgoing_call_result(Ok(vec![
        CallHierarchyCall {
            item: CallHierarchyItem {
                name: "validate_token".into(),
                kind: "function".into(),
                detail: Some("fn validate_token()".into()),
                file: "src/token.rs".into(),
                line: 15,
                column: 4,
                data: None,
            },
            call_sites: vec![9],
        },
        CallHierarchyCall {
            item: CallHierarchyItem {
                name: "validate_token".into(),
                kind: "function".into(),
                detail: Some("fn validate_token()".into()),
                file: "src/token.rs".into(),
                line: 15,
                column: 4,
                data: None,
            },
            call_sites: vec![10],
        },
    ]));

    let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

    let params = InspectParams {
        semantic_path: "src/auth.rs::login".to_owned(),
        ..Default::default()
    };
    let result = server.read_with_deep_context_impl(params).await;
    let call_res = result.expect("should succeed");
    let val: crate::server::types::ReadWithDeepContextMetadata =
        serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

    assert!(!val.degraded);
    // Dedup should prevent the duplicate
    assert_eq!(
        val.dependencies.len(),
        1,
        "duplicate callees should be deduped, got {}",
        val.dependencies.len()
    );
}

// ── java_resolve_pattern tests ─────────────────────────────────────────

fn make_java_re(candidate: &str) -> regex::Regex {
    let pattern = super::super::java_resolve_pattern(candidate);
    regex::Regex::new(&pattern).expect("valid regex")
}

#[test]
fn test_java_resolve_pattern_constructor() {
    let re = make_java_re("MyClass");
    assert!(re.is_match("public MyClass(String name)"));
    assert!(re.is_match("  private MyClass()"));
    assert!(
        re.is_match("public void MyClass()"),
        "method arm correctly matches 'public void MyClass()' as a method definition"
    );
    assert!(!re.is_match("new MyClass()"));
}

#[test]
fn test_java_resolve_pattern_method() {
    let re = make_java_re("process");
    assert!(re.is_match("public void process()"));
    assert!(re.is_match("int[] process()"));
    assert!(re.is_match("public int[][] process()"));
    assert!(re.is_match("public <T> T process()"));
    assert!(re.is_match("public strictfp void process()"));
    assert!(!re.is_match("new process()"));
}

#[test]
fn test_java_resolve_pattern_record() {
    let re = make_java_re("Point");
    assert!(re.is_match("public record Point(int x, int y)"));
    assert!(re.is_match("record Point(String name)"));
}

#[test]
fn test_java_resolve_pattern_class() {
    let re = make_java_re("MyClass");
    assert!(re.is_match("public class MyClass"));
    assert!(re.is_match("sealed class MyClass"));
    assert!(re.is_match("non-sealed class MyClass"));
    assert!(re.is_match("public strictfp class MyClass"));
}

#[test]
fn test_java_resolve_pattern_rejects_false_positives() {
    let re = make_java_re("MyError");
    assert!(!re.is_match("throw new MyError(\"msg\")"));
    assert!(!re.is_match("return new MyError()"));
    let re2 = make_java_re("MyClass");
    assert!(
        !re2.is_match("new MyClass()"),
        "constructor call 'new MyClass()' must not match"
    );
}

#[test]
fn test_java_resolve_pattern_bounded_generics() {
    let re = make_java_re("sort");
    assert!(
        re.is_match("public <T extends Comparable<T>> void sort(List<T> list)"),
        "must match bounded generics in method type params"
    );
    let re2 = make_java_re("MyClass");
    assert!(
        re2.is_match("public <T extends Comparable<T>> MyClass(T item)"),
        "must match bounded generics in constructor type params"
    );
}

#[test]
fn test_java_resolve_pattern_static_record_and_strictfp_class() {
    let re = make_java_re("Inner");
    assert!(
        re.is_match("static record Inner(String name)"),
        "must match 'static record Inner(String name)'"
    );
    let re2 = make_java_re("MathUtils");
    assert!(
        re2.is_match("strictfp class MathUtils"),
        "must match 'strictfp class MathUtils'"
    );
    assert!(
        re2.is_match("public strictfp class MathUtils"),
        "must match 'public strictfp class MathUtils'"
    );
}