knot 1.16.0

Codebase Graph + Vector RAG Indexer for Java, TypeScript, JavaScript, Kotlin, Rust, Python, Groovy, C/C++, C#, Build Systems, and HTML/CSS codebases
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
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
//! Core find_callers logic shared between CLI and MCP
//!
//! Performs comprehensive reverse dependency lookup: given an entity name,
//! finds all other entities that reference it through any relationship type
//! (CALLS, EXTENDS, IMPLEMENTS, REFERENCES).

use std::sync::Arc;

use crate::db::graph::{DEFAULT_MAX_TARGETS, GraphDb, QueryExt};

use crate::models::RepoScope;

use crate::cli_tools::json_target_name;

use crate::cli_tools::append_signature_if_present;
use crate::cli_tools::compact_signature;
use crate::cli_tools::format_file_line;
use crate::cli_tools::resolution::{ResolutionView, overload_label};
use crate::cli_tools::search_hybrid_context::enrich::is_test_reference;
use std::collections::{BTreeSet, HashSet};

/// Name of the file-level entity holding a file's imports.
const MODULE_ENTITY: &str = "<module>";

/// How a `find_callers` Markdown answer is rendered (issue #52).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CallersFormat {
    /// List the references made from test code instead of only counting
    /// them.
    pub include_tests: bool,
}

/// Main find_callers function called by both CLI and MCP
///
/// `max_targets` raises the resolution cap (default: [`DEFAULT_MAX_TARGETS`],
/// hard ceiling: 500). `None` keeps the default — an explicit `Some(n)` is how
/// callers opt in to the full impact set when the response reports a
/// truncated target list.
///
/// `kinds` scopes the entity kinds the query may resolve against
/// ([`crate::cli_tools::kinds::KindFilter`]): `None` keeps the default
/// code-only scope (documentation/config/build metadata can never be
/// presented as resolved targets), `all` disables filtering, and any other
/// spec is an explicit alias/exact-kind list.
pub async fn run_find_callers(
    entity_name: &str,
    repo: &RepoScope,
    graph_db: &Arc<GraphDb>,
    max_targets: Option<usize>,
    kinds: Option<&str>,
) -> anyhow::Result<serde_json::Value> {
    let repo_names = repo.filter_names();
    let max_targets = max_targets.unwrap_or(DEFAULT_MAX_TARGETS);
    let references = graph_db
        .find_references(entity_name, &repo_names, max_targets, kinds)
        .await?;
    Ok(references)
}

/// The answer's buckets, in order: every relationship type the pipeline
/// produces (see `find_references_rel_labels`) plus the two OVERRIDES
/// projections, the calls that reach the target through dynamic dispatch and
/// the HTTP client calls linked to the target endpoint or handler. Empty
/// buckets are skipped, so repositories without web/VCL/macro edges render
/// exactly as before.
const REL_TYPES: &[(&str, &str)] = &[
    ("calls", "Calls (function/method invocations)"),
    ("extends", "Extends (class inheritance)"),
    ("implements", "Implements (interface implementation)"),
    ("references", "References (type annotations/usages)"),
    ("macro_calls", "Macro calls (macro invocations)"),
    ("references_dom", "DOM references (JS → HTML element id)"),
    ("uses_css_class", "CSS class usage (JS → CSS class)"),
    ("imports_script", "Script imports (HTML → JS file)"),
    ("imports_stylesheet", "Stylesheet imports (HTML → CSS file)"),
    ("uses_backend", "Backend usage (VCL)"),
    ("uses_probe", "Probe usage (VCL)"),
    ("uses_acl", "ACL usage (VCL)"),
    ("includes", "File includes (VCL)"),
    ("imports_vmod", "VMOD imports (VCL)"),
    ("declared_unused", "Declared unused (VCL)"),
    ("routes_to", "HTTP routes (endpoint → handler)"),
    ("overridden_by", "Overridden by (method implementations)"),
    ("overrides", "Overrides (declared supertype methods)"),
    (
        "dispatched_calls",
        "Dispatched calls (bound to an override or supertype method)",
    ),
    (
        "http_calls",
        "HTTP callers (heuristic: client call → endpoint)",
    ),
];

/// [`format_references_result_with`] in the default format: test code is
/// counted, not listed.
pub fn format_references_result(entity_name: &str, references: &serde_json::Value) -> String {
    format_references_result_with(entity_name, references, CallersFormat::default())
}

/// The Markdown answer of `find_callers` (issue #52):
/// - every count covers every reference, but a reference made from test
///   code is listed only with [`CallersFormat::include_tests`];
/// - an answer within one repository names it once, on the `Found` line,
///   instead of on every row;
/// - a file's `<module>` row (its import) is folded into its other rows;
/// - one line per row, with its signature on that line when it says
///   something.
pub fn format_references_result_with(
    entity_name: &str,
    references: &serde_json::Value,
    format: CallersFormat,
) -> String {
    let mut output = format!("# References to `{}`\n\n", entity_name);
    output.push_str(&format_resolution_markdown(references));

    let rel_types = REL_TYPES;

    let total_refs: usize = rel_types
        .iter()
        .filter_map(|(key, _)| references.get(key).and_then(|v| v.as_array()))
        .map(|arr| arr.len())
        .sum();

    if total_refs == 0 {
        // Three honest outcomes instead of a blanket "may be unused":
        //   targets > 0              — entity exists in scope; unused so far.
        //   targets = 0, hidden > 0  — only filtered metadata matched; say so.
        //   targets = 0, hidden = 0  — the name matched nothing at all.
        // A missing/unparseable `resolution` key (old wire shape) cannot
        // distinguish these, so it keeps the legacy wording unchanged.
        match ResolutionView::from_references(references) {
            // A truncated resolution may show zero targets while the true
            // total is large; the name still matched something in scope.
            Some(view) if view.count() > 0 || view.total_targets() > 0 => {
                output.push_str(&format!(
                    "No references found for `{}`. This entity may be unused.\n",
                    entity_name
                ))
            }
            Some(view) if !view.overload_notice(true).is_empty() => {
                output.push_str(&view.overload_notice(true));
                output.push('\n');
            }
            Some(view) if view.hidden_non_code() > 0 => output.push_str(&format!(
                "No code entity matched `{}` — see the disclosure above; the name only \
                 hit documentation/config/build metadata.\n",
                entity_name
            )),
            Some(_) => output.push_str(&format!(
                "No entity named `{}` was found in the indexed scope. \
                 Check the spelling, the repository scope (`--repo`), or search \
                 semantically with `search_hybrid_context` first.\n",
                entity_name
            )),
            None => output.push_str(&format!(
                "No references found for `{}`. This entity may be unused.\n",
                entity_name
            )),
        }
        return output;
    }

    let single_repo = single_repo(references, rel_types);
    output.push_str(&found_line(
        references,
        total_refs,
        single_repo.as_deref(),
        format,
    ));
    let style = RowStyle {
        label_repos: single_repo.is_none(),
        include_tests: format.include_tests,
    };

    // Whether the query resolved to more than one candidate. Homonym
    // attribution must be driven by the *resolution*, not by how many
    // targets happened to accumulate references: when 2 targets resolve
    // and only 1 has callers, the reader still needs to know which one.
    let mut multiple_targets = false;
    let mut overloaded = std::collections::HashSet::new();
    if let Some(view) = ResolutionView::from_references(references) {
        multiple_targets = view.count() > 1 || view.total_targets() > 1;
        overloaded = view.overloaded_fqns();

        // When the target resolution was truncated, the per-bucket counts
        // cover only the shown targets. State that explicitly (with the real
        // totals) so a sample can never be mistaken for the complete set.
        let caveat = view.partial_counts_caveat();
        if !caveat.is_empty() {
            output.push_str(&format!("> **{}**\n", caveat));
            output.push_str("> Re-run with a fully qualified name, or raise `max_targets`, for the complete set.\n\n");
        }
    }

    for &(key, label) in rel_types {
        if let Some(arr) = references.get(key).and_then(|v| v.as_array())
            && !arr.is_empty()
        {
            output.push_str(&format!("## {} ({})\n\n", label, arr.len()));
            // Dispatched calls are bound to a method other than the queried
            // one, and HTTP calls to an endpoint, so their target is always
            // named.
            output.push_str(&format_relationship_bucket(
                entity_name,
                arr,
                multiple_targets || matches!(key, "dispatched_calls" | "http_calls"),
                &overloaded,
                style,
            ));
        }
    }

    output
}

/// `Found N reference(s) …`, naming the repository of a single-repository
/// answer and the references from test code that are not listed.
fn found_line(
    references: &serde_json::Value,
    total_refs: usize,
    single_repo: Option<&str>,
    format: CallersFormat,
) -> String {
    let repo_label = single_repo
        .map(|repo| format!(" (repo: {repo})"))
        .unwrap_or_default();
    let tests = REL_TYPES
        .iter()
        .filter_map(|(key, _)| references.get(key).and_then(|v| v.as_array()))
        .flatten()
        .filter(|row| is_test_reference(row))
        .count();
    let tests_note = if tests > 0 && !format.include_tests {
        format!(" — {tests} in tests, counted but not listed (`include_tests` lists them)")
    } else {
        String::new()
    };
    format!(
        "Found {total_refs} reference(s) across all relationship types{repo_label}{tests_note}:\n\n"
    )
}

/// Render the `resolution` block (which targets the query resolved to, plus
/// fuzzy/truncation caveats) as Markdown. Empty when no block is present.
fn format_resolution_markdown(references: &serde_json::Value) -> String {
    let Some(view) = ResolutionView::from_references(references) else {
        return String::new();
    };

    let mut output = format!("{}:\n", view.summary());
    output.push_str(&view.target_bullets());
    output.push('\n');

    if view.is_fuzzy() {
        output.push_str(&format!(
            "> **Fuzzy match** — no entity matched `{}` exactly. The {} target(s) below were\n\
             > found by substring match and may be unrelated. Re-run with an exact name or a\n\
             > fully qualified name (e.g. `Namespace.Type.Member`) for precise results.\n\n",
            view.query(),
            view.count()
        ));
    }

    if view.is_truncated() {
        output.push_str(&format!(
            "> **Truncated** — {} targets matched; showing the first {} by FQN.\n\n",
            view.total_targets(),
            view.count()
        ));
    }

    let hidden = view.hidden_notice(true);
    if !hidden.is_empty() {
        // The Markdown variant already carries its own `**bold**` headline.
        output.push_str(&format!("> {hidden}\n\n"));
    }

    // When the caller overrode the default code-only scope, state it — an
    // empty-looking target list must be explainable by the reader.
    if view.count() == 0 && view.kind_filter() == "explicit" {
        output.push_str(
            "> Scope: an explicit `kinds` allow-list was applied; empty resolution means no \
             matching entity of those kinds exists in scope.\n\n",
        );
    }

    output
}

/// Render one relationship bucket, attributing each reference to the resolved
/// target it points at.
///
/// The `### Target:` header is emitted when the bucket spans more than one
/// target **or** when the query resolved to more than one target
/// (`multiple_targets`). The second condition is what keeps attribution alive
/// for homonyms where only one candidate has callers: grouping by bucket
/// content alone collapses to a single group and silently drops the header,
/// leaving the reader unable to tell which homonym is referenced.
///
/// Rows without target identity (`None` key) are never given a header — a
/// fabricated `### Target: <query> at unknown` would attribute by bare name,
/// which is precisely what the header exists to avoid. They sort first
/// (`None < Some` under `Ord`) and render directly under the bucket heading.
///
/// The grouping uses a `BTreeMap`, not a `HashMap`: iterating a `HashMap`
/// yields the `### Target:` sections in a process-random order (SipHash keys
/// are seeded per process), which made the rendered output non-reproducible
/// across runs and across nodes serving the same graph. Sorting by the group
/// key (target file path, then start line) keeps the output deterministic.
fn format_relationship_bucket(
    entity_name: &str,
    arr: &[serde_json::Value],
    multiple_targets: bool,
    overloaded: &HashSet<&str>,
    style: RowStyle,
) -> String {
    use std::collections::BTreeMap;

    let mut grouped: BTreeMap<Option<String>, Vec<&serde_json::Value>> = BTreeMap::new();
    for entity in arr {
        grouped
            .entry(target_group_key(entity))
            .or_default()
            .push(entity);
    }

    let show_targets = grouped.len() > 1 || multiple_targets;
    let mut output = String::new();

    for (target_key, entities) in grouped {
        if let Some(target_key) = target_key.filter(|_| show_targets) {
            output.push_str(&format_target_header(
                entities[0],
                entity_name,
                &target_key,
                overloaded,
                style,
            ));
        }
        output.push_str(&format_group_rows(&entities, style));
        output.push('\n');
    }

    output
}

/// How the rows of an answer are rendered.
#[derive(Debug, Clone, Copy)]
struct RowStyle {
    /// Label every row with its repository: the answer spans several.
    label_repos: bool,
    include_tests: bool,
}

/// The rows of one target's references, one line each: imports folded,
/// test code counted on a closing line unless listed.
fn format_group_rows(entities: &[&serde_json::Value], style: RowStyle) -> String {
    let files_with_rows: HashSet<&str> = entities
        .iter()
        .filter(|e| !is_module(e))
        .filter_map(|e| file_of(e))
        .collect();
    let (folded, kept): (Vec<&serde_json::Value>, Vec<&serde_json::Value>) = entities
        .iter()
        .partition(|e| is_module(e) && file_of(e).is_some_and(|f| files_with_rows.contains(f)));
    let (listed, tests): (Vec<&serde_json::Value>, Vec<&serde_json::Value>) = kept
        .into_iter()
        .partition(|e| style.include_tests || !is_test_reference(e));

    let mut output: String = listed
        .iter()
        .map(|e| format_reference_row(e, style.label_repos))
        .collect();
    let mut notes = Vec::new();
    if !tests.is_empty() {
        let more = if listed.is_empty() { "" } else { "+" };
        notes.push(format!(
            "{more}{} in tests (`include_tests` lists them)",
            tests.len()
        ));
    }
    if !folded.is_empty() {
        notes.push(format!(
            "{} import row(s) folded into the rows of their file",
            folded.len()
        ));
    }
    if !notes.is_empty() {
        output.push_str(&format!("- {}\n", notes.join("; ")));
    }
    output
}

fn file_of(entity: &serde_json::Value) -> Option<&str> {
    entity.get("file_path").and_then(|v| v.as_str())
}

fn is_module(entity: &serde_json::Value) -> bool {
    entity.get("name").and_then(|v| v.as_str()) == Some(MODULE_ENTITY)
}

/// `- **\`name\`** (kind) at \`path:line\`` and, when they say something, the
/// repository label and the one-line signature.
fn format_reference_row(entity: &serde_json::Value, label_repo: bool) -> String {
    let name = entity.get("name").and_then(|v| v.as_str()).unwrap_or("?");
    let mut row = match entity.get("kind").and_then(|v| v.as_str()) {
        Some(kind) => format!("- **`{name}`** ({kind})"),
        None => format!("- **`{name}`**"),
    };
    if let Some(file_path) = entity.get("file_path").and_then(|v| v.as_str()) {
        let path = match entity.get("start_line").and_then(|v| v.as_i64()) {
            Some(start_line) => format!("{file_path}:{start_line}"),
            None => file_path.to_string(),
        };
        let repo = entity
            .get("repo_name")
            .and_then(|v| v.as_str())
            .filter(|_| label_repo);
        row.push_str(" at ");
        row.push_str(&format_file_line(&path, repo));
    }
    if let Some(signature) = entity
        .get("signature")
        .and_then(|v| v.as_str())
        .and_then(compact_signature)
    {
        row.push_str(&format!(" — `{signature}`"));
    }
    row.push('\n');
    row
}

/// The repository every row and resolved target belongs to, when there is
/// exactly one.
fn single_repo(references: &serde_json::Value, rel_types: &[(&str, &str)]) -> Option<String> {
    let rows = rel_types
        .iter()
        .filter_map(|(key, _)| references.get(key).and_then(|v| v.as_array()))
        .flatten();
    let row_repos = rows.flat_map(|row| {
        ["repo_name", "target_repo_name"]
            .into_iter()
            .filter_map(move |field| row.get(field).and_then(|v| v.as_str()))
    });
    let target_repos = references
        .pointer("/resolution/targets")
        .and_then(|v| v.as_array())
        .into_iter()
        .flatten()
        .filter_map(|target| target.get("repo_name").and_then(|v| v.as_str()));
    let repos: BTreeSet<&str> = row_repos
        .chain(target_repos)
        .filter(|repo| !repo.is_empty())
        .collect();
    let mut repos = repos.into_iter();
    match (repos.next(), repos.next()) {
        (Some(repo), None) => Some(repo.to_string()),
        _ => None,
    }
}

/// `### Target:` section header plus the target signature line. A target
/// whose FQN is shared by another resolved target (an overload) is labelled
/// by its parameter list, `Foo.bar(int, int)` (issue #37).
fn format_target_header(
    first_entity: &serde_json::Value,
    entity_name: &str,
    target_key: &str,
    overloaded: &HashSet<&str>,
    style: RowStyle,
) -> String {
    // Prefer target_fqn when available — qualified identifiers
    // disambiguate homonyms (e.g., `WidgetA::new` vs `WidgetB::new`).
    let target_name = overload_label(
        &json_target_name(first_entity, entity_name),
        first_entity
            .get("target_name")
            .and_then(|v| v.as_str())
            .unwrap_or(""),
        first_entity
            .get("target_signature")
            .and_then(|v| v.as_str()),
        overloaded,
    );
    let target_repo = first_entity
        .get("target_repo_name")
        .and_then(|v| v.as_str())
        .filter(|_| style.label_repos);

    let mut output = format!(
        "### Target: `{}` at {}\n\n",
        target_name,
        format_file_line(target_key, target_repo)
    );

    if let Some(target_sig) = first_entity
        .get("target_signature")
        .and_then(|v| v.as_str())
        .and_then(compact_signature)
    {
        output.push_str(&format!("Signature: `{}`\n\n", target_sig));
    }

    output
}

/// Grouping key identifying the target a reference points at.
///
/// `None` when the row carries no target identity — such a row cannot be
/// attributed to a homonym and must never be rendered under a fabricated
/// `### Target:` header.
fn target_group_key(entity: &serde_json::Value) -> Option<String> {
    let target_file = entity
        .get("target_file_path")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())?;

    Some(
        match entity.get("target_start_line").and_then(|v| v.as_i64()) {
            Some(target_line) => format!("{}:{}", target_file, target_line),
            None => target_file.to_string(),
        },
    )
}

pub fn format_reference_entry(entity: &serde_json::Value) -> String {
    let mut output = String::new();

    if let Some(name) = entity.get("name").and_then(|v| v.as_str()) {
        if let Some(kind) = entity.get("kind").and_then(|v| v.as_str()) {
            output.push_str(&format!("- **`{}`** ({})", name, kind));
        } else {
            output.push_str(&format!("- **`{}`**", name));
        }
    }

    // Path rendering goes through the shared `format_file_line` helper so the
    // `(repo: ...)` annotation is appended whenever the row carries a repo.
    let repo = entity.get("repo_name").and_then(|v| v.as_str());
    if let Some(file_path) = entity.get("file_path").and_then(|v| v.as_str()) {
        let path = match entity.get("start_line").and_then(|v| v.as_i64()) {
            Some(start_line) => format!("{}:{}", file_path, start_line),
            None => file_path.to_string(),
        };
        output.push_str(" at ");
        output.push_str(&format_file_line(&path, repo));
    }

    output.push('\n');

    append_signature_if_present(&mut output, entity);

    output.push('\n');
    output
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    /// A callers row of `repo` (issue #52 fixtures).
    fn row(name: &str, kind: &str, file: &str, line: i64, repo: &str) -> serde_json::Value {
        json!({
            "name": name, "kind": kind, "file_path": file, "start_line": line,
            "repo_name": repo, "target_repo_name": repo,
            "target_fqn": "com.x.Ledger.post", "target_file_path": "src/Ledger.java",
            "target_start_line": 3
        })
    }

    fn ledger_references(calls: Vec<serde_json::Value>) -> serde_json::Value {
        json!({
            "calls": calls,
            "resolution": {
                "query": "Ledger.post", "tier": "exact_fqn", "fuzzy": false, "truncated": false,
                "total_targets": 1,
                "targets": [{"name": "post", "fqn": "com.x.Ledger.post", "kind": "method",
                             "file_path": "src/Ledger.java", "start_line": 3, "repo_name": "shop"}]
            }
        })
    }

    #[test]
    fn test_callers_are_counted_and_listed_only_on_request() {
        let mut test_row = row(
            "postsEntry",
            "method",
            "src/test/LedgerTest.java",
            9,
            "shop",
        );
        let mut rust_test = row("inline_case", "rust_function", "src/ledger.rs", 40, "shop");
        rust_test["is_test_context"] = json!(true);
        test_row["signature"] = json!("()");
        let references = ledger_references(vec![
            row("bill", "method", "src/Invoicer.java", 12, "shop"),
            test_row,
            rust_test,
        ]);

        let compact = format_references_result("Ledger.post", &references);
        assert!(compact.contains("## Calls (function/method invocations) (3)"));
        assert!(compact.contains("- **`bill`** (method) at `src/Invoicer.java:12`\n"));
        assert!(!compact.contains("postsEntry"));
        assert!(!compact.contains("inline_case"));
        assert!(compact.contains("- +2 in tests (`include_tests` lists them)\n"));
        assert!(compact.contains(
            "Found 3 reference(s) across all relationship types (repo: shop) — 2 in tests"
        ));

        let full = format_references_result_with(
            "Ledger.post",
            &references,
            CallersFormat {
                include_tests: true,
            },
        );
        assert!(full.contains("postsEntry") && full.contains("inline_case"));
        assert!(!full.contains("in tests"));
    }

    #[test]
    fn test_callers_only_in_tests_have_no_plus_sign() {
        let references = ledger_references(vec![row(
            "postsEntry",
            "method",
            "src/test/LedgerTest.java",
            9,
            "shop",
        )]);
        let formatted = format_references_result("Ledger.post", &references);
        assert!(formatted.contains("- 1 in tests (`include_tests` lists them)\n"));
    }

    #[test]
    fn test_single_repository_is_named_once() {
        let references = ledger_references(vec![
            row("bill", "method", "src/Invoicer.java", 12, "shop"),
            row("refund", "method", "src/Refunder.java", 8, "shop"),
        ]);
        let formatted = format_references_result("Ledger.post", &references);
        let rows: Vec<&str> = formatted
            .lines()
            .filter(|l| l.starts_with("- **`"))
            .collect();
        assert_eq!(rows.len(), 2);
        assert!(rows.iter().all(|r| !r.contains("(repo: ")));
        assert!(formatted.contains("across all relationship types (repo: shop):"));
        // One line per row: no blank line between them.
        assert!(formatted.contains("`src/Invoicer.java:12`\n- **`refund`**"));
    }

    #[test]
    fn test_several_repositories_label_every_row() {
        let references = ledger_references(vec![
            row("bill", "method", "src/Invoicer.java", 12, "shop"),
            row("audit", "method", "src/Audit.java", 4, "audit"),
        ]);
        let formatted = format_references_result("Ledger.post", &references);
        assert!(formatted.contains("at `src/Invoicer.java:12`  (repo: shop)"));
        assert!(formatted.contains("at `src/Audit.java:4`  (repo: audit)"));
        assert!(formatted.contains("across all relationship types:"));
    }

    #[test]
    fn test_import_rows_fold_into_their_file() {
        let references = ledger_references(vec![
            row("<module>", "function", "src/Invoicer.java", 1, "shop"),
            row("Invoicer", "class", "src/Invoicer.java", 5, "shop"),
            row("<module>", "function", "src/Unused.java", 1, "shop"),
        ]);
        let formatted = format_references_result("Ledger.post", &references);
        assert!(!formatted.contains("`<module>`** (function) at `src/Invoicer.java:1`"));
        assert!(formatted.contains("`<module>`** (function) at `src/Unused.java:1`"));
        assert!(formatted.contains("- 1 import row(s) folded into the rows of their file\n"));
    }

    #[test]
    fn test_signature_is_on_the_row_and_empty_ones_are_dropped() {
        let mut with_sig = row("bill", "method", "src/Invoicer.java", 12, "shop");
        with_sig["signature"] = json!("public void bill(\n    String id\n)");
        let mut empty_sig = row("run", "method", "src/Job.java", 3, "shop");
        empty_sig["signature"] = json!("()");
        let formatted =
            format_references_result("Ledger.post", &ledger_references(vec![with_sig, empty_sig]));
        assert!(formatted.contains("at `src/Invoicer.java:12` — `public void bill(String id)`\n"));
        assert!(formatted.contains("at `src/Job.java:3`\n"));
        assert!(!formatted.contains("Signature: `()`"));
    }

    #[test]
    fn test_format_references_result_empty() {
        let references = json!({
            "calls": [],
            "extends": [],
            "implements": [],
            "references": []
        });
        let formatted = format_references_result("MyEntity", &references);
        assert!(formatted.contains("No references found"));
    }

    #[test]
    fn test_format_references_result_with_data() {
        let references = json!({
            "calls": [
                {
                    "name": "caller1",
                    "kind": "method",
                    "file_path": "file1.java",
                    "start_line": 10,
                    "signature": "void caller1()"
                }
            ],
            "extends": [],
            "implements": [],
            "references": []
        });
        let formatted = format_references_result("MyEntity", &references);
        assert!(formatted.contains("caller1"));
        assert!(formatted.contains("file1.java:10"));
    }

    #[test]
    fn test_format_references_result_with_multiple_relationship_types() {
        let references = json!({
            "calls": [{"name": "caller1", "kind": "method", "file_path": "file1.java", "start_line": 10}],
            "extends": [{"name": "ChildClass", "kind": "class", "file_path": "file2.java", "start_line": 20}],
            "implements": [{"name": "ImplClass", "kind": "class", "file_path": "file3.java", "start_line": 30}],
            "references": [{"name": "refUser", "kind": "method", "file_path": "file4.java", "start_line": 40}]
        });
        let formatted = format_references_result("MyEntity", &references);
        assert!(formatted.contains("Found 4 reference(s)"));
        assert!(formatted.contains("Calls (function/method invocations)"));
        assert!(formatted.contains("Extends (class inheritance)"));
        assert!(formatted.contains("Implements (interface implementation)"));
        assert!(formatted.contains("References (type annotations/usages)"));
    }

    #[test]
    fn test_format_reference_entry_complete() {
        let entity = json!({
            "name": "myMethod",
            "kind": "method",
            "file_path": "src/Handler.java",
            "start_line": 42,
            "signature": "public void myMethod() throws Exception"
        });
        let formatted = format_reference_entry(&entity);
        assert!(formatted.contains("myMethod"));
        assert!(formatted.contains("method"));
        assert!(formatted.contains("src/Handler.java:42"));
        assert!(formatted.contains("public void myMethod() throws Exception"));
    }

    #[test]
    fn test_format_reference_entry_without_line_number() {
        let entity = json!({
            "name": "myMethod",
            "kind": "method",
            "file_path": "src/Handler.java"
        });
        let formatted = format_reference_entry(&entity);
        assert!(formatted.contains("myMethod"));
        assert!(formatted.contains("src/Handler.java"));
        assert!(!formatted.contains(":"));
    }

    #[test]
    fn test_format_reference_entry_without_kind() {
        let entity = json!({
            "name": "UnknownEntity",
            "file_path": "src/Unknown.java",
            "start_line": 50
        });
        let formatted = format_reference_entry(&entity);
        assert!(formatted.contains("UnknownEntity"));
        assert!(formatted.contains("src/Unknown.java:50"));
    }

    // ---- §7.2 reference repo attribution renderers ----

    #[test]
    fn format_reference_entry_appends_repo_annotation() {
        let entity = json!({
            "name": "caller1",
            "kind": "method",
            "file_path": "file1.java",
            "start_line": 10,
            "repo_name": "alpha"
        });
        let formatted = format_reference_entry(&entity);
        assert!(formatted.contains("file1.java:10"), "got {formatted}");
        assert!(formatted.contains("(repo: alpha)"), "got {formatted}");
    }

    #[test]
    fn format_reference_entry_without_repo_omits_annotation() {
        let entity = json!({
            "name": "caller1",
            "kind": "method",
            "file_path": "file1.java",
            "start_line": 10
        });
        let formatted = format_reference_entry(&entity);
        assert!(!formatted.contains("(repo:"), "got {formatted}");
    }

    #[test]
    fn format_reference_entry_with_empty_repo_omits_annotation() {
        let entity = json!({
            "name": "caller1",
            "kind": "method",
            "file_path": "file1.java",
            "start_line": 10,
            "repo_name": ""
        });
        let formatted = format_reference_entry(&entity);
        assert!(!formatted.contains("(repo:"), "got {formatted}");
    }

    #[test]
    fn target_header_labels_target_repo() {
        let references = json!({
            "calls": [
                {
                    "name": "caller1", "kind": "function",
                    "file_path": "a.rs", "start_line": 1,
                    "target_name": "find_me",
                    "target_file_path": "orphans.rs", "target_start_line": 92,
                    "repo_name": "alpha", "target_repo_name": "beta"
                },
                {
                    "name": "caller2", "kind": "function",
                    "file_path": "b.rs", "start_line": 2,
                    "target_name": "find_me",
                    "target_file_path": "rust.rs", "target_start_line": 445,
                    "repo_name": "alpha", "target_repo_name": "gamma"
                }
            ],
            "extends": [],
            "implements": [],
            "references": []
        });
        let formatted = format_references_result("find_me", &references);
        assert!(formatted.contains("### Target:"));
        assert!(formatted.contains("(repo: beta)"), "got {formatted}");
        assert!(formatted.contains("(repo: gamma)"), "got {formatted}");
    }

    #[test]
    fn test_format_references_result_only_extends() {
        let references = json!({
            "calls": [],
            "extends": [
                {"name": "ChildClass1", "kind": "class", "file_path": "file1.java", "start_line": 10},
                {"name": "ChildClass2", "kind": "class", "file_path": "file2.java", "start_line": 20}
            ],
            "implements": [],
            "references": []
        });
        let formatted = format_references_result("BaseClass", &references);
        assert!(formatted.contains("Found 2 reference(s)"));
        assert!(formatted.contains("Extends (class inheritance) (2)"));
        assert!(!formatted.contains("Calls (function/method invocations)"));
    }

    #[test]
    fn test_format_references_result_dead_code() {
        let references = json!({
            "calls": [],
            "extends": [],
            "implements": [],
            "references": []
        });
        let formatted = format_references_result("UnusedMethod", &references);
        assert!(formatted.contains("No references found"));
        assert!(formatted.contains("This entity may be unused"));
    }

    #[test]
    fn test_format_references_result_multiple_targets_same_name() {
        let references = json!({
            "calls": [
                {
                    "name": "caller1",
                    "kind": "function",
                    "file_path": "src/parser/orphans.rs",
                    "start_line": 8,
                    "target_name": "find_nearest_entity_by_line",
                    "target_file_path": "src/parser/orphans.rs",
                    "target_start_line": 92,
                    "target_signature": "pub(crate) fn find_nearest_entity_by_line(entities: &[ParsedEntity], target_line: usize) -> usize"
                },
                {
                    "name": "caller2",
                    "kind": "function",
                    "file_path": "src/parser/languages/rust.rs",
                    "start_line": 258,
                    "target_name": "find_nearest_entity_by_line",
                    "target_file_path": "src/parser/languages/rust.rs",
                    "target_start_line": 445,
                    "target_signature": "fn find_nearest_entity_by_line(entities: &[ParsedEntity], line: usize) -> usize"
                },
                {
                    "name": "caller3",
                    "kind": "function",
                    "file_path": "src/parser/orphans.rs",
                    "start_line": 175,
                    "target_name": "find_nearest_entity_by_line",
                    "target_file_path": "src/parser/orphans.rs",
                    "target_start_line": 92,
                    "target_signature": "pub(crate) fn find_nearest_entity_by_line(entities: &[ParsedEntity], target_line: usize) -> usize"
                }
            ],
            "extends": [],
            "implements": [],
            "references": []
        });

        let formatted = format_references_result("find_nearest_entity_by_line", &references);

        assert!(formatted.contains("Found 3 reference(s)"));
        assert!(formatted.contains("### Target:"));
        assert!(formatted.contains("src/parser/orphans.rs:92"));
        assert!(formatted.contains("src/parser/languages/rust.rs:445"));
        assert!(formatted.contains("pub(crate) fn find_nearest_entity_by_line"));
        assert!(formatted.contains("fn find_nearest_entity_by_line"));
        assert!(formatted.contains("caller1"));
        assert!(formatted.contains("caller2"));
        assert!(formatted.contains("caller3"));
    }

    #[test]
    fn test_format_references_result_target_order_is_deterministic() {
        // The `### Target:` sections are grouped in a BTreeMap keyed by
        // `file:line`. A HashMap here would render them in process-random
        // order (SipHash keys are seeded per process), making the output
        // non-reproducible across runs and across nodes serving the same
        // graph. Pin the sorted-by-key order.
        let references = json!({
            "calls": [
                {
                    "name": "caller_z", "kind": "function",
                    "file_path": "src/z.rs", "start_line": 1,
                    "target_name": "shared", "target_file_path": "src/zeta.rs",
                    "target_start_line": 20
                },
                {
                    "name": "caller_a", "kind": "function",
                    "file_path": "src/a.rs", "start_line": 1,
                    "target_name": "shared", "target_file_path": "src/alpha.rs",
                    "target_start_line": 5
                },
                {
                    "name": "caller_m", "kind": "function",
                    "file_path": "src/m.rs", "start_line": 1,
                    "target_name": "shared", "target_file_path": "src/mu.rs",
                    "target_start_line": 99
                }
            ],
            "extends": [],
            "implements": [],
            "references": []
        });

        let formatted = format_references_result("shared", &references);
        let alpha = formatted
            .find("src/alpha.rs:5")
            .expect("alpha target present");
        let mu = formatted.find("src/mu.rs:99").expect("mu target present");
        let zeta = formatted
            .find("src/zeta.rs:20")
            .expect("zeta target present");
        assert!(
            alpha < mu && mu < zeta,
            "targets must render sorted by file:line, not in map order"
        );
    }

    #[test]
    fn test_format_references_result_renders_override_buckets() {
        // Scenario Q3 — formatter renders the new OVERRIDES buckets.
        let references = json!({
            "calls": [],
            "extends": [],
            "implements": [],
            "references": [],
            "overridden_by": [
                {"name": "Session.getUniqueId", "kind": "groovy_method",
                 "file_path": "Session.groovy", "start_line": 26}
            ],
            "overrides": [
                {"name": "ISession.getUniqueId", "kind": "groovy_method",
                 "file_path": "ISession.groovy", "start_line": 3}
            ]
        });
        let formatted = format_references_result("getUniqueId", &references);
        assert!(formatted.contains("Found 2 reference(s)"));
        assert!(formatted.contains("Overridden by (method implementations)"));
        assert!(formatted.contains("Overrides (declared supertype methods)"));
        assert!(formatted.contains("Session.getUniqueId"));
        assert!(formatted.contains("ISession.getUniqueId"));
    }

    #[test]
    fn test_format_references_result_dispatched_calls_name_bound_method() {
        // Issue #29: a query on the interface method surfaces a caller bound
        // to the implementation, and always says which method it is bound to
        // even when the query resolved to a single target.
        let references = json!({
            "calls": [],
            "dispatched_calls": [
                {"name": "options", "kind": "method",
                 "file_path": "src/web/LookupController.java", "start_line": 12,
                 "target_name": "listOptions",
                 "target_fqn": "com.acme.DefaultLookupService.listOptions",
                 "target_file_path": "src/service/DefaultLookupService.java",
                 "target_start_line": 8}
            ],
            "resolution": {
                "query": "LookupService.listOptions",
                "tier": "fqn_suffix",
                "fuzzy": false,
                "truncated": false,
                "total_targets": 1,
                "targets": [{"fqn": "com.acme.LookupService.listOptions"}]
            }
        });
        let formatted = format_references_result("LookupService.listOptions", &references);
        assert!(formatted.contains("Found 1 reference(s)"));
        assert!(!formatted.contains("may be unused"));
        assert!(formatted.contains("Dispatched calls (bound to an override or supertype method)"));
        assert!(
            formatted.contains("### Target: `com.acme.DefaultLookupService.listOptions`"),
            "the bound method must be named:\n{formatted}"
        );
        assert!(formatted.contains("**`options`**"));
    }

    #[test]
    fn test_format_references_result_single_target_no_grouping() {
        let references = json!({
            "calls": [
                {
                    "name": "caller1",
                    "kind": "method",
                    "file_path": "file1.java",
                    "start_line": 10,
                    "target_name": "myMethod",
                    "target_file_path": "src/Handler.java",
                    "target_start_line": 42,
                    "target_signature": "public void myMethod()"
                },
                {
                    "name": "caller2",
                    "kind": "method",
                    "file_path": "file2.java",
                    "start_line": 20,
                    "target_name": "myMethod",
                    "target_file_path": "src/Handler.java",
                    "target_start_line": 42,
                    "target_signature": "public void myMethod()"
                }
            ],
            "extends": [],
            "implements": [],
            "references": []
        });

        let formatted = format_references_result("myMethod", &references);

        assert!(formatted.contains("Found 2 reference(s)"));
        assert!(!formatted.contains("### Target:"));
        assert!(formatted.contains("caller1"));
        assert!(formatted.contains("caller2"));
    }

    #[test]
    fn test_format_renders_resolution_header() {
        let references = json!({
            "calls": [{"name": "caller1", "kind": "method", "file_path": "file1.java", "start_line": 10}],
            "extends": [],
            "implements": [],
            "references": [],
            "resolution": {
                "query": "Off",
                "tier": "exact_name",
                "fuzzy": false,
                "truncated": false,
                "targets": [
                    {
                        "uuid": "uuid-123",
                        "name": "Off",
                        "fqn": "OpenLogi.Core.Gestures.GestureOwner.Off",
                        "kind": "csharp_record",
                        "file_path": "src/OpenLogi.Core/Gestures/GestureOwner.cs",
                        "start_line": 15
                    }
                ]
            }
        });
        let formatted = format_references_result("Off", &references);
        assert!(formatted.contains("Resolved to 1 target by exact name match:"));
        assert!(formatted.contains("OpenLogi.Core.Gestures.GestureOwner.Off"));
        assert!(formatted.contains("csharp_record"));
        assert!(formatted.contains("src/OpenLogi.Core/Gestures/GestureOwner.cs:15"));
    }

    #[test]
    fn test_format_renders_fuzzy_warning() {
        let references = json!({
            "calls": [{"name": "caller1", "kind": "method", "file_path": "file1.java", "start_line": 10}],
            "extends": [],
            "implements": [],
            "references": [],
            "resolution": {
                "query": "Offlin",
                "tier": "fuzzy",
                "fuzzy": true,
                "truncated": false,
                "targets": [
                    {
                        "uuid": "uuid-123",
                        "name": "OfflineSlot",
                        "fqn": "OpenLogi.Tests.Hid.InventoryDedupeTests.OfflineSlot",
                        "kind": "csharp_method",
                        "file_path": "src/OpenLogi.Tests/Hid/InventoryDedupeTests.cs",
                        "start_line": 20
                    }
                ]
            }
        });
        let formatted = format_references_result("Offlin", &references);
        assert!(formatted.contains("**Fuzzy match**"));
        assert!(formatted.contains("no entity matched `Offlin` exactly."));
    }

    #[test]
    fn test_format_renders_truncation_notice() {
        let references = json!({
            "calls": [{"name": "caller1", "kind": "method", "file_path": "file1.java", "start_line": 10}],
            "extends": [],
            "implements": [],
            "references": [],
            "resolution": {
                "query": "DuplicateName",
                "tier": "exact_name",
                "fuzzy": false,
                "truncated": true,
                "total_targets": 112,
                "targets": [
                    {
                        "uuid": "uuid-123",
                        "name": "DuplicateName",
                        "fqn": "Some.Namespace.DuplicateName",
                        "kind": "class",
                        "file_path": "src/Duplicate.java",
                        "start_line": 10
                    }
                ]
            }
        });
        let formatted = format_references_result("DuplicateName", &references);
        assert!(
            formatted.contains("**Truncated** — 112 targets matched; showing the first 1 by FQN.")
        );
    }

    #[test]
    fn test_format_without_resolution_key_is_unchanged() {
        let references = json!({
            "calls": [{"name": "caller1", "kind": "method", "file_path": "file1.java", "start_line": 10}],
            "extends": [],
            "implements": [],
            "references": []
        });
        let formatted = format_references_result("myMethod", &references);
        let expected = "# References to `myMethod`\n\n\
                        Found 1 reference(s) across all relationship types:\n\n\
                        ## Calls (function/method invocations) (1)\n\n\
                        - **`caller1`** (method) at `file1.java:10`\n\n";
        assert_eq!(formatted, expected);
    }

    // ---- §Truncation quantification (v1.10.0) ----------------------------

    /// Fixture for the bug-report scenario: one resolution target (truncated
    /// from a larger set) that accumulated 21 caller rows.
    fn truncated_resolution_with_21_callers() -> serde_json::Value {
        let calls: Vec<serde_json::Value> = (0..21)
            .map(|i| {
                json!({
                    "name": format!("caller{}", i),
                    "kind": "function",
                    "file_path": format!("src/caller_{}.rs", i),
                    "start_line": i,
                })
            })
            .collect();
        json!({
            "calls": calls,
            "extends": [],
            "implements": [],
            "references": [],
            "resolution": {
                "query": "delete",
                "tier": "exact_name",
                "fuzzy": false,
                "truncated": true,
                "total_targets": 112,
                "targets": [
                    {
                        "uuid": "uuid-1",
                        "name": "delete",
                        "fqn": "repo::module::delete",
                        "kind": "method",
                        "file_path": "src/target.rs",
                        "start_line": 1
                    }
                ]
            }
        })
    }

    #[test]
    fn format_partial_counts_caveat_is_empty_when_not_truncated() {
        // No resolution key at all.
        let bare = json!({
            "calls": [{"name": "caller1", "kind": "method", "file_path": "f.rs", "start_line": 1}],
            "extends": [],
            "implements": [],
            "references": []
        });
        let view = ResolutionView::from_references(&bare);
        if let Some(view) = view {
            assert_eq!(view.partial_counts_caveat(), "");
        }

        // Resolution present, complete.
        let complete = json!({
            "resolution": {
                "tier": "exact_name",
                "truncated": false,
                "total_targets": 3,
                "targets": [{"fqn": "A"}, {"fqn": "B"}, {"fqn": "C"}]
            }
        });
        let view = ResolutionView::from_references(&complete).expect("resolution");
        assert_eq!(view.partial_counts_caveat(), "");
    }

    #[test]
    fn format_partial_counts_caveat_uses_true_total_not_sample_size() {
        let references = json!({
            "resolution": {
                "tier": "exact_name",
                "truncated": true,
                "total_targets": 112,
                // 1 shown target; the naive post-truncation count (25) or the
                // shown count (1) must never leak in here.
                "targets": [{"fqn": "A"}]
            }
        });
        let view = ResolutionView::from_references(&references).expect("resolution");
        assert_eq!(
            view.partial_counts_caveat(),
            "Counts below are partial — they cover only the 1 of 112 targets shown."
        );
    }

    #[test]
    fn format_renders_partial_counts_caveat_when_targets_truncated() {
        // Regression for the v1.10.0 bug: `total_targets` was never emitted
        // by the DB layer, so this shape was unreachable in production and
        // bucket counts could read as the complete impact set.
        let formatted = format_references_result("delete", &truncated_resolution_with_21_callers());

        // The caveat must be machine-visible and quantified.
        assert!(
            formatted
                .contains("Counts below are partial — they cover only the 1 of 112 targets shown."),
            "got:\n{formatted}"
        );
        assert!(formatted.contains("Re-run with a fully qualified name, or raise `max_targets`"));
    }

    #[test]
    fn format_bucket_counts_remain_samples_of_the_real_thing() {
        // The bucket header states 21 (the rows actually fetched), and the
        // caveat sits right above it quantifying the incompleteness — both
        // in the same output so no reader can miss the distinction.
        let formatted = format_references_result("delete", &truncated_resolution_with_21_callers());
        assert!(formatted.contains("## Calls (function/method invocations) (21)"));
        let caveat = formatted
            .find("Counts below are partial")
            .expect("caveat present");
        let buckets = formatted.find("## Calls").expect("bucket header");
        assert!(caveat < buckets, "caveat must precede the bucket counts");
    }

    #[test]
    fn format_omits_partial_counts_caveat_when_not_truncated() {
        let references = json!({
            "calls": [
                {"name": "caller1", "kind": "method", "file_path": "file1.java", "start_line": 10},
                {"name": "caller2", "kind": "method", "file_path": "file2.java", "start_line": 20}
            ],
            "extends": [],
            "implements": [],
            "references": [],
            "resolution": {
                "query": "myMethod",
                "tier": "exact_name",
                "fuzzy": false,
                "truncated": false,
                "total_targets": 1,
                "targets": [{}]
            }
        });
        let formatted = format_references_result("myMethod", &references);
        assert!(!formatted.contains("Counts below are partial"));
        assert!(!formatted.contains("Truncated"));
    }

    #[test]
    fn format_no_references_with_truncated_resolution_still_discloses_truncation() {
        // Truncated resolution but zero references land in the shown 25: the
        // early-return branch must still be explicit about truncation.
        let references = json!({
            "calls": [],
            "extends": [],
            "implements": [],
            "references": [],
            "resolution": {
                "query": "delete",
                "tier": "exact_name",
                "fuzzy": false,
                "truncated": true,
                "total_targets": 112,
                "targets": []
            }
        });
        let formatted = format_references_result("delete", &references);
        assert!(formatted.contains("No references found"));
        assert!(formatted.contains("**Truncated** — 112 targets matched; showing the first 0"));
        // No partial-counts caveat here: there are no counts to qualify.
        assert!(!formatted.contains("Counts below are partial"));
    }

    // ---- §Homonym attribution driven by the resolution, not the bucket ----

    /// Two resolved homonyms, callers land on only one. The header must name
    /// the referenced homonym — collapsing to the headerless single-group
    /// form erased the attribution entirely.
    #[test]
    fn format_attributes_callers_when_only_one_homonym_has_them() {
        let references = json!({
            "calls": [
                {
                    "name": "handleClick",
                    "kind": "function",
                    "file_path": "src/channels/ChannelsPage.tsx",
                    "start_line": 30,
                    "target_fqn": "channels.ChannelsPage.onDelete",
                    "target_name": "onDelete",
                    "target_file_path": "src/channels/ChannelsPage.tsx",
                    "target_start_line": 20,
                    "target_signature": "function onDelete(channelId: string)"
                }
            ],
            "extends": [],
            "implements": [],
            "references": [],
            "resolution": {
                "query": "onDelete",
                "tier": "exact_name",
                "fuzzy": false,
                "truncated": false,
                "total_targets": 2,
                "targets": [
                    {
                        "fqn": "channels.ChannelsPage.onDelete",
                        "file_path": "src/channels/ChannelsPage.tsx",
                        "start_line": 20
                    },
                    {
                        "fqn": "profile.ProfilePage.onDelete",
                        "file_path": "src/profile/ProfilePage.tsx",
                        "start_line": 69
                    }
                ]
            }
        });

        let formatted = format_references_result("onDelete", &references);

        // The caller must be attributed to the homonym it actually calls.
        assert!(
            formatted.contains("### Target: `channels.ChannelsPage.onDelete`"),
            "got:\n{formatted}"
        );
        assert!(formatted.contains("src/channels/ChannelsPage.tsx:20"));
        assert!(formatted.contains("handleClick"));
        // The callerless homonym must never be attributed any callers.
        assert!(
            !formatted.contains("### Target: `profile.ProfilePage.onDelete`"),
            "callerless homonym must not be attributed:\n{formatted}"
        );
    }

    /// Truncated resolution showing one target of many: the true total
    /// (`total_targets`) alone is enough to force attribution.
    #[test]
    fn format_attributes_callers_when_resolution_truncated_to_one_shown() {
        let references = json!({
            "calls": [
                {
                    "name": "caller1",
                    "kind": "function",
                    "file_path": "src/caller.rs",
                    "start_line": 3,
                    "target_fqn": "repo::module::delete",
                    "target_name": "delete",
                    "target_file_path": "src/target.rs",
                    "target_start_line": 1
                }
            ],
            "extends": [],
            "implements": [],
            "references": [],
            "resolution": {
                "query": "delete",
                "tier": "exact_name",
                "fuzzy": false,
                "truncated": true,
                "total_targets": 112,
                "targets": [
                    {
                        "fqn": "repo::module::delete",
                        "file_path": "src/target.rs",
                        "start_line": 1
                    }
                ]
            }
        });

        let formatted = format_references_result("delete", &references);

        assert!(
            formatted.contains("### Target: `repo::module::delete`"),
            "got:\n{formatted}"
        );
        assert!(formatted.contains("src/target.rs:1"));
    }

    /// A genuinely single-target resolution keeps the concise shape — the
    /// footer of rule: header only when the resolution matched more than
    /// one candidate. Complements the no-resolution-key case above.
    #[test]
    fn format_single_resolved_target_keeps_concise_form() {
        let references = json!({
            "calls": [
                {
                    "name": "caller1",
                    "kind": "method",
                    "file_path": "file1.java",
                    "start_line": 10,
                    "target_fqn": "myapp::Handler::myMethod",
                    "target_name": "myMethod",
                    "target_file_path": "src/Handler.java",
                    "target_start_line": 42
                },
                {
                    "name": "caller2",
                    "kind": "method",
                    "file_path": "file2.java",
                    "start_line": 20,
                    "target_fqn": "myapp::Handler::myMethod",
                    "target_name": "myMethod",
                    "target_file_path": "src/Handler.java",
                    "target_start_line": 42
                }
            ],
            "extends": [],
            "implements": [],
            "references": [],
            "resolution": {
                "query": "myMethod",
                "tier": "exact_fqn",
                "fuzzy": false,
                "truncated": false,
                "total_targets": 1,
                "targets": [
                    {
                        "fqn": "myapp::Handler::myMethod",
                        "file_path": "src/Handler.java",
                        "start_line": 42
                    }
                ]
            }
        });

        let formatted = format_references_result("myMethod", &references);

        assert!(formatted.contains("Found 2 reference(s)"));
        assert!(
            !formatted.contains("### Target:"),
            "single-target resolution must stay headerless:\n{formatted}"
        );
    }

    /// The header condition applies to every relationship bucket, including
    /// the mirrored `overrides` projection.
    #[test]
    fn format_attributes_every_relationship_bucket() {
        let row = json!({
            "name": "someCaller",
            "kind": "method",
            "file_path": "src/caller.java",
            "start_line": 10,
            "target_fqn": "com.acme.MyService.myMethod",
            "target_name": "myMethod",
            "target_file_path": "src/MyService.java",
            "target_start_line": 42
        });
        let references = json!({
            "calls": [row],
            "extends": [row],
            "implements": [row],
            "references": [row],
            "overridden_by": [row],
            "overrides": [row],
            "resolution": {
                "query": "myMethod",
                "tier": "exact_name",
                "fuzzy": false,
                "truncated": false,
                "total_targets": 2,
                "targets": [
                    {"fqn": "com.acme.MyService.myMethod"},
                    {"fqn": "com.other.MyService.myMethod"}
                ]
            }
        });

        let formatted = format_references_result("myMethod", &references);

        assert!(formatted.contains("Calls (function/method invocations)"));
        assert!(formatted.contains("Extends (class inheritance)"));
        assert!(formatted.contains("Implements (interface implementation)"));
        assert!(formatted.contains("References (type annotations/usages)"));
        assert!(formatted.contains("Overridden by (method implementations)"));
        assert!(formatted.contains("Overrides (declared supertype methods)"));
        assert_eq!(
            formatted.matches("### Target:").count(),
            6,
            "every bucket must attribute its caller:\n{formatted}"
        );
    }

    /// Rows without target identity must never receive a fabricated
    /// `### Target: <query> at unknown` header, even when the resolution
    /// resolved to many targets. Attribution by bare name is exactly what
    /// the header exists to avoid.
    #[test]
    fn format_never_fabricates_target_header_without_identity() {
        let formatted = format_references_result("delete", &truncated_resolution_with_21_callers());

        assert!(
            !formatted.contains("### Target:"),
            "unattributable rows must stay headerless:\n{formatted}"
        );
        assert!(!formatted.contains("unknown"));
    }

    // ---- §Kind-filter disclosure (kind-filtered fuzzy targets) ------------

    /// Fixture for the reported bug: a fuzzy query that resolved to a large
    /// set of documentation/build entities, all filtered out by the default
    /// code-kind scope, leaving zero code targets.
    fn all_hidden_resolution() -> serde_json::Value {
        json!({
            "calls": [],
            "extends": [],
            "implements": [],
            "references": [],
            "resolution": {
                "query": "cargo",
                "tier": "fuzzy",
                "fuzzy": true,
                "truncated": false,
                "total_targets": 0,
                "kind_filter": "code_default",
                "hidden_non_code": 93,
                "hidden_kinds": [
                    "build_dependency",
                    "cargo_feature",
                    "cargo_package",
                    "markdown_section",
                    "project_identity"
                ],
                "targets": []
            }
        })
    }

    #[test]
    fn format_discloses_hidden_non_code_matches() {
        let formatted = format_references_result("cargo", &all_hidden_resolution());

        assert!(
            formatted.contains("**Non-code matches hidden** — 93 entities matched `cargo`"),
            "got:\n{formatted}"
        );
        assert!(formatted.contains("build_dependency"));
        assert!(formatted.contains("markdown_section"));
        assert!(formatted.contains("kinds=all"));
        // The blanket "may be unused" claim must not survive a hidden-only
        // resolution: it would read as if a real, dead code entity resolved.
        assert!(
            !formatted.contains("This entity may be unused"),
            "got:\n{formatted}"
        );
        // And it must not claim the entity was never found at all.
        assert!(!formatted.contains("No entity named"));
    }

    #[test]
    fn format_zero_targets_zero_hidden_says_not_found() {
        let references = json!({
            "calls": [],
            "extends": [],
            "implements": [],
            "references": [],
            "resolution": {
                "query": "no_such_thing",
                "tier": "fuzzy",
                "fuzzy": true,
                "truncated": false,
                "total_targets": 0,
                "kind_filter": "code_default",
                "hidden_non_code": 0,
                "hidden_kinds": [],
                "targets": []
            }
        });
        let formatted = format_references_result("no_such_thing", &references);

        assert!(
            formatted.contains("No entity named `no_such_thing` was found in the indexed scope"),
            "got:\n{formatted}"
        );
        assert!(!formatted.contains("This entity may be unused"));
        assert!(!formatted.contains("Non-code matches hidden"));
    }

    #[test]
    fn format_keeps_unused_wording_when_code_target_resolved() {
        // Exactly one code target, zero references: the original dead-code
        // wording is still the correct one.
        let references = json!({
            "calls": [],
            "extends": [],
            "implements": [],
            "references": [],
            "resolution": {
                "query": "legacy_fn",
                "tier": "exact_name",
                "fuzzy": false,
                "truncated": false,
                "total_targets": 1,
                "kind_filter": "code_default",
                "hidden_non_code": 0,
                "hidden_kinds": [],
                "targets": [
                    {"fqn": "app::legacy_fn", "name": "legacy_fn", "kind": "rust_function"}
                ]
            }
        });
        let formatted = format_references_result("legacy_fn", &references);

        assert!(formatted.contains("No references found for `legacy_fn`"));
        assert!(formatted.contains("This entity may be unused"));
        assert!(!formatted.contains("Non-code matches hidden"));
        assert!(!formatted.contains("No entity named"));
    }

    #[test]
    fn format_omits_hidden_notice_when_none_hidden() {
        let references = json!({
            "calls": [{"name": "caller1", "kind": "method", "file_path": "file1.java", "start_line": 10}],
            "extends": [],
            "implements": [],
            "references": [],
            "resolution": {
                "query": "myMethod",
                "tier": "exact_name",
                "fuzzy": false,
                "truncated": false,
                "total_targets": 1,
                "kind_filter": "code_default",
                "hidden_non_code": 0,
                "hidden_kinds": [],
                "targets": [{"fqn": "app.myMethod"}]
            }
        });
        let formatted = format_references_result("myMethod", &references);

        assert!(!formatted.contains("Non-code matches hidden"));
    }

    #[test]
    fn format_renders_extended_relationship_buckets() {
        // Regression coverage for the never-consulted edge types: the
        // formatter must render (and count) the new buckets.
        let references = json!({
            "calls": [],
            "extends": [],
            "implements": [],
            "references": [],
            "macro_calls": [
                {"name": "main", "kind": "rust_function", "file_path": "sample.rs", "start_line": 145}
            ],
            "references_dom": [
                {"name": "submitBtn", "kind": "rust_function", "file_path": "ui.js", "start_line": 12}
            ],
            "uses_css_class": [],
            "imports_script": [],
            "imports_stylesheet": [],
            "uses_backend": [],
            "uses_probe": [],
            "uses_acl": [],
            "includes": [],
            "imports_vmod": [],
            "declared_unused": [],
            "overridden_by": [],
            "overrides": []
        });
        let formatted = format_references_result("init_vec", &references);

        assert!(formatted.contains("Macro calls (macro invocations)"));
        assert!(formatted.contains("DOM references (JS → HTML element id)"));
        // Empty buckets are intentionally not rendered.
        assert!(!formatted.contains("CSS class usage"));
        assert!(formatted.contains("Found 2 reference(s)"));
        assert!(formatted.contains("submitBtn"));

        // CSS-class usage over an html_id target: both are *code* kinds and
        // must keep rendering under the default filter.
        let references = json!({
            "calls": [],
            "extends": [],
            "implements": [],
            "references": [],
            "references_dom": [
                {"name": "main", "kind": "rust_function", "file_path": "ui.js", "start_line": 3}
            ],
            "macro_calls": [],
            "imports_script": [],
            "imports_stylesheet": [],
            "uses_backend": [],
            "uses_probe": [],
            "uses_acl": [],
            "includes": [],
            "imports_vmod": [],
            "declared_unused": [],
        });
        let formatted = format_references_result("copybutton__status", &references);
        assert!(formatted.contains("DOM references"));
    }
}