openusd 0.6.0

Rust native USD library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
//! Stage-level namespace editing, the Rust port of C++ `UsdNamespaceEditor`
//! (`pxr/usd/usd/namespaceEditor.h`).
//!
//! [`NamespaceEditor`] renames, reparents, and deletes prims and properties on
//! a composed [`Stage`], fixing up everything that points at the moved or
//! deleted objects — relationship targets, attribute connections, and internal
//! references / inherits / specializes — and authoring relocates when an
//! object's opinions arrive across a reference or payload arc.
//!
//! Unlike C++, which applies one edit at a time, edits batch: each staging call
//! appends to an ordered queue and [`apply`](NamespaceEditor::apply) commits the
//! whole batch. The batch is sequential — a later edit sees the result of the
//! earlier ones, so `move /A → /B` then `delete /B/Child` resolves naturally.
//! This falls out of the atomic copy-on-write staging: structural ops stage in
//! each layer's overlay, whose reads already reflect the prior edits, and all
//! layers commit together once the batch authors cleanly.
//!
//! The current edit target selects one of two authoring shapes. An identity
//! target on the local root layer stack authors across the whole stack, as C++
//! does: it moves local specs directly and synthesizes `layerRelocates` for
//! content that arrives across a reference or payload arc. A variant or
//! cross-arc edit target authors into the layer stack it writes to — the
//! referenced asset's stack for an arc target, the root stack for a variant —
//! in that target's namespace, with each edit path mapped through the target: a
//! variant move lands at the `{set=sel}` paths, a cross-arc move edits the
//! shared source layer.
//!
//! A mapped target edits whatever its own layer stack can reach. Content with a
//! spec in that stack moves or deletes directly across the stack's layers;
//! content arriving across an arc nested below the target has no spec to move,
//! so the editor synthesizes a `layerRelocates` pair into the target's stack (in
//! the target's namespace) — the only stack where, per spec §10.3.2.6, that
//! relocate takes effect. A source that also composes from a layer stack the
//! target does not own — a stronger override above a reference target, or a
//! sibling arc — cannot be expressed through the target's stack and is rejected
//! ([`RequiresRelocate`](NamespaceEditError::RequiresRelocate)). A move onto a
//! destination already occupied on the composed stage collides
//! ([`DestinationExists`](NamespaceEditError::DestinationExists)) rather than
//! silently merging.
//!
//! In both shapes the structural move is [`copy_spec_within`](crate::sdf::copy_spec_within)
//! plus [`Layer::remove_spec`](crate::sdf::Layer::remove_spec), and the fixup
//! remaps embedded paths in place through
//! [`Value::filter_map_paths`](crate::sdf::Value::filter_map_paths), preserving
//! list-op structure rather than flattening opinions. The local-stack fixup
//! remaps in stage namespace; the mapped fixup lifts each path to stage
//! namespace, follows the batch's moves, then maps it back into the target
//! layer's namespace.

use std::collections::{HashMap, HashSet};

use super::{EditTarget, Prim, Stage, StageAuthoringError};
use crate::{pcp, sdf};

/// Batches namespace edits — prim/property renames, reparents, and deletes —
/// and applies them to a [`Stage`] with full target/connection/reference fixup.
/// Mirrors C++ `UsdNamespaceEditor`.
///
/// Stage an edit with one of the staging methods, then [`apply`](Self::apply)
/// (or check feasibility first with [`can_apply`](Self::can_apply)). A
/// successful [`apply`](Self::apply) clears the queue.
pub struct NamespaceEditor {
    stage: Stage,
    edits: Vec<NamespaceEdit>,
}

/// One staged namespace edit. Paths are in composed stage namespace and are
/// interpreted after the edits queued before them. `kind` is fixed by the
/// staging method (a prim or a property edit) and the paths are validated
/// against it, so a prim path passed to a property method is rejected.
enum NamespaceEdit {
    /// Remove the object (prim or property) at `path` and its namespace
    /// descendants.
    Delete { path: sdf::Path, kind: ObjectKind },
    /// Move the object at `src` (and its descendants) to `dst`.
    Move {
        src: sdf::Path,
        dst: sdf::Path,
        kind: ObjectKind,
    },
}

/// Whether a staged edit targets a prim or a property. The staging method fixes
/// this, and each edit path is checked to be of the matching kind.
#[derive(Clone, Copy, PartialEq)]
enum ObjectKind {
    Prim,
    Property,
}

impl ObjectKind {
    /// Whether `path` is of this kind — a property path for `Property`, a
    /// non-property (prim) path for `Prim`.
    fn matches(self, path: &sdf::Path) -> bool {
        path.is_property_path() == (self == ObjectKind::Property)
    }
}

impl NamespaceEdit {
    /// The path the edit reads from — the move source or the deletion target.
    fn source(&self) -> &sdf::Path {
        match self {
            NamespaceEdit::Delete { path, .. } => path,
            NamespaceEdit::Move { src, .. } => src,
        }
    }
}

/// Errors raised while staging, validating, or applying a namespace edit.
#[derive(Debug, thiserror::Error)]
pub enum NamespaceEditError {
    /// [`apply`](NamespaceEditor::apply) was called with no edits staged.
    #[error("no namespace edits staged")]
    NoEdits,

    /// A source path is not an absolute prim or property path.
    #[error("source path {0} is not an absolute prim or property path")]
    InvalidSource(sdf::Path),

    /// A destination path is not a valid absolute object path.
    #[error("destination path {0} is not a valid absolute object path")]
    InvalidDestination(sdf::Path),

    /// An edit targets the pseudo-root, which cannot be renamed or deleted.
    #[error("cannot namespace-edit the pseudo-root")]
    PseudoRoot,

    /// Nothing is composed at a source path (accounting for the edits queued
    /// before it).
    #[error("nothing composed at the source path {0}")]
    SourceNotFound(sdf::Path),

    /// An object already exists at a destination path.
    #[error("an object already exists at the destination {0}")]
    DestinationExists(sdf::Path),

    /// The batch cannot be expressed as a valid relocate set: deleting a
    /// cross-arc prim would orphan a descendant an earlier edit relocated out of
    /// it, or the synthesized relocates violate Pcp's structural/conflict rules.
    /// USD relocates cannot represent the requested namespace, so the batch is
    /// rejected rather than authored as relocates Pcp would silently drop.
    #[error("the requested edits cannot be represented as valid relocates (at {0})")]
    UnrepresentableRelocateBatch(sdf::Path),

    /// A destination is the source itself or a descendant of it, so the move
    /// would nest a subtree inside itself.
    #[error("destination {dst} is the source or a descendant of {src}")]
    DestinationUnderSource {
        /// The move's source path.
        src: sdf::Path,
        /// The move's destination path.
        dst: sdf::Path,
    },

    /// An edit path is the wrong namespace kind for the operation — a prim path
    /// passed to a property edit, or a property path to a prim edit.
    #[error("path is the wrong namespace kind for this edit (prim vs property)")]
    KindMismatch,

    /// An edit against a mapped (variant or cross-arc) edit target cannot be
    /// expressed through the target's own layer stack: the source composes from
    /// a layer stack the target does not own — a stronger override above a
    /// reference target, or a sibling arc — so a direct edit would leave it
    /// composed and no relocate the target's stack can carry would suppress it.
    /// Content arriving across an arc nested below the target is realized by a
    /// synthesized relocate instead and does not raise this.
    #[error("the edit at {0} would need a relocate the current edit target cannot author")]
    RequiresRelocate(sdf::Path),

    /// A composed-stage query needed to validate or apply an edit failed.
    #[error(transparent)]
    Composition(#[from] anyhow::Error),

    /// Authoring the edit onto a layer failed.
    #[error(transparent)]
    Stage(#[from] StageAuthoringError),
}

impl From<sdf::sink::Error> for NamespaceEditError {
    fn from(error: sdf::sink::Error) -> Self {
        NamespaceEditError::Stage(StageAuthoringError::Rejected(error))
    }
}

impl NamespaceEditor {
    /// Create an editor with an empty edit queue targeting `stage`.
    pub fn new(stage: &Stage) -> Self {
        Self {
            stage: stage.clone(),
            edits: Vec::new(),
        }
    }

    /// Stage a move of the prim at `old` to `new`. Mirrors C++
    /// `MovePrimAtPath`.
    pub fn move_prim(&mut self, old: impl Into<sdf::Path>, new: impl Into<sdf::Path>) -> &mut Self {
        self.push_move(old, new, ObjectKind::Prim)
    }

    /// Stage a move of the property at `old` to `new`. Mirrors C++
    /// `MovePropertyAtPath`.
    pub fn move_property(&mut self, old: impl Into<sdf::Path>, new: impl Into<sdf::Path>) -> &mut Self {
        self.push_move(old, new, ObjectKind::Property)
    }

    /// Stage a deletion of the prim at `path`. Mirrors C++ `DeletePrimAtPath`.
    pub fn delete_prim(&mut self, path: impl Into<sdf::Path>) -> &mut Self {
        self.push_delete(path, ObjectKind::Prim)
    }

    /// Stage a deletion of the property at `path`. Mirrors C++
    /// `DeletePropertyAtPath`.
    pub fn delete_property(&mut self, path: impl Into<sdf::Path>) -> &mut Self {
        self.push_delete(path, ObjectKind::Property)
    }

    fn push_move(&mut self, old: impl Into<sdf::Path>, new: impl Into<sdf::Path>, kind: ObjectKind) -> &mut Self {
        self.edits.push(NamespaceEdit::Move {
            src: old.into(),
            dst: new.into(),
            kind,
        });
        self
    }

    fn push_delete(&mut self, path: impl Into<sdf::Path>, kind: ObjectKind) -> &mut Self {
        self.edits.push(NamespaceEdit::Delete {
            path: path.into(),
            kind,
        });
        self
    }

    /// Stage a rename of `prim` to the sibling name `new_name`. Mirrors C++
    /// `RenamePrim`.
    pub fn rename_prim(&mut self, prim: &Prim, new_name: &str) -> Result<&mut Self, NamespaceEditError> {
        let src = prim.path().clone();
        let parent = src.parent().ok_or(NamespaceEditError::PseudoRoot)?;
        let dst = parent
            .append_path(new_name)
            .map_err(|_| NamespaceEditError::InvalidDestination(src.clone()))?;
        Ok(self.move_prim(src, dst))
    }

    /// Stage a reparent of `prim` under `new_parent`, keeping its name. Mirrors
    /// C++ `ReparentPrim`.
    pub fn reparent_prim(&mut self, prim: &Prim, new_parent: &Prim) -> Result<&mut Self, NamespaceEditError> {
        let name = prim.path().name().ok_or(NamespaceEditError::PseudoRoot)?.to_owned();
        self.reparent_prim_with_name(prim, new_parent, &name)
    }

    /// Stage a reparent of `prim` under `new_parent`, renaming it to `new_name`.
    /// Mirrors C++ `ReparentPrim` with a new name.
    pub fn reparent_prim_with_name(
        &mut self,
        prim: &Prim,
        new_parent: &Prim,
        new_name: &str,
    ) -> Result<&mut Self, NamespaceEditError> {
        let src = prim.path().clone();
        let dst = new_parent
            .path()
            .append_path(new_name)
            .map_err(|_| NamespaceEditError::InvalidDestination(src.clone()))?;
        Ok(self.move_prim(src, dst))
    }

    /// Check whether [`apply`](Self::apply) would succeed, without changing the
    /// stage. Mirrors C++ `CanApplyEdits`. This runs the same path as
    /// [`apply`](Self::apply) but always rolls the transactions back, so any
    /// error surfaces here exactly as it would there.
    pub fn can_apply(&self) -> Result<(), NamespaceEditError> {
        self.execute(false)
    }

    /// Apply every staged edit to the stage's local layer stack, fixing up
    /// targets / connections / internal references and authoring relocates for
    /// objects composed across an arc. On success the edit queue is cleared.
    /// Mirrors C++ `ApplyEdits`.
    ///
    /// The whole batch is atomic: the edits stage into every affected layer's
    /// overlay in order, and the layers commit together only once every one has
    /// authored cleanly. An authoring error rolls every layer back, so a failed
    /// apply leaves the stage exactly as it was. This atomicity is only against
    /// authoring errors,
    /// not a database-style guarantee: a layer's backing
    /// [`AbstractData`](sdf::AbstractData) can be any implementation (an
    /// in-memory store, `CrateData`, a custom backend), and committing a staged
    /// edit into it is not assumed to itself be atomic or recoverable.
    ///
    /// When the batch touches more than one layer, the single
    /// [`CommittedChange`](super::CommittedChange) delivered to
    /// [`after_commit`](super::StageSink::after_commit) merges the per-layer
    /// change records and attributes them to the strongest edited layer.
    /// Composed-path reporting is exact, but a sink that reads the merged change
    /// list — notably [`ReplayStage`](super::ReplayStage) — cannot recover which
    /// layer each record landed in, so forward-diff replication of a multi-layer
    /// namespace edit is not supported yet. (An [`UndoStage`](super::UndoStage)
    /// captures per layer at [`before_commit`](super::StageSink::before_commit),
    /// so it is unaffected.)
    pub fn apply(&mut self) -> Result<(), NamespaceEditError> {
        self.execute(true)?;
        self.edits.clear();
        Ok(())
    }

    /// Stage the batch onto the local layer stack as one atomic multi-layer edit.
    /// Runs in two phases. First a [`NamespaceProjection`] replays the batch over
    /// the composed pre-batch namespace to settle the cross-arc facts the staged
    /// overlays cannot see — whether each source/destination resolves to content
    /// realized by a relocate — and to build the relocate plan; this must finish
    /// before the layer graph is borrowed mutably, since composition queries and
    /// layer mutation cannot borrow the stage at once. Then each edit stages in
    /// order against every affected layer, combining its projected facts with the
    /// staged overlays (which reflect the prior edits), embedded paths are
    /// remapped, and the relocates authored. The layers either commit together
    /// (driving one composition-invalidation cycle) or — when `commit` is false —
    /// roll back for a dry run. The shared path behind
    /// [`can_apply`](Self::can_apply) and [`apply`](Self::apply).
    ///
    /// Any failure — an invalid edit or an authoring error — rolls every layer
    /// back, so a failed batch leaves the stage untouched and the cache valid. A
    /// dry run runs this same path, so [`can_apply`](Self::can_apply) reports an
    /// error exactly as
    /// [`apply`](Self::apply) would hit it.
    fn execute(&self, commit: bool) -> Result<(), NamespaceEditError> {
        if self.edits.is_empty() {
            return Err(NamespaceEditError::NoEdits);
        }
        match self.plan()? {
            BatchPlan::LocalStack {
                layer_ids,
                seeds,
                relocates,
                per_edit,
            } => self.execute_local_stack(commit, layer_ids, seeds, relocates, per_edit),
            BatchPlan::Mapped {
                target,
                per_edit,
                stack_layer_ids,
                seeds,
                relocates,
            } => self.execute_mapped(commit, &target, &per_edit, stack_layer_ids, seeds, relocates),
        }
    }

    /// Stage the batch into the local root layer stack: direct structural moves
    /// and deletes at the composed (stage == spec) paths across every local
    /// layer, embedded-path fixup, and synthesized relocates for content that
    /// arrives across an arc. The identity-target authoring shape behind
    /// [`execute`](Self::execute).
    fn execute_local_stack(
        &self,
        commit: bool,
        layer_ids: Vec<pcp::LayerId>,
        seeds: HashMap<pcp::LayerId, sdf::RelocateList>,
        relocate_plan: RelocateStackPlan,
        plan: Vec<EditPlan>,
    ) -> Result<(), NamespaceEditError> {
        let resolved = relocate_plan.resolve(seeds)?;

        // Stage the structural edits atomically across the layer
        // stack. The whole batch commits through `edit_layers`: every layer's
        // sinks veto first, then all commit, so a multi-layer namespace edit is
        // all-or-nothing even under a rejecting sink, and each commit feeds the
        // stage's aggregator for the recompose below. A dry run (`dry_run_layers`)
        // stages the same way to prove the batch applies, then discards it. The
        // batch assumes its layers carry no uncommitted direct edits — a discard
        // drops the whole overlay.
        {
            let mut graph = self.stage.layers_mut();
            let mut layers: Vec<(pcp::LayerId, &mut sdf::Layer)> = graph.layers_mut(&layer_ids).into_iter().collect();
            let ids: Vec<pcp::LayerId> = layers.iter().map(|(id, _)| *id).collect();
            let mut batch: Vec<&mut sdf::Layer> = layers.iter_mut().map(|(_, layer)| &mut **layer).collect();
            let stage_edits = |edits: &mut [sdf::LayerEdit<'_>]| -> Result<(), NamespaceEditError> {
                {
                    let mut refs: Vec<&mut sdf::LayerEdit<'_>> = edits.iter_mut().collect();
                    for (edit, plan) in self.edits.iter().zip(&plan) {
                        apply_edit(&mut refs, edit, plan)?;
                    }
                }
                for (id, layer) in ids.iter().zip(edits.iter_mut()) {
                    fixup_embedded_paths(layer, &self.edits)?;
                    // The plan is the sole authority for relocates; the generic
                    // fixup above leaves them alone.
                    if let Some(next) = resolved.change_for(*id) {
                        layer.set_relocates(next).map_err(StageAuthoringError::Layer)?;
                    }
                }
                Ok(())
            };
            if commit {
                sdf::edit_layers(&mut batch, stage_edits)?;
            } else {
                // Dry run: stage to prove the batch applies cleanly, then discard.
                // No sink sees a dry run.
                return sdf::dry_run_layers(&mut batch, stage_edits);
            }
        }
        self.stage.process_pending();
        Ok(())
    }

    /// Stage the batch into the layer a variant or cross-arc edit target writes
    /// to, in that target's namespace, across the target's own layer stack. Each
    /// edit's paths are mapped through the target ([`MappedEdit`]); a directly
    /// reachable source moves or deletes as a spec edit in the target layer, and
    /// a source arriving across an arc nested below the target is realized by a
    /// relocate synthesized into the target's layer stack
    /// ([`RelocateStackPlan`], resolved per stack layer). Embedded paths are
    /// fixed up through the lift-then-map chain on every stack layer. The mapped
    /// authoring shape behind [`execute`](Self::execute).
    ///
    /// The whole batch — spec moves, relocates, and fixups — commits together as
    /// one atomic transaction over the stack (or dry-runs for
    /// [`can_apply`](Self::can_apply)). An edit whose source composes from a
    /// layer stack the target does not own is rejected by
    /// [`plan_mapped`](Self::plan_mapped) before staging, since no relocate in
    /// the target's stack can express it.
    fn execute_mapped(
        &self,
        commit: bool,
        target: &EditTarget,
        per_edit: &[MappedEdit],
        stack_layer_ids: Vec<pcp::LayerId>,
        seeds: HashMap<pcp::LayerId, sdf::RelocateList>,
        relocates: RelocateStackPlan,
    ) -> Result<(), NamespaceEditError> {
        let resolved = relocates.resolve(seeds)?;
        self.stage
            .author_layers_txn(&stack_layer_ids, Some(target.map_function()), commit, |ids, edits| {
                for mapped in per_edit {
                    apply_mapped_edit(edits, mapped)?;
                }
                for (id, layer) in ids.iter().zip(edits.iter_mut()) {
                    fixup_mapped_paths(layer, target, &self.edits)?;
                    // The plan owns relocates; the generic fixup leaves them alone.
                    if let Some(next) = resolved.change_for(*id) {
                        layer.set_relocates(next).map_err(StageAuthoringError::Layer)?;
                    }
                }
                Ok(())
            })
    }

    /// Resolve the current edit target into a [`BatchPlan`], the read-only first
    /// half of [`execute`](Self::execute) shared with
    /// [`layers_to_edit`](Self::layers_to_edit). An identity local-stack target
    /// plans direct authoring plus relocate synthesis
    /// ([`plan_local_stack`](Self::plan_local_stack)); a variant or cross-arc
    /// target plans direct mapped authoring ([`plan_mapped`](Self::plan_mapped)).
    /// Runs before the layer graph is borrowed mutably for staging: composition
    /// queries and layer mutation cannot borrow the stage at once.
    fn plan(&self) -> Result<BatchPlan, NamespaceEditError> {
        let edit_target = self.stage.edit_target_layer_id()?;
        let layer_ids = self.stage.root_stack_layer_ids();
        let target = self.stage.edit_target();
        // An identity mapping into a local-stack layer authors at the composed
        // (stage == spec) paths verbatim, so the batch can move local specs
        // directly and synthesize relocates for cross-arc content. Any other
        // target is single-layer and mapped: every path goes through the target
        // and only directly reachable content is edited.
        if layer_ids.contains(&edit_target) && target.map_function().is_identity() {
            self.plan_local_stack(layer_ids, edit_target)
        } else {
            self.plan_mapped(edit_target, target)
        }
    }

    /// Plan the identity local-stack authoring shape: seed every local-stack
    /// layer's relocates and evolve them through the edits, deciding per edit
    /// whether its source and destination resolve to cross-arc content.
    fn plan_local_stack(
        &self,
        layer_ids: Vec<pcp::LayerId>,
        edit_target: pcp::LayerId,
    ) -> Result<BatchPlan, NamespaceEditError> {
        // `seeds` (per layer) is the baseline each layer's final list is compared
        // against; the plan tracks per-occurrence freshness so validation blames
        // only the pairs this batch created or changed.
        let seeds = seed_relocates(&self.stage.layers(), &layer_ids);
        let projection = NamespaceProjection::new(&self.stage);
        let mut relocates = RelocateStackPlan::new(&layer_ids, &seeds, edit_target);
        let mut per_edit: Vec<EditPlan> = Vec::with_capacity(self.edits.len());
        // TODO(perf): each edit replays the growing `earlier` prefix through
        // `cross_arc_facts`/`occupied` (premove/project over all prior edits),
        // making the projection work O(edits^2); a forward cumulative path
        // projection would make it linear if batches ever grow large.
        for (i, edit) in self.edits.iter().enumerate() {
            validate_edit_shape(edit)?;
            let earlier = &self.edits[..i];
            let entry = match edit {
                NamespaceEdit::Move { src, dst, .. } => {
                    let occupied = projection.occupied(dst, earlier)?;
                    let (present, masks) = projection.cross_arc_facts(src, earlier)?;
                    if present && masks {
                        return Err(NamespaceEditError::UnrepresentableRelocateBatch(src.clone()));
                    }
                    relocates.record_move(src, dst, present)?;
                    EditPlan { present, occupied }
                }
                NamespaceEdit::Delete { path, .. } => {
                    let (present, masks) = projection.cross_arc_facts(path, earlier)?;
                    if present && masks {
                        return Err(NamespaceEditError::UnrepresentableRelocateBatch(path.clone()));
                    }
                    relocates.record_delete(path, present)?;
                    EditPlan {
                        present,
                        occupied: false,
                    }
                }
            };
            per_edit.push(entry);
        }
        Ok(BatchPlan::LocalStack {
            layer_ids,
            seeds,
            relocates,
            per_edit,
        })
    }

    /// Plan the mapped authoring shape for a variant or cross-arc `target`:
    /// translate each edit's paths into the target layer's namespace, rejecting a
    /// move endpoint the target cannot express
    /// ([`StageAuthoringError::OutsideEditTarget`]), classify each source against
    /// the edit-target node's subtree, and evolve a [`RelocateStackPlan`] over the
    /// target's own layer stack for the sources that need a relocate.
    ///
    /// The target writes into one layer stack — its own. A source's contributing
    /// opinions are reachable through that stack when they sit at or below the
    /// edit-target node ([`NamespaceProjection::target_facts`]): a spec in the
    /// target's own stack moves directly, and content arriving across an arc
    /// nested below the target is realized by a relocate synthesized into the
    /// target's stack (in target namespace). A source that also composes from a
    /// layer stack the target does not own — a stronger override above a
    /// reference target, or a sibling arc — cannot be expressed through the
    /// target's stack and is rejected
    /// ([`RequiresRelocate`](NamespaceEditError::RequiresRelocate)). Per spec
    /// §10.3.2.6 a relocate only takes effect in the stack where its bringing-in
    /// arc is authored, so authoring it anywhere else would not relink
    /// composition.
    fn plan_mapped(&self, layer_id: pcp::LayerId, target: EditTarget) -> Result<BatchPlan, NamespaceEditError> {
        let map = |path: &sdf::Path| {
            target
                .map_to_spec_path(path)
                .ok_or_else(|| NamespaceEditError::Stage(StageAuthoringError::OutsideEditTarget { path: path.clone() }))
        };
        // The target authors into its own layer stack; seed the relocate plan
        // from that stack's existing pairs, under one graph borrow.
        let stack_id = self
            .stage
            .mapped_target_stack_id(layer_id)
            .map_err(NamespaceEditError::Stage)?;
        let (stack_layer_ids, seeds) = {
            let layers = self.stage.layers();
            let ids: Vec<pcp::LayerId> = layers.layer_stack(stack_id).iter().map(|&(id, _)| id).collect();
            let seeds = seed_relocates(&layers, &ids);
            (ids, seeds)
        };
        let projection = NamespaceProjection::new(&self.stage);
        let mut relocates = RelocateStackPlan::new(&stack_layer_ids, &seeds, layer_id);
        let mut per_edit: Vec<MappedEdit> = Vec::with_capacity(self.edits.len());
        // TODO(perf): like `plan_local_stack`, each edit rebuilds the composed
        // index for its source prim (`target_facts` clones the cached index) and
        // replays the growing `earlier` prefix, making the projection work
        // O(edits^2); a forward cumulative path projection would make it linear.
        for (i, edit) in self.edits.iter().enumerate() {
            validate_edit_shape(edit)?;
            let earlier = &self.edits[..i];
            let stage_src = edit.source().clone();
            let src = map(&stage_src)?;
            let composed = self.stage.has_spec(&stage_src)?;
            let facts = projection.target_facts(&stage_src, earlier, stack_id, &target)?;
            // A contributor in a layer stack the target does not own survives a
            // direct edit and cannot be relocated from the target's stack.
            if facts.outside {
                return Err(NamespaceEditError::RequiresRelocate(stage_src));
            }
            // A masking relocate target cannot be moved or deleted as one
            // relocate: doing so reveals the masked plain content at the old path.
            if facts.masks {
                return Err(NamespaceEditError::UnrepresentableRelocateBatch(stage_src));
            }
            // Only a prim arriving across an arc below the target needs (and can
            // carry) a relocate; a property is moved or deleted directly.
            let relocated = facts.below_target && !stage_src.is_property_path();
            let (dst, occupied) = match edit {
                NamespaceEdit::Move { dst, .. } => {
                    let mapped_dst = map(dst)?;
                    let occupied = projection.occupied(dst, earlier)?;
                    relocates.record_move(&src, &mapped_dst, relocated)?;
                    (Some(mapped_dst), occupied)
                }
                NamespaceEdit::Delete { .. } => {
                    relocates.record_delete(&src, relocated)?;
                    (None, false)
                }
            };
            per_edit.push(MappedEdit {
                stage_src,
                src,
                dst,
                composed,
                occupied,
                relocated,
            });
        }
        Ok(BatchPlan::Mapped {
            target,
            per_edit,
            stack_layer_ids,
            seeds,
            relocates,
        })
    }

    /// The identifiers of the local-stack layers a successful apply would write:
    /// a layer holding a spec at a source path (the structural move or delete) or
    /// one whose `layerRelocates` the batch would change — including a sublayer
    /// whose relocate follows a moved or deleted prim. Mirrors C++
    /// `GetLayersToEdit`.
    pub fn layers_to_edit(&self) -> Result<Vec<String>, NamespaceEditError> {
        if self.edits.is_empty() {
            return Ok(Vec::new());
        }
        // TODO(perf): this preflight runs the full `plan()` — composed-index
        // builds and relocate analysis per edit — because the evolved relocates
        // decide which layers' `layerRelocates` change. A future fast path could
        // skip the composition projection when no edit is cross-arc and no layer
        // authors relocates, leaving only the cheap per-layer spec scan.
        match self.plan()? {
            BatchPlan::LocalStack {
                layer_ids,
                seeds,
                relocates,
                ..
            } => {
                let resolved = relocates.resolve(seeds)?;
                let sources: Vec<&sdf::Path> = self.edits.iter().map(NamespaceEdit::source).collect();
                self.touched_layers(&layer_ids, &resolved, &sources, |p| Ok(project_path(p, &self.edits)))
            }
            // A mapped target authors into its own layer stack: the target layer
            // (a spec move or delete), any stack layer whose relocates change, and
            // any stack layer whose embedded paths the mapped fixup rewrites.
            BatchPlan::Mapped {
                target,
                stack_layer_ids,
                seeds,
                relocates,
                per_edit,
            } => {
                let resolved = relocates.resolve(seeds)?;
                let sources: Vec<&sdf::Path> = per_edit.iter().map(|mapped| &mapped.src).collect();
                self.touched_layers(&stack_layer_ids, &resolved, &sources, |p| {
                    remap_embedded_path(p, &target, &self.edits)
                })
            }
        }
    }

    /// The identifiers of the layers in `layer_ids` a successful apply would
    /// write: one holding a spec at any path in `sources` (a structural move or
    /// delete), one whose `layerRelocates` the batch would change (`resolved`),
    /// or one whose embedded paths the fixup `rewrite` would rewrite (a
    /// relationship/connection/internal-reference target into a moved or deleted
    /// object, even with no source spec of its own). The per-layer scan shared by
    /// the local-stack and mapped [`layers_to_edit`](Self::layers_to_edit) shapes.
    // TODO(perf): each layer is independent — the spec scan, the relocate
    // comparison, and the embedded-path scan can run in parallel.
    fn touched_layers(
        &self,
        layer_ids: &[pcp::LayerId],
        resolved: &ResolvedRelocates,
        sources: &[&sdf::Path],
        rewrite: impl Fn(&sdf::Path) -> Result<Option<sdf::Path>, NamespaceEditError>,
    ) -> Result<Vec<String>, NamespaceEditError> {
        let layers = self.stage.layers();
        let mut result = Vec::new();
        for id in layer_ids {
            let Some(node) = layers.get(*id) else { continue };
            let touches = sources.iter().any(|src| node.layer.data().has_spec(src))
                || resolved.change_for(*id).is_some()
                || layer_fixup_touches(node.layer.data(), &rewrite)?;
            if touches {
                result.push(layers.identifier(*id).to_string());
            }
        }
        Ok(result)
    }
}

/// The read-only result of [`NamespaceEditor::plan`], one variant per authoring
/// shape. Consumed by `execute` to validate and stage, and by `layers_to_edit`
/// to report which layers a successful apply would write.
enum BatchPlan {
    /// An identity local-stack target: the local-stack layer ids, each layer's
    /// seed relocates, the evolved relocate stack plan, and the per-edit
    /// cross-arc facts.
    LocalStack {
        layer_ids: Vec<pcp::LayerId>,
        seeds: HashMap<pcp::LayerId, sdf::RelocateList>,
        relocates: RelocateStackPlan,
        per_edit: Vec<EditPlan>,
    },
    /// A variant or cross-arc target: the layer it writes to, that target
    /// (carrying the namespace mapping), the batch edits translated into the
    /// target layer's namespace, and — for content arriving across an arc nested
    /// below the target — the relocate plan over the target's own layer stack
    /// (its member layer ids and their seed relocates) that realizes those
    /// edits. A pure direct move authors no relocates, leaving the plan a no-op.
    Mapped {
        target: EditTarget,
        per_edit: Vec<MappedEdit>,
        stack_layer_ids: Vec<pcp::LayerId>,
        seeds: HashMap<pcp::LayerId, sdf::RelocateList>,
        relocates: RelocateStackPlan,
    },
}

/// One batch edit translated into a mapped target layer's namespace. A move
/// copies the source spec subtree to the destination and removes the source; a
/// delete (`dst` is `None`) removes the source spec. When `relocated`, the
/// source's content arrives across an arc nested below the edit target, so a
/// synthesized relocate (authored separately into the target's layer stack)
/// realizes the edit and the structural op authors nothing for it.
struct MappedEdit {
    /// The edit's source path in composed stage namespace, for error reporting.
    stage_src: sdf::Path,
    /// The source spec path in the target layer's namespace — a move source or
    /// a deletion target.
    src: sdf::Path,
    /// The destination spec path for a move, `None` for a delete.
    dst: Option<sdf::Path>,
    /// Whether the source composes on the stage before the batch, separating a
    /// source that arrives across a deeper arc (and would need a relocate) from
    /// one that is simply absent.
    composed: bool,
    /// Whether a composed object already occupies the move destination on the
    /// stage (a referenced or otherwise cross-arc occupant the target layer's
    /// overlay alone cannot see). Always `false` for a delete.
    occupied: bool,
    /// Whether the edit is realized by a relocate synthesized into the target's
    /// own layer stack — content arriving across an arc nested below the edit
    /// target, which has no spec in the target's stack to move directly. The
    /// structural op may author nothing yet the source still counts as present.
    relocated: bool,
}

impl MappedEdit {
    /// The error for a source the structural op could not author and that no
    /// synthesized relocate realizes: a composed source thus reaches the stage
    /// only from a layer stack the target cannot author into
    /// ([`RequiresRelocate`](NamespaceEditError::RequiresRelocate)); an uncomposed
    /// one is simply missing ([`SourceNotFound`](NamespaceEditError::SourceNotFound)).
    fn unreachable_source(&self) -> NamespaceEditError {
        if self.composed {
            NamespaceEditError::RequiresRelocate(self.stage_src.clone())
        } else {
            NamespaceEditError::SourceNotFound(self.stage_src.clone())
        }
    }
}

/// Answers composed-namespace questions the staged layer overlays cannot.
///
/// A referenced or payload prim has no local spec, and relocates take effect
/// only on recomposition — which does not happen between the edits of a batch —
/// so the overlays alone cannot tell whether a source composes or a destination
/// is occupied after the earlier edits. Each query replays the edit prefix
/// against the pre-batch `stage`, mapping a path back to its pre-batch location
/// and confirming the content still lands there.
struct NamespaceProjection<'a> {
    stage: &'a Stage,
}

impl<'a> NamespaceProjection<'a> {
    fn new(stage: &'a Stage) -> Self {
        Self { stage }
    }

    /// The cross-arc facts for a move or delete of `path` after the `earlier`
    /// edits, read from one composed-index build.
    ///
    /// `realized` is whether the edit must be realized by a relocate: its opinion
    /// arrives across an arc rooted away from `path`, so it has no local spec of
    /// its own to move. `masks` is whether `path` is a relocate target that also
    /// masks its own direct ancestral content — content composed directly at
    /// `path` (through a plain arc) that a relocate happens to shadow. Moving or
    /// deleting such a path would reveal the masked content, leaving `path` still
    /// composed, so the edit cannot be expressed as a single relocate and the
    /// batch is rejected. In the composed index the relocated-in content sits
    /// under a `Relocate` arc while the masked content reaches `path` through a
    /// plain arc; both kinds present means a masking relocate target. Property
    /// paths are never realized by a relocate.
    fn cross_arc_facts(&self, path: &sdf::Path, earlier: &[NamespaceEdit]) -> Result<(bool, bool), NamespaceEditError> {
        if path.is_property_path() {
            return Ok((false, false));
        }
        let Some(origin) = projected_origin(path, earlier) else {
            return Ok((false, false));
        };
        let index = self.stage.prim(origin.clone()).prim_index().graph()?;
        let facts = classify_source_nodes(&index, &origin, None);
        Ok((facts.realized, facts.masks))
    }

    /// Whether a composed object (prim or property) occupies `path` after the
    /// `earlier` edits and so blocks a move onto it. A destination an earlier
    /// edit vacated round-trips to a different path and is free. Catches
    /// composed-only occupants the staged per-layer check cannot see, including a
    /// property arriving across a reference.
    fn occupied(&self, path: &sdf::Path, earlier: &[NamespaceEdit]) -> Result<bool, NamespaceEditError> {
        let Some(origin) = projected_origin(path, earlier) else {
            return Ok(false);
        };
        Ok(self.stage.has_spec(&origin)?)
    }

    /// Classify the source at `path`, after the `earlier` edits, against the
    /// edit-target node N — the node a mapped `target` writes into. N is the node
    /// whose path is the source mapped into the target's namespace, found among
    /// the nodes on the target's own layer stack `stack`. The facts decide how a
    /// mapped edit can be authored: a contributor at or below N is reachable
    /// through the target's stack (a direct spec move for N's own content, a
    /// relocate for content arriving across an arc below N), while a contributor
    /// outside N's subtree cannot be expressed through that stack.
    ///
    /// Keying N on the mapped path, not merely the stack, separates N from a
    /// same-stack sibling: a variant target's node sits on the root stack
    /// alongside a direct root opinion at the same composed path, and only the
    /// mapped path (`/Prim{set=sel}child` vs `/Prim/child`) tells them apart — so
    /// the direct opinion is correctly flagged outside the variant N's reach.
    ///
    /// A spec node below N counts as cross-arc content
    /// ([`below_target`](TargetFacts::below_target)) only when it sits in a
    /// different layer stack than N: a local class or variant arc within N's own
    /// stack moves with N's specs and needs no relocate.
    fn target_facts(
        &self,
        path: &sdf::Path,
        earlier: &[NamespaceEdit],
        stack: pcp::LayerStackId,
        target: &EditTarget,
    ) -> Result<TargetFacts, NamespaceEditError> {
        let Some(origin) = projected_origin(path, earlier) else {
            return Ok(TargetFacts::default());
        };
        let prim = origin.prim_path();
        let index = self.stage.prim(prim.clone()).prim_index().graph()?;
        let target_spec = target.map_to_spec_path(&prim);
        let target_node = target_spec.as_ref().and_then(|spec| {
            index
                .nodes_with_ids()
                .find(|(_, node)| node.layer_stack_id() == stack && node.path() == spec)
                .map(|(id, _)| id)
        });
        let Some(target_node) = target_node else {
            // The target does not reach this prim; the source composes (if at
            // all) only through stacks the target cannot author, an outside
            // contributor the direct edit path resolves into a missing-source or
            // requires-relocate error.
            return Ok(TargetFacts {
                outside: index.nodes_with_ids().any(|(_, node)| node.has_specs()),
                below_target: false,
                masks: false,
            });
        };
        let facts = classify_source_nodes(&index, &prim, Some(target_node));
        Ok(TargetFacts {
            below_target: facts.below_target,
            outside: facts.outside,
            // A property cannot itself be a relocate target, so it never masks
            // (matching `cross_arc_facts`'s property short-circuit).
            masks: !path.is_property_path() && facts.masks,
        })
    }
}

/// How a mapped edit's source composes relative to the edit-target node N (see
/// [`NamespaceProjection::target_facts`]). The default — no contributor below or
/// outside N — is a source reached directly through the target's own stack.
#[derive(Default)]
struct TargetFacts {
    /// A spec-bearing node in N's subtree is brought in by an arc rooted above
    /// the prim (due to an ancestor): content nested below the target with no
    /// spec at the mapped path to move, realized by a relocate synthesized into
    /// the target's stack.
    below_target: bool,
    /// A spec-bearing node sits outside N's subtree — a stronger override in an
    /// ancestor stack, or a sibling arc — so the source composes from a layer
    /// stack the target does not own and cannot be expressed through it.
    outside: bool,
    /// The source is a relocate target that also masks plain ancestral content
    /// reached through an arc. Moving or deleting it would retarget or drop the
    /// relocate and reveal the masked content at the old path, leaving the prim
    /// composed, so no single relocate can express the edit (mirrors the
    /// local-stack `masks` rejection in `cross_arc_facts`).
    masks: bool,
}

/// The non-empty `layerRelocates` of each layer in `layer_ids`, keyed by layer:
/// the per-layer baseline a [`RelocateStackPlan`] seeds from and validation
/// compares each layer's evolved list against.
fn seed_relocates(layers: &pcp::LayerGraph, layer_ids: &[pcp::LayerId]) -> HashMap<pcp::LayerId, sdf::RelocateList> {
    let mut seeds: HashMap<pcp::LayerId, sdf::RelocateList> = HashMap::new();
    for id in layer_ids {
        if let Some(node) = layers.get(*id) {
            let pairs = node.layer.relocates();
            if !pairs.is_empty() {
                seeds.insert(*id, pairs);
            }
        }
    }
    seeds
}

/// The composed-namespace classification of a source prim's spec-bearing nodes,
/// shared by the local-stack and mapped planners (see
/// [`classify_source_nodes`]). Each planner reads the subset it needs:
/// `cross_arc_facts` uses `realized` and `masks`, `target_facts` uses
/// `below_target`, `outside`, and `masks`.
struct SourceNodeFacts {
    /// A non-root node's opinion arrives across an arc rooted away from the prim,
    /// so the edit has no local spec to move and must be realized by a relocate
    /// (the local-stack cross-arc signal).
    realized: bool,
    /// The prim is a relocate target that also masks plain ancestral content: a
    /// node reached via a relocate coexists with one introduced away by a
    /// non-relocate arc, so moving or deleting it would reveal the masked content.
    masks: bool,
    /// A spec node in N's subtree is brought in by an arc rooted above the prim
    /// (due to an ancestor), so it has no spec at the mapped path to move
    /// directly: cross-arc content the mapped target realizes with a synthesized
    /// relocate. Covers content from another layer stack and content from an
    /// internal reference within N's own stack alike. Always `false` when no
    /// target node is given.
    below_target: bool,
    /// A spec node sits outside N's subtree — a contributor the mapped target's
    /// own layer stack cannot reach. Always `false` when no target node is given.
    outside: bool,
}

/// Walk the spec-bearing nodes of `origin`'s composition index once and classify
/// them. `origin` is the composed prim path the introduced-away test keys on.
/// When `target_node` is given (the mapped edit-target node N and its layer
/// stack), nodes are also classified relative to N's subtree
/// ([`below_target`](SourceNodeFacts::below_target) /
/// [`outside`](SourceNodeFacts::outside)); without it those stay `false` and only
/// the local-stack signals are computed. The single source of the cross-arc and
/// masking classification both planners enforce.
// TODO(perf): each spec node walks parent links to the root twice
// (`node_under_relocate` and `node_in_subtree`), making this O(nodes × depth)
// per call; a single pass precomputing each node's depth and relocate-ancestor
// flag would make it linear.
fn classify_source_nodes(
    index: &pcp::PrimIndex,
    origin: &sdf::Path,
    target_node: Option<pcp::NodeId>,
) -> SourceNodeFacts {
    let mut realized = false;
    let mut via_relocate = false;
    let mut direct_ancestral = false;
    let mut below_target = false;
    let mut outside = false;
    for (id, node) in index.nodes_with_ids() {
        if !node.has_specs() {
            continue;
        }
        // The introduction path of a node inside a variant carries `{set=sel}`,
        // which map functions never do; strip before mapping (C++
        // `PcpTranslatePathFromNodeToRoot`), so the comparison against the
        // selection-free `origin` stays like-for-like.
        let mut intro_path = index.graph().path_at_introduction(id);
        if intro_path.contains_prim_variant_selection() {
            intro_path = intro_path.strip_all_variant_selections();
        }
        let introduced_away = node
            .map_to_root()
            .map_source_to_target(&intro_path)
            .is_some_and(|intro| &intro != origin);
        if node.arc() != pcp::ArcType::Root && introduced_away {
            realized = true;
        }
        if node_under_relocate(index, id) {
            via_relocate = true;
        } else if introduced_away {
            direct_ancestral = true;
        }
        match target_node {
            Some(target) if id != target => {
                if node_in_subtree(index, id, target) {
                    // Content brought into N's subtree by an arc rooted above the
                    // prim (due to an ancestor) has no spec at the mapped path to
                    // move directly, so it needs a relocate — whether it arrives
                    // from another layer stack or from an internal reference
                    // within N's own stack. A direct arc on the prim itself (an
                    // inherit, a same-prim reference) moves with the spec.
                    below_target |= index.graph().is_due_to_ancestor(id);
                } else {
                    outside = true;
                }
            }
            _ => {}
        }
    }
    SourceNodeFacts {
        realized,
        masks: via_relocate && direct_ancestral,
        below_target,
        outside,
    }
}

/// Whether `node` is `ancestor` or one of its descendants in the composition
/// tree, walking parent links from `node` up to the root.
fn node_in_subtree(index: &pcp::PrimIndex, node: pcp::NodeId, ancestor: pcp::NodeId) -> bool {
    let mut current = Some(node);
    while let Some(id) = current {
        if id == ancestor {
            return true;
        }
        current = index.parent(id);
    }
    false
}

/// Whether `node` (or any ancestor in the composed index) was introduced by a
/// `Relocate` arc, so its content reaches the prim through a relocate rather
/// than directly.
fn node_under_relocate(index: &pcp::PrimIndex, node: pcp::NodeId) -> bool {
    let mut current = Some(node);
    while let Some(id) = current {
        if index.node(id).arc() == pcp::ArcType::Relocate {
            return true;
        }
        current = index.parent(id);
    }
    false
}

/// One relocate pair as the batch evolves it, tagged with the layer that owns
/// it. `source` is the path Pcp sees as the relocate source — in the current,
/// possibly already-relocated, parent namespace — and `target` the live composed
/// destination, or empty for a deletion.
struct RelocatedEntry {
    source: sdf::Path,
    target: sdf::Path,
    layer: pcp::LayerId,
    /// The pair as it was seeded from the layer, or `None` when the batch
    /// synthesized this occurrence. An occurrence is fresh — created or changed
    /// by the batch — when this is `None` or differs from the current pair, even
    /// if the current pair's value happens to coincide with another layer's
    /// pre-existing one. Validation blames fresh occurrences by identity, not by
    /// value.
    original: Option<sdf::Relocate>,
    /// Whether Pcp dropped this seed when classifying the pre-batch relocate set,
    /// for any reason — structurally invalid, duplicate source, or conflict. An
    /// immutable before-snapshot, used only to reject a batch that would make a
    /// previously-dropped pair live again; it is never consulted to decide how a
    /// pair evolves (that uses the live classification of the current pairs).
    ///
    /// Frozen at seed time, not recomputed at validation: a pair's seed-time
    /// status depends on the whole initial set, including pairs the batch later
    /// deletes (duplicate-source and conflict groups drop together), so it cannot
    /// be reconstructed from the surviving entries alone. This bool is the minimal
    /// record of the "before" half of the resurrection check; the live analysis
    /// over the current pairs supplies the "after" half.
    dropped_at_seed: bool,
}

impl RelocatedEntry {
    /// Whether the batch created or changed this occurrence, so validation may
    /// blame it for being invalid or conflicting.
    fn is_fresh(&self) -> bool {
        self.original
            .as_ref()
            .is_none_or(|(s, t)| s != &self.source || t != &self.target)
    }

    /// Whether the batch collapsed a created or non-identity seed pair to an
    /// identity relocate omitted from authored metadata.
    fn drops_as_identity(&self) -> bool {
        self.source == self.target
            && match &self.original {
                None => true,
                Some((source, target)) => source != target,
            }
    }
}

/// The evolving `layerRelocates` of one layer stack — the local root stack for
/// an identity target, or a mapped target's own layer stack — in that stack's
/// namespace.
///
/// Pcp validates relocates over the combined layer stack, not the authoring
/// layer alone, so the plan owns every stack layer's pairs (tagged by owning
/// layer) and evolves them through each edit: a move reprojects endpoints, a
/// delete empties a target or drops a source, and a cross-arc move or delete
/// synthesizes a new pair — always on `edit_target`, the layer the editor
/// authors new pairs into. Authoring writes each layer's evolved list back to
/// that layer; validation runs over the combined set. Tracking every layer (not
/// just the authoring layer) lets a later edit recognize a relocate target an
/// earlier edit moved, and lets a delete reject an orphaned cross-layer relocate.
struct RelocateStackPlan {
    entries: Vec<RelocatedEntry>,
    edit_target: pcp::LayerId,
    layer_rank: HashMap<pcp::LayerId, usize>,
}

impl RelocateStackPlan {
    /// Seed the plan with each local-stack layer's existing relocates, tagged by
    /// owning layer. New pairs synthesized by the batch land on `edit_target`.
    fn new(
        layer_ids: &[pcp::LayerId],
        seeds: &HashMap<pcp::LayerId, sdf::RelocateList>,
        edit_target: pcp::LayerId,
    ) -> Self {
        let mut seen_layers: HashSet<pcp::LayerId> = HashSet::new();
        let ordered_layers: Vec<pcp::LayerId> = layer_ids
            .iter()
            .copied()
            .filter(|layer| seen_layers.insert(*layer))
            .collect();
        let layer_rank: HashMap<pcp::LayerId, usize> = ordered_layers
            .iter()
            .enumerate()
            .map(|(rank, layer)| (*layer, rank))
            .collect();
        let seeded: Vec<(pcp::LayerId, sdf::Relocate)> = ordered_layers
            .iter()
            .filter_map(|layer| seeds.get(layer).map(|pairs| (*layer, pairs)))
            .flat_map(|(layer, pairs)| pairs.iter().map(move |pair| (layer, (pair.0.clone(), pair.1.clone()))))
            .collect();
        let pairs: sdf::RelocateList = seeded.iter().map(|(_, pair)| pair.clone()).collect();
        let status = pcp::analyze_relocate_occurrences(&pairs);
        let entries = seeded
            .into_iter()
            .zip(status)
            .map(|((layer, pair), status)| RelocatedEntry {
                source: pair.0.clone(),
                target: pair.1.clone(),
                layer,
                // Pcp did not apply this seed over the initial stack: the
                // before-snapshot for the resurrection check.
                dropped_at_seed: !status.is_active(),
                original: Some(pair),
            })
            .collect();
        Self {
            entries,
            edit_target,
            layer_rank,
        }
    }

    /// Record a move `src -> dst`. Always follows the moved subtree through every
    /// entry, so a relocate on any layer whose endpoint sits under `src` tracks
    /// the edit. When `cross_arc`, the move is realized by a relocate, so a fresh
    /// pair is appended on the edit target unless `src` is already a live target
    /// (then [`reproject`](Self::reproject) just retargets it, chain-free).
    // TODO(perf): this recomputes the active classification several times for one
    // edit — `continuation_source` and `prohibiting_source` each call
    // `active_relocates` -> `active_flags`, and `reproject` calls `active_flags`
    // again — all O(n^2) over an entry set that does not change until the
    // reproject. Compute `active_flags()` once here and thread the mask into
    // those helpers.
    fn record_move(&mut self, src: &sdf::Path, dst: &sdf::Path, cross_arc: bool) -> Result<(), NamespaceEditError> {
        let continues_source = self.continuation_source(src);
        if let Some(source) = self.prohibiting_source(dst) {
            if continues_source.as_ref() != Some(&source) || dst != &source {
                return Err(NamespaceEditError::UnrepresentableRelocateBatch(source));
            }
        }
        let continues = continues_source.is_some();
        self.reproject(src, dst);
        if cross_arc && !continues {
            self.insert_edit_target_entry(RelocatedEntry {
                source: src.clone(),
                target: dst.clone(),
                layer: self.edit_target,
                original: None,
                dropped_at_seed: false,
            });
        }
        Ok(())
    }

    /// Record a delete of `path`. Evolves every entry against the live
    /// classification: an active relocate wholly inside the deleted subtree
    /// (sourced under `path`) is removed with it, and an active relocate whose
    /// target is under `path` collapses to a deletion. Inert (dropped) pairs are
    /// left exactly as authored — they place no content, so deleting a directly
    /// composed prim must not rewrite them. When `cross_arc`, a deletion pair is
    /// appended on the edit target unless an active pair already targets `path`.
    /// Rejected as
    /// [`UnrepresentableRelocateBatch`](NamespaceEditError::UnrepresentableRelocateBatch)
    /// when an active relocate was sourced under `path` but targets outside it: a
    /// descendant relocated out of the deleted subtree would lose its source, and
    /// no valid relocate set keeps the moved child while deleting its parent.
    fn record_delete(&mut self, path: &sdf::Path, cross_arc: bool) -> Result<(), NamespaceEditError> {
        let active = self.active_flags();
        let orphans_child = self.entries.iter().zip(&active).any(|(e, &a)| {
            a && &e.source != path && e.source.has_prefix(path) && !e.target.is_empty() && !e.target.has_prefix(path)
        });
        if orphans_child {
            return Err(NamespaceEditError::UnrepresentableRelocateBatch(path.clone()));
        }
        let mut continues = false;
        let kept: Vec<RelocatedEntry> = std::mem::take(&mut self.entries)
            .into_iter()
            .zip(active)
            .filter_map(|(mut e, a)| {
                if a && &e.source != path && e.source.has_prefix(path) {
                    return None;
                }
                if a && &e.target == path {
                    continues = true;
                }
                if a && !e.target.is_empty() && e.target.has_prefix(path) {
                    e.target = sdf::Path::default();
                }
                Some(e)
            })
            .collect();
        self.entries = kept;
        if cross_arc && !continues {
            self.insert_edit_target_entry(RelocatedEntry {
                source: path.clone(),
                target: sdf::Path::default(),
                layer: self.edit_target,
                original: None,
                dropped_at_seed: false,
            });
        }
        Ok(())
    }

    /// Insert a synthesized edit-target pair at the edit target's layer-stack
    /// strength, after any earlier pairs from the same layer.
    fn insert_edit_target_entry(&mut self, entry: RelocatedEntry) {
        debug_assert_eq!(entry.layer, self.edit_target);
        let edit_rank = self.layer_rank[&self.edit_target];
        let insert_at = self
            .entries
            .iter()
            .position(|e| self.layer_rank[&e.layer] > edit_rank)
            .unwrap_or(self.entries.len());
        self.entries.insert(insert_at, entry);
    }

    /// The live Pcp classification of the current entries, index-aligned: whether
    /// each occurrence is active over the current `(source, target)` set. Derived
    /// on demand from the current values — not cached — so it stays correct as the
    /// batch evolves the entries.
    // TODO(perf): re-analyzes the whole set (O(n^2)) on each call; n is small and
    // this is a cold authoring path, but a cached-and-invalidated mask would help.
    fn active_flags(&self) -> Vec<bool> {
        let pairs: sdf::RelocateList = self
            .entries
            .iter()
            .map(|e| (e.source.clone(), e.target.clone()))
            .collect();
        pcp::analyze_relocate_occurrences(&pairs)
            .into_iter()
            .map(|status| status.is_active())
            .collect()
    }

    fn active_relocates(&self) -> sdf::RelocateList {
        self.entries
            .iter()
            .zip(self.active_flags())
            .filter(|(_, active)| *active)
            .map(|(e, _)| (e.source.clone(), e.target.clone()))
            .collect()
    }

    fn continuation_source(&self, path: &sdf::Path) -> Option<sdf::Path> {
        self.active_relocates()
            .into_iter()
            .find_map(|(source, target)| (!target.is_empty() && target == *path).then_some(source))
    }

    /// The active relocate source that prohibits authoring at `path`, if any.
    fn prohibiting_source(&self, path: &sdf::Path) -> Option<sdf::Path> {
        self.active_relocates()
            .into_iter()
            .filter_map(|(source, _)| path.has_prefix(&source).then_some(source))
            .max_by_key(|source| source.element_count())
    }

    /// Follow a subtree moved from `old` to `new` through every entry. A target
    /// strictly under `old` is inside a renamed subtree and follows regardless of
    /// whether the pair is active. A target exactly equal to `old` follows only
    /// for the active relocate that actually places content there — an inert
    /// (dropped) pair that merely names `old` does not place the moved prim, so
    /// re-rooting it would manufacture a spurious conflict. A source strictly
    /// under `old` (a child already relocated out) follows; the pair whose source
    /// is exactly `old` keeps it (the pre-relocation location).
    fn reproject(&mut self, old: &sdf::Path, new: &sdf::Path) {
        let active = self.active_flags();
        for (e, is_active) in self.entries.iter_mut().zip(active) {
            if !e.target.is_empty() {
                if e.target == *old {
                    if is_active {
                        e.target = new.clone();
                    }
                } else {
                    e.target = rebased(&e.target, old, new);
                }
            }
            if &e.source != old {
                e.source = rebased(&e.source, old, new);
            }
        }
    }

    /// Every current pair across the stack, tagged with its freshness and
    /// dropped-seed provenance and with no-op `source == target` pairs dropped,
    /// for the combined Pcp-equivalent validation.
    fn combined(&self) -> Vec<pcp::BatchRelocate> {
        self.entries
            .iter()
            .filter(|e| e.source != e.target)
            .map(|e| pcp::BatchRelocate {
                pair: (e.source.clone(), e.target.clone()),
                fresh: e.is_fresh(),
                dropped_seed: e.dropped_at_seed,
            })
            .collect()
    }

    /// Validate the relocates Pcp will see: the combined set across the whole
    /// local stack. Pcp validates the layer stack as a whole, not the edit target
    /// alone, and a cross-layer conflict only appears in the combined list. Fresh
    /// occurrences are blamed for being dropped; seed occurrences that Pcp dropped
    /// before the batch are rejected if the edit would make them active.
    fn validate(&self) -> Result<(), NamespaceEditError> {
        let combined = self.combined();
        let pairs: sdf::RelocateList = combined.iter().map(|r| r.pair.clone()).collect();
        let status = pcp::analyze_relocate_occurrences(&pairs);
        if let Some(path) = pcp::first_unrepresentable_relocate(&combined, &status) {
            return Err(NamespaceEditError::UnrepresentableRelocateBatch(path));
        }
        if let Some((r, _)) = combined
            .iter()
            .zip(&status)
            .find(|(r, s)| r.dropped_seed && s.is_active())
        {
            return Err(NamespaceEditError::UnrepresentableRelocateBatch(r.pair.0.clone()));
        }
        Ok(())
    }

    /// The final relocate list per owning layer. A no-op `source == target` the
    /// batch produced (a pair folded to identity) is dropped, but one the batch
    /// left untouched is preserved as authored — an unrelated edit must not
    /// rewrite a layer's existing metadata away. A layer that had relocates but
    /// is absent from the result has had all its pairs removed and must be
    /// cleared by the caller.
    fn into_by_layer(self) -> HashMap<pcp::LayerId, sdf::RelocateList> {
        let mut by_layer: HashMap<pcp::LayerId, sdf::RelocateList> = HashMap::new();
        for e in self.entries {
            if e.drops_as_identity() {
                continue;
            }
            by_layer.entry(e.layer).or_default().push((e.source, e.target));
        }
        by_layer
    }

    /// Validate the combined stack and resolve each layer's final
    /// `layerRelocates` against the `seeds` baseline. The shared back half of
    /// [`execute`](NamespaceEditor::execute) and
    /// [`layers_to_edit`](NamespaceEditor::layers_to_edit): both validate, fold
    /// the plan to per-layer lists, and compare against the seeds to touch a
    /// layer only when its relocates change.
    fn resolve(self, seeds: HashMap<pcp::LayerId, sdf::RelocateList>) -> Result<ResolvedRelocates, NamespaceEditError> {
        self.validate()?;
        Ok(ResolvedRelocates {
            seeds,
            final_by_layer: self.into_by_layer(),
        })
    }
}

/// Per-layer relocate authoring resolved from a validated [`RelocateStackPlan`]:
/// the final `layerRelocates` each layer should hold and the seed baseline to
/// compare against.
struct ResolvedRelocates {
    seeds: HashMap<pcp::LayerId, sdf::RelocateList>,
    final_by_layer: HashMap<pcp::LayerId, sdf::RelocateList>,
}

impl ResolvedRelocates {
    /// The relocate list `id` should hold after the batch when it differs from
    /// the layer's seed baseline, or `None` when unchanged. Authoring on a change
    /// covers clearing pairs the batch folded away, while skipping an unchanged
    /// layer leaves a pre-existing (possibly invalid) pair exactly as authored.
    fn change_for(&self, id: pcp::LayerId) -> Option<sdf::RelocateList> {
        let next = self.final_by_layer.get(&id).cloned().unwrap_or_default();
        let prev = self.seeds.get(&id).cloned().unwrap_or_default();
        (next != prev).then_some(next)
    }
}

/// The cross-arc facts the [`NamespaceProjection`] settles for one edit, read
/// during staging: whether the source resolves to composed content realized by
/// a relocate (so it has no local spec yet counts as present), and whether the
/// destination is occupied by such content. Both account for the earlier edits.
struct EditPlan {
    present: bool,
    occupied: bool,
}

/// Validate `edit` against the staged state and its [`EditPlan`], then stage it
/// into every layer. The staged overlays already reflect the earlier edits, so
/// local-spec checks read precise data: a destination collision is a local spec
/// at `dst` (or a composed cross-arc occupant from `plan`), and a missing source
/// is an edit that moves or removes nothing in any layer and is not realized by
/// a relocate (`plan.present`).
fn apply_edit(
    layers: &mut [&mut sdf::LayerEdit<'_>],
    edit: &NamespaceEdit,
    plan: &EditPlan,
) -> Result<(), NamespaceEditError> {
    validate_edit_shape(edit)?;
    match edit {
        NamespaceEdit::Move { src, dst, .. } => {
            // A composed cross-arc occupant (`plan.occupied`) or a local spec
            // staged by an earlier edit in this batch blocks the move.
            if plan.occupied || layers.iter().any(|layer| layer.data().has_spec(dst)) {
                return Err(NamespaceEditError::DestinationExists(dst.clone()));
            }
            stage_across_layers(layers, src, plan.present, |layer| move_spec(layer, src, dst))?;
        }
        NamespaceEdit::Delete { path, .. } => {
            stage_across_layers(layers, path, plan.present, |layer| layer.remove_spec(path))?;
        }
    }
    Ok(())
}

fn validate_edit_shape(edit: &NamespaceEdit) -> Result<(), NamespaceEditError> {
    match edit {
        NamespaceEdit::Move { src, dst, kind } => {
            check_editable(src, *kind, NamespaceEditError::InvalidSource)?;
            check_editable(dst, *kind, NamespaceEditError::InvalidDestination)?;
            if dst.has_prefix(src) {
                return Err(NamespaceEditError::DestinationUnderSource {
                    src: src.clone(),
                    dst: dst.clone(),
                });
            }
        }
        NamespaceEdit::Delete { path, kind } => {
            check_editable(path, *kind, NamespaceEditError::InvalidSource)?;
        }
    }
    Ok(())
}

/// Stage `op` into every layer, tracking whether any layer authored a change.
/// Errors with [`SourceNotFound`](NamespaceEditError::SourceNotFound) when no
/// layer did and the source is not realized through a relocate (`present`).
fn stage_across_layers(
    layers: &mut [&mut sdf::LayerEdit<'_>],
    path: &sdf::Path,
    present: bool,
    mut op: impl FnMut(&mut sdf::LayerEdit<'_>) -> Result<bool, sdf::AuthoringError>,
) -> Result<(), NamespaceEditError> {
    let mut authored = false;
    for layer in layers.iter_mut() {
        if op(layer).map_err(StageAuthoringError::Layer)? {
            authored = true;
        }
    }
    if !authored && !present {
        return Err(NamespaceEditError::SourceNotFound(path.clone()));
    }
    Ok(())
}

/// Author one translated batch edit across the mapped target's layer stack: a
/// move copies the source spec subtree to the destination and removes the
/// source, a delete removes the source spec, in whichever stack layers hold it.
/// A destination is blocked by a composed occupant settled in the plan
/// ([`MappedEdit::occupied`]) or a spec an earlier batch edit staged into a
/// layer overlay. A source the structural op could not author anywhere is
/// reported through [`unreachable_source`](MappedEdit::unreachable_source),
/// unless the edit is realized by a synthesized relocate
/// ([`MappedEdit::relocated`]), which authors the destination on its own.
fn apply_mapped_edit(layers: &mut [sdf::LayerEdit<'_>], edit: &MappedEdit) -> Result<(), NamespaceEditError> {
    let mut authored = false;
    match &edit.dst {
        Some(dst) => {
            // A composed cross-arc occupant (`edit.occupied`) or a spec staged by
            // an earlier edit in this batch blocks the move.
            if edit.occupied || layers.iter().any(|layer| layer.data().has_spec(dst)) {
                return Err(NamespaceEditError::DestinationExists(dst.clone()));
            }
            for layer in layers.iter_mut() {
                authored |= move_spec(layer, &edit.src, dst).map_err(StageAuthoringError::Layer)?;
            }
        }
        None => {
            for layer in layers.iter_mut() {
                authored |= layer.remove_spec(&edit.src).map_err(StageAuthoringError::Layer)?;
            }
        }
    }
    if !authored && !edit.relocated {
        return Err(edit.unreachable_source());
    }
    Ok(())
}

/// Move the spec subtree at `src` to `dst` within one layer: copy it then remove
/// the source, returning whether a spec was present to move. The structural move
/// shared by the local-stack and mapped authoring paths.
fn move_spec(layer: &mut sdf::LayerEdit<'_>, src: &sdf::Path, dst: &sdf::Path) -> Result<bool, sdf::AuthoringError> {
    let moved = sdf::copy_spec_within(layer.data_mut(), src, dst)?;
    if moved {
        layer.remove_spec(src)?;
    }
    Ok(moved)
}

/// Rewrite every embedded namespace path in `layer` for an identity local-stack
/// edit: a path under a move source re-roots onto the destination, one under a
/// deletion source drops out of its list op.
fn fixup_embedded_paths(layer: &mut sdf::LayerEdit<'_>, edits: &[NamespaceEdit]) -> Result<(), NamespaceEditError> {
    rewrite_embedded_paths(layer, |p| Ok(project_path(p, edits)))
}

/// Rewrite every embedded namespace path in `layer` for a mapped edit, through
/// the lift-then-map chain ([`remap_embedded_path`]): lift the layer-namespace
/// path to stage namespace, follow the batch's moves, then map it back into the
/// target layer's namespace.
fn fixup_mapped_paths(
    layer: &mut sdf::LayerEdit<'_>,
    target: &EditTarget,
    edits: &[NamespaceEdit],
) -> Result<(), NamespaceEditError> {
    rewrite_embedded_paths(layer, |p| remap_embedded_path(p, target, edits))
}

/// The embedded-path rewrites `rewrite` would make to `data`: for each spec
/// field whose value changes — a relationship/connection/internal-reference
/// target into a moved or deleted object — the spec path, field name, and
/// rewritten value, preserving list-op structure. `rewrite` maps one path to
/// its replacement, `Ok(None)` to drop it from its list op, or an error to fail
/// the batch.
///
/// `layerRelocates` is skipped: a layer-level relocate's source and target carry
/// different meaning, and a deleted target becomes the empty sentinel rather than
/// dropping out, so it is owned by [`RelocateStackPlan`] for a local-stack edit
/// and not modeled for a mapped target. Spec-level `relocates` are ordinary
/// embedded paths and are rewritten here.
///
/// The shared scan behind [`rewrite_embedded_paths`], which applies the
/// rewrites, and [`layer_fixup_touches`], which only asks whether any exist.
//
// TODO(perf): scans every spec and field in the layer and clones each
// path-bearing value to compare. A path-keyed index of specs carrying
// target/connection/reference opinions would bound this to the opinions that
// can actually reference a moved object.
fn embedded_path_rewrites(
    data: &dyn sdf::AbstractData,
    rewrite: impl Fn(&sdf::Path) -> Result<Option<sdf::Path>, NamespaceEditError>,
) -> Result<Vec<(sdf::Path, String, sdf::Value)>, NamespaceEditError> {
    // `filter_map_paths` takes a `Fn` that cannot itself fail, so a rejected
    // path is parked here and surfaced after the rewrite.
    let failed: std::cell::Cell<Option<NamespaceEditError>> = std::cell::Cell::new(None);
    let mut changes = Vec::new();
    for path in data.spec_paths() {
        let fields = data.list_fields(&path).unwrap_or_default();
        for field in &fields {
            if field == sdf::FieldKey::LayerRelocates.as_str() {
                continue;
            }
            let Some(value) = data
                .try_field(&path, field)
                .map_err(|e| StageAuthoringError::Layer(e.into()))?
            else {
                continue;
            };
            if !value.has_embedded_paths() {
                continue;
            }
            let value = value.into_owned();
            let rewritten = value.filter_map_paths(|p| match rewrite(p) {
                Ok(mapped) => mapped,
                Err(error) => {
                    failed.set(Some(error));
                    Some(p.clone())
                }
            });
            if let Some(error) = failed.take() {
                return Err(error);
            }
            if rewritten != value {
                changes.push((path.clone(), field.clone(), rewritten));
            }
        }
    }
    Ok(changes)
}

/// Rewrite every embedded namespace path in `layer` through `rewrite` (see
/// [`embedded_path_rewrites`]), writing each changed field back.
fn rewrite_embedded_paths(
    layer: &mut sdf::LayerEdit<'_>,
    rewrite: impl Fn(&sdf::Path) -> Result<Option<sdf::Path>, NamespaceEditError>,
) -> Result<(), NamespaceEditError> {
    for (path, field, value) in embedded_path_rewrites(layer.data(), rewrite)? {
        layer.data_mut().set_field(&path, &field, value);
    }
    Ok(())
}

/// Whether [`rewrite_embedded_paths`] would change any embedded path in `data`:
/// a relationship/connection/internal-reference target into a moved or deleted
/// object. The read-only preflight twin of [`rewrite_embedded_paths`], so
/// [`layers_to_edit`](NamespaceEditor::layers_to_edit) reports a layer the fixup
/// rewrites even when it holds no source spec and no relocate of its own.
fn layer_fixup_touches(
    data: &dyn sdf::AbstractData,
    rewrite: impl Fn(&sdf::Path) -> Result<Option<sdf::Path>, NamespaceEditError>,
) -> Result<bool, NamespaceEditError> {
    Ok(!embedded_path_rewrites(data, rewrite)?.is_empty())
}

/// Rewrite one embedded namespace path for a mapped edit: lift it to composed
/// stage namespace through the target's mapping, follow the batch's moves with
/// [`project_path`], then map it back into the target layer's namespace.
/// `Ok(None)` drops a path whose target a deletion removed; an `Err` rejects a
/// projected target the arc cannot express
/// ([`StageAuthoringError::OutsideEditTarget`]). A path the mapping cannot lift
/// names nothing in the arc's stage projection, so no stage-namespace move can
/// affect it and it is left as authored.
fn remap_embedded_path(
    path: &sdf::Path,
    target: &EditTarget,
    edits: &[NamespaceEdit],
) -> Result<Option<sdf::Path>, NamespaceEditError> {
    let Some(scene) = target.map_function().map_source_to_target(path) else {
        return Ok(Some(path.clone()));
    };
    match project_path(&scene, edits) {
        None => Ok(None),
        Some(projected) => target
            .map_to_spec_target_path(&projected)
            .map(Some)
            .ok_or_else(|| NamespaceEditError::Stage(StageAuthoringError::OutsideEditTarget { path: projected })),
    }
}

/// `path` with prefix `from` rewritten to `to`, or `path` unchanged when it does
/// not start with `from`.
fn rebased(path: &sdf::Path, from: &sdf::Path, to: &sdf::Path) -> sdf::Path {
    path.replace_prefix(from, to).unwrap_or_else(|| path.clone())
}

/// Apply the batch in order to one path, returning its post-batch path or
/// `None` if a deletion removed it.
fn project_path(path: &sdf::Path, edits: &[NamespaceEdit]) -> Option<sdf::Path> {
    let mut current = path.clone();
    for edit in edits {
        match edit {
            NamespaceEdit::Delete { path: removed, .. } => {
                if current.has_prefix(removed) {
                    return None;
                }
            }
            NamespaceEdit::Move { src, dst, .. } => {
                current = rebased(&current, src, dst);
            }
        }
    }
    Some(current)
}

/// Map `path` back through `earlier` moves, in reverse, to the namespace it
/// occupied before those edits ran. The inverse of [`project_path`] over the
/// move subsequence: each earlier move `src -> dst` is undone by rewriting the
/// `dst` prefix back to `src`, so a path that an earlier move landed under a
/// relocated subtree resolves to its pre-batch location (where its cross-arc
/// opinions can be looked up).
fn premove_path(path: &sdf::Path, earlier: &[NamespaceEdit]) -> sdf::Path {
    let mut original = path.clone();
    for edit in earlier.iter().rev() {
        if let NamespaceEdit::Move { src, dst, .. } = edit {
            original = rebased(&original, dst, src);
        }
    }
    original
}

/// The pre-batch origin a composed query at `path` should read, or `None` when
/// `path` is not where that origin lands after the `earlier` edits — an earlier
/// delete removed it, or it round-trips elsewhere — so the query has nothing to
/// read there. The shared guard the composed-namespace projections key on.
fn projected_origin(path: &sdf::Path, earlier: &[NamespaceEdit]) -> Option<sdf::Path> {
    let origin = premove_path(path, earlier);
    (project_path(&origin, earlier).as_ref() == Some(path)).then_some(origin)
}

/// Validate that `path` is an absolute, non-pseudo-root object path of the
/// edit's `kind`. A non-absolute path maps through `invalid` to the caller's
/// source or destination error variant; a path of the wrong kind (a prim path
/// for a property edit, or vice versa) is a [`KindMismatch`](NamespaceEditError::KindMismatch).
fn check_editable(
    path: &sdf::Path,
    kind: ObjectKind,
    invalid: fn(sdf::Path) -> NamespaceEditError,
) -> Result<(), NamespaceEditError> {
    if path.is_abs_root() {
        return Err(NamespaceEditError::PseudoRoot);
    }
    if !path.is_abs() {
        return Err(invalid(path.clone()));
    }
    if !kind.matches(path) {
        return Err(NamespaceEditError::KindMismatch);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use super::*;
    use crate::sdf::{self, path, FieldKey, LayerOffset, Specifier, Variability};
    use crate::usd::{EditTarget, EditTargetArc, Stage};

    /// Author into `layer` and commit, for building a test layer before it joins a
    /// stage.
    fn edit_layer(layer: &mut sdf::Layer, f: impl FnOnce(&mut sdf::LayerEdit<'_>)) {
        layer
            .edit(|e| {
                f(e);
                Ok(())
            })
            .expect("authored");
    }

    /// A stage with `/A` (Xform) → `/A/Child`, a relationship `/Other.rel`
    /// targeting `[/A, /Keep]`, and an attribute `/Other.con` connected to
    /// `/A.out`, all authored in one anonymous root layer.
    fn sample() -> Stage {
        let stage = Stage::builder().in_memory("root.usda").unwrap();
        stage.define_prim("/A").unwrap().set_type_name("Xform").unwrap();
        stage.define_prim("/A/Child").unwrap();
        stage.create_attribute("/A.out", "double").unwrap();
        stage.define_prim("/Keep").unwrap();
        stage.define_prim("/Other").unwrap();
        stage
            .create_relationship("/Other.rel")
            .unwrap()
            .set_targets([path("/A").unwrap(), path("/Keep").unwrap()])
            .unwrap();
        stage
            .create_attribute("/Other.con", "double")
            .unwrap()
            .set_connections([path("/A.out").unwrap()])
            .unwrap();
        stage
    }

    fn valid(stage: &Stage, p: &str) -> bool {
        stage.prim(path(p).unwrap()).is_valid().unwrap()
    }

    fn rel_targets(stage: &Stage, p: &str) -> Vec<String> {
        stage
            .relationship(path(p).unwrap())
            .targets()
            .unwrap()
            .iter()
            .map(|t| t.as_str().to_owned())
            .collect()
    }

    fn connections(stage: &Stage, p: &str) -> Vec<String> {
        stage
            .attribute(path(p).unwrap())
            .connections()
            .unwrap()
            .iter()
            .map(|t| t.as_str().to_owned())
            .collect()
    }

    #[test]
    fn rename_subtree_targets() {
        let stage = sample();
        NamespaceEditor::new(&stage)
            .rename_prim(&stage.prim(path("/A").unwrap()), "B")
            .unwrap()
            .apply()
            .unwrap();

        // The subtree moves, and every external opinion that named the prim — a
        // relationship target and an attribute connection — follows it.
        assert!(valid(&stage, "/B"));
        assert!(valid(&stage, "/B/Child"));
        assert!(!valid(&stage, "/A"));
        assert_eq!(rel_targets(&stage, "/Other.rel"), vec!["/B", "/Keep"]);
        assert_eq!(connections(&stage, "/Other.con"), vec!["/B.out"]);
    }

    #[test]
    fn reparent_under_parent() {
        let stage = sample();
        let mut editor = NamespaceEditor::new(&stage);
        editor
            .reparent_prim(&stage.prim(path("/A").unwrap()), &stage.prim(path("/Keep").unwrap()))
            .unwrap();
        editor.apply().unwrap();

        assert!(valid(&stage, "/Keep/A"));
        assert!(valid(&stage, "/Keep/A/Child"));
        assert!(!valid(&stage, "/A"));
    }

    #[test]
    fn delete_subtree_targets() {
        let stage = sample();
        let mut editor = NamespaceEditor::new(&stage);
        editor.delete_prim(path("/A").unwrap());
        editor.apply().unwrap();

        // The subtree is removed, and every external opinion that named the prim
        // is cleared: the relationship target drops, the connection empties.
        assert!(!valid(&stage, "/A"));
        assert!(!valid(&stage, "/A/Child"));
        assert_eq!(rel_targets(&stage, "/Other.rel"), vec!["/Keep"]);
        assert!(connections(&stage, "/Other.con").is_empty());
    }

    #[test]
    fn rename_fixes_internal_ref() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/A", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Other", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Other").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    prim_path: path("/A").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let stage = Stage::builder().make_stage(vec![root], 0, Vec::new());

        NamespaceEditor::new(&stage)
            .rename_prim(&stage.prim(path("/A").unwrap()), "B")
            .unwrap()
            .apply()
            .unwrap();

        let references = stage
            .root_layer()
            .data()
            .try_field(&path("/Other").unwrap(), FieldKey::References.as_str())
            .unwrap()
            .unwrap()
            .into_owned()
            .try_as_reference_list_op()
            .unwrap();
        assert_eq!(references.prepended_items[0].prim_path.as_str(), "/B");
    }

    #[test]
    fn rename_preserves_listop() {
        // A prepended (not explicit) target survives the fixup as prepended.
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/A", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Other", Specifier::Def, "").unwrap();
            sdf::RelationshipSpec::new(e.data_mut(), "/Other.rel", Variability::Varying, false).unwrap();
            e.data_mut().set_field(
                &path("/Other.rel").unwrap(),
                FieldKey::TargetPaths.as_str(),
                sdf::Value::PathListOp(sdf::PathListOp::prepended([path("/A").unwrap()])),
            );
        });
        let stage = Stage::builder().make_stage(vec![root], 0, Vec::new());

        NamespaceEditor::new(&stage)
            .rename_prim(&stage.prim(path("/A").unwrap()), "B")
            .unwrap()
            .apply()
            .unwrap();

        let op = stage
            .root_layer()
            .data()
            .try_field(&path("/Other.rel").unwrap(), FieldKey::TargetPaths.as_str())
            .unwrap()
            .unwrap()
            .into_owned()
            .try_as_path_list_op()
            .unwrap();
        assert!(op.explicit_items.is_empty());
        assert_eq!(op.prepended_items, vec![path("/B").unwrap()]);
    }

    #[test]
    fn move_property_renames() {
        let stage = sample();
        NamespaceEditor::new(&stage)
            .move_property(path("/A.out").unwrap(), path("/A.renamed").unwrap())
            .apply()
            .unwrap();

        assert!(stage.has_spec(&path("/A.renamed").unwrap()).unwrap());
        assert!(!stage.has_spec(&path("/A.out").unwrap()).unwrap());
    }

    #[test]
    fn delete_property_works() {
        let stage = sample();
        NamespaceEditor::new(&stage)
            .delete_property(path("/A.out").unwrap())
            .apply()
            .unwrap();

        assert!(!stage.has_spec(&path("/A.out").unwrap()).unwrap());
    }

    #[test]
    fn batched_two_moves() {
        let stage = sample();
        let mut editor = NamespaceEditor::new(&stage);
        editor
            .move_prim(path("/A").unwrap(), path("/B").unwrap())
            .move_prim(path("/Keep").unwrap(), path("/Kept").unwrap());
        editor.apply().unwrap();

        assert!(valid(&stage, "/B") && valid(&stage, "/Kept"));
        assert!(!valid(&stage, "/A") && !valid(&stage, "/Keep"));
    }

    #[test]
    fn batched_delete_then_move_onto() {
        // Deleting an object then moving another onto its vacated path succeeds:
        // the destination occupancy reflects the earlier delete, not just the
        // pre-batch state.
        let stage = sample();
        let mut editor = NamespaceEditor::new(&stage);
        editor
            .delete_prim(path("/Keep").unwrap())
            .move_prim(path("/A").unwrap(), path("/Keep").unwrap());
        editor.apply().unwrap();

        assert!(valid(&stage, "/Keep") && valid(&stage, "/Keep/Child"));
        assert!(!valid(&stage, "/A"));
    }

    #[test]
    fn batched_move_then_delete() {
        let stage = sample();
        let mut editor = NamespaceEditor::new(&stage);
        editor
            .move_prim(path("/A").unwrap(), path("/B").unwrap())
            .delete_prim(path("/B/Child").unwrap());
        editor.apply().unwrap();

        assert!(valid(&stage, "/B"));
        assert!(!valid(&stage, "/B/Child"));
    }

    #[test]
    fn local_child_no_relocate() {
        let stage = sample();
        NamespaceEditor::new(&stage)
            .move_prim(path("/A/Child").unwrap(), path("/B").unwrap())
            .apply()
            .unwrap();

        assert!(valid(&stage, "/B"));
        assert!(!valid(&stage, "/A/Child"));
        assert!(
            stage.root_layer().relocates().is_empty(),
            "local spec move should not author relocates: {:?}",
            stage.root_layer().relocates()
        );
    }

    #[test]
    fn chained_move_then_move() {
        let stage = sample();
        let mut editor = NamespaceEditor::new(&stage);
        editor
            .move_prim(path("/A").unwrap(), path("/B").unwrap())
            .move_prim(path("/B").unwrap(), path("/C").unwrap());
        editor.apply().unwrap();

        assert!(valid(&stage, "/C") && valid(&stage, "/C/Child"));
        assert!(!valid(&stage, "/A") && !valid(&stage, "/B"));
        // A chained move drags the external target through both hops.
        assert_eq!(rel_targets(&stage, "/Other.rel"), vec!["/C", "/Keep"]);
    }

    #[test]
    fn fixup_across_sublayers() {
        let stage = Stage::builder().in_memory("root.usda").unwrap();
        let mut sub = sdf::Layer::new_in_memory("sub.usda");
        edit_layer(&mut sub, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/A", Specifier::Def, "Xform").unwrap();
        });
        let root_id = stage.root_layer().identifier().to_string();
        stage.insert_layer(&root_id, 0, sub, LayerOffset::IDENTITY).unwrap();
        stage.define_prim("/Other").unwrap();
        stage
            .create_relationship("/Other.rel")
            .unwrap()
            .set_targets([path("/A").unwrap()])
            .unwrap();

        NamespaceEditor::new(&stage)
            .rename_prim(&stage.prim(path("/A").unwrap()), "B")
            .unwrap()
            .apply()
            .unwrap();

        assert!(valid(&stage, "/B"));
        assert!(!valid(&stage, "/A"));
        assert_eq!(rel_targets(&stage, "/Other.rel"), vec!["/B"]);
    }

    /// A root referencing `model.usda` so `/Ref/Geom` composes across the arc
    /// with no local spec — the case that needs a relocate to edit.
    fn referenced_stage() -> Stage {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Geom", Specifier::Def, "").unwrap();
        });
        Stage::builder().make_stage(vec![root, model], 0, Vec::new())
    }

    #[test]
    fn relocate_moves_cross_arc() {
        let stage = referenced_stage();
        assert!(valid(&stage, "/Ref/Geom"));
        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref/Geom").unwrap(), path("/Ref/Renamed").unwrap())
            .apply()
            .unwrap();

        // The relocate is authored on the local layer stack...
        let relocates = stage.root_layer().relocates();
        assert!(relocates
            .iter()
            .any(|(s, t)| s == &path("/Ref/Geom").unwrap() && t == &path("/Ref/Renamed").unwrap()));
        // ...and the composed prim moves to the relocate target.
        assert!(valid(&stage, "/Ref/Renamed"));
        assert!(!valid(&stage, "/Ref/Geom"));
    }

    #[test]
    fn relocate_deletes_cross_arc() {
        let stage = referenced_stage();
        NamespaceEditor::new(&stage)
            .delete_prim(path("/Ref/Geom").unwrap())
            .apply()
            .unwrap();

        let relocates = stage.root_layer().relocates();
        assert!(relocates
            .iter()
            .any(|(s, t)| s == &path("/Ref/Geom").unwrap() && t.is_empty()));
        assert!(!valid(&stage, "/Ref/Geom"));
    }

    #[test]
    fn rejects_composed_only_dst() {
        // `/Ref/Geom` composes across the reference with no local spec; a move
        // onto it must still collide rather than silently overlay it.
        let stage = referenced_stage();
        stage.define_prim("/Src").unwrap();
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/Src").unwrap(), path("/Ref/Geom").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::DestinationExists(_))
        ));
    }

    #[test]
    fn can_apply_dry_run() {
        let stage = sample();
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/A").unwrap(), path("/B").unwrap());
        // A feasible batch checks out, and the dry run leaves the stage untouched.
        editor.can_apply().unwrap();
        assert!(valid(&stage, "/A"));
        assert!(!valid(&stage, "/B"));
        // The same editor still applies for real afterward.
        editor.apply().unwrap();
        assert!(valid(&stage, "/B"));
        assert!(!valid(&stage, "/A"));
    }

    #[test]
    fn rejects_no_edits() {
        let stage = sample();
        assert!(matches!(
            NamespaceEditor::new(&stage).can_apply(),
            Err(NamespaceEditError::NoEdits)
        ));
    }

    #[test]
    fn rejects_missing_source() {
        let stage = sample();
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/Nope").unwrap(), path("/B").unwrap());
        assert!(matches!(editor.can_apply(), Err(NamespaceEditError::SourceNotFound(_))));
    }

    #[test]
    fn rejects_collision() {
        let stage = sample();
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/A").unwrap(), path("/Keep").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::DestinationExists(_))
        ));
    }

    #[test]
    fn rejects_self_descendant() {
        let stage = sample();
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/A").unwrap(), path("/A/Inside").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::DestinationUnderSource { .. })
        ));
    }

    #[test]
    fn rejects_cross_arc_descendant() {
        let stage = referenced_stage();
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/Ref/Geom").unwrap(), path("/Ref/Geom/Sub").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::DestinationUnderSource { .. })
        ));
    }

    #[test]
    fn rejects_kind_mismatch() {
        let stage = sample();
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/A").unwrap(), path("/Other.con").unwrap());
        assert!(matches!(editor.can_apply(), Err(NamespaceEditError::KindMismatch)));
    }

    #[test]
    fn rejects_prim_path_in_property_edit() {
        let stage = sample();
        let mut editor = NamespaceEditor::new(&stage);
        // A prim path handed to a property method is rejected, not silently
        // moved as a prim subtree.
        editor.move_property(path("/A").unwrap(), path("/B").unwrap());
        assert!(matches!(editor.can_apply(), Err(NamespaceEditError::KindMismatch)));
    }

    #[test]
    fn rejects_property_path_in_prim_edit() {
        let stage = sample();
        let mut editor = NamespaceEditor::new(&stage);
        editor.delete_prim(path("/A.out").unwrap());
        assert!(matches!(editor.can_apply(), Err(NamespaceEditError::KindMismatch)));
    }

    /// A stage whose root layer holds `/Prim`, and inside its `{set=sel}` variant
    /// a child `/Prim/child` (with an attribute connected to `/Prim/other.in`)
    /// and a sibling `/Prim/sibling`. The edit target is left on the variant, so
    /// a namespace edit authors at `{set=sel}` paths.
    fn variant_stage() -> Stage {
        let stage = Stage::builder().in_memory("root.usda").unwrap();
        stage.define_prim("/Prim").unwrap();
        let root = stage.root_layer().identifier().to_string();
        stage
            .set_edit_target(EditTarget::for_local_direct_variant(
                root,
                path("/Prim{set=sel}").unwrap(),
            ))
            .unwrap();
        stage.define_prim("/Prim/child").unwrap();
        stage
            .create_attribute("/Prim/child.out", "double")
            .unwrap()
            .set_connections([path("/Prim/other.in").unwrap()])
            .unwrap();
        stage.define_prim("/Prim/sibling").unwrap();
        stage
    }

    /// A variant-target rename authors at the `{set=sel}` paths: the child spec
    /// and its attribute move inside the variant, the connection target stays
    /// free of variant selections, and the variant sibling is untouched.
    #[test]
    fn variant_rename() {
        let stage = variant_stage();
        NamespaceEditor::new(&stage)
            .move_prim(path("/Prim/child").unwrap(), path("/Prim/renamed").unwrap())
            .apply()
            .unwrap();

        let layer = stage.root_layer();
        let data = layer.data();
        assert_eq!(
            data.spec_type(&path("/Prim{set=sel}renamed").unwrap()),
            Some(sdf::SpecType::Prim)
        );
        assert_eq!(
            data.spec_type(&path("/Prim{set=sel}renamed.out").unwrap()),
            Some(sdf::SpecType::Attribute)
        );
        assert!(!data.has_spec(&path("/Prim{set=sel}child").unwrap()));
        // The sibling inside the variant is left alone.
        assert_eq!(
            data.spec_type(&path("/Prim{set=sel}sibling").unwrap()),
            Some(sdf::SpecType::Prim)
        );
        // The connection target never carries a variant selection.
        let connections = data
            .try_field(
                &path("/Prim{set=sel}renamed.out").unwrap(),
                FieldKey::ConnectionPaths.as_str(),
            )
            .unwrap()
            .expect("connections authored")
            .into_owned()
            .try_as_path_list_op()
            .expect("connections are a path list op");
        assert_eq!(connections.explicit_items, vec![path("/Prim/other.in").unwrap()]);
    }

    /// A variant-target reparent moves the child subtree under another variant
    /// prim, landing at the `{set=sel}` destination.
    #[test]
    fn variant_reparent() {
        let stage = variant_stage();
        NamespaceEditor::new(&stage)
            .move_prim(path("/Prim/child").unwrap(), path("/Prim/sibling/child").unwrap())
            .apply()
            .unwrap();

        let layer = stage.root_layer();
        let data = layer.data();
        assert_eq!(
            data.spec_type(&path("/Prim{set=sel}sibling/child").unwrap()),
            Some(sdf::SpecType::Prim)
        );
        assert!(!data.has_spec(&path("/Prim{set=sel}child").unwrap()));
    }

    /// A variant-target delete removes the child spec inside the variant.
    #[test]
    fn variant_delete() {
        let stage = variant_stage();
        NamespaceEditor::new(&stage)
            .delete_prim(path("/Prim/child").unwrap())
            .apply()
            .unwrap();

        let layer = stage.root_layer();
        let data = layer.data();
        assert!(!data.has_spec(&path("/Prim{set=sel}child").unwrap()));
        assert!(!data.has_spec(&path("/Prim{set=sel}child.out").unwrap()));
        assert_eq!(
            data.spec_type(&path("/Prim{set=sel}sibling").unwrap()),
            Some(sdf::SpecType::Prim)
        );
    }

    /// A variant edit target cannot author a direct (local) opinion that composes
    /// at the same path as the variant content. Moving such a prim is rejected
    /// rather than silently moving only the variant copy and leaving the stronger
    /// direct opinion composed: `/Prim/child` is defined both directly and inside
    /// the selected `{set=sel}` variant, so the variant target reaches only one of
    /// its two contributors.
    #[test]
    fn variant_rejects_direct_opinion() {
        let text = r#"#usda 1.0
            def "Prim" (
                variants = { string set = "sel" }
                variantSets = "set"
            ) {
                def "child" {}
                variantSet "set" = {
                    "sel" {
                        def "child" {}
                    }
                }
            }
"#;
        let data = crate::usda::parser::Parser::new(text).parse().expect("parse usda");
        let layer = sdf::Layer::new("root.usda", Box::new(sdf::Data::from_specs(data)));
        let stage = Stage::builder().make_stage(vec![layer], 0, Vec::new());
        // The prim composes from both the direct opinion and the variant.
        assert!(valid(&stage, "/Prim/child"));
        let root = stage.root_layer().identifier().to_string();
        stage
            .set_edit_target(EditTarget::for_local_direct_variant(
                root,
                path("/Prim{set=sel}").unwrap(),
            ))
            .unwrap();

        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/Prim/child").unwrap(), path("/Prim/renamed").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::RequiresRelocate(_))
        ));
    }

    /// A stage where `/Ref` references `model.usda`'s `/Model`, bringing in two
    /// children `/Ref/A` and `/Ref/B` with no local specs. The edit target is
    /// left on the reference arc, so a namespace edit authors into `model.usda`
    /// in the `/Model` namespace.
    fn arc_target_stage() -> Stage {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/A", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/B", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());
        let target = stage
            .edit_target_for_node(&path("/Ref").unwrap(), EditTargetArc::Reference)
            .unwrap();
        stage.set_edit_target(target).unwrap();
        stage
    }

    /// A cross-arc move authors the structural move into the arc source layer
    /// (not the root), and the prim composes back through the arc.
    #[test]
    fn arc_move_child() {
        let stage = arc_target_stage();
        assert!(valid(&stage, "/Ref/A"));
        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref/A").unwrap(), path("/Ref/Renamed").unwrap())
            .apply()
            .unwrap();

        let model = stage.layer("model.usda").expect("model layer");
        assert_eq!(
            model.data().spec_type(&path("/Model/Renamed").unwrap()),
            Some(sdf::SpecType::Prim)
        );
        assert!(!model.data().has_spec(&path("/Model/A").unwrap()));
        // The edit landed in the source layer, not the root.
        assert!(!stage.root_layer().data().has_spec(&path("/Ref/Renamed").unwrap()));
        assert!(valid(&stage, "/Ref/Renamed"));
        assert!(!valid(&stage, "/Ref/A"));
        // No relocate is authored: the move is a direct edit of the source.
        assert!(stage.root_layer().relocates().is_empty());
    }

    /// A cross-arc delete removes the spec from the arc source layer, so the prim
    /// stops composing.
    #[test]
    fn arc_delete_child() {
        let stage = arc_target_stage();
        NamespaceEditor::new(&stage)
            .delete_prim(path("/Ref/A").unwrap())
            .apply()
            .unwrap();

        let model = stage.layer("model.usda").expect("model layer");
        assert!(!model.data().has_spec(&path("/Model/A").unwrap()));
        assert!(!valid(&stage, "/Ref/A"));
        assert!(valid(&stage, "/Ref/B"));
    }

    /// An arc edit target resolves to the referenced asset's own layer stack even
    /// when that asset is also sublayered into the root: the authoring stack is
    /// taken from the target node, not inferred from the layer's root-stack
    /// membership, so a valid cross-arc move is not wrongly rejected.
    #[test]
    fn arc_target_referenced_and_sublayered() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            e.data_mut().set_field(
                &sdf::Path::abs_root(),
                FieldKey::SubLayers.as_str(),
                sdf::Value::StringVec(vec!["model.usda".into()]),
            );
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/A", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());
        assert!(valid(&stage, "/Ref/A"));
        let target = stage
            .edit_target_for_node(&path("/Ref").unwrap(), EditTargetArc::Reference)
            .unwrap();
        stage.set_edit_target(target).unwrap();

        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref/A").unwrap(), path("/Ref/Renamed").unwrap())
            .apply()
            .unwrap();

        let model = stage.layer("model.usda").expect("model layer");
        assert_eq!(
            model.data().spec_type(&path("/Model/Renamed").unwrap()),
            Some(sdf::SpecType::Prim)
        );
        assert!(valid(&stage, "/Ref/Renamed"));
        assert!(!valid(&stage, "/Ref/A"));
        assert!(stage.root_layer().relocates().is_empty());
    }

    /// A cross-arc move follows an external relationship target authored in the
    /// arc source layer: a sibling relationship to the moved prim is rewritten in
    /// the source's namespace and composes back through the arc.
    #[test]
    fn arc_move_fixes_target() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/A", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/B", Specifier::Def, "").unwrap();
            sdf::RelationshipSpec::new(e.data_mut(), "/Model/B.rel", Variability::Varying, false).unwrap();
            e.data_mut().set_field(
                &path("/Model/B.rel").unwrap(),
                FieldKey::TargetPaths.as_str(),
                sdf::Value::PathListOp(sdf::PathListOp::explicit([path("/Model/A").unwrap()])),
            );
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());
        let target = stage
            .edit_target_for_node(&path("/Ref").unwrap(), EditTargetArc::Reference)
            .unwrap();
        stage.set_edit_target(target).unwrap();

        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref/A").unwrap(), path("/Ref/Renamed").unwrap())
            .apply()
            .unwrap();

        // The sibling relationship target follows the move, in the source layer's
        // namespace, and composes back through the arc.
        let model = stage.layer("model.usda").expect("model layer");
        let op = model
            .data()
            .try_field(&path("/Model/B.rel").unwrap(), FieldKey::TargetPaths.as_str())
            .unwrap()
            .expect("targets authored")
            .into_owned()
            .try_as_path_list_op()
            .expect("targets are a path list op");
        assert_eq!(op.explicit_items, vec![path("/Model/Renamed").unwrap()]);
        assert_eq!(rel_targets(&stage, "/Ref/B.rel"), vec!["/Ref/Renamed"]);
    }

    /// A move onto a destination occupied by another referenced child collides,
    /// detected against the arc source layer's overlay.
    #[test]
    fn arc_dest_occupied() {
        let stage = arc_target_stage();
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/Ref/A").unwrap(), path("/Ref/B").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::DestinationExists(_))
        ));
    }

    /// A move endpoint outside the arc's reach is rejected up front: the
    /// destination cannot be mapped into the arc source layer.
    #[test]
    fn mapped_outside_arc() {
        let stage = arc_target_stage();
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/Ref/A").unwrap(), path("/Elsewhere").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::Stage(StageAuthoringError::OutsideEditTarget { .. }))
        ));
    }

    /// A `/Ref` referencing `model.usda`'s `/Model`, which itself references
    /// `deep.usda`'s `/Deep` so `/Ref/Inner` arrives across an arc nested below
    /// the reference target — it has no spec in `model.usda`. The edit target is
    /// left on the `/Ref` reference arc, writing into `model.usda`.
    fn deep_arc_stage() -> Stage {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            // /Model brings in its own children across a deeper reference, so
            // they have no spec in this layer.
            e.data_mut().set_field(
                &path("/Model").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "deep.usda".into(),
                    prim_path: path("/Deep").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut deep = sdf::Layer::new_in_memory("deep.usda");
        edit_layer(&mut deep, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Deep", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Deep/Inner", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model, deep], 0, Vec::new());
        let target = stage
            .edit_target_for_node(&path("/Ref").unwrap(), EditTargetArc::Reference)
            .unwrap();
        stage.set_edit_target(target).unwrap();
        stage
    }

    /// A mapped move of a source arriving across an arc nested below the target
    /// synthesizes a relocate in the target's own layer stack (here
    /// `model.usda`), expressed in the target's namespace, and the prim composes
    /// back through the outer reference.
    #[test]
    fn mapped_deep_arc_move() {
        let stage = deep_arc_stage();
        assert!(valid(&stage, "/Ref/Inner"));

        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref/Inner").unwrap(), path("/Ref/Moved").unwrap())
            .apply()
            .unwrap();

        // The relocate lands in the target's stack, in the target's namespace.
        let model = stage.layer("model.usda").expect("model layer");
        assert!(model
            .relocates()
            .iter()
            .any(|(s, t)| s == &path("/Model/Inner").unwrap() && t == &path("/Model/Moved").unwrap()));
        // Not in the consuming root stack — a relocate there would be dropped.
        assert!(stage.root_layer().relocates().is_empty());
        // The deeper-arc content composes back at the moved path.
        assert!(valid(&stage, "/Ref/Moved"));
        assert!(!valid(&stage, "/Ref/Inner"));
    }

    /// A mapped delete of a source arriving across an arc nested below the
    /// target synthesizes a deletion relocate in the target's layer stack, so
    /// the prim stops composing.
    #[test]
    fn mapped_deep_arc_delete() {
        let stage = deep_arc_stage();
        assert!(valid(&stage, "/Ref/Inner"));

        NamespaceEditor::new(&stage)
            .delete_prim(path("/Ref/Inner").unwrap())
            .apply()
            .unwrap();

        let model = stage.layer("model.usda").expect("model layer");
        assert!(model
            .relocates()
            .iter()
            .any(|(s, t)| s == &path("/Model/Inner").unwrap() && t.is_empty()));
        assert!(stage.root_layer().relocates().is_empty());
        assert!(!valid(&stage, "/Ref/Inner"));
    }

    /// A mapped move of content an internal reference brings into the target —
    /// nested in the target's own layer stack, not a deeper external asset —
    /// still synthesizes a relocate there: the arc is rooted above the prim
    /// (`/Model` references `/Deep` within the same layer), so the source has no
    /// spec at the mapped path to move directly.
    #[test]
    fn mapped_internal_arc_relocates() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            // An internal reference (no asset path) to a sibling prim in the same
            // layer brings /Deep/Inner in at /Model/Inner with no spec there.
            e.data_mut().set_field(
                &path("/Model").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    prim_path: path("/Deep").unwrap(),
                    ..Default::default()
                }])),
            );
            sdf::PrimSpec::new(e.data_mut(), "/Deep", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Deep/Inner", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());
        assert!(valid(&stage, "/Ref/Inner"));
        let target = stage
            .edit_target_for_node(&path("/Ref").unwrap(), EditTargetArc::Reference)
            .unwrap();
        stage.set_edit_target(target).unwrap();

        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref/Inner").unwrap(), path("/Ref/Moved").unwrap())
            .apply()
            .unwrap();

        let model = stage.layer("model.usda").expect("model layer");
        assert!(model
            .relocates()
            .iter()
            .any(|(s, t)| s == &path("/Model/Inner").unwrap() && t == &path("/Model/Moved").unwrap()));
        assert!(valid(&stage, "/Ref/Moved"));
        assert!(!valid(&stage, "/Ref/Inner"));
    }

    /// A mapped move authors across every layer of the target's own stack, not
    /// only the layer the target writes to. When a referenced asset's root and
    /// its sublayer both carry the source spec, both move — leaving no residual
    /// opinion in the sublayer and needing no relocate, since the content is all
    /// local to the target's stack.
    #[test]
    fn mapped_within_stack_residue() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            e.data_mut().set_field(
                &sdf::Path::abs_root(),
                FieldKey::SubLayers.as_str(),
                sdf::Value::StringVec(vec!["model_sub.usda".into()]),
            );
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/A", Specifier::Def, "").unwrap();
        });
        let mut model_sub = sdf::Layer::new_in_memory("model_sub.usda");
        edit_layer(&mut model_sub, |e| {
            // The sublayer of the referenced asset also contributes /Model/A.
            sdf::PrimSpec::over(e.data_mut(), "/Model/A").unwrap();
            sdf::AttributeSpec::new(e.data_mut(), "/Model/A.attr", "double", Variability::Varying, false).unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model, model_sub], 0, Vec::new());
        let target = stage
            .edit_target_for_node(&path("/Ref").unwrap(), EditTargetArc::Reference)
            .unwrap();
        stage.set_edit_target(target).unwrap();

        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref/A").unwrap(), path("/Ref/Renamed").unwrap())
            .apply()
            .unwrap();

        // Both stack layers moved their spec; no residue lingers in the sublayer.
        let model = stage.layer("model.usda").expect("model layer");
        let model_sub = stage.layer("model_sub.usda").expect("model_sub layer");
        assert_eq!(
            model.data().spec_type(&path("/Model/Renamed").unwrap()),
            Some(sdf::SpecType::Prim)
        );
        assert!(!model.data().has_spec(&path("/Model/A").unwrap()));
        assert_eq!(
            model_sub.data().spec_type(&path("/Model/Renamed.attr").unwrap()),
            Some(sdf::SpecType::Attribute)
        );
        assert!(!model_sub.data().has_spec(&path("/Model/A").unwrap()));
        // All content is local to the target's stack, so no relocate is needed.
        assert!(model.relocates().is_empty());
        assert!(valid(&stage, "/Ref/Renamed"));
        assert!(!valid(&stage, "/Ref/A"));
    }

    /// A mapped edit that writes more than one layer of the target's stack
    /// reports its committed change with the edit-target provenance, not
    /// `LocalStack`: every stack layer is authored in the target's namespace, so
    /// the merged change must translate through the target's mapping for sinks
    /// to see composed (`/Ref/...`) rather than layer (`/Model/...`) paths.
    #[test]
    fn mapped_multi_layer_provenance() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            e.data_mut().set_field(
                &sdf::Path::abs_root(),
                FieldKey::SubLayers.as_str(),
                sdf::Value::StringVec(vec!["model_sub.usda".into()]),
            );
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/A", Specifier::Def, "").unwrap();
        });
        let mut model_sub = sdf::Layer::new_in_memory("model_sub.usda");
        edit_layer(&mut model_sub, |e| {
            sdf::PrimSpec::over(e.data_mut(), "/Model/A").unwrap();
            sdf::AttributeSpec::new(e.data_mut(), "/Model/A.attr", "double", Variability::Varying, false).unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model, model_sub], 0, Vec::new());
        let target = stage
            .edit_target_for_node(&path("/Ref").unwrap(), EditTargetArc::Reference)
            .unwrap();
        stage.set_edit_target(target).unwrap();

        let seen: std::rc::Rc<std::cell::Cell<Option<&'static str>>> = std::rc::Rc::new(std::cell::Cell::new(None));
        {
            let seen = seen.clone();
            stage.add_sink(move |_: &Stage, change: &crate::usd::CommittedChange<'_>| {
                seen.set(Some(match change.provenance {
                    crate::usd::Provenance::LocalStack => "local",
                    crate::usd::Provenance::EditTarget(_) => "target",
                    crate::usd::Provenance::DirectLayerEdit => "direct",
                }));
            });
        }

        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref/A").unwrap(), path("/Ref/Renamed").unwrap())
            .apply()
            .unwrap();

        // Both model.usda and model_sub.usda moved their spec, so the commit drains
        // two layer records; the merged change keeps the arc target's provenance.
        assert_eq!(seen.get(), Some("target"));
    }

    /// A failed mapped relocate batch leaves the target's layer stack and the
    /// cache untouched: a deep-arc move (which would synthesize a relocate)
    /// followed by a missing source rolls the whole batch back, authoring no
    /// relocate and leaving composition unchanged.
    #[test]
    fn mapped_relocate_atomic() {
        let stage = deep_arc_stage();
        let mut editor = NamespaceEditor::new(&stage);
        editor
            .move_prim(path("/Ref/Inner").unwrap(), path("/Ref/Moved").unwrap())
            .move_prim(path("/Ref/Missing").unwrap(), path("/Ref/X").unwrap());
        assert!(editor.apply().is_err());

        let model = stage.layer("model.usda").expect("model layer");
        assert!(model.relocates().is_empty());
        assert!(valid(&stage, "/Ref/Inner"));
        assert!(!valid(&stage, "/Ref/Moved"));
    }

    /// A mapped batch that would synthesize an unrepresentable relocate set is
    /// rejected, not authored: relocating a grandchild out of `/Ref/Inner` and
    /// then deleting `/Ref/Inner` would orphan the moved grandchild, which no
    /// valid relocate set in the target's stack can express.
    #[test]
    fn mapped_relocate_orphans_child() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            e.data_mut().set_field(
                &path("/Model").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "deep.usda".into(),
                    prim_path: path("/Deep").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut deep = sdf::Layer::new_in_memory("deep.usda");
        edit_layer(&mut deep, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Deep", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Deep/Inner", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Deep/Inner/Grand", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model, deep], 0, Vec::new());
        assert!(valid(&stage, "/Ref/Inner/Grand"));
        let target = stage
            .edit_target_for_node(&path("/Ref").unwrap(), EditTargetArc::Reference)
            .unwrap();
        stage.set_edit_target(target).unwrap();

        let mut editor = NamespaceEditor::new(&stage);
        editor
            .move_prim(path("/Ref/Inner/Grand").unwrap(), path("/Ref/Grand").unwrap())
            .delete_prim(path("/Ref/Inner").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::UnrepresentableRelocateBatch(_))
        ));
    }

    /// A failed mapped batch leaves the arc source layer and the cache untouched:
    /// a feasible move followed by an infeasible one rolls the whole batch back.
    #[test]
    fn mapped_atomic() {
        let stage = arc_target_stage();
        let mut editor = NamespaceEditor::new(&stage);
        editor
            .move_prim(path("/Ref/A").unwrap(), path("/Ref/Moved").unwrap())
            .move_prim(path("/Ref/Missing").unwrap(), path("/Ref/X").unwrap());
        assert!(editor.apply().is_err());

        let model = stage.layer("model.usda").expect("model layer");
        assert!(model.data().has_spec(&path("/Model/A").unwrap()));
        assert!(!model.data().has_spec(&path("/Model/Moved").unwrap()));
        assert!(valid(&stage, "/Ref/A"));
        assert!(!valid(&stage, "/Ref/Moved"));
    }

    /// A mapped batch with no edits staged is rejected the same as a local one.
    #[test]
    fn mapped_no_source() {
        let stage = arc_target_stage();
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/Ref/Missing").unwrap(), path("/Ref/X").unwrap());
        assert!(matches!(editor.can_apply(), Err(NamespaceEditError::SourceNotFound(_))));
    }

    /// `layers_to_edit` for a mapped target names exactly the layer it writes to.
    #[test]
    fn mapped_layers_to_edit() {
        let stage = arc_target_stage();
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/Ref/A").unwrap(), path("/Ref/Renamed").unwrap());
        assert_eq!(editor.layers_to_edit().unwrap(), vec!["model.usda".to_string()]);
    }

    /// `layers_to_edit` reports a target-stack layer the fixup rewrites even when
    /// it holds no source spec: a referenced asset's sublayer carrying only a
    /// relationship target to the moved prim is rewritten by `apply`, so the
    /// preflight must name it alongside the layer holding the moved spec.
    #[test]
    fn mapped_layers_to_edit_fixup_only() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            e.data_mut().set_field(
                &sdf::Path::abs_root(),
                FieldKey::SubLayers.as_str(),
                sdf::Value::StringVec(vec!["model_sub.usda".into()]),
            );
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/A", Specifier::Def, "").unwrap();
        });
        let mut model_sub = sdf::Layer::new_in_memory("model_sub.usda");
        edit_layer(&mut model_sub, |e| {
            sdf::RelationshipSpec::new(e.data_mut(), "/Model/B.rel", Variability::Varying, false).unwrap();
            e.data_mut().set_field(
                &path("/Model/B.rel").unwrap(),
                FieldKey::TargetPaths.as_str(),
                sdf::Value::PathListOp(sdf::PathListOp::explicit([path("/Model/A").unwrap()])),
            );
        });
        let stage = Stage::builder().make_stage(vec![root, model, model_sub], 0, Vec::new());
        let target = stage
            .edit_target_for_node(&path("/Ref").unwrap(), EditTargetArc::Reference)
            .unwrap();
        stage.set_edit_target(target).unwrap();

        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/Ref/A").unwrap(), path("/Ref/Renamed").unwrap());
        let layers = editor.layers_to_edit().unwrap();
        assert!(layers.contains(&"model.usda".to_string()), "got {layers:?}");
        assert!(layers.contains(&"model_sub.usda".to_string()), "got {layers:?}");
    }

    /// A `/Ref` referencing `model.usda`'s `/Model`, with the root layer also
    /// authoring local overrides for the prims named in `overrides` (so each
    /// composes from both the root and the arc). The edit target is left on the
    /// reference arc, writing into `model.usda`.
    fn arc_overridden_stage(overrides: &[&str]) -> Stage {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
            for name in overrides {
                sdf::PrimSpec::over(e.data_mut(), format!("/Ref/{name}").as_str()).unwrap();
            }
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/A", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());
        let target = stage
            .edit_target_for_node(&path("/Ref").unwrap(), EditTargetArc::Reference)
            .unwrap();
        stage.set_edit_target(target).unwrap();
        stage
    }

    /// A mapped move onto a destination occupied only by content composed from
    /// another layer (not the target's overlay) is rejected: authoring the move
    /// into the arc source would merge with the root-layer override at the
    /// destination rather than collide.
    #[test]
    fn mapped_dest_composed_elsewhere() {
        let stage = arc_overridden_stage(&["B"]);
        assert!(valid(&stage, "/Ref/B"));
        // The target layer holds no `/Model/B` spec, so only the composed-stage
        // occupancy check catches the collision.
        assert!(!stage
            .layer("model.usda")
            .unwrap()
            .data()
            .has_spec(&path("/Model/B").unwrap()));
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/Ref/A").unwrap(), path("/Ref/B").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::DestinationExists(_))
        ));
    }

    /// A mapped move of a source that composes from both the root override and
    /// the arc is rejected: the root opinion sits in the consuming root stack,
    /// which the arc target does not own, so editing the arc source alone leaves
    /// it behind and no relocate in the target's stack can suppress it.
    #[test]
    fn mapped_source_multi_layer() {
        let stage = arc_overridden_stage(&["A"]);
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/Ref/A").unwrap(), path("/Ref/Renamed").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::RequiresRelocate(_))
        ));
    }

    /// A mapped delete of a source that composes from both the root override and
    /// the arc is rejected for the same reason: deleting the arc source spec
    /// alone leaves the prim composed from the root override, in a stack the arc
    /// target cannot author into.
    #[test]
    fn mapped_delete_multi_layer() {
        let stage = arc_overridden_stage(&["A"]);
        let mut editor = NamespaceEditor::new(&stage);
        editor.delete_prim(path("/Ref/A").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::RequiresRelocate(_))
        ));
    }

    #[test]
    fn rejects_relative_path() {
        let stage = sample();
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(sdf::Path::from("A"), path("/B").unwrap());
        assert!(matches!(editor.can_apply(), Err(NamespaceEditError::InvalidSource(_))));
    }

    #[test]
    fn invalid_batch_atomic() {
        let stage = sample();
        let mut editor = NamespaceEditor::new(&stage);
        // A feasible move followed by an infeasible one: the batch is rejected
        // before anything is authored, so the first move never lands.
        editor
            .move_prim(path("/A").unwrap(), path("/B").unwrap())
            .move_prim(path("/Nope").unwrap(), path("/X").unwrap());
        assert!(editor.apply().is_err());
        assert!(valid(&stage, "/A"));
        assert!(!valid(&stage, "/B"));
    }

    #[test]
    fn rejects_pseudo_root() {
        let stage = sample();
        let mut editor = NamespaceEditor::new(&stage);
        editor.delete_prim(sdf::Path::abs_root());
        assert!(matches!(editor.can_apply(), Err(NamespaceEditError::PseudoRoot)));
    }

    #[test]
    fn layers_to_edit_lists() {
        let stage = sample();
        let mut editor = NamespaceEditor::new(&stage);
        editor.delete_prim(path("/A").unwrap());
        let layers = editor.layers_to_edit().unwrap();
        assert_eq!(layers, vec![stage.root_layer().identifier().to_string()]);
    }

    #[test]
    fn layers_to_edit_rejects() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/B", Specifier::Def, "").unwrap();
            e.set_relocates(vec![
                (path("/A/X").unwrap(), path("/B/Y").unwrap()),
                (path("/C/Y").unwrap(), path("/D/Y").unwrap()),
            ])
            .unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root], 0, Vec::new());
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/B").unwrap(), path("/D").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::UnrepresentableRelocateBatch(_))
        ));
        assert!(matches!(
            editor.layers_to_edit(),
            Err(NamespaceEditError::UnrepresentableRelocateBatch(_))
        ));
    }

    /// A pre-existing `(/Ref/Orig, /Ref/Geom)` relocate brings referenced content
    /// to `/Ref/Geom`; moving `/Ref/Geom -> /Ref/Final` retargets that live pair
    /// to `(/Ref/Orig, /Ref/Final)` rather than chaining, preserving the original
    /// source `/Ref/Orig`.
    #[test]
    fn relocate_fold_existing() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
            // Pre-existing relocate bringing the referenced /Ref/Orig to /Ref/Geom.
            e.set_relocates(vec![(path("/Ref/Orig").unwrap(), path("/Ref/Geom").unwrap())])
                .unwrap();
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Orig", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());

        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref/Geom").unwrap(), path("/Ref/Final").unwrap())
            .apply()
            .unwrap();

        let relocates = stage.root_layer().relocates();
        // Moving the live target /Ref/Geom retargets the existing pair to
        // (/Ref/Orig, /Ref/Final); the original source /Ref/Orig is preserved and
        // no transient (/Ref/Geom, /Ref/Final) pair is authored.
        assert!(
            relocates
                .iter()
                .any(|(s, t)| s == &path("/Ref/Orig").unwrap() && t == &path("/Ref/Final").unwrap()),
            "expected (/Ref/Orig, /Ref/Final) in {relocates:?}"
        );
        assert!(
            !relocates.iter().any(|(s, _)| s == &path("/Ref/Geom").unwrap()),
            "transient /Ref/Geom source must be dropped: {relocates:?}"
        );
        let targets: Vec<_> = relocates
            .iter()
            .filter(|(_, t)| !t.is_empty())
            .map(|(_, t)| t)
            .collect();
        assert_eq!(
            targets.len(),
            targets.iter().collect::<HashSet<_>>().len(),
            "duplicate destinations: {relocates:?}"
        );
    }

    /// A pre-existing relocate whose destination is a child of a deleted cross-arc
    /// prim collapses to the delete sentinel — its target re-roots onto the empty
    /// path rather than becoming a truncated path like `/Sub`.
    #[test]
    fn fold_delete_child() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
            // Pre-existing relocate with a child of /Ref/Geom as its destination.
            e.set_relocates(vec![(path("/Ref/B").unwrap(), path("/Ref/Geom/Sub").unwrap())])
                .unwrap();
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Geom", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Geom/Sub", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());

        NamespaceEditor::new(&stage)
            .delete_prim(path("/Ref/Geom").unwrap())
            .apply()
            .unwrap();

        let relocates = stage.root_layer().relocates();
        // Deleting /Ref/Geom re-roots (/Ref/B, /Ref/Geom/Sub) onto the sentinel.
        assert!(
            relocates
                .iter()
                .any(|(s, t)| s == &path("/Ref/B").unwrap() && t.is_empty()),
            "expected (/Ref/B, '') in {relocates:?}"
        );
        assert!(
            relocates
                .iter()
                .any(|(s, t)| s == &path("/Ref/Geom").unwrap() && t.is_empty()),
            "expected (/Ref/Geom, '') in {relocates:?}"
        );
    }

    /// Move a cross-arc prim then delete it in the same batch: the second edit
    /// must also produce a relocate.
    #[test]
    fn chain_move_delete() {
        let stage = referenced_stage();
        let mut editor = NamespaceEditor::new(&stage);
        editor
            .move_prim(path("/Ref/Geom").unwrap(), path("/Ref/Renamed").unwrap())
            .delete_prim(path("/Ref/Renamed").unwrap());
        editor.apply().unwrap();

        let relocates = stage.root_layer().relocates();
        // The chain collapses to a single delete on the original cross-arc
        // source: (/Ref/Geom, '').
        assert!(
            relocates
                .iter()
                .any(|(s, t)| s == &path("/Ref/Geom").unwrap() && t.is_empty()),
            "expected (/Ref/Geom, '') in {relocates:?}"
        );
        assert!(!valid(&stage, "/Ref/Geom"));
        assert!(!valid(&stage, "/Ref/Renamed"));
    }

    /// Move a cross-arc prim, then move the result again in the same batch:
    /// both edits must produce relocates, and the first must be folded through
    /// the second so the list contains no chain.
    #[test]
    fn chain_two_moves() {
        let stage = referenced_stage();
        let mut editor = NamespaceEditor::new(&stage);
        editor
            .move_prim(path("/Ref/Geom").unwrap(), path("/Ref/Renamed").unwrap())
            .move_prim(path("/Ref/Renamed").unwrap(), path("/Ref/Final").unwrap());
        editor.apply().unwrap();

        let relocates = stage.root_layer().relocates();
        // The two-hop chain collapses into a single pair targeting the final
        // destination: (/Ref/Geom, /Ref/Final).
        assert!(
            relocates
                .iter()
                .any(|(s, t)| s == &path("/Ref/Geom").unwrap() && t == &path("/Ref/Final").unwrap()),
            "expected (/Ref/Geom, /Ref/Final) in {relocates:?}"
        );
        // No path appears as both a source and a target (no chains).
        let sources: HashSet<_> = relocates.iter().map(|(s, _)| s).collect();
        let targets: HashSet<_> = relocates.iter().map(|(_, t)| t).collect();
        assert!(
            sources.intersection(&targets).next().is_none(),
            "chain found in {relocates:?}"
        );
        assert!(valid(&stage, "/Ref/Final"));
        assert!(!valid(&stage, "/Ref/Geom"));
        assert!(!valid(&stage, "/Ref/Renamed"));
    }

    /// A delete that targets a path only produced by a *later* edit in the
    /// same batch is rejected: the earlier edit must not be validated against
    /// a path that does not yet exist when it runs.
    #[test]
    fn rejects_premature_delete() {
        // edit 0: Delete(/Ref/Renamed) — /Ref/Renamed does not exist yet
        // edit 1: Move(/Ref/Geom → /Ref/Renamed) — would have created it
        let stage = referenced_stage();
        let mut editor = NamespaceEditor::new(&stage);
        editor
            .delete_prim(path("/Ref/Renamed").unwrap())
            .move_prim(path("/Ref/Geom").unwrap(), path("/Ref/Renamed").unwrap());
        assert!(matches!(editor.can_apply(), Err(NamespaceEditError::SourceNotFound(_))));
    }

    /// Two separate applies form a chain across an already-authored relocate:
    /// move `/Ref/Geom → /Ref/Renamed`, commit, then move `/Ref/Renamed →
    /// /Ref/Final`. The second batch must fold through the committed pair onto
    /// the genuine origin `/Ref/Geom`, not keep the transient `/Ref/Renamed`
    /// source, so the prim ends up composed at `/Ref/Final`.
    #[test]
    fn relocate_fold_sequential() {
        let stage = referenced_stage();
        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref/Geom").unwrap(), path("/Ref/Renamed").unwrap())
            .apply()
            .unwrap();
        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref/Renamed").unwrap(), path("/Ref/Final").unwrap())
            .apply()
            .unwrap();

        let relocates = stage.root_layer().relocates();
        assert!(
            relocates
                .iter()
                .any(|(s, t)| s == &path("/Ref/Geom").unwrap() && t == &path("/Ref/Final").unwrap()),
            "expected (/Ref/Geom, /Ref/Final) in {relocates:?}"
        );
        assert!(
            !relocates.iter().any(|(s, _)| s == &path("/Ref/Renamed").unwrap()),
            "transient /Ref/Renamed source must be dropped: {relocates:?}"
        );
        assert!(valid(&stage, "/Ref/Final"));
        assert!(!valid(&stage, "/Ref/Geom"));
        assert!(!valid(&stage, "/Ref/Renamed"));
    }

    /// Move a cross-arc prim, then in the same batch move a descendant that
    /// only exists under the relocated subtree: the descendant has no local
    /// spec, so it must be recognized as cross-arc and earn its own relocate
    /// authored in the relocated parent's namespace.
    #[test]
    fn chain_move_descendant() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Geom", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Geom/Sub", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());

        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref/Geom").unwrap(), path("/Ref/Renamed").unwrap())
            .move_prim(path("/Ref/Renamed/Sub").unwrap(), path("/Ref/Renamed/Sub2").unwrap())
            .apply()
            .unwrap();

        let relocates = stage.root_layer().relocates();
        assert!(
            relocates
                .iter()
                .any(|(s, t)| s == &path("/Ref/Renamed/Sub").unwrap() && t == &path("/Ref/Renamed/Sub2").unwrap()),
            "expected (/Ref/Renamed/Sub, /Ref/Renamed/Sub2) in {relocates:?}"
        );
        assert!(valid(&stage, "/Ref/Renamed/Sub2"));
        assert!(!valid(&stage, "/Ref/Renamed/Sub"));
        assert!(!valid(&stage, "/Ref/Geom"));
    }

    /// A later move whose source descends from a moved cross-arc root but names
    /// no real prim (a typo under the relocated subtree) is rejected as
    /// `SourceNotFound` rather than gaining a phantom relocate.
    #[test]
    fn rejects_missing_descendant() {
        let stage = referenced_stage(); // /Ref/Geom has no children
        let mut editor = NamespaceEditor::new(&stage);
        editor
            .move_prim(path("/Ref/Geom").unwrap(), path("/Ref/Renamed").unwrap())
            .move_prim(
                path("/Ref/Renamed/Missing").unwrap(),
                path("/Ref/Renamed/Other").unwrap(),
            );
        assert!(matches!(editor.can_apply(), Err(NamespaceEditError::SourceNotFound(_))));
    }

    /// A property under a moved cross-arc root cannot be relocated (relocates
    /// are prim-only), so a cross-arc property move is rejected and authors no
    /// relocate.
    #[test]
    fn rejects_property_descendant() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Geom", Specifier::Def, "").unwrap();
            sdf::AttributeSpec::new(e.data_mut(), "/Model/Geom.attr", "double", Variability::Varying, false).unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());
        let mut editor = NamespaceEditor::new(&stage);
        editor
            .move_prim(path("/Ref/Geom").unwrap(), path("/Ref/Renamed").unwrap())
            .move_property(path("/Ref/Renamed.attr").unwrap(), path("/Ref/Renamed.attr2").unwrap());
        assert!(matches!(editor.can_apply(), Err(NamespaceEditError::SourceNotFound(_))));
        assert!(
            !stage.root_layer().relocates().iter().any(|(s, _)| s.is_property_path()),
            "no property relocate must be authored"
        );
    }

    fn nested_ref_stage(children: &[&str]) -> Stage {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Geom", Specifier::Def, "").unwrap();
            for c in children {
                sdf::PrimSpec::new(e.data_mut(), format!("/Model/Geom/{c}").as_str(), Specifier::Def, "").unwrap();
            }
        });
        Stage::builder().make_stage(vec![root, model], 0, Vec::new())
    }

    /// Moving a descendant onto a destination occupied by a referenced sibling
    /// inside a relocated subtree collides: `/A/Other` composes from the moved
    /// `/Ref/Geom/Other`, so the second move must report `DestinationExists`.
    #[test]
    fn occupied_in_relocated() {
        let stage = nested_ref_stage(&["Sub", "Other"]);
        let mut editor = NamespaceEditor::new(&stage);
        editor
            .move_prim(path("/Ref/Geom").unwrap(), path("/A").unwrap())
            .move_prim(path("/A/Sub").unwrap(), path("/A/Other").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::DestinationExists(_))
        ));
    }

    /// After a child is relocated out of a cross-arc subtree, moving the parent
    /// root again must carry the child's relocate source with it: move
    /// `/Ref/Geom -> /A`, `/A/Sub -> /B`, then `/A -> /C` leaves the child pair
    /// sourced at `/C/Sub`, so `/B` is still created.
    #[test]
    fn child_source_follows_parent() {
        let stage = nested_ref_stage(&["Sub"]);
        let mut editor = NamespaceEditor::new(&stage);
        editor
            .move_prim(path("/Ref/Geom").unwrap(), path("/A").unwrap())
            .move_prim(path("/A/Sub").unwrap(), path("/B").unwrap())
            .move_prim(path("/A").unwrap(), path("/C").unwrap());
        editor.apply().unwrap();

        let relocates = stage.root_layer().relocates();
        assert!(
            relocates
                .iter()
                .any(|(s, t)| s == &path("/C/Sub").unwrap() && t == &path("/B").unwrap()),
            "expected (/C/Sub, /B) in {relocates:?}"
        );
        assert!(valid(&stage, "/C"));
        assert!(valid(&stage, "/B"));
        assert!(!valid(&stage, "/A"));
        assert!(!valid(&stage, "/C/Sub"));
    }

    /// Deleting a cross-arc parent after a descendant was relocated out of it
    /// cannot be represented: preserving `/B` would need a child relocate source
    /// under the deleted parent source, which Pcp rejects. The batch must fail
    /// explicitly rather than author a dead `(/A/Sub, /B)` pair that silently
    /// drops `/B`.
    #[test]
    fn delete_orphans_moved_child() {
        let stage = nested_ref_stage(&["Sub"]);
        let mut editor = NamespaceEditor::new(&stage);
        editor
            .move_prim(path("/Ref/Geom").unwrap(), path("/A").unwrap())
            .move_prim(path("/A/Sub").unwrap(), path("/B").unwrap())
            .delete_prim(path("/A").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::UnrepresentableRelocateBatch(_))
        ));
    }

    /// A destination vacated by earlier moves is free for a later move. With
    /// `move /Ref/A -> /Ref/B`, `move /Ref/B -> /Ref/C`, then `move /Ref/X ->
    /// /Ref/B`, the slot `/Ref/B` is transient (its occupant moved on to
    /// `/Ref/C`), so the third move must succeed rather than report
    /// `DestinationExists` just because `/Ref/B` held composed content earlier in
    /// the batch. The relocates collapse to the chain-free `(/Ref/A, /Ref/C)` and
    /// `(/Ref/X, /Ref/B)`.
    #[test]
    fn move_into_vacated_dst() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/A", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/X", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());

        let mut editor = NamespaceEditor::new(&stage);
        editor
            .move_prim(path("/Ref/A").unwrap(), path("/Ref/B").unwrap())
            .move_prim(path("/Ref/B").unwrap(), path("/Ref/C").unwrap())
            .move_prim(path("/Ref/X").unwrap(), path("/Ref/B").unwrap());
        editor.apply().unwrap();

        assert!(valid(&stage, "/Ref/C"));
        assert!(valid(&stage, "/Ref/B"));
        assert!(!valid(&stage, "/Ref/A"));
        assert!(!valid(&stage, "/Ref/X"));
    }

    /// Renaming a prim that carries its own reference moves the local spec (which
    /// carries the arc); the reference is rooted at the prim itself, not an
    /// ancestor, so no relocate is needed and the rename is not rejected.
    #[test]
    fn rename_referenced_prim() {
        let stage = referenced_stage();
        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref").unwrap(), path("/Ref2").unwrap())
            .apply()
            .unwrap();
        assert!(valid(&stage, "/Ref2/Geom"));
        assert!(!valid(&stage, "/Ref"));
        assert!(
            stage.root_layer().relocates().is_empty(),
            "rename should author no relocate"
        );
    }

    /// Moving a property onto a destination occupied only by a referenced
    /// composed property collides: `/Ref.attr` composes from `/Model.attr`, so
    /// the move must report `DestinationExists` rather than overlay it.
    #[test]
    fn move_onto_composed_property() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
            sdf::PrimSpec::new(e.data_mut(), "/Src", Specifier::Def, "").unwrap();
            sdf::AttributeSpec::new(e.data_mut(), "/Src.attr", "double", Variability::Varying, false).unwrap();
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::AttributeSpec::new(e.data_mut(), "/Model.attr", "double", Variability::Varying, false).unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());
        // /Ref.attr composes from the referenced /Model.attr (no local spec).
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_property(path("/Src.attr").unwrap(), path("/Ref.attr").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::DestinationExists(_))
        ));
    }

    /// Moving an already-relocated prim back to its original source folds the
    /// relocate to a no-op; the edit-target metadata must be cleared rather than
    /// left holding the stale pair.
    #[test]
    fn fold_relocate_to_empty() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
            e.set_relocates(vec![(path("/Ref/Orig").unwrap(), path("/Ref/Geom").unwrap())])
                .unwrap();
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Orig", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());
        assert!(valid(&stage, "/Ref/Geom"));
        // Move the relocated prim back to its original source: the relocate folds
        // to a no-op and the metadata must be cleared.
        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref/Geom").unwrap(), path("/Ref/Orig").unwrap())
            .apply()
            .unwrap();
        let relocates = stage.root_layer().relocates();
        assert!(relocates.is_empty(), "stale relocate left authored: {relocates:?}");
        assert!(valid(&stage, "/Ref/Orig"), "prim should be back at /Ref/Orig");
        assert!(!valid(&stage, "/Ref/Geom"), "prim should no longer be at /Ref/Geom");
    }

    /// A purely local move of a prim that hosts a relocate target carries the
    /// relocate with it: with `(/Ref/Geom, /Local/Geom)` authored, moving the
    /// local `/Local` to `/Moved` retargets the relocate to `(/Ref/Geom,
    /// /Moved/Geom)` so the relocated prim follows the namespace edit.
    #[test]
    fn local_retarget_relocate() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
            sdf::PrimSpec::new(e.data_mut(), "/Local", Specifier::Def, "").unwrap();
            // /Ref/Geom is relocated under the local prim /Local.
            e.set_relocates(vec![(path("/Ref/Geom").unwrap(), path("/Local/Geom").unwrap())])
                .unwrap();
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Geom", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());
        assert!(valid(&stage, "/Local/Geom"));
        // A purely local move of /Local must carry the relocate target with it.
        NamespaceEditor::new(&stage)
            .move_prim(path("/Local").unwrap(), path("/Moved").unwrap())
            .apply()
            .unwrap();
        let relocates = stage.root_layer().relocates();
        assert!(
            relocates
                .iter()
                .any(|(s, t)| s == &path("/Ref/Geom").unwrap() && t == &path("/Moved/Geom").unwrap()),
            "relocate target should follow the local move: {relocates:?}"
        );
        assert!(
            valid(&stage, "/Moved/Geom"),
            "relocated prim should follow to /Moved/Geom"
        );
        assert!(!valid(&stage, "/Local/Geom"));
    }

    /// A purely local rename that neither creates nor changes a relocate must
    /// succeed even when the layer already holds a structurally-invalid relocate
    /// that Pcp drops as a recoverable error; the batch is not blamed for the
    /// pre-existing pair.
    #[test]
    fn local_keeps_invalid() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Local", Specifier::Def, "").unwrap();
            // A pre-existing structurally-invalid relocate (root-prim source) that
            // Pcp drops as a recoverable error. The batch below does not touch it.
            e.set_relocates(vec![(path("/B").unwrap(), path("/C").unwrap())])
                .unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root], 0, Vec::new());
        NamespaceEditor::new(&stage)
            .move_prim(path("/Local").unwrap(), path("/Moved").unwrap())
            .apply()
            .unwrap();
        assert!(valid(&stage, "/Moved"));
        assert!(!valid(&stage, "/Local"));
    }

    #[test]
    fn invalid_seed_resurrection() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/A", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/A/X", Specifier::Def, "").unwrap();
            e.set_relocates(vec![(path("/A/X").unwrap(), path("/A").unwrap())])
                .unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root], 0, Vec::new());
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/A").unwrap(), path("/C").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::UnrepresentableRelocateBatch(_))
        ));
        assert!(valid(&stage, "/A"));
        assert!(!valid(&stage, "/C"));
        assert_eq!(
            stage.root_layer().relocates(),
            vec![(path("/A/X").unwrap(), path("/A").unwrap())]
        );
    }

    /// A relocate authored on a sublayer (not the edit target) folds with a move
    /// of the relocated prim: moving `/Ref/Geom` to `/Ref/Final` lets fixup
    /// remap the sublayer pair to `(/Ref/Orig, /Ref/Final)` and authors no
    /// conflicting duplicate on the root, so the prim ends up at `/Ref/Final`.
    #[test]
    fn relocate_in_sublayer_folds() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            e.data_mut().set_field(
                &sdf::Path::abs_root(),
                FieldKey::SubLayers.as_str(),
                sdf::Value::StringVec(vec!["sub.usda".into()]),
            );
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut sub = sdf::Layer::new_in_memory("sub.usda");
        edit_layer(&mut sub, |e| {
            // The relocate lives on the sublayer, not the edit target (root).
            e.set_relocates(vec![(path("/Ref/Orig").unwrap(), path("/Ref/Geom").unwrap())])
                .unwrap();
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Orig", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, sub, model], 0, Vec::new());
        assert!(valid(&stage, "/Ref/Geom"), "sublayer relocate should compose");
        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref/Geom").unwrap(), path("/Ref/Final").unwrap())
            .apply()
            .unwrap();
        assert!(valid(&stage, "/Ref/Final"), "relocated prim should move to /Ref/Final");
        assert!(!valid(&stage, "/Ref/Geom"));
        // No conflicting duplicate authored on the root edit target.
        assert!(
            stage.root_layer().relocates().is_empty(),
            "root should author no relocate: {:?}",
            stage.root_layer().relocates()
        );
    }

    /// The synthesized relocate must be validated against the whole local stack,
    /// not the edit target alone: a sublayer pair `(/Ref/C, /Ref/D)` makes the
    /// new root pair `(/Ref/X, /Ref/C)` a target-is-source chain that Pcp drops,
    /// so the batch is rejected rather than silently failing to compose.
    #[test]
    fn rejects_cross_layer_conflict() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            e.data_mut().set_field(
                &sdf::Path::abs_root(),
                FieldKey::SubLayers.as_str(),
                sdf::Value::StringVec(vec!["sub.usda".into()]),
            );
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut sub = sdf::Layer::new_in_memory("sub.usda");
        edit_layer(&mut sub, |e| {
            e.set_relocates(vec![(path("/Ref/C").unwrap(), path("/Ref/D").unwrap())])
                .unwrap();
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/X", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, sub, model], 0, Vec::new());
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/Ref/X").unwrap(), path("/Ref/C").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::UnrepresentableRelocateBatch(_))
        ));
    }

    /// A structurally-invalid pre-existing relocate is dropped by Pcp before
    /// conflict detection, so it must not block a newly synthesized pair: with an
    /// invalid `(/B, /C)` authored, moving referenced `/Ref/X` to `/B` (whose
    /// target coincides with the invalid pair's source) still succeeds.
    #[test]
    fn new_ignores_invalid() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
            // Invalid: a root prim cannot be a relocate source. Pcp drops it.
            e.set_relocates(vec![(path("/B").unwrap(), path("/C").unwrap())])
                .unwrap();
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/X", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());
        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref/X").unwrap(), path("/B").unwrap())
            .apply()
            .unwrap();
        assert!(valid(&stage, "/B"));
        assert!(!valid(&stage, "/Ref/X"));
    }

    /// A structurally-invalid seed relocate is metadata only: Pcp ignores it, so
    /// the namespace editor must not evolve it as a live relocate even when its
    /// target overlaps the edited path. Moving the referenced `/Ref/Geom` authors
    /// a new valid pair and leaves the invalid old pair unchanged.
    #[test]
    fn invalid_seed_stays_inert() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
            e.set_relocates(vec![(path("/A").unwrap(), path("/Ref/Geom").unwrap())])
                .unwrap();
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Geom", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());
        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref/Geom").unwrap(), path("/Final").unwrap())
            .apply()
            .unwrap();

        let relocates = stage.root_layer().relocates();
        assert!(
            relocates
                .iter()
                .any(|(s, t)| s == &path("/A").unwrap() && t == &path("/Ref/Geom").unwrap()),
            "invalid old pair should remain unchanged: {relocates:?}"
        );
        assert!(
            relocates
                .iter()
                .any(|(s, t)| s == &path("/Ref/Geom").unwrap() && t == &path("/Final").unwrap()),
            "valid move pair should be authored: {relocates:?}"
        );
        assert!(valid(&stage, "/Final"));
        assert!(!valid(&stage, "/Ref/Geom"));
    }

    /// A pre-existing relocate dropped only by a conflict must follow namespace
    /// moves with the conflicting pair. If it stayed at the old target while the
    /// conflicting pair moved away, Pcp would start applying it and hide
    /// `/Other/X`.
    #[test]
    fn inactive_conflict_reprojects() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/World", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Other", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Other/X", Specifier::Def, "").unwrap();
            e.set_relocates(vec![
                (path("/World/A").unwrap(), path("/World/C").unwrap()),
                (path("/Other/X").unwrap(), path("/World/A/B").unwrap()),
            ])
            .unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root], 0, Vec::new());
        assert!(valid(&stage, "/Other/X"));

        NamespaceEditor::new(&stage)
            .move_prim(path("/World").unwrap(), path("/Scene").unwrap())
            .apply()
            .unwrap();

        let relocates = stage.root_layer().relocates();
        assert!(
            relocates
                .iter()
                .any(|(s, t)| s == &path("/Scene/A").unwrap() && t == &path("/Scene/C").unwrap()),
            "conflicting pair target should follow /World -> /Scene: {relocates:?}"
        );
        assert!(
            relocates
                .iter()
                .any(|(s, t)| s == &path("/Other/X").unwrap() && t == &path("/Scene/A/B").unwrap()),
            "dropped pair target should follow /World -> /Scene: {relocates:?}"
        );
        assert!(valid(&stage, "/Other/X"));
    }

    /// A weaker duplicate-source relocate is ignored by Pcp extraction. Its
    /// target must not make a cross-arc move look like a continuation of a live
    /// relocate; the move still needs its own pair.
    #[test]
    fn duplicate_source_inert() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            e.data_mut().set_field(
                &sdf::Path::abs_root(),
                FieldKey::SubLayers.as_str(),
                sdf::Value::StringVec(vec!["sub.usda".into()]),
            );
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
            e.set_relocates(vec![(path("/Ref/Orig").unwrap(), path("/Ref/Strong").unwrap())])
                .unwrap();
        });
        let mut sub = sdf::Layer::new_in_memory("sub.usda");
        edit_layer(&mut sub, |e| {
            e.set_relocates(vec![(path("/Ref/Orig").unwrap(), path("/Ref/Geom").unwrap())])
                .unwrap();
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Orig", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Geom", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, sub, model], 0, Vec::new());
        assert!(valid(&stage, "/Ref/Strong"));
        assert!(valid(&stage, "/Ref/Geom"));

        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref/Geom").unwrap(), path("/Final").unwrap())
            .apply()
            .unwrap();

        let root_relocates = stage.root_layer().relocates();
        assert!(
            root_relocates
                .iter()
                .any(|(s, t)| s == &path("/Ref/Geom").unwrap() && t == &path("/Final").unwrap()),
            "move pair should be authored: {root_relocates:?}"
        );
        assert!(valid(&stage, "/Final"));
        assert!(!valid(&stage, "/Ref/Geom"));
    }

    /// Fresh relocates authored on a stronger edit target must validate at that
    /// layer's strength, ahead of weaker sublayer pairs with the same source.
    #[test]
    fn edit_target_strength() {
        let root = pcp::LayerId::from_raw(0);
        let sub = pcp::LayerId::from_raw(1);
        let source = path("/Ref/X").unwrap();
        let weak_target = path("/Ref/T").unwrap();
        let move_target = path("/Final").unwrap();
        let mut seeds = HashMap::new();
        seeds.insert(sub, vec![(source.clone(), weak_target.clone())]);

        let mut move_plan = RelocateStackPlan::new(&[root, sub], &seeds, root);
        move_plan.record_move(&source, &move_target, true).unwrap();
        let combined = move_plan.combined();
        assert_eq!(combined[0].pair, (source.clone(), move_target));
        assert!(combined[0].fresh);
        let pairs: sdf::RelocateList = combined.iter().map(|r| r.pair.clone()).collect();
        let status = pcp::analyze_relocate_occurrences(&pairs);
        assert_eq!(pcp::first_unrepresentable_relocate(&combined, &status), None);

        let mut delete_plan = RelocateStackPlan::new(&[root, sub], &seeds, root);
        delete_plan.record_delete(&source, true).unwrap();
        let combined = delete_plan.combined();
        assert_eq!(combined[0].pair, (source, sdf::Path::default()));
        assert!(combined[0].fresh);
        let pairs: sdf::RelocateList = combined.iter().map(|r| r.pair.clone()).collect();
        let status = pcp::analyze_relocate_occurrences(&pairs);
        assert_eq!(pcp::first_unrepresentable_relocate(&combined, &status), None);
    }

    #[test]
    fn rejects_deleted_source() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
            sdf::PrimSpec::new(e.data_mut(), "/Local", Specifier::Def, "").unwrap();
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Geom", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Geom/Sub", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());

        let mut editor = NamespaceEditor::new(&stage);
        editor
            .move_prim(path("/Ref/Geom").unwrap(), path("/A").unwrap())
            .delete_prim(path("/A/Sub").unwrap())
            .move_prim(path("/Local").unwrap(), path("/A/Sub").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::UnrepresentableRelocateBatch(_))
        ));
        assert!(valid(&stage, "/Local"));
        assert!(!valid(&stage, "/A"));
    }

    /// Deleting a prim relocated by a sublayer empties that sublayer pair (its
    /// target collapses to the delete sentinel) so the prim stops composing,
    /// rather than leaving the pair pointing at a now-deleted path.
    #[test]
    fn delete_sublayer_relocate_target() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            e.data_mut().set_field(
                &sdf::Path::abs_root(),
                FieldKey::SubLayers.as_str(),
                sdf::Value::StringVec(vec!["sub.usda".into()]),
            );
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut sub = sdf::Layer::new_in_memory("sub.usda");
        edit_layer(&mut sub, |e| {
            e.set_relocates(vec![(path("/Ref/Orig").unwrap(), path("/Ref/Geom").unwrap())])
                .unwrap();
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Orig", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, sub, model], 0, Vec::new());
        assert!(valid(&stage, "/Ref/Geom"));
        NamespaceEditor::new(&stage)
            .delete_prim(path("/Ref/Geom").unwrap())
            .apply()
            .unwrap();
        assert!(
            !valid(&stage, "/Ref/Geom"),
            "deleted relocated prim should no longer compose"
        );
    }

    fn sublayer_relocate_stage(relocate: (&str, &str), model_children: &[&str]) -> Stage {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            e.data_mut().set_field(
                &sdf::Path::abs_root(),
                FieldKey::SubLayers.as_str(),
                sdf::Value::StringVec(vec!["sub.usda".into()]),
            );
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
            sdf::PrimSpec::new(e.data_mut(), "/Local", Specifier::Def, "").unwrap();
        });
        let mut sub = sdf::Layer::new_in_memory("sub.usda");
        edit_layer(&mut sub, |e| {
            e.set_relocates(vec![(path(relocate.0).unwrap(), path(relocate.1).unwrap())])
                .unwrap();
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            for c in model_children {
                sdf::PrimSpec::new(e.data_mut(), format!("/Model/{c}").as_str(), Specifier::Def, "").unwrap();
            }
        });
        Stage::builder().make_stage(vec![root, sub, model], 0, Vec::new())
    }

    /// Deleting a prim whose relocated child (described by a sublayer pair) was
    /// moved out of the deleted subtree earlier in the batch is rejected, like
    /// the edit-target orphan case: no valid relocate set keeps the moved child
    /// while deleting its parent.
    #[test]
    fn delete_orphans_sublayer_child() {
        let stage = sublayer_relocate_stage(("/Ref/Orig", "/Ref/Geom"), &["Orig"]);
        assert!(valid(&stage, "/Ref/Geom"));
        let mut editor = NamespaceEditor::new(&stage);
        editor
            .move_prim(path("/Ref/Geom").unwrap(), path("/B").unwrap())
            .delete_prim(path("/Ref").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::UnrepresentableRelocateBatch(_))
        ));
    }

    /// A relocate target on a sublayer that an earlier edit moved is recognized
    /// by a later edit: moving local `/Local -> /Moved` carries the sublayer pair
    /// `(/Ref/Orig, /Local/Geom)` to `/Moved/Geom`, and the subsequent move of
    /// `/Moved/Geom -> /Final` retargets that same pair instead of synthesizing a
    /// conflicting duplicate.
    #[test]
    fn sublayer_target_reprojects() {
        let stage = sublayer_relocate_stage(("/Ref/Orig", "/Local/Geom"), &["Orig"]);
        assert!(valid(&stage, "/Local/Geom"));
        NamespaceEditor::new(&stage)
            .move_prim(path("/Local").unwrap(), path("/Moved").unwrap())
            .move_prim(path("/Moved/Geom").unwrap(), path("/Final").unwrap())
            .apply()
            .unwrap();
        assert!(valid(&stage, "/Final"));
        assert!(!valid(&stage, "/Moved/Geom"));
    }

    /// Renaming a prim that owns a subroot reference (`@model@</Model/Geom>`)
    /// moves the local spec that carries the reference; the arc is authored at
    /// the prim itself, so no relocate is needed and the rename is not rejected.
    #[test]
    fn rename_subroot_referenced_prim() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model/Geom").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Geom", Specifier::Def, "Xform").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());
        NamespaceEditor::new(&stage)
            .move_prim(path("/Ref").unwrap(), path("/Ref2").unwrap())
            .apply()
            .unwrap();
        assert!(valid(&stage, "/Ref2"));
        assert!(!valid(&stage, "/Ref"));
        assert!(
            stage.root_layer().relocates().is_empty(),
            "rename should author no relocate"
        );
    }

    /// Spec-level `relocates` metadata is ordinary embedded-path data (it is not
    /// owned by the relocate stack plan, which handles only layer-level
    /// `layerRelocates`), so moving the prim that holds it reprojects its paths
    /// like any other field.
    #[test]
    fn move_reprojects_spec_relocates() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/A", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/A").unwrap(),
                FieldKey::Relocates.as_str(),
                sdf::Value::Relocates(vec![(path("/A/X").unwrap(), path("/A/Y").unwrap())]),
            );
        });
        let stage = Stage::builder().make_stage(vec![root], 0, Vec::new());
        NamespaceEditor::new(&stage)
            .move_prim(path("/A").unwrap(), path("/Moved").unwrap())
            .apply()
            .unwrap();

        let value = stage
            .root_layer()
            .data()
            .try_field(&path("/Moved").unwrap(), FieldKey::Relocates.as_str())
            .unwrap()
            .expect("spec-level relocates should move with the prim")
            .into_owned();
        let relocates = value.try_as_relocates().expect("relocates value");
        assert_eq!(
            relocates,
            vec![(path("/Moved/X").unwrap(), path("/Moved/Y").unwrap())],
            "spec-level relocate paths should reproject onto the moved prim"
        );
    }

    /// A pre-existing relocate the batch does not touch is left as authored, even
    /// a structurally-invalid no-op `source == target`: an unrelated local move
    /// must not rewrite a layer's existing relocate metadata away.
    #[test]
    fn untouched_noop_relocate_preserved() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/A", Specifier::Def, "").unwrap();
            e.set_relocates(vec![(path("/X/Keep").unwrap(), path("/X/Keep").unwrap())])
                .unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root], 0, Vec::new());
        NamespaceEditor::new(&stage)
            .move_prim(path("/A").unwrap(), path("/Moved").unwrap())
            .apply()
            .unwrap();
        assert!(
            stage
                .root_layer()
                .relocates()
                .iter()
                .any(|(s, t)| s == &path("/X/Keep").unwrap() && t == &path("/X/Keep").unwrap()),
            "untouched no-op relocate must be preserved: {:?}",
            stage.root_layer().relocates()
        );
    }

    #[test]
    fn moved_noop_preserved() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/A", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/A/X", Specifier::Def, "").unwrap();
            e.set_relocates(vec![(path("/A/X").unwrap(), path("/A/X").unwrap())])
                .unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root], 0, Vec::new());
        NamespaceEditor::new(&stage)
            .move_prim(path("/A").unwrap(), path("/B").unwrap())
            .apply()
            .unwrap();
        assert_eq!(
            stage.root_layer().relocates(),
            vec![(path("/B/X").unwrap(), path("/B/X").unwrap())],
            "moved no-op relocate metadata follows the namespace edit"
        );
    }

    /// A layer included more than once in the root stack has one authored
    /// relocate list. Seeding the relocate plan must not duplicate that layer's
    /// entries and write doubled metadata during an unrelated edit.
    #[test]
    fn duplicate_sublayer_seed() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            e.data_mut().set_field(
                &sdf::Path::abs_root(),
                FieldKey::SubLayers.as_str(),
                sdf::Value::StringVec(vec!["sub.usda".into(), "sub.usda".into()]),
            );
            sdf::PrimSpec::new(e.data_mut(), "/A", Specifier::Def, "").unwrap();
        });
        let mut sub = sdf::Layer::new_in_memory("sub.usda");
        edit_layer(&mut sub, |e| {
            e.set_relocates(vec![(path("/Ref/Orig").unwrap(), path("/Ref/Geom").unwrap())])
                .unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, sub], 0, Vec::new());

        NamespaceEditor::new(&stage)
            .move_prim(path("/A").unwrap(), path("/Moved").unwrap())
            .apply()
            .unwrap();

        let relocates = stage.layer("sub.usda").expect("sub layer").relocates();
        assert_eq!(
            relocates,
            vec![(path("/Ref/Orig").unwrap(), path("/Ref/Geom").unwrap())],
            "unrelated edit must not duplicate repeated sublayer relocates"
        );
    }

    /// `layers_to_edit` reports a sublayer whose relocate the batch would rewrite:
    /// moving a prim relocated by `sub.usda` mutates that sublayer, even though no
    /// source spec lives there, so the preflight must name it.
    #[test]
    fn layers_to_edit_relocates() {
        let stage = sublayer_relocate_stage(("/Ref/Orig", "/Ref/Geom"), &["Orig"]);
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/Ref/Geom").unwrap(), path("/Ref/Final").unwrap());
        let layers = editor.layers_to_edit().unwrap();
        assert!(
            layers.iter().any(|id| id == "sub.usda"),
            "sublayer whose relocate is rewritten should be reported: {layers:?}"
        );
    }

    fn relocate_target_masking_stage() -> Stage {
        // /Ref references a model with BOTH Orig and Geom; a relocate
        // /Ref/Orig -> /Ref/Geom puts Orig's content at /Ref/Geom, masking the
        // referenced /Ref/Geom.
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
            e.set_relocates(vec![(path("/Ref/Orig").unwrap(), path("/Ref/Geom").unwrap())])
                .unwrap();
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Orig", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Geom", Specifier::Def, "").unwrap();
        });
        Stage::builder().make_stage(vec![root, model], 0, Vec::new())
    }

    /// Moving a relocate target that masks its own referenced content is
    /// rejected: retargeting the relocate would reveal the masked `/Ref/Geom`,
    /// so the move cannot be cleanly expressed and must not silently leave both
    /// `/Final` and `/Ref/Geom` composed.
    #[test]
    fn rejects_masking_move() {
        let stage = relocate_target_masking_stage();
        assert!(valid(&stage, "/Ref/Geom"));
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/Ref/Geom").unwrap(), path("/Final").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::UnrepresentableRelocateBatch(_))
        ));
    }

    /// Deleting a relocate target that masks its own referenced content is
    /// rejected for the same reason: emptying the relocate would reveal the
    /// masked `/Ref/Geom` rather than removing it.
    #[test]
    fn rejects_masking_delete() {
        let stage = relocate_target_masking_stage();
        let mut editor = NamespaceEditor::new(&stage);
        editor.delete_prim(path("/Ref/Geom").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::UnrepresentableRelocateBatch(_))
        ));
    }

    /// A mapped (arc) target enforces the same masking rejection as the local
    /// stack: when the target stack relocates `/Model/Orig -> /Model/Geom` over a
    /// deeper-arc `/Model/Geom`, moving `/Ref/Geom` would retarget the relocate
    /// and reveal the masked deeper content at the old path, so it is rejected
    /// rather than leaving both prims composed.
    #[test]
    fn mapped_rejects_masking() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            // /Model brings Orig and Geom across a deeper reference, then relocates
            // Orig onto Geom, masking the deeper-arc Geom.
            e.data_mut().set_field(
                &path("/Model").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "deep.usda".into(),
                    prim_path: path("/Deep").unwrap(),
                    ..Default::default()
                }])),
            );
            e.set_relocates(vec![(path("/Model/Orig").unwrap(), path("/Model/Geom").unwrap())])
                .unwrap();
        });
        let mut deep = sdf::Layer::new_in_memory("deep.usda");
        edit_layer(&mut deep, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Deep", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Deep/Orig", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Deep/Geom", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model, deep], 0, Vec::new());
        assert!(valid(&stage, "/Ref/Geom"));
        let target = stage
            .edit_target_for_node(&path("/Ref").unwrap(), EditTargetArc::Reference)
            .unwrap();
        stage.set_edit_target(target).unwrap();

        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/Ref/Geom").unwrap(), path("/Ref/Final").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::UnrepresentableRelocateBatch(_))
        ));
    }

    /// /Ref references a model with Geom, A, B; the root authors two relocates
    /// onto the same target (/Ref/A -> /Ref/Geom, /Ref/B -> /Ref/Geom), so both
    /// are conflict-dropped and /Ref/Geom composes directly from the reference.
    /// Moving /Ref/Geom would author /Ref/Geom -> /Dst, whose source is the target
    /// of those dropped relocates; Pcp would drop the fresh pair too, so the batch
    /// is rejected.
    #[test]
    fn rejects_dropped_conflict() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
            e.set_relocates(vec![
                (path("/Ref/A").unwrap(), path("/Ref/Geom").unwrap()),
                (path("/Ref/B").unwrap(), path("/Ref/Geom").unwrap()),
            ])
            .unwrap();
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Geom", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/A", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/B", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());
        assert!(valid(&stage, "/Ref/Geom"));
        let mut editor = NamespaceEditor::new(&stage);
        editor.move_prim(path("/Ref/Geom").unwrap(), path("/Dst").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::UnrepresentableRelocateBatch(_))
        ));
    }

    /// The root authors a target-is-source chain (/Ref/X -> /Ref/Geom, /Ref/Geom
    /// -> /Ref/Y); both are conflict-dropped and /Ref/Geom composes directly.
    /// Deleting /Ref/Geom cannot be represented: the deletion pair (/Ref/Geom,'')
    /// is a duplicate source of the inert (/Ref/Geom,/Ref/Y) and source-is-target
    /// with (/Ref/X,/Ref/Geom), so it would be dropped — the batch is rejected
    /// rather than silently leaving /Ref/Geom composed.
    #[test]
    fn delete_over_dropped_chain() {
        let mut root = sdf::Layer::new_in_memory("root.usda");
        edit_layer(&mut root, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Ref", Specifier::Def, "").unwrap();
            e.data_mut().set_field(
                &path("/Ref").unwrap(),
                FieldKey::References.as_str(),
                sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                    asset_path: "model.usda".into(),
                    prim_path: path("/Model").unwrap(),
                    ..Default::default()
                }])),
            );
            e.set_relocates(vec![
                (path("/Ref/X").unwrap(), path("/Ref/Geom").unwrap()),
                (path("/Ref/Geom").unwrap(), path("/Ref/Y").unwrap()),
            ])
            .unwrap();
        });
        let mut model = sdf::Layer::new_in_memory("model.usda");
        edit_layer(&mut model, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Model", Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/Geom", Specifier::Def, "").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Model/X", Specifier::Def, "").unwrap();
        });
        let stage = Stage::builder().make_stage(vec![root, model], 0, Vec::new());
        assert!(valid(&stage, "/Ref/Geom"));
        let mut editor = NamespaceEditor::new(&stage);
        editor.delete_prim(path("/Ref/Geom").unwrap());
        assert!(matches!(
            editor.can_apply(),
            Err(NamespaceEditError::UnrepresentableRelocateBatch(_))
        ));
    }
}