pathfinder-mcp 0.22.0

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
use super::*;

// ── Schema Description Tests ────────────────────────────────────────
//
// These tests verify that agent-visible schema descriptions (generated by
// schemars from doc comments) contain the required semantic information.
// They catch regressions where a doc comment change silently drops
// important guidance from the MCP-facing parameter schema.

/// Finding 6: `exclude_glob` schema description must include brace expansion docs.
///
/// Agents see the `description` field from the JSON Schema generated by schemars.
/// Without this, agents don't know they can pass `{**/*.spec.*,**/*.test.*}` to
/// exclude multiple patterns in one call, and will incorrectly believe only a
/// single glob pattern is supported.
#[test]
fn test_search_params_exclude_glob_schema_documents_brace_expansion() {
    let schema = schemars::schema_for!(SearchParams);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    let description = schema_json["properties"]["exclude_glob"]["description"]
        .as_str()
        .expect("`exclude_glob` property must have a `description` field in the generated schema");

    assert!(
        description.contains("brace expansion"),
        "`exclude_glob` schema description must mention brace expansion so agents know \
         they can use `{{**/*.spec.*,**/*.test.*}}` syntax.\nGot description: {description:?}"
    );

    assert!(
        description.contains('{') && description.contains('}'),
        "`exclude_glob` schema description must include a brace expansion example.\n\
         Got description: {description:?}"
    );
}

#[test]
fn test_read_params_max_lines_per_file_schema_documents_truncation() {
    let schema = schemars::schema_for!(ReadParams);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    let description = schema_json["properties"]["max_lines_per_file"]["description"]
        .as_str()
        .expect(
            "`max_lines_per_file` property must have a `description` field in the generated schema",
        );

    assert!(
        description.contains("batch mode and config/raw files"),
        "`max_lines_per_file` schema description must document that it applies to batch mode and config/raw files.\nGot description: {description:?}"
    );
}

/// Finding 2: `FindCallersCalleesMetadata.incoming` schema description must document
/// the null vs [] contract so agents can distinguish unknown from confirmed-zero.
///
/// MCP exposes `inputSchema` but not `outputSchema`. Agents learn the response
/// contract from the tool description field. The doc comment on the struct field
/// IS included in the schemars-generated schema (via `JsonSchema` derive) and
/// available as `structured_content`, so it must be correct and complete.
#[test]
fn test_find_callers_callees_metadata_incoming_schema_documents_null_vs_empty() {
    let schema = schemars::schema_for!(FindCallersCalleesMetadata);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    let description = schema_json["properties"]["incoming"]["description"]
        .as_str()
        .expect("`incoming` property must have a `description` field in the generated schema");

    assert!(
        description.contains("null") || description.contains("`null`"),
        "`incoming` schema description must explicitly mention `null` so agents know \
         the field is absent when degraded, not just empty.\nGot: {description:?}"
    );

    assert!(
        description.contains("[]") || description.contains("empty array"),
        "`incoming` schema description must distinguish `[]` (confirmed zero) from `null` \
         (unknown/degraded).\nGot: {description:?}"
    );

    assert!(
        description.contains("degraded"),
        "`incoming` schema description must reference the `degraded` field to explain \
         when null is returned.\nGot: {description:?}"
    );
}

/// Companion check for `outgoing` — same null vs [] contract as `incoming`.
#[test]
fn test_find_callers_callees_metadata_outgoing_schema_documents_null_vs_empty() {
    let schema = schemars::schema_for!(FindCallersCalleesMetadata);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    let description = schema_json["properties"]["outgoing"]["description"]
        .as_str()
        .expect("`outgoing` property must have a `description` field in the generated schema");

    assert!(
        description.contains("null") || description.contains("`null`"),
        "`outgoing` schema description must mention `null`.\nGot: {description:?}"
    );

    assert!(
        description.contains("[]") || description.contains("empty array"),
        "`outgoing` schema description must distinguish `[]` from `null`.\nGot: {description:?}"
    );
}

/// `FindAllReferencesMetadata.references` must document the same contract.
#[test]
fn test_find_all_references_metadata_references_schema_documents_null_vs_empty() {
    let schema = schemars::schema_for!(FindAllReferencesMetadata);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    let description = schema_json["properties"]["references"]["description"]
        .as_str()
        .expect("`references` property must have a `description` field in the generated schema");

    assert!(
        description.contains("null") || description.contains("`null`"),
        "`references` schema description must mention `null`.\nGot: {description:?}"
    );

    assert!(
        description.contains("[]") || description.contains("empty array"),
        "`references` schema description must distinguish `[]` from `null`.\nGot: {description:?}"
    );
}

/// `ImpactSummary.incoming` (used by `SymbolOverviewResponse`) has `skip_serializing_if`.
/// Its doc must clarify the field is **absent** (not null) when unavailable.
#[test]
fn test_impact_summary_incoming_schema_documents_absent_semantics() {
    let schema = schemars::schema_for!(ImpactSummary);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    let description = schema_json["properties"]["incoming"]["description"]
        .as_str()
        .expect("`incoming` property must have a `description` field");

    assert!(
        description.contains("absent") || description.contains("omitted"),
        "`ImpactSummary.incoming` uses `skip_serializing_if` — doc must say \
         the field is absent (not null) when unavailable.\nGot: {description:?}"
    );
}

/// Same check for `ImpactSummary.outgoing`.
#[test]
fn test_impact_summary_outgoing_schema_documents_absent_semantics() {
    let schema = schemars::schema_for!(ImpactSummary);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    let description = schema_json["properties"]["outgoing"]["description"]
        .as_str()
        .expect("`outgoing` property must have a `description` field");

    assert!(
        description.contains("absent") || description.contains("omitted"),
        "`ImpactSummary.outgoing` uses `skip_serializing_if` — doc must say \
         the field is absent (not null) when unavailable.\nGot: {description:?}"
    );
}

/// `SymbolOverviewResponse.references` has `skip_serializing_if` — doc must
/// clarify the field is absent when unavailable, and present as `[]` when
/// LSP confirmed zero references.
#[test]
fn test_symbol_overview_response_references_schema_documents_absent_semantics() {
    let schema = schemars::schema_for!(SymbolOverviewResponse);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    let description = schema_json["properties"]["references"]["description"]
        .as_str()
        .expect("`references` property must have a `description` field");

    assert!(
        description.contains("absent") || description.contains("omitted"),
        "`SymbolOverviewResponse.references` uses `skip_serializing_if` — doc \
         must say the field is absent when unavailable.\nGot: {description:?}"
    );

    assert!(
        description.contains("[]") || description.contains("empty array"),
        "`SymbolOverviewResponse.references` must document that `[]` means \
         LSP confirmed zero references.\nGot: {description:?}"
    );
}

/// `FindCallersCalleesMetadata.degraded` doc says "When `true`, `incoming`
/// and `outgoing` are `null` (not empty arrays)" — but code can produce
/// `degraded=true` with `Some(vec)` from grep fallback. The doc must
/// accurately reflect the actual code behavior.
#[test]
fn test_find_callers_callees_degraded_doc_is_accurate() {
    let schema = schemars::schema_for!(FindCallersCalleesMetadata);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    let description = schema_json["properties"]["degraded"]["description"]
        .as_str()
        .expect("`degraded` property must have a `description` field");

    // The doc must NOT claim incoming/outgoing are always null when degraded,
    // because grep fallback can produce Some(results) while degraded.
    assert!(
        !description.contains("are `null` (not empty arrays)"),
        "`degraded` doc must not claim incoming/outgoing are always null when degraded — \
         grep fallback can produce heuristic results while degraded=true.\nGot: {description:?}"
    );
}

/// `GetRepoMapMetadata.visibility_degraded` doc says "always true" but the
/// code always sets it to `None`. The doc must match the implementation.
#[test]
fn test_visibility_degraded_doc_matches_code() {
    let schema = schemars::schema_for!(GetRepoMapMetadata);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    // The field is Option<bool> with skip_serializing_if — may not have a description
    // if the doc comment is removed. But if it exists, it must not say "always true".
    if let Some(description) =
        schema_json["properties"]["visibility_degraded"]["description"].as_str()
    {
        assert!(
            !description.contains("Always `true`") && !description.contains("always true"),
            "`visibility_degraded` doc says 'always true' but code always sets None.\n\
             Got: {description:?}"
        );
    }
}

// ── Serialization Behavior Tests ────────────────────────────────────
//
// These verify that the JSON serialization of None vs Some(vec![])
// matches what the doc comments promise agents will see.

/// `FindCallersCalleesMetadata.incoming` serializes as JSON `null` when `None`
/// (no `skip_serializing_if`), and as `[]` when `Some(vec![])`.
#[test]
fn test_find_callers_callees_incoming_serialization_null_vs_empty() {
    // None → JSON null
    let meta_none = FindCallersCalleesMetadata {
        incoming: None,
        ..Default::default()
    };
    let json = serde_json::to_value(&meta_none).expect("serialize");
    assert!(
        json["incoming"].is_null(),
        "`incoming: None` must serialize as JSON `null`, got: {}",
        json["incoming"]
    );

    // Some(vec![]) → JSON []
    let meta_empty = FindCallersCalleesMetadata {
        incoming: Some(vec![]),
        ..Default::default()
    };
    let json = serde_json::to_value(&meta_empty).expect("serialize");
    assert!(
        json["incoming"].is_array() && json["incoming"].as_array().unwrap().is_empty(),
        "`incoming: Some(vec![])` must serialize as JSON `[]`, got: {}",
        json["incoming"]
    );
}

/// `ImpactSummary.incoming` (with `skip_serializing_if`) is ABSENT when None.
#[test]
fn test_impact_summary_incoming_serialization_absent_vs_empty() {
    // None → field absent
    let summary = ImpactSummary {
        incoming: None,
        outgoing: None,
        degraded: true,
    };
    let json = serde_json::to_value(&summary).expect("serialize");
    let obj = json.as_object().expect("object");
    assert!(
        !obj.contains_key("incoming"),
        "`ImpactSummary.incoming: None` must be ABSENT from JSON, \
         but it was present: {json}"
    );

    // Some(vec![]) → present as []
    let summary_empty = ImpactSummary {
        incoming: Some(vec![]),
        outgoing: None,
        degraded: false,
    };
    let json = serde_json::to_value(&summary_empty).expect("serialize");
    assert!(
        json["incoming"].is_array() && json["incoming"].as_array().unwrap().is_empty(),
        "`ImpactSummary.incoming: Some(vec![])` must serialize as `[]`, got: {}",
        json["incoming"]
    );
}

/// `SymbolOverviewResponse.references` (with `skip_serializing_if`) is ABSENT when None.
#[test]
fn test_symbol_overview_response_references_serialization_absent_vs_empty() {
    let resp = SymbolOverviewResponse {
        references: None,
        source: None,
        impact: None,
        files_referenced: 0,
        degraded: true,
        impact_degraded: false,
        references_degraded: false,
        degraded_reason: None,
        actionable_guidance: None,
        lsp_readiness: None,
        warm_start_in_progress: None,
    };
    let json = serde_json::to_value(&resp).expect("serialize");
    let obj = json.as_object().expect("object");
    assert!(
        !obj.contains_key("references"),
        "`SymbolOverviewResponse.references: None` must be ABSENT from JSON, \
         but it was present: {json}"
    );
}

#[test]
fn test_default_value_helpers() {
    assert_eq!(default_path_glob(), "**/*");
    assert_eq!(default_max_results(), 50);
    assert_eq!(default_context_lines(), 2);
    assert_eq!(default_repo_map_path(), ".");
    assert_eq!(default_max_tokens(), 16_000);
    assert_eq!(default_max_tokens_per_file(), 2_000);
    assert_eq!(default_max_depth(), 3);
    assert_eq!(default_max_references(), 50);
    assert_eq!(default_max_dependencies(), 50);
    assert_eq!(default_start_line(), 1);
    assert_eq!(default_max_lines(), 500);
    assert_eq!(default_detail_level(), "compact");
    assert!(default_group_by_file());
    assert_eq!(default_filter_mode(), FilterMode::CodeOnly);
}

#[test]
fn test_filepath_alias_deserialization() {
    let json_data = serde_json::json!({
        "path": "src/lib.rs",
        "start_line": 10,
    });
    let read_params: ReadParams = serde_json::from_value(json_data).unwrap();
    assert_eq!(read_params.filepath, Some("src/lib.rs".to_string()));
}

// ── Serde Roundtrip Tests ───────────────────────────────────────────

#[test]
fn test_degraded_reason_serde_roundtrip() {
    use pathfinder_common::types::DegradedReason;

    let variants = vec![
        (DegradedReason::NoLsp, "\"no_lsp\""),
        (
            DegradedReason::LspWarmupEmptyUnverified,
            "\"lsp_warmup_empty_unverified\"",
        ),
        (
            DegradedReason::LspWarmupGrepFallback,
            "\"lsp_warmup_grep_fallback\"",
        ),
        (
            DegradedReason::LspTimeoutGrepFallback,
            "\"lsp_timeout_grep_fallback\"",
        ),
        (
            DegradedReason::LspErrorGrepFallback,
            "\"lsp_error_grep_fallback\"",
        ),
        (
            DegradedReason::NoLspGrepFallback,
            "\"no_lsp_grep_fallback\"",
        ),
        (
            DegradedReason::GrepFallbackFileScoped,
            "\"grep_fallback_file_scoped\"",
        ),
        (
            DegradedReason::GrepFallbackImplScoped,
            "\"grep_fallback_impl_scoped\"",
        ),
        (
            DegradedReason::GrepFallbackGlobal,
            "\"grep_fallback_global\"",
        ),
        (
            DegradedReason::GrepFallbackDependencies,
            "\"grep_fallback_dependencies\"",
        ),
        (
            DegradedReason::UnsupportedLanguageFilterBypassed,
            "\"unsupported_language_filter_bypassed\"",
        ),
        (
            DegradedReason::UnsupportedLanguage,
            "\"unsupported_language\"",
        ),
        (DegradedReason::GitError, "\"git_error\""),
    ];

    for (variant, expected_json) in variants {
        let serialized = serde_json::to_string(&variant).expect("serialize DegradedReason");
        assert_eq!(
            serialized, expected_json,
            "serialize mismatch for {variant:?}"
        );

        let deserialized: DegradedReason =
            serde_json::from_str(&serialized).expect("deserialize DegradedReason");
        assert_eq!(deserialized, variant, "roundtrip mismatch for {variant:?}");
    }
}

#[test]
fn test_detail_enum_serde() {
    let cases = vec![
        ("\"structure\"", "structure"),
        ("\"files\"", "files"),
        ("\"symbols\"", "symbols"),
    ];

    for (json_str, label) in cases {
        let detail: Detail = serde_json::from_str(json_str)
            .unwrap_or_else(|e| panic!("failed to deserialize Detail from {json_str}: {e}"));
        match (label, &detail) {
            ("structure", Detail::Structure)
            | ("files", Detail::Files)
            | ("symbols", Detail::Symbols) => {}
            _ => panic!("unexpected Detail variant for {label}: {detail:?}"),
        }
    }
}

#[test]
fn test_search_mode_serde() {
    let cases = vec![
        ("\"text\"", "text"),
        ("\"symbol\"", "symbol"),
        ("\"regex\"", "regex"),
    ];

    for (json_str, label) in cases {
        let mode: SearchMode = serde_json::from_str(json_str)
            .unwrap_or_else(|e| panic!("failed to deserialize SearchMode from {json_str}: {e}"));
        match (label, &mode) {
            ("text", SearchMode::Text)
            | ("symbol", SearchMode::Symbol)
            | ("regex", SearchMode::Regex) => {}
            _ => panic!("unexpected SearchMode variant for {label}: {mode:?}"),
        }
    }
}

#[test]
fn test_trace_scope_serde() {
    let cases = vec![
        ("\"callers\"", "callers"),
        ("\"references\"", "references"),
        ("\"overview\"", "overview"),
    ];

    for (json_str, label) in cases {
        let scope: TraceScope = serde_json::from_str(json_str)
            .unwrap_or_else(|e| panic!("failed to deserialize TraceScope from {json_str}: {e}"));
        match (label, &scope) {
            ("callers", TraceScope::Callers)
            | ("references", TraceScope::References)
            | ("overview", TraceScope::Overview) => {}
            _ => panic!("unexpected TraceScope variant for {label}: {scope:?}"),
        }
    }
}

// ── Default Impl Tests ──────────────────────────────────────────────

#[test]
fn test_search_params_default() {
    let params = SearchParams::default();
    assert_eq!(params.query, "");
    assert!(matches!(params.mode, SearchMode::Text));
    assert_eq!(params.path_glob, "**/*");
    assert_eq!(params.max_results, 50);
    assert_eq!(params.context_lines, 2);
    assert!(params.known_files.is_empty());
    assert_eq!(params.exclude_glob, ExcludeGlob::default());
    assert_eq!(params.offset, 0);
    assert!(params.kind.is_none());
    assert!(params.group_by_file);
    assert!(matches!(params.filter_mode, FilterMode::CodeOnly));
}

#[test]
fn test_inspect_params_default() {
    let params = InspectParams::default();
    assert_eq!(params.semantic_path, None);
    assert_eq!(params.semantic_paths, None); // new batch field must also default to None
    assert!(!params.include_dependencies);
    assert_eq!(params.max_dependencies, 50);
    assert!(!params.include_imports);
}

#[test]
fn test_trace_params_default() {
    let params = TraceParams::default();
    assert_eq!(params.semantic_path, "");
    assert!(matches!(params.scope, TraceScope::Callers));
    assert_eq!(params.max_depth, 3);
    assert_eq!(params.max_references, 50);
    assert_eq!(params.offset, 0);
}

#[test]
fn test_explore_depth_default() {
    assert_eq!(default_explore_depth(), 3);
}

// ── is_false Helper Tests ───────────────────────────────────────────

#[test]
fn test_is_false_true_value() {
    // is_false returns !b, so is_false(true) == false
    assert!(!is_false(&true));
}

#[test]
fn test_is_false_false_value() {
    // is_false returns !b, so is_false(false) == true
    assert!(is_false(&false));
}

// ── skip_serializing_if Behavior Tests ──────────────────────────────

#[test]
fn test_symbol_overview_response_skip_empty_fields() {
    let resp = SymbolOverviewResponse {
        source: None,
        impact: None,
        references: None,
        files_referenced: 0,
        degraded: false,
        impact_degraded: false,
        references_degraded: false,
        degraded_reason: None,
        actionable_guidance: None,
        lsp_readiness: None,
        warm_start_in_progress: None,
    };

    let json = serde_json::to_value(&resp).expect("serialize SymbolOverviewResponse");
    let obj = json.as_object().expect("should be JSON object");

    // Fields with skip_serializing_if = Option::is_none should be absent
    assert!(
        !obj.contains_key("source"),
        "source should be absent when None"
    );
    assert!(
        !obj.contains_key("impact"),
        "impact should be absent when None"
    );
    assert!(
        !obj.contains_key("references"),
        "references should be absent when None"
    );
    assert!(
        !obj.contains_key("degraded_reason"),
        "degraded_reason should be absent when None"
    );
    assert!(
        !obj.contains_key("actionable_guidance"),
        "actionable_guidance should be absent when None"
    );
    assert!(
        !obj.contains_key("lsp_readiness"),
        "lsp_readiness should be absent when None"
    );
    assert!(
        !obj.contains_key("warm_start_in_progress"),
        "warm_start_in_progress should be absent when None"
    );

    // Fields with skip_serializing_if = Not::not should be absent when false
    assert!(
        !obj.contains_key("impact_degraded"),
        "impact_degraded should be absent when false"
    );
    assert!(
        !obj.contains_key("references_degraded"),
        "references_degraded should be absent when false"
    );

    // Always-present fields should exist
    assert!(obj.contains_key("files_referenced"));
    assert!(obj.contains_key("degraded"));
}

#[test]
fn test_find_all_references_metadata_default_roundtrip() {
    let meta = FindAllReferencesMetadata::default();
    let json = serde_json::to_value(&meta).expect("serialize FindAllReferencesMetadata");
    let obj = json.as_object().expect("should be JSON object");

    // Always-present fields
    assert!(
        obj.contains_key("references"),
        "references should be present (defaults to None/null)"
    );
    assert!(obj.contains_key("files_referenced"));
    assert!(obj.contains_key("degraded"));

    // Optional fields with skip_serializing_if should be absent when default
    assert!(
        !obj.contains_key("truncated"),
        "truncated should be absent when false (default)"
    );
    assert!(
        !obj.contains_key("degraded_reason"),
        "degraded_reason should be absent when None"
    );
    assert!(!obj.contains_key("actionable_guidance"));
    assert!(!obj.contains_key("lsp_readiness"));
    assert!(!obj.contains_key("duration_ms"));
    assert!(!obj.contains_key("resolution_strategy"));
    assert!(!obj.contains_key("hint"));
}

#[test]
fn test_source_symbol_serde_missing_children() {
    let json_str = r#"{"name":"foo","semantic_path":"foo::bar","kind":"function","start_line":10,"end_line":20}"#;
    let symbol: SourceSymbol = serde_json::from_str(json_str).expect("deserialize SourceSymbol");
    assert_eq!(symbol.name, "foo");
    assert_eq!(symbol.semantic_path, "foo::bar");
    assert_eq!(symbol.kind, "function");
    assert_eq!(symbol.start_line, 10);
    assert_eq!(symbol.end_line, 20);
    assert!(symbol.children.is_empty());

    // Serialize it back and make sure children is not serialized when empty
    let serialized = serde_json::to_string(&symbol).expect("serialize SourceSymbol");
    assert!(!serialized.contains("children"));
}

/// Verify that `ExploreParams.visibility` has a valid schema description.
#[test]
fn test_explore_params_visibility_schema_description() {
    let schema = schemars::schema_for!(ExploreParams);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    let description = schema_json["properties"]["visibility"]["description"]
        .as_str()
        .expect("`visibility` property must have a `description` field");

    assert!(
        description.contains("public") || description.contains("all"),
        "`visibility` schema description must document the possible options.\nGot: {description:?}"
    );
}

/// Verify that `ExploreParams.include_extensions` and `exclude_extensions`
/// document raw format examples and mutual exclusion error behavior.
#[test]
fn test_explore_params_extensions_schema_descriptions() {
    let schema = schemars::schema_for!(ExploreParams);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    // include_extensions
    let include_desc = schema_json["properties"]["include_extensions"]["description"]
        .as_str()
        .expect("`include_extensions` must have a description");
    assert!(
        include_desc.contains("\"rs\"") && include_desc.contains("\".rs\""),
        "`include_extensions` description must contrast raw extensions (e.g. \"rs\") with dotted ones.\nGot: {include_desc:?}"
    );
    assert!(
        include_desc.to_lowercase().contains("mutually exclusive") && include_desc.contains("error"),
        "`include_extensions` description must explain mutual exclusion and error behavior.\nGot: {include_desc:?}"
    );

    // exclude_extensions
    let exclude_desc = schema_json["properties"]["exclude_extensions"]["description"]
        .as_str()
        .expect("`exclude_extensions` must have a description");
    assert!(
        exclude_desc.contains("\"rs\"") && exclude_desc.contains("\".rs\""),
        "`exclude_extensions` description must contrast raw extensions (e.g. \"rs\") with dotted ones.\nGot: {exclude_desc:?}"
    );
    assert!(
        exclude_desc.to_lowercase().contains("mutually exclusive") && exclude_desc.contains("error"),
        "`exclude_extensions` description must explain mutual exclusion and error behavior.\nGot: {exclude_desc:?}"
    );
}

/// Verify `SearchParams.path_glob` documents brace expansion.
#[test]
fn test_search_params_path_glob_schema_documents_brace_expansion() {
    let schema = schemars::schema_for!(SearchParams);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    let description = schema_json["properties"]["path_glob"]["description"]
        .as_str()
        .expect("`path_glob` must have a description");

    assert!(
        description.contains("brace expansion"),
        "`path_glob` description must mention brace expansion.\nGot: {description:?}"
    );
    assert!(
        description.contains('{') && description.contains('}'),
        "`path_glob` description must include a brace expansion example.\nGot: {description:?}"
    );
}

/// Verify `ExploreParams.changed_since` documents empty-string behavior.
#[test]
fn test_explore_params_changed_since_schema_documents_empty_string_behavior() {
    let schema = schemars::schema_for!(ExploreParams);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    let description = schema_json["properties"]["changed_since"]["description"]
        .as_str()
        .expect("`changed_since` must have a description");

    assert!(
        description.contains("empty") && description.contains("entire"),
        "`changed_since` description must document empty string / full repository mapping behavior.\nGot: {description:?}"
    );
}

/// Verify `FindCallersCalleesMetadata.test_callers` documents absent vs empty array semantics.
#[test]
fn test_find_callers_callees_test_callers_schema_documents_absent_vs_empty() {
    let schema = schemars::schema_for!(FindCallersCalleesMetadata);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    let description = schema_json["properties"]["test_callers"]["description"]
        .as_str()
        .expect("`test_callers` must have a description");

    assert!(
        description.contains("absent") || description.contains("omitted"),
        "`test_callers` description must mention absent/omitted semantics.\nGot: {description:?}"
    );
    assert!(
        description.contains("[]") || description.contains("empty array"),
        "`test_callers` description must mention `[]`/empty array semantics.\nGot: {description:?}"
    );
}

/// `GetSemanticPathResult.semantic_path` and `.symbol` use `skip_serializing_if`.
/// When `None`, both fields must be **absent** from JSON (not `null`).
#[test]
fn test_get_semantic_path_result_serialization_absent_when_none() {
    let result = GetSemanticPathResult {
        semantic_path: None,
        symbol: None,
        file: "src/lib.rs".to_string(),
        line: 42,
    };
    let json = serde_json::to_value(&result).expect("serialize");
    let obj = json.as_object().expect("object");

    assert!(
        !obj.contains_key("semantic_path"),
        "`semantic_path: None` must be ABSENT from JSON, but it was present: {json}"
    );
    assert!(
        !obj.contains_key("symbol"),
        "`symbol: None` must be ABSENT from JSON, but it was present: {json}"
    );

    // Always-present fields
    assert_eq!(json["file"], "src/lib.rs");
    assert_eq!(json["line"], 42);
}

/// When `Some`, `GetSemanticPathResult` fields must be present.
#[test]
fn test_get_semantic_path_result_serialization_present_when_some() {
    let result = GetSemanticPathResult {
        semantic_path: Some("src/lib.rs::MyStruct.method".to_string()),
        symbol: Some("MyStruct.method".to_string()),
        file: "src/lib.rs".to_string(),
        line: 42,
    };
    let json = serde_json::to_value(&result).expect("serialize");

    assert_eq!(
        json["semantic_path"], "src/lib.rs::MyStruct.method",
        "`semantic_path` must be present when Some"
    );
    assert_eq!(
        json["symbol"], "MyStruct.method",
        "`symbol` must be present when Some"
    );
}

/// `GetSemanticPathResult.semantic_path` doc must say "absent" or "omitted"
/// (not "null") since the field uses `skip_serializing_if`.
#[test]
fn test_get_semantic_path_result_schema_documents_absent_semantics() {
    let schema = schemars::schema_for!(GetSemanticPathResult);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    let sp_desc = schema_json["properties"]["semantic_path"]["description"]
        .as_str()
        .expect("`semantic_path` must have a description");
    assert!(
        sp_desc.contains("absent") || sp_desc.contains("omitted"),
        "`semantic_path` doc must say absent/omitted (not null) since it uses \
         skip_serializing_if.\nGot: {sp_desc:?}"
    );

    let sym_desc = schema_json["properties"]["symbol"]["description"]
        .as_str()
        .expect("`symbol` must have a description");
    assert!(
        sym_desc.contains("absent") || sym_desc.contains("omitted"),
        "`symbol` doc must say absent/omitted (not null) since it uses \
         skip_serializing_if.\nGot: {sym_desc:?}"
    );
}

/// `FileResult.version_hash` doc must describe the short format (7-char hex),
/// not claim it's a full SHA-256 hash.
#[test]
fn test_file_result_version_hash_schema_describes_short_format() {
    let schema = schemars::schema_for!(FileResult);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    let description = schema_json["properties"]["version_hash"]["description"]
        .as_str()
        .expect("`version_hash` must have a description");

    assert!(
        !description.contains("SHA-256 hash"),
        "`FileResult.version_hash` doc must NOT say 'SHA-256 hash' — the actual \
         value is a 7-char truncated hex. Got: {description:?}"
    );
    assert!(
        description.contains("7-char") || description.contains("short") || description.contains("fingerprint"),
        "`FileResult.version_hash` doc must describe the short/fingerprint format. Got: {description:?}"
    );
}

/// `SearchResultGroup.version_hash` doc must describe the short format.
#[test]
fn test_search_result_group_version_hash_schema_describes_short_format() {
    let schema = schemars::schema_for!(SearchResultGroup);
    let schema_json = serde_json::to_value(&schema).expect("schema to JSON");

    let description = schema_json["properties"]["version_hash"]["description"]
        .as_str()
        .expect("`version_hash` must have a description");

    assert!(
        !description.contains("SHA-256 hash"),
        "`SearchResultGroup.version_hash` doc must NOT say 'SHA-256 hash' — the actual \
         value is a 7-char truncated hex. Got: {description:?}"
    );
    assert!(
        description.contains("7-char") || description.contains("short") || description.contains("fingerprint"),
        "`SearchResultGroup.version_hash` doc must describe the short/fingerprint format. Got: {description:?}"
    );
}