BREP_render 0.2.1

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
use super::*;

// ===========================================================================
// Import / export — the file-interchange lane (the ONE platform exception).
// STEP/IGES are text; STL/OBJ bytes are submitted to the background runner for
// RANSAC reconstruction, then return as validated STEP for IMPORT3D. Exports
// collect the CURRENT model's resident solids and serialize them.
// ===========================================================================
impl EngineState {
    /// Import an STL triangle mesh through topology-aware RANSAC recognition.
    /// Unsupported regions remain as validated facets, so every repairable
    /// source triangle reaches the resulting CAD body.
    pub fn import_stl_feature(&mut self, bytes: &[u8]) -> Result<String, String> {
        self.submit_mesh_import(crate::runner::MeshImportFormat::Stl, bytes.to_vec())
    }

    /// Import a Wavefront OBJ mesh through the same RANSAC reconstruction path.
    pub fn import_obj_feature(&mut self, text: &str) -> Result<String, String> {
        self.import_obj_bytes_feature(text.as_bytes())
    }

    /// Byte-oriented OBJ entry used by the picker so decoding also stays on the
    /// background runner with parsing and reconstruction.
    pub fn import_obj_bytes_feature(&mut self, bytes: &[u8]) -> Result<String, String> {
        self.submit_mesh_import(crate::runner::MeshImportFormat::Obj, bytes.to_vec())
    }

    fn submit_mesh_import(
        &mut self,
        format: crate::runner::MeshImportFormat,
        bytes: Vec<u8>,
    ) -> Result<String, String> {
        if bytes.is_empty() {
            return Err("mesh import failed: file is empty".into());
        }
        let id = self.next_mesh_import_id;
        self.next_mesh_import_id = self.next_mesh_import_id.wrapping_add(1);
        self.pending_mesh_imports.insert(id);
        self.runner
            .submit_mesh_import(crate::runner::MeshImportRequest { id, format, bytes });
        // InlineRunner completes now for tests/embedders. Production's native
        // thread and browser Worker return immediately and are polled per frame.
        self.pump();
        Ok(serde_json::json!({ "meshImport": "submitted", "id": id }).to_string())
    }

    /// Import a STEP document into the model: append an `IMPORT3D` feature whose
    /// `inputParams.stepText` is the raw ISO-10303-21 text (the exact headless
    /// source the kernel importer reads — no `fileToImport` data-URL marshaling
    /// needed), mint it a persistent-counter id, roll to it, and rebuild. Returns the
    /// build report JSON (imported bodies + any per-feature error). A non-STEP
    /// payload is refused up front so a bad upload never leaves a dead feature.
    pub fn import_step_feature(&mut self, step_text: &str) -> Result<String, String> {
        if !step_text.contains("ISO-10303-21") {
            return Err("not a STEP file (missing the ISO-10303-21 header)".into());
        }
        let id = self.next_feature_id(&crate::features::feature_short_name("IMPORT3D"));
        let feature = serde_json::json!({
            "type": "IMPORT3D",
            "inputParams": { "id": id, "stepText": step_text },
            "persistentData": {},
        });
        // Frame the imported body once the (possibly async) run lands — see
        // [`EngineState::pending_fit`]. An immediate fit here would frame the still
        // empty scene under a background runner (native thread / wasm worker).
        self.pending_fit = true;
        self.add_feature(&feature.to_string())
    }

    /// Export the CURRENT model's resident solids to an ISO-10303-21 STEP
    /// document. Collects the resident handles of the rolled-to model (a warm
    /// re-run of the same prefix the display scene was built from — see
    /// [`crate::pipeline::resident_solid_handles`]) and hands them to the kernel's
    /// [`brep_kernel::export_step_handles`], so the exact NURBS topology is
    /// serialized (never the display mesh). Errs clearly when the model is empty.
    pub fn export_step_text(&self) -> Result<String, String> {
        let request: HistoryRequest = serde_json::from_value(self.history.prefix_request())
            .map_err(|e| format!("export STEP: history request: {e}"))?;
        let handles: Vec<u32> = crate::pipeline::resident_solid_handles(&request)
            .into_iter()
            .map(|(_, handle)| handle)
            .collect();
        if handles.is_empty() {
            return Err("nothing to export: the model has no solids".into());
        }
        brep_kernel::export_step_handles(&handles, "Part", "MM", "")
    }

    /// Resident handle of the part's target sheet-metal body for a flat-pattern
    /// export. Enumerates the current resident solids (a warm re-run of the same
    /// prefix the display scene was built from, like the STEP lane) and keeps the
    /// ones carrying a sheet-metal tree; uses the SELECTED sheet-metal body if the
    /// selection names exactly one, else the SOLE sheet-metal body (the same
    /// auto-target SM.CUTOUT uses). Errs with the exact `"no sheet-metal body in
    /// the part"` when there is none, and loudly when several are ambiguous.
    fn flat_pattern_target_handle(&self) -> Result<u32, String> {
        let request: HistoryRequest = serde_json::from_value(self.history.prefix_request())
            .map_err(|e| format!("export flat pattern: history request: {e}"))?;
        let sheet_metal: Vec<(String, u32)> = crate::pipeline::resident_solid_handles(&request)
            .into_iter()
            .filter(|(_, handle)| brep_kernel::is_sheet_metal_handle(*handle))
            .collect();
        if sheet_metal.is_empty() {
            return Err("no sheet-metal body in the part".into());
        }
        // Prefer a selected sheet-metal body when the selection names exactly one.
        let selected: Vec<u32> = sheet_metal
            .iter()
            .filter(|(name, _)| self.emphasis.selected_solids.contains(name))
            .map(|(_, handle)| *handle)
            .collect();
        if let [handle] = selected.as_slice() {
            return Ok(*handle);
        }
        match sheet_metal.as_slice() {
            [(_, handle)] => Ok(*handle),
            _ => Err(
                "several sheet-metal bodies in the part — select the one to export".into(),
            ),
        }
    }

    /// Export the part's sheet-metal FLAT PATTERN (the unfold) as a DXF (R12
    /// ASCII) 2D vector document. Runs the unfold TRANSIENTLY off the target
    /// body's resident tree — no feature is added and history is not mutated. Errs
    /// (`"no sheet-metal body in the part"`) when the part carries no sheet metal.
    pub fn export_flat_pattern_dxf(&self) -> Result<String, String> {
        brep_kernel::flat_pattern_dxf(self.flat_pattern_target_handle()?)
    }

    /// Export the part's sheet-metal flat pattern as an SVG — the DXF sibling of
    /// [`Self::export_flat_pattern_dxf`].
    pub fn export_flat_pattern_svg(&self) -> Result<String, String> {
        brep_kernel::flat_pattern_svg(self.flat_pattern_target_handle()?)
    }

    /// Import an IGES document into the model: append an `IMPORT3D` feature whose
    /// `inputParams.igesText` is the raw IGES text (the kernel importer reads it
    /// via [`brep_kernel::import_iges`]), mint an id, roll to it, and rebuild.
    /// Refuses a non-IGES payload up front so a bad upload never leaves a dead
    /// feature.
    pub fn import_iges_feature(&mut self, iges_text: &str) -> Result<String, String> {
        if iges_text.contains("ISO-10303-21") {
            return Err("not an IGES file (this looks like a STEP document)".into());
        }
        // IGES records carry an S/G/D/P/T section letter in column 73.
        let looks_like_iges = iges_text.lines().any(|line| {
            matches!(line.chars().nth(72), Some('S' | 'G' | 'D' | 'P' | 'T'))
        });
        if !looks_like_iges {
            return Err("not an IGES file (no S/G/D/P/T section records found)".into());
        }
        let id = self.next_feature_id(&crate::features::feature_short_name("IMPORT3D"));
        let feature = serde_json::json!({
            "type": "IMPORT3D",
            "inputParams": { "id": id, "igesText": iges_text },
            "persistentData": {},
        });
        // Frame the imported body once the (possibly async) run lands — see
        // [`EngineState::pending_fit`] (mirrors the STEP lane above).
        self.pending_fit = true;
        self.add_feature(&feature.to_string())
    }

    /// Export the CURRENT model's resident solids to an IGES 5.3 document of
    /// trimmed NURBS surfaces — the IGES analogue of [`Self::export_step_text`],
    /// handing the resident handles to [`brep_kernel::export_iges_handles`].
    pub fn export_iges_text(&self) -> Result<String, String> {
        let request: HistoryRequest = serde_json::from_value(self.history.prefix_request())
            .map_err(|e| format!("export IGES: history request: {e}"))?;
        let handles: Vec<u32> = crate::pipeline::resident_solid_handles(&request)
            .into_iter()
            .map(|(_, handle)| handle)
            .collect();
        if handles.is_empty() {
            return Err("nothing to export: the model has no solids".into());
        }
        brep_kernel::export_iges_handles(&handles, "Part", "MM", "")
    }

    /// Export the CURRENT display scene to an ASCII STL string (one `solid` with a
    /// per-triangle geometric normal for every mesh triangle of every displayed
    /// solid). STL is a triangle-soup format with no multi-body concept, so all
    /// solids fold into a single `solid brep … endsolid brep`. String-shaped so it
    /// crosses the same string `ModelStore` seam the STEP lane uses. Errs when the
    /// scene has no triangles.
    pub fn export_stl_text(&self) -> Result<String, String> {
        let mut out = String::from("solid brep\n");
        let mut triangles = 0usize;
        for solid in self.scene.solids() {
            let positions = &solid.mesh.positions;
            for tri in solid.mesh.indices.chunks_exact(3) {
                let a = positions[tri[0] as usize];
                let b = positions[tri[1] as usize];
                let c = positions[tri[2] as usize];
                let normal = triangle_normal(a, b, c);
                out.push_str(&format!(
                    "  facet normal {} {} {}\n    outer loop\n",
                    normal[0], normal[1], normal[2]
                ));
                for v in [a, b, c] {
                    out.push_str(&format!("      vertex {} {} {}\n", v[0], v[1], v[2]));
                }
                out.push_str("    endloop\n  endfacet\n");
                triangles += 1;
            }
        }
        out.push_str("endsolid brep\n");
        if triangles == 0 {
            return Err("nothing to export: the scene has no triangles".into());
        }
        Ok(out)
    }
}

/// Unit (or zero, for a degenerate triangle) geometric normal of triangle
/// `(a, b, c)` — the per-facet normal an ASCII STL record carries.
fn triangle_normal(a: [f32; 3], b: [f32; 3], c: [f32; 3]) -> [f32; 3] {
    let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
    let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
    let n = [
        u[1] * v[2] - u[2] * v[1],
        u[2] * v[0] - u[0] * v[2],
        u[0] * v[1] - u[1] * v[0],
    ];
    let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
    if len > 0.0 {
        [n[0] / len, n[1] / len, n[2] / len]
    } else {
        [0.0, 0.0, 0.0]
    }
}

// ===========================================================================
// STRUCTURED STEP import — the assembly lane (kernel-plan
// `step-assembly-import.md` §3.7).
//
// The flat lane above (`import_step_feature`) appends ONE IMPORT3D holding the
// raw Part-21 text and lets the kernel bake every occurrence's world transform
// into its own body: N bodies, no parts, no tree. This lane keeps the structure
// instead — each unique geometry-bearing PRODUCT_DEFINITION becomes ONE
// parts-library entry holding a NATIVE payload (`nativeBrep`, no STEP text
// anywhere past this door), and each occurrence of it becomes an ACOMP instance
// carrying the composed world pose. Six bolts are then one entry × six
// instances, which is what makes the BOM, the structure tree, per-component
// selection and constraints work on imported geometry.
//
// # FLAT or NESTED — the user's choice, both correct
//
// [`StepAssemblyImport::nested`] picks between two shapes of the same geometry
// (kernel-plan §3.3):
//
// - **Flat** flattens the occurrence tree to its geometry-bearing leaves: one
//   ACOMP per leaf occurrence, each carrying the COMPOSED world pose. Every
//   part is stored once for the whole document.
// - **Nested** keeps the tree: each assembly-node product becomes a part
//   document that itself carries `{partsLibrary, features: [ACOMP…,
//   IMPORT3D…]}`, built bottom-up by the same recursive builder, and the
//   parent gets ONE ACOMP per sub-assembly occurrence. Build-spec §2.2's
//   rigid nesting — the sub-assembly arrives already-solved and moves as one
//   component, the live `ComponentMap` stays flat, and the structure tree
//   expands it read-only from the namespace chain (`ACOMP2:ACOMP1:…`).
//
// Neither is the deprecated one. Nested shows the real tree; flat is the right
// answer for a deep or pathological file, and it stores a part reused at two
// levels ONCE, where nesting stores it once PER LEVEL (build-spec §2.2). For a
// depth-1 tree the two lanes produce byte-identical documents — the cheapest
// correctness check there is, and `nested_matches_flat_for_a_depth_one_tree`
// asserts exactly it.
//
// # PROBE then CONSUME — because the parse is the expensive half
//
// The app must know the counts BEFORE it can offer the choice ("7 parts, 23
// instances — import as assembly or as bodies?"), and re-reading multi-MB
// Part-21 text after the user clicks would pay the file's single most expensive
// cost twice. So [`EngineState::probe_step_assembly`] performs the ONE parse and
// stashes the [`brep_kernel::StepAssembly`] in
// [`EngineState::pending_step_assembly`];
// [`EngineState::import_probed_step_assembly`] TAKES it. Cancel
// ([`EngineState::discard_probed_step_assembly`]), a second probe, and a
// document switch all drop it, so a user who cancels three imports is holding
// zero parsed assemblies — a real consideration, since the stash keeps every
// product's solids resident for as long as the dialog is open.
//
// # ONE rebuild for the whole import
//
// `add_feature` re-runs the entire history per call, so appending N instances
// through it is O(N²). This lane appends them all through
// [`EngineState::add_features`] — one push batch, one rebuild, one undo step.
// (Not `set_history_json`: that is the document-SWITCH path, which clears the
// kernel history cache and resets the runner's delta baseline.)
//
// # Fallback, never a silent zero
//
// No structure at all, or every geometry-bearing product failing to encode, both
// end at today's flat lane. "A successful import that produces zero components"
// is a failure wearing a result's clothes, so the zero-component case is an
// `Err` for the dialog-driven entry point (the app owns the file text and re-runs
// the flat import) and an automatic fall-back for the text-taking convenience.
// ===========================================================================

/// What the import dialog needs to describe a STEP file's structure — counts
/// only, so the probe can answer without building anything.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StepAssemblyProbe {
    /// Unique geometry-bearing products → parts-library entries. The floor, not
    /// the final count: a non-rigid occurrence bakes its own extra entry (§3.4).
    pub parts: usize,
    /// Geometry-bearing occurrences → ACOMP instance features.
    pub instances: usize,
    /// Longest root→node chain of occurrences. `1` is a flat assembly; `> 1`
    /// means sub-assemblies exist, so [`StepAssemblyImport::nested`] changes
    /// the shape of the result and the dialog's choice is worth offering.
    pub nested_depth: usize,
}

/// The choices the import dialog collects.
#[derive(Debug, Clone, Copy, Default)]
pub struct StepAssemblyImport {
    /// Build nested rigid sub-assembly documents (kernel-plan §3.3 Phase 2)
    /// instead of flattening the tree to its leaf occurrences.
    ///
    /// `false` (the `Default`) is the flat lane, byte-for-byte unchanged. On a
    /// depth-1 tree the two produce the same document, so this flag only ever
    /// matters for a file that really has sub-assemblies.
    pub nested: bool,
}

/// What an import did — the numbers the status line and notice report.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct StepAssemblyReport {
    /// Parts-library entries this import added or reused — the entries of the
    /// USER'S document. On a nested import that is the top level only: a
    /// sub-assembly's own entries live in ITS document's library, which the
    /// parent never sees.
    pub parts: usize,
    /// ACOMP instance features appended to the user's document. Nested: one per
    /// ROOT-level occurrence (a sub-assembly is one component, per build-spec
    /// §2.2), not one per leaf body.
    pub instances: usize,
    /// Occurrences whose non-rigid factor was baked into a distinct part
    /// (§3.4), summed over every level a nested import built.
    pub baked_nonrigid: usize,
    /// Products (or baked non-rigid variants of one) that did not encode to a
    /// payload — skipped and counted, never fatal: the importer's
    /// graceful-degradation contract, carried up to this altitude. Summed over
    /// every level a nested import built.
    pub failed_products: usize,
    /// The first thing that went wrong, from the kernel's body-build errors or
    /// this lane's own encode failures.
    pub first_error: Option<String>,
    /// The structured lane did not run: the file carries no usable structure, or
    /// nothing in it encoded, so the bodies were imported through the flat lane
    /// exactly as before. Only ever `true` from [`EngineState::import_step_assembly`],
    /// which holds the text; the dialog-driven entry point returns `Err` instead
    /// and lets its caller re-run the flat import it already has the text for.
    pub flat_fallback: bool,
}

/// The outcome of consuming a parsed assembly, before it is shaped into either
/// an `Err` (dialog lane) or a flat fallback (text lane) — so neither has to
/// recognise "nothing imported" by matching an error string.
enum Consumed {
    Imported(StepAssemblyReport),
    /// Every geometry-bearing product failed to encode: no components, so this
    /// is not an import.
    NoComponents {
        failed_products: usize,
        first_error: Option<String>,
    },
}

/// A row-major 4×4 affine, the shape `StepOccurrence::placement` and
/// `AffineTransform` both use.
type Mat4 = [f64; 16];

/// One node of the composed occurrence tree — a product at a world pose.
struct PlacedProduct {
    /// Index into `StepAssembly::products`.
    product: usize,
    /// Composed child-local → world transform.
    world: Mat4,
    /// Occurrence edges between a root and this node (`0` at a root).
    depth: usize,
    /// Every edge on the path here was rigid, so `world` IS a component pose.
    /// False means the non-rigid factor must be baked into the part (§3.4).
    rigid_path: bool,
}

/// A parts-library entry this import needs: a product, plus the bits of the
/// non-rigid factor baked into it (all-zero linear block ⇒ none). Two
/// occurrences of one product under DIFFERENT non-rigid factors are different
/// parts — never a wrong-handed reuse.
type PartKey = (usize, [u64; 9]);

/// The `PartKey` factor slot for a plain rigid instance.
const NO_FACTOR: [u64; 9] = [0; 9];

impl EngineState {
    /// Read a STEP file's product structure — THE parse of a structured import.
    /// Stashes the parsed assembly (with every product's solids) for
    /// [`Self::import_probed_step_assembly`] and returns the dialog's counts.
    ///
    /// `Ok(None)` = no usable structure (no NAUO edges, or none reaching built
    /// geometry): the caller imports through the flat
    /// [`Self::import_step_feature`] lane with the text it already holds, which
    /// is byte-for-byte today's behaviour. `Err` only for text that is not a
    /// Part 21 file at all — a BROKEN assembly degrades, it does not fail.
    ///
    /// Replaces any previously stashed assembly on EVERY outcome, `Ok(None)`
    /// included: a stale stash surviving a probe of a different file is how a
    /// consume silently imports the wrong one.
    pub fn probe_step_assembly(
        &mut self,
        step_text: &str,
    ) -> Result<Option<StepAssemblyProbe>, String> {
        self.pending_step_assembly = None;
        let Some(assembly) = brep_kernel::read_step_assembly(step_text)? else {
            return Ok(None);
        };
        let probe = probe_counts(&assembly);
        // The kernel already refuses a structure that reaches no geometry, so
        // this is belt-and-braces: an assembly with zero instances would import
        // as zero components, which is the silent failure this lane forbids.
        if probe.instances == 0 {
            return Ok(None);
        }
        self.pending_step_assembly = Some(assembly);
        Ok(Some(probe))
    }

    /// Import the assembly [`Self::probe_step_assembly`] stashed: one
    /// parts-library entry per unique product, one ACOMP instance per
    /// occurrence, ONE rebuild. TAKES the stash, so a double-import is an error
    /// rather than a double-insert.
    ///
    /// `doc_name` names products the file left unnamed (`{doc_name}-part-{id}`).
    /// `opts.nested` chooses between the flat and nested shapes — see
    /// [`StepAssemblyImport::nested`]. Errs when nothing is stashed, and when
    /// every product failed to encode — the latter being the caller's cue to
    /// re-run the flat import with the file text it holds.
    /// `sink` receives every unique part document so the app can write it to
    /// the model store and hand back a real `sourceKey`; pass [`EmbeddedOnly`]
    /// to keep the parts embedded (what a caller with no store does).
    pub fn import_probed_step_assembly(
        &mut self,
        doc_name: &str,
        opts: StepAssemblyImport,
        sink: &mut dyn PartSink,
    ) -> Result<StepAssemblyReport, String> {
        let assembly = self.pending_step_assembly.take().ok_or_else(|| {
            "import STEP assembly: nothing probed (call probe_step_assembly first)".to_string()
        })?;
        match self.consume_step_assembly(assembly, doc_name, opts.nested, sink) {
            Consumed::Imported(report) => Ok(report),
            Consumed::NoComponents { first_error, .. } => Err(format!(
                "import STEP assembly: no part of the assembly could be built{}",
                first_error
                    .map(|error| format!(" ({error})"))
                    .unwrap_or_default()
            )),
        }
    }

    /// Drop a probed assembly and the solids it holds resident — the dialog's
    /// Cancel. Idempotent.
    pub fn discard_probed_step_assembly(&mut self) {
        self.pending_step_assembly = None;
    }

    /// Probe + consume in one call, falling back to the flat lane by itself —
    /// the HEADLESS/test entry point. The app uses the probe/consume pair
    /// instead, because it has a dialog between the two halves.
    ///
    /// Still exactly one parse: this is `probe_step_assembly` followed by the
    /// consume of what it stashed.
    ///
    /// Parts stay EMBEDDED here ([`EmbeddedOnly`]): this entry point has no
    /// store handle and no way to ask for a destination. The app uses the
    /// probe/consume pair with a real sink.
    pub fn import_step_assembly(
        &mut self,
        step_text: &str,
        doc_name: &str,
        opts: StepAssemblyImport,
    ) -> Result<StepAssemblyReport, String> {
        let structured = self.probe_step_assembly(step_text)?.is_some();
        let outcome = structured.then(|| {
            let assembly = self
                .pending_step_assembly
                .take()
                .expect("a Some probe stashed the assembly it counted");
            self.consume_step_assembly(assembly, doc_name, opts.nested, &mut EmbeddedOnly)
        });
        match outcome {
            Some(Consumed::Imported(report)) => Ok(report),
            // No structure, or a structure nothing built out of: import the
            // bodies exactly as the pre-assembly lane did.
            Some(Consumed::NoComponents {
                failed_products,
                first_error,
            }) => {
                self.import_step_feature(step_text)?;
                Ok(StepAssemblyReport {
                    failed_products,
                    first_error,
                    flat_fallback: true,
                    ..StepAssemblyReport::default()
                })
            }
            None => {
                self.import_step_feature(step_text)?;
                Ok(StepAssemblyReport {
                    flat_fallback: true,
                    ..StepAssemblyReport::default()
                })
            }
        }
    }

    /// The import itself (kernel-plan §3.7 steps 2-5), shared by both entry
    /// points so neither has to recognise "nothing imported" from an error
    /// string.
    fn consume_step_assembly(
        &mut self,
        assembly: brep_kernel::StepAssembly,
        doc_name: &str,
        nested: bool,
        sink: &mut dyn PartSink,
    ) -> Consumed {
        let mut first_error = assembly.first_error.clone();
        // ONE writer for the whole import, so identical content is written to
        // the store exactly once however many products or LEVELS share it.
        let mut writer = PartWriter::new(sink);

        // --- what to build ------------------------------------------------
        // One row per component the USER'S document gets, each naming the
        // library entry it needs. Flat walks the whole tree to its leaves;
        // nested stops at the root's own children and folds everything below
        // each of them into that child's part document.
        let plan = if nested {
            plan_nested(&assembly, doc_name, &mut first_error, &mut writer)
        } else {
            plan_flat(&assembly, &mut first_error)
        };
        let Plan {
            wanted,
            factors,
            documents,
            mut failed_products,
            baked_below_root,
        } = plan;

        // --- build the library entries -------------------------------------
        // In (pd_ref, factor) order so an import is deterministic regardless of
        // the tree's emit order, and ONCE per key however many instances use it.
        let mut keys: Vec<PartKey> = wanted.iter().map(|(key, _)| *key).collect();
        keys.sort_unstable();
        keys.dedup();
        let mut entry_names: std::collections::HashMap<PartKey, String> =
            std::collections::HashMap::new();
        {
            // THE metadata bracket. `native_import_payload` seals whatever record
            // this thread's scene-metadata store holds for each name it stamps —
            // right for a snapshot of the live scene, catastrophic here: a new
            // part whose stamped face names collide with names already in THIS
            // document would silently carry the current document's metadata.
            // Scoped to the encode alone; the rebuild below stamps records the
            // document must keep, and this guard's drop would discard them.
            //
            // The nested lane's payloads are encoded inside `plan_nested`,
            // which holds a bracket of its own for exactly the same reason.
            let _isolation = brep_kernel::IsolatedSceneMetadata::begin();
            for key in &keys {
                // Nested pre-built the whole document (a sub-assembly's is a
                // recursive `{partsLibrary, features}`); flat builds the §3.2
                // native part document right here.
                let built = match documents.get(key) {
                    Some((name, document)) => install_part(name, document, &mut writer),
                    None => {
                        let product = assembly
                            .products
                            .iter()
                            .find(|product| product.pd_ref == key.0)
                            .expect("every key names a product of this assembly");
                        build_library_entry(product, factors.get(key), doc_name, &mut writer)
                    }
                };
                match built {
                    Ok(name) => {
                        entry_names.insert(*key, name);
                    }
                    Err(error) => {
                        failed_products += 1;
                        note(&mut first_error, error);
                    }
                }
            }
        }
        if entry_names.is_empty() {
            return Consumed::NoComponents {
                failed_products,
                first_error,
            };
        }

        // --- append every instance in ONE history mutation -----------------
        // `insert_component`'s rule, verbatim: ground the FIRST component only
        // when the document has none yet. Grounding a second one over-constrains
        // the next solve.
        let mut ground_next = !(0..self.history.len()).any(|index| {
            matches!(
                self.history.feature_type(index).as_deref(),
                Some("ACOMP") | Some("ASSEMBLY COMPONENT")
            )
        });
        let mut features: Vec<serde_json::Value> = Vec::with_capacity(wanted.len());
        let mut baked_nonrigid = 0usize;
        for (key, pose) in &wanted {
            let Some(part_name) = entry_names.get(key) else {
                continue; // this product failed to encode; counted above
            };
            let transform = match brep_kernel::AffineTransform::new(*pose) {
                Ok(transform) => transform,
                Err(error) => {
                    note(&mut first_error, format!("occurrence pose: {error}"));
                    continue;
                }
            };
            if key.1 != NO_FACTOR {
                baked_nonrigid += 1;
            }
            features.push(serde_json::json!({
                "type": "ACOMP",
                "inputParams": {
                    "id": self.history.next_feature_id("ACOMP"),
                    "partName": part_name,
                    "transform": brep_kernel::transform_to_pose_params(&transform),
                    "isFixed": ground_next,
                },
                "persistentData": {}
            }));
            ground_next = false;
        }
        if features.is_empty() {
            return Consumed::NoComponents {
                failed_products,
                first_error,
            };
        }

        // The library block must ride the request so the display runner ingests
        // the new entries on the very next run (as `insert_component` does).
        // Written only now that there are components to reference them, so an
        // import that produced nothing leaves the document untouched.
        if let Ok(library) =
            serde_json::from_str::<serde_json::Value>(&brep_kernel::parts_library_json())
        {
            self.history.set_parts_library(library);
        }
        // Frame the assembly once the (possibly async) run lands — see
        // [`EngineState::pending_fit`], same reasoning as `import_step_feature`.
        self.pending_fit = true;
        let instances = features.len();
        let baked_nonrigid = baked_nonrigid + baked_below_root;
        self.add_features(&features);
        Consumed::Imported(StepAssemblyReport {
            // DISTINCT entries, not distinct keys: `add_part_to_library` reuses
            // an entry whose content already matches, so two products that are
            // the same geometry collapse to one part (§3.5's free content dedup).
            parts: entry_names
                .values()
                .collect::<std::collections::HashSet<_>>()
                .len(),
            instances,
            baked_nonrigid,
            failed_products,
            first_error,
            flat_fallback: false,
        })
    }
}

/// What one import decided to build, before any of it is installed: the rows
/// the user's document gets, and whatever each lane needed to work out on the
/// way there.
#[derive(Default)]
struct Plan {
    /// One row per component of the USER'S document, in emit order.
    wanted: Vec<(PartKey, Mat4)>,
    /// FLAT only: the non-rigid factor a key's part must bake (§3.4). The
    /// nested lane bakes inside its own builder and hands the finished document
    /// over in `documents` instead.
    factors: std::collections::HashMap<PartKey, Mat4>,
    /// NESTED only: `(entry name, part document)` per key, already built — a
    /// leaf's §3.2 native document, or a sub-assembly's recursive
    /// `{partsLibrary, features}`.
    documents: std::collections::HashMap<PartKey, (String, serde_json::Value)>,
    /// Products that did not encode while planning (nested builds payloads
    /// during the plan; flat builds them during the install).
    failed_products: usize,
    /// Non-rigid occurrences baked BELOW the root — nested only, since the flat
    /// lane has no below-the-root and counts its bakes at install time.
    baked_below_root: usize,
}

/// **FLAT** (kernel-plan §3.3 Phase 1): flatten the occurrence tree to its
/// geometry-bearing nodes, each carrying the COMPOSED world pose. Byte-for-byte
/// the lane A6 shipped.
fn plan_flat(assembly: &brep_kernel::StepAssembly, first_error: &mut Option<String>) -> Plan {
    let mut plan = Plan::default();
    for placed in &compose_world_occurrences(assembly) {
        let product = &assembly.products[placed.product];
        if product.bodies.is_empty() {
            continue; // a pure assembly node contributes structure, not a component
        }
        let (key, pose) = if placed.rigid_path {
            ((product.pd_ref, NO_FACTOR), placed.world)
        } else {
            // §3.4: world = rigid · factor. Bake `factor` into a distinct part
            // and give the instance the rigid residue, so a mirrored instance
            // never lands on its unmirrored twin.
            match split_rigid(&placed.world) {
                // Non-rigid edges that cancel out along the path leave an
                // identity factor: that is an ordinary instance of the ordinary
                // part, not a bake.
                Ok((rigid, factor)) if is_identity(&factor) => {
                    ((product.pd_ref, NO_FACTOR), rigid)
                }
                Ok((rigid, factor)) => {
                    let key = (product.pd_ref, factor_key(&factor));
                    plan.factors.insert(key, factor);
                    (key, rigid)
                }
                Err(error) => {
                    note(first_error, error);
                    continue;
                }
            }
        };
        plan.wanted.push((key, pose));
    }
    plan
}

/// **NESTED** (kernel-plan §3.3 Phase 2): the live document plays the ROOT, so
/// it gets one component per root-level row and nothing deeper —
///
/// - a root's OWN bodies become a leaf part at identity (exactly the flat
///   lane's treatment of interior geometry at the root), and
/// - each root-child occurrence becomes ONE component: a leaf part when the
///   child has no children of its own, else a rigid sub-assembly whose part
///   document carries its own `partsLibrary` and its own ACOMPs.
///
/// Emit order matches [`plan_flat`]'s DFS pre-order — root before its children,
/// children by ascending `nauo_ref` — which is what makes the two lanes produce
/// the SAME document for a depth-1 tree.
fn plan_nested(
    assembly: &brep_kernel::StepAssembly,
    doc_name: &str,
    first_error: &mut Option<String>,
    writer: &mut PartWriter<'_>,
) -> Plan {
    // The same bracket the install loop holds, for the same reason: every
    // payload this builder encodes (at every level) must see an empty ambient
    // scene-metadata store, or a nested leaf whose stamped face names collide
    // with the live document's silently inherits the live document's records.
    let _isolation = brep_kernel::IsolatedSceneMetadata::begin();
    let mut build = NestedBuild {
        assembly,
        doc_name,
        writer,
        memo: std::collections::HashMap::new(),
        factors: std::collections::HashMap::new(),
        entries: 0,
        bytes: 0,
        failed_products: 0,
        baked_nonrigid: 0,
        first_error: None,
    };
    let mut plan = Plan::default();
    for &root in &assembly.roots {
        let mut rows: Vec<(DocKey, Mat4)> = Vec::new();
        // The root's OWN bodies become a leaf part at identity — exactly the
        // flat lane's treatment, and the reason a depth-1 tree comes out the
        // same either way.
        if !assembly.products[root].bodies.is_empty() {
            rows.push((
                DocKey::Leaf((assembly.products[root].pd_ref, NO_FACTOR)),
                MAT4_IDENTITY,
            ));
        }
        // Root-level bakes are counted by the install loop's own pass over
        // `wanted` (they are ordinary top-level rows); only bakes BELOW the root
        // — which never become rows of the user's document — are counted here.
        let mut root_level_bakes = 0usize;
        build.place_children(root, &[root], &mut rows, &mut root_level_bakes);
        for (key, pose) in rows {
            let part = match build.document(key, &mut vec![root]) {
                Ok(Some(document)) => document,
                // A subtree with no geometry anywhere places nothing — the flat
                // lane says the same thing by emitting no component for it.
                Ok(None) => continue,
                Err(error) => {
                    build.failed_products += 1;
                    note(&mut build.first_error, error);
                    continue;
                }
            };
            let part_key = key.part_key(assembly);
            plan.documents.insert(part_key, part);
            plan.wanted.push((part_key, pose));
        }
    }
    plan.failed_products = build.failed_products;
    plan.baked_below_root = build.baked_nonrigid;
    if let Some(error) = build.first_error {
        note(first_error, error);
    }
    plan
}

/// How deep the recursive builder will go before it refuses. `read_step_assembly`
/// guards cycles inside its own walk and [`NestedBuild::document`] guards them
/// again along the recursion path, so this is the SECOND line: a malformed file
/// that is merely pathologically deep (rather than cyclic) must not run the
/// native stack out. Sixty-four levels of embedded documents is already far past
/// anything a real CAD assembly carries — and each level embeds the whole
/// subtree below it, so the document would be unusable long before then.
const MAX_NESTED_DEPTH: usize = 64;

/// How many DISTINCT part documents a nested import may build. Bounds the
/// builder's work; it does NOT bound the result's size — see
/// [`MAX_NESTED_BYTES`], which is the guard that matters.
const MAX_NESTED_ENTRIES: usize = 10_000;

/// How many bytes of part document a nested import may EMBED, summed over every
/// `partsLibrary` entry it writes at every level.
///
/// This is the guard neither the depth cap nor the entry count provides. A
/// product reachable at many different depths is stored once PER LEVEL
/// (build-spec §2.2) — the memo builds its document once, but each parent
/// embeds a COPY, so a diamond-shaped structure well inside the depth cap can
/// still multiply out geometrically. Charging the embedded bytes is the only
/// place that multiplication is visible, so it is charged where it happens.
const MAX_NESTED_BYTES: usize = 256 * 1024 * 1024;

/// What a nested part document is memoised under. A product is either a leaf
/// (no occurrence children) or an assembly node, never both, so the two
/// variants can never name the same product — except at a ROOT, whose own
/// bodies become a leaf part while the root itself is an assembly node. That
/// case is exactly why this is an enum and not a bare [`PartKey`].
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
enum DocKey {
    /// A geometry-bearing product placed as a part: `(pd_ref, baked factor)`.
    Leaf(PartKey),
    /// A product placed as a rigid sub-assembly, by index into `products`.
    Assembly(usize),
}

impl DocKey {
    /// The parts-library identity this document is stored under. Always keyed on
    /// the `pd_ref` (never the product INDEX, which lives in a different number
    /// space and would collide with some other product's `pd_ref`). An assembly
    /// node never carries a baked factor — a non-rigid edge into one is skipped,
    /// see [`NestedBuild::place_children`] — so `NO_FACTOR` is exact.
    fn part_key(self, assembly: &brep_kernel::StepAssembly) -> PartKey {
        match self {
            DocKey::Leaf(key) => key,
            DocKey::Assembly(product) => (assembly.products[product].pd_ref, NO_FACTOR),
        }
    }
}

/// The recursive builder behind [`plan_nested`]: turns one product into the part
/// document that represents it, bottom-up, memoised so a product reached from
/// several parents is built ONCE however many places embed it.
struct NestedBuild<'a, 'w> {
    assembly: &'a brep_kernel::StepAssembly,
    doc_name: &'a str,
    /// Where a CHILD library entry's document is written, shared with the
    /// top-level install loop so one part is one file at every level.
    writer: &'a mut PartWriter<'w>,
    /// `None` = this subtree carries no geometry at all, so nothing places it.
    memo: std::collections::HashMap<DocKey, Option<(String, serde_json::Value)>>,
    /// The non-rigid factor behind every baked [`DocKey::Leaf`] key, so the
    /// builder never has to reconstruct a matrix out of its own hash key.
    factors: std::collections::HashMap<PartKey, Mat4>,
    entries: usize,
    /// Bytes of part document embedded so far — the [`MAX_NESTED_BYTES`] charge.
    bytes: usize,
    failed_products: usize,
    baked_nonrigid: usize,
    first_error: Option<String>,
}

impl NestedBuild<'_, '_> {
    /// The part document for `key`, built once and reused. `ancestors` is the
    /// recursion path — the cycle guard, and the depth the cap is measured on.
    ///
    /// A cyclic file gets ONE deterministic truncation: the memo keeps whichever
    /// path reached a node first, and that path's skipped back-edge is the one
    /// every embedding sees. Deterministic and finite is the whole contract for
    /// input that is malformed by construction.
    fn document(
        &mut self,
        key: DocKey,
        ancestors: &mut Vec<usize>,
    ) -> Result<Option<(String, serde_json::Value)>, String> {
        if let Some(hit) = self.memo.get(&key) {
            return Ok(hit.clone());
        }
        if ancestors.len() >= MAX_NESTED_DEPTH {
            return Err(format!(
                "nested import: sub-assembly nesting deeper than {MAX_NESTED_DEPTH} levels \
                 (import as bodies, or import flat)"
            ));
        }
        let built = match key {
            DocKey::Leaf(part) => self.leaf_document(part),
            DocKey::Assembly(product) => {
                ancestors.push(product);
                let built = self.assembly_document(product, ancestors);
                ancestors.pop();
                built
            }
        }?;
        self.memo.insert(key, built.clone());
        Ok(built)
    }

    /// A geometry-bearing product as the §3.2 part document — the same one the
    /// flat lane installs, built by the same helper, so a depth-1 nested import
    /// and a flat one store byte-identical entries.
    fn leaf_document(
        &mut self,
        key: PartKey,
    ) -> Result<Option<(String, serde_json::Value)>, String> {
        let product = self
            .assembly
            .products
            .iter()
            .find(|product| product.pd_ref == key.0)
            .expect("every key names a product of this assembly");
        if product.bodies.is_empty() {
            return Ok(None);
        }
        let factor = self.factors.get(&key).copied();
        self.spend_entry()?;
        native_part_document(product, factor.as_ref(), self.doc_name).map(Some)
    }

    /// An assembly-node product as a rigid sub-assembly document: its OWN bodies
    /// as plain native IMPORT3D features (the interior-node geometry Phase 1
    /// could only make a SIBLING of its own children), one ACOMP per child
    /// occurrence, and the children's documents in this level's own
    /// `partsLibrary`.
    ///
    /// The entries carry NO snapshot. An entry with an unreadable snapshot heals
    /// from its embedded document (`assembly_component.rs`'s SELF-HEAL lane),
    /// and for a native part that heal is a decode + re-encode — so the level
    /// above bakes this whole subtree into ITS snapshot on insert, and these
    /// inner caches would only ever be rebuilt to be thrown away. Kernel-plan §6
    /// names this exact economy ("omit the persisted snapshot for an entry whose
    /// document is a single native IMPORT3D"); nesting is where it pays, because
    /// otherwise every level stores the level below it twice.
    fn assembly_document(
        &mut self,
        product: usize,
        ancestors: &mut Vec<usize>,
    ) -> Result<Option<(String, serde_json::Value)>, String> {
        let node = &self.assembly.products[product];
        let mut library = serde_json::Map::new();
        let mut features: Vec<serde_json::Value> = Vec::new();

        // The node's own bodies first, matching the flat lane's "a node before
        // its children" emit order.
        if !node.bodies.is_empty() {
            let payload = brep_kernel::native_import_payload_with_appearance(
                "IMPORT3D1",
                &node.bodies,
                &node.appearances,
            )
            .map_err(|error| format!("part '{}': {error}", part_name(node, self.doc_name)))?;
            features.push(serde_json::json!({
                "type": "IMPORT3D",
                "inputParams": { "id": "IMPORT3D1", "nativeBrep": payload },
                "persistentData": {},
            }));
        }

        // One ACOMP per child occurrence, children by ascending `nauo_ref`.
        let mut rows: Vec<(DocKey, Mat4)> = Vec::new();
        let mut bakes = 0usize;
        self.place_children(product, ancestors, &mut rows, &mut bakes);
        self.baked_nonrigid += bakes;
        let mut names: std::collections::HashMap<DocKey, String> =
            std::collections::HashMap::new();
        // `add_part_to_library`'s content reuse, applied to this level's block:
        // two products that are the SAME geometry collapse to one entry (§3.5's
        // free dedup), and every instance of either references it.
        let mut by_signature: std::collections::HashMap<String, String> =
            std::collections::HashMap::new();
        let mut components = 0usize;
        for (key, pose) in rows {
            let name = match names.get(&key) {
                Some(name) => name.clone(),
                None => {
                    let built = match self.document(key, ancestors) {
                        Ok(Some(built)) => built,
                        Ok(None) => continue,
                        Err(error) => {
                            self.failed_products += 1;
                            note(&mut self.first_error, error);
                            continue;
                        }
                    };
                    let serialized = built.1.to_string();
                    let signature = document_signature(&serialized);
                    let name = match by_signature.get(&signature) {
                        Some(name) => name.clone(),
                        None => {
                            // Charged HERE, at the embedding, because that is
                            // where a product stored once per level multiplies.
                            self.spend_bytes(serialized.len())?;
                            // Unique WITHIN this level's library — parent and
                            // child libraries are independent (build-spec §2.2),
                            // so a name taken upstairs is free down here.
                            let name = unique_entry_name(&library, &built.0);
                            // A nested child is a part like any other: it gets
                            // its own store document and a REAL sourceKey, so
                            // Open Part and update-components work the same way
                            // however deep it sits.
                            let source_key =
                                self.writer.key_for(&name, &serialized, &signature);
                            library.insert(
                                name.clone(),
                                serde_json::json!({
                                    "sourceKey": source_key,
                                    "sourceSignature": signature.clone(),
                                    "document": built.1,
                                    "snapshot": "",
                                }),
                            );
                            by_signature.insert(signature, name.clone());
                            name
                        }
                    };
                    names.insert(key, name.clone());
                    name
                }
            };
            let Ok(transform) = brep_kernel::AffineTransform::new(pose) else {
                note(
                    &mut self.first_error,
                    format!("sub-assembly '{name}': occurrence pose is not an affine"),
                );
                continue;
            };
            components += 1;
            features.push(serde_json::json!({
                "type": "ACOMP",
                "inputParams": {
                    // Its OWN counter, so the ids read `ACOMP1..n` whether or
                    // not this node also owns bodies. (The id must match
                    // `ACOMP<digits>`: it IS the namespace prefix.)
                    "id": format!("ACOMP{components}"),
                    "partName": name,
                    "transform": brep_kernel::transform_to_pose_params(&transform),
                    // Written EXPLICITLY rather than left to the kernel's
                    // auto-ground rule, which keys on ABSENCE: the first
                    // component of an assembly is grounded, and every other one
                    // must not be, or the next solve is over-constrained.
                    "isFixed": components == 1,
                },
                "persistentData": {},
            }));
        }

        // A node whose whole subtree failed to produce geometry places nothing.
        // Returning `None` rather than a feature-less document matters: an empty
        // document is a hard error inside `add_part_to_library`, which would turn
        // "there was nothing here" into "the import failed".
        if features.is_empty() {
            return Ok(None);
        }
        self.spend_entry()?;
        Ok(Some((
            part_name(node, self.doc_name),
            serde_json::json!({ "partsLibrary": library, "features": features }),
        )))
    }

    /// The child occurrences of `product`, as `(document key, pose)` rows in the
    /// kernel walk's order — ascending `nauo_ref`, with the same ancestor cycle
    /// guard. The pose is the occurrence's own child→parent placement: nesting
    /// is precisely what stops it having to be composed.
    fn place_children(
        &mut self,
        product: usize,
        ancestors: &[usize],
        rows: &mut Vec<(DocKey, Mat4)>,
        bakes: &mut usize,
    ) {
        let mut children: Vec<&brep_kernel::StepOccurrence> = self
            .assembly
            .occurrences
            .iter()
            .filter(|occurrence| occurrence.parent == product)
            .collect();
        children.sort_by_key(|occurrence| occurrence.nauo_ref);
        for occurrence in children {
            if ancestors.contains(&occurrence.child) {
                note(
                    &mut self.first_error,
                    format!(
                        "occurrence #{} closes a cycle in the product structure and was skipped",
                        occurrence.nauo_ref
                    ),
                );
                continue;
            }
            let child = &self.assembly.products[occurrence.child];
            let is_assembly = self
                .assembly
                .occurrences
                .iter()
                .any(|edge| edge.parent == occurrence.child);
            if occurrence.rigid {
                let key = if is_assembly {
                    DocKey::Assembly(occurrence.child)
                } else {
                    DocKey::Leaf((child.pd_ref, NO_FACTOR))
                };
                rows.push((key, occurrence.placement));
                continue;
            }
            // §3.4 on a single edge: a leaf bakes its non-rigid factor into its
            // own part, exactly as the flat lane does with the composed pose.
            match split_rigid(&occurrence.placement) {
                Ok((rigid, factor)) if is_identity(&factor) => {
                    let key = if is_assembly {
                        DocKey::Assembly(occurrence.child)
                    } else {
                        DocKey::Leaf((child.pd_ref, NO_FACTOR))
                    };
                    rows.push((key, rigid));
                }
                // A mirrored/scaled SUB-ASSEMBLY would have to push its factor
                // down through a whole document tree, rewriting every level's
                // poses. Nothing in the corpus does it, and a wrong answer here
                // would be a silently mis-handed assembly: skip and say so, so
                // the user can re-import flat (which bakes it correctly).
                Ok(_) if is_assembly => {
                    note(
                        &mut self.first_error,
                        format!(
                            "occurrence #{} places sub-assembly '{}' with a non-rigid transform, \
                             which a nested import cannot represent — import flat instead",
                            occurrence.nauo_ref,
                            part_name(child, self.doc_name)
                        ),
                    );
                }
                Ok((rigid, factor)) => {
                    *bakes += 1;
                    let key = (child.pd_ref, factor_key(&factor));
                    self.factors.insert(key, factor);
                    rows.push((DocKey::Leaf(key), rigid));
                }
                Err(error) => note(&mut self.first_error, error),
            }
        }
    }

    /// Charge one built part document against [`MAX_NESTED_ENTRIES`].
    fn spend_entry(&mut self) -> Result<(), String> {
        self.entries += 1;
        if self.entries > MAX_NESTED_ENTRIES {
            return Err(format!(
                "nested import: more than {MAX_NESTED_ENTRIES} distinct parts \
                 (import as bodies, or import flat)"
            ));
        }
        Ok(())
    }

    /// Charge one embedded part document against [`MAX_NESTED_BYTES`].
    fn spend_bytes(&mut self, bytes: usize) -> Result<(), String> {
        self.bytes = self.bytes.saturating_add(bytes);
        if self.bytes > MAX_NESTED_BYTES {
            return Err(format!(
                "nested import: the embedded sub-assembly documents exceed \
                 {} MB (import as bodies, or import flat)",
                MAX_NESTED_BYTES / (1024 * 1024)
            ));
        }
        Ok(())
    }
}

/// A part name not yet used in THIS level's library: `requested`, else
/// `requested-2`, `requested-3`, … — the kernel `parts_library::unique_name`
/// convention, applied to an embedded block the kernel never sees inserted.
fn unique_entry_name(library: &serde_json::Map<String, serde_json::Value>, requested: &str) -> String {
    if !library.contains_key(requested) {
        return requested.to_string();
    }
    (2..)
        .map(|counter| format!("{requested}-{counter}"))
        .find(|candidate| !library.contains_key(candidate))
        .expect("the counter loop is unbounded")
}

/// Keep the FIRST thing that went wrong (the report carries one, and the first
/// is the one that explains the rest).
fn note(slot: &mut Option<String>, error: String) {
    if slot.is_none() {
        *slot = Some(error);
    }
}

/// Encode one product as a parts-library entry and return the EFFECTIVE entry
/// name the instances must reference (`add_part_to_library` disambiguates a name
/// clash and REUSES an entry with identical content, which is where cross-import
/// dedup comes from).
///
/// `factor`, when present, is the non-rigid part of an occurrence's placement:
/// applied to the geometry HERE, so the instance can carry a rigid pose (§3.4).
fn build_library_entry(
    product: &brep_kernel::StepProduct,
    factor: Option<&Mat4>,
    doc_name: &str,
    writer: &mut PartWriter<'_>,
) -> Result<String, String> {
    let (name, document) = native_part_document(product, factor, doc_name)?;
    install_part(&name, &document, writer)
}

/// The §3.2 part document for one product's OWN bodies: ONE IMPORT3D whose only
/// input is the native payload, plus the library name it wants. No STEP text is
/// stored anywhere — a rebuild of this part is a base64 decode, not a re-parse.
///
/// `factor`, when present, is the non-rigid part of an occurrence's placement:
/// applied to the geometry HERE, so the instance can carry a rigid pose (§3.4).
///
/// Split out from [`build_library_entry`] because the nested lane needs the
/// DOCUMENT before it installs anything — a leaf's document is embedded in its
/// parent's `partsLibrary`, where there is no `add_part_to_library` to call.
/// One producer, so a leaf part is byte-identical however deep it lands.
fn native_part_document(
    product: &brep_kernel::StepProduct,
    factor: Option<&Mat4>,
    doc_name: &str,
) -> Result<(String, serde_json::Value), String> {
    let mut name = part_name(product, doc_name);
    let bodies = match factor {
        None => product.bodies.clone(),
        Some(factor) => {
            let transform = brep_kernel::AffineTransform::new(*factor)
                .map_err(|error| format!("part '{name}': non-rigid factor: {error}"))?;
            let mirrored = transform.determinant3() < 0.0;
            name.push_str(if mirrored { " (mirrored)" } else { " (scaled)" });
            product
                .bodies
                .iter()
                .map(|body| {
                    // A mirror MUST reverse orientation or `transform_brep`
                    // refuses it (an unreversed reflection inverts the solid).
                    brep_kernel::transform_brep(body, transform, mirrored)
                        .map_err(|error| format!("part '{name}': {error}"))
                })
                .collect::<Result<Vec<_>, _>>()?
        }
    };
    // The product's STEP colours ride into the payload with the geometry (the
    // snapshot captures the records the stamp writes), so a coloured part keeps
    // its colour through the parts library and every reload.
    let payload = brep_kernel::native_import_payload_with_appearance(
        "IMPORT3D1",
        &bodies,
        &product.appearances,
    )
    .map_err(|error| format!("part '{name}': {error}"))?;
    let document = serde_json::json!({
        "features": [{
            "type": "IMPORT3D",
            "inputParams": { "id": "IMPORT3D1", "nativeBrep": payload },
            "persistentData": {},
        }]
    });
    Ok((name, document))
}

/// Install a part document as a parts-library entry of the OPEN document and
/// return the EFFECTIVE entry name the instances must reference
/// (`add_part_to_library` disambiguates a name clash and REUSES an entry with
/// identical content, which is where cross-import dedup comes from).
///
/// The `sourceKey` comes from the [`PartSink`]: an imported part is written to
/// the store as its own document and carries a REAL key, exactly like a part
/// inserted from the parts library, so there is no second kind of part. A sink
/// that declines (no store, or a failed write) yields `""` — the embedded-only
/// entry this lane used to produce unconditionally, and the case
/// `UpdateComponents` already skips.
fn install_part(
    name: &str,
    document: &serde_json::Value,
    writer: &mut PartWriter<'_>,
) -> Result<String, String> {
    let document = document.to_string();
    let signature = document_signature(&document);
    let source_key = writer.key_for(name, &document, &signature);
    brep_kernel::add_part_to_library(name, &source_key, &signature, &document)
        .map_err(|error| format!("part '{name}': {error:?}"))
}

/// Where an imported assembly's unique parts are written, so each becomes a
/// document in its own right rather than a payload embedded in one assembly.
///
/// A trait, and not a `&dyn ModelStore`, because the store lives in `BREP_app`
/// and this crate is BELOW it — `BREP_app` depends on `BREP_render`, so naming
/// the store here would be a dependency cycle. The import therefore asks for a
/// key and the app answers with one, which is also what keeps the destination
/// (and any prompt for it) entirely the app's business.
pub trait PartSink {
    /// Store `document_json` under a name derived from `part_name` and return
    /// the stable key it can be read back by. `None` declines — no store, or a
    /// write that failed — and the entry stays embedded-only.
    fn store_part(&mut self, part_name: &str, document_json: &str) -> Option<String>;
}

/// The sink that stores nothing: every entry stays embedded-only. The default
/// for headless callers and tests, which have no store to write to.
pub struct EmbeddedOnly;

impl PartSink for EmbeddedOnly {
    fn store_part(&mut self, _part_name: &str, _document_json: &str) -> Option<String> {
        None
    }
}

/// A [`PartSink`] plus the CONTENT DEDUP that must ride with it.
///
/// `add_part_to_library` reuses an entry whose `(sourceKey, sourceSignature)`
/// both match, which is where §3.5's free dedup came from while every imported
/// part carried the same empty key. Give each part its own key and that reuse
/// stops: the same product under two `PRODUCT_DEFINITION`s would become two
/// entries AND two identical files.
///
/// So the dedup moves in front of the write, keyed on the document signature
/// alone. Identical content is written ONCE and every occurrence of it gets the
/// SAME key — which then makes `add_part_to_library`'s own `(key, signature)`
/// reuse fire exactly as before. Dedup ACROSS imports keeps working for the
/// same reason: a re-import derives the same file name, so the same key and
/// signature come back and the resident entry is reused.
struct PartWriter<'a> {
    sink: &'a mut dyn PartSink,
    by_signature: std::collections::HashMap<String, String>,
}

impl<'a> PartWriter<'a> {
    fn new(sink: &'a mut dyn PartSink) -> Self {
        Self {
            sink,
            by_signature: std::collections::HashMap::new(),
        }
    }

    /// The `sourceKey` for a part with this content — writing it exactly once
    /// however many products share it.
    fn key_for(&mut self, name: &str, document_json: &str, signature: &str) -> String {
        if let Some(key) = self.by_signature.get(signature) {
            return key.clone();
        }
        let key = self
            .sink
            .store_part(name, document_json)
            .unwrap_or_default();
        self.by_signature.insert(signature.to_string(), key.clone());
        key
    }
}

/// The library name for a product: its `PRODUCT.name`, else a stem built from
/// the imported document's name so an unnamed product is still identifiable.
fn part_name(product: &brep_kernel::StepProduct, doc_name: &str) -> String {
    let named = product.name.trim();
    if !named.is_empty() {
        return named.to_string();
    }
    match doc_name.trim() {
        "" => format!("part-{}", product.pd_ref),
        stem => format!("{stem}-part-{}", product.pd_ref),
    }
}

/// The dialog's counts, taken from the SAME walk the import runs, so the numbers
/// the user was shown are the numbers they get (bar an encode failure, and bar
/// the extra entry a non-rigid occurrence bakes).
fn probe_counts(assembly: &brep_kernel::StepAssembly) -> StepAssemblyProbe {
    let mut parts = std::collections::HashSet::new();
    let mut instances = 0usize;
    let mut nested_depth = 0usize;
    for placed in compose_world_occurrences(assembly) {
        let product = &assembly.products[placed.product];
        if product.bodies.is_empty() {
            continue;
        }
        parts.insert(product.pd_ref);
        instances += 1;
        nested_depth = nested_depth.max(placed.depth);
    }
    StepAssemblyProbe {
        parts: parts.len(),
        instances,
        nested_depth,
    }
}

/// Depth-first from the roots, composing each occurrence's child→parent
/// placement into a world transform — the consumer half of `read_step_assembly`,
/// which deliberately transforms nothing.
///
/// Emit order, child ordering (by `nauo_ref`) and the ancestor cycle guard mirror
/// the kernel's own `walk_occurrences`, which is what makes the components this
/// lane produces the same solids, in the same order, as the flat lane's — the
/// kernel asserts that equivalence BIT-for-bit
/// (`step_import/tests/assembly_structure.rs`), and
/// `structured_import_matches_the_flat_lane_geometry` below re-asserts it from
/// this side, where a divergence would actually land.
fn compose_world_occurrences(assembly: &brep_kernel::StepAssembly) -> Vec<PlacedProduct> {
    struct Node {
        placed: PlacedProduct,
        ancestors: Vec<usize>,
    }
    let mut out = Vec::new();
    let mut stack: Vec<Node> = assembly
        .roots
        .iter()
        .rev()
        .map(|&product| Node {
            placed: PlacedProduct {
                product,
                world: MAT4_IDENTITY,
                depth: 0,
                rigid_path: true,
            },
            ancestors: vec![product],
        })
        .collect();
    while let Some(node) = stack.pop() {
        let (product, world, depth, rigid_path) = (
            node.placed.product,
            node.placed.world,
            node.placed.depth,
            node.placed.rigid_path,
        );
        out.push(node.placed);
        let mut children: Vec<&brep_kernel::StepOccurrence> = assembly
            .occurrences
            .iter()
            .filter(|occurrence| occurrence.parent == product)
            .collect();
        children.sort_by_key(|occurrence| occurrence.nauo_ref);
        for occurrence in children.into_iter().rev() {
            if node.ancestors.contains(&occurrence.child) {
                continue; // the cycle guard the kernel's walk applies
            }
            let mut ancestors = node.ancestors.clone();
            ancestors.push(occurrence.child);
            stack.push(Node {
                placed: PlacedProduct {
                    product: occurrence.child,
                    world: mat4_mul(&world, &occurrence.placement),
                    depth: depth + 1,
                    // The kernel's per-edge rigidity flag, carried down the path:
                    // a composed pose is a component pose only when every edge
                    // on the way to it was one.
                    rigid_path: rigid_path && occurrence.rigid,
                },
                ancestors,
            });
        }
    }
    out
}

const MAT4_IDENTITY: Mat4 = [
    1.0, 0.0, 0.0, 0.0, //
    0.0, 1.0, 0.0, 0.0, //
    0.0, 0.0, 1.0, 0.0, //
    0.0, 0.0, 0.0, 1.0,
];

/// Row-major 4×4 product `a · b`.
fn mat4_mul(a: &Mat4, b: &Mat4) -> Mat4 {
    let mut out = [0.0; 16];
    for row in 0..4 {
        for column in 0..4 {
            out[row * 4 + column] = (0..4)
                .map(|k| a[row * 4 + k] * b[k * 4 + column])
                .sum();
        }
    }
    out
}

/// Split a non-rigid world placement into `world = rigid · factor`, where
/// `rigid` is a component pose (rotation + translation, det +1) and `factor` is
/// a purely linear residue carrying the mirror/scale/shear.
///
/// Gram-Schmidt on the linear block's columns gives `A = Q·U` with `U` upper
/// triangular and positively-diagonalled; when `Q` came out left-handed the pair
/// is re-signed through `D = diag(-1, 1, 1)` (`Q' = Q·D`, `U' = D·U`, still
/// `Q'U' = A`) so the ROTATION is a rotation and the reflection rides in the
/// factor. A mirror composed with a rotation therefore yields the same factor
/// whatever the rotation, which keeps every such instance on ONE baked part.
fn split_rigid(world: &Mat4) -> Result<(Mat4, Mat4), String> {
    let column = |index: usize| [world[index], world[4 + index], world[8 + index]];
    let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
    let axpy = |a: [f64; 3], scale: f64, b: [f64; 3]| {
        [a[0] - scale * b[0], a[1] - scale * b[1], a[2] - scale * b[2]]
    };
    let (a1, a2, a3) = (column(0), column(1), column(2));

    let r11 = dot(a1, a1).sqrt();
    let mut q1 = normalize(a1, r11)?;
    let r12 = dot(q1, a2);
    let v2 = axpy(a2, r12, q1);
    let r22 = dot(v2, v2).sqrt();
    let q2 = normalize(v2, r22)?;
    let r13 = dot(q1, a3);
    let r23 = dot(q2, a3);
    let v3 = axpy(axpy(a3, r13, q1), r23, q2);
    let r33 = dot(v3, v3).sqrt();
    let q3 = normalize(v3, r33)?;

    // det Q = q1 · (q2 × q3); -1 means Q is a reflection, not a rotation.
    let cross = [
        q2[1] * q3[2] - q2[2] * q3[1],
        q2[2] * q3[0] - q2[0] * q3[2],
        q2[0] * q3[1] - q2[1] * q3[0],
    ];
    let (mut r11, mut r12, mut r13) = (r11, r12, r13);
    if dot(q1, cross) < 0.0 {
        q1 = [-q1[0], -q1[1], -q1[2]];
        r11 = -r11;
        r12 = -r12;
        r13 = -r13;
    }
    let rigid = [
        q1[0], q2[0], q3[0], world[3], //
        q1[1], q2[1], q3[1], world[7], //
        q1[2], q2[2], q3[2], world[11], //
        0.0, 0.0, 0.0, 1.0,
    ];
    let factor = [
        r11, r12, r13, 0.0, //
        0.0, r22, r23, 0.0, //
        0.0, 0.0, r33, 0.0, //
        0.0, 0.0, 0.0, 1.0,
    ];
    Ok((rigid, factor))
}

/// Unit vector, or a clear error for the degenerate column a near-singular
/// placement produces (skipped and counted, never fatal).
fn normalize(vector: [f64; 3], length: f64) -> Result<[f64; 3], String> {
    if !(length > 1e-12) || !length.is_finite() {
        return Err("occurrence placement is singular (a degenerate axis)".into());
    }
    Ok([vector[0] / length, vector[1] / length, vector[2] / length])
}

/// Is this affine the identity to 1e-9 — the tolerance the kernel's own
/// rigidity gate uses?
fn is_identity(matrix: &Mat4) -> bool {
    matrix
        .iter()
        .zip(MAT4_IDENTITY.iter())
        .all(|(value, want)| (value - want).abs() <= 1e-9)
}

/// The linear block of a baked factor as an exact bit key — two occurrences
/// share a baked part only when their factor is bit-identical, so a wrong-handed
/// reuse is not reachable through rounding.
fn factor_key(factor: &Mat4) -> [u64; 9] {
    let mut key = [0u64; 9];
    for (slot, index) in key.iter_mut().zip([0, 1, 2, 4, 5, 6, 8, 9, 10]) {
        *slot = factor[index].to_bits();
    }
    key
}

#[cfg(test)]
mod io_tests {
    use super::*;

    /// A full history document for a single P.CU cube of side `size` (volume
    /// `size^3`), fed to [`EngineState::set_history_json`].
    fn cube_history(id: &str, size: f64) -> String {
        serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [{
                "type": "P.CU",
                "inputParams": {
                    "id": id,
                    "sizeX": size, "sizeY": size, "sizeZ": size,
                    "transform": {
                        "position": [0.0, 0.0, 0.0],
                        "rotationEuler": [0.0, 0.0, 0.0],
                        "scale": [1.0, 1.0, 1.0]
                    },
                    "boolean": { "targets": [], "operation": "NONE" }
                },
                "persistentData": {}
            }]
        })
        .to_string()
    }

    /// STEP text for an axis-aligned box `sx × sy × sz`, via the kernel exporter.
    fn box_step(sx: f64, sy: f64, sz: f64) -> String {
        let solid =
            brep_kernel::make_box_brep(brep_kernel::Vec3::new(0.0, 0.0, 0.0), sx, sy, sz)
                .unwrap();
        brep_kernel::export_step(&[solid], "part", "MM", "").unwrap()
    }

    /// Volume of the single solid `import_step` recovers from STEP text.
    fn imported_volume(step_text: &str) -> f64 {
        let solids = brep_kernel::import_step(step_text).unwrap();
        assert_eq!(solids.len(), 1, "STEP round-trips to one solid");
        brep_kernel::solid_mass_properties(&solids[0]).unwrap().volume
    }

    /// Importing a STEP box appends an IMPORT3D feature that yields the body in
    /// the model: the scene shows one solid whose bbox matches the box. A
    /// non-STEP payload is refused up front, leaving no dead feature behind.
    #[test]
    fn import_step_feature_adds_the_body_to_the_model() {
        let step = box_step(4.0, 3.0, 2.0);
        let mut state = EngineState::new();
        state.import_step_feature(&step).unwrap();
        assert_eq!(state.scene.solids().len(), 1, "one imported body");
        let size = state.scene.solids()[0].bbox.size();
        assert!(
            (size[0] - 4.0).abs() < 1e-4
                && (size[1] - 3.0).abs() < 1e-4
                && (size[2] - 2.0).abs() < 1e-4,
            "imported bbox {size:?} != 4x3x2"
        );

        let mut empty = EngineState::new();
        assert!(empty.import_step_feature("not a step file").is_err());
        assert_eq!(empty.history_len(), 0, "a bad import adds no feature");
    }

    /// THE COLOUR SEAM (kernel-plan §3.8, A10). The kernel stamps an imported
    /// STEP colour into ITS name-keyed scene-metadata store, which is
    /// thread-local to whoever ran the history and is not the store the Info
    /// window edits. `SceneRunner::run` reads it runner-side and ships it in the
    /// `RunOutput`; `apply_run_output` folds it in here. Without that seam the
    /// colour exists and nothing can see it.
    ///
    /// `freecad_partdesign_body.step` styles its MANIFOLD_SOLID_BREP with
    /// `COLOUR_RGB(0.8, 0.8, 0.8)` = `#CCCCCC` (and a near-black CURVE_STYLE that
    /// must not win). One body, no product structure — the flat import lane.
    #[test]
    fn imported_step_colour_reaches_the_engine_metadata_store() {
        let step = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../BREP_kernel/tests/fixtures/step-import/freecad_partdesign_body.step"
        ));
        let mut state = EngineState::new();
        state.import_step_feature(step).expect("fixture imports");
        let name = state.scene.solids()[0].name.clone();
        assert_eq!(
            state.metadata.attribute(&name, "color"),
            Some("#CCCCCC"),
            "the imported body colour must reach the store the Info window reads"
        );

        // NON-overwriting: a user's edit survives the next run of the same
        // history (which re-stamps the imported colour kernel-side).
        state.set_metadata_attribute(&name, "color", "#123456");
        state.roll_to(0);
        state.roll_to(state.history_len());
        assert_eq!(
            state.metadata.attribute(&name, "color"),
            Some("#123456"),
            "a user-edited colour must win over the re-stamped import"
        );
    }

    /// Mesh imports run recognition/reconstruction first, then enter the same
    /// history lane as a native STEP import. This small OBJ cube exercises the
    /// complete UI-facing path without relying on an external fixture.
    #[test]
    fn import_obj_feature_reconstructs_mesh_into_a_cad_body() {
        let cube = r#"
v 0 0 0
v 1 0 0
v 1 1 0
v 0 1 0
v 0 0 1
v 1 0 1
v 1 1 1
v 0 1 1
f 1 3 2
f 1 4 3
f 5 6 7
f 5 7 8
f 1 2 6
f 1 6 5
f 2 3 7
f 2 7 6
f 3 4 8
f 3 8 7
f 4 1 5
f 4 5 8
"#;
        let mut state = EngineState::new();
        state.import_obj_feature(cube).unwrap();

        assert_eq!(
            state.history_len(),
            1,
            "mesh import adds one undoable feature"
        );
        assert_eq!(
            state.scene.solids().len(),
            1,
            "reconstruction yields one body"
        );
        let size = state.scene.solids()[0].bbox.size();
        assert!(
            size.iter().all(|axis| (*axis - 1.0).abs() < 1e-4),
            "bbox: {size:?}"
        );
        assert!(
            state.history_request_json().contains("ISO-10303-21"),
            "history stores the validated reconstructed BREP as STEP"
        );
    }

    /// Binary STL follows the byte-preserving path and uses the source f32
    /// precision floor before RANSAC recognition. Production's ThreadRunner
    /// returns immediately, then the regular engine pump applies both stages.
    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn import_binary_stl_feature_reconstructs_mesh_into_a_cad_body() {
        let bytes = include_bytes!("../../../tests/fixtures/stl/PartDesignExample-Body.stl");
        let mut state = EngineState::new();
        state.set_runner(Box::new(crate::runner::ThreadRunner::new()));
        let submitted = std::time::Instant::now();
        state.import_stl_feature(bytes).unwrap();

        assert!(state.mesh_imports_pending(), "RANSAC is running off-thread");
        assert_eq!(
            state.history_len(),
            0,
            "no feature is added before reconstruction"
        );
        assert!(
            submitted.elapsed() < std::time::Duration::from_secs(1),
            "submission must not wait for RANSAC"
        );
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
        while state.mesh_imports_pending() || state.run_pending() {
            assert!(
                std::time::Instant::now() < deadline,
                "background import timed out"
            );
            state.pump();
            std::thread::sleep(std::time::Duration::from_millis(2));
        }
        assert_eq!(state.history_len(), 1);
        assert_eq!(state.scene.solids().len(), 1);
        assert!(state.history_request_json().contains("ISO-10303-21"));
    }

    /// Exporting a box model produces STEP text that `import_step` round-trips to
    /// one solid of the same volume. An empty model has nothing to export.
    #[test]
    fn export_step_text_round_trips_a_box_model() {
        let mut state = EngineState::new();
        state.set_history_json(&cube_history("Box", 10.0)).unwrap();
        let step = state.export_step_text().unwrap();
        assert!(step.contains("ISO-10303-21"), "STEP header present");
        let volume = imported_volume(&step);
        assert!((volume - 1000.0).abs() < 1e-3, "exported volume {volume} != 1000");

        let empty = EngineState::new();
        assert!(empty.export_step_text().is_err(), "empty model errs on export");
    }

    /// Round trip: import a STEP box into the model, export the model back to
    /// STEP, re-import — the solid count and volume are preserved.
    #[test]
    fn import_export_import_preserves_count_and_volume() {
        let step_in = box_step(5.0, 4.0, 3.0); // volume 60
        let mut state = EngineState::new();
        state.import_step_feature(&step_in).unwrap();
        assert_eq!(state.scene.solids().len(), 1);

        let step_out = state.export_step_text().unwrap();
        let solids = brep_kernel::import_step(&step_out).unwrap();
        assert_eq!(solids.len(), 1, "solid count preserved");
        let volume = brep_kernel::solid_mass_properties(&solids[0]).unwrap().volume;
        assert!((volume - 60.0).abs() < 1e-3, "round-trip volume {volume} != 60");
    }

    /// Round trip through IGES: build a box model, export to IGES, then
    /// re-import via both the kernel and the import feature — the solid count and
    /// volume are preserved. An empty model errs; a non-IGES payload is refused.
    #[test]
    fn export_iges_text_round_trips_a_box_model() {
        let mut state = EngineState::new();
        state.set_history_json(&cube_history("Box", 5.0)).unwrap(); // volume 125
        let iges = state.export_iges_text().unwrap();
        assert_eq!(iges.chars().nth(72), Some('S'), "first record is the start section");

        let solids = brep_kernel::import_iges(&iges).unwrap();
        assert_eq!(solids.len(), 1, "one solid round-trips through IGES");
        let volume = brep_kernel::solid_mass_properties(&solids[0]).unwrap().volume;
        assert!((volume - 125.0).abs() < 1e-3, "IGES round-trip volume {volume} != 125");

        let mut other = EngineState::new();
        other.import_iges_feature(&iges).unwrap();
        assert_eq!(other.scene.solids().len(), 1, "imported one body via the feature");

        let empty = EngineState::new();
        assert!(empty.export_iges_text().is_err(), "empty model errs on IGES export");
        assert!(
            other.import_iges_feature("not an iges file").is_err(),
            "a non-IGES payload is refused"
        );
    }

    /// A minimal sheet-metal part: a 40×25 rectangle sketch extruded to a 2mm tab
    /// (SM.TAB), whose resident body carries a sheet-metal tree for the unfold.
    fn sheet_metal_tab_history() -> String {
        serde_json::json!({
            "expressions": "", "configurator": {},
            "features": [
                {
                    "type": "S",
                    "inputParams": { "id": "SkTab" },
                    "persistentData": {
                        "basis": { "origin": [0,0,0], "x": [1,0,0], "y": [0,1,0], "z": [0,0,1] },
                        "sketch": {
                            "points": [
                                {"id":1,"x":0.0,"y":0.0,"fixed":true},
                                {"id":2,"x":40.0,"y":0.0,"fixed":true},
                                {"id":3,"x":40.0,"y":25.0,"fixed":true},
                                {"id":4,"x":0.0,"y":25.0,"fixed":true}
                            ],
                            "geometries": [
                                {"id":10,"type":"line","points":[1,2]},
                                {"id":11,"type":"line","points":[2,3]},
                                {"id":12,"type":"line","points":[3,4]},
                                {"id":13,"type":"line","points":[4,1]}
                            ],
                            "constraints": []
                        }
                    },
                    "timestamp": null
                },
                {
                    "type": "SM.TAB",
                    "inputParams": { "id": "tab1", "profile": "SkTab", "thickness": 2.0, "placementMode": "midplane" },
                    "persistentData": {},
                    "timestamp": null
                }
            ]
        })
        .to_string()
    }

    /// The flat-pattern export finds the part's sheet-metal body, unfolds it
    /// transiently, and returns well-formed DXF (R12) and SVG text. A non
    /// sheet-metal model (a plain box) errs with the exact target-missing message.
    #[test]
    fn export_flat_pattern_dxf_and_svg_for_a_sheet_metal_part() {
        let mut state = EngineState::new();
        state.set_history_json(&sheet_metal_tab_history()).unwrap();

        let dxf = state.export_flat_pattern_dxf().unwrap();
        assert!(dxf.contains("AC1009"), "DXF R12 header present");
        assert!(dxf.contains("\nPOLYLINE\n"), "DXF has a polyline entity");
        assert!(dxf.trim_end().ends_with("EOF"), "DXF terminates with EOF");

        let svg = state.export_flat_pattern_svg().unwrap();
        assert!(svg.starts_with("<svg"), "SVG opens with the svg root");
        assert!(svg.contains("<path"), "SVG has a path per loop");

        // The export must NOT have mutated history (transient unfold).
        assert_eq!(state.history_len(), 2, "flat-pattern export adds no feature");

        // A non sheet-metal model has no target body.
        let mut box_model = EngineState::new();
        box_model.set_history_json(&cube_history("Box", 10.0)).unwrap();
        let err = box_model.export_flat_pattern_dxf().unwrap_err();
        assert_eq!(err, "no sheet-metal body in the part", "clear no-target error");
    }

    /// `is_sheet_metal_object` marks a sheet-metal body — and its faces/edges —
    /// straight off the display scene (no history re-run), while a plain box is
    /// not. This is the run-free, thread-safe gate the SM edit features (Flange /
    /// Fillet / Chamfer) key on.
    #[test]
    fn is_sheet_metal_object_marks_the_sheet_body_not_a_box() {
        let mut state = EngineState::new();
        state.set_history_json(&sheet_metal_tab_history()).unwrap();

        // The tab leaves exactly one sheet-metal body; find it in the scene.
        let sheet = state
            .scene
            .solids()
            .iter()
            .find(|s| s.is_sheet_metal)
            .expect("the SM.TAB body carries the sheet-metal marker");
        let solid_name = sheet.name.clone();
        let face_name = sheet.faces.iter().find(|f| !f.name.is_empty()).map(|f| f.name.clone());
        let edge_name = sheet.edges.iter().find(|e| !e.name.is_empty()).map(|e| e.name.clone());

        assert!(state.is_sheet_metal_object(&solid_name), "the solid is sheet metal");
        if let Some(face) = face_name {
            assert!(state.is_sheet_metal_object(&face), "a face of it is sheet metal");
        }
        if let Some(edge) = edge_name {
            assert!(state.is_sheet_metal_object(&edge), "an edge of it is sheet metal");
        }
        // Empty / unknown names are never sheet metal.
        assert!(!state.is_sheet_metal_object(""), "empty name is not sheet metal");
        assert!(!state.is_sheet_metal_object("nope"), "unknown name is not sheet metal");

        // A plain box is not sheet metal.
        let mut box_model = EngineState::new();
        box_model.set_history_json(&cube_history("Box", 10.0)).unwrap();
        assert!(!box_model.is_sheet_metal_object("Box"), "a plain box is not sheet metal");
    }

    /// ASCII STL export of a box model is well-formed (`solid brep … endsolid
    /// brep`) with the box's 12 triangles / 36 vertices. An empty scene errs.
    #[test]
    fn export_stl_text_emits_ascii_facets() {
        let mut state = EngineState::new();
        state.set_history_json(&cube_history("Box", 6.0)).unwrap();
        let stl = state.export_stl_text().unwrap();
        assert!(stl.starts_with("solid brep"), "STL opens with the solid header");
        assert!(stl.trim_end().ends_with("endsolid brep"), "STL closes the solid");
        assert_eq!(
            stl.matches("facet normal").count(),
            12,
            "a box tessellates to 12 triangles"
        );
        assert_eq!(stl.matches("vertex").count(), 36, "3 vertices per triangle");

        let empty = EngineState::new();
        assert!(empty.export_stl_text().is_err(), "empty scene errs on STL export");
    }

    // -----------------------------------------------------------------------
    // Structured STEP assembly import (kernel-plan `step-assembly-import.md`
    // §3.7 / §5) — the engine seam: probe, consume, ONE rebuild, flat fallback.
    // -----------------------------------------------------------------------

    /// A STEP fixture from the kernel's corpus, read at RUNTIME: that corpus is
    /// test-only root data which deliberately stays outside every crate package
    /// archive, so it must not be `include_str!`d into this crate.
    fn step_fixture(name: &str) -> String {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../BREP_kernel/tests/fixtures/step-import")
            .join(name);
        std::fs::read_to_string(&path)
            .unwrap_or_else(|error| panic!("read fixture {}: {error}", path.display()))
    }

    /// The kernel's parts library, parsed.
    fn library() -> serde_json::Map<String, serde_json::Value> {
        serde_json::from_str::<serde_json::Value>(&brep_kernel::parts_library_json())
            .expect("the parts library serializes as JSON")
            .as_object()
            .cloned()
            .expect("the parts library is an object")
    }

    /// Every ACOMP feature's `partName`, in history order.
    fn component_part_names(state: &EngineState) -> Vec<String> {
        serde_json::from_str::<serde_json::Value>(&state.history_request_json())
            .expect("history JSON")["features"]
            .as_array()
            .expect("features array")
            .iter()
            .filter(|feature| feature["type"] == "ACOMP")
            .map(|feature| feature["inputParams"]["partName"].as_str().unwrap().to_string())
            .collect()
    }

    /// `name → how many ACOMP instances reference it`.
    fn instance_counts(state: &EngineState) -> std::collections::BTreeMap<String, usize> {
        let mut counts = std::collections::BTreeMap::new();
        for name in component_part_names(state) {
            *counts.entry(name).or_insert(0usize) += 1;
        }
        counts
    }

    /// The native payload a library entry's part DOCUMENT carries (the §3.2
    /// shape: one IMPORT3D whose only input is `nativeBrep`).
    fn entry_payload(entry: &serde_json::Value) -> String {
        entry["document"]["features"][0]["inputParams"]["nativeBrep"]
            .as_str()
            .expect("the part document is one native IMPORT3D")
            .to_string()
    }

    /// The multiset of scene-solid `(bbox center, bbox size)` rounded to 1e-4,
    /// sorted — the shape-and-place fingerprint of a displayed model.
    fn placed_bboxes(state: &EngineState) -> Vec<[i64; 6]> {
        let mut out: Vec<[i64; 6]> = state
            .scene
            .solids()
            .iter()
            .map(|solid| {
                let (center, size) = (solid.bbox.center(), solid.bbox.size());
                let q = |value: f64| (value * 1.0e4).round() as i64;
                [
                    q(center[0]),
                    q(center[1]),
                    q(center[2]),
                    q(size[0]),
                    q(size[1]),
                    q(size[2]),
                ]
            })
            .collect();
        out.sort_unstable();
        out
    }

    /// A hand-built [`brep_kernel::StepAssembly`]: a root assembly node with no
    /// geometry, one geometry-bearing child product, and one occurrence of that
    /// child per `placements` entry. The seam the kernel's own fixtures cannot
    /// reach — no fixture in the corpus carries a NON-RIGID occurrence, and a
    /// name COLLISION with the live document needs the part's geometry to be
    /// chosen, not discovered.
    fn synthetic_assembly(
        bodies: Vec<brep_kernel::BrepSolid>,
        placements: &[([f64; 16], bool)],
    ) -> brep_kernel::StepAssembly {
        brep_kernel::StepAssembly {
            products: vec![
                brep_kernel::StepProduct {
                    pd_ref: 1,
                    name: "root".into(),
                    id: "root".into(),
                    bodies: Vec::new(),
                    appearances: Vec::new(),
                    failed_bodies: 0,
                },
                brep_kernel::StepProduct {
                    pd_ref: 2,
                    name: "widget".into(),
                    id: "widget".into(),
                    bodies,
                    appearances: Vec::new(),
                    failed_bodies: 0,
                },
            ],
            occurrences: placements
                .iter()
                .enumerate()
                .map(|(index, (placement, rigid))| brep_kernel::StepOccurrence {
                    nauo_ref: 10 + index,
                    parent: 0,
                    child: 1,
                    designator: format!("widget-{index}"),
                    placement: *placement,
                    rigid: *rigid,
                })
                .collect(),
            roots: vec![0],
            first_error: None,
        }
    }

    /// THE O(N²) guard. `add_feature` re-runs the whole history per call, so an
    /// import that looped it would bump `applied_generation` once per instance.
    /// The batch bumps it EXACTLY once for the whole file — and leaves exactly
    /// one undo step, so the user backs the import out in one press.
    #[test]
    fn import_step_assembly_runs_one_rebuild() {
        let text = step_fixture("as1-ug-214.stp");
        let mut state = EngineState::new();
        let before = state.applied_generation();

        let report = state
            .import_step_assembly(&text, "as1-ug", StepAssemblyImport::default())
            .expect("as1-ug-214 imports as an assembly");
        assert!(!report.flat_fallback, "as1-ug-214 carries a product structure");
        assert!(
            report.instances > 5,
            "the fixture is a real assembly: {} instances",
            report.instances
        );
        assert_eq!(
            state.applied_generation(),
            before + 1,
            "ONE rebuild for {} instances, not one per instance",
            report.instances
        );
        assert_eq!(
            component_part_names(&state).len(),
            report.instances,
            "every reported instance is an ACOMP feature"
        );

        assert!(state.can_undo(), "the import is undoable");
        state.undo();
        assert!(
            component_part_names(&state).is_empty(),
            "the whole import undoes in ONE step"
        );
    }

    /// The parse happens ONCE: the probe performs it and stashes the structure;
    /// the consume TAKES that stash and never sees the text again (its signature
    /// cannot — the structural proof). A second consume therefore errs rather
    /// than importing the file twice.
    #[test]
    fn import_step_assembly_parses_once() {
        let text = step_fixture("as1-ug-214.stp");
        let mut state = EngineState::new();

        let probe = state
            .probe_step_assembly(&text)
            .expect("as1-ug-214 parses")
            .expect("as1-ug-214 carries structure");
        assert!(
            state.pending_step_assembly.is_some(),
            "the probe stashes THE parse for the consume"
        );
        assert!(probe.parts > 0 && probe.instances >= probe.parts);
        assert!(
            probe.nested_depth > 1,
            "as1-ug-214 has sub-assemblies: depth {}",
            probe.nested_depth
        );

        let report = state
            .import_probed_step_assembly("as1-ug", StepAssemblyImport::default(), &mut EmbeddedOnly)
            .expect("the probed assembly imports");
        assert!(
            state.pending_step_assembly.is_none(),
            "the consume TAKES the stash"
        );
        assert_eq!(
            (report.parts, report.instances),
            (probe.parts, probe.instances),
            "the dialog's counts are the import's counts"
        );
        assert_eq!(report.baked_nonrigid, 0, "every as1 occurrence is rigid");
        assert_eq!(report.failed_products, 0, "every product encodes");

        assert!(
            state
                .import_probed_step_assembly("as1-ug", StepAssemblyImport::default(), &mut EmbeddedOnly)
                .is_err(),
            "a second consume has nothing to import — never a double insert"
        );
    }

    /// The stash never outlives the file it was parsed from: a second probe
    /// REPLACES it (including a probe that finds no structure — the case that
    /// would otherwise consume the PREVIOUS file), Cancel drops it, and a
    /// document switch drops it.
    #[test]
    fn probing_replaces_the_stash_and_never_accumulates() {
        let assembly = step_fixture("as1-ug-214.stp");
        let part = step_fixture("analytic_cube.step");
        let mut state = EngineState::new();

        assert!(state.probe_step_assembly(&assembly).unwrap().is_some());
        assert!(
            state.probe_step_assembly(&part).unwrap().is_none(),
            "a part file has no structure"
        );
        assert!(
            state.pending_step_assembly.is_none(),
            "a structureless probe must CLEAR the stash, or the next consume \
             imports the previous file"
        );

        assert!(state.probe_step_assembly(&assembly).unwrap().is_some());
        state.discard_probed_step_assembly();
        assert!(state.pending_step_assembly.is_none(), "Cancel drops the parse");

        assert!(state.probe_step_assembly(&assembly).unwrap().is_some());
        state.set_history_json(&cube_history("Box", 4.0)).unwrap();
        assert!(
            state.pending_step_assembly.is_none(),
            "a document switch drops a parse that belonged to the old document"
        );
    }

    /// A single-part STEP file has no structure to keep, so the import lands on
    /// today's flat lane, byte-for-byte: one IMPORT3D carrying the text, no
    /// library entries, no components.
    #[test]
    fn import_step_assembly_falls_back_to_flat_for_a_part_file() {
        let text = step_fixture("analytic_cube.step");
        let mut state = EngineState::new();

        assert!(
            state.probe_step_assembly(&text).unwrap().is_none(),
            "the probe reports no structure, so the app never offers the dialog"
        );
        let report = state
            .import_step_assembly(&text, "analytic_cube", StepAssemblyImport::default())
            .expect("the part file still imports");

        assert!(report.flat_fallback, "the flat lane ran");
        assert_eq!((report.parts, report.instances), (0, 0));
        assert!(library().is_empty(), "no parts-library entry for a flat import");
        assert_eq!(state.history_len(), 1, "one IMPORT3D feature");
        assert!(
            state.history_request_json().contains("stepText"),
            "the flat lane stores the STEP text, exactly as before"
        );
        assert!(!state.scene.solids().is_empty(), "the bodies are in the model");
    }

    /// The dedup that makes an imported assembly an ASSEMBLY: one library entry
    /// per unique geometry-bearing product, one ACOMP per occurrence of it. On
    /// the six-bolt classic that is six instances of ONE stored bolt.
    #[test]
    fn structured_import_dedups_parts() {
        let text = step_fixture("as1-ug-214.stp");
        let mut state = EngineState::new();
        let report = state
            .import_step_assembly(&text, "as1-ug", StepAssemblyImport::default())
            .expect("as1-ug-214 imports as an assembly");

        let library = library();
        assert_eq!(
            library.len(),
            report.parts,
            "one entry per unique geometry-bearing product"
        );
        let counts = instance_counts(&state);
        assert_eq!(
            counts.values().sum::<usize>(),
            report.instances,
            "one ACOMP per geometry-bearing occurrence"
        );
        assert_eq!(
            counts.len(),
            library.len(),
            "every entry is instanced, and every instance names an entry"
        );
        assert_eq!(
            counts.get("bolt").copied(),
            Some(6),
            "the six-bolt classic: ONE stored bolt, six instances — {counts:?}"
        );
        assert_eq!(
            counts.get("nut").copied(),
            Some(8),
            "eight nuts (six on the bolts, two on the rods): {counts:?}"
        );
        assert_eq!(
            counts.get("l_bracket").copied(),
            Some(2),
            "two L-brackets: {counts:?}"
        );
        assert_eq!(
            (report.parts, report.instances),
            (5, 18),
            "as1-ug-214: 5 distinct parts in 18 places"
        );

        // This import ran with the `EmbeddedOnly` sink, so every entry is
        // embedded-only and holds the §3.2 part document.
        //
        // CHANGED MEANING (was: "an imported part is ALWAYS embedded-only",
        // §3.5): an import now writes its unique parts to the store and gives
        // each a real `sourceKey` when the caller supplies a sink — see
        // `a_sink_gives_every_unique_part_a_real_source_key`. What survives
        // here is the OTHER half of that contract: a caller with NO store
        // (this one, and every headless caller) still gets an entry that
        // update-components skips instead of badging falsely outdated.
        for (name, entry) in &library {
            assert_eq!(
                entry["sourceKey"], "",
                "'{name}': with no sink there is no file, so the entry must \
                 stay embedded-only or update-components badges it as falsely \
                 outdated"
            );
            assert_eq!(
                entry["sourceSignature"],
                serde_json::Value::String(document_signature(&entry["document"].to_string())),
                "'{name}' signature is the ONE signature fn over its document"
            );
            assert!(
                !entry_payload(entry).is_empty(),
                "'{name}' carries a native payload"
            );
            assert!(
                !entry["document"].to_string().contains("ISO-10303-21"),
                "'{name}' must store NATIVE geometry, never the STEP text"
            );
        }
    }

    /// A recording [`PartSink`]: hands back a key derived from the part name
    /// and keeps every document it was offered — the app's store writer,
    /// minus the store.
    #[derive(Default)]
    struct RecordingSink {
        written: std::collections::BTreeMap<String, String>,
        offers: usize,
    }

    impl PartSink for RecordingSink {
        fn store_part(&mut self, part_name: &str, document_json: &str) -> Option<String> {
            self.offers += 1;
            let key = format!("/models/{part_name}.BREP.json");
            self.written.insert(key.clone(), document_json.to_string());
            Some(key)
        }
    }

    /// WITH a sink, every unique part is written to the store and carries a
    /// REAL `sourceKey` — the owner's "no distinction between part kinds".
    ///
    /// This is the half that REPLACES the old §3.5 decision (an imported part
    /// was embedded-only by design). What it must not break is the dedup that
    /// decision used to give for free: `add_part_to_library` reuses on
    /// `(sourceKey, sourceSignature)`, and every part having its OWN key would
    /// have turned six instances of one bolt into six entries and six
    /// identical files. So the six-bolt classic is asserted here too — five
    /// entries, five writes, five keys.
    #[test]
    fn a_sink_gives_every_unique_part_a_real_source_key_without_losing_dedup() {
        let text = step_fixture("as1-ug-214.stp");
        let mut state = EngineState::new();
        let mut sink = RecordingSink::default();
        state.probe_step_assembly(&text).unwrap();
        let report = state
            .import_probed_step_assembly("as1-ug", StepAssemblyImport::default(), &mut sink)
            .expect("structured import");

        assert_eq!(
            (report.parts, report.instances),
            (5, 18),
            "still 5 distinct parts in 18 places — the sink must not split them"
        );
        assert_eq!(
            sink.written.len(),
            5,
            "one file per DISTINCT part, not per occurrence: {:?}",
            sink.written.keys().collect::<Vec<_>>()
        );
        assert_eq!(
            sink.offers, 5,
            "and the store is offered each part exactly once — identical \
             content is written once, not written and then deduped"
        );

        let library: serde_json::Map<String, serde_json::Value> = serde_json::from_str(
            &brep_kernel::parts_library_json(),
        )
        .unwrap();
        assert_eq!(library.len(), 5, "five entries, one per part");
        for (name, entry) in &library {
            let key = entry["sourceKey"].as_str().unwrap_or_default();
            assert!(!key.is_empty(), "'{name}' must carry a real sourceKey");
            let stored = sink
                .written
                .get(key)
                .unwrap_or_else(|| panic!("'{name}' key '{key}' names a written file"));
            // The signature stamped on the entry hashes the EXACT bytes that
            // were written, or the app's write-through guard ("has the file
            // moved on?") is wrong from the first save.
            assert_eq!(
                entry["sourceSignature"],
                serde_json::Value::String(document_signature(stored)),
                "'{name}': the entry's signature and the stored file must \
                 describe the same content"
            );
        }
    }

    /// A sink that DECLINES one part (a failed write) leaves that entry
    /// embedded-only and imports everything else — a storage failure costs one
    /// part's file, never the import.
    #[test]
    fn a_declining_sink_leaves_that_part_embedded_and_imports_the_rest() {
        struct PickySink;
        impl PartSink for PickySink {
            fn store_part(&mut self, part_name: &str, _document: &str) -> Option<String> {
                (part_name != "bolt").then(|| format!("/models/{part_name}.BREP.json"))
            }
        }
        let text = step_fixture("as1-ug-214.stp");
        let mut state = EngineState::new();
        state.probe_step_assembly(&text).unwrap();
        let report = state
            .import_probed_step_assembly("as1-ug", StepAssemblyImport::default(), &mut PickySink)
            .expect("structured import");
        assert_eq!(
            (report.parts, report.instances),
            (5, 18),
            "the import is unaffected by one refused write"
        );
        let library: serde_json::Map<String, serde_json::Value> =
            serde_json::from_str(&brep_kernel::parts_library_json()).unwrap();
        assert_eq!(
            library["bolt"]["sourceKey"], "",
            "the refused part falls back to embedded-only"
        );
        for (name, entry) in library.iter().filter(|(name, _)| name.as_str() != "bolt") {
            assert!(
                !entry["sourceKey"].as_str().unwrap_or_default().is_empty(),
                "'{name}' still got its file"
            );
        }
    }

    /// The structured lane places the same geometry the flat lane does. The
    /// kernel proves the equivalence bit-for-bit against `resolve_assembly`;
    /// this asserts it from the side where a divergence would actually land —
    /// the composed world poses this crate walks out of the occurrence tree.
    /// (Volume alone would not: it is invariant under the rigid transforms a
    /// mis-composed placement gets wrong.)
    #[test]
    fn structured_import_matches_the_flat_lane_geometry() {
        let text = step_fixture("as1-ug-214.stp");

        let mut flat = EngineState::new();
        flat.import_step_feature(&text).expect("flat import");

        let mut structured = EngineState::new();
        structured
            .import_step_assembly(&text, "as1-ug", StepAssemblyImport::default())
            .expect("structured import");

        assert_eq!(
            structured.scene.solids().len(),
            flat.scene.solids().len(),
            "same body count"
        );
        assert_eq!(
            placed_bboxes(&structured),
            placed_bboxes(&flat),
            "every component must sit where the flat lane's baked body sits"
        );
    }

    /// §5's convergence gate. A library entry whose snapshot is gone re-executes
    /// its embedded document (the ACOMP self-heal) and rewrites the snapshot; for
    /// a NATIVE part that heal is a decode + re-encode, so it must land on the
    /// same solids under the same names — and a SECOND heal must reproduce the
    /// first byte-for-byte.
    ///
    /// The strong form holds here: the heal reproduces the INSERT's snapshot
    /// exactly, which is why the import goes through `add_part_to_library` rather
    /// than injecting a hand-made snapshot. (Both are supersets of the raw
    /// payload — the isolated run stamps `sourceFeatureId` records the payload
    /// never carried — so convergence, not payload == snapshot, is the invariant.)
    #[test]
    fn native_part_document_heals_and_converges() {
        let text = step_fixture("as1-ug-214.stp");
        let mut state = EngineState::new();
        state
            .import_step_assembly(&text, "as1-ug", StepAssemblyImport::default())
            .expect("as1-ug-214 imports as an assembly");
        let inserted = library();

        // The §5 lever: reopen the document with every entry's snapshot CLEARED,
        // which is what an unreadable cache looks like to the ACOMP fast lane.
        // `set_history_json` drops the kernel library and re-seeds it from the
        // block, so the run that follows must heal every entry.
        let heal_once = |state: &mut EngineState| -> serde_json::Map<String, serde_json::Value> {
            let mut document: serde_json::Value =
                serde_json::from_str(&state.history_request_json()).expect("document JSON");
            for (_, entry) in document["partsLibrary"]
                .as_object_mut()
                .expect("the document carries the library")
                .iter_mut()
            {
                entry["snapshot"] = serde_json::Value::String(String::new());
            }
            state.set_history_json(&document.to_string()).expect("reopen");
            let healed = library();
            for (name, entry) in &healed {
                assert!(
                    !entry["snapshot"].as_str().unwrap_or_default().is_empty(),
                    "'{name}' must have healed its cleared snapshot"
                );
            }
            healed
        };

        let first = heal_once(&mut state);
        let second = heal_once(&mut state);
        assert_eq!(
            first, second,
            "a second heal must reproduce the first BYTE for byte"
        );
        assert_eq!(first.len(), inserted.len(), "the heal keeps the same entries");

        for (name, entry) in &first {
            assert_eq!(
                entry["snapshot"],
                inserted[name.as_str()]["snapshot"],
                "'{name}': the heal must reproduce what the INSERT stored — the \
                 whole reason the import goes through add_part_to_library"
            );
            // The healed snapshot restores to the payload's solids under the
            // payload's names: the geometry survived the round trip.
            let payload = brep_kernel::restore_solids(&entry_payload(entry))
                .expect("the stored payload decodes");
            let healed = brep_kernel::restore_solids(entry["snapshot"].as_str().unwrap())
                .expect("the healed snapshot decodes");
            let names = |snapshot: &brep_kernel::RestoredSnapshot| -> Vec<String> {
                snapshot.solids.iter().map(|solid| solid.name.clone()).collect()
            };
            assert_eq!(names(&healed), names(&payload), "'{name}': identical body names");
            for (healed, stored) in healed.solids.iter().zip(payload.solids.iter()) {
                let (healed_data, healed_names) = brep_kernel::encode_solid(&healed.solid).unwrap();
                let (stored_data, stored_names) = brep_kernel::encode_solid(&stored.solid).unwrap();
                assert_eq!(healed_data, stored_data, "'{name}': identical geometry");
                assert_eq!(
                    healed_names.faces, stored_names.faces,
                    "'{name}': identical face names"
                );
                assert_eq!(
                    healed_names.edges, stored_names.edges,
                    "'{name}': identical edge names"
                );
            }
            assert!(
                healed.metadata.len() >= payload.metadata.len(),
                "'{name}': the heal's snapshot is a superset (sourceFeatureId records)"
            );
        }
    }

    /// THE ambient-metadata hazard. `native_import_payload` seals whatever record
    /// this thread's scene-metadata store holds for each name it stamps — right
    /// for a snapshot of the live scene, catastrophic for a NEW part whose
    /// stamped names collide with the CURRENT document's. The import brackets the
    /// encode; here the same call made WITHOUT that bracket captures the live
    /// records, which is what makes the assertion mean something.
    #[test]
    fn imported_part_payloads_never_capture_the_live_documents_metadata() {
        let step = box_step(4.0, 3.0, 2.0);
        let bodies = brep_kernel::import_step(&step).expect("the box imports");

        // A LIVE document built from the very same geometry: its history run
        // stamps `sourceFeatureId` records under exactly the names a part built
        // from these bodies will stamp.
        let mut state = EngineState::new();
        state.import_step_feature(&step).expect("flat import");

        // The collision is real: an UNBRACKETED encode of these bodies picks up
        // the live document's records. (If this ever comes back empty the test
        // has gone vacuous and must be re-armed, not deleted.)
        let leaked = brep_kernel::restore_solids(
            &brep_kernel::native_import_payload("IMPORT3D1", &bodies).unwrap(),
        )
        .unwrap();
        assert!(
            !leaked.metadata.is_empty(),
            "the live document must actually hold records under these names"
        );

        state.pending_step_assembly = Some(synthetic_assembly(bodies.clone(), &[(MAT4_IDENTITY, true)]));
        state
            .import_probed_step_assembly("collide", StepAssemblyImport::default(), &mut EmbeddedOnly)
            .expect("the synthetic assembly imports");

        let entry = library().into_iter().next().expect("one entry").1;
        let stored = brep_kernel::restore_solids(&entry_payload(&entry)).expect("payload decodes");
        assert!(
            stored.metadata.is_empty(),
            "the part's payload must carry the PART's metadata (it has none), \
             never the live document's: {:?}",
            stored.metadata
        );

        // The bracket RESTORED the store rather than eating it — the same
        // unbracketed encode still sees the live document's records.
        let after = brep_kernel::restore_solids(
            &brep_kernel::native_import_payload("IMPORT3D1", &bodies).unwrap(),
        )
        .unwrap();
        assert_eq!(
            after.metadata, leaked.metadata,
            "the live document's scene metadata must survive the import"
        );
    }

    /// §3.4: an occurrence whose placement is not rigid has no ACOMP pose, so its
    /// non-rigid factor is baked into a DISTINCT library entry and the instance
    /// carries the rigid residue. Never a wrong-handed reuse of the unmirrored
    /// twin. No fixture in the corpus carries one, so the occurrence is
    /// synthetic — which is also the only honest way to test it.
    #[test]
    fn nonrigid_occurrence_bakes_a_distinct_part() {
        let bodies = brep_kernel::import_step(&box_step(4.0, 3.0, 2.0)).expect("box imports");
        // x → −x about the origin, then translated: a mirror, det = −1.
        let mirrored = [
            -1.0, 0.0, 0.0, 20.0, //
            0.0, 1.0, 0.0, 0.0, //
            0.0, 0.0, 1.0, 0.0, //
            0.0, 0.0, 0.0, 1.0,
        ];
        let mut state = EngineState::new();
        state.pending_step_assembly = Some(synthetic_assembly(
            bodies,
            &[(MAT4_IDENTITY, true), (mirrored, false)],
        ));
        let report = state
            .import_probed_step_assembly("mirror", StepAssemblyImport::default(), &mut EmbeddedOnly)
            .expect("the mirrored assembly imports");

        assert_eq!(report.instances, 2, "both occurrences become components");
        assert_eq!(report.baked_nonrigid, 1, "one of them baked its factor");
        assert_eq!(report.parts, 2, "the mirrored instance is its OWN part");
        let counts = instance_counts(&state);
        assert_eq!(
            counts.get("widget").copied(),
            Some(1),
            "the plain instance keeps the plain part: {counts:?}"
        );
        assert_eq!(
            counts.get("widget (mirrored)").copied(),
            Some(1),
            "the mirrored instance gets its own entry: {counts:?}"
        );
        // Two bodies, and the mirrored one sits where the placement put it:
        // x → 20 − x, so the two centres straddle x = 10.
        assert_eq!(state.scene.solids().len(), 2);
        let mut centers: Vec<f64> = state
            .scene
            .solids()
            .iter()
            .map(|solid| solid.bbox.center()[0])
            .collect();
        centers.sort_by(|a, b| a.partial_cmp(b).expect("finite"));
        assert!(
            (centers[0] + centers[1] - 20.0).abs() < 1e-3
                && (centers[1] - centers[0]).abs() > 1e-3,
            "the mirror must land at 20 − x̄, not on top of its twin: {centers:?}"
        );
    }

    // -----------------------------------------------------------------------
    // A8 — nested rigid sub-assemblies (kernel-plan §3.3 Phase 2)
    // -----------------------------------------------------------------------

    /// `{ nested: true }`.
    const NESTED: StepAssemblyImport = StepAssemblyImport { nested: true };

    /// The `partsLibrary` block of a part DOCUMENT — the child library a nested
    /// sub-assembly document carries (empty map when it carries none).
    fn child_library(document: &serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
        document["partsLibrary"]
            .as_object()
            .cloned()
            .unwrap_or_default()
    }

    /// The `partName`s the ACOMP features of a part DOCUMENT reference, in
    /// document order.
    fn child_components(document: &serde_json::Value) -> Vec<String> {
        document["features"]
            .as_array()
            .map(Vec::as_slice)
            .unwrap_or_default()
            .iter()
            .filter(|feature| feature["type"] == "ACOMP")
            .map(|feature| feature["inputParams"]["partName"].as_str().unwrap().to_string())
            .collect()
    }

    /// One component's geometry as the world places it: volume, centroid and
    /// vertex bbox of every solid the component's part contributes, posed by the
    /// component's transform. EXACT `f64` — the snapshot restores the same
    /// solids the flat lane baked, the pose is the kernel's own
    /// `AffineTransform`, and the bbox is taken over exact vertex points, so
    /// this reads the GEOMETRY rather than a tessellation of it.
    ///
    /// Call it while `state`'s import is the LAST one this thread ran: the
    /// kernel parts library is a thread-local the next `EngineState` clears and
    /// refills, so a second import invalidates the first state's entries.
    fn world_placed(state: &mut EngineState) -> Vec<[f64; 10]> {
        state.ensure_assembly_synced();
        let library = library();
        let mut out = Vec::new();
        for record in state.assembly_components() {
            let entry = &library[record.part_name.as_str()];
            let restored = brep_kernel::restore_solids(entry["snapshot"].as_str().unwrap())
                .expect("every entry's snapshot decodes");
            let mirrored = record.transform.determinant3() < 0.0;
            for solid in &restored.solids {
                let posed = brep_kernel::transform_brep(&solid.solid, record.transform, mirrored)
                    .expect("a component pose is rigid");
                let mass =
                    brep_kernel::solid_mass_properties_full(&posed).expect("mass properties");
                let mut lo = [f64::INFINITY; 3];
                let mut hi = [f64::NEG_INFINITY; 3];
                for vertex in &posed.vertices {
                    for axis in 0..3 {
                        let value = [vertex.point.x, vertex.point.y, vertex.point.z][axis];
                        lo[axis] = lo[axis].min(value);
                        hi[axis] = hi[axis].max(value);
                    }
                }
                out.push([
                    mass.volume,
                    mass.centroid.x,
                    mass.centroid.y,
                    mass.centroid.z,
                    lo[0],
                    lo[1],
                    lo[2],
                    hi[0],
                    hi[1],
                    hi[2],
                ]);
            }
        }
        // Sorted on a COARSE key so the pairing is stable, then compared at the
        // tight tolerance by the caller.
        out.sort_by_key(|row| row.map(|value| (value * 1.0e6).round() as i64));
        out
    }

    /// Every row of `a` matches `b` to `tolerance`.
    fn assert_placed_eq(a: &[[f64; 10]], b: &[[f64; 10]], tolerance: f64, what: &str) {
        assert_eq!(a.len(), b.len(), "{what}: solid count");
        for (index, (left, right)) in a.iter().zip(b.iter()).enumerate() {
            for (column, (l, r)) in left.iter().zip(right.iter()).enumerate() {
                assert!(
                    (l - r).abs() <= tolerance,
                    "{what}: solid {index} column {column}: {l} != {r}"
                );
            }
        }
    }

    /// §5's `nested_import_builds_child_libraries`. `as1-ug-214.stp` is the real
    /// three-level article: `as1-ug` → { plate, lb_assem ×2, rod_assem }, where
    /// `lb_assem` → { l_bracket, nba ×3 } and `nba` → { bolt, nut }.
    ///
    /// The root must therefore get ONE component per sub-assembly OCCURRENCE
    /// (not per leaf body), each sub-document must carry its OWN `partsLibrary`,
    /// and the entity names must chain a namespace per level.
    #[test]
    fn nested_import_builds_child_libraries() {
        let text = step_fixture("as1-ug-214.stp");
        let mut state = EngineState::new();
        let report = state
            .import_step_assembly(&text, "as1-ug", NESTED)
            .expect("as1-ug-214 imports as a nested assembly");

        assert!(!report.flat_fallback, "the structured lane ran");
        assert_eq!(
            (report.parts, report.instances),
            (3, 4),
            "the ROOT's children: plate, lb_assem ×2, rod_assem — a sub-assembly \
             is ONE component (build-spec §2.2), not one per leaf body"
        );
        assert_eq!(report.failed_products, 0, "every product encodes");
        assert_eq!(report.baked_nonrigid, 0, "every as1 occurrence is rigid");
        assert_eq!(
            instance_counts(&state),
            [("lb_assem".to_string(), 2), ("plate".to_string(), 1), ("rod_assem".to_string(), 1)]
                .into_iter()
                .collect::<std::collections::BTreeMap<_, _>>(),
        );

        // Level 2 — `lb_assem` carries its OWN library and its own components.
        let library = library();
        let lb = &library["lb_assem"]["document"];
        assert_eq!(
            child_library(lb).keys().cloned().collect::<Vec<_>>(),
            vec!["l_bracket".to_string(), "nba".to_string()],
            "the sub-document's library is its own (build-spec §2.2: a part \
             reused across levels is stored once PER level)"
        );
        assert_eq!(
            child_components(lb),
            vec!["l_bracket", "nba", "nba", "nba"],
            "one ACOMP per child occurrence — three nut-bolt assemblies"
        );

        // Level 3 — `nba` is a sub-assembly OF a sub-assembly.
        let nba = &child_library(lb)["nba"]["document"];
        assert_eq!(
            child_library(nba).keys().cloned().collect::<Vec<_>>(),
            vec!["bolt".to_string(), "nut".to_string()],
        );
        assert_eq!(child_components(nba), vec!["bolt", "nut"]);
        // The deepest entries are the §3.2 native part documents — the leaves of
        // the recursion, identical in shape to what a flat import stores.
        // CHANGED MEANING, as above: a nested child is a part like any other
        // and takes a real `sourceKey` from a sink. This import has none, so
        // the entries stay embedded — which is what the empty key now asserts.
        for (name, entry) in child_library(nba) {
            assert_eq!(
                entry["sourceKey"], "",
                "'{name}': no sink, so the nested child stays embedded"
            );
            assert!(!entry_payload(&entry).is_empty(), "'{name}' is a native part");
        }

        // The namespace CHAINS, one segment per level: a bolt inside `nba`
        // inside `lb_assem` inside the document.
        let names: Vec<&str> = state
            .scene
            .solids()
            .iter()
            .map(|solid| solid.name.as_str())
            .collect();
        assert!(
            names.iter().any(|name| name.matches("ACOMP").count() == 3),
            "a three-level chain must appear in the scene names: {names:?}"
        );
        assert!(
            names.iter().any(|name| name.starts_with("ACOMP2:ACOMP2:ACOMP1:")),
            "the chained prefix the structure tree reads back: {names:?}"
        );
        assert_eq!(
            names.len(),
            18,
            "the same 18 bodies the flat lane produces, reached through the tree"
        );
    }

    /// Phase 1's output IS Phase 2's output for a depth-1 tree — the cheapest
    /// correctness check the nesting slice has, asserted on the whole document
    /// (features, poses, library entries, snapshots) rather than a summary.
    ///
    /// `AssemblyExample-Assembly.step` is a real single-level assembly; the
    /// synthetic pair covers the case the fixture cannot, a root that owns
    /// bodies AND children (interior geometry at the root, which BOTH lanes
    /// place as a component of its own).
    #[test]
    fn nested_matches_flat_for_a_depth_one_tree() {
        let text = step_fixture("AssemblyExample-Assembly.step");
        let mut state = EngineState::new();
        let probe = state
            .probe_step_assembly(&text)
            .unwrap()
            .expect("the fixture carries structure");
        assert_eq!(probe.nested_depth, 1, "the fixture must be depth 1");

        let mut flat = EngineState::new();
        let flat_report = flat
            .import_step_assembly(&text, "example", StepAssemblyImport::default())
            .expect("flat");
        let flat_document = flat.history_request_json();

        let mut nested = EngineState::new();
        let nested_report = nested
            .import_step_assembly(&text, "example", NESTED)
            .expect("nested");
        assert_eq!(nested_report, flat_report, "identical report");
        assert_eq!(
            nested.history_request_json(),
            flat_document,
            "a depth-1 nested import must produce the FLAT document, byte for byte"
        );

        // Same again with a root that owns geometry of its own AND a mirrored
        // occurrence — the two branches the fixture cannot reach, and the only
        // ones where the nested lane runs its own §3.4 bake rather than the flat
        // lane's. Byte equality covers both for free.
        let bodies = brep_kernel::import_step(&box_step(4.0, 3.0, 2.0)).expect("box imports");
        let placed = [
            1.0, 0.0, 0.0, 12.0, //
            0.0, 1.0, 0.0, 0.0, //
            0.0, 0.0, 1.0, 0.0, //
            0.0, 0.0, 0.0, 1.0,
        ];
        let mirrored = [
            -1.0, 0.0, 0.0, 30.0, //
            0.0, 1.0, 0.0, 0.0, //
            0.0, 0.0, 1.0, 0.0, //
            0.0, 0.0, 0.0, 1.0,
        ];
        let with_root_bodies = || {
            let mut assembly =
                synthetic_assembly(bodies.clone(), &[(placed, true), (mirrored, false)]);
            assembly.products[0].bodies = bodies.clone();
            assembly
        };
        let mut flat = EngineState::new();
        flat.pending_step_assembly = Some(with_root_bodies());
        flat.import_probed_step_assembly("root", StepAssemblyImport::default(), &mut EmbeddedOnly)
            .expect("flat");
        let flat_document = flat.history_request_json();

        let mut nested = EngineState::new();
        nested.pending_step_assembly = Some(with_root_bodies());
        let report = nested
            .import_probed_step_assembly("root", NESTED, &mut EmbeddedOnly)
            .expect("nested");
        assert_eq!(report.baked_nonrigid, 1, "the mirrored occurrence baked");
        assert_eq!(
            nested.history_request_json(),
            flat_document,
            "interior geometry AT THE ROOT, and a mirrored leaf, are the same \
             components in both lanes"
        );
    }

    /// THE §6 limitation this slice removes. A product that owns bodies AND
    /// children is a real thing in real files, and Phase 1 could only make its
    /// geometry a SIBLING of its own children in the structure tree. Nested puts
    /// the bodies where they belong: plain native IMPORT3D features inside that
    /// node's own document, alongside its ACOMPs.
    ///
    /// No fixture reaches it — `as1-ug-214`'s interior nodes (`lb_assem`, `nba`,
    /// `rod_assem`) are all pure assembly nodes — so the shape is synthetic:
    /// root → mid (bodies + one child) → leaf.
    #[test]
    fn interior_node_geometry_lives_inside_its_own_document() {
        let mid_bodies = brep_kernel::import_step(&box_step(6.0, 6.0, 1.0)).expect("plate");
        let leaf_bodies = brep_kernel::import_step(&box_step(2.0, 2.0, 2.0)).expect("stud");
        let shift = |x: f64, z: f64| {
            [
                1.0, 0.0, 0.0, x, //
                0.0, 1.0, 0.0, 0.0, //
                0.0, 0.0, 1.0, z, //
                0.0, 0.0, 0.0, 1.0,
            ]
        };
        let assembly = || brep_kernel::StepAssembly {
            products: vec![
                brep_kernel::StepProduct {
                    pd_ref: 1,
                    name: "root".into(),
                    id: "root".into(),
                    bodies: Vec::new(),
                    appearances: Vec::new(),
                    failed_bodies: 0,
                },
                brep_kernel::StepProduct {
                    pd_ref: 2,
                    name: "mid".into(),
                    id: "mid".into(),
                    // Bodies AND children — the interior node.
                    bodies: mid_bodies.clone(),
                    appearances: Vec::new(),
                    failed_bodies: 0,
                },
                brep_kernel::StepProduct {
                    pd_ref: 3,
                    name: "stud".into(),
                    id: "stud".into(),
                    bodies: leaf_bodies.clone(),
                    appearances: Vec::new(),
                    failed_bodies: 0,
                },
            ],
            occurrences: vec![
                brep_kernel::StepOccurrence {
                    nauo_ref: 10,
                    parent: 0,
                    child: 1,
                    designator: "mid-1".into(),
                    placement: shift(20.0, 0.0),
                    rigid: true,
                },
                brep_kernel::StepOccurrence {
                    nauo_ref: 11,
                    parent: 1,
                    child: 2,
                    designator: "stud-1".into(),
                    placement: shift(2.0, 1.0),
                    rigid: true,
                },
            ],
            roots: vec![0],
            first_error: None,
        };

        let mut nested = EngineState::new();
        nested.pending_step_assembly = Some(assembly());
        let report = nested
            .import_probed_step_assembly("interior", NESTED, &mut EmbeddedOnly)
            .expect("nested import");
        assert_eq!(
            (report.parts, report.instances),
            (1, 1),
            "ONE component — `mid` and everything under it"
        );

        // `mid`'s document: its own bodies as an IMPORT3D, its child as an ACOMP.
        let document = &library()["mid"]["document"];
        let kinds: Vec<&str> = document["features"]
            .as_array()
            .unwrap()
            .iter()
            .map(|feature| feature["type"].as_str().unwrap())
            .collect();
        assert_eq!(
            kinds,
            vec!["IMPORT3D", "ACOMP"],
            "the node's OWN bodies ride in ITS document, alongside its children"
        );
        assert_eq!(child_components(document), vec!["stud"]);
        assert!(
            !document["features"][0]["inputParams"]["nativeBrep"]
                .as_str()
                .unwrap_or_default()
                .is_empty(),
            "the interior geometry is a native payload, not STEP text"
        );

        // In the scene the two sit at DIFFERENT namespace depths under the one
        // component — the parent's body one segment in, the child's two — which
        // is exactly the parent/sibling distinction Phase 1 could not express.
        let names: Vec<&str> = nested
            .scene
            .solids()
            .iter()
            .map(|solid| solid.name.as_str())
            .collect();
        assert!(names.contains(&"ACOMP1:IMPORT3D1"), "mid's own body: {names:?}");
        assert!(
            names.contains(&"ACOMP1:ACOMP1:IMPORT3D1"),
            "the stud, one level deeper: {names:?}"
        );

        // And it lands where the flat lane puts it. Read the nested geometry
        // BEFORE the flat import: the kernel parts library is a thread-local the
        // next `EngineState` clears and refills.
        let nested_geometry = world_placed(&mut nested);
        let mut flat = EngineState::new();
        flat.pending_step_assembly = Some(assembly());
        flat.import_probed_step_assembly("interior", StepAssemblyImport::default(), &mut EmbeddedOnly)
            .expect("flat import");
        assert_eq!(
            placed_bboxes(&nested),
            placed_bboxes(&flat),
            "interior geometry must sit where the flat lane's composed pose puts it"
        );
        assert_placed_eq(
            &nested_geometry,
            &world_placed(&mut flat),
            1.0e-9,
            "interior node, nested vs flat",
        );
    }

    /// A non-rigid edge into a SUB-ASSEMBLY has no nested representation: the
    /// factor would have to be pushed down through a whole document tree,
    /// rewriting every level's poses. It is skipped with an explanation rather
    /// than silently mis-handed, and the flat lane — which composes the pose and
    /// bakes it into the leaf part — is where that file belongs. No fixture in
    /// the corpus carries one, so the occurrence is synthetic.
    #[test]
    fn a_mirrored_sub_assembly_is_reported_not_silently_mis_handed() {
        let bodies = brep_kernel::import_step(&box_step(4.0, 3.0, 2.0)).expect("box imports");
        let mirror = [
            -1.0, 0.0, 0.0, 30.0, //
            0.0, 1.0, 0.0, 0.0, //
            0.0, 0.0, 1.0, 0.0, //
            0.0, 0.0, 0.0, 1.0,
        ];
        // root → subasm (MIRRORED) → widget, plus a plain leaf under the root so
        // the import still lands rather than degenerating to "nothing built".
        let assembly = || brep_kernel::StepAssembly {
            products: vec![
                brep_kernel::StepProduct {
                    pd_ref: 1,
                    name: "root".into(),
                    id: "root".into(),
                    bodies: Vec::new(),
                    appearances: Vec::new(),
                    failed_bodies: 0,
                },
                brep_kernel::StepProduct {
                    pd_ref: 2,
                    name: "subasm".into(),
                    id: "subasm".into(),
                    bodies: Vec::new(),
                    appearances: Vec::new(),
                    failed_bodies: 0,
                },
                brep_kernel::StepProduct {
                    pd_ref: 3,
                    name: "widget".into(),
                    id: "widget".into(),
                    bodies: bodies.clone(),
                    appearances: Vec::new(),
                    failed_bodies: 0,
                },
            ],
            occurrences: vec![
                brep_kernel::StepOccurrence {
                    nauo_ref: 10,
                    parent: 0,
                    child: 1,
                    designator: "sub".into(),
                    placement: mirror,
                    rigid: false,
                },
                brep_kernel::StepOccurrence {
                    nauo_ref: 11,
                    parent: 0,
                    child: 2,
                    designator: "loose".into(),
                    placement: MAT4_IDENTITY,
                    rigid: true,
                },
                brep_kernel::StepOccurrence {
                    nauo_ref: 12,
                    parent: 1,
                    child: 2,
                    designator: "inner".into(),
                    placement: MAT4_IDENTITY,
                    rigid: true,
                },
            ],
            roots: vec![0],
            first_error: None,
        };

        let mut state = EngineState::new();
        state.pending_step_assembly = Some(assembly());
        let report = state
            .import_probed_step_assembly("mirror-sub", NESTED, &mut EmbeddedOnly)
            .expect("the rest of the file still imports");
        assert_eq!(report.instances, 1, "only the plain leaf lands");
        assert_eq!(report.baked_nonrigid, 0, "a sub-assembly is never baked");
        assert!(
            report
                .first_error
                .as_deref()
                .is_some_and(|error| error.contains("import flat instead")),
            "the user is told what to do instead: {:?}",
            report.first_error
        );

        // The FLAT lane handles it: the mirror composes onto the leaf and bakes.
        let mut flat = EngineState::new();
        flat.pending_step_assembly = Some(assembly());
        let flat_report = flat
            .import_probed_step_assembly("mirror-sub", StepAssemblyImport::default(), &mut EmbeddedOnly)
            .expect("flat");
        assert_eq!(
            (flat_report.instances, flat_report.baked_nonrigid),
            (2, 1),
            "flat places both and bakes the mirrored one"
        );
    }

    /// The nested lane places the same geometry the flat lane does — read as
    /// exact `f64` volume / centroid / bbox off the restored part geometry under
    /// the kernel's own component poses, not off a tessellation. Three levels of
    /// baked snapshots and pose round trips have to agree with one composed
    /// world transform.
    #[test]
    fn nested_import_matches_the_flat_lane_geometry() {
        let text = step_fixture("as1-ug-214.stp");

        let mut flat = EngineState::new();
        flat.import_step_assembly(&text, "as1-ug", StepAssemblyImport::default())
            .expect("flat import");
        let flat_geometry = world_placed(&mut flat);

        let mut nested = EngineState::new();
        nested
            .import_step_assembly(&text, "as1-ug", NESTED)
            .expect("nested import");
        let nested_geometry = world_placed(&mut nested);

        assert_eq!(flat_geometry.len(), 18, "as1-ug-214 places 18 bodies");
        assert_placed_eq(&nested_geometry, &flat_geometry, 1.0e-9, "nested vs flat");
        // The displayed scene agrees too — the same assertion the flat lane's
        // own oracle test makes, from the side the user sees.
        assert_eq!(placed_bboxes(&nested), placed_bboxes(&flat));
    }

    /// A nested sub-assembly heals like any other part: its entry's snapshot is
    /// a decode + re-encode of a document that is itself ACOMPs over native
    /// leaves, so a cleared cache must reproduce the insert's bytes and a second
    /// heal must reproduce the first.
    #[test]
    fn nested_part_documents_heal_and_converge() {
        let text = step_fixture("as1-ug-214.stp");
        let mut state = EngineState::new();
        state
            .import_step_assembly(&text, "as1-ug", NESTED)
            .expect("nested import");
        let inserted = library();

        let heal_once = |state: &mut EngineState| {
            let mut document: serde_json::Value =
                serde_json::from_str(&state.history_request_json()).expect("document JSON");
            for (_, entry) in document["partsLibrary"].as_object_mut().unwrap().iter_mut() {
                entry["snapshot"] = serde_json::Value::String(String::new());
            }
            state.set_history_json(&document.to_string()).expect("reopen");
            library()
        };
        let first = heal_once(&mut state);
        let second = heal_once(&mut state);
        assert_eq!(first, second, "a second heal reproduces the first");
        assert_eq!(
            first, inserted,
            "a heal of a SUB-ASSEMBLY entry reproduces what the insert stored — \
             the inner entries carry no snapshot, so this is the whole recursive \
             re-execution converging"
        );
        for (name, entry) in &first {
            assert!(
                !entry["snapshot"].as_str().unwrap_or_default().is_empty(),
                "'{name}' healed its cleared snapshot"
            );
        }
    }

    /// The recursion needs its OWN guard: `read_step_assembly` guards cycles
    /// inside its walk, but a document builder that recurses per level would
    /// blow the native stack on a malformed file long before the walk ever
    /// noticed. Both shapes must degrade to a clean result, never a crash.
    #[test]
    fn nested_import_guards_cycles_and_depth() {
        let bodies = brep_kernel::import_step(&box_step(2.0, 2.0, 2.0)).expect("box imports");
        let shift = |x: f64| {
            [
                1.0, 0.0, 0.0, x, //
                0.0, 1.0, 0.0, 0.0, //
                0.0, 0.0, 1.0, 0.0, //
                0.0, 0.0, 0.0, 1.0,
            ]
        };
        // A chain `root -> n1 -> n2 -> ... -> n{levels}`, the last link carrying
        // the geometry, plus an optional back-edge from the tail to `n1`.
        let chain = |levels: usize, cycle: bool| {
            let mut products: Vec<brep_kernel::StepProduct> = (0..=levels)
                .map(|index| brep_kernel::StepProduct {
                    pd_ref: index + 1,
                    name: format!("n{index}"),
                    id: format!("n{index}"),
                    bodies: (index == levels).then(|| bodies.clone()).unwrap_or_default(),
                    appearances: Vec::new(),
                    failed_bodies: 0,
                })
                .collect();
            products[0].name = "root".into();
            let mut occurrences: Vec<brep_kernel::StepOccurrence> = (0..levels)
                .map(|index| brep_kernel::StepOccurrence {
                    nauo_ref: 100 + index,
                    parent: index,
                    child: index + 1,
                    designator: format!("link{index}"),
                    placement: shift(1.0),
                    rigid: true,
                })
                .collect();
            if cycle {
                occurrences.push(brep_kernel::StepOccurrence {
                    nauo_ref: 90,
                    parent: levels,
                    child: 1,
                    designator: "back".into(),
                    placement: shift(1.0),
                    rigid: true,
                });
            }
            brep_kernel::StepAssembly {
                products,
                occurrences,
                roots: vec![0],
                first_error: None,
            }
        };

        // A CYCLE: the back-edge is skipped and said so, and the import lands.
        let mut state = EngineState::new();
        state.pending_step_assembly = Some(chain(3, true));
        let report = state
            .import_probed_step_assembly("cyclic", NESTED, &mut EmbeddedOnly)
            .expect("a cyclic structure still imports what it can");
        assert_eq!(report.instances, 1, "the root places its one child");
        assert!(
            report
                .first_error
                .as_deref()
                .is_some_and(|error| error.contains("cycle")),
            "the skipped back-edge is reported: {:?}",
            report.first_error
        );
        assert!(!state.scene.solids().is_empty(), "the geometry still arrives");

        // PATHOLOGICALLY DEEP: refused cleanly, no stack overflow, and the flat
        // lane (which composes rather than embeds) still handles it.
        let mut state = EngineState::new();
        state.pending_step_assembly = Some(chain(MAX_NESTED_DEPTH + 40, false));
        let error = state
            .import_probed_step_assembly("deep", NESTED, &mut EmbeddedOnly)
            .expect_err("a 100-level nesting has no usable document");
        assert!(
            error.contains("no part of the assembly could be built"),
            "the dialog's cue to fall back to the flat import: {error}"
        );
        let mut state = EngineState::new();
        state.pending_step_assembly = Some(chain(MAX_NESTED_DEPTH + 40, false));
        assert!(
            state
                .import_probed_step_assembly("deep", StepAssemblyImport::default(), &mut EmbeddedOnly)
                .is_ok(),
            "the FLAT lane composes instead of embedding, so depth costs it nothing"
        );
    }

    /// The batch mutation on its own: N features, ONE rebuild, ONE undo step;
    /// an empty batch is a no-op that neither runs nor checkpoints.
    #[test]
    fn add_features_appends_a_batch_in_one_rebuild() {
        let mut state = EngineState::new();
        state.set_history_json(&cube_history("Box", 4.0)).unwrap();
        let before = state.applied_generation();

        state.add_features(&[]);
        assert_eq!(
            (state.applied_generation(), state.history_len()),
            (before, 1),
            "an empty batch neither re-runs nor appends"
        );

        let features: Vec<serde_json::Value> = (0..3)
            .map(|index| {
                serde_json::json!({
                    "type": "P.CU",
                    "inputParams": {
                        "id": format!("Cube{index}"),
                        "sizeX": 2.0, "sizeY": 2.0, "sizeZ": 2.0,
                        "transform": {
                            "position": [10.0 * index as f64, 0.0, 0.0],
                            "rotationEuler": [0.0, 0.0, 0.0],
                            "scale": [1.0, 1.0, 1.0]
                        },
                        "boolean": { "targets": [], "operation": "NONE" }
                    },
                    "persistentData": {}
                })
            })
            .collect();
        state.add_features(&features);

        assert_eq!(state.history_len(), 4, "all three appended");
        assert_eq!(
            state.applied_generation(),
            before + 1,
            "ONE rebuild for the batch"
        );
        assert_eq!(state.scene.solids().len(), 4);
        state.undo();
        assert_eq!(state.history_len(), 1, "the batch undoes in ONE step");
    }
}

// ===========================================================================
// Feature dimensions (FD-1) — the ◎ DIMENSION-gizmo mode.
//
// When a primitive-solid feature is armed in DIMENSION mode (the ◎'s second
// cycle state), its key numeric params render as draggable dimension
// annotations: a leader from world `pointA → pointB` whose length is the param
// value, editing `fieldKey`. The geometry lives in `crate::feature_dimensions`
// (ported from the previous feature-dimension annotation builder); THIS block owns the
// engine surface: reporting the annotations (JSON + the `feature-dim-leaders`
// overlay), dragging a handle (project the pointer onto the `a → b` world axis →
// new param value), and value-editing a label (numeric literal OR a live
// expression via the kernel `eval_expression`). Every mutator re-runs the
// history (the model updates live) and re-projects the leaders. Kept in ONE
// appended block so concurrent edits to the primary impl land clean.
// ===========================================================================