RoboHome / code /robohome /src /engine /room_program.py
RoboParty Release
Unify robohome source, assets and scenes delivery
3f15e9f
Raw History Blame Contribute Delete
80.6 kB
"""Frozen room contracts and measured polygon checks, without native execution. Only declared doors and explicit open connections form the circulation graph. World footprints are used as supplied; source footprints require a measured XY center and yaw and use the native uniform-scale convention (default one). Dimensions alone never stand in for a footprint or support-contact evidence. """ from __future__ import annotations import copy import hashlib import heapq import json import math from pathlib import Path from shapely import affinity from shapely.errors import GEOSException from shapely.geometry import Polygon, box if __package__: from .floor_cover_contacts import is_floor_cover, export_arithmetic_guard from .support_contract import authored_support_parent, resolve_support_contract, wall_gap_accepted, verify_surface_evidence else: from floor_cover_contacts import is_floor_cover, export_arithmetic_guard from support_contract import authored_support_parent, resolve_support_contract, wall_gap_accepted, verify_surface_evidence __all__ = ['compile_room_program', 'evaluate_room_program'] _SCHEMA = 'rhg.wholehouse-room-program.v1' _SUPPORT = ('supported_by_entity_id', 'support_entity_id', 'parent_entity_id') _SEMANTICS = ('role', 'category', 'procedural_kind', 'asset_pool_key', 'layout_slot_id', 'layout_relation', 'support_relation', 'support_type', 'front_target_entity_id', 'face_target_slot_id', '_layout_parent_id', '_layout_targets', 'attributes', 'semantic_group', 'binding_semantic_key') _NATIVE = ('dimensions_m', 'source_dimensions_m', 'uniform_scale', 'asset_sha256', 'runtime_sha256', 'canonical_path', 'runtime_path', 'canonical_transform', 'canonical_front_axis', 'pool_candidate_key', 'source_dependency_sha256', 'units', 'up_axis', 'prepared_source_frame_contract', 'source_geometry_probe_key') _SOURCE_GEOMETRY = ('source_visual_footprint_polygon_xy_m', 'source_support_geometry', 'source_support_plane_offset_m') _TASK = ('task_kind', 'task', 'task_text', 'natural_language_task', 'task_contract_v16', 'benchmark_episode_v16', 'required_entity_ids') _EPS = 1e-9 # Explicit slot kinds accepted by the native binder, including its role aliases. # Unknown kinds retain strict equality; they cannot opt into this transition. _BINDING_ROLES = ('armchair', 'bed', 'book', 'bottle', 'bowl', 'cabinet', 'coffee_table', 'cup', 'desk', 'dining_chair', 'dining_table', 'lamp', 'mirror', 'plant', 'plate', 'range_hood', 'refrigerator', 'rug', 'shower', 'side_table', 'sink', 'sofa', 'television', 'toilet', 'vase', 'wardrobe') _BINDING_KINDS = {role: (role, role) for role in _BINDING_ROLES} _BINDING_KINDS.update({'fallback_asset_pool_' + role: (role, role) for role in _BINDING_ROLES}) _BINDING_KINDS.update({ 'kitchen_counter': ('cabinet', 'kitchen_counter'), 'kitchen_upper_cabinet': ('cabinet', 'upper_cabinet'), # Generated house programs request overhead storage with procedural_kind 'upper_cabinet'. 'upper_cabinet': ('cabinet', 'upper_cabinet'), 'kitchen_sink': ('sink', 'kitchen_sink'), 'cooktop': ('oven', 'cooktop'), 'bookcase': ('cabinet', 'bookcase'), 'media_console': ('cabinet', 'media_console'), 'vanity_table': ('desk', 'vanity'), 'dining_plate': ('cup', 'plate'), 'bath_counter_bottle': ('cup', 'bottle'), 'small_bowl': ('vase', 'bowl'), 'counter_bowl': ('vase', 'bowl'), 'bath_sink': ('sink', 'sink'), 'bedroom_desk': ('desk', 'desk'), 'bedside_lamp': ('lamp', 'lamp'), 'book_stack': ('book', 'book'), 'guest_bed_compact': ('bed', 'bed'), 'master_bed_compact': ('bed', 'bed'), 'shower_stall': ('shower', 'shower'), 'table_cup': ('cup', 'cup'), }) def _qualified_bookcase_source(bound): """Recognize a shelf taxonomy label only for an exact bookcase source.""" evidence=bound.get('source_semantic_evidence') if (not isinstance(evidence,dict) or evidence.get('schema')!='rhg.source_semantic_evidence.v1' or evidence.get('evidence_verification')!='current_bytes_verified'): return False for source,target in (('asset_id','asset_id'),('source_sha256','asset_sha256'), ('runtime_sha256','runtime_sha256')): if not bound.get(target) or evidence.get(source)!=bound[target]:return False transform=bound.get('canonical_transform') if (not isinstance(transform,list) or len(transform)!=16 or any(type(v) not in (int,float) or not math.isfinite(v) for v in transform) or evidence.get('canonical_transform')!=transform):return False role=evidence.get('semantic_role') or {} authored=evidence.get('authored_source') or {} return (isinstance(role,dict) and isinstance(authored,dict) and isinstance(role.get('catalog_roles'),list) and 'bookcase' in role['catalog_roles'] and role.get('authored_wordnet_category')=='bookcase' and authored.get('source_category')=='bookcase' and authored.get('wordnet_synset')=='bookcase.n.01') def _floor_range_released(old, row): """The binder turned a counter cooktop slot into a free-standing range: it stands on the floor in the counter's run and no longer names a parent. Same condition as run_chain.floor_range_released_support (kept equal by a test).""" parent = old.get('supported_by_entity_id') or old.get('support_entity_id') return bool(parent and row.get('cooking_appliance_mode') == 'floor_range' and row.get('floor_range_counter_id') == parent and not any(row.get(k) for k in ('supported_by_entity_id', 'support_entity_id', 'parent_entity_id')) and abs(row.get('base_z_m', 1.)) <= .005 and row.get('support_type') == 'floor') _FLOOR_RANGE_TRANSITION_FIELDS = ('layout_relation', 'support_type') def binding_allowed_categories(slot): """(semantic, categories) a final binding may report for this slot, or None. Static part of the binder's category contract, shared with retrieval so a candidate that this audit would reject is not selected in the first place. Source-dependent refinements (a qualified bookcase shelf, a lamp-family source label, a floor-range cooktop) are added by _binding_transition_fields. """ kind = slot.get('procedural_kind') if not isinstance(kind, str) or kind not in _BINDING_KINDS: return None semantic = _BINDING_KINDS[kind][1] allowed = (semantic, 'desk') if semantic == 'vanity' else (semantic,) # The native catalogue has no 'upper_cabinet' category: wall-hung kitchen # cabinets are catalogued 'kitchen_wall_cabinet', the same object. if semantic == 'upper_cabinet': allowed = ('upper_cabinet', 'kitchen_wall_cabinet') # The native taxonomy retains a prepared lamp's source subtype. A generic # authored lamp slot may be refined, but an authored subtype stays exact. if semantic == 'lamp': authored = slot.get('category') allowed = ('lamp', 'table_lamp', 'floor_lamp') if authored in (None, 'lamp') else (authored,) # The native taxonomy labels a prepared bathroom sink 'bathroom_sink'. A generic # authored sink slot (no category or 'sink') may be refined to it; an authored # subtype stays exact and kitchen_sink keeps its own semantic. if semantic == 'sink' and slot.get('category') in (None, 'sink'): allowed = ('sink', 'bathroom_sink') # A plant slot may bind to an asset the catalogue calls a planter / potted plant. if semantic == 'plant': allowed = tuple(allowed) + ('planter', 'potted_plant', 'houseplant') # Binding an asset of exactly the slot's authored category (a 'nightstand' # side-table slot bound to a nightstand) does not change its semantics. authored = slot.get('category') if semantic != 'lamp' and isinstance(authored, str) and authored and authored not in allowed: allowed = tuple(allowed) + (authored,) return semantic, tuple(allowed) def _binding_transition_fields(slot, bound, manifest): """Recognize binder metadata, without certifying source bytes or geometry.""" kind = slot.get('procedural_kind') if not isinstance(kind, str) or kind not in _BINDING_KINDS: return () role, semantic = _BINDING_KINDS[kind] binding = manifest.get('fixed_layout_real_asset_binding') if (not isinstance(binding, dict) or binding.get('binding_phase') != 'final' or any(binding.get(key) is not True for key in ('final_binding_passed', 'uniform_scale_only', 'preserve_source_materials')) or 'procedural_kind' in bound or slot.get('entity_id') != bound.get('entity_id') or slot.get('room_id') != bound.get('room_id') or slot.get('role') != role or bound.get('role') != role or bound.get('binding_semantic_key') != semantic): return () old_asset, asset = slot.get('asset_id'), bound.get('asset_id') if ((old_asset is not None and (not isinstance(old_asset, str) or not old_asset.startswith(('procedural:', 'astra_generated:', 'request:')))) or not isinstance(asset, str) or not asset or asset.startswith(('procedural:', 'astra_generated:', 'request:'))): return () category = bound.get('category') allowed_categories = binding_allowed_categories(slot)[1] if semantic=='bookcase' and _qualified_bookcase_source(bound): allowed_categories=('bookcase','shelf') # A free-standing range is catalogued as an oven; only the binder's own floor-range marker lets it bind to the cooktop slot. if semantic=='cooktop' and bound.get('cooking_appliance_mode')=='floor_range' and bound.get('floor_range_counter_id'): allowed_categories=tuple(allowed_categories)+('oven','stove') if not isinstance(category, str): return () normalized_category = '_'.join(category.lower().split()) # A generic lamp slot may bind to a prepared lamp whose native source category is a # longer lamp-family label (e.g. malay_lamp_base_...). Accept it only when the label # names a lamp and not a shade; an authored lamp subtype stays exact. tokens = normalized_category.split('_') source_lamp_family = (semantic == 'lamp' and slot.get('category') in (None, 'lamp') and 'lamp' in tokens and not {'shade', 'shades'} & set(tokens)) if normalized_category not in allowed_categories and not source_lamp_family: return () for key in ('asset_sha256', 'runtime_sha256'): digest = bound.get(key) if (not isinstance(digest, str) or len(digest) != 64 or any(char not in '0123456789abcdef' for char in digest)): return () if any(not isinstance(bound.get(key), str) or not bound[key].strip() for key in ('canonical_path', 'runtime_path')): return () dimensions, source = bound.get('dimensions_m'), bound.get('source_dimensions_m') if (not isinstance(dimensions, list) or not isinstance(source, list) or len(dimensions) != 3 or len(source) != 3 or any(not math.isclose(d, s * bound.get('uniform_scale', 1), rel_tol=1e-6, abs_tol=1e-9) for d, s in zip(dimensions, source))): return () fields = ['procedural_kind', 'category', 'binding_semantic_key'] # requested_shell.project supplies only this default when no label was authored. if (slot.get('layout_slot_id') is None and bound.get('layout_slot_id') == role and bound.get('layout_authority') == 'explicit_scene_request_functional_entity'): fields.append('layout_slot_id') return fields def _json(value): def visit(item): if type(item) is dict: for key, child in item.items(): if type(key) is not str: raise ValueError('JSON object keys must be strings') visit(child) elif type(item) is list: for child in item: visit(child) elif type(item) is float: if not math.isfinite(item): raise ValueError('JSON numbers must be finite') elif type(item) not in (str, int, bool, type(None)): raise ValueError('Only JSON data is supported') try: visit(value) except RecursionError as error: raise ValueError('JSON data must be acyclic and within nesting limits') from error def _object(value, name): if not isinstance(value, dict): raise ValueError(name + ' must be an object') return value def _text(value, name): if not isinstance(value, str) or not value.strip(): raise ValueError(name + ' must be a nonempty string') return value def _number(value, name): try: valid = type(value) in (int, float) and math.isfinite(value) except OverflowError: valid = False if not valid: raise ValueError(name + ' must be a finite number') return value def _vector(value, count, name): if not isinstance(value, list) or len(value) != count: raise ValueError(name + ' has invalid dimensions') for number in value: _number(number, name) return value def _ids(value, name): if not isinstance(value, list): raise ValueError(name + ' must be a list') for item in value: _text(item, name) if len(value) != len(set(value)): raise ValueError(name + ' contains duplicate IDs') return value def _rows(value, key, name): if not isinstance(value, list) or not value: raise ValueError(name + ' must be a nonempty inventory') result = {} for row in value: _object(row, name + ' row') identifier = _text(row.get(key), name + '.' + key) if identifier in result: raise ValueError('Duplicate ' + name + ' ID: ' + identifier) result[identifier] = row return result def _fingerprint(value): return hashlib.sha256(json.dumps(value, sort_keys=True, allow_nan=False, separators=(',', ':')).encode()).hexdigest() def _parent(row): parents = [_text(row[key], key) for key in _SUPPORT if row.get(key) is not None] if len(set(parents)) > 1: raise ValueError('Conflicting support aliases: ' + row['entity_id']) return next(iter(parents), None) def _polygon(points, name): if not isinstance(points, list) or len(points) < 3: raise ValueError(name + ' requires at least three XY points') for point in points: _vector(point, 2, name) try: polygon = Polygon(points) if not polygon.is_valid or polygon.is_empty or not math.isfinite(polygon.area) or polygon.area <= 0: raise ValueError(name + ' must be a valid positive-area polygon') except GEOSException as error: raise ValueError('Invalid ' + name) from error return polygon def _geometry(row): for key in ('center_xy_m',): if row.get(key) is not None: _vector(row[key], 2, key) for key in ('dimensions_m', 'source_dimensions_m'): if row.get(key) is not None: if any(n <= 0 for n in _vector(row[key], 3, key)): raise ValueError(key + ' must be positive') for key in ('yaw_deg', 'base_z_m', 'uniform_scale'): if row.get(key) is not None: _number(row[key], key) if row.get('uniform_scale', 1) is not None and row.get('uniform_scale', 1) <= 0: raise ValueError('uniform_scale must be positive') for key in ('footprint_polygon_xy_m', 'source_visual_footprint_polygon_xy_m'): if row.get(key) is not None: _polygon(row[key], key) def _inventory(manifest): _object(manifest, 'manifest') _json(manifest) plan = _object(manifest.get('floor_plan'), 'floor_plan') rooms = _rows(plan.get('rooms'), 'room_id', 'rooms') for room in rooms.values(): if room.get('bounds_m') is not None: x0, y0, x1, y1 = _vector(room['bounds_m'], 4, 'room.bounds_m') if x1 <= x0 or y1 <= y0: raise ValueError('Room bounds must enclose positive area') entities = _rows(manifest.get('entities'), 'entity_id', 'entities') for row in entities.values(): room_id = _text(row.get('room_id'), 'entity.room_id') if room_id not in rooms: raise ValueError('Unknown entity room: ' + room_id) _text(row.get('role'), 'entity.role') _text(row.get('asset_id'), 'entity.asset_id') _geometry(row) return plan, rooms, entities def _support_order(entities): parents = {eid: _parent(row) for eid, row in entities.items()} children = {eid: [] for eid in entities} for eid, parent in parents.items(): if parent is not None: if parent not in entities: raise ValueError('Unknown support parent: ' + parent) if entities[eid]['room_id'] != entities[parent]['room_id']: raise ValueError('Cross-room support: ' + eid) children[parent].append(eid) ready = [eid for eid in entities if parents[eid] is None] heapq.heapify(ready) order = [] while ready: eid = heapq.heappop(ready) order.append(eid) for child in sorted(children[eid]): heapq.heappush(ready, child) if len(order) != len(entities): raise ValueError('Support cycle detected') return parents, order def _relations(value, entities): if not isinstance(value, list): raise ValueError('relations must be a list') for row in value: _object(row, 'relation') _text(row.get('kind'), 'relation.kind') for key in ('subject', 'object', 'target'): if key == 'target' and key not in row: continue if _text(row.get(key), 'relation.' + key) not in entities: raise ValueError('Unknown relation ' + key) def _request(manifest, request, entities, parents): _object(request, 'request') _json(request) if request.get('mode') not in ('locked', 'pool'): raise ValueError('Request mode must be locked or pool') if request.get('task_kind', 'scene_generation') != manifest.get('task_kind', 'scene_generation'): raise ValueError('Request task_kind differs from manifest') if 'floor_plan' in request and request['floor_plan'] != manifest['floor_plan']: raise ValueError('Request floor_plan differs from manifest') if ('floor_plan_sha256' in request and request['floor_plan_sha256'] != _fingerprint(manifest['floor_plan'])): raise ValueError('Request floor_plan_sha256 differs from manifest') furniture = _rows(request.get('furniture'), 'entity_id', 'furniture') collections = [furniture] if 'entities' in request: collections.append(_rows(request['entities'], 'entity_id', 'request.entities')) for collection in collections: if collection.keys() != entities.keys(): raise ValueError('Request must preserve the complete entity inventory') for eid, row in collection.items(): original = entities[eid] _geometry(row) transition = _binding_transition_fields(row, original, manifest) for key in ('room_id', *_SEMANTICS): if key in row and row[key] != original.get(key) and key not in transition: raise ValueError('Request changed ' + key + ': ' + eid) for key in (*_NATIVE, *_SOURCE_GEOMETRY): if key in row and key in original and row[key] != original[key]: raise ValueError('Request changed native ' + key + ': ' + eid) parent = _parent(row) expected_parent = authored_support_parent(original, entities) if row.get('derived_support_relation') is not None: parent = authored_support_parent(row, entities) if parent is not None and parent != expected_parent: raise ValueError('Request changed support assignment: ' + eid) domains = {} for eid, row in furniture.items(): if request['mode'] == 'locked': asset = _text(row.get('asset_id'), 'locked asset_id') if asset != entities[eid]['asset_id']: raise ValueError('Locked request changed asset: ' + eid) domains[eid] = [asset] else: domain = _ids(row.get('candidate_asset_ids'), 'candidate_asset_ids') if not domain: raise ValueError('Candidate asset domain must be nonempty') # A verified effective domain may exclude the original asset. domains[eid] = sorted(domain) if 'candidate_record_ids' in row: if not _ids(row['candidate_record_ids'], 'candidate_record_ids'): raise ValueError('candidate_record_ids must be nonempty') for key in ('source_sha256', 'record_id'): if key in row: _text(row[key], key) for source in (manifest, request): if 'relations' in source: _relations(source['relations'], entities) for key in _TASK: if key in manifest and key in request and manifest[key] != request[key]: raise ValueError('Request changed ' + key) return domains def _room_graph(plan, rooms): adjacency = {rid: set() for rid in sorted(rooms)} edges, entries, entry_rooms = [], [], set() seen = set() for key, kind in (('doors', 'door'), ('topology_adjacencies', 'open_connection')): rows = plan.get(key, []) if not isinstance(rows, list): raise ValueError(key + ' must be a list') for row in rows: _object(row, key + ' row') ids = _ids(row.get('room_ids'), 'opening.room_ids') exterior = row.get('exterior', False) if type(exterior) is not bool or any(rid not in rooms for rid in ids): raise ValueError('Invalid opening room references') if len(ids) != (1 if exterior else 2): raise ValueError('Opening requires two rooms or one explicit exterior room') if key == 'topology_adjacencies': if type(row.get('open_connection', False)) is not bool: raise ValueError('open_connection must be boolean') if row.get('open_connection') is not True: continue interval_key = 'door_interval_m' if kind == 'door' else 'open_interval_m' low, high = _vector(row.get(interval_key), 2, interval_key) if low >= high or row.get('wall_orientation') not in ('V', 'H'): raise ValueError('Invalid opening interval or wall orientation') line = _number(row.get('wall_line_m'), 'wall_line_m') opening = dict(kind=kind, room_ids=sorted(ids), opening_id=row.get('door_id', 'open__' + '__'.join(sorted(ids))), wall_orientation=row['wall_orientation'], wall_line_m=line, interval_m=[low, high], exterior=exterior) for height in ('opening_height_m', 'door_height_m', 'head_height_m', 'sill_height_m'): if row.get(height) is not None: opening[height] = _number(row[height], height) if height != 'sill_height_m' and row[height] <= 0: raise ValueError('Opening heights must be positive') if ('head_height_m' in opening and opening['head_height_m'] <= opening.get('sill_height_m', 0)): raise ValueError('Opening head must be above its sill') identity = (tuple(sorted(ids)), row['wall_orientation'], line, low, high) if identity in seen: continue seen.add(identity) if exterior: entries.append(opening) entry_rooms.update(ids) else: edges.append(opening) a, b = ids adjacency[a].add(b) adjacency[b].add(a) components, pending = [], set(rooms) while pending: found, queue = set(), [min(pending)] while queue: rid = queue.pop() if rid in found: continue found.add(rid) queue.extend(adjacency[rid] - found) pending -= found components.append(sorted(found)) return dict(adjacency={rid: sorted(value) for rid, value in adjacency.items()}, edges=sorted(edges, key=lambda e: (e['room_ids'], e['opening_id'])), entry_rooms=sorted(entry_rooms), entry_openings=entries, components=components) def _note(code, message, *, entity_ids=(), room_ids=()): return dict(code=code, message=message, entity_ids=list(entity_ids), room_ids=list(room_ids)) def _report(schema): return dict(schema=schema, passed=False, issues=[], warnings=[], unknowns=[], scope='declared_room_contract_and_measured_polygon_geometry', physical_qualified=False, whole_task_acceptance=False) def _policy(policy, rooms, entities): policy = {} if policy is None else _object(policy, 'policy') _json(policy) allowed = {'required_rooms', 'required_roles', 'recommended_roles', 'doorway_approach_m', 'search_reservations'} if set(policy) - allowed: raise ValueError('Unknown room policy fields: ' + ', '.join(sorted(set(policy) - allowed))) result = copy.deepcopy(policy) for rid in _ids(policy.get('required_rooms', []), 'required_rooms'): if rid not in rooms: raise ValueError('Required room missing: ' + rid) for key in ('required_roles', 'recommended_roles'): mapping = _object(policy.get(key, {}), key) for rid, roles in mapping.items(): if rid not in rooms: raise ValueError('Unknown policy room: ' + rid) _ids(roles, key) actual = {e['role'] for e in entities.values() if e['room_id'] == rid} if key == 'required_roles' and set(roles) - actual: raise ValueError('Required room role missing: ' + rid) approach = _number(policy.get('doorway_approach_m', .6), 'doorway_approach_m') if approach <= 0: raise ValueError('doorway_approach_m must be positive') result['doorway_approach_m'] = approach reservations = policy.get('search_reservations', []) if not isinstance(reservations, list): raise ValueError('search_reservations must be a list') for row in reservations: _object(row, 'search reservation') if row.get('room_id') not in rooms: raise ValueError('Search reservation requires an existing room') _text(row.get('purpose'), 'search reservation purpose') return result def compile_room_program(manifest, request, policy=None): """Compile a deterministic contract; invalid hard assignments raise ValueError. A pool request defines the output asset domain and need not contain the baseline asset. Its provenance is verified by the caller's native adapter. Compilation itself does not certify candidates, contact, or physical safety. """ plan, rooms, entities = _inventory(manifest) parents, order = _support_order(entities) domains = _request(manifest, request, entities, parents) policy = _policy(policy, rooms, entities) graph = _room_graph(plan, rooms) program = _report(_SCHEMA) program.update(source_manifest_sha256=_fingerprint(manifest), source_request_sha256=_fingerprint(request), baseline_manifest=copy.deepcopy(manifest), request=copy.deepcopy(request), policy=policy, entities=[copy.deepcopy(entities[eid]) for eid in sorted(entities)], asset_domains=copy.deepcopy(domains), support_parents=parents, support_order=order, room_graph=graph, rooms=[], search=dict(enforced=False, reservations=copy.deepcopy(policy.get('search_reservations', [])))) if len(graph['components']) > 1: program['issues'].append(_note('rooms_disconnected', 'Declared passages do not connect all rooms', room_ids=sorted(rooms))) recommendations = {'living': ['sofa'], 'living_room': ['sofa'], 'bedroom': ['bed'], 'master_bedroom': ['bed'], 'guest_bedroom': ['bed'], 'dining_room': ['dining_table'], 'bathroom': ['toilet'], 'kitchen': ['sink']} for rid in sorted(rooms): room = copy.deepcopy(rooms[rid]) ids = sorted(eid for eid, entity in entities.items() if entity['room_id'] == rid) roles = sorted({entities[eid]['role'] for eid in ids}) room.update(entity_ids=ids, roles=roles) program['rooms'].append(room) wanted = policy.get('recommended_roles', {}).get(rid, recommendations.get(room.get('room_type'), [])) for role in sorted(set(wanted) - set(roles)): program['warnings'].append(_note('recommended_role_missing', 'Recommended role is absent: ' + role, room_ids=[rid])) program['passed'] = not program['issues'] return program def _saved_room_boundary(row, entities, bounds, program, evidence, cache): """Resolve only the anchored wall side from current, pinned saved triangles.""" try: if (evidence.get('status') != 'measured' or evidence.get('complete') is not True or evidence.get('geometry_passed') is not True or not _readback_matches(row, evidence) or row.get('wall_anchor') not in ('N', 'S', 'E', 'W')): return None if resolve_support_contract(row, entities)['support_type'] == 'floor': # A visual overhang is not a ground contact. Keep the exact saved # floor rays AND continuous base-region coverage as prerequisites. contacts = [c for c in evidence.get('contact_checks', []) if c.get('entity_id') == row['entity_id']] if len(contacts) != 1: return None contact, tolerance = contacts[0], evidence.get('contact_tolerance_m') gaps = contact.get('gaps_m') low, high = evidence['entity_readbacks'][row['entity_id']]['world_bbox_m'] area = (high[0]-low[0])*(high[1]-low[1]) if (contact.get('passed') is not True or contact.get('complete') is not True or contact.get('status') != 'measured' or contact.get('pending_fields') != [] or contact.get('support_type') != 'floor' or contact.get('support_entity_id') is not None or contact.get('method') != 'bottom_vertices_and_face_centroids' or contact.get('flat_contact_region_checked') is not True or not _finite(contact.get('unsupported_area_m2')) or not 0 <= contact['unsupported_area_m2'] <= max(1e-12, area*1e-10) or not _finite(contact.get('support_coverage')) or not 1-1e-10 <= contact['support_coverage'] <= 1 or not _finite(tolerance) or not 0 < tolerance <= 1e-4 or not isinstance(gaps, list) or not gaps or type(contact.get('sample_count')) is not int or contact['sample_count'] != len(gaps) or any(not _finite(g) or abs(g) > tolerance for g in gaps)): return None if 'shell' not in cache: import gzip cache['shell'] = [] provenance = evidence['provenance'] path = Path(provenance['mesh_path']) expected = evidence['input_sha256'].get(str(path)) raw = path.read_bytes() if (not expected or hashlib.sha256(raw).hexdigest() != expected or provenance.get('mesh_sha256') != expected): return None payload = json.loads(gzip.decompress(raw)) if (payload.get('schema') != 'rhg.v6.saved-house-collision-meshes.v1' or payload.get('source_blend_sha256') != evidence['scene_sha256'] or payload.get('world_vertices') is not True or payload.get('geometry_modified') is not False): return None cache['shell'] = [m for m in payload['meshes'] if m.get('entity_id') is None] if __package__: from .triangle_contacts import wall_face_targets else: from triangle_contacts import wall_face_targets from shapely.ops import unary_union targets, proof = wall_face_targets(row, program['baseline_manifest'], cache['shell']) axis = 0 if row['wall_anchor'] in ('E', 'W') else 1 along = 1-axis sign = 1 if row['wall_anchor'] in ('E', 'N') else -1 edge_index = axis+2 if sign > 0 else axis edge = bounds[edge_index] footprint = _footprint(row) low, high = evidence['entity_readbacks'][row['entity_id']]['world_bbox_m'] cross_section = box(footprint.bounds[along], low[2], footprint.bounds[along+2], high[2]) planes = {} for mesh in targets: for triangle in mesh['triangles']: points = [mesh['vertices'][i] for i in triangle] plane = float(points[0][axis]) if any(float(p[axis]) != plane for p in points): continue projected = Polygon([(float(p[along]), float(p[2])) for p in points]) if projected.area > _EPS: planes.setdefault(plane, []).append(projected) region, corrections = box(*bounds), [] for plane, faces in planes.items(): if sign*(plane-edge) <= 0 or cross_section.difference(unary_union(faces)).area > _EPS: continue for authored in proof['regions']: if (authored['origin'] != 'topology_adjacency' or abs(plane-authored['plane_m']) > proof['plane_binding_tolerance_m']): continue start, end = authored['interval_m'] corrected = list(bounds) corrected[edge_index] = plane corrected[along] = max(corrected[along], start) corrected[along+2] = min(corrected[along+2], end) if corrected[along] < corrected[along+2]: region = region.union(box(*corrected)) corrections.append(dict(wall_anchor=row['wall_anchor'], plane_m=plane, interval_m=[start, end])) if not corrections: return None return region, dict(entity_id=row['entity_id'], declared_bounds_m=list(bounds), saved_wall_boundaries=corrections, wall_target=proof, mesh_sha256=evidence['provenance']['mesh_sha256']) except (OSError, ValueError, KeyError, TypeError, IndexError, ArithmeticError, GEOSException): return None def _footprint(row): if row.get('footprint_polygon_xy_m') is not None: return _polygon(row['footprint_polygon_xy_m'], 'footprint_polygon_xy_m') if row.get('source_visual_footprint_polygon_xy_m') is None: return None if any(row.get(key) is None for key in ('center_xy_m', 'yaw_deg')): return None polygon = _polygon(row['source_visual_footprint_polygon_xy_m'], 'source_visual_footprint_polygon_xy_m') scale = row.get('uniform_scale', 1) if scale is None: return None polygon = affinity.scale(polygon, xfact=scale, yfact=scale, origin=(0, 0)) polygon = affinity.rotate(polygon, row['yaw_deg'], origin=(0, 0)) polygon = affinity.translate(polygon, *row['center_xy_m']) if not polygon.is_valid or not math.isfinite(polygon.area): raise ValueError('Transformed footprint is invalid') return polygon def _current_geometry_evidence(manifest, evidence): """Recheck the saved inputs; a cached inputs_unchanged flag is insufficient.""" if not isinstance(evidence, dict): return {} try: if __package__: from .geometry_validation import evidence_current else: from geometry_validation import evidence_current _json(evidence) status = evidence.get('status') if ((status == 'measured' and (evidence.get('complete') is not True or evidence.get('pending_fields') != [])) or (status == 'pending' and (evidence.get('complete') is not False or not isinstance(evidence.get('pending_fields'), list))) or not evidence_current(manifest, evidence)): return {} readbacks = evidence.get('entity_readbacks') if (not isinstance(readbacks, dict) or set(readbacks) != { row['entity_id'] for row in manifest['entities']}): return {} pins = evidence.get('input_sha256') # Currency binds the exported mesh and scene bytes. Bind the JSON file # too: the canonical in-memory fingerprint is not its raw-file digest. digest = evidence.get('manifest_sha256') if (not isinstance(digest, str) or len(digest) != 64 or any(c not in '0123456789abcdef' for c in digest)): return {} manifest_paths = [] for name, expected in pins.items(): path = Path(name) if expected == digest and path.suffix == '.json': with path.open() as stream: if _fingerprint(json.load(stream)) == _fingerprint(manifest): manifest_paths.append(path.resolve()) if len(manifest_paths) != 1: return {} return evidence except (OSError, ValueError, TypeError, OverflowError, RecursionError): return {} def _finite(value): try: return type(value) in (int, float) and math.isfinite(value) except OverflowError: return False def _passed_lift_probe(pair): """Accept only a complete, measured lift proof within its penetration limit.""" tolerance, lift = pair.get('penetration_tolerance_m'), pair.get('lift_probe_m') volume = pair.get('lift_probe_overlap_volume_m3') depth = pair.get('lift_probe_overlap_equivalent_depth_m') return (pair.get('method') == 'manifold3d_solid_intersection_lift_probe' and pair.get('passed') is True and pair.get('complete') is True and pair.get('status') == 'measured' and _finite(tolerance) and 0 < tolerance <= .005 and _finite(lift) and 0 < lift <= tolerance / 10. and _finite(volume) and (volume <= 1e-15 or _finite(depth) and 0 <= depth <= tolerance)) def _zero_or_tolerated_overlap(pair): """Accept zero overlap, tolerated equivalent depth, or a passed lift probe. Mirrors geometry_validation.audit_meshes: a large flush contact may carry a float-roundoff sliver of positive volume but negligible depth. The recorded penetration tolerance is bounded by the validator's own maximum (0.005 m). """ if pair.get('method') == 'manifold3d_solid_intersection_lift_probe': return _passed_lift_probe(pair) tolerance = pair.get('penetration_tolerance_m') if 'penetration_tolerance_m' in pair and not (_finite(tolerance) and 0 < tolerance <= .005): return False volume = pair.get('overlap_volume_m3') if not _finite(volume): return False if -1e-15 <= volume <= 1e-15: return True depth = pair.get('overlap_equivalent_depth_m') return (volume > 1e-15 and _finite(depth) and _finite(tolerance) and 0 < tolerance <= .005 and 0 <= depth <= tolerance) def _readback_matches(row, evidence): measured = evidence.get('entity_readbacks', {}).get(row['entity_id']) if not isinstance(measured, dict): return False try: bbox = measured.get('world_bbox_m') if not isinstance(bbox, list) or len(bbox) != 2: return False for point in bbox: _vector(point, 3, 'world_bbox_m') if any(bbox[1][i] <= bbox[0][i] for i in range(3)): return False _vector(measured.get('center_xy_m'), 2, 'center_xy_m') _number(measured.get('yaw_deg'), 'yaw_deg') _number(measured.get('base_z_m'), 'base_z_m') if any(n <= 0 for n in _vector(measured.get('dimensions_m'), 3, 'dimensions_m')): return False for key in ('world_bbox_m', 'center_xy_m', 'yaw_deg', 'base_z_m', 'dimensions_m'): expected = (row.get('actual_center_xy_m') or row.get(key) if key == 'center_xy_m' else row.get(key)) if expected is not None: def equal(a, b): if isinstance(a, list): return (isinstance(b, list) and len(a) == len(b) and all(equal(x, y) for x, y in zip(a, b))) return _finite(b) and abs(a - b) <= 1e-6 if not equal(expected, measured[key]): return False return True except (ValueError, KeyError, TypeError, OverflowError): return False def _measured_wall_gap(row, contact, evidence): """Bind the measured nominal gap to its small source receipt, not mesh data.""" expected = contact.get('expected_gap_m', 0.) if not _finite(expected) or expected < 0: return None if 'installation_gap' not in row: return 0. if expected == 0 and 'installation_evidence' not in contact else None declaration, proof = row['installation_gap'], contact.get('installation_evidence') if (not isinstance(declaration, dict) or not isinstance(proof, dict) or not _finite(declaration.get('gap_m')) or declaration['gap_m'] != expected): return None try: path = Path(declaration['evidence_path']) if not path.is_absolute(): return None name, digest = str(path.resolve()), declaration['evidence_sha256'] provenance = evidence['provenance'] if (proof.get('evidence_path') != name or proof.get('evidence_sha256') != digest or evidence.get('input_sha256', {}).get(name) != digest or proof.get('scene_sha256') != evidence.get('scene_sha256') or proof.get('scene_sha256') != provenance.get('scene_sha256') or not isinstance(proof.get('mesh_fingerprint'), str) or len(proof['mesh_fingerprint']) != 64 or proof['mesh_fingerprint'] != provenance.get('mesh_fingerprint')): return None raw = path.read_bytes() if hashlib.sha256(raw).hexdigest() != digest: return None source = json.loads(raw) _json(source) identity = {key: row.get(key) for key in ('asset_id', 'asset_sha256', 'runtime_sha256', 'canonical_transform')} if (not identity['asset_id'] or identity['canonical_transform'] is None or any(not isinstance(identity[key], str) or len(identity[key]) != 64 or any(c not in '0123456789abcdef' for c in identity[key]) for key in ('asset_sha256', 'runtime_sha256')) or not isinstance(source, dict) or source.get('schema') != 'rhg.source-installation-gap.v1' or source.get('entity_id') != row['entity_id'] or source.get('support_type') != 'wall' or source.get('wall_anchor') != row.get('wall_anchor') or source.get('source_identity') != identity or not _finite(source.get('gap_m')) or source['gap_m'] != expected or source.get('scene_sha256') != proof['scene_sha256'] or source.get('mesh_fingerprint') != proof['mesh_fingerprint']): return None names = source.get('target_mesh_names') if (not isinstance(names, list) or not names or any(not isinstance(n, str) or not n for n in names) or len(set(names)) != len(names) or contact.get('target_mesh_names') != names): return None return expected except (OSError, ValueError, KeyError, TypeError): return None def _declared_skipped_sink_support(row, parent, entities, evidence, contact): """Consume only the validator's explicit, still-uncertified sink scope.""" identifier = row['entity_id'] sink = (str(row.get('role', '')).lower() == 'sink' or not row.get('role') and row.get('layout_slot_id') == 'kitchen_sink') contract = resolve_support_contract(row, entities) scope, skipped = evidence.get('acceptance_scope'), evidence.get('skipped_checks') fields = contact.get('pending_fields') allowed = {'support_parent:' + identifier, 'installation_evidence:' + identifier, 'support_entity_geometry:' + identifier, 'support_geometry:' + identifier} checks = evidence.get('entity_checks') summary = checks.get(identifier) if isinstance(checks, dict) else None if (not sink or contract['support_type'] != 'inset' or contact.get('support_type') != 'inset' or contact.get('support_entity_id') != parent or contact.get('status') != 'skipped' or contact.get('passed') is not None or contact.get('complete') is not False or contact.get('reason') != 'asset_installation_evidence_incomplete' or contact.get('scope') != 'inset_sink_installation_support_contact_only' or not isinstance(fields, list) or not fields or any(not isinstance(f, str) or f not in allowed for f in fields) or set(fields) == {'installation_evidence:' + identifier} or any(key in contact for key in ('gap_m', 'gaps_m', 'sample_count', 'seam_bridging')) or not isinstance(scope, dict) or not isinstance(skipped, list) or scope.get('policy') != 'skip_incomplete_inset_sink_installation_support' or scope.get('policy_enabled') is not True or not isinstance(scope.get('excluded_contact_entity_ids'), list) or scope['excluded_contact_entity_ids'].count(identifier) != 1 or [s for s in skipped if isinstance(s, dict) and s.get('entity_id') == identifier] != [contact] or any(evidence.get(key) is not False for key in ('full_geometry_complete', 'full_geometry_passed', 'full_scope_qualified')) or not isinstance(summary, dict) or summary.get('contact_skipped') is not True or summary.get('contact_gate_passed') is not True or summary.get('contact_complete') is not False or summary.get('contact_passed') is not None or summary.get('full_geometry_complete') is not False): return False return all(isinstance(values, list) and all(f in values for f in fields) for values in ( scope.get('excluded_support_pending_fields'), evidence.get('skipped_pending_fields'), evidence.get('full_pending_fields'))) and not any( f in evidence.get('pending_fields', []) for f in fields) def _skipped_support_collisions_clear(entities, evidence): """A contact exclusion cannot waive any unknown or failing collision gate.""" checks, pairs = evidence.get('entity_checks'), evidence.get('pair_checks') if (not isinstance(checks, dict) or not isinstance(pairs, list) or evidence.get('collision_method') != 'manifold3d_solid_intersection' or any(not isinstance(checks.get(eid), dict) or any( checks[eid].get(key) is not True for key in ('solid_complete', 'collision_complete', 'collision_passed')) or not _readback_matches(entities[eid], evidence) for eid in entities) or any(d.get('code') == 'collision' for d in evidence['diagnostics'] if isinstance(d, dict))): return False seen = set() for pair in pairs: if not isinstance(pair, dict): return False a, b, volume = pair.get('left'), pair.get('right'), pair.get('overlap_volume_m3') if not isinstance(a, str) or not isinstance(b, str) or a == b: return False key = frozenset((a, b)) if (key in seen or pair.get('complete') is not True or pair.get('passed') is not True or pair.get('status') != 'measured' or pair.get('method') not in ('manifold3d_solid_intersection', 'manifold3d_solid_intersection_lift_probe', 'saved_mesh_aabb_separation') or not _zero_or_tolerated_overlap(pair)): return False seen.add(key) shell = {name for key in seen for name in key if name.startswith('shell:')} return (all(frozenset((a, b)) in seen for a in entities for b in entities if a < b) and all(frozenset((eid, name)) in seen for eid in entities for name in shell)) def _measured_support(row, parent, entities, evidence): contacts = evidence.get('contact_checks') tolerance = evidence.get('contact_tolerance_m') if (not isinstance(contacts, list) or not _finite(tolerance) or not 0 < tolerance <= 1e-4 or not all(_readback_matches(entities[eid], evidence) for eid in ((row['entity_id'], parent) if parent else (row['entity_id'],)))): return False records = [record for record in contacts if isinstance(record, dict) and record.get('entity_id') == row['entity_id']] if len(records) != 1: return False contact = records[0] if contact.get('status') == 'skipped': diagnostics = evidence.get('diagnostics') if not isinstance(diagnostics, list) or any( isinstance(d, dict) and d.get('code') in ('support_contact_invalid', 'support_footprint_outside_region') and row['entity_id'] in d.get('entity_ids', []) for d in diagnostics): return False return _declared_skipped_sink_support(row, parent, entities, evidence, contact) complete_default = evidence.get('status') == 'measured' and evidence.get('complete') is True if (contact.get('passed') is not True or contact.get('support_entity_id') != parent or contact.get('complete', complete_default) is not True or contact.get('status', 'measured' if complete_default else None) != 'measured' or contact.get('pending_fields', [] if complete_default else None) != []): return False diagnostics = evidence.get('diagnostics') if not isinstance(diagnostics, list) or any( isinstance(d, dict) and d.get('code') in ('support_contact_invalid', 'support_footprint_outside_region') and row['entity_id'] in d.get('entity_ids', []) for d in diagnostics): return False method = contact.get('method') # The audit already validated installation provenance with the mesh export. # Resolve only structural semantics here; verify that proof separately. contract = resolve_support_contract({k: v for k, v in row.items() if k != 'installation_gap'}, entities) kind = contract['support_type'] if (contract['status'] != 'ready' or contact.get('support_type', kind) != kind or ('installation_gap' in row and kind != 'wall')): return False if 'seam_bridging' in contact: checks = evidence.get('entity_checks') summary = checks.get(row['entity_id']) if isinstance(checks, dict) else None if kind != 'surface' or not isinstance(summary, dict): return False # Reuse the independent audit's typed, file-bound seam reconciliation. if __package__: from .feedback import _measured_contact else: from feedback import _measured_contact try: return _measured_contact(row, entities, contact, summary, evidence) except (OSError, ValueError, KeyError, TypeError, ArithmeticError): return False if kind != { 'bottom_vertices_and_face_centroids': 'surface', 'saved_triangle_extreme_vertices_and_face_centroids_rays': 'surface', 'declared_wall_direction_back_surface_rays': 'wall', 'declared_installation_surface_distance': 'inset'}.get(method): return False if method in ('bottom_vertices_and_face_centroids', 'saved_triangle_extreme_vertices_and_face_centroids_rays', 'declared_wall_direction_back_surface_rays'): expected_gap = _measured_wall_gap(row, contact, evidence) if kind == 'wall' else 0. if expected_gap is None or (kind != 'wall' and 'installation_gap' in row): return False gaps = contact.get('gaps_m') if (not isinstance(gaps, list) or not gaps or type(contact.get('sample_count')) is not int or contact['sample_count'] != len(gaps) or any(not _finite(g) or (not wall_gap_accepted(g) if kind == 'wall' else abs(g - expected_gap) > tolerance) for g in gaps)): return False if method == 'declared_wall_direction_back_surface_rays': if (row.get('wall_anchor') not in ('N', 'S', 'E', 'W') or contact.get('wall_anchor') != row['wall_anchor']): return False elif 'flat_contact_region_checked' in contact: area, coverage = contact.get('unsupported_area_m2'), contact.get('support_coverage') low, high = evidence['entity_readbacks'][row['entity_id']]['world_bbox_m'] max_base_area = (high[0] - low[0]) * (high[1] - low[1]) if (contact['flat_contact_region_checked'] is not True or not _finite(area) or area < 0 or not _finite(coverage) or area > max(1e-12, max_base_area * 1e-10) or not 1-1e-10 <= coverage <= 1): return False elif method == 'declared_installation_surface_distance': gap = contact.get('gap_m') if ((row.get('support_type') != 'inset' and row.get('layout_slot_id') != 'kitchen_sink') or not _finite(gap) or not 0 <= gap <= tolerance): return False else: return False return True def _permitted_floor_cover_contact(a, b, entities, evidence, pair): """Consume only a complete native geometry result, never a source annotation.""" try: tolerance = pair.get('penetration_tolerance_m') if 'penetration_tolerance_m' in pair and not (_finite(tolerance) and 0 < tolerance <= .005): return None if (evidence.get('status')!='measured' or evidence.get('complete') is not True or any(evidence.get(k) is not True for k in ('geometry_passed','full_geometry_complete','full_geometry_passed','full_scope_qualified')) or evidence.get('pending_fields')!=[] or evidence.get('full_pending_fields')!=[] or evidence.get('diagnostics')!=[] or evidence.get('skipped_checks')!=[] or evidence.get('physical_qualified') is not False or evidence.get('whole_task_acceptance') is not False or pair.get('permitted_contact') is not True or pair.get('complete') is not True or pair.get('status')!='measured' or (pair.get('method')!='manifold3d_solid_intersection' and not _passed_lift_probe(pair)) or pair.get('passed') is not True):return None ids=sorted((a,b));certificates=evidence.get('permitted_floor_cover_contacts') if not isinstance(certificates,list) or any(not isinstance(c,dict) for c in certificates):return None matches=[c for c in certificates if c.get('entity_ids')==ids] if len(matches)!=1:return None cert=matches[0];identifier=cert.get('certificate_id') if (not isinstance(identifier,str) or len(identifier)!=64 or identifier!=pair.get('permitted_contact_certificate_id') or identifier!=_fingerprint({k:v for k,v in cert.items() if k!='certificate_id'}) or cert.get('schema')!='rhg.permitted_floor_cover_contact.v1' or cert.get('policy_revision')!='thin-floor-cover-common-floor-v1' or cert.get('kind')!='thin_floor_cover_common_floor_contact' or cert.get('complete') is not True or cert.get('passed') is not True or cert.get('physical_qualified') is not False):return None cover,other=cert.get('floor_cover_entity_id'),cert.get('furniture_entity_id') if (cover==other or set((cover,other))!=set(ids) or not is_floor_cover(entities[cover]) or is_floor_cover(entities[other]) or not cert.get('room_id') or any(entities[eid].get('room_id')!=cert['room_id'] for eid in ids)):return None provenance=evidence.get('provenance') or {} if (cert.get('scene_sha256')!=evidence.get('scene_sha256') or cert.get('scene_sha256')!=provenance.get('scene_sha256') or cert.get('manifest_fingerprint')!=evidence.get('manifest_fingerprint') or not isinstance(cert.get('mesh_fingerprint'),str) or len(cert['mesh_fingerprint'])!=64 or cert['mesh_fingerprint']!=provenance.get('mesh_fingerprint')):return None volume=pair.get('overlap_volume_m3') if not _finite(volume) or volume<=1e-15 or cert.get('overlap_volume_m3')!=volume:return None identity={k:entities[cover].get(k) for k in ('asset_id','asset_sha256','runtime_sha256','canonical_transform')} source_path,source_sha=cert.get('source_evidence_path'),cert.get('source_evidence_sha256') if (not identity['asset_id'] or identity['canonical_transform'] is None or cert.get('source_identity')!=identity or any(not isinstance(identity[k],str) or len(identity[k])!=64 or any(c not in '0123456789abcdef' for c in identity[k]) for k in ('asset_sha256','runtime_sha256')) or not isinstance(source_path,str) or not Path(source_path).is_absolute() or not isinstance(source_sha,str) or len(source_sha)!=64 or evidence.get('input_sha256',{}).get(source_path)!=source_sha):return None source=verify_surface_evidence(entities[cover],source_path,source_sha, inputs=dict(evidence['input_sha256'])) if (source['source_identity']!=identity or source['pool_candidate_key']!=entities[cover].get('pool_candidate_key')):return None floor=cert.get('common_floor_z_m');span=cert.get('intersection_z_range_m') names=cert.get('common_floor_mesh_names') band=cert.get('permitted_band_m') if not _finite(floor):return None if 'measured_cover_thickness_m' in cert: thickness=cert['measured_cover_thickness_m'];guard=export_arithmetic_guard(floor) low,high=evidence['entity_readbacks'][cover]['world_bbox_m'] if (not _finite(thickness) or thickness<=0 or thickness!=high[2]-floor or cert.get('policy_ceiling_m')!=.005 or cert.get('float32_export_arithmetic_guard_m')!=guard or band!=[0.,min(thickness,.005+guard)]):return None elif band!=[0.,.005]:return None if (not isinstance(span,list) or len(span)!=2 or not all(_finite(v) for v in span) or not floor<=span[0]<span[1]<=floor+band[1] or not isinstance(names,list) or not names or names!=sorted(set(names)) or any(not isinstance(n,str) or not (n=='floor' or n.startswith('floor__')) for n in names)): return None proofs=cert.get('floor_support_proofs');contacts=evidence.get('contact_checks') checks=evidence.get('entity_checks') if (not isinstance(proofs,list) or len(proofs)!=2 or any(not isinstance(p,dict) for p in proofs) or sorted(p.get('entity_id','') for p in proofs)!=ids or not isinstance(contacts,list) or not isinstance(checks,dict)):return None tolerance=evidence.get('contact_tolerance_m') if not _finite(tolerance) or not 0<tolerance<=1e-4:return None for eid in ids: if not _readback_matches(entities[eid],evidence):return None contract=resolve_support_contract(entities[eid],entities) summary=checks.get(eid) if (contract['status']!='ready' or contract['support_type']!='floor' or contract['support_entity_id'] is not None or not isinstance(summary,dict) or any(summary.get(k) is not True for k in ('solid_complete','contact_complete','contact_passed','collision_complete', 'collision_passed','geometry_complete','geometry_passed', 'full_geometry_complete','full_geometry_passed'))):return None proof=next(p for p in proofs if p['entity_id']==eid) rows=[c for c in contacts if isinstance(c,dict) and c.get('entity_id')==eid] bottom=evidence['entity_readbacks'][eid]['world_bbox_m'][0][2] if (len(rows)!=1 or proof.get('support_type')!='floor' or proof.get('support_entity_id') is not None or proof.get('complete') is not True or proof.get('passed') is not True or not _finite(proof.get('actual_bottom_z_m')) or abs(proof['actual_bottom_z_m']-bottom)>1e-9 or abs(bottom-floor)>1e-9 or proof.get('common_floor_mesh_names')!=names):return None bottom_proof=proof.get('bottom_contact_geometry_proof') if (not isinstance(bottom_proof,dict) or bottom_proof.get('method')!='complete_saved_triangle_minimum_plane_points_edges_faces_covered' or bottom_proof.get('complete') is not True or bottom_proof.get('passed') is not True or bottom_proof.get('uncovered_geometry_empty') is not True or not _finite(bottom_proof.get('actual_bottom_z_m')) or abs(bottom_proof['actual_bottom_z_m']-bottom)>1e-9 or bottom_proof.get('common_floor_mesh_names')!=names or bottom_proof.get('contact_geometry_kind') not in ('Point','MultiPoint', 'LineString','MultiLineString','Polygon','MultiPolygon','GeometryCollection')):return None contact=rows[0];gaps=contact.get('gaps_m');count=contact.get('sample_count') if (contact.get('support_type')!='floor' or contact.get('support_entity_id') is not None or contact.get('complete') is not True or contact.get('passed') is not True or contact.get('status')!='measured' or contact.get('pending_fields')!=[] or contact.get('method') not in ('bottom_vertices_and_face_centroids', 'saved_triangle_extreme_vertices_and_face_centroids_rays') or type(count) is not int or count<=0 or not isinstance(gaps,list) or len(gaps)!=count or any(not _finite(g) or not 0<=g<=tolerance for g in gaps)):return None lo,hi=evidence['entity_readbacks'][eid]['world_bbox_m'] # Native contacts may have only points/edges at the minimum plane. # The complete bottom geometry proof above remains mandatory; any # separately measured flat-region fields must also pass unchanged. if any(k in contact for k in ('flat_contact_region_checked','unsupported_area_m2','support_coverage')): if (contact.get('flat_contact_region_checked') is not True or not _finite(contact.get('unsupported_area_m2')) or contact['unsupported_area_m2']<0 or contact['unsupported_area_m2']>max(1e-12,(hi[0]-lo[0])*(hi[1]-lo[1])*1e-10) or not _finite(contact.get('support_coverage')) or not 1-1e-10<=contact['support_coverage']<=1):return None if eid==cover and not floor<=lo[2]<hi[2]<=floor+band[1]:return None return cert except (OSError,ValueError,KeyError,TypeError,OverflowError): return None def _exact_pair_clear(a, b, entities, evidence): if (evidence.get('collision_method') != 'manifold3d_solid_intersection' or not all(_readback_matches(entities[eid], evidence) for eid in (a, b))): return False pairs = evidence.get('pair_checks') if not isinstance(pairs, list): return False records = [p for p in pairs if isinstance(p, dict) and ((p.get('left') == a and p.get('right') == b) or (p.get('left') == b and p.get('right') == a))] if len(records) != 1: return False pair = records[0] volume = pair.get('overlap_volume_m3') complete_default = evidence.get('status') == 'measured' and evidence.get('complete') is True method = pair.get('method', 'manifold3d_solid_intersection') # The solid validator also proves disjoint saved meshes by their AABBs. # This proof must be explicit and exactly zero; solid penetration tolerances # and legacy default fields apply only to the intersection method. aabb_clear = (method == 'saved_mesh_aabb_separation' and pair.get('complete') is True and pair.get('status') == 'measured' and _finite(volume) and volume == 0) solid_clear = (method == 'manifold3d_solid_intersection' and _finite(volume) and (_zero_or_tolerated_overlap(pair) or _permitted_floor_cover_contact(a,b,entities,evidence,pair) is not None)) return (pair.get('passed') is True and pair.get('complete', complete_default) is True and pair.get('status', 'measured' if complete_default else None) == 'measured' and (aabb_clear or solid_clear or _passed_lift_probe(pair)) and not any(isinstance(d, dict) and d.get('code') == 'collision' and a in d.get('entity_ids', []) and b in d.get('entity_ids', []) for d in evidence.get('diagnostics', []))) def _measured_geometry(entities, rooms, program, report, geometry_evidence=None): evidence = geometry_evidence or {} polygons, heights = {}, {} room_boundary_cache = {} parents, _ = _support_order(entities) for eid in sorted(entities): row = entities[eid] polygon = _footprint(row) if polygon is None: report['unknowns'].append(_note('footprint_unknown', 'Measured footprint and its transform are required', entity_ids=[eid])) else: polygons[eid] = polygon bounds = rooms[row['room_id']].get('bounds_m') if bounds is None: report['unknowns'].append(_note('room_bounds_unknown', 'Room bounds are required for containment', entity_ids=[eid])) elif polygon.difference(box(*bounds)).area > _EPS: resolved = _saved_room_boundary(row, entities, bounds, program, evidence, room_boundary_cache) if resolved is not None: region, receipt = resolved report.setdefault('room_boundary_readbacks', []).append(receipt) else: region = box(*bounds) report['unknowns'].append(_note('room_boundary_geometry_unknown', 'Outside declared bounds requires a current saved room-wall boundary', entity_ids=[eid])) if polygon.difference(region).area > _EPS: report['issues'].append(_note('room_occupancy_outside', 'Measured footprint extends outside its assigned room', entity_ids=[eid])) if row.get('base_z_m') is None or row.get('dimensions_m') is None: report['unknowns'].append(_note('height_unknown', 'Base elevation and measured height are required', entity_ids=[eid])) else: heights[eid] = (row['base_z_m'], row['base_z_m'] + row['dimensions_m'][2]) requires_contact = (parents[eid] is not None or 'installation_gap' in row or resolve_support_contract(row, entities)['support_type'] != 'floor') if (requires_contact and not _measured_support(row, parents[eid], entities, evidence)): report['unknowns'].append(_note('support_contact_unknown', 'A support assignment and visual hull do not measure support contact', entity_ids=[eid])) elif requires_contact: skipped = [c for c in evidence.get('contact_checks', []) if isinstance(c, dict) and c.get('entity_id') == eid and c.get('status') == 'skipped'] if skipped: report.setdefault('skipped_checks', []).extend(copy.deepcopy(skipped)) if not _skipped_support_collisions_clear(entities, evidence): failed = any(isinstance(p, dict) and p.get('passed') is False for p in evidence.get('pair_checks', [])) or any( isinstance(d, dict) and d.get('code') == 'collision' for d in evidence.get('diagnostics', [])) report['issues' if failed else 'unknowns'].append(_note( 'collision' if failed else 'collision_geometry_unknown', 'Skipped installation support does not waive collision evidence', entity_ids=[eid])) ids = sorted(polygons) def ancestor(a, b): while b is not None: if b == a: return True b = parents[b] return False for i, a in enumerate(ids): for b in ids[i + 1:]: if a not in heights or b not in heights or ancestor(a, b) or ancestor(b, a): continue low = max(heights[a][0], heights[b][0]) high = min(heights[a][1], heights[b][1]) if (high - low > _EPS and polygons[a].intersection(polygons[b]).area > _EPS and not _exact_pair_clear(a, b, entities, evidence)): report['issues'].append(_note('occupancy_conflict', 'Measured polygons overlap within overlapping height intervals', entity_ids=[a, b])) elif high-low>_EPS and polygons[a].intersection(polygons[b]).area>_EPS: pairs=[p for p in evidence.get('pair_checks',[]) if isinstance(p,dict) and {p.get('left'),p.get('right')}=={a,b}] if len(pairs)==1: certificate=_permitted_floor_cover_contact(a,b,entities,evidence,pairs[0]) if certificate is not None: report.setdefault('permitted_floor_cover_contacts',[]).append(copy.deepcopy(certificate)) graph = program['room_graph'] approach = program['policy']['doorway_approach_m'] for opening in graph['edges'] + graph['entry_openings']: low, high = opening['interval_m'] line = opening['wall_line_m'] bounds = ((line - approach, low, line + approach, high) if opening['wall_orientation'] == 'V' else (low, line - approach, high, line + approach)) zone = box(*bounds) for eid, polygon in polygons.items(): if entities[eid]['room_id'] not in opening['room_ids']: continue # With no vertical opening measurements, XY intrusion still blocks # this conservative planning check; it never certifies clearance. head = opening.get('head_height_m', opening.get('opening_height_m', opening.get('door_height_m'))) sill = opening.get('sill_height_m', 0) if head is not None and eid in heights: if heights[eid][0] >= head or heights[eid][1] <= sill: continue if polygon.intersection(zone).area > _EPS: report['issues'].append(_note('doorway_conflict', 'Measured footprint enters passage approach: ' + opening['opening_id'], entity_ids=[eid])) def _task_value(manifest, key): if key in manifest or key != 'task_text': return manifest.get(key) declaration = manifest.get('joint_request') if not isinstance(declaration, dict): return None digest, text = declaration.get('sha256'), declaration.get('task_text') if (isinstance(digest, str) and len(digest) == 64 and all(c in '0123456789abcdef' for c in digest) and declaration.get('mode') in ('locked', 'pool') and isinstance(text, str) and text.strip()): return text return None def evaluate_room_program(manifest, program, geometry_evidence=None): """Audit contracts and polygons, optionally consuming a current geometry receipt. Pass the unmodified geometry_validation result. Its input_sha256 must pin the current saved manifest JSON and scene .blend, whose digests match manifest_sha256 and scene_sha256. A pending scene may resolve a complete local contact or exact pair check; other unknowns remain unresolved. Source installation receipts bind nominal wall gaps without relaxing tolerance. """ report = _report('rhg.wholehouse-room-evaluation.v1') try: _object(program, 'program') _json(program) if program.get('schema') != _SCHEMA: raise ValueError('Unsupported room program schema') baseline = program['baseline_manifest'] # Recompile the contract so altered cached domains/graphs cannot bypass # the frozen request and original manifest recorded in the program. if (_fingerprint(baseline) != program['source_manifest_sha256'] or _fingerprint(program['request']) != program['source_request_sha256']): raise ValueError('Room program source fingerprint mismatch') frozen = compile_room_program(baseline, program['request'], program['policy']) report['issues'].extend(frozen['issues']) report['warnings'].extend(frozen['warnings']) _object(manifest, 'manifest') _json(manifest) actual = _rows(manifest.get('entities'), 'entity_id', 'entities') original = {row['entity_id']: row for row in frozen['entities']} if actual.keys() != original.keys(): report['issues'].append(_note('entity_inventory_changed', 'Output entity inventory differs')) for key, code in (('floor_plan', 'floor_plan_changed'), ('seed', 'seed_changed'), ('source_assets', 'native_asset_changed')): if manifest.get(key) != baseline.get(key): report['issues'].append(_note(code, 'Output changed ' + key)) expected_relations = baseline.get('relations', frozen['request'].get('relations')) if ('relations' not in baseline and expected_relations is not None and 'relations' not in manifest): report['unknowns'].append(_note('relation_evidence_unknown', 'Output must declare the requested relations')) elif manifest.get('relations') != expected_relations: report['issues'].append(_note('relations_changed', 'Output changed relations')) for key in _TASK: expected = baseline.get(key, frozen['request'].get(key)) if key == 'task_kind': expected = baseline.get(key, frozen['request'].get(key, 'scene_generation')) value = manifest.get(key, baseline.get(key, 'scene_generation')) else: value = _task_value(manifest, key) if key not in baseline and key in frozen['request'] and value is None: report['unknowns'].append(_note('task_evidence_unknown', 'Output does not declare requested ' + key)) continue if value != expected: report['issues'].append(_note('task_kind_changed' if key == 'task_kind' else 'task_changed', 'Output changed ' + key)) furniture = {row['entity_id']: row for row in frozen['request']['furniture']} for eid in sorted(actual.keys() & original.keys()): row, old = actual[eid], original[eid] _geometry(row) if row.get('room_id') != old['room_id']: report['issues'].append(_note('room_assignment_changed', 'Output changed room', entity_ids=[eid])) transition = _binding_transition_fields(old, row, manifest) floor_range = _floor_range_released(old, row) if floor_range: transition = tuple(transition) + _FLOOR_RANGE_TRANSITION_FIELDS if any(row.get(key) != old.get(key) for key in _SEMANTICS if key not in transition): report['issues'].append(_note('entity_semantics_changed', 'Output changed entity semantics', entity_ids=[eid])) try: _parent(row) same_parent = (authored_support_parent(row, actual) == authored_support_parent(old, original)) except (ValueError, TypeError): same_parent = False if not same_parent and not floor_range: report['issues'].append(_note('support_assignment_changed', 'Output changed support assignment', entity_ids=[eid])) asset = row.get('asset_id') if asset not in frozen['asset_domains'][eid]: report['issues'].append(_note('asset_outside_domain', 'Output asset is outside the request domain', entity_ids=[eid])) elif asset != old['asset_id']: report['unknowns'].append(_note('native_candidate_evidence_unknown', 'Domain membership alone does not verify native size, source bytes or frame', entity_ids=[eid])) native_changed = any(row.get(key) != old.get(key) for key in _NATIVE) native_changed |= any(old.get(key) is not None and row.get(key) != old[key] for key in _SOURCE_GEOMETRY) if asset == old['asset_id'] and native_changed: report['issues'].append(_note('native_asset_changed', 'Output changed native asset fields', entity_ids=[eid])) pin = furniture[eid] if ((pin.get('source_sha256') and row.get('asset_sha256') != pin['source_sha256']) or (pin.get('record_id') and row.get('pool_candidate_key') != pin['record_id']) or ('candidate_record_ids' in pin and row.get('pool_candidate_key') not in pin['candidate_record_ids'])): report['issues'].append(_note('asset_pin_mismatch', 'Output violates a source or record pin', entity_ids=[eid])) if actual.keys() == original.keys(): _, rooms, entities = _inventory(manifest) evidence = _current_geometry_evidence(manifest, geometry_evidence) _measured_geometry(entities, rooms, frozen, report, evidence) if report.get('skipped_checks'): report['acceptance_scope'] = copy.deepcopy(evidence['acceptance_scope']) for key in ('full_geometry_complete', 'full_geometry_passed', 'full_scope_qualified'): report[key] = False except (ValueError, KeyError, TypeError, OverflowError, GEOSException) as error: report['issues'].append(_note('invalid_room_evidence', str(error))) report['passed'] = not report['issues'] and not report['unknowns'] return report
"""Frozen room contracts and measured polygon checks, without native execution.
Only declared doors and explicit open connections form the circulation graph.
World footprints are used as supplied; source footprints require a measured XY
center and yaw and use the native uniform-scale convention (default one).
Dimensions alone never stand in for a footprint or support-contact evidence.
"""
from __future__ import annotations
import copy
import hashlib
import heapq
import json
import math
from pathlib import Path
from shapely import affinity
from shapely.errors import GEOSException
from shapely.geometry import Polygon, box
if __package__:
from .floor_cover_contacts import is_floor_cover, export_arithmetic_guard
from .support_contract import authored_support_parent, resolve_support_contract, wall_gap_accepted, verify_surface_evidence
else:
from floor_cover_contacts import is_floor_cover, export_arithmetic_guard
from support_contract import authored_support_parent, resolve_support_contract, wall_gap_accepted, verify_surface_evidence
__all__ = ['compile_room_program', 'evaluate_room_program']
_SCHEMA = 'rhg.wholehouse-room-program.v1'
_SUPPORT = ('supported_by_entity_id', 'support_entity_id', 'parent_entity_id')
_SEMANTICS = ('role', 'category', 'procedural_kind', 'asset_pool_key',
'layout_slot_id', 'layout_relation', 'support_relation', 'support_type',
'front_target_entity_id', 'face_target_slot_id', '_layout_parent_id',
'_layout_targets', 'attributes', 'semantic_group', 'binding_semantic_key')
_NATIVE = ('dimensions_m', 'source_dimensions_m', 'uniform_scale', 'asset_sha256',
'runtime_sha256', 'canonical_path', 'runtime_path', 'canonical_transform',
'canonical_front_axis', 'pool_candidate_key', 'source_dependency_sha256',
'units', 'up_axis', 'prepared_source_frame_contract', 'source_geometry_probe_key')
_SOURCE_GEOMETRY = ('source_visual_footprint_polygon_xy_m', 'source_support_geometry',
'source_support_plane_offset_m')
_TASK = ('task_kind', 'task', 'task_text', 'natural_language_task', 'task_contract_v16',
'benchmark_episode_v16', 'required_entity_ids')
_EPS = 1e-9
# Explicit slot kinds accepted by the native binder, including its role aliases.
# Unknown kinds retain strict equality; they cannot opt into this transition.
_BINDING_ROLES = ('armchair', 'bed', 'book', 'bottle', 'bowl', 'cabinet',
'coffee_table', 'cup', 'desk', 'dining_chair', 'dining_table',
'lamp', 'mirror', 'plant', 'plate', 'range_hood', 'refrigerator',
'rug', 'shower', 'side_table', 'sink', 'sofa', 'television',
'toilet', 'vase', 'wardrobe')
_BINDING_KINDS = {role: (role, role) for role in _BINDING_ROLES}
_BINDING_KINDS.update({'fallback_asset_pool_' + role: (role, role)
for role in _BINDING_ROLES})
_BINDING_KINDS.update({
'kitchen_counter': ('cabinet', 'kitchen_counter'),
'kitchen_upper_cabinet': ('cabinet', 'upper_cabinet'),
# Generated house programs request overhead storage with procedural_kind 'upper_cabinet'.
'upper_cabinet': ('cabinet', 'upper_cabinet'),
'kitchen_sink': ('sink', 'kitchen_sink'),
'cooktop': ('oven', 'cooktop'),
'bookcase': ('cabinet', 'bookcase'),
'media_console': ('cabinet', 'media_console'),
'vanity_table': ('desk', 'vanity'),
'dining_plate': ('cup', 'plate'),
'bath_counter_bottle': ('cup', 'bottle'),
'small_bowl': ('vase', 'bowl'),
'counter_bowl': ('vase', 'bowl'),
'bath_sink': ('sink', 'sink'),
'bedroom_desk': ('desk', 'desk'),
'bedside_lamp': ('lamp', 'lamp'),
'book_stack': ('book', 'book'),
'guest_bed_compact': ('bed', 'bed'),
'master_bed_compact': ('bed', 'bed'),
'shower_stall': ('shower', 'shower'),
'table_cup': ('cup', 'cup'),
})
def _qualified_bookcase_source(bound):
"""Recognize a shelf taxonomy label only for an exact bookcase source."""
evidence=bound.get('source_semantic_evidence')
if (not isinstance(evidence,dict)
or evidence.get('schema')!='rhg.source_semantic_evidence.v1'
or evidence.get('evidence_verification')!='current_bytes_verified'):
return False
for source,target in (('asset_id','asset_id'),('source_sha256','asset_sha256'),
('runtime_sha256','runtime_sha256')):
if not bound.get(target) or evidence.get(source)!=bound[target]:return False
transform=bound.get('canonical_transform')
if (not isinstance(transform,list) or len(transform)!=16
or any(type(v) not in (int,float) or not math.isfinite(v) for v in transform)
or evidence.get('canonical_transform')!=transform):return False
role=evidence.get('semantic_role') or {}
authored=evidence.get('authored_source') or {}
return (isinstance(role,dict) and isinstance(authored,dict)
and isinstance(role.get('catalog_roles'),list)
and 'bookcase' in role['catalog_roles']
and role.get('authored_wordnet_category')=='bookcase'