wyrd-client 0.3.0

Shared Wyrd client: transport, authentication, and composed client capabilities.
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
//! Local loading and indexing of complete hydrated Card bundles.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::fs::{self, File};
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, OnceLock};

use crate::WyrdClient;
use crate::bifrost::{Bifrost, BifrostOptions, QueueConfig, TableConfig};
use crate::cards::{CardSelector, Cards};
use crate::observe::Run;
use crate::observe::lifecycle::{BifrostLifecycle, StartedBifrost};
use base64::Engine;
use serde::Deserialize;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use wyrd_cards::data::DataCard;
use wyrd_cards::model::ModelCard;
use wyrd_cards::prompt::PromptCard;
use wyrd_spec::api_version::ApiVersion;
use wyrd_spec::card::agent::AgentCard;
use wyrd_spec::card::verifier::{VerificationBinding, VerifierSpec};
use wyrd_spec::envelope::{Card, CardKind, Relationships, Spec};
use wyrd_spec::error::WyrdError;
use wyrd_spec::ids::CardUid;
use wyrd_spec::reference::{
    CardRef, registration_only_sibling_refs, scope_child_card_refs, unresolved_card_ref_paths,
};
#[cfg(feature = "internal")]
use wyrd_spec::registry::{
    ArtifactManifestEntry, RelativeArtifactPath, canonical_artifact_manifest_hash,
};
use wyrd_spec::registry::{BundleArtifactManifest, BundleCardManifest, BundleManifest, BundleMode};

/// One verified artifact payload in a local `WyrdState` bundle.
///
/// Internal inventory: load-time validation checks each payload against it,
/// and the trusted-manifest hash is rebuilt from it. It is not public API.
#[derive(Debug, Clone)]
struct HydratedArtifact {
    /// Server-declared relative path within the Card artifact directory.
    relative_path: String,
    /// Canonical absolute path to the verified local payload.
    local_path: PathBuf,
    /// Server-declared base64-encoded SHA-256 digest.
    #[cfg(feature = "internal")]
    sha256: String,
    /// Verified payload byte length.
    #[cfg(feature = "internal")]
    size_bytes: u64,
    /// Optional server-declared MIME type.
    #[cfg(feature = "internal")]
    content_type: Option<String>,
}

/// Native typed projections retained for the runtime-relevant Card kinds.
///
/// The maps use the same canonical exact `CardRef` keys as the complete Card
/// graph. They deliberately retain no artifact bytes and no runtime clients;
/// the projections are immutable local views over validated bundle envelopes.
#[derive(Default)]
struct TypedCards {
    /// Agent Card holders keyed by exact `CardRef`.
    agents: BTreeMap<String, AgentCard>,
    /// Prompt Card holders keyed by exact `CardRef`.
    prompts: BTreeMap<String, PromptCard>,
    /// Model Card holders keyed by exact `CardRef`.
    models: BTreeMap<String, ModelCard>,
    /// Data Card holders keyed by exact `CardRef`.
    data: BTreeMap<String, DataCard>,
}

impl fmt::Debug for TypedCards {
    /// Format typed-card indexes without requiring Python-backed holder types
    /// to implement `Debug`.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TypedCards")
            .field("agents", &self.agents.keys().collect::<Vec<_>>())
            .field("prompts", &self.prompts.keys().collect::<Vec<_>>())
            .field("models", &self.models.keys().collect::<Vec<_>>())
            .field("data", &self.data.keys().collect::<Vec<_>>())
            .finish()
    }
}

impl TypedCards {
    /// Pair the Agent at `key` with the exact Prompt Card its spec pins.
    ///
    /// # Errors
    /// Returns `WYRD_SDK_400_INVALID_STATE_BUNDLE` when no Agent is indexed at
    /// `key`, or its Prompt is inline, an unresolved path, or names no Prompt
    /// Card in this graph.
    fn agent(&self, key: &str) -> Result<HydratedAgent<'_>, WyrdError> {
        let card = self.agents.get(key).ok_or_else(|| {
            state_bundle_error(
                "validated typed Card map is missing its exact CardRef entry",
                json!({ "card_ref_key": key, "expected_kind": CardKind::Agent.wire_name() }),
            )
        })?;
        let prompt_ref = card.spec.prompt.as_card_ref().ok_or_else(|| {
            state_bundle_error(
                "Agent Prompt has no registered Prompt Card identity; re-register and rehydrate",
                json!({ "card_ref_key": key }),
            )
        })?;
        let prompt = self.prompts.get(&prompt_ref.to_string()).ok_or_else(|| {
            state_bundle_error(
                "Agent prompt target is missing or is not a Prompt Card",
                json!({ "card_ref_key": key, "card_ref": prompt_ref }),
            )
        })?;
        Ok(HydratedAgent {
            card,
            prompt_ref,
            prompt,
        })
    }
}

/// A hydrated Agent Card paired with the exact Prompt Card it pins.
///
/// Borrowed from the immutable state index: [`HydratedAgent::prompt`] is a
/// local read of the registered Prompt Card the Agent's `prompt` reference
/// names, never a registry call. State construction guarantees every Agent
/// resolves, so a view exists only for a complete relationship.
#[derive(Clone, Copy)]
pub struct HydratedAgent<'a> {
    /// The declarative Agent Card holder.
    card: &'a AgentCard,
    /// The exact UID-bearing reference the Agent pins as its Prompt.
    prompt_ref: &'a CardRef,
    /// The registered Prompt Card `prompt_ref` names in this graph.
    prompt: &'a PromptCard,
}

impl<'a> HydratedAgent<'a> {
    /// Return the declarative Agent Card holder.
    #[must_use]
    pub fn card(&self) -> &'a AgentCard {
        self.card
    }

    /// Return the hydrated Prompt Card this Agent pins.
    #[must_use]
    pub fn prompt(&self) -> &'a PromptCard {
        self.prompt
    }

    /// Return the exact Prompt reference stored in the Agent's spec.
    #[must_use]
    pub fn prompt_ref(&self) -> &'a CardRef {
        self.prompt_ref
    }
}

/// A Card resolved by alias, in the holder its kind's typed accessor returns.
///
/// Kinds without a dedicated holder are served as their stored envelope.
#[derive(Clone, Copy)]
pub enum HydratedCard<'a> {
    /// An Agent paired with its Prompt Card.
    Agent(HydratedAgent<'a>),
    /// A Prompt Card holder.
    Prompt(&'a PromptCard),
    /// A Model Card holder.
    Model(&'a ModelCard),
    /// A Data Card holder.
    Data(&'a DataCard),
    /// Any other kind's stored envelope.
    Envelope(&'a Card),
}

/// Immutable indexes for a validated hydrated Card bundle.
///
/// `HydratedStateIndex` owns the exact-reference, alias, and artifact maps
/// after `WyrdState` has completed filesystem loading and cross-card
/// validation. It indexes the Card relationships loaded from disk; it does
/// not perform the remote graph traversal owned by `wyrd_client::cards`.
#[derive(Debug)]
struct HydratedStateIndex {
    /// Canonical exact-reference key for the Service root.
    root_key: String,
    /// Exact root reference emitted by the hydration producer.
    root_ref: CardRef,
    /// Complete Card envelopes indexed by canonical exact-reference key.
    cards_by_ref: BTreeMap<String, Card>,
    /// Exact Card references indexed by their canonical key.
    refs_by_key: BTreeMap<String, CardRef>,
    /// Persisted aliases mapped to canonical exact-reference keys.
    aliases: BTreeMap<String, String>,
    /// Sorted aliases grouped by canonical exact-reference key.
    #[cfg(feature = "internal")]
    aliases_by_ref: BTreeMap<String, Vec<String>>,
    /// Verified artifact metadata grouped by canonical exact-reference key.
    #[cfg(feature = "internal")]
    artifacts_by_ref: BTreeMap<String, Vec<HydratedArtifact>>,
    /// Confined artifact directories grouped by canonical exact-reference key.
    #[cfg(feature = "internal")]
    artifact_dirs_by_ref: BTreeMap<String, PathBuf>,
    /// Native typed Card holders grouped by canonical exact-reference key.
    typed: TypedCards,
}

impl HydratedStateIndex {
    /// Assemble validated Cards, references, aliases, and artifacts into one graph.
    ///
    /// The caller has already loaded every manifest entry and validated the
    /// graph closure. This method performs only deterministic map assembly and
    /// retains a final root-membership check before publishing the graph.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle error when the validated root key is not
    /// present in the assembled Card map.
    fn assemble(
        root_ref: CardRef,
        loaded: Vec<LoadedManifestCard>,
        aliases: BTreeMap<String, String>,
    ) -> Result<Self, WyrdError> {
        let root_key = root_ref.to_string();
        let mut cards_by_ref = BTreeMap::new();
        let mut refs_by_key = BTreeMap::new();
        #[cfg(feature = "internal")]
        let mut aliases_by_ref = BTreeMap::<String, Vec<String>>::new();
        #[cfg(feature = "internal")]
        let mut artifacts_by_ref = BTreeMap::new();
        #[cfg(feature = "internal")]
        let mut artifact_dirs_by_ref = BTreeMap::new();

        for item in loaded {
            let key = item.key;
            refs_by_key.insert(key.clone(), item.card_ref);
            cards_by_ref.insert(key.clone(), item.card);
            #[cfg(feature = "internal")]
            {
                let mut item_aliases = item.aliases;
                item_aliases.sort();
                aliases_by_ref.insert(key.clone(), item_aliases);
                if let Some(artifact_dir) = item.artifact_dir {
                    artifact_dirs_by_ref.insert(key.clone(), artifact_dir);
                }
                artifacts_by_ref.insert(key, item.artifacts);
            }
        }
        if !cards_by_ref.contains_key(&root_key) {
            return Err(state_bundle_error(
                "validated root key points to a missing Card",
                json!({ "root": root_ref }),
            ));
        }
        let typed = hydrate_typed_cards(&cards_by_ref)?;
        Ok(Self {
            root_key,
            root_ref,
            cards_by_ref,
            refs_by_key,
            aliases,
            #[cfg(feature = "internal")]
            aliases_by_ref,
            #[cfg(feature = "internal")]
            artifacts_by_ref,
            #[cfg(feature = "internal")]
            artifact_dirs_by_ref,
            typed,
        })
    }

    /// Resolve one persisted alias to its canonical exact-reference key.
    ///
    /// # Errors
    ///
    /// Returns `WYRD_SDK_404_UNKNOWN_ALIAS` when the alias is absent.
    fn resolve_key(&self, alias: &str) -> Result<&str, WyrdError> {
        self.aliases
            .get(alias)
            .map(String::as_str)
            .ok_or_else(|| WyrdError::SdkUnknownAlias {
                message: format!("WyrdState alias {alias:?} is not known"),
                details: json!({
                    "alias": alias,
                    "available_aliases": self.aliases.keys().cloned().collect::<Vec<_>>(),
                }),
            })
    }

    /// Resolve a canonical exact-reference key to its complete Card envelope.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle error when the key is absent from the
    /// validated Card map.
    fn card_by_key(&self, key: &str) -> Result<&Card, WyrdError> {
        self.cards_by_ref.get(key).ok_or_else(|| {
            state_bundle_error(
                "validated CardRef key points to a missing Card",
                json!({ "card_ref_key": key }),
            )
        })
    }

    /// Resolve a canonical exact-reference key to its stored Card reference.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle error when the key is absent from the
    /// validated reference map.
    fn card_ref_by_key(&self, key: &str) -> Result<&CardRef, WyrdError> {
        self.refs_by_key.get(key).ok_or_else(|| {
            state_bundle_error(
                "validated CardRef key points to a missing reference",
                json!({ "card_ref_key": key }),
            )
        })
    }

    /// Resolve a canonical exact-reference key to its sorted aliases.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle error when the key is absent from the
    /// validated alias map.
    #[cfg(feature = "internal")]
    fn aliases_by_key(&self, key: &str) -> Result<&[String], WyrdError> {
        self.aliases_by_ref
            .get(key)
            .map(Vec::as_slice)
            .ok_or_else(|| {
                state_bundle_error(
                    "validated CardRef key points to missing aliases",
                    json!({ "card_ref_key": key }),
                )
            })
    }

    /// Resolve a canonical exact-reference key to its verified artifacts.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle error when the key is absent from the
    /// validated artifact map.
    #[cfg(feature = "internal")]
    fn artifacts_by_key(&self, key: &str) -> Result<&[HydratedArtifact], WyrdError> {
        self.artifacts_by_ref
            .get(key)
            .map(Vec::as_slice)
            .ok_or_else(|| {
                state_bundle_error(
                    "validated CardRef key points to missing artifacts",
                    json!({ "card_ref_key": key }),
                )
            })
    }

    /// Resolve a canonical exact-reference key to its confined artifact directory.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle error when the key is absent from the
    /// validated reference map.
    #[cfg(feature = "internal")]
    fn artifact_dir_by_key(&self, key: &str) -> Result<Option<&Path>, WyrdError> {
        if !self.refs_by_key.contains_key(key) {
            return Err(state_bundle_error(
                "validated CardRef key points to a missing reference",
                json!({ "card_ref_key": key }),
            ));
        }
        Ok(self.artifact_dirs_by_ref.get(key).map(PathBuf::as_path))
    }

    /// Compute the canonical artifact-manifest hash for one validated Card.
    ///
    /// The hydrated inventory was verified before this method becomes
    /// reachable. Rebuilding the wire manifest here binds executable-loader
    /// trust to the exact publication rather than to an alias or local bytes.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle error when the exact Card key is absent
    /// or an artifact path is not a valid wire path, and propagates
    /// canonicalization failures from `wyrd-spec`.
    #[cfg(feature = "internal")]
    fn artifact_manifest_hash_by_key(&self, key: &str) -> Result<Option<String>, WyrdError> {
        let manifest = self
            .artifacts_by_key(key)?
            .iter()
            .map(|artifact| {
                Ok(ArtifactManifestEntry {
                    relative_path: RelativeArtifactPath::new(&artifact.relative_path)?,
                    sha256: Some(artifact.sha256.clone()),
                    size_bytes: Some(artifact.size_bytes),
                    content_type: artifact.content_type.clone(),
                })
            })
            .collect::<Result<Vec<_>, WyrdError>>()?;
        canonical_artifact_manifest_hash(&manifest)
    }
}

/// The alias of the root Service view `WyrdState::run` opens.
const ROOT_ALIAS: &str = "root";

/// A Verifier bound to a subject, resolved for one execution.
#[derive(Debug)]
pub(crate) struct BoundVerifier {
    /// The exact Verifier Card version.
    pub(crate) verifier_card_uid: CardUid,
    /// The exact subject Card version it judges.
    pub(crate) card_uid: CardUid,
    /// The building-block Verifier, whose slots fix each input's projection.
    pub(crate) spec: VerifierSpec,
}

/// The server-resolved UID a hydrated reference carries.
///
/// # Errors
/// Returns `WYRD_SDK_400_INVALID_STATE_BUNDLE` when the reference has none,
/// which a server-produced bundle always supplies.
fn required_uid(card_ref: &CardRef) -> Result<CardUid, WyrdError> {
    card_ref.uid.clone().ok_or_else(|| {
        state_bundle_error(
            "a hydrated Card reference carries no UID",
            json!({ "card_ref": card_ref }),
        )
    })
}

/// A complete, local, non-executing Card graph, and its one Bifrost lifetime.
///
/// Cloning a state shares both the hydrated graph and the Bifrost writer: one
/// runtime-owned writer survives every clone, so a clone handed to a task
/// cannot start a second transport or strand the first one's pending batches.
#[derive(Debug, Clone)]
pub struct WyrdState {
    /// Shared immutable hydrated-state index safe to read across state clones.
    index: Arc<HydratedStateIndex>,
    /// The one Bifrost lifetime every observation of every run emits through.
    bifrost: Arc<BifrostLifecycle>,
    /// The client every server call of this state goes through — Bifrost
    /// startup and `observe.verify` — shared by every clone: the client the
    /// state was created with, else one resolved from the ambient
    /// configuration on first use and kept.
    client: Arc<OnceLock<WyrdClient>>,
}

/// How [`WyrdState::declare_with`] declares a Card file and prepares its state.
#[derive(Debug, Clone, Default)]
pub struct DeclareOptions {
    /// The client the declaration, the pull, and every later server call of
    /// the state run as; `None` resolves the ambient client once.
    pub client: Option<WyrdClient>,
    /// A caller-owned directory to publish the complete bundle to, which
    /// persists after the state drops and loads offline with
    /// [`WyrdState::from_path`]; an existing bundle there is replaced only
    /// after the new one is complete. `None` loads the graph into memory and
    /// keeps no files, so artifact payloads are not available locally.
    pub bundle_dir: Option<PathBuf>,
}

/// Private filesystem reader for one confined Card bundle root.
///
/// `WyrdState` owns the published immutable graph. This reader owns only the
/// synchronous filesystem assembly context so no bundle path leaks into the
/// public state API or into declarative Card values.
#[derive(Debug)]
struct BundleReader<'a> {
    /// Original root supplied by the caller for structured hydration failures.
    requested_root: &'a Path,
    /// Canonical directory that confines every bundle projection and payload.
    root: PathBuf,
}

/// Establishes the canonical filesystem confinement boundary.
impl<'a> BundleReader<'a> {
    /// Construct a reader for one canonical Card bundle root.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle error when the supplied root cannot be
    /// inspected, is not a directory, or cannot be canonicalized before any
    /// manifest-controlled path is read.
    fn new(bundle: &'a Path) -> Result<Self, WyrdError> {
        Ok(Self {
            requested_root: bundle,
            root: absolute_bundle(bundle)?,
        })
    }

    /// Read the bundle manifest through the fixed confined metadata projection.
    ///
    /// # Errors
    ///
    /// Returns the same stable hydration errors as `WyrdState::from_path` when
    /// metadata is absent, escapes the root, or cannot be decoded.
    fn read_manifest(&self) -> Result<BundleManifest, WyrdError> {
        let metadata_path = self.root.join("metadata.yaml");
        let metadata = fs::symlink_metadata(&metadata_path).map_err(|error| {
            if error.kind() == std::io::ErrorKind::NotFound {
                unhydrated_error(&metadata_path, "Card bundle metadata.yaml is absent")
            } else {
                state_bundle_error(
                    "Card bundle metadata.yaml cannot be read",
                    json!({ "path": metadata_path, "source": error.to_string() }),
                )
            }
        })?;
        if !metadata.file_type().is_symlink() && !metadata.is_file() {
            return Err(unhydrated_error(
                &metadata_path,
                "Card bundle metadata.yaml is not a regular file",
            ));
        }
        let metadata_path = confined_existing_file(&self.root, "metadata.yaml")?;
        read_yaml(&metadata_path)
    }
}

impl WyrdState {
    /// Load and validate a complete Card bundle without contacting Wyrd.
    ///
    /// The state has no client yet: its first server call resolves one from
    /// the ambient configuration, as [`WyrdClient::from_global`] does, and keeps
    /// it, so later environment changes do not change its principal.
    ///
    /// # Arguments
    /// * `path` - The Card bundle directory, as [`crate::cards::Cards::pull`]
    ///   publishes it.
    ///
    /// # Errors
    ///
    /// Returns a stable SDK error when the bundle is incomplete, malformed,
    /// internally inconsistent, contains an unconfined path, or preserves a
    /// registration-only sibling reference.
    pub fn from_path(path: impl AsRef<Path>) -> Result<Self, WyrdError> {
        let reader = BundleReader::new(path.as_ref())?;
        let manifest = reader.read_manifest()?;
        reader.validate_manifest_header(&manifest)?;
        let index = reader.load_index(manifest)?;
        Ok(Self {
            index: Arc::new(index),
            bifrost: Arc::new(BifrostLifecycle::default()),
            client: Arc::new(OnceLock::new()),
        })
    }

    /// Load and validate a complete Card bundle whose server calls run as
    /// `client`.
    ///
    /// Identical to [`Self::from_path`], except that the state's identity is
    /// fixed now: Bifrost startup and every `observe.verify` call go through
    /// `client`, and the ambient configuration is never read.
    ///
    /// # Arguments
    /// * `path` - The Card bundle directory.
    /// * `client` - The client every server call of this state and its clones
    ///   is sent through, as its principal.
    ///
    /// # Errors
    /// As [`Self::from_path`].
    pub fn from_path_with(path: impl AsRef<Path>, client: WyrdClient) -> Result<Self, WyrdError> {
        let state = Self::from_path(path)?;
        let _ = state.client.set(client);
        Ok(state)
    }

    /// Declare the Card file at `path` and return the state of its graph,
    /// ready to run, as the ambient client.
    ///
    /// The online counterpart of [`Self::from_path`]: one call replaces
    /// `Cards::declare_from_path`, `Cards::pull`, and `from_path`.
    ///
    /// # Arguments
    /// * `path` - The root Service Card file; its `./path` references are
    ///   resolved relative to it and declared with it.
    ///
    /// # Errors
    /// As [`Self::declare_with`].
    pub async fn declare(path: impl AsRef<Path>) -> Result<Self, WyrdError> {
        Self::declare_with(path, DeclareOptions::default()).await
    }

    /// Declare the Card file at `path` and return the state of its graph,
    /// ready to run, with `options`.
    ///
    /// The file and the files it references are declared under the
    /// registry's usual version rules, so an unchanged rerun declares
    /// nothing new. The declared root's complete graph is then pulled and
    /// loaded with the same validation as [`Self::from_path`]. The declaration,
    /// the pull, and every later server call of the state use one client.
    ///
    /// Without `bundle_dir`, the bundle is pulled into a temporary directory,
    /// loaded into memory, and deleted before this returns; artifact payloads
    /// are not kept, so a graph whose Model or Data payloads must load needs
    /// `bundle_dir`.
    ///
    /// # Arguments
    /// * `path` - The root Service Card file.
    /// * `options` - The client and the optional caller-owned bundle directory.
    ///
    /// # Errors
    /// Returns the client's configuration or credential error, the loader's
    /// `WYRD_LOADER_400_INVALID_ENVELOPE` for an unreadable or invalid Card
    /// file, the registry's error when it refuses the declaration (for
    /// example `WYRD_REGISTRY_409_SPEC_DRIFT` or an authorization refusal),
    /// the pull's error, and [`Self::from_path`]'s errors for the bundle.
    ///
    /// # Cancellation
    /// A failure or a dropped future after the registry accepted the
    /// declaration leaves the declaration committed, but returns no state
    /// and removes the temporary directory; a `bundle_dir` keeps its prior
    /// bundle, as [`crate::cards::Cards::pull`] describes.
    pub async fn declare_with(
        path: impl AsRef<Path>,
        options: DeclareOptions,
    ) -> Result<Self, WyrdError> {
        let client = match options.client {
            Some(client) => client,
            None => WyrdClient::from_global().map_err(WyrdError::from)?,
        };
        let cards = Cards::connect_with(&client).await?;
        let receipt = cards.declare_from_path(path).await?;
        let root = CardSelector::exact(receipt.root);
        if let Some(bundle_dir) = options.bundle_dir {
            cards.pull(root, &bundle_dir, BundleMode::Complete).await?;
            return Self::from_path_with(&bundle_dir, client);
        }
        let staging = tempfile::Builder::new()
            .prefix("wyrd-state-")
            .tempdir()
            .map_err(|error| {
                state_bundle_error(
                    "the temporary state directory cannot be created",
                    json!({ "source": error.to_string() }),
                )
            })?;
        let bundle = staging.path().join("bundle");
        cards.pull(root, &bundle, BundleMode::Complete).await?;
        Self::from_path_with(&bundle, client)
    }

    /// Connect this state's one Bifrost writer as the state's client.
    ///
    /// The client is the one the state was created with, else the ambient
    /// one [`WyrdState::from_path`] describes. Startup describes the fixed Drift
    /// observation table before reporting success, so a run can never
    /// enqueue against a missing, unauthorized, or incompatible system table.
    ///
    /// # Errors
    /// Returns `WYRD_SDK_409_BIFROST_ALREADY_STARTED` when this state (or any
    /// clone of it) already started Bifrost, `WYRD_SDK_409_BIFROST_CLOSED`
    /// after a successful shutdown, the client configuration or credential
    /// error, the transport error from the connect, and the server's error for
    /// either fixed table.
    ///
    /// # Cancellation
    /// Abandoning the future releases the start claim, so a later
    /// `start_bifrost` on the same state is accepted rather than refused.
    pub async fn start_bifrost(&self) -> Result<(), WyrdError> {
        self.start_bifrost_with_config(None, QueueConfig::default())
            .await
    }

    /// Connect this state's one Bifrost writer with an active write table.
    ///
    /// `table` retains its existing Bifrost meaning as the handle's active
    /// write binding; it does not choose a run's destination and does not
    /// replace a fixed system table. The queue keeps its default configuration;
    /// [`WyrdState::start_bifrost_with_config`] is the configured form.
    ///
    /// # Arguments
    /// * `table` - The handle's active write table, or `None` for none.
    ///
    /// # Errors
    /// As [`WyrdState::start_bifrost`].
    ///
    /// # Cancellation
    /// As [`WyrdState::start_bifrost`].
    pub async fn start_bifrost_with(&self, table: Option<TableConfig>) -> Result<(), WyrdError> {
        self.start_bifrost_with_config(table, QueueConfig::default())
            .await
    }

    /// Connect this state's one Bifrost writer with an active write table and
    /// queue configuration.
    ///
    /// Calls [`Bifrost::connect_with`] over the state's client with `table`
    /// and `queue` as its [`BifrostOptions`], under the same start claim.
    ///
    /// # Arguments
    /// * `table` - The handle's active write table, or `None`, with the
    ///   meaning described on [`WyrdState::start_bifrost_with`].
    /// * `queue` - Bounds the one producer queue every run of this state
    ///   shares.
    ///
    /// # Errors
    /// As [`WyrdState::start_bifrost`], plus the queue-configuration refusal of
    /// [`Bifrost::connect_with`].
    ///
    /// # Cancellation
    /// As [`WyrdState::start_bifrost`].
    pub async fn start_bifrost_with_config(
        &self,
        table: Option<TableConfig>,
        queue: QueueConfig,
    ) -> Result<(), WyrdError> {
        let claim = self.bifrost.claim()?;
        let client = self.client()?;
        claim
            .complete(Bifrost::connect_with(client, BifrostOptions { table, queue }).await?)
            .await
    }

    /// The client this state's server calls go through.
    ///
    /// The client the state was created with when there is one; otherwise one
    /// is resolved from the ambient configuration on first use and kept for
    /// every clone, as [`WyrdClient::from_global`] resolves it. Resolution
    /// performs no network IO.
    ///
    /// # Errors
    /// Returns the client configuration error when the global config file
    /// cannot be read or parsed, or the credential resolution error.
    pub fn client(&self) -> Result<&WyrdClient, WyrdError> {
        if let Some(client) = self.client.get() {
            return Ok(client);
        }
        let client = WyrdClient::from_global().map_err(WyrdError::from)?;
        Ok(self.client.get_or_init(|| client))
    }

    /// Resolve the Verifier named `name` bound in `verified_by` to `subject`.
    ///
    /// A subject's bindings are the root Service's own when it is the root,
    /// those of every Service component occurrence that references it, and a
    /// standalone Agent's own. Each bound Verifier is in the hydrated graph,
    /// so resolution is a local lookup with no network IO.
    ///
    /// # Errors
    /// Returns `WYRD_SDK_404_UNKNOWN_VERIFIER` when no bound Verifier has that
    /// name, and `WYRD_SDK_400_INVALID_STATE_BUNDLE` when a bound Verifier or
    /// the subject is absent from the graph or carries no UID.
    pub(crate) fn bound_verifier(
        &self,
        subject: &CardRef,
        name: &str,
    ) -> Result<BoundVerifier, WyrdError> {
        let subject_key = subject.to_string();
        let mut bindings: Vec<&VerificationBinding> = Vec::new();
        if let Spec::Service(service) = &self.service().spec {
            if subject_key == self.index.root_key {
                bindings.extend(&service.verified_by);
            }
            for component in &service.components {
                if component.card_ref.as_card_ref() == Some(subject) {
                    bindings.extend(&component.verified_by);
                }
            }
        }
        if let Spec::Agent(agent) = &self.index.card_by_key(&subject_key)?.spec {
            bindings.extend(&agent.verified_by);
        }
        for binding in bindings {
            let Some(verifier_ref) = binding.verifier.as_card_ref() else {
                continue;
            };
            let card = self.index.card_by_key(&verifier_ref.to_string())?;
            if card.metadata.name.as_str() != name {
                continue;
            }
            let Spec::Verifier(spec) = &card.spec else {
                return Err(state_bundle_error(
                    "a verified_by binding names a Card that is not a Verifier",
                    json!({ "verifier": verifier_ref }),
                ));
            };
            // Staged switch point: until the hydrated `Spec::Verifier`
            // carries building blocks, an implementation-kind Verifier has
            // no slots to project onto and is refused here. The cutover
            // replaces this conversion with a borrow.
            let spec = serde_json::to_value(spec)
                .ok()
                .and_then(|value| serde_json::from_value(value).ok())
                .ok_or_else(|| {
                    state_bundle_error(
                        "a bound Verifier does not declare building-block inputs and requirements",
                        json!({ "verifier": verifier_ref }),
                    )
                })?;
            return Ok(BoundVerifier {
                verifier_card_uid: required_uid(verifier_ref)?,
                card_uid: required_uid(subject)?,
                spec,
            });
        }
        Err(WyrdError::SdkUnknownVerifier {
            message: format!("no Verifier named {name:?} is bound to {subject}"),
            details: json!({ "verifier": name, "subject": subject }),
        })
    }

    /// Open one invocation over this state, targeting the root Service Card.
    ///
    /// Local only: no network IO, no server-side Run resource, and no Verifier
    /// execution. The run mints a UUIDv7 `run_id` that every view of it shares.
    #[must_use]
    pub fn run(&self) -> Run {
        Run::new(self.clone(), ROOT_ALIAS.to_owned(), self.root_ref().clone())
    }

    /// Open one invocation over this state whose first view observes `alias`.
    ///
    /// The concise single-Card form of `run().for_card(alias)`: the alias is
    /// resolved locally in the hydrated graph before the run mints its UUIDv7
    /// `run_id`, so no root view is constructed. Later [`Run::for_card`] views
    /// share that `run_id`. No network IO and no server-side Run resource.
    ///
    /// # Arguments
    /// * `alias` - The bundle alias of the Card the run's first view observes.
    ///
    /// # Errors
    /// Returns `WYRD_SDK_404_UNKNOWN_ALIAS` when the alias is not registered in
    /// this bundle; nothing is opened.
    pub fn run_for_card(&self, alias: &str) -> Result<Run, WyrdError> {
        let subject = self.card_ref(alias)?.clone();
        Ok(Run::new(self.clone(), alias.to_owned(), subject))
    }

    /// Drain every producer of this state's writer without closing it.
    ///
    /// The explicit durability barrier a test or a finite job uses; ordinary
    /// callers drain once at [`WyrdState::shutdown`].
    ///
    /// # Errors
    /// Returns `WYRD_SDK_400_BIFROST_NOT_STARTED` before startup,
    /// `WYRD_SDK_409_BIFROST_CLOSED` after shutdown, and the first producer or
    /// sink failure from the drain.
    pub async fn flush(&self) -> Result<(), WyrdError> {
        Ok(self.bifrost.started()?.bifrost.flush().await?)
    }

    /// Drain every producer of this state's writer and close it to writes.
    ///
    /// Graceful shutdown is the durability barrier: queue admission is not a
    /// Scribe acknowledgement, so an abrupt exit before this resolves can lose
    /// pending rows. A drain failure is ambiguous, so the writer is kept and
    /// the caller retries `shutdown` on the same state rather than replacing a
    /// writer that may still hold batches. A never-started state has nothing to
    /// drain; it succeeds and closes, so every successful shutdown is terminal.
    ///
    /// # Errors
    /// Returns the first producer or sink failure from the drain.
    pub async fn shutdown(&self) -> Result<(), WyrdError> {
        self.bifrost.shutdown().await
    }

    /// Start Bifrost over an already-assembled writer, for server-free tests.
    ///
    /// Takes the same `StartClaim` and runs the same fixed-table describes as
    /// the public doors, so the lifecycle under test is the production one; only
    /// the ingest sink is a mock, which is what lets a unit lane prove startup
    /// without dialling a gRPC channel.
    ///
    /// # Errors
    /// As [`WyrdState::start_bifrost`].
    #[cfg(test)]
    pub(crate) async fn adopt_started_bifrost_for_test(
        &self,
        bifrost: Bifrost,
    ) -> Result<(), WyrdError> {
        self.bifrost.claim()?.complete(bifrost).await
    }

    /// The started writer and its described fixed Drift table.
    ///
    /// # Errors
    /// Returns `WYRD_SDK_400_BIFROST_NOT_STARTED` before startup and
    /// `WYRD_SDK_409_BIFROST_CLOSED` after shutdown.
    pub(crate) fn started_bifrost(&self) -> Result<Arc<StartedBifrost>, WyrdError> {
        self.bifrost.started()
    }

    /// Point-in-time bounded-ownership accounting for this state's one writer.
    ///
    /// Test-harness only: a capacity benchmark samples `owned_bytes` while
    /// runs emit through the state, which a separately connected `Bifrost`
    /// cannot see because it owns a different writer. Reads atomics; no IO.
    ///
    /// # Errors
    /// Returns `WYRD_SDK_400_BIFROST_NOT_STARTED` before startup and
    /// `WYRD_SDK_409_BIFROST_CLOSED` after shutdown.
    #[cfg(feature = "test-support")]
    #[cfg(feature = "internal")]
    pub fn bifrost_metrics(&self) -> Result<crate::bifrost::BifrostMetrics, WyrdError> {
        Ok(self.started_bifrost()?.bifrost.metrics())
    }

    /// Return the exact root Card reference.
    #[must_use]
    pub fn root_ref(&self) -> &CardRef {
        &self.index.root_ref
    }

    /// Return the stored root Service Card envelope.
    ///
    /// # Panics
    /// Panics only if the private graph invariant established by `from_path`
    /// is violated after construction.
    #[must_use]
    pub fn service(&self) -> &Card {
        self.index
            .card_by_key(&self.index.root_key)
            .expect("validated hydrated state index root key must identify a Card")
    }

    /// Return all persisted aliases in stable sorted order.
    pub fn aliases(&self) -> impl Iterator<Item = &str> {
        self.index.aliases.keys().map(String::as_str)
    }

    /// Resolve an alias to its stored complete Card envelope.
    ///
    /// # Arguments
    /// * `alias` - The bundle alias to resolve.
    ///
    /// # Errors
    ///
    /// Returns `WYRD_SDK_404_UNKNOWN_ALIAS` for an unknown alias or an
    /// invalid-state-bundle error if a validated alias index is inconsistent.
    pub fn card(&self, alias: &str) -> Result<&Card, WyrdError> {
        let key = self.index.resolve_key(alias)?;
        self.index.card_by_key(key).map_err(|_| {
            state_bundle_error(
                "validated alias points to a missing Card",
                json!({ "alias": alias, "card_ref_key": key }),
            )
        })
    }

    /// Resolve an alias to its exact Card reference.
    ///
    /// # Arguments
    /// * `alias` - The bundle alias to resolve.
    ///
    /// # Errors
    ///
    /// Returns `WYRD_SDK_404_UNKNOWN_ALIAS` for an unknown alias or an
    /// invalid-state-bundle error if a validated reference index is inconsistent.
    pub fn card_ref(&self, alias: &str) -> Result<&CardRef, WyrdError> {
        let key = self.index.resolve_key(alias)?;
        self.index.card_ref_by_key(key).map_err(|_| {
            state_bundle_error(
                "validated alias points to a missing Card reference",
                json!({ "alias": alias, "card_ref_key": key }),
            )
        })
    }

    /// Return all aliases registered for an exact Card reference.
    ///
    /// # Arguments
    /// * `card_ref` - The exact Card reference whose aliases are listed.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle error when the reference is not present
    /// in the validated graph indexes.
    #[cfg(feature = "internal")]
    pub fn aliases_for(&self, card_ref: &CardRef) -> Result<&[String], WyrdError> {
        let key = card_ref.to_string();
        self.index.aliases_by_key(&key).map_err(|_| {
            state_bundle_error(
                "requested CardRef is not a member of this WyrdState graph",
                json!({ "card_ref": card_ref }),
            )
        })
    }

    /// Return the confined artifact directory for an alias, when non-empty.
    ///
    /// # Arguments
    /// * `alias` - The bundle alias whose artifact directory is returned.
    ///
    /// # Errors
    ///
    /// Returns `WYRD_SDK_404_UNKNOWN_ALIAS` for an unknown alias or an
    /// invalid-state-bundle error if the artifact index is inconsistent.
    #[cfg(feature = "internal")]
    pub fn artifact_dir(&self, alias: &str) -> Result<Option<&Path>, WyrdError> {
        let key = self.index.resolve_key(alias)?;
        self.artifact_dir_by_key(key)
    }

    /// Resolve an alias to its hydrated Agent Card and pinned Prompt Card.
    ///
    /// # Arguments
    /// * `alias` - The bundle alias of an Agent Card.
    ///
    /// # Errors
    /// Returns `WYRD_SDK_404_UNKNOWN_ALIAS` for an unknown alias,
    /// `WYRD_SDK_400_CARD_KIND_MISMATCH` when the alias names another kind,
    /// or `WYRD_SDK_400_INVALID_STATE_BUNDLE` when a validated typed index is
    /// internally inconsistent.
    pub fn agent(&self, alias: &str) -> Result<HydratedAgent<'_>, WyrdError> {
        let key = self.typed_key(alias, &CardKind::Agent)?;
        self.index.typed.agent(key)
    }

    /// Resolve an alias to the kind-appropriate hydrated Card.
    ///
    /// Agents, Prompts, Models, and Data return the same holder their
    /// typed accessor returns; every other kind returns its stored envelope.
    /// The lookup is a local index read with no IO.
    ///
    /// # Arguments
    /// * `alias` - The bundle alias to resolve.
    ///
    /// # Errors
    /// Returns `WYRD_SDK_404_UNKNOWN_ALIAS` for an unknown alias or
    /// `WYRD_SDK_400_INVALID_STATE_BUNDLE` when a validated index is
    /// internally inconsistent.
    pub fn get(&self, alias: &str) -> Result<HydratedCard<'_>, WyrdError> {
        Ok(match self.card_ref(alias)?.kind {
            CardKind::Agent => HydratedCard::Agent(self.agent(alias)?),
            CardKind::Prompt => HydratedCard::Prompt(self.prompt(alias)?),
            CardKind::Model => HydratedCard::Model(self.model(alias)?),
            CardKind::Data => HydratedCard::Data(self.data(alias)?),
            _ => HydratedCard::Envelope(self.card(alias)?),
        })
    }

    /// Resolve an alias to a native Prompt Card holder.
    ///
    /// # Arguments
    /// * `alias` - The bundle alias of a Prompt Card.
    ///
    /// # Errors
    /// Returns `WYRD_SDK_404_UNKNOWN_ALIAS` for an unknown alias,
    /// `WYRD_SDK_400_CARD_KIND_MISMATCH` when the alias names another kind,
    /// or `WYRD_SDK_400_INVALID_STATE_BUNDLE` when a validated typed index is
    /// internally inconsistent.
    pub fn prompt(&self, alias: &str) -> Result<&PromptCard, WyrdError> {
        let key = self.typed_key(alias, &CardKind::Prompt)?;
        self.index
            .typed
            .prompts
            .get(key)
            .ok_or_else(|| typed_map_invariant(alias, key, &CardKind::Prompt))
    }

    /// Resolve an alias to a native Model Card holder.
    ///
    /// # Arguments
    /// * `alias` - The bundle alias of a Model Card.
    ///
    /// # Errors
    /// Returns `WYRD_SDK_404_UNKNOWN_ALIAS` for an unknown alias,
    /// `WYRD_SDK_400_CARD_KIND_MISMATCH` when the alias names another kind,
    /// or `WYRD_SDK_400_INVALID_STATE_BUNDLE` when a validated typed index is
    /// internally inconsistent.
    pub fn model(&self, alias: &str) -> Result<&ModelCard, WyrdError> {
        let key = self.typed_key(alias, &CardKind::Model)?;
        self.index
            .typed
            .models
            .get(key)
            .ok_or_else(|| typed_map_invariant(alias, key, &CardKind::Model))
    }

    /// Resolve an alias to a native Data Card holder.
    ///
    /// # Arguments
    /// * `alias` - The bundle alias of a Data Card.
    ///
    /// # Errors
    /// Returns `WYRD_SDK_404_UNKNOWN_ALIAS` for an unknown alias,
    /// `WYRD_SDK_400_CARD_KIND_MISMATCH` when the alias names another kind,
    /// or `WYRD_SDK_400_INVALID_STATE_BUNDLE` when a validated typed index is
    /// internally inconsistent.
    pub fn data(&self, alias: &str) -> Result<&DataCard, WyrdError> {
        let key = self.typed_key(alias, &CardKind::Data)?;
        self.index
            .typed
            .data
            .get(key)
            .ok_or_else(|| typed_map_invariant(alias, key, &CardKind::Data))
    }

    /// Resolve an alias to the pure Verifier spec borrowed from its envelope.
    ///
    /// Returns the declarative building blocks directly: `inputs`, `steps`,
    /// `requirements`, `decide`, `context_capture`, and `order_by`. Drift and Agent
    /// judging are requirement check kinds inside those blocks, so one
    /// accessor covers every Verifier and no per-check accessor exists.
    ///
    /// # Arguments
    /// * `alias` - The bundle alias of a Verifier Card.
    ///
    /// # Errors
    /// Returns `WYRD_SDK_404_UNKNOWN_ALIAS` for an unknown alias,
    /// `WYRD_SDK_400_CARD_KIND_MISMATCH` when the alias names another kind,
    /// or `WYRD_SDK_400_INVALID_STATE_BUNDLE` for an inconsistent envelope.
    pub fn verifier(&self, alias: &str) -> Result<&VerifierSpec, WyrdError> {
        self.spec_of_kind(alias, &CardKind::Verifier, |spec| match spec {
            Spec::Verifier(spec) => Some(spec),
            _ => None,
        })
    }

    /// Resolve an alias to a typed-holder key and enforce its exact Card kind.
    ///
    /// # Errors
    /// Returns the shared unknown-alias, kind-mismatch, or invalid-state-bundle
    /// error when the lookup or immutable graph invariant fails.
    fn typed_key(&self, alias: &str, expected: &CardKind) -> Result<&str, WyrdError> {
        let key = self.index.resolve_key(alias)?;
        let card_ref = self.index.card_ref_by_key(key)?;
        if &card_ref.kind != expected {
            return Err(WyrdError::SdkCardKindMismatch {
                message: format!("alias `{alias}` is not a {} Card", expected.wire_name()),
                details: json!({
                    "alias": alias,
                    "expected_kind": expected.wire_name(),
                    "actual_kind": card_ref.kind.wire_name(),
                    "card_ref": card_ref,
                }),
            });
        }
        Ok(key)
    }

    /// Borrow one pure spec after applying the same exact-kind check as holder
    /// accessors.
    ///
    /// # Errors
    ///
    /// Returns `WYRD_SDK_404_UNKNOWN_ALIAS` when the alias is absent,
    /// `WYRD_SDK_400_CARD_KIND_MISMATCH` when the exact `CardRef` names another
    /// kind, or `WYRD_SDK_400_INVALID_STATE_BUNDLE` when the validated
    /// envelope and its spec variant disagree.
    fn spec_of_kind<T, F>(
        &self,
        alias: &str,
        expected: &CardKind,
        extract: F,
    ) -> Result<&T, WyrdError>
    where
        F: FnOnce(&Spec) -> Option<&T>,
    {
        let key = self.typed_key(alias, expected)?;
        let card = self.index.card_by_key(key)?;
        extract(&card.spec).ok_or_else(|| {
            state_bundle_error(
                "Card envelope kind and spec variant disagree",
                json!({
                    "alias": alias,
                    "expected_kind": expected.wire_name(),
                    "actual_kind": card.kind.wire_name(),
                    "card_ref": self.index.card_ref_by_key(key).ok(),
                }),
            )
        })
    }

    /// Iterate over every loaded Card keyed by its canonical exact `CardRef`.
    #[cfg(feature = "internal")]
    pub fn cards(&self) -> impl Iterator<Item = (&str, &Card)> {
        self.index
            .cards_by_ref
            .iter()
            .map(|(key, card)| (key.as_str(), card))
    }

    /// Iterate over loaded Cards of one kind keyed by exact `CardRef`.
    ///
    /// # Arguments
    /// * `kind` - The Card kind to keep.
    #[cfg(feature = "internal")]
    pub fn cards_of_kind(&self, kind: CardKind) -> impl Iterator<Item = (&str, &Card)> {
        self.index
            .cards_by_ref
            .iter()
            .filter(move |(_, card)| card.kind == kind)
            .map(|(key, card)| (key.as_str(), card))
    }

    /// Resolve a canonical exact `CardRef` key to its stored reference.
    ///
    /// # Arguments
    /// * `key` - A canonical exact `CardRef` string, as [`WyrdState::cards`] yields it.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle error when the key is absent from the
    /// validated Card index.
    #[cfg(feature = "internal")]
    pub fn card_ref_by_key(&self, key: &str) -> Result<&CardRef, WyrdError> {
        self.index.card_ref_by_key(key)
    }

    /// Resolve a canonical exact `CardRef` key to its aliases.
    ///
    /// # Arguments
    /// * `key` - A canonical exact `CardRef` string, as [`WyrdState::cards`] yields it.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle error when the key is absent from the
    /// validated alias index.
    #[cfg(feature = "internal")]
    pub fn aliases_by_key(&self, key: &str) -> Result<&[String], WyrdError> {
        self.index.aliases_by_key(key)
    }

    /// Resolve a canonical exact `CardRef` key to its artifact directory.
    ///
    /// # Arguments
    /// * `key` - A canonical exact `CardRef` string, as [`WyrdState::cards`] yields it.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle error when the key is absent from the
    /// validated graph indexes.
    #[cfg(feature = "internal")]
    pub fn artifact_dir_by_key(&self, key: &str) -> Result<Option<&Path>, WyrdError> {
        self.index.artifact_dir_by_key(key)
    }

    /// Return the canonical artifact-manifest hash for an exact indexed Card.
    ///
    /// Python hydration calls this only after native bundle validation and
    /// before an executable serializer can run. `None` means the Card has no
    /// declared artifacts.
    ///
    /// # Arguments
    /// * `key` - A canonical exact `CardRef` string, as [`WyrdState::cards`] yields it.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle or canonicalization error when the
    /// validated index cannot reproduce the Card artifact manifest.
    #[cfg(feature = "internal")]
    pub fn artifact_manifest_hash_by_key(&self, key: &str) -> Result<Option<String>, WyrdError> {
        self.index.artifact_manifest_hash_by_key(key)
    }
}

/// Validates bundle metadata and assembles its exact Card graph.
impl BundleReader<'_> {
    /// Validate bundle-level hydration mode, counts, and Service root identity.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle error for unsupported headers, count
    /// mismatches, non-Service roots, or roots without exact identity.
    fn validate_manifest_header(&self, manifest: &BundleManifest) -> Result<(), WyrdError> {
        if manifest.api_version != "wyrd/bundle/v1" {
            return Err(state_bundle_error(
                "unsupported Card bundle apiVersion",
                json!({ "path": self.requested_root, "api_version": manifest.api_version }),
            ));
        }
        if manifest.mode == BundleMode::MetadataOnly {
            return Err(unhydrated_error(
                self.requested_root,
                "Card bundle contains metadata only and cannot be used as runtime state",
            ));
        }
        if manifest.cards.is_empty()
            || manifest.card_count != manifest.cards.len()
            || manifest.artifact_count
                != manifest
                    .cards
                    .iter()
                    .map(|card| card.artifacts.len())
                    .sum::<usize>()
            || manifest.downloaded_artifact_count != manifest.artifact_count
        {
            return Err(state_bundle_error(
                "Card bundle manifest counts are inconsistent",
                json!({
                    "path": self.requested_root,
                    "card_count": manifest.card_count,
                    "actual_card_count": manifest.cards.len(),
                    "artifact_count": manifest.artifact_count,
                    "downloaded_artifact_count": manifest.downloaded_artifact_count,
                }),
            ));
        }
        if manifest.root.kind != CardKind::Service {
            return Err(state_bundle_error(
                "Card bundle root must be a Service Card",
                json!({ "root": manifest.root }),
            ));
        }
        if manifest.root.space.is_none() || manifest.root.uid.is_none() {
            return Err(state_bundle_error(
                "Card bundle root must have an exact space and UID",
                json!({ "root": manifest.root }),
            ));
        }
        Ok(())
    }

    /// Load all manifest entries, validate graph closure, and publish a graph.
    ///
    /// Loading is deliberately two-pass: all exact Card identities and aliases
    /// are collected before spec and relationship references are checked. This
    /// allows forward references while keeping the final `HydratedStateIndex` immutable.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle or unhydrated-artifact error when any
    /// Card projection, reference, relationship, artifact, or root is invalid.
    fn load_index(&self, manifest: BundleManifest) -> Result<HydratedStateIndex, WyrdError> {
        let mut loaded = Vec::with_capacity(manifest.cards.len());
        let mut known = BTreeSet::new();
        let mut aliases = BTreeMap::new();

        for entry in &manifest.cards {
            let item = self.load_manifest_card(entry)?;
            if !known.insert(item.key.clone()) {
                return Err(invalid_duplicate_ref(&item.card_ref));
            }
            for alias in &item.aliases {
                if let Some(existing) = aliases.insert(alias.clone(), item.key.clone()) {
                    return Err(conflicting_alias(alias, &existing, &item.key));
                }
            }
            loaded.push(item);
        }

        for item in &loaded {
            Self::validate_spec_refs(&item.card, &known)?;
            Self::validate_relationships(&item.card, &aliases, &known)?;
        }

        Self::validate_root(&manifest.root, &loaded)?;
        Self::validate_reachable_from_root(&manifest.root, &loaded)?;
        HydratedStateIndex::assemble(manifest.root, loaded, aliases)
    }

    /// Load and verify one Card, relationship, alias, and artifact projection.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle or unhydrated-artifact error when a
    /// projection is missing, mismatched, malformed, unconfined, or unverifiable.
    fn load_manifest_card(
        &self,
        entry: &BundleCardManifest,
    ) -> Result<LoadedManifestCard, WyrdError> {
        let card_path = confined_existing_file(&self.root, &entry.card_path)?;
        let relationships_path = confined_existing_file(&self.root, &entry.relationships_path)?;
        let inventory_path = confined_existing_file(&self.root, &entry.artifact_inventory_path)?;
        let card: Card = read_yaml(&card_path)?;
        if card.api_version.as_str() != ApiVersion::V1 {
            return Err(state_bundle_error(
                "hydrated Card does not use apiVersion wyrd/v1",
                json!({ "path": card_path, "api_version": card.api_version }),
            ));
        }
        let relationships: Relationships = read_yaml(&relationships_path)?;
        let inventory: Vec<BundleArtifactManifest> = read_yaml(&inventory_path)?;
        if relationships != card.relationships {
            return Err(state_bundle_error(
                "hydrated relationship projection does not match its Card envelope",
                json!({ "card_path": card_path, "relationships_path": relationships_path }),
            ));
        }
        if inventory != entry.artifacts {
            return Err(state_bundle_error(
                "hydrated artifact inventory projection does not match its manifest",
                json!({ "card_path": card_path, "inventory_path": inventory_path }),
            ));
        }
        let card_ref = exact_card_ref(&card, &card_path)?;
        if card_ref != entry.card_ref {
            return Err(state_bundle_error(
                "hydrated Card envelope does not match its manifest CardRef",
                json!({ "card_path": card_path, "manifest_card_ref": entry.card_ref, "actual_card_ref": card_ref }),
            ));
        }
        if card_ref.uid.is_none() {
            return Err(state_bundle_error(
                "hydrated Card is missing its required UID",
                json!({ "card_ref": card_ref, "card_path": card_path }),
            ));
        }

        let mut artifacts = Vec::with_capacity(entry.artifacts.len());
        for artifact in &entry.artifacts {
            artifacts.push(self.validate_artifact(artifact)?);
        }
        let artifact_dir = if artifacts.is_empty() {
            None
        } else {
            let card_dir = card_path.parent().ok_or_else(|| {
                state_bundle_error(
                    "hydrated Card path has no parent directory",
                    json!({ "path": card_path }),
                )
            })?;
            let artifact_dir = confined_existing_dir(
                &self.root,
                &relative_path(&self.root, &card_dir.join("artifacts"))?,
            )?;
            for artifact in &artifacts {
                let expected = artifact_dir.join(&artifact.relative_path);
                if artifact.local_path != expected {
                    return Err(state_bundle_error(
                        "hydrated artifact payload is outside its Card artifact directory",
                        json!({ "relative_path": artifact.relative_path, "local_path": artifact.local_path, "artifact_dir": artifact_dir }),
                    ));
                }
            }
            Some(artifact_dir)
        };

        for alias in &entry.aliases {
            validate_alias(alias)?;
            let alias_path = confined_existing_file(&self.root, &format!("aliases/{alias}.yaml"))?;
            let record: AliasRecord = read_yaml(&alias_path)?;
            if record.alias != *alias
                || record.card_ref != card_ref
                || record.card_path != entry.card_path
            {
                return Err(state_bundle_error(
                    "hydrated alias projection does not match its Card manifest",
                    json!({ "alias": alias, "alias_path": alias_path, "card_ref": card_ref }),
                ));
            }
        }

        // The directory and artifacts are validated above either way; only
        // the `internal` introspection surface retains them.
        #[cfg(not(feature = "internal"))]
        let _ = (artifact_dir, artifacts);
        Ok(LoadedManifestCard {
            key: card_ref.to_string(),
            card_ref,
            card,
            aliases: entry.aliases.clone(),
            #[cfg(feature = "internal")]
            artifacts,
            #[cfg(feature = "internal")]
            artifact_dir,
        })
    }

    /// Validate durable, nested, and registration-only references in one Card spec.
    ///
    /// Validation precedence is fixed: unresolved paths, registration-only
    /// siblings, missing UIDs, then missing graph targets. Sibling detection is
    /// typed and includes nested inline Agent and Prompt bodies.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle error describing the first reference
    /// violation in the prescribed precedence order.
    fn validate_spec_refs(card: &Card, known: &BTreeSet<String>) -> Result<(), WyrdError> {
        if let Some(path) = unresolved_card_ref_paths(&card.spec).first() {
            return Err(state_bundle_error(
                "hydrated Card contains an unresolved path reference",
                json!({ "card_ref": exact_card_ref_for_error(card), "path": path }),
            ));
        }
        if let Some(sibling) = registration_only_sibling_refs(&card.spec).first() {
            return Err(state_bundle_error(
                "hydrated Card contains a registration-only sibling reference",
                json!({
                    "owner": exact_card_ref_for_error(card),
                    "card_ref": sibling,
                    "reference_form": "sibling",
                }),
            ));
        }
        for card_ref in scope_child_card_refs(&card.spec) {
            if card_ref.uid.is_none() {
                return Err(state_bundle_error(
                    "hydrated Card reference is missing its required UID",
                    json!({ "card_ref": card_ref, "owner": exact_card_ref_for_error(card) }),
                ));
            }
            let key = card_ref.to_string();
            if !known.contains(&key) {
                return Err(state_bundle_error(
                    "hydrated Card spec reference is absent from the graph",
                    json!({ "card_ref": card_ref, "owner": exact_card_ref_for_error(card) }),
                ));
            }
        }
        Ok(())
    }

    /// Validate every server-derived outbound relationship against graph indexes.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle error when a relationship lacks a UID,
    /// points outside the graph, or disagrees with its alias projection.
    fn validate_relationships(
        card: &Card,
        aliases: &BTreeMap<String, String>,
        known: &BTreeSet<String>,
    ) -> Result<(), WyrdError> {
        let expected = wyrd_spec::graph::relationships_from_spec(&card.spec);
        if card.relationships.outbound != expected.outbound
            || card.relationships.outbound_refs != expected.outbound_refs
        {
            return Err(state_bundle_error(
                "hydrated relationship projection does not match its resolved Card spec",
                json!({ "owner": exact_card_ref_for_error(card) }),
            ));
        }
        for relationship in &card.relationships.outbound_refs {
            let card_ref = &relationship.card_ref;
            if card_ref.uid.is_none() {
                return Err(state_bundle_error(
                    "hydrated relationship is missing its required UID",
                    json!({ "owner": exact_card_ref_for_error(card), "card_ref": card_ref }),
                ));
            }
            let key = card_ref.to_string();
            if !known.contains(&key) {
                return Err(state_bundle_error(
                    "hydrated relationship target is absent from the graph",
                    json!({ "owner": exact_card_ref_for_error(card), "card_ref": card_ref }),
                ));
            }
            if let Some(alias) = &relationship.alias
                && aliases.get(alias) != Some(&key)
            {
                return Err(state_bundle_error(
                    "hydrated relationship alias does not resolve to its CardRef",
                    json!({ "owner": exact_card_ref_for_error(card), "alias": alias, "card_ref": card_ref }),
                ));
            }
        }
        Ok(())
    }

    /// Verify one artifact's confined path, size, digest, and metadata.
    ///
    /// # Errors
    ///
    /// Returns an unhydrated-artifact error when complete payload metadata is
    /// absent, or an invalid-state-bundle error when path, filesystem, size,
    /// or digest validation fails.
    fn validate_artifact(
        &self,
        entry: &BundleArtifactManifest,
    ) -> Result<HydratedArtifact, WyrdError> {
        validate_artifact_path(&entry.relative_path)?;
        let local_path = entry.local_path.as_deref().ok_or_else(|| {
            unhydrated_error(
                &self.root,
                "complete hydration is missing an artifact payload path",
            )
        })?;
        let payload = confined_existing_file(&self.root, local_path)?;
        let metadata = fs::metadata(&payload).map_err(|error| {
            state_bundle_error(
                "hydrated artifact payload cannot be read",
                json!({ "path": payload, "source": error.to_string() }),
            )
        })?;
        let expected_size = u64::try_from(entry.size_bytes).map_err(|_| {
            state_bundle_error(
                "hydrated artifact inventory has a negative size",
                json!({ "path": payload, "size_bytes": entry.size_bytes }),
            )
        })?;
        if metadata.len() != expected_size {
            return Err(state_bundle_error(
                "hydrated artifact payload size does not match its inventory",
                json!({ "path": payload, "expected_size": expected_size, "actual_size": metadata.len() }),
            ));
        }
        let digest = sha256_base64(&payload)?;
        if digest != entry.sha256 {
            return Err(state_bundle_error(
                "hydrated artifact payload digest does not match its inventory",
                json!({ "path": payload, "expected_sha256": entry.sha256, "actual_sha256": digest }),
            ));
        }
        Ok(HydratedArtifact {
            relative_path: entry.relative_path.clone(),
            local_path: payload,
            #[cfg(feature = "internal")]
            sha256: entry.sha256.clone(),
            #[cfg(feature = "internal")]
            size_bytes: expected_size,
            #[cfg(feature = "internal")]
            content_type: entry.content_type.clone(),
        })
    }
}

/// Build a structured invalid-state-bundle error for local hydration failures.
///
/// The helper is stateless because its result depends only on the supplied
/// message and detail payload; the owning validation stage remains on
/// `WyrdState`.
fn state_bundle_error(message: impl Into<String>, details: Value) -> WyrdError {
    WyrdError::SdkInvalidStateBundle {
        message: message.into(),
        details,
    }
}

/// Construct native typed holders from the already validated Card envelope map.
///
/// This is the third immutable-state construction pass. It consumes envelope
/// clones because each native holder owns its declarative spec projection; it
/// never reads or copies artifact payload bytes. Conversion failures are
/// normalized here so callers receive the exact `CardRef` and kind that failed.
///
/// # Errors
/// Returns `WYRD_SDK_400_INVALID_STATE_BUNDLE` when a validated envelope cannot
/// be converted to its required native typed holder.
fn hydrate_typed_cards(cards: &BTreeMap<String, Card>) -> Result<TypedCards, WyrdError> {
    let mut typed = TypedCards::default();
    for (key, envelope) in cards {
        match envelope.kind {
            CardKind::Agent => {
                let holder = AgentCard::from_envelope(envelope.clone())
                    .map_err(|error| typed_hydration_error(envelope, &error))?;
                typed.agents.insert(key.clone(), holder);
            }
            CardKind::Prompt => {
                let holder = PromptCard::from_card(envelope.clone())
                    .map_err(|error| typed_hydration_error(envelope, &error))?;
                typed.prompts.insert(key.clone(), holder);
            }
            CardKind::Model => {
                let holder = ModelCard::from_card(envelope.clone())
                    .map_err(|error| typed_hydration_error(envelope, &error))?;
                typed.models.insert(key.clone(), holder);
            }
            CardKind::Data => {
                let holder = DataCard::from_card(envelope.clone())
                    .map_err(|error| typed_hydration_error(envelope, &error))?;
                typed.data.insert(key.clone(), holder);
            }
            _ => {}
        }
    }
    for key in typed.agents.keys() {
        typed.agent(key)?;
    }
    Ok(typed)
}

/// Normalize one native holder conversion failure at the state boundary.
///
/// The bundle graph has already validated this envelope's identity, so the
/// error detail uses that identity directly and never introduces a second
/// fallible `CardRef` conversion path.
#[must_use]
fn typed_hydration_error(card: &Card, source: &WyrdError) -> WyrdError {
    WyrdError::SdkInvalidStateBundle {
        message: format!(
            "failed to construct typed {} Card from validated bundle envelope",
            card.kind.wire_name(),
        ),
        details: json!({
            "card_ref": exact_card_ref_for_error(card),
            "kind": card.kind.wire_name(),
            "reason": source.to_string(),
        }),
    }
}

/// Report a typed map omission after graph validation and holder construction.
///
/// # Panics
/// This helper never panics; it only constructs a stable invariant error.
#[must_use]
fn typed_map_invariant(alias: &str, key: &str, expected: &CardKind) -> WyrdError {
    state_bundle_error(
        "validated typed Card map is missing its exact CardRef entry",
        json!({
            "alias": alias,
            "card_ref_key": key,
            "expected_kind": expected.wire_name(),
        }),
    )
}

/// Validates exact root identity and persisted relationship projections.
impl BundleReader<'_> {
    /// Confirm that the manifest root is an exact, loaded Service Card.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle error when the root is absent, has a
    /// mismatched identity, or is not a Service Card.
    fn validate_root(root: &CardRef, loaded: &[LoadedManifestCard]) -> Result<(), WyrdError> {
        let Some(item) = loaded.iter().find(|item| item.key == root.to_string()) else {
            return Err(state_bundle_error(
                "Card bundle root is not present in its Card set",
                json!({ "root": root }),
            ));
        };
        if item.card_ref != *root || item.card.kind != CardKind::Service {
            return Err(state_bundle_error(
                "Card bundle root identity or kind does not match its manifest",
                json!({ "root": root, "actual": item.card_ref, "actual_kind": item.card.kind }),
            ));
        }
        Ok(())
    }

    /// Require the declared root to reach every Card published in its bundle.
    ///
    /// A hydrated state is one immutable Service graph, not a local Card cache.
    /// Walking canonical outbound relationships from the exact Service root
    /// rejects an otherwise individually valid orphan before the state becomes
    /// visible to callers.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state-bundle error when a published Card is not
    /// reachable from the declared root through canonical outbound references.
    fn validate_reachable_from_root(
        root: &CardRef,
        loaded: &[LoadedManifestCard],
    ) -> Result<(), WyrdError> {
        let cards = loaded
            .iter()
            .map(|item| (item.key.as_str(), &item.card))
            .collect::<BTreeMap<_, _>>();
        let mut pending = vec![root.to_string()];
        let mut reachable = BTreeSet::new();

        while let Some(key) = pending.pop() {
            if !reachable.insert(key.clone()) {
                continue;
            }
            let card = cards.get(key.as_str()).ok_or_else(|| {
                state_bundle_error(
                    "hydrated root traversal encountered a missing Card",
                    json!({ "card_ref_key": key }),
                )
            })?;
            pending.extend(
                card.relationships
                    .outbound_refs
                    .iter()
                    .map(|relationship| relationship.card_ref.to_string()),
            );
        }

        if reachable.len() != cards.len() {
            let unreachable = cards
                .keys()
                .filter(|key| !reachable.contains::<str>(*key))
                .copied()
                .collect::<Vec<_>>();
            return Err(state_bundle_error(
                "Card bundle contains Cards unreachable from its root",
                json!({ "root": root, "unreachable": unreachable }),
            ));
        }
        Ok(())
    }
}

/// Convert a hydrated Card envelope into its exact UID-bearing reference.
///
/// # Errors
///
/// Returns an invalid-state-bundle error when the Card lacks a pinned version,
/// resolved space, or required UID.
fn exact_card_ref(card: &Card, path: &Path) -> Result<CardRef, WyrdError> {
    let version = card.metadata.resolved_pin().cloned().ok_or_else(|| {
        state_bundle_error(
            "hydrated Card is missing an exact version pin",
            json!({ "path": path }),
        )
    })?;
    let space = card.metadata.space.clone().ok_or_else(|| {
        state_bundle_error(
            "hydrated Card is missing a resolved space",
            json!({ "path": path }),
        )
    })?;
    let uid = card.metadata.uid.clone().ok_or_else(|| {
        state_bundle_error(
            "hydrated Card is missing its required UID",
            json!({ "path": path }),
        )
    })?;
    Ok(CardRef {
        kind: card.kind.clone(),
        name: card.metadata.name.clone(),
        version,
        space: Some(space),
        uid: Some(uid),
    })
}

/// Canonicalize and verify the root directory used for local hydration.
///
/// # Errors
///
/// Returns an invalid-state-bundle error when the path cannot be inspected,
/// is not a directory, or cannot be canonicalized.
fn absolute_bundle(bundle: &Path) -> Result<PathBuf, WyrdError> {
    let metadata = fs::symlink_metadata(bundle).map_err(|error| {
        state_bundle_error(
            "Card bundle directory cannot be read",
            json!({ "path": bundle, "source": error.to_string() }),
        )
    })?;
    if !metadata.is_dir() {
        return Err(state_bundle_error(
            "Card bundle path is not a directory",
            json!({ "path": bundle }),
        ));
    }
    fs::canonicalize(bundle).map_err(|error| {
        state_bundle_error(
            "Card bundle directory cannot be canonicalized",
            json!({ "path": bundle, "source": error.to_string() }),
        )
    })
}

/// Join one manifest-relative path to a bundle without permitting traversal.
///
/// # Errors
///
/// Returns an invalid-state-bundle error when the relative path is empty,
/// absolute, or contains parent/root/prefix components.
fn confined_path(root: &Path, relative: &str) -> Result<PathBuf, WyrdError> {
    if relative.is_empty() {
        return Err(state_bundle_error(
            "Card bundle path is empty",
            json!({ "path": relative }),
        ));
    }
    let path = Path::new(relative);
    if path.is_absolute()
        || path.components().any(|component| {
            matches!(
                component,
                Component::ParentDir | Component::RootDir | Component::Prefix(_)
            )
        })
    {
        return Err(state_bundle_error(
            "Card bundle path escapes its root",
            json!({ "path": relative, "root": root }),
        ));
    }
    Ok(root.join(path))
}

/// Resolve a manifest file and verify its canonical target stays in the bundle.
///
/// # Errors
///
/// Returns an invalid-state-bundle error when the path is missing, not a regular
/// file, cannot be canonicalized, or escapes the bundle through a symlink.
fn confined_existing_file(root: &Path, relative: &str) -> Result<PathBuf, WyrdError> {
    let root = absolute_bundle(root)?;
    let path = confined_path(&root, relative)?;
    let metadata = fs::symlink_metadata(&path).map_err(|error| {
        state_bundle_error(
            "Card bundle file cannot be read",
            json!({ "path": path, "source": error.to_string() }),
        )
    })?;
    if !metadata.is_file() {
        return Err(state_bundle_error(
            "Card bundle projection is not a regular file",
            json!({ "path": path }),
        ));
    }
    let canonical = fs::canonicalize(&path).map_err(|error| {
        state_bundle_error(
            "Card bundle file cannot be canonicalized",
            json!({ "path": path, "source": error.to_string() }),
        )
    })?;
    if !canonical.starts_with(&root) {
        return Err(state_bundle_error(
            "Card bundle path escapes its root",
            json!({ "path": path, "root": root }),
        ));
    }
    Ok(canonical)
}

/// Resolve an artifact directory and verify its canonical target stays in the bundle.
///
/// # Errors
///
/// Returns an invalid-state-bundle error when the path is missing, not a
/// directory, cannot be canonicalized, or escapes the bundle through a symlink.
fn confined_existing_dir(root: &Path, relative: &str) -> Result<PathBuf, WyrdError> {
    let root = absolute_bundle(root)?;
    let path = confined_path(&root, relative)?;
    let metadata = fs::symlink_metadata(&path).map_err(|error| {
        state_bundle_error(
            "hydrated artifact directory cannot be read",
            json!({ "path": path, "source": error.to_string() }),
        )
    })?;
    if !metadata.is_dir() {
        return Err(state_bundle_error(
            "hydrated artifact directory is not a directory",
            json!({ "path": path }),
        ));
    }
    let canonical = fs::canonicalize(&path).map_err(|error| {
        state_bundle_error(
            "hydrated artifact directory cannot be canonicalized",
            json!({ "path": path, "source": error.to_string() }),
        )
    })?;
    if !canonical.starts_with(&root) {
        return Err(state_bundle_error(
            "hydrated artifact directory escapes its root",
            json!({ "path": path, "root": root }),
        ));
    }
    Ok(canonical)
}

/// Validate the filename-safe alias syntax used by hydration projections.
///
/// # Errors
///
/// Returns an invalid-state-bundle error when the alias is empty, traversal-like,
/// contains a separator, or contains a character outside the safe ASCII set.
fn validate_alias(alias: &str) -> Result<(), WyrdError> {
    if alias.is_empty()
        || alias == "."
        || alias == ".."
        || alias.contains('/')
        || alias.contains('\\')
        || alias.bytes().any(
            |byte| !matches!(byte, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'.' | b'_' | b'-'),
        )
    {
        return Err(state_bundle_error(
            "Card bundle contains an unsafe alias",
            json!({ "alias": alias }),
        ));
    }
    Ok(())
}

/// Validate the slash-delimited relative path recorded for one artifact.
///
/// # Errors
///
/// Returns an invalid-state-bundle error when the path is empty, absolute,
/// contains separators or traversal segments, or contains unsafe characters.
fn validate_artifact_path(path: &str) -> Result<(), WyrdError> {
    if path.is_empty()
        || path.starts_with('/')
        || path.contains('\\')
        || path.split('/').any(|segment| {
            segment.is_empty()
                || segment == "."
                || segment == ".."
                || segment.bytes().any(
                    |byte| !matches!(byte, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'.' | b'_' | b'-'),
                )
        })
    {
        return Err(state_bundle_error(
            "artifact path is not confined to the Card bundle",
            json!({ "relative_path": path }),
        ));
    }
    Ok(())
}

/// Hash a verified local artifact payload using the bundle's digest encoding.
///
/// # Errors
///
/// Returns an invalid-state-bundle error when the payload cannot be opened or
/// read during streaming hashing.
fn sha256_base64(path: &Path) -> Result<String, WyrdError> {
    let mut file = File::open(path).map_err(|error| {
        state_bundle_error(
            "hydrated artifact cannot be opened",
            json!({ "path": path, "source": error.to_string() }),
        )
    })?;
    let mut hasher = Sha256::new();
    let mut buffer = vec![0_u8; 128 * 1024];
    loop {
        let read = file.read(&mut buffer).map_err(|error| {
            state_bundle_error(
                "hydrated artifact cannot be read",
                json!({ "path": path, "source": error.to_string() }),
            )
        })?;
        if read == 0 {
            break;
        }
        hasher.update(&buffer[..read]);
    }
    Ok(base64::engine::general_purpose::STANDARD.encode(hasher.finalize()))
}

/// Decode one hydrated YAML projection into its typed Rust contract.
///
/// # Errors
///
/// Returns an invalid-state-bundle error when the projection cannot be read or
/// does not deserialize as the requested type.
fn read_yaml<T: for<'de> Deserialize<'de>>(path: &Path) -> Result<T, WyrdError> {
    let contents = fs::read(path).map_err(|error| {
        state_bundle_error(
            "Card bundle file cannot be read",
            json!({ "path": path, "source": error.to_string() }),
        )
    })?;
    serde_yaml::from_slice(&contents).map_err(|error| {
        state_bundle_error(
            "Card bundle YAML is invalid",
            json!({ "path": path, "source": error.to_string() }),
        )
    })
}

/// Return a UTF-8 manifest-relative path after confinement has been established.
///
/// # Errors
///
/// Returns an invalid-state-bundle error when the path is outside the bundle or
/// cannot be represented as UTF-8.
fn relative_path(root: &Path, path: &Path) -> Result<String, WyrdError> {
    path.strip_prefix(root)
        .map_err(|_| {
            state_bundle_error(
                "hydrated path is outside its bundle",
                json!({ "path": path, "root": root }),
            )
        })
        .and_then(|relative| {
            relative.to_str().map(str::to_owned).ok_or_else(|| {
                state_bundle_error("hydrated path is not valid UTF-8", json!({ "path": path }))
            })
        })
}

/// Project the already validated envelope identity into exact `CardRef`
/// details for a state error without introducing a second fallible conversion.
#[must_use]
fn exact_card_ref_for_error(card: &Card) -> Value {
    json!({ "kind": card.kind, "name": card.metadata.name, "version": card.metadata.version, "space": card.metadata.space, "uid": card.metadata.uid })
}

/// Construct the stable error for a duplicate exact Card reference.
#[must_use]
fn invalid_duplicate_ref(card_ref: &CardRef) -> WyrdError {
    state_bundle_error(
        "Card bundle contains a duplicate CardRef",
        json!({ "card_ref": card_ref }),
    )
}

/// Construct the stable error for two Cards claiming one alias.
#[must_use]
fn conflicting_alias(alias: &str, existing: &str, incoming: &str) -> WyrdError {
    state_bundle_error(
        "Card bundle contains a conflicting alias",
        json!({ "alias": alias, "existing_card_ref_key": existing, "incoming_card_ref_key": incoming }),
    )
}

/// Construct the stable error for a metadata-only or incomplete bundle.
#[must_use]
fn unhydrated_error(path: &Path, message: &str) -> WyrdError {
    WyrdError::SdkUnhydratedArtifact {
        message: message.to_owned(),
        details: json!({ "path": path }),
    }
}

/// One Card from a Card bundle manifest after its envelope, identity,
/// aliases, and artifacts have been validated against disk.
///
/// Produced per manifest entry while loading a local bundle and then indexed
/// by `key` to build the in-memory Card graph; construction guarantees the
/// Card carries a UID and that every artifact lies inside `artifact_dir`.
#[derive(Debug)]
struct LoadedManifestCard {
    /// Canonical exact-reference key used by every graph index.
    key: String,
    /// Exact identity read from the Card envelope and manifest.
    card_ref: CardRef,
    /// Complete Card envelope loaded from disk.
    card: Card,
    /// Manifest aliases validated against their projection files.
    aliases: Vec<String>,
    /// Verified artifacts owned by this Card.
    #[cfg(feature = "internal")]
    artifacts: Vec<HydratedArtifact>,
    /// Canonical artifact directory when the Card has artifacts.
    #[cfg(feature = "internal")]
    artifact_dir: Option<PathBuf>,
}

/// On-disk alias projection read from `aliases/<alias>.yaml` in a hydrated
/// bundle.
///
/// Bundle loading rejects the bundle unless every field matches the manifest
/// entry that declares the alias; unknown fields are refused so a tampered or
/// newer-format projection fails closed.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct AliasRecord {
    /// Alias represented by this projection filename.
    alias: String,
    /// Exact Card reference addressed by the alias.
    card_ref: CardRef,
    /// Relative Card projection path paired with the alias.
    card_path: String,
}

/// How a state's runtime-managed OpenTelemetry tracer provider failed to flush.
///
/// Python and TypeScript state flush and shutdown first flush the provider
/// their `start_telemetry` installed, then always attempt the native Bifrost
/// drain. This value carries the provider stage's outcome across that drain so
/// both runtimes report the same catalog error: OTEL is primary and the
/// drain's stable code, when it also failed, is secondary detail. `cause` is a
/// payload-free stage description such as an exception type name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TelemetryFlushFailure {
    /// Whether the provider reported its configured export bound expired.
    timed_out: bool,
    /// Payload-free description of the failure, never an exception message.
    cause: String,
}

impl TelemetryFlushFailure {
    /// A provider flush that did not finish within its configured bound.
    pub fn timeout(cause: impl Into<String>) -> Self {
        Self {
            timed_out: true,
            cause: cause.into(),
        }
    }

    /// A provider flush that raised or rejected for any other reason.
    pub fn failed(cause: impl Into<String>) -> Self {
        Self {
            timed_out: false,
            cause: cause.into(),
        }
    }

    /// Build the catalog error, recording `native_code` from a failed drain.
    ///
    /// Produces `WYRD_SDK_504_TELEMETRY_FLUSH_TIMEOUT` or
    /// `WYRD_SDK_503_TELEMETRY_FLUSH_FAILED` with `details.stage`,
    /// `details.cause`, and `details.native_code` (null when the drain passed).
    pub fn into_error(self, native_code: Option<&str>) -> WyrdError {
        let details = json!({
            "stage": "opentelemetry",
            "cause": self.cause,
            "native_code": native_code,
        });
        if self.timed_out {
            WyrdError::SdkTelemetryFlushTimeout {
                message: format!(
                    "the managed OpenTelemetry provider did not flush completed spans within its export timeout ({})",
                    self.cause
                ),
                details,
            }
        } else {
            WyrdError::SdkTelemetryFlushFailed {
                message: format!(
                    "the managed OpenTelemetry provider failed to flush completed spans ({})",
                    self.cause
                ),
                details,
            }
        }
    }

    /// Combine an optional provider failure with the native drain's result.
    ///
    /// # Errors
    /// Returns the telemetry error carrying the drain's code when the provider
    /// failed, otherwise the drain's own error unchanged.
    pub fn settle(telemetry: Option<Self>, native: Result<(), WyrdError>) -> Result<(), WyrdError> {
        match (telemetry, native) {
            (None, native) => native,
            (Some(failure), native) => {
                Err(failure.into_error(native.as_ref().err().map(WyrdError::code)))
            }
        }
    }
}

#[cfg(test)]
/// Exercises local Card bundle loading, typed Card projections, reference
/// closure, alias identity, and artifact confinement without network access.
pub(crate) mod tests {
    use std::cell::RefCell;
    use std::collections::BTreeMap;
    use std::fs;
    use std::path::{Path, PathBuf};

    use base64::Engine;
    use serde::Serialize;
    use serde_json::Value;
    use sha2::{Digest, Sha256};
    use skald_spec::{OpenAiChatRequest, Prompt, ProviderRequest};
    use tempfile::{TempDir, tempdir};
    use wyrd_semver::{VersionBlock, VersionSpec};
    use wyrd_spec::api_version::ApiVersion;
    use wyrd_spec::card::agent::{AgentRunConfigSpec, AgentSpec};
    use wyrd_spec::card::data::{CustomDataMeta, DataInterface, DataSchema, DataSpec, DataStats};
    use wyrd_spec::card::field::FieldSpec;
    use wyrd_spec::card::model::{CustomMeta, ModelInterface, ModelSignature, ModelSpec, TaskType};
    use wyrd_spec::card::prompt::PromptSpec;
    use wyrd_spec::card::service::{ServiceComponent, ServiceSpec};
    use wyrd_spec::card::trigger::{TriggerActivation, TriggerSpec};
    use wyrd_spec::card::verifier::{
        AgentCall, Check, Requirement, VerificationBinding, VerifierSpec,
    };
    use wyrd_spec::envelope::{Card, CardKind, Metadata, Relationships, Spec};
    use wyrd_spec::graph::relationships_from_spec;
    use wyrd_spec::ids::{CardName, CardUid, SpaceName};
    use wyrd_spec::reference::{CardRef, InlineableRef, Ref};
    use wyrd_spec::registry::{
        BundleArtifactManifest, BundleCardManifest, BundleManifest, BundleMode,
    };

    use super::{HydratedArtifact, HydratedCard, WyrdState};
    use wyrd_spec::error::WyrdError;

    /// Deterministic payload metadata used to materialize a hydrated artifact
    /// in a temporary bundle fixture.
    #[derive(Clone)]
    struct TestArtifact {
        /// Bundle-relative payload path recorded in the artifact manifest.
        relative_path: String,
        /// Exact bytes written to the fixture payload and hashed in its manifest.
        bytes: Vec<u8>,
        /// Optional content type copied into the hydrated artifact manifest.
        content_type: Option<String>,
    }

    /// Owns a complete temporary Card bundle and the in-memory values used
    /// to rewrite projections while testing validation failures.
    pub(crate) struct TestBundle {
        /// Temporary directory containing metadata, Card projections, aliases,
        /// and verified artifact payloads.
        root: TempDir,
        /// Mutable Card bundle manifest serialized by [`Self::write`].
        manifest: BundleManifest,
        /// Card envelopes keyed by their exact canonical `CardRef` string.
        cards: RefCell<BTreeMap<String, Card>>,
        /// Artifact bytes keyed by exact `CardRef` and relative payload path.
        artifact_bytes: RefCell<BTreeMap<(String, String), Vec<u8>>>,
    }

    impl TestBundle {
        /// Build the smallest complete Service graph used by validation tests.
        ///
        /// # Panics
        /// Panics if the temporary directory cannot be created or fixture
        /// values cannot be serialized and written.
        pub(crate) fn complete_service() -> Self {
            let root_ref = test_ref(CardKind::Service, "service", 1);
            let model_ref = test_ref(CardKind::Model, "model", 2);
            let backup_ref = test_ref(CardKind::Model, "backup", 3);
            let service_spec = ServiceSpec {
                components: vec![
                    ServiceComponent {
                        alias: "model".to_owned(),
                        card_ref: Ref::Ref(model_ref.clone()),
                        verified_by: Vec::new(),
                        source: None,
                        config: BTreeMap::new(),
                        credential_refs: Vec::new(),
                    },
                    ServiceComponent {
                        alias: "backup".to_owned(),
                        card_ref: Ref::Ref(backup_ref.clone()),
                        verified_by: Vec::new(),
                        source: None,
                        config: BTreeMap::new(),
                        credential_refs: Vec::new(),
                    },
                ],
                ..ServiceSpec::default()
            };
            let mut bundle = Self {
                root: tempdir().expect("test bundle tempdir is available"),
                manifest: BundleManifest {
                    api_version: "wyrd/bundle/v1".to_owned(),
                    mode: BundleMode::Complete,
                    root: root_ref.clone(),
                    cards: Vec::new(),
                    card_count: 0,
                    artifact_count: 0,
                    downloaded_artifact_count: 0,
                },
                cards: RefCell::new(BTreeMap::new()),
                artifact_bytes: RefCell::new(BTreeMap::new()),
            };
            bundle.add_card(
                "root",
                card(
                    &root_ref,
                    CardKind::Service,
                    Spec::Service(service_spec.clone()),
                    relationships_from_spec(&Spec::Service(service_spec)),
                ),
                &[],
            );
            bundle.add_card(
                "model",
                card(
                    &model_ref,
                    CardKind::Model,
                    Spec::Model(model_spec()),
                    Relationships::default(),
                ),
                &[],
            );
            bundle.add_card(
                "backup",
                card(
                    &backup_ref,
                    CardKind::Model,
                    Spec::Model(model_spec()),
                    Relationships::default(),
                ),
                &[],
            );
            bundle.manifest.card_count = bundle.manifest.cards.len();
            bundle.manifest.artifact_count = 0;
            bundle.manifest.downloaded_artifact_count = 0;
            bundle.write();
            bundle
        }

        /// Add one deterministic Model artifact to the complete Service graph.
        ///
        /// # Panics
        /// Panics if the model entry is absent, fixture sizes cannot convert,
        /// or the updated bundle cannot be written.
        fn with_artifact() -> Self {
            let mut bundle = Self::complete_service();
            let model_ref = test_ref(CardKind::Model, "model", 2);
            let artifact = TestArtifact {
                relative_path: "weights.bin".to_owned(),
                bytes: b"weights".to_vec(),
                content_type: Some("application/octet-stream".to_owned()),
            };
            let entry = bundle
                .manifest
                .cards
                .iter_mut()
                .find(|entry| entry.card_ref == model_ref)
                .expect("model fixture exists");
            bundle.artifact_bytes.borrow_mut().insert(
                (model_ref.to_string(), artifact.relative_path.clone()),
                artifact.bytes.clone(),
            );
            entry.artifacts.push(BundleArtifactManifest {
                relative_path: artifact.relative_path.clone(),
                sha256: digest(&artifact.bytes),
                size_bytes: i64::try_from(artifact.bytes.len()).expect("fixture size fits"),
                content_type: artifact.content_type,
                local_path: Some("cards/model/artifacts/weights.bin".to_owned()),
            });
            bundle.manifest.card_count = bundle.manifest.cards.len();
            bundle.manifest.artifact_count = 1;
            bundle.manifest.downloaded_artifact_count = 1;
            bundle.write();
            bundle
        }

        /// Build a graph containing every typed SDK projection and two prompt
        /// forms while keeping artifact bytes outside the holder values.
        ///
        /// # Panics
        /// Panics if fixture construction or serialization fails.
        pub(crate) fn with_typed_cards() -> Self {
            let mut bundle = Self::complete_service();
            let prompt_ref = test_ref(CardKind::Prompt, "triage", 4);
            let agent_ref = test_ref(CardKind::Agent, "triage", 6);
            let data_ref = test_ref(CardKind::Data, "training", 7);
            let check_ref = test_ref(CardKind::Verifier, "quality", 8);
            let drift_ref = test_ref(CardKind::Verifier, "model-drift", 9);

            bundle.add_card(
                "triage_prompt",
                card(
                    &prompt_ref,
                    CardKind::Prompt,
                    Spec::Prompt(prompt_spec("triage")),
                    Relationships::default(),
                ),
                &[],
            );
            bundle.add_card(
                "agent_triage",
                canonical_card(
                    &agent_ref,
                    CardKind::Agent,
                    registered_agent_spec(&prompt_ref),
                ),
                &[],
            );
            bundle.add_card(
                "training_data",
                card(
                    &data_ref,
                    CardKind::Data,
                    Spec::Data(data_spec()),
                    Relationships::default(),
                ),
                &[],
            );
            bundle.add_card(
                "quality_check",
                card(
                    &check_ref,
                    CardKind::Verifier,
                    Spec::Verifier(assert_verifier()),
                    Relationships::default(),
                ),
                &[],
            );
            bundle.add_card(
                "model_drift",
                card(
                    &drift_ref,
                    CardKind::Verifier,
                    Spec::Verifier(drift_verifier()),
                    Relationships::default(),
                ),
                &[],
            );
            let root_ref = test_ref(CardKind::Service, "service", 1);
            bundle.rewrite_card(&root_ref, |card| {
                let Spec::Service(spec) = &mut card.spec else {
                    panic!("fixture root is a Service");
                };
                spec.components.extend([
                    service_component("triage_prompt", &prompt_ref),
                    service_component("training_data", &data_ref),
                    service_component("agent_triage", &agent_ref),
                ]);
                spec.verified_by.extend([
                    verification_binding(check_ref, None),
                    verification_binding(
                        drift_ref,
                        Some(TriggerActivation::Schedule {
                            cron: "0 * * * *".to_owned(),
                            tz: None,
                        }),
                    ),
                ]);
            });
            bundle.write();
            bundle
        }

        /// Add a Verifier, bound to the root Service, whose agent check runs
        /// an inline Agent with a prompt in the supplied reference form.
        ///
        /// # Panics
        /// Panics if the agent-check fixture cannot be built, rewritten, or
        /// serialized.
        fn with_nested_prompt(&mut self, prompt_ref: CardRef, sibling: bool) -> CardRef {
            use wyrd_spec::verification::TaskId;

            let verifier_ref = test_ref(CardKind::Verifier, "judge", 4);
            let check = Check::Agent(AgentCall {
                agent: InlineableRef::Inline(Box::new(AgentSpec {
                    prompt: if sibling {
                        InlineableRef::Sibling {
                            sibling: prompt_ref,
                        }
                    } else {
                        InlineableRef::Ref(prompt_ref)
                    },
                    execution_route: wyrd_spec::ExecutionRoute::Native {},
                    tool_names: Vec::new(),
                    run_config: AgentRunConfigSpec::default(),
                    verified_by: Vec::new(),
                })),
                inputs: BTreeMap::new(),
                workspace: BTreeMap::new(),
            });
            let verifier = VerifierSpec {
                requirements: vec![Requirement {
                    id: TaskId::new("judge").expect("fixture requirement id is valid"),
                    statement: "The answer follows the policy.".to_owned(),
                    check,
                }],
                ..assert_verifier()
            };
            self.add_card(
                "judge",
                canonical_card(&verifier_ref, CardKind::Verifier, Spec::Verifier(verifier)),
                &[],
            );
            let root_ref = test_ref(CardKind::Service, "service", 1);
            self.rewrite_card(&root_ref, |card| {
                if let Spec::Service(spec) = &mut card.spec {
                    spec.verified_by
                        .push(verification_binding(verifier_ref.clone(), None));
                }
            });
            self.write();
            verifier_ref
        }

        /// Add a Card, aliases, manifest projections, and optional payloads.
        ///
        /// # Panics
        /// Panics if artifact sizes cannot convert to the manifest type.
        fn add_card(&mut self, alias: &str, card: Card, artifacts: &[TestArtifact]) -> CardRef {
            let card_ref = card_ref_from_card(&card);
            let key = card_ref.to_string();
            self.cards.borrow_mut().insert(key.clone(), card);
            let entries = artifacts
                .iter()
                .map(|artifact| {
                    self.artifact_bytes.borrow_mut().insert(
                        (key.clone(), artifact.relative_path.clone()),
                        artifact.bytes.clone(),
                    );
                    BundleArtifactManifest {
                        relative_path: artifact.relative_path.clone(),
                        sha256: digest(&artifact.bytes),
                        size_bytes: i64::try_from(artifact.bytes.len()).expect("fixture size fits"),
                        content_type: artifact.content_type.clone(),
                        local_path: Some(format!(
                            "cards/{alias}/artifacts/{}",
                            artifact.relative_path
                        )),
                    }
                })
                .collect::<Vec<_>>();
            self.manifest.cards.push(BundleCardManifest {
                aliases: vec![alias.to_owned()],
                card_ref: card_ref.clone(),
                card_path: format!("cards/{alias}/card.yaml"),
                relationships_path: format!("cards/{alias}/relationships.yaml"),
                artifact_inventory_path: format!("cards/{alias}/artifacts.yaml"),
                artifacts: entries,
            });
            card_ref
        }

        /// Add another persisted alias for an existing exact `CardRef`.
        ///
        /// # Panics
        /// Panics if the target Card is absent from the fixture manifest.
        fn add_alias(&mut self, alias: &str, target: &CardRef) {
            let entry = self
                .manifest
                .cards
                .iter_mut()
                .find(|entry| entry.card_ref == *target)
                .expect("fixture target exists");
            entry.aliases.push(alias.to_owned());
        }

        /// Materialize all fixture projections, payloads, aliases, and metadata.
        ///
        /// # Panics
        /// Panics if any fixture value is missing or filesystem/YAML writing fails.
        fn write(&self) {
            fs::create_dir_all(self.root.path().join("aliases"))
                .expect("fixture aliases dir writes");
            for entry in &self.manifest.cards {
                let card = self
                    .cards
                    .borrow()
                    .get(&entry.card_ref.to_string())
                    .cloned()
                    .expect("fixture Card exists");
                write_yaml(&self.root.path().join(&entry.card_path), &card);
                write_yaml(
                    &self.root.path().join(&entry.relationships_path),
                    &card.relationships,
                );
                write_yaml(
                    &self.root.path().join(&entry.artifact_inventory_path),
                    &entry.artifacts,
                );
                for artifact in &entry.artifacts {
                    let bytes = self
                        .artifact_bytes
                        .borrow()
                        .get(&(entry.card_ref.to_string(), artifact.relative_path.clone()))
                        .cloned()
                        .expect("fixture artifact bytes exist");
                    let path = self.root.path().join(
                        artifact
                            .local_path
                            .as_ref()
                            .expect("complete fixture artifact path"),
                    );
                    fs::create_dir_all(path.parent().expect("fixture artifact parent writes"))
                        .expect("fixture artifact parent exists");
                    fs::write(path, bytes).expect("fixture artifact writes");
                }
                for alias in &entry.aliases {
                    write_yaml(
                        &self
                            .root
                            .path()
                            .join("aliases")
                            .join(format!("{alias}.yaml")),
                        &serde_json::json!({ "alias": alias, "card_ref": entry.card_ref, "card_path": entry.card_path }),
                    );
                }
            }
            let mut manifest = self.manifest.clone();
            manifest.card_count = manifest.cards.len();
            manifest.artifact_count = manifest
                .cards
                .iter()
                .map(|entry| entry.artifacts.len())
                .sum();
            manifest.downloaded_artifact_count = manifest.artifact_count;
            write_yaml(&self.root.path().join("metadata.yaml"), &manifest);
        }

        /// Return the temporary bundle root used by `WyrdState::from_path`.
        pub(crate) fn path(&self) -> &Path {
            self.root.path()
        }

        /// Mutate and persist the manifest and each affected artifact inventory.
        ///
        /// # Panics
        /// Panics if updated projections cannot be serialized or written.
        fn rewrite_manifest(&mut self, f: impl FnOnce(&mut BundleManifest)) {
            f(&mut self.manifest);
            write_yaml(&self.root.path().join("metadata.yaml"), &self.manifest);
            for entry in &self.manifest.cards {
                write_yaml(
                    &self.root.path().join(&entry.artifact_inventory_path),
                    &entry.artifacts,
                );
            }
        }

        /// Mutate and persist one Card projection while retaining fixture state.
        ///
        /// # Panics
        /// Panics if the Card or manifest entry is absent or serialization fails.
        fn rewrite_card(&self, card_ref: &CardRef, f: impl FnOnce(&mut Card)) {
            let mut cards = self.cards.borrow_mut();
            let card = cards
                .get_mut(&card_ref.to_string())
                .expect("fixture Card exists");
            f(card);
            card.relationships = relationships_from_spec(&card.spec);
            let entry = self
                .manifest
                .cards
                .iter()
                .find(|entry| entry.card_ref == *card_ref)
                .expect("fixture manifest Card exists");
            write_yaml(&self.root.path().join(&entry.card_path), card);
            write_yaml(
                &self.root.path().join(&entry.relationships_path),
                &card.relationships,
            );
        }

        /// Replace one local artifact payload without changing its manifest digest.
        ///
        /// # Panics
        /// Panics if the Card, artifact entry, or local path is absent, or writing fails.
        fn rewrite_artifact(&self, card_ref: &CardRef, relative: &str, bytes: &[u8]) {
            let entry = self
                .manifest
                .cards
                .iter()
                .find(|entry| entry.card_ref == *card_ref)
                .expect("fixture artifact Card exists");
            let artifact = entry
                .artifacts
                .iter()
                .find(|artifact| artifact.relative_path == relative)
                .expect("fixture artifact exists");
            fs::write(
                self.root
                    .path()
                    .join(artifact.local_path.as_ref().expect("fixture artifact path")),
                bytes,
            )
            .expect("fixture artifact rewrite");
        }
    }

    /// The verified artifact inventory the state indexed for `alias`.
    ///
    /// # Panics
    /// Panics when the alias is unknown or has no indexed inventory.
    fn artifacts<'s>(state: &'s WyrdState, alias: &str) -> &'s [HydratedArtifact] {
        let key = state.index.resolve_key(alias).expect("alias resolves");
        state
            .index
            .artifacts_by_key(key)
            .expect("artifacts resolve")
    }

    /// Build a complete Card envelope with identity copied from `card_ref`.
    ///
    /// # Panics
    /// This pure constructor does not panic itself; invalid fixture identities
    /// are rejected by callers when constructing the input `CardRef`.
    fn card(card_ref: &CardRef, kind: CardKind, spec: Spec, relationships: Relationships) -> Card {
        Card {
            api_version: ApiVersion::v1(),
            kind,
            metadata: Metadata {
                name: card_ref.name.clone(),
                version: Some(VersionSpec::Pin(card_ref.version.clone())),
                bump: None,
                space: card_ref.space.clone(),
                uid: card_ref.uid.clone(),
                labels: wyrd_spec::metadata::Labels::default(),
                annotations: wyrd_spec::metadata::Annotations::default(),
                spec_hash: None,
                artifact_hash: None,
                origin: None,
            },
            spec,
            relationships,
            status: None,
        }
    }

    /// Build a fixture Card with the canonical relationship projection derived
    /// from its resolved spec.
    fn canonical_card(card_ref: &CardRef, kind: CardKind, spec: Spec) -> Card {
        let relationships = relationships_from_spec(&spec);
        card(card_ref, kind, spec, relationships)
    }

    /// Build one runtime-owned Service component for a resolved fixture Card.
    fn service_component(alias: &str, card_ref: &CardRef) -> ServiceComponent {
        ServiceComponent {
            alias: alias.to_owned(),
            card_ref: Ref::Ref(card_ref.clone()),
            verified_by: Vec::new(),
            source: None,
            config: BTreeMap::new(),
            credential_refs: Vec::new(),
        }
    }

    /// Build a valid custom Model spec for typed-holder fixtures.
    ///
    /// # Panics
    /// Panics if fixture field names violate identifier grammar.
    fn model_spec() -> ModelSpec {
        ModelSpec {
            interface: ModelInterface::Custom(CustomMeta {
                framework_version: "1".to_owned(),
                model_subtype: None,
                loader_module: "fixture".to_owned(),
                loader_class: "Model".to_owned(),
                extra: BTreeMap::new(),
            }),
            task_type: TaskType::Other,
            signature: ModelSignature::new(
                vec![FieldSpec::new(
                    wyrd_spec::ids::ColumnName::new("input").expect("fixture field is valid"),
                    "float64",
                )],
                vec![FieldSpec::new(
                    wyrd_spec::ids::ColumnName::new("output").expect("fixture field is valid"),
                    "float64",
                )],
            ),
            sample_input: None,
            card_refs: Vec::new(),
        }
    }

    /// Project the exact pinned identity from a fixture Card envelope.
    ///
    /// # Panics
    /// Panics if fixture metadata has no pinned version.
    fn card_ref_from_card(card: &Card) -> CardRef {
        CardRef {
            kind: card.kind.clone(),
            name: card.metadata.name.clone(),
            version: card
                .metadata
                .resolved_pin()
                .cloned()
                .expect("fixture version is pinned"),
            space: card.metadata.space.clone(),
            uid: card.metadata.uid.clone(),
        }
    }

    /// Build a minimal valid native prompt for typed-state fixtures.
    ///
    /// # Panics
    /// Panics if the fixture chat request or prompt violates Skald validation.
    fn prompt(text: &str) -> skald_spec::Prompt {
        let request: OpenAiChatRequest = serde_json::from_value(serde_json::json!({
            "model": "fixture-model",
            "messages": [{ "role": "user", "content": text }]
        }))
        .expect("fixture chat request is valid");
        Prompt::new(
            ProviderRequest::OpenAiChatCompletion(request),
            "fixture-model",
        )
        .expect("fixture prompt is valid")
    }

    /// Build a valid Prompt Card spec for the typed-state fixture.
    ///
    /// # Panics
    /// Panics if the generated prompt fails `PromptSpec` validation.
    fn prompt_spec(text: &str) -> PromptSpec {
        PromptSpec::new(prompt(text)).expect("fixture prompt spec is valid")
    }

    /// Build an Agent spec that resolves its prompt through the fixture graph.
    fn registered_agent_spec(prompt_ref: &CardRef) -> Spec {
        Spec::Agent(AgentSpec {
            prompt: InlineableRef::Ref(prompt_ref.clone()),
            execution_route: wyrd_spec::ExecutionRoute::Native {},
            tool_names: Vec::new(),
            run_config: AgentRunConfigSpec::default(),
            verified_by: Vec::new(),
        })
    }

    /// Build a valid custom Data Card spec without embedding artifact bytes.
    ///
    /// # Panics
    /// This pure constructor does not panic; validation occurs when its Card is loaded.
    fn data_spec() -> DataSpec {
        DataSpec {
            interface: DataInterface::Custom(CustomDataMeta {
                loader_module: "fixture".to_owned(),
                loader_class: "Data".to_owned(),
                extra: BTreeMap::new(),
            }),
            schema: DataSchema::empty(),
            card_refs: Vec::new(),
            splits: std::collections::HashMap::new(),
            target_columns: Vec::new(),
            sql: None,
            stats: DataStats {
                row_count: None,
                col_count: None,
                byte_count: 0,
                sha256: "0".repeat(64),
            },
        }
    }

    /// Build a one-requirement assert Verifier used to prove pure-spec
    /// borrowing.
    ///
    /// # Panics
    /// Panics if the static fixture stops decoding as a Verifier spec.
    fn assert_verifier() -> VerifierSpec {
        serde_json::from_value(serde_json::json!({
            "inputs": {"answer": {"type": "json"}},
            "requirements": [{
                "id": "answered",
                "statement": "The agent produced an answer.",
                "check": {"kind": "assert", "path": "inputs.answer", "operator": "is_not_null"},
            }],
        }))
        .expect("static assert Verifier decodes")
    }

    /// Build a deterministic Custom metric drift Verifier for typed-state
    /// projection tests.
    ///
    /// # Panics
    /// Panics if the static fixture stops decoding as a Verifier spec.
    fn drift_verifier() -> VerifierSpec {
        serde_json::from_value(serde_json::json!({
            "description": "fixture drift",
            "inputs": {"current": {"type": "samples", "features": ["score"]}},
            "requirements": [{
                "id": "score-stable",
                "statement": "The score stays near its baseline.",
                "check": {
                    "kind": "drift",
                    "on": "inputs.current",
                    "method": "Custom",
                    "signal": {"kind": "Metric", "name": "score"},
                    "condition": {"kind": "Statistical"},
                    "profile": {
                        "kind": "Custom",
                        "metric_name": "score",
                        "baseline_value": 0.5,
                        "alert_threshold": 0.1,
                    },
                },
            }],
        }))
        .expect("static drift Verifier decodes")
    }

    /// Build a binding that attaches `verifier`, with an inline Trigger
    /// activation when one is given and explicit-only otherwise.
    ///
    /// # Panics
    /// This pure constructor does not panic.
    fn verification_binding(
        verifier: CardRef,
        activation: Option<TriggerActivation>,
    ) -> VerificationBinding {
        VerificationBinding {
            verifier: Ref::Ref(verifier),
            runs_on: activation.map(|activation| {
                InlineableRef::Inline(Box::new(TriggerSpec {
                    description: None,
                    activation,
                }))
            }),
            on_failure: Vec::new(),
            on_verdict_change: Vec::new(),
        }
    }

    /// Build a deterministic UID-bearing exact `CardRef` for fixture identities.
    ///
    /// # Panics
    /// Panics if generated identifiers violate their grammar.
    fn test_ref(kind: CardKind, name: &str, uid_suffix: u8) -> CardRef {
        let uid = format!("01890f28-7c4a-7cc3-98e7-4f4a3c2d1b{uid_suffix:02x}");
        CardRef {
            kind,
            name: CardName::new(name).expect("fixture name is valid"),
            version: VersionBlock::parse("1.0.0").expect("fixture version is valid"),
            space: Some(SpaceName::new("default").expect("fixture space is valid")),
            uid: Some(CardUid::new(uid).expect("fixture UID is valid")),
        }
    }

    /// Compute the base64-encoded SHA-256 digest stored in artifact manifests.
    fn digest(bytes: &[u8]) -> String {
        base64::engine::general_purpose::STANDARD.encode(Sha256::digest(bytes))
    }

    /// Serialize a fixture projection as YAML, creating its parent directory.
    ///
    /// # Panics
    /// Panics if the path has no parent, serialization fails, or filesystem I/O fails.
    fn write_yaml<T: Serialize>(path: &Path, value: &T) {
        fs::create_dir_all(path.parent().expect("fixture YAML path has parent"))
            .expect("fixture YAML parent exists");
        fs::write(
            path,
            serde_yaml::to_string(value).expect("fixture YAML serializes"),
        )
        .expect("fixture YAML writes");
    }

    /// Extract the structured details object from a public Wyrd error.
    fn problem_details(error: &WyrdError) -> Value {
        error.as_problem_json()["details"].clone()
    }

    /// Assert a state-construction failure has the expected stable code/detail.
    ///
    /// # Panics
    /// Panics if construction succeeds, the code differs, or the detail field is absent.
    fn assert_error(result: Result<WyrdState, WyrdError>, code: &str, field: &str) {
        let error = result.expect_err("bundle fixture must be rejected");
        assert_eq!(error.code(), code);
        assert!(
            !problem_details(&error)[field].is_null(),
            "missing detail field {field}: {}",
            problem_details(&error)
        );
    }

    /// Assert that a rejected bundle's recovery prescribes a complete pull into
    /// an explicit directory, never the envelope-only `get`.
    ///
    /// # Panics
    /// Panics if the bundle loads or the remediation names another recovery.
    fn assert_pull_recovery(result: Result<WyrdState, WyrdError>) {
        let error = result.expect_err("bundle fixture must be rejected");
        let remediation = error.remediation();
        assert!(
            remediation.contains("wyrd pull")
                && remediation.contains("--output-dir")
                && !remediation.contains("wyrd get"),
            "{remediation}"
        );
    }

    /// Assert the stable error shape used when durable state contains a sibling.
    fn assert_sibling_error(result: Result<WyrdState, WyrdError>, expected_ref: &CardRef) {
        let error = result.expect_err("sibling reference must be rejected");
        assert_eq!(error.code(), "WYRD_SDK_400_INVALID_STATE_BUNDLE");
        let details = problem_details(&error);
        assert!(!details["owner"].is_null(), "owner detail is required");
        assert_eq!(details["card_ref"], serde_json::json!(expected_ref));
        assert_eq!(details["reference_form"], "sibling");
    }

    #[test]
    /// Loads a complete hydrated Service graph locally and resolves its root and model aliases.
    ///
    /// # Panics
    /// Panics if the complete fixture cannot load or an expected alias/card assertion fails.
    fn loads_complete_service_graph_without_network() {
        let bundle = TestBundle::complete_service();
        let state = WyrdState::from_path(bundle.path()).expect("complete graph loads");
        assert_eq!(state.root_ref().kind, CardKind::Service);
        assert_eq!(state.service().kind, CardKind::Service);
        assert_eq!(
            state.card("model").expect("model alias resolves").kind,
            CardKind::Model
        );
    }

    #[test]
    /// Rejects a locally valid Card that is not reachable from the Service root.
    ///
    /// # Panics
    /// Panics if fixture construction fails or root-closure validation accepts
    /// an orphaned Card.
    fn rejects_orphaned_card_outside_root_closure() {
        let mut bundle = TestBundle::complete_service();
        let orphan_ref = test_ref(CardKind::Model, "orphan", 9);
        bundle.add_card(
            "orphan",
            card(
                &orphan_ref,
                CardKind::Model,
                Spec::Model(model_spec()),
                Relationships::default(),
            ),
            &[],
        );
        bundle.write();

        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "unreachable",
        );
    }

    /// Prove every runtime-relevant typed accessor returns its native Rust
    /// projection while Verifier specs remain borrowed envelope specs.
    ///
    /// # Panics
    /// Panics if typed-card loading, alias resolution, or projection assertions fail.
    #[test]
    fn typed_accessors_return_native_rust_cards() {
        let bundle = TestBundle::with_typed_cards();
        let state = WyrdState::from_path(bundle.path()).expect("typed graph loads");
        assert_eq!(state.model("model").expect("model resolves").name, "model");
        assert_eq!(
            state.data("training_data").expect("data resolves").name,
            "training"
        );
        assert_eq!(
            state
                .agent("agent_triage")
                .expect("agent resolves")
                .card()
                .name,
            "triage"
        );
        assert_eq!(
            state.prompt("triage_prompt").expect("prompt resolves").name,
            "triage"
        );
        assert_eq!(
            state
                .verifier("quality_check")
                .expect("assert verifier resolves"),
            &assert_verifier()
        );
        let drift = state
            .verifier("model_drift")
            .expect("drift verifier resolves");
        assert_eq!(drift.description.as_deref(), Some("fixture drift"));
        assert!(matches!(
            drift.requirements.as_slice(),
            [requirement] if matches!(requirement.check, Check::Drift(_))
        ));
    }

    /// Prove two exact Model Card identities retain distinct native holders.
    ///
    /// # Panics
    /// Panics if the fixture cannot load, either alias is absent, or identity assertions fail.
    #[test]
    fn two_model_aliases_return_distinct_holders() {
        let bundle = TestBundle::complete_service();
        let state = WyrdState::from_path(bundle.path()).expect("typed graph loads");
        let primary = state.model("model").expect("primary model resolves");
        let backup = state.model("backup").expect("backup model resolves");
        assert!(!std::ptr::eq(primary, backup));
        assert_eq!(primary.uid, "01890f28-7c4a-7cc3-98e7-4f4a3c2d1b02");
        assert_eq!(backup.uid, "01890f28-7c4a-7cc3-98e7-4f4a3c2d1b03");
    }

    /// Prove duplicate aliases for one Prompt Card share one stored holder.
    ///
    /// # Panics
    /// Panics if the fixture cannot be rewritten or either prompt alias fails to resolve.
    #[test]
    fn duplicate_prompt_aliases_return_same_holder_address() {
        let mut bundle = TestBundle::with_typed_cards();
        let target = test_ref(CardKind::Prompt, "triage", 4);
        bundle.add_alias("triage_prompt_alt", &target);
        bundle.write();
        let state = WyrdState::from_path(bundle.path()).expect("typed graph loads");
        assert!(std::ptr::eq(
            state.prompt("triage_prompt").expect("prompt resolves"),
            state
                .prompt("triage_prompt_alt")
                .expect("prompt alias resolves")
        ));
    }

    /// Prove an old bundle whose Agent Prompt is still inline, and so has no
    /// registered Prompt Card identity, is refused as an invalid bundle rather
    /// than given a fabricated identity.
    ///
    /// # Panics
    /// Panics if the inline-only fixture loads or fails with another code.
    #[test]
    fn agent_with_inline_prompt_is_an_invalid_bundle() {
        let bundle = TestBundle::with_typed_cards();
        let agent_ref = test_ref(CardKind::Agent, "triage", 6);
        bundle.rewrite_card(&agent_ref, |card| {
            if let Spec::Agent(spec) = &mut card.spec {
                spec.prompt = InlineableRef::Inline(Box::new(prompt("inline")));
            }
        });
        bundle.write();
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "card_ref_key",
        );
    }

    /// Prove a hydrated Agent navigates to the same Prompt Card holder its
    /// explicit alias returns, and exposes the exact reference it pins.
    ///
    /// # Panics
    /// Panics if the fixture cannot load or the navigation differs.
    #[test]
    fn agent_prompt_returns_the_aliased_prompt_card() {
        let bundle = TestBundle::with_typed_cards();
        let state = WyrdState::from_path(bundle.path()).expect("typed graph loads");
        let agent = state.agent("agent_triage").expect("agent resolves");
        assert!(std::ptr::eq(
            agent.prompt(),
            state.prompt("triage_prompt").expect("prompt resolves")
        ));
        assert_eq!(
            agent.prompt_ref(),
            state
                .card_ref("triage_prompt")
                .expect("prompt ref resolves")
        );
    }

    /// Prove generic lookup returns each kind's typed holder, the envelope for
    /// kinds without one, and the strict unknown-alias refusal.
    ///
    /// # Panics
    /// Panics if the fixture cannot load or a lookup returns another variant.
    #[test]
    fn get_returns_the_kind_appropriate_hydrated_card() {
        let bundle = TestBundle::with_typed_cards();
        let state = WyrdState::from_path(bundle.path()).expect("typed graph loads");
        let Ok(HydratedCard::Agent(agent)) = state.get("agent_triage") else {
            panic!("agent alias returns an Agent");
        };
        assert!(std::ptr::eq(
            agent.prompt(),
            state.prompt("triage_prompt").expect("prompt resolves")
        ));
        assert!(matches!(
            state.get("triage_prompt"),
            Ok(HydratedCard::Prompt(_))
        ));
        assert!(matches!(state.get("model"), Ok(HydratedCard::Model(_))));
        assert!(matches!(
            state.get("training_data"),
            Ok(HydratedCard::Data(_))
        ));
        assert!(matches!(
            state.get("quality_check"),
            Ok(HydratedCard::Envelope(card)) if card.kind == CardKind::Verifier
        ));
        let Err(unknown) = state.get("missing") else {
            panic!("unknown alias is refused");
        };
        assert_eq!(unknown.code(), "WYRD_SDK_404_UNKNOWN_ALIAS");
        let Err(mismatch) = state.agent("triage_prompt") else {
            panic!("typed mismatch is refused");
        };
        assert_eq!(mismatch.code(), "WYRD_SDK_400_CARD_KIND_MISMATCH");
    }

    /// Prove an Agent prompt target absent from the validated graph fails as an
    /// invalid bundle instead of becoming an unknown runtime alias.
    ///
    /// # Panics
    /// Panics if the malformed fixture is accepted or the expected error details are absent.
    #[test]
    fn agent_prompt_rejects_missing_target() {
        let bundle = TestBundle::with_typed_cards();
        let agent_ref = test_ref(CardKind::Agent, "triage", 6);
        let missing = test_ref(CardKind::Prompt, "missing", 11);
        bundle.rewrite_card(&agent_ref, |card| {
            if let Spec::Agent(spec) = &mut card.spec {
                spec.prompt = InlineableRef::Ref(missing);
            }
        });
        bundle.write();
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "owner",
        );
    }

    /// Prove an Agent prompt target with another kind fails closed at bundle
    /// load rather than being coerced into a Prompt holder.
    ///
    /// # Panics
    /// Panics if the wrong-kind fixture loads or fails with another code.
    #[test]
    fn agent_prompt_rejects_non_prompt_target() {
        let bundle = TestBundle::with_typed_cards();
        let agent_ref = test_ref(CardKind::Agent, "triage", 6);
        let model_ref = test_ref(CardKind::Model, "model", 2);
        bundle.rewrite_card(&agent_ref, |card| {
            if let Spec::Agent(spec) = &mut card.spec {
                spec.prompt = InlineableRef::Ref(model_ref);
            }
        });
        bundle.write();
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "card_ref",
        );
    }

    /// Prove native holders retain only declarative metadata while verified
    /// model and data payloads remain available through state artifact paths.
    ///
    /// # Panics
    /// Panics if artifact setup, state loading, file reads, or holder metadata assertions fail.
    #[test]
    fn model_and_data_artifacts_remain_external_to_holders() {
        let mut bundle = TestBundle::with_artifact();
        let data_ref = test_ref(CardKind::Data, "training", 12);
        let data_artifact = TestArtifact {
            relative_path: "training.bin".to_owned(),
            bytes: b"training".to_vec(),
            content_type: Some("application/octet-stream".to_owned()),
        };
        bundle.add_card(
            "training",
            card(
                &data_ref,
                CardKind::Data,
                Spec::Data(data_spec()),
                Relationships::default(),
            ),
            &[data_artifact],
        );
        let root_ref = test_ref(CardKind::Service, "service", 1);
        bundle.rewrite_card(&root_ref, |card| {
            if let Spec::Service(spec) = &mut card.spec {
                spec.components.push(ServiceComponent {
                    alias: "training".to_owned(),
                    card_ref: Ref::Ref(data_ref.clone()),
                    verified_by: Vec::new(),
                    source: None,
                    config: BTreeMap::new(),
                    credential_refs: Vec::new(),
                });
            }
        });
        bundle.write();
        let state = WyrdState::from_path(bundle.path()).expect("artifact graph loads");
        let model_artifact = &artifacts(&state, "model")[0];
        let data_artifact = &artifacts(&state, "training")[0];
        assert_eq!(
            fs::read(&model_artifact.local_path).expect("model bytes read"),
            b"weights"
        );
        assert_eq!(
            fs::read(&data_artifact.local_path).expect("data bytes read"),
            b"training"
        );
        assert_eq!(
            state
                .model("model")
                .expect("model holder resolves")
                .metadata
                .card_refs
                .len(),
            0
        );
        assert_eq!(
            state
                .data("training")
                .expect("data holder resolves")
                .metadata
                .stats
                .byte_count,
            0
        );
    }

    /// Prove every typed accessor reports the requested and actual kinds.
    ///
    /// # Panics
    /// Panics if the fixture cannot load or any wrong-kind lookup is unexpectedly accepted.
    #[test]
    fn each_typed_accessor_reports_expected_and_actual_kind() {
        let bundle = TestBundle::with_typed_cards();
        let state = WyrdState::from_path(bundle.path()).expect("typed graph loads");
        macro_rules! assert_wrong_kind {
            ($lookup:expr) => {{
                let Err(error) = $lookup else {
                    panic!("wrong-kind lookup must fail");
                };
                assert_eq!(error.code(), "WYRD_SDK_400_CARD_KIND_MISMATCH");
                let details = problem_details(&error);
                assert!(!details["expected_kind"].is_null());
                assert!(!details["actual_kind"].is_null());
                assert!(!details["card_ref"].is_null());
            }};
        }
        assert_wrong_kind!(state.agent("model"));
        assert_wrong_kind!(state.prompt("model"));
        assert_wrong_kind!(state.model("agent_triage"));
        assert_wrong_kind!(state.data("agent_triage"));
        assert_wrong_kind!(state.verifier("agent_triage"));
    }

    /// Prove generic Card access remains available for unprojected kinds.
    ///
    /// # Panics
    /// Panics if the typed fixture cannot load or either generic Card assertion fails.
    #[test]
    fn generic_card_supports_unprojected_kinds() {
        let bundle = TestBundle::with_typed_cards();
        let state = WyrdState::from_path(bundle.path()).expect("typed graph loads");
        assert_eq!(
            state.card("quality_check").expect("verifier card").kind,
            CardKind::Verifier
        );
        assert_eq!(
            state.card("model_drift").expect("drift card").kind,
            CardKind::Verifier
        );
    }

    #[test]
    /// Confirms aliases for one Card resolve the same stored envelope address.
    ///
    /// # Panics
    /// Panics if alias fixture setup, state loading, or pointer identity checks fail.
    fn aliases_for_same_card_resolve_same_address() {
        let mut bundle = TestBundle::complete_service();
        let target = test_ref(CardKind::Model, "model", 2);
        bundle.add_alias("model-alt", &target);
        bundle.write();
        let state = WyrdState::from_path(bundle.path()).expect("complete graph loads");
        assert!(std::ptr::eq(
            state.card("model").expect("model resolves"),
            state.card("model-alt").expect("alias resolves")
        ));
    }

    #[test]
    /// Confirms persisted aliases are returned in deterministic lexical order.
    ///
    /// # Panics
    /// Panics if the fixture cannot load or the sorted alias list differs from the contract.
    fn aliases_are_stably_sorted() {
        let mut bundle = TestBundle::complete_service();
        bundle.add_alias("aaa", &test_ref(CardKind::Model, "model", 2));
        bundle.add_alias("zzz", &test_ref(CardKind::Model, "model", 2));
        bundle.write();
        let state = WyrdState::from_path(bundle.path()).expect("complete graph loads");
        assert_eq!(
            state.aliases().collect::<Vec<_>>(),
            vec!["aaa", "backup", "model", "root", "zzz"]
        );
    }

    #[test]
    /// Rejects a path without hydrated metadata using the stable unhydrated error.
    ///
    /// # Panics
    /// Panics if the temporary fixture cannot be created or the expected rejection is absent.
    fn rejects_missing_manifest_as_unhydrated() {
        let bundle = tempdir().expect("test tempdir is available");
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_UNHYDRATED_ARTIFACT",
            "path",
        );
    }

    #[test]
    /// Rejects metadata-only bundles because `WyrdState` requires complete
    /// hydration, and prescribes a complete pull as the recovery.
    ///
    /// # Panics
    /// Panics if fixture rewriting fails, the expected unhydrated error is not
    /// returned, or its remediation does not prescribe a complete pull.
    fn rejects_metadata_only_bundle_as_unhydrated() {
        let mut bundle = TestBundle::complete_service();
        bundle.rewrite_manifest(|manifest| manifest.mode = BundleMode::MetadataOnly);
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_UNHYDRATED_ARTIFACT",
            "path",
        );
        assert_pull_recovery(WyrdState::from_path(bundle.path()));
    }

    #[test]
    /// Rejects the retired `wyrd/hydrated-bundle/v1` header: no compatibility
    /// reader exists, and the recovery is a fresh complete pull.
    ///
    /// # Panics
    /// Panics if fixture rewriting fails, the retired header is accepted, or
    /// the remediation does not prescribe a complete pull.
    fn rejects_retired_bundle_api_version() {
        let mut bundle = TestBundle::complete_service();
        bundle.rewrite_manifest(|manifest| {
            manifest.api_version = "wyrd/hydrated-bundle/v1".to_owned();
        });
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "api_version",
        );
        assert_pull_recovery(WyrdState::from_path(bundle.path()));
    }

    #[test]
    /// Rejects manifests whose declared Card count disagrees with their contents.
    ///
    /// # Panics
    /// Panics if fixture mutation fails or count validation does not return the expected error.
    fn rejects_inconsistent_manifest_counts() {
        let mut bundle = TestBundle::complete_service();
        bundle.rewrite_manifest(|manifest| manifest.card_count += 1);
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "card_count",
        );
    }

    #[test]
    /// Rejects a Card bundle whose manifest root is not a Service Card.
    ///
    /// # Panics
    /// Panics if fixture mutation fails or root-kind validation accepts the malformed bundle.
    fn rejects_non_service_root() {
        let mut bundle = TestBundle::complete_service();
        bundle.rewrite_manifest(|manifest| manifest.root.kind = CardKind::Model);
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "root",
        );
    }

    #[test]
    /// Rejects a manifest root whose identity differs from the loaded root Card.
    ///
    /// # Panics
    /// Panics if fixture mutation fails or identity validation returns no error.
    fn rejects_root_manifest_identity_mismatch() {
        let mut bundle = TestBundle::complete_service();
        bundle.rewrite_manifest(|manifest| {
            manifest.root.name = CardName::new("other").expect("fixture name is valid");
        });
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "root",
        );
    }

    #[test]
    /// Rejects a root `CardRef` without the UID required for hydrated identity.
    ///
    /// # Panics
    /// Panics if fixture mutation fails or UID validation accepts the malformed root.
    fn rejects_root_without_uid() {
        let mut bundle = TestBundle::complete_service();
        bundle.rewrite_manifest(|manifest| manifest.root.uid = None);
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "root",
        );
    }

    #[test]
    /// Rejects a child Card that omits its durable UID.
    ///
    /// # Panics
    /// Panics if fixture mutation fails or child identity validation accepts the missing UID.
    fn rejects_child_without_uid() {
        let bundle = TestBundle::complete_service();
        let child = test_ref(CardKind::Model, "model", 2);
        bundle.rewrite_card(&child, |card| card.metadata.uid = None);
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "path",
        );
    }

    #[test]
    /// Rejects a manifest `CardRef` that does not match its persisted Card envelope.
    ///
    /// # Panics
    /// Panics if fixture mutation fails or manifest identity validation misses the mismatch.
    fn rejects_manifest_card_identity_mismatch() {
        let mut bundle = TestBundle::complete_service();
        bundle.rewrite_manifest(|manifest| {
            manifest.cards[1].card_ref.name =
                CardName::new("other").expect("fixture name is valid");
        });
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "manifest_card_ref",
        );
    }

    #[test]
    /// Rejects duplicate exact `CardRef`s rather than silently replacing a loaded Card.
    ///
    /// # Panics
    /// Panics if fixture assumptions fail or duplicate-identity validation accepts the bundle.
    fn rejects_duplicate_exact_card_ref() {
        let mut bundle = TestBundle::complete_service();
        let model = test_ref(CardKind::Model, "model", 2);
        let duplicate = bundle
            .cards
            .borrow()
            .get(&model.to_string())
            .cloned()
            .expect("fixture model exists");
        bundle.cards.borrow_mut().insert(
            test_ref(CardKind::Model, "backup", 3).to_string(),
            duplicate,
        );
        bundle.manifest.cards[2].card_ref = model.clone();
        bundle.manifest.cards[2].aliases = vec!["backup".to_owned()];
        bundle.write();
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "card_ref",
        );
    }

    #[test]
    /// Rejects an alias that points to a different Card than its existing projection.
    ///
    /// # Panics
    /// Panics if alias fixture setup fails or conflicting-alias validation is bypassed.
    fn rejects_conflicting_alias() {
        let mut bundle = TestBundle::complete_service();
        bundle.add_alias("model", &test_ref(CardKind::Model, "backup", 3));
        bundle.write();
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "alias",
        );
    }

    #[test]
    /// Rejects an alias projection whose `CardRef` disagrees with the manifest index.
    ///
    /// # Panics
    /// Panics if fixture writing fails or projection validation accepts the mismatch.
    fn rejects_alias_projection_mismatch() {
        let bundle = TestBundle::complete_service();
        write_yaml(
            &bundle.path().join("aliases/model.yaml"),
            &serde_json::json!({ "alias": "model", "card_ref": test_ref(CardKind::Model, "backup", 3), "card_path": "cards/model/card.yaml" }),
        );
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "alias",
        );
    }

    #[test]
    /// Rejects a relationship projection that differs from the Card envelope.
    ///
    /// # Panics
    /// Panics if fixture writing fails or relationship projection validation misses the mismatch.
    fn rejects_relationship_projection_mismatch() {
        let bundle = TestBundle::complete_service();
        write_yaml(
            &bundle.path().join("cards/root/relationships.yaml"),
            &Relationships::default(),
        );
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "relationships_path",
        );
    }

    #[test]
    /// Rejects an artifact inventory projection that omits the manifest entries.
    ///
    /// # Panics
    /// Panics if fixture writing fails or inventory validation accepts the mismatch.
    fn rejects_artifact_inventory_projection_mismatch() {
        let bundle = TestBundle::with_artifact();
        write_yaml(
            &bundle.path().join("cards/model/artifacts.yaml"),
            &Vec::<BundleArtifactManifest>::new(),
        );
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "inventory_path",
        );
    }

    #[test]
    /// Rejects a relationship that targets a Card absent from the loaded graph.
    ///
    /// # Panics
    /// Panics if fixture mutation or projection writing fails, or the missing target is accepted.
    fn rejects_missing_relationship_target() {
        let bundle = TestBundle::complete_service();
        let child = test_ref(CardKind::Model, "model", 2);
        bundle.rewrite_card(&test_ref(CardKind::Service, "service", 1), |card| {
            let Spec::Service(spec) = &mut card.spec else {
                panic!("fixture root is a Service");
            };
            spec.components[0].card_ref = Ref::Ref(CardRef {
                name: CardName::new("missing").expect("fixture name is valid"),
                ..child
            });
        });
        bundle.write();
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "card_ref",
        );
    }

    #[test]
    /// Rejects authored nested path references that should have been hydrated to `CardRef`s.
    ///
    /// # Panics
    /// Panics if fixture mutation fails or unresolved-path validation accepts the bundle.
    fn rejects_unresolved_nested_path_reference() {
        let bundle = TestBundle::complete_service();
        bundle.rewrite_card(&test_ref(CardKind::Service, "service", 1), |card| {
            if let Spec::Service(spec) = &mut card.spec {
                spec.components[0].card_ref = Ref::Path(PathBuf::from("nested/model.yaml"));
            }
        });
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "path",
        );
    }

    /// Reject a registration-only sibling in a top-level Service component.
    ///
    /// # Panics
    /// Panics if sibling validation does not return the expected structured rejection.
    #[test]
    fn rejects_top_level_sibling_reference() {
        let bundle = TestBundle::complete_service();
        let sibling = test_ref(CardKind::Model, "model", 2);
        bundle.rewrite_card(&test_ref(CardKind::Service, "service", 1), |card| {
            if let Spec::Service(spec) = &mut card.spec {
                spec.components[0].card_ref = Ref::Sibling {
                    sibling: sibling.clone(),
                };
            }
        });

        assert_sibling_error(WyrdState::from_path(bundle.path()), &sibling);
    }

    /// Reject a sibling in the prompt slot of a nested inline Agent.
    ///
    /// # Panics
    /// Panics if nested sibling validation does not return the expected structured rejection.
    #[test]
    fn rejects_nested_inline_agent_prompt_sibling_reference() {
        let sibling = test_ref(CardKind::Model, "model", 2);
        let mut bundle = TestBundle::complete_service();
        bundle.with_nested_prompt(sibling.clone(), true);

        assert_sibling_error(WyrdState::from_path(bundle.path()), &sibling);
    }

    /// Load the nested inline Agent when its prompt uses a durable reference.
    ///
    /// # Panics
    /// Panics if the durable nested reference cannot load or resolve to the judge Verifier Card.
    #[test]
    fn loads_nested_inline_agent_prompt_durable_reference() {
        let target = test_ref(CardKind::Model, "model", 2);
        let mut bundle = TestBundle::complete_service();
        let verifier_ref = bundle.with_nested_prompt(target, false);
        let state = WyrdState::from_path(bundle.path()).expect("durable nested ref loads");

        assert_eq!(
            state.card_ref("judge").expect("judge Verifier resolves"),
            &verifier_ref
        );
    }

    #[test]
    /// Rejects a durable spec reference that is not represented in the hydrated graph.
    ///
    /// # Panics
    /// Panics if fixture mutation fails or graph-closure validation accepts the absent reference.
    fn rejects_spec_ref_absent_from_graph() {
        let bundle = TestBundle::complete_service();
        bundle.rewrite_card(&test_ref(CardKind::Service, "service", 1), |card| {
            if let Spec::Service(spec) = &mut card.spec {
                spec.components[0].card_ref = Ref::Ref(test_ref(CardKind::Model, "missing", 4));
            }
        });
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "owner",
        );
    }

    #[test]
    /// Rejects manifest Card paths that escape the Card bundle root.
    ///
    /// # Panics
    /// Panics if fixture mutation fails or path confinement accepts the escaping path.
    fn rejects_escaping_manifest_path() {
        let mut bundle = TestBundle::complete_service();
        bundle.rewrite_manifest(|manifest| manifest.cards[0].card_path = "../card.yaml".to_owned());
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "path",
        );
    }

    #[test]
    /// Rejects aliases containing path traversal components.
    ///
    /// # Panics
    /// Panics if fixture mutation fails or alias confinement accepts the unsafe alias.
    fn rejects_unsafe_alias() {
        let mut bundle = TestBundle::complete_service();
        bundle
            .rewrite_manifest(|manifest| manifest.cards[1].aliases = vec!["../escape".to_owned()]);
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "alias",
        );
    }

    #[test]
    /// Rejects an artifact manifest whose local payload is missing.
    ///
    /// # Panics
    /// Panics if fixture deletion fails or payload validation accepts the missing file.
    fn rejects_missing_artifact_payload() {
        let bundle = TestBundle::with_artifact();
        fs::remove_file(bundle.path().join("cards/model/artifacts/weights.bin"))
            .expect("fixture payload exists");
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "path",
        );
    }

    #[test]
    /// Rejects an artifact path that resolves to a directory instead of a regular file.
    ///
    /// # Panics
    /// Panics if fixture replacement fails or payload validation accepts the directory.
    fn rejects_non_file_artifact_payload() {
        let bundle = TestBundle::with_artifact();
        fs::remove_file(bundle.path().join("cards/model/artifacts/weights.bin"))
            .expect("fixture payload exists");
        fs::create_dir(bundle.path().join("cards/model/artifacts/weights.bin"))
            .expect("fixture directory creates");
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "path",
        );
    }

    #[cfg(unix)]
    #[test]
    /// Rejects an artifact symlink that escapes the bundle root.
    ///
    /// # Panics
    /// Panics if symlink setup fails or path confinement accepts the external target.
    fn rejects_symlinked_artifact_escape() {
        let bundle = TestBundle::with_artifact();
        let payload = bundle.path().join("cards/model/artifacts/weights.bin");
        fs::remove_file(&payload).expect("fixture payload exists");
        std::os::unix::fs::symlink("/etc/hosts", payload).expect("fixture symlink creates");
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "path",
        );
    }

    #[cfg(not(unix))]
    #[test]
    /// Keeps the artifact symlink regression test portable on non-Unix systems.
    ///
    /// # Panics
    /// This no-op has no panic path.
    fn rejects_symlinked_artifact_escape() {}

    /// Reject a metadata manifest symlink whose target is outside the bundle.
    ///
    /// The stable invalid-bundle error must retain the manifest path detail so
    /// callers can identify the rejected projection without exposing the
    /// external target path.
    ///
    /// # Panics
    /// Panics if symlink setup fails or metadata path confinement accepts the external target.
    #[cfg(unix)]
    #[test]
    fn rejects_external_metadata_symlink() {
        let bundle = TestBundle::complete_service();
        let external = tempdir().expect("external fixture tempdir is available");
        let target = external.path().join("metadata.yaml");
        fs::write(&target, "apiVersion: wyrd/bundle/v1\n")
            .expect("external metadata fixture writes");
        fs::remove_file(bundle.path().join("metadata.yaml"))
            .expect("bundle metadata fixture exists");
        std::os::unix::fs::symlink(&target, bundle.path().join("metadata.yaml"))
            .expect("external metadata symlink creates");

        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "path",
        );
    }

    /// Keep the Unix-only metadata symlink regression test portable.
    ///
    /// # Panics
    /// This no-op has no panic path.
    #[cfg(not(unix))]
    #[test]
    fn rejects_external_metadata_symlink() {}

    #[test]
    /// Rejects an artifact manifest whose expected size differs from the local payload.
    ///
    /// # Panics
    /// Panics if fixture mutation fails or size verification accepts the mismatch.
    fn rejects_artifact_size_mismatch() {
        let mut bundle = TestBundle::with_artifact();
        bundle.rewrite_manifest(|manifest| manifest.cards[1].artifacts[0].size_bytes += 1);
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "expected_size",
        );
    }

    #[test]
    /// Rejects an artifact whose SHA-256 digest differs from its manifest digest.
    ///
    /// # Panics
    /// Panics if fixture mutation fails or digest verification accepts the mismatch.
    fn rejects_artifact_digest_mismatch() {
        let bundle = TestBundle::with_artifact();
        bundle.rewrite_artifact(
            &test_ref(CardKind::Model, "model", 2),
            "weights.bin",
            b"corrupt",
        );
        assert_error(
            WyrdState::from_path(bundle.path()),
            "WYRD_SDK_400_INVALID_STATE_BUNDLE",
            "expected_sha256",
        );
    }

    #[test]
    /// Reports a stable unknown-alias error including the available graph aliases.
    ///
    /// # Panics
    /// Panics if the graph cannot load or the unknown-alias details differ from the contract.
    fn unknown_alias_lists_available_aliases() {
        let bundle = TestBundle::complete_service();
        let state = WyrdState::from_path(bundle.path()).expect("complete graph loads");
        let error = state.card("missing").expect_err("unknown alias rejects");
        assert_eq!(error.code(), "WYRD_SDK_404_UNKNOWN_ALIAS");
        assert_eq!(
            problem_details(&error)["available_aliases"],
            serde_json::json!(["backup", "model", "root"])
        );
    }

    #[test]
    /// Confirms artifact paths are absolute, bundle-confined, and content-verified.
    ///
    /// # Panics
    /// Panics if artifact loading, canonicalization, or path and metadata assertions fail.
    fn artifact_paths_are_absolute_confined_and_verified() {
        let bundle = TestBundle::with_artifact();
        let state = WyrdState::from_path(bundle.path()).expect("complete artifact graph loads");
        let artifact = &artifacts(&state, "model")[0];
        assert!(artifact.local_path.is_absolute());
        assert!(
            artifact
                .local_path
                .starts_with(fs::canonicalize(bundle.path()).expect("fixture root canonicalizes"))
        );
        assert_eq!(artifact.size_bytes, 7);
        assert_eq!(
            artifact.content_type.as_deref(),
            Some("application/octet-stream")
        );
        assert_eq!(
            state
                .artifact_dir("model")
                .expect("artifact dir resolves")
                .expect("artifact dir exists"),
            artifact
                .local_path
                .parent()
                .expect("artifact parent exists")
        );
    }

    /// A provider failure is primary and keeps the drain's code as secondary
    /// detail; a provider success passes the drain's own result through.
    ///
    /// # Panics
    ///
    /// Panics when a settlement that must fail succeeds, when a failed
    /// settlement is not the expected timeout or failure variant, or when a
    /// code, `native_code` detail, or passed-through drain result differs.
    #[test]
    fn telemetry_flush_failure_settles_with_the_native_drain() {
        use super::TelemetryFlushFailure;

        let native = WyrdError::SdkBifrostClosed {
            message: "closed".to_owned(),
            details: serde_json::json!({}),
        };
        let both = TelemetryFlushFailure::settle(
            Some(TelemetryFlushFailure::timeout("force_flush returned false")),
            Err(native.clone()),
        )
        .expect_err("telemetry timeout must fail");
        assert_eq!(both.code(), "WYRD_SDK_504_TELEMETRY_FLUSH_TIMEOUT");
        let WyrdError::SdkTelemetryFlushTimeout { details, .. } = &both else {
            panic!("expected the timeout variant, got {both:?}");
        };
        assert_eq!(details["native_code"], "WYRD_SDK_409_BIFROST_CLOSED");

        let only = TelemetryFlushFailure::settle(
            Some(TelemetryFlushFailure::failed("ValueError")),
            Ok(()),
        )
        .expect_err("telemetry failure must fail");
        assert_eq!(only.code(), "WYRD_SDK_503_TELEMETRY_FLUSH_FAILED");
        let WyrdError::SdkTelemetryFlushFailed { details, .. } = &only else {
            panic!("expected the failure variant, got {only:?}");
        };
        assert!(details["native_code"].is_null());

        let native_only =
            TelemetryFlushFailure::settle(None, Err(native)).expect_err("drain failure");
        assert_eq!(native_only.code(), "WYRD_SDK_409_BIFROST_CLOSED");
        assert!(TelemetryFlushFailure::settle(None, Ok(())).is_ok());
    }
}