morpharch 2.2.3

Monorepo architecture drift visualizer with animated TUI
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
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
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
//! 6-Component Scale-Aware Architecture Health Scoring Engine.
//!
//! Computes a 0-100 "Debt" score using six structural metrics.
//! Health = 100 - Debt.
//!
//! # Components (weighted sum → total debt)
//!
//! | Component       | Weight | What it Measures                               |
//! |-----------------|--------|------------------------------------------------|
//! | Cycle Debt      |  30%   | SCC count + cyclic node fraction + largest SCC |
//! | Layering Debt   |  25%   | Back-edge ratio in topological ordering        |
//! | Hub Debt        |  15%   | True god modules (high in AND out)             |
//! | Coupling Debt   |  12%   | Weighted coupling intensity via edge weights   |
//! | Cognitive Debt  |  10%   | Shannon entropy + edge excess ratio            |
//! | Instability Debt|   8%   | Refined Martin metric (leaf packages excluded) |
//!
//! # Design Philosophy
//! 1. **Scale Agnostic**: Asymptotic/logarithmic curves adapt to any codebase size.
//! 2. **Monorepo Aware**: Works identically for Deno, Turborepo, Nx, Moon, Gradle, Lage.
//! 3. **Legitimate Hubs Exempt**: High fan-in + low fan-out = shared core (no penalty).
//! 4. **Leaf Packages Exempt**: `ca=0` → `I=1.0` is natural, not brittle.
//! 5. **Edge Weights Used**: Import count drives coupling intensity measurement.

use petgraph::algo::kosaraju_scc;
use petgraph::graph::{DiGraph, NodeIndex};
use std::collections::HashMap;
use std::time::{Duration, Instant};
use tracing::debug;

use crate::config::{Exemptions, ScoringConfig, Thresholds};
use crate::models::DriftScore;

#[derive(Debug, Default, Clone, Copy)]
pub struct DriftTimings {
    pub cycle: Duration,
    pub layering: Duration,
    pub boundary_rules: Duration,
    pub hub: Duration,
    pub coupling: Duration,
    pub cognitive: Duration,
    pub instability: Duration,
    pub fan_deltas: Duration,
}

/// Legacy boundary violation rules — retained only for backward compatibility
/// with the `analyze` CLI command when no `morpharch.toml` boundaries are configured.
pub const LEGACY_BOUNDARY_RULES: &[(&str, &str)] = &[
    ("packages::", "apps::"),
    ("lib::", "apps::"),
    ("core::", "apps::"),
    ("shared::", "apps::"),
    ("packages::", "cmd::"),
    ("lib::", "cmd::"),
    ("packages/", "apps/"),
    ("libs/", "apps/"),
    ("libs/", "cli/"),
    ("ext/", "cli/"),
    ("runtime/", "cli/"),
    ("libs/", "runtime/"),
];

// ═════════════════════════════════════════════════════════════════════════════
// Component 1: Cycle Debt (Weight: 30%)
// ═════════════════════════════════════════════════════════════════════════════

/// Computes cycle debt from SCC analysis.
///
/// Three sub-factors:
/// - `cyclic_fraction` (50%): fraction of nodes trapped in non-trivial SCCs
/// - `max_scc_fraction` (30%): largest SCC as fraction of total nodes
/// - `scc_count_score` (20%): log-scaled count of SCCs
///
/// Returns (debt_0_to_100, scc_count)
fn compute_cycle_debt(graph: &DiGraph<String, u32>) -> (f64, usize) {
    let n = graph.node_count();
    if n == 0 {
        return (0.0, 0);
    }

    let sccs = kosaraju_scc(graph);
    let non_trivial: Vec<&Vec<NodeIndex>> = sccs.iter().filter(|scc| scc.len() > 1).collect();
    let scc_count = non_trivial.len();

    if scc_count == 0 {
        return (0.0, 0);
    }

    // Nodes trapped in any non-trivial SCC
    let cyclic_nodes: usize = non_trivial.iter().map(|scc| scc.len()).sum();
    let cyclic_fraction = cyclic_nodes as f64 / n as f64;

    // Largest SCC as fraction of total
    let max_scc_size = non_trivial.iter().map(|scc| scc.len()).max().unwrap_or(0);
    let max_scc_fraction = max_scc_size as f64 / n as f64;

    // Log-scaled SCC count: ln(1+count) / ln(1+N/4), capped at 1.0
    let count_score = ((1.0 + scc_count as f64).ln() / (1.0 + n as f64 / 4.0).ln()).min(1.0);

    let raw = 0.50 * cyclic_fraction + 0.30 * max_scc_fraction + 0.20 * count_score;

    // Asymptotic scaling: 100 * (1 - e^(-3 * raw))
    let debt = 100.0 * (1.0 - (-3.0 * raw).exp());
    (debt, scc_count)
}

// ═════════════════════════════════════════════════════════════════════════════
// Component 2: Layering Debt (Weight: 25%)
// ═════════════════════════════════════════════════════════════════════════════

/// Computes layering debt via structural analysis.
///
/// Measures how much the graph deviates from a clean layered (DAG) architecture.
/// Cycle debt already penalizes the EXISTENCE of cycles; layering debt penalizes
/// the DENSITY of edges that violate clean directional flow.
///
/// For each non-trivial SCC: a minimal ring needs exactly `S` edges.
/// Any edges beyond that are excess cross-cutting violations within the cycle.
///
/// Returns (debt_0_to_100, violation_count)
fn compute_layering_debt(graph: &DiGraph<String, u32>) -> (f64, usize) {
    let n = graph.node_count();
    let e = graph.edge_count();
    if n < 3 || e == 0 {
        return (0.0, 0);
    }

    let sccs = kosaraju_scc(graph);

    // Map each node → its SCC index
    let mut node_to_scc: HashMap<NodeIndex, usize> = HashMap::new();
    for (scc_idx, scc) in sccs.iter().enumerate() {
        for &node in scc {
            node_to_scc.insert(node, scc_idx);
        }
    }

    // Count internal edges per non-trivial SCC
    let mut scc_internal_edges: Vec<usize> = vec![0; sccs.len()];
    for edge_idx in graph.edge_indices() {
        let (src, tgt) = graph.edge_endpoints(edge_idx).unwrap();
        let src_scc = node_to_scc[&src];
        let tgt_scc = node_to_scc[&tgt];
        if src_scc == tgt_scc && sccs[src_scc].len() > 1 {
            scc_internal_edges[src_scc] += 1;
        }
    }

    // For each non-trivial SCC: excess edges beyond a minimal ring
    // A ring of size S needs exactly S edges. Excess = internal - S.
    // These excess edges represent additional layering violations within the cycle.
    let mut violations = 0usize;
    for (scc_idx, scc) in sccs.iter().enumerate() {
        if scc.len() > 1 {
            let internal = scc_internal_edges[scc_idx];
            violations += internal.saturating_sub(scc.len());
        }
    }

    if violations == 0 {
        return (0.0, 0);
    }

    let violation_ratio = violations as f64 / e as f64;
    // Asymptotic scaling: 100 * (1 - e^(-3 * ratio))
    let debt = 100.0 * (1.0 - (-3.0 * violation_ratio).exp());
    (debt, violations)
}

fn compute_boundary_rule_violations(graph: &DiGraph<String, u32>, config: &ScoringConfig) -> usize {
    if config.boundaries.is_empty() {
        return 0;
    }

    let mut source_rule_cache: HashMap<NodeIndex, Vec<usize>> = HashMap::new();
    for node_idx in graph.node_indices() {
        let from = &graph[node_idx];
        let matching_rules: Vec<usize> = config
            .boundaries
            .iter()
            .enumerate()
            .filter_map(|(rule_idx, rule)| rule.matches_from(from).then_some(rule_idx))
            .collect();
        if !matching_rules.is_empty() {
            source_rule_cache.insert(node_idx, matching_rules);
        }
    }

    let mut target_rule_cache: HashMap<(usize, NodeIndex), bool> = HashMap::new();
    let mut violations = 0usize;
    for edge_idx in graph.edge_indices() {
        let Some((src, tgt)) = graph.edge_endpoints(edge_idx) else {
            continue;
        };
        let Some(rule_indices) = source_rule_cache.get(&src) else {
            continue;
        };
        let to = &graph[tgt];
        if rule_indices.iter().any(|&rule_idx| {
            *target_rule_cache
                .entry((rule_idx, tgt))
                .or_insert_with(|| config.boundaries[rule_idx].matches_to(to))
        }) {
            violations += 1;
        }
    }
    violations
}

// ═════════════════════════════════════════════════════════════════════════════
// Component 3: Hub Debt (Weight: 15%)
// ═════════════════════════════════════════════════════════════════════════════

/// Computes hub/god module debt.
///
/// A **god module** is one that sits in the MIDDLE of the dependency graph with
/// both high fan-in AND high fan-out. It knows too much and is known by too many.
///
/// Two architectural patterns are explicitly EXEMPT:
/// - **Shared cores** (high in, low out): e.g., `deno_core` — ratio < 0.3
/// - **Composition roots** (low in, high out): e.g., `cli/tools` — fan_in ≤ 2
///   These are entry points / orchestrators that naturally wire things together.
///
/// Uses scale-adaptive threshold: `2·√N`.
fn compute_hub_debt(
    graph: &DiGraph<String, u32>,
    thresholds: &Thresholds,
    exemptions: &Exemptions,
) -> f64 {
    let n = graph.node_count();
    if n < 6 {
        return 0.0;
    }

    let threshold = (2.0 * (n as f64).sqrt()).max(8.0);
    let mut total_god_penalty = 0.0f64;
    let mut god_count = 0u32;

    for node_idx in graph.node_indices() {
        let module_name = &graph[node_idx];

        // Explicit exemption by name
        if exemptions
            .hub_exempt
            .iter()
            .any(|e| module_name.contains(e.as_str()))
        {
            continue;
        }

        // ── Exemption: Named entry point stems ──
        // Modules whose file stem matches a configured entry point (e.g., "main",
        // "index", "app") are composition roots by definition — not god modules.
        if is_entry_point_stem(module_name, &exemptions.entry_point_stems) {
            continue;
        }

        let fan_in = graph
            .neighbors_directed(node_idx, petgraph::Direction::Incoming)
            .count();
        let fan_out = graph
            .neighbors_directed(node_idx, petgraph::Direction::Outgoing)
            .count();
        let total_degree = fan_in + fan_out;

        if (total_degree as f64) < threshold {
            continue;
        }

        // Hub ratio: how much does this module export vs import?
        let hub_ratio = fan_out as f64 / (fan_in as f64 + 1.0);

        // ── Exemption: Legitimate shared core ──
        // High fan-in, low fan-out (e.g., deno_core: 42 in, 3 out → ratio = 0.07)
        if hub_ratio < thresholds.hub_exemption_ratio {
            continue;
        }

        // ── Exemption: Composition root by fan-in threshold ──
        // Zero or very low fan-in means this is a top-level orchestrator, not a god
        // module. cli/tools (0 in, 46 out) is an entry point, not an anti-pattern.
        if fan_in <= thresholds.entry_point_max_fan_in {
            continue;
        }

        // At this point: module has high fan-in AND high fan-out → true god module
        // Excess ratio: how far above threshold
        let excess_ratio = (total_degree as f64 - threshold) / threshold;

        // Weight multiplier based on coupling strength via edge weights
        let weighted_degree: u32 = graph
            .edges_directed(node_idx, petgraph::Direction::Incoming)
            .map(|e| *e.weight())
            .sum::<u32>()
            + graph
                .edges_directed(node_idx, petgraph::Direction::Outgoing)
                .map(|e| *e.weight())
                .sum::<u32>();
        let weight_multiplier =
            (weighted_degree as f64 / total_degree.max(1) as f64 / 2.0).clamp(0.5, 2.0);

        let penalty = excess_ratio * weight_multiplier * hub_ratio.min(1.0);
        total_god_penalty += penalty;
        god_count += 1;
    }

    if god_count == 0 {
        return 0.0;
    }

    // Scale: multiple god modules compound
    let raw = (total_god_penalty / god_count as f64) * (1.0 + 0.3 * (god_count - 1) as f64);
    // Asymptotic: 100 * (1 - e^(-2 * raw))
    (100.0 * (1.0 - (-2.0 * raw).exp())).min(100.0)
}

// ═════════════════════════════════════════════════════════════════════════════
// Component 4: Coupling Debt (Weight: 12%)
// ═════════════════════════════════════════════════════════════════════════════

/// Computes coupling debt using log-dampened edge weights.
///
/// Edge weights can vary wildly (1 vs 234) which makes raw sums misleading.
/// We apply `ln(1 + w)` to each weight before aggregation — this respects
/// that w=234 is heavier than w=1, but not 234× heavier.
///
/// Two sub-factors:
/// - Log-dampened density excess (60%): Σ(ln(1+w))/N vs expected `3.0 + 2·ln(N)`
/// - Weight concentration (40%): coefficient of variation of log-dampened weights
fn compute_coupling_debt(graph: &DiGraph<String, u32>) -> f64 {
    let n = graph.node_count();
    let e = graph.edge_count();
    if n < 3 || e == 0 {
        return 0.0;
    }

    // Log-dampened weights: ln(1 + w) compresses extreme outliers
    let log_weights: Vec<f64> = graph
        .edge_indices()
        .map(|ei| (1.0 + graph[ei] as f64).ln())
        .collect();
    let total_log_weight: f64 = log_weights.iter().sum();
    let log_density = total_log_weight / n as f64;

    // Expected density adapts to scale: 3.0 + 2·ln(N)
    // Real monorepos naturally have higher connectivity than 3+ln(N)
    let expected = 3.0 + 2.0 * (n as f64).ln();
    let density_excess = ((log_density - expected).max(0.0) / expected).min(1.0);

    // Weight concentration: CV of log-dampened weights
    let mean_log = total_log_weight / e as f64;
    let variance: f64 = log_weights
        .iter()
        .map(|w| (w - mean_log).powi(2))
        .sum::<f64>()
        / e as f64;
    let std_dev = variance.sqrt();
    let cv = if mean_log > 0.0 {
        std_dev / mean_log
    } else {
        0.0
    };
    // High CV means extreme coupling outliers even after log dampening
    let concentration = (cv / 2.0).min(1.0);

    let raw = 0.60 * density_excess + 0.40 * concentration;
    // Asymptotic: 100 * (1 - e^(-3 * raw))
    100.0 * (1.0 - (-3.0 * raw).exp())
}

// ═════════════════════════════════════════════════════════════════════════════
// Component 5: Cognitive Debt (Weight: 10%)
// ═════════════════════════════════════════════════════════════════════════════

/// Computes cognitive debt — how hard the dependency graph is to reason about.
///
/// Real software isn't a tree. A module typically has 2-4 dependencies, so
/// the natural baseline is ~2N edges (not N-1). We measure excess above that.
///
/// Two sub-factors:
/// - Edge excess ratio: E / 2N, penalized only when > 1.0 (more than 2 deps avg)
/// - Degree excess: avg degree vs 2·ln(N), penalized only when above that
fn compute_cognitive_debt(graph: &DiGraph<String, u32>) -> f64 {
    let n = graph.node_count();
    let e = graph.edge_count();
    if n < 3 {
        return 0.0;
    }

    // Edge excess: how many more edges than a realistic baseline (2N)
    // A module having ~2 dependencies on average is normal for real software
    let baseline_edges = 2 * n;
    let edge_excess = if baseline_edges > 0 {
        ((e as f64 / baseline_edges as f64) - 1.0).max(0.0)
    } else {
        0.0
    };
    // 3x the baseline = fully saturated (6N edges would be extreme)
    let excess_ratio = (edge_excess / 2.0).min(1.0);

    // Average degree vs expected: 2·ln(N) is a reasonable expectation
    // for well-structured software (slightly more interconnected than sparse)
    let avg_degree = if n > 0 {
        2.0 * e as f64 / n as f64
    } else {
        0.0
    };
    let expected_avg = (2.0 * (n as f64).ln()).max(3.0);
    let degree_excess = ((avg_degree / expected_avg) - 1.0).clamp(0.0, 1.0);

    // Scale factor: soften penalties for small graphs where ratios are misleading
    let scale = 1.0 - (-(n as f64) / 20.0).exp();

    let raw = (0.50 * excess_ratio + 0.50 * degree_excess) * scale;
    // Asymptotic: 100 * (1 - e^(-3 * raw))
    100.0 * (1.0 - (-3.0 * raw).exp())
}

// ═════════════════════════════════════════════════════════════════════════════
// Component 6: Instability Debt (Weight: 8%)
// ═════════════════════════════════════════════════════════════════════════════

/// Computes instability debt using refined Martin metric.
///
/// Key fix: Excludes leaf packages (ca=0) which naturally have I=1.0.
/// Only penalizes non-leaf brittle modules: I > threshold AND fan_in > 0 AND degree ≥ 3.
fn compute_instability_debt(
    graph: &DiGraph<String, u32>,
    thresholds: &Thresholds,
    exemptions: &Exemptions,
) -> f64 {
    let n = graph.node_count();
    if n < 3 {
        return 0.0;
    }

    let mut brittle_count = 0usize;
    let mut eligible_count = 0usize;

    for node_idx in graph.node_indices() {
        let module_name = &graph[node_idx];

        // Explicit exemption by name
        if exemptions
            .instability_exempt
            .iter()
            .any(|e| module_name.contains(e.as_str()))
        {
            continue;
        }

        // Entry point stems are exempt — they naturally have high fan-out
        if is_entry_point_stem(module_name, &exemptions.entry_point_stems) {
            continue;
        }

        let ca = graph
            .neighbors_directed(node_idx, petgraph::Direction::Incoming)
            .count();
        let ce = graph
            .neighbors_directed(node_idx, petgraph::Direction::Outgoing)
            .count();
        let total = ca + ce;

        // Skip isolated nodes and low-connectivity nodes
        if total < 3 {
            continue;
        }

        // Skip leaf packages: ca=0 naturally produces I=1.0, which is not brittle
        if ca == 0 {
            continue;
        }

        eligible_count += 1;

        let instability = ce as f64 / total as f64;
        if instability > thresholds.brittle_instability_ratio {
            brittle_count += 1;
        }
    }

    if eligible_count == 0 {
        return 0.0;
    }

    let brittle_ratio = brittle_count as f64 / eligible_count as f64;

    // Scale factor for small graphs (softens penalty)
    let scale = 1.0 - (-(n as f64) / 30.0).exp();

    let raw = brittle_ratio * scale;
    // Asymptotic: 100 * (1 - e^(-3 * raw))
    100.0 * (1.0 - (-3.0 * raw).exp())
}

// ═════════════════════════════════════════════════════════════════════════════
// Fan Delta Computation (Median-based)
// ═════════════════════════════════════════════════════════════════════════════

/// Computes median fan-in and fan-out deltas between current and previous graph.
///
/// Uses median (not max) for robustness against outliers.
fn compute_fan_deltas(
    graph: &DiGraph<String, u32>,
    prev_graph: Option<&DiGraph<String, u32>>,
) -> (i32, i32) {
    let prev = match prev_graph {
        Some(p) => p,
        None => return (0, 0),
    };

    // Build name → (fan_in, fan_out) maps
    let current_map = build_fan_map(graph);
    let prev_map = build_fan_map(prev);

    let mut in_deltas: Vec<i32> = Vec::new();
    let mut out_deltas: Vec<i32> = Vec::new();

    for (name, (cur_in, cur_out)) in &current_map {
        if let Some(&(prev_in, prev_out)) = prev_map.get(name) {
            in_deltas.push(*cur_in as i32 - prev_in as i32);
            out_deltas.push(*cur_out as i32 - prev_out as i32);
        }
    }

    (median_i32(&mut in_deltas), median_i32(&mut out_deltas))
}

fn build_fan_map(graph: &DiGraph<String, u32>) -> HashMap<String, (usize, usize)> {
    let mut map = HashMap::new();
    for node_idx in graph.node_indices() {
        let fan_in = graph
            .neighbors_directed(node_idx, petgraph::Direction::Incoming)
            .count();
        let fan_out = graph
            .neighbors_directed(node_idx, petgraph::Direction::Outgoing)
            .count();
        map.insert(graph[node_idx].clone(), (fan_in, fan_out));
    }
    map
}

fn median_i32(values: &mut [i32]) -> i32 {
    if values.is_empty() {
        return 0;
    }
    values.sort_unstable();
    let mid = values.len() / 2;
    if values.len().is_multiple_of(2) {
        // Use i64 intermediary to avoid i32 overflow on addition
        ((values[mid - 1] as i64 + values[mid] as i64) / 2) as i32
    } else {
        values[mid]
    }
}

// ═════════════════════════════════════════════════════════════════════════════
// Public API: Instability Metrics (used by TUI hotspots table)
// ═════════════════════════════════════════════════════════════════════════════

/// Computes per-node instability index (I = Ce / (Ca + Ce)).
/// Returns (Module Name, Instability, Fan-in (Ca), Fan-out (Ce))
pub fn compute_instability_metrics(
    graph: &DiGraph<String, u32>,
) -> Vec<(String, f64, usize, usize)> {
    let mut metrics = Vec::new();
    for node_idx in graph.node_indices() {
        let ca = graph
            .neighbors_directed(node_idx, petgraph::Direction::Incoming)
            .count();
        let ce = graph
            .neighbors_directed(node_idx, petgraph::Direction::Outgoing)
            .count();
        let instability = if ca + ce > 0 {
            ce as f64 / (ca + ce) as f64
        } else {
            0.0
        };
        metrics.push((graph[node_idx].clone(), instability, ca, ce));
    }
    // Sort primarily by highest fan-out + fan-in (most active modules), then by instability
    metrics.sort_by(|a, b| {
        let total_b = b.2 + b.3;
        let total_a = a.2 + a.3;
        total_b
            .cmp(&total_a)
            .then(b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal))
    });
    metrics
}

// ═════════════════════════════════════════════════════════════════════════════
// Main Scoring Function
// ═════════════════════════════════════════════════════════════════════════════

/// Calculates the absolute architectural debt score (0-100).
/// 0 debt = 100% Health.
///
/// Uses 6-component weighted sum with configurable weights.
/// When called with `ScoringConfig::default()`, produces identical results
/// to the original hardcoded engine.
pub fn calculate_drift(
    graph: &DiGraph<String, u32>,
    prev_graph: Option<&DiGraph<String, u32>>,
    timestamp: i64,
    config: &ScoringConfig,
) -> DriftScore {
    let n = graph.node_count();

    if n == 0 {
        return DriftScore {
            total: 0,
            fan_in_delta: 0,
            fan_out_delta: 0,
            new_cycles: 0,
            boundary_violations: 0,
            layering_violations: 0,
            cognitive_complexity: 0.0,
            timestamp,
            cycle_debt: 0.0,
            layering_debt: 0.0,
            hub_debt: 0.0,
            coupling_debt: 0.0,
            cognitive_debt: 0.0,
            instability_debt: 0.0,
        };
    }

    // ── Compute all 6 components ──
    let (cycle_score, scc_count) = compute_cycle_debt(graph);
    let (structural_layering_score, layering_violations) = compute_layering_debt(graph);
    let boundary_violations = compute_boundary_rule_violations(graph, config);
    let boundary_rule_score = if graph.edge_count() == 0 || boundary_violations == 0 {
        0.0
    } else {
        let ratio = boundary_violations as f64 / graph.edge_count() as f64;
        100.0 * (1.0 - (-3.0 * ratio).exp())
    };
    let layering_score = structural_layering_score.max(boundary_rule_score);
    let hub_score = compute_hub_debt(graph, &config.thresholds, &config.exemptions);
    let coupling_score = compute_coupling_debt(graph);
    let cognitive_score = compute_cognitive_debt(graph);
    let instability_score = compute_instability_debt(graph, &config.thresholds, &config.exemptions);

    // ── Weighted sum (normalized weights) ──
    let w = config.weights.normalized();
    let total_debt = (w.cycle * cycle_score
        + w.layering * layering_score
        + w.hub * hub_score
        + w.coupling * coupling_score
        + w.cognitive * cognitive_score
        + w.instability * instability_score)
        .round()
        .min(100.0) as u8;

    // ── Fan deltas (median-based) ──
    let (fan_in_delta, fan_out_delta) = compute_fan_deltas(graph, prev_graph);

    // ── Cognitive complexity (real entropy-based value) ──
    let cog_complexity = (cognitive_score * 10.0).round() / 10.0;

    debug!(
        total_debt,
        cycle_score,
        layering_score,
        structural_layering_score,
        boundary_rule_score,
        hub_score,
        coupling_score,
        cognitive_score,
        instability_score,
        "Architectural Health assessment complete"
    );

    DriftScore {
        total: total_debt,
        fan_in_delta,
        fan_out_delta,
        new_cycles: scc_count,
        boundary_violations,
        layering_violations,
        cognitive_complexity: cog_complexity,
        timestamp,
        cycle_debt: (cycle_score * 10.0).round() / 10.0,
        layering_debt: (layering_score * 10.0).round() / 10.0,
        hub_debt: (hub_score * 10.0).round() / 10.0,
        coupling_debt: (coupling_score * 10.0).round() / 10.0,
        cognitive_debt: (cognitive_score * 10.0).round() / 10.0,
        instability_debt: (instability_score * 10.0).round() / 10.0,
    }
}

pub fn calculate_drift_profiled(
    graph: &DiGraph<String, u32>,
    prev_graph: Option<&DiGraph<String, u32>>,
    timestamp: i64,
    config: &ScoringConfig,
) -> (DriftScore, DriftTimings) {
    let mut timings = DriftTimings::default();
    let n = graph.node_count();

    if n == 0 {
        return (
            DriftScore {
                total: 0,
                fan_in_delta: 0,
                fan_out_delta: 0,
                new_cycles: 0,
                boundary_violations: 0,
                layering_violations: 0,
                cognitive_complexity: 0.0,
                timestamp,
                cycle_debt: 0.0,
                layering_debt: 0.0,
                hub_debt: 0.0,
                coupling_debt: 0.0,
                cognitive_debt: 0.0,
                instability_debt: 0.0,
            },
            timings,
        );
    }

    let cycle_start = Instant::now();
    let (cycle_score, scc_count) = compute_cycle_debt(graph);
    timings.cycle += cycle_start.elapsed();

    let layering_start = Instant::now();
    let (structural_layering_score, layering_violations) = compute_layering_debt(graph);
    timings.layering += layering_start.elapsed();

    let boundary_start = Instant::now();
    let boundary_violations = compute_boundary_rule_violations(graph, config);
    timings.boundary_rules += boundary_start.elapsed();

    let boundary_rule_score = if graph.edge_count() == 0 || boundary_violations == 0 {
        0.0
    } else {
        let ratio = boundary_violations as f64 / graph.edge_count() as f64;
        100.0 * (1.0 - (-3.0 * ratio).exp())
    };
    let layering_score = structural_layering_score.max(boundary_rule_score);

    let hub_start = Instant::now();
    let hub_score = compute_hub_debt(graph, &config.thresholds, &config.exemptions);
    timings.hub += hub_start.elapsed();

    let coupling_start = Instant::now();
    let coupling_score = compute_coupling_debt(graph);
    timings.coupling += coupling_start.elapsed();

    let cognitive_start = Instant::now();
    let cognitive_score = compute_cognitive_debt(graph);
    timings.cognitive += cognitive_start.elapsed();

    let instability_start = Instant::now();
    let instability_score = compute_instability_debt(graph, &config.thresholds, &config.exemptions);
    timings.instability += instability_start.elapsed();

    let w = config.weights.normalized();
    let total_debt = (w.cycle * cycle_score
        + w.layering * layering_score
        + w.hub * hub_score
        + w.coupling * coupling_score
        + w.cognitive * cognitive_score
        + w.instability * instability_score)
        .round()
        .min(100.0) as u8;

    let fan_delta_start = Instant::now();
    let (fan_in_delta, fan_out_delta) = compute_fan_deltas(graph, prev_graph);
    timings.fan_deltas += fan_delta_start.elapsed();

    let cog_complexity = (cognitive_score * 10.0).round() / 10.0;

    debug!(
        total_debt,
        cycle_score,
        layering_score,
        structural_layering_score,
        boundary_rule_score,
        hub_score,
        coupling_score,
        cognitive_score,
        instability_score,
        "Architectural Health assessment complete"
    );

    (
        DriftScore {
            total: total_debt,
            fan_in_delta,
            fan_out_delta,
            new_cycles: scc_count,
            boundary_violations,
            layering_violations,
            cognitive_complexity: cog_complexity,
            timestamp,
            cycle_debt: (cycle_score * 10.0).round() / 10.0,
            layering_debt: (layering_score * 10.0).round() / 10.0,
            hub_debt: (hub_score * 10.0).round() / 10.0,
            coupling_debt: (coupling_score * 10.0).round() / 10.0,
            cognitive_debt: (cognitive_score * 10.0).round() / 10.0,
            instability_debt: (instability_score * 10.0).round() / 10.0,
        },
        timings,
    )
}

// ═════════════════════════════════════════════════════════════════════════════
// Helpers
// ═════════════════════════════════════════════════════════════════════════════

fn count_cycles(graph: &DiGraph<String, u32>) -> usize {
    kosaraju_scc(graph)
        .iter()
        .filter(|scc| scc.len() > 1)
        .count()
}

pub fn count_cycles_public(graph: &DiGraph<String, u32>) -> usize {
    count_cycles(graph)
}

/// Extracts the members of each non-trivial SCC (strongly-connected component).
///
/// Returns groups sorted by size descending. Each group contains module names
/// sorted alphabetically. Only SCCs with 2+ members are included.
pub fn extract_scc_members(graph: &DiGraph<String, u32>) -> Vec<Vec<String>> {
    let sccs = kosaraju_scc(graph);
    let mut groups: Vec<Vec<String>> = sccs
        .into_iter()
        .filter(|scc| scc.len() > 1)
        .map(|scc| {
            let mut names: Vec<String> = scc.iter().map(|&idx| graph[idx].clone()).collect();
            names.sort();
            names
        })
        .collect();
    groups.sort_by_key(|g| std::cmp::Reverse(g.len()));
    groups
}

pub fn edges_to_pairs(edges: &[crate::models::DependencyEdge]) -> Vec<(String, String)> {
    edges
        .iter()
        .map(|e| (e.from_module.clone(), e.to_module.clone()))
        .collect()
}

/// Returns `true` if the module name's file stem matches any configured entry point stem.
///
/// Example: `"cli/tools"` → stem `"tools"`, `"src/main.rs"` → stem `"main"`.
fn is_entry_point_stem(module_name: &str, stems: &[String]) -> bool {
    let basename = module_name.split('/').next_back().unwrap_or(module_name);
    let stem = basename.split('.').next().unwrap_or(basename);
    stems.iter().any(|s| s == stem)
}

// ═════════════════════════════════════════════════════════════════════════════
// Component Diagnostics (for TUI advisory display)
// ═════════════════════════════════════════════════════════════════════════════

/// Generates human-friendly advisory lines explaining WHY each elevated component
/// contributes to architectural debt. Designed for non-expert users — uses plain
/// language, names specific modules, and suggests actionable next steps.
///
/// Called from TUI to populate the ADVISORY section in the Health tab.
pub fn generate_diagnostics(
    graph: &DiGraph<String, u32>,
    drift: &crate::models::DriftScore,
    config: &ScoringConfig,
) -> Vec<String> {
    let mut lines = Vec::new();
    let n = graph.node_count();
    let e = graph.edge_count();

    // ── Cycle diagnostics ──
    if drift.cycle_debt > 10.0 {
        let sccs = kosaraju_scc(graph);
        let non_trivial: Vec<_> = sccs.iter().filter(|scc| scc.len() > 1).collect();
        if !non_trivial.is_empty() {
            let largest = non_trivial.iter().map(|s| s.len()).max().unwrap_or(0);
            let cyclic_nodes: usize = non_trivial.iter().map(|s| s.len()).sum();
            if non_trivial.len() == 1 {
                lines.push(format!(
                    "{} modules form a circular dependency chain. \
                     Break the cycle with interfaces or traits.",
                    cyclic_nodes
                ));
            } else {
                lines.push(format!(
                    "{} circular dependency groups found ({} modules involved, \
                     largest spans {}). Consider dependency inversion.",
                    non_trivial.len(),
                    cyclic_nodes,
                    largest
                ));
            }
        }
    }

    // ── Layering diagnostics ──
    if drift.layering_debt > 10.0 && drift.layering_violations > 0 {
        let count = drift.layering_violations;
        if count == 1 {
            lines.push(
                "1 extra cross-cutting edge inside a cycle. \
                 Simplifying internal wiring would improve clarity."
                    .to_string(),
            );
        } else {
            lines.push(format!(
                "{} extra edges inside dependency cycles make the \
                 structure harder to follow. Simplify internal wiring.",
                count
            ));
        }
    }

    if drift.boundary_violations > 0 {
        if drift.boundary_violations == 1 {
            lines.push(
                "1 configured package boundary is being crossed. Tighten module ownership."
                    .to_string(),
            );
        } else {
            lines.push(format!(
                "{} configured package boundaries are being crossed. Review the violating edges.",
                drift.boundary_violations
            ));
        }
    }

    // ── Hub diagnostics ──
    // Only show truly problematic god modules (high in AND out, not composition roots)
    if drift.hub_debt > 10.0 {
        let threshold = (2.0 * (n as f64).sqrt()).max(8.0);
        let mut hubs: Vec<(String, usize, usize)> = Vec::new();
        for node_idx in graph.node_indices() {
            let module_name = &graph[node_idx];
            if config
                .exemptions
                .hub_exempt
                .iter()
                .any(|e| module_name.contains(e.as_str()))
            {
                continue;
            }
            let fi = graph
                .neighbors_directed(node_idx, petgraph::Direction::Incoming)
                .count();
            let fo = graph
                .neighbors_directed(node_idx, petgraph::Direction::Outgoing)
                .count();
            let total = fi + fo;
            if total as f64 >= threshold {
                let ratio = fo as f64 / (fi as f64 + 1.0);
                // Match scoring: skip shared cores and composition roots
                if ratio >= config.thresholds.hub_exemption_ratio
                    && fi > config.thresholds.entry_point_max_fan_in
                {
                    hubs.push((graph[node_idx].clone(), fi, fo));
                }
            }
        }
        hubs.sort_by(|a, b| (b.1 + b.2).cmp(&(a.1 + a.2)));
        for (name, fi, fo) in hubs.iter().take(2) {
            lines.push(format!(
                "{} has {} incoming and {} outgoing deps — \
                 it's doing too much. Split responsibilities.",
                name, fi, fo
            ));
        }
    }

    // ── Coupling diagnostics ──
    if drift.coupling_debt > 10.0 {
        // Use log-dampened density consistent with scoring formula
        let total_log_w: f64 = graph
            .edge_indices()
            .map(|ei| (1.0 + graph[ei] as f64).ln())
            .sum();
        let log_density = total_log_w / n.max(1) as f64;
        let expected = 3.0 + 2.0 * (n as f64).ln();

        // Find heaviest edge
        let mut heaviest = ("?".to_string(), "?".to_string(), 0u32);
        for edge_idx in graph.edge_indices() {
            let w = graph[edge_idx];
            if w > heaviest.2 {
                let (src, tgt) = graph.edge_endpoints(edge_idx).unwrap();
                heaviest = (graph[src].clone(), graph[tgt].clone(), w);
            }
        }

        let ratio = log_density / expected;
        if ratio > 1.5 {
            lines.push(format!(
                "Modules are more tightly connected than expected ({:.1}x). \
                 Introduce abstractions to reduce direct dependencies.",
                ratio
            ));
        } else {
            lines.push(
                "Some modules share more dependencies than expected. \
                 Review coupling and consider interfaces."
                    .to_string(),
            );
        }

        if heaviest.2 > 5 {
            lines.push(format!(
                "Strongest link: {} \u{2192} {} ({} imports). \
                 This tight binding makes both harder to change.",
                heaviest.0, heaviest.1, heaviest.2
            ));
        }
    }

    // ── Cognitive diagnostics ──
    if drift.cognitive_debt > 10.0 {
        // Use 2N baseline consistent with scoring formula
        let baseline = 2 * n;
        let pct = if baseline > 0 {
            (((e as f64 / baseline as f64) - 1.0) * 100.0).round() as i32
        } else {
            0
        };
        if pct > 0 {
            lines.push(format!(
                "The graph has {}% more connections than typical. \
                 Fewer links would make the architecture easier to reason about.",
                pct
            ));
        }
    }

    // ── Instability diagnostics ──
    if drift.instability_debt > 10.0 {
        let mut brittle_names: Vec<String> = Vec::new();
        let mut eligible = 0usize;
        for node_idx in graph.node_indices() {
            let module_name = &graph[node_idx];
            if config
                .exemptions
                .instability_exempt
                .iter()
                .any(|e| module_name.contains(e.as_str()))
            {
                continue;
            }
            let ca = graph
                .neighbors_directed(node_idx, petgraph::Direction::Incoming)
                .count();
            let ce = graph
                .neighbors_directed(node_idx, petgraph::Direction::Outgoing)
                .count();
            if ca + ce >= 3 && ca > 0 {
                eligible += 1;
                if ce as f64 / (ca + ce) as f64 > config.thresholds.brittle_instability_ratio {
                    let name = graph[node_idx].clone();
                    let basename = name.split('/').next_back().unwrap_or(&name);
                    let stem = basename.split('.').next().unwrap_or(basename);
                    let is_entry = config
                        .exemptions
                        .entry_point_stems
                        .iter()
                        .any(|s| s == stem);

                    if !is_entry {
                        brittle_names.push(name);
                    }
                }
            }
        }
        if !brittle_names.is_empty() {
            if brittle_names.len() <= 3 {
                lines.push(format!(
                    "{} fragile: depends on many others but few depend on \
                     it. Changes upstream will likely cascade here.",
                    brittle_names.join(", ")
                ));
            } else {
                lines.push(format!(
                    "{} of {} core modules are fragile — they depend heavily \
                     on others. Stabilize with dependency injection.",
                    brittle_names.len(),
                    eligible
                ));
            }
        }
    }

    lines
}

// =============================================================================
// AI Context Extraction — detailed breakdowns for the AI assistant
// =============================================================================

/// Detailed breakdown of cognitive debt sub-factors.
#[derive(Debug, Clone)]
pub struct CognitiveDebtDetail {
    pub score: f64,
    pub edge_excess_ratio: f64,
    pub degree_excess: f64,
    pub avg_degree: f64,
    pub expected_avg_degree: f64,
    pub baseline_edges: usize,
    pub actual_edges: usize,
    pub scale_factor: f64,
}

/// Extracts cognitive debt breakdown for AI context.
pub fn extract_cognitive_detail(graph: &DiGraph<String, u32>) -> CognitiveDebtDetail {
    let n = graph.node_count();
    let e = graph.edge_count();
    if n < 3 {
        return CognitiveDebtDetail {
            score: 0.0,
            edge_excess_ratio: 0.0,
            degree_excess: 0.0,
            avg_degree: 0.0,
            expected_avg_degree: 0.0,
            baseline_edges: 0,
            actual_edges: e,
            scale_factor: 0.0,
        };
    }

    let baseline_edges = 2 * n;
    let edge_excess = if baseline_edges > 0 {
        ((e as f64 / baseline_edges as f64) - 1.0).max(0.0)
    } else {
        0.0
    };
    let excess_ratio = (edge_excess / 2.0).min(1.0);

    let avg_degree = 2.0 * e as f64 / n as f64;
    let expected_avg = (2.0 * (n as f64).ln()).max(3.0);
    let degree_excess = ((avg_degree / expected_avg) - 1.0).clamp(0.0, 1.0);

    let scale = 1.0 - (-(n as f64) / 20.0).exp();
    let raw = (0.50 * excess_ratio + 0.50 * degree_excess) * scale;
    let score = 100.0 * (1.0 - (-3.0 * raw).exp());

    CognitiveDebtDetail {
        score,
        edge_excess_ratio: (excess_ratio * 100.0).round() / 100.0,
        degree_excess: (degree_excess * 100.0).round() / 100.0,
        avg_degree: (avg_degree * 100.0).round() / 100.0,
        expected_avg_degree: (expected_avg * 100.0).round() / 100.0,
        baseline_edges,
        actual_edges: e,
        scale_factor: (scale * 100.0).round() / 100.0,
    }
}

/// A god module flagged by the hub debt algorithm.
#[derive(Debug, Clone)]
pub struct GodModuleInfo {
    pub name: String,
    pub fan_in: usize,
    pub fan_out: usize,
    pub hub_ratio: f64,
    pub excess_ratio: f64,
}

/// Extracts the list of god modules (matching `compute_hub_debt` logic).
pub fn extract_god_modules(
    graph: &DiGraph<String, u32>,
    thresholds: &Thresholds,
    exemptions: &Exemptions,
) -> Vec<GodModuleInfo> {
    let n = graph.node_count();
    if n < 6 {
        return Vec::new();
    }

    let threshold = (2.0 * (n as f64).sqrt()).max(8.0);
    let mut gods = Vec::new();

    for node_idx in graph.node_indices() {
        let module_name = &graph[node_idx];

        if exemptions
            .hub_exempt
            .iter()
            .any(|e| module_name.contains(e.as_str()))
        {
            continue;
        }

        if is_entry_point_stem(module_name, &exemptions.entry_point_stems) {
            continue;
        }

        let fan_in = graph
            .neighbors_directed(node_idx, petgraph::Direction::Incoming)
            .count();
        let fan_out = graph
            .neighbors_directed(node_idx, petgraph::Direction::Outgoing)
            .count();
        let total_degree = fan_in + fan_out;

        if (total_degree as f64) < threshold {
            continue;
        }

        let hub_ratio = fan_out as f64 / (fan_in as f64 + 1.0);

        if hub_ratio < thresholds.hub_exemption_ratio {
            continue;
        }

        if fan_in <= thresholds.entry_point_max_fan_in {
            continue;
        }

        let excess = (total_degree as f64 - threshold) / threshold;

        gods.push(GodModuleInfo {
            name: module_name.clone(),
            fan_in,
            fan_out,
            hub_ratio: (hub_ratio * 100.0).round() / 100.0,
            excess_ratio: (excess * 100.0).round() / 100.0,
        });
    }

    gods.sort_by(|a, b| (b.fan_in + b.fan_out).cmp(&(a.fan_in + a.fan_out)));
    gods.truncate(10);
    gods
}

/// A boundary rule violation with edge detail.
#[derive(Debug, Clone)]
pub struct BoundaryViolationDetail {
    pub from_module: String,
    pub to_module: String,
    pub rule_from_pattern: String,
    pub rule_deny_patterns: Vec<String>,
}

/// Extracts detailed boundary violations for AI context.
pub fn extract_boundary_violations(
    graph: &DiGraph<String, u32>,
    config: &ScoringConfig,
) -> Vec<BoundaryViolationDetail> {
    if config.boundaries.is_empty() {
        return Vec::new();
    }

    let mut source_rule_cache: HashMap<NodeIndex, Vec<usize>> = HashMap::new();
    for node_idx in graph.node_indices() {
        let from = &graph[node_idx];
        let matching_rules: Vec<usize> = config
            .boundaries
            .iter()
            .enumerate()
            .filter_map(|(rule_idx, rule)| rule.matches_from(from).then_some(rule_idx))
            .collect();
        if !matching_rules.is_empty() {
            source_rule_cache.insert(node_idx, matching_rules);
        }
    }

    let mut target_rule_cache: HashMap<(usize, NodeIndex), bool> = HashMap::new();
    let mut violations = Vec::new();

    for edge_idx in graph.edge_indices() {
        let Some((src, tgt)) = graph.edge_endpoints(edge_idx) else {
            continue;
        };
        let Some(rule_indices) = source_rule_cache.get(&src) else {
            continue;
        };
        let to = &graph[tgt];
        for &rule_idx in rule_indices {
            let is_match = *target_rule_cache
                .entry((rule_idx, tgt))
                .or_insert_with(|| config.boundaries[rule_idx].matches_to(to));
            if is_match {
                violations.push(BoundaryViolationDetail {
                    from_module: graph[src].clone(),
                    to_module: graph[tgt].clone(),
                    rule_from_pattern: config.boundaries[rule_idx].from.clone(),
                    rule_deny_patterns: config.boundaries[rule_idx].deny.clone(),
                });
                break; // One violation per edge is enough
            }
        }
    }

    violations.truncate(15);
    violations
}

// =============================================================================
// Tests
// =============================================================================
#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{ProjectConfig, ScoringConfig};

    fn default_config() -> ScoringConfig {
        ScoringConfig::default()
    }

    // ── Test Helpers ──

    fn make_tree_graph(n: usize) -> DiGraph<String, u32> {
        let mut g = DiGraph::new();
        let nodes: Vec<_> = (0..n).map(|i| g.add_node(format!("node_{i}"))).collect();
        // Perfect binary-ish tree: parent → child edges only
        for i in 1..n {
            g.add_edge(nodes[i / 2], nodes[i], 1);
        }
        g
    }

    fn make_layered_graph(layers: &[usize]) -> DiGraph<String, u32> {
        let mut g = DiGraph::new();
        let mut layer_nodes: Vec<Vec<NodeIndex>> = Vec::new();

        for (l, &count) in layers.iter().enumerate() {
            let mut nodes = Vec::new();
            for i in 0..count {
                nodes.push(g.add_node(format!("L{l}_{i}")));
            }
            layer_nodes.push(nodes);
        }

        // Connect each layer to the next (forward edges only)
        for l in 0..layer_nodes.len() - 1 {
            for &src in &layer_nodes[l] {
                for &tgt in &layer_nodes[l + 1] {
                    g.add_edge(src, tgt, 1);
                }
            }
        }
        g
    }

    fn make_simple_graph() -> DiGraph<String, u32> {
        let mut g = DiGraph::new();
        let a = g.add_node("A".to_string());
        let b = g.add_node("B".to_string());
        let c = g.add_node("C".to_string());
        g.add_edge(a, b, 1);
        g.add_edge(a, c, 1);
        g.add_edge(b, c, 1);
        g
    }

    fn make_cyclic_graph() -> DiGraph<String, u32> {
        let mut g = DiGraph::new();
        let a = g.add_node("A".to_string());
        let b = g.add_node("B".to_string());
        let c = g.add_node("C".to_string());
        g.add_edge(a, b, 1);
        g.add_edge(b, c, 1);
        g.add_edge(c, a, 1);
        g
    }

    // ── Test 1: Empty graph → 0 debt ──
    #[test]
    fn test_empty_graph_zero_debt() {
        let g: DiGraph<String, u32> = DiGraph::new();
        let score = calculate_drift(&g, None, 0, &default_config());
        assert_eq!(score.total, 0, "Empty graph should have 0 debt");
        assert_eq!(score.cycle_debt, 0.0);
        assert_eq!(score.layering_debt, 0.0);
    }

    // ── Test 2: Perfect tree → debt < 10 ──
    #[test]
    fn test_perfect_tree_low_debt() {
        let g = make_tree_graph(31); // 5-level binary tree
        let score = calculate_drift(&g, None, 0, &default_config());
        assert!(
            score.total < 10,
            "Perfect tree should have <10 debt, got: {}",
            score.total
        );
        assert_eq!(score.new_cycles, 0, "Tree should have no cycles");
    }

    // ── Test 3: Clean 3-layer graph → 5-15 debt ──
    #[test]
    fn test_clean_layered_graph() {
        let g = make_layered_graph(&[3, 5, 4]); // 3 layers, forward-only
        let score = calculate_drift(&g, None, 0, &default_config());
        assert!(
            score.total <= 20,
            "Clean layered graph should have ≤20 debt, got: {}",
            score.total
        );
        assert_eq!(score.new_cycles, 0, "No cycles in clean layers");
        assert_eq!(
            score.boundary_violations, 0,
            "No back-edges in clean layers"
        );
    }

    // ── Test 4: Single 3-node cycle → cycle debt 15-30 ──
    #[test]
    fn test_single_cycle() {
        let g = make_cyclic_graph();
        let score = calculate_drift(&g, None, 0, &default_config());
        assert!(
            score.total >= 10 && score.total <= 40,
            "Single cycle should produce 10-40 debt, got: {}",
            score.total
        );
        assert_eq!(score.new_cycles, 1, "Should detect 1 SCC");
        assert!(score.cycle_debt > 0.0, "Cycle debt sub-score should be > 0");
    }

    // ── Test 5: Large SCC (10 nodes in cycle) → high cycle debt ──
    #[test]
    fn test_large_scc_high_cycle_debt() {
        let mut g = DiGraph::new();
        let nodes: Vec<_> = (0..10).map(|i| g.add_node(format!("cyc_{i}"))).collect();
        // Ring: 0→1→2→...→9→0
        for i in 0..10 {
            g.add_edge(nodes[i], nodes[(i + 1) % 10], 1);
        }
        // Add some non-cyclic context
        for i in 10..20 {
            let n = g.add_node(format!("leaf_{i}"));
            g.add_edge(nodes[0], n, 1);
        }
        let score = calculate_drift(&g, None, 0, &default_config());
        assert!(
            score.cycle_debt > 30.0,
            "Large SCC should produce high cycle debt, got: {}",
            score.cycle_debt
        );
    }

    // ── Test 6: Legitimate hub (high in, low out) → 0 hub debt ──
    #[test]
    fn test_legitimate_hub_zero_penalty() {
        let mut g = DiGraph::new();
        let core = g.add_node("shared_core".to_string());
        // 30 modules depend on core, but core depends on nothing
        for i in 0..30 {
            let n = g.add_node(format!("consumer_{i}"));
            g.add_edge(n, core, 1);
        }
        let score = calculate_drift(&g, None, 0, &default_config());
        assert_eq!(
            score.hub_debt, 0.0,
            "Legitimate hub (high in, zero out) should have 0 hub debt"
        );
    }

    // ── Test 7: God module (high in AND out) → high hub debt ──
    #[test]
    fn test_god_module_high_hub_debt() {
        let mut g = DiGraph::new();
        let god = g.add_node("god_module".to_string());
        // 15 modules depend on god
        for i in 0..15 {
            let n = g.add_node(format!("dep_{i}"));
            g.add_edge(n, god, 1);
        }
        // God also depends on 10 modules (high fan-out)
        for i in 0..10 {
            let n = g.add_node(format!("target_{i}"));
            g.add_edge(god, n, 1);
        }
        let score = calculate_drift(&g, None, 0, &default_config());
        assert!(
            score.hub_debt > 0.0,
            "God module (high in AND out) should have positive hub debt, got: {}",
            score.hub_debt
        );
    }

    // ── Test 8: Heavy edge weights → higher coupling debt ──
    #[test]
    fn test_heavy_weights_coupling_debt() {
        let mut g_light = DiGraph::new();
        let mut g_heavy = DiGraph::new();
        // Same topology, different weights
        let nodes_l: Vec<_> = (0..10)
            .map(|i| g_light.add_node(format!("n_{i}")))
            .collect();
        let nodes_h: Vec<_> = (0..10)
            .map(|i| g_heavy.add_node(format!("n_{i}")))
            .collect();
        for i in 0..9 {
            g_light.add_edge(nodes_l[i], nodes_l[i + 1], 1);
            g_heavy.add_edge(nodes_h[i], nodes_h[i + 1], 20); // 20x heavier
        }
        let score_light = calculate_drift(&g_light, None, 0, &default_config());
        let score_heavy = calculate_drift(&g_heavy, None, 0, &default_config());
        assert!(
            score_heavy.coupling_debt >= score_light.coupling_debt,
            "Heavy weights should produce ≥ coupling debt: light={}, heavy={}",
            score_light.coupling_debt,
            score_heavy.coupling_debt
        );
    }

    // ── Test 9: Back-edges in layered graph → layering debt ──
    #[test]
    fn test_back_edges_layering_debt() {
        let mut g = make_layered_graph(&[3, 4, 3]);
        // Add back-edges from layer 2 to layer 0
        let l2_nodes: Vec<_> = g
            .node_indices()
            .filter(|&n| g[n].starts_with("L2"))
            .collect();
        let l0_nodes: Vec<_> = g
            .node_indices()
            .filter(|&n| g[n].starts_with("L0"))
            .collect();
        for &src in &l2_nodes {
            for &tgt in &l0_nodes {
                g.add_edge(src, tgt, 1);
            }
        }
        let score = calculate_drift(&g, None, 0, &default_config());
        assert!(
            score.layering_debt > 0.0,
            "Back-edges should produce layering debt, got: {}",
            score.layering_debt
        );
        assert!(
            score.layering_violations > 0,
            "Back-edges should be counted as layering violations"
        );
    }

    #[test]
    fn test_boundary_rule_violations_raise_layering_debt() {
        let mut g = DiGraph::new();
        let packages_core = g.add_node("packages/core".to_string());
        let apps_web = g.add_node("apps/web".to_string());
        g.add_edge(packages_core, apps_web, 1);

        let config: ProjectConfig = toml::from_str(
            r#"
[[scoring.boundaries]]
from = "packages/**"
deny = ["apps/**"]
"#,
        )
        .unwrap();

        let score = calculate_drift(&g, None, 0, &config.scoring);
        assert_eq!(score.layering_violations, 0);
        assert_eq!(score.boundary_violations, 1);
        assert!(score.layering_debt > 0.0);
    }

    // ── Test 10: Leaf packages with I=1.0 → 0 instability debt ──
    #[test]
    fn test_leaf_packages_zero_instability() {
        let mut g = DiGraph::new();
        let core = g.add_node("core".to_string());
        // 5 leaf packages that only import from core (ca=0, ce=1, I=1.0)
        for i in 0..5 {
            let leaf = g.add_node(format!("leaf_{i}"));
            g.add_edge(leaf, core, 1);
        }
        let score = calculate_drift(&g, None, 0, &default_config());
        assert_eq!(
            score.instability_debt, 0.0,
            "Leaf packages (ca=0) should not contribute instability debt"
        );
    }

    // ── Test 11: Non-leaf brittle module → instability debt ──
    #[test]
    fn test_nonleaf_brittle_instability() {
        let mut g = DiGraph::new();
        // Create a module with high instability BUT with fan_in > 0
        let hub = g.add_node("hub".to_string());
        let brittle = g.add_node("brittle".to_string());
        let t1 = g.add_node("target1".to_string());
        let t2 = g.add_node("target2".to_string());
        let t3 = g.add_node("target3".to_string());
        let t4 = g.add_node("target4".to_string());

        // hub depends on brittle (brittle has fan_in = 1)
        g.add_edge(hub, brittle, 1);
        // brittle depends on 4 things (fan_out = 4, I = 4/5 = 0.8)
        g.add_edge(brittle, t1, 1);
        g.add_edge(brittle, t2, 1);
        g.add_edge(brittle, t3, 1);
        g.add_edge(brittle, t4, 1);

        // Add more nodes to meet minimum size
        for i in 0..20 {
            let n = g.add_node(format!("extra_{i}"));
            g.add_edge(hub, n, 1);
        }

        let score = calculate_drift(&g, None, 0, &default_config());
        // Note: instability debt may still be 0 if brittle_ratio is very low
        // The important thing is the algorithm runs without error
        assert!(
            score.instability_debt >= 0.0,
            "Instability debt should be non-negative"
        );
    }

    // ── Test 12: 100-node clean graph → health > 85% ──
    #[test]
    fn test_100_node_clean_graph_high_health() {
        let g = make_tree_graph(100);
        let score = calculate_drift(&g, None, 0, &default_config());
        let health = 100 - score.total;
        assert!(
            health >= 85,
            "100-node clean tree should have health ≥ 85%, got: {}%",
            health
        );
    }

    // ── Test 13: 100-node spaghetti → health < 40% ──
    #[test]
    fn test_100_node_spaghetti_low_health() {
        let mut g = DiGraph::new();
        let nodes: Vec<_> = (0..100).map(|i| g.add_node(format!("s_{i}"))).collect();
        // Dense random-ish connections + cycles
        for i in 0..100 {
            for j in 0..100 {
                if i != j && (i * 7 + j * 13) % 5 == 0 {
                    g.add_edge(nodes[i], nodes[j], ((i + j) % 10 + 1) as u32);
                }
            }
        }
        let score = calculate_drift(&g, None, 0, &default_config());
        let health = 100u8.saturating_sub(score.total);
        assert!(
            health < 40,
            "100-node spaghetti should have health < 40%, got: {}%",
            health
        );
    }

    // ── Test 14: Old DriftScore JSON backward compat ──
    #[test]
    fn test_drift_score_backward_compat() {
        // Simulate old JSON without new fields
        let old_json = r#"{
            "total": 42,
            "fan_in_delta": 2,
            "fan_out_delta": -1,
            "new_cycles": 1,
            "boundary_violations": 0,
            "cognitive_complexity": 3.5,
            "timestamp": 1234567890
        }"#;
        let score: DriftScore = serde_json::from_str(old_json).unwrap();
        assert_eq!(score.total, 42);
        assert_eq!(score.cycle_debt, 0.0, "Default for missing sub-scores");
        assert_eq!(score.layering_debt, 0.0);
        assert_eq!(score.hub_debt, 0.0);
        assert_eq!(score.coupling_debt, 0.0);
        assert_eq!(score.cognitive_debt, 0.0);
        assert_eq!(score.instability_debt, 0.0);
    }

    // ── Test 15: Median fan delta computation ──
    #[test]
    fn test_median_fan_delta() {
        // Build two graphs with known fan-in/out changes
        let mut prev = DiGraph::new();
        let pa = prev.add_node("A".to_string());
        let pb = prev.add_node("B".to_string());
        let pc = prev.add_node("C".to_string());
        prev.add_edge(pa, pb, 1);
        prev.add_edge(pa, pc, 1);

        let mut curr = DiGraph::new();
        let ca = curr.add_node("A".to_string());
        let cb = curr.add_node("B".to_string());
        let cc = curr.add_node("C".to_string());
        let cd = curr.add_node("D".to_string());
        curr.add_edge(ca, cb, 1);
        curr.add_edge(ca, cc, 1);
        curr.add_edge(ca, cd, 1); // A gained one more out-edge
        curr.add_edge(cb, cc, 1); // B gained one out-edge

        let score = calculate_drift(&curr, Some(&prev), 0, &default_config());
        // Fan deltas should be computed based on median of per-node changes
        // The exact values depend on which nodes overlap; just verify they're reasonable
        assert!(
            score.fan_in_delta.abs() <= 5,
            "Fan-in delta should be small: {}",
            score.fan_in_delta
        );
        assert!(
            score.fan_out_delta.abs() <= 5,
            "Fan-out delta should be small: {}",
            score.fan_out_delta
        );
    }

    // ── Test: Small clean graph (existing test, updated) ──
    #[test]
    fn test_calculate_health_clean_small() {
        let graph = make_simple_graph();
        let score = calculate_drift(&graph, None, 0, &default_config());
        assert!(
            score.total <= 10,
            "Score should be very low for a clean tiny graph: {}",
            score.total
        );
    }

    // ── Test: Cyclic graph (existing test, updated) ──
    #[test]
    fn test_calculate_health_with_cycle() {
        let graph = make_cyclic_graph();
        let score = calculate_drift(&graph, None, 0, &default_config());
        assert!(
            score.total >= 10 && score.total <= 50,
            "Cycle should add significant debt: {}",
            score.total
        );
    }

    // ── Test: Entry Point Exemption (Main/Index/App) ──
    #[test]
    fn test_entry_point_exemption() {
        let mut g = DiGraph::new();
        // Create an entry point module that acts as a "God Module" (high fan-out, zero fan-in)
        let entry = g.add_node("src/main.rs".to_string());
        let mut targets = Vec::new();

        for i in 0..15 {
            let n = g.add_node(format!("module_{i}"));
            targets.push(n);
            g.add_edge(entry, n, 1);
        }

        // Add an extra connection to bump up instability parameters
        let child = g.add_node("child".to_string());
        g.add_edge(targets[0], child, 1);
        g.add_edge(child, targets[0], 1); // create a cycle to force non-zero score to trigger diagnostics

        let _score = calculate_drift(&g, None, 0, &default_config());

        // Ensure hub_debt is 0 for entry points despite high fan-out
        // Note: The logic in `compute_hub_debt` checks `is_entry`
        let mut g_regular = DiGraph::new();
        let reg = g_regular.add_node("src/utils.rs".to_string());
        for i in 0..15 {
            let n = g_regular.add_node(format!("module_{i}"));
            g_regular.add_edge(reg, n, 1);
            g_regular.add_edge(n, reg, 1); // Make it high fan-in AND fan-out
        }

        let _score_reg = calculate_drift(&g_regular, None, 0, &default_config());

        // generate_diagnostics shouldn't flag 'main.rs' as brittle
        let mock_score = DriftScore {
            total: 50,
            fan_in_delta: 0,
            fan_out_delta: 0,
            new_cycles: 0,
            boundary_violations: 0,
            layering_violations: 0,
            cognitive_complexity: 0.0,
            timestamp: 0,
            cognitive_debt: 0.0,
            cycle_debt: 0.0,
            layering_debt: 0.0,
            coupling_debt: 0.0,
            hub_debt: 20.0,         // Force diagnostic generation
            instability_debt: 20.0, // Force diagnostic generation
        };

        let diagnostics = generate_diagnostics(&g, &mock_score, &default_config());
        let joined_diagnostics = diagnostics.join(" ");

        // The word "main" or "main.rs" should NOT be flagged as fragile
        assert!(
            !joined_diagnostics.contains("main.rs fragile"),
            "Entry points should not be flagged as fragile"
        );
    }

    #[test]
    fn test_is_entry_point_stem_matching() {
        let stems: Vec<String> = ["main", "index", "app"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        assert!(is_entry_point_stem("src/main.rs", &stems));
        assert!(is_entry_point_stem("cli/index", &stems));
        assert!(is_entry_point_stem("app", &stems));
        assert!(is_entry_point_stem("packages/web/app.ts", &stems));
        assert!(!is_entry_point_stem("src/utils.rs", &stems));
        assert!(!is_entry_point_stem("core/server", &stems));
        assert!(!is_entry_point_stem("main_helper", &stems));
    }

    #[test]
    fn test_entry_point_stems_exempt_from_hub_and_instability_scoring() {
        // Build a graph where "cli/app" is a god-module-shaped entry point:
        // high fan-in AND fan-out, which would normally trigger hub + instability debt.
        let mut g = DiGraph::new();
        let app = g.add_node("cli/app".to_string());
        for i in 0..12 {
            let n = g.add_node(format!("module_{i}"));
            g.add_edge(app, n, 1); // high fan-out
            g.add_edge(n, app, 1); // high fan-in
        }

        // With default config, "app" is in entry_point_stems → should be exempt
        let cfg = default_config();
        let hub = compute_hub_debt(&g, &cfg.thresholds, &cfg.exemptions);
        let instability = compute_instability_debt(&g, &cfg.thresholds, &cfg.exemptions);
        assert_eq!(hub, 0.0, "Entry point 'app' should be exempt from hub debt");
        assert_eq!(
            instability, 0.0,
            "Entry point 'app' should be exempt from instability debt"
        );

        // With a config where "app" is NOT an entry point stem → should trigger debt
        let mut cfg_no_app = default_config();
        cfg_no_app.exemptions.entry_point_stems =
            ["main", "index"].iter().map(|s| s.to_string()).collect();
        let hub_no_exempt = compute_hub_debt(&g, &cfg_no_app.thresholds, &cfg_no_app.exemptions);
        assert!(
            hub_no_exempt > 0.0,
            "Without 'app' in stems, hub debt should be non-zero"
        );
    }
}