File size: 38,144 Bytes
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
"""Read-only static G1 task precheck; no IK, robot execution or dynamics."""
from __future__ import annotations

import argparse
import copy
import gzip
import hashlib
import json
import math
from pathlib import Path


def _digest(value):
    return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"),
                                     allow_nan=True).encode()).hexdigest()


CHECKS = ("source_binding", "living_support", "cup_grip_native_xy", "support_height",
          "near_edge_reach", "navigation", "lift_headroom")
SCHEMA = "rhg.v6.saved-house-collision-meshes.v1"


def _finite(value):
    return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)


def _hash(value):
    return isinstance(value, str) and len(value) == 64 and all(c in "0123456789abcdef" for c in value)


def _triangles(payload, manifest):
    """Validate the actual exporter interface; ignore all nominal/bbox dimensions."""
    if payload.get("schema") != SCHEMA or payload.get("world_vertices") is not True:
        raise ValueError("expected_saved_world_triangle_export")
    rows = payload.get("meshes", [])
    ids = [r["entity_id"] for r in manifest["entities"]]
    if not ids or len(ids) != len(set(ids)):
        raise ValueError("missing_or_duplicate_manifest_entities")
    if set(r["entity_id"] for r in payload.get("entities", [])) != set(ids):
        raise ValueError("export_entity_inventory_differs")
    if not rows or payload.get("mesh_count") != len(rows):
        raise ValueError("missing_or_incomplete_mesh_inventory")
    result = []
    names = set()
    for row in rows:
        if row["name"] in names:
            raise ValueError("duplicate_mesh_name")
        names.add(row["name"])
        if row.get("entity_id") is not None and row["entity_id"] not in ids:
            raise ValueError("unknown_mesh_entity")
        vertices = row["vertices"]
        if not vertices or any(len(p) != 3 or not all(_finite(v) for v in p) for p in vertices):
            raise ValueError("invalid_world_vertices")
        faces = row["triangles"]
        if not faces:
            raise ValueError("missing_mesh_triangles")
        for face in faces:
            if len(face) != 3 or any(type(i) is not int or not 0 <= i < len(vertices) for i in face):
                raise ValueError("invalid_triangle_indices")
            result.append((row.get("entity_id"), row["name"], [vertices[i] for i in face]))
    if payload.get("triangle_count") != len(result):
        raise ValueError("incomplete_triangle_inventory")
    observed = {eid for eid, _, _ in result}
    if any(identifier not in observed for identifier in ids):
        raise ValueError("missing_entity_meshes")
    if not _hash(payload.get("source_blend_sha256")):
        raise ValueError("missing_saved_blend_identity")
    return result


def _projection(points):
    """Exact triangle XY projection, retaining vertical triangles as lines/points."""
    from shapely.geometry import LineString, Point, Polygon
    xy = list(dict.fromkeys((p[0], p[1]) for p in points))
    if not xy:
        return Polygon()
    if len(xy) == 1:
        return Point(xy[0])
    if len(xy) >= 3:
        poly = Polygon(xy)
        if poly.area > 0:
            return poly
    return LineString(xy)


def _horizontal(triangles, height, tolerance):
    from shapely.ops import unary_union
    return unary_union([_projection(p) for p in triangles
                        if max(v[2] for v in p)-min(v[2] for v in p) <= 1e-6
                        and abs(sum(v[2] for v in p)/3-height) <= tolerance
                        and _projection(p).area > 0])


def _clip_z(points, low, high):
    """Clip each world triangle to a vertical slab before projecting it."""
    for plane, sign in ((low, 1), (high, -1)):
        output = []
        if not points:
            break
        for a, b in zip(points, points[1:]+points[:1]):
            ina, inb = sign*(a[2]-plane) >= 0, sign*(b[2]-plane) >= 0
            if ina:
                output.append(a)
            if ina != inb:
                t = (plane-a[2])/(b[2]-a[2])
                output.append([a[i]+t*(b[i]-a[i]) for i in range(3)])
        points = output
    return points


def depth_bands(profile, height):
    """Continuous native task_constraints.depth_bands rule, including deductions."""
    models = profile.get("depth_models") or [profile["depth_model"]]
    bands = []
    for m in models:
        scalars = [m[k] for k in ("arm_total_to_tool_m", "front_to_shoulder_m",
                   "per_side_hand_reserve_m", "contact_offset_m", "reference_object_half_height_m",
                   "body_edge_clearance_m")] + list(m["shoulder_height_posture_envelope_m"])
        if not all(_finite(v) and v >= 0 for v in scalars):
            raise ValueError("invalid_profile_depth_model")
        center = height+m["reference_object_half_height_m"]
        low, high = m["shoulder_height_posture_envelope_m"]
        vertical = center-min(max(center, low), high)
        deductions = m["front_to_shoulder_m"]+m["body_edge_clearance_m"]+m["per_side_hand_reserve_m"]
        values = {}
        for tier in ("comfort", "reachable", "edge"):
            k = m["k"][tier]
            if not _finite(k) or not 0 < k <= 1:
                raise ValueError("invalid_profile_reach_factor")
            values[tier+"_m"] = max(0, math.sqrt(max(0,
                (k*m["arm_total_to_tool_m"]+m["contact_offset_m"])**2-vertical**2))-deductions)
        bands.append(values)
    return {key: min(b[key] for b in bands) for key in bands[0]}


def _sweep(footprint, start, end):
    """Exact translation sweep of a polygon, including nonconvex boundaries."""
    from shapely.affinity import translate
    from shapely.geometry import Polygon
    from shapely.ops import unary_union
    pieces = [translate(footprint, xoff=p[0], yoff=p[1]) for p in (start, end)]
    if start != end:
        polygons = [footprint] if footprint.geom_type == "Polygon" else footprint.geoms
        for poly in polygons:
            for ring in [poly.exterior, *poly.interiors]:
                coords = list(ring.coords)
                for a, b in zip(coords, coords[1:]):
                    quad = Polygon([(a[0]+start[0], a[1]+start[1]),
                                    (b[0]+start[0], b[1]+start[1]),
                                    (b[0]+end[0], b[1]+end[1]),
                                    (a[0]+end[0], a[1]+end[1])])
                    if quad.area > 0:
                        pieces.append(quad)
    return unary_union(pieces)


def _navigation(measurements, hashes, triangles, surface, cup_center, profile, bands,
                start_xy, start_yaw_deg, tolerance):
    from shapely.affinity import rotate, translate
    from shapely.geometry import LineString, Point, shape
    from shapely.ops import unary_union
    unknown = lambda reason, **data: dict(status="unknown", reason=reason, **data)
    m = measurements or {}
    if (m.get("schema") != "rhg.static-task-measurements.v1"
            or any(m.get(key) != hashes[label] for key, label in (
                ("source_runtime_sha256", "manifest"), ("source_geometry_sha256", "saved_geometry"),
                ("profile_sha256", "profile")))):
        return unknown("missing_or_stale_navigation_measurements")
    f = m.get("robot_footprint", {})
    if (f.get("measured") is not True or not _hash(f.get("source_sha256"))
            or f.get("profile_id") != "g1" or f.get("frame") != "robot_base_xy"
            or f.get("units") != "m" or f.get("front_axis") != "+X" or f.get("proxy") is True
            or f.get("scope") != "full_body_collision_projection"):
        return unknown("missing_measured_robot_polygon_no_scalar_proxy")
    footprint = shape(f["polygon"])
    if (footprint.geom_type not in ("Polygon", "MultiPolygon") or not footprint.is_valid
            or footprint.is_empty or footprint.area <= 0):
        return unknown("invalid_measured_robot_polygon")
    low, high = f["z_range_m"]
    if not all(_finite(v) for v in (low, high)) or low < 0 or high <= low:
        return unknown("invalid_robot_vertical_envelope")
    floor = m.get("floor", {})
    height = floor.get("height_m")
    if not _finite(height) or not floor.get("mesh_names"):
        return unknown("missing_measured_floor_mesh_selection")
    names = set(floor["mesh_names"])
    if not names.issubset({name for eid, name, _ in triangles if eid is None}):
        return unknown("floor_mesh_not_in_saved_shell")
    floor_region = _horizontal([p for _, name, p in triangles if name in names], height, tolerance)
    if floor_region.is_empty or floor_region.area <= 0:
        return unknown("missing_horizontal_measured_floor_polygon")
    # Every physical mesh contributes; no bbox/hull or nominal-width obstacles.
    obstacles = unary_union([_projection(_clip_z(p, height+max(low,tolerance), height+high))
                             for _, _, p in triangles])
    free = floor_region.difference(obstacles)
    if not _finite(start_yaw_deg):
        return unknown("start_yaw_unresolved", start_xy_m=list(start_xy))
    oriented = rotate(footprint, start_yaw_deg, origin=(0,0))
    occupied_start = translate(oriented, xoff=start_xy[0], yoff=start_xy[1])
    evidence = dict(start_xy_m=list(start_xy), start_yaw_deg=start_yaw_deg,
                    floor_area_m2=floor_region.area, free_area_m2=free.area,
                    measured_footprint_area_m2=footprint.area,
                    robot_footprint_source_sha256=f["source_sha256"],
                    scope="fixed_yaw_translation_of_measured_full_body_xy_envelope")
    if not floor_region.covers(occupied_start) or obstacles.intersects(occupied_start):
        return dict(status="fail", reason="specified_start_not_free", **evidence)
    candidates = []
    angle = math.radians(start_yaw_deg)
    forward = (math.cos(angle), math.sin(angle))
    polygons = [oriented] if oriented.geom_type == "Polygon" else oriented.geoms
    front = max(x*forward[0]+y*forward[1] for poly in polygons for x,y in poly.exterior.coords)
    clearance = profile["depth_model"]["body_edge_clearance_m"]
    for goal in m.get("docking_goals", []):
        yaw = goal.get("yaw_deg")
        if not _finite(yaw) or abs((yaw-start_yaw_deg+180)%360-180) > 1e-6:
            candidates.append(dict(status="unknown", reason="rotation_not_checked"))
            continue
        xy = goal["position_xy_m"]
        if len(xy) != 2 or not all(_finite(v) for v in xy):
            raise ValueError("invalid_docking_goal")
        delta = [cup_center.x-xy[0], cup_center.y-xy[1]]
        distance = sum(a*b for a,b in zip(delta,forward))
        lateral = abs(delta[0]*forward[1]-delta[1]*forward[0])
        if distance <= 0 or lateral > tolerance:
            candidates.append(dict(status="unknown", reason="goal_not_facing_cup"))
            continue
        # Bands already deduct the profile's edge clearance; account for extra stand-off.
        effective_depth = distance-front-clearance
        table_crossing = LineString([xy, [cup_center.x,cup_center.y]]).intersection(surface)
        stand_off = Point(xy).distance(table_crossing)-front if not table_crossing.is_empty else -1
        path = goal.get("path_xy_m", [list(start_xy), xy])
        if (len(path) < 2 or any(len(p) != 2 or not all(_finite(v) for v in p) for p in path)
                or math.dist(path[0], start_xy) > 1e-9 or math.dist(path[-1], xy) > 1e-9):
            raise ValueError("candidate_path_endpoints_differ")
        sweep = unary_union([_sweep(oriented,a,b) for a,b in zip(path,path[1:])])
        free_path = floor_region.covers(sweep) and not obstacles.intersects(sweep)
        usable = free_path and stand_off >= clearance-1e-9 and 0 <= effective_depth <= bands["reachable_m"]
        candidates.append(dict(status="pass" if usable else "unknown", position_xy_m=xy,
            yaw_deg=yaw, path_xy_m=path, swept_area_m2=sweep.area,
            effective_depth_m=effective_depth, stand_off_m=stand_off, path_free=free_path))
        if usable:
            return dict(status="pass", reason="verified_candidate_translation_sweep", **evidence,
                        candidates=candidates)
    return unknown("no_verified_candidate_not_a_proof_of_no_route", **evidence, candidates=candidates)


def audit(manifest, saved_geometry, profile, *, measurements=None, start_xy=(1.,1.),
          start_yaw_deg=None, cup_id=None, table_id=None, evidence_hashes=None, tolerance_m=.001):
    """Pure read-only audit of dictionaries. Hashes default to canonical JSON SHA256.

    CLI passes hashes of actual input bytes (including compressed geometry bytes).
    Unknown means missing evidence or an inconclusive bounded check, never success.
    Only native saved triangle exports are supported; bbox-only summaries stay unknown.
    """
    hashes = {"manifest":_digest(manifest), "saved_geometry":_digest(saved_geometry),
              "profile":_digest(profile)}
    if measurements is not None:
        hashes["measurements"] = _digest(measurements)
    if evidence_hashes:
        hashes.update(evidence_hashes)
    checks = {key:dict(status="unknown", reason="measured_geometry_unavailable") for key in CHECKS}

    def finish():
        unknowns = [dict(check=k, reason=v["reason"]) for k,v in checks.items() if v["status"] == "unknown"]
        failures = [k for k,v in checks.items() if v["status"] == "fail"]
        return dict(schema="rhg.static-task-audit.v1", status="fail" if failures else (
            "unknown" if unknowns else "static_precheck_passed"), checks=checks, unknowns=unknowns,
            failures=failures, evidence_hashes=hashes, evidence_sha256=_digest(hashes),
            source_blend_sha256=saved_geometry.get("source_blend_sha256"),
            profile_id="g1", start_xy_m=list(start_xy), ik="not_run", dynamics="not_run",
            physical_qualified=False, whole_task_acceptance=False,
            scope="saved_mesh_static_precheck_only; measured_evidence_is_not_execution")

    try:
        if not _finite(tolerance_m) or not 0 < tolerance_m <= .001:
            raise ValueError("tolerance_m_must_be_positive_and_at_most_0.001")
        if len(start_xy) != 2 or not all(_finite(v) for v in start_xy):
            raise ValueError("invalid_start_xy")
        if saved_geometry.get("source_runtime_sha256") != hashes["manifest"]:
            raise ValueError("saved_geometry_runtime_hash_mismatch")
        triangles = _triangles(saved_geometry, manifest)
        from shapely.geometry import Point, Polygon
        from shapely.ops import unary_union
    except (KeyError, TypeError, ValueError, ImportError, AttributeError) as exc:
        checks["source_binding"] = dict(status="unknown", reason=str(exc))
        return finish()
    checks["source_binding"] = dict(status="pass", reason="export_inventory_and_runtime_hash_match",
                                    mesh_count=saved_geometry["mesh_count"], triangle_count=len(triangles))
    entities = manifest["entities"]
    explicit_cup, explicit_table = cup_id is not None, table_id is not None
    cups = [e for e in entities if (e["entity_id"] == cup_id if cup_id else
                                   e.get("category") == "cup" and e.get("room_id") == "living")]
    tables = [e for e in entities if (e["entity_id"] == table_id if table_id else
                                     e.get("category") == "coffee_table" and e.get("room_id") == "living")]
    if len(cups) != 1 or len(tables) != 1:
        checks["living_support"] = dict(status="unknown", reason="select_unique_living_cup_and_coffee_table",
                                         cup_candidates=[e["entity_id"] for e in cups],
                                         table_candidates=[e["entity_id"] for e in tables])
        return finish()
    cup, table = cups[0], tables[0]
    cup_id, table_id = cup["entity_id"], table["entity_id"]
    declared = (cup.get("room_id") == table.get("room_id") == "living"
        and (explicit_cup or cup.get("category") == "cup")
        and (explicit_table or table.get("category") == "coffee_table")
        and (cup.get("supported_by_entity_id") or cup.get("support_entity_id")) == table_id
        and (cup.get("support_relation") or cup.get("layout_relation")) == "on_top")
    cup_tri = [p for eid,_,p in triangles if eid == cup_id]
    table_tri = [p for eid,_,p in triangles if eid == table_id]
    points = [p for t in cup_tri for p in t]
    bottom, top = min(p[2] for p in points), max(p[2] for p in points)
    footprint = unary_union([_projection(t) for t in cup_tri])
    center = footprint.centroid
    contact = _horizontal(cup_tri, bottom, tolerance_m)
    surface = _horizontal(table_tri, bottom, tolerance_m)
    contact_ok = not contact.is_empty and contact.area > 0 and surface.covers(contact)
    checks["living_support"] = dict(status="pass" if declared and contact_ok else (
        "fail" if not declared or surface.is_empty else "unknown"),
        reason="measured_bottom_contact_on_declared_living_table" if declared and contact_ok else
               "initial_support_relation_or_measured_contact_not_satisfied",
        cup_entity_id=cup_id, support_entity_id=table_id, cup_base_z_m=bottom,
        identity_selection="explicit_task_ids" if explicit_cup and explicit_table else "category_fallback",
        bottom_contact_area_m2=contact.area)
    try:
        yaw = cup["yaw_deg"]
        if not _finite(yaw):
            raise ValueError("missing_finite_saved_native_yaw")
        pose = saved_geometry["entity_pose_checks"][cup_id]
        if (not all(_finite(pose[k]) and 0 <= pose[k] <= tolerance_m
                    for k in ("center_error_m", "hull_vertex_error_m"))):
            raise ValueError("saved_pose_check_not_verified")
        theta = math.radians(yaw)
        native = [(x*math.cos(theta)+y*math.sin(theta),-x*math.sin(theta)+y*math.cos(theta))
                  for x,y,z in points]
        dims = [max(p[i] for p in native)-min(p[i] for p in native) for i in (0,1)]
        limit = profile["max_grip_dimension_m"]
        if profile.get("profile_id", "g1") != "g1" or not _finite(limit) or limit <= 0:
            raise ValueError("missing_selected_g1_grip_limit")
        checks["cup_grip_native_xy"] = dict(status="pass" if max(dims) <= limit else "fail",
            reason="inverse_saved_yaw_world_mesh_native_XY_max", native_xy_m=dims,
            max_native_xy_m=max(dims), limit_m=limit, yaw_deg=yaw)
    except (KeyError, TypeError, ValueError) as exc:
        checks["cup_grip_native_xy"] = dict(status="unknown", reason=str(exc))
    if not surface.is_empty and surface.area > 0 and surface.covers(center):
        # Read the coplanar triangles themselves, never the highest table bbox point.
        planes = [sum(v[2] for v in p)/3 for p in table_tri
                  if max(v[2] for v in p)-min(v[2] for v in p) <= 1e-6
                  and abs(sum(v[2] for v in p)/3-bottom) <= tolerance_m and _projection(p).area > 0]
        height = min(planes, key=lambda z:abs(z-bottom))
        try:
            low, high = profile["support_height_range_m"]
            if not all(_finite(v) for v in (low, high)) or high < low:
                raise ValueError("invalid_profile_height_range")
            checks["support_height"] = dict(status="pass" if low <= height <= high else "fail",
                reason="measured_horizontal_contact_surface", surface_height_m=height, range_m=[low, high])
            bands = depth_bands(profile, height)
            components = [surface] if surface.geom_type == "Polygon" else surface.geoms
            exteriors = unary_union([p.exterior for p in components if p.geom_type == "Polygon" and p.covers(center)])
            depth = center.distance(exteriors)
            checks["near_edge_reach"] = dict(status="pass" if depth <= bands["reachable_m"] else "fail",
                reason="cup_projection_centroid_to_external_contact_surface_edge_native_depth_rule",
                surface_height_m=height, near_edge_distance_m=depth, **bands)
            checks["navigation"] = _navigation(measurements, hashes, triangles, surface, center,
                profile, bands, start_xy, start_yaw_deg, tolerance_m)
        except (KeyError, TypeError, ValueError, AttributeError) as exc:
            # Keep already proven independent checks; do not turn missing evidence into a pass.
            checks["navigation"] = dict(status="unknown", reason=str(exc))
    if any(eid is None for eid,_,_ in triangles):
        blockers = set()
        # Surface clipping cannot exclude full containment inside a closed solid.
        # AABB is used ONLY to force unknown here, never to certify free headroom.
        sample = [center.x, center.y, (bottom+top+.1)/2]
        enclosures = []
        for mesh in saved_geometry["meshes"]:
            if mesh.get("entity_id") == cup_id:
                continue
            vertices = mesh["vertices"]
            if all(min(p[i] for p in vertices) < sample[i] < max(p[i] for p in vertices) for i in range(3)):
                enclosures.append(mesh["name"])
        for eid,name,p in triangles:
            if eid == cup_id:
                continue
            if eid == table_id and max(v[2] for v in p) <= bottom+tolerance_m:
                continue  # Initial support contact is allowed; raised table features are not.
            if max(v[2] for v in p) < bottom or min(v[2] for v in p) > top+.1:
                continue
            xmin,ymin,xmax,ymax = footprint.bounds
            if (max(v[0] for v in p) < xmin or min(v[0] for v in p) > xmax
                    or max(v[1] for v in p) < ymin or min(v[1] for v in p) > ymax):
                continue
            clipped = _clip_z(p, bottom, top+.1)
            if clipped and footprint.intersects(_projection(clipped)):
                blockers.add(name)
        checks["lift_headroom"] = dict(status="unknown" if blockers or enclosures else "pass",
            reason="conservative_swept_prism_overlap_or_containment_unresolved" if blockers or enclosures else
                   "measured_world_z_swept_prism_clear",
            lift_vector_world_m=[0,0,.1], initial_z_range_m=[bottom,top],
            swept_z_range_m=[bottom,top+.1], potential_blockers=sorted(blockers),
            enclosing_mesh_candidates=sorted(enclosures),
            scope="conservative_cup_projection_prism_only_no_gripper_arm_or_hold_dynamics")
    return finish()


def _self_test():
    """Synthetic contract regressions, deliberately separate from scene acceptance."""
    import unittest

    def box(identifier, low, high, name=None, yaw=0):
        vertices = [[x, y, z] for z in (low[2], high[2])
                    for y in (low[1], high[1]) for x in (low[0], high[0])]
        c, s = math.cos(math.radians(yaw)), math.sin(math.radians(yaw))
        cx, cy = (low[0]+high[0])/2, (low[1]+high[1])/2
        vertices = [[cx+c*(x-cx)-s*(y-cy), cy+s*(x-cx)+c*(y-cy), z]
                    for x, y, z in vertices]
        faces = [[0, 2, 3], [0, 3, 1], [4, 5, 7], [4, 7, 6],
                 [0, 1, 5], [0, 5, 4], [2, 6, 7], [2, 7, 3],
                 [0, 4, 6], [0, 6, 2], [1, 3, 7], [1, 7, 5]]
        return dict(entity_id=identifier, name=name or identifier,
                    vertices=vertices, triangles=faces)

    def polygon(points):
        return dict(type="Polygon", coordinates=[points + [points[0]]])

    class AuditTests(unittest.TestCase):
        def setUp(self):
            self.manifest = dict(entities=[
                dict(entity_id="cup", category="cup", room_id="living", yaw_deg=45,
                     supported_by_entity_id="coffee_table", support_relation="on_top"),
                dict(entity_id="coffee_table", category="coffee_table", room_id="living")])
            # A non-square native cup rotated 45 degrees: world AABB is too wide.
            self.geometry = dict(schema="rhg.v6.saved-house-collision-meshes.v1",
                world_vertices=True, source_blend_sha256="a"*64,
                entity_pose_checks={"cup":dict(center_error_m=0.,hull_vertex_error_m=0.)},
                entities=copy.deepcopy(self.manifest["entities"]), meshes=[
                    box("cup", [2.74, .97, .6], [2.86, 1.03, .7], yaw=45),
                    box("coffee_table", [2.5, .5, .4], [3.5, 1.5, .6]),
                    box(None, [0, 0, -.1], [5, 4, 0], "floor"),
                    box(None, [0, 0, 2.5], [5, 4, 2.6], "ceiling")])
            self.profile = dict(profile_id="g1", max_grip_dimension_m=.13,
                support_height_range_m=[.4, 1.3], depth_model=dict(
                    arm_total_to_tool_m=.452002356977085,
                    front_to_shoulder_m=.125004873903219,
                    shoulder_height_posture_envelope_m=[.7138164174362676, 1.0836437524222113],
                    per_side_hand_reserve_m=.0055, contact_offset_m=.073,
                    reference_object_half_height_m=.05, body_edge_clearance_m=.01,
                    k=dict(comfort=.8, reachable=.95, edge=1.)))
            self.measurements = dict(schema="rhg.static-task-measurements.v1",
                robot_footprint=dict(measured=True, source_sha256="b"*64,
                    frame="robot_base_xy", units="m", front_axis="+X", profile_id="g1",
                    scope="full_body_collision_projection",
                    # Deliberately asymmetric true polygon; not profile width/depth.
                    polygon=polygon([[-.1,-.15],[.09,-.15],[.12,0],[.09,.15],[-.1,.15]]),
                    z_range_m=[0, 1.3]),
                floor=dict(mesh_names=["floor"], height_m=0),
                docking_goals=[dict(position_xy_m=[2.37,1], yaw_deg=0)])

        def run_audit(self, **kwargs):
            self.geometry["source_runtime_sha256"] = _digest(self.manifest)
            self.geometry["mesh_count"] = len(self.geometry["meshes"])
            self.geometry["triangle_count"] = sum(len(m["triangles"]) for m in self.geometry["meshes"])
            self.measurements.update(source_runtime_sha256=_digest(self.manifest),
                source_geometry_sha256=_digest(self.geometry), profile_sha256=_digest(self.profile))
            return audit(self.manifest, self.geometry, self.profile,
                         measurements=self.measurements, start_yaw_deg=0, **kwargs)

        def test_measured_support_native_xy_and_straight_path(self):
            result = self.run_audit()
            for key in ("source_binding", "living_support", "cup_grip_native_xy",
                        "support_height", "near_edge_reach", "navigation", "lift_headroom"):
                self.assertEqual(result["checks"][key]["status"], "pass", (key,result))
            self.assertAlmostEqual(result["checks"]["cup_grip_native_xy"]["max_native_xy_m"], .12)
            self.assertFalse(result["physical_qualified"])
            self.assertEqual(result["ik"], "not_run")
            self.assertEqual(result["dynamics"], "not_run")

        def test_surface_is_contact_plane_not_table_bbox_top(self):
            self.geometry["meshes"].append(box("coffee_table",[3.3,1.3,.6],[3.4,1.4,1.5],"ornament"))
            result = self.run_audit()
            self.assertAlmostEqual(result["checks"]["support_height"]["surface_height_m"],.6)
            self.assertEqual(result["checks"]["living_support"]["status"],"pass")

        def test_wrong_parent_room_or_float_does_not_pass(self):
            for mutation in ("parent", "room", "float"):
                with self.subTest(mutation=mutation):
                    previous = copy.deepcopy(self.manifest), copy.deepcopy(self.geometry)
                    if mutation == "parent": self.manifest["entities"][0]["supported_by_entity_id"]="other"
                    if mutation == "room": self.manifest["entities"][0]["room_id"]="bedroom"
                    if mutation == "float":
                        for p in self.geometry["meshes"][0]["vertices"]: p[2] += .03
                    self.assertNotEqual(self.run_audit()["checks"]["living_support"]["status"],"pass")
                    self.manifest, self.geometry = previous

        def test_missing_polygon_scalar_proxy_and_rotation_are_unknown(self):
            for mode in ("missing", "proxy", "rotation"):
                with self.subTest(mode=mode):
                    previous=copy.deepcopy(self.measurements)
                    if mode == "missing": self.measurements.pop("robot_footprint")
                    if mode == "proxy": self.measurements["robot_footprint"]["measured"]=False
                    if mode == "rotation": self.measurements["docking_goals"][0]["yaw_deg"]=90
                    self.assertEqual(self.run_audit()["checks"]["navigation"]["status"],"unknown")
                    self.measurements=previous

        def test_blocked_straight_path_is_not_claim_of_no_route(self):
            self.geometry["meshes"].append(box(None,[1.6,.7,0],[1.7,1.3,2],"barrier"))
            result=self.run_audit()
            self.assertEqual(result["checks"]["navigation"]["status"],"unknown")
            self.assertIn("no_verified_candidate",result["checks"]["navigation"]["reason"])

        def test_world_z_headroom_includes_low_overhang(self):
            self.geometry["meshes"].append(box(None,[2.7,.9,.75],[2.9,1.1,.76],"overhang"))
            check=self.run_audit()["checks"]["lift_headroom"]
            self.assertNotEqual(check["status"],"pass")
            self.assertEqual(check["lift_vector_world_m"],[0,0,.1])

        def test_reach_uses_height_dependent_rule(self):
            low=self.run_audit()["checks"]["near_edge_reach"]["reachable_m"]
            for mesh in self.geometry["meshes"][:2]:
                for p in mesh["vertices"]: p[2] += .3
            high=self.run_audit()["checks"]["near_edge_reach"]["reachable_m"]
            self.assertGreater(high,low)

        def test_missing_or_stale_geometry_never_passes(self):
            for mode in ("bbox_only","binding","inventory","nonfinite"):
                with self.subTest(mode=mode):
                    self.run_audit()
                    g=copy.deepcopy(self.geometry)
                    if mode == "bbox_only": g.pop("meshes")
                    if mode == "binding": g["source_runtime_sha256"]="c"*64
                    if mode == "inventory": g["meshes"].pop()
                    if mode == "nonfinite": g["meshes"][0]["vertices"][0][0]=float("nan")
                    r=audit(self.manifest,g,self.profile)
                    self.assertTrue(r["unknowns"])
                    self.assertNotEqual(r["status"],"static_precheck_passed")

        def test_hashes_and_no_mutation(self):
            self.run_audit()
            before=copy.deepcopy((self.manifest,self.geometry,self.profile,self.measurements))
            result=self.run_audit()
            self.assertEqual(before,(self.manifest,self.geometry,self.profile,self.measurements))
            self.assertEqual(result["evidence_hashes"]["saved_geometry"],_digest(self.geometry))
            self.assertEqual(result["evidence_sha256"],_digest(result["evidence_hashes"]))

        def test_excess_grip_and_far_edge_fail_scalar_prechecks(self):
            self.profile["max_grip_dimension_m"] = .1
            self.assertEqual(self.run_audit()["checks"]["cup_grip_native_xy"]["status"],"fail")
            for p in self.geometry["meshes"][0]["vertices"]: p[0] += .2
            self.assertEqual(self.run_audit()["checks"]["near_edge_reach"]["status"],"fail")

        def test_tabletop_hole_cannot_be_filled_by_a_hull(self):
            self.geometry["meshes"][1:2] = [
                box("coffee_table",[2.5,.5,.4],[2.65,1.5,.6],"left"),
                box("coffee_table",[3.35,.5,.4],[3.5,1.5,.6],"right"),
                box("coffee_table",[2.65,.5,.4],[3.35,.65,.6],"front"),
                box("coffee_table",[2.65,1.35,.4],[3.35,1.5,.6],"back")]
            self.assertNotEqual(self.run_audit()["checks"]["living_support"]["status"],"pass")

        def test_nonconvex_polygon_sweep_keeps_real_notch(self):
            from shapely.geometry import Point, shape
            f=shape(polygon([[-.1,-.1],[.1,-.1],[.1,-.02],[-.02,-.02],[-.02,.1],[-.1,.1]]))
            actual=_sweep(f,[0,0],[1,0])
            self.assertFalse(actual.covers(Point(1.02,.02)))
            self.assertTrue(_sweep(f.convex_hull,[0,0],[1,0]).covers(Point(1.02,.02)))

        def test_stale_sidecar_and_unknown_start_yaw_cannot_pass_navigation(self):
            self.run_audit()
            self.measurements["source_geometry_sha256"]="d"*64
            result=audit(self.manifest,self.geometry,self.profile,measurements=self.measurements,start_yaw_deg=0)
            self.assertEqual(result["checks"]["navigation"]["status"],"unknown")
            self.assertEqual(self.run_audit()["checks"]["navigation"]["status"],"pass")
            result=audit(self.manifest,self.geometry,self.profile,measurements=self.measurements)
            self.assertEqual(result["checks"]["navigation"]["reason"],"start_yaw_unresolved")

        def test_cli_consumes_raw_hashes_gzip_and_preserves_all_input_bytes(self):
            import contextlib
            import io
            import tempfile
            self.run_audit()
            with tempfile.TemporaryDirectory(prefix="static-task-audit-") as directory:
                root=Path(directory)
                m=root/"manifest.json";g=root/"savedgeometry.json.gz";p=root/"profile.json"
                m.write_text(json.dumps(self.manifest,indent=2))
                self.geometry["source_runtime_sha256"]=hashlib.sha256(m.read_bytes()).hexdigest()
                g.write_bytes(gzip.compress(json.dumps(self.geometry).encode()))
                p.write_text(json.dumps(self.profile))
                before={f.name:f.read_bytes() for f in root.iterdir()}
                output=io.StringIO()
                with contextlib.redirect_stdout(output):
                    code=main(["--manifest",str(m),"--saved-geometry",str(g),"--profile",str(p)])
                result=json.loads(output.getvalue())
                self.assertEqual(code,2)  # No measured robot footprint supplied.
                self.assertEqual(result["checks"]["source_binding"]["status"],"pass")
                self.assertEqual(result["checks"]["cup_grip_native_xy"]["status"],"pass")
                self.assertEqual(result["evidence_hashes"]["saved_geometry"],hashlib.sha256(g.read_bytes()).hexdigest())
                self.assertEqual(before,{f.name:f.read_bytes() for f in root.iterdir()})

        def test_explicit_task_ids_survive_category_binding_changes(self):
            self.manifest["entities"][0]["category"]="table_cup"
            self.manifest["entities"][1]["category"]="table"
            result=self.run_audit(cup_id="cup",table_id="coffee_table")
            self.assertEqual(result["checks"]["living_support"]["status"],"pass")

        def test_enclosing_volume_is_not_missed_by_surface_slab(self):
            self.geometry["meshes"].append(box(None,[2,0,.2],[4,2,2],"enclosure"))
            self.assertEqual(self.run_audit()["checks"]["lift_headroom"]["status"],"unknown")

    result=unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(AuditTests))
    return 0 if result.wasSuccessful() else 1


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--self-test", action="store_true")
    parser.add_argument("--manifest", type=Path)
    parser.add_argument("--saved-geometry", type=Path,
                        help="Native physical_meshes.json[.gz]; summaries remain unknown")
    parser.add_argument("--profile", type=Path, help="Selected G1 profile JSON or native robot catalog YAML")
    parser.add_argument("--measurements", type=Path, help="Optional measured navigation evidence JSON")
    parser.add_argument("--start-xy", nargs=2, type=float, default=[1.,1.])
    parser.add_argument("--start-yaw-deg", type=float, default=None)
    parser.add_argument("--cup-id")
    parser.add_argument("--table-id")
    args = parser.parse_args(argv)
    if args.self_test:
        return _self_test()
    if not all((args.manifest, args.saved_geometry, args.profile)):
        parser.error("--manifest, --saved-geometry and --profile are required")
    hashes = {}

    def read(path, label):
        data = path.read_bytes()
        hashes[label] = hashlib.sha256(data).hexdigest()
        if path.suffix == ".gz":
            data = gzip.decompress(data)
        if path.suffix in (".yaml", ".yml"):
            import yaml
            return yaml.safe_load(data)
        return json.loads(data)

    try:
        manifest = read(args.manifest, "manifest")
        geometry = read(args.saved_geometry, "saved_geometry")
        profile = read(args.profile, "profile")
        if "robots" in profile:
            profile = dict(profile["robots"]["g1"], profile_id="g1")
        elif "constraints" in profile:
            robot = profile["constraints"]["robot"]
            if robot.get("profile_key") != "g1":
                raise ValueError("profile_source_does_not_select_g1")
            profile = dict(robot["profile"], profile_id="g1")
        measurements = read(args.measurements, "measurements") if args.measurements else None
        result = audit(manifest, geometry, profile, measurements=measurements,
                       start_xy=args.start_xy, start_yaw_deg=args.start_yaw_deg,
                       cup_id=args.cup_id, table_id=args.table_id, evidence_hashes=hashes)
    except (OSError, ValueError, KeyError, TypeError, ImportError) as exc:
        result = dict(schema="rhg.static-task-audit.v1", status="unknown",
            unknowns=[dict(check="input", reason=str(exc))], evidence_hashes=hashes,
            evidence_sha256=_digest(hashes), ik="not_run", dynamics="not_run",
            physical_qualified=False, whole_task_acceptance=False)
    print(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False))
    return {"static_precheck_passed":0, "fail":1, "unknown":2}[result["status"]]


if __name__ == "__main__":
    raise SystemExit(main())