calcit 0.13.25

Interpreter and js codegen for Calcit
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
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
use cirru_edn::{Edn, EdnListView, EdnMapView, EdnSetView, EdnStructView, EdnTag, from_edn};
use cirru_parser::Cirru;
use md5::{Digest, Md5};
use serde::{Deserialize, Serialize};
use std::collections::hash_map::HashMap;
use std::collections::hash_set::HashSet;
use std::path::Path;
use std::sync::Arc;

use crate::calcit::{
  Calcit, CalcitFnTypeAnnotation, CalcitTypeAnnotation, DYNAMIC_TYPE, SchemaKind, with_type_annotation_warning_context,
};
use crate::data::edn::{format_deserialize_error, format_edn_display};

const SNAPSHOT_ABOUT_MESSAGE: &str = "Machine-generated snapshot. Do not edit directly — changes will be overwritten. Use `cr query` to inspect and `cr edit`/`cr tree` to modify. Run `cr docs agents --full` first. Manual edits must follow format and schema conventions, then run `cr edit format`.";

fn default_version() -> String {
  "0.0.0".to_owned()
}

pub const DEFAULT_ENTRY_NAME: &str = "default";

fn default_active_entry() -> String {
  DEFAULT_ENTRY_NAME.to_owned()
}

fn format_edn_preview(value: &Edn) -> String {
  format_edn_display(value)
}

fn schema_path_label(path: &[String]) -> String {
  if path.is_empty() { "<root>".to_owned() } else { path.join("") }
}

fn map_key_path_segment(key: &Edn) -> String {
  match key {
    Edn::Tag(tag) => format!(".{}", tag.ref_str()),
    Edn::Str(text) => format!(".{text}"),
    Edn::Symbol(text) => format!(".{text}"),
    _ => ".<key>".to_owned(),
  }
}

fn canonical_schema_field_name(text: &str) -> Option<&'static str> {
  match text.trim_start_matches(':') {
    "kind" => Some("kind"),
    "args" => Some("args"),
    "return" => Some("return"),
    "rest" => Some("rest"),
    "generics" => Some("generics"),
    "where" => Some("where"),
    _ => None,
  }
}

fn canonical_schema_kind_name(text: &str) -> Option<&'static str> {
  match text.trim_start_matches(':') {
    "fn" => Some("fn"),
    "macro" => Some("macro"),
    _ => None,
  }
}

fn is_callable_schema_wrapper_variant(value: &str) -> bool {
  matches!(value, "fn" | "macro" | "Fn" | "Macro")
}

fn is_macro_schema_wrapper_variant(value: &str) -> bool {
  matches!(value, "macro" | "Macro")
}

fn normalize_schema_map(map: &EdnMapView) -> EdnMapView {
  let mut normalized = EdnMapView::default();

  for (key, value) in map.0.iter() {
    let normalized_key = match key {
      Edn::Tag(tag) => Edn::tag(tag.ref_str()),
      Edn::Str(text) => canonical_schema_field_name(text).map(Edn::tag).unwrap_or_else(|| key.clone()),
      Edn::Symbol(text) => canonical_schema_field_name(text).map(Edn::tag).unwrap_or_else(|| key.clone()),
      _ => key.clone(),
    };

    let normalized_value = match (&normalized_key, value) {
      (Edn::Tag(tag), Edn::Str(text)) | (Edn::Tag(tag), Edn::Symbol(text)) if tag.ref_str() == "kind" => {
        canonical_schema_kind_name(text).map(Edn::tag).unwrap_or_else(|| value.clone())
      }
      _ => value.clone(),
    };

    normalized.insert(normalized_key, normalized_value);
  }

  normalized
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SnapshotRunMode {
  Native,
  Js,
}

impl SnapshotRunMode {
  pub fn as_str(self) -> &'static str {
    match self {
      SnapshotRunMode::Native => "native",
      SnapshotRunMode::Js => "js",
    }
  }
}

impl std::fmt::Display for SnapshotRunMode {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.write_str(self.as_str())
  }
}

/// Host target selected by an entry. This stays separate from the execution
/// mode because Node.js code is emitted by the JavaScript backend too.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SnapshotTarget {
  Browser,
  Node,
  Native,
  Wasm,
}

impl SnapshotTarget {
  pub fn as_str(self) -> &'static str {
    match self {
      Self::Browser => "browser",
      Self::Node => "node",
      Self::Native => "native",
      Self::Wasm => "wasm",
    }
  }
}

/// Per-entry capability policy. Features remain implementation metadata; this
/// policy only controls the diagnostics emitted when a body uses a capability
/// without declaring it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum FeaturePolicy {
  #[default]
  Allow,
  Warn,
  Error,
}

impl FeaturePolicy {
  pub fn as_str(self) -> &'static str {
    match self {
      Self::Allow => "allow",
      Self::Warn => "warn",
      Self::Error => "error",
    }
  }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SnapshotEntry {
  pub mode: SnapshotRunMode,
  #[serde(rename = "init-fn")]
  pub init_fn: String,
  #[serde(rename = "reload-fn")]
  pub reload_fn: String,
  /// Human-oriented semantic context for this entry.
  #[serde(default)]
  pub description: String,
  #[serde(default)]
  pub modules: Vec<String>,
  #[serde(default, rename = "type-slots")]
  pub type_slots: HashMap<String, String>,
  #[serde(default, rename = "feature-policy")]
  pub feature_policy: HashMap<String, FeaturePolicy>,
  /// Optional host target. Omitting it preserves old projects and disables
  /// target-specific FFI validation for that entry.
  #[serde(default)]
  pub target: Option<SnapshotTarget>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NsEntry {
  pub doc: String,
  pub code: Cirru,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileInSnapShot {
  pub ns: NsEntry,
  pub defs: HashMap<String, CodeEntry>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct RawCodeEntry {
  pub doc: String,
  #[serde(default)]
  pub examples: Vec<Cirru>,
  #[serde(default)]
  pub tests: Vec<RawTestEntry>,
  #[serde(default)]
  pub tags: Vec<String>,
  pub code: Cirru,
  #[serde(default)]
  pub schema: Option<Edn>,
  #[serde(default)]
  pub ffi: Option<Edn>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct RawTestEntry {
  pub name: String,
  pub code: Cirru,
  #[serde(default)]
  pub tags: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct RawFileInSnapShot {
  pub ns: NsEntry,
  pub defs: HashMap<String, RawCodeEntry>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct RawSnapshot {
  pub package: String,
  pub about: Option<String>,
  #[serde(default = "default_version")]
  pub version: String,
  pub entries: HashMap<String, SnapshotEntry>,
  pub files: HashMap<String, RawFileInSnapShot>,
}

impl RawCodeEntry {
  fn into_code_entry(self, owner: &str) -> Result<CodeEntry, String> {
    let schema = match self.schema {
      None | Some(Edn::Nil) => DYNAMIC_TYPE.clone(),
      Some(value) => with_type_annotation_warning_context(owner.to_owned(), || parse_loaded_schema_annotation(&value, owner))?,
    };

    let tests = self
      .tests
      .into_iter()
      .map(|test| TestEntry {
        name: test.name,
        code: test.code,
        tags: tags_vec_to_set(test.tags),
      })
      .collect::<Vec<_>>();
    validate_test_entries(&tests, owner)?;

    Ok(CodeEntry {
      doc: self.doc,
      examples: self.examples,
      tests,
      tags: tags_vec_to_set(self.tags),
      code: self.code,
      schema,
      ffi: self.ffi,
    })
  }
}

pub fn decode_binary_snapshot(bytes: &[u8]) -> Result<Snapshot, String> {
  let raw: RawSnapshot = rmp_serde::from_slice(bytes).map_err(|e| e.to_string())?;
  let mut files: HashMap<String, FileInSnapShot> = HashMap::with_capacity(raw.files.len());

  for (file_name, raw_file) in raw.files {
    let ns = raw_file.ns;
    let mut defs: HashMap<String, CodeEntry> = HashMap::with_capacity(raw_file.defs.len());

    for (def_name, raw_entry) in raw_file.defs {
      let owner = format!("{file_name}/{def_name}");
      defs.insert(def_name, raw_entry.into_code_entry(&owner)?);
    }

    files.insert(file_name, FileInSnapShot { ns, defs });
  }

  Ok(Snapshot {
    package: raw.package,
    about: raw.about,
    version: raw.version,
    entries: raw.entries,
    files,
    active_entry: default_active_entry(),
  })
}

impl From<&FileInSnapShot> for Edn {
  fn from(data: &FileInSnapShot) -> Edn {
    let mut defs_map = EdnMapView::default();
    for (k, v) in &data.defs {
      defs_map.insert(Edn::str(k.as_str()), Edn::from(v));
    }
    Edn::Struct(EdnStructView {
      name: Arc::from("FileEntry"),
      pairs: vec![("defs".into(), Edn::from(defs_map)), ("ns".into(), Edn::from(&data.ns))], // TODO
    })
  }
}

impl TryFrom<Edn> for FileInSnapShot {
  type Error = String;
  fn try_from(data: Edn) -> Result<Self, String> {
    match data {
      Edn::Map(_) => {
        let preview = data.clone();
        from_edn(data).map_err(|e| format!("failed to parse FileInSnapShot: {}", format_deserialize_error(&e, &preview)))
      }
      Edn::Struct(struct_value) => {
        let mut ns = None;
        let mut defs = None;

        for (key, value) in struct_value.pairs.iter() {
          match key.arc_str().as_ref() {
            "ns" => {
              ns = Some(value.to_owned().try_into().map_err(|e| format!("failed to parse ns: {e}"))?);
            }
            "defs" => {
              defs = Some(value.to_owned().try_into().map_err(|e| format!("failed to parse defs: {e}"))?);
            }
            _ => {}
          }
        }

        let ns = ns.ok_or("Missing ns field in FileEntry")?;
        let defs = defs.ok_or("Missing defs field in FileEntry")?;
        Ok(FileInSnapShot { ns, defs })
      }
      _ => Err(format!(
        "Expected FileInSnapShot map or struct, but got: {}",
        format_edn_display(&data)
      )),
    }
  }
}

impl From<FileInSnapShot> for Edn {
  fn from(data: FileInSnapShot) -> Edn {
    let mut defs_map = EdnMapView::default();
    for (k, v) in data.defs {
      defs_map.insert(Edn::str(k.as_str()), Edn::from(v));
    }
    Edn::map_from_iter([("defs".into(), Edn::from(defs_map)), ("ns".into(), data.ns.into())])
  }
}

impl TryFrom<Edn> for NsEntry {
  type Error = String;
  fn try_from(data: Edn) -> Result<Self, String> {
    let mut doc = String::new();
    let mut code: Option<Cirru> = None;

    match data {
      Edn::Struct(struct_value) => {
        for (key, value) in &struct_value.pairs {
          match key.arc_str().as_ref() {
            "doc" => {
              doc = from_edn(value.to_owned())
                .map_err(|e| format!("failed to parse NsEntry.doc: {}", format_deserialize_error(&e, value)))?;
            }
            "code" => {
              code = Some(
                from_edn(value.to_owned())
                  .map_err(|e| format!("failed to parse NsEntry.code: {}", format_deserialize_error(&e, value)))?,
              );
            }
            _ => {}
          }
        }
      }
      Edn::Map(map) => {
        if let Some(value) = map.get(&Edn::Tag(EdnTag::new("doc"))) {
          doc =
            from_edn(value.to_owned()).map_err(|e| format!("failed to parse NsEntry.doc: {}", format_deserialize_error(&e, value)))?;
        }
        if let Some(value) = map.get(&Edn::Tag(EdnTag::new("code"))) {
          code = Some(
            from_edn(value.to_owned()).map_err(|e| format!("failed to parse NsEntry.code: {}", format_deserialize_error(&e, value)))?,
          );
        }
      }
      other => {
        return Err(format!(
          "failed to parse NsEntry: expected struct/map, got: {}",
          format_edn_display(&other)
        ));
      }
    }

    Ok(NsEntry {
      doc,
      code: code.ok_or_else(|| "failed to parse NsEntry: missing code field".to_owned())?,
    })
  }
}

impl From<NsEntry> for Edn {
  fn from(data: NsEntry) -> Self {
    Edn::struct_from_pairs("NsEntry", &[("doc".into(), data.doc.into()), ("code".into(), data.code.into())])
  }
}

impl From<&NsEntry> for Edn {
  fn from(data: &NsEntry) -> Self {
    Edn::struct_from_pairs(
      "NsEntry",
      &[
        ("doc".into(), data.doc.to_owned().into()),
        ("code".into(), data.code.to_owned().into()),
      ],
    )
  }
}

/// Custom serde for `CodeEntry::schema`.
/// The binary RMP format stores schemas as `Option<Edn>` (compatible with `build.rs`);
/// at runtime we keep a parsed `Arc<CalcitTypeAnnotation>` for direct use.
mod schema_serde {
  use super::*;

  pub fn default_schema() -> Arc<CalcitTypeAnnotation> {
    DYNAMIC_TYPE.clone()
  }

  pub fn serialize<S>(schema: &Arc<CalcitTypeAnnotation>, s: S) -> Result<S::Ok, S::Error>
  where
    S: serde::Serializer,
  {
    let edn: Option<Edn> = match schema.as_ref() {
      CalcitTypeAnnotation::Dynamic => None,
      // Keep the binary snapshot representation of function schemas stable:
      // build.rs and older runtimes expect the direct map form here. Value
      // annotations use their ordinary type-expression representation.
      CalcitTypeAnnotation::Fn(fn_annot) => Some(fn_annot.to_schema_edn()),
      annotation => Some(schema_annotation_to_edn(annotation)),
    };
    edn.serialize(s)
  }

  pub fn deserialize<'de, D>(d: D) -> Result<Arc<CalcitTypeAnnotation>, D::Error>
  where
    D: serde::Deserializer<'de>,
  {
    let opt = Option::<Edn>::deserialize(d)?;
    Ok(match opt {
      None | Some(Edn::Nil) => DYNAMIC_TYPE.clone(),
      Some(v) => parse_loaded_schema_annotation(&v, "CodeEntry.schema").map_err(serde::de::Error::custom)?,
    })
  }
}

mod tags_serde {
  use super::*;

  pub fn serialize<S>(tags: &HashSet<EdnTag>, s: S) -> Result<S::Ok, S::Error>
  where
    S: serde::Serializer,
  {
    tags_set_to_vec(tags).serialize(s)
  }

  pub fn deserialize<'de, D>(d: D) -> Result<HashSet<EdnTag>, D::Error>
  where
    D: serde::Deserializer<'de>,
  {
    let tags = Vec::<String>::deserialize(d)?;
    Ok(tags_vec_to_set(tags))
  }
}

fn parse_loaded_schema_annotation(value: &Edn, owner: &str) -> Result<Arc<CalcitTypeAnnotation>, String> {
  if matches!(value, Edn::Nil) {
    return Ok(DYNAMIC_TYPE.clone());
  }

  // A top-level quoted symbol is rendered by Cirru EDN as `'String` (rather
  // than as a list context such as `[] 'String`) and parses back as `Quote`.
  // Treat that one-node quote as the canonical nominal type spelling while
  // keeping all older tag spellings accepted below.
  if let Edn::Quote(Cirru::Leaf(symbol)) = value {
    let annotation = CalcitTypeAnnotation::parse_type_annotation_from_edn(&Edn::Symbol(symbol.clone()));
    if CalcitTypeAnnotation::canonical_type_symbol_name(symbol).is_some() {
      return Ok(annotation);
    }
  }

  if matches!(value, Edn::Enum(view) if view.variant.as_ref() == "Dynamic" && view.extra.is_empty()) {
    return Ok(DYNAMIC_TYPE.clone());
  }

  // Primitive type tag stored as a plain EDN tag (e.g. :string, :number).
  if let Edn::Tag(tag) = value {
    let tag_name = tag.ref_str();
    if PRIMITIVE_SCHEMA_TAGS.contains(&tag_name) {
      return Ok(Arc::new(CalcitTypeAnnotation::from_tag_name(tag_name)));
    }
    return Err(format!(
      "unknown primitive schema tag `:{tag_name}` in {owner}; valid tags: {}",
      PRIMITIVE_SCHEMA_TAGS.join(", ")
    ));
  }

  if let Ok(normalized) = normalize_schema_edn(value) {
    let schema_cirru = parse_schema_cirru_from_edn(&normalized).map_err(|e| {
      format!(
        "failed to convert {owner} into Cirru: {e}; schema={}",
        format_edn_preview(&normalized)
      )
    })?;
    parse_schema_data(&schema_cirru)
      .map_err(|e| format!("failed to validate {owner}: {e}; schema={}", format_edn_preview(&normalized)))?;

    return CalcitTypeAnnotation::parse_fn_schema_from_edn(&normalized)
      .map(|s| Arc::new(CalcitTypeAnnotation::Fn(Arc::new(s))))
      .ok_or_else(|| {
        format!(
          "failed to parse {owner} as function schema after normalization; schema={}",
          format_edn_preview(&normalized)
        )
      });
  }

  let schema_cirru = parse_schema_cirru_from_edn(value)
    .map_err(|e| format!("failed to convert {owner} into Cirru: {e}; schema={}", format_edn_preview(value)))?;
  parse_schema_data(&schema_cirru).map_err(|e| format!("failed to validate {owner}: {e}; schema={}", format_edn_preview(value)))?;

  let annotation = CalcitTypeAnnotation::parse_type_annotation_from_edn(value);
  if matches!(annotation.as_ref(), CalcitTypeAnnotation::Dynamic) {
    return Err(format!(
      "failed to parse {owner} as a standalone type annotation; schema={}",
      format_edn_preview(value)
    ));
  }
  Ok(annotation)
}

fn tags_vec_to_set(tags: Vec<String>) -> HashSet<EdnTag> {
  tags.into_iter().map(|tag| EdnTag::new(tag.trim_start_matches(':'))).collect()
}

fn tags_set_to_vec(tags: &HashSet<EdnTag>) -> Vec<String> {
  let mut items: Vec<String> = tags.iter().map(|tag| format!(":{}", tag.ref_str())).collect();
  items.sort();
  items
}

pub fn parse_code_entry_tags_from_edn(value: &Edn) -> Result<HashSet<EdnTag>, String> {
  match value {
    Edn::Set(set) => {
      let mut tags = HashSet::with_capacity(set.0.len());
      for item in &set.0 {
        match item {
          Edn::Tag(tag) => {
            tags.insert(tag.clone());
          }
          other => {
            return Err(format!("CodeEntry.tags expects tag items, got: {}", format_edn_preview(other)));
          }
        }
      }
      Ok(tags)
    }
    other => Err(format!("CodeEntry.tags expects a hashset, got: {}", format_edn_preview(other))),
  }
}

fn tags_to_edn(tags: &HashSet<EdnTag>) -> Edn {
  #[allow(clippy::mutable_key_type)]
  let items: HashSet<Edn> = tags.iter().map(|tag| Edn::Tag(tag.clone())).collect();
  Edn::Set(EdnSetView(items))
}

/// Convert a loaded definition schema annotation into snapshot-style EDN.
pub fn schema_annotation_to_edn(schema: &CalcitTypeAnnotation) -> Edn {
  let expression = match schema {
    CalcitTypeAnnotation::Dynamic => Edn::Symbol(Arc::from("Dynamic")),
    CalcitTypeAnnotation::Fn(fn_annot) => fn_annot.to_wrapped_schema_edn(),
    // Runtime-resolved nominal types are intentionally persisted as their
    // broad schema kinds. Their concrete definitions belong to source code,
    // and serializing only a local name would lose namespace identity.
    CalcitTypeAnnotation::Custom(value) => match value.as_ref() {
      crate::calcit::Calcit::Tag(tag) => CalcitTypeAnnotation::canonical_type_symbol_name(tag.ref_str())
        .map(|name| Edn::Symbol(Arc::from(name)))
        .unwrap_or_else(|| Edn::Symbol(Arc::from("Dynamic"))),
      _ => Edn::Symbol(Arc::from("Dynamic")),
    },
    CalcitTypeAnnotation::StructValue(_) => Edn::Symbol(Arc::from("Struct")),
    CalcitTypeAnnotation::Struct(..) => Edn::Symbol(Arc::from("Struct")),
    CalcitTypeAnnotation::Enum(..) => Edn::Symbol(Arc::from("Enum")),
    CalcitTypeAnnotation::EnumValue(_) => Edn::Symbol(Arc::from("Enum")),
    CalcitTypeAnnotation::Trait(_) => Edn::Symbol(Arc::from("Trait")),
    other => other.to_type_edn(),
  };
  // A lone EDN symbol in a struct field is parsed as a Cirru quote. Wrap it
  // as a zero-argument type expression so Snapshot serialization remains
  // structurally unambiguous while rendering source-level `:: 'String`.
  match expression {
    Edn::Symbol(name) => Edn::enum_value(name, vec![]),
    other => other,
  }
}

fn code_entry_edn_pairs(data: &CodeEntry) -> Vec<(EdnTag, Edn)> {
  let schema = normalize_schema_for_code(&data.code, &data.schema);
  let schema_edn = schema_annotation_to_edn(schema.as_ref());
  let mut pairs = vec![
    ("doc".into(), data.doc.to_owned().into()),
    ("examples".into(), data.examples.to_owned().into()),
    ("code".into(), data.code.to_owned().into()),
    ("schema".into(), schema_edn),
  ];
  if !data.tests.is_empty() {
    pairs.insert(
      2,
      ("tests".into(), Edn::List(EdnListView(data.tests.iter().map(Edn::from).collect()))),
    );
  }
  if !data.tags.is_empty() {
    pairs.insert(2, ("tags".into(), tags_to_edn(&data.tags)));
  }
  if let Some(ffi) = &data.ffi {
    pairs.push(("ffi".into(), ffi.clone()));
  }
  pairs
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TestEntry {
  pub name: String,
  pub code: Cirru,
  #[serde(default, with = "tags_serde")]
  pub tags: HashSet<EdnTag>,
}

pub fn validate_test_names<'a>(names: impl IntoIterator<Item = &'a str>, owner: &str) -> Result<(), String> {
  let mut seen = HashSet::new();
  for name in names {
    if name.trim().is_empty() {
      return Err(format!("{owner}: test name must not be empty"));
    }
    if name != name.trim() {
      return Err(format!("{owner}: test name must not have leading or trailing whitespace: `{name}`"));
    }
    if !seen.insert(name) {
      return Err(format!("{owner}: duplicate test name `{name}`"));
    }
  }
  Ok(())
}

fn validate_test_entries(tests: &[TestEntry], owner: &str) -> Result<(), String> {
  validate_test_names(tests.iter().map(|test| test.name.as_str()), owner)
}

impl TryFrom<Edn> for TestEntry {
  type Error = String;

  fn try_from(data: Edn) -> Result<Self, Self::Error> {
    let mut name = None;
    let mut code = None;
    let mut tags = HashSet::new();
    let pairs = match data {
      Edn::Struct(value) => value.pairs,
      Edn::Map(value) => value
        .0
        .into_iter()
        .map(|(key, value)| match key {
          Edn::Tag(key) => Ok((key, value)),
          other => Err(format!("TestEntry field must use a tag key, got: {other}")),
        })
        .collect::<Result<Vec<_>, _>>()?,
      other => return Err(format!("failed to parse TestEntry: expected struct/map, got: {other}")),
    };

    for (key, value) in pairs {
      match key.ref_str() {
        "name" => {
          name = Some(
            from_edn(value.to_owned())
              .map_err(|error| format!("failed to parse TestEntry.name: {}", format_deserialize_error(&error, &value)))?,
          );
        }
        "code" => {
          code = Some(
            from_edn(value.to_owned())
              .map_err(|error| format!("failed to parse TestEntry.code: {}", format_deserialize_error(&error, &value)))?,
          );
        }
        "tags" => tags = parse_code_entry_tags_from_edn(&value)?,
        _ => {}
      }
    }

    let name: String = name.ok_or_else(|| "failed to parse TestEntry: missing name field".to_owned())?;
    validate_test_names([name.as_str()], "TestEntry").map_err(|error| format!("failed to parse {error}"))?;
    let code = code.ok_or_else(|| "failed to parse TestEntry: missing code field".to_owned())?;
    Ok(TestEntry { name, code, tags })
  }
}

impl From<&TestEntry> for Edn {
  fn from(data: &TestEntry) -> Self {
    let mut pairs = vec![
      (EdnTag::new("name"), Edn::Str(data.name.clone().into())),
      (EdnTag::new("code"), data.code.clone().into()),
    ];
    if !data.tags.is_empty() {
      pairs.push((EdnTag::new("tags"), tags_to_edn(&data.tags)));
    }
    Edn::struct_from_pairs("TestEntry", &pairs)
  }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CodeEntry {
  pub doc: String,
  #[serde(default)]
  pub examples: Vec<Cirru>,
  #[serde(default)]
  pub tests: Vec<TestEntry>,
  #[serde(default, with = "tags_serde")]
  pub tags: HashSet<EdnTag>,
  pub code: Cirru,
  #[serde(default = "schema_serde::default_schema", with = "schema_serde")]
  pub schema: Arc<CalcitTypeAnnotation>,
  #[serde(default)]
  pub ffi: Option<Edn>,
}

/// Return an opaque, deterministic revision for one definition.
///
/// The revision covers every persisted `CodeEntry` field and deliberately
/// sorts set-like metadata before hashing. It can therefore be used as a
/// read-only identity or as a future stale-edit precondition without depending
/// on map iteration order, file timestamps, or the definition's position in a
/// snapshot.
pub fn definition_revision(entry: &CodeEntry) -> Result<String, String> {
  fn update_part(hasher: &mut Md5, label: &str, content: &[u8]) {
    hasher.update(label.as_bytes());
    hasher.update([0]);
    hasher.update((content.len() as u64).to_le_bytes());
    hasher.update(content);
  }

  fn render_cirru_node_for_revision(node: &Cirru, label: &str) -> Result<Vec<u8>, String> {
    match node {
      // `cirru_parser::format` accepts top-level expressions, not a standalone
      // leaf. Examples and definition-attached tests intentionally allow both.
      Cirru::Leaf(value) => {
        let mut rendered = b"leaf\0".to_vec();
        rendered.extend_from_slice(value.as_bytes());
        Ok(rendered)
      }
      Cirru::List(_) => cirru_parser::format(std::slice::from_ref(node), true.into())
        .map(String::into_bytes)
        .map_err(|error| format!("Failed to format definition {label} for revision: {error}")),
    }
  }

  let mut hasher = Md5::new();
  update_part(&mut hasher, "doc", entry.doc.as_bytes());

  let mut tags = entry.tags.iter().map(|tag| tag.ref_str()).collect::<Vec<_>>();
  tags.sort_unstable();
  for tag in tags {
    update_part(&mut hasher, "tag", tag.as_bytes());
  }

  let schema = cirru_edn::format(&schema_annotation_to_edn(entry.schema.as_ref()), true)
    .map_err(|error| format!("Failed to format definition schema for revision: {error}"))?;
  update_part(&mut hasher, "schema", schema.as_bytes());

  let code = render_cirru_node_for_revision(&entry.code, "code")?;
  update_part(&mut hasher, "code", &code);

  for example in &entry.examples {
    let rendered = render_cirru_node_for_revision(example, "example")?;
    update_part(&mut hasher, "example", &rendered);
  }

  for test in &entry.tests {
    update_part(&mut hasher, "test-name", test.name.as_bytes());
    let mut tags = test.tags.iter().map(|tag| tag.ref_str()).collect::<Vec<_>>();
    tags.sort_unstable();
    for tag in tags {
      update_part(&mut hasher, "test-tag", tag.as_bytes());
    }
    let rendered = render_cirru_node_for_revision(&test.code, "test")?;
    update_part(&mut hasher, "test-code", &rendered);
  }

  if let Some(ffi) = &entry.ffi {
    let rendered =
      cirru_edn::format(ffi, true).map_err(|error| format!("Failed to format definition FFI metadata for revision: {error}"))?;
    update_part(&mut hasher, "ffi", rendered.as_bytes());
  }

  Ok(format!("md5:{}", hex::encode(hasher.finalize())))
}

impl TryFrom<Edn> for CodeEntry {
  type Error = String;
  fn try_from(data: Edn) -> Result<Self, String> {
    let mut doc = String::new();
    let mut examples: Vec<Cirru> = vec![];
    let mut tests: Vec<TestEntry> = vec![];
    let mut tags: HashSet<EdnTag> = HashSet::new();
    let mut code: Option<Cirru> = None;
    let mut schema: Arc<CalcitTypeAnnotation> = DYNAMIC_TYPE.clone();
    let mut ffi: Option<Edn> = None;

    match data {
      Edn::Struct(struct_value) => {
        for (key, value) in &struct_value.pairs {
          match key.arc_str().as_ref() {
            "doc" => {
              doc = from_edn(value.to_owned())
                .map_err(|e| format!("failed to parse CodeEntry.doc: {}", format_deserialize_error(&e, value)))?;
            }
            "examples" => {
              examples = from_edn(value.to_owned())
                .map_err(|e| format!("failed to parse CodeEntry.examples: {}", format_deserialize_error(&e, value)))?;
            }
            "tests" => {
              let Edn::List(items) = value else {
                return Err(format!("failed to parse CodeEntry.tests: expected list, got: {value}"));
              };
              tests = items.0.iter().cloned().map(TestEntry::try_from).collect::<Result<Vec<_>, _>>()?;
            }
            "tags" => {
              tags = parse_code_entry_tags_from_edn(value)?;
            }
            "code" => {
              code = Some(
                from_edn(value.to_owned())
                  .map_err(|e| format!("failed to parse CodeEntry.code: {}", format_deserialize_error(&e, value)))?,
              );
            }
            "schema" if !matches!(value, Edn::Nil) => {
              schema = parse_loaded_schema_annotation(value, "CodeEntry.schema")?;
            }
            "ffi" if !matches!(value, Edn::Nil) => {
              ffi = Some(value.to_owned());
            }
            _ => {}
          }
        }
      }
      Edn::Map(map) => {
        if let Some(value) = map.get(&Edn::Tag(EdnTag::new("doc"))) {
          doc = from_edn(value.to_owned())
            .map_err(|e| format!("failed to parse CodeEntry.doc: {}", format_deserialize_error(&e, value)))?;
        }
        if let Some(value) = map.get(&Edn::Tag(EdnTag::new("examples"))) {
          examples = from_edn(value.to_owned())
            .map_err(|e| format!("failed to parse CodeEntry.examples: {}", format_deserialize_error(&e, value)))?;
        }
        if let Some(value) = map.get(&Edn::Tag(EdnTag::new("tests"))) {
          let Edn::List(items) = value else {
            return Err(format!("failed to parse CodeEntry.tests: expected list, got: {value}"));
          };
          tests = items.0.iter().cloned().map(TestEntry::try_from).collect::<Result<Vec<_>, _>>()?;
        }
        if let Some(value) = map.get(&Edn::Tag(EdnTag::new("tags"))) {
          tags = parse_code_entry_tags_from_edn(value)?;
        }
        if let Some(value) = map.get(&Edn::Tag(EdnTag::new("code"))) {
          code = Some(
            from_edn(value.to_owned())
              .map_err(|e| format!("failed to parse CodeEntry.code: {}", format_deserialize_error(&e, value)))?,
          );
        }
        if let Some(value) = map.get(&Edn::Tag(EdnTag::new("schema")))
          && !matches!(value, Edn::Nil)
        {
          schema = parse_loaded_schema_annotation(value, "CodeEntry.schema")?;
        }
        if let Some(value) = map.get(&Edn::Tag(EdnTag::new("ffi")))
          && !matches!(value, Edn::Nil)
        {
          ffi = Some(value.to_owned());
        }
      }
      other => {
        return Err(format!(
          "failed to parse CodeEntry: expected struct/map, got: {}",
          format_edn_display(&other)
        ));
      }
    }

    let code = code.ok_or_else(|| "failed to parse CodeEntry: missing code field".to_owned())?;
    validate_test_entries(&tests, "CodeEntry.tests")?;
    let schema = normalize_schema_for_code(&code, &schema);

    Ok(CodeEntry {
      doc,
      examples,
      tests,
      tags,
      code,
      schema,
      ffi,
    })
  }
}

/// Normalize a schema Edn value.
/// Wrapped `(:: 'Fn ({} ...))` / `(:: 'Macro ({} ...))` forms are converted to a direct map Edn.
/// Legacy `:fn` / `:macro` tags remain accepted while loading.
/// Direct map format is returned as-is.
fn normalize_schema_edn(value: &Edn) -> Result<Edn, String> {
  if matches!(value, Edn::Map(_)) {
    let Edn::Map(map) = value else { unreachable!() };
    let normalized = Edn::Map(normalize_schema_map(map));
    validate_schema_edn_no_legacy_quotes(&normalized)?;
    return Ok(normalized);
  }

  if let Edn::Enum(view) = value
    && is_callable_schema_wrapper_variant(view.variant.as_ref())
    && let Some(Edn::Map(map)) = view.extra.first()
  {
    let mut normalized_map = normalize_schema_map(map);
    if normalized_map.tag_get("kind").is_none() && is_macro_schema_wrapper_variant(view.variant.as_ref()) {
      normalized_map.insert_key("kind", Edn::tag("macro"));
    }
    let normalized = Edn::Map(normalized_map);
    validate_schema_edn_no_legacy_quotes(&normalized)?;
    return Ok(normalized);
  }

  Err(format!(
    "invalid schema format: expected wrapped `(:: 'Fn ({{}} ...))` / `(:: 'Macro ({{}} ...))` or a normalized schema map, got {}",
    format_edn_preview(value)
  ))
}

fn validate_schema_edn_no_legacy_quotes(value: &Edn) -> Result<(), String> {
  fn walk(value: &Edn, path: &mut Vec<String>) -> Result<(), String> {
    match value {
      Edn::Symbol(s) => {
        if s.starts_with('\'') {
          let inner = s.trim_start_matches('\'');
          return Err(format!(
            "invalid schema generic symbol `{s}` at {}. Use source syntax like `'{inner}`, but store it as plain EDN symbol `{inner}`.",
            schema_path_label(path)
          ));
        }
        Ok(())
      }
      Edn::List(xs) => {
        for (idx, item) in xs.0.iter().enumerate() {
          path.push(format!("[{idx}]"));
          walk(item, path)?;
          path.pop();
        }
        Ok(())
      }
      Edn::Map(map) => {
        for (k, v) in map.0.iter() {
          path.push(map_key_path_segment(k));
          walk(v, path)?;
          path.pop();
        }
        Ok(())
      }
      Edn::Enum(view) => {
        for (idx, item) in view.extra.iter().enumerate() {
          path.push(format!("[{idx}]"));
          walk(item, path)?;
          path.pop();
        }
        Ok(())
      }
      Edn::Set(set) => {
        for (idx, item) in set.0.iter().enumerate() {
          path.push(format!("[#{idx}]"));
          walk(item, path)?;
          path.pop();
        }
        Ok(())
      }
      Edn::Struct(struct_value) => {
        let _ = struct_value;
        Ok(())
      }
      _ => Ok(()),
    }
  }

  let mut path = vec![];
  walk(value, &mut path)
}

/// Convert a schema Edn value to Cirru for operations that require Cirru (validation, runtime).
/// Handles both old Quote-wrapped format and new direct map format.
pub fn schema_edn_to_cirru(value: &Edn) -> Result<Cirru, String> {
  parse_schema_cirru_from_edn(value)
}

fn parse_schema_cirru_from_edn(value: &Edn) -> Result<Cirru, String> {
  // Do not use `from_edn::<Cirru>` here: EDN symbols such as `Edn::Symbol("T")`
  // would become Cirru leaves like `'T`, while valid schema source should round-trip
  // through the parser into `(quote T)` / `'T` syntax without embedding quote
  // characters inside leaf names.
  let schema_text = cirru_edn::format(value, true).map_err(|e| format!("Failed to format schema EDN to Cirru: {e}"))?;
  let schema_nodes = cirru_parser::parse(&schema_text).map_err(|e| format!("Failed to parse schema Cirru from EDN text: {e}"))?;

  if schema_nodes.len() != 1 {
    return Err(format!(
      "Schema EDN should convert to exactly 1 Cirru expression, got {}",
      schema_nodes.len()
    ));
  }
  Ok(schema_nodes[0].to_owned())
}

pub fn parse_schema_data(schema: &Cirru) -> Result<(), String> {
  if let Cirru::List(items) = schema
    && let Some(Cirru::Leaf(head)) = items.first()
  {
    if &**head == ":optional" {
      if items.len() != 2 {
        return Err("schema `:optional` expects exactly one payload".to_owned());
      }
      return parse_schema_data(&items[1]);
    }
    if &**head == "::" && items.len() == 3 && matches!(items.get(1), Some(Cirru::Leaf(tag)) if &**tag == ":optional") {
      return parse_schema_data(&items[2]);
    }
  }

  let schema_text =
    cirru_parser::format(std::slice::from_ref(schema), true.into()).map_err(|e| format!("Failed to format schema to Cirru: {e}"))?;

  cirru_edn::parse(&schema_text).map_err(|e| format!("Failed to parse schema as Cirru EDN: {e}"))?;

  Ok(())
}

/// Convert a Cirru schema tree to a direct Edn value (not Quote-wrapped).
/// Used when serializing CodeEntry to file: the schema is stored as a native
/// EDN map instead of a quoted Cirru expression.
/// `cr edit format` normalises old quote-wrapped schemas to this format.
/// Returns `Edn::Nil` if conversion fails (should not happen for valid schemas).
pub fn schema_cirru_to_edn(schema: Cirru) -> Edn {
  fn cirru_schema_to_edn(node: &Cirru) -> Option<Edn> {
    match node {
      Cirru::Leaf(text) => {
        let value = text.as_ref();
        if let Some(stripped) = value.strip_prefix(':') {
          Some(Edn::Tag(EdnTag::new(stripped)))
        } else if let Some(stripped) = value.strip_prefix('\'') {
          Some(Edn::Symbol(Arc::from(stripped)))
        } else if let Some(stripped) = value.strip_prefix('|') {
          Some(Edn::str(stripped))
        } else {
          Some(Edn::Symbol(text.clone()))
        }
      }
      Cirru::List(items) => match items.first() {
        Some(Cirru::Leaf(head)) if head.as_ref() == "quote" && items.len() == 2 => match items.get(1) {
          Some(Cirru::Leaf(name)) => Some(Edn::Symbol(name.clone())),
          _ => None,
        },
        Some(Cirru::Leaf(head)) if head.as_ref() == "{}" => {
          let mut map = EdnMapView::default();
          for pair in items.iter().skip(1) {
            let Cirru::List(xs) = pair else {
              return None;
            };
            if xs.len() < 2 {
              return None;
            }
            let key = cirru_schema_to_edn(&xs[0])?;
            let value_node = if xs.len() == 2 {
              xs[1].clone()
            } else {
              Cirru::List(xs.iter().skip(1).cloned().collect())
            };
            let value = cirru_schema_to_edn(&value_node)?;
            map.insert(key, value);
          }
          Some(Edn::Map(map))
        }
        Some(Cirru::Leaf(head)) if head.as_ref() == "[]" => {
          let values: Option<Vec<Edn>> = items.iter().skip(1).map(cirru_schema_to_edn).collect();
          values.map(|xs| Edn::List(cirru_edn::EdnListView(xs)))
        }
        Some(Cirru::Leaf(head)) if head.as_ref() == "#{}" => {
          let values: Option<Vec<Edn>> = items.iter().skip(1).map(cirru_schema_to_edn).collect();
          values.map(|xs| {
            let mut set = EdnSetView::default();
            for item in xs {
              set.insert(item);
            }
            Edn::Set(set)
          })
        }
        Some(Cirru::Leaf(head)) if head.as_ref() == "::" && items.len() >= 2 => {
          let tag = cirru_schema_to_edn(&items[1])?;
          let variant = match tag {
            Edn::Tag(tag) => tag.arc_str(),
            Edn::Symbol(symbol) => symbol,
            _ => return None,
          };
          let extra: Option<Vec<Edn>> = items.iter().skip(2).map(cirru_schema_to_edn).collect();
          extra.map(|xs| Edn::enum_value(variant, xs))
        }
        _ => {
          let values: Option<Vec<Edn>> = items.iter().map(cirru_schema_to_edn).collect();
          values.map(|xs| Edn::List(cirru_edn::EdnListView(xs)))
        }
      },
    }
  }

  cirru_schema_to_edn(&schema).unwrap_or(Edn::Nil)
}

fn validate_schema_for_snapshot_write(owner: &str, schema: &Arc<CalcitTypeAnnotation>) -> Result<(), String> {
  let CalcitTypeAnnotation::Fn(fn_annot) = schema.as_ref() else {
    return Ok(());
  };

  let schema_edn = fn_annot.to_wrapped_schema_edn();
  let schema_text =
    cirru_edn::format(&schema_edn, true).map_err(|e| format!("{owner}: failed to format `:schema` for snapshot write: {e}"))?;
  let schema_nodes = cirru_parser::parse(&schema_text)
    .map_err(|e| format!("{owner}: failed to parse serialized `:schema` during snapshot write validation: {e}"))?;

  if schema_nodes.len() != 1 {
    return Err(format!(
      "{owner}: serialized `:schema` should produce exactly 1 Cirru expression, got {}",
      schema_nodes.len()
    ));
  }

  validate_schema_for_write(&schema_nodes[0])
    .map_err(|e| format!("{owner}: serialized `:schema` becomes invalid during snapshot write: {e}; schema={schema_text}"))
}

fn validate_snapshot_schemas_for_write(snapshot: &Snapshot) -> Result<(), String> {
  for (ns_name, file_data) in &snapshot.files {
    if ns_name.ends_with(".$meta") {
      continue;
    }

    for (def_name, code_entry) in &file_data.defs {
      validate_schema_for_snapshot_write(&format!("{ns_name}/{def_name}"), &code_entry.schema)?;
    }
  }

  Ok(())
}

fn validate_serialized_snapshot_content(content: &str) -> Result<(), String> {
  fn validate_serialized_schema(schema: &Cirru) -> Result<(), String> {
    if let Cirru::Leaf(tag) = schema {
      let tag_name = tag.trim_start_matches(':');
      if PRIMITIVE_SCHEMA_TAGS.contains(&tag_name) {
        return Ok(());
      }
    }
    validate_schema_for_write(schema)
  }

  fn walk(node: &Cirru, path: &mut Vec<usize>) -> Result<(), String> {
    if let Cirru::List(items) = node {
      if let Some(Cirru::Leaf(head)) = items.first()
        && &**head == ":schema"
        && let Some(schema_node) = items.get(1)
      {
        if matches!(schema_node, Cirru::Leaf(s) if s.as_ref() == "nil") {
          return Ok(());
        }
        return validate_serialized_schema(schema_node)
          .map_err(|e| format!("serialized snapshot has invalid `:schema` at {path:?}: {e}"));
      }

      for (idx, item) in items.iter().enumerate() {
        path.push(idx);
        walk(item, path)?;
        path.pop();
      }
    }
    Ok(())
  }

  let nodes = cirru_parser::parse(content).map_err(|e| format!("Failed to parse serialized snapshot content: {e}"))?;
  let mut path = vec![];
  for (idx, node) in nodes.iter().enumerate() {
    path.push(idx);
    walk(node, &mut path)?;
    path.pop();
  }
  Ok(())
}

/// Valid top-level field names accepted in a schema map.
pub const VALID_SCHEMA_FIELDS: &[&str] = &[":kind", ":args", ":return", ":rest", ":generics", ":where", ":features"];

/// Recursively check a Cirru schema tree for deprecated `:nil` type annotations.
fn check_no_nil_type(node: &Cirru) -> Result<(), String> {
  match node {
    Cirru::Leaf(s) if s.as_ref() == ":nil" => Err(
      "`:nil` is no longer a valid schema type. Use `:unit` for functions returning nil/unit, or `:dynamic` for unknown types."
        .to_owned(),
    ),
    Cirru::List(items) => {
      for item in items.iter() {
        check_no_nil_type(item)?;
      }
      Ok(())
    }
    _ => Ok(()),
  }
}

/// Recursively check for symbols with excess leading single-quotes.
/// In schema source, a valid generic type variable is written as `'T`, so a single
/// leading quote in a leaf is valid, but `''T` and deeper are malformed.
fn check_no_excess_quotes(node: &Cirru) -> Result<(), String> {
  match node {
    Cirru::Leaf(s) => {
      // A leaf with one leading quote is valid schema source syntax for an EDN symbol.
      // More than one means the underlying symbol name itself also contains quote chars.
      let name = s.as_ref();
      if name.starts_with('\'') && !name.trim_start_matches('\'').is_empty() {
        let inner = name.trim_start_matches('\'');
        if name.chars().filter(|c| *c == '\'').count() > 1 {
          return Err(format!(
            "Type variable `{name}` has excess leading quotes. Use a single-quoted uppercase symbol like `'{inner}`."
          ));
        }
      }
      Ok(())
    }
    Cirru::List(items) => {
      for item in items.iter() {
        check_no_excess_quotes(item)?;
      }
      Ok(())
    }
  }
}

/// Recursively collect all type-variable names from a Cirru node.
/// A type variable is represented as `(quote Name)` in the Cirru AST,
/// i.e. the source form `'T` parses to `(quote T)`.
fn collect_type_vars(node: &Cirru, out: &mut HashSet<String>) {
  match node {
    Cirru::Leaf(value) => {
      if let Some(name) = value.strip_prefix('\'')
        && !name.is_empty()
      {
        out.insert(name.to_owned());
      }
    }
    Cirru::List(items) => {
      if items.len() == 2
        && let (Some(Cirru::Leaf(head)), Some(Cirru::Leaf(name))) = (items.first(), items.get(1))
        && head.as_ref() == "quote"
      {
        out.insert(name.to_string());
        return;
      }
      for item in items.iter() {
        collect_type_vars(item, out);
      }
    }
  }
}

/// Extract the list of declared generic type-variable names from a `:generics` value node.
/// Accepts `([] 'T 'U ...)` — each `(quote X)` child is one variable.
fn parse_generics_vars(node: &Cirru) -> HashSet<String> {
  let mut vars = HashSet::new();
  if let Cirru::List(items) = node {
    // skip leading `[]` head if present
    let start = match items.first() {
      Some(Cirru::Leaf(s)) if s.as_ref() == "[]" => 1,
      _ => 0,
    };
    for item in items.iter().skip(start) {
      collect_type_vars(item, &mut vars);
    }
  }
  vars
}

fn looks_like_undeclared_type_var(name: &str) -> bool {
  name.len() == 1 && name.as_bytes()[0].is_ascii_uppercase()
}

/// Allowed primitive tag types usable as a bare leaf schema (e.g. `:string`, `:number`).
pub const PRIMITIVE_SCHEMA_TAGS: &[&str] = &[
  "any",
  "bool",
  "number",
  "string",
  "symbol",
  "tag",
  "list",
  "map",
  "set",
  "fn",
  "tuple",
  "ref",
  "buffer",
  "dynamic",
  "unit",
  "record",
  "struct",
  "enum",
  "struct-def",
  "enum-def",
  "trait",
  "impl",
];

const PARAMETERIZED_SCHEMA_TAGS: &[&str] = &["list", "map", "set", "fn", "ref"];

fn canonical_schema_symbol_from_cirru(node: &Cirru) -> Option<&'static str> {
  let Cirru::Leaf(value) = node else {
    return None;
  };
  CalcitTypeAnnotation::canonical_type_symbol_name(value.trim_start_matches('\''))
}

fn is_qualified_nominal_schema_ref(value: &str) -> bool {
  let Some(name) = value.strip_prefix('\'') else {
    return false;
  };
  let Some((namespace, definition)) = name.rsplit_once('/') else {
    return false;
  };
  !namespace.is_empty() && !definition.is_empty()
}

fn check_no_legacy_data_type_names(schema: &Cirru) -> Result<(), String> {
  match schema {
    Cirru::Leaf(value) => {
      let name = value.trim_start_matches(['\'', ':']);
      let replacement = match name {
        "record" | "Record" => Some("Struct"),
        "tuple" | "Tuple" => Some("Enum"),
        _ => None,
      };
      if let Some(replacement) = replacement {
        return Err(format!(
          "Legacy type name `{name}` was removed by the struct/enum data-model migration; use `'{replacement}`."
        ));
      }
      Ok(())
    }
    Cirru::List(items) => {
      for item in items {
        check_no_legacy_data_type_names(item)?;
      }
      Ok(())
    }
  }
}

fn validate_standalone_type_schema(schema: &Cirru) -> Result<(), String> {
  parse_schema_data(schema)?;
  check_no_nil_type(schema)?;
  check_no_excess_quotes(schema)?;

  if let Cirru::List(items) = schema
    && matches!(items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "::")
    && let Some(Cirru::Leaf(type_name)) = items.get(1)
    && canonical_schema_symbol_from_cirru(&items[1]).is_none()
    && !is_qualified_nominal_schema_ref(type_name)
  {
    return Err(format!(
      "Unknown standalone type `{type_name}`. Use a built-in type name or a fully qualified nominal type such as `'app.schema/Store`."
    ));
  }

  let schema_edn = schema_cirru_to_edn(schema.clone());
  if matches!(schema_edn, Edn::Nil) {
    return Err("Failed to convert standalone type schema into EDN".to_owned());
  }
  let annotation = CalcitTypeAnnotation::parse_type_annotation_from_edn(&schema_edn);
  if matches!(annotation.as_ref(), CalcitTypeAnnotation::Dynamic)
    && matches!(schema, Cirru::List(items) if items.len() == 2 && matches!(items.first(), Some(Cirru::Leaf(marker)) if marker.as_ref() == "::") && items.get(1).and_then(canonical_schema_symbol_from_cirru) == Some("Dynamic"))
  {
    return Ok(());
  }
  if matches!(annotation.as_ref(), CalcitTypeAnnotation::Dynamic | CalcitTypeAnnotation::Tag) {
    return Err(format!(
      "Unsupported standalone type schema: {}",
      cirru_parser::format(std::slice::from_ref(schema), true.into()).unwrap_or_else(|_| format!("{schema:?}"))
    ));
  }
  Ok(())
}

/// Strict validation for schemas submitted via `cr edit schema`.
/// New writes use one canonical form: direct value types or wrapped
/// `(:: :fn ({} ...))` / `(:: :macro ({} ...))` callable schemas. Loading
/// existing snapshots remains deliberately more permissive.
pub fn validate_schema_for_write(schema: &Cirru) -> Result<(), String> {
  check_no_legacy_data_type_names(schema)?;
  let raw_items = match schema {
    Cirru::List(items) => items,
    Cirru::Leaf(s) => {
      let tag_name = s.trim_start_matches(':');
      if let Some(canonical) = canonical_schema_symbol_from_cirru(schema) {
        let parameterized = matches!(canonical, "List" | "Map" | "Set" | "Fn" | "Ref");
        if !parameterized {
          return Ok(());
        }
        return Err(format!(
          "Bare `'{canonical}` leaves its nested type dynamic. Use an explicit type expression such as `:: '{canonical} 'Bool`; write `'Dynamic` as a nested type only when the boundary is intentionally dynamic."
        ));
      }
      if is_qualified_nominal_schema_ref(s) {
        check_no_excess_quotes(schema)?;
        let schema_edn = schema_cirru_to_edn(schema.clone());
        let annotation = CalcitTypeAnnotation::parse_type_annotation_from_edn(&schema_edn);
        if matches!(
          annotation.as_ref(),
          CalcitTypeAnnotation::TypeRef(name, args)
            if name.as_ref() == s.trim_start_matches('\'') && args.is_empty()
        ) {
          return Ok(());
        }
        return Err(format!("Failed to parse fully qualified nominal value schema `{s}`"));
      }
      if PARAMETERIZED_SCHEMA_TAGS.contains(&tag_name) {
        let example = match tag_name {
          "map" => ":: :map :tag :bool",
          "fn" => ":: :fn $ {} (:args $ []) (:return :unit)",
          other => {
            return Err(format!(
              "Bare `:{other}` leaves its nested type dynamic. Use an explicit type expression such as `:: :{other} :bool`; write `:dynamic` as the nested type only when the boundary is intentionally dynamic."
            ));
          }
        };
        return Err(format!(
          "Bare `:{tag_name}` leaves its nested type dynamic. Use an explicit type expression such as `{example}`; write `:dynamic` as a nested type only when the boundary is intentionally dynamic."
        ));
      }
      if PRIMITIVE_SCHEMA_TAGS.contains(&tag_name) {
        return Ok(());
      }
      return Err(format!(
        "Unknown value schema `{s}`. Use a direct type such as `'String`, a fully qualified nominal type such as `'app.schema/Store`, a parameterized value type such as `:: 'Ref 'Bool`, or a callable schema such as `:: 'Fn $ {{}} (:args $ []) (:return 'Unit)`."
      ));
    }
  };

  let items: &[Cirru] = if matches!(raw_items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "::") {
    let is_function_schema = raw_items
      .get(1)
      .and_then(canonical_schema_symbol_from_cirru)
      .is_some_and(|name| matches!(name, "Fn" | "Macro"));
    if !is_function_schema {
      return validate_standalone_type_schema(schema);
    }
    if raw_items.len() != 3 {
      return Err("Wrapped schema `(:: :fn schema-map)` or `(:: :macro schema-map)` expects exactly 3 items".to_owned());
    }
    match (&raw_items[1], &raw_items[2]) {
      (tag, Cirru::List(inner_items)) if canonical_schema_symbol_from_cirru(tag).is_some_and(|name| matches!(name, "Fn" | "Macro")) => {
        inner_items
      }
      (Cirru::Leaf(tag), _) => {
        return Err(format!(
          "Wrapped schema type must be `'Fn` or `'Macro`, got: `{tag}`. Example: `(:: 'Fn ({{}} (:args ([] 'String)) (:return 'Bool)))`"
        ));
      }
      _ => return Err("Wrapped schema second item must be `:fn` or `:macro` and third item must be a `{}` map".to_owned()),
    }
  } else if matches!(raw_items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "{}") {
    return Err(
      "Legacy unwrapped callable schema maps are not accepted by `cr edit schema`. Use the canonical wrapped form `:: :fn $ {} ...` or `:: :macro $ {} ...`."
        .to_owned(),
    );
  } else {
    return validate_standalone_type_schema(schema);
  };

  for pair in items.iter().skip(1) {
    if matches!(pair, Cirru::List(xs) if matches!(xs.first(), Some(Cirru::Leaf(key)) if key.as_ref() == ":kind")) {
      return Err(
        "Wrapped callable schemas must not repeat `:kind`. Keep the outer `:: :fn` or `:: :macro` tag and remove the inner `(:kind ...)` field."
          .to_owned(),
      );
    }
  }

  let Some(Cirru::Leaf(head)) = items.first() else {
    return Err("Schema must be a non-empty list starting with `{}`".to_owned());
  };

  if head.as_ref() != "{}" {
    return Err(format!(
      "Schema top-level must start with `{{}}` or be wrapped as `(:: :fn ({{}} ...))` / `(:: :macro ({{}} ...))`, got: `{head}`. \
       Example: `(:: :fn ({{}} (:args ([] :string)) (:return :bool)))`"
    ));
  }

  // EDN-level validity
  parse_schema_data(schema)?;

  // Reject deprecated :nil type annotation
  check_no_nil_type(schema)?;

  // Reject excess-quoted type variables like ''T.
  check_no_excess_quotes(schema)?;

  // Field-level validation
  for pair in items.iter().skip(1) {
    let Cirru::List(xs) = pair else {
      let text = cirru_parser::format(std::slice::from_ref(pair), true.into()).unwrap_or_else(|_| format!("{pair:?}"));
      return Err(format!("Each schema field must be a `(:key val)` pair list, got: {text}"));
    };

    if xs.len() < 2 {
      return Err(format!(
        "Schema field pair must have exactly 2 elements, got {} in: {xs:?}",
        xs.len()
      ));
    }

    let Some(Cirru::Leaf(key)) = xs.first() else {
      return Err(format!("Schema field key must be a leaf tag, got: {:?}", xs.first()));
    };

    if !VALID_SCHEMA_FIELDS.contains(&key.as_ref()) {
      return Err(format!(
        "Unknown schema field: `{key}`. Valid fields: {}",
        VALID_SCHEMA_FIELDS.join(", ")
      ));
    }
  }

  // --- Type-variable consistency check ---
  // Collect declared generics, args, and return from the schema pairs.
  let mut generics_node: Option<&Cirru> = None;
  let mut args_node: Option<&Cirru> = None;
  let mut return_node: Option<&Cirru> = None;
  let mut rest_node: Option<&Cirru> = None;
  let mut where_node: Option<&Cirru> = None;
  let mut features_node: Option<&Cirru> = None;

  for pair in items.iter().skip(1) {
    if let Cirru::List(xs) = pair
      && let (Some(Cirru::Leaf(key)), Some(val)) = (xs.first(), xs.get(1))
    {
      match key.as_ref() {
        ":generics" => generics_node = Some(val),
        ":args" => args_node = Some(val),
        ":return" => return_node = Some(val),
        ":rest" => rest_node = Some(val),
        ":where" => where_node = Some(val),
        ":features" => features_node = Some(val),
        _ => {}
      }
    }
  }

  if let Some(gen_node) = generics_node {
    let declared: HashSet<String> = parse_generics_vars(gen_node);

    // Collect used type vars from :args, :return, :rest
    let mut used: HashSet<String> = HashSet::new();
    if let Some(node) = args_node {
      collect_type_vars(node, &mut used);
    }
    if let Some(node) = return_node {
      collect_type_vars(node, &mut used);
    }
    if let Some(node) = rest_node {
      collect_type_vars(node, &mut used);
    }
    if let Some(node) = where_node {
      collect_type_vars(node, &mut used);
    }

    // Every declared var must be used at least once
    for var in &declared {
      if !used.contains(var) {
        return Err(format!(
          "Generic type variable `'{var}` is declared in `:generics` but never used in `:args`, `:rest`, or `:return`."
        ));
      }
    }

    // Every used var must be declared in :generics
    for var in &used {
      if !declared.contains(var) && looks_like_undeclared_type_var(var) {
        return Err(format!(
          "Type variable `'{var}` is used in `:args`/`:rest`/`:return` but not declared in `:generics`."
        ));
      }
    }
  } else {
    // No :generics — any type var usage is an error
    let mut used: HashSet<String> = HashSet::new();
    if let Some(node) = args_node {
      collect_type_vars(node, &mut used);
    }
    if let Some(node) = return_node {
      collect_type_vars(node, &mut used);
    }
    if let Some(node) = rest_node {
      collect_type_vars(node, &mut used);
    }
    if let Some(node) = where_node {
      collect_type_vars(node, &mut used);
    }
    if let Some(var) = used.iter().find(|name| looks_like_undeclared_type_var(name)) {
      return Err(format!("Type variable `'{var}` is used but no `:generics` field is declared."));
    }
  }

  // Validate :features value — must be a hashset of tags
  if let Some(features_val) = features_node {
    match features_val {
      Cirru::List(items) => {
        // Check it's a hashset: `(#{} tag1 tag2 ...)`
        let Some(Cirru::Leaf(first)) = items.first() else {
          return Err("`:features` must be a hashset like `(#{} :tag1 :tag2)`".to_owned());
        };
        if first.as_ref() != "#{}" {
          return Err("`:features` must be a hashset like `(#{} :tag1 :tag2)`".to_owned());
        }
        for item in items.iter().skip(1) {
          if !matches!(item, Cirru::Leaf(_)) {
            return Err("`:features` hashset items must be simple leaf tags".to_owned());
          }
        }
      }
      _ => {
        return Err("`:features` must be a hashset like `(#{} :tag1 :tag2)`".to_owned());
      }
    }
  }

  Ok(())
}

impl From<CodeEntry> for Edn {
  fn from(data: CodeEntry) -> Self {
    Edn::struct_from_pairs("CodeEntry", &code_entry_edn_pairs(&data))
  }
}

/// Validate and parse one schema submitted through `cr edit schema`.
/// Leaf schemas cannot be round-tripped through `parse_schema_data`, whose
/// Cirru formatter requires a top-level expression, so they are converted
/// directly into EDN before type parsing.
pub fn parse_schema_annotation_for_write(schema: &Cirru) -> Result<Arc<CalcitTypeAnnotation>, String> {
  validate_schema_for_write(schema)?;
  if !matches!(schema, Cirru::Leaf(_)) {
    parse_schema_data(schema)?;
  }
  let schema_edn = schema_cirru_to_edn(schema.clone());
  Ok(
    CalcitTypeAnnotation::parse_fn_schema_from_edn(&schema_edn)
      .map(|signature| Arc::new(CalcitTypeAnnotation::Fn(Arc::new(signature))))
      .unwrap_or_else(|| CalcitTypeAnnotation::parse_type_annotation_from_edn(&schema_edn)),
  )
}

impl From<&CodeEntry> for Edn {
  fn from(data: &CodeEntry) -> Self {
    Edn::struct_from_pairs("CodeEntry", &code_entry_edn_pairs(data))
  }
}

impl CodeEntry {
  pub fn from_code(code: Cirru) -> Self {
    CodeEntry {
      doc: "".to_owned(),
      examples: vec![],
      tests: vec![],
      tags: HashSet::new(),
      code,
      schema: DYNAMIC_TYPE.clone(),
      ffi: None,
    }
  }
}

fn code_declares_macro(code: &Cirru) -> bool {
  matches!(code, Cirru::List(items) if matches!(items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "defmacro"))
}

fn normalize_schema_for_code(code: &Cirru, schema: &Arc<CalcitTypeAnnotation>) -> Arc<CalcitTypeAnnotation> {
  // Data declarations are definition values, not untyped application data.
  // Older snapshots stored their root schema as Dynamic because the concrete
  // fields/variants/methods live in the source form. Keep that compatibility
  // on load, but immediately canonicalize it to the existing definition-kind
  // markers so Dynamic metrics only describe genuinely unknown slots.
  if matches!(schema.as_ref(), CalcitTypeAnnotation::Dynamic)
    && let Cirru::List(items) = code
    && let Some(Cirru::Leaf(head)) = items.first()
  {
    let marker = match head.as_ref() {
      "defstruct" => Some("struct-def"),
      "defenum" => Some("enum-def"),
      "deftrait" => Some("trait"),
      "defimpl" => Some("impl"),
      _ => None,
    };
    if let Some(marker) = marker {
      return Arc::new(CalcitTypeAnnotation::Custom(Arc::new(Calcit::tag(marker))));
    }
  }

  let CalcitTypeAnnotation::Fn(fn_annot) = schema.as_ref() else {
    return schema.clone();
  };

  if !code_declares_macro(code) || matches!(fn_annot.fn_kind, SchemaKind::Macro) {
    return schema.clone();
  }

  Arc::new(CalcitTypeAnnotation::Fn(Arc::new(CalcitFnTypeAnnotation {
    generics: fn_annot.generics.clone(),
    where_bounds: fn_annot.where_bounds.clone(),
    arg_types: fn_annot.arg_types.clone(),
    return_type: fn_annot.return_type.clone(),
    fn_kind: SchemaKind::Macro,
    rest_type: fn_annot.rest_type.clone(),
    features: fn_annot.features.clone(),
  })))
}

/// structure of runtime snapshot files such as `calcit.cirru` (legacy: `compact.cirru`)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Snapshot {
  pub package: String,
  pub about: Option<String>,
  pub version: String,
  pub entries: HashMap<String, SnapshotEntry>,
  pub files: HashMap<String, FileInSnapShot>,
  #[serde(skip, default = "default_active_entry")]
  #[doc(hidden)]
  pub active_entry: String,
}

impl Snapshot {
  pub fn active_entry_name(&self) -> &str {
    &self.active_entry
  }

  pub fn active_entry(&self) -> Result<&SnapshotEntry, String> {
    self
      .entries
      .get(&self.active_entry)
      .ok_or_else(|| format!("Snapshot is missing active entry '{}'", self.active_entry))
  }

  pub fn select_entry(&mut self, entry: Option<&str>) -> Result<(), String> {
    let name = entry.unwrap_or(DEFAULT_ENTRY_NAME);
    if self.entries.contains_key(name) {
      self.active_entry = name.to_owned();
      Ok(())
    } else {
      let mut available = self.entries.keys().cloned().collect::<Vec<_>>();
      available.sort();
      Err(format!("Unknown entry `{name}`. Available entries: {}", available.join(", ")))
    }
  }
}

impl TryFrom<Edn> for SnapshotEntry {
  type Error = String;
  fn try_from(data: Edn) -> Result<SnapshotEntry, String> {
    parse_snapshot_entry_with_context(data, "entry", true)
  }
}

fn parse_snapshot_config_string_field(data: &EdnMapView, key: &str, owner: &str) -> Result<String, String> {
  let value = data.get(&Edn::tag(key)).ok_or_else(|| format!("{owner}: missing `:{key}` field"))?;

  let text: Arc<str> = value
    .to_owned()
    .try_into()
    .map_err(|e| format!("{owner}.{key}: {e}; got {}", format_edn_preview(value)))?;

  if key == "version" && (text.trim().is_empty() || text.as_ref() == "|") {
    return Err(format!(
      "{owner}.version cannot be empty; check the project `:version`; got {}",
      format_edn_preview(value)
    ));
  }

  Ok(text.to_string())
}

/// Entry functions identify Calcit definitions, not text values. Both strings
/// and symbols remain readable for compatibility, while writers use symbols.
fn parse_snapshot_ns_def_field(data: &EdnMapView, key: &str, owner: &str) -> Result<String, String> {
  let value = data.get(&Edn::tag(key)).ok_or_else(|| format!("{owner}: missing `:{key}` field"))?;
  match value {
    Edn::Str(text) | Edn::Symbol(text) => Ok(text.to_string()),
    _ => Err(format!(
      "{owner}.{key}: expected a namespace/definition string or symbol; got {}",
      format_edn_preview(value)
    )),
  }
}

fn parse_optional_snapshot_config_string_field(data: &EdnMapView, key: &str, owner: &str) -> Result<String, String> {
  match data.get(&Edn::tag(key)) {
    Some(_) => parse_snapshot_config_string_field(data, key, owner),
    None => Ok(String::new()),
  }
}

fn parse_snapshot_run_mode(data: &EdnMapView, owner: &str, require_mode: bool) -> Result<SnapshotRunMode, String> {
  let Some(value) = data.get(&Edn::tag("mode")) else {
    return if require_mode {
      Err(format!("{owner}: missing `:mode` field; expected `:native` or `:js`"))
    } else {
      Ok(SnapshotRunMode::Native)
    };
  };
  let mode = match value {
    Edn::Tag(tag) => tag.ref_str(),
    Edn::Str(text) | Edn::Symbol(text) => text.trim_start_matches(':'),
    _ => {
      return Err(format!(
        "{owner}.mode: expected `:native` or `:js`, got {}",
        format_edn_preview(value)
      ));
    }
  };
  match mode {
    "native" => Ok(SnapshotRunMode::Native),
    "js" => Ok(SnapshotRunMode::Js),
    _ => Err(format!("{owner}.mode: expected `:native` or `:js`, got `{mode}`")),
  }
}

fn parse_snapshot_entry_with_context(data: Edn, owner: &str, require_mode: bool) -> Result<SnapshotEntry, String> {
  let data = data
    .view_map()
    .map_err(|e| format!("{owner}: failed to parse entry map: {e}; got {}", format_edn_preview(&data)))?;

  let mode = parse_snapshot_run_mode(&data, owner, require_mode)?;
  let init_fn = parse_snapshot_ns_def_field(&data, "init-fn", owner)?;
  let reload_fn = parse_snapshot_ns_def_field(&data, "reload-fn", owner)?;
  let description = parse_optional_snapshot_config_string_field(&data, "description", owner)?;

  let modules = match data.get(&Edn::tag("modules")) {
    Some(value) => from_edn(value.to_owned()).map_err(|e| format!("{owner}.modules: {e}; got {}", format_edn_preview(value)))?,
    None => Vec::new(),
  };

  let type_slots = match data.get(&Edn::tag("type-slots")) {
    Some(value) => parse_snapshot_type_slots(value, owner)?,
    None => HashMap::new(),
  };
  let feature_policy = match data.get(&Edn::tag("feature-policy")) {
    Some(value) => parse_snapshot_feature_policy(value, owner)?,
    None => HashMap::new(),
  };
  let target = match data.get(&Edn::tag("target")) {
    Some(value) => Some(parse_snapshot_target(value, owner)?),
    None => None,
  };

  Ok(SnapshotEntry {
    mode,
    init_fn,
    reload_fn,
    description,
    modules,
    type_slots,
    feature_policy,
    target,
  })
}

fn parse_snapshot_target(value: &Edn, owner: &str) -> Result<SnapshotTarget, String> {
  let target = match value {
    Edn::Tag(tag) => tag.ref_str(),
    Edn::Str(text) | Edn::Symbol(text) => text.trim_start_matches(':'),
    _ => {
      return Err(format!(
        "{owner}.target: expected :browser, :node, :native, or :wasm, got {}",
        format_edn_preview(value)
      ));
    }
  };
  match target {
    "browser" => Ok(SnapshotTarget::Browser),
    "node" => Ok(SnapshotTarget::Node),
    "native" => Ok(SnapshotTarget::Native),
    "wasm" => Ok(SnapshotTarget::Wasm),
    _ => Err(format!(
      "{owner}.target: expected :browser, :node, :native, or :wasm, got `{target}`"
    )),
  }
}

fn parse_snapshot_feature_policy(data: &Edn, owner: &str) -> Result<HashMap<String, FeaturePolicy>, String> {
  let policies = data
    .view_map()
    .map_err(|e| format!("{owner}.feature-policy: expected a map: {e}; got {}", format_edn_preview(data)))?;
  let mut result = HashMap::with_capacity(policies.0.len());
  for (raw_feature, raw_policy) in policies.0.iter() {
    let feature = match raw_feature {
      Edn::Tag(tag) => tag.ref_str().to_owned(),
      Edn::Str(text) | Edn::Symbol(text) => text.trim_start_matches(':').to_owned(),
      _ => {
        return Err(format!(
          "{owner}.feature-policy: feature name must be a tag, string, or symbol; got {}",
          format_edn_preview(raw_feature)
        ));
      }
    };
    if feature.trim().is_empty() {
      return Err(format!("{owner}.feature-policy: feature name cannot be empty"));
    }
    let policy_name = match raw_policy {
      Edn::Tag(tag) => tag.ref_str(),
      Edn::Str(text) | Edn::Symbol(text) => text.trim_start_matches(':'),
      _ => {
        return Err(format!(
          "{owner}.feature-policy.{feature}: expected :allow, :warn, or :error; got {}",
          format_edn_preview(raw_policy)
        ));
      }
    };
    let policy = match policy_name {
      "allow" => FeaturePolicy::Allow,
      "warn" => FeaturePolicy::Warn,
      "error" => FeaturePolicy::Error,
      _ => {
        return Err(format!(
          "{owner}.feature-policy.{feature}: expected :allow, :warn, or :error, got `{policy_name}`"
        ));
      }
    };
    if result.insert(feature.clone(), policy).is_some() {
      return Err(format!("{owner}.feature-policy: duplicate feature `:{feature}`"));
    }
  }
  Ok(result)
}

fn parse_snapshot_type_slots(data: &Edn, owner: &str) -> Result<HashMap<String, String>, String> {
  let slots = data
    .view_map()
    .map_err(|e| format!("{owner}.type-slots: expected a map: {e}; got {}", format_edn_preview(data)))?;
  let mut result = HashMap::with_capacity(slots.0.len());

  for (raw_slot, raw_type) in slots.0.iter() {
    let slot = match raw_slot {
      Edn::Tag(tag) => tag.ref_str().to_owned(),
      Edn::Str(text) | Edn::Symbol(text) => text.trim_start_matches(':').to_owned(),
      _ => {
        return Err(format!(
          "{owner}.type-slots: slot name must be a tag, string, or symbol; got {}",
          format_edn_preview(raw_slot)
        ));
      }
    };
    if slot.is_empty() {
      return Err(format!("{owner}.type-slots: slot name cannot be empty"));
    }

    let type_path = match raw_type {
      Edn::Str(text) | Edn::Symbol(text) if text.as_ref() == "Dynamic" => ":dynamic".to_owned(),
      Edn::Str(text) | Edn::Symbol(text) => text.to_string(),
      Edn::Tag(tag) if tag.ref_str() == "dynamic" => ":dynamic".to_owned(),
      _ => {
        return Err(format!(
          "{owner}.type-slots.{slot}: type must be a full `namespace/definition` string or `:dynamic`; got {}",
          format_edn_preview(raw_type)
        ));
      }
    };
    if result.insert(slot.clone(), type_path).is_some() {
      return Err(format!("{owner}.type-slots: duplicate slot name `:{slot}`"));
    }
  }

  Ok(result)
}

fn parse_entries_with_context(data: &Edn, require_mode: bool) -> Result<HashMap<String, SnapshotEntry>, String> {
  let entries_map = data
    .view_map()
    .map_err(|e| format!("entries: failed to parse entries map: {e}; got {}", format_edn_preview(data)))?;

  let mut entries = HashMap::with_capacity(entries_map.0.len());
  for (entry_key, entry_value) in entries_map.0.iter() {
    let entry_name: String = from_edn(entry_key.to_owned())
      .map_err(|e| format!("entries: failed to parse entry name: {e}; got {}", format_edn_preview(entry_key)))?;
    let owner = format!("entries.{entry_name}");
    let entry = parse_snapshot_entry_with_context(entry_value.to_owned(), &owner, require_mode)?;
    entries.insert(entry_name, entry);
  }

  Ok(entries)
}

fn legacy_snapshot_recovery_hint(path: &str) -> Option<String> {
  let snapshot_path = Path::new(path);
  let compact_path = snapshot_path.parent()?.join("compact.cirru");
  if snapshot_path.file_name()?.to_str()? == "calcit.cirru" && compact_path.is_file() {
    Some(format!(
      "A sibling `{}` exists. If it is the last runnable compact Snapshot, back up this `calcit.cirru`, copy `compact.cirru` over it, then run `cr calcit.cirru edit format` before `cr calcit.cirru --check-only`.",
      compact_path.display()
    ))
  } else {
    None
  }
}

/// Parse a Snapshot while preserving the source path in deserialization errors.
pub fn load_snapshot_data(data: &Edn, path: &str) -> Result<Snapshot, String> {
  load_snapshot_data_inner(data, path).map_err(|error| {
    let mut message = format!("Failed to load Snapshot `{path}`: {error}");
    if let Some(hint) = legacy_snapshot_recovery_hint(path) {
      message.push_str("\nLegacy Snapshot recovery: ");
      message.push_str(&hint);
    }
    message
  })
}

fn load_snapshot_data_inner(data: &Edn, path: &str) -> Result<Snapshot, String> {
  let data = data.view_map()?;
  let pkg: Arc<str> = data.get_or_nil("package").try_into()?;
  let mut files: HashMap<String, FileInSnapShot> = parse_files_with_context(&data.get_or_nil("files"))?;
  let about = match data.get_or_nil("about") {
    Edn::Nil => None,
    value => {
      let s: Arc<str> = value.try_into()?;
      Some(s.to_string())
    }
  };
  let meta_ns = format!("{pkg}.$meta");
  files.insert(meta_ns.to_owned(), gen_meta_ns(&meta_ns, path));
  let legacy_configs = data.get(&Edn::tag("configs"));
  let mut entries = parse_entries_with_context(&data.get_or_nil("entries"), legacy_configs.is_none())?;
  let version = match data.get(&Edn::tag("version")) {
    Some(_) => parse_snapshot_config_string_field(&data, "version", "snapshot")?,
    None => match legacy_configs {
      Some(configs) => {
        let configs_map = configs
          .view_map()
          .map_err(|e| format!("configs: failed to parse config map: {e}; got {}", format_edn_preview(configs)))?;
        match configs_map.get(&Edn::tag("version")) {
          Some(_) => parse_snapshot_config_string_field(&configs_map, "version", "configs")?,
          None => default_version(),
        }
      }
      None => default_version(),
    },
  };

  if let Some(configs) = legacy_configs {
    if entries.contains_key(DEFAULT_ENTRY_NAME) {
      return Err("Snapshot cannot contain both legacy `:configs` and `:entries.default`".to_owned());
    }
    entries.insert(
      DEFAULT_ENTRY_NAME.to_owned(),
      parse_snapshot_entry_with_context(configs.to_owned(), "entries.default", false)?,
    );
  } else if !entries.contains_key(DEFAULT_ENTRY_NAME) {
    return Err("Snapshot `:entries` must contain a `:default` entry".to_owned());
  }

  let s = Snapshot {
    package: pkg.to_string(),
    about,
    version,
    entries,
    files,
    active_entry: default_active_entry(),
  };
  Ok(s)
}

fn parse_code_entry_with_context(data: Edn, owner: &str) -> Result<CodeEntry, String> {
  with_type_annotation_warning_context(owner.to_owned(), || data.try_into()).map_err(|e| format!("{owner}: {e}"))
}

fn parse_file_in_snapshot_with_context(data: Edn, file_name: &str) -> Result<FileInSnapShot, String> {
  match data {
    Edn::Map(map) => {
      let ns_value = map
        .get(&Edn::tag("ns"))
        .ok_or_else(|| format!("{file_name}: missing `:ns` field in FileEntry"))?;
      let defs_value = map
        .get(&Edn::tag("defs"))
        .ok_or_else(|| format!("{file_name}: missing `:defs` field in FileEntry"))?;

      let ns: NsEntry = ns_value
        .to_owned()
        .try_into()
        .map_err(|e: String| format!("{file_name}/:ns: {e}"))?;
      let defs_map = defs_value.view_map().map_err(|e| {
        format!(
          "{file_name}: failed to parse `:defs` as map: {e}; got {}",
          format_edn_preview(defs_value)
        )
      })?;

      let mut defs = HashMap::with_capacity(defs_map.0.len());
      for (def_key, def_value) in defs_map.0.iter() {
        let def_name: String = from_edn(def_key.to_owned())
          .map_err(|e| format!("{file_name}: failed to parse def name: {e}; got {}", format_edn_preview(def_key)))?;
        let owner = format!("{file_name}/{def_name}");
        defs.insert(def_name, parse_code_entry_with_context(def_value.to_owned(), &owner)?);
      }

      Ok(FileInSnapShot { ns, defs })
    }
    Edn::Struct(struct_value) => {
      let mut ns: Option<NsEntry> = None;
      let mut defs = HashMap::new();

      for (key, value) in struct_value.pairs.iter() {
        match key.arc_str().as_ref() {
          "ns" => {
            ns = Some(value.to_owned().try_into().map_err(|e: String| format!("{file_name}/:ns: {e}"))?);
          }
          "defs" => {
            let defs_map = value.view_map().map_err(|e| {
              format!(
                "{file_name}: failed to parse `:defs` as map: {e}; got {}",
                format_edn_preview(value)
              )
            })?;
            for (def_key, def_value) in defs_map.0.iter() {
              let def_name: String = from_edn(def_key.to_owned())
                .map_err(|e| format!("{file_name}: failed to parse def name: {e}; got {}", format_edn_preview(def_key)))?;
              let owner = format!("{file_name}/{def_name}");
              defs.insert(def_name, parse_code_entry_with_context(def_value.to_owned(), &owner)?);
            }
          }
          _ => {}
        }
      }

      Ok(FileInSnapShot {
        ns: ns.ok_or_else(|| format!("{file_name}: missing `:ns` field in FileEntry"))?,
        defs,
      })
    }
    other => Err(format!(
      "{file_name}: expected FileEntry map/struct, got {}",
      format_edn_preview(&other)
    )),
  }
}

fn parse_files_with_context(data: &Edn) -> Result<HashMap<String, FileInSnapShot>, String> {
  let files_map = data
    .view_map()
    .map_err(|e| format!("failed to parse snapshot `:files` as map: {e}; got {}", format_edn_preview(data)))?;
  let mut files = HashMap::with_capacity(files_map.0.len());
  for (file_key, file_value) in files_map.0.iter() {
    let file_name: String = from_edn(file_key.to_owned())
      .map_err(|e| format!("failed to parse snapshot file key: {e}; got {}", format_edn_preview(file_key)))?;
    files.insert(
      file_name.clone(),
      parse_file_in_snapshot_with_context(file_value.to_owned(), &file_name)?,
    );
  }
  Ok(files)
}

pub fn gen_meta_ns(ns: &str, path: &str) -> FileInSnapShot {
  let path_data = Path::new(path);
  let parent = path_data.parent().expect("parent path");
  let parent_str = parent.to_str().expect("get path string");

  let def_dict: HashMap<String, CodeEntry> = HashMap::from_iter([
    (
      "calcit-filename".into(),
      CodeEntry::from_code(vec!["def", "calcit-filename", &format!("|{}", path.escape_default())].into()),
    ),
    (
      "calcit-dirname".into(),
      CodeEntry::from_code(vec!["def", "calcit-dirname", &format!("|{}", parent_str.escape_default())].into()),
    ),
  ]);

  FileInSnapShot {
    ns: NsEntry {
      doc: "".to_owned(),
      code: vec!["ns", ns].into(),
    },
    defs: def_dict,
  }
}

impl Default for Snapshot {
  fn default() -> Snapshot {
    let default_entry = SnapshotEntry {
      mode: SnapshotRunMode::Native,
      init_fn: "app.main/main!".into(),
      reload_fn: "app.main/reload!".into(),
      description: String::new(),
      modules: vec![],
      type_slots: HashMap::new(),
      feature_policy: HashMap::new(),
      target: None,
    };
    Snapshot {
      package: "app".into(),
      about: Some(SNAPSHOT_ABOUT_MESSAGE.to_string()),
      version: default_version(),
      entries: HashMap::from([(DEFAULT_ENTRY_NAME.to_owned(), default_entry)]),
      files: HashMap::new(),
      active_entry: default_active_entry(),
    }
  }
}

/// Keywords that introduce a named top-level definition in Calcit.
/// When a snippet contains multiple such forms, each is extracted as its own
/// `CodeEntry` so the type-checker can inspect them individually (no-run mode).
const TOP_LEVEL_DEF_HEADS: &[&str] = &[
  "def",
  "defn",
  "defwasm-export",
  "defwasm-import",
  "defcomp",
  "defeffect",
  "defatom",
  "defstruct",
  "defenum",
  "defmacro",
  "defrecord",
];

/// Extract the binding name from a top-level definition form.
/// Returns `Some(name)` for recognised `(def name ...)` / `(defn name args ...)` etc.
fn extract_def_name(items: &[Cirru]) -> Option<&str> {
  match (items.first(), items.get(1)) {
    (Some(Cirru::Leaf(head)), Some(Cirru::Leaf(name))) if TOP_LEVEL_DEF_HEADS.contains(&head.as_ref()) => Some(name.as_ref()),
    _ => None,
  }
}

pub fn create_file_from_snippet(raw: &str) -> Result<FileInSnapShot, String> {
  match cirru_parser::parse(raw) {
    Ok(lines) => {
      let mut ns_code: Cirru = vec!["ns", "app.main"].into();
      let mut body_start = 0;
      if let Some(Cirru::List(items)) = lines.first()
        && let Some(Cirru::Leaf(head)) = items.first()
        && &**head == "ns"
      {
        if items.len() < 2 {
          return Err("Invalid `ns` expression in snippet: expected namespace after `ns`".to_string());
        }
        let mut merged_ns = vec![Cirru::leaf("ns"), Cirru::leaf("app.main")];
        merged_ns.extend(items.iter().skip(2).cloned());
        ns_code = Cirru::List(merged_ns);
        body_start = 1;
      }

      let body_lines: Vec<Cirru> = lines.into_iter().skip(body_start).collect();

      // If every body line is a top-level definition (def/defn/defcomp/…), promote
      // each to its own CodeEntry.  This lets the type-checker handle multi-def
      // snippets that appear in documentation (no-run mode).
      let all_top_level = !body_lines.is_empty()
        && body_lines.iter().all(|line| {
          if let Cirru::List(items) = line {
            extract_def_name(items).is_some()
          } else {
            false
          }
        });

      let mut def_dict: HashMap<String, CodeEntry> = HashMap::with_capacity(body_lines.len() + 2);

      if all_top_level {
        for line in &body_lines {
          if let Cirru::List(items) = line
            && let Some(name) = extract_def_name(items)
          {
            def_dict.insert(name.to_owned(), CodeEntry::from_code(line.clone()));
          }
        }
        // Each def is registered as its own CodeEntry so the type-checker can
        // analyse multi-def snippets individually.  A no-op main! is still
        // required so run_eval_in_process (Run mode) can find the entry point.
      } else {
        let mut func_code = vec![Cirru::leaf("defn"), "main!".into(), Cirru::List(vec![])];
        for line in body_lines {
          func_code.push(line);
        }
        def_dict.insert("main!".into(), CodeEntry::from_code(Cirru::List(func_code)));
      }

      def_dict
        .entry("main!".to_string())
        .or_insert_with(|| CodeEntry::from_code(vec![Cirru::leaf("defn"), "main!".into(), Cirru::List(vec![])].into()));
      def_dict
        .entry("reload!".to_string())
        .or_insert_with(|| CodeEntry::from_code(vec![Cirru::leaf("defn"), "reload!".into(), Cirru::List(vec![])].into()));

      Ok(FileInSnapShot {
        ns: NsEntry {
          doc: "".to_owned(),
          code: ns_code,
        },
        defs: def_dict,
      })
    }
    Err(e) => {
      eprintln!("\nFailed to parse code snippet:");
      eprintln!("{}", e.format_detailed(Some(raw)));
      Err("Failed to parse code snippet".to_string())
    }
  }
}

#[derive(Debug, PartialEq, Clone, Eq)]
pub struct FileChangeInfo {
  pub ns: Option<Cirru>,
  pub added_defs: HashMap<String, Cirru>,
  pub removed_defs: HashSet<String>,
  pub changed_defs: HashMap<String, Cirru>,
}

impl From<&FileChangeInfo> for Edn {
  fn from(data: &FileChangeInfo) -> Edn {
    let mut map = EdnMapView::default();
    if let Some(ns) = &data.ns {
      map.insert_key("ns", Edn::Quote(ns.to_owned()));
    }

    if !data.added_defs.is_empty() {
      #[allow(clippy::mutable_key_type)]
      let defs: HashMap<Edn, Edn> = data
        .added_defs
        .iter()
        .map(|(name, def)| (Edn::str(&**name), Edn::Quote(def.to_owned())))
        .collect();
      map.insert_key("added-defs", Edn::from(defs));
    }
    if !data.removed_defs.is_empty() {
      map.insert_key(
        "removed-defs",
        Edn::Set(EdnSetView(data.removed_defs.iter().map(|s| Edn::str(&**s)).collect())),
      );
    }
    if !data.changed_defs.is_empty() {
      map.insert_key(
        "changed-defs",
        Edn::Map(EdnMapView(
          data
            .changed_defs
            .iter()
            .map(|(name, def)| (Edn::str(&**name), Edn::Quote(def.to_owned())))
            .collect(),
        )),
      );
    }
    map.into()
  }
}

impl From<FileChangeInfo> for Edn {
  fn from(data: FileChangeInfo) -> Edn {
    // call previous implementation to convert
    (&data).into()
  }
}

impl TryFrom<Edn> for FileChangeInfo {
  type Error = String;

  fn try_from(data: Edn) -> Result<Self, Self::Error> {
    let data = data.view_map()?;
    Ok(Self {
      ns: match data.get_or_nil("ns") {
        Edn::Nil => None,
        ns => Some(ns.try_into()?),
      },
      added_defs: data.get_or_nil("added-defs").try_into()?,
      removed_defs: data.get_or_nil("removed-defs").try_into()?,
      changed_defs: data.get_or_nil("changed-defs").try_into()?,
    })
  }
}

/// TODO: Support for :doc and :examples fields has been added, needs to be handled properly
#[derive(Debug, PartialEq, Clone, Eq, Default)]
pub struct ChangesDict {
  pub added: HashMap<Arc<str>, FileInSnapShot>,
  pub removed: HashSet<Arc<str>>,
  pub changed: HashMap<Arc<str>, FileChangeInfo>,
}

impl ChangesDict {
  pub fn is_empty(&self) -> bool {
    self.added.is_empty() && self.removed.is_empty() && self.changed.is_empty()
  }
}

impl TryFrom<Edn> for ChangesDict {
  type Error = String;

  fn try_from(data: Edn) -> Result<Self, Self::Error> {
    let data = data.view_map()?;
    Ok(Self {
      added: data.get_or_nil("added").try_into()?,
      changed: data.get_or_nil("changed").try_into()?,
      removed: data.get_or_nil("removed").try_into()?,
    })
  }
}

impl TryFrom<ChangesDict> for Edn {
  type Error = String;

  fn try_from(x: ChangesDict) -> Result<Edn, Self::Error> {
    let mut map = EdnMapView::default();
    map.insert_key("added", x.added.into());
    map.insert_key("changed", x.changed.into());
    map.insert_key("removed", x.removed.into());
    Ok(Edn::Map(map))
  }
}

fn type_slots_to_edn(type_slots: &HashMap<String, String>) -> Edn {
  let mut slots_map = EdnMapView::default();
  let mut slots: Vec<(&String, &String)> = type_slots.iter().collect();
  slots.sort_by_key(|(slot, _)| *slot);
  for (slot, type_path) in slots {
    let value = if type_path == ":dynamic" {
      Edn::Symbol(Arc::from("Dynamic"))
    } else {
      Edn::Str(type_path.as_str().into())
    };
    slots_map.insert_key(slot.as_str(), value);
  }
  slots_map.into()
}

fn feature_policy_to_edn(feature_policy: &HashMap<String, FeaturePolicy>) -> Edn {
  let mut policies = EdnMapView::default();
  let mut items = feature_policy.iter().collect::<Vec<_>>();
  items.sort_by_key(|(feature, _)| *feature);
  for (feature, policy) in items {
    policies.insert_key(feature.as_str(), Edn::tag(policy.as_str()));
  }
  policies.into()
}

fn canonicalize_legacy_type_leaf(node: &Cirru) -> Option<Cirru> {
  let Cirru::Leaf(value) = node else {
    return None;
  };
  let legacy_name = value.strip_prefix(':')?;
  let canonical = CalcitTypeAnnotation::canonical_type_symbol_name(legacy_name)?;
  Some(Cirru::leaf(format!("'{canonical}")))
}

fn canonicalize_type_expression(node: &Cirru) -> (Cirru, usize) {
  if let Some(canonical) = canonicalize_legacy_type_leaf(node) {
    return (canonical, 1);
  }
  match node {
    Cirru::Leaf(_) => (node.clone(), 0),
    Cirru::List(items) => {
      let implicit_constructor = items.first().and_then(canonical_schema_symbol_from_cirru).is_some()
        && !matches!(items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "::");
      let mut rewritten = Vec::with_capacity(items.len());
      let mut changed = 0;
      if implicit_constructor {
        rewritten.push(Cirru::leaf("::"));
      }
      for (index, item) in items.iter().enumerate() {
        let (next, count) = canonicalize_type_expression(item);
        rewritten.push(next);
        changed += count;
        if implicit_constructor && index == 0 && canonicalize_legacy_type_leaf(item).is_none() {
          changed += 1;
        }
      }
      (Cirru::List(rewritten), changed)
    }
  }
}

fn canonicalize_schema_map_types(node: &Cirru) -> (Cirru, usize) {
  let Cirru::List(items) = node else {
    return (node.clone(), 0);
  };
  if !matches!(items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "{}") {
    return canonicalize_type_expression(node);
  }

  let mut rewritten = Vec::with_capacity(items.len());
  let mut changed = 0;
  rewritten.push(items[0].clone());
  for pair in items.iter().skip(1) {
    let (next, count) = match pair {
      Cirru::List(pair_items)
        if matches!(pair_items.first(), Some(Cirru::Leaf(key)) if matches!(key.as_ref(), ":args" | ":return" | ":rest" | ":where"))
          && pair_items.len() >= 2 =>
      {
        let mut next_pair = pair_items.clone();
        let (value, count) = canonicalize_type_expression(&pair_items[1]);
        next_pair[1] = value;
        (Cirru::List(next_pair), count)
      }
      _ => (pair.clone(), 0),
    };
    rewritten.push(next);
    changed += count;
  }
  (Cirru::List(rewritten), changed)
}

fn canonicalize_code_type_syntax(node: &Cirru) -> (Cirru, usize) {
  let Cirru::List(items) = node else {
    return (node.clone(), 0);
  };
  let mut rewritten = Vec::with_capacity(items.len());
  let mut changed = 0;
  for item in items {
    let (next, count) = canonicalize_code_type_syntax(item);
    rewritten.push(next);
    changed += count;
  }

  let head = items.first().and_then(|item| match item {
    Cirru::Leaf(value) => Some(value.as_ref()),
    _ => None,
  });
  match head {
    Some("assert-type" | "unsafe-coerce") if items.len() >= 3 => {
      let (next, count) = canonicalize_type_expression(&items[2]);
      rewritten[2] = next;
      changed += count;
    }
    Some("defstruct" | "defrecord" | "defenum") if items.len() >= 3 => {
      for index in 2..items.len() {
        let Cirru::List(field) = &items[index] else {
          continue;
        };
        if field.len() < 2 {
          continue;
        }
        let mut next_field = field.clone();
        for type_index in 1..field.len() {
          let (next, count) = canonicalize_type_expression(&field[type_index]);
          next_field[type_index] = next;
          changed += count;
        }
        rewritten[index] = Cirru::List(next_field);
      }
    }
    Some("hint-fn") => {
      for index in 1..items.len() {
        let (next, count) = canonicalize_schema_map_types(&items[index]);
        rewritten[index] = next;
        changed += count;
      }
    }
    Some("fn" | "defn" | "defmacro" | "defcomp" | "defeffect") => {
      let args_index = if head == Some("fn") { 1 } else { 2 };
      let type_index = args_index + 1;
      if let Some(type_form) = items.get(type_index)
        && (canonicalize_legacy_type_leaf(type_form).is_some()
          || matches!(type_form, Cirru::List(inner) if matches!(inner.first(), Some(Cirru::Leaf(marker)) if marker.as_ref() == "::")))
      {
        let (next, count) = canonicalize_type_expression(type_form);
        rewritten[type_index] = next;
        changed += count;
      }
    }
    _ => {}
  }
  (Cirru::List(rewritten), changed)
}

/// Rewrite legacy tag-based type syntax in code type positions. This is intentionally
/// called by `cr edit format`, not by unrelated structural edits: old snapshots stay
/// compatible until users explicitly request canonical formatting.
pub fn canonicalize_snapshot_type_syntax(snapshot: &mut Snapshot) -> usize {
  let mut changed = 0;
  for file in snapshot.files.values_mut() {
    let (ns_code, count) = canonicalize_code_type_syntax(&file.ns.code);
    file.ns.code = ns_code;
    changed += count;
    for entry in file.defs.values_mut() {
      let (code, count) = canonicalize_code_type_syntax(&entry.code);
      entry.code = code;
      changed += count;
      let mut rewritten_examples = Vec::with_capacity(entry.examples.len());
      for example in &entry.examples {
        let (code, count) = canonicalize_code_type_syntax(example);
        rewritten_examples.push(code);
        changed += count;
      }
      entry.examples = rewritten_examples;
    }
  }
  changed
}

/// Render snapshot content for runtime snapshot files such as `calcit.cirru`
/// This is a shared utility function used by CLI edit commands
pub fn render_snapshot_content(snapshot: &Snapshot) -> Result<String, String> {
  validate_snapshot_schemas_for_write(snapshot)?;

  // Build root level Edn mapping
  let mut edn_map = EdnMapView::default();

  // Build package
  edn_map.insert_key("package", Edn::Str(snapshot.package.as_str().into()));

  // Insert about message (always enforce canonical hint)
  edn_map.insert_key("about", Edn::Str(SNAPSHOT_ABOUT_MESSAGE.into()));

  // Build entries
  let mut entries_map = EdnMapView::default();
  for (k, v) in &snapshot.entries {
    let mut entry_map = EdnMapView::default();
    entry_map.insert_key("mode", Edn::tag(v.mode.as_str()));
    entry_map.insert_key("init-fn", Edn::Symbol(v.init_fn.as_str().into()));
    entry_map.insert_key("reload-fn", Edn::Symbol(v.reload_fn.as_str().into()));
    entry_map.insert_key("description", Edn::Str(v.description.as_str().into()));
    entry_map.insert_key(
      "modules",
      Edn::from(v.modules.iter().map(|s| Edn::Str(s.as_str().into())).collect::<Vec<_>>()),
    );
    entry_map.insert_key("type-slots", type_slots_to_edn(&v.type_slots));
    entry_map.insert_key("feature-policy", feature_policy_to_edn(&v.feature_policy));
    if let Some(target) = v.target {
      entry_map.insert_key("target", Edn::tag(target.as_str()));
    }
    entries_map.insert_key(k.as_str(), entry_map.into());
  }
  edn_map.insert_key("entries", entries_map.into());

  // Build files
  let mut files_map = EdnMapView::default();
  for (k, v) in &snapshot.files {
    // Skip $meta namespaces as they are special and should not be serialized to file
    if k.ends_with(".$meta") {
      continue;
    }
    files_map.insert(Edn::str(k.as_str()), Edn::from(v));
  }
  edn_map.insert_key("files", files_map.into());

  let edn_data = Edn::from(edn_map);

  // Normalize on AST directly, avoiding parse-after-format roundtrip.
  let normalized = normalize_pipe_prefixed_leaf(edn_data.cirru());
  let content = cirru_parser::format(std::slice::from_ref(&normalized), true.into())
    .map_err(|e| format!("Failed to format snapshot as Cirru: {e}"))?;

  validate_serialized_snapshot_content(&content)?;

  Ok(content)
}

fn normalize_pipe_prefixed_leaf(node: Cirru) -> Cirru {
  match node {
    Cirru::Leaf(token) => {
      if let Some(rest) = token.strip_prefix('"') {
        Cirru::leaf(format!("|{rest}"))
      } else {
        Cirru::Leaf(token)
      }
    }
    Cirru::List(items) => Cirru::List(items.into_iter().map(normalize_pipe_prefixed_leaf).collect()),
  }
}

/// Save snapshot to a runtime snapshot file such as `calcit.cirru`
/// This is a shared utility function used by CLI edit commands
pub fn save_snapshot_to_file<P: AsRef<Path>>(snapshot_path: P, snapshot: &Snapshot) -> Result<(), String> {
  let content = render_snapshot_content(snapshot)?;

  // Write to file
  std::fs::write(&snapshot_path, content)
    .map_err(|e| format!("Failed to write snapshot file {}: {e}", snapshot_path.as_ref().display()))?;

  Ok(())
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::calcit::CalcitFnTypeAnnotation;
  use cirru_edn::EdnListView;

  fn parse_one(source: &str) -> Cirru {
    cirru_parser::parse(source)
      .unwrap_or_else(|error| panic!("failed to parse test Cirru `{source}`: {error}"))
      .into_iter()
      .next()
      .expect("test Cirru should contain one expression")
  }

  #[test]
  fn snapshot_load_error_names_source_and_compact_recovery_path() {
    let root = std::env::temp_dir().join(format!("calcit-legacy-snapshot-recovery-{}", std::process::id()));
    fs::create_dir_all(&root).expect("create legacy snapshot fixture directory");
    let snapshot_path = root.join("calcit.cirru");
    let compact_path = root.join("compact.cirru");
    fs::write(&snapshot_path, "legacy full snapshot").expect("write full snapshot marker");
    fs::write(&compact_path, "compact snapshot").expect("write compact snapshot marker");

    let error = load_snapshot_data(&Edn::Nil, snapshot_path.to_str().expect("utf-8 temp path"))
      .expect_err("invalid legacy snapshot data should fail with recovery guidance");

    assert!(error.contains(snapshot_path.to_str().unwrap()), "error: {error}");
    assert!(error.contains(compact_path.to_str().unwrap()), "error: {error}");
    assert!(error.contains("cr calcit.cirru edit format"), "error: {error}");
    assert!(error.contains("cr calcit.cirru --check-only"), "error: {error}");

    fs::remove_dir_all(root).expect("remove legacy snapshot fixture directory");
  }

  fn revision_test_entry(tags: &[&str]) -> CodeEntry {
    CodeEntry {
      doc: "revision test".to_owned(),
      examples: vec![Cirru::List(vec![Cirru::leaf("inc"), Cirru::leaf("1")])],
      tests: vec![TestEntry {
        name: "returns-answer".to_owned(),
        code: Cirru::List(vec![Cirru::leaf("assert="), Cirru::leaf("42"), Cirru::leaf("answer")]),
        tags: [EdnTag::new("unit")].into_iter().collect(),
      }],
      tags: tags.iter().map(|tag| EdnTag::new(*tag)).collect(),
      code: Cirru::List(vec![Cirru::leaf("def"), Cirru::leaf("answer"), Cirru::leaf("42")]),
      schema: Arc::new(CalcitTypeAnnotation::Number),
      ffi: None,
    }
  }

  #[test]
  fn definition_revision_is_stable_and_covers_persisted_fields() {
    let entry = revision_test_entry(&["public", "demo"]);
    let reordered_tags = revision_test_entry(&["demo", "public"]);
    let revision = definition_revision(&entry).expect("revision should render");

    assert_eq!(
      revision,
      definition_revision(&reordered_tags).expect("tag order should not affect revision")
    );
    assert!(revision.starts_with("md5:"));

    let mut changed = entry.clone();
    changed.doc.push('!');
    assert_ne!(revision, definition_revision(&changed).expect("changed revision should render"));

    let mut changed = entry.clone();
    changed.code = Cirru::List(vec![Cirru::leaf("def"), Cirru::leaf("answer"), Cirru::leaf("43")]);
    assert_ne!(
      revision,
      definition_revision(&changed).expect("changed code revision should render")
    );

    let mut changed = entry.clone();
    changed.tests[0].code = Cirru::List(vec![Cirru::leaf("assert="), Cirru::leaf("43"), Cirru::leaf("answer")]);
    assert_ne!(
      revision,
      definition_revision(&changed).expect("changed test revision should render")
    );
  }

  #[test]
  fn definition_revision_supports_leaf_examples_and_tests() {
    let mut entry = revision_test_entry(&["public"]);
    entry.examples = vec![Cirru::leaf("literal-example")];
    entry.tests[0].code = Cirru::leaf("run-test");

    let revision = definition_revision(&entry).expect("leaf code entries should have a revision");

    assert!(revision.starts_with("md5:"));
    entry.tests[0].code = Cirru::leaf("run-other-test");
    assert_ne!(
      revision,
      definition_revision(&entry).expect("changed leaf test should have a revision")
    );
  }

  #[test]
  fn code_entry_tests_round_trip_through_edn() {
    let entry = revision_test_entry(&["public"]);
    let edn = Edn::from(&entry);
    let decoded = CodeEntry::try_from(edn).expect("CodeEntry tests should deserialize");
    assert_eq!(decoded.tests, entry.tests);
  }

  #[test]
  fn code_entry_rejects_duplicate_test_names() {
    let test = TestEntry {
      name: "duplicate".to_owned(),
      code: Cirru::leaf("nil"),
      tags: HashSet::new(),
    };
    let edn = Edn::struct_from_pairs(
      "CodeEntry",
      &[
        (EdnTag::new("doc"), Edn::Str(Arc::from(""))),
        (EdnTag::new("examples"), Edn::List(EdnListView(vec![]))),
        (
          EdnTag::new("tests"),
          Edn::List(EdnListView(vec![Edn::from(&test), Edn::from(&test)])),
        ),
        (EdnTag::new("code"), Cirru::leaf("nil").into()),
      ],
    );
    let error = CodeEntry::try_from(edn).expect_err("duplicate test names should be rejected");
    assert!(error.contains("duplicate test name `duplicate`"), "unexpected error: {error}");
  }

  #[test]
  fn test_names_reject_surrounding_whitespace() {
    let error = validate_test_names([" stable-name "], "CodeEntry.tests").expect_err("whitespace must be rejected");
    assert!(error.contains("leading or trailing whitespace"), "unexpected error: {error}");
  }

  use std::fs;

  #[test]
  fn normalizes_simple_quoted_tokens_to_pipe_prefix() {
    let input = "{} (:a \"|&\") (:b \"|56px\") (:c \"|hello-world\")";
    let nodes = cirru_parser::parse(input).expect("input should parse");
    let output_node = normalize_pipe_prefixed_leaf(nodes[0].to_owned());
    let output = cirru_parser::format(std::slice::from_ref(&output_node), true.into()).expect("output should format");
    assert_eq!(output.trim(), "{} (:a |&) (:b |56px) (:c |hello-world)");
  }

  #[test]
  fn normalizes_all_quote_prefixed_leaves_from_ast() {
    let input = "{} (:a \"|hello world\") (:b \"|line\\nfeed\") (:c \"|x(y)\")";
    let nodes = cirru_parser::parse(input).expect("input should parse");
    let output_node = normalize_pipe_prefixed_leaf(nodes[0].to_owned());
    let output = cirru_parser::format(std::slice::from_ref(&output_node), true.into()).expect("output should format");

    let nodes = cirru_parser::parse(&output).expect("normalized output should still be parseable");
    let Cirru::List(root_items) = &nodes[0] else {
      panic!("expected one root list");
    };

    for pair in root_items.iter().skip(1) {
      let Cirru::List(pair_items) = pair else {
        continue;
      };
      if pair_items.len() < 2 {
        continue;
      }
      let Cirru::Leaf(value) = &pair_items[1] else {
        continue;
      };
      assert!(
        value.starts_with('|'),
        "expected string leaf to be normalized to pipe-prefix in AST, got: {value}"
      );
    }
  }

  #[test]
  fn test_examples_field_parsing() {
    // 读取实际的 calcit-core.cirru 文件
    let core_file_content = fs::read_to_string("src/cirru/calcit-core.cirru").expect("Failed to read calcit-core.cirru");

    // 直接解析为 EDN
    let edn_data = cirru_edn::parse(&core_file_content).expect("Failed to parse cirru content as EDN");

    // 解析为 Snapshot
    let snapshot: Snapshot = load_snapshot_data(&edn_data, "calcit-core.cirru").expect("Failed to parse snapshot");

    // 验证文件存在
    assert!(snapshot.files.contains_key("calcit.core"));

    let core_file = &snapshot.files["calcit.core"];

    // 验证我们添加了 examples 的函数
    let functions_with_examples = vec![
      ("+", 2),
      ("-", 2),
      ("*", 6),
      ("/", 2),
      ("map", 2),
      ("filter", 2),
      ("first", 3),
      ("count", 2),
      ("concat", 1),
      ("inc", 2),
      ("reduce", 1), // 原本就有的,只有1个example
    ];

    println!("Verifying examples in calcit-core.cirru:");
    for (func_name, expected_count) in functions_with_examples {
      if let Some(func_def) = core_file.defs.get(func_name) {
        println!("  {}: {} examples", func_name, func_def.examples.len());
        assert_eq!(
          func_def.examples.len(),
          expected_count,
          "Function '{func_name}' should have {expected_count} examples"
        );
      } else {
        panic!("Function '{func_name}' not found in calcit.core");
      }
    }
  }

  #[test]
  fn test_code_entry_with_examples() {
    // 创建一个带有 examples 的 CodeEntry
    let examples = vec![
      Cirru::List(vec![Cirru::leaf("add"), Cirru::leaf("1"), Cirru::leaf("2")]),
      Cirru::List(vec![Cirru::leaf("add"), Cirru::leaf("10"), Cirru::leaf("20")]),
    ];

    let code_entry = CodeEntry {
      doc: "Test function".to_string(),
      code: Cirru::List(vec![
        Cirru::leaf("defn"),
        Cirru::leaf("add"),
        Cirru::List(vec![Cirru::leaf("a"), Cirru::leaf("b")]),
        Cirru::List(vec![Cirru::leaf("+"), Cirru::leaf("a"), Cirru::leaf("b")]),
      ]),
      examples,
      tests: vec![],
      tags: HashSet::new(),
      schema: {
        let schema_edn = schema_cirru_to_edn(Cirru::List(vec![
          Cirru::leaf("{}"),
          Cirru::List(vec![Cirru::leaf(":kind"), Cirru::leaf(":fn")]),
          Cirru::List(vec![Cirru::leaf(":name"), Cirru::leaf("'add")]),
          Cirru::List(vec![Cirru::leaf(":args"), Cirru::List(vec![Cirru::leaf("[]")])]),
          Cirru::List(vec![Cirru::leaf(":return"), Cirru::leaf(":number")]),
        ]));
        CalcitTypeAnnotation::parse_fn_schema_from_edn(&schema_edn)
          .map(|s| std::sync::Arc::new(CalcitTypeAnnotation::Fn(std::sync::Arc::new(s))))
          .unwrap_or_else(|| DYNAMIC_TYPE.clone())
      },
      ffi: None,
    };

    // 验证 examples 字段
    assert_eq!(code_entry.examples.len(), 2);

    // 验证第一个 example
    if let Cirru::List(list) = &code_entry.examples[0] {
      assert_eq!(list.len(), 3);
      if let Cirru::Leaf(s) = &list[0] {
        assert_eq!(&**s, "add");
      }
    }

    // 转换为 EDN 再转换回来,验证序列化/反序列化
    let edn: Edn = code_entry.clone().into();
    let parsed_entry: CodeEntry = edn.try_into().expect("Failed to parse CodeEntry from EDN");

    assert_eq!(parsed_entry.examples.len(), 2);

    // 验证解析后的第一个 example
    if let Cirru::List(list) = &parsed_entry.examples[0] {
      assert_eq!(list.len(), 3);
      if let Cirru::Leaf(s) = &list[0] {
        assert_eq!(&**s, "add");
      }
    }

    println!("✅ CodeEntry with examples test passed!");
  }

  #[test]
  fn test_code_entry_tags_field_defaults_and_round_trip() {
    let entry_edn = Edn::struct_from_pairs(
      "CodeEntry",
      &[
        ("doc".into(), Edn::str("tagged def")),
        ("examples".into(), Edn::List(EdnListView(vec![]))),
        ("code".into(), Cirru::leaf("x").into()),
        ("schema".into(), Edn::tag("dynamic")),
      ],
    );
    let parsed: CodeEntry = entry_edn.try_into().expect("missing tags should default to empty set");
    assert!(parsed.tags.is_empty());

    let mut tagged = parsed.clone();
    tagged.tags.insert(EdnTag::new("smoke"));
    tagged.tags.insert(EdnTag::new("doc"));

    let serialized = Edn::from(&tagged);
    let Edn::Struct(struct_value) = &serialized else {
      panic!("expected CodeEntry struct");
    };
    assert!(struct_value.pairs.iter().any(|(k, _)| k.ref_str() == "tags"));

    let reloaded: CodeEntry = serialized.try_into().expect("tags should round-trip");
    assert_eq!(reloaded.tags, tagged.tags);

    let mut external = tagged.clone();
    external.ffi = Some(Edn::map_from_iter([
      (Edn::tag("backend"), Edn::tag("js")),
      (Edn::tag("kind"), Edn::tag("external-object")),
    ]));
    let external_serialized = Edn::from(&external);
    let external_reloaded: CodeEntry = external_serialized.try_into().expect("ffi metadata should round-trip");
    assert_eq!(external_reloaded.ffi, external.ffi);

    let empty_serialized = Edn::from(&parsed);
    let Edn::Struct(empty_struct) = &empty_serialized else {
      panic!("expected CodeEntry struct");
    };
    assert!(!empty_struct.pairs.iter().any(|(k, _)| k.ref_str() == "tags"));
  }

  #[test]
  fn test_parse_schema_data_valid_and_invalid() {
    let valid = Cirru::List(vec![
      Cirru::leaf("{}"),
      Cirru::List(vec![Cirru::leaf(":kind"), Cirru::leaf(":fn")]),
      Cirru::List(vec![Cirru::leaf(":name"), Cirru::leaf("'demo")]),
      Cirru::List(vec![Cirru::leaf(":args"), Cirru::List(vec![Cirru::leaf("[]")])]),
      Cirru::List(vec![Cirru::leaf(":return"), Cirru::leaf(":dynamic")]),
    ]);
    assert!(parse_schema_data(&valid).is_ok());

    let missing_return = Cirru::List(vec![
      Cirru::leaf("{}"),
      Cirru::List(vec![Cirru::leaf(":kind"), Cirru::leaf(":fn")]),
      Cirru::List(vec![Cirru::leaf(":name"), Cirru::leaf("'demo")]),
      Cirru::List(vec![Cirru::leaf(":args"), Cirru::List(vec![Cirru::leaf("[]")])]),
    ]);
    assert!(parse_schema_data(&missing_return).is_ok());

    let optional_wrapped = Cirru::List(vec![Cirru::leaf(":optional"), valid.clone()]);
    assert!(parse_schema_data(&optional_wrapped).is_ok());

    let optional_wrapped_by_enum = Cirru::List(vec![Cirru::leaf("::"), Cirru::leaf(":optional"), valid]);
    assert!(parse_schema_data(&optional_wrapped_by_enum).is_ok());

    let invalid_edn = Cirru::List(vec![Cirru::leaf("~"), Cirru::leaf("x")]);
    assert!(parse_schema_data(&invalid_edn).is_err());
  }

  #[test]
  fn test_validate_schema_for_write() {
    let valid = parse_one(":: :fn $ {} (:args ([] :string)) (:return :bool)");
    assert!(validate_schema_for_write(&valid).is_ok(), "valid schema should pass");

    let valid_with_where = parse_one(":: :fn $ {} (:generics ([] 'T)) (:args ([] 'T)) (:where {} ('T Show)) (:return :string)");
    assert!(
      validate_schema_for_write(&valid_with_where).is_ok(),
      "schema with :where should pass"
    );

    let wrapped_macro = Cirru::List(vec![
      Cirru::leaf("::"),
      Cirru::leaf(":macro"),
      Cirru::List(vec![
        Cirru::leaf("{}"),
        Cirru::List(vec![
          Cirru::leaf(":args"),
          Cirru::List(vec![Cirru::leaf("[]"), Cirru::leaf(":dynamic")]),
        ]),
        Cirru::List(vec![Cirru::leaf(":return"), Cirru::leaf(":dynamic")]),
      ]),
    ]);
    assert!(
      validate_schema_for_write(&wrapped_macro).is_ok(),
      "wrapped macro schema should pass"
    );

    let ref_bool = Cirru::List(vec![Cirru::leaf("::"), Cirru::leaf(":ref"), Cirru::leaf(":bool")]);
    assert!(
      validate_schema_for_write(&ref_bool).is_ok(),
      "standalone parameterized value schema should pass"
    );

    let qualified_struct = Cirru::Leaf(Arc::from("'app.schema/Store"));
    let qualified_result = validate_schema_for_write(&qualified_struct);
    assert!(
      qualified_result.is_ok(),
      "fully qualified nominal value schema should pass: {qualified_result:?}"
    );
    let qualified_annotation =
      parse_schema_annotation_for_write(&qualified_struct).expect("fully qualified nominal value schema should parse");
    assert!(matches!(
      qualified_annotation.as_ref(),
      CalcitTypeAnnotation::TypeRef(name, args) if name.as_ref() == "app.schema/Store" && args.is_empty()
    ));
    let unqualified_struct = Cirru::Leaf(Arc::from("'Store"));
    let error = validate_schema_for_write(&unqualified_struct).expect_err("unqualified nominal value schema should fail");
    assert!(error.contains("fully qualified nominal type"), "error: {error}");

    // Legacy unwrapped callable maps are rejected even when they carry :kind.
    let legacy_unwrapped = parse_one("{} (:kind :fn) (:args ([] :string)) (:return :bool)");
    let error = validate_schema_for_write(&legacy_unwrapped).expect_err("legacy map should fail");
    assert!(error.contains("Legacy unwrapped callable schema"), "error: {error}");

    // Missing callable wrapper
    let no_kind = Cirru::List(vec![
      Cirru::leaf("{}"),
      Cirru::List(vec![Cirru::leaf(":args"), Cirru::List(vec![Cirru::leaf("[]")])]),
    ]);
    assert!(validate_schema_for_write(&no_kind).is_err(), "missing :kind should fail");

    // Unknown field
    let unknown_field = parse_one(":: :fn $ {} (:foobar :dynamic)");
    assert!(validate_schema_for_write(&unknown_field).is_err(), "unknown field should fail");

    // Bad outer callable kind.
    let bad_kind = parse_one(":: :something-else $ {}");
    assert!(validate_schema_for_write(&bad_kind).is_err(), "bad :kind value should fail");

    let repeated_kind = parse_one(":: :fn $ {} (:kind :fn) (:return :unit)");
    let error = validate_schema_for_write(&repeated_kind).expect_err("redundant inner kind should fail");
    assert!(error.contains("must not repeat `:kind`"), "error: {error}");

    // Primitive type tag leaves are now accepted.
    let leaf_string = Cirru::Leaf(Arc::from(":string"));
    assert!(validate_schema_for_write(&leaf_string).is_ok(), ":string leaf should pass");
    let parsed_leaf_string = parse_schema_annotation_for_write(&leaf_string).expect(":string leaf should parse");
    assert!(matches!(parsed_leaf_string.as_ref(), CalcitTypeAnnotation::String));
    let quoted_string = Cirru::Leaf(Arc::from("'String"));
    let parsed_quoted_string = parse_schema_annotation_for_write(&quoted_string).expect("'String leaf should parse");
    assert!(matches!(parsed_quoted_string.as_ref(), CalcitTypeAnnotation::String));

    for (legacy, replacement) in [
      ("'Record", "'Struct"),
      ("'Tuple", "'Enum"),
      (":record", "'Struct"),
      (":tuple", "'Enum"),
    ] {
      let error =
        validate_schema_for_write(&Cirru::Leaf(Arc::from(legacy))).expect_err("legacy data type names must be rejected on write");
      assert!(error.contains(replacement), "error should point to {replacement}: {error}");
    }

    let nested_legacy = parse_one(":: 'List 'Record");
    let error = validate_schema_for_write(&nested_legacy).expect_err("nested legacy data type names must be rejected on write");
    assert!(error.contains("'Struct"), "nested error should point to 'Struct: {error}");
    let leaf_fn = Cirru::Leaf(Arc::from(":fn"));
    assert!(validate_schema_for_write(&leaf_fn).is_err(), "bare :fn should require a signature");
    let leaf_ref = Cirru::Leaf(Arc::from(":ref"));
    let error = validate_schema_for_write(&leaf_ref).expect_err("bare :ref should require an inner type");
    assert!(error.contains("leaves its nested type dynamic"), "error: {error}");
    let leaf_number = Cirru::Leaf(Arc::from(":number"));
    assert!(validate_schema_for_write(&leaf_number).is_ok(), ":number leaf should pass");
    let leaf_any = Cirru::Leaf(Arc::from(":any"));
    assert!(validate_schema_for_write(&leaf_any).is_ok(), ":any leaf should pass");
    let leaf_trait = Cirru::Leaf(Arc::from(":trait"));
    assert!(validate_schema_for_write(&leaf_trait).is_ok(), ":trait leaf should pass");
    let leaf_enum = Cirru::Leaf(Arc::from(":enum"));
    assert!(validate_schema_for_write(&leaf_enum).is_ok(), ":enum leaf should pass");
    let leaf_struct = Cirru::Leaf(Arc::from(":struct"));
    assert!(validate_schema_for_write(&leaf_struct).is_ok(), ":struct leaf should pass");
    let leaf_impl = Cirru::Leaf(Arc::from(":impl"));
    assert!(validate_schema_for_write(&leaf_impl).is_ok(), ":impl leaf should pass");
    for kind in ["struct", "enum", "trait", "impl"] {
      let schema = Cirru::Leaf(Arc::from(format!(":{kind}")));
      let annotation = parse_schema_annotation_for_write(&schema).unwrap_or_else(|error| panic!(":{kind} should parse: {error}"));
      assert!(
        matches!(annotation.as_ref(), CalcitTypeAnnotation::Custom(value) if matches!(value.as_ref(), crate::calcit::Calcit::Tag(tag) if tag.ref_str() == kind)),
        ":{kind} should keep its broad schema kind, got {annotation}"
      );
    }

    // Unknown leaf (not a known primitive type) must still fail.
    let leaf_unknown = Cirru::Leaf(Arc::from(":not-a-type"));
    assert!(validate_schema_for_write(&leaf_unknown).is_err(), "unknown leaf should fail");

    // Wrong head (still quote-wrapped - must be unwrapped by caller first)
    let quote_wrapped = Cirru::List(vec![
      Cirru::leaf("quote"),
      Cirru::List(vec![Cirru::leaf("{}"), Cirru::List(vec![Cirru::leaf(":kind"), Cirru::leaf(":fn")])]),
    ]);
    assert!(
      validate_schema_for_write(&quote_wrapped).is_err(),
      "quote-wrapped should fail (caller must unwrap)"
    );
  }

  #[test]
  fn standalone_value_schema_round_trips_without_becoming_dynamic() {
    let schema_edn = Edn::enum_value("ref", vec![Edn::tag("bool")]);
    let annotation = parse_loaded_schema_annotation(&schema_edn, "tests/*flag").expect("ref<bool> should load");

    assert!(matches!(
      annotation.as_ref(),
      CalcitTypeAnnotation::Ref(inner) if matches!(inner.as_ref(), CalcitTypeAnnotation::Bool)
    ));
    assert_eq!(
      schema_annotation_to_edn(annotation.as_ref()),
      Edn::enum_value("Ref", vec![Edn::Symbol(Arc::from("Bool"))])
    );

    let mut entry = CodeEntry::from_code(Cirru::leaf("nil"));
    entry.schema = annotation;
    let encoded = rmp_serde::to_vec(&entry).expect("value schema should serialize into binary snapshot data");
    let decoded: CodeEntry = rmp_serde::from_slice(&encoded).expect("value schema should deserialize from binary snapshot data");
    assert!(matches!(
      decoded.schema.as_ref(),
      CalcitTypeAnnotation::Ref(inner) if matches!(inner.as_ref(), CalcitTypeAnnotation::Bool)
    ));

    let nominal_edn = Edn::Symbol(Arc::from("app.schema/Store"));
    let nominal = parse_loaded_schema_annotation(&nominal_edn, "app.schema/store").expect("qualified nominal schema should load");
    assert!(matches!(
      nominal.as_ref(),
      CalcitTypeAnnotation::TypeRef(name, args) if name.as_ref() == "app.schema/Store" && args.is_empty()
    ));
    let stored_nominal = schema_annotation_to_edn(nominal.as_ref());
    assert_eq!(stored_nominal, Edn::enum_value("app.schema/Store", vec![]));
    let reloaded = parse_loaded_schema_annotation(&stored_nominal, "app.schema/store").expect("stored nominal schema should reload");
    assert!(matches!(
      reloaded.as_ref(),
      CalcitTypeAnnotation::TypeRef(name, args) if name.as_ref() == "app.schema/Store" && args.is_empty()
    ));
  }

  #[test]
  fn format_canonicalizes_legacy_type_tags_only_in_type_positions() {
    let typed = parse_one(
      "defn example (value) :string\n  hint-fn $ {} (:args $ [] :number) (:return $ :: :list :string)\n  assert-type value :string\n  unsafe-coerce value $ :: :ref :bool",
    );
    let enum_decl = parse_one("defenum Result (:ok :string) (:err :tag)");
    let ordinary_data = parse_one("def config $ {} (:kind :string)");

    let (typed, typed_count) = canonicalize_code_type_syntax(&typed);
    let (enum_decl, enum_count) = canonicalize_code_type_syntax(&enum_decl);
    let (ordinary_data, data_count) = canonicalize_code_type_syntax(&ordinary_data);

    let typed_text = cirru_parser::format(&[typed], true.into()).expect("typed code should render");
    let enum_text = cirru_parser::format(&[enum_decl], true.into()).expect("enum should render");
    let data_text = cirru_parser::format(&[ordinary_data], true.into()).expect("data should render");
    assert_eq!(typed_count, 7, "typed text: {typed_text}");
    assert_eq!(enum_count, 2, "enum text: {enum_text}");
    assert_eq!(data_count, 0, "data text: {data_text}");
    assert!(typed_text.contains("'String") && typed_text.contains(":: 'List 'String") && typed_text.contains(":: 'Ref 'Bool"));
    assert!(enum_text.contains("(:ok 'String)") && enum_text.contains("(:err 'Tag)"));
    assert!(
      data_text.contains("(:kind :string)"),
      "ordinary tag data must not be rewritten: {data_text}"
    );
  }

  #[test]
  fn test_typevar_consistency_validation() {
    // Valid: 'T declared and used in both args and return
    let valid_generic = parse_one(":: :fn $ {} (:generics ([] 'T)) (:args ([] (:: :list 'T))) (:return 'T)");
    assert!(validate_schema_for_write(&valid_generic).is_ok(), "valid generics should pass");

    // Invalid: 'K used in :return but not declared in :generics
    let undeclared = parse_one(":: :fn $ {} (:generics ([] 'T)) (:args ([] (:: :list 'T))) (:return 'K)");
    assert!(
      validate_schema_for_write(&undeclared).is_err(),
      "undeclared type var 'K should fail"
    );

    // Invalid: 'U declared but never used
    let unused_declared = parse_one(":: :fn $ {} (:generics ([] 'T 'U)) (:args ([] (:: :list 'T))) (:return 'T)");
    assert!(
      validate_schema_for_write(&unused_declared).is_err(),
      "unused declared 'U should fail"
    );

    // Invalid: type var used without any :generics
    let typevar_no_generics = parse_one(":: :fn $ {} (:args ([] 'T)) (:return 'T)");
    assert!(
      validate_schema_for_write(&typevar_no_generics).is_err(),
      "type var without :generics should fail"
    );
  }

  #[test]
  fn test_schema_cirru_to_edn_no_quote_wrapper() {
    let schema = Cirru::List(vec![
      Cirru::leaf("{}"),
      Cirru::List(vec![Cirru::leaf(":kind"), Cirru::leaf(":fn")]),
      Cirru::List(vec![Cirru::leaf(":return"), Cirru::leaf(":string")]),
    ]);
    let edn = schema_cirru_to_edn(schema);
    assert!(!matches!(edn, Edn::Nil), "should not produce Nil for valid schema");
    assert!(
      !matches!(edn, Edn::Quote(_)),
      "output must NOT be Quote-wrapped (new direct-map format)"
    );
  }

  #[test]
  fn test_schema_generics_round_trip_uses_single_quote_source_syntax() {
    let schema_text = "{} (:kind :fn) (:args ([] 'T)) (:generics ([] 'T)) (:return 'T)";
    let schema_cirru = cirru_parser::parse(schema_text)
      .expect("should parse")
      .into_iter()
      .next()
      .expect("should have one node");

    let schema_edn = schema_cirru_to_edn(schema_cirru);
    let fn_schema = CalcitTypeAnnotation::parse_fn_schema_from_edn(&schema_edn).expect("must parse generic schema");
    assert_eq!(fn_schema.generics.as_ref(), &[Arc::from("T")]);

    let saved_edn = fn_schema.to_schema_edn();
    let Edn::Map(saved_map) = &saved_edn else {
      panic!("saved schema must be a map, got {saved_edn:?}");
    };
    let Some(Edn::List(generics)) = saved_map.tag_get("generics") else {
      panic!("saved schema must contain :generics, got {saved_edn:?}");
    };
    assert_eq!(generics.0, vec![Edn::Symbol(Arc::from("T"))]);

    let saved_cirru = schema_edn_to_cirru(&fn_schema.to_wrapped_schema_edn()).expect("schema edn to cirru");
    validate_schema_for_write(&saved_cirru).expect("saved schema should still be writable");
    let saved_text = cirru_parser::format(&[saved_cirru], true.into()).expect("format schema");
    assert!(
      saved_text.contains(":generics $ [] 'T"),
      "saved schema should use single-quoted source syntax: {saved_text}"
    );
    assert!(
      !saved_text.contains("''T"),
      "saved schema must not contain double-leading-quote generics: {saved_text}"
    );
  }

  #[test]
  fn test_schema_where_round_trip_is_preserved() {
    let schema_text = ":: :fn $ {} (:generics ([] 'T)) (:args ([] 'T)) (:where {} ('T Show)) (:return :string)";
    let schema_cirru = cirru_parser::parse(schema_text)
      .expect("should parse")
      .into_iter()
      .next()
      .expect("should have one node");

    validate_schema_for_write(&schema_cirru).expect("schema with where should be writable");

    let schema_edn = schema_cirru_to_edn(schema_cirru);
    let fn_schema =
      CalcitTypeAnnotation::parse_fn_schema_from_edn(&schema_edn).unwrap_or_else(|| panic!("must parse where schema: {schema_edn:?}"));
    assert_eq!(fn_schema.where_bounds.len(), 1, "schema_edn={schema_edn:?}");
    assert_eq!(fn_schema.where_bounds[0].name.as_ref(), "T");
    assert_eq!(fn_schema.where_bounds[0].traits[0].name.ref_str(), "Show");

    let saved_cirru = schema_edn_to_cirru(&fn_schema.to_wrapped_schema_edn()).expect("schema edn to cirru");
    validate_schema_for_write(&saved_cirru).expect("saved where schema should still be writable");
    let saved_text = cirru_parser::format(&[saved_cirru], true.into()).expect("format schema");
    assert!(saved_text.contains(":where"), "saved schema should keep :where: {saved_text}");
    assert!(
      saved_text.contains("Show"),
      "saved schema should keep trait bound payload: {saved_text}"
    );
  }

  #[test]
  fn test_schema_named_type_refs_round_trip_without_becoming_type_vars() {
    let schema_text = "{} (:kind :fn) (:generics ([] 'T 'E)) (:args ([] 'T)) (:return (:: 'Result 'T 'E))";
    let schema_cirru = cirru_parser::parse(schema_text)
      .expect("should parse")
      .into_iter()
      .next()
      .expect("should have one node");

    let schema_edn = schema_cirru_to_edn(schema_cirru);
    let fn_schema = CalcitTypeAnnotation::parse_fn_schema_from_edn(&schema_edn).expect("must parse named ref schema");

    assert!(
      matches!(fn_schema.arg_types.first().map(|t| t.as_ref()), Some(CalcitTypeAnnotation::TypeVar(name)) if name.as_ref() == "T")
    );
    assert!(
      matches!(fn_schema.return_type.as_ref(), CalcitTypeAnnotation::TypeRef(name, args) if name.as_ref() == "Result" && args.len() == 2)
    );

    let saved_text = cirru_parser::format(
      &[schema_edn_to_cirru(&fn_schema.to_schema_edn()).expect("schema edn to cirru")],
      true.into(),
    )
    .expect("format schema");
    assert!(
      saved_text.contains(":return $ :: 'Result 'T 'E"),
      "saved schema should keep named type reference syntax: {saved_text}"
    );
  }

  #[test]
  fn test_normalize_schema_rejects_legacy_quoted_generic_symbol() {
    let schema = Edn::Map(EdnMapView::from(HashMap::from([
      (Edn::tag("kind"), Edn::tag("fn")),
      (Edn::tag("args"), Edn::List(cirru_edn::EdnListView(vec![Edn::tag("number")]))),
      (
        Edn::tag("generics"),
        Edn::List(cirru_edn::EdnListView(vec![Edn::Symbol(Arc::from("'T"))])),
      ),
      (Edn::tag("return"), Edn::tag("number")),
    ])));

    let err = normalize_schema_edn(&schema).expect_err("legacy quoted generic symbol should fail on load");
    assert!(err.contains("invalid schema generic symbol"), "unexpected error: {err}");
  }

  #[test]
  fn test_schema_write_rejects_double_quoted_generics() {
    let schema_text = ":: :fn $ {} (:args ([] :number)) (:generics ([] ''T)) (:return :number)";
    let schema_cirru = cirru_parser::parse(schema_text)
      .expect("should parse")
      .into_iter()
      .next()
      .expect("should have one node");

    let err = validate_schema_for_write(&schema_cirru).expect_err("double-quoted generic should be rejected");
    assert!(err.contains("excess leading quotes"), "unexpected error: {err}");
  }

  #[test]
  fn test_normalize_schema_rejects_quoted_singleton_list() {
    let quoted = Edn::Quote(Cirru::List(vec![
      Cirru::leaf("[]"),
      Cirru::List(vec![
        Cirru::leaf("{}"),
        Cirru::List(vec![Cirru::leaf(":kind"), Cirru::leaf(":fn")]),
        Cirru::List(vec![Cirru::leaf(":args"), Cirru::List(vec![Cirru::leaf("[]")])]),
        Cirru::List(vec![Cirru::leaf(":return"), Cirru::leaf(":dynamic")]),
      ]),
    ]));

    let err = normalize_schema_edn(&quoted).expect_err("legacy quoted schema should be rejected");
    assert!(err.contains("invalid schema"), "unexpected error: {err}");
  }

  #[test]
  fn test_normalize_schema_unwraps_wrapped_fn_enum() {
    let wrapped = Edn::enum_value(
      "fn",
      vec![Edn::Map(EdnMapView::from(HashMap::from([
        (Edn::tag("kind"), Edn::tag("fn")),
        (Edn::tag("args"), Edn::List(EdnListView(vec![]))),
        (Edn::tag("return"), Edn::tag("dynamic")),
      ])))],
    );

    let normalized = normalize_schema_edn(&wrapped).expect("wrapped schema should normalize");
    let Edn::Map(map) = normalized else {
      panic!("normalized schema should be a map");
    };
    assert!(matches!(map.tag_get("kind"), Some(Edn::Tag(tag)) if tag.ref_str() == "fn"));
  }

  #[test]
  fn test_normalize_schema_unwraps_wrapped_macro_enum() {
    let wrapped = Edn::enum_value(
      "macro",
      vec![Edn::Map(EdnMapView::from(HashMap::from([
        (Edn::tag("args"), Edn::List(EdnListView(vec![]))),
        (Edn::tag("return"), Edn::tag("dynamic")),
      ])))],
    );

    let normalized = normalize_schema_edn(&wrapped).expect("wrapped macro schema should normalize");
    let Edn::Map(map) = normalized else {
      panic!("normalized schema should be a map");
    };
    assert!(matches!(map.tag_get("kind"), Some(Edn::Tag(tag)) if tag.ref_str() == "macro"));
  }

  #[test]
  fn test_normalize_schema_canonicalizes_string_keys_and_kind_values() {
    let wrapped = Edn::enum_value(
      "fn",
      vec![Edn::Map(EdnMapView::from(HashMap::from([
        (Edn::Str(Arc::from(":args")), Edn::List(EdnListView(vec![Edn::tag("set")]))),
        (Edn::Str(Arc::from(":return")), Edn::tag("bool")),
        (Edn::Str(Arc::from(":kind")), Edn::Str(Arc::from(":fn"))),
      ])))],
    );

    let normalized = normalize_schema_edn(&wrapped).expect("string-key schema should normalize");
    let Edn::Map(map) = normalized else {
      panic!("normalized schema should be a map");
    };

    assert!(matches!(map.tag_get("args"), Some(Edn::List(_))));
    assert!(matches!(map.tag_get("return"), Some(Edn::Tag(tag)) if tag.ref_str() == "bool"));
    assert!(matches!(map.tag_get("kind"), Some(Edn::Tag(tag)) if tag.ref_str() == "fn"));
    assert!(CalcitTypeAnnotation::parse_fn_schema_from_edn(&Edn::Map(map)).is_some());
  }

  #[test]
  fn data_definition_schema_uses_definition_kind_marker() {
    for (head, marker) in [
      ("defstruct", "struct-def"),
      ("defenum", "enum-def"),
      ("deftrait", "trait"),
      ("defimpl", "impl"),
    ] {
      let code = Cirru::List(vec![Cirru::leaf(head)]);
      let normalized = normalize_schema_for_code(&code, &DYNAMIC_TYPE);
      assert!(
        matches!(normalized.as_ref(), CalcitTypeAnnotation::Custom(value) if matches!(value.as_ref(), Calcit::Tag(tag) if tag.ref_str() == marker)),
        "{head} should normalize Dynamic to {marker}, got {normalized}"
      );
      assert!(
        !matches!(normalized.as_ref(), CalcitTypeAnnotation::Dynamic),
        "{head} definition marker must not remain Dynamic"
      );
    }
  }

  #[test]
  fn explicit_data_definition_schema_is_not_overwritten() {
    let code = Cirru::List(vec![Cirru::leaf("defstruct")]);
    let explicit = Arc::new(CalcitTypeAnnotation::Custom(Arc::new(Calcit::tag("struct"))));
    assert_eq!(normalize_schema_for_code(&code, &explicit), explicit);
  }

  #[test]
  fn test_macro_schema_full_file_round_trip() {
    use crate::calcit::SchemaKind;
    // Simulate saving + loading via the actual file format:
    // 1. Write a CodeEntry with :kind :macro schema to Edn (as done by save_snapshot_to_file)
    // 2. Format it to Cirru string (via cirru_edn::format)
    // 3. Parse it back (via cirru_edn::parse)
    // 4. TryFrom<Edn> for CodeEntry
    // 5. Check entry.schema is Fn with fn_kind: Macro

    let schema_text = "{} (:kind :macro) (:return :bool) (:args ([] :number :number))";
    let schema_cirru = cirru_parser::parse(schema_text)
      .expect("should parse")
      .into_iter()
      .next()
      .expect("should have one node");
    let schema_edn = schema_cirru_to_edn(schema_cirru);

    let fn_schema = CalcitTypeAnnotation::parse_fn_schema_from_edn(&schema_edn).expect("must parse");
    assert_eq!(fn_schema.fn_kind, SchemaKind::Macro);

    // Build a minimal CodeEntry with this schema
    let entry = CodeEntry {
      doc: "test fn".to_owned(),
      examples: vec![],
      tests: vec![],
      tags: HashSet::new(),
      code: vec!["defmacro", "test-fn", "(a b)", "nil"].into(),
      schema: std::sync::Arc::new(CalcitTypeAnnotation::Fn(std::sync::Arc::new(fn_schema))),
      ffi: None,
    };

    // Serialize to Edn (as From<&CodeEntry> for Edn does)
    let entry_edn: Edn = Edn::from(&entry);

    // Format to Cirru string and parse back (as save_snapshot + load_snapshot do)
    let cirru_text = cirru_edn::format(&entry_edn, true).expect("format should succeed");
    assert!(
      cirru_text.contains(":schema $ :: 'Macro"),
      "macro schema should use canonical wrapped 'Macro symbol: {cirru_text}"
    );
    assert!(
      cirru_text.contains(":return 'Bool"),
      "macro schema should preserve non-dynamic return field during serialization: {cirru_text}"
    );
    let parsed_edn = cirru_edn::parse(&cirru_text).expect("parse should succeed");

    // Deserialize back to CodeEntry
    let reloaded: CodeEntry = parsed_edn.try_into().expect("TryFrom<Edn> should succeed");

    // Check the schema was preserved
    match reloaded.schema.as_ref() {
      CalcitTypeAnnotation::Fn(fn_annot) => {
        assert_eq!(
          fn_annot.fn_kind,
          SchemaKind::Macro,
          "fn_kind must survive round-trip; cirru_text: {cirru_text:?}"
        );
        assert_eq!(fn_annot.arg_types.len(), 2, "arg_types must survive round-trip");
      }
      other => panic!("schema must be Fn after round-trip, got {other:?}; cirru_text: {cirru_text:?}"),
    }
  }

  #[test]
  fn test_code_entry_serializes_schema_as_wrapped_fn() {
    use crate::calcit::SchemaKind;

    let entry = CodeEntry {
      doc: "wrapped schema".to_owned(),
      examples: vec![],
      tests: vec![],
      tags: HashSet::new(),
      code: vec!["defn", "wrapped", "()", "nil"].into(),
      schema: std::sync::Arc::new(CalcitTypeAnnotation::Fn(std::sync::Arc::new(CalcitFnTypeAnnotation {
        generics: std::sync::Arc::new(vec![]),
        where_bounds: std::sync::Arc::new(vec![]),
        arg_types: vec![],
        return_type: crate::calcit::DYNAMIC_TYPE.clone(),
        fn_kind: SchemaKind::Fn,
        rest_type: None,
        features: std::sync::Arc::new(std::collections::HashSet::new()),
      }))),
      ffi: None,
    };

    let entry_edn: Edn = Edn::from(&entry);
    let schema = match entry_edn {
      Edn::Struct(struct_value) => struct_value
        .pairs
        .iter()
        .find(|(k, _)| k.arc_str().as_ref() == "schema")
        .map(|(_, v)| v.to_owned())
        .expect("schema field should exist"),
      _ => panic!("expected struct edn"),
    };

    let Edn::Enum(view) = schema else {
      panic!("top-level schema should serialize as wrapped fn tuple");
    };
    assert_eq!(view.variant.as_ref(), "Fn");
    let Some(Edn::Map(map)) = view.extra.first() else {
      panic!("wrapped schema payload should be a map");
    };
    assert!(
      map.tag_get("kind").is_none(),
      "wrapped plain fn schema should omit redundant :kind :fn"
    );
  }

  #[test]
  fn test_code_entry_serializes_macro_rest_schema_without_losing_rest() {
    use crate::calcit::SchemaKind;

    let entry = CodeEntry {
      doc: "wrapped macro schema".to_owned(),
      examples: vec![],
      tests: vec![],
      tags: HashSet::new(),
      code: vec!["defmacro", "wrapped", "(& body)", "nil"].into(),
      schema: std::sync::Arc::new(CalcitTypeAnnotation::Fn(std::sync::Arc::new(CalcitFnTypeAnnotation {
        generics: std::sync::Arc::new(vec![]),
        where_bounds: std::sync::Arc::new(vec![]),
        arg_types: vec![crate::calcit::DYNAMIC_TYPE.clone()],
        return_type: crate::calcit::DYNAMIC_TYPE.clone(),
        fn_kind: SchemaKind::Macro,
        rest_type: Some(crate::calcit::DYNAMIC_TYPE.clone()),
        features: std::sync::Arc::new(std::collections::HashSet::new()),
      }))),
      ffi: None,
    };

    let entry_edn: Edn = Edn::from(&entry);
    let schema = match entry_edn {
      Edn::Struct(struct_value) => struct_value
        .pairs
        .iter()
        .find(|(k, _)| k.arc_str().as_ref() == "schema")
        .map(|(_, v)| v.to_owned())
        .expect("schema field should exist"),
      _ => panic!("expected struct edn"),
    };

    let Edn::Enum(view) = schema else {
      panic!("top-level schema should serialize as wrapped macro tuple");
    };
    assert_eq!(view.variant.as_ref(), "Macro");
    let Some(Edn::Map(map)) = view.extra.first() else {
      panic!("wrapped schema payload should be a map");
    };
    assert!(
      map.tag_get("kind").is_none(),
      "wrapped macro schema should omit redundant inner :kind"
    );
    assert!(map.tag_get("return").is_none(), "wrapped macro schema should omit redundant return");
    assert!(matches!(map.tag_get("rest"), Some(Edn::Symbol(name)) if name.as_ref() == "Dynamic"));
  }

  #[test]
  fn test_code_entry_serializes_macro_non_dynamic_return() {
    use crate::calcit::SchemaKind;

    let entry = CodeEntry {
      doc: "wrapped macro schema".to_owned(),
      examples: vec![],
      tests: vec![],
      tags: HashSet::new(),
      code: vec!["defmacro", "wrapped", "(x)", "x"].into(),
      schema: std::sync::Arc::new(CalcitTypeAnnotation::Fn(std::sync::Arc::new(CalcitFnTypeAnnotation {
        generics: std::sync::Arc::new(vec![]),
        where_bounds: std::sync::Arc::new(vec![]),
        arg_types: vec![crate::calcit::DYNAMIC_TYPE.clone()],
        return_type: std::sync::Arc::new(CalcitTypeAnnotation::Custom(std::sync::Arc::new(crate::calcit::Calcit::tag(
          "record",
        )))),
        fn_kind: SchemaKind::Macro,
        rest_type: None,
        features: std::sync::Arc::new(std::collections::HashSet::new()),
      }))),
      ffi: None,
    };

    let entry_edn: Edn = Edn::from(&entry);
    let schema = match entry_edn {
      Edn::Struct(struct_value) => struct_value
        .pairs
        .iter()
        .find(|(k, _)| k.arc_str().as_ref() == "schema")
        .map(|(_, v)| v.to_owned())
        .expect("schema field should exist"),
      _ => panic!("expected struct edn"),
    };

    let Edn::Enum(view) = schema else {
      panic!("top-level schema should serialize as wrapped macro tuple");
    };
    let Some(Edn::Map(map)) = view.extra.first() else {
      panic!("wrapped schema payload should be a map");
    };
    assert!(matches!(map.tag_get("return"), Some(Edn::Symbol(name)) if name.as_ref() == "Struct"));
  }

  #[test]
  fn test_defmacro_code_normalizes_fn_schema_kind_on_load() {
    let code = cirru_parser::parse("defmacro demo (x) x")
      .expect("should parse code")
      .into_iter()
      .next()
      .expect("should have one node");
    let schema = Edn::enum_value(
      "fn",
      vec![Edn::Map(EdnMapView::from(HashMap::from([
        (Edn::tag("args"), Edn::List(EdnListView(vec![Edn::tag("dynamic")]))),
        (Edn::tag("return"), Edn::tag("dynamic")),
      ])))],
    );

    let entry = Edn::struct_from_pairs(
      "CodeEntry",
      &[
        ("doc".into(), Edn::Str(Arc::from(""))),
        ("examples".into(), Edn::List(EdnListView(vec![]))),
        ("code".into(), code.into()),
        ("schema".into(), schema),
      ],
    );

    let entry: CodeEntry = entry.try_into().expect("code entry should parse");
    let CalcitTypeAnnotation::Fn(fn_annot) = entry.schema.as_ref() else {
      panic!("schema should be fn-like");
    };
    assert_eq!(fn_annot.fn_kind, SchemaKind::Macro);
  }

  #[test]
  fn test_macro_schema_round_trip() {
    use crate::calcit::SchemaKind;
    // Simulate writing a :kind :macro schema and reading it back
    let schema_text = "{} (:kind :macro) (:return :bool) (:args ([] :number :number))";
    let schema_cirru = cirru_parser::parse(schema_text)
      .expect("should parse")
      .into_iter()
      .next()
      .expect("should have one node");

    // Convert to EDN (as done by handle_schema)
    let schema_edn = schema_cirru_to_edn(schema_cirru);
    assert!(!matches!(schema_edn, Edn::Nil), "schema_edn must not be Nil: {schema_edn:?}");

    // Parse the schema (as done when reading back)
    let fn_schema = CalcitTypeAnnotation::parse_fn_schema_from_edn(&schema_edn);
    assert!(
      fn_schema.is_some(),
      "parse_fn_schema_from_edn must return Some for macro schema; schema_edn={schema_edn:?}"
    );
    let fn_schema = fn_schema.unwrap();
    assert_eq!(fn_schema.fn_kind, SchemaKind::Macro, "fn_kind must be Macro");
    assert_eq!(fn_schema.arg_types.len(), 2, "must have 2 arg types");

    // Simulate a save (to_schema_edn) + reload
    let saved_edn = fn_schema.to_schema_edn();
    let fn_schema2 = CalcitTypeAnnotation::parse_fn_schema_from_edn(&saved_edn);
    assert!(
      fn_schema2.is_some(),
      "reload: parse_fn_schema_from_edn must return Some; saved_edn={saved_edn:?}"
    );
    let fn_schema2 = fn_schema2.unwrap();
    assert_eq!(fn_schema2.fn_kind, SchemaKind::Macro, "reload: fn_kind must be Macro");
    assert_eq!(fn_schema2.arg_types.len(), 2, "reload: must have 2 arg types");

    // Simulate normalize_schema_edn path (as used in TryFrom<Edn> for CodeEntry)
    let normalized = normalize_schema_edn(&saved_edn).expect("normalize must succeed");
    let fn_schema3 = CalcitTypeAnnotation::parse_fn_schema_from_edn(&normalized);
    assert!(
      fn_schema3.is_some(),
      "normalized: parse_fn_schema_from_edn must return Some; normalized={normalized:?}"
    );
    let fn_schema3 = fn_schema3.unwrap();
    assert_eq!(fn_schema3.fn_kind, SchemaKind::Macro, "normalized: fn_kind must be Macro");
  }

  #[test]
  fn test_load_snapshot_preserves_selected_real_world_schemas() {
    let core_file_content = fs::read_to_string("src/cirru/calcit-core.cirru").expect("Failed to read calcit-core.cirru");
    let edn_data = cirru_edn::parse(&core_file_content).expect("Failed to parse cirru content as EDN");
    let snapshot = load_snapshot_data(&edn_data, "src/cirru/calcit-core.cirru").expect("Failed to parse snapshot");

    let core_file = snapshot.files.get("calcit.core").expect("calcit.core file should exist");

    for def_name in [
      "&+",
      "%{}",
      "deftrait",
      "[,]",
      "not",
      "not=",
      "noted",
      "nth",
      "number?",
      "option:map",
      "optionally",
    ] {
      let entry = core_file.defs.get(def_name).unwrap_or_else(|| panic!("missing def: {def_name}"));
      assert!(
        matches!(entry.schema.as_ref(), CalcitTypeAnnotation::Fn(_)),
        "schema for {def_name} should stay fn-like after load, got {:?}",
        entry.schema
      );
    }
  }

  #[test]
  fn optionally_schema_bridges_nullable_values_to_nominal_option() {
    let core_file_content = fs::read_to_string("src/cirru/calcit-core.cirru").expect("Failed to read calcit-core.cirru");
    let edn_data = cirru_edn::parse(&core_file_content).expect("Failed to parse cirru content as EDN");
    let snapshot = load_snapshot_data(&edn_data, "src/cirru/calcit-core.cirru").expect("Failed to parse snapshot");
    let entry = snapshot
      .files
      .get("calcit.core")
      .and_then(|file| file.defs.get("optionally"))
      .expect("calcit.core/optionally should exist");
    let CalcitTypeAnnotation::Fn(schema) = entry.schema.as_ref() else {
      panic!("optionally should have a function schema");
    };

    let input_var = match schema.arg_types.as_slice() {
      [arg] => match arg.as_ref() {
        CalcitTypeAnnotation::Optional(inner) => match inner.as_ref() {
          CalcitTypeAnnotation::TypeVar(name) => name,
          other => panic!("optionally Optional input should contain a type variable, got {other:?}"),
        },
        other => panic!("optionally should accept Optional<T>, got {other:?}"),
      },
      args => panic!("optionally should accept exactly one argument, got {args:?}"),
    };
    let output_var = match schema.return_type.as_ref() {
      CalcitTypeAnnotation::TypeRef(name, args) if name.as_ref() == "Option" => match args.as_slice() {
        [arg] => match arg.as_ref() {
          CalcitTypeAnnotation::TypeVar(name) => name,
          other => panic!("optionally Option output should contain a type variable, got {other:?}"),
        },
        args => panic!("optionally Option output should have one type argument, got {args:?}"),
      },
      other => panic!("optionally should return Option<T>, got {other:?}"),
    };
    assert_eq!(input_var, output_var, "optionally must preserve its input type variable");
  }

  #[test]
  fn test_save_snapshot_round_trip_keeps_real_world_schema_markers() {
    let core_file_content = fs::read_to_string("src/cirru/calcit-core.cirru").expect("Failed to read calcit-core.cirru");
    let edn_data = cirru_edn::parse(&core_file_content).expect("Failed to parse cirru content as EDN");
    let snapshot = load_snapshot_data(&edn_data, "src/cirru/calcit-core.cirru").expect("Failed to parse snapshot");

    let temp_path = std::env::temp_dir().join(format!("calcit-schema-roundtrip-{}.cirru", std::process::id()));

    save_snapshot_to_file(&temp_path, &snapshot).expect("round-trip save should succeed");
    let saved = fs::read_to_string(&temp_path).expect("should read saved snapshot");
    let saved_edn = cirru_edn::parse(&saved).expect("saved snapshot should remain valid EDN");
    let saved_snapshot =
      load_snapshot_data(&saved_edn, temp_path.to_str().expect("temp path should be utf-8")).expect("saved snapshot should load again");

    let source_core_file = snapshot.files.get("calcit.core").expect("source calcit.core file should exist");
    let saved_core_file = saved_snapshot
      .files
      .get("calcit.core")
      .expect("saved calcit.core file should exist");

    for def_name in ["&+", "%{}", "not", "not=", "noted", "nth", "number?", "option:map", "optionally"] {
      let source_entry = source_core_file
        .defs
        .get(def_name)
        .unwrap_or_else(|| panic!("missing source def: {def_name}"));
      let saved_entry = saved_core_file
        .defs
        .get(def_name)
        .unwrap_or_else(|| panic!("missing saved def: {def_name}"));
      // Parallel tests may populate the core registry between the two loads,
      // causing the latter parser to qualify `Option` as `calcit.core/Option`.
      // Those references are nominally equivalent; the round-trip contract is
      // semantic type equality, while the assertions below separately protect
      // the serialized Fn/Macro markers.
      assert!(
        saved_entry.schema.matches_annotation(source_entry.schema.as_ref())
          && source_entry.schema.matches_annotation(saved_entry.schema.as_ref()),
        "schema should round-trip for {def_name}: source={:?}, saved={:?}",
        source_entry.schema,
        saved_entry.schema
      );
    }

    let _ = fs::remove_file(&temp_path);

    assert!(
      saved.contains("|&+ $ %{} 'CodeEntry") && saved.contains(":schema $ :: 'Fn"),
      "saved snapshot should retain wrapped fn schemas"
    );
    assert!(
      saved.contains("|%{} $ %{} 'CodeEntry") && saved.contains(":schema $ :: 'Macro"),
      "saved snapshot should retain wrapped macro schemas"
    );
  }

  #[test]
  fn test_custom_kind_schema_tags_round_trip_instead_of_degrading_to_dynamic() {
    // Regression test: `:struct`/`:enum`/`:trait`/`:impl`/`:record` shorthand tags load
    // into `CalcitTypeAnnotation::Custom(Arc<Calcit>)` (see `from_tag_name`). Any file
    // save previously coerced these back through `builtin_tag_name`, which doesn't know
    // about `Custom` and silently fell back to `:dynamic`, destroying the original kind
    // on every unrelated `cr edit`/`cr tree` write to the containing file.
    for kind in ["struct", "enum", "trait", "impl", "record"] {
      let schema = CalcitTypeAnnotation::from_tag_name(kind);
      let edn = schema_annotation_to_edn(&schema);
      assert_eq!(
        edn,
        Edn::enum_value(CalcitTypeAnnotation::canonical_type_symbol_name(kind).expect("known kind"), vec![]),
        "schema kind `:{kind}` must round-trip as a canonical symbol, not degrade to dynamic"
      );
    }
  }

  #[test]
  fn test_validate_serialized_snapshot_content_rejects_double_quoted_generics() {
    let content = r#"{} (:package |mini)
  :version |0.0.0
  :entries $ {}
    :default $ {} (:mode :native) (:init-fn |mini/main!) (:reload-fn |mini/main!)
      :modules $ []
  :files $ {}
    |mini $ %{} :FileEntry
      :ns $ %{} :CodeEntry (:doc |) (:code $ quote (ns mini)) (:examples $ []) (:schema nil)
      :defs $ {}
        |main! $ %{} :CodeEntry (:doc |)
          :code $ quote (defn main! (x) x)
          :examples $ []
          :schema $ :: :fn
            {} (:args $ [] :dynamic) (:generics $ [] ''T) (:return :dynamic)
"#;

    let err = validate_serialized_snapshot_content(content).expect_err("serialized snapshot should reject double-quoted generics");
    assert!(
      err.contains("serialized snapshot has invalid `:schema`") && err.contains("excess leading quotes"),
      "unexpected error: {err}"
    );
  }

  #[test]
  fn test_load_snapshot_reports_empty_top_level_version_with_field_context() {
    let content = r#"{} (:package |mini)
  :version ||
  :entries $ {}
    :default $ {} (:mode :native) (:init-fn |mini/main!) (:reload-fn |mini/main!)
      :modules $ []
  :files $ {}
    |mini $ %{} :FileEntry
      :ns $ %{} :CodeEntry (:doc |) (:code $ quote (ns mini)) (:examples $ []) (:schema nil)
      :defs $ {}
        |main! $ %{} :CodeEntry (:doc |)
          :code $ quote (defn main! () nil)
          :examples $ []
          :schema nil
"#;

    let edn_data = cirru_edn::parse(content).expect("snapshot text should parse as EDN");
    let err = load_snapshot_data(&edn_data, "mini.cirru").expect_err("empty top-level version should fail on load");

    assert!(err.contains("snapshot.version cannot be empty"), "unexpected error: {err}");
    assert!(err.contains("||"), "unexpected error: {err}");
  }

  #[test]
  fn test_entry_type_slots_and_feature_policy_round_trip_for_default_and_named_entries() {
    let content = r#"{} (:package |mini)
  :version |0.0.0
  :entries $ {}
    :default $ {} (:mode :js) (:init-fn |mini/main!) (:reload-fn 'mini/reload!)
      :description "|Browser client entry"
      :target :browser
      :modules $ []
      :type-slots $ {} (:dispatch-op |mini.schema/ClientOp)
      :feature-policy $ {} (:js-ffi :error)
    :server $ {} (:mode :native) (:init-fn 'mini/server-main!) (:reload-fn 'mini/reload!)
      :description "|HTTP server entry"
      :target :node
      :modules $ []
      :type-slots $ {} (:dispatch-op |mini.schema/ServerOp) (:optional-op :dynamic)
      :feature-policy $ {} (:js-ffi :warn)
  :files $ {}
    |mini $ %{} :FileEntry
      :ns $ %{} :CodeEntry (:doc |) (:code $ quote (ns mini)) (:examples $ []) (:schema nil)
      :defs $ {}
        |main! $ %{} :CodeEntry (:doc |) (:code $ quote (defn main! () nil)) (:examples $ []) (:schema nil)
        |reload! $ %{} :CodeEntry (:doc |) (:code $ quote (defn reload! () nil)) (:examples $ []) (:schema nil)
"#;

    let edn_data = cirru_edn::parse(content).expect("snapshot text should parse as EDN");
    let snapshot = load_snapshot_data(&edn_data, "mini.cirru").expect("snapshot should load");
    assert_eq!(
      snapshot.entries[DEFAULT_ENTRY_NAME]
        .type_slots
        .get("dispatch-op")
        .map(String::as_str),
      Some("mini.schema/ClientOp")
    );
    assert_eq!(snapshot.entries[DEFAULT_ENTRY_NAME].mode, SnapshotRunMode::Js);
    assert_eq!(snapshot.entries[DEFAULT_ENTRY_NAME].description, "Browser client entry");
    assert_eq!(snapshot.entries[DEFAULT_ENTRY_NAME].target, Some(SnapshotTarget::Browser));
    assert_eq!(
      snapshot.entries[DEFAULT_ENTRY_NAME].feature_policy.get("js-ffi"),
      Some(&FeaturePolicy::Error)
    );
    let server = snapshot.entries.get("server").expect("server entry");
    assert_eq!(server.description, "HTTP server entry");
    assert_eq!(server.target, Some(SnapshotTarget::Node));
    assert_eq!(
      server.type_slots.get("dispatch-op").map(String::as_str),
      Some("mini.schema/ServerOp")
    );
    assert_eq!(server.type_slots.get("optional-op").map(String::as_str), Some(":dynamic"));
    assert_eq!(server.feature_policy.get("js-ffi"), Some(&FeaturePolicy::Warn));

    let rendered = render_snapshot_content(&snapshot).expect("snapshot should render");
    assert!(
      !rendered.contains(":version"),
      "snapshot version must stay in deps.cirru, not calcit.cirru: {rendered}"
    );
    assert!(
      rendered.contains(":init-fn 'mini/main!"),
      "entry function should be stored as a symbol: {rendered}"
    );
    assert!(
      rendered.contains(":reload-fn 'mini/reload!"),
      "entry function should be stored as a symbol: {rendered}"
    );
    let rendered_edn = cirru_edn::parse(&rendered).expect("rendered snapshot should parse");
    let restored = load_snapshot_data(&rendered_edn, "mini.cirru").expect("rendered snapshot should load");
    assert_eq!(
      restored.entries[DEFAULT_ENTRY_NAME].type_slots,
      snapshot.entries[DEFAULT_ENTRY_NAME].type_slots
    );
    assert_eq!(restored.entries["server"].type_slots, server.type_slots);
    assert_eq!(
      restored.entries[DEFAULT_ENTRY_NAME].target,
      snapshot.entries[DEFAULT_ENTRY_NAME].target
    );
    assert_eq!(restored.entries["server"].target, server.target);
    assert_eq!(
      restored.entries[DEFAULT_ENTRY_NAME].feature_policy,
      snapshot.entries[DEFAULT_ENTRY_NAME].feature_policy
    );
    assert_eq!(restored.entries["server"].feature_policy, server.feature_policy);
  }

  #[test]
  fn legacy_configs_migrate_to_default_native_entry() {
    let content = r#"{} (:package |mini)
  :configs $ {} (:init-fn |mini/main!) (:reload-fn |mini/reload!) (:version |1.2.3)
    :modules $ [] |legacy/
  :entries $ {}
  :files $ {}
"#;
    let edn_data = cirru_edn::parse(content).expect("legacy snapshot text should parse");
    let snapshot = load_snapshot_data(&edn_data, "mini.cirru").expect("legacy snapshot should load");
    let default_entry = snapshot.entries.get(DEFAULT_ENTRY_NAME).expect("migrated default entry");
    assert_eq!(snapshot.version, "1.2.3");
    assert_eq!(default_entry.mode, SnapshotRunMode::Native);
    assert_eq!(default_entry.modules, vec!["legacy/"]);
    assert!(default_entry.description.is_empty());

    let rendered = render_snapshot_content(&snapshot).expect("legacy snapshot should render canonically");
    assert!(!rendered.contains(":version"));
    assert!(rendered.contains(":default $ {}") && rendered.contains(":mode :native"));
    assert!(!rendered.contains(":configs"));
  }

  #[test]
  fn test_entry_type_slots_reject_duplicate_normalized_names() {
    let slots = Edn::Map(EdnMapView(HashMap::from([
      (Edn::tag("dispatch-op"), Edn::str("mini.schema/ClientOp")),
      (Edn::str(":dispatch-op"), Edn::str("mini.schema/ServerOp")),
    ])));
    let err = parse_snapshot_type_slots(&slots, "configs").expect_err("duplicate normalized slot names should fail");
    assert!(err.contains("duplicate slot name `:dispatch-op`"), "unexpected error: {err}");
  }

  #[test]
  fn test_feature_policy_rejects_empty_feature_name() {
    let policies = Edn::map_from_iter([(Edn::str(""), Edn::tag("error"))]);
    let err = parse_snapshot_feature_policy(&policies, "entry").expect_err("empty feature names should be rejected");
    assert!(err.contains("feature name cannot be empty"), "unexpected error: {err}");
  }

  #[test]
  fn create_file_from_snippet_promotes_top_level_defs() {
    let raw = r#"ns app.demo
  :require
    respo.core :refer $ div

def style-space $ {}
  :width "|1px"

defn compute (w h)
  + w h

defcomp comp-space (w h)
  div $ {}
"#;
    let file = create_file_from_snippet(raw).expect("snippet should parse");
    assert!(file.defs.contains_key("style-space"));
    assert!(file.defs.contains_key("compute"));
    assert!(file.defs.contains_key("comp-space"));
    // main! and reload! are always injected as no-op entry points
    assert!(file.defs.contains_key("main!"));
    assert!(file.defs.contains_key("reload!"));
  }
}