File size: 75,131 Bytes
8ca7ba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import ast
import csv
import hashlib
import json
import math
import os
import re
import sqlite3
import struct
import threading
import time
import traceback
import urllib.parse
import xml.etree.ElementTree as ET
from collections import Counter, defaultdict
from collections.abc import Iterable, Sequence
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Literal, cast

from PIL import Image, ImageDraw
from shapely.geometry import MultiPoint, Polygon, box  # type: ignore[import-untyped]
from shapely.ops import unary_union  # type: ignore[import-untyped]

from packages.asset_registry.admission import normalize_category
from packages.asset_registry.descriptors import (
    AssetDescriptor,
    AssetQuality,
    OperationalClearance,
    OrientedBoundingBox,
    PbrChannels,
    Point2,
)
from packages.asset_registry.models import AdmissionStatus, AssetCatalog, AssetKind, AssetRecord
from packages.core.files import atomic_write_text

# USD's resolver and stage caches are not safe to drive from several Python
# threads in the same process.  GLB/GLTF inspection remains parallel, while
# USD loading is serialized through this narrow gate.
_USD_INSPECTION_LOCK = threading.Lock()


SUPPORTED_GEOMETRY_EXTENSIONS = {
    ".glb",
    ".gltf",
    ".obj",
    ".fbx",
    ".usd",
    ".usda",
    ".usdc",
    ".usdz",
    ".sdf",
}
NON_GEOMETRY_KINDS = {AssetKind.MATERIAL, AssetKind.LIGHTING}
STYLE_WORDS = {
    "art deco",
    "bohemian",
    "classic",
    "contemporary",
    "industrial",
    "japanese",
    "mid century",
    "minimal",
    "modern",
    "rustic",
    "scandinavian",
    "traditional",
    "vintage",
}
COLOR_WORDS = {
    "beige",
    "black",
    "blue",
    "brass",
    "bronze",
    "brown",
    "copper",
    "cream",
    "gold",
    "gray",
    "green",
    "grey",
    "orange",
    "pink",
    "purple",
    "red",
    "silver",
    "teal",
    "white",
    "yellow",
}
MATERIAL_WORDS = {
    "bamboo",
    "ceramic",
    "concrete",
    "fabric",
    "glass",
    "leather",
    "marble",
    "metal",
    "plastic",
    "rattan",
    "steel",
    "stone",
    "wood",
    "wooden",
}

CATEGORY_SYNONYMS: dict[str, tuple[str, ...]] = {
    "armchair": ("accent chair", "easy chair", "reading chair"),
    "bookcase": ("bookshelf", "book shelf", "low bookcase"),
    "cabinet": ("cupboard", "storage cabinet", "drawer cabinet"),
    "chair": ("seat", "work chair", "office chair"),
    "chest of drawers": ("drawer cabinet", "dresser", "storage cabinet"),
    "desk": ("work desk", "worktable", "writing desk"),
    "floor lamp": ("standing lamp", "floor light"),
    "lamp": ("light", "lighting fixture"),
    "picture": ("wall art", "artwork", "framed art"),
    "plant": ("indoor plant", "potted plant", "greenery"),
    "potted plant": ("indoor plant", "plant", "greenery"),
    "shelf": ("shelving", "storage shelf"),
    "side table": ("end table", "occasional table", "small table"),
    "sofa": ("couch", "settee"),
    "table": ("worktable", "dining table", "desk"),
    "vase": ("flower vase", "decorative vessel"),
}


@dataclass(slots=True)
class HssdSemantic:
    category: str = ""
    articulated: bool = False
    pickable: bool = False
    name: str = ""


@dataclass(frozen=True, slots=True)
class FrontAxisOverride:
    asset_id: str
    asset_sha256: str
    front_axis: Literal["+X", "-X", "+Y", "-Y"]
    source: Literal["multiview_verified", "manual_override"]
    confidence: float
    evidence: tuple[str, ...]
    note: str = ""


@dataclass(slots=True)
class ReleaseMetadata:
    hssd_root: Path | None = None
    hssd_semantics: dict[str, HssdSemantic] = field(default_factory=dict)
    affordances_by_category: dict[str, list[str]] = field(default_factory=dict)
    front_axis_overrides: dict[str, FrontAxisOverride] = field(default_factory=dict)


_PROCESS_OUTPUT_ROOT: Path | None = None
_PROCESS_METADATA: ReleaseMetadata | None = None
_PROCESS_RENDER_VIEWS = True


@dataclass(slots=True)
class GeometryEvidence:
    vertices: Any
    collision_vertices: Any | None
    triangle_count: int
    material_count: int
    pbr_channels: PbrChannels
    material_names: list[str]
    texture_dependencies: list[str]
    missing_dependencies: list[str]
    format_extensions: list[str]
    loader_compatibility: dict[str, str]
    native_up: tuple[float, float, float]
    native_front: tuple[float, float, float]
    native_to_meter_scale: float
    canonical_transform: tuple[float, ...]
    source_bbox_min_m: tuple[float, float, float]
    source_bbox_max_m: tuple[float, float, float]
    articulated: bool = False
    movable_parts: list[dict[str, Any]] = field(default_factory=list)
    explicit_collision: bool = False
    inferred: list[str] = field(default_factory=list)


class _MissingAssetDependencies(Exception):
    def __init__(self, paths: Sequence[str]) -> None:
        self.paths = list(paths)
        super().__init__("|".join(self.paths))


def _sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def _sha256_json(value: Any) -> str:
    return hashlib.sha256(
        json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()


def _words(value: str) -> list[str]:
    return re.findall(r"[a-z0-9]+", value.casefold().replace("_", " ").replace("-", " "))


def _clean_category(value: str) -> str:
    normalized = normalize_category(value).strip()
    aliases = {
        "bin": "trash can",
        "bookshelf": "bookcase",
        "couch": "sofa",
        "drawer": "chest of drawers",
        "dresser": "chest of drawers",
        "filing cabinet": "cabinet",
        "fridge": "refrigerator",
        "office chair": "chair",
        "painting": "picture",
        "picture frame": "picture",
        "seat": "chair",
        "standing lamp": "floor lamp",
        "trashcan": "trash can",
        "tv": "television",
        "wardrobe": "wardrobe",
    }
    return aliases.get(normalized, normalized or "object")


_CATEGORY_HINTS: tuple[tuple[tuple[str, ...], str], ...] = (
    (("floor lamp", "standing lamp"), "floor lamp"),
    (("ceiling lamp", "ceiling light", "pendant light"), "ceiling lamp"),
    (("desk lamp", "table lamp"), "table lamp"),
    (("office chair", "desk chair", "task chair", "work chair"), "chair"),
    (("armchair", "accent chair", "easy chair", "reading chair"), "armchair"),
    (("side table", "bedside table", "nightstand", "end table"), "side table"),
    (("chest of drawers", "drawer chest", "dresser"), "chest of drawers"),
    (("bookcase", "bookshelf", "book shelf"), "bookcase"),
    (("work desk", "writing desk", "computer desk", "desk"), "desk"),
    (("dining table", "coffee table", "work table", "table"), "table"),
    (("storage cabinet", "shoe cabinet", "sideboard", "cupboard", "cabinet"), "cabinet"),
    (("wardrobe", "armoire"), "wardrobe"),
    (("floor plant", "potted plant", "houseplant", "plant"), "potted plant"),
    (("wall art", "painting", "picture", "poster", "artwork"), "picture"),
    (("trash can", "trashcan", "waste bin", "pedal bin", "bin"), "trash can"),
    (("sofa", "couch", "settee"), "sofa"),
    (("stool",), "stool"),
    (("bench",), "bench"),
    (("shelf",), "shelf"),
    (("chair",), "chair"),
    (("lamp", "lightbox"), "lamp"),
    (("bed",), "bed"),
    (("basket",), "basket"),
    (("carton", "cardboard box", "storage box"), "box"),
    (("clock",), "clock"),
    (("monitor", "display"), "monitor"),
    (("vase",), "vase"),
    (("mug", "cup"), "mug"),
    (("bottle",), "bottle"),
    (("medical", "surgical", "anesthesia", "incubator", "ultrasound"), "medical equipment"),
)


def _record_category(record: AssetRecord, semantic: HssdSemantic | None) -> str:
    display = " ".join(_words(record.display_name))
    # Prefer explicit object names for well-defined refinements when an
    # upstream semantic class is broad (for example HSSD labels some open
    # bookcases as cabinets, which would incorrectly invent door clearance).
    refinements: tuple[tuple[tuple[str, ...], str], ...] = (
        (("floor lamp", "standing lamp"), "floor lamp"),
        (("bookcase", "bookshelf", "book shelf"), "bookcase"),
        (("side table", "bedside table", "end table", "nightstand"), "side table"),
        (("chest of drawers", "drawer chest", "dresser"), "chest of drawers"),
        (("armchair", "accent chair", "easy chair", "reading chair"), "armchair"),
        (("potted plant", "indoor plant"), "potted plant"),
        (("wall art", "painting", "picture"), "picture"),
        (("wardrobe", "armoire"), "wardrobe"),
    )
    for phrases, category in refinements:
        if any(phrase in display for phrase in phrases):
            return category
    if semantic and semantic.category:
        return _clean_category(semantic.category)
    candidate = _clean_category(record.normalized_category or "")
    candidate_words = _words(candidate)
    # Earlier indexes sometimes stored the complete tokenized search document
    # in normalized_category.  It is useful for retrieval, but is not a class.
    if candidate not in {"", "object"} and len(candidate_words) <= 5:
        return candidate
    text = " ".join(
        _words(
            " ".join(
                [
                    record.display_name,
                    record.description,
                    record.category,
                    Path(record.usd_path).stem,
                ]
            )
        )
    )
    for phrases, category in _CATEGORY_HINTS:
        if any(phrase in text for phrase in phrases):
            return category
    source_category = _clean_category(record.category.split("/")[-1])
    return source_category if len(_words(source_category)) <= 4 else "object"


def _bool_cell(value: str) -> bool:
    return value.strip().casefold() in {"1", "true", "yes", "y"}


def load_front_axis_overrides(path: Path | None) -> dict[str, FrontAxisOverride]:
    if path is None:
        return {}
    payload = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(payload, dict) or payload.get("schema_version") != "1.0":
        raise ValueError("front-axis override file must use schema_version 1.0")
    entries = payload.get("overrides")
    if not isinstance(entries, list):
        raise ValueError("front-axis override file requires an overrides list")
    output: dict[str, FrontAxisOverride] = {}
    allowed_axes = {"+X", "-X", "+Y", "-Y"}
    allowed_sources = {"multiview_verified", "manual_override"}
    for index, raw in enumerate(entries):
        if not isinstance(raw, dict):
            raise ValueError(f"front-axis override {index} must be an object")
        asset_id = str(raw.get("asset_id") or "").strip()
        asset_sha256 = str(raw.get("asset_sha256") or "").casefold()
        front_axis = str(raw.get("front_axis") or "")
        source = str(raw.get("source") or "")
        confidence = float(raw.get("confidence", 0.0))
        evidence_raw = raw.get("evidence")
        evidence = (
            tuple(str(item).strip() for item in evidence_raw if str(item).strip())
            if isinstance(evidence_raw, list)
            else ()
        )
        if not asset_id:
            raise ValueError(f"front-axis override {index} has no asset_id")
        if asset_id in output:
            raise ValueError(f"duplicate front-axis override: {asset_id}")
        if not re.fullmatch(r"[0-9a-f]{64}", asset_sha256):
            raise ValueError(f"invalid front-axis override sha256: {asset_id}")
        if front_axis not in allowed_axes:
            raise ValueError(f"invalid front-axis override direction: {asset_id}")
        if source not in allowed_sources:
            raise ValueError(f"invalid front-axis override source: {asset_id}")
        if not 0.9 <= confidence <= 1.0:
            raise ValueError(f"verified front-axis confidence must be in [0.9, 1]: {asset_id}")
        if not evidence:
            raise ValueError(f"verified front-axis override requires evidence: {asset_id}")
        output[asset_id] = FrontAxisOverride(
            asset_id=asset_id,
            asset_sha256=asset_sha256,
            front_axis=cast(Literal["+X", "-X", "+Y", "-Y"], front_axis),
            source=cast(Literal["multiview_verified", "manual_override"], source),
            confidence=confidence,
            evidence=evidence,
            note=str(raw.get("note") or "").strip(),
        )
    return output


def load_release_metadata(
    hssd_root: Path | None,
    front_axis_overrides_path: Path | None = None,
) -> ReleaseMetadata:
    metadata = ReleaseMetadata(
        hssd_root=hssd_root,
        front_axis_overrides=load_front_axis_overrides(front_axis_overrides_path),
    )
    if hssd_root is None or not hssd_root.is_dir():
        return metadata
    semantics_path = hssd_root / "metadata" / "hssd_obj_semantics_condensed.csv"
    if semantics_path.is_file():
        with semantics_path.open("r", encoding="utf-8-sig", newline="") as handle:
            rows = csv.reader(handle)
            next(rows, None)
            for row in rows:
                if len(row) < 4 or not row[0].strip():
                    continue
                metadata.hssd_semantics[row[0].strip()] = HssdSemantic(
                    category=_clean_category(row[3]),
                    articulated=_bool_cell(row[1]),
                    pickable=_bool_cell(row[2]),
                )
    objects_path = hssd_root / "metadata" / "objects.json"
    if objects_path.is_file():
        payload = json.loads(objects_path.read_text(encoding="utf-8"))
        for asset_id, value in payload.items():
            item = metadata.hssd_semantics.setdefault(str(asset_id), HssdSemantic())
            item.name = str(value.get("name") or "")
    affordance_path = hssd_root / "metadata" / "affordance_objects.csv"
    if affordance_path.is_file():
        with affordance_path.open("r", encoding="utf-8-sig", newline="") as handle:
            for row in csv.reader(handle):
                if len(row) < 3:
                    continue
                try:
                    categories = ast.literal_eval(row[-1])
                except (ValueError, SyntaxError):
                    continue
                if not isinstance(categories, list):
                    continue
                action = row[0].strip()
                for category in categories:
                    key = _clean_category(str(category))
                    if action and action not in metadata.affordances_by_category.setdefault(
                        key, []
                    ):
                        metadata.affordances_by_category[key].append(action)
    return metadata


def _hssd_id(record: AssetRecord, path: Path) -> str | None:
    if record.source == "HSSD" or record.asset_id.startswith("hssd:"):
        stem = path.stem
        for suffix in (".collider", ".filteredSupportSurface", ".supportSurface"):
            stem = stem.removesuffix(suffix)
        return stem
    return None


def _gltf_document(path: Path) -> dict[str, Any] | None:
    if path.suffix.casefold() == ".gltf":
        document = json.loads(path.read_text(encoding="utf-8"))
        if not isinstance(document, dict):
            raise ValueError("gltf_root_is_not_an_object")
        return cast(dict[str, Any], document)
    if path.suffix.casefold() != ".glb":
        return None
    with path.open("rb") as handle:
        header = handle.read(12)
        if len(header) != 12:
            raise ValueError("truncated_glb_header")
        magic, version, total_length = struct.unpack("<4sII", header)
        if magic != b"glTF" or version != 2 or total_length > path.stat().st_size:
            raise ValueError("invalid_glb_header")
        while handle.tell() + 8 <= total_length:
            length, chunk_type = struct.unpack("<II", handle.read(8))
            payload = handle.read(length)
            if len(payload) != length:
                raise ValueError("truncated_glb_chunk")
            if chunk_type == 0x4E4F534A:
                document = json.loads(payload.rstrip(b"\x00 \t\r\n").decode("utf-8"))
                if not isinstance(document, dict):
                    raise ValueError("glb_json_root_is_not_an_object")
                return cast(dict[str, Any], document)
    raise ValueError("glb_has_no_json_chunk")


def _gltf_material_evidence(
    path: Path, document: dict[str, Any]
) -> tuple[PbrChannels, int, list[str], list[str], list[str], list[str]]:
    dependencies: list[str] = []
    missing: list[str] = []
    for section in ("buffers", "images"):
        for item in document.get(section) or []:
            uri = str(item.get("uri") or "")
            if not uri or uri.startswith("data:"):
                continue
            candidate = (path.parent / urllib.parse.unquote(uri)).resolve()
            dependencies.append(str(candidate))
            if not candidate.is_file():
                missing.append(str(candidate))
    materials = document.get("materials") or []
    names = [str(item.get("name") or "") for item in materials if item.get("name")]
    base = normal = roughness = metallic = occlusion = emissive = False
    for material in materials:
        pbr = material.get("pbrMetallicRoughness") or {}
        base = base or bool(pbr.get("baseColorTexture") or pbr.get("baseColorFactor"))
        roughness = roughness or bool(
            pbr.get("metallicRoughnessTexture") or "roughnessFactor" in pbr
        )
        metallic = metallic or bool(pbr.get("metallicRoughnessTexture") or "metallicFactor" in pbr)
        normal = normal or bool(material.get("normalTexture"))
        occlusion = occlusion or bool(material.get("occlusionTexture"))
        emissive = emissive or bool(
            material.get("emissiveTexture") or material.get("emissiveFactor")
        )
    if materials and not base:
        base = True
    return (
        PbrChannels(
            base_color=base,
            normal=normal,
            roughness=roughness,
            metallic=metallic,
            occlusion=occlusion,
            emissive=emissive,
        ),
        len(materials),
        names,
        dependencies,
        missing,
        sorted(set(str(value) for value in document.get("extensionsRequired") or [])),
    )


def _orientation_from_config(
    path: Path, default_up: Sequence[float], default_front: Sequence[float]
) -> tuple[tuple[float, float, float], tuple[float, float, float], bool]:
    stem = path.stem.split(".", 1)[0]
    config = path.with_name(f"{stem}.object_config.json")
    if config.is_file():
        payload = json.loads(config.read_text(encoding="utf-8"))
        up = payload.get("up")
        front = payload.get("front")
        if isinstance(up, list) and len(up) == 3 and isinstance(front, list) and len(front) == 3:
            return (
                (float(up[0]), float(up[1]), float(up[2])),
                (float(front[0]), float(front[1]), float(front[2])),
                True,
            )
    return (
        (float(default_up[0]), float(default_up[1]), float(default_up[2])),
        (float(default_front[0]), float(default_front[1]), float(default_front[2])),
        False,
    )


def _canonical_rotation(up: Sequence[float], front: Sequence[float]) -> Any:
    import numpy as np

    source_up = np.asarray(up, dtype=float)
    source_front = np.asarray(front, dtype=float)
    if not np.isfinite(source_up).all() or not np.isfinite(source_front).all():
        raise ValueError("non_finite_orientation")
    source_up /= np.linalg.norm(source_up)
    source_front -= source_up * float(np.dot(source_front, source_up))
    if np.linalg.norm(source_front) < 1.0e-8:
        raise ValueError("parallel_up_and_front")
    source_front /= np.linalg.norm(source_front)
    source_right = np.cross(source_front, source_up)
    source_right /= np.linalg.norm(source_right)
    target_right = np.array([1.0, 0.0, 0.0])
    target_up = np.array([0.0, 0.0, 1.0])
    target_front = np.array([0.0, 1.0, 0.0])
    source_basis = np.column_stack([source_right, source_up, source_front])
    target_basis = np.column_stack([target_right, target_up, target_front])
    return target_basis @ np.linalg.inv(source_basis)


def _transform_matrix(rotation: Any, scale: float) -> tuple[float, ...]:
    import numpy as np

    matrix = np.eye(4, dtype=float)
    matrix[:3, :3] = rotation * scale
    return tuple(float(value) for value in matrix.reshape(-1))


_CANONICAL_FRONT_VECTORS: dict[str, tuple[float, float, float]] = {
    "+X": (1.0, 0.0, 0.0),
    "-X": (-1.0, 0.0, 0.0),
    "+Y": (0.0, 1.0, 0.0),
    "-Y": (0.0, -1.0, 0.0),
}


def _native_front_for_canonical_axis(
    canonical_transform: Sequence[float], front_axis: str
) -> tuple[float, float, float]:
    import numpy as np

    transform = np.asarray(canonical_transform, dtype=float).reshape(4, 4)
    canonical = np.asarray(_CANONICAL_FRONT_VECTORS[front_axis], dtype=float)
    native = np.linalg.solve(transform[:3, :3], canonical)
    length = float(np.linalg.norm(native))
    if not math.isfinite(length) or length <= 1.0e-9:
        raise ValueError("front-axis override produced an invalid native direction")
    native /= length
    return (
        round(float(native[0]), 9),
        round(float(native[1]), 9),
        round(float(native[2]), 9),
    )


def certify_descriptor_front_axis(
    descriptor: AssetDescriptor,
    override: FrontAxisOverride | None = None,
) -> AssetDescriptor:
    """Attach truthful semantic-front provenance without changing asset geometry."""

    if descriptor.status != "ACTIVE":
        return descriptor
    if override is None and descriptor.front_axis_source != "unknown":
        return descriptor
    value = descriptor.model_dump(mode="json")
    observed = set(descriptor.observed_fields)
    inferred = set(descriptor.inferred_fields)
    confidence = dict(descriptor.confidence)
    if override is None:
        from_source_metadata = "native_front_vector" in observed
        value["front_axis_source"] = (
            "source_metadata" if from_source_metadata else "dataset_convention"
        )
        value["front_axis_evidence"] = [
            (
                "source orientation metadata; semantic front not yet verified by material views"
                if from_source_metadata
                else "format default orientation; semantic front not yet verified by material views"
            )
        ]
        confidence["front_axis"] = 0.75 if from_source_metadata else 0.55
        if from_source_metadata:
            observed.add("front_axis")
            inferred.discard("front_axis")
        else:
            inferred.add("front_axis")
            observed.discard("front_axis")
    else:
        if descriptor.asset_id != override.asset_id:
            raise ValueError("front-axis override asset_id mismatch")
        if descriptor.sha256 != override.asset_sha256:
            raise ValueError(
                f"front-axis override sha256 mismatch for {descriptor.asset_id}: "
                f"expected {override.asset_sha256}, observed {descriptor.sha256}"
            )
        evidence = list(override.evidence)
        if override.note:
            evidence.append(f"note:{override.note}")
        value.update(
            front_axis=override.front_axis,
            front_axis_source=override.source,
            front_axis_evidence=evidence,
            native_front_vector=_native_front_for_canonical_axis(
                descriptor.canonical_transform, override.front_axis
            ),
        )
        confidence["front_axis"] = override.confidence
        confidence["native_front_vector"] = override.confidence
        observed.add("front_axis")
        inferred.discard("front_axis")
        # The semantic native vector is derived by applying the inverse of the
        # measured canonical transform to the verified canonical direction.
        inferred.add("native_front_vector")
        observed.discard("native_front_vector")
    value["observed_fields"] = sorted(observed - inferred)
    value["inferred_fields"] = sorted(inferred)
    value["confidence"] = confidence
    return AssetDescriptor.model_validate(value)


def _mesh_geometry(path: Path, record: AssetRecord) -> GeometryEvidence:
    import numpy as np
    import trimesh  # type: ignore[import-not-found]

    document = _gltf_document(path)
    if document is not None:
        pbr, material_count, names, dependencies, missing, format_extensions = (
            _gltf_material_evidence(path, document)
        )
    else:
        pbr = PbrChannels(base_color=True)
        material_count, names, dependencies, missing = 1, [], [], []
        format_extensions = []
    loaded = trimesh.load(str(path), force="scene", process=False)
    mesh = loaded.to_geometry() if isinstance(loaded, trimesh.Scene) else loaded
    vertices = np.asarray(mesh.vertices, dtype=float)
    faces = np.asarray(mesh.faces)
    if vertices.ndim != 2 or vertices.shape[1] != 3 or len(vertices) < 3:
        raise ValueError("no_geometry_vertices")
    if faces.ndim != 2 or len(faces) < 1:
        raise ValueError("no_geometry_faces")
    if not np.isfinite(vertices).all():
        raise ValueError("non_finite_geometry")
    default_up = (0.0, 1.0, 0.0) if path.suffix.casefold() in {".glb", ".gltf"} else (0.0, 0.0, 1.0)
    default_front = (0.0, 0.0, -1.0) if default_up[1] else (0.0, 1.0, 0.0)
    native_up, native_front, observed_orientation = _orientation_from_config(
        path, default_up, default_front
    )
    rotation = _canonical_rotation(native_up, native_front)
    source_min = vertices.min(axis=0)
    source_max = vertices.max(axis=0)
    scale = 1.0
    canonical = (rotation @ (vertices * scale).T).T
    collision_path = path.with_name(f"{path.stem}.collider{path.suffix}")
    collision_vertices = None
    explicit_collision = False
    if collision_path.is_file():
        collision_loaded = trimesh.load(str(collision_path), force="scene", process=False)
        collision_mesh = (
            collision_loaded.to_geometry()
            if isinstance(collision_loaded, trimesh.Scene)
            else collision_loaded
        )
        collision_raw = np.asarray(collision_mesh.vertices, dtype=float)
        if collision_raw.ndim == 2 and collision_raw.shape[1] == 3 and len(collision_raw) >= 3:
            collision_vertices = (rotation @ (collision_raw * scale).T).T
            explicit_collision = bool(np.isfinite(collision_vertices).all())
    inferred = [] if observed_orientation else ["native_orientation"]
    return GeometryEvidence(
        vertices=canonical,
        collision_vertices=collision_vertices,
        triangle_count=int(len(faces)),
        material_count=material_count,
        pbr_channels=pbr,
        material_names=names,
        texture_dependencies=dependencies,
        missing_dependencies=missing,
        format_extensions=format_extensions,
        loader_compatibility={
            "trimesh": "verified",
            "blender_gltf": (
                "unsupported" if "KHR_texture_basisu" in format_extensions else "compatible"
            ),
            "blender_gltf_basisu_repair": (
                "compatible" if "KHR_texture_basisu" in format_extensions else "not_tested"
            ),
        },
        native_up=native_up,
        native_front=native_front,
        native_to_meter_scale=scale,
        canonical_transform=_transform_matrix(rotation, scale),
        source_bbox_min_m=(
            float(source_min[0] * scale),
            float(source_min[1] * scale),
            float(source_min[2] * scale),
        ),
        source_bbox_max_m=(
            float(source_max[0] * scale),
            float(source_max[1] * scale),
            float(source_max[2] * scale),
        ),
        explicit_collision=explicit_collision,
        inferred=inferred,
    )


def _asset_paths(value: Any) -> Iterable[str]:
    try:
        from pxr import Sdf  # type: ignore[import-not-found]
    except ImportError:
        return []
    if isinstance(value, Sdf.AssetPath):
        # Prefer USD's layer-aware resolved path.  Referenced material layers
        # (notably ArtVIP's resource/material.usd) author paths relative to
        # their own layer, not relative to the root model layer.
        return [value.resolvedPath or value.path]
    if isinstance(value, (list, tuple)):
        output: list[str] = []
        for item in value:
            output.extend(_asset_paths(item))
        return output
    return []


def _usd_composition_dependencies(path: Path) -> tuple[list[str], list[str]]:
    from pxr import UsdUtils

    layers, assets, unresolved = UsdUtils.ComputeAllDependencies(str(path))
    dependencies: list[str] = []
    for layer in layers:
        layer_path = str(getattr(layer, "realPath", "") or getattr(layer, "identifier", ""))
        if layer_path and not layer_path.startswith("anon:"):
            dependencies.append(layer_path)
    dependencies.extend(str(asset) for asset in assets if str(asset))
    missing = [str(asset) for asset in unresolved if str(asset)]
    return sorted(set(dependencies)), sorted(set(missing))


def _usd_geometry(path: Path, _record: AssetRecord) -> GeometryEvidence:
    import numpy as np
    from pxr import Gf, Usd, UsdGeom, UsdPhysics

    dependencies, missing = _usd_composition_dependencies(path)
    if missing:
        raise _MissingAssetDependencies(missing)
    stage = Usd.Stage.Open(str(path))
    if stage is None:
        raise ValueError("usd_stage_open_failed")
    meters_per_unit = float(UsdGeom.GetStageMetersPerUnit(stage))
    if not math.isfinite(meters_per_unit) or meters_per_unit <= 0:
        raise ValueError("invalid_usd_meters_per_unit")
    up_axis = str(UsdGeom.GetStageUpAxis(stage)).upper()
    default_up = (0.0, 0.0, 1.0) if up_axis == "Z" else (0.0, 1.0, 0.0)
    default_front = (0.0, 1.0, 0.0) if up_axis == "Z" else (0.0, 0.0, -1.0)
    native_up, native_front, observed_orientation = _orientation_from_config(
        path, default_up, default_front
    )
    rotation = _canonical_rotation(native_up, native_front)
    xforms = UsdGeom.XformCache(Usd.TimeCode.Default())
    vertices: list[tuple[float, float, float]] = []
    collision_vertices: list[tuple[float, float, float]] = []
    triangle_count = 0
    material_names: list[str] = []
    joints: list[dict[str, Any]] = []
    articulated = False
    channels = Counter[str]()
    for prim in stage.Traverse():
        if prim.IsA(UsdGeom.Mesh):
            points = UsdGeom.Mesh(prim).GetPointsAttr().Get() or []
            matrix = xforms.GetLocalToWorldTransform(prim)
            transformed = [matrix.Transform(Gf.Vec3d(*point)) for point in points]
            tuples = [(float(point[0]), float(point[1]), float(point[2])) for point in transformed]
            vertices.extend(tuples)
            if prim.HasAPI(UsdPhysics.CollisionAPI):
                collision_vertices.extend(tuples)
            counts = UsdGeom.Mesh(prim).GetFaceVertexCountsAttr().Get() or []
            triangle_count += sum(max(int(count) - 2, 0) for count in counts)
        if prim.GetTypeName() == "Material":
            material_names.append(prim.GetName())
        if prim.HasAPI(UsdPhysics.ArticulationRootAPI):
            articulated = True
        if prim.IsA(UsdPhysics.Joint):
            articulated = True
            joints.append({"name": prim.GetName(), "type": prim.GetTypeName()})
        for attribute in prim.GetAttributes():
            name = attribute.GetName().casefold()
            if "diffuse" in name or "basecolor" in name:
                channels["base_color"] += 1
            if "normal" in name:
                channels["normal"] += 1
            if "roughness" in name:
                channels["roughness"] += 1
            if "metallic" in name:
                channels["metallic"] += 1
            try:
                value = attribute.Get()
            except Exception:
                continue
            for asset_path in _asset_paths(value):
                if not asset_path or asset_path.startswith(("http://", "https://")):
                    continue
                candidate = (path.parent / asset_path).resolve()
                dependencies.append(str(candidate))
                if not candidate.is_file():
                    missing.append(str(candidate))
    raw = np.asarray(vertices, dtype=float)
    if raw.ndim != 2 or raw.shape[1] != 3 or len(raw) < 3 or triangle_count < 1:
        raise ValueError("usd_has_no_triangle_geometry")
    if not np.isfinite(raw).all():
        raise ValueError("non_finite_geometry")
    source_min = raw.min(axis=0) * meters_per_unit
    source_max = raw.max(axis=0) * meters_per_unit
    canonical = (rotation @ (raw * meters_per_unit).T).T
    collision = None
    if collision_vertices:
        collision_raw = np.asarray(collision_vertices, dtype=float)
        collision = (rotation @ (collision_raw * meters_per_unit).T).T
    inferred = [] if observed_orientation else ["native_orientation"]
    if collision is None:
        inferred.append("collision_footprint_polygon_m")
    return GeometryEvidence(
        vertices=canonical,
        collision_vertices=collision,
        triangle_count=triangle_count,
        material_count=len(material_names),
        pbr_channels=PbrChannels(
            base_color=bool(channels["base_color"] or material_names),
            normal=bool(channels["normal"]),
            roughness=bool(channels["roughness"]),
            metallic=bool(channels["metallic"]),
        ),
        material_names=material_names,
        texture_dependencies=sorted(set(dependencies)),
        missing_dependencies=sorted(set(missing)),
        format_extensions=[],
        loader_compatibility={"pxr_usd": "verified"},
        native_up=native_up,
        native_front=native_front,
        native_to_meter_scale=meters_per_unit,
        canonical_transform=_transform_matrix(rotation, meters_per_unit),
        source_bbox_min_m=(
            float(source_min[0]),
            float(source_min[1]),
            float(source_min[2]),
        ),
        source_bbox_max_m=(
            float(source_max[0]),
            float(source_max[1]),
            float(source_max[2]),
        ),
        articulated=articulated,
        movable_parts=joints,
        explicit_collision=collision is not None,
        inferred=inferred,
    )


def _sdf_geometry(path: Path, record: AssetRecord) -> GeometryEvidence:
    root = ET.parse(path).getroot()
    uri = root.findtext(".//mesh/uri")
    if uri:
        normalized = uri.removeprefix("file://")
        candidate = Path(normalized)
        if not candidate.is_absolute():
            candidate = (path.parent / candidate).resolve()
        if not candidate.is_file():
            raise ValueError(f"sdf_missing_mesh:{candidate}")
        if candidate.suffix.casefold() in {".usd", ".usda", ".usdc", ".usdz"}:
            with _USD_INSPECTION_LOCK:
                evidence = _usd_geometry(candidate, record)
        else:
            evidence = _mesh_geometry(candidate, record)
        evidence.texture_dependencies = sorted(
            set([*evidence.texture_dependencies, str(candidate)])
        )
        return evidence
    raise ValueError("sdf_has_no_supported_mesh_geometry")


def load_geometry_evidence(path: Path, record: AssetRecord) -> GeometryEvidence:
    suffix = path.suffix.casefold()
    if suffix in {".glb", ".gltf", ".obj", ".fbx"}:
        return _mesh_geometry(path, record)
    if suffix in {".usd", ".usda", ".usdc", ".usdz"}:
        with _USD_INSPECTION_LOCK:
            return _usd_geometry(path, record)
    if suffix == ".sdf":
        return _sdf_geometry(path, record)
    raise ValueError(f"unsupported_geometry_format:{suffix or 'none'}")


def _polygon(points: Any, *, minimum_thickness_m: float = 0.005) -> Polygon:
    import numpy as np

    values = np.asarray(points, dtype=float)
    if values.ndim != 2 or values.shape[1] != 2 or len(values) < 1:
        raise ValueError("footprint_has_no_points")
    if len(values) > 100_000:
        stride = max(1, len(values) // 100_000)
        extrema = values[
            np.unique(
                np.concatenate(
                    [
                        np.argmin(values, axis=0),
                        np.argmax(values, axis=0),
                        np.arange(0, len(values), stride),
                    ]
                )
            )
        ]
        values = extrema
    geometry = MultiPoint(values).convex_hull
    if isinstance(geometry, Polygon) and geometry.area > 1.0e-10:
        return geometry
    return geometry.buffer(minimum_thickness_m / 2.0, cap_style="square").convex_hull


def _points(polygon: Polygon) -> list[Point2]:
    return [(round(float(x), 6), round(float(y), 6)) for x, y in polygon.exterior.coords[:-1]]


def _clearances(category: str, visual: Polygon, height: float) -> list[OperationalClearance]:
    min_x, min_y, max_x, max_y = visual.bounds
    width = max_x - min_x
    result: list[OperationalClearance] = []
    if category in {"cabinet", "chest of drawers", "refrigerator", "wardrobe"}:
        polygon = box(min_x - 0.05, max_y, max_x + 0.05, max_y + min(0.9, max(0.45, width)))
        result.append(
            OperationalClearance(
                clearance_id="front_opening",
                operation="open doors or drawers",
                polygon_m=_points(polygon),
                height_range_m=(0.0, max(height, 0.1)),
                source="inferred",
                confidence=0.72,
            )
        )
    elif category in {"chair", "office chair"}:
        polygon = box(min_x - 0.08, min_y - 0.75, max_x + 0.08, min_y)
        result.append(
            OperationalClearance(
                clearance_id="chair_pull_out",
                operation="pull chair out and sit",
                polygon_m=_points(polygon),
                height_range_m=(0.0, max(height, 0.1)),
                source="inferred",
                confidence=0.78,
            )
        )
    elif category == "armchair":
        polygon = box(min_x - 0.05, max_y, max_x + 0.05, max_y + 0.45)
        result.append(
            OperationalClearance(
                clearance_id="reading_approach",
                operation="approach and sit",
                polygon_m=_points(polygon),
                height_range_m=(0.0, max(height, 0.1)),
                source="inferred",
                confidence=0.70,
            )
        )
    return result


def _support_semantics(category: str) -> tuple[str, str]:
    if category in {"picture", "wall art", "mirror", "wall lamp"}:
        return "wall", "required"
    if category in {"ceiling lamp", "ceiling light"}:
        return "ceiling", "none"
    if category in {
        "book",
        "bottle",
        "bowl",
        "cup",
        "mug",
        "vase",
        "target object",
    }:
        return "surface", "none"
    if category in {"bookcase", "cabinet", "chest of drawers", "desk", "shelf", "television"}:
        return "floor", "preferred"
    return "floor", "none"


def _obb(visual: Polygon, minimum_z: float, maximum_z: float) -> OrientedBoundingBox:
    rectangle = visual.minimum_rotated_rectangle
    coordinates = list(rectangle.exterior.coords)[:-1]
    lengths = [math.dist(coordinates[index], coordinates[(index + 1) % 4]) for index in range(4)]
    longest = max(range(4), key=lengths.__getitem__)
    first = coordinates[longest]
    second = coordinates[(longest + 1) % 4]
    yaw = math.degrees(math.atan2(second[1] - first[1], second[0] - first[0]))
    width = lengths[longest]
    depth = lengths[(longest + 1) % 4]
    center = rectangle.centroid
    return OrientedBoundingBox(
        center_m=(float(center.x), float(center.y), (minimum_z + maximum_z) / 2.0),
        size_m=(float(width), float(depth), float(maximum_z - minimum_z)),
        yaw_deg=float(((yaw + 180.0) % 360.0) - 180.0),
        footprint_polygon_m=_points(rectangle),
    )


def _semantic_tags(record: AssetRecord, category: str, semantic: HssdSemantic | None) -> list[str]:
    values = set(_words(" ".join([record.display_name, record.category, *record.tags])))
    values.update(_words(category))
    if semantic and semantic.pickable:
        values.add("pickable")
    if record.admission_status != AdmissionStatus.ACTIVE:
        values.add("newly_released")
    return sorted(values)


def _tag_subset(text: str, candidates: Iterable[str]) -> list[str]:
    normalized = " ".join(_words(text))
    return sorted(candidate for candidate in candidates if candidate in normalized)


def _quality(
    evidence: GeometryEvidence,
    *,
    collision_explicit: bool,
    support_observed: bool,
) -> AssetQuality:
    geometry = 55 + min(25, int(math.log10(max(10, evidence.triangle_count)) * 8))
    geometry += 10 if collision_explicit else 0
    geometry += 5 if support_observed else 0
    geometry = min(100, geometry)
    material_channels = sum(bool(value) for value in evidence.pbr_channels.model_dump().values())
    materials = min(100, 35 + material_channels * 10 + min(15, evidence.material_count * 3))
    realism = min(100, round(0.55 * geometry + 0.45 * materials))
    overall = round(0.45 * geometry + 0.35 * materials + 0.20 * realism)
    return AssetQuality(
        geometry=geometry,
        materials=materials,
        realism=realism,
        overall=overall,
    )


def _project(vertices: Any, view: str) -> Any:
    import numpy as np

    if view == "top":
        return vertices[:, [0, 1]]
    if view == "front":
        return vertices[:, [0, 2]]
    if view == "side":
        return vertices[:, [1, 2]]
    matrix = np.array([[0.86, -0.50, 0.0], [0.24, 0.42, 0.82]], dtype=float)
    return vertices @ matrix.T


def _render_view(path: Path, vertices: Any, view: str, size: int, label: str) -> None:
    import numpy as np

    projected = _project(vertices, view)
    polygon = _polygon(projected, minimum_thickness_m=0.001)
    coordinates = np.asarray(polygon.exterior.coords[:-1], dtype=float)
    minimum = coordinates.min(axis=0)
    maximum = coordinates.max(axis=0)
    span = np.maximum(maximum - minimum, 1.0e-6)
    margin = max(12, size // 12)
    usable = size - 2 * margin
    scale = min(usable / span[0], usable / span[1])
    pixels = [
        (
            margin + float((point[0] - minimum[0]) * scale),
            size - margin - float((point[1] - minimum[1]) * scale),
        )
        for point in coordinates
    ]
    image = Image.new("RGB", (size, size), (247, 244, 236))
    draw = ImageDraw.Draw(image)
    draw.rounded_rectangle((4, 4, size - 5, size - 5), radius=9, outline=(185, 177, 160), width=2)
    draw.polygon(pixels, fill=(91, 121, 112), outline=(26, 55, 52))
    draw.line([*pixels, pixels[0]], fill=(26, 55, 52), width=max(1, size // 96))
    draw.text((margin, 7), f"{label[:22]} · {view}", fill=(39, 48, 45))
    path.parent.mkdir(parents=True, exist_ok=True)
    # Identical assets can be inspected concurrently before deduplication.
    # A per-thread temporary name prevents the two renderers from racing on
    # the same shared-content view path.
    temporary = path.with_suffix(path.suffix + f".{os.getpid()}.{threading.get_ident()}.tmp")
    image.save(temporary, format="PNG", optimize=True)
    temporary.replace(path)


def render_multiviews(
    output_root: Path, sha256: str, vertices: Any, label: str
) -> tuple[str, list[str]]:
    directory = output_root / "views" / sha256[:2] / sha256
    thumbnail = directory / "thumbnail.png"
    view_paths = [directory / f"{view}.png" for view in ("front", "side", "top", "perspective")]
    if not thumbnail.is_file():
        _render_view(thumbnail, vertices, "perspective", 128, label)
    for view_path, view in zip(view_paths, ("front", "side", "top", "perspective"), strict=True):
        if not view_path.is_file():
            _render_view(view_path, vertices, view, 256, label)
    return str(thumbnail.resolve()), [str(path.resolve()) for path in view_paths]


def _minimal_quarantine(record: AssetRecord, path: Path, reason: str) -> AssetDescriptor:
    synthetic_hash = hashlib.sha256(
        (record.content_hash or f"{record.asset_id}\0{path}").encode("utf-8")
    ).hexdigest()
    return AssetDescriptor(
        asset_id=record.asset_id,
        source=record.source or "unknown",
        source_license=record.source_license or "unknown",
        source_path=str(path),
        canonical_path=str(path),
        sha256=synthetic_hash,
        category=_clean_category(record.normalized_category or record.category),
        display_name=record.display_name or record.asset_id,
        canonical_transform=(
            1.0,
            0.0,
            0.0,
            0.0,
            0.0,
            1.0,
            0.0,
            0.0,
            0.0,
            0.0,
            1.0,
            0.0,
            0.0,
            0.0,
            0.0,
            1.0,
        ),
        native_bbox_m=(0.0, 0.0, 0.0),
        source_bbox_min_m=(0.0, 0.0, 0.0),
        source_bbox_max_m=(0.0, 0.0, 0.0),
        quality=AssetQuality(geometry=0, materials=0, realism=0, overall=0),
        geometry_format=path.suffix.casefold().lstrip("."),
        loader_compatibility={},
        status="QUARANTINED",
        status_reason=reason[:1000],
        inferred_fields=["sha256"] if not path.is_file() else [],
        confidence={"status": 1.0},
    )


def inspect_record(
    record: AssetRecord,
    *,
    output_root: Path,
    metadata: ReleaseMetadata,
    render_views: bool,
) -> AssetDescriptor:
    path = Path(record.usd_path)
    normalized_path = path.as_posix().casefold()
    if record.source.casefold().endswith("artvip") and "/resource/" in normalized_path:
        return _minimal_quarantine(
            record,
            path,
            "artvip_internal_resource_component:not_a_primary_scene_asset",
        )
    if record.asset_kind in NON_GEOMETRY_KINDS:
        return _minimal_quarantine(record, path, "non_3d_asset_kind")
    if not path.is_file():
        return _minimal_quarantine(record, path, "missing_runtime_path")
    if path.suffix.casefold() not in SUPPORTED_GEOMETRY_EXTENSIONS:
        return _minimal_quarantine(record, path, f"unsupported_geometry_format:{path.suffix}")
    if not record.source_license.strip() or record.source_license.casefold() in {
        "unknown",
        "not permitted",
        "prohibited",
    }:
        return _minimal_quarantine(record, path, "source_license_not_permitted")
    try:
        evidence = load_geometry_evidence(path, record)
    except _MissingAssetDependencies as error:
        return _minimal_quarantine(
            record,
            path,
            "missing_material_or_texture_dependencies:" + "|".join(error.paths[:8]),
        )
    except Exception as error:
        reason = f"geometry_load_failed:{type(error).__name__}:{error}"
        return _minimal_quarantine(record, path, reason)
    import numpy as np

    hssd_id = _hssd_id(record, path)
    semantic = metadata.hssd_semantics.get(hssd_id or "")
    category = _record_category(record, semantic)
    if category == "chair" and any(
        token in " ".join(_words(record.display_name))
        for token in ("armchair", "accent chair", "easy chair")
    ):
        category = "armchair"
    if category == "table" and any(
        phrase in " ".join(_words(record.display_name)) for phrase in ("side table", "end table")
    ):
        category = "side table"
    vertices = np.asarray(evidence.vertices, dtype=float)
    # Thin wall-mounted art is frequently authored flat in HSSD even though
    # its semantic mounting direction is vertical.  Rotate the longest plane
    # dimension into canonical Z while retaining a thin wall-normal footprint.
    preliminary_dimensions = vertices.max(axis=0) - vertices.min(axis=0)
    if category in {"picture", "painting", "wall art", "mirror"} and (
        preliminary_dimensions[2] < max(preliminary_dimensions[0], preliminary_dimensions[1]) * 0.20
    ):
        if preliminary_dimensions[1] >= preliminary_dimensions[0]:
            repair = np.array(((1.0, 0.0, 0.0), (0.0, 0.0, -1.0), (0.0, 1.0, 0.0)))
        else:
            repair = np.array(((0.0, 1.0, 0.0), (0.0, 0.0, 1.0), (1.0, 0.0, 0.0)))
        vertices = (repair @ vertices.T).T
        if evidence.collision_vertices is not None:
            evidence.collision_vertices = (
                repair @ np.asarray(evidence.collision_vertices, dtype=float).T
            ).T
        transform = np.asarray(evidence.canonical_transform, dtype=float).reshape(4, 4)
        transform[:3, :3] = repair @ transform[:3, :3]
        evidence.canonical_transform = tuple(float(value) for value in transform.reshape(-1))
        evidence.inferred.append("semantic_wall_mount_orientation_repair")
    minimum = vertices.min(axis=0)
    maximum = vertices.max(axis=0)
    dimensions = maximum - minimum
    if not np.isfinite(dimensions).all() or any(float(value) <= 1.0e-5 for value in dimensions):
        return _minimal_quarantine(record, path, f"invalid_dimensions:{dimensions.tolist()}")
    if float(dimensions.max()) > 15.0 or float(dimensions.min()) < 1.0e-5:
        return _minimal_quarantine(record, path, f"abnormal_dimensions_m:{dimensions.tolist()}")
    if evidence.missing_dependencies:
        return _minimal_quarantine(
            record,
            path,
            "missing_material_or_texture_dependencies:"
            + "|".join(evidence.missing_dependencies[:8]),
        )
    visual = _polygon(vertices[:, :2])
    if evidence.collision_vertices is not None:
        collision = _polygon(np.asarray(evidence.collision_vertices)[:, :2])
        collision_source = "explicit"
    else:
        collision = visual.buffer(0.002, join_style="mitre")
        collision_source = "visual_conservative"
        evidence.inferred.append("collision_footprint_polygon_m")
    ground_band = max(0.004, min(0.03, float(dimensions[2]) * 0.025))
    ground_points = vertices[vertices[:, 2] <= minimum[2] + ground_band, :2]
    support_observed = len(ground_points) >= 3
    if support_observed:
        support = _polygon(ground_points)
    else:
        support = collision.buffer(-min(0.005, math.sqrt(collision.area) * 0.02))
        if support.is_empty or not isinstance(support, Polygon):
            support = collision
        evidence.inferred.append("support_footprint_polygon_m")
    clearances = _clearances(category, visual, float(dimensions[2]))
    envelope_parts = [visual, collision, *[Polygon(item.polygon_m) for item in clearances]]
    envelope = unary_union(envelope_parts).convex_hull
    if not isinstance(envelope, Polygon):
        envelope = collision
    asset_sha = _sha256_file(path)
    front_axis_override = metadata.front_axis_overrides.get(record.asset_id)
    if front_axis_override and asset_sha != front_axis_override.asset_sha256:
        return _minimal_quarantine(
            record,
            path,
            "front_axis_override_sha256_mismatch:"
            f"expected={front_axis_override.asset_sha256}:observed={asset_sha}",
        )
    if render_views:
        thumbnail, multiview = render_multiviews(
            output_root, asset_sha, vertices, record.display_name
        )
    else:
        placeholder_dir = output_root / "views" / asset_sha[:2] / asset_sha
        thumbnail = str((placeholder_dir / "thumbnail.png").resolve())
        multiview = [
            str((placeholder_dir / f"{view}.png").resolve())
            for view in ("front", "side", "top", "perspective")
        ]
    text = " ".join([record.display_name, record.description, record.category, *record.tags])
    material_text = " ".join([text, *evidence.material_names])
    support_type, wall_affinity = _support_semantics(category)
    affordances = sorted(
        set(
            [*record.affordances, *metadata.affordances_by_category.get(category, [])]
            + (["pick up and carry"] if semantic and semantic.pickable else [])
        )
    )
    synonyms = sorted(set([*record.synonyms, *CATEGORY_SYNONYMS.get(category, ())]))
    articulated = bool(evidence.articulated or (semantic and semantic.articulated))
    quality = _quality(
        evidence,
        collision_explicit=evidence.explicit_collision,
        support_observed=support_observed,
    )
    geometry_signature = _sha256_json(
        {
            "category": category,
            "dimensions_5cm": [round(float(value) / 0.05) for value in dimensions],
            "triangles_log2": round(math.log2(max(1, evidence.triangle_count))),
            "materials": min(8, evidence.material_count),
        }
    )[:24]
    observed = {
        "sha256",
        "native_bbox_m",
        "visual_footprint_polygon_m",
        "pbr_channels",
        "geometry_counts",
        "texture_dependencies",
        "format_extensions",
    }
    if evidence.explicit_collision:
        observed.add("collision_footprint_polygon_m")
    if support_observed:
        observed.add("support_footprint_polygon_m")
    if "native_orientation" not in evidence.inferred:
        observed.update({"native_up_vector", "native_front_vector"})
    inferred = set(evidence.inferred)
    inferred.update(
        {
            "category",
            "synonyms",
            "style_tags",
            "color_tags",
            "material_tags",
            "support_type",
            "wall_affinity",
            "operational_clearance",
            "layout_reserve_envelope_polygon_m",
            "quality",
            "loader_compatibility",
        }
    )
    confidence = {
        "geometry": 1.0,
        "units": 1.0 if hssd_id or path.suffix.casefold().startswith(".usd") else 0.9,
        "orientation": 1.0 if "native_orientation" not in inferred else 0.65,
        "category": 0.98 if semantic and semantic.category else 0.78,
        "collision": 1.0 if evidence.explicit_collision else 0.72,
        "support_footprint": 0.95 if support_observed else 0.65,
        "operational_clearance": 0.72 if clearances else 0.60,
        "quality": 0.85,
        "loader_compatibility": 0.95,
    }
    descriptor = AssetDescriptor(
        asset_id=record.asset_id,
        source=record.source,
        source_license=record.source_license,
        source_path=str(path.resolve()),
        canonical_path=str(path.resolve()),
        sha256=asset_sha,
        category=category,
        subcategory=record.category,
        display_name=semantic.name if semantic and semantic.name else record.display_name,
        semantic_tags=_semantic_tags(record, category, semantic),
        synonyms=synonyms,
        style_tags=_tag_subset(text, STYLE_WORDS),
        color_tags=_tag_subset(text, COLOR_WORDS),
        material_tags=_tag_subset(material_text, MATERIAL_WORDS),
        pbr_channels=evidence.pbr_channels,
        native_units="meter",
        native_to_meter_scale=evidence.native_to_meter_scale,
        native_up_vector=evidence.native_up,
        native_front_vector=evidence.native_front,
        canonical_transform=evidence.canonical_transform,
        native_bbox_m=(
            round(float(dimensions[0]), 6),
            round(float(dimensions[1]), 6),
            round(float(dimensions[2]), 6),
        ),
        source_bbox_min_m=evidence.source_bbox_min_m,
        source_bbox_max_m=evidence.source_bbox_max_m,
        visual_footprint_polygon_m=_points(visual),
        collision_footprint_polygon_m=_points(collision),
        support_footprint_polygon_m=_points(support),
        layout_reserve_envelope_polygon_m=_points(envelope),
        obb_m=_obb(visual, float(minimum[2]), float(maximum[2])),
        height_m=round(float(dimensions[2]), 6),
        support_type=support_type,  # type: ignore[arg-type]
        wall_affinity=wall_affinity,  # type: ignore[arg-type]
        articulated=articulated,
        movable_parts=evidence.movable_parts,
        operational_clearance=clearances,
        affordances=affordances,
        uniform_scale_range=(1.0, 1.0) if articulated else (0.9, 1.1),
        quality=quality,
        thumbnail=thumbnail,
        multiview_images=multiview,
        geometry_format=path.suffix.casefold().lstrip("."),
        format_extensions=evidence.format_extensions,
        loader_compatibility=evidence.loader_compatibility,  # type: ignore[arg-type]
        vertex_count=int(len(vertices)),
        triangle_count=evidence.triangle_count,
        material_count=evidence.material_count,
        collision_source=collision_source,  # type: ignore[arg-type]
        texture_dependencies=evidence.texture_dependencies,
        missing_dependencies=[],
        geometry_signature=geometry_signature,
        status="ACTIVE",
        status_reason="",
        observed_fields=sorted(observed - inferred),
        inferred_fields=sorted(inferred),
        confidence=confidence,
    )
    return certify_descriptor_front_axis(descriptor, front_axis_override)


def _resolve_duplicates(descriptors: list[AssetDescriptor]) -> list[AssetDescriptor]:
    by_hash: dict[str, list[int]] = defaultdict(list)
    for index, descriptor in enumerate(descriptors):
        if descriptor.status == "ACTIVE":
            by_hash[descriptor.sha256].append(index)
    for indices in by_hash.values():
        if len(indices) < 2:
            continue
        canonical_index = max(
            indices,
            key=lambda index: (
                descriptors[index].quality.overall,
                bool(descriptors[index].collision_source == "explicit"),
                descriptors[index].asset_id,
            ),
        )
        canonical_id = descriptors[canonical_index].asset_id
        for index in indices:
            if index == canonical_index:
                continue
            value = descriptors[index].model_dump(mode="json")
            value.update(
                status="QUARANTINED",
                status_reason=f"duplicate_content:{canonical_id}",
                canonical_asset_id=canonical_id,
            )
            descriptors[index] = AssetDescriptor.model_validate(value)
    by_signature: dict[str, list[int]] = defaultdict(list)
    for index, descriptor in enumerate(descriptors):
        if descriptor.status == "ACTIVE" and descriptor.geometry_signature:
            by_signature[descriptor.geometry_signature].append(index)
    for indices in by_signature.values():
        if len(indices) < 2:
            continue
        ids = [descriptors[index].asset_id for index in indices]
        for index in indices:
            value = descriptors[index].model_dump(mode="json")
            value["near_duplicate_asset_ids"] = [
                asset_id for asset_id in ids if asset_id != descriptors[index].asset_id
            ][:64]
            descriptors[index] = AssetDescriptor.model_validate(value)
    return descriptors


def _write_descriptor_index(descriptors: Sequence[AssetDescriptor], path: Path) -> None:
    temporary = path.with_suffix(path.suffix + ".tmp")
    temporary.unlink(missing_ok=True)
    connection = sqlite3.connect(temporary)
    try:
        connection.executescript(
            """
            PRAGMA journal_mode=OFF;
            PRAGMA synchronous=OFF;
            CREATE TABLE asset_descriptors (
                asset_id TEXT PRIMARY KEY,
                asset_sha256 TEXT NOT NULL,
                source TEXT NOT NULL,
                category TEXT NOT NULL,
                support_type TEXT NOT NULL,
                quality_overall INTEGER NOT NULL,
                status TEXT NOT NULL,
                status_reason TEXT NOT NULL,
                canonical_path TEXT NOT NULL,
                descriptor_json TEXT NOT NULL
            );
            CREATE INDEX descriptor_status_category ON asset_descriptors(status, category);
            CREATE INDEX descriptor_sha256 ON asset_descriptors(asset_sha256);
            CREATE VIRTUAL TABLE active_descriptor_fts USING fts5(
                asset_id, display_name, category, semantic_tags, synonyms,
                style_tags, color_tags, material_tags, affordances, content=''
            );
            """
        )
        for row_id, descriptor in enumerate(descriptors, start=1):
            connection.execute(
                "INSERT INTO asset_descriptors VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                (
                    descriptor.asset_id,
                    descriptor.sha256,
                    descriptor.source,
                    descriptor.category,
                    descriptor.support_type,
                    descriptor.quality.overall,
                    descriptor.status,
                    descriptor.status_reason,
                    descriptor.canonical_path,
                    descriptor.model_dump_json(),
                ),
            )
            if descriptor.status == "ACTIVE":
                connection.execute(
                    "INSERT INTO active_descriptor_fts("
                    "rowid, asset_id, display_name, category, semantic_tags, synonyms, "
                    "style_tags, color_tags, material_tags, affordances"
                    ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                    (
                        row_id,
                        descriptor.asset_id,
                        descriptor.display_name,
                        descriptor.category,
                        " ".join(descriptor.semantic_tags),
                        " ".join(descriptor.synonyms),
                        " ".join(descriptor.style_tags),
                        " ".join(descriptor.color_tags),
                        " ".join(descriptor.material_tags),
                        " ".join(descriptor.affordances),
                    ),
                )
        connection.commit()
    finally:
        connection.close()
    temporary.replace(path)


def _jsonl(path: Path, descriptors: Iterable[AssetDescriptor]) -> None:
    temporary = path.with_suffix(path.suffix + ".tmp")
    with temporary.open("w", encoding="utf-8") as handle:
        for descriptor in descriptors:
            handle.write(descriptor.model_dump_json() + "\n")
    temporary.replace(path)


def _inventory_roots(roots: Sequence[Path], indexed_paths: set[Path]) -> dict[str, Any]:
    output: dict[str, Any] = {}
    for root in roots:
        resolved = root.resolve()
        if not resolved.exists():
            output[str(resolved)] = {
                "exists": False,
                "geometry_files": 0,
                "indexed_primary_files": 0,
            }
            continue
        extensions = Counter[str]()
        geometry_files = 0
        indexed = 0
        for path in resolved.rglob("*"):
            if not path.is_file() or path.suffix.casefold() not in SUPPORTED_GEOMETRY_EXTENSIONS:
                continue
            geometry_files += 1
            extensions[path.suffix.casefold()] += 1
            try:
                if path.resolve() in indexed_paths:
                    indexed += 1
            except OSError:
                pass
        output[str(resolved)] = {
            "exists": True,
            "geometry_files": geometry_files,
            "indexed_primary_files": indexed,
            "unindexed_or_auxiliary_geometry_files": geometry_files - indexed,
            "by_extension": dict(sorted(extensions.items())),
        }
    return output


def _inspect_record_safely(
    record: AssetRecord,
    *,
    output_root: Path,
    metadata: ReleaseMetadata,
    render_views: bool,
) -> AssetDescriptor:
    try:
        return inspect_record(
            record,
            output_root=output_root,
            metadata=metadata,
            render_views=render_views,
        )
    except Exception as error:  # defensive per-asset isolation
        details = "".join(traceback.format_exception_only(type(error), error)).strip()
        return _minimal_quarantine(
            record,
            Path(record.usd_path),
            f"inspection_internal_error:{details}",
        )


def _initialize_inspection_process(
    output_root: Path,
    metadata: ReleaseMetadata,
    render_views: bool,
) -> None:
    global _PROCESS_METADATA, _PROCESS_OUTPUT_ROOT, _PROCESS_RENDER_VIEWS
    _PROCESS_OUTPUT_ROOT = output_root
    _PROCESS_METADATA = metadata
    _PROCESS_RENDER_VIEWS = render_views


def _inspect_record_in_process(record: AssetRecord) -> AssetDescriptor:
    if _PROCESS_OUTPUT_ROOT is None or _PROCESS_METADATA is None:
        raise RuntimeError("asset inspection process was not initialized")
    return _inspect_record_safely(
        record,
        output_root=_PROCESS_OUTPUT_ROOT,
        metadata=_PROCESS_METADATA,
        render_views=_PROCESS_RENDER_VIEWS,
    )


def release_catalog(
    catalog_path: Path,
    output_root: Path,
    *,
    hssd_root: Path | None = None,
    front_axis_overrides_path: Path | None = None,
    scan_roots: Sequence[Path] = (),
    workers: int = 4,
    inspection_backend: str = "process",
    render_views: bool = True,
    maximum_records: int | None = None,
) -> dict[str, Any]:
    started = time.perf_counter()
    output_root.mkdir(parents=True, exist_ok=False)
    catalog = AssetCatalog.model_validate_json(catalog_path.read_text(encoding="utf-8"))
    records = catalog.assets[:maximum_records] if maximum_records is not None else catalog.assets
    metadata = load_release_metadata(hssd_root, front_axis_overrides_path)
    stage_started = time.perf_counter()

    if inspection_backend not in {"process", "thread"}:
        raise ValueError("inspection_backend must be 'process' or 'thread'")
    descriptors: list[AssetDescriptor] = []
    worker_count = max(1, workers)
    executor_context: ProcessPoolExecutor | ThreadPoolExecutor
    if inspection_backend == "process":
        executor_context = ProcessPoolExecutor(
            max_workers=worker_count,
            initializer=_initialize_inspection_process,
            initargs=(output_root, metadata, render_views),
        )
        descriptor_iterator = executor_context.map(
            _inspect_record_in_process,
            records,
            chunksize=1,
        )
    else:
        executor_context = ThreadPoolExecutor(max_workers=worker_count)
        descriptor_iterator = executor_context.map(
            lambda record: _inspect_record_safely(
                record,
                output_root=output_root,
                metadata=metadata,
                render_views=render_views,
            ),
            records,
        )
    with executor_context:
        for index, descriptor in enumerate(descriptor_iterator, start=1):
            descriptors.append(descriptor)
            if index == len(records) or index % 250 == 0:
                active_so_far = sum(item.status == "ACTIVE" for item in descriptors)
                print(
                    f"asset-release progress={index}/{len(records)} "
                    f"loadable={active_so_far} quarantined={index - active_so_far}",
                    flush=True,
                )
    inspection_duration = time.perf_counter() - stage_started
    dedupe_started = time.perf_counter()
    descriptors = _resolve_duplicates(descriptors)
    descriptors.sort(key=lambda descriptor: descriptor.asset_id)
    dedupe_duration = time.perf_counter() - dedupe_started
    active = [descriptor for descriptor in descriptors if descriptor.status == "ACTIVE"]
    quarantined = [descriptor for descriptor in descriptors if descriptor.status == "QUARANTINED"]
    _jsonl(output_root / "asset_descriptors.jsonl", descriptors)
    _jsonl(output_root / "quarantine.jsonl", quarantined)
    _write_descriptor_index(descriptors, output_root / "asset_descriptor_index.sqlite3")
    before_active = [
        record for record in records if record.admission_status == AdmissionStatus.ACTIVE
    ]
    before_categories = Counter(
        (record.normalized_category or normalize_category(record.category))
        for record in before_active
    )
    after_categories = Counter(descriptor.category for descriptor in active)
    reasons = Counter(descriptor.status_reason.split(":", 1)[0] for descriptor in quarantined)
    indexed_paths = {
        Path(record.usd_path).resolve() for record in records if Path(record.usd_path).is_file()
    }
    inventory_started = time.perf_counter()
    inventory = _inventory_roots(scan_roots, indexed_paths)
    inventory_duration = time.perf_counter() - inventory_started
    report: dict[str, Any] = {
        "schema_version": "2.0",
        "truth_policy": (
            "ACTIVE only after file, loader, triangle, units, orientation, dimensions, "
            "dependency and footprint checks"
        ),
        "source_catalog": str(catalog_path.resolve()),
        "output_root": str(output_root.resolve()),
        "inspection_backend": inspection_backend,
        "inspection_workers": worker_count,
        "front_axis_overrides": {
            "path": (
                str(front_axis_overrides_path.resolve()) if front_axis_overrides_path else None
            ),
            "configured": len(metadata.front_axis_overrides),
            "applied_active": sum(
                descriptor.front_axis_source in {"multiview_verified", "manual_override"}
                for descriptor in active
            ),
        },
        "before": {
            "catalog_records": len(records),
            "active_records": len(before_active),
            "active_3d_records": sum(
                record.asset_kind not in NON_GEOMETRY_KINDS for record in before_active
            ),
            "active_category_count": len(before_categories),
            "active_by_category": dict(before_categories.most_common()),
        },
        "after": {
            "descriptor_records": len(descriptors),
            "active_records": len(active),
            "quarantined_records": len(quarantined),
            "active_category_count": len(after_categories),
            "active_by_category": dict(after_categories.most_common()),
            "active_by_source": dict(Counter(item.source for item in active).most_common()),
            "quarantine_reasons": dict(reasons.most_common()),
            "exact_duplicate_quarantines": sum(
                item.status_reason.startswith("duplicate_content:") for item in quarantined
            ),
            "near_duplicate_members": sum(bool(item.near_duplicate_asset_ids) for item in active),
        },
        "source_inventory": inventory,
        "durations_s": {
            "inspection_and_views": round(inspection_duration, 3),
            "deduplication": round(dedupe_duration, 3),
            "source_inventory": round(inventory_duration, 3),
            "total": round(time.perf_counter() - started, 3),
        },
        "files": {},
    }
    for path in (
        output_root / "asset_descriptors.jsonl",
        output_root / "quarantine.jsonl",
        output_root / "asset_descriptor_index.sqlite3",
    ):
        report["files"][path.name] = {"path": str(path.resolve()), "sha256": _sha256_file(path)}
    atomic_write_text(
        output_root / "asset_release_report.json",
        json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
    )
    manifest: dict[str, Any] = {
        "schema_version": "2.0",
        "descriptor_schema": "packages.asset_registry.descriptors.AssetDescriptor/2.0",
        "active_records": len(active),
        "quarantined_records": len(quarantined),
        "active_by_kind": {"OBJECT_OR_ROOM": len(active)},
        "active_by_category": dict(after_categories.most_common()),
        "files": {
            **report["files"],
            "asset_release_report.json": {
                "path": str((output_root / "asset_release_report.json").resolve()),
                "sha256": _sha256_file(output_root / "asset_release_report.json"),
            },
        },
        "old_indexes_preserved": True,
    }
    atomic_write_text(
        output_root / "asset_index_manifest.json",
        json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
    )
    return report


def load_active_descriptors(
    index_path: Path,
    asset_ids: Sequence[str] = (),
    *,
    categories: Sequence[str] = (),
) -> list[AssetDescriptor]:
    uri = f"file:{index_path.resolve()}?mode=ro&immutable=1"
    connection = sqlite3.connect(uri, uri=True)
    try:
        clauses = ["status='ACTIVE'"]
        parameters: list[str] = []
        if asset_ids:
            placeholders = ",".join("?" for _ in asset_ids)
            clauses.append(f"asset_id IN ({placeholders})")
            parameters.extend(asset_ids)
        if categories:
            normalized_categories = sorted({_clean_category(item) for item in categories})
            placeholders = ",".join("?" for _ in normalized_categories)
            clauses.append(f"category IN ({placeholders})")
            parameters.extend(normalized_categories)
        rows = connection.execute(
            "SELECT descriptor_json FROM asset_descriptors WHERE "
            + " AND ".join(clauses)
            + " ORDER BY asset_id",
            tuple(parameters),
        ).fetchall()
    finally:
        connection.close()
    return [AssetDescriptor.model_validate_json(row[0]) for row in rows]


def search_active_descriptors(
    index_path: Path,
    *,
    query: str,
    category: str | None = None,
    limit: int = 20,
) -> list[AssetDescriptor]:
    uri = f"file:{index_path.resolve()}?mode=ro&immutable=1"
    connection = sqlite3.connect(uri, uri=True)
    connection.row_factory = sqlite3.Row
    try:
        terms = list(dict.fromkeys(_words(query)))
        expression = " OR ".join(f'"{term}"' for term in terms)
        if expression:
            row_ids = [
                int(row[0])
                for row in connection.execute(
                    "SELECT rowid FROM active_descriptor_fts "
                    "WHERE active_descriptor_fts MATCH ? LIMIT ?",
                    (expression, max(limit * 10, 100)),
                )
            ]
        else:
            row_ids = []
        clauses = ["status='ACTIVE'"]
        parameters: list[Any] = []
        if category:
            clauses.append("category=?")
            parameters.append(_clean_category(category))
        if row_ids:
            clauses.append(f"rowid IN ({','.join('?' for _ in row_ids)})")
            parameters.extend(row_ids)
        rows = connection.execute(
            "SELECT descriptor_json FROM asset_descriptors WHERE "
            + " AND ".join(clauses)
            + " ORDER BY quality_overall DESC, asset_id LIMIT ?",
            (*parameters, limit),
        ).fetchall()
    finally:
        connection.close()
    return [AssetDescriptor.model_validate_json(row[0]) for row in rows]