leindex 1.9.0

LeIndex MCP and semantic code search engine for AI tools and large codebases
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
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
use super::*;

fn v(s: &str) -> Value {
    serde_json::from_str(s).unwrap()
}

#[test]
fn test_trim_context_keeps_analysis_result() {
    // Regression: `leindex.context` returns an `AnalysisResult`
    // with the exact field set { query, results, context,
    // tokens_used, processing_time_ms }. The trim must keep all
    // five so the LLM can see the expanded PDG context and the
    // timing metadata.
    let input = v(r#"{
            "query": "Context for node main",
            "results": [
                {"rank": 1, "file_path": "src/main.rs", "symbol_name": "main", "language": "rust"}
            ],
            "context": "fn main() { ... }",
            "tokens_used": 120,
            "processing_time_ms": 5
        }"#);
    let t = trim_context(&input);
    assert_eq!(t["query"], "Context for node main");
    assert!(t["results"].is_array());
    assert_eq!(t["context"], "fn main() { ... }");
    assert_eq!(t["tokens_used"], 120);
    assert_eq!(t["processing_time_ms"], 5);
    // The stale-index `_warning` is preserved by `merge_meta`
    // after the trim, not by the trim function itself.
    let merged = trim_llm_payload(
        "leindex.context",
        &v(r#"{
            "query": "q", "results": [], "context": "c",
            "tokens_used": 0, "processing_time_ms": 0,
            "_warning": "stale"
        }"#),
    );
    assert_eq!(merged["_warning"], "stale");
}

#[test]
fn test_trim_symbol_lookup_keeps_actual_fields() {
    // Regression: `leindex.symbol-lookup` returns the shape
    // built by `lookup_single_symbol`: { symbol, type, file,
    // byte_range, complexity, language, callers, callees,
    // impact_radius, source }. Keep the same names — the
    // previous trim used `file_path` / `line` / `symbol_type`
    // / `signature` which do not exist on the raw output and
    // resolved to `null`.
    let input = v(r#"{
            "symbol": "main",
            "type": "function",
            "file": "src/main.rs",
            "byte_range": [0, 100],
            "complexity": 3,
            "language": "rust",
            "callers": [{"name": "test_main"}],
            "callees": [],
            "impact_radius": {"affected_symbols": 5, "affected_files": 2},
            "source": "fn main() { ... }"
        }"#);
    let t = trim_symbol_lookup(&input);
    assert_eq!(t["symbol"], "main");
    assert_eq!(t["type"], "function");
    assert_eq!(t["file"], "src/main.rs");
    assert_eq!(t["byte_range"][0], 0);
    assert_eq!(t["complexity"], 3);
    assert_eq!(t["language"], "rust");
    assert!(t["callers"].is_array());
    assert!(t["callees"].is_array());
    assert_eq!(t["impact_radius"]["affected_symbols"], 5);
    assert_eq!(t["source"], "fn main() { ... }");
    // The pre-fix trim used `file_path` / `signature` — those
    // must NOT appear since the handler does not emit them.
    assert!(t.get("file_path").is_none());
    assert!(t.get("signature").is_none());
}

#[test]
fn test_trim_search_drops_verbose_fields() {
    let input = v(r#"{
            "results": [
                {
                    "rank": 1,
                    "node_id": "abc123",
                    "file_path": "/p/src/foo.rs",
                    "symbol_name": "main",
                    "symbol_type": "function",
                    "language": "rust",
                    "byte_range": [0, 100],
                    "line_number": 42,
                    "complexity": 3,
                    "caller_count": 5,
                    "dependency_count": 2,
                    "context": "// first line",
                    "score": {"overall": 0.85, "neural": 0.9, "text": 0.7, "structural": 0.8}
                }
            ],
            "offset": 0,
            "count": 1,
            "has_more": false,
            "suggestion": "nope"
        }"#);
    let t = trim_search(&input);
    let r = &t["results"][0];
    assert_eq!(r["file_path"], "/p/src/foo.rs");
    assert_eq!(r["symbol"], "main");
    assert_eq!(r["symbol_type"], "function");
    assert_eq!(r["line_number"], 42);
    assert_eq!(r["score"], 0.85);
    assert_eq!(r["snippet"], "// first line");
    // Verbose fields the LLM doesn't need
    assert!(r.get("node_id").is_none() || r["node_id"].is_null());
    assert!(r.get("byte_range").is_none() || r["byte_range"].is_null());
    assert!(r.get("complexity").is_none() || r["complexity"].is_null());
    assert!(r.get("caller_count").is_none() || r["caller_count"].is_null());
    assert!(r.get("language").is_none() || r["language"].is_null());
}

#[test]
fn test_trim_search_falls_back_to_symbol_key() {
    // Regression: the trim path previously only looked at
    // `symbol_name`. If a search result only had `symbol`
    // populated, the trim dropped it to `Null` and
    // `render_search` (which reads `symbol` first) got no
    // name. The trim now walks both keys.
    let input = v(r#"{
            "results": [
                {
                    "rank": 1,
                    "file_path": "/p/src/foo.rs",
                    "symbol": "main",
                    "symbol_type": "function",
                    "context": "fn main() { return 0; }"
                }
            ]
        }"#);
    let t = trim_search(&input);
    let r = &t["results"][0];
    assert_eq!(r["symbol"], "main");
    assert_eq!(r["file_path"], "/p/src/foo.rs");
}

#[test]
fn test_trim_search_prefers_symbol_name_when_both_present() {
    // When both `symbol` and `symbol_name` are populated,
    // `symbol_name` wins because it is the canonical
    // `SearchResult` field and we want trim output to be
    // stable regardless of which key the caller used.
    let input = v(r#"{
            "results": [
                {
                    "file_path": "/p/src/foo.rs",
                    "symbol": "alias",
                    "symbol_name": "canonical",
                    "symbol_type": "function",
                    "context": "x"
                }
            ]
        }"#);
    let t = trim_search(&input);
    let r = &t["results"][0];
    assert_eq!(r["symbol"], "canonical");
}

#[test]
fn test_trim_edit_keeps_structured_diff() {
    let input = v(r#"{
            "preview_token": "tok",
            "diff": {"file_path": "src/foo.rs", "additions": 1, "deletions": 1, "hunks": []},
            "diff_text": "--- a\n+++ b\n@@ ...",
            "affected_symbols": ["main"],
            "affected_files": ["src/foo.rs"],
            "breaking_changes": [],
            "risk_level": "low",
            "change_count": 1,
            "validation": {"x": 1}
        }"#);
    let t = trim_edit(&input);
    assert_eq!(t["preview_token"], "tok");
    assert!(t["diff"].is_object());
    assert_eq!(t["risk_level"], "low");
    assert_eq!(t["change_count"], 1);
    assert_eq!(t["affected_symbols"][0], "main");
    // diff_text is now preserved so the LLM can see the unified diff
    assert!(t.get("diff_text").is_some());
    // validation subtree is dropped (internal detail)
    assert!(t.get("validation").is_none());
}

#[test]
fn test_trim_edit_keeps_apply_result_fields() {
    // Regression: `edit_apply` returns `success`, `changes_applied`,
    // `file_path`, `edit_region`, and a no-op `message`. The trim
    // must preserve these so the LLM gets confirmation context
    // for a successful or no-op apply.
    let input = v(r#"{
            "success": true,
            "changes_applied": 3,
            "file_path": "src/foo.rs",
            "edit_region": {"start": 10, "end": 25},
            "message": "Applied 3 changes",
            "diff": {"file_path": "src/foo.rs", "additions": 3, "deletions": 0, "hunks": []}
        }"#);
    let t = trim_edit(&input);
    assert_eq!(t["success"], true);
    assert_eq!(t["changes_applied"], 3);
    assert_eq!(t["file_path"], "src/foo.rs");
    assert!(t["edit_region"].is_object());
    assert_eq!(t["message"], "Applied 3 changes");
}

#[test]
fn test_trim_read_symbol_caps_callers() {
    let callers: Vec<Value> = (0..20)
        .map(|i| serde_json::json!({"name": format!("c{}", i), "file": "a.rs", "line": i}))
        .collect();
    let input = v(&format!(
        r#"{{
            "symbol": "main",
            "type": "function",
            "file": "src/main.rs",
            "language": "rust",
            "complexity": 5,
            "line_start": 1,
            "line_end": 10,
            "doc_comment": "/// entry",
            "source": "{}",
            "callers": {},
            "callees": []
        }}"#,
        "x".repeat(3000),
        serde_json::to_string(&callers).unwrap()
    ));
    let t = trim_read_symbol(&input);
    // Source is truncated to 2000 chars + 3-char "..." ellipsis.
    // The previous byte-slice version could panic on multi-byte
    // UTF-8 sequences; the new char-boundary truncation cannot.
    let src = t["source"].as_str().unwrap();
    assert!(src.chars().count() <= 2003, "got {}", src.chars().count());
    assert!(
        src.ends_with("..."),
        "missing ellipsis: {:?}",
        src.chars().rev().take(10).collect::<String>()
    );
    assert_eq!(t["source_truncated"], true);
    // Callers capped at 5
    assert_eq!(t["callers"].as_array().unwrap().len(), 5);
    assert_eq!(t["callers_more"], true);
}

#[test]
fn test_trim_grep_symbols_drops_byte_range() {
    let input = v(r#"{
            "results": [
                {
                    "name": "main",
                    "type": "function",
                    "file": "src/main.rs",
                    "byte_range": [0, 200],
                    "complexity": 3,
                    "language": "rust",
                    "caller_count": 10,
                    "callers": [{"name": "a"}, {"name": "b"}, {"name": "c"}, {"name": "d"}, {"name": "e"}, {"name": "f"}, {"name": "g"}],
                    "callees": [{"name": "x"}]
                }
            ],
            "total_matches": 1,
            "shown": 1,
            "offset": 0,
            "mode": "code"
        }"#);
    let t = trim_grep_symbols(&input);
    let r = &t["results"][0];
    assert!(r.get("byte_range").is_none());
    assert!(r.get("language").is_none());
    assert_eq!(r["callers"].as_array().unwrap().len(), 5);
    assert_eq!(r["callee_count"], Value::Null); // not present in input
    // caller_count (kept) reflects blast radius even when callers list is capped
    assert_eq!(r["caller_count"], 10);
}

#[test]
fn test_trim_text_search_preserves_context_windows() {
    let input = v(r#"{
            "count": 1,
            "total_matched": 1,
            "has_more": false,
            "offset": 0,
            "results": [
                {
                    "file": "src/foo.rs",
                    "line": 42,
                    "content": "let x = 1;",
                    "before": ["fn main() {", "  let y = 2;"],
                    "after": ["  let z = 3;", "}"],
                    "in_symbol": "main",
                    "symbol_type": "function"
                }
            ]
        }"#);
    let t = trim_text_search(&input);
    let r = &t["results"][0];
    // before/after context windows are now preserved so the LLM
    // can understand match context without a follow-up read_file.
    assert!(r.get("before").is_some());
    assert!(r.get("after").is_some());
    assert_eq!(r["file"], "src/foo.rs");
    assert_eq!(r["line"], 42);
}

#[test]
fn test_trim_deep_analyze_caps_results() {
    let results: Vec<Value> = (0..15)
        .map(|i| {
            serde_json::json!({
                "rank": i + 1,
                "node_id": format!("n{}", i),
                "file_path": format!("/p/src/file{}.rs", i),
                "symbol_name": format!("sym{}", i),
                "symbol_type": "function",
                "signature": "fn x()",
                "complexity": i as u32,
                "context": "ctx",
                "score": {"overall": 0.5}
            })
        })
        .collect();
    let input = v(&format!(
        r#"{{
            "query": "what is X",
            "tokens_used": 1500,
            "processing_time_ms": 250,
            "context": "expanded prose here",
            "results": {}
        }}"#,
        serde_json::to_string(&results).unwrap()
    ));
    let t = trim_deep_analyze(&input);
    // Capped at 10
    assert_eq!(t["results"].as_array().unwrap().len(), 10);
    assert_eq!(t["results_more"], 5);
    // Per-result verbose fields dropped
    let r0 = &t["results"][0];
    assert!(r0.get("node_id").is_none());
    assert!(r0.get("complexity").is_none());
}

#[test]
fn test_trim_write_drops_byte_range() {
    let input = v(r#"{
            "success": true,
            "file_path": "src/new.rs",
            "language": "rust",
            "symbols": [
                {"name": "main", "type": "function", "byte_range": [0, 50]},
                {"name": "helper", "type": "function", "byte_range": [50, 100]}
            ]
        }"#);
    let t = trim_write(&input);
    assert_eq!(t["success"], true);
    let syms = t["symbols"].as_array().unwrap();
    for s in syms {
        assert!(s.get("byte_range").is_none());
    }
}

#[test]
fn test_trim_index_collapses_parse_failures() {
    let input = v(r#"{
            "total_files": 100,
            "files_parsed": 95,
            "successful_parses": 95,
            "failed_parses": 5,
            "total_signatures": 200,
            "pdg_nodes": 1000,
            "pdg_edges": 2000,
            "indexed_nodes": 1000,
            "indexing_time_ms": 1234,
            "external_deps_in_lockfile": 50,
            "external_deps_resolved": 45,
            "external_deps_unresolved": 5
        }"#);
    let t = trim_index(&input);
    assert_eq!(t["parse_failures"], 5);
    assert_eq!(t["total_files"], 100);
    assert!(t.get("successful_parses").is_none());
    assert_eq!(t["external_deps_unresolved"], 5);
    assert!(t.get("external_deps_in_lockfile").is_none());
    assert!(t.get("external_deps_resolved").is_none());
}

#[test]
fn test_trim_llm_payload_dispatches() {
    // Test the public entry point picks the right trim function.
    let search_data = v(r#"{"results": [{"file_path": "/p.rs", "symbol_name": "f"}]}"#);
    let out = trim_llm_payload("leindex.search", &search_data);
    assert!(out.get("results").is_some());
    assert!(out.get("count").is_some());

    // Edit payload keeps the structured diff and diff_text
    let edit_data = v(
        r#"{"preview_token": "x", "diff": {"file_path": "a.rs", "hunks": []}, "diff_text": "unified", "validation": {}}"#,
    );
    let out = trim_llm_payload("leindex.edit_preview", &edit_data);
    assert!(out.get("diff").is_some());
    assert!(out.get("diff_text").is_some());
    assert!(out.get("validation").is_none());

    // Unknown tool passes through unchanged
    let raw = v(r#"{"any": "value", "x": 1}"#);
    let out = trim_llm_payload("leindex.something_new", &raw);
    assert_eq!(out, raw);
}

#[test]
fn test_trim_llm_payload_preserves_meta_warning() {
    // Regression: a stale index attaches `_warning` via
    // `wrap_with_meta` so the LLM knows to reindex. The trim
    // pipeline must not silently drop that field — otherwise the
    // model serves stale results thinking they are fresh.
    let stale_search = v(r#"{
            "count": 1,
            "results": [{"file_path": "src/foo.rs", "symbol": "main"}],
            "_warning": "index is stale (last update: 60s ago) — call leindex.index to refresh"
        }"#);
    let out = trim_llm_payload("leindex.search", &stale_search);
    assert_eq!(out["count"], 1);
    assert!(out.get("results").is_some());
    assert_eq!(
        out["_warning"],
        "index is stale (last update: 60s ago) — call leindex.index to refresh"
    );

    // _warning also preserved for tools that build a fresh object
    // (trim_diagnostics, trim_edit, etc.)
    let stale_edit = v(r#"{
            "preview_token": "tok",
            "diff": {"file_path": "a.rs", "hunks": []},
            "_warning": "stale"
        }"#);
    let out = trim_llm_payload("leindex.edit_apply", &stale_edit);
    assert_eq!(out["_warning"], "stale");

    // Non-`_`-prefixed fields are NOT merged (trim is still the
    // primary filter — `_` is the explicit out-of-band prefix).
    let extra = v(r#"{
            "results": [{"file_path": "src/foo.rs"}],
            "ignored_warning": "should not appear"
        }"#);
    let out = trim_llm_payload("leindex.search", &extra);
    assert!(out.get("ignored_warning").is_none());
}

#[test]
fn test_trim_symbol_lookup_preserves_batch_results() {
    // Regression: when `leindex.symbol-lookup` is called in
    // batch mode (with the `symbols` array containing more
    // than one entry), the handler returns
    // `{batch: true, count, results: [...]}`. The trim
    // must detect the batch shape, recurse into each entry,
    // and preserve the requested results — otherwise the
    // LLM-visible payload becomes an empty object.
    let data = v(r#"{
            "batch": true,
            "count": 2,
            "results": [
                {
                    "symbol": "alpha",
                    "type": "function",
                    "file": "src/a.rs",
                    "byte_range": [10, 50],
                    "complexity": 3,
                    "language": "rust",
                    "callers": [],
                    "callees": [],
                    "impact_radius": {"affected_symbols": 0, "affected_files": 0}
                },
                {
                    "symbol": "beta",
                    "type": "function",
                    "file": "src/b.rs",
                    "byte_range": [60, 90],
                    "complexity": 1,
                    "language": "rust",
                    "callers": [],
                    "callees": [],
                    "impact_radius": {"affected_symbols": 0, "affected_files": 0}
                }
            ]
        }"#);
    let out = trim_llm_payload("leindex.symbol-lookup", &data);
    assert_eq!(out["batch"], true);
    assert_eq!(out["count"], 2);
    let results = out["results"].as_array().expect("results must be an array");
    assert_eq!(results.len(), 2);
    assert_eq!(results[0]["symbol"], "alpha");
    assert_eq!(results[0]["file"], "src/a.rs");
    assert_eq!(results[0]["type"], "function");
    assert_eq!(results[0]["byte_range"][0], 10);
    assert_eq!(results[1]["symbol"], "beta");
    assert_eq!(results[1]["file"], "src/b.rs");
}

#[test]
fn test_trim_symbol_lookup_batch_with_lookup_error_entry() {
    // Regression: a batch entry that hit a lookup error
    // comes back as `{"symbol": "...", "error": "..."}`
    // without the per-symbol fields. The per-entry
    // recursion must not crash on the missing fields and
    // must still copy the error entry through unchanged.
    let data = v(r#"{
            "batch": true,
            "count": 2,
            "results": [
                {"symbol": "ok", "type": "function", "file": "src/ok.rs", "byte_range": [0, 1], "complexity": 1, "language": "rust", "callers": [], "callees": [], "impact_radius": {}},
                {"symbol": "missing", "error": "Symbol not found"}
            ]
        }"#);
    let out = trim_llm_payload("leindex.symbol-lookup", &data);
    let results = out["results"].as_array().unwrap();
    assert_eq!(results.len(), 2);
    assert_eq!(results[0]["symbol"], "ok");
    assert_eq!(results[0]["file"], "src/ok.rs");
    // The error entry has no `file` / `type` / etc. — those
    // fields simply don't appear in the trimmed copy. The
    // `error` field is not on the per-symbol whitelist but
    // the entry still survives as a result the LLM can
    // surface to the user.
    assert_eq!(results[1]["symbol"], "missing");
}

#[test]
fn test_trim_read_symbol_includes_dependencies_when_present() {
    // Regression: when the caller passes
    // `include_dependencies=true`, the handler adds a
    // `dependencies` array to the payload. The trim must
    // preserve it so the caller-requested extra context
    // is not silently dropped.
    let data = v(r#"{
            "symbol": "compute",
            "type": "function",
            "file": "src/lib.rs",
            "language": "rust",
            "complexity": 4,
            "line_start": 10,
            "line_end": 25,
            "doc_comment": "/// Compute result",
            "source": "fn compute() {}",
            "callers": [],
            "callees": [],
            "dependencies": ["fn helper_a()", "fn helper_b()"]
        }"#);
    let out = trim_llm_payload("leindex.read-symbol", &data);
    assert_eq!(out["symbol"], "compute");
    let deps = out["dependencies"]
        .as_array()
        .expect("dependencies must be an array");
    assert_eq!(deps.len(), 2);
    assert_eq!(deps[0], "fn helper_a()");
    assert_eq!(deps[1], "fn helper_b()");
}

#[test]
fn test_trim_search_falls_through_explicit_null_context() {
    // Regression: when a search result row carries an
    // explicit `context: null` (e.g. the handler skipped
    // snippet expansion for an unindexed file), the
    // trim fallback chain must NOT stop at the null —
    // it has to fall through to `content` and then to
    // `signature`. The previous `r.get("context").or_else(...)`
    // chain short-circuited on `Some(&Value::Null)`, so
    // the snippet was always `null` even when a
    // non-null `content` was available.
    let data = v(r#"{
            "query": "compute",
            "results": [
                {
                    "file_path": "src/lib.rs",
                    "symbol_name": "compute",
                    "symbol_type": "function",
                    "score": 0.9,
                    "context": null,
                    "content": "fn compute() -> i32 { 42 }",
                    "signature": "fn compute() -> i32"
                }
            ]
        }"#);
    let out = trim_llm_payload("leindex.search", &data);
    let results = out["results"].as_array().unwrap();
    let snippet = &results[0]["snippet"];
    // The `content` field carries the source body — the
    // trim path's snippet transform takes the first line
    // and truncates to 240 chars. Assert the body text is
    // present (not the literal `null`).
    let s = snippet
        .as_str()
        .expect("snippet must be a string, not null");
    assert!(
        s.contains("fn compute()"),
        "snippet should contain content body: {}",
        s
    );
}

#[test]
fn test_trim_search_falls_through_explicit_null_symbol_name() {
    // Regression: same null-blocking pattern for the
    // `symbol` / `symbol_name` pair — an explicit
    // `null` in `symbol_name` must not block the
    // fallback to `symbol`.
    let data = v(r#"{
            "query": "x",
            "results": [
                {
                    "file_path": "src/lib.rs",
                    "symbol_name": null,
                    "symbol": "fallback_name",
                    "symbol_type": "function",
                    "score": 0.5,
                    "content": "fn fallback_name() {}"
                }
            ]
        }"#);
    let out = trim_llm_payload("leindex.search", &data);
    let results = out["results"].as_array().unwrap();
    assert_eq!(
        results[0]["symbol"], "fallback_name",
        "explicit null in symbol_name must fall through to symbol"
    );
}

/// Regression for P2 #3342365969: the search payload is
/// paginated. `SearchHandler` returns `{results, count, offset,
/// has_more, [suggestion]}` and the renderer/trim path was
/// dropping `offset`, `has_more`, and `suggestion`. After the
/// fix, all three must round-trip.
#[test]
fn test_trim_search_preserves_pagination_fields() {
    let data = v(r#"{
            "query": "find me",
            "results": [
                {"file": "a.rs", "byte_range": [0, 10], "content": "x"}
            ],
            "count": 1,
            "offset": 5,
            "has_more": true,
            "suggestion": "try a broader query"
        }"#);
    let out = trim_llm_payload("leindex.search", &data);
    assert_eq!(out["count"], 1, "count must round-trip");
    assert_eq!(out["offset"], 5, "offset must round-trip");
    assert_eq!(out["has_more"], true, "has_more must round-trip");
    assert_eq!(
        out["suggestion"], "try a broader query",
        "suggestion must round-trip"
    );
    assert_eq!(out["results"].as_array().unwrap().len(), 1);
}

/// `has_more=false` and `suggestion` absent on success is also
/// the typical shape, not just the zero-results case. Verify
/// both fields are accepted.
#[test]
fn test_trim_search_preserves_pagination_fields_no_more_no_suggestion() {
    let data = v(r#"{
            "query": "find me",
            "results": [{"file": "a.rs", "byte_range": [0, 10], "content": "x"}],
            "count": 1,
            "offset": 0,
            "has_more": false
        }"#);
    let out = trim_llm_payload("leindex.search", &data);
    assert_eq!(out["count"], 1);
    assert_eq!(out["offset"], 0);
    assert_eq!(out["has_more"], false);
    assert!(
        out.get("suggestion").is_none(),
        "no suggestion key when absent"
    );
}

/// Regression for HIGH round 12: `trim_search` used to clone the
/// entire `results` array (`as_array().cloned()`), then clone
/// each entry's `context` / `content` strings during the
/// per-entry mapping. The intermediate allocations were
/// unnecessary because only a few whitelisted fields are kept
/// per entry. After the fix, the function borrows the source
/// array and clones only the whitelisted fields.
///
/// The contract we test: the output shape is unchanged. Each
/// entry's `snippet` is taken from `context` / `content` /
/// `signature` (truncated to first line, ≤ 240 chars), `score`
/// collapses to `score.overall` or `score`, `symbol` falls
/// through `symbol_name` → `symbol`, and `file_path` /
/// `symbol_type` round-trip.
#[test]
fn test_trim_search_borrows_input_array() {
    // The "context" string is intentionally long to make the
    // "would have been cloned" cost observable in the
    // pre-fix code path. The post-fix code only borrows it.
    let big_context = "x".repeat(50_000);
    let data = v(&format!(
        r#"{{
                "query": "find me",
                "results": [
                    {{
                        "file_path": "src/a.rs",
                        "symbol_name": "alpha",
                        "symbol_type": "function",
                        "context": "{}",
                        "score": {{"overall": 0.91, "tfidf": 0.5, "neural": 0.95}}
                    }},
                    {{
                        "file_path": "src/b.rs",
                        "symbol": "beta",
                        "symbol_type": "struct",
                        "content": "struct Beta {{ x: u32 }}",
                        "score": 0.42
                    }}
                ],
                "count": 2,
                "offset": 0,
                "has_more": false
            }}"#,
        big_context
    ));
    let out = trim_llm_payload("leindex.search", &data);
    let results = out["results"].as_array().unwrap();
    assert_eq!(results.len(), 2);

    // First entry: context was 50_000 chars, snippet must be
    // the first line truncated to 240 chars + "..." ellipsis
    // (243 chars total — `truncate_chars(s, 240)` preserves
    // 240 input chars and appends "...").
    let snippet0 = results[0]["snippet"].as_str().unwrap();
    assert_eq!(
        snippet0.len(),
        243,
        "snippet must be 240 chars + '...' ellipsis"
    );
    assert!(snippet0.ends_with("..."));
    assert!(snippet0[..240].chars().all(|c| c == 'x'));
    assert_eq!(results[0]["symbol"], "alpha");
    assert_eq!(results[0]["file_path"], "src/a.rs");
    assert_eq!(results[0]["symbol_type"], "function");
    // score collapsed to `overall`.
    assert!((results[0]["score"].as_f64().unwrap() - 0.91).abs() < 1e-9);

    // Second entry: content used (no context), symbol_name
    // absent so falls through to `symbol`.
    let snippet1 = results[1]["snippet"].as_str().unwrap();
    assert_eq!(snippet1, "struct Beta { x: u32 }");
    assert_eq!(results[1]["symbol"], "beta");
    // score is a plain number, not a struct.
    assert!((results[1]["score"].as_f64().unwrap() - 0.42).abs() < 1e-9);
}

/// Regression for HIGH round 12: `trim_read_symbol` used to
/// clone the entire `callers` and `callees` arrays just to
/// check `len() > 5`. The post-fix code computes the length
/// without cloning via `as_array().map(|a| a.len())`.
///
/// The contract: when `callers` / `callees` have more than 5
/// entries, `*_more` is true; otherwise false. The first 5
/// entries are still passed through via `take_n`.
#[test]
fn test_trim_read_symbol_callers_more_flag_no_clone() {
    // 7 callers — `callers_more` must be true, first 5 must
    // be passed through.
    let mut callers = Vec::new();
    for i in 0..7 {
        callers.push(serde_json::json!({"name": format!("c{}", i), "file": "x.rs", "type": "fn"}));
    }
    let data = v(&format!(
        r#"{{
                "symbol": "main",
                "type": "function",
                "file": "src/main.rs",
                "byte_range": [0, 100],
                "language": "rust",
                "callers": {},
                "callees": []
            }}"#,
        serde_json::to_string(&callers).unwrap()
    ));
    let out = trim_llm_payload("leindex.read-symbol", &data);
    assert_eq!(
        out["callers"].as_array().unwrap().len(),
        5,
        "first 5 callers passed through"
    );
    assert_eq!(
        out["callers_more"], true,
        "more than 5 callers => callers_more true"
    );

    // 3 callers — `callers_more` must be false, all 3 pass through.
    let mut small_callers = Vec::new();
    for i in 0..3 {
        small_callers.push(serde_json::json!({"name": format!("c{}", i)}));
    }
    let data = v(&format!(
        r#"{{
                "symbol": "main",
                "callers": {},
                "callees": []
            }}"#,
        serde_json::to_string(&small_callers).unwrap()
    ));
    let out = trim_llm_payload("leindex.read-symbol", &data);
    assert_eq!(out["callers"].as_array().unwrap().len(), 3);
    assert_eq!(
        out["callers_more"], false,
        "3 callers => callers_more false"
    );
}

/// Regression for HIGH round 12: `trim_deep_analyze` used to
/// clone the whole `results` array, then clone the first 10
/// entries into a second vector, then clone each whitelisted
/// field on each entry. The post-fix code borrows the source
/// array, takes 10, and clones only the whitelisted fields.
///
/// The contract: with N>10 results, the trimmed output has
/// 10 entries, `results_more` is N-10, and the whitelisted
/// fields are present.
#[test]
fn test_trim_deep_analyze_caps_at_10_without_clone() {
    // 15 results.
    let mut results = Vec::new();
    for i in 0..15 {
        results.push(serde_json::json!({
            "rank": i,
            "file_path": format!("src/f{}.rs", i),
            "symbol_name": format!("sym{}", i),
            "symbol_type": "function",
            "signature": format!("fn sym{}()", i),
            // Verbose fields the trim should drop.
            "byte_range": [0, 1000],
            "language": "rust",
            "complexity": 5,
        }));
    }
    let data = v(&format!(
        r#"{{
                "query": "x",
                "tokens_used": 100,
                "processing_time_ms": 5,
                "context": "some context",
                "results": {}
            }}"#,
        serde_json::to_string(&results).unwrap()
    ));
    let out = trim_llm_payload("leindex.deep-analyze", &data);
    assert_eq!(
        out["results"].as_array().unwrap().len(),
        10,
        "cap at 10 entries"
    );
    assert_eq!(out["results_more"], 5, "results_more = 15 - 10 = 5");
    // First entry: whitelisted fields present, dropped fields absent.
    let first = &out["results"].as_array().unwrap()[0];
    assert_eq!(first["rank"], 0);
    assert_eq!(first["file_path"], "src/f0.rs");
    assert_eq!(first["symbol_name"], "sym0");
    assert_eq!(first["symbol_type"], "function");
    assert_eq!(first["signature"], "fn sym0()");
    assert!(
        first.get("byte_range").is_none(),
        "byte_range must be dropped"
    );
    assert!(first.get("language").is_none(), "language must be dropped");
    assert!(
        first.get("complexity").is_none(),
        "complexity must be dropped"
    );

    // 5 results: no cap, all pass through, results_more = 0.
    let mut small = Vec::new();
    for i in 0..5 {
        small.push(serde_json::json!({"rank": i, "file_path": "a.rs"}));
    }
    let data = v(&format!(
        r#"{{"query": "x", "results": {}}}"#,
        serde_json::to_string(&small).unwrap()
    ));
    let out = trim_llm_payload("leindex.deep-analyze", &data);
    assert_eq!(out["results"].as_array().unwrap().len(), 5);
    assert_eq!(out["results_more"], 0);
}

/// Regression for MED round 14 (gemini `3344534855`):
/// `take_n` used to do `v.as_array().cloned().unwrap_or_default()`,
/// which deep-cloned the entire source array before taking `n`.
/// The post-fix code borrows the source and only clones the
/// first `n` elements. The contract: with N=100 source items
/// and n=3, the output is a 3-element array of the first three
/// source items, preserving order.
#[test]
fn test_take_n_borrows_source() {
    let mut arr = Vec::new();
    for i in 0..100 {
        arr.push(serde_json::json!({"rank": i, "payload": "x".repeat(64)}));
    }
    let v = Value::Array(arr);
    let out = take_n(&v, 3);
    let out = out.as_array().unwrap();
    assert_eq!(out.len(), 3);
    assert_eq!(out[0]["rank"], 0);
    assert_eq!(out[1]["rank"], 1);
    assert_eq!(out[2]["rank"], 2);
}

/// Regression for MED round 14 (gemini `3344534868`):
/// `thin_symbol_map` used to clone the whole source array, then
/// clone the first 5 callers and first 5 callees for each entry
/// (cloning the unused tail as well). The post-fix code borrows
/// the source array and clones only the 5-item windows of
/// callers/callees. The contract: with callers/callees arrays
/// of length 20 each, the output caps each at 5, drops
/// `complexity`, and preserves the entry-level fields.
#[test]
fn test_thin_symbol_map_caps_callers_callees_at_5() {
    let mut big_callers = Vec::new();
    let mut big_callees = Vec::new();
    for i in 0..20 {
        big_callers.push(serde_json::json!({"name": format!("c{}", i)}));
        big_callees.push(serde_json::json!({"name": format!("e{}", i)}));
    }
    let sm = serde_json::json!([
        {
            "name": "foo",
            "complexity": 42,
            "callers": big_callers,
            "callees": big_callees,
        },
        {
            "name": "bar",
            "complexity": 7,
            "callers": [{"name": "only"}],
            "callees": [],
        }
    ]);
    let out = thin_symbol_map(&sm);
    let arr = out.as_array().unwrap();
    assert_eq!(arr.len(), 2);
    let foo = &arr[0];
    assert!(
        foo.get("complexity").is_none(),
        "complexity must be dropped"
    );
    assert_eq!(foo["name"], "foo");
    assert_eq!(
        foo["callers"].as_array().unwrap().len(),
        5,
        "callers must cap at 5 even when source has 20"
    );
    assert_eq!(foo["callers"][0]["name"], "c0");
    assert_eq!(foo["callers"][4]["name"], "c4");
    assert_eq!(
        foo["callees"].as_array().unwrap().len(),
        5,
        "callees must cap at 5 even when source has 20"
    );
    let bar = &arr[1];
    assert_eq!(bar["callers"].as_array().unwrap().len(), 1);
    assert_eq!(bar["callees"].as_array().unwrap().len(), 0);
}

/// Regression for MED round 14 (gemini `3344534871`):
/// `trim_rename_symbol` used to clone the whole `diffs` array,
/// then `take(25).map(|d| ...)` cloned only the first 25
/// entries' file/diff fields. The post-fix code borrows the
/// source array, takes 25, and clones only the file/diff
/// fields of those 25. The contract: with N=50 source diffs,
/// the output has 25 entries, `diffs_more` is 25, and
/// `diffs_total` (if present) reflects the source length.
#[test]
fn test_trim_rename_symbol_caps_diffs_at_25() {
    let mut diffs = Vec::new();
    for i in 0..50 {
        diffs.push(serde_json::json!({
            "file": format!("src/f{}.rs", i),
            "diff": format!("--- a/src/f{}.rs\n+++ b/src/f{}.rs\n@@ -1,1 +1,1 @@\n-x\n+y", i, i),
            "diff_text": format!("long echo of diff {}", i),
        }));
    }
    let data = serde_json::json!({
        "old_name": "foo",
        "new_name": "bar",
        "diffs": diffs,
    });
    let out = trim_rename_symbol(&data);
    let shown = out["diffs"].as_array().unwrap();
    assert_eq!(shown.len(), 25, "must cap at 25 when source has 50");
    assert_eq!(out["diffs_more"], 25, "diffs_more = total - 25");
    assert_eq!(out["old_name"], "foo");
    assert_eq!(out["new_name"], "bar");
    // First shown is the first source; the long `diff_text` echo
    // is dropped (we keep only `file` and `diff`).
    assert!(shown[0].get("diff_text").is_none());
    assert_eq!(shown[0]["file"], "src/f0.rs");
}

/// Regression for MED round 20: `trim_write` previously
/// cloned the entire `symbols` array via
/// `.cloned().unwrap_or_default()` and then mapped over
/// the clone. The clone was a deep copy (every
/// `serde_json::Map` node, every string, every number)
/// for elements that mostly get reduced to a
/// two-field `{name, type}` object. The fix borrows the
/// input array and only allocates the small output
/// objects. This test locks the output contract: the
/// trimmed `symbols` array has the same whitelisted
/// fields and the same shape as before, so a future
/// refactor that re-introduces the deep clone (or that
/// accidentally changes the whitelist) is caught.
#[test]
fn test_trim_write_borrows_symbols_array() {
    // Each symbol carries a `byte_range` (the field
    // we're dropping) plus an unrelated `metadata`
    // object to make the "deep clone would have copied
    // all of this" cost visible.
    let input = v(r#"{
            "success": true,
            "file_path": "src/new.rs",
            "language": "rust",
            "symbols": [
                {
                    "name": "main",
                    "type": "function",
                    "byte_range": [0, 50],
                    "metadata": {"scope": "crate", "visibility": "pub", "attrs": ["inline"]}
                },
                {
                    "name": "helper",
                    "type": "function",
                    "byte_range": [50, 100],
                    "metadata": {"scope": "module", "visibility": "pub(crate)", "attrs": []}
                }
            ]
        }"#);
    let t = trim_write(&input);
    // Top-level fields preserved.
    assert_eq!(t["success"], true);
    assert_eq!(t["file_path"], "src/new.rs");
    assert_eq!(t["language"], "rust");
    // Per-symbol: only `name` and `type` are kept.
    let syms = t["symbols"].as_array().unwrap();
    assert_eq!(syms.len(), 2);
    for s in syms {
        assert!(s.get("byte_range").is_none());
        assert!(s.get("metadata").is_none());
        // The whitelist keys exist and are populated.
        assert!(s.get("name").is_some());
        assert!(s.get("type").is_some());
    }
    assert_eq!(syms[0]["name"], "main");
    assert_eq!(syms[0]["type"], "function");
    assert_eq!(syms[1]["name"], "helper");
    assert_eq!(syms[1]["type"], "function");
}

/// Regression for MED round 20: `trim_impact` /
/// `trim_side` previously cloned the entire impact array
/// upfront via `v.as_array().cloned().unwrap_or_default()`.
/// Each cloned element was a `serde_json::Map` with
/// dozens of fields (file, line, byte_range, scope,
/// call_graph, ...), and most of the data was discarded
/// in the subsequent mapping. The fix borrows the input
/// array and only allocates the small output objects.
/// This test locks the output contract: the per-entry
/// shape is `{name, file, line}` with no other fields,
/// and the top-level `symbol` / `risk_level` /
/// `forward_impact` / `backward_impact` fields are
/// preserved.
#[test]
fn test_trim_impact_borrows_impact_array() {
    let input = v(r#"{
            "symbol": "Foo::bar",
            "file": "src/foo.rs",
            "change_type": "modify",
            "risk_level": "medium",
            "direct_callers": ["caller_a", "caller_b"],
            "transitive_affected_symbols": ["callee_x", "callee_y", "callee_z"],
            "transitive_affected_files": 2,
            "transitive_callers": 5,
            "summary": "Changing 'Foo::bar' directly affects 3 symbols in 2 files (risk: medium)"
        }"#);
    let t = trim_impact(&input);
    // Top-level: all handler fields are preserved.
    assert_eq!(t["symbol"], "Foo::bar");
    assert_eq!(t["file"], "src/foo.rs");
    assert_eq!(t["change_type"], "modify");
    assert_eq!(t["risk_level"], "medium");
    assert!(t.get("direct_callers").is_some());
    assert!(t.get("transitive_affected_symbols").is_some());
    assert!(t.get("transitive_affected_files").is_some());
    assert!(t.get("transitive_callers").is_some());
    assert!(t.get("summary").is_some());
    // direct_callers array preserved
    let callers = t["direct_callers"].as_array().unwrap();
    assert_eq!(callers.len(), 2);
    assert_eq!(callers[0], "caller_a");
    // transitive_affected_symbols array preserved
    let affected = t["transitive_affected_symbols"].as_array().unwrap();
    assert_eq!(affected.len(), 3);
    assert_eq!(affected[0], "callee_x");
    // summary string preserved
    assert!(t["summary"].as_str().unwrap().contains("3 symbols"));
}

#[test]
fn test_trim_git_status_preserves_pdg_enrichment() {
    // Regression: trim_git_status must preserve pdg_enrichment
    // and impact_summary so they survive trimming and reach the
    // MCP response (VAL-TRANSPORT-008).
    let input = v(r#"{
            "is_git_repo": true,
            "branch": "main",
            "summary": {"modified": 1, "staged": 0, "untracked": 0},
            "modified_files": ["src/main.rs"],
            "staged_files": [],
            "untracked_files": [],
            "changed_symbols": [
                {"file": "src/main.rs", "status": "modified", "symbols": [{"name": "main"}]}
            ],
            "pdg_enrichment": {"available": true},
            "impact_summary": {
                "total_affected_symbols": 3,
                "affected_files": ["src/main.rs"],
                "pdg_enriched": true
            },
            "diff": "some diff"
        }"#);
    let t = trim_git_status(&input);
    // Core fields preserved
    assert_eq!(t["branch"], "main");
    assert!(t["modified_files"].is_array());
    assert!(t["changed_symbols"].is_array());
    // pdg_enrichment and impact_summary must survive trimming
    assert!(t.get("pdg_enrichment").is_some());
    assert_eq!(t["pdg_enrichment"]["available"], true);
    assert!(t.get("impact_summary").is_some());
    assert_eq!(t["impact_summary"]["total_affected_symbols"], 3);
}

#[test]
fn test_trim_git_status_pdg_unavailable() {
    // When PDG is unavailable, pdg_enrichment should still be
    // present with available=false.
    let input = v(r#"{
            "branch": "main",
            "summary": {"modified": 0, "staged": 0, "untracked": 0},
            "modified_files": [],
            "staged_files": [],
            "untracked_files": [],
            "changed_symbols": [],
            "pdg_enrichment": {
                "available": false,
                "reason": "PDG load failed",
                "error": "database error"
            },
            "impact_summary": {
                "total_affected_symbols": 0,
                "affected_files": [],
                "pdg_enriched": false
            }
        }"#);
    let t = trim_git_status(&input);
    assert_eq!(t["pdg_enrichment"]["available"], false);
    assert_eq!(t["pdg_enrichment"]["reason"], "PDG load failed");
    assert_eq!(t["pdg_enrichment"]["error"], "database error");
    assert_eq!(t["impact_summary"]["pdg_enriched"], false);
}