leindex 2.1.1

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
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
//! Per-tool CLI render functions and the central dispatcher.
//!
//! Each `render_*` function reads a JSON `Value` (the same data the
//! LLM sees) and produces a human-readable, colored string for the
//! CLI. They use shared helpers (`header`, `field`,
//! `suffix`) defined at the top of this file so the visual style stays
//! consistent across tools.
//!
//! `render_tool_output` is the single entry point used by
//! `leindex tools run` and any other CLI surface; it dispatches on the
//! normalized tool name to the right `render_*` function.

use serde_json::Value;

use super::diff::{render_default, render_diff_value};
use super::{
    BOLD, DIM, LIGHT_BLUE, LIGHT_CYAN, LIGHT_GREEN, LIGHT_GREY, LIGHT_MAGENTA, LIGHT_RED,
    LIGHT_YELLOW, RESET, WHITE, normalize_tool_name, truncate_chars,
};
mod git_status;
use git_status::render_git_status;

mod symbol_phase;
use symbol_phase::*;

mod map_impact;
use map_impact::*;

#[cfg(test)]
#[path = "tests.rs"]
mod tests;

// =============================================================================
// Shared formatters — small helpers used by multiple render_* fns
// =============================================================================

pub(super) fn header(title: &str, color: bool) -> String {
    if color {
        format!("{}── {} ──{}", LIGHT_CYAN, title, RESET)
    } else {
        format!("── {} ──", title)
    }
}

fn field(name: &str, value: &str, color: bool) -> String {
    if color {
        format!(
            "  {}{}:{} {}{}{}\n",
            BOLD, name, RESET, LIGHT_CYAN, value, RESET
        )
    } else {
        format!("  {}: {}\n", name, value)
    }
}

fn suffix(symbol_count: u64, color: &str, reset: &str) -> String {
    if symbol_count == 0 {
        String::new()
    } else {
        format!("  {}[{} symbols]{}", color, symbol_count, reset)
    }
}

fn line_for(data: &Value) -> u64 {
    // Top-level `line` is the legacy flat shape (a real source line
    // number). The canonical `AnalysisResult` only carries the
    // anchor node's byte range in `results[0].byte_range` — and
    // `byte_range[0]` is a *byte offset* in the source file, not a
    // line number. Showing a byte offset as a line number is
    // misleading (e.g. an anchor at byte 15342 in a long file would
    // render as "Line: 15342" for a symbol that is actually on a
    // much earlier source line). The renderer does not have file
    // contents available to convert bytes to lines, so for the
    // canonical shape we return 0 — the caller interprets 0 as
    // "no real line available, start the gutter at 1" and omits
    // the `Line` field. See the
    // `byte_range_to_line_range` helper in `helpers.rs` for the
    // proper conversion when file contents are available.
    if let Some(n) = data.get("line").and_then(|v| v.as_u64()) {
        return n;
    }
    0
}

/// Strip ANSI CSI escape sequences from a string. Used by tests
/// (and only by tests) to assert on the visible text of the
/// rendered output. Handles only the SGR (colour) subset that
/// this module emits: `\x1b[<n>m`.
#[cfg(test)]
fn strip_ansi(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut iter = s.chars().peekable();
    while let Some(c) = iter.next() {
        if c == '\x1b' {
            // Skip `ESC[`
            if iter.peek() == Some(&'[') {
                iter.next();
                // Skip parameters (digits and semicolons) and the
                // terminating letter.
                for c2 in iter.by_ref() {
                    if c2.is_ascii_alphabetic() {
                        break;
                    }
                }
                continue;
            }
        }
        out.push(c);
    }
    out
}

fn extract_array(data: &Value, keys: &[&str]) -> Vec<Value> {
    if let Some(arr) = data.as_array() {
        return arr.clone();
    }
    for k in keys {
        if let Some(arr) = data.get(*k).and_then(|v| v.as_array()) {
            return arr.clone();
        }
    }
    Vec::new()
}

// =============================================================================
// Tree rendering
// =============================================================================

/// Render a project structure as an ASCII tree with branch glyphs.
pub fn render_tree(nodes: &[Value], color: bool) -> String {
    let mut out = String::new();
    for (i, node) in nodes.iter().enumerate() {
        out.push_str(&render_tree_node(
            node,
            "",
            i == nodes.len() - 1,
            color,
            true,
        ));
    }
    out
}

fn render_tree_node(
    node: &Value,
    prefix: &str,
    is_last: bool,
    color: bool,
    is_root: bool,
) -> String {
    let mut out = String::new();
    let name = node.get("name").and_then(|v| v.as_str()).unwrap_or("?");
    let node_type = node.get("type").and_then(|v| v.as_str()).unwrap_or("file");
    let symbol_count = node
        .get("symbol_count")
        .or_else(|| node.get("symbols"))
        .and_then(|v| v.as_u64())
        .unwrap_or(0);
    let children = node.get("children").and_then(|v| v.as_array());

    let connector = if is_root {
        ""
    } else if is_last {
        "└── "
    } else {
        "├── "
    };

    let name_color = if color {
        match node_type {
            "directory" | "dir" => LIGHT_BLUE,
            "module" => LIGHT_MAGENTA,
            _ => WHITE,
        }
    } else {
        ""
    };
    let count_color = if color { DIM } else { "" };
    let reset = if color { RESET } else { "" };

    // Dependency info for file nodes
    let incoming = node
        .get("incoming_dependencies")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);
    let outgoing = node
        .get("outgoing_dependencies")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);
    let dep_suffix = if incoming > 0 || outgoing > 0 {
        format!("  {}[{}→{}]{}", count_color, outgoing, incoming, reset,)
    } else {
        String::new()
    };

    if is_root {
        out.push_str(&format!(
            "{}{}{}{}{}\n",
            name_color,
            name,
            reset,
            suffix(symbol_count, count_color, reset),
            dep_suffix,
        ));
    } else {
        // `suffix(symbol_count, count_color, reset)` already wraps the
        // symbol-count line in `count_color` and ends with `reset`.
        // The earlier code emitted `count_color` immediately before
        // the suffix (and a trailing `reset` after it), so the final
        // output was `…reset {color} [N symbols]{reset} reset…` —
        // printing empty ANSI escapes when `symbol_count == 0` and
        // leaving a trailing reset that does nothing useful when it
        // is non-zero. Drop both the leading `count_color` and the
        // trailing `reset`; the suffix already opens and closes
        // colour for the symbol-count segment.
        out.push_str(&format!(
            "{}{}{}{}{}{}{}\n",
            prefix,
            connector,
            name_color,
            name,
            reset,
            suffix(symbol_count, count_color, reset),
            dep_suffix,
        ));
    }

    if let Some(kids) = children {
        // The child prefix is the vertical continuation that should
        // appear to the left of a grandchild's connector — it shows
        // whether this node has a sibling (│) or is the last ( ).
        // Root nodes pass no continuation because they have no
        // connector themselves; the first level of children sits at
        // column 0.
        let child_prefix = if is_last { "    " } else { "│   " };
        let combined_prefix = format!("{}{}", prefix, child_prefix);
        for (i, child) in kids.iter().enumerate() {
            out.push_str(&render_tree_node(
                child,
                &combined_prefix,
                i == kids.len() - 1,
                color,
                false,
            ));
        }
    }
    out
}

// =============================================================================
// Per-tool render functions
// =============================================================================

fn search_result_text(result: &Value) -> Option<&str> {
    result
        .get("signature")
        .and_then(|v| v.as_str())
        .map(str::trim)
        .filter(|text| !text.is_empty())
        .or_else(|| {
            result
                .get("context")
                .and_then(|v| v.as_str())
                .and_then(|text| text.lines().next())
                .map(str::trim)
                .filter(|text| !text.is_empty())
        })
        .or_else(|| {
            result
                .get("snippet")
                .and_then(|v| v.as_str())
                .map(str::trim)
                .filter(|text| !text.is_empty())
        })
}

fn render_search_result_preview(result: &Value, color: bool) -> String {
    let (dim, reset) = if color { (DIM, RESET) } else { ("", "") };
    if let Some(text) = search_result_text(result) {
        return format!("      {dim}{}{reset}\n", truncate_chars(text, 160));
    }

    let Some(range) = result.get("byte_range").and_then(|v| v.as_array()) else {
        return String::new();
    };
    if range.len() != 2 {
        return String::new();
    }
    let start = range[0].as_u64().unwrap_or(0);
    let end = range[1].as_u64().unwrap_or(0);
    if end <= start {
        return String::new();
    }
    format!("      {dim}(bytes {start}-{end}){reset}\n")
}

fn render_search_result(result: &Value, index: usize, color: bool) -> String {
    let (bold, yellow, cyan, dim, reset) = if color {
        (BOLD, LIGHT_YELLOW, LIGHT_CYAN, DIM, RESET)
    } else {
        ("", "", "", "", "")
    };
    let file = result
        .get("file_path")
        .and_then(|v| v.as_str())
        .unwrap_or("?");
    let mut out = format!("  {bold}{}.{reset} {yellow}{file}{reset}", index + 1);

    if let Some(symbol) = result
        .get("symbol")
        .or_else(|| result.get("symbol_name"))
        .and_then(|v| v.as_str())
    {
        out.push_str(&format!(" :: {cyan}{symbol}{reset}"));
    }
    if let Some(symbol_type) = result.get("symbol_type").and_then(|v| v.as_str()) {
        out.push_str(&format!(" {dim}[{symbol_type}]{reset}"));
    }
    if let Some(line) = result.get("line_number").and_then(|v| v.as_u64()) {
        out.push_str(&format!(" {dim}:{line}{reset}"));
    }
    if let Some(score) = result
        .get("score")
        .and_then(|v| v.get("overall"))
        .and_then(|v| v.as_f64())
        .or_else(|| result.get("score").and_then(|v| v.as_f64()))
    {
        out.push_str(&format!(
            "  {dim}{}%{reset}",
            (score * 100.0).round() as usize
        ));
    }
    out.push('\n');
    out.push_str(&render_search_result_preview(result, color));
    out
}

fn render_search(data: &Value, query: &str, color: bool) -> String {
    let arr = extract_array(data, &["results", "items"]);
    if arr.is_empty() {
        return format!(
            "{}\n  No results for: {}\n",
            header(&format!("Search: \"{}\"", query), color),
            query,
        );
    }
    let mut out = header(
        &format!("Search: \"{}\" ({} results)", query, arr.len()),
        color,
    );
    out.push('\n');
    for (idx, r) in arr.iter().enumerate() {
        out.push_str(&render_search_result(r, idx, color));
    }
    // Low-signal warning (F-07): when the top composite score is below the
    // confidence floor the handler flags it; make that visible in the text
    // surface too so agents do not act on coincidental token-overlap hits.
    if data.get("low_signal").and_then(Value::as_bool) == Some(true) {
        let score = data
            .get("top_score")
            .and_then(Value::as_f64)
            .map(|s| format!(" ({:.2})", s))
            .unwrap_or_default();
        out.push_str(&format!(
            "\n  ⚠ low signal{}: results may be coincidental token overlap; rephrase or use mode=find.\n",
            score
        ));
    }
    out
}

fn context_anchor(data: &Value) -> Option<&Value> {
    data.get("results")
        .and_then(|v| v.as_array())
        .and_then(|results| results.first())
}

fn render_context_metadata(data: &Value, color: bool) -> String {
    let anchor = context_anchor(data);
    let mut out = String::new();
    if let Some(symbol) = anchor
        .and_then(|result| result.get("symbol_name"))
        .and_then(|v| v.as_str())
        .or_else(|| data.get("symbol").and_then(|v| v.as_str()))
    {
        out.push_str(&field("Symbol", symbol, color));
    }
    if let Some(file) = anchor
        .and_then(|result| result.get("file_path"))
        .and_then(|v| v.as_str())
        .or_else(|| data.get("file_path").and_then(|v| v.as_str()))
    {
        out.push_str(&field("File", file, color));
    }
    if let Some(symbol_type) = anchor
        .and_then(|result| result.get("symbol_type"))
        .and_then(|v| v.as_str())
        .or_else(|| data.get("symbol_type").and_then(|v| v.as_str()))
    {
        out.push_str(&field("Type", symbol_type, color));
    }
    if let Some(line) = data.get("line").and_then(|v| v.as_u64()) {
        out.push_str(&field("Line", &line.to_string(), color));
    } else if let Some(range) = anchor
        .and_then(|result| result.get("byte_range"))
        .and_then(|v| v.as_array())
    {
        if range.len() == 2 {
            let start = range[0].as_u64().unwrap_or(0);
            let end = range[1].as_u64().unwrap_or(0);
            if end > start {
                out.push_str(&field("Range", &format!("bytes {start}-{end}"), color));
            }
        }
    }
    out
}

fn render_context_body(data: &Value, color: bool) -> String {
    let (cyan, dim, reset) = if color {
        (LIGHT_CYAN, DIM, RESET)
    } else {
        ("", "", "")
    };
    let body = data
        .get("context")
        .and_then(|v| v.as_str())
        .or_else(|| data.get("content").and_then(|v| v.as_str()));
    if let Some(snippet) = body {
        let base = line_for(data);
        let gutter_base = if base == 0 { 1 } else { base };
        let mut out = String::from("\n");
        for (index, line) in snippet.lines().enumerate() {
            let number = gutter_base.saturating_add(index as u64);
            out.push_str(&format!("  {dim}{number:>4}{reset}│ {line}\n"));
        }
        return out;
    }

    let mut out = String::new();
    if let Some(results) = data.get("results").and_then(|v| v.as_array()) {
        for result in results {
            let symbol = result
                .get("symbol_name")
                .and_then(|v| v.as_str())
                .unwrap_or("?");
            let file = result
                .get("file_path")
                .and_then(|v| v.as_str())
                .unwrap_or("?");
            out.push_str(&format!("  → {cyan}{symbol}{reset} {dim}{file}{reset}\n"));
        }
    }
    out
}

fn render_context(data: &Value, node_id: &str, color: bool) -> String {
    // `ContextHandler` returns a `AnalysisResult` (see
    // `src/cli/leindex/types.rs::AnalysisResult`) with shape:
    //   { query, results: [SearchResult, ...], context: Option<String>,
    //     tokens_used, processing_time_ms }
    // The expanded PDG text lives in `context`, not `content`. Node
    // metadata (symbol, file, type, line) is not on the top level —
    // it lives in `results[0]` (a `SearchResult`). Old callers
    // sometimes still emit a flat `content` / `file_path` /
    // `symbol_type` / `line` / `symbol` shape (e.g. the dispatcher
    // pre-trim payloads), so we fall back to that path before
    // showing the `results` summary.
    let mut out = header(&format!("Context: {}", node_id), color);
    out.push('\n');
    out.push_str(&render_context_metadata(data, color));
    out.push_str(&render_context_body(data, color));
    out
}

fn render_diagnostics_health(data: &Value, color: bool) -> String {
    let Some(health) = data.get("system_health") else {
        return String::new();
    };
    let mut out = String::from("\n  System Health:\n");
    if let Some(value) = health.get("index_health").and_then(|v| v.as_str()) {
        out.push_str(&field("  Index health", value, color));
    }
    if let Some(value) = health.get("pdg_loaded").and_then(|v| v.as_bool()) {
        out.push_str(&field("  PDG loaded", &value.to_string(), color));
    }
    for (key, label) in [
        ("pdg_nodes", "  PDG nodes"),
        ("pdg_edges", "  PDG edges"),
        ("search_index_nodes", "  Search nodes"),
        ("total_signatures", "  Total signatures"),
        ("failed_parses", "  Failed parses"),
    ] {
        if let Some(value) = health.get(key).and_then(|v| v.as_u64()) {
            out.push_str(&field(label, &value.to_string(), color));
        }
    }
    // A delta-scoped signature count covers only the files parsed in the last
    // (incremental) run — annotate it so it is not read as the project total.
    if health.get("signature_scope").and_then(Value::as_str) == Some("delta") {
        out.push_str(&field(
            "  Signature scope",
            "delta — count covers only files parsed in the last incremental run",
            color,
        ));
    }
    if let Some(value) = health.get("embedding_model").and_then(|v| v.as_str()) {
        out.push_str(&field("  Embedding model", value, color));
    }
    out
}

fn render_diagnostics_issues(data: &Value, color: bool) -> String {
    let Some(issues) = data.get("issues").and_then(|v| v.as_array()) else {
        return String::new();
    };
    if issues.is_empty() {
        return String::new();
    }

    let reset = if color { RESET } else { "" };
    let mut out = String::from("\n  Issues:\n");
    for issue in issues.iter().take(10) {
        let severity = issue
            .get("severity")
            .and_then(|v| v.as_str())
            .unwrap_or("info");
        let message = issue.get("message").and_then(|v| v.as_str()).unwrap_or("?");
        let severity_color = if color {
            match severity {
                "error" => LIGHT_RED,
                "warning" => LIGHT_YELLOW,
                _ => LIGHT_BLUE,
            }
        } else {
            ""
        };
        out.push_str(&format!(
            "    {severity_color}{severity}{reset} {message}\n"
        ));
    }
    out
}

fn render_diagnostics(data: &Value, color: bool) -> String {
    let mut out = header("Diagnostics", color);
    out.push('\n');
    if let Some(p) = data.get("project_path").and_then(|v| v.as_str()) {
        out.push_str(&field("Project", p, color));
    }
    if let Some(v) = data.get("indexed_files").and_then(|v| v.as_u64()) {
        out.push_str(&field("Indexed files", &v.to_string(), color));
    }
    if let Some(v) = data.get("symbol_count").and_then(|v| v.as_u64()) {
        out.push_str(&field("Symbols", &v.to_string(), color));
    }
    if let Some(v) = data.get("index_size_mb").and_then(|v| v.as_f64()) {
        out.push_str(&field(
            "Index size (on disk)",
            &format!("{:.2} MB", v),
            color,
        ));
    }
    if let Some(v) = data.get("index_heap_estimate_mb").and_then(|v| v.as_f64()) {
        out.push_str(&field(
            "Index heap (estimated)",
            &format!("{:.2} MB", v),
            color,
        ));
    }
    if let Some(v) = data.get("memory_rss_mb").and_then(|v| v.as_f64()) {
        out.push_str(&field("Memory RSS", &format!("{:.2} MB", v), color));
    }
    if let Some(v) = data.get("db_size_bytes").and_then(|v| v.as_u64()) {
        out.push_str(&field("DB size", &format!("{} bytes", v), color));
    }
    if let Some(v) = data.get("stale").and_then(|v| v.as_bool()) {
        out.push_str(&field("Stale", &v.to_string(), color));
    }
    if let Some(v) = data.get("last_indexed_secs_ago").and_then(|v| v.as_u64()) {
        out.push_str(&field("Last indexed", &format!("{}s ago", v), color));
    }
    // VAL-ONNX-006: Show embedding model status at top level for CLI diagnostics
    if let Some(v) = data.get("embedding_model").and_then(|v| v.as_str()) {
        out.push_str(&field("Embedding model", v, color));
    }
    if let Some(preset) = data.get("embedding_preset").and_then(Value::as_str) {
        out.push_str(&field("Embedding preset", preset, color));
    }
    if let Some(dimension) = data.get("measured_embedding_dimension") {
        let value = dimension
            .as_u64()
            .map(|dimension| dimension.to_string())
            .unwrap_or_else(|| "unknown (no successful remote response)".to_string());
        out.push_str(&field("Measured embedding dimension", &value, color));
    }
    out.push_str(&render_diagnostics_engram(data, color));
    out.push_str(&render_diagnostics_precision(data, color));
    out.push_str(&render_diagnostics_provider(data, color));
    out.push_str(&render_diagnostics_health(data, color));
    out.push_str(&render_diagnostics_issues(data, color));
    out
}

/// Render the `engram` cache status line: hit/miss/entry counts when the
/// feature is enabled, an off-note pointing at the feature flag otherwise.
/// Emits nothing when the handler did not report the field.
fn render_diagnostics_engram(data: &Value, color: bool) -> String {
    let Some(engram) = data.get("engram") else {
        return String::new();
    };
    let enabled = engram.get("enabled").and_then(|v| v.as_bool()) == Some(true);
    let summary = if enabled {
        let count = |key: &str| engram.get(key).and_then(|v| v.as_u64()).unwrap_or(0);
        format!(
            "on ({} hits / {} misses, {} entries)",
            count("hits"),
            count("misses"),
            count("entries")
        )
    } else {
        "off (LEINDEX_FEATURE_ENGRAM=1 to enable)".to_string()
    };
    field("Engram", &summary, color)
}

/// Render the SCIP-precision block: enabled flag, node count, and the
/// comma-joined language list (the language line is omitted when the
/// list is empty).
fn render_diagnostics_precision(data: &Value, color: bool) -> String {
    let mut out = String::new();
    if let Some(enabled) = data.get("precision_enabled").and_then(|v| v.as_bool()) {
        let status = if enabled { "enabled" } else { "disabled" };
        out.push_str(&field("SCIP precision", status, color));
    }
    if let Some(v) = data.get("precision_nodes").and_then(|v| v.as_u64()) {
        out.push_str(&field("Precision nodes", &v.to_string(), color));
    }
    if let Some(languages) = data.get("precision_languages").and_then(|v| v.as_array()) {
        let names = languages
            .iter()
            .filter_map(|v| v.as_str())
            .collect::<Vec<_>>()
            .join(", ");
        if !names.is_empty() {
            out.push_str(&field("Precision languages", &names, color));
        }
    }
    out
}

// VAL-CROSS-015 / VAL-ORT-022: surface resolved ORT library info so support
// engineers can debug any install surface identically via `leindex diagnostics`.
fn render_diagnostics_provider(data: &Value, color: bool) -> String {
    let mut out = String::new();
    if let Some(v) = data.get("ort_version").and_then(|v| v.as_str()) {
        out.push_str(&field("ORT version", v, color));
    }
    if let Some(v) = data.get("ort_path").and_then(|v| v.as_str()) {
        out.push_str(&field("ORT dylib path", v, color));
    }
    if let Some(v) = data.get("execution_provider").and_then(|v| v.as_str()) {
        out.push_str(&field("Execution provider", v, color));
    }
    // The configured provider is a request; the worker reports what actually
    // loaded. When they differ (e.g. migraphx requested, cpu active after a
    // provider-library load failure) surface the fallback explicitly instead
    // of letting the requested value masquerade as the active one.
    if let Some(active) = data
        .get("execution_provider_active")
        .and_then(|v| v.as_str())
    {
        if let Some(requested) = data.get("execution_provider").and_then(|v| v.as_str()) {
            if active != requested {
                out.push_str(&field(
                    "Provider fallback",
                    &format!("{requested} requested, {active} ACTIVE"),
                    color,
                ));
            }
        }
    }
    out
}

fn render_file_summary_symbols(data: &Value, color: bool) -> String {
    let Some(symbols) = data.get("symbols").and_then(|v| v.as_array()) else {
        return String::new();
    };
    if symbols.is_empty() {
        return String::new();
    }

    let mut out = String::from("\n  Symbols:\n");
    for symbol in symbols.iter().take(50) {
        let name = symbol.get("name").and_then(|v| v.as_str()).unwrap_or("?");
        let typ = symbol
            .get("type")
            .and_then(|v| v.as_str())
            .unwrap_or("symbol");
        let (icon, icon_color) = if color {
            match typ {
                "function" | "fn" => ("ƒ", LIGHT_GREEN),
                "method" => ("m", LIGHT_CYAN),
                "struct" => ("S", LIGHT_MAGENTA),
                "enum" => ("E", LIGHT_YELLOW),
                "trait" => ("T", LIGHT_BLUE),
                "impl" => ("I", LIGHT_MAGENTA),
                "const" | "static" => ("c", LIGHT_CYAN),
                "field" => ("f", LIGHT_YELLOW),
                _ => ("•", WHITE),
            }
        } else {
            ("•", "")
        };
        out.push_str(&format!(
            "    {}{}{} {}{}{}\n",
            icon_color,
            icon,
            if color { RESET } else { "" },
            if color { LIGHT_CYAN } else { "" },
            name,
            if color { RESET } else { "" },
        ));
    }

    let truncated = data
        .get("symbols_truncated")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let total = data
        .get("symbol_count")
        .and_then(|v| v.as_u64())
        .unwrap_or(0) as usize;
    let shown = symbols.len().min(50);
    if truncated || shown < total {
        out.push_str(&format!(
            "    {}… {} more symbols (truncated){}\n",
            if color { DIM } else { "" },
            total.saturating_sub(shown),
            if color { RESET } else { "" },
        ));
    }
    out
}

fn render_file_summary(data: &Value, color: bool) -> String {
    let mut out = header("File Summary", color);
    out.push('\n');
    if let Some(file) = data.get("file_path").and_then(|v| v.as_str()) {
        out.push_str(&field("File", file, color));
    }
    if let Some(lang) = data.get("language").and_then(|v| v.as_str()) {
        out.push_str(&field("Language", lang, color));
    }
    if let Some(lc) = data.get("line_count").and_then(|v| v.as_u64()) {
        out.push_str(&field("Lines", &lc.to_string(), color));
    }
    if let Some(sc) = data.get("symbol_count").and_then(|v| v.as_u64()) {
        out.push_str(&field("Symbols", &sc.to_string(), color));
    }
    if let Some(role) = data.get("module_role").and_then(|v| v.as_str()) {
        out.push_str(&field("Role", role, color));
    }
    out.push_str(&render_file_summary_symbols(data, color));
    out
}

fn render_read_file(data: &Value, color: bool) -> String {
    let mut out = String::new();
    if let Some(path) = data.get("file_path").and_then(|v| v.as_str()) {
        out.push_str(&header(&format!("Read: {}", path), color));
        out.push('\n');
    }
    let content = data
        .get("content")
        .and_then(|v| v.as_str())
        .unwrap_or_default();
    let start = data.get("start_line").and_then(|v| v.as_u64()).unwrap_or(1);
    for (i, line) in content.lines().enumerate() {
        let n = start + i as u64;
        let gutter = format!("{:>4}", n);
        out.push_str(&format!(
            "  {}{}{}│ {}\n",
            if color { DIM } else { "" },
            gutter,
            if color { RESET } else { "" },
            line,
        ));
    }
    // `include_symbol_map=true` requests per-symbol PDG annotations for the
    // read range; the handler builds them and the trimmer keeps them, but
    // this renderer silently dropped the field — the parameter looked like a
    // no-op (N-08). Render a compact map when present.
    out.push_str(&render_read_file_symbol_map(data, color));
    out
}

/// Render the compact per-symbol map requested by `include_symbol_map`:
/// up to 20 symbols with optional `[type]` tag and `:start-end` line
/// range. Emits nothing when the map is absent or empty.
fn render_read_file_symbol_map(data: &Value, color: bool) -> String {
    let Some(symbols) = data.get("symbol_map").and_then(|v| v.as_array()) else {
        return String::new();
    };
    if symbols.is_empty() {
        return String::new();
    }
    let mut out = format!(
        "\n  {}Symbols in range ({}):{}\n",
        if color { DIM } else { "" },
        symbols.len(),
        if color { RESET } else { "" },
    );
    for symbol in symbols.iter().take(20) {
        let name = symbol.get("name").and_then(|v| v.as_str()).unwrap_or("?");
        let typ = symbol.get("type").and_then(|v| v.as_str()).unwrap_or("");
        let line_start = symbol.get("line_start").and_then(|v| v.as_u64());
        let line_end = symbol.get("line_end").and_then(|v| v.as_u64());
        let location = match (line_start, line_end) {
            (Some(s), Some(e)) => format!(":{s}-{e}"),
            (Some(s), None) => format!(":{s}"),
            _ => String::new(),
        };
        out.push_str(&format!(
            "    {}{}{} {}{}{}{}\n",
            if color { LIGHT_CYAN } else { "" },
            name,
            if color { RESET } else { "" },
            if color { DIM } else { "" },
            if typ.is_empty() {
                String::new()
            } else {
                format!("[{typ}]")
            },
            location,
            if color { RESET } else { "" },
        ));
    }
    out
}

fn render_write_symbols(data: &Value, color: bool) -> String {
    let Some(symbols) = data.get("symbols").and_then(|v| v.as_array()) else {
        return String::new();
    };
    if symbols.is_empty() {
        return String::new();
    }

    let mut out = format!(
        "\n  {}Symbols ({}):{}\n",
        if color { DIM } else { "" },
        symbols.len(),
        if color { RESET } else { "" },
    );
    for symbol in symbols.iter().take(20) {
        let name = symbol.get("name").and_then(|v| v.as_str()).unwrap_or("?");
        let typ = symbol.get("type").and_then(|v| v.as_str()).unwrap_or("");
        out.push_str(&format!(
            "    {}{}{} {}{}{}\n",
            if color { LIGHT_CYAN } else { "" },
            name,
            if color { RESET } else { "" },
            if color { DIM } else { "" },
            if typ.is_empty() {
                String::new()
            } else {
                format!("[{}]", typ)
            },
            if color { RESET } else { "" },
        ));
    }
    if symbols.len() > 20 {
        out.push_str(&format!(
            "    {}…and {} more{}\n",
            if color { DIM } else { "" },
            symbols.len() - 20,
            if color { RESET } else { "" },
        ));
    }
    out
}

fn render_write(data: &Value, color: bool) -> String {
    // `WriteHandler` returns `{ success, file_path, language, symbols }`, not a diff.
    let success = data
        .get("success")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let (status_label, status_color) = if success {
        ("Wrote", if color { LIGHT_GREEN } else { "" })
    } else {
        ("Write failed", if color { LIGHT_RED } else { "" })
    };
    let mut out = format!(
        "{}{}{}\n",
        status_color,
        status_label,
        if color { RESET } else { "" },
    );
    if let Some(path) = data.get("file_path").and_then(|v| v.as_str()) {
        out.push_str(&field("File", path, color));
    }
    if let Some(lang) = data.get("language").and_then(|v| v.as_str()) {
        out.push_str(&field("Language", lang, color));
    }
    out.push_str(&render_write_symbols(data, color));
    out
}

fn render_meta_line(label: &str, value: &str, color: bool) -> String {
    format!(
        "  {}{}:{} {}",
        if color { BOLD } else { "" },
        label,
        if color { RESET } else { "" },
        value,
    )
}

fn append_meta_lines(mut out: String, meta_lines: &[String]) -> String {
    if meta_lines.is_empty() {
        return out;
    }
    if !out.is_empty() {
        out.push('\n');
    }
    out.push_str(&meta_lines.join("\n"));
    out.push('\n');
    out
}

/// Render edit-preview output: diff followed by metadata fields
/// (affected_symbols, affected_files, risk_level, change_count).
fn render_edit_preview(data: &Value, color: bool) -> String {
    let mut meta_lines = Vec::new();

    if let Some(symbols) = data.get("affected_symbols").and_then(|v| v.as_array()) {
        if !symbols.is_empty() {
            let names: Vec<&str> = symbols.iter().filter_map(|v| v.as_str()).collect();
            meta_lines.push(render_meta_line(
                "Affected symbols",
                &names.join(", "),
                color,
            ));
        }
    }
    if let Some(files) = data.get("affected_files").and_then(|v| v.as_array()) {
        if !files.is_empty() {
            let names: Vec<&str> = files.iter().filter_map(|v| v.as_str()).collect();
            meta_lines.push(render_meta_line("Affected files", &names.join(", "), color));
        }
    }
    if let Some(risk) = data.get("risk_level").and_then(|v| v.as_str()) {
        meta_lines.push(render_meta_line("Risk level", risk, color));
    }
    if let Some(count) = data.get("change_count").and_then(|v| v.as_u64()) {
        meta_lines.push(render_meta_line("Change count", &count.to_string(), color));
    }
    if let Some(breaks) = data.get("breaking_changes").and_then(|v| v.as_array()) {
        for description in breaks.iter().filter_map(|value| value.as_str()) {
            meta_lines.push(render_meta_line("Breaking", description, color));
        }
    }

    append_meta_lines(render_diff_value(data, color), &meta_lines)
}

/// Render rename-symbol output: multi-file diffs followed by metadata
/// (old_name, new_name, files_affected, preview_only).
fn render_rename_symbol(data: &Value, color: bool) -> String {
    let mut meta_lines = Vec::new();

    if let (Some(old), Some(new)) = (
        data.get("old_name").and_then(|v| v.as_str()),
        data.get("new_name").and_then(|v| v.as_str()),
    ) {
        meta_lines.push(render_meta_line("Rename", &format!("{old} → {new}"), color));
    }
    if let Some(count) = data.get("files_affected").and_then(|v| v.as_u64()) {
        meta_lines.push(render_meta_line(
            "Files affected",
            &count.to_string(),
            color,
        ));
    }
    if let Some(diffs_more) = data
        .get("diffs_more")
        .and_then(|v| v.as_u64())
        .filter(|count| *count > 0)
    {
        meta_lines.push(render_meta_line(
            "Additional diffs",
            &format!("{diffs_more} more (not shown)"),
            color,
        ));
    }
    if data
        .get("preview_only")
        .and_then(|v| v.as_bool())
        .unwrap_or(false)
    {
        meta_lines.push(render_meta_line(
            "Preview only",
            "changes not applied",
            color,
        ));
    }

    append_meta_lines(render_diff_value(data, color), &meta_lines)
}

fn render_edit_region(region_value: &Value, color: bool) -> String {
    // `edit_region` may be a source excerpt or a byte-range object retained by `trim_edit`.
    let region_text = if let Some(s) = region_value.as_str() {
        if s.is_empty() {
            None
        } else {
            Some(s.to_string())
        }
    } else if let Some(obj) = region_value.as_object() {
        let start = obj.get("start").and_then(|v| v.as_u64());
        let end = obj.get("end").and_then(|v| v.as_u64());
        match (start, end) {
            (Some(s), Some(e)) => Some(format!("bytes {s}..{e}")),
            (Some(s), None) => Some(format!("bytes {s}..")),
            (None, Some(e)) => Some(format!("bytes ..{e}")),
            (None, None) => Some("bytes ?".to_string()),
        }
    } else {
        None
    };
    let Some(text) = region_text else {
        return String::new();
    };

    let mut out = String::from("\n");
    if region_value.is_string() {
        out.push_str(&format!(
            "  {}Surrounding region:{}\n",
            if color { DIM } else { "" },
            if color { RESET } else { "" },
        ));
        for line in text.lines() {
            out.push_str(&format!(
                "      {}{}{}\n",
                if color { DIM } else { "" },
                truncate_chars(line, 160),
                if color { RESET } else { "" },
            ));
        }
    } else {
        out.push_str(&format!(
            "  {}Surrounding region:{} {}\n",
            if color { DIM } else { "" },
            if color { RESET } else { "" },
            text,
        ));
    }
    out
}

fn render_edit_apply(data: &Value, color: bool) -> String {
    // `EditApplyHandler` returns a confirmation payload with shape
    // (see `src/cli/mcp/edit_apply_handler.rs::EditApplyHandler::
    // execute`):
    //   { success, changes_applied, file_path, edit_region,
    //     affected_symbols, affected_files, breaking_changes,
    //     [validation], [message] (no-op only) }
    // The handler never emits `diff` / `diffs` / `diff_text`, so
    // `render_diff_value` returns an empty string for the apply
    // response and the CLI prints nothing for a successful (or
    // no-op) apply. Surface the success status, the change count,
    // the file path, the affected-symbol/file summary, breaking
    // changes, and the surrounding-region excerpt.
    let mut out = String::new();
    let success = data
        .get("success")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let (status_label, status_color) = edit_apply_status(success, data, color);
    out.push_str(&format!(
        "{}{}{}\n",
        status_color,
        status_label,
        if color { RESET } else { "" },
    ));
    if let Some(path) = data.get("file_path").and_then(|v| v.as_str()) {
        out.push_str(&field("File", path, color));
    }
    if let Some(msg) = data.get("message").and_then(|v| v.as_str()) {
        out.push_str(&field("Message", msg, color));
    }
    if let Some(arr) = data.get("affected_symbols").and_then(|v| v.as_array()) {
        if !arr.is_empty() {
            out.push_str(&field("Affected symbols", &arr.len().to_string(), color));
        }
    }
    if let Some(arr) = data.get("affected_files").and_then(|v| v.as_array()) {
        if !arr.is_empty() {
            out.push_str(&field("Affected files", &arr.len().to_string(), color));
        }
    }
    if let Some(bc) = data.get("breaking_changes").and_then(|v| v.as_array()) {
        if !bc.is_empty() {
            out.push_str(&field("Breaking changes", &bc.len().to_string(), color));
        }
    }
    out.push_str(
        &data
            .get("edit_region")
            .map_or_else(String::new, |region| render_edit_region(region, color)),
    );
    out
}

/// Pick the first status line of the edit-apply render: failure, dry-run
/// preview, no-op, or successful apply. A dry run always reports zero
/// applied changes by design; labeling it "No-op (content identical)"
/// misdescribes a real preview.
fn edit_apply_status(success: bool, data: &Value, color: bool) -> (&'static str, &'static str) {
    if !success {
        ("Edit apply failed", if color { LIGHT_RED } else { "" })
    } else if data.get("dry_run").and_then(|v| v.as_bool()) == Some(true) {
        (
            "Dry run (no changes written)",
            if color { LIGHT_YELLOW } else { "" },
        )
    } else if data
        .get("changes_applied")
        .and_then(|v| v.as_u64())
        .unwrap_or(0)
        == 0
    {
        (
            "No-op (content identical)",
            if color { LIGHT_YELLOW } else { "" },
        )
    } else {
        ("Applied", if color { LIGHT_GREEN } else { "" })
    }
}

// =============================================================================
// Central dispatch — single entry point for CLI tool rendering
// =============================================================================

/// Render a tool's value for the CLI surface. The MCP transport uses
/// the raw `Value` (clean JSON for the LLM); the CLI uses this function
/// to produce a human-readable, colored view of the same data.
pub fn render_tool_output(name: &str, data: &Value, args: &Value) -> String {
    render_tool_output_with_color(name, data, args, true)
}

/// Render a tool's value with the freshness footer split out.
///
/// CLI one-shot consumers (`tools run`) print the body to stdout and the
/// footer to stderr so JSON-emitting tools stay parseable with a plain
/// `json.load`; the MCP transport concatenates both via
/// [`render_tool_output`].
pub fn render_tool_output_split(
    name: &str,
    data: &Value,
    args: &Value,
) -> (String, Option<String>) {
    let (rendered, footer) = render_tool_output_inner(name, data, args, true);
    (rendered, footer)
}

/// Render a tool's value *without* ANSI color codes. Used by the MCP
/// transport to produce clean text for the LLM (the CLI uses the
/// colored `render_tool_output`).
pub fn render_tool_output_plain(name: &str, data: &Value, args: &Value) -> String {
    render_tool_output_with_color(name, data, args, false)
}

fn render_tool_output_with_color(name: &str, data: &Value, args: &Value, color: bool) -> String {
    let (mut rendered, footer) = render_tool_output_inner(name, data, args, color);
    if let Some(footer) = footer {
        rendered.push_str(&footer);
    }
    rendered
}

fn render_tool_output_inner(
    name: &str,
    data: &Value,
    args: &Value,
    color: bool,
) -> (String, Option<String>) {
    let normalized = normalize_tool_name(name);
    let query = args.get("query").and_then(|v| v.as_str()).unwrap_or("");
    let node_id = args.get("node_id").and_then(|v| v.as_str()).unwrap_or("");

    let rendered = match normalized.as_str() {
        "leindex_search" | "search" => render_search(data, query, color),
        "leindex_find" | "find" => render_find(data),
        "leindex_structural" | "structural" => render_structural(data),
        "leindex_context" | "context" => render_context(data, node_id, color),
        "leindex_diagnostics" | "diagnostics" => render_diagnostics(data, color),
        "leindex_project_map" | "project_map" => render_project_map(data, color),
        "leindex_impact_analysis" | "impact_analysis" => render_impact(data, color),
        "leindex_symbol_lookup" | "symbol_lookup" => render_symbol_lookup(data, color),
        "leindex_phase_analysis" | "phase_analysis" => render_phase(data, color),
        "leindex_git_status" | "git_status" => render_git_status(data, color),
        "leindex_file_summary" | "file_summary" => render_file_summary(data, color),
        "leindex_read_file" | "read_file" => render_read_file(data, color),
        "leindex_edit_preview" | "edit_preview" => render_edit_preview(data, color),
        // `EditApplyHandler` returns a confirmation payload
        // (`success, changes_applied, file_path, edit_region, …`)
        // not a diff, so `render_diff_value` returns an empty
        // string for the apply response. Use the dedicated
        // confirmation renderer instead.
        "leindex_edit_apply" | "edit_apply" => render_edit_apply(data, color),
        // `WriteHandler` returns a confirmation payload
        // (`{success, file_path, language, symbols}`) not a diff, so
        // `render_diff_value` would return an empty string here.
        "leindex_write" | "write" => render_write(data, color),
        "leindex_rename_symbol" | "rename_symbol" => render_rename_symbol(data, color),
        _ => render_default(data, color),
    };
    let mut footer = String::new();
    if let Some(freshness) = data
        .get("_meta")
        .and_then(|meta| meta.get("freshness"))
        .or_else(|| data.get("freshness"))
    {
        let status = freshness
            .get("status")
            .and_then(Value::as_str)
            .unwrap_or("unknown");
        let generation = freshness
            .get("generation")
            .and_then(Value::as_u64)
            .map(|value| value.to_string())
            .unwrap_or_else(|| "none".to_string());
        let advisory = freshness
            .get("advisory")
            .and_then(Value::as_str)
            .or_else(|| freshness.get("warning").and_then(Value::as_str));
        footer.push_str(&format!(
            "\nFreshness: status={status}, generation={generation}\n"
        ));
        if let Some(advisory) = advisory {
            footer.push_str(&format!("Advisory: {advisory}\n"));
        }
    }
    if let Some(gate) = system_one_footer(data) {
        footer.push_str(&gate);
    }
    if footer.is_empty() {
        (rendered, None)
    } else {
        (rendered, Some(footer))
    }
}

/// One footer line for the System-One gate annotation (`_system_one`), so the
/// model sees healed arguments and filtered results on the text surface (L1
/// tier) too, not only in raw JSON. `None` (zero tokens) when the gate did
/// nothing — `Notes::attach` only emits the key when it has something to say.
/// Not feature-gated: without the `system-one` build the `_system_one` key
/// never exists, so this returns `None` at zero cost.
pub(crate) fn system_one_footer(data: &Value) -> Option<String> {
    let note = data.get("_system_one")?;
    let mut parts: Vec<String> = Vec::new();
    if let Some(healed) = note.get("healed").and_then(Value::as_array) {
        for change in healed {
            let param = change.get("param").and_then(Value::as_str).unwrap_or("?");
            let by = change.get("by").and_then(Value::as_str).unwrap_or("code");
            let show = |key: &str| {
                change.get(key).map(|value| match value {
                    Value::String(s) => s.clone(),
                    other => other.to_string(),
                })
            };
            match (show("from"), show("to")) {
                (Some(from), Some(to)) => parts.push(format!("{param} {from} → {to} ({by})")),
                _ => parts.push(format!("{param} repaired ({by})")),
            }
        }
    }
    if let Some(hints) = note.get("hints").and_then(Value::as_array) {
        parts.extend(
            hints
                .iter()
                .filter_map(Value::as_str)
                .map(|hint| format!("hint: {hint}")),
        );
    }
    if let Some(count) = note
        .get("filtered")
        .and_then(|filtered| filtered.get("count"))
        .and_then(Value::as_u64)
    {
        parts.push(format!("filtered {count} results"));
    }
    if note.get("reordered").and_then(Value::as_bool) == Some(true) {
        parts.push("reordered by relevance".to_string());
    }
    if parts.is_empty() {
        return None;
    }
    Some(format!("\nSystem-One: {}\n", parts.join("; ")))
}

// =============================================================================
// Backward-compatible Formatter structs — thin wrappers for callers
// outside this module that build a formatter explicitly. New code
// should call `render_tool_output` instead.
// =============================================================================

/// Formatter for search results with ranked listings and scores
pub struct SearchFormatter {
    color: bool,
}

impl SearchFormatter {
    /// Create a new SearchFormatter with default settings
    pub fn new() -> Self {
        Self { color: true }
    }

    /// Enable or disable color output
    pub fn with_color(mut self, color: bool) -> Self {
        self.color = color;
        self
    }

    /// Format search results with ranking and scoring
    pub fn format(&self, results: &Value, query: &str) -> String {
        render_search(results, query, self.color)
    }
}

impl Default for SearchFormatter {
    fn default() -> Self {
        Self::new()
    }
}

/// Formatter for project structure/dependency tree visualization
pub struct ProjectMapFormatter {
    color: bool,
}

impl ProjectMapFormatter {
    /// Create a new ProjectMapFormatter with default settings
    pub fn new() -> Self {
        Self { color: true }
    }

    /// Enable or disable color output
    pub fn with_color(mut self, color: bool) -> Self {
        self.color = color;
        self
    }

    /// Format project structure data as a tree view
    pub fn format(&self, data: &Value) -> String {
        render_project_map(data, self.color)
    }
}

impl Default for ProjectMapFormatter {
    fn default() -> Self {
        Self::new()
    }
}

/// Formatter for project diagnostics and index status
pub struct DiagnosticsFormatter {
    color: bool,
}

impl DiagnosticsFormatter {
    /// Create a new DiagnosticsFormatter with default settings
    pub fn new() -> Self {
        Self { color: true }
    }

    /// Enable or disable color output
    pub fn with_color(mut self, color: bool) -> Self {
        self.color = color;
        self
    }

    /// Format diagnostics data including index stats and issues
    pub fn format(&self, data: &Value) -> String {
        render_diagnostics(data, self.color)
    }
}

impl Default for DiagnosticsFormatter {
    fn default() -> Self {
        Self::new()
    }
}

/// Formatter for symbol impact analysis showing forward/backward dependencies
pub struct ImpactFormatter {
    color: bool,
}

impl ImpactFormatter {
    /// Create a new ImpactFormatter with default settings
    pub fn new() -> Self {
        Self { color: true }
    }

    /// Enable or disable color output
    pub fn with_color(mut self, color: bool) -> Self {
        self.color = color;
        self
    }

    /// Format impact analysis data with risk levels and affected symbols
    pub fn format(&self, data: &Value) -> String {
        render_impact(data, self.color)
    }
}

impl Default for ImpactFormatter {
    fn default() -> Self {
        Self::new()
    }
}

/// Formatter for symbol lookup results with callers and callees
pub struct SymbolLookupFormatter {
    color: bool,
}

impl SymbolLookupFormatter {
    /// Create a new SymbolLookupFormatter with default settings
    pub fn new() -> Self {
        Self { color: true }
    }

    /// Enable or disable color output
    pub fn with_color(mut self, color: bool) -> Self {
        self.color = color;
        self
    }

    /// Format symbol lookup data showing definition, callers, and callees
    pub fn format(&self, data: &Value) -> String {
        render_symbol_lookup(data, self.color)
    }
}

impl Default for SymbolLookupFormatter {
    fn default() -> Self {
        Self::new()
    }
}

/// Formatter for phase analysis results
pub struct PhaseFormatter {
    color: bool,
}

impl PhaseFormatter {
    /// Create a new PhaseFormatter with default settings
    pub fn new() -> Self {
        Self { color: true }
    }

    /// Enable or disable color output
    pub fn with_color(mut self, color: bool) -> Self {
        self.color = color;
        self
    }

    /// Format phase analysis data with phase status and summaries
    pub fn format(&self, data: &Value) -> String {
        render_phase(data, self.color)
    }
}

impl Default for PhaseFormatter {
    fn default() -> Self {
        Self::new()
    }
}

/// Formatter for git status with staged, modified, and untracked files
pub struct GitStatusFormatter {
    color: bool,
}

impl GitStatusFormatter {
    /// Create a new GitStatusFormatter with default settings
    pub fn new() -> Self {
        Self { color: true }
    }

    /// Enable or disable color output
    pub fn with_color(mut self, color: bool) -> Self {
        self.color = color;
        self
    }

    /// Format git status data showing branch and file changes
    pub fn format(&self, data: &Value) -> String {
        render_git_status(data, self.color)
    }
}

impl Default for GitStatusFormatter {
    fn default() -> Self {
        Self::new()
    }
}

/// Formatter for file summary with symbols and complexity metrics
pub struct FileSummaryFormatter {
    color: bool,
}

impl FileSummaryFormatter {
    /// Create a new FileSummaryFormatter with default settings
    pub fn new() -> Self {
        Self { color: true }
    }

    /// Enable or disable color output
    pub fn with_color(mut self, color: bool) -> Self {
        self.color = color;
        self
    }

    /// Format file summary data with file info and symbol list
    pub fn format(&self, data: &Value) -> String {
        render_file_summary(data, self.color)
    }
}

impl Default for FileSummaryFormatter {
    fn default() -> Self {
        Self::new()
    }
}

// =============================================================================
// Tests
// =============================================================================

// =============================================================================
// leindex_find — compact, token-lean text
// =============================================================================

/// String accessor for `leindex_find` payloads: `""` when the field is
/// missing or not a string.
fn find_text(v: &Value, key: &str) -> String {
    v.get(key).and_then(Value::as_str).unwrap_or("").to_string()
}

/// Numeric accessor for `leindex_find` payloads: `0` when the field is
/// missing or not a number.
fn find_num(v: &Value, key: &str) -> u64 {
    v.get(key).and_then(Value::as_u64).unwrap_or(0)
}

/// Render a `leindex_find` result. Hits are grouped by file and, inside a file,
/// by enclosing symbol, so a symbol name is paid for once rather than per line.
fn render_find(data: &Value) -> String {
    use std::fmt::Write as _;

    if data.get("is_git_repo").is_some() {
        return render_default(data, false);
    }
    let pattern = find_text(data, "pattern");
    if data["target"] == "symbols" {
        return render_find_symbols(data, &pattern);
    }

    let mut out = String::new();
    render_find_summary(&mut out, data, &pattern);
    render_find_output_section(&mut out, data);
    if data["has_more"] == true {
        let _ = writeln!(
            out,
            "… more results: offset={}",
            find_num(data, "next_offset")
        );
    }
    if let Some(note) = data.get("note").and_then(Value::as_str) {
        let _ = writeln!(out, "{note}");
    }
    out
}

/// Render `target=symbols` results: one line per matching symbol with
/// optional line anchor and stale-file annotation.
fn render_find_symbols(data: &Value, pattern: &str) -> String {
    use std::fmt::Write as _;
    let mut out = String::new();
    let total = find_num(data, "total_symbols");
    let _ = writeln!(out, "{total} symbol(s) named like \"{pattern}\"");
    for symbol in data["symbols"].as_array().into_iter().flatten() {
        let line = find_num(symbol, "line");
        let _ = writeln!(
            out,
            "  {} {} — {}{}{}",
            find_text(symbol, "kind"),
            find_text(symbol, "name"),
            find_text(symbol, "file"),
            if line > 0 {
                format!(":{line}")
            } else {
                String::new()
            },
            if symbol["stale"] == true {
                " (file changed since indexing)"
            } else {
                ""
            },
        );
    }
    if data["has_more"] == true {
        let _ = writeln!(out, "… more: offset={}", find_num(data, "next_offset"));
    }
    if let Some(note) = data.get("note").and_then(Value::as_str) {
        let _ = writeln!(out, "{note}");
    }
    out
}

/// Render the match-count summary line (with indexed-state suffix) and the
/// optional search-fallback note.
fn render_find_summary(out: &mut String, data: &Value, pattern: &str) {
    use std::fmt::Write as _;
    let stats = &data["stats"];
    let indexed = data["roots"]
        .as_array()
        .is_some_and(|roots| roots.iter().all(|r| r["indexed"] == true));
    let _ = writeln!(
        out,
        "{} match(es) in {} file(s) for \"{}\" · {}ms{}",
        find_num(data, "total_matches"),
        find_num(data, "total_files"),
        pattern,
        find_num(stats, "millis"),
        if indexed { " · indexed" } else { "" },
    );
    if let Some(fallback) = data.get("fallback").and_then(Value::as_str) {
        let _ = writeln!(out, "({fallback})");
    }
}

/// Dispatch on the requested `output` mode: bare counts, file list,
/// symbol list, or full content hits.
fn render_find_output_section(out: &mut String, data: &Value) {
    match find_text(data, "output").as_str() {
        "count" => {}
        "files" => render_find_files_output(out, data),
        "symbols" => render_find_symbol_matches(out, data),
        _ => render_find_content_hits(out, data),
    }
}

/// `output=files`: one line per matching file.
fn render_find_files_output(out: &mut String, data: &Value) {
    use std::fmt::Write as _;
    for file in data["files"].as_array().into_iter().flatten() {
        let _ = writeln!(
            out,
            "  {} ({})",
            find_text(file, "file"),
            find_num(file, "matches")
        );
    }
}

/// `output=symbols`: one line per matching symbol with its match count.
fn render_find_symbol_matches(out: &mut String, data: &Value) {
    use std::fmt::Write as _;
    for symbol in data["symbols"].as_array().into_iter().flatten() {
        let _ = writeln!(
            out,
            "  {} {} — {} ({})",
            find_text(symbol, "kind"),
            find_text(symbol, "name"),
            find_text(symbol, "file"),
            find_num(symbol, "matches"),
        );
    }
}

/// Default content mode: per-file hit blocks, hits grouped under their
/// enclosing symbol so a symbol name is printed once.
fn render_find_content_hits(out: &mut String, data: &Value) {
    use std::fmt::Write as _;
    for file in data["files"].as_array().into_iter().flatten() {
        let shown = file["hits"].as_array().map_or(0, Vec::len) as u64;
        let total = find_num(file, "matches");
        let _ = writeln!(
            out,
            "{}{}",
            find_text(file, "file"),
            if total > shown {
                format!(" ({shown} of {total} shown)")
            } else {
                String::new()
            },
        );
        let mut current: Option<String> = None;
        for hit in file["hits"].as_array().into_iter().flatten() {
            render_find_hit(out, &mut current, hit);
        }
    }
}

/// Render a single content hit: the enclosing-symbol header (when the
/// symbol changes), the `before` context lines, the match line, and the
/// `after` context lines.
fn render_find_hit(out: &mut String, current: &mut Option<String>, hit: &Value) {
    use std::fmt::Write as _;
    let symbol = hit
        .get("symbol")
        .and_then(Value::as_str)
        .map(str::to_string);
    if symbol != *current {
        if let Some(name) = &symbol {
            let _ = writeln!(out, " {} ({})", name, find_text(hit, "kind"));
        }
        *current = symbol;
    }
    for line in hit["before"].as_array().into_iter().flatten() {
        let _ = writeln!(out, "   | {}", line.as_str().unwrap_or(""));
    }
    let _ = writeln!(
        out,
        "  {}: {}",
        find_num(hit, "line"),
        find_text(hit, "text")
    );
    for line in hit["after"].as_array().into_iter().flatten() {
        let _ = writeln!(out, "   | {}", line.as_str().unwrap_or(""));
    }
}

// =============================================================================
// leindex_structural — AST-pattern matches
// =============================================================================

/// Render a `leindex_structural` result: one header with the pattern and
/// language, then matches grouped by file so the path is paid for once.
fn render_structural(data: &Value) -> String {
    use std::fmt::Write as _;

    let pattern = find_text(data, "pattern");
    let lang = find_text(data, "lang");
    let total = find_num(data, "total_matches");
    let returned = find_num(data, "returned");
    let mut out = String::new();

    if data["returned"] == 0 {
        let _ = writeln!(out, "No structural matches for {pattern:?} in {lang}");
        if let Some(note) = data.get("note").and_then(Value::as_str) {
            let _ = writeln!(out, "{note}");
        }
        return out;
    }

    let _ = writeln!(
        out,
        "{total} structural match(es) for {pattern:?} in {lang} ({returned} shown)"
    );
    for file in data["files"].as_array().into_iter().flatten() {
        let _ = writeln!(out, "{}", find_text(file, "path"));
        for hit in file["hits"].as_array().into_iter().flatten() {
            let capture = hit
                .get("captured")
                .and_then(Value::as_str)
                .filter(|text| !text.is_empty());
            let _ = match capture {
                Some(captured) => writeln!(
                    out,
                    "  {}: [{}] {} — {}",
                    find_num(hit, "line"),
                    find_text(hit, "kind"),
                    collapse_whitespace(&find_text(hit, "text")),
                    captured
                ),
                None => writeln!(
                    out,
                    "  {}: [{}] {}",
                    find_num(hit, "line"),
                    find_text(hit, "kind"),
                    collapse_whitespace(&find_text(hit, "text"))
                ),
            };
        }
    }
    if data["has_more"] == true {
        let _ = writeln!(out, "… more matches: raise limit or use offset");
    }
    if let Some(note) = data.get("note").and_then(Value::as_str) {
        let _ = writeln!(out, "{note}");
    }
    out
}

/// Collapse newlines/indentation so a multi-line match stays on one row —
/// ast-grep matches whole functions, which are rarely single-line.
fn collapse_whitespace(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut last_space = false;
    for ch in text.chars() {
        if ch.is_whitespace() {
            if !last_space && !out.is_empty() {
                out.push(' ');
            }
            last_space = true;
        } else {
            out.push(ch);
            last_space = false;
        }
    }
    let trimmed = out.trim_end().to_string();
    truncate_chars(&trimmed, 160)
}