pathfinder-mcp 0.6.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
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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::needless_return)]
use crate::server::types::ReplaceFullParams;
use crate::server::PathfinderServer;

use super::helpers::UnsupportedDiagLawyer;
use pathfinder_common::config::PathfinderConfig;
use pathfinder_common::sandbox::Sandbox;
use pathfinder_common::types::{VersionHash, WorkspaceRoot};
use pathfinder_search::MockScout;
use pathfinder_treesitter::mock::MockSurgeon;
use rmcp::handler::server::wrapper::Parameters;
use std::sync::Arc;
use tempfile::tempdir;

fn make_server_with_lawyer(
    ws_dir: &tempfile::TempDir,
    mock_surgeon: MockSurgeon,
    mock_lawyer: pathfinder_lsp::MockLawyer,
) -> PathfinderServer {
    let ws = WorkspaceRoot::new(ws_dir.path()).expect("valid root");
    let config = PathfinderConfig::default();
    let sandbox = Sandbox::new(ws.path(), &config.sandbox);
    PathfinderServer::with_all_engines(
        ws,
        config,
        sandbox,
        Arc::new(MockScout::default()),
        Arc::new(mock_surgeon),
        Arc::new(mock_lawyer),
    )
}

/// Helper: write a tiny Go source file and build a `MockSurgeon` whose
/// `resolve_full_range` returns a range covering the whole file.
fn setup_full_replace_fixture(
    ws_dir: &tempfile::TempDir,
    filepath: &str,
    src: &str,
) -> (MockSurgeon, VersionHash) {
    let abs = ws_dir.path().join(filepath);
    std::fs::create_dir_all(abs.parent().unwrap()).unwrap();
    std::fs::write(&abs, src).unwrap();

    let src_bytes = src.as_bytes();
    let hash = VersionHash::compute(src_bytes);

    let mock_surgeon = MockSurgeon::new();
    mock_surgeon
        .resolve_full_range_results
        .lock()
        .unwrap()
        .push(Ok((
            pathfinder_treesitter::surgeon::FullRange {
                start_byte: 0,
                end_byte: src_bytes.len(),
                indent_column: 0,
            },
            std::sync::Arc::from(src_bytes),
            hash.clone(),
        )));

    (mock_surgeon, hash)
}

// ── no_lsp: did_open returns NoLspAvailable → validation skipped ────

#[tokio::test]
async fn test_run_lsp_validation_no_lsp() {
    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();
    mock_lawyer.set_did_open_error(pathfinder_lsp::LspError::NoLspAvailable);

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { return }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed — no_lsp gracefully degrades");
    let resp = result.0;

    assert!(resp.success);
    // TS-1: Tree-sitter fallback upgrades status from "skipped" to "passed" for valid Go code.
    // validation_skipped remains true (LSP was still unavailable), but status reflects
    // the Tree-sitter syntax check result.
    assert_eq!(resp.validation.status, "passed");
    assert_eq!(
        resp.validation.validation_confidence.as_deref(),
        Some("syntax_only")
    );
    assert!(resp.validation_skipped);
    assert_eq!(resp.validation_skipped_reason.as_deref(), Some("no_lsp"));
}

// ── unsupported: did_open returns UnsupportedCapability → skipped ───

#[tokio::test]
async fn test_run_lsp_validation_unsupported() {
    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();
    mock_lawyer.set_did_open_error(pathfinder_lsp::LspError::UnsupportedCapability {
        capability: "textDocument/diagnostic".to_owned(),
    });

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { return }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed — unsupported gracefully degrades");
    let resp = result.0;

    // TS-1: Tree-sitter fallback upgrades status for valid Go syntax.
    assert_eq!(resp.validation.status, "passed");
    assert_eq!(
        resp.validation.validation_confidence.as_deref(),
        Some("syntax_only")
    );
    assert!(resp.validation_skipped);
    assert_eq!(
        resp.validation_skipped_reason.as_deref(),
        Some("pull_diagnostics_unsupported")
    );
}

// ── pre_diag_timeout: first pull_diagnostics errors → skipped ───────

#[tokio::test]
async fn test_run_lsp_validation_pre_diag_timeout() {
    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();
    // did_open succeeds (default); first pull_diagnostics returns a protocol
    // error — any error that is not UnsupportedCapability maps to
    // "diagnostic_timeout" in run_lsp_validation.
    mock_lawyer.push_pull_diagnostics_result(Err("LSP timed out".to_owned()));

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { return }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed — pre-diag timeout gracefully degrades");
    let resp = result.0;

    assert!(resp.success);
    // TS-1: Tree-sitter fallback upgrades status for valid Go syntax.
    assert_eq!(resp.validation.status, "passed");
    assert_eq!(
        resp.validation.validation_confidence.as_deref(),
        Some("syntax_only")
    );
    assert!(resp.validation_skipped);
    assert_eq!(
        resp.validation_skipped_reason.as_deref(),
        Some("lsp_protocol_error")
    );
}

// ── pre_diag_unsupported: first pull_diagnostics → UnsupportedCapability
//    → skipped with "pull_diagnostics_unsupported" reason ────────────────

#[tokio::test]
async fn test_run_lsp_validation_pull_diagnostics_unsupported() {
    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    // `mock_surgeon` is used in the first call but we need a fresh surgeon
    // for the second server construction; discard the first fixture result.
    let (_mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    // UnsupportedDiagLawyer always returns UnsupportedCapability from
    // pull_diagnostics, exercising the "pull_diagnostics_unsupported" branch.
    let (mock_surgeon_2, _) = setup_full_replace_fixture(&ws_dir, filepath, src);
    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()),
        Arc::new(mock_surgeon_2),
        Arc::new(UnsupportedDiagLawyer),
    );

    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { return }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed — pull_diagnostics_unsupported degrades");
    let resp = result.0;

    // TS-1: Tree-sitter fallback upgrades status for valid Go syntax.
    assert_eq!(resp.validation.status, "passed");
    assert_eq!(
        resp.validation.validation_confidence.as_deref(),
        Some("syntax_only")
    );
    assert_eq!(
        resp.validation_skipped_reason.as_deref(),
        Some("pull_diagnostics_unsupported")
    );
}

// ── post_diag_timeout: second pull_diagnostics errors → skipped ──────

#[tokio::test]
async fn test_run_lsp_validation_post_diag_timeout() {
    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();
    // Pre-edit pull_diagnostics succeeds with empty diags.
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![]));
    // Post-edit pull_diagnostics errors (e.g. timeout).
    mock_lawyer.push_pull_diagnostics_result(Err("timeout after 10s".to_owned()));

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { return }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed — post-diag timeout gracefully degrades");
    let resp = result.0;

    assert!(resp.success);
    // TS-1: Tree-sitter fallback upgrades status for valid Go syntax.
    assert_eq!(resp.validation.status, "passed");
    assert_eq!(
        resp.validation.validation_confidence.as_deref(),
        Some("syntax_only")
    );
    assert!(resp.validation_skipped);
    assert_eq!(
        resp.validation_skipped_reason.as_deref(),
        Some("lsp_protocol_error")
    );
}

// ── blocking: new errors introduced + ignore_validation_failures=false ─

#[tokio::test]
async fn test_run_lsp_validation_blocking() {
    use pathfinder_lsp::types::{LspDiagnostic, LspDiagnosticSeverity};

    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();
    // Pre-edit: no errors.
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![]));
    // Post-edit: one new error introduced.
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![LspDiagnostic {
        severity: LspDiagnosticSeverity::Error,
        code: Some("E001".into()),
        message: "undefined: Foo".into(),
        file: filepath.to_owned(),
        start_line: 1,
        end_line: 1,
    }]));

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    // ignore_validation_failures = false → should block
    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { Foo() }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server.replace_full(Parameters(params)).await;

    let Err(err) = result else {
        panic!("expected VALIDATION_FAILED error when new errors are introduced");
    };
    let code = err
        .data
        .as_ref()
        .and_then(|d| d.get("error"))
        .and_then(|v| v.as_str())
        .unwrap_or("");
    assert_eq!(code, "VALIDATION_FAILED", "got: {err:?}");
    // Confirm the introduced error is surfaced (nested under details.introduced_errors
    // because pathfinder_to_error_data serializes ErrorResponse which has a `details` field)
    let introduced = err
        .data
        .as_ref()
        .and_then(|d| d.get("details"))
        .and_then(|d| d.get("introduced_errors"))
        .and_then(|v| v.as_array())
        .map_or(0, Vec::len);
    assert_eq!(
        introduced, 1,
        "one new error should appear in introduced_errors"
    );
}

// ── workspace blocking: new errors in other files block the edit ────────

#[tokio::test]
async fn test_run_lsp_validation_workspace_blocking() {
    use pathfinder_lsp::types::{LspDiagnostic, LspDiagnosticSeverity};

    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();
    // Pre-edit diagnostics (file + workspace)
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![]));
    mock_lawyer.push_pull_workspace_diagnostics_result(Ok(vec![]));

    // Post-edit diagnostics (no errors in single file, but 1 error in workspace)
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![]));
    mock_lawyer.push_pull_workspace_diagnostics_result(Ok(vec![LspDiagnostic {
        severity: LspDiagnosticSeverity::Error,
        code: Some("E002".into()),
        message: "cannot call Login with 1 argument".into(),
        file: "src/main.go".to_owned(), // Different file!
        start_line: 5,
        end_line: 5,
    }]));

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    // ignore_validation_failures = false → should block
    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login(a string) { }\n".to_owned(), // changed signature
        ignore_validation_failures: false,
    };
    let result = server.replace_full(Parameters(params)).await;

    let Err(err) = result else {
        panic!("expected VALIDATION_FAILED error when workspace errors are introduced");
    };
    let code = err
        .data
        .as_ref()
        .and_then(|d| d.get("error"))
        .and_then(|v| v.as_str())
        .unwrap_or("");
    assert_eq!(code, "VALIDATION_FAILED", "got: {err:?}");

    // Confirm the workspace error is reported
    let introduced = err
        .data
        .as_ref()
        .and_then(|d| d.get("details"))
        .and_then(|d| d.get("introduced_errors"))
        .and_then(|v| v.as_array())
        .expect("should have introduced_errors");
    assert_eq!(
        introduced.len(),
        1,
        "one workspace error should appear in introduced_errors"
    );
    let first_err_file = introduced[0].get("file").and_then(|v| v.as_str()).unwrap();
    assert_eq!(
        first_err_file, "src/main.go",
        "error should be in src/main.go"
    );
}

// ── blocking_ignored: new errors + ignore_validation_failures=true → passes

#[tokio::test]
async fn test_run_lsp_validation_blocking_ignored() {
    use pathfinder_lsp::types::{LspDiagnostic, LspDiagnosticSeverity};

    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![]));
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![LspDiagnostic {
        severity: LspDiagnosticSeverity::Error,
        code: Some("E001".into()),
        message: "undefined: Foo".into(),
        file: filepath.to_owned(),
        start_line: 1,
        end_line: 1,
    }]));

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    // ignore_validation_failures = true → should NOT block, file is written
    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { Foo() }\n".to_owned(),
        ignore_validation_failures: true,
    };
    let _result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed when ignore_validation_failures=true");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();
    // One pre-existing warning (non-error) in both pre and post.
    let existing_warning = LspDiagnostic {
        severity: LspDiagnosticSeverity::Warning,
        code: Some("W001".into()),
        message: "unused import".into(),
        file: filepath.to_owned(),
        start_line: 1,
        end_line: 1,
    };
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![existing_warning.clone()]));
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![existing_warning]));

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { return }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed — no new errors");
    let resp = result.0;

    assert!(resp.success);
    assert_eq!(resp.validation.status, "passed");
    assert!(!resp.validation_skipped);
    assert!(resp.validation.introduced_errors.is_empty());
    assert!(resp.validation.resolved_errors.is_empty());
}

// ── empty_diagnostics_both_snapshots: warmup signal ─────────────────────────

#[test]
fn test_build_validation_outcome_empty_snapshots_signals_warmup() {
    // When both pre and post diagnostic snapshots are empty, the validation
    // outcome must be skipped with reason "empty_diagnostics_both_snapshots".
    // This prevents agents from trusting a vacuously-clean pass during LSP warmup.
    use crate::server::tools::edit::text_edit::build_validation_outcome;
    use std::path::Path;

    let outcome = build_validation_outcome(
        &[], // pre_diags: empty (LSP warmup or genuinely clean)
        &[], // post_diags: empty
        false,
        Path::new("src/lib.rs"),
        "pull",
    );

    assert!(
        outcome.skipped,
        "validation_skipped must be true when both snapshots are empty"
    );
    assert_eq!(
        outcome.skipped_reason.as_deref(),
        Some("empty_diagnostics_both_snapshots"),
        "skipped_reason must identify the warmup signal"
    );
    assert_eq!(
        outcome.validation.status, "uncertain",
        "status must be 'uncertain' when both snapshots are empty (LSP may be warming up)"
    );
    assert!(
        !outcome.should_block,
        "should_block must be false — empty snapshots are never a blocker"
    );
}

#[test]
fn test_build_validation_outcome_non_empty_pre_does_not_skip() {
    // If pre_diags has errors but post is empty (errors resolved),
    // we must NOT trigger the warmup-skip path — the diff is meaningful.
    use crate::server::tools::edit::text_edit::build_validation_outcome;
    use pathfinder_lsp::types::{LspDiagnostic, LspDiagnosticSeverity};
    use std::path::Path;

    let pre = vec![LspDiagnostic {
        severity: LspDiagnosticSeverity::Error,
        code: None,
        message: "pre-existing error".to_owned(),
        file: "src/lib.rs".to_owned(),
        start_line: 1,
        end_line: 1,
    }];

    let outcome = build_validation_outcome(&pre, &[], false, Path::new("src/lib.rs"), "pull");

    // pre non-empty → NOT the warmup-skip path
    assert!(
        !outcome.skipped,
        "must not skip when pre_diags is non-empty (diff is meaningful)"
    );
    assert_eq!(outcome.validation.status, "passed");
    assert!(!outcome.should_block);
}

// ── Push diagnostics tests (PATCH-002) ──────────────────────────────
//
// These tests verify the push diagnostics path in run_lsp_validation.
// The push path is triggered when capability_status reports diagnostics_strategy
// as "push" for the file's language. This is the path used by gopls and
// typescript-language-server (they don't support pull diagnostics).
//
// Mock setup: set_capability_status with diagnostics_strategy: Some("push")
// queues results via push_pull_diagnostics_result (shared queue with pull).

// ── push_validation_no_errors: pre and post both empty → passes ────

#[tokio::test]
async fn test_push_validation_no_errors() {
    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();

    // Configure capability_status to report push diagnostics for Go
    mock_lawyer.set_capability_status(std::collections::HashMap::from([(
        "go".to_string(),
        pathfinder_lsp::types::LspLanguageStatus {
            validation: true,
            reason: "gopls connected (push diagnostics)".to_string(),
            navigation_ready: Some(true),
            indexing_complete: Some(true),
            uptime_seconds: Some(30),
            diagnostics_strategy: Some("push".to_string()),
            supports_definition: Some(true),
            supports_call_hierarchy: Some(true),
            supports_diagnostics: Some(true),
            supports_formatting: Some(false),

            server_name: None,
        },
    )]));

    // Pre-edit: no errors (collect_diagnostics call 1)
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![]));
    // Post-edit: no errors (collect_diagnostics call 2)
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![]));

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { return }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed — push validation with no errors");
    let resp = result.0;

    assert!(
        resp.success,
        "edit should succeed when push validation finds no new errors"
    );
    // TS-1: Tree-sitter fallback upgrades status from "uncertain" to "passed" for valid Go code.
    // The warmup skip path triggers first (both snapshots empty), then Tree-sitter runs
    // and sees valid syntax, upgrading status to "passed" with "syntax_only" confidence.
    assert_eq!(
        resp.validation.status, "passed",
        "TS-1 fallback should upgrade status to 'passed' for valid Go syntax"
    );
    assert_eq!(
        resp.validation.validation_confidence.as_deref(),
        Some("syntax_only"),
        "confidence must be syntax_only when upgraded by Tree-sitter"
    );
    assert!(
        resp.validation_skipped,
        "empty push snapshots should trigger skip"
    );
    assert_eq!(
        resp.validation_skipped_reason.as_deref(),
        Some("empty_diagnostics_both_snapshots"),
        "skip reason should indicate empty snapshots"
    );
}

// ── push_validation_clean_pass: pre and post both non-empty, no new errors → passes ──

#[tokio::test]
async fn test_push_validation_clean_pass() {
    use pathfinder_lsp::types::{LspDiagnostic, LspDiagnosticSeverity};

    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();

    mock_lawyer.set_capability_status(std::collections::HashMap::from([(
        "go".to_string(),
        pathfinder_lsp::types::LspLanguageStatus {
            validation: true,
            reason: "gopls connected (push diagnostics)".to_string(),
            navigation_ready: Some(true),
            indexing_complete: Some(true),
            uptime_seconds: Some(30),
            diagnostics_strategy: Some("push".to_string()),
            supports_definition: Some(true),
            supports_call_hierarchy: Some(true),
            supports_diagnostics: Some(true),
            supports_formatting: Some(false),

            server_name: None,
        },
    )]));

    // Same pre-existing warning in both snapshots → no NEW errors
    let existing_warning = LspDiagnostic {
        severity: LspDiagnosticSeverity::Warning,
        code: Some("W001".into()),
        message: "unused variable".into(),
        file: filepath.to_owned(),
        start_line: 1,
        end_line: 1,
    };
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![existing_warning.clone()]));
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![existing_warning]));

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { return }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed — push validation with no new errors");
    let resp = result.0;

    assert!(resp.success);
    assert_eq!(resp.validation.status, "passed");
    assert!(!resp.validation_skipped);
    assert!(resp.validation.introduced_errors.is_empty());
    assert!(resp.validation.resolved_errors.is_empty());
}

// ── push_validation_introduced_error: post has new error → blocks edit ──

#[tokio::test]
async fn test_push_validation_introduced_error() {
    use pathfinder_lsp::types::{LspDiagnostic, LspDiagnosticSeverity};

    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();

    mock_lawyer.set_capability_status(std::collections::HashMap::from([(
        "go".to_string(),
        pathfinder_lsp::types::LspLanguageStatus {
            validation: true,
            reason: "gopls connected (push diagnostics)".to_string(),
            navigation_ready: Some(true),
            indexing_complete: Some(true),
            uptime_seconds: Some(30),
            diagnostics_strategy: Some("push".to_string()),
            supports_definition: Some(true),
            supports_call_hierarchy: Some(true),
            supports_diagnostics: Some(true),
            supports_formatting: Some(false),

            server_name: None,
        },
    )]));

    // Pre-edit: no errors
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![]));
    // Post-edit: one new error introduced
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![LspDiagnostic {
        severity: LspDiagnosticSeverity::Error,
        code: Some("E001".into()),
        message: "undefined: Foo".into(),
        file: filepath.to_owned(),
        start_line: 1,
        end_line: 1,
    }]));

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { Foo() }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server.replace_full(Parameters(params)).await;

    let Err(err) = result else {
        panic!("expected VALIDATION_FAILED error when push diagnostics finds new errors");
    };
    let code = err
        .data
        .as_ref()
        .and_then(|d| d.get("error"))
        .and_then(|v| v.as_str())
        .unwrap_or("");
    assert_eq!(code, "VALIDATION_FAILED", "got: {err:?}");

    let introduced = err
        .data
        .as_ref()
        .and_then(|d| d.get("details"))
        .and_then(|d| d.get("introduced_errors"))
        .and_then(|v| v.as_array())
        .map_or(0, Vec::len);
    assert_eq!(
        introduced, 1,
        "one new error should appear in introduced_errors from push path"
    );
}

// ── push_validation_pre_fails: pre-edit collect_diagnostics errors → skipped ──

#[tokio::test]
async fn test_push_validation_pre_fails() {
    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();

    mock_lawyer.set_capability_status(std::collections::HashMap::from([(
        "go".to_string(),
        pathfinder_lsp::types::LspLanguageStatus {
            validation: true,
            reason: "gopls connected (push diagnostics)".to_string(),
            navigation_ready: Some(true),
            indexing_complete: Some(true),
            uptime_seconds: Some(30),
            diagnostics_strategy: Some("push".to_string()),
            supports_definition: Some(true),
            supports_call_hierarchy: Some(true),
            supports_diagnostics: Some(true),
            supports_formatting: Some(false),

            server_name: None,
        },
    )]));

    // Pre-edit collect_diagnostics fails (e.g., LSP timeout)
    mock_lawyer.push_pull_diagnostics_result(Err("push collection timed out".to_owned()));

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { return }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed — push pre-diag failure gracefully degrades");
    let resp = result.0;

    assert!(resp.success, "edit should succeed despite pre-diag failure");
    // TS-1: Tree-sitter fallback upgrades status for valid Go syntax.
    assert_eq!(resp.validation.status, "passed");
    assert_eq!(
        resp.validation.validation_confidence.as_deref(),
        Some("syntax_only")
    );
    assert!(resp.validation_skipped);
    assert_eq!(
        resp.validation_skipped_reason.as_deref(),
        Some("lsp_protocol_error"),
        "push pre-diag failure should map to lsp_protocol_error"
    );
}

// ── push_validation_post_fails: post-edit collect_diagnostics errors → skipped ──

#[tokio::test]
async fn test_push_validation_post_fails() {
    let ws_dir = tempdir().expect("temp dir");
    let filepath = "src/auth.go";
    let src = "func Login() {}";
    let (mock_surgeon, hash) = setup_full_replace_fixture(&ws_dir, filepath, src);

    let mock_lawyer = pathfinder_lsp::MockLawyer::default();

    mock_lawyer.set_capability_status(std::collections::HashMap::from([(
        "go".to_string(),
        pathfinder_lsp::types::LspLanguageStatus {
            validation: true,
            reason: "gopls connected (push diagnostics)".to_string(),
            navigation_ready: Some(true),
            indexing_complete: Some(true),
            uptime_seconds: Some(30),
            diagnostics_strategy: Some("push".to_string()),
            supports_definition: Some(true),
            supports_call_hierarchy: Some(true),
            supports_diagnostics: Some(true),
            supports_formatting: Some(false),

            server_name: None,
        },
    )]));

    // Pre-edit: succeeds with empty diags
    mock_lawyer.push_pull_diagnostics_result(Ok(vec![]));
    // Post-edit: fails (e.g., LSP crashed mid-collection)
    mock_lawyer
        .push_pull_diagnostics_result(Err("connection lost during push collection".to_owned()));

    let server = make_server_with_lawyer(&ws_dir, mock_surgeon, mock_lawyer);

    let params = ReplaceFullParams {
        semantic_path: format!("{filepath}::Login"),
        base_version: hash.as_str().to_owned(),
        new_code: "func Login() { return }\n".to_owned(),
        ignore_validation_failures: false,
    };
    let result = server
        .replace_full(Parameters(params))
        .await
        .expect("should succeed — push post-diag failure gracefully degrades");
    let resp = result.0;

    assert!(
        resp.success,
        "edit should succeed despite post-diag failure"
    );
    // TS-1: Tree-sitter fallback upgrades status for valid Go syntax.
    assert_eq!(resp.validation.status, "passed");
    assert_eq!(
        resp.validation.validation_confidence.as_deref(),
        Some("syntax_only")
    );
    assert!(resp.validation_skipped);
    assert_eq!(
        resp.validation_skipped_reason.as_deref(),
        Some("lsp_protocol_error"),
        "push post-diag failure should map to lsp_protocol_error"
    );
}

// ── lsp_error_to_skip_reason: pure function, all variants tested ──────
//
// These tests verify that every LspError variant maps to the correct
// skip reason string. This ensures complete coverage of the match
// statement in lsp_error_to_skip_reason.

#[test]
fn test_lsp_error_to_skip_reason_no_lsp() {
    use crate::server::PathfinderServer;
    use pathfinder_lsp::LspError;

    let err = LspError::NoLspAvailable;
    let reason = PathfinderServer::lsp_error_to_skip_reason(&err);
    assert_eq!(reason, "no_lsp");
}

#[test]
fn test_lsp_error_to_skip_reason_timeout() {
    use crate::server::PathfinderServer;
    use pathfinder_lsp::LspError;

    let err = LspError::Timeout {
        operation: "textDocument/definition".to_owned(),
        timeout_ms: 10_000,
    };
    let reason = PathfinderServer::lsp_error_to_skip_reason(&err);
    assert_eq!(reason, "lsp_timeout");
}

#[test]
fn test_lsp_error_to_skip_reason_protocol() {
    use crate::server::PathfinderServer;
    use pathfinder_lsp::LspError;

    let err = LspError::Protocol("malformed JSON response".to_owned());
    let reason = PathfinderServer::lsp_error_to_skip_reason(&err);
    assert_eq!(reason, "lsp_protocol_error");
}

#[test]
fn test_lsp_error_to_skip_reason_connection_lost() {
    use crate::server::PathfinderServer;
    use pathfinder_lsp::LspError;

    let err = LspError::ConnectionLost;
    let reason = PathfinderServer::lsp_error_to_skip_reason(&err);
    assert_eq!(reason, "lsp_crash");
}

#[test]
fn test_lsp_error_to_skip_reason_unsupported_capability() {
    use crate::server::PathfinderServer;
    use pathfinder_lsp::LspError;

    let err = LspError::UnsupportedCapability {
        capability: "diagnosticProvider".to_owned(),
    };
    let reason = PathfinderServer::lsp_error_to_skip_reason(&err);
    assert_eq!(reason, "pull_diagnostics_unsupported");
}

#[test]
fn test_lsp_error_to_skip_reason_io_not_found() {
    use crate::server::PathfinderServer;
    use pathfinder_lsp::LspError;
    use std::io::{Error, ErrorKind};

    // Io(NotFound) maps to "lsp_not_on_path" - this is the case where
    // the LSP binary is not installed or not in PATH.
    let io_err = Error::new(ErrorKind::NotFound, "No such file or directory");
    let err = LspError::Io(io_err);
    let reason = PathfinderServer::lsp_error_to_skip_reason(&err);
    assert_eq!(reason, "lsp_not_on_path");
}

#[test]
fn test_lsp_error_to_skip_reason_io_other_kinds() {
    use crate::server::PathfinderServer;
    use pathfinder_lsp::LspError;
    use std::io::{Error, ErrorKind};

    // All non-NotFound Io errors map to "lsp_start_failed".
    // Test several common error kinds.
    for (kind, name) in [
        (ErrorKind::PermissionDenied, "PermissionDenied"),
        (ErrorKind::ConnectionRefused, "ConnectionRefused"),
        (ErrorKind::BrokenPipe, "BrokenPipe"),
        (ErrorKind::TimedOut, "TimedOut"),
        (ErrorKind::Other, "Other"),
    ] {
        let io_err = Error::new(kind, format!("{name} error"));
        let err = LspError::Io(io_err);
        let reason = PathfinderServer::lsp_error_to_skip_reason(&err);
        assert_eq!(
            reason, "lsp_start_failed",
            "ErrorKind::{name} should map to 'lsp_start_failed'"
        );
    }
}