aver-lang 0.26.0

VM and transpiler for Aver, a statically-typed language designed for AI-assisted development
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
//! `aver shape` — module-shape presentation layer.
//!
//! Stage 1 of issue #232 (0.23 "Shape") split this file into two
//! tiers:
//!
//! - **Recognition** (`aver::analysis::shape`) — per-fn facts walk,
//!   archetype classifier, call-graph SCC. Stable typed primitives.
//! - **Presentation** (this module) — `ModuleShape` vector + `Kind` +
//!   verify report + histogram + Layer fingerprint distance + corpus
//!   walker + renderer + `aver.toml [[shape.layer]]` / `[[shape.expected]]`
//!   bridges. Everything the CLI / LSP / JSON consumers see.
//!
//! The recognition primitives are re-exported below so existing
//! callers (and the research test) keep working through this module
//! during the transition; downstream stages will migrate them to
//! import directly from `aver::analysis::shape`.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::Path;

use crate::ast::TopLevel;
use crate::ir::hir::{ResolvedFnDef, ResolvedTopLevel};
use crate::ir::{PipelineConfig, TypecheckMode};
use crate::types::Type;

/// ANSI styling shim for the `render_text` renderer. With
/// `tty-render` enabled (the default for the CLI / LSP / playground
/// builds), `Colorize` is re-exported from the `colored` crate so
/// calls like `"X".bold().cyan()` produce the actual escape
/// sequences. Without `tty-render` (the fuzz crates and any
/// future `--no-default-features` consumer), the trait still
/// resolves but every method is a no-op that returns the input as
/// `String` — the renderer keeps working, just emits plain text.
#[cfg(feature = "tty-render")]
use colored::Colorize as _shape_colorize;
#[cfg(not(feature = "tty-render"))]
use shape_color::Colorize as _shape_colorize;

#[cfg(not(feature = "tty-render"))]
mod shape_color {
    /// No-op stand-in for `colored::Colorize` when the `tty-render`
    /// feature is off. Every method returns the input as `String`,
    /// so `"X".bold().cyan()` chains the same way it does with the
    /// real crate — just without escapes.
    pub trait Colorize {
        fn bold(&self) -> String;
        fn cyan(&self) -> String;
        fn yellow(&self) -> String;
        fn magenta(&self) -> String;
        fn dimmed(&self) -> String;
    }
    impl<S: AsRef<str> + ?Sized> Colorize for S {
        fn bold(&self) -> String {
            self.as_ref().to_string()
        }
        fn cyan(&self) -> String {
            self.as_ref().to_string()
        }
        fn yellow(&self) -> String {
            self.as_ref().to_string()
        }
        fn magenta(&self) -> String {
            self.as_ref().to_string()
        }
        fn dimmed(&self) -> String {
            self.as_ref().to_string()
        }
    }
}

// Recognition primitives moved to `aver::analysis::shape` in stage 1
// (#232). Stage 2 drops the re-exports — callers import from
// `analysis::shape` directly so the presentation tier doesn't double
// as an API entry point for the recognition tier. This file holds
// only the presentation surface from here on: `ModuleShape` vector +
// `Kind` + Layer fingerprints + verify report + histogram + corpus
// walker + renderers + `aver.toml` bridges. Internal use of the
// recognition API in this file goes through `crate::analysis::shape`
// directly (see imports below).
use crate::analysis::shape::{Archetype, ModulePattern, analyze_program_with_modules};

// ─── ModuleShape vector + derived Kind ───────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Purity {
    Pure,
    ClassifiedEffectful,
    ShellEffectful,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Entry {
    None,
    Main,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StateShape {
    Stateless,
    PureStateMachine,
    ExternalWorld,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeSurface {
    NoTypes,
    PlainDataTypes,
    UserOpaque,
    RuntimeHandle,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApiShape {
    Closed,
    ExposedLibrary,
    ServiceBoundary,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ModuleShape {
    pub purity: Purity,
    pub entry: Entry,
    pub state_shape: StateShape,
    pub type_surface: TypeSurface,
    pub api_shape: ApiShape,
}

impl Purity {
    pub fn as_str(&self) -> &'static str {
        match self {
            Purity::Pure => "Pure",
            Purity::ClassifiedEffectful => "ClassifiedEffectful",
            Purity::ShellEffectful => "ShellEffectful",
        }
    }

    /// One-line user-facing explanation of what each purity value means.
    /// Surfaced in CLI help / hover text — answers "what makes this
    /// module ShellEffectful vs ClassifiedEffectful?".
    pub fn description(&self) -> &'static str {
        match self {
            Purity::Pure => "no effects declared",
            Purity::ClassifiedEffectful => {
                "all effects are Oracle-classified (one-shot req/resp shape)"
            }
            Purity::ShellEffectful => {
                "contains at least one shell/lifecycle effect (e.g. HttpServer.listen) — Oracle skips by design"
            }
        }
    }
}

impl Entry {
    pub fn as_str(&self) -> &'static str {
        match self {
            Entry::None => "None",
            Entry::Main => "Main",
        }
    }
}

impl StateShape {
    pub fn as_str(&self) -> &'static str {
        match self {
            StateShape::Stateless => "Stateless",
            StateShape::PureStateMachine => "PureStateMachine",
            StateShape::ExternalWorld => "ExternalWorld",
        }
    }
}

impl TypeSurface {
    pub fn as_str(&self) -> &'static str {
        match self {
            TypeSurface::NoTypes => "NoTypes",
            TypeSurface::PlainDataTypes => "PlainDataTypes",
            TypeSurface::UserOpaque => "UserOpaque",
            TypeSurface::RuntimeHandle => "RuntimeHandle",
        }
    }
}

impl ApiShape {
    pub fn as_str(&self) -> &'static str {
        match self {
            ApiShape::Closed => "Closed",
            ApiShape::ExposedLibrary => "ExposedLibrary",
            ApiShape::ServiceBoundary => "ServiceBoundary",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Kind {
    PureHelpers,
    DataModule,
    SmartConstructor,
    Library,
    Orchestration,
    ServiceClient,
    EffectfulLibrary,
    EffectfulShell,
}

impl Kind {
    pub fn as_str(&self) -> &'static str {
        match self {
            Kind::PureHelpers => "PureHelpers",
            Kind::DataModule => "DataModule",
            Kind::SmartConstructor => "SmartConstructor",
            Kind::Library => "Library",
            Kind::Orchestration => "Orchestration",
            Kind::ServiceClient => "ServiceClient",
            Kind::EffectfulLibrary => "EffectfulLibrary",
            Kind::EffectfulShell => "EffectfulShell",
        }
    }

    /// Plain-English explanation of the rule that picked this Kind from
    /// the vector. Used as JSON `rule` field and as a hover snippet.
    pub fn rule(&self) -> &'static str {
        match self {
            Kind::PureHelpers => "pure module, no exposed surface, plain types",
            Kind::DataModule => "pure module exposing library API over plain data types",
            Kind::SmartConstructor => "pure module exposing an opaque user type",
            Kind::Library => "classified effects with exposed API, no main",
            Kind::Orchestration => "classified effects with main entry point",
            Kind::ServiceClient => "classified effects threaded through a runtime handle",
            Kind::EffectfulLibrary => "effectful library — exposed surface, no main",
            Kind::EffectfulShell => {
                "shell/lifecycle effects (e.g. HttpServer.listen) — long-running, not Oracle-classified"
            }
        }
    }
}

/// Threshold for "this module is genuinely effectful": at least this
/// fraction of its non-main fns must declare effects in their `! [...]`.
/// Below the threshold, a `main` that prints `Console.print("done")`
/// after running pure code shouldn't drag the module into `Orchestration`.
const EFFECTFUL_FN_RATIO_FOR_ORCHESTRATION: f64 = 0.3;

pub fn derive_kind(shape: &ModuleShape, effectful_fn_ratio: f64) -> Kind {
    // Effectful Kinds (both Classified and Shell flavors): a Shell effect
    // is a long-running lifecycle (HttpServer.listen, Tcp.listen) — Oracle
    // skips it by design, not because the classifier doesn't recognize it.
    // From the user's perspective a module with a shell-effect entrypoint
    // is still Orchestration (or ServiceClient if it threads a handle);
    // the `purity` field tells the rest of the story.
    if !matches!(shape.purity, Purity::Pure) {
        // ServiceClient = module that re-exports its handle-using API
        // surface (api_shape == ServiceBoundary, i.e. some exposed fn
        // takes/returns the handle). Threading a handle internally is
        // not enough — those modules show up as Orchestration / Library
        // depending on whether they have `main`.
        if matches!(shape.api_shape, ApiShape::ServiceBoundary) {
            return Kind::ServiceClient;
        }
        if matches!(shape.entry, Entry::Main) {
            // "Has main + has effects" used to unconditionally pick
            // Orchestration. That dragged pure algorithm modules with
            // a demo `main(); Console.print(result)` (quicksort,
            // calculator, …) into Orchestration even though only one
            // fn out of N actually touches an effect. Now we only
            // commit to Orchestration when ≥30% of non-main fns are
            // effectful — below that the module is library-shaped
            // with a demo entry, and falls through to the api-shape
            // and pure paths below.
            if effectful_fn_ratio >= EFFECTFUL_FN_RATIO_FOR_ORCHESTRATION {
                return Kind::Orchestration;
            }
            // Fall through: treat as library-with-demo by api/purity rules.
        }
        if matches!(shape.api_shape, ApiShape::ExposedLibrary) {
            return Kind::Library;
        }
        if matches!(shape.purity, Purity::ShellEffectful) {
            return Kind::EffectfulShell;
        }
        // Pure-dominated module with a demo main and no exposes —
        // ergonomically the same as PureHelpers, even though one fn
        // has effects.
        if matches!(shape.entry, Entry::Main)
            && effectful_fn_ratio < EFFECTFUL_FN_RATIO_FOR_ORCHESTRATION
        {
            return Kind::PureHelpers;
        }
        return Kind::EffectfulLibrary;
    }
    // Pure from here.
    if matches!(shape.type_surface, TypeSurface::UserOpaque) {
        return Kind::SmartConstructor;
    }
    if matches!(
        shape.api_shape,
        ApiShape::ExposedLibrary | ApiShape::ServiceBoundary
    ) {
        return Kind::DataModule;
    }
    Kind::PureHelpers
}

// ─── Verification report (orthogonal to Kind mapping) ────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VerifyLevel {
    None,
    Cases,
    Laws,
    Trace,
    Mixed,
}

impl VerifyLevel {
    pub fn as_str(&self) -> &'static str {
        match self {
            VerifyLevel::None => "None",
            VerifyLevel::Cases => "Cases",
            VerifyLevel::Laws => "Laws",
            VerifyLevel::Trace => "Trace",
            VerifyLevel::Mixed => "Mixed",
        }
    }
}

#[derive(Debug, Clone)]
pub struct VerifyReport {
    pub level: VerifyLevel,
    pub blocks: usize,
    pub covered_fns: usize,
    pub eligible_fns: usize,
}

// ─── Histogram ──────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Default)]
pub struct Histogram {
    pub counts: BTreeMap<Archetype, usize>,
    pub total_fns: usize,
}

impl Histogram {
    pub fn percentage(&self, archetype: Archetype) -> f64 {
        if self.total_fns == 0 {
            return 0.0;
        }
        let c = self.counts.get(&archetype).copied().unwrap_or(0) as f64;
        100.0 * c / self.total_fns as f64
    }

    /// Returns archetype-percentage pairs in descending count order.
    pub fn sorted(&self) -> Vec<(Archetype, usize, f64)> {
        let mut entries: Vec<(Archetype, usize)> = self
            .counts
            .iter()
            .filter(|(_, c)| **c > 0)
            .map(|(k, c)| (*k, *c))
            .collect();
        entries.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.as_str().cmp(b.0.as_str())));
        entries
            .into_iter()
            .map(|(name, count)| {
                let pct = if self.total_fns == 0 {
                    0.0
                } else {
                    100.0 * count as f64 / self.total_fns as f64
                };
                (name, count, pct)
            })
            .collect()
    }
}

// ─── Layer fingerprint + distance ────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Layer {
    Domain,
    Parse,
    Command,
    AiStrategy,
    RenderUi,
    Infra,
}

impl Layer {
    pub fn as_str(&self) -> &'static str {
        match self {
            Layer::Domain => "Domain",
            Layer::Parse => "Parse",
            Layer::Command => "Command",
            Layer::AiStrategy => "AiStrategy",
            Layer::RenderUi => "RenderUi",
            Layer::Infra => "Infra",
        }
    }

    pub fn parse(s: &str) -> Option<Layer> {
        match s {
            "Domain" => Some(Layer::Domain),
            "Parse" => Some(Layer::Parse),
            "Command" => Some(Layer::Command),
            "AiStrategy" | "AI-strategy" | "AIStrategy" => Some(Layer::AiStrategy),
            "RenderUi" | "RenderUI" | "render-UI" => Some(Layer::RenderUi),
            "Infra" => Some(Layer::Infra),
            _ => None,
        }
    }

    pub fn all() -> &'static [Layer] {
        &[
            Layer::Domain,
            Layer::Parse,
            Layer::Command,
            Layer::AiStrategy,
            Layer::RenderUi,
            Layer::Infra,
        ]
    }
}

/// Five-bucket histogram a `Layer` fingerprint is defined against.
/// Mapped from the 14 archetype labels via `archetype_to_bucket`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Bucket {
    Match,
    Recursion,
    Pipeline,
    Orchestration,
    Helpers,
}

impl Bucket {
    pub fn as_str(&self) -> &'static str {
        match self {
            Bucket::Match => "match",
            Bucket::Recursion => "recursion",
            Bucket::Pipeline => "pipeline",
            Bucket::Orchestration => "orchestration",
            Bucket::Helpers => "helpers",
        }
    }
}

pub fn archetype_to_bucket(archetype: Archetype) -> Option<Bucket> {
    match archetype {
        Archetype::MatchDispatcher | Archetype::MatchOnValue => Some(Bucket::Match),
        Archetype::SccMutual | Archetype::StructuralRecursion => Some(Bucket::Recursion),
        Archetype::PipelineResult | Archetype::LetPipeline | Archetype::ManualResultAdapter => {
            Some(Bucket::Pipeline)
        }
        Archetype::Orchestration | Archetype::EffectfulLeaf => Some(Bucket::Orchestration),
        Archetype::TrivialHelper
        | Archetype::PureExpression
        | Archetype::ConstructorWrapper
        | Archetype::DataAsFunction
        | Archetype::RendererFormatter => Some(Bucket::Helpers),
        Archetype::Unclassified => None,
    }
}

#[derive(Debug, Clone)]
pub struct LayerFingerprint {
    pub layer: Layer,
    /// Bucket percentages summing to ~100.
    pub buckets: [(Bucket, f64); 5],
}

/// Built-in v0 fingerprints sourced from the casual single-author
/// corpus measurement that landed on the tweet. Concrete numbers:
///
/// ```text
/// LAYER       match  recursion  pipeline  orchestration  helpers
/// Domain      ~40%   ~25%       ~0%       ~5%            ~30%
/// Parse       ~15%   ~10%       ~65%      ~10%           ~0%
/// Command     ~10%    ~5%       ~75%      ~10%           ~0%
/// AiStrategy  ~60%   ~15%       ~0%       ~10%           ~15%
/// RenderUi    ~50%    ~5%       ~0%       ~25%           ~20%
/// Infra       ~20%   ~10%       ~30%      ~40%            ~0%
/// ```
/// Translate `aver.toml [[shape.layer]]` entries into the runtime
/// fingerprint representation. Returns an error if `name` doesn't match
/// any known `Layer` variant. Unknown layers are deliberately rejected
/// here, not silently dropped — typo-detection is cheap and a silently
/// missing fingerprint would change the nearest-neighbor result.
pub fn fingerprints_from_config(
    entries: &[crate::config::ShapeLayerFingerprint],
) -> Result<Vec<LayerFingerprint>, String> {
    use Bucket::*;
    entries
        .iter()
        .map(|e| {
            let layer = Layer::parse(&e.name).ok_or_else(|| {
                format!(
                    "aver.toml: [[shape.layer]] name '{}' is not a known Layer (expected one of: Domain, Parse, Command, AiStrategy, RenderUi, Infra)",
                    e.name
                )
            })?;
            Ok(LayerFingerprint {
                layer,
                buckets: [
                    (Match, e.match_pct),
                    (Recursion, e.recursion_pct),
                    (Pipeline, e.pipeline_pct),
                    (Orchestration, e.orchestration_pct),
                    (Helpers, e.helpers_pct),
                ],
            })
        })
        .collect()
}

pub fn builtin_v0_layer_fingerprints() -> Vec<LayerFingerprint> {
    use Bucket::*;
    let mk = |layer, m, r, p, o, h| LayerFingerprint {
        layer,
        buckets: [
            (Match, m),
            (Recursion, r),
            (Pipeline, p),
            (Orchestration, o),
            (Helpers, h),
        ],
    };
    vec![
        mk(Layer::Domain, 40.0, 25.0, 0.0, 5.0, 30.0),
        mk(Layer::Parse, 15.0, 10.0, 65.0, 10.0, 0.0),
        mk(Layer::Command, 10.0, 5.0, 75.0, 10.0, 0.0),
        mk(Layer::AiStrategy, 60.0, 15.0, 0.0, 10.0, 15.0),
        mk(Layer::RenderUi, 50.0, 5.0, 0.0, 25.0, 20.0),
        mk(Layer::Infra, 20.0, 10.0, 30.0, 40.0, 0.0),
    ]
}

fn histogram_to_buckets(hist: &Histogram) -> [(Bucket, f64); 5] {
    use Bucket::*;
    let mut counts: HashMap<Bucket, usize> = HashMap::new();
    for (arch, c) in &hist.counts {
        if let Some(b) = archetype_to_bucket(*arch) {
            *counts.entry(b).or_insert(0) += c;
        }
    }
    let total = hist.total_fns.max(1) as f64;
    let pct = |b: Bucket| 100.0 * counts.get(&b).copied().unwrap_or(0) as f64 / total;
    [
        (Match, pct(Match)),
        (Recursion, pct(Recursion)),
        (Pipeline, pct(Pipeline)),
        (Orchestration, pct(Orchestration)),
        (Helpers, pct(Helpers)),
    ]
}

#[derive(Debug, Clone)]
pub struct LayerVerdict {
    pub layer: Layer,
    /// Absolute fit: how close `layer` is to the observed histogram,
    /// normalised against the max possible Euclidean distance in the
    /// 5-bucket simplex. Penalised on small modules (<5 fns capped at
    /// 0.2, <10 fns softened by 0.7×).
    pub confidence: f64,
    /// Distance gap between the chosen layer and the runner-up.
    /// High margin = clear winner. Low margin = classifier is hesitating
    /// between multiple fingerprints — read with care.
    pub margin: f64,
    /// True when the verdict shouldn't be read as a hard label —
    /// either confidence is low OR margin to the runner-up is small.
    /// Renderers should surface this with explicit "uncertain" wording.
    pub uncertain: bool,
    /// Top three nearest layers with their raw distances. Lets the
    /// caller show "next: Domain Δ4.1, RenderUi Δ8.3" so the verdict
    /// is auditable without pretending the second-best didn't exist.
    pub candidates: Vec<(Layer, f64)>,
    pub basis: String,
    pub support_fns: usize,
}

/// Confidence threshold below which a verdict is marked `uncertain`.
const UNCERTAIN_CONFIDENCE_THRESHOLD: f64 = 0.4;
/// Margin (distance gap to runner-up) below which a verdict is marked
/// `uncertain` even at high confidence — fingerprints are close to
/// each other and the classifier could plausibly pick either.
const UNCERTAIN_MARGIN_THRESHOLD: f64 = 10.0;

/// Nearest fingerprint by Euclidean distance over bucket %.
/// Confidence is `(max_dist - chosen_dist) / max_dist`, penalized by
/// small `total_fns` (< 5 fns flattens confidence regardless of fit).
pub fn classify_layer(
    hist: &Histogram,
    fingerprints: &[LayerFingerprint],
    basis: &str,
) -> Option<LayerVerdict> {
    if fingerprints.is_empty() || hist.total_fns == 0 {
        return None;
    }
    let observed = histogram_to_buckets(hist);
    let mut scored: Vec<(Layer, f64)> = Vec::new();
    for fp in fingerprints {
        let mut sq = 0.0_f64;
        for ((b1, p1), (b2, p2)) in observed.iter().zip(fp.buckets.iter()) {
            debug_assert_eq!(b1, b2);
            let d = p1 - p2;
            sq += d * d;
        }
        scored.push((fp.layer, sq.sqrt()));
    }
    scored.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
    let (best_layer, best_dist) = scored[0];
    // Max meaningful Euclidean distance across 5 bucket pcts is sqrt(5 * 100^2) ≈ 223.6.
    let max_dist = (5.0_f64 * 100.0 * 100.0).sqrt();
    let raw_conf = ((max_dist - best_dist) / max_dist).clamp(0.0, 1.0);
    let n = hist.total_fns;
    let small_n_penalty = if n < 5 {
        // Hard-cap confidence for tiny modules — 3 fns is noise.
        0.2_f64.min(raw_conf)
    } else if n < 10 {
        // Soft-penalize medium modules at most ~30% of headroom.
        raw_conf * 0.7
    } else {
        raw_conf
    };
    // Margin = how far ahead the winner is from the second-best.
    // Captures ambivalence the confidence number alone misses
    // (two fingerprints both 0.2 fit is ambivalent; one at 0.5 + one
    // at 0.1 is decisive even if confidence is the same).
    let margin = if scored.len() >= 2 {
        scored[1].1 - scored[0].1
    } else {
        f64::INFINITY
    };
    let uncertain =
        small_n_penalty < UNCERTAIN_CONFIDENCE_THRESHOLD || margin < UNCERTAIN_MARGIN_THRESHOLD;
    let candidates: Vec<(Layer, f64)> = scored.into_iter().take(3).collect();
    Some(LayerVerdict {
        layer: best_layer,
        confidence: small_n_penalty,
        margin,
        uncertain,
        candidates,
        basis: basis.to_string(),
        support_fns: n,
    })
}

// ─── Top-level analysis ──────────────────────────────────────────────────────

#[derive(Debug, Clone)]
pub struct FnShape {
    pub name: String,
    pub primary: Archetype,
    pub labels: Vec<Archetype>,
}

#[derive(Debug, Clone)]
pub struct ShapeReport {
    pub module: String,
    pub file: String,
    pub depends: Vec<String>,
    pub effects: Vec<String>,
    pub exposes_opaque: Vec<String>,
    pub has_main: bool,
    pub shape: ModuleShape,
    pub kind: Kind,
    /// Fraction of non-`main` fns that declare effects in their
    /// `! [...]`. Drives the Orchestration vs PureHelpers decision in
    /// `derive_kind` so a pure module with a demo `main()` doesn't
    /// read as Orchestration.
    pub effectful_fn_ratio: f64,
    pub verify: VerifyReport,
    pub histogram: Histogram,
    pub layer: Option<LayerVerdict>,
    pub fns: Vec<FnShape>,
    /// Module-level typed patterns recognized by `analysis::shape`
    /// (stage 6 of #232). Populated from `program_shape.patterns`;
    /// the renderer surfaces them in their own section so callers see
    /// every refinement / wrapper / pipeline / renderer / fold the
    /// substrate identified.
    pub patterns: Vec<ModulePattern>,
}

pub fn analyze_path(path: &Path, module_root_hint: Option<&str>) -> Result<ShapeReport, String> {
    analyze_path_with(
        path,
        module_root_hint,
        &builtin_v0_layer_fingerprints(),
        "built-in v0",
    )
}

/// Same as `analyze_path` but lets the caller supply a custom layer
/// fingerprint table + basis label (used by the CLI when `aver.toml` has
/// `[[shape.layer]]` overrides).
pub fn analyze_path_with(
    path: &Path,
    module_root_hint: Option<&str>,
    fingerprints: &[LayerFingerprint],
    basis: &str,
) -> Result<ShapeReport, String> {
    let source = std::fs::read_to_string(path).map_err(|e| format!("read: {}", e))?;
    let module_root = match module_root_hint {
        Some(r) => r.to_string(),
        None => path
            .parent()
            .and_then(|p| p.to_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| ".".to_string()),
    };
    let file_label = path.to_string_lossy().to_string();
    let fallback_module_name = path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("<unnamed>")
        .to_string();
    analyze_source_with(
        &source,
        &module_root,
        &file_label,
        &fallback_module_name,
        fingerprints,
        basis,
    )
}

/// Analyze a source string directly, without touching the filesystem
/// for the entry file. Used by the LSP (editor buffer may differ from
/// on-disk content) and any future embedder that holds the program in
/// memory. `module_root` resolves `depends [...]`; `file_label` is the
/// path string surfaced in the report's `file` field; `fallback_module_name`
/// is used when the source has no `module` declaration.
pub fn analyze_source_with(
    source: &str,
    module_root: &str,
    file_label: &str,
    fallback_module_name: &str,
    fingerprints: &[LayerFingerprint],
    basis: &str,
) -> Result<ShapeReport, String> {
    let mut items = crate::source::parse_source(source).map_err(|e| format!("parse: {}", e))?;
    let module_root = module_root.to_string();

    let dep_modules = crate::source::load_compile_deps(&items, &module_root)
        .map_err(|e| format!("deps: {}", e))?;
    let pipeline_result = crate::ir::pipeline::run(
        &mut items,
        PipelineConfig {
            typecheck: Some(TypecheckMode::Full {
                base_dir: Some(&module_root),
            }),
            dep_modules: &dep_modules,
            ..Default::default()
        },
    );
    if let Some(tc) = pipeline_result.typecheck.as_ref()
        && !tc.errors.is_empty()
    {
        let first = tc
            .errors
            .first()
            .map(|e| e.message.clone())
            .unwrap_or_default();
        return Err(format!("typecheck errors: {first}"));
    }

    let module = items.iter().find_map(|i| match i {
        TopLevel::Module(m) => Some(m.clone()),
        _ => None,
    });
    let (module_name, depends, effects, exposes_opaque, exposes) = match module {
        Some(m) => (
            m.name.clone(),
            m.depends.clone(),
            m.effects.clone().unwrap_or_default(),
            m.exposes_opaque.clone(),
            m.exposes.clone(),
        ),
        None => (
            fallback_module_name.to_string(),
            vec![],
            vec![],
            vec![],
            vec![],
        ),
    };

    let resolved_fns: Vec<&ResolvedFnDef> = pipeline_result
        .resolved_items
        .iter()
        .filter_map(|t| match t {
            ResolvedTopLevel::FnDef(fd) => Some(fd),
            _ => None,
        })
        .collect();

    // Stage 4/6 of #232: recognition substrate.
    // `analyze_program_with_modules` runs facts walk + SCC + classify
    // and also populates `patterns` (module-level typed patterns:
    // `RefinementSmartConstructor`, `WrapperOverRecursion`,
    // `ResultPipelineChain`, `RendererFormatter`,
    // `MatchDispatcherFold`). Presentation tier reads both —
    // per-fn archetypes drive the histogram + Kind / Layer
    // scaffolding; patterns get their own section in the renderer.
    let program_shape = analyze_program_with_modules(&resolved_fns, &items, &dep_modules);

    let exposes_set: HashSet<&str> = exposes.iter().map(|s| s.as_str()).collect();
    let mut fn_shapes = Vec::with_capacity(resolved_fns.len());
    let mut histogram = Histogram::default();
    let mut has_main = false;
    let mut classified_uses_handle = false;
    let mut exposed_uses_handle = false;
    let mut non_main_fns = 0usize;
    let mut effectful_non_main_fns = 0usize;

    for fd in &resolved_fns {
        if fd.name == "main" {
            has_main = true;
        } else {
            non_main_fns += 1;
            if !fd.effects.is_empty() {
                effectful_non_main_fns += 1;
            }
        }
        let this_uses_handle = uses_runtime_handle(fd);
        if this_uses_handle {
            classified_uses_handle = true;
            if exposes_set.contains(fd.name.as_str()) {
                exposed_uses_handle = true;
            }
        }
        let recognition = program_shape
            .for_fn(fd.fn_id)
            .expect("analyze_program populates per_fn for every resolved fn");
        let primary = recognition.primary;
        let labels = recognition.labels.clone();
        if fd.name != "main" {
            *histogram.counts.entry(primary).or_insert(0) += 1;
            histogram.total_fns += 1;
        }
        fn_shapes.push(FnShape {
            name: fd.name.clone(),
            primary,
            labels,
        });
    }

    let effectful_fn_ratio = if non_main_fns > 0 {
        effectful_non_main_fns as f64 / non_main_fns as f64
    } else {
        // No non-main fns to classify — `derive_kind` falls through to
        // the pure/api-shape paths anyway, so the value here is moot.
        0.0
    };

    let verify = compute_verify_report(&items, &resolved_fns);

    let shape = derive_shape(
        &effects,
        has_main,
        &exposes_opaque,
        classified_uses_handle,
        exposed_uses_handle,
        &exposes,
    );
    let kind = derive_kind(&shape, effectful_fn_ratio);
    let layer = classify_layer(&histogram, fingerprints, basis);

    Ok(ShapeReport {
        module: module_name,
        file: file_label.to_string(),
        depends,
        effects,
        exposes_opaque,
        has_main,
        shape,
        kind,
        effectful_fn_ratio,
        verify,
        histogram,
        layer,
        fns: fn_shapes,
        patterns: program_shape.patterns,
    })
}

fn uses_runtime_handle(fd: &ResolvedFnDef) -> bool {
    fd.params.iter().any(|(_, ty)| is_runtime_handle_type(ty))
        || is_runtime_handle_type(&fd.return_type)
}

fn is_runtime_handle_type(t: &Type) -> bool {
    use crate::types::checker::effect_classification::is_verify_fabricable_handle;
    walk_type_named(t, &is_verify_fabricable_handle)
}

fn walk_type_named(t: &Type, pred: &dyn Fn(&str) -> bool) -> bool {
    match t {
        Type::Named { name, .. } => pred(name),
        Type::Result(a, b) | Type::Map(a, b) => {
            walk_type_named(a, pred) || walk_type_named(b, pred)
        }
        Type::Option(a) | Type::List(a) | Type::Vector(a) => walk_type_named(a, pred),
        Type::Tuple(xs) => xs.iter().any(|x| walk_type_named(x, pred)),
        Type::Fn(args, ret, _) => {
            args.iter().any(|a| walk_type_named(a, pred)) || walk_type_named(ret, pred)
        }
        _ => false,
    }
}

fn compute_verify_report(items: &[TopLevel], resolved_fns: &[&ResolvedFnDef]) -> VerifyReport {
    use crate::ast::VerifyKind;
    let mut blocks = 0usize;
    let mut covered: HashSet<String> = HashSet::new();
    let mut has_cases = false;
    let mut has_laws = false;
    let mut has_trace = false;
    for it in items {
        if let TopLevel::Verify(v) = it {
            blocks += 1;
            covered.insert(v.fn_name.clone());
            if v.trace {
                has_trace = true;
            } else {
                match &v.kind {
                    VerifyKind::Cases => has_cases = true,
                    VerifyKind::Law(_) => has_laws = true,
                }
            }
        }
    }
    let level = match (has_cases, has_laws, has_trace) {
        (false, false, false) => VerifyLevel::None,
        (true, false, false) => VerifyLevel::Cases,
        (false, true, false) => VerifyLevel::Laws,
        (false, false, true) => VerifyLevel::Trace,
        _ => VerifyLevel::Mixed,
    };
    // Eligible = non-main fns. Coverage = eligible fns that appear in at
    // least one verify block under their name.
    let eligible_names: HashSet<String> = resolved_fns
        .iter()
        .filter(|f| f.name != "main")
        .map(|f| f.name.clone())
        .collect();
    let covered_count = eligible_names.intersection(&covered).count();
    VerifyReport {
        level,
        blocks,
        covered_fns: covered_count,
        eligible_fns: eligible_names.len(),
    }
}

fn derive_shape(
    effects: &[String],
    has_main: bool,
    exposes_opaque: &[String],
    classified_uses_handle: bool,
    exposed_uses_handle: bool,
    exposes: &[String],
) -> ModuleShape {
    use crate::types::checker::effect_classification::is_classified;

    let any_effect = !effects.is_empty();
    let all_classified = any_effect
        && effects
            .iter()
            .all(|e| is_classified_effect_or_namespace(e, &is_classified));
    let purity = if !any_effect {
        Purity::Pure
    } else if all_classified {
        Purity::ClassifiedEffectful
    } else {
        Purity::ShellEffectful
    };
    let entry = if has_main { Entry::Main } else { Entry::None };
    let state_shape = match purity {
        Purity::Pure => StateShape::Stateless,
        _ if classified_uses_handle => StateShape::PureStateMachine,
        _ => StateShape::ExternalWorld,
    };
    let type_surface = if classified_uses_handle {
        TypeSurface::RuntimeHandle
    } else if !exposes_opaque.is_empty() {
        TypeSurface::UserOpaque
    } else if !exposes.is_empty() {
        TypeSurface::PlainDataTypes
    } else {
        TypeSurface::NoTypes
    };
    // ServiceBoundary only when the handle actually reaches the exposed
    // surface — i.e. at least one fn in `exposes [...]` takes/returns the
    // handle. A module that threads `Tcp.Connection` only internally
    // (a webapp that talks to Redis but doesn't re-export its client)
    // stays at `ExposedLibrary` so its Kind doesn't get mis-labeled as
    // `ServiceClient`.
    let api_shape = if exposed_uses_handle {
        ApiShape::ServiceBoundary
    } else if !exposes.is_empty() {
        ApiShape::ExposedLibrary
    } else {
        ApiShape::Closed
    };
    ModuleShape {
        purity,
        entry,
        state_shape,
        type_surface,
        api_shape,
    }
}

fn is_classified_effect_or_namespace(eff: &str, is_classified: &dyn Fn(&str) -> bool) -> bool {
    if is_classified(eff) {
        return true;
    }
    // Namespace shorthand: `Disk`, `Tcp`, `Http`, etc. Accept if at least
    // one classified method has this prefix.
    let with_dot = format!("{eff}.");
    use crate::types::checker::effect_classification::classifications_for_proof_subset;
    classifications_for_proof_subset()
        .iter()
        .any(|c| c.method.starts_with(&with_dot))
}

// ─── Renderers ───────────────────────────────────────────────────────────────

pub struct RenderOptions {
    pub summary: bool,
}

/// One human-readable line for a single `ModulePattern`. Format:
/// `<VariantName>  <key facts>` with the variant on the left so a
/// `grep RefinementSmartConstructor` over the corpus output works.
/// Scope-qualified names are rendered as `prefix::name` when the
/// pattern lives in a dep module.
fn render_module_pattern_line(p: &ModulePattern) -> String {
    // `_shape_colorize` is in module scope above — its methods
    // (`bold`, `cyan`, …) are usable directly without a local import.
    let scoped = |scope: &Option<String>, name: &str| -> String {
        match scope {
            Some(prefix) => format!("{prefix}::{name}"),
            None => name.to_string(),
        }
    };
    match p {
        ModulePattern::RefinementSmartConstructor {
            scope,
            type_name,
            carrier_field,
            carrier_type,
            constructor_fn,
            ..
        } => format!(
            "{}  {}({}: {})  via {}",
            "RefinementSmartConstructor".magenta().bold(),
            scoped(scope, type_name).bold(),
            carrier_field,
            carrier_type.cyan(),
            scoped(scope, constructor_fn).bold(),
        ),
        ModulePattern::WrapperOverRecursion {
            wrapper_scope,
            wrapper_fn,
            inner_scope,
            inner_fn,
        } => format!(
            "{}        {} → {}",
            "WrapperOverRecursion".magenta().bold(),
            scoped(wrapper_scope, wrapper_fn).bold(),
            scoped(inner_scope, inner_fn).bold(),
        ),
        ModulePattern::ResultPipelineChain {
            scope,
            fn_name,
            step_count,
            ..
        } => format!(
            "{}         {}  ({} steps)",
            "ResultPipelineChain".magenta().bold(),
            scoped(scope, fn_name).bold(),
            step_count.to_string().yellow(),
        ),
        ModulePattern::RendererFormatter { scope, fn_name } => format!(
            "{}           {}",
            "RendererFormatter".magenta().bold(),
            scoped(scope, fn_name).bold(),
        ),
        ModulePattern::MatchDispatcherFold {
            scope,
            fn_name,
            list_param,
        } => format!(
            "{}         {}  (over {})",
            "MatchDispatcherFold".magenta().bold(),
            scoped(scope, fn_name).bold(),
            list_param.cyan(),
        ),
        ModulePattern::AccumulatorFold {
            scope,
            wrapper_fn,
            loop_fn,
            step_fn,
            step_op,
            finish_fn,
            ..
        } => {
            let step = step_fn
                .clone()
                .unwrap_or_else(|| step_op.map(|o| format!("{o:?}")).unwrap_or_default());
            let finish = finish_fn.clone().unwrap_or_else(|| "id".to_string());
            format!(
                "{}           {} → {}  (step {}, finish {})",
                "AccumulatorFold".magenta().bold(),
                scoped(scope, wrapper_fn).bold(),
                scoped(scope, loop_fn).bold(),
                step.cyan(),
                finish.cyan(),
            )
        }
    }
}

pub fn render_text(report: &ShapeReport, opts: &RenderOptions) -> String {
    // `_shape_colorize` is in module scope above (see top-of-file
    // shim). Auto-disables coloring on non-TTY pipes and when the
    // `tty-render` feature is off (e.g. fuzz / mutator builds).
    let mut out = String::new();
    // Header: `Module:` and `Kind:` share the value column. `Module:` is
    // 7 chars + space, `Kind:` is 5 chars + 3 spaces — same total width.
    // Colors auto-disable on non-TTY (the `colored` crate detects
    // pipes and the NO_COLOR env var), so tests + JSON consumers see
    // plain text.
    out.push_str(&format!("{}  {}\n", "Module:".bold(), report.module.bold()));
    out.push_str(&format!(
        "{}    {}\n\n",
        "Kind:".bold(),
        report.kind.as_str().cyan().bold()
    ));
    out.push_str(&format!("{}\n", "ModuleShape:".bold()));
    out.push_str(&format!(
        "  purity        {}\n",
        report.shape.purity.as_str()
    ));
    out.push_str(&format!(
        "  entry         {}\n",
        report.shape.entry.as_str()
    ));
    out.push_str(&format!(
        "  state_shape   {}\n",
        report.shape.state_shape.as_str()
    ));
    out.push_str(&format!(
        "  type_surface  {}\n",
        report.shape.type_surface.as_str()
    ));
    out.push_str(&format!(
        "  api_shape     {}\n\n",
        report.shape.api_shape.as_str()
    ));

    // Verification: collapse the zero-block case to a single line — the
    // "0 (no) blocks, 0/0 fns covered" reading was confusing.
    if report.verify.blocks == 0 {
        out.push_str(&format!("{}  no verify blocks\n\n", "Verification:".bold()));
    } else {
        out.push_str(&format!(
            "{}  {} {} block{}, {}/{} fns covered\n\n",
            "Verification:".bold(),
            report.verify.blocks.to_string().yellow(),
            match report.verify.level {
                VerifyLevel::None => "(no)",
                VerifyLevel::Cases => "cases",
                VerifyLevel::Laws => "law",
                VerifyLevel::Trace => "trace",
                VerifyLevel::Mixed => "mixed",
            },
            if report.verify.blocks == 1 { "" } else { "s" },
            report.verify.covered_fns.to_string().yellow(),
            report.verify.eligible_fns.to_string().yellow(),
        ));
    }

    if report.histogram.total_fns == 0 {
        out.push_str(&format!(
            "{}     no classifiable fns (module only has `main` or no fns)\n",
            "Histogram:".bold()
        ));
    } else {
        out.push_str(&format!(
            "{} ({} fns):\n",
            "Histogram".bold(),
            report.histogram.total_fns.to_string().yellow()
        ));
        let sorted = report.histogram.sorted();
        let name_w = sorted
            .iter()
            .map(|(n, _, _)| n.as_str().len())
            .max()
            .unwrap_or(0)
            .max(20);
        for (name, count, pct) in &sorted {
            let bar = histogram_bar(*pct, 20);
            out.push_str(&format!(
                "  {:<width$}  {}  {:>3}  ({})\n",
                name.as_str(),
                bar.cyan(),
                format!("{:.0}%", pct).yellow(),
                count.to_string().dimmed(),
                width = name_w,
            ));
        }
    }
    if let Some(verdict) = &report.layer {
        if verdict.uncertain {
            out.push_str(&format!(
                "\n{} {}  (best: {}, confidence {}, margin Δ{}, basis: {})\n",
                "Layer:".bold(),
                "uncertain".yellow().bold(),
                verdict.layer.as_str().cyan().bold(),
                format!("{:.2}", verdict.confidence).yellow(),
                format!("{:.1}", verdict.margin).yellow(),
                verdict.basis.dimmed(),
            ));
        } else {
            out.push_str(&format!(
                "\n{} {}  (confidence {}, margin Δ{}, basis: {})\n",
                "Layer:".bold(),
                verdict.layer.as_str().cyan().bold(),
                format!("{:.2}", verdict.confidence).yellow(),
                format!("{:.1}", verdict.margin).yellow(),
                verdict.basis.dimmed(),
            ));
        }
        // Runners-up (top 3 minus best). Hides nothing — even when
        // confidence is high the user sees how far the alternatives
        // are. "Δ" is the raw Euclidean distance in the 5-bucket %
        // simplex; higher = further from observed histogram.
        let runners: Vec<String> = verdict
            .candidates
            .iter()
            .skip(1)
            .map(|(layer, dist)| format!("{} Δ{:.1}", layer.as_str(), dist))
            .collect();
        if !runners.is_empty() {
            out.push_str(&format!(
                "       {} {}\n",
                "next:".dimmed(),
                runners.join(", ").dimmed()
            ));
        }
    } else {
        out.push_str(&format!("\n{} insufficient data\n", "Layer:".bold()));
    }

    if !report.patterns.is_empty() {
        out.push_str(&format!("\n{}\n", "Module patterns:".bold()));
        for p in &report.patterns {
            out.push_str("  ");
            out.push_str(&render_module_pattern_line(p));
            out.push('\n');
        }
    }

    if !opts.summary {
        out.push_str(&format!("\n{}\n", "Functions:".bold()));
        let name_w = report
            .fns
            .iter()
            .map(|f| f.name.len())
            .max()
            .unwrap_or(0)
            .max(16);
        for f in &report.fns {
            let labels_str = if f.labels.is_empty() {
                "unclassified".to_string()
            } else {
                f.labels
                    .iter()
                    .map(|a| a.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            };
            out.push_str(&format!(
                "  {:<width$}  {}\n",
                f.name,
                labels_str.dimmed(),
                width = name_w,
            ));
        }
    }

    out
}

fn histogram_bar(pct: f64, width: usize) -> String {
    let filled = ((pct / 100.0) * width as f64).round() as usize;
    let filled = filled.min(width);
    let mut s = String::with_capacity(width * 3);
    for _ in 0..filled {
        s.push('â–ˆ');
    }
    for _ in filled..width {
        s.push('â–‘');
    }
    s
}

pub fn render_json(report: &ShapeReport) -> serde_json::Value {
    use serde_json::json;
    let layer = report.layer.as_ref().map(|v| {
        let candidates: Vec<serde_json::Value> = v
            .candidates
            .iter()
            .map(|(layer, dist)| json!({"name": layer.as_str(), "distance": dist}))
            .collect();
        json!({
            "name": v.layer.as_str(),
            "confidence": v.confidence,
            "margin": v.margin,
            "uncertain": v.uncertain,
            "candidates": candidates,
            "basis": v.basis,
            "support_fns": v.support_fns,
        })
    });
    let histogram_counts: serde_json::Value = report
        .histogram
        .counts
        .iter()
        .filter(|(_, c)| **c > 0)
        .map(|(k, c)| (k.as_str().to_string(), serde_json::Value::from(*c)))
        .collect::<serde_json::Map<_, _>>()
        .into();
    let fns: Vec<serde_json::Value> = report
        .fns
        .iter()
        .map(|f| {
            let labels: Vec<&str> = f.labels.iter().map(|a| a.as_str()).collect();
            json!({
                "name": f.name,
                "primary": f.primary.as_str(),
                "labels": labels,
            })
        })
        .collect();
    let patterns: Vec<serde_json::Value> =
        report.patterns.iter().map(module_pattern_to_json).collect();
    json!({
        "module": report.module,
        "file": report.file,
        "facts": {
            "fn_count": report.fns.len(),
            "has_main": report.has_main,
            "exposes_opaque": report.exposes_opaque,
            "depends": report.depends,
            "effects": report.effects,
        },
        "vector": {
            "purity": report.shape.purity.as_str(),
            "entry": report.shape.entry.as_str(),
            "state_shape": report.shape.state_shape.as_str(),
            "type_surface": report.shape.type_surface.as_str(),
            "api_shape": report.shape.api_shape.as_str(),
        },
        "kind": {
            "name": report.kind.as_str(),
            "rule": report.kind.rule(),
        },
        "verification": {
            "level": report.verify.level.as_str(),
            "blocks": report.verify.blocks,
            "covered_fns": report.verify.covered_fns,
            "eligible_fns": report.verify.eligible_fns,
        },
        "histogram": {
            "counts": histogram_counts,
            "total_fns": report.histogram.total_fns,
        },
        "layer": layer,
        "fns": fns,
        "patterns": patterns,
    })
}

/// JSON encoding of one [`ModulePattern`]. Each variant becomes an
/// object with a `kind` tag plus the variant's typed payload, mirror
/// of the text renderer's grep-friendly format. `null` instead of
/// `None` keeps the schema explicit for downstream tooling.
fn module_pattern_to_json(p: &ModulePattern) -> serde_json::Value {
    use serde_json::json;
    let scope_json = |s: &Option<String>| match s {
        Some(prefix) => serde_json::Value::String(prefix.clone()),
        None => serde_json::Value::Null,
    };
    match p {
        ModulePattern::RefinementSmartConstructor {
            scope,
            type_name,
            carrier_field,
            carrier_type,
            constructor_fn,
            param_name,
            ..
        } => json!({
            "kind": "RefinementSmartConstructor",
            "scope": scope_json(scope),
            "type_name": type_name,
            "carrier_field": carrier_field,
            "carrier_type": carrier_type,
            "constructor_fn": constructor_fn,
            "param_name": param_name,
        }),
        ModulePattern::WrapperOverRecursion {
            wrapper_scope,
            wrapper_fn,
            inner_scope,
            inner_fn,
        } => json!({
            "kind": "WrapperOverRecursion",
            "wrapper_scope": scope_json(wrapper_scope),
            "wrapper_fn": wrapper_fn,
            "inner_scope": scope_json(inner_scope),
            "inner_fn": inner_fn,
        }),
        ModulePattern::ResultPipelineChain {
            scope,
            fn_name,
            step_count,
            step_fns,
        } => json!({
            "kind": "ResultPipelineChain",
            "scope": scope_json(scope),
            "fn_name": fn_name,
            "step_count": step_count,
            "step_fns": step_fns,
        }),
        ModulePattern::RendererFormatter { scope, fn_name } => json!({
            "kind": "RendererFormatter",
            "scope": scope_json(scope),
            "fn_name": fn_name,
        }),
        ModulePattern::MatchDispatcherFold {
            scope,
            fn_name,
            list_param,
        } => json!({
            "kind": "MatchDispatcherFold",
            "scope": scope_json(scope),
            "fn_name": fn_name,
            "list_param": list_param,
        }),
        ModulePattern::AccumulatorFold {
            scope,
            wrapper_fn,
            loop_fn,
            list_param,
            acc_param,
            step_fn,
            step_op,
            finish_fn,
            driver_type,
            step_value_first,
        } => json!({
            "kind": "AccumulatorFold",
            "scope": scope_json(scope),
            "wrapper_fn": wrapper_fn,
            "loop_fn": loop_fn,
            "list_param": list_param,
            "acc_param": acc_param,
            "step_fn": step_fn,
            "step_op": step_op.map(|o| format!("{o:?}")),
            "finish_fn": finish_fn,
            "driver_type": driver_type,
            "step_value_first": step_value_first,
        }),
    }
}

// ─── Corpus (directory) mode ────────────────────────────────────────────────

/// Outcome of analyzing a single file inside a corpus walk. Files that
/// fail typecheck or parse get the error attached instead of being
/// silently skipped — the corpus view should show what's broken.
///
/// `report` is boxed because `ShapeReport` carries the full per-fn
/// listing — a large size delta between the two variants would inflate
/// every `Vec<CorpusEntry>` with padding (clippy's `large_enum_variant`).
#[derive(Debug, Clone)]
pub enum CorpusEntry {
    Analyzed {
        rel_path: String,
        report: Box<ShapeReport>,
    },
    Skipped {
        rel_path: String,
        reason: String,
    },
}

/// Walk a directory recursively and analyze every `.av` file.
/// `root` is also used as the default `module_root` for dep resolution
/// — callers that want a different module root can pass it explicitly.
pub fn analyze_dir(
    root: &Path,
    module_root_hint: Option<&str>,
    fingerprints: &[LayerFingerprint],
    basis: &str,
) -> Result<Vec<CorpusEntry>, String> {
    let mut files = Vec::new();
    collect_av_files(root, &mut files)?;
    files.sort();
    let effective_module_root = match module_root_hint {
        Some(r) => r.to_string(),
        None => root.to_string_lossy().to_string(),
    };
    let mut entries = Vec::with_capacity(files.len());
    for path in files {
        let rel = path
            .strip_prefix(root)
            .unwrap_or(&path)
            .to_string_lossy()
            .to_string();
        match analyze_path_with(&path, Some(&effective_module_root), fingerprints, basis) {
            Ok(report) => entries.push(CorpusEntry::Analyzed {
                rel_path: rel,
                report: Box::new(report),
            }),
            Err(reason) => entries.push(CorpusEntry::Skipped {
                rel_path: rel,
                reason,
            }),
        }
    }
    Ok(entries)
}

fn collect_av_files(path: &Path, out: &mut Vec<std::path::PathBuf>) -> Result<(), String> {
    if path.is_file() {
        if path.extension().and_then(|s| s.to_str()) == Some("av") {
            out.push(path.to_path_buf());
        }
        return Ok(());
    }
    let entries = std::fs::read_dir(path).map_err(|e| {
        format!(
            "aver shape: cannot read directory '{}': {}",
            path.display(),
            e
        )
    })?;
    for entry in entries {
        let entry = entry
            .map_err(|e| format!("aver shape: read_dir error in '{}': {}", path.display(), e))?;
        let name = entry.file_name();
        let name_str = name.to_string_lossy();
        // Skip hidden + common build/dep directories.
        if name_str.starts_with('.')
            || name_str == "target"
            || name_str == "node_modules"
            || name_str == "pkg"
        {
            continue;
        }
        let p = entry.path();
        if p.is_dir() {
            collect_av_files(&p, out)?;
        } else if p.extension().and_then(|s| s.to_str()) == Some("av") {
            out.push(p);
        }
    }
    Ok(())
}

/// Per-Kind / per-Layer aggregate over a corpus.
#[derive(Debug, Clone, Default)]
pub struct CorpusSummary {
    pub total_files: usize,
    pub analyzed_files: usize,
    pub skipped_files: usize,
    pub total_fns: usize,
    pub kind_counts: BTreeMap<Kind, usize>,
    pub layer_counts: BTreeMap<Layer, usize>,
    pub archetype_counts: BTreeMap<Archetype, usize>,
}

pub fn summarize_corpus(entries: &[CorpusEntry]) -> CorpusSummary {
    let mut s = CorpusSummary {
        total_files: entries.len(),
        ..Default::default()
    };
    for e in entries {
        match e {
            CorpusEntry::Analyzed { report, .. } => {
                s.analyzed_files += 1;
                s.total_fns += report.histogram.total_fns;
                *s.kind_counts.entry(report.kind).or_insert(0) += 1;
                if let Some(v) = &report.layer {
                    *s.layer_counts.entry(v.layer).or_insert(0) += 1;
                }
                for (arch, c) in &report.histogram.counts {
                    *s.archetype_counts.entry(*arch).or_insert(0) += c;
                }
            }
            CorpusEntry::Skipped { .. } => {
                s.skipped_files += 1;
            }
        }
    }
    s
}

pub fn render_corpus_text(entries: &[CorpusEntry], opts: &RenderOptions) -> String {
    let mut out = String::new();
    let summary = summarize_corpus(entries);

    if !opts.summary {
        out.push_str(&format!(
            "Corpus: {} files ({} analyzed, {} skipped)\n\n",
            summary.total_files, summary.analyzed_files, summary.skipped_files,
        ));
        let path_w = entries
            .iter()
            .map(|e| match e {
                CorpusEntry::Analyzed { rel_path, .. } | CorpusEntry::Skipped { rel_path, .. } => {
                    rel_path.len()
                }
            })
            .max()
            .unwrap_or(0)
            .max(30);
        for e in entries {
            match e {
                CorpusEntry::Analyzed { rel_path, report } => {
                    // Layer cell carries confidence + margin always; when
                    // uncertain, prefix with "uncertain — " so the user
                    // can scan a corpus column and see ambivalent verdicts
                    // without losing the best-fit name.
                    let layer = report
                        .layer
                        .as_ref()
                        .map(|v| {
                            let suffix = format!(
                                "{} (conf {:.2}, Δ{:.1})",
                                v.layer.as_str(),
                                v.confidence,
                                v.margin
                            );
                            if v.uncertain {
                                format!("uncertain — {}", suffix)
                            } else {
                                suffix
                            }
                        })
                        .unwrap_or_else(|| "—".to_string());
                    out.push_str(&format!(
                        "  {:<width$}  {:<16}  layer: {}\n",
                        rel_path,
                        report.kind.as_str(),
                        layer,
                        width = path_w,
                    ));
                }
                CorpusEntry::Skipped { rel_path, reason } => {
                    out.push_str(&format!(
                        "  {:<width$}  SKIPPED        ({})\n",
                        rel_path,
                        reason,
                        width = path_w,
                    ));
                }
            }
        }
        out.push('\n');
    }

    // Aggregate block — printed in both modes; --summary just omits the
    // per-file table above.
    out.push_str(&format!(
        "Corpus summary: {}/{} analyzed, {} fns classified\n",
        summary.analyzed_files, summary.total_files, summary.total_fns,
    ));
    if !summary.kind_counts.is_empty() {
        out.push_str("\n  Kind distribution:\n");
        let mut kinds: Vec<_> = summary.kind_counts.iter().collect();
        kinds.sort_by(|a, b| b.1.cmp(a.1));
        for (kind, count) in kinds {
            out.push_str(&format!("    {:<24}  {}\n", kind.as_str(), count));
        }
    }
    if !summary.layer_counts.is_empty() {
        out.push_str("\n  Layer distribution:\n");
        let mut layers: Vec<_> = summary.layer_counts.iter().collect();
        layers.sort_by(|a, b| b.1.cmp(a.1));
        for (layer, count) in layers {
            out.push_str(&format!("    {:<24}  {}\n", layer.as_str(), count));
        }
    }
    if !summary.archetype_counts.is_empty() {
        out.push_str("\n  Archetype distribution (across all fns):\n");
        let mut archs: Vec<_> = summary
            .archetype_counts
            .iter()
            .filter(|(_, c)| **c > 0)
            .collect();
        archs.sort_by(|a, b| b.1.cmp(a.1));
        let name_w = archs
            .iter()
            .map(|(n, _)| n.as_str().len())
            .max()
            .unwrap_or(0)
            .max(20);
        for (arch, count) in archs {
            let pct = if summary.total_fns == 0 {
                0.0
            } else {
                100.0 * *count as f64 / summary.total_fns as f64
            };
            let bar = histogram_bar(pct, 20);
            out.push_str(&format!(
                "    {:<width$}  {}  {:>3.0}%  ({})\n",
                arch.as_str(),
                bar,
                pct,
                count,
                width = name_w,
            ));
        }
    }
    // Skipped files: list per-file reason so the user sees what got
    // dropped and why. Without this the summary's "X analyzed, Y
    // skipped" line gave a count but no actionable info.
    let skipped: Vec<(&str, &str)> = entries
        .iter()
        .filter_map(|e| match e {
            CorpusEntry::Skipped { rel_path, reason } => Some((rel_path.as_str(), reason.as_str())),
            _ => None,
        })
        .collect();
    if !skipped.is_empty() {
        out.push_str(&format!("\n  Skipped ({} files):\n", skipped.len()));
        let path_w = skipped
            .iter()
            .map(|(p, _)| p.len())
            .max()
            .unwrap_or(0)
            .max(30);
        for (path, reason) in skipped {
            // Trim reason: typecheck errors can carry full module-line
            // diagnostics; one-liner is enough at corpus summary level.
            let one_line = reason.lines().next().unwrap_or(reason);
            out.push_str(&format!(
                "    {:<width$}  {}\n",
                path,
                one_line,
                width = path_w
            ));
        }
    }
    out
}

pub fn render_corpus_json(entries: &[CorpusEntry]) -> Vec<serde_json::Value> {
    use serde_json::json;
    entries
        .iter()
        .map(|e| match e {
            CorpusEntry::Analyzed { rel_path, report } => {
                let mut v = render_json(report);
                if let Some(obj) = v.as_object_mut() {
                    obj.insert("rel_path".to_string(), json!(rel_path));
                }
                v
            }
            CorpusEntry::Skipped { rel_path, reason } => json!({
                "rel_path": rel_path,
                "skipped": true,
                "reason": reason,
            }),
        })
        .collect()
}