rust_widgets 2.8.7

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! The designer's view of a capability, as JSON.
//!
//! # What this is for
//!
//! A designer that lets a user pick a control, see what it can do and wire an event to a property
//! needs the capability table in a form it can **save and reload**. That means JSON, and it means
//! the JSON has to be *round-trippable*: what is written to a file must come back as the same
//! description, or every reopening of a project silently loses information.
//!
//! [`capability_manifest_json`] writes that document; [`DesignerManifest::from_json`] reads it
//! back. The pair is asserted by `tools/check_designer_manifest_roundtrip.py`, which exports,
//! re-loads through the parser here, exports again, and requires the two strings to be
//! **byte-identical** — and requires the sentinels to be present, so two empty documents cannot
//! satisfy it.
//!
//! # Why the serialisation is written by hand
//!
//! `serde` is a device-profile feature (`desktop`/`tablet`/`mobile`), not a universal one: it is
//! absent from both `mini` and `embedded`. Deriving `Serialize` on the capability types would
//! therefore make the capability layer's shape depend on the profile, and the alternative — a
//! second, `cfg`-gated description of the same data — is the duplication rule #54 forbids.
//!
//! The value set here is closed: scalars, arrays of records, and the tagged IconSpec object. Writing
//! the escaping and key order by hand keeps the output **stable** (field order is the order in this
//! file, not the order a macro happened to emit) and **readable in a diff**, which matters because
//! these files are checked in by designers.
//!
//! # Stability is a contract, not an accident
//!
//! [`capability_manifest_json`] sorts controls by name and events by name, so the same capability
//! table always produces the same bytes. Without that, a round-trip test would pass and a
//! designer's diff would not: re-saving a project would reorder the file.

use super::types::{
    CapabilityValue, EventManifest, EventPayloadShape, PropertySchema, PropertyValueKind,
};
use crate::compat::{format, String, Vec};

/// The key names in the exported document.
///
/// Named constants rather than literals because the writer and the reader must agree exactly, and
/// a typo in one of them is a key that silently reads back as absent.
mod keys {
    pub(crate) const CONTROL: &str = "control";
    pub(crate) const NAME: &str = "name";
    pub(crate) const ALIASES: &str = "aliases";
    pub(crate) const PROPERTIES: &str = "properties";
    pub(crate) const EVENTS: &str = "events";
    pub(crate) const COMMANDS: &str = "commands";
    pub(crate) const KIND: &str = "kind";
    pub(crate) const READABLE: &str = "readable";
    pub(crate) const WRITABLE: &str = "writable";
    pub(crate) const TOKENS: &str = "tokens";
    pub(crate) const DEFAULT: &str = "default";
    pub(crate) const PAYLOAD: &str = "payload";
    pub(crate) const SHAPE: &str = "shape";
    /// The protocol version this document is written in (BLUE26 B26.01).
    pub(crate) const PROTOCOL: &str = "protocol";
    /// The library version the document was exported from.
    pub(crate) const LIBRARY: &str = "library";
    /// The build profile the facts describe.
    pub(crate) const PROFILE: &str = "profile";
    /// The target triple the facts describe.
    pub(crate) const TRIPLE: &str = "triple";
    /// A command's parameter shape token (BLUE26 B26.03).
    pub(crate) const SIGNATURE: &str = "signature";
    /// A command's parameter name.
    pub(crate) const PARAMETER: &str = "parameter";
    /// A command's element kind.
    pub(crate) const ELEMENT: &str = "element";
    /// A command's payload arity.
    pub(crate) const ARITY: &str = "arity";
    /// A command's side-effect class.
    pub(crate) const EFFECT: &str = "effect";
    /// A property's constraint list (BLUE26 B26.02).
    pub(crate) const CONSTRAINTS: &str = "constraints";
    /// A constraint's inclusive minimum.
    pub(crate) const MINIMUM: &str = "minimum";
    /// A constraint's inclusive maximum.
    pub(crate) const MAXIMUM: &str = "maximum";
    /// A constraint's step.
    pub(crate) const STEP: &str = "step";
    /// A constraint's decimal places.
    pub(crate) const PLACES: &str = "places";
    /// A constraint's kind token.
    pub(crate) const RULE: &str = "rule";
}

/// The manifest protocol version this build writes and can read.
///
/// # Why this is a number of its own rather than the library version
///
/// The two move independently, and coupling them would make one of them lie. The library version
/// changes for any code change, including ones that do not touch this document; the protocol
/// version changes only when the document's *shape* does — a new key, a removed key, a changed
/// meaning. A reader uses the protocol version to decide whether it understands the document at
/// all, which is a question the library version cannot answer (2.8.5 and 2.9.0 could be the same
/// protocol, and two protocol versions could ship in one library version during a transition).
///
/// # Compatibility rule
///
/// A reader accepts a document whose protocol is **at or below** [`MANIFEST_PROTOCOL_VERSION`]:
/// older documents are readable by construction, because every version so far has only *added*
/// keys. A document with a **higher** protocol is refused explicitly
/// ([`ManifestParseError`]), never partially read — a partial read of a newer document is how a
/// designer silently drops a field it does not understand and re-saves a lossy file.
///
/// History:
/// * `1` — control, aliases, properties, events, commands.
/// * `2` — adds `protocol`, `library`, `profile` and `triple` (BLUE26 B26.01).
/// * `3` — adds structured IconSpec property defaults (BLUE27 U5).
pub const MANIFEST_PROTOCOL_VERSION: u32 = 3;

/// The oldest protocol version this reader still accepts.
///
/// Kept as an explicit number rather than implied by [`MANIFEST_PROTOCOL_VERSION`], because the
/// two answer different questions: one is "what do I write", the other is "what can I still
/// read". Dropping support for v1 would be a deliberate change here, not a side effect of
/// bumping the written version.
pub const MANIFEST_MIN_PROTOCOL_VERSION: u32 = 1;

/// The designer-facing spelling of a [`PropertyValueKind`].
///
/// Deliberately a token rather than a number: a designer reading the JSON, or a human reading a
/// diff, needs to see `"int"`, and an ordinal would change meaning the moment a variant is added
/// in the middle of the enum.
pub fn value_kind_token(kind: PropertyValueKind) -> &'static str {
    match kind {
        PropertyValueKind::Bool => "bool",
        PropertyValueKind::Int => "int",
        PropertyValueKind::UInt => "uint",
        PropertyValueKind::Float => "float",
        PropertyValueKind::Number => "number",
        PropertyValueKind::String => "string",
        PropertyValueKind::Enum => "enum",
        PropertyValueKind::Color => "color",
        PropertyValueKind::Rect => "rect",
        PropertyValueKind::IconSpec => "icon-spec",
        PropertyValueKind::Records => "records",
    }
}

/// The inverse of [`value_kind_token`]; `None` for an unrecognised spelling.
///
/// Returning `None` rather than a default is what makes a corrupt document an error instead of a
/// document that quietly describes the wrong types.
pub fn value_kind_from_token(token: &str) -> Option<PropertyValueKind> {
    match token {
        "bool" => Some(PropertyValueKind::Bool),
        "int" => Some(PropertyValueKind::Int),
        "uint" => Some(PropertyValueKind::UInt),
        "float" => Some(PropertyValueKind::Float),
        "number" => Some(PropertyValueKind::Number),
        "string" => Some(PropertyValueKind::String),
        "enum" => Some(PropertyValueKind::Enum),
        "color" => Some(PropertyValueKind::Color),
        "rect" => Some(PropertyValueKind::Rect),
        "icon-spec" => Some(PropertyValueKind::IconSpec),
        "records" => Some(PropertyValueKind::Records),
        _ => None,
    }
}

/// The designer-facing spelling of an [`EventPayloadShape`].
pub fn shape_token(shape: EventPayloadShape) -> &'static str {
    match shape {
        EventPayloadShape::Scalar => "scalar",
        EventPayloadShape::OptionalScalar => "optional",
        EventPayloadShape::ListScalar => "list",
        EventPayloadShape::Tuple2 => "tuple2",
        EventPayloadShape::Tuple3 => "tuple3",
        EventPayloadShape::Tuple4 => "tuple4",
        EventPayloadShape::OptionalTuple2 => "optional_tuple2",
        EventPayloadShape::Mixed => "mixed",
    }
}

/// The inverse of [`shape_token`]; `None` for an unrecognised spelling.
pub fn shape_from_token(token: &str) -> Option<EventPayloadShape> {
    match token {
        "scalar" => Some(EventPayloadShape::Scalar),
        "optional" => Some(EventPayloadShape::OptionalScalar),
        "list" => Some(EventPayloadShape::ListScalar),
        "tuple2" => Some(EventPayloadShape::Tuple2),
        "tuple3" => Some(EventPayloadShape::Tuple3),
        "tuple4" => Some(EventPayloadShape::Tuple4),
        "optional_tuple2" => Some(EventPayloadShape::OptionalTuple2),
        "mixed" => Some(EventPayloadShape::Mixed),
        _ => None,
    }
}

/// One property as the designer sees it: its declared type, accessibility and default value.
#[derive(Debug, Clone, PartialEq)]
pub struct DesignerProperty {
    /// The property's name.
    pub name: String,
    /// The declared value kind.
    pub kind: PropertyValueKind,
    /// Whether a read is allowed.
    pub readable: bool,
    /// Whether a write is allowed.
    pub writable: bool,
    /// The accepted spellings of an enum property, empty for every other kind.
    pub tokens: Vec<String>,
    /// The value the property holds on a freshly created control.
    pub default_value: CapabilityValue,
    /// The runtime-enforced constraints, empty when the property has none (BLUE26 B26.02).
    ///
    /// A designer renders these directly: a `Range` becomes a bounded slider, a `Required` an
    /// asterisk. Only constraints the control actually enforces are present (see
    /// [`Constraint`](crate::widget::capability::Constraint)), so an editor built from them accepts
    /// exactly what the control accepts.
    pub constraints: Vec<DesignerConstraint>,
}

/// One constraint as a designer sees it (BLUE26 B26.02).
///
/// A flat, tagged form rather than re-using the runtime [`Constraint`](crate::widget::capability::Constraint)
/// enum directly, because this is a *wire* type: it must round-trip through JSON with the rest of the
/// manifest, and a tagged object is the shape a reader can extend without renumbering an enum.
#[derive(Debug, Clone, PartialEq)]
pub struct DesignerConstraint {
    /// The constraint's kind: `"range"`, `"precision"`, or `"required"`.
    pub kind: &'static str,
    /// The inclusive minimum, for a `"range"` constraint.
    pub minimum: Option<f64>,
    /// The inclusive maximum, for a `"range"` constraint.
    pub maximum: Option<f64>,
    /// The step, for a `"range"` constraint that has one.
    pub step: Option<f64>,
    /// The decimal places, for a `"precision"` constraint.
    pub places: Option<u8>,
}

/// One event as the designer sees it: its name and the type of the value it carries.
#[derive(Debug, Clone, PartialEq)]
pub struct DesignerEvent {
    /// The published name, as `connect_event` accepts it.
    pub name: String,
    /// The declared payload kind, or `None` when the event carries no value.
    pub payload: Option<PropertyValueKind>,
    /// The arrangement of the payload.
    pub shape: Option<EventPayloadShape>,
}

/// One command as the designer sees it: its name, its parameter shape and its effect
/// (BLUE26 B26.03).
#[derive(Debug, Clone, PartialEq)]
pub struct DesignerCommand {
    /// The published command name.
    pub name: String,
    /// The parameter shape: `"none"`, `"value"`, or `"composite"`.
    pub signature: &'static str,
    /// The parameter name, empty for a payload-free command.
    pub parameter: String,
    /// The declared kind of a `"value"` parameter, empty for the other shapes.
    pub kind: Option<PropertyValueKind>,
    /// How many values a `"composite"` payload carries, or `None` for a list.
    pub arity: Option<usize>,
    /// The declared kind of each composite element, when homogeneous.
    pub element: Option<PropertyValueKind>,
    /// The side-effect class: `"mutates-control"`, `"mutates-collection"`, `"side-effecting"`.
    pub effect: &'static str,
}

/// One control's full designer-facing description.
#[derive(Debug, Clone, PartialEq)]
pub struct DesignerManifest {
    /// The capability-manifest protocol version this document is written in.
    ///
    /// Present on every manifest so a reader never has to guess: a document without it is
    /// protocol 1 by definition (see [`MANIFEST_PROTOCOL_VERSION`]), and one with a version
    /// above what this build writes is refused rather than half-read.
    pub protocol: u32,
    /// The library version that produced the document, for diagnostics and support.
    ///
    /// Not used to decide compatibility — that is [`Self::protocol`]'s job — but recorded so a
    /// bug report about a manifest can name the exact build it came from without a guess.
    pub library: String,
    /// The build profile the facts describe (BLUE26 B26.01/B26.06).
    ///
    /// The question this answers is "which build said so", which is exactly what is missing when
    /// a `desktop` build's `video_codec` support is read as a claim about a `mini` device.
    pub profile: String,
    /// The target triple the facts describe, as `build.rs` captured it.
    pub triple: String,
    /// The canonical control name.
    pub control: String,
    /// Every name the factory also accepts for this control.
    pub aliases: Vec<String>,
    /// The properties it publishes.
    pub properties: Vec<DesignerProperty>,
    /// The events it publishes, with payload types.
    pub events: Vec<DesignerEvent>,
    /// The commands it accepts, with parameter shape and effect.
    pub commands: Vec<DesignerCommand>,
}

/// Why a designer document could not be read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ManifestParseError {
    /// What was wrong, positioned by key path where the parser can tell.
    pub detail: String,
}

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

/// Why a manifest could not be produced.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ManifestExportError {
    /// No control is registered under the requested name.
    UnknownControl,
    /// The control exists but its property default values could not all be read, so the document
    /// would describe fewer properties than the control publishes.
    ///
    /// Reported rather than skipped: a designer that silently omits a property shows the user a
    /// control with capabilities it does not have.
    IncompleteDefaults,
}

impl core::fmt::Display for ManifestExportError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::UnknownControl => f.write_str("no control registered under that name"),
            Self::IncompleteDefaults => f.write_str(
                "a property default value could not be read, so the export is incomplete",
            ),
        }
    }
}

// ── Writing ────────────────────────────────────────────────────────────────────────

/// Appends `text` as a JSON string, escaping exactly what RFC 8259 requires.
///
/// The escape set is the conservative one — quote, backslash and the C0 controls — rather than
/// also escaping non-ASCII. Capability names are ASCII today, but a property default may hold a
/// label in any script, and escaping those would make the file unreadable for no gain: JSON is
/// UTF-8 and needs no escaping there.
fn push_json_string(out: &mut String, text: &str) {
    out.push('"');
    for ch in text.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            // The remaining C0 controls, plus DEL, which is not printable and has no shorthand.
            c if (c as u32) < 0x20 || c as u32 == 0x7f => {
                out.push_str(&format!("\\u{:04x}", c as u32));
            }
            c => out.push(c),
        }
    }
    out.push('"');
}

/// Appends `value` as a JSON value.
///
/// Every [`CapabilityValue`] variant maps to a distinct JSON form, including the ones that could
/// have shared one: `Int` and `UInt` both become numbers but are written from their own arms, so a
/// change to one cannot silently change the other. `Null` is the JSON `null`, which is why
/// `Option<usize>`-style payloads have a way to say "absent" without a second encoding.
///
/// # Why `Color` and `Rect` are written as their strings
///
/// The capability *table* declares every colour default as `CapabilityValue::String("#DCDCDCFF")`
/// and every geometry default as `CapabilityValue::String("0,0,0,0")` — see
/// `access::default_widget_property_default_value`. So a manifest that converted them into a
/// structured form would be inventing a representation the library does not actually store: the
/// re-loaded document would then hold a `Color` where the table holds a `String`, the two exports
/// would differ, and the designer's saved value would stop matching what a runtime read returns.
///
/// The declared `value_kind` in the schema still says `Color`/`Rect`, which is what a designer uses
/// to pick a colour picker; the *value* travels in the spelling the property API accepts. That
/// split is the same one the event side makes between `payload` and `shape`: the type says what a
/// value means, and the carrier says how it is written.
fn push_json_value(out: &mut String, value: &CapabilityValue) {
    match value {
        CapabilityValue::Null => out.push_str("null"),
        CapabilityValue::Bool(inner) => out.push_str(if *inner { "true" } else { "false" }),
        CapabilityValue::Int(inner) => push_json_int(out, *inner),
        CapabilityValue::UInt(inner) => out.push_str(&format!("{inner}")),
        CapabilityValue::Float(inner) => push_json_float(out, *inner),
        CapabilityValue::String(inner) => push_json_string(out, inner),
        CapabilityValue::Color(color) => {
            // `#rrggbbaa`. Reached only for a value the table typed as a colour; the spelling
            // matches what `access` writes so both forms re-read identically.
            out.push_str(&format!(
                "\"#{:02x}{:02x}{:02x}{:02x}\"",
                color.r, color.g, color.b, color.a
            ));
        }
        CapabilityValue::Rect(rect) => {
            // `"x,y,w,h"`, the same spelling `geometry_to_value` produces and
            // `access::...@parse_rect` reads, so a manifest value and a property value are one
            // representation rather than two that must be kept in step.
            out.push_str(&format!("\"{},{},{},{}\"", rect.x, rect.y, rect.width, rect.height));
        }
        CapabilityValue::IconSpec(spec) => match spec {
            crate::widget::icon_source::IconSpec::Builtin(name) => {
                out.push_str("{\"kind\":\"builtin\",\"name\":");
                push_json_string(out, name.as_str());
                out.push('}');
            }
            crate::widget::icon_source::IconSpec::Resource { id, color_mode } => {
                out.push_str("{\"kind\":\"resource\",\"id\":");
                push_json_string(out, id);
                out.push_str(",\"color_mode\":");
                push_json_string(
                    out,
                    match color_mode {
                        crate::widget::icon_source::IconColorMode::Monochrome => "monochrome",
                        crate::widget::icon_source::IconColorMode::Original => "original",
                    },
                );
                out.push('}');
            }
        },
        CapabilityValue::Tuple(items) => {
            // A composite payload exports as a JSON **array** of its components, each written by its
            // own kind. That is the natural JSON shape for an ordered group and keeps the round trip
            // lossless for the kinds a tuple can carry (a list of scalars), which is why a tuple
            // payload no longer exports as its debug spelling.
            out.push('[');
            for (index, item) in items.iter().enumerate() {
                if index > 0 {
                    out.push(',');
                }
                push_json_value(out, item);
            }
            out.push(']');
        }
        CapabilityValue::Records(list) => {
            // A record list exports as a JSON **array of objects**, each object's keys written by
            // `push_json_string` so a field name with a quote or a backslash stays valid JSON. This is
            // the shape a document declares, so the manifest form and the document form are one
            // representation rather than two (BLUE26 B26.09).
            out.push('[');
            for (record_index, record) in list.items().iter().enumerate() {
                if record_index > 0 {
                    out.push(',');
                }
                out.push('{');
                for (field_index, (name, value)) in record.fields().iter().enumerate() {
                    if field_index > 0 {
                        out.push(',');
                    }
                    push_json_string(out, name);
                    out.push(':');
                    push_json_value(out, value);
                }
                out.push('}');
            }
            out.push(']');
        }
    }
}

/// Appends one constraint object (BLUE26 B26.02).
///
/// Optional numeric fields are written as `null` when absent rather than omitted, so every
/// constraint object has the same keys. That is what makes the reader a fixed shape: a missing key
/// and a `null` value mean the same thing here, and writing one spelling keeps the round trip
/// byte-stable.
fn push_constraint(out: &mut String, constraint: &DesignerConstraint) {
    out.push_str("      {\n        ");
    push_json_string(out, keys::RULE);
    out.push_str(": ");
    push_json_string(out, constraint.kind);
    out.push_str(",\n        ");
    push_json_string(out, keys::MINIMUM);
    out.push_str(": ");
    push_optional_float(out, constraint.minimum);
    out.push_str(",\n        ");
    push_json_string(out, keys::MAXIMUM);
    out.push_str(": ");
    push_optional_float(out, constraint.maximum);
    out.push_str(",\n        ");
    push_json_string(out, keys::STEP);
    out.push_str(": ");
    push_optional_float(out, constraint.step);
    out.push_str(",\n        ");
    push_json_string(out, keys::PLACES);
    out.push_str(": ");
    match constraint.places {
        Some(places) => out.push_str(&format!("{places}")),
        None => out.push_str("null"),
    }
    out.push_str("\n      }");
}

/// Appends an optional float, writing `null` for `None`.
///
/// A present value goes through [`push_json_float`], so it keeps the integral-value marker that
/// distinguishes a float from an int on reload.
fn push_optional_float(out: &mut String, value: Option<f64>) {
    match value {
        Some(inner) => push_json_float(out, inner),
        None => out.push_str("null"),
    }
}

/// Appends a signed integer, ensuring the result re-reads as an `Int`.
///
/// # Why a non-negative `Int` needs more than its digits
///
/// JSON has one number type and no signed/unsigned distinction, so `Int(100)` and `UInt(100)` are
/// the same three characters. The reader has to pick one, and it picks `UInt` for a non-negative
/// value — `UInt` is the only arm that holds a non-negative integer without a lossy cast, and
/// every non-negative integer default in the capability table is declared `UInt`. That made the
/// round trip **partial**: `Int(100)` exported as `100` and reloaded as `UInt(100)`, so
/// export → load → export produced a different value kind from its input.
///
/// That path is reachable, not hypothetical: `Slider`'s capability declares `minimum` as `Int(0)`
/// and `maximum` as `Int(100)` (`access::...`), both non-negative.
///
/// A leading `+` is the marker. JSON's grammar allows it (`number = [ "-" ] int [ frac ] [ exp ]`,
/// and an unsigned int is `digit1-9 *digit`), the reader records whether it saw one, and no
/// capability default is written with a redundant `+` — so the two arms stay distinguishable
/// without inventing a second document shape (a wrapper object, a `"100i"` string) that a
/// consumer would have to learn. `UInt` keeps the bare spelling, so every existing document and
/// the whole rest of the table is unchanged.
fn push_json_int(out: &mut String, value: i64) {
    if value < 0 {
        out.push_str(&format!("{value}"));
    } else {
        out.push('+');
        out.push_str(&format!("{value}"));
    }
}

/// Appends a float, ensuring the result re-reads as a float.
///
/// `format!("{}", 1.0f64)` is `"1"`, which a reader would take for an `Int` — and the round-trip
/// would then produce a different value kind from the one declared. Non-finite values are written
/// as `null`, because JSON has no spelling for them and writing `NaN` would produce a document
/// that no conforming parser accepts.
fn push_json_float(out: &mut String, value: f64) {
    if !value.is_finite() {
        out.push_str("null");
        return;
    }
    let rendered = format!("{value}");
    if rendered.contains('.') || rendered.contains('e') || rendered.contains('E') {
        out.push_str(&rendered);
        return;
    }
    out.push_str(&rendered);
    out.push_str(".0");
}

/// Writes one control's description as a JSON document.
///
/// # Layout
///
/// One key per line, in a fixed order, so a saved project diffs by field rather than by offset.
/// The property list and the event list each carry their own object per entry, which is what lets a
/// designer patch a single entry instead of rewriting the file.
fn write_manifest(out: &mut String, manifest: &DesignerManifest) {
    out.push_str("{\n");
    out.push_str("  ");
    push_json_string(out, keys::PROTOCOL);
    out.push_str(": ");
    out.push_str(&format!("{},\n", manifest.protocol));
    out.push_str("  ");
    push_json_string(out, keys::LIBRARY);
    out.push_str(": ");
    push_json_string(out, &manifest.library);
    out.push_str(",\n  ");
    push_json_string(out, keys::PROFILE);
    out.push_str(": ");
    push_json_string(out, &manifest.profile);
    out.push_str(",\n  ");
    push_json_string(out, keys::TRIPLE);
    out.push_str(": ");
    push_json_string(out, &manifest.triple);
    out.push_str(",\n  ");
    push_json_string(out, keys::CONTROL);
    out.push_str(": ");
    push_json_string(out, &manifest.control);
    out.push_str(",\n");

    push_array(
        out,
        keys::ALIASES,
        &manifest.aliases,
        |out, alias| {
            push_json_string(out, alias);
        },
        true,
    );

    out.push_str("  ");
    push_json_string(out, keys::PROPERTIES);
    out.push_str(": [\n");
    for (index, property) in manifest.properties.iter().enumerate() {
        out.push_str("    {\n      ");
        push_json_string(out, keys::NAME);
        out.push_str(": ");
        push_json_string(out, &property.name);
        out.push_str(",\n      ");
        push_json_string(out, keys::KIND);
        out.push_str(": ");
        push_json_string(out, value_kind_token(property.kind));
        out.push_str(",\n      ");
        push_json_string(out, keys::READABLE);
        out.push_str(&format!(": {},\n      ", property.readable));
        push_json_string(out, keys::WRITABLE);
        out.push_str(&format!(": {},\n      ", property.writable));
        push_json_string(out, keys::TOKENS);
        out.push_str(": ");
        push_token_array(out, &property.tokens);
        out.push_str(",\n      ");
        push_json_string(out, keys::DEFAULT);
        out.push_str(": ");
        push_json_value(out, &property.default_value);
        out.push_str(",\n      ");
        push_json_string(out, keys::CONSTRAINTS);
        out.push_str(": [");
        if !property.constraints.is_empty() {
            out.push('\n');
            for (c_index, constraint) in property.constraints.iter().enumerate() {
                push_constraint(out, constraint);
                out.push_str(if c_index + 1 == property.constraints.len() { "\n" } else { ",\n" });
            }
        }
        out.push_str("    ]");
        out.push_str("\n    }");
        out.push_str(if index + 1 == manifest.properties.len() { "\n" } else { ",\n" });
    }
    out.push_str("  ],\n");

    out.push_str("  ");
    push_json_string(out, keys::EVENTS);
    out.push_str(": [\n");
    for (index, event) in manifest.events.iter().enumerate() {
        out.push_str("    {\n      ");
        push_json_string(out, keys::NAME);
        out.push_str(": ");
        push_json_string(out, &event.name);
        out.push_str(",\n      ");
        push_json_string(out, keys::PAYLOAD);
        out.push_str(": ");
        match event.payload {
            Some(kind) => push_json_string(out, value_kind_token(kind)),
            None => out.push_str("null"),
        }
        out.push_str(",\n      ");
        push_json_string(out, keys::SHAPE);
        out.push_str(": ");
        match event.shape {
            Some(shape) => push_json_string(out, shape_token(shape)),
            None => out.push_str("null"),
        }
        out.push_str("\n    }");
        out.push_str(if index + 1 == manifest.events.len() { "\n" } else { ",\n" });
    }
    out.push_str("  ],\n");

    out.push_str("  ");
    push_json_string(out, keys::COMMANDS);
    out.push_str(": [\n");
    for (index, command) in manifest.commands.iter().enumerate() {
        push_command(out, command);
        out.push_str(if index + 1 == manifest.commands.len() { "\n" } else { ",\n" });
    }
    out.push_str("  ]\n");

    out.push_str("}\n");
}

/// Appends one command object, so a designer can validate a binding against its parameter shape.
///
/// A command used to be a bare string. A string is enough to *offer* a command but not to check a
/// wire to it: a designer must know whether it takes an argument, of what type, and whether its
/// effect warrants a warning (BLUE26 B26.03). The object form carries exactly that — and nothing
/// else — so the document describes the command the control actually dispatches.
fn push_command(out: &mut String, command: &DesignerCommand) {
    out.push_str("    {\n      ");
    push_json_string(out, keys::NAME);
    out.push_str(": ");
    push_json_string(out, &command.name);
    out.push_str(",\n      ");
    push_json_string(out, keys::SIGNATURE);
    out.push_str(": ");
    push_json_string(out, command.signature);
    out.push_str(",\n      ");
    push_json_string(out, keys::PARAMETER);
    out.push_str(": ");
    push_json_string(out, &command.parameter);
    out.push_str(",\n      ");
    push_json_string(out, keys::KIND);
    out.push_str(": ");
    match command.kind {
        Some(kind) => push_json_string(out, value_kind_token(kind)),
        None => out.push_str("null"),
    }
    out.push_str(",\n      ");
    push_json_string(out, keys::ELEMENT);
    out.push_str(": ");
    match command.element {
        Some(kind) => push_json_string(out, value_kind_token(kind)),
        None => out.push_str("null"),
    }
    out.push_str(",\n      ");
    push_json_string(out, keys::ARITY);
    out.push_str(": ");
    match command.arity {
        Some(count) => out.push_str(&format!("{count}")),
        None => out.push_str("null"),
    }
    out.push_str(",\n      ");
    push_json_string(out, keys::EFFECT);
    out.push_str(": ");
    push_json_string(out, command.effect);
    out.push_str("\n    }");
}

/// Appends `"key": ["a", "b"]` for a list of strings that needs no nested objects.
///
/// The trailing comma is the **caller's** decision, because the last list in the document is
/// followed by `}` and must not carry one. An earlier revision always emitted it and relied on the
/// caller not to add another, which produced a comma before the closing brace — a syntax error the
/// round-trip test caught on its first run. Making the separator a parameter rather than a
/// convention is what keeps that from being reintroduced by the next list added here.
fn push_array<T, F>(out: &mut String, key: &str, items: &[T], mut write: F, trailing_comma: bool)
where
    F: FnMut(&mut String, &T),
{
    let sep = if trailing_comma { ",\n" } else { "\n" };
    out.push_str("  ");
    push_json_string(out, key);
    out.push_str(": [");
    if items.is_empty() {
        out.push(']');
        out.push_str(sep);
        return;
    }
    out.push('\n');
    for (index, item) in items.iter().enumerate() {
        out.push_str("    ");
        write(out, item);
        out.push_str(if index + 1 == items.len() { "\n" } else { ",\n" });
    }
    out.push_str("  ]");
    out.push_str(sep);
}

/// Appends a list of already-owned strings, one per line, without the trailing comma of a key.
fn push_token_array(out: &mut String, items: &[String]) {
    out.push('[');
    if items.is_empty() {
        out.push(']');
        return;
    }
    // Inline, because an enum's tokens are a short closed set and a vertical list would triple the
    // height of the document for no readability gain.
    for (index, item) in items.iter().enumerate() {
        if index > 0 {
            out.push_str(", ");
        }
        push_json_string(out, item);
    }
    out.push(']');
}

// ── Reading ────────────────────────────────────────────────────────────────────────

/// A minimal JSON reader for the documents this module writes.
///
/// # Why this is not `serde_json`
///
/// `src/json/` already depends on `serde_json`, but that module is `full_widgets`-gated and the
/// capability layer is not the JSON layer's owner. Depending on it here would make the round-trip
/// untestable in any profile without it, and the document this parser reads is one this module
/// wrote — a closed grammar with no numbers in exponent form, no duplicate keys and no nesting
/// beyond arrays of objects.
///
/// It is still a real parser, not a substring search: every key is matched as a key, strings are
/// unescaped, and anything unexpected is an error. A parser that guessed would make the round-trip
/// test unable to fail, which is the one property this module exists to have.
struct JsonReader<'a> {
    bytes: &'a [u8],
    cursor: usize,
}

impl<'a> JsonReader<'a> {
    fn new(text: &'a str) -> Self {
        Self { bytes: text.as_bytes(), cursor: 0 }
    }

    /// The error to report for the current position.
    fn fail<T>(&self, detail: &str) -> Result<T, ManifestParseError> {
        Err(ManifestParseError { detail: format!("{} at byte {}", detail, self.cursor) })
    }

    /// Advances past whitespace.
    fn skip_whitespace(&mut self) {
        while let Some(byte) = self.bytes.get(self.cursor) {
            if byte.is_ascii_whitespace() {
                self.cursor += 1;
            } else {
                break;
            }
        }
    }

    /// Consumes `expected`, or fails.
    fn expect(&mut self, expected: u8, what: &str) -> Result<(), ManifestParseError> {
        self.skip_whitespace();
        match self.bytes.get(self.cursor) {
            Some(byte) if *byte == expected => {
                self.cursor += 1;
                Ok(())
            }
            _ => self.fail(what),
        }
    }

    /// Reports whether the next non-space byte is `byte`, without consuming it.
    fn peek(&mut self, byte: u8) -> bool {
        self.skip_whitespace();
        self.bytes.get(self.cursor) == Some(&byte)
    }

    /// Reads the literal `null`, or fails.
    fn read_null(&mut self) -> Result<(), ManifestParseError> {
        self.skip_whitespace();
        if self.bytes[self.cursor..].starts_with(b"null") {
            self.cursor += 4;
            return Ok(());
        }
        self.fail("expected `null`")
    }

    /// Reads `true` or `false`, or fails.
    fn read_bool(&mut self) -> Result<bool, ManifestParseError> {
        self.skip_whitespace();
        if self.bytes[self.cursor..].starts_with(b"true") {
            self.cursor += 4;
            return Ok(true);
        }
        if self.bytes[self.cursor..].starts_with(b"false") {
            self.cursor += 5;
            return Ok(false);
        }
        self.fail("expected `true` or `false`")
    }

    /// Reads a JSON string, unescaping it.
    fn read_string(&mut self) -> Result<String, ManifestParseError> {
        self.expect(b'"', "expected a string")?;
        let mut out = String::new();
        loop {
            let Some(byte) = self.bytes.get(self.cursor).copied() else {
                return self.fail("unterminated string");
            };
            self.cursor += 1;
            match byte {
                b'"' => return Ok(out),
                b'\\' => {
                    let Some(escape) = self.bytes.get(self.cursor).copied() else {
                        return self.fail("unterminated escape");
                    };
                    self.cursor += 1;
                    match escape {
                        b'"' => out.push('"'),
                        b'\\' => out.push('\\'),
                        b'n' => out.push('\n'),
                        b'r' => out.push('\r'),
                        b't' => out.push('\t'),
                        b'u' => {
                            let code = self.read_hex4()?;
                            // A surrogate pair is two `\u` escapes; both arrive here, and
                            // `char::from_u32` rejects an unpaired half rather than producing a
                            // replacement character that would not re-serialize identically.
                            let Some(ch) = char::from_u32(code) else {
                                return self.fail("invalid \\u escape");
                            };
                            out.push(ch);
                        }
                        _ => return self.fail("unknown escape"),
                    }
                }
                _ => {
                    // The document is UTF-8 and this reader walks bytes, so a multi-byte character
                    // must be copied whole. Re-decoding from the cursor position is what keeps a
                    // label in any script intact through the round trip.
                    let start = self.cursor - 1;
                    let width = utf8_width(byte);
                    if width == 1 {
                        out.push(byte as char);
                    } else {
                        let end = start + width;
                        if end > self.bytes.len() {
                            return self.fail("truncated UTF-8 sequence");
                        }
                        let Some(text) = core::str::from_utf8(&self.bytes[start..end]).ok() else {
                            return self.fail("invalid UTF-8 sequence");
                        };
                        out.push_str(text);
                        self.cursor = end;
                    }
                }
            }
        }
    }

    /// Reads the four hex digits of a `\u` escape.
    fn read_hex4(&mut self) -> Result<u32, ManifestParseError> {
        let mut value = 0u32;
        for _ in 0..4 {
            let Some(byte) = self.bytes.get(self.cursor).copied() else {
                return self.fail("truncated \\u escape");
            };
            self.cursor += 1;
            let digit = match byte {
                b'0'..=b'9' => (byte - b'0') as u32,
                b'a'..=b'f' => (byte - b'a') as u32 + 10,
                b'A'..=b'F' => (byte - b'A') as u32 + 10,
                _ => return self.fail("non-hex digit in \\u escape"),
            };
            value = value * 16 + digit;
        }
        Ok(value)
    }

    /// Reads an integer or float, reporting whether it had a fractional part.
    fn read_number(&mut self) -> Result<(f64, bool), ManifestParseError> {
        self.skip_whitespace();
        let start = self.cursor;
        while let Some(byte) = self.bytes.get(self.cursor) {
            if byte.is_ascii_digit() || matches!(byte, b'-' | b'+' | b'.' | b'e' | b'E') {
                self.cursor += 1;
            } else {
                break;
            }
        }
        if start == self.cursor {
            return self.fail("expected a number");
        }
        let Some(text) = core::str::from_utf8(&self.bytes[start..self.cursor]).ok() else {
            return self.fail("number is not ASCII");
        };
        let is_float = text.contains('.') || text.contains('e') || text.contains('E');
        match text.parse::<f64>() {
            Ok(value) => Ok((value, is_float)),
            Err(_) => self.fail("malformed number"),
        }
    }

    /// Reads a non-negative integer, for keys that are counts or versions.
    ///
    /// A dedicated reader rather than [`read_number`](Self::read_number) because a version is a
    /// `u32` and a parse through `f64` would lose precision above 2^53 and silently accept a
    /// fractional value (`2.5` would truncate). The digits are parsed directly, and anything that
    /// is not a plain run of digits — a sign, a fraction, an exponent — is a malformed document.
    fn read_uint(&mut self) -> Result<u32, ManifestParseError> {
        self.skip_whitespace();
        let start = self.cursor;
        while self.bytes.get(self.cursor).is_some_and(u8::is_ascii_digit) {
            self.cursor += 1;
        }
        if start == self.cursor {
            return self.fail("expected a non-negative integer");
        }
        let Some(text) = core::str::from_utf8(&self.bytes[start..self.cursor]).ok() else {
            return self.fail("number is not ASCII");
        };
        text.parse::<u32>().map_err(|_| ManifestParseError {
            detail: format!("`{text}` is not a valid version number"),
        })
    }

    /// Whether the number at the cursor is written with a **leading `+`**.
    ///
    /// # Why the sign is asked about separately
    ///
    /// [`read_number`](Self::read_number) returns a magnitude and nothing else, because that is
    /// all a `f64` can carry. But JSON has no signed/unsigned distinction, so the magnitude alone
    /// cannot say whether `100` means `Int(100)` or `UInt(100)` — and the writer emits the `UInt`
    /// spelling for every non-negative value in the capability table, so the reader must be able to
    /// tell the two apart or `Int(100)` reloads as a different kind than it was written as. This is
    /// the other half of [`push_json_int`]: the marker is written there and observed here.
    ///
    /// It looks ahead without consuming, so it can be asked before or after `read_number` as long
    /// as the cursor has not moved past the token.
    fn peek_leading_plus(&mut self) -> bool {
        self.skip_whitespace();
        self.bytes.get(self.cursor) == Some(&b'+')
    }

    /// Reads the key at the cursor and the colon after it.
    fn read_key(&mut self) -> Result<String, ManifestParseError> {
        let key = self.read_string()?;
        self.expect(b':', "expected `:` after a key")?;
        Ok(key)
    }
}

/// How many bytes the UTF-8 sequence starting with `first` occupies.
fn utf8_width(first: u8) -> usize {
    match first {
        0x00..=0x7f => 1,
        0xc0..=0xdf => 2,
        0xe0..=0xef => 3,
        _ => 4,
    }
}

/// Reads an array of strings.
fn read_string_array(reader: &mut JsonReader<'_>) -> Result<Vec<String>, ManifestParseError> {
    reader.expect(b'[', "expected `[`")?;
    let mut items = Vec::new();
    if reader.peek(b']') {
        reader.expect(b']', "expected `]`")?;
        return Ok(items);
    }
    loop {
        items.push(reader.read_string()?);
        if reader.peek(b',') {
            reader.expect(b',', "expected `,`")?;
            continue;
        }
        reader.expect(b']', "expected `]` or `,` in a string array")?;
        return Ok(items);
    }
}

/// Reads one property object.
fn read_property(reader: &mut JsonReader<'_>) -> Result<DesignerProperty, ManifestParseError> {
    reader.expect(b'{', "expected `{` to start a property")?;
    let mut name = None;
    let mut kind = None;
    let mut readable = None;
    let mut writable = None;
    let mut tokens = Vec::new();
    let mut constraints = Vec::new();
    let mut default_value = CapabilityValue::Null;
    let mut saw_default = false;

    loop {
        let key = reader.read_key()?;
        match key.as_str() {
            // Matching the literal would allocate a key we already own; the constants are `&str`
            // and the parsed key is a `String`, so the comparison is against the token.
            k if k == keys::NAME => name = Some(reader.read_string()?),
            k if k == keys::KIND => {
                let token = reader.read_string()?;
                kind = value_kind_from_token(&token);
                if kind.is_none() {
                    return Err(ManifestParseError {
                        detail: format!("unknown property kind `{token}`"),
                    });
                }
            }
            k if k == keys::READABLE => readable = Some(reader.read_bool()?),
            k if k == keys::WRITABLE => writable = Some(reader.read_bool()?),
            k if k == keys::TOKENS => tokens = read_string_array(reader)?,
            k if k == keys::CONSTRAINTS => constraints = read_constraints(reader)?,
            k if k == keys::DEFAULT => {
                default_value = read_value(reader)?;
                saw_default = true;
            }
            // An unknown key is an error rather than a skip: a document this writer did not produce
            // is a document whose round trip cannot be reasoned about.
            other => {
                return Err(ManifestParseError {
                    detail: format!("unexpected key `{other}` in a property"),
                })
            }
        }
        if reader.peek(b',') {
            reader.expect(b',', "expected `,`")?;
            continue;
        }
        reader.expect(b'}', "expected `}` or `,` in a property")?;
        break;
    }

    Ok(DesignerProperty {
        name: name.ok_or(ManifestParseError { detail: "a property has no name".into() })?,
        kind: kind.ok_or(ManifestParseError { detail: "a property has no kind".into() })?,
        readable: readable.unwrap_or(false),
        writable: writable.unwrap_or(false),
        tokens,
        constraints,
        default_value: if saw_default { default_value } else { CapabilityValue::Null },
    })
}

/// Reads a constraint array (BLUE26 B26.02).
fn read_constraints(
    reader: &mut JsonReader<'_>,
) -> Result<Vec<DesignerConstraint>, ManifestParseError> {
    reader.expect(b'[', "expected `[` to start a constraint list")?;
    let mut constraints = Vec::new();
    if reader.peek(b']') {
        reader.expect(b']', "expected `]`")?;
        return Ok(constraints);
    }
    loop {
        constraints.push(read_constraint(reader)?);
        if reader.peek(b',') {
            reader.expect(b',', "expected `,`")?;
            continue;
        }
        reader.expect(b']', "expected `]` or `,` in a constraint list")?;
        return Ok(constraints);
    }
}

/// Reads one constraint object (BLUE26 B26.02).
fn read_constraint(reader: &mut JsonReader<'_>) -> Result<DesignerConstraint, ManifestParseError> {
    reader.expect(b'{', "expected `{` to start a constraint")?;
    let mut kind: Option<&'static str> = None;
    let mut minimum = None;
    let mut maximum = None;
    let mut step = None;
    let mut places = None;

    loop {
        let key = reader.read_key()?;
        match key.as_str() {
            k if k == keys::RULE => {
                let token = reader.read_string()?;
                kind = Some(constraint_rule_token(&token).ok_or(ManifestParseError {
                    detail: format!("unknown constraint kind `{token}`"),
                })?);
            }
            k if k == keys::MINIMUM => minimum = read_optional_float(reader)?,
            k if k == keys::MAXIMUM => maximum = read_optional_float(reader)?,
            k if k == keys::STEP => step = read_optional_float(reader)?,
            k if k == keys::PLACES => {
                if reader.peek(b'n') {
                    reader.read_null()?;
                } else {
                    places = Some(reader.read_uint()? as u8);
                }
            }
            other => {
                return Err(ManifestParseError {
                    detail: format!("unexpected key `{other}` in a constraint"),
                })
            }
        }
        if reader.peek(b',') {
            reader.expect(b',', "expected `,`")?;
            continue;
        }
        reader.expect(b'}', "expected `}` or `,` in a constraint")?;
        break;
    }

    Ok(DesignerConstraint {
        kind: kind.ok_or(ManifestParseError { detail: "a constraint has no kind".into() })?,
        minimum,
        maximum,
        step,
        places,
    })
}

/// Reads an optional float, consuming `null` as `None`.
fn read_optional_float(reader: &mut JsonReader<'_>) -> Result<Option<f64>, ManifestParseError> {
    if reader.peek(b'n') {
        reader.read_null()?;
        return Ok(None);
    }
    let (value, _is_float) = reader.read_number()?;
    Ok(Some(value))
}

/// The constraint-rule tokens a document may carry, and their inverse.
fn constraint_rule_token(token: &str) -> Option<&'static str> {
    match token {
        "range" => Some("range"),
        "precision" => Some("precision"),
        "required" => Some("required"),
        _ => None,
    }
}

/// Reads one event object.
fn read_event(reader: &mut JsonReader<'_>) -> Result<DesignerEvent, ManifestParseError> {
    reader.expect(b'{', "expected `{` to start an event")?;
    let mut name = None;
    let mut payload = None;
    let mut shape = None;

    loop {
        let key = reader.read_key()?;
        match key.as_str() {
            k if k == keys::NAME => name = Some(reader.read_string()?),
            k if k == keys::PAYLOAD => {
                if reader.peek(b'n') {
                    reader.read_null()?;
                } else {
                    let token = reader.read_string()?;
                    payload = Some(value_kind_from_token(&token).ok_or(ManifestParseError {
                        detail: format!("unknown event payload kind `{token}`"),
                    })?);
                }
            }
            k if k == keys::SHAPE => {
                if reader.peek(b'n') {
                    reader.read_null()?;
                } else {
                    let token = reader.read_string()?;
                    shape = Some(shape_from_token(&token).ok_or(ManifestParseError {
                        detail: format!("unknown event shape `{token}`"),
                    })?);
                }
            }
            other => {
                return Err(ManifestParseError {
                    detail: format!("unexpected key `{other}` in an event"),
                })
            }
        }
        if reader.peek(b',') {
            reader.expect(b',', "expected `,`")?;
            continue;
        }
        reader.expect(b'}', "expected `}` or `,` in an event")?;
        break;
    }

    Ok(DesignerEvent {
        name: name.ok_or(ManifestParseError { detail: "an event has no name".into() })?,
        payload,
        shape,
    })
}

/// Reads one command object (BLUE26 B26.03).
///
/// The signature token is validated against the closed set the writer emits, so a document naming
/// a signature this build does not understand is refused rather than read as a payload-free command
/// — which would tell a designer a wire to a value-taking command is legal.
fn read_command(reader: &mut JsonReader<'_>) -> Result<DesignerCommand, ManifestParseError> {
    reader.expect(b'{', "expected `{` to start a command")?;
    let mut name = None;
    let mut signature: Option<&'static str> = None;
    let mut parameter = String::new();
    let mut kind = None;
    let mut element = None;
    let mut arity = None;
    let mut effect: Option<&'static str> = None;

    loop {
        let key = reader.read_key()?;
        match key.as_str() {
            k if k == keys::NAME => name = Some(reader.read_string()?),
            k if k == keys::SIGNATURE => {
                let token = reader.read_string()?;
                signature = Some(command_signature_token(&token).ok_or(ManifestParseError {
                    detail: format!("unknown command signature `{token}`"),
                })?);
            }
            k if k == keys::PARAMETER => parameter = reader.read_string()?,
            k if k == keys::KIND => {
                if reader.peek(b'n') {
                    reader.read_null()?;
                } else {
                    let token = reader.read_string()?;
                    kind = Some(value_kind_from_token(&token).ok_or(ManifestParseError {
                        detail: format!("unknown command parameter kind `{token}`"),
                    })?);
                }
            }
            k if k == keys::ELEMENT => {
                if reader.peek(b'n') {
                    reader.read_null()?;
                } else {
                    let token = reader.read_string()?;
                    element = Some(value_kind_from_token(&token).ok_or(ManifestParseError {
                        detail: format!("unknown command element kind `{token}`"),
                    })?);
                }
            }
            k if k == keys::ARITY => {
                if reader.peek(b'n') {
                    reader.read_null()?;
                } else {
                    arity = Some(reader.read_uint()? as usize);
                }
            }
            k if k == keys::EFFECT => {
                let token = reader.read_string()?;
                effect = Some(command_effect_token(&token).ok_or(ManifestParseError {
                    detail: format!("unknown command effect `{token}`"),
                })?);
            }
            other => {
                return Err(ManifestParseError {
                    detail: format!("unexpected key `{other}` in a command"),
                })
            }
        }
        if reader.peek(b',') {
            reader.expect(b',', "expected `,`")?;
            continue;
        }
        reader.expect(b'}', "expected `}` or `,` in a command")?;
        break;
    }

    Ok(DesignerCommand {
        name: name.ok_or(ManifestParseError { detail: "a command has no name".into() })?,
        signature: signature
            .ok_or(ManifestParseError { detail: "a command has no signature".into() })?,
        parameter,
        kind,
        element,
        arity,
        effect: effect.ok_or(ManifestParseError { detail: "a command has no effect".into() })?,
    })
}

/// The signature tokens a command document may carry, and their inverse.
///
/// A `&'static str` rather than the `CommandSignature` enum because the two live in different
/// layers: this module owns the wire spelling, `command_schema` owns the semantics. The mapping is
/// the join between them, kept closed so an unknown token is an error.
fn command_signature_token(token: &str) -> Option<&'static str> {
    match token {
        "none" => Some("none"),
        "value" => Some("value"),
        "composite" => Some("composite"),
        _ => None,
    }
}

/// The effect tokens a command document may carry, and their inverse.
fn command_effect_token(token: &str) -> Option<&'static str> {
    match token {
        "mutates-control" => Some("mutates-control"),
        "mutates-collection" => Some("mutates-collection"),
        "side-effecting" => Some("side-effecting"),
        _ => None,
    }
}

/// Builds a [`DesignerCommand`] from a capability's command schema.
///
/// Kept here rather than in `command_schema` so the *wire vocabulary* (`"none"`/`"value"`/
/// `"composite"`) lives with the rest of the document's vocabulary, while the derivation of the
/// shape stays in `command_schema`. A command with no derivable schema is dropped by the caller —
/// publishing a command a designer cannot describe is the gap B26.03 closes.
pub fn designer_command_from(
    name: &str,
    schema: &super::command_schema::CommandSchema,
) -> DesignerCommand {
    use super::command_schema::{CommandEffect, CommandSignature};
    let (signature, parameter, kind, arity, element) = match schema.signature {
        CommandSignature::PayloadFree => ("none", String::new(), None, None, None),
        CommandSignature::OneValue { parameter, kind } => {
            ("value", String::from(parameter), Some(kind), None, None)
        }
        CommandSignature::Composite { parameter, arity, element } => {
            ("composite", String::from(parameter), None, arity, element)
        }
    };
    let effect = match schema.effect {
        CommandEffect::MutatesControl => "mutates-control",
        CommandEffect::MutatesCollection => "mutates-collection",
        CommandEffect::SideEffecting => "side-effecting",
    };
    DesignerCommand { name: String::from(name), signature, parameter, kind, arity, element, effect }
}

/// Reads a JSON value into a [`CapabilityValue`].
///
/// Strings are taken verbatim: `"#DCDCDCFF"` and `"0,0,0,0"` are how the capability table spells a
/// colour default and a geometry default, so recovering a `Color`/`Rect` here would produce a value
/// the table does not hold and the two exports would disagree. The schema's `kind` is what says how
/// to interpret the string.
fn read_value(reader: &mut JsonReader<'_>) -> Result<CapabilityValue, ManifestParseError> {
    if reader.peek(b'n') {
        reader.read_null()?;
        return Ok(CapabilityValue::Null);
    }
    // `true`/`false` must be tested before the number arm: a `t` is not a digit, so the number arm
    // would report a malformed number for a valid boolean. The order of these guards is the whole
    // reason `read_value` is not a `match` on the first byte — `t` and `f` have no other meaning in
    // this grammar, but relying on that would make the reader silently wrong if one were added.
    if reader.peek(b't') || reader.peek(b'f') {
        return Ok(CapabilityValue::Bool(reader.read_bool()?));
    }
    if reader.peek(b'"') {
        return Ok(CapabilityValue::String(reader.read_string()?));
    }
    if reader.peek(b'{') {
        return read_icon_spec(reader).map(CapabilityValue::IconSpec);
    }
    // A record list (B26.09). Tested before the number arm for the same reason the booleans are:
    // `[` is not a digit, so the number arm would report a malformed number for a valid list.
    if reader.peek(b'[') {
        return Ok(CapabilityValue::Records(read_record_list(reader)?));
    }
    let leading_plus = reader.peek_leading_plus();
    let (number, is_float) = reader.read_number()?;
    if is_float {
        return Ok(CapabilityValue::Float(number));
    }
    // An integral number without a fractional part is `Int` when it is negative or carries the
    // writer's leading `+`, and `UInt` otherwise. The reader must make the same distinction the
    // writer did, or `Int(100)` — a value `Slider`'s `maximum` genuinely declares — would reload as
    // `UInt(100)` and the round trip would not be a round trip. The marker is only consulted for a
    // non-negative integral value: a `-3` is already unambiguous, and requiring a `-` *and* a `+`
    // would be a marker no writer produces.
    if number < 0.0 || leading_plus {
        return Ok(CapabilityValue::Int(number as i64));
    }
    Ok(CapabilityValue::UInt(number as u64))
}

fn read_icon_spec(
    reader: &mut JsonReader<'_>,
) -> Result<crate::widget::icon_source::IconSpec, ManifestParseError> {
    use crate::widget::icon_source::{IconColorMode, IconSpec};

    reader.expect(b'{', "expected `{` to start an icon source")?;
    let mut kind = None;
    let mut name = None;
    let mut id = None;
    let mut color_mode = None;
    loop {
        let key = reader.read_key()?;
        let slot = match key.as_str() {
            "kind" => &mut kind,
            "name" => &mut name,
            "id" => &mut id,
            "color_mode" => &mut color_mode,
            _ => {
                return reader.fail(&format!("unexpected icon source field `{key}`"));
            }
        };
        if slot.is_some() {
            return reader.fail(&format!("duplicate icon source field `{key}`"));
        }
        *slot = Some(reader.read_string()?);
        if reader.peek(b',') {
            reader.expect(b',', "expected `,` in icon source")?;
            continue;
        }
        reader.expect(b'}', "expected `}` or `,` in icon source")?;
        break;
    }
    match kind.as_deref() {
        Some("builtin") if id.is_none() && color_mode.is_none() => {
            let token = name.ok_or_else(|| ManifestParseError {
                detail: "a built-in icon source has no name".into(),
            })?;
            let icon = crate::widget::display_widgets::icon::IconName::from_name(&token)
                .ok_or_else(|| ManifestParseError {
                    detail: format!("unknown built-in icon `{token}`"),
                })?;
            Ok(IconSpec::Builtin(icon))
        }
        Some("resource") if name.is_none() => {
            let resource_id = id.ok_or_else(|| ManifestParseError {
                detail: "a resource icon source has no id".into(),
            })?;
            if resource_id.trim().is_empty() {
                return reader.fail("a resource icon source has an empty id");
            }
            let mode = match color_mode.as_deref() {
                Some("monochrome") => IconColorMode::Monochrome,
                Some("original") => IconColorMode::Original,
                _ => return reader.fail("a resource icon source has an invalid color_mode"),
            };
            Ok(IconSpec::Resource { id: resource_id, color_mode: mode })
        }
        Some("builtin" | "resource") => reader.fail("icon source fields conflict with its kind"),
        Some(other) => reader.fail(&format!("unknown icon source kind `{other}`")),
        None => reader.fail("icon source has no kind"),
    }
}

/// Reads a JSON array of objects as a record list (B26.09).
///
/// # What it accepts, and why it is strict
///
/// One object per record, each object's keys becoming that record's fields in document order, and each
/// field value read by [`read_value`] — so a nested array or object inside a record is refused by the
/// same reader that refuses one anywhere else. Strictness is the point: this reader's contract is that
/// the document it half-understands is one whose next export would silently differ, so an element that
/// is not an object is an error rather than a skipped element.
///
/// # Why the list carries no schema
///
/// The manifest describes properties, and this reader has no schema in hand — the same situation the
/// JSON loader and the C ABI are in. The list therefore carries
/// [`EMPTY_RECORD_SCHEMA`](crate::widget::capability::EMPTY_RECORD_SCHEMA) and the *property* is what
/// supplies the record shape; see
/// [`RecordList::validate_against`](crate::widget::capability::RecordList::validate_against).
fn read_record_list(
    reader: &mut JsonReader<'_>,
) -> Result<crate::widget::capability::RecordList, ManifestParseError> {
    use crate::widget::capability::{RecordList, RecordValue};
    reader.expect(b'[', "expected `[` to start a record list")?;
    let mut items = Vec::new();
    if reader.peek(b']') {
        reader.expect(b']', "expected `]`")?;
        return Ok(RecordList::from_items(&crate::widget::capability::EMPTY_RECORD_SCHEMA, items));
    }
    loop {
        reader.expect(b'{', "expected `{` to start a record")?;
        let mut record = RecordValue::new();
        if !reader.peek(b'}') {
            loop {
                let name = reader.read_string()?;
                reader.expect(b':', "expected `:` after a field name")?;
                record = record.with(name, read_value(reader)?);
                if reader.peek(b',') {
                    reader.expect(b',', "expected `,` between fields")?;
                    continue;
                }
                break;
            }
        }
        reader.expect(b'}', "expected `}` to end a record")?;
        items.push(record);
        if reader.peek(b',') {
            reader.expect(b',', "expected `,` between records")?;
            continue;
        }
        reader.expect(b']', "expected `]` to end a record list")?;
        break;
    }
    Ok(RecordList::from_items(&crate::widget::capability::EMPTY_RECORD_SCHEMA, items))
}

impl DesignerManifest {
    /// Reads a document written by [`capability_manifest_json`].    ///
    /// Every key this writer emits is required, and an unknown key is an error: a document that
    /// this reader half-understands is one whose next export would silently differ from its input,
    /// which is exactly the failure the round-trip check exists to catch.
    pub fn from_json(text: &str) -> Result<Self, ManifestParseError> {
        let mut reader = JsonReader::new(text);
        reader.expect(b'{', "expected `{` to start a document")?;

        // Protocol first, but a writer may order keys freely, so the version check happens
        // **after** the loop: a document that names a future protocol anywhere is refused as a
        // whole rather than read until the offending key and then abandoned, which would leave a
        // caller holding a half-built manifest.
        let mut protocol: Option<u32> = None;
        let mut library = String::new();
        let mut profile = String::new();
        let mut triple = String::new();
        let mut control = None;
        let mut aliases = Vec::new();
        let mut properties = Vec::new();
        let mut events = Vec::new();
        let mut commands = Vec::new();

        loop {
            let key = reader.read_key()?;
            match key.as_str() {
                k if k == keys::PROTOCOL => protocol = Some(reader.read_uint()?),
                k if k == keys::LIBRARY => library = reader.read_string()?,
                k if k == keys::PROFILE => profile = reader.read_string()?,
                k if k == keys::TRIPLE => triple = reader.read_string()?,
                k if k == keys::CONTROL => control = Some(reader.read_string()?),
                k if k == keys::ALIASES => aliases = read_string_array(&mut reader)?,
                k if k == keys::COMMANDS => {
                    reader.expect(b'[', "expected `[` to start the command list")?;
                    if !reader.peek(b']') {
                        loop {
                            commands.push(read_command(&mut reader)?);
                            if reader.peek(b',') {
                                reader.expect(b',', "expected `,`")?;
                                continue;
                            }
                            break;
                        }
                    }
                    reader.expect(b']', "expected `]` after the command list")?;
                }
                k if k == keys::PROPERTIES => {
                    reader.expect(b'[', "expected `[` to start the property list")?;
                    if !reader.peek(b']') {
                        loop {
                            properties.push(read_property(&mut reader)?);
                            if reader.peek(b',') {
                                reader.expect(b',', "expected `,`")?;
                                continue;
                            }
                            break;
                        }
                    }
                    reader.expect(b']', "expected `]` after the property list")?;
                }
                k if k == keys::EVENTS => {
                    reader.expect(b'[', "expected `[` to start the event list")?;
                    if !reader.peek(b']') {
                        loop {
                            events.push(read_event(&mut reader)?);
                            if reader.peek(b',') {
                                reader.expect(b',', "expected `,`")?;
                                continue;
                            }
                            break;
                        }
                    }
                    reader.expect(b']', "expected `]` after the event list")?;
                }
                other => {
                    return Err(ManifestParseError {
                        detail: format!("unexpected key `{other}` in a manifest"),
                    })
                }
            }
            if reader.peek(b',') {
                reader.expect(b',', "expected `,`")?;
                continue;
            }
            reader.expect(b'}', "expected `}` or `,` in a manifest")?;
            break;
        }

        // A document with no `protocol` key is protocol 1 by definition: every document written
        // before B26.01 lacked it, and reading them as v1 is what keeps an old project openable.
        let protocol = protocol.unwrap_or(MANIFEST_MIN_PROTOCOL_VERSION);
        if protocol > MANIFEST_PROTOCOL_VERSION {
            return Err(ManifestParseError {
                detail: format!(
                    "manifest protocol {protocol} is newer than this build understands \
                     ({MANIFEST_PROTOCOL_VERSION}); refusing to read it partially"
                ),
            });
        }

        Ok(Self {
            protocol,
            library,
            profile,
            triple,
            control: control.ok_or(ManifestParseError {
                detail: "the document does not name its control".into(),
            })?,
            aliases,
            properties,
            events,
            commands,
        })
    }
}

/// Serialises one control's designer-facing description.
///
/// This is the export half of the round trip. It reads the capability table for the structure and
/// the factory for each property's default value, sorts both lists by name, and writes the document
/// [`DesignerManifest::from_json`] reads.
///
/// # Why defaults are read rather than declared
///
/// The default value is what a designer shows for a freshly dropped control. Taking it from the
/// same call the property API uses means the panel and the runtime cannot disagree; a table of
/// defaults kept beside the schema would be a second answer to the same question.
///
/// # Errors
///
/// * [`ManifestExportError::UnknownControl`] — no control is registered under `control`.
/// * [`ManifestExportError::IncompleteDefaults`] — some property's default could not be read, so
///   the document would describe fewer properties than the control publishes.
#[cfg(full_widgets)]
pub fn designer_manifest(
    factory: &super::WidgetFactory,
    control: &str,
) -> Result<DesignerManifest, ManifestExportError> {
    let capability = factory.capability(control).ok_or(ManifestExportError::UnknownControl)?;

    let mut properties = Vec::with_capacity(capability.properties.len());
    for schema in capability.properties {
        let default_value = factory
            .schema_default_value(capability.kind, schema.name)
            .ok_or(ManifestExportError::IncompleteDefaults)?;
        properties.push(DesignerProperty {
            name: schema.name.into(),
            kind: schema.value_kind,
            readable: schema.readable,
            writable: schema.writable,
            tokens: schema.accepted_tokens.iter().map(|token| String::from(*token)).collect(),
            constraints: schema.constraints.iter().map(designer_constraint_from).collect(),
            default_value,
        });
    }
    properties.sort_by(|left, right| left.name.cmp(&right.name));

    let mut events: Vec<DesignerEvent> = capability
        .events
        .iter()
        .map(|schema| DesignerEvent {
            name: schema.name.into(),
            payload: schema.payload,
            shape: schema.shape,
        })
        .collect();
    events.sort_by(|left, right| left.name.cmp(&right.name));

    let mut commands: Vec<DesignerCommand> = capability
        .commands
        .iter()
        .filter_map(|command| {
            super::command_schema::command_schema(command, capability.properties)
                .map(|schema| designer_command_from(command, &schema))
        })
        .collect();
    commands.sort_by(|left, right| left.name.cmp(&right.name));

    let mut aliases: Vec<String> =
        capability.aliases.iter().map(|alias| String::from(*alias)).collect();
    aliases.sort();

    Ok(DesignerManifest {
        protocol: MANIFEST_PROTOCOL_VERSION,
        library: String::from(env!("CARGO_PKG_VERSION")),
        profile: String::from(crate::widget::capability::TargetSpec::current().profile),
        triple: String::from(crate::widget::capability::TargetSpec::current().triple),
        control: capability.canonical_name.into(),
        aliases,
        properties,
        events,
        commands,
    })
}

/// Serialises one control's designer-facing description as a JSON document.
///
/// The document is stable: the same capability table produces the same bytes, which is what makes
/// it usable as a checked-in artifact and what lets the round-trip check compare strings rather
/// than parse trees.
#[cfg(full_widgets)]
pub fn capability_manifest_json(
    factory: &super::WidgetFactory,
    control: &str,
) -> Result<String, ManifestExportError> {
    let manifest = designer_manifest(factory, control)?;
    let mut out = String::new();
    write_manifest(&mut out, &manifest);
    Ok(out)
}

/// Serialises an already-built manifest, for a caller that has one in hand.
pub fn manifest_to_json(manifest: &DesignerManifest) -> String {
    let mut out = String::new();
    write_manifest(&mut out, manifest);
    out
}

/// Serialises every control the factory knows, as a JSON array.
///
/// # Why an array and not an object keyed by name
///
/// Order is part of the contract: the entries are sorted by control name, and a designer building a
/// palette reads them in that order. An object keyed by name would make the order incidental and
/// the document harder to diff.
#[cfg(full_widgets)]
pub fn all_capability_manifests_json(
    factory: &super::WidgetFactory,
) -> Result<String, ManifestExportError> {
    let mut names: Vec<&str> =
        factory.capabilities().iter().map(|capability| capability.canonical_name).collect();
    names.sort_unstable();

    let mut out = String::from("[\n");
    for (index, name) in names.iter().enumerate() {
        let manifest = designer_manifest(factory, name)?;
        let mut body = String::new();
        write_manifest(&mut body, &manifest);
        // Indented by one level so the array reads as a list of documents rather than a run of
        // top-level objects.
        for line in body.lines() {
            if line.is_empty() {
                continue;
            }
            out.push_str("  ");
            out.push_str(line);
            out.push('\n');
        }
        if index + 1 != names.len() {
            out.push_str("  ,\n");
        }
    }
    out.push(']');
    out.push('\n');
    Ok(out)
}

/// Builds a [`DesignerConstraint`] from a runtime [`Constraint`](crate::widget::capability::Constraint).
///
/// The join between the two layers, kept here so the wire vocabulary (`"range"`/`"precision"`/
/// `"required"`) lives with the rest of the document's vocabulary while the semantics stay in
/// `types`. A variant added to the runtime enum without a case here fails to compile, which is the
/// property that keeps the two from drifting.
pub fn designer_constraint_from(
    constraint: &crate::widget::capability::Constraint,
) -> DesignerConstraint {
    use crate::widget::capability::Constraint as C;
    match constraint {
        C::Range(range) => DesignerConstraint {
            kind: "range",
            minimum: Some(range.minimum),
            maximum: Some(range.maximum),
            step: range.step,
            places: None,
        },
        C::Precision { places } => DesignerConstraint {
            kind: "precision",
            minimum: None,
            maximum: None,
            step: None,
            places: *places,
        },
        C::Required => DesignerConstraint {
            kind: "required",
            minimum: None,
            maximum: None,
            step: None,
            places: None,
        },
    }
}

/// The events a control publishes, as manifest entries.
///
/// Exposed so a consumer that already holds a manifest can reach the event list without going back
/// through the factory.
pub fn events_of_manifest(manifest: &DesignerManifest) -> &[DesignerEvent] {
    &manifest.events
}

impl From<&EventManifest> for DesignerEvent {
    fn from(manifest: &EventManifest) -> Self {
        Self { name: manifest.name.clone(), payload: manifest.payload, shape: manifest.shape }
    }
}

impl From<&PropertySchema> for (String, PropertyValueKind) {
    fn from(schema: &PropertySchema) -> Self {
        (schema.name.into(), schema.value_kind)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{Color, Rect};

    fn sample() -> DesignerManifest {
        DesignerManifest {
            protocol: MANIFEST_PROTOCOL_VERSION,
            library: String::from(env!("CARGO_PKG_VERSION")),
            profile: String::from("desktop"),
            triple: String::from("aarch64-apple-darwin"),
            control: String::from("slider"),
            aliases: vec![String::from("range")],
            properties: vec![DesignerProperty {
                name: String::from("value"),
                kind: PropertyValueKind::Int,
                readable: true,
                writable: true,
                tokens: Vec::new(),
                constraints: Vec::new(),
                default_value: CapabilityValue::Int(42),
            }],
            events: vec![DesignerEvent {
                name: String::from("value_changed"),
                payload: Some(PropertyValueKind::Int),
                shape: Some(EventPayloadShape::Scalar),
            }],
            commands: vec![DesignerCommand {
                name: String::from("set_value"),
                signature: "value",
                parameter: String::from("value"),
                kind: Some(PropertyValueKind::Int),
                arity: None,
                element: None,
                effect: "mutates-control",
            }],
        }
    }

    /// The round trip must reproduce the document byte for byte.
    #[test]
    fn a_manifest_round_trips_through_json() {
        let manifest = sample();
        let first = manifest_to_json(&manifest);
        let reloaded = DesignerManifest::from_json(&first).expect("the document this wrote parses");
        let second = manifest_to_json(&reloaded);
        assert_eq!(first, second, "export -> load -> export changed the document");
    }

    /// A record-list property's value survives the round trip **with its fields** (B26.09).
    ///
    /// The control that publishes one today starts empty, so the per-control round-trip check only
    /// ever exercises `[]`. That would leave the interesting half — field names, values and their
    /// order — untested, which is exactly the half the writer builds by hand.
    #[test]
    fn a_record_list_value_round_trips_with_its_fields() {
        let mut manifest = sample();
        let list = crate::widget::capability::RecordList::from_items(
            &crate::widget::capability::EMPTY_RECORD_SCHEMA,
            vec![
                crate::widget::capability::RecordValue::new()
                    .with("id", CapabilityValue::String(String::from("a")))
                    .with("label", CapabilityValue::String(String::from("Alpha")))
                    .with("selected", CapabilityValue::Bool(true))
                    .with("weight", CapabilityValue::Float(2.5)),
                // A field whose *name* needs escaping in the document, and one that is spelled
                // differently from its neighbour, so the order is what is compared rather than a set.
                crate::widget::capability::RecordValue::new()
                    .with("id", CapabilityValue::String(String::from("b\"c")))
                    .with("note", CapabilityValue::String(String::from("no label here"))),
            ],
        );
        let records = CapabilityValue::Records(list.clone());
        manifest.properties.push(DesignerProperty {
            name: String::from("items"),
            kind: crate::widget::capability::PropertyValueKind::Records,
            readable: true,
            writable: true,
            tokens: Vec::new(),
            constraints: Vec::new(),
            default_value: records.clone(),
        });

        let json = manifest_to_json(&manifest);
        let reloaded = DesignerManifest::from_json(&json).expect("the document this wrote parses");
        assert_eq!(manifest_to_json(&reloaded), json, "export -> load -> export changed it");

        let restored = &reloaded.properties[reloaded.properties.len() - 1].default_value;
        let CapabilityValue::Records(round_tripped) = restored else {
            panic!("`items` must come back as a record list, got {restored:?}");
        };
        // Field order is part of the value, so the whole list is compared — a set comparison would
        // accept a document whose fields were reordered.
        assert_eq!(round_tripped.items(), list.items());
        assert_eq!(
            round_tripped.get(0).expect("first").names(),
            vec!["id", "label", "selected", "weight"]
        );
        assert_eq!(round_tripped.get(0).expect("first").text("label"), "Alpha");
        assert_eq!(round_tripped.get(1).expect("second").text("id"), "b\"c");
        // The reloaded list carries no schema, like every other schema-free boundary.
        assert!(round_tripped.schema().fields.is_empty());
    }

    /// A payload-free event keeps its absence of a payload through the round trip.
    #[test]
    fn a_payload_free_event_round_trips_as_null() {
        let mut manifest = sample();
        manifest.events.push(DesignerEvent {
            name: String::from("slider_pressed"),
            payload: None,
            shape: None,
        });
        let json = manifest_to_json(&manifest);
        assert!(json.contains("\"payload\": null"), "a payload-free event must declare null");
        let reloaded = DesignerManifest::from_json(&json).expect("parses");
        assert_eq!(reloaded.events[1].payload, None);
        assert_eq!(reloaded.events[1].shape, None);
    }

    /// Every `CapabilityValue` variant survives, including the two structured ones.
    ///
    /// `Color` and `Rect` are written as the strings the capability table uses, so they come back
    /// as `String` — the round trip is over the *document*, and the schema's `kind` is what tells a
    /// consumer to interpret that string as a colour. Asserting `String` here rather than
    /// `Color`/`Rect` is the check that the writer did not invent a second representation.
    #[test]
    fn every_value_variant_round_trips() {
        let cases: [(CapabilityValue, CapabilityValue); 14] = [
            (CapabilityValue::Null, CapabilityValue::Null),
            (CapabilityValue::Bool(true), CapabilityValue::Bool(true)),
            (CapabilityValue::Bool(false), CapabilityValue::Bool(false)),
            (CapabilityValue::UInt(7), CapabilityValue::UInt(7)),
            (CapabilityValue::UInt(0), CapabilityValue::UInt(0)),
            (CapabilityValue::Float(1.5), CapabilityValue::Float(1.5)),
            (CapabilityValue::Int(-3), CapabilityValue::Int(-3)),
            // **The cases that used to lose their kind.** `Int(0)` and `Int(100)` are exactly what
            // `Slider`'s capability declares for `minimum`/`maximum`, and both were written as bare
            // numbers, which the reader necessarily took for `UInt`. The round trip was therefore
            // partial for the two defaults the table actually contains, not for a hypothetical
            // value — and the old test's only `Int` case was `Int(-3)`, whose sign made it the one
            // non-negative-free case that happened to work.
            (CapabilityValue::Int(0), CapabilityValue::Int(0)),
            (CapabilityValue::Int(100), CapabilityValue::Int(100)),
            (
                CapabilityValue::String(String::from("a \"quoted\" \\ value\nwith a newline")),
                CapabilityValue::String(String::from("a \"quoted\" \\ value\nwith a newline")),
            ),
            (
                CapabilityValue::String(String::from("Café ☕ Value")),
                CapabilityValue::String(String::from("Café ☕ Value")),
            ),
            (
                CapabilityValue::Color(Color::rgba(1, 2, 3, 4)),
                CapabilityValue::String(String::from("#01020304")),
            ),
            (
                CapabilityValue::IconSpec(crate::widget::icon_source::IconSpec::Builtin(
                    crate::widget::display_widgets::icon::IconName::Info,
                )),
                CapabilityValue::IconSpec(crate::widget::icon_source::IconSpec::Builtin(
                    crate::widget::display_widgets::icon::IconName::Info,
                )),
            ),
            (
                CapabilityValue::IconSpec(crate::widget::icon_source::IconSpec::Resource {
                    id: String::from("project/icons/a\"b\\c"),
                    color_mode: crate::widget::icon_source::IconColorMode::Monochrome,
                }),
                CapabilityValue::IconSpec(crate::widget::icon_source::IconSpec::Resource {
                    id: String::from("project/icons/a\"b\\c"),
                    color_mode: crate::widget::icon_source::IconColorMode::Monochrome,
                }),
            ),
        ];
        for (written, expected) in cases {
            let mut manifest = sample();
            manifest.properties[0].default_value = written.clone();
            let json = manifest_to_json(&manifest);
            let reloaded = DesignerManifest::from_json(&json)
                .unwrap_or_else(|error| panic!("{written:?} failed to parse: {error}"));
            assert_eq!(
                reloaded.properties[0].default_value, expected,
                "{written:?} did not survive the round trip"
            );
        }
    }

    #[test]
    fn icon_spec_manifest_rejects_unknown_conflicting_and_duplicate_fields() {
        let mut manifest = sample();
        manifest.properties[0].default_value =
            CapabilityValue::IconSpec(crate::widget::icon_source::IconSpec::Builtin(
                crate::widget::display_widgets::icon::IconName::Info,
            ));
        let valid = manifest_to_json(&manifest);
        for (from, to) in [
            (
                r#"{"kind":"builtin","name":"info"}"#,
                r#"{"kind":"builtin","name":"info","extra":"x"}"#,
            ),
            (
                r#"{"kind":"builtin","name":"info"}"#,
                r#"{"kind":"builtin","name":"info","id":"icons/info"}"#,
            ),
            (
                r#"{"kind":"builtin","name":"info"}"#,
                r#"{"kind":"builtin","name":"info","name":"save"}"#,
            ),
            (r#"{"kind":"builtin","name":"info"}"#, r#"{"kind":"builtin","name":"unknown-token"}"#),
        ] {
            let malformed = valid.replace(from, to);
            assert_ne!(malformed, valid, "fixture must replace the icon descriptor");
            assert!(
                DesignerManifest::from_json(&malformed).is_err(),
                "manifest accepted malformed icon descriptor: {to}"
            );
        }
    }

    /// A non-negative `Int` must not be written in the `UInt` spelling.
    ///
    /// The assertion above proves the *round trip* holds; this proves **how**, so a writer that
    /// stopped distinguishing the two would be caught here rather than by whichever test happened
    /// to compare the two kinds first.
    #[test]
    fn a_non_negative_int_carries_the_marker_that_distinguishes_it_from_a_uint() {
        let mut manifest = sample();
        manifest.properties[0].default_value = CapabilityValue::Int(100);
        let int_json = manifest_to_json(&manifest);
        assert!(
            int_json.contains("\"default\":+100") || int_json.contains(": +100"),
            "a non-negative `Int` must be marked with a leading `+`, or it is indistinguishable
             from `UInt`: {int_json}"
        );

        manifest.properties[0].default_value = CapabilityValue::UInt(100);
        let uint_json = manifest_to_json(&manifest);
        assert!(
            !uint_json.contains("+100"),
            "`UInt` keeps the bare spelling — the marker is what distinguishes the two: {uint_json}"
        );
        assert_ne!(int_json, uint_json, "the two kinds must not export identically");

        // A negative `Int` needs no marker: its sign is already unambiguous.
        manifest.properties[0].default_value = CapabilityValue::Int(-100);
        let negative_json = manifest_to_json(&manifest);
        assert!(negative_json.contains("-100"));
        assert!(!negative_json.contains("+-100"), "a negative must not also carry the marker");
    }

    /// Export → load → export must be a fixed point of the writer.
    ///
    /// The round-trip cases assert that one value survives; this asserts that a whole *document*
    /// does, which is the property a designer's save/load cycle actually needs. A value that
    /// reloads as a different kind re-exports to different bytes, so an equality check on the two
    /// exports catches every such case at once instead of one per kind.
    #[test]
    fn exporting_a_reloaded_document_reproduces_it_byte_for_byte() {
        let mut manifest = sample();
        manifest.properties[0].default_value = CapabilityValue::Int(100);
        let first = manifest_to_json(&manifest);
        let reloaded =
            DesignerManifest::from_json(&first).expect("a document this writer produced must load");
        let second = manifest_to_json(&reloaded);
        assert_eq!(
            first, second,
            "export → load → export must be stable; a value that changes kind on load is the
             reason it is not"
        );
    }

    /// A structured value must be written in the spelling the capability table uses.
    #[test]
    fn structured_values_use_the_property_api_spelling() {
        let mut manifest = sample();
        manifest.properties[0].default_value = CapabilityValue::Rect(Rect::new(-5, 6, 7, 8));
        let json = manifest_to_json(&manifest);
        assert!(
            json.contains("\"-5,6,7,8\""),
            "a rectangle must be written as the `x,y,w,h` string the property API accepts: {json}"
        );

        manifest.properties[0].default_value =
            CapabilityValue::Color(Color::rgba(0xdc, 0xdc, 0xdc, 0xff));
        let json = manifest_to_json(&manifest);
        assert!(json.contains("\"#dcdcdcff\""), "a colour must be written as `#rrggbbaa`: {json}");
    }

    /// A whole float must not come back as an integer.
    ///
    /// `format!("{}", 1.0f64)` is `"1"`, so a writer that does not add the fractional part produces
    /// a document that reads back as a different kind.
    #[test]
    fn a_whole_float_keeps_its_fractional_part() {
        let mut manifest = sample();
        manifest.properties[0].default_value = CapabilityValue::Float(1.0);
        let json = manifest_to_json(&manifest);
        assert!(json.contains("1.0"), "a float must be written so it reads back as a float");
        let reloaded = DesignerManifest::from_json(&json).expect("parses");
        assert_eq!(reloaded.properties[0].default_value, CapabilityValue::Float(1.0));
    }

    /// An unknown kind or shape must be refused rather than defaulted.
    ///
    /// The sentinel is `"quaternion"`, which is not a token this reader knows and is not
    /// about to be one. It used to be `"number"`, which stopped being a valid sentinel the
    /// moment `PropertyValueKind::Number` was added — the test then failed for the right
    /// reason (the token is accepted now) and had to move to a spelling that stays unknown.
    #[test]
    fn an_unrecognised_kind_is_refused() {
        let json =
            manifest_to_json(&sample()).replace("\"kind\": \"int\"", "\"kind\": \"quaternion\"");
        assert_ne!(json, manifest_to_json(&sample()), "the sentinel must actually appear");
        let result = DesignerManifest::from_json(&json);
        assert!(result.is_err(), "a kind this reader does not know must not be accepted");
    }

    /// A key this writer never emits must be refused, so a half-understood file cannot be read.
    #[test]
    fn an_unknown_key_is_refused() {
        let json = manifest_to_json(&sample()).replace("\"control\":", "\"controller\":");
        assert!(DesignerManifest::from_json(&json).is_err());
    }

    /// Truncated input must fail rather than return a partial document.
    #[test]
    fn a_truncated_document_is_refused() {
        let json = manifest_to_json(&sample());
        assert!(DesignerManifest::from_json(&json[..json.len() / 2]).is_err());
    }

    /// Every `PropertyValueKind` and `EventPayloadShape` token must survive its own mapping.
    #[test]
    fn every_token_maps_both_ways() {
        for kind in [
            PropertyValueKind::Bool,
            PropertyValueKind::Int,
            PropertyValueKind::UInt,
            PropertyValueKind::Float,
            PropertyValueKind::Number,
            PropertyValueKind::String,
            PropertyValueKind::Enum,
            PropertyValueKind::Color,
            PropertyValueKind::Rect,
        ] {
            assert_eq!(value_kind_from_token(value_kind_token(kind)), Some(kind));
        }
        for shape in [
            EventPayloadShape::Scalar,
            EventPayloadShape::OptionalScalar,
            EventPayloadShape::ListScalar,
            EventPayloadShape::Tuple2,
            EventPayloadShape::Tuple3,
            EventPayloadShape::Tuple4,
            EventPayloadShape::OptionalTuple2,
            EventPayloadShape::Mixed,
        ] {
            assert_eq!(shape_from_token(shape_token(shape)), Some(shape));
        }
        assert_eq!(value_kind_from_token("no_such_kind"), None);
        assert_eq!(shape_from_token("no_such_shape"), None);
    }

    /// The document must name its protocol, library, profile and triple (BLUE26 B26.01).
    ///
    /// Without these a designer cannot tell which build answered — the whole reason a manifest
    /// would otherwise read a `desktop` fact as a claim about a `mini` device.
    #[test]
    fn a_manifest_declares_its_protocol_and_target_scope() {
        let json = manifest_to_json(&sample());
        for key in ["\"protocol\":", "\"library\":", "\"profile\":", "\"triple\":"] {
            assert!(json.contains(key), "the document must name `{key}`: {json}");
        }
        assert!(
            json.contains(&format!("\"protocol\": {}", MANIFEST_PROTOCOL_VERSION)),
            "the written protocol must be the current version: {json}"
        );
        let reloaded = DesignerManifest::from_json(&json).expect("parses");
        assert_eq!(reloaded.protocol, MANIFEST_PROTOCOL_VERSION);
        assert_eq!(reloaded.library, env!("CARGO_PKG_VERSION"));
    }

    /// A document with no `protocol` key is read as version 1, not refused.
    ///
    /// Every project saved before B26.01 lacks the key, and reading them as v1 is what keeps an
    /// old project openable — the compatibility half of the protocol contract.
    #[test]
    fn a_protocol_one_document_is_still_readable() {
        // Strip the four new keys to reproduce the v1 shape exactly.
        let json = manifest_to_json(&sample());
        let stripped: String = json
            .lines()
            .filter(|line| {
                !line.contains("\"protocol\":")
                    && !line.contains("\"library\":")
                    && !line.contains("\"profile\":")
                    && !line.contains("\"triple\":")
            })
            .collect::<Vec<_>>()
            .join("\n");
        let reloaded = DesignerManifest::from_json(&stripped)
            .expect("a document without a protocol key is protocol 1");
        assert_eq!(reloaded.protocol, MANIFEST_MIN_PROTOCOL_VERSION);
    }

    /// A document naming a *newer* protocol must be refused, not partially read.
    ///
    /// A partial read of a future document is how a designer silently drops a field it does not
    /// understand and re-saves a lossy file, so the refusal is the point.
    #[test]
    fn a_future_protocol_version_is_refused() {
        let json = manifest_to_json(&sample()).replace(
            &format!("\"protocol\": {MANIFEST_PROTOCOL_VERSION}"),
            &format!("\"protocol\": {}", MANIFEST_PROTOCOL_VERSION + 1),
        );
        let result = DesignerManifest::from_json(&json);
        assert!(result.is_err(), "a newer protocol must be refused");
        let message = result.unwrap_err().detail;
        assert!(
            message.contains("newer"),
            "the refusal must say the document is newer, not just fail: {message}"
        );
    }

    /// A fractional or signed protocol value must be refused rather than truncated.
    #[test]
    fn a_malformed_protocol_value_is_refused() {
        for bad in ["\"protocol\": 2.5", "\"protocol\": -1", "\"protocol\": \"two\""] {
            let json = manifest_to_json(&sample())
                .replace(&format!("\"protocol\": {MANIFEST_PROTOCOL_VERSION}"), bad);
            assert!(
                DesignerManifest::from_json(&json).is_err(),
                "`{bad}` must not be read as a protocol version"
            );
        }
    }

    /// A command must carry its parameter shape and effect through the round trip (B26.03).
    ///
    /// A command used to be a bare string, which says nothing a designer can validate a binding
    /// against. This asserts the object form survives — a name plus the three facts a wire check
    /// needs (shape, parameter, effect).
    #[test]
    fn a_typed_command_round_trips() {
        let mut manifest = sample();
        manifest.commands = vec![
            DesignerCommand {
                name: String::from("set_value"),
                signature: "value",
                parameter: String::from("value"),
                kind: Some(PropertyValueKind::UInt),
                arity: None,
                element: None,
                effect: "mutates-control",
            },
            DesignerCommand {
                name: String::from("toggle"),
                signature: "none",
                parameter: String::new(),
                kind: None,
                arity: None,
                element: None,
                effect: "mutates-control",
            },
            DesignerCommand {
                name: String::from("set_range"),
                signature: "composite",
                parameter: String::from("lower"),
                kind: None,
                arity: Some(2),
                element: Some(PropertyValueKind::Float),
                effect: "mutates-control",
            },
        ];
        let json = manifest_to_json(&manifest);
        let reloaded = DesignerManifest::from_json(&json).expect("parses");
        assert_eq!(reloaded.commands, manifest.commands);
        assert_eq!(manifest_to_json(&reloaded), json, "the command objects must be stable");
        // The name must be a JSON key, not a bare element, so a reader sees a shape.
        assert!(json.contains("\"signature\": \"value\""), "{json}");
        assert!(json.contains("\"effect\": \"mutates-control\""), "{json}");
    }

    /// An unrecognised command signature or effect must be refused, not defaulted.
    #[test]
    fn a_malformed_command_shape_is_refused() {
        let json = manifest_to_json(&sample());
        let bad_sig = json.replace("\"signature\": \"value\"", "\"signature\": \"sausage\"");
        assert_ne!(bad_sig, json, "the signature sentinel must appear");
        assert!(DesignerManifest::from_json(&bad_sig).is_err());

        let bad_effect =
            json.replace("\"effect\": \"mutates-control\"", "\"effect\": \"explodes\"");
        assert_ne!(bad_effect, json, "the effect sentinel must appear");
        assert!(DesignerManifest::from_json(&bad_effect).is_err());
    }

    /// A property's constraints must survive the round trip (B26.02).
    #[test]
    fn a_constrained_property_round_trips() {
        use crate::widget::capability::{Constraint, RangeSpec};
        let mut manifest = sample();
        manifest.properties[0].constraints =
            vec![designer_constraint_from(&Constraint::Range(RangeSpec {
                minimum: 0.0,
                maximum: 1.0,
                step: Some(0.05),
            }))];
        let json = manifest_to_json(&manifest);
        assert!(json.contains("\"constraints\": ["), "the constraint list must appear: {json}");
        assert!(json.contains("\"rule\": \"range\""), "{json}");
        let reloaded = DesignerManifest::from_json(&json).expect("parses");
        assert_eq!(reloaded.properties[0].constraints, manifest.properties[0].constraints);
        assert_eq!(manifest_to_json(&reloaded), json, "the constraint must be byte-stable");
    }

    /// An unrecognised constraint kind must be refused, not silently dropped.
    #[test]
    fn a_malformed_constraint_is_refused() {
        use crate::widget::capability::{Constraint, RangeSpec};
        let mut manifest = sample();
        manifest.properties[0].constraints =
            vec![designer_constraint_from(&Constraint::Range(RangeSpec {
                minimum: 0.0,
                maximum: 1.0,
                step: None,
            }))];
        let json = manifest_to_json(&manifest);
        let bad = json.replace("\"rule\": \"range\"", "\"rule\": \"sausage\"");
        assert_ne!(bad, json, "the sentinel must appear");
        assert!(DesignerManifest::from_json(&bad).is_err());
    }
}