File size: 57,923 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
870b85a
 
 
 
3f15e9f
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
 
 
 
 
 
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
870b85a
 
 
 
 
 
 
 
 
3f15e9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
 
870b85a
 
 
 
 
 
 
 
 
3f15e9f
 
870b85a
 
 
 
 
 
 
 
3f15e9f
 
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
870b85a
 
 
 
 
 
 
3f15e9f
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
870b85a
 
 
 
 
 
3f15e9f
 
 
 
870b85a
 
 
 
 
 
 
 
 
 
 
 
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
"""Fresh saved-scene geometry gates. No dynamics or robot qualification."""
from __future__ import annotations

import hashlib
import copy
import itertools
import json
import math
from pathlib import Path
import sys
import time

if __package__:
    from . import floor_cover_contacts, support_contract, saved_mesh_seams
    from .support_contract import resolve_support_contract, wall_gap_accepted, WALL_GAP_RANGE_M, WALL_GAP_ACCEPTANCE
    from .saved_mesh_seams import measure_seam
else:
    import floor_cover_contacts, support_contract, saved_mesh_seams
    from support_contract import resolve_support_contract, wall_gap_accepted, WALL_GAP_RANGE_M, WALL_GAP_ACCEPTANCE
    from saved_mesh_seams import measure_seam

BASE = Path(__file__).resolve().parent
SCHEMA = 'rhg.generation-geometry.v1'
VALIDATOR_REVISION = 'xyz-seam-floor-cover-proof-v2.6'
_HELPER_MODULES = {'floor_cover_contacts.py': floor_cover_contacts,
                   'support_contract.py': support_contract,
                   'saved_mesh_seams.py': saved_mesh_seams}
# Pin all initial helper bytes without loading the NumPy-dependent contact
# module in the stdlib-only supervisor. Actual geometry imports it below.
_HELPER_IMPORT_SHA256 = {name: hashlib.sha256((BASE/name).read_bytes()).hexdigest()
                       for name in (*_HELPER_MODULES, 'triangle_contacts.py')}


def implementation_identity():
    """Identify the actual root validator file used by this interpreter."""
    path = Path(__file__).resolve()
    helpers = {}
    for name, initial_sha in _HELPER_IMPORT_SHA256.items():
        expected = BASE/name
        module = _HELPER_MODULES.get(name)
        if name == 'triangle_contacts.py':
            module = sys.modules.get((__package__ + '.' if __package__ else '') + 'triangle_contacts')
        actual_file = getattr(module, '__file__', None) if module is not None else str(expected)
        if not isinstance(actual_file, str) or Path(actual_file).resolve() != expected:
            raise ValueError('Geometry helper import is from another workspace: ' + name)
        helper = Path(actual_file).resolve()
        digest = _file_sha256(helper)
        if digest != initial_sha:
            raise ValueError('Geometry helper import is stale or from another workspace: ' + str(helper))
        helpers[helper.name] = digest
    return dict(module_path=str(path), sha256=_file_sha256(path),
                revision=VALIDATOR_REVISION, helper_sha256=helpers)


def fingerprint(value):
    return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':'),
                                     allow_nan=False).encode()).hexdigest()


def solid_backend():
    try:
        import manifold3d
    except ImportError:
        sys.path.insert(0, str(BASE / 'vendor'))
        import manifold3d
    return manifold3d


def settings(config):
    value = config.get('geometry_validation')
    if value is None:
        return None
    if not isinstance(value, dict) or set(value) - {
            'enabled', 'blender', 'timeout_s', 'contact_tolerance_m',
            'penetration_tolerance_m'}:
        raise ValueError('Invalid geometry_validation settings')
    if type(value.get('enabled', True)) is not bool:
        raise ValueError('geometry_validation.enabled must be boolean')
    _tolerance(value)
    _penetration_tolerance(value)
    if 'timeout_s' in value and (type(value['timeout_s']) not in (int, float)
            or not math.isfinite(value['timeout_s']) or value['timeout_s'] <= 0):
        raise ValueError('geometry_validation.timeout_s must be finite and positive')
    return value if value.get('enabled', True) else None


def _tolerance(value):
    tolerance = value.get('contact_tolerance_m', 1e-5)
    if (type(tolerance) not in (int, float) or not math.isfinite(tolerance)
            or not 0 < tolerance <= 1e-4):
        raise ValueError('contact_tolerance_m must be in (0, 0.0001]')
    return tolerance


def _penetration_tolerance(value):
    tolerance = value.get('penetration_tolerance_m', _tolerance(value))
    if (type(tolerance) not in (int, float) or not 0 < tolerance <= .005
            or not math.isfinite(tolerance)):
        raise ValueError('penetration_tolerance_m must be in (0, 0.005]')
    return tolerance


def _mesh(mesh, backend, np):
    vertices = np.asarray(mesh['vertices'], dtype=np.float64)
    raw = mesh['triangles']
    if (vertices.ndim != 2 or vertices.shape[1] != 3 or not len(vertices)
            or not np.isfinite(vertices).all() or not isinstance(raw, list) or not raw
            or any(not isinstance(row, list) or len(row) != 3 or any(
                type(i) is not int or not 0 <= i < len(vertices) for i in row) for row in raw)):
        raise ValueError('Malformed physical mesh: ' + str(mesh.get('name')))
    triangles = np.asarray(raw, dtype=np.uint64)
    # Join exact duplicate positions only, preserving the saved surface geometry.
    unique, inverse = np.unique(vertices, axis=0, return_inverse=True)
    mapped = inverse[triangles]
    if np.any((mapped[:, 0] == mapped[:, 1]) | (mapped[:, 1] == mapped[:, 2]) |
              (mapped[:, 2] == mapped[:, 0])):
        return vertices, triangles, None
    faces = unique[mapped]
    if np.any(np.all(np.cross(faces[:, 1]-faces[:, 0], faces[:, 2]-faces[:, 0]) == 0,
                     axis=1)):
        return vertices, triangles, None
    edges = np.concatenate((mapped[:, [0, 1]], mapped[:, [1, 2]], mapped[:, [2, 0]]))
    _, edge_ids, counts = np.unique(np.sort(edges, axis=1), axis=0,
                                    return_inverse=True, return_counts=True)
    winding = np.bincount(edge_ids, weights=np.where(edges[:, 0] < edges[:, 1], 1, -1))
    # Invalid saved surfaces can crash the native constructor on Linux.
    if np.any(counts != 2) or np.any(winding != 0):
        return vertices, triangles, None
    native = backend.Mesh64(np.ascontiguousarray(unique),
                            np.ascontiguousarray(mapped, dtype=np.uint64))
    solid = backend.Manifold(native)
    if solid.status() != backend.Error.NoError or solid.is_empty() or solid.volume() <= 0:
        return vertices, triangles, None
    return vertices, triangles, solid


def _cap_boundary_loops(vertices, triangles, np):
    """Close simple boundary loops of an open surface with centroid fans.

    Returns (vertices, triangles) or None when the boundary is not a set of
    simple, consistently oriented loops (the caller then uses a convex hull).
    """
    unique, inverse = np.unique(np.asarray(vertices, dtype=np.float64), axis=0, return_inverse=True)
    faces = inverse.reshape(-1)[np.asarray(triangles, dtype=np.int64)]
    directed = np.concatenate((faces[:, [0, 1]], faces[:, [1, 2]], faces[:, [2, 0]])).tolist()
    keys = set(map(tuple, directed))
    boundary = [(a, b) for a, b in directed if (b, a) not in keys]
    if not boundary or len(boundary) > 50000 or len(set(boundary)) != len(boundary):
        return None
    following = {}
    for a, b in boundary:
        if a in following:
            return None
        following[a] = b
    new_vertices, new_faces, seen = list(unique), faces.tolist(), set()
    for start in list(following):
        if start in seen:
            continue
        loop, v = [], start
        while v not in seen:
            seen.add(v)
            loop.append(v)
            v = following.get(v)
            if v is None:
                return None
        if v != start or len(loop) < 3:
            return None
        center = len(new_vertices)
        new_vertices.append(unique[loop].mean(axis=0))
        # The cap uses the reversed boundary edge so every edge is shared by
        # exactly two faces with opposite orientation.
        new_faces.extend([following[a], a, center] for a in loop)
    return np.asarray(new_vertices), np.asarray(new_faces, dtype=np.int64)


def _hull(points, backend, np):
    """Convex hull of points; a 1 mm slab for (near-)planar points. (solid, planar)"""
    points = np.unique(np.asarray(points, dtype=np.float64), axis=0)
    if len(points) < 3:
        return None, False
    if len(points) >= 4:
        hull = backend.Manifold.hull_points(points)
        if hull.status() == backend.Error.NoError and not hull.is_empty() and hull.volume() > 1e-12:
            return hull, False
    normal = np.linalg.svd(points - points.mean(axis=0), full_matrices=False)[2][-1]
    hull = backend.Manifold.hull_points(np.concatenate((points + 5e-4 * normal, points - 5e-4 * normal)))
    if hull.status() == backend.Error.NoError and not hull.is_empty() and hull.volume() > 0:
        return hull, True
    return None, False


def _components(vertices, triangles, np):
    """Vertex groups of the connected components of a triangle surface."""
    unique, inverse = np.unique(np.asarray(vertices, dtype=np.float64), axis=0, return_inverse=True)
    faces = inverse.reshape(-1)[np.asarray(triangles, dtype=np.int64)]
    parent = np.arange(len(unique))

    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    for a, b, c in faces.tolist():
        for p, q in ((a, b), (b, c)):
            rp, rq = find(p), find(q)
            if rp != rq:
                parent[rp] = rq
    roots = np.asarray([find(i) for i in range(len(unique))])
    return [unique[roots == r] for r in np.unique(roots)]


def _proxy_solid(item, backend, np, max_components=256):
    """Closed collision proxy for one open saved part.

    1. Cap its boundary loops into a closed surface.
    2. Else, if it has several disconnected components (e.g. four legs saved as
       one object), the union of each component's convex hull, so the space
       between legs stays free.
    3. Else the part's own convex hull (a 1 mm slab if planar).
    Never a hull of the whole entity.
    """
    capped = _cap_boundary_loops(item['vertices'], item['triangles'], np)
    if capped is not None:
        _, _, solid = _mesh(dict(name=item['name'], vertices=capped[0].tolist(),
                                 triangles=capped[1].tolist()), backend, np)
        if solid is not None:
            return solid, 'repaired_boundary_caps'
    components = _components(item['vertices'], item['triangles'], np)
    if 1 < len(components) <= max_components:
        hulls = [h for h, _ in (_hull(points, backend, np) for points in components) if h is not None]
        if hulls:
            union = backend.Manifold.batch_boolean(hulls, backend.OpType.Add)
            if union.status() == backend.Error.NoError and not union.is_empty() and union.volume() > 0:
                return union, 'component_convex_hulls'
    hull, planar = _hull(item['vertices'], backend, np)
    if hull is None:
        return None, None
    return hull, 'planar_part_convex_hull_1mm' if planar else 'part_convex_hull'


def _flat_region(meshes, z, band, *, upward):
    import numpy as np
    from shapely.geometry import Polygon
    from shapely.ops import unary_union
    polygons = []
    for mesh in meshes:
        values = mesh['vertices'][mesh['triangles']]
        normal = np.cross(values[:,1]-values[:,0], values[:,2]-values[:,0])[:,2]
        selected = (np.max(abs(values[:,:,2]-z), axis=1) <= band) & (
            normal > 1e-12 if upward else normal < -1e-12)
        polygons.extend(Polygon(triangle[:,:2]) for triangle in values[selected])
    return unary_union(polygons)


def _wall_contact(meshes, targets, anchor, tolerance, expected_gap=0.):
    import numpy as np
    directions = {'E': (1.,0.,0.), 'W': (-1.,0.,0.),
                  'N': (0.,1.,0.), 'S': (0.,-1.,0.)}
    if anchor not in directions:
        raise ValueError('Unsupported declared wall direction: ' + str(anchor))
    direction = np.asarray(directions[anchor])
    points = np.concatenate([item['vertices'] for item in meshes])
    plane = float((points @ direction).max())
    samples = {tuple(p) for p in points if abs(float(p @ direction)-plane) <= 1e-7}
    for item in meshes:
        for triangle in item['vertices'][item['triangles']]:
            if np.max(abs(triangle @ direction-plane)) <= 1e-7:
                samples.add(tuple(triangle.mean(axis=0)))
    axis = 0 if direction[0] else 1
    extent = max(direction[axis]*target.bounding_box()[axis+(3 if direction[axis]>0 else 0)]
                 for target in targets)
    gaps = []
    for value in sorted(samples):
        point = np.asarray(value)
        start = point-direction*tolerance*2
        end = point+direction*max(1., extent-plane+1.)
        hits = [hit for target in targets for hit in target.ray_cast(tuple(start), tuple(end))
                if np.dot(hit.normal, direction) < -.5]
        gaps.append(None if not hits else min(float(np.dot(np.asarray(hit.position)-point,
                                                          direction)) for hit in hits))
    return dict(passed=bool(gaps) and all(wall_gap_accepted(g) for g in gaps),
                gaps_m=gaps, sample_count=len(gaps), wall_anchor=anchor,
                expected_gap_m=expected_gap,
                accepted_gap_range_m=list(WALL_GAP_RANGE_M), gap_acceptance=WALL_GAP_ACCEPTANCE,
                nominal_gap_match=bool(gaps) and all(g is not None and abs(g-expected_gap)<=tolerance for g in gaps),
                method='declared_wall_direction_back_surface_rays')


def _triangle_contact(meshes, targets, direction, tolerance, **kwargs):
    if __package__:
        from .triangle_contacts import ray_contact
    else:
        from triangle_contacts import ray_contact
    return ray_contact(meshes, targets, direction, tolerance, **kwargs)


def _pending_contact(row, contract, fields, pair_checks):
    """Exclude only unresolved inset sink installation, retaining all unknowns."""
    identifier = row['entity_id']
    contact = dict(entity_id=identifier, support_entity_id=contract['support_entity_id'],
        support_type=contract['support_type'], passed=None, complete=False,
        status='pending', pending_fields=list(fields))
    sink = (str(row.get('role', '')).lower() == 'sink' or
            not row.get('role') and row.get('layout_slot_id') == 'kitchen_sink')
    unavailable = {'support_parent:' + identifier, 'installation_evidence:' + identifier,
                   'support_entity_geometry:' + identifier, 'support_geometry:' + identifier}
    collision = any(p['passed'] is False and identifier in (p['left'], p['right'])
                    for p in pair_checks)
    if (sink and contract['support_type'] == 'inset' and fields
            and set(fields) <= unavailable
            and set(fields) != {'installation_evidence:' + identifier} and not collision):
        contact.update(status='skipped', reason='asset_installation_evidence_incomplete',
                       scope='inset_sink_installation_support_contact_only')
    return contact


def collision_mesh_partitions(manifest, payload, *, resolver=None):
    """Authenticate structural subsets against the original, freshly hashed source."""
    if resolver is None:
        def resolver(row):
            qualification = row.get('collision_qualification') or {}
            if qualification.get('representation') != 'source_frame_nodes':
                return None
            import importlib.util
            path = BASE/'source/scripts/internal/scene_generation/real_assets/collision_frame_identity.py'
            spec = importlib.util.spec_from_file_location('_saved_collision_identity', path)
            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)
            return module.resolve_frame_identity(row)
    entities = {row['entity_id']: row for row in manifest['entities']}
    proofs = payload.get('collision_representations', {})
    if not isinstance(proofs, dict) or set(proofs)-set(entities):
        raise ValueError('Unknown saved collision representation')
    partitions = {}
    names = [mesh['name'] for mesh in payload['meshes']]
    if len(names) != len(set(names)):
        raise ValueError('Duplicate saved mesh names')
    for identifier, row in entities.items():
        meshes = [mesh for mesh in payload['meshes'] if mesh.get('entity_id') == identifier]
        expected = resolver(row)
        if expected is None:
            if identifier in proofs or any(mesh.get('collision_role') == 'visual_only' for mesh in meshes):
                raise ValueError('Unqualified collision subset: '+identifier)
            partitions[identifier] = {mesh['name'] for mesh in meshes}
            continue
        proof = proofs.get(identifier)
        if not isinstance(proof, dict) or any(proof.get(key) != value for key, value in expected.items()):
            raise ValueError('Stale source collision identity: '+identifier)
        structural, visual = proof.get('structural_mesh_names'), proof.get('visual_mesh_names')
        if (not isinstance(structural, list) or not structural or not isinstance(visual, list)
                or len(structural) != len(set(structural)) or len(visual) != len(set(visual))
                or set(structural) & set(visual)
                or set(structural) | set(visual) != {mesh['name'] for mesh in meshes}):
            raise ValueError('Incomplete saved collision partition: '+identifier)
        frames = set(expected['frame_node_indices'])
        source_nodes = set(expected['all_source_mesh_node_indices'])
        observed = set()
        for mesh in meshes:
            node = mesh.get('source_node_index')
            role = 'structural' if mesh['name'] in structural else 'visual_only'
            if (type(node) is not int or node not in source_nodes
                    or mesh.get('collision_role') != role or (node in frames) != (role == 'structural')):
                raise ValueError('Saved collision mesh identity differs: '+mesh['name'])
            observed.add(node)
        if observed != source_nodes or len(observed) != len(meshes):
            raise ValueError('Missing original source mesh node: '+identifier)
        partitions[identifier] = set(structural)
    return partitions


def audit_meshes(manifest, payload, options):
    """Check closed saved solids, exact solid overlap and sampled support contact.

    An open entity part that cannot be exactly joined into a closed surface gets
    a recorded collision proxy: its boundary loops capped, else its own convex
    hull (readbacks[...]['collision_proxies']). Parts with no valid proxy stay
    pending. Contact tolerance applies to support gaps, not a blanket penetration waiver.
    """
    import numpy as np
    tolerance = _tolerance(options)
    penetration_tolerance = _penetration_tolerance(options)
    backend = solid_backend()
    if payload.get('world_vertices') is not True:
        raise ValueError('Saved geometry requires world-space mesh vertices')
    rows = manifest['entities']
    entities = {row['entity_id']: row for row in rows}
    if not entities or len(entities) != len(rows):
        raise ValueError('Geometry requires a complete unique entity inventory')
    partitions = collision_mesh_partitions(manifest, payload)
    groups = {eid: [] for eid in entities}
    shell, pending, diagnostics, readbacks = [], [], [], {}
    evidence_inputs = {}
    contracts = {eid: resolve_support_contract(row, entities, payload=payload,
                    inputs=evidence_inputs) for eid, row in entities.items()}
    for mesh in payload['meshes']:
        vertices, triangles, solid = _mesh(mesh, backend, np)
        identifier = mesh.get('entity_id')
        if identifier is not None and identifier not in groups:
            raise ValueError('Unknown physical mesh entity: ' + str(identifier))
        item = dict(name=mesh['name'], vertices=vertices, triangles=triangles,
                    solid=solid, low=vertices.min(axis=0), high=vertices.max(axis=0))
        (shell if identifier is None else groups[identifier]).append(item)
        if solid is None and identifier is None:
            pending.append('non_solid_mesh:' + mesh['name'])
    solids = {}
    for identifier, meshes in groups.items():
        if not meshes:
            raise ValueError('Missing saved mesh entity: ' + identifier)
        points = np.concatenate([m['vertices'] for m in meshes])
        bbox = [points.min(axis=0).tolist(), points.max(axis=0).tolist()]
        row = entities[identifier]
        if 'world_bbox_m' in row:
            expected = np.asarray(row['world_bbox_m'])
            if expected.shape != (2, 3) or not np.allclose(expected, bbox, rtol=0, atol=1e-6):
                raise ValueError('Stale saved world bbox: ' + identifier)
        readbacks[identifier] = dict(world_bbox_m=bbox,
            center_xy_m=list(row.get('actual_center_xy_m') or row['center_xy_m']),
            yaw_deg=row['yaw_deg'], base_z_m=bbox[0][2], dimensions_m=row['dimensions_m'],
            joined_surface_meshes=[])
        collision_meshes = [item for item in meshes if item['name'] in partitions[identifier]]
        if identifier in payload.get('collision_representations', {}):
            readbacks[identifier]['collision_representation'] = payload['collision_representations'][identifier]
        valid = [item['solid'] for item in collision_meshes if item['solid'] is not None]
        parts = [item for item in collision_meshes if item['solid'] is None]
        if parts:
            # Material splits can partition one closed surface across objects.
            # Reuse all original faces; exact welding adds no caps or thickness.
            triangles, offset = [], 0
            for item in parts:
                triangles.append(item['triangles'] + offset)
                offset += len(item['vertices'])
            _, _, joined = _mesh(dict(name=identifier,
                vertices=np.concatenate([item['vertices'] for item in parts]).tolist(),
                triangles=np.concatenate(triangles).tolist()), backend, np)
            if joined is None:
                # Per open part: capped closed surface, else that part's own
                # convex hull. Record the proxy; unresolvable parts stay pending.
                proxies, unresolved = [], []
                for item in parts:
                    proxy, kind = _proxy_solid(item, backend, np)
                    if proxy is None:
                        unresolved.append(item['name'])
                    else:
                        valid.append(proxy)
                        proxies.append(dict(mesh=item['name'], proxy=kind))
                readbacks[identifier]['collision_proxies'] = proxies
                if unresolved:
                    pending.extend('non_solid_mesh:' + name for name in unresolved)
                    continue
            else:
                valid.append(joined)
                readbacks[identifier]['joined_surface_meshes'] = [item['name'] for item in parts]
        solid = backend.Manifold.batch_boolean(valid, backend.OpType.Add)
        if solid.status() != backend.Error.NoError or solid.is_empty() or solid.volume() <= 0:
            pending.append('solid_union:' + identifier)
        else:
            solids[identifier] = solid
    pair_checks = []
    intersections = {}

    bounds = {eid: tuple(readbacks[eid]['world_bbox_m'][0]) +
                   tuple(readbacks[eid]['world_bbox_m'][1]) for eid in entities}

    def pair(left_id, left, right_id, right, a, b):
        check = dict(left=left_id, right=right_id)
        if any(min(a[i+3], b[i+3]) < max(a[i], b[i]) for i in range(3)):
            pair_checks.append(dict(check, complete=True, status='measured', passed=True,
                overlap_volume_m3=0., method='saved_mesh_aabb_separation'))
            return
        if left is None or right is None:
            pair_checks.append(dict(check, complete=False, status='pending', passed=None,
                method='solid_geometry_unavailable'))
            return
        overlap = left ^ right
        if overlap.status() != backend.Error.NoError:
            pending.append('solid_intersection:' + left_id + ':' + right_id)
            pair_checks.append(dict(check, complete=False, status='pending', passed=None,
                method='manifold3d_solid_intersection'))
            return
        volume = overlap.volume()
        if not math.isfinite(volume) or volume < -1e-15:
            raise ValueError('Invalid solid intersection volume')
        # Judge interpenetration by equivalent penetration depth, not raw volume:
        # for a thin overlap sliver of contact area A and depth d, V = A*d and
        # its surface is ~2A, so d ~= 2V/S. A large flush contact with float
        # roundoff may leave a thin sliver. Penetration has its own tolerance;
        # support and wall gaps continue to use contact_tolerance_m.
        area = overlap.surface_area() if volume > 1e-15 else 0.
        if not math.isfinite(area) or area < 0:
            raise ValueError('Invalid solid intersection surface area')
        if volume <= 1e-15:
            depth, illegal = 0., False
        elif area <= 0:
            depth, illegal = None, True  # degenerate measurement: never waive
        else:
            depth = 2. * volume / area
            illegal = depth > penetration_tolerance
        check.update(overlap_volume_m3=volume, overlap_equivalent_depth_m=depth,
                     penetration_tolerance_m=penetration_tolerance,
                     passed=not illegal, complete=True, status='measured',
                     method='manifold3d_solid_intersection')
        if illegal and depth is not None:
            lift = min(1e-6, penetration_tolerance / 10.)
            # Shell geometry stays fixed, even when its bbox bottom is higher.
            # translate returns a new manifold; saved solids/contact rays stay put.
            lift_left = (not left_id.startswith('shell:') and
                         (right_id.startswith('shell:') or a[2] >= b[2]))
            lifted = (left.translate((0., 0., lift)) ^ right if lift_left else
                      left ^ right.translate((0., 0., lift)))
            if lifted.status() == backend.Error.NoError:
                lifted_volume = lifted.volume()
                if math.isfinite(lifted_volume) and lifted_volume >= -1e-15:
                    lifted_area = lifted.surface_area() if lifted_volume > 1e-15 else 0.
                    lifted_depth = None
                    if lifted_volume <= 1e-15:
                        lifted_depth = 0.
                    elif math.isfinite(lifted_area) and lifted_area > 0:
                        lifted_depth = 2. * lifted_volume / lifted_area
                    if lifted_depth is not None and lifted_depth <= penetration_tolerance:
                        illegal = False
                        # Existing overlap fields retain the pre-probe measurement.
                        check.update(passed=True,
                            method='manifold3d_solid_intersection_lift_probe',
                            lift_probe_m=lift,
                            lift_probe_entity_id=left_id if lift_left else right_id,
                            lift_probe_overlap_volume_m3=lifted_volume,
                            lift_probe_overlap_equivalent_depth_m=lifted_depth)
        pair_checks.append(check)
        if illegal:
            intersections[left_id, right_id] = overlap

    for a, b in itertools.combinations(entities, 2):
        pair(a, solids.get(a), b, solids.get(b), bounds[a], bounds[b])
    for identifier in entities:
        for item in shell:
            pair(identifier, solids.get(identifier), 'shell:' + item['name'], item['solid'],
                 bounds[identifier], tuple(item['low']) + tuple(item['high']))
    contacts = []
    for identifier, row in entities.items():
        contract = contracts[identifier]
        parent = contract['support_entity_id']
        kind = contract['support_type']
        contact_pending = list(contract['pending_fields'])
        if not groups[identifier] or (kind == 'inset' and identifier not in solids):
            contact_pending.append('support_entity_geometry:' + identifier)
        if contact_pending:
            pending.extend(contact_pending)
            contacts.append(_pending_contact(row, contract, contact_pending, pair_checks))
            continue
        target_meshes = groups[parent] if parent else shell
        targets = ([solids[parent]] if parent in solids else [] if parent else
                   [item['solid'] for item in shell if item['solid'] is not None])
        mounted, inset = kind == 'wall', kind == 'inset'
        if mounted:
            names = contract.get('target_mesh_names')
            target_meshes = [s for s in shell if names is None or s['name'] in names]
            targets = [s['solid'] for s in target_meshes if s['solid'] is not None]
            if names is not None and len(target_meshes) != len(names):
                target_meshes = []
        if not target_meshes or (inset and not targets):
            field = ('installation_geometry:' if mounted else 'support_geometry:') + identifier
            pending.append(field)
            contacts.append(_pending_contact(row, contract, [field], pair_checks))
            continue
        footprint_diagnostic = None
        raw_contact = (not inset and (mounted or identifier not in solids
                       or any(item['solid'] is None for item in target_meshes)))
        if mounted:
            if __package__:
                from .triangle_contacts import wall_face_targets
            else:
                from triangle_contacts import wall_face_targets
            try:
                target_meshes, wall_target = wall_face_targets(row, manifest, target_meshes,
                    target_mesh_names=contract.get('target_mesh_names'))
            except ValueError as error:
                field = 'installation_wall_target:' + identifier
                pending.append(field)
                contacts.append(dict(entity_id=identifier, support_entity_id=parent,
                    support_type=kind, passed=None, complete=False, status='pending',
                    pending_fields=[field], target_error=str(error)))
                continue
            direction = {'E': (1., 0., 0.), 'W': (-1., 0., 0.),
                         'N': (0., 1., 0.), 'S': (0., -1., 0.)}[row['wall_anchor']]
            contact = _triangle_contact(groups[identifier], target_meshes, direction,
                tolerance, expected_gap=contract['expected_gap_m'], gap_range=WALL_GAP_RANGE_M,
                target_regions=wall_target['regions'] or None)
            contact.update(ray_method=contact['method'],
                method='declared_wall_direction_back_surface_rays', wall_target=wall_target,
                passed=bool(contact['gaps_m']) and all(wall_gap_accepted(g) for g in contact['gaps_m']),
                wall_anchor=row['wall_anchor'], expected_gap_m=contract['expected_gap_m'],
                accepted_gap_range_m=list(WALL_GAP_RANGE_M), gap_acceptance=WALL_GAP_ACCEPTANCE,
                nominal_gap_match=bool(contact['gaps_m']) and all(g is not None and
                    abs(g-contract['expected_gap_m']) <= tolerance for g in contact['gaps_m']))
            contact.update(entity_id=identifier, support_entity_id=parent)
            for key in ('target_mesh_names', 'installation_evidence'):
                if key in contract:
                    contact[key] = contract[key]
            passed = contact['passed']
        elif inset:
            gap = min(target.min_gap(solids[identifier], tolerance * 2) for target in targets)
            passed = gap <= tolerance
            contact = dict(entity_id=identifier, support_entity_id=parent, passed=passed,
                           gap_m=gap, method='declared_installation_surface_distance')
        else:
            low = readbacks[identifier]['world_bbox_m'][0][2]
            samples = set()
            contact_samples = set()
            for item in groups[identifier]:
                for p in item['vertices']:
                    if abs(p[2]-low) <= 1e-7:
                        samples.add((float(p[0]), float(p[1])))
                        contact_samples.add(tuple(float(value) for value in p))
                for tri in item['vertices'][item['triangles']]:
                    if np.max(abs(tri[:, 2]-low)) <= 1e-7:
                        center = tri.mean(axis=0)
                        samples.add((float(center[0]), float(center[1])))
                        contact_samples.add(tuple(float(value) for value in center))
            if raw_contact:
                contact = _triangle_contact(groups[identifier], target_meshes, (0., 0., -1.),
                    tolerance, gap_range=(0., tolerance),
                    **({'target_selection': 'nearest_contact_plane'} if parent is None else
                       {'ray_origin': 'contact_plane'}))
                contact.update(entity_id=identifier, support_entity_id=parent)
                passed = contact['passed']
            else:
                gaps = []
                endpoint = min(target.bounding_box()[2] for target in targets) - 1.
                for x, y, z in sorted(contact_samples):
                    hits = [hit for target in targets for hit in target.ray_cast(
                        (x, y, z+tolerance*2), (x, y, min(endpoint, z-1.)))
                            if hit.normal[2] > .5]
                    gaps.append(None if not hits else z-max(hit.position[2] for hit in hits))
                passed = bool(gaps) and all(g is not None and 0 <= g <= tolerance for g in gaps)
                contact = dict(entity_id=identifier, support_entity_id=parent, passed=passed,
                               gaps_m=gaps, sample_count=len(gaps), method='bottom_vertices_and_face_centroids')
            base = _flat_region(groups[identifier], low, 1e-7, upward=False)
            if not base.is_empty:
                support = _flat_region(target_meshes, low, tolerance,
                                       upward=True)
                missing_area = base.difference(support).area
                covered = missing_area <= max(1e-12, base.area*1e-10)
                contact.update(flat_contact_region_checked=True,
                    unsupported_area_m2=missing_area, support_coverage=1-missing_area/base.area)
                if not covered:
                    contact['passed'] = passed = False
                    seam_samples = (sorted(samples) if raw_contact else
                                    [(x, y) for x, y, z in sorted(contact_samples)])
                    seam = (measure_seam(row, entities.get(parent), base, target_meshes,
                        low, seam_samples, contact['gaps_m'], closed_child=identifier in solids,
                        tolerance=tolerance) if kind == 'surface' else None)
                    if seam is not None:
                        contact['seam_bridging'] = seam
                        contact['passed'] = passed = True
                    else:
                        footprint_diagnostic = dict(code='support_footprint_outside_region',
                            entity_ids=[identifier], message='Actual flat contact region extends over a hole or support edge',
                            unsupported_area_m2=missing_area, support_entity_id=parent)
        # A missing closed target is not proof of missing contact when an open
        # saved surface occupies the declared contact zone. Unrelated surfaces
        # do not suppress reliable local failures or passing contact evidence.
        uncertain_targets = []
        if not raw_contact and not passed and (parent is None or mounted):
            a = bounds[identifier]
            axis = {'E': 0, 'W': 0, 'N': 1, 'S': 1}.get(row.get('wall_anchor')) if mounted else 2
            plane = ((a[axis+3] if row['wall_anchor'] in ('E', 'N') else a[axis]) +
                     (1 if row['wall_anchor'] in ('E', 'N') else -1) * contract['expected_gap_m']
                     if mounted else a[2])
            contact_low = contact_high = plane
            if mounted:
                back = a[axis+3] if row['wall_anchor'] in ('E', 'N') else a[axis]
                far = back + (1 if row['wall_anchor'] in ('E', 'N') else -1) * WALL_GAP_RANGE_M[1]
                contact_low, contact_high = sorted((back, far))
            for item in shell:
                if item['solid'] is not None or (mounted and contract.get('target_mesh_names')
                        and item['name'] not in contract['target_mesh_names']):
                    continue
                if (item['low'][axis] <= contact_high+tolerance and item['high'][axis] >= contact_low-tolerance
                        and all(item['low'][i] <= a[i+3] and item['high'][i] >= a[i]
                                for i in range(3) if i != axis)):
                    uncertain_targets.append('support_target_geometry:' + identifier + ':' + item['name'])
        if uncertain_targets:
            pending.extend(uncertain_targets)
            contact.update(support_type=kind, complete=False, status='pending', passed=None,
                           pending_fields=uncertain_targets)
            contacts.append(contact)
            continue
        contact.update(support_type=kind, complete=True, status='measured', pending_fields=[])
        contacts.append(contact)
        if not passed:
            if footprint_diagnostic is not None:
                diagnostics.append(footprint_diagnostic)
            diagnostics.append(dict(code='support_contact_invalid', entity_ids=[identifier],
                message='Saved support contact is missing or outside the declared tolerance',
                support_entity_id=parent))
    permitted_contacts = []
    manifest_fingerprint = fingerprint(manifest)
    mesh_fingerprint = fingerprint(payload['meshes'])
    contact_by_id = {c['entity_id']: c for c in contacts}
    for check in pair_checks:
        if check['passed'] is not False:
            continue
        left, right = check['left'], check['right']
        certificate = None
        if left in entities and right in entities:
            certificate = floor_cover_contacts.measure_contact(left, right,
                intersections[left, right], entities=entities, groups=groups, shell=shell,
                solids=solids, contacts=contact_by_id, flat_region=_flat_region,
                manifest_fingerprint=manifest_fingerprint, mesh_fingerprint=mesh_fingerprint,
                scene_sha256=payload.get('source_blend_sha256'), evidence_inputs=evidence_inputs)
        if certificate is not None:
            permitted_contacts.append(certificate)
            check.update(passed=True, permitted_contact=True,
                         permitted_contact_certificate_id=certificate['certificate_id'])
        else:
            diagnostics.append(dict(code='collision', entity_ids=[eid for eid in
                (left, right) if eid in entities], message='Saved physical solids interpenetrate',
                collision_object=right, overlap_volume_m3=check['overlap_volume_m3']))
    skipped = [c for c in contacts if c['status'] == 'skipped']
    skipped_pending = list(dict.fromkeys(f for c in skipped for f in c['pending_fields']))
    full_pending = list(pending)
    pending = [f for f in pending if f not in set(skipped_pending)]
    entity_checks = {}
    for contact in contacts:
        identifier = contact['entity_id']
        pairs = [p for p in pair_checks if identifier in (p['left'], p['right'])]
        contact_skipped = contact['status'] == 'skipped'
        local_pending = [] if contact_skipped else list(contact['pending_fields'])
        if identifier not in solids:
            local_pending.append('solid_geometry:' + identifier)
        local_pending.extend('pair_geometry:' + p['left'] + ':' + p['right']
                             for p in pairs if not p['complete'])
        collision_complete = all(p['complete'] for p in pairs)
        collision_passed = (all(p['passed'] is True for p in pairs)
                            if collision_complete else None)
        full_complete = identifier in solids and contact['complete'] and collision_complete
        complete = identifier in solids and (contact['complete'] or contact_skipped) and collision_complete
        contact_gate_passed = contact_skipped or contact['passed'] is True
        entity_checks[identifier] = dict(solid_complete=identifier in solids,
            contact_complete=contact['complete'], contact_passed=contact['passed'],
            contact_skipped=contact_skipped, contact_gate_passed=contact_gate_passed,
            collision_complete=collision_complete, collision_passed=collision_passed,
            geometry_complete=complete, geometry_passed=complete and contact_gate_passed
            and collision_passed is True, pending_fields=local_pending,
            full_geometry_complete=full_complete,
            full_geometry_passed=full_complete and contact['passed'] is True and collision_passed is True,
            full_pending_fields=local_pending + (contact['pending_fields'] if contact_skipped else []),
            skipped_pending_fields=list(contact['pending_fields']) if contact_skipped else [])
    provenance = dict(scene_sha256=payload.get('source_blend_sha256'),
        source_runtime_sha256=payload.get('source_runtime_sha256'),
        manifest_fingerprint=manifest_fingerprint, mesh_fingerprint=mesh_fingerprint)
    return dict(complete=not pending, geometry_passed=not pending and not diagnostics,
        full_geometry_complete=not full_pending,
        full_geometry_passed=not full_pending and not diagnostics,
        full_scope_qualified=not full_pending and not diagnostics and not skipped,
        full_pending_fields=full_pending, skipped_pending_fields=skipped_pending,
        diagnostics=diagnostics, pending_fields=pending, entity_readbacks=readbacks,
        entity_checks=entity_checks, provenance=provenance, evidence_input_sha256=evidence_inputs,
        contact_checks=contacts, pair_checks=pair_checks, contact_tolerance_m=tolerance,
        permitted_floor_cover_contacts=permitted_contacts,
        skipped_checks=skipped, physical_qualified=False, whole_task_acceptance=False,
        validator_identity=implementation_identity(),
        acceptance_scope=dict(
            policy='skip_incomplete_inset_sink_installation_support', policy_enabled=True,
            excluded_contact_entity_ids=[c['entity_id'] for c in skipped],
            excluded_support_pending_fields=skipped_pending,
            complete=not pending, passed=not pending and not diagnostics,
            collision_pairs='all', geometry_unknowns='retained',
            permitted_contact_policy=floor_cover_contacts.POLICY_REVISION,
            all_other_support_checks='retained', whole_house_acceptance=False),
        collision_method='manifold3d_solid_intersection',
        scope='static_closed_solid_overlap_with_typed_common_floor_thin_cover_contact_and_saved_triangle_sampled_contact_excluding_declared_skipped_sink_support; no stability or dynamics')


class _AuditWorkerTimeout(TimeoutError):
    """Only a process receipt declaring timed_out permits an audit retry."""


def _audit_in_worker(manifest_path, mesh_path, options, output_dir, timeout_s):
    if __package__:
        from .process_control import execute_command
    else:
        from process_control import execute_command
    output = Path(output_dir)
    result_path = output / 'solid_audit.json'
    command = [sys.executable, '-X', 'faulthandler', '-B', str(Path(__file__).resolve()),
               '--audit-worker', '--manifest', str(manifest_path), '--meshes', str(mesh_path),
               '--output', str(result_path), '--contact-tolerance-m', str(_tolerance(options)),
               '--penetration-tolerance-m', str(_penetration_tolerance(options))]
    if timeout_s <= 0:
        raise TimeoutError('Saved solid audit deadline exhausted')
    expected_identity = implementation_identity()
    receipt = execute_command(command, BASE, output / 'solid_audit.log', timeout_s)
    receipt.update(expected_worker_identity=expected_identity, worker_identity=None,
                   worker_identity_verified=False)
    (output / 'solid_audit_receipt.json').write_text(
        json.dumps(receipt, indent=2, allow_nan=False)+'\n')
    if receipt.get('timed_out') and receipt.get('cleanup_passed') is True:
        raise _AuditWorkerTimeout('Saved solid audit worker timed out; inspect retained log/receipt')
    if (receipt.get('exit_code') != 0 or receipt.get('timed_out')
            or receipt.get('cleanup_passed') is not True or not result_path.is_file()):
        raise ValueError('Saved solid audit worker failed; inspect retained log/receipt')
    with result_path.open() as stream:
        result = json.load(stream)
    actual_identity = result.get('worker_identity') if isinstance(result, dict) else None
    identity_verified = (actual_identity == expected_identity
                         and implementation_identity() == expected_identity)
    receipt.update(worker_identity=actual_identity, worker_identity_verified=identity_verified)
    (output / 'solid_audit_receipt.json').write_text(
        json.dumps(receipt, indent=2, allow_nan=False)+'\n')
    if not identity_verified:
        raise ValueError('Saved solid audit worker identity mismatch; inspect retained receipt')
    if (not isinstance(result, dict) or type(result.get('complete')) is not bool
            or type(result.get('geometry_passed')) is not bool):
        raise ValueError('Saved solid audit worker failed to produce a valid result')
    return result


def validate_generated_scene(config, manifest_path, output_dir, *, timeout_s):
    """Export current saved Blender geometry and retain a hash-bound gate receipt."""
    if __package__:
        from .measurement_refresh import file_sha256, load_json
        from .real_test.measure_saved_scene import measure_saved_scene
    else:
        from measurement_refresh import file_sha256, load_json
        from real_test.measure_saved_scene import measure_saved_scene
    started = time.monotonic()
    options = settings(config)
    if options is None:
        raise ValueError('Saved geometry validation is not enabled')
    output = Path(output_dir).resolve()
    output.mkdir(parents=True, exist_ok=False)
    manifest_path = Path(manifest_path).resolve()
    manifest = load_json(manifest_path)
    scene_name = config.get('generation', {}).get('scene_output', manifest['scene_id'] + '.blend')
    scene = (manifest_path.parent / scene_name).resolve(strict=True)
    requirements = output / 'measurement_request.json'
    requirements.write_text('{}\n')
    pins = {str(path): file_sha256(path) for path in (manifest_path, scene, Path(__file__),
                                                     BASE / 'support_contract.py',
                                                     BASE / 'floor_cover_contacts.py',
                                                     BASE / 'saved_mesh_seams.py')}
    triangle_implementation = BASE / 'triangle_contacts.py'
    if triangle_implementation.is_file():
        pins[str(triangle_implementation)] = file_sha256(triangle_implementation)
    backend = solid_backend()
    pins[str(Path(backend.__file__).resolve())] = file_sha256(backend.__file__)
    budget = min(timeout_s, options.get('timeout_s', timeout_s))
    deadline = started + budget
    result = dict(schema=SCHEMA, status='failed', complete=False, geometry_passed=False,
        diagnostics=[], pending_fields=[], entity_readbacks={}, entity_checks={},
        contact_checks=[], pair_checks=[],
        skipped_checks=[], validator_identity=implementation_identity(), worker_identity=None,
        skipped_pending_fields=[], full_pending_fields=[], full_geometry_complete=False,
        full_geometry_passed=False, full_scope_qualified=False,
        manifest_sha256=pins[str(manifest_path)], scene_sha256=pins[str(scene)],
        manifest_fingerprint=fingerprint(manifest), physical_qualified=False,
        whole_task_acceptance=False, input_sha256=pins, inputs_unchanged=True)
    try:
        measured = measure_saved_scene(manifest_path, scene, output / 'mesh_evidence.json',
            source_root=BASE / 'source', requirements_path=requirements,
            blender=options.get('blender'), timeout_s=budget)
        pins.update(measured['input_sha256'])
        mesh_path = output / 'geometry/physical_meshes.json.gz'
        pins[str(mesh_path)] = file_sha256(mesh_path)
        audit_started = time.monotonic()
        try:
            audited = _audit_in_worker(manifest_path, mesh_path, options, output,
                                       deadline-audit_started)
        except _AuditWorkerTimeout:
            retry = dict(first_elapsed_s=time.monotonic()-audit_started,
                         second_elapsed_s=0., succeeded=False)
            result['timeout_retry'] = retry
            # execute_command creates logs exclusively. Retain attempt one and
            # discard its partial result before starting a fresh worker.
            for name in ('solid_audit.log', 'solid_audit_receipt.json', 'solid_audit.json'):
                path = output / name
                if path.exists():
                    path.rename(output / (path.stem + '.timeout-first' + path.suffix))
            retry_started = time.monotonic()
            deadline = retry_started + 2 * budget
            try:
                audited = _audit_in_worker(manifest_path, mesh_path, options, output, 2 * budget)
                retry['succeeded'] = True
            finally:
                retry['second_elapsed_s'] = time.monotonic()-retry_started
                receipt_path = output / 'solid_audit_receipt.json'
                if receipt_path.is_file():
                    receipt = load_json(receipt_path)
                    receipt['timeout_retry'] = retry
                    receipt_path.write_text(json.dumps(receipt, indent=2, allow_nan=False)+'\n')
        result.update(audited)
        if result.get('provenance', {}).get('scene_sha256') != pins[str(scene)]:
            raise ValueError('Solid audit export does not match the saved scene')
        if result['provenance'].get('mesh_sha256') != pins[str(mesh_path)]:
            raise ValueError('Solid audit export bytes changed')
        result['provenance'].update(scene_path=str(scene), mesh_path=str(mesh_path))
        pins.update(result.get('evidence_input_sha256', {}))
        pins[str(output / 'solid_audit.json')] = file_sha256(output / 'solid_audit.json')
        if time.monotonic() > deadline:
            raise TimeoutError('Saved geometry audit exceeded its budget')
        result['status'] = 'measured' if result['complete'] else 'pending'
    except Exception as error:
        result.update(status='failed', complete=False, geometry_passed=False,
                      error_type=type(error).__name__, error=str(error))
    result['inputs_unchanged'] = all(Path(p).is_file() and file_sha256(p) == sha
                                      for p, sha in pins.items())
    if not result['inputs_unchanged']:
        result.update(status='failed', complete=False, geometry_passed=False,
                      error='Geometry input changed during audit')
    result['elapsed_s'] = time.monotonic()-started
    result['result_path'] = str(output / 'result.json')
    Path(result['result_path']).write_text(json.dumps(result, indent=2, allow_nan=False)+'\n')
    return result


def evidence_matches(manifest, evidence):
    """Fresh evidence may prove preservation even when its layout needs repair."""
    return (isinstance(evidence, dict) and evidence.get('schema') == SCHEMA
        and evidence.get('status') == 'measured' and evidence.get('complete') is True
        and evidence.get('inputs_unchanged') is True
        and evidence.get('manifest_fingerprint') == fingerprint(manifest)
        and set(evidence.get('entity_readbacks', {})) == {
            row['entity_id'] for row in manifest['entities']}
        and all(evidence.get(k) is False for k in ('physical_qualified', 'whole_task_acceptance')))


def evidence_current(manifest, evidence):
    """Verify file-bound currency, permitting a partially measurable scene.

    This certifies provenance only. Consumers must inspect scoped completeness
    and pass flags; pending evidence never becomes a whole-house acceptance.
    """
    if not (isinstance(evidence, dict) and evidence.get('schema') == SCHEMA
            and evidence.get('status') in ('measured', 'pending')
            and evidence.get('inputs_unchanged') is True
            and evidence.get('manifest_fingerprint') == fingerprint(manifest)
            and all(evidence.get(k) is False for k in ('physical_qualified', 'whole_task_acceptance'))):
        return False
    pins, provenance = evidence.get('input_sha256'), evidence.get('provenance')
    if not isinstance(pins, dict) or not pins or not isinstance(provenance, dict):
        return False
    for path_key, hash_key in (('scene_path', 'scene_sha256'), ('mesh_path', 'mesh_sha256')):
        path, sha = provenance.get(path_key), provenance.get(hash_key)
        if (not isinstance(path, str) or not Path(path).is_absolute()
                or not isinstance(sha, str) or len(sha) != 64 or pins.get(path) != sha):
            return False
    if provenance['scene_sha256'] != evidence.get('scene_sha256'):
        return False
    try:
        return all(isinstance(path, str) and Path(path).is_absolute()
                   and isinstance(sha, str) and len(sha) == 64
                   and Path(path).is_file() and _file_sha256(path) == sha
                   for path, sha in pins.items())
    except OSError:
        return False


def scoped_evidence(manifest, evidence, entity_ids, *, include_pairs=True):
    """Return current local measurements, or None for a stale/unknown scope.

    Pair completeness and entity flags remain explicit. A reliable collision
    diagnostic or readback can therefore drive repair while other meshes are
    pending. The returned subset cannot be used as final preservation evidence.
    """
    if not evidence_current(manifest, evidence):
        return None
    if isinstance(entity_ids, str):
        entity_ids = [entity_ids]
    try:
        wanted = set(entity_ids)
    except TypeError:
        return None
    inventory = {r['entity_id'] for r in manifest['entities']}
    readbacks, checks = evidence.get('entity_readbacks', {}), evidence.get('entity_checks', {})
    if (not wanted or wanted - inventory or not isinstance(readbacks, dict)
            or not isinstance(checks, dict) or wanted - readbacks.keys() or wanted - checks.keys()):
        return None
    return copy.deepcopy(dict(schema='rhg.generation-geometry-scope.v1',
        provenance=evidence['provenance'], manifest_fingerprint=evidence['manifest_fingerprint'],
        entity_readbacks={eid: readbacks[eid] for eid in sorted(wanted)},
        entity_checks={eid: checks[eid] for eid in sorted(wanted)},
        contact_checks=[c for c in evidence.get('contact_checks', []) if c.get('entity_id') in wanted],
        skipped_checks=[c for c in evidence.get('skipped_checks', []) if c.get('entity_id') in wanted],
        acceptance_scope=dict(evidence.get('acceptance_scope', {}),
            excluded_contact_entity_ids=[c['entity_id'] for c in evidence.get('skipped_checks', [])
                                         if c.get('entity_id') in wanted],
            excluded_support_pending_fields=[f for c in evidence.get('skipped_checks', [])
                if c.get('entity_id') in wanted for f in c.get('pending_fields', [])],
            whole_house_acceptance=False),
        validator_identity=evidence.get('validator_identity'),
        worker_identity=evidence.get('worker_identity'),
        pair_checks=[p for p in evidence.get('pair_checks', [])
                     if wanted.intersection((p.get('left'), p.get('right')))] if include_pairs else [],
        diagnostics=[d for d in evidence.get('diagnostics', [])
                     if wanted.intersection(d.get('entity_ids', []))],
        physical_qualified=False, whole_task_acceptance=False))


def _file_sha256(path):
    digest = hashlib.sha256()
    with Path(path).open('rb') as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b''):
            digest.update(chunk)
    return digest.hexdigest()


def _worker_main():
    import argparse
    import gzip
    parser = argparse.ArgumentParser()
    parser.add_argument('--audit-worker', action='store_true', required=True)
    parser.add_argument('--manifest', type=Path, required=True)
    parser.add_argument('--meshes', type=Path, required=True)
    parser.add_argument('--output', type=Path, required=True)
    parser.add_argument('--contact-tolerance-m', type=float, default=1e-5)
    parser.add_argument('--penetration-tolerance-m', type=float)
    args = parser.parse_args()
    worker_identity = implementation_identity()
    with args.manifest.open() as stream:
        manifest = json.load(stream)
    with gzip.open(args.meshes, 'rt') as stream:
        payload = json.load(stream)
    options = {'contact_tolerance_m': args.contact_tolerance_m}
    if args.penetration_tolerance_m is not None:
        options['penetration_tolerance_m'] = args.penetration_tolerance_m
    result = audit_meshes(manifest, payload, options)
    if implementation_identity() != worker_identity:
        raise ValueError('Saved solid audit worker identity changed during audit')
    result['worker_identity'] = worker_identity
    result['provenance'].update(mesh_path=str(args.meshes.resolve()),
                                mesh_sha256=_file_sha256(args.meshes))
    with args.output.open('x') as stream:
        json.dump(result, stream, indent=2, allow_nan=False)
        stream.write('\n')


if __name__ == '__main__':
    _worker_main()