"""Coordinate already selected dwelling suites without selecting or editing assets. compile_material_plan accepts a native structural manifest, or a composition with floor_plan.rooms (or rooms) and an embedded structural_materials dict. structural_material_manifest may also be an embedded dict; file references are never silently loaded. Native roles and room_floor_roles are preserved. Policy: pins maps native roles (or door_family) to material_id, family_id and/or material_revision constraints. wall_material_id and door_family_id are native selector aliases. style_traits is advisory; furniture_requirements maps entity IDs to explicit identity constraints on existing furniture metadata. Unsupported policy fields raise ValueError rather than silently dropping requirements. style is an explicit native request.style candidate filter (name, materials, palette_hex and compatibility thresholds), never a furniture shader override. compile_material_search_policy separates supported runtime selector pins from audit-only requirements. Floor/revision/furniture identity pins have no native selector equivalent here and still require output audits. Planning does not prove that a native selector ran or that a requested palette was qualified. Both APIs return finite JSON with schema, passed, issues, warnings and unknowns. Compilation proves plan consistency only. Audit additionally checks native slot assignments and dependency bytes. Advisory unknowns do not block passed; missing required evidence does. Neither API proves rendered material/camera fidelity. dependency_root resolves relative dependency paths; absolute paths stay absolute so a remote path is never guessed onto an unrelated local file. """ from __future__ import annotations import copy import hashlib import json from pathlib import Path import re SCHEMA = 'rhg.wholehouse-material-plan.v1' ROLES = ('interior_wall', 'door_leaf', 'door_frame', 'floor_dry', 'floor_wet') IDENTITY = ('material_id', 'family_id', 'material_revision') WET_TYPES = ('bathroom', 'kitchen', 'balcony') def _json(value): try: return json.loads(json.dumps(value, allow_nan=False, sort_keys=True)) except (TypeError, ValueError) as error: raise ValueError('Expected finite JSON data') from error def _report(phase): return dict(schema=SCHEMA, phase=phase, passed=False, issues=[], warnings=[], unknowns=[], visual_fidelity_proven=False, camera_fidelity_proven=False, furniture_materials_modified=False) def _add(report, field, code, location, blocking=True): row = dict(code=code, location=str(location)) if field == 'unknowns': row['blocking'] = blocking if row not in report[field]: report[field].append(row) def _finish(report): for field in ('issues', 'warnings', 'unknowns'): report[field].sort(key=lambda row: (row['location'], row['code'])) report['passed'] = not report['issues'] and not any( row['blocking'] for row in report['unknowns']) return _json(report) def _structural(manifest): if manifest.get('schema') == 'rhg.structural_material_manifest.v1' or 'roles' in manifest: return manifest for key in ('structural_materials', 'structural_material_manifest'): value = manifest.get(key) if isinstance(value, dict) and 'roles' in value: return value return {} def _policy(value): value = _json(value or {}) allowed = {'pins', 'style_traits', 'furniture_requirements', 'wall_material_id', 'door_family_id', 'style'} if not isinstance(value, dict) or set(value) - allowed: raise ValueError('Unsupported material policy') for key in ('pins', 'style_traits', 'furniture_requirements'): if not isinstance(value.setdefault(key, {}), dict): raise ValueError(key + ' must be an object') for alias, role, key in [('wall_material_id', 'interior_wall', 'material_id'), ('door_family_id', 'door_family', 'family_id')]: if value.get(alias) is not None: pin = value['pins'].setdefault(role, {}) if key in pin and pin[key] != value[alias]: raise ValueError('Conflicting explicit pin: ' + alias) pin[key] = value[alias] for role, pin in value['pins'].items(): if role not in (*ROLES, 'door_family'): raise ValueError('Unsupported pin role: ' + role) _validate_requirement(pin) for requirement in value['furniture_requirements'].values(): _validate_requirement(requirement) _style(value.get('style', {})) return value def _validate_requirement(requirement): if (not isinstance(requirement, dict) or not requirement or set(requirement) - set(IDENTITY) or any(not isinstance(v, str) or not v for v in requirement.values())): raise ValueError('Requirements must specify material_id/family_id/material_revision strings') def _style(style, complete=False): allowed = {'name', 'compatible_labels', 'minimum_compatibility', 'materials', 'palette_hex', 'maximum_palette_distance', 'shape_terms', 'maximum_combination_distance'} if not isinstance(style, dict) or set(style) - allowed: raise ValueError('Unsupported native style filter') if 'name' in style or complete: if not isinstance(style.get('name'), str) or not style['name'].strip(): raise ValueError('Native style filter requires a style name') for key in ('materials', 'palette_hex', 'shape_terms'): if key in style: values = style[key] if (not isinstance(values, list) or not values or any(not isinstance(v, str) or not v.strip() for v in values)): raise ValueError(key + ' must be a nonempty string list') if key == 'palette_hex' and any(not re.fullmatch('#?[0-9a-fA-F]{6}', v) for v in values): raise ValueError('Invalid palette_hex') for key in ('minimum_compatibility', 'maximum_palette_distance', 'maximum_combination_distance'): if key in style and (type(style[key]) not in (int, float) or not 0 <= style[key] <= 1): raise ValueError(key + ' must be a finite number between zero and one') if 'compatible_labels' in style: labels = style['compatible_labels'] if (not isinstance(labels, dict) or not labels or any(not isinstance(k, str) or not k.strip() or type(v) not in (int, float) or not 0 < v <= 1 for k, v in labels.items())): raise ValueError('compatible_labels requires positive finite weights up to one') def compile_material_search_policy(policy=None, request_style=None, *, require_style_name=False): """Return native request/runtime inputs and explicit enforcement limitations. The native selector accepts wall material IDs and a shared door family ID. Other pins remain output requirements; do not inject unsupported scene or runtime fields. style_traits remains advisory and is never promoted to a hard palette filter. Explicit style fields merge only without conflicts. """ policy = _policy(policy) style = copy.deepcopy(request_style) if policy.get('style'): if style is None: style = {} if not isinstance(style, dict): raise ValueError('Native style filter must be an object') for key, value in policy['style'].items(): if key in style and style[key] != value: raise ValueError('Conflicting explicit native style field: ' + key) style[key] = copy.deepcopy(value) _style(style, complete=require_style_name) pins = copy.deepcopy(policy['pins']) runtime = {} for role, field, key in [('interior_wall', 'material_id', 'wall_material_id'), ('door_family', 'family_id', 'door_family_id')]: if field in pins.get(role, {}): runtime[key] = pins[role].pop(field) if not pins[role]: del pins[role] return _json(dict(request_style=style, runtime_overrides=runtime, audit_only_pins=pins, audit_only_furniture_requirements=policy['furniture_requirements'], search_enforced=False, palette_qualification_proven=False)) def compile_material_plan(manifest, policy=None): """Freeze native selections and derive room continuity, with no reselection.""" manifest = _json(manifest) if not isinstance(manifest, dict): raise ValueError('manifest must be an object') structural = _structural(manifest) policy = _policy(policy) plan = _report('compile') rooms = manifest.get('floor_plan', {}).get('rooms', manifest.get('rooms')) if rooms is None: rooms = [{'room_id': room} for room in structural.get('room_floor_roles', {})] _add(plan, 'unknowns', 'room_inventory_independent_evidence_unknown', 'rooms') if not isinstance(rooms, list) or any(not isinstance(r, dict) or not isinstance(r.get('room_id'), str) or not r['room_id'] for r in rooms): raise ValueError('rooms must contain room_id strings') ids = [room['room_id'] for room in rooms] if len(ids) != len(set(ids)): _add(plan, 'issues', 'duplicate_room_id', 'rooms') plan.update(scene_id=manifest.get('scene_id', structural.get('scene_id')), rooms=sorted(rooms, key=lambda r: r['room_id']), selected_suites=copy.deepcopy(structural.get('roles', {})), room_wall_roles=copy.deepcopy(structural.get('room_wall_roles', {})), source_dependency_sha256=copy.deepcopy(structural.get('source_dependency_sha256', {})), policy=policy, search_policy=compile_material_search_policy(policy), furniture=copy.deepcopy(manifest.get('entities', manifest.get('furniture', []))), room_assignments=[], continuity_groups=[]) for room in plan['rooms']: rid = room['room_id'] if room.get('room_type'): floor_role = 'floor_wet' if room['room_type'] in WET_TYPES or rid in ('bath', 'kitchen', 'balcony') else 'floor_dry' elif rid in ('bath', 'kitchen', 'balcony'): floor_role = 'floor_wet' else: floor_role = structural.get('room_floor_roles', {}).get(rid) _add(plan, 'unknowns', 'room_type_unknown', rid) plan['room_assignments'].append(dict(room_id=rid, floor_role=floor_role, wall_role='interior_wall', door_roles=['door_leaf', 'door_frame'])) for group, roles in [('walls', ['interior_wall']), ('door_family', ['door_leaf', 'door_frame']), ('dry_floors', ['floor_dry']), ('wet_floors', ['floor_wet'])]: members = [row['room_id'] for row in plan['room_assignments'] if not group.endswith('_floors') or row['floor_role'] == roles[0]] plan['continuity_groups'].append(dict(group_id=group, roles=roles, room_ids=members)) _check_selection(plan, structural) return _finish(plan) def _require(report, record, requirement, location): for key, expected in requirement.items(): if record.get(key) is None: _add(report, 'unknowns', 'explicit_requirement_evidence_unknown', location + '/' + key) elif record[key] != expected: _add(report, 'issues', 'explicit_requirement_mismatch', location + '/' + key) def _check_selection(report, structural): roles = structural.get('roles', {}) expected = {r['room_id']: r['floor_role'] for r in report['room_assignments']} actual = structural.get('room_floor_roles', {}) if 'room_floor_roles' not in structural: _add(report, 'unknowns', 'floor_assignments_unknown', 'room_floor_roles') elif set(expected) != set(actual): _add(report, 'issues', 'room_coverage_mismatch', 'room_floor_roles') if not expected: _add(report, 'unknowns', 'room_inventory_unknown', 'rooms') for room, role in expected.items(): if role not in ('floor_dry', 'floor_wet'): _add(report, 'unknowns', 'floor_role_unknown', room) elif 'room_floor_roles' in structural and actual.get(room) != role: _add(report, 'issues', 'floor_role_mismatch', room) required = {'interior_wall', 'door_leaf', 'door_frame'} | {v for v in expected.values() if v} for role in sorted(required): if role not in roles: _add(report, 'unknowns', 'selected_suite_unknown', role) room_wall_roles = structural.get('room_wall_roles', {}) registered_wall_roles = {'interior_wall__room__' + room for room in expected if isinstance(room_wall_roles, dict) and room_wall_roles.get(room) == 'interior_wall__room__' + room} for role, spec in sorted(roles.items()): if role not in ROLES and role not in registered_wall_roles: _add(report, 'issues', 'unexpected_structural_role', role) for key in IDENTITY: if not spec.get(key): _add(report, 'unknowns', 'selected_identity_unknown', role + '/' + key) if role in ('floor_dry', 'floor_wet') and spec.get('role', role) != role: _add(report, 'issues', 'floor_role_mismatch', role) requested = spec.get('requested_material_or_family_id') if requested is not None and requested not in ( (spec.get('material_id'), spec.get('family_id')) if role.startswith('door_') else (spec.get('material_id'),)): _add(report, 'issues', 'explicit_requirement_mismatch', role) old = report['selected_suites'].get(role) if old is not None and old != spec: _add(report, 'issues', 'selected_suite_mismatch', role) if set(report['selected_suites']) != set(roles): _add(report, 'issues', 'selected_suite_mismatch', 'roles') leaf, frame = roles.get('door_leaf', {}), roles.get('door_frame', {}) if leaf.get('family_id') != frame.get('family_id'): _add(report, 'issues', 'door_family_mismatch', 'door_family') if any(leaf.get(k) != frame.get(k) for k in (*IDENTITY, 'channels', 'texture_scale_m')): _add(report, 'issues', 'door_suite_mismatch', 'door_family') for role, requirement in report['policy']['pins'].items(): for native in ('door_leaf', 'door_frame') if role == 'door_family' else (role,): _require(report, roles.get(native, {}), requirement, native) furniture = {r.get('entity_id'): r for r in report['furniture']} for entity, requirement in report['policy']['furniture_requirements'].items(): record = furniture.get(entity, {}) metadata = dict(record.get('material_metadata', {}), **{k: record[k] for k in IDENTITY if k in record}) _require(report, metadata, requirement, 'furniture/' + entity) for entity, record in sorted(furniture.items(), key=lambda pair: str(pair[0])): for trait, preferred in report['policy']['style_traits'].items(): actual_trait = record.get('style_traits', {}).get(trait) if actual_trait is None: _add(report, 'unknowns', 'style_metadata_unknown', str(entity) + '/' + trait, False) elif actual_trait != preferred: _add(report, 'warnings', 'style_preference_mismatch', str(entity) + '/' + trait) if structural.get('furniture_materials_modified') or structural.get('application', {}).get('furniture_materials_touched'): _add(report, 'issues', 'furniture_material_override', 'furniture') def _sha(path): before = path.stat() digest = hashlib.sha256() with path.open('rb') as stream: for block in iter(lambda: stream.read(1024 * 1024), b''): digest.update(block) after = path.stat() fields = ('st_dev', 'st_ino', 'st_size', 'st_mtime_ns', 'st_ctime_ns') if any(getattr(before, key) != getattr(after, key) for key in fields): raise OSError('Dependency changed while hashing') return digest.hexdigest() def audit_material_plan(plan, structural_manifest, dependency_root=None): """Check selection, observed native slots and available dependency bytes.""" plan, structural = _json(plan), _json(structural_manifest) if plan.get('schema') != SCHEMA: raise ValueError('Unsupported material plan schema') report = copy.deepcopy(plan) report.update(phase='audit', passed=False, issues=[], warnings=[], unknowns=[], visual_fidelity_proven=False, camera_fidelity_proven=False, furniture_materials_modified=False) # Recompile inventory checks instead of trusting a cached passed flag. baseline = compile_material_plan(dict(rooms=plan['rooms'], structural_materials={ 'roles': plan['selected_suites'], 'room_floor_roles': { row['room_id']: row['floor_role'] for row in plan['room_assignments']}, 'room_wall_roles': plan.get('room_wall_roles', {}), 'source_dependency_sha256': plan['source_dependency_sha256']}, entities=plan['furniture']), plan['policy']) report['search_policy'] = baseline['search_policy'] for field in ('issues', 'warnings', 'unknowns'): report[field].extend(baseline[field]) if baseline['room_assignments'] != plan['room_assignments'] or baseline['continuity_groups'] != plan['continuity_groups']: _add(report, 'issues', 'plan_continuity_mismatch', 'room_assignments') if plan.get('scene_id') is not None and structural.get('scene_id') != plan['scene_id']: _add(report, 'issues', 'scene_identity_mismatch', 'scene_id') _check_selection(report, structural) roles = structural.get('roles', {}) expected = {r['room_id']: r['floor_role'] for r in report['room_assignments']} seen_rooms, seen_roles, slots = set(), set(), set() continuous=structural.get('floor_geometry_schema')=='rhg.continuous-room-partitioned-floor.v1' region_rooms=structural.get('floor_region_room_ids',[]) if continuous else [] partition_valid=(isinstance(region_rooms,list) and all(isinstance(room,str) for room in region_rooms) and len(region_rooms)==len(set(region_rooms)) and set(region_rooms)==set(expected)) if continuous and not partition_valid: _add(report,'issues','floor_region_partition_mismatch','floor_region_room_ids') for index, row in enumerate(structural.get('assignments', [])): role, room = row.get('role'), row.get('room_id') location = 'assignments/' + str(index) if role not in roles: _add(report, 'issues', 'assignment_role_unknown', location) continue seen_roles.add(role) slot = (row.get('object_name'), row.get('material_slot_index')) if slot in slots: _add(report, 'issues', 'duplicate_assignment_slot', location) slots.add(slot) if role in ('floor_dry', 'floor_wet'): expected_object='floor__whole_house' if continuous else 'floor__'+str(room) partition_matches=(not continuous or (partition_valid and room in region_rooms and type(row.get('material_slot_index')) is int and row['material_slot_index']==region_rooms.index(room)+1 and row.get('object_material_slot_count')==len(region_rooms)+1)) if (room not in expected or expected[room] != role or row.get('object_name') != expected_object or not partition_matches): _add(report, 'issues', 'floor_role_mismatch', location) else: seen_rooms.add(room) elif str(row.get('object_name', '')).startswith('floor__'): _add(report, 'issues', 'floor_role_mismatch', location) for key in ('material_id', 'family_id'): if not row.get(key): _add(report, 'unknowns', 'assignment_identity_unknown', location + '/' + key) elif row[key] != roles[role].get(key): _add(report, 'issues', 'assignment_suite_mismatch', location + '/' + key) for key in ('material_revision', 'uv_policy', 'texture_scale_m'): if key in row and row[key] != roles[role].get(key): _add(report, 'issues', 'assignment_suite_mismatch', location + '/' + key) for room in sorted(set(expected) - seen_rooms): _add(report, 'issues', 'room_assignment_missing', room) for role in ('interior_wall', 'door_leaf'): if role not in seen_roles: _add(report, 'unknowns', 'surface_assignment_unknown', role) if 'door_frame' not in seen_roles: reason = structural.get('application', {}).get('target_absence_reasons', {}).get('door_frame') _add(report, 'warnings' if reason else 'unknowns', 'door_frame_geometry_absent' if reason else 'surface_assignment_unknown', 'door_frame') dependencies = dict(structural.get('source_dependency_sha256', {})) for path, sha in plan['source_dependency_sha256'].items(): if dependencies.get(path) != sha: _add(report, 'issues', 'dependency_manifest_mismatch', path) dependencies.setdefault(path, sha) for role, spec in sorted(roles.items()): channels = spec.get('channels', {}) for channel in sorted(set(spec.get('required_channels', [])) | {'baseColor', 'roughness', 'normal'}): if not channels.get(channel): _add(report, 'issues', 'pbr_channel_missing', role + '/' + channel) for channel, record in sorted(channels.items()): location = role + '/' + channel space = record.get('color_space') if space is None: _add(report, 'unknowns', 'channel_color_space_unknown', location) elif space != ('sRGB' if channel == 'baseColor' else 'raw'): _add(report, 'issues', 'channel_color_space_mismatch', location) records = [(record.get('source_path'), record.get('sha256'))] conversion = record.get('conversion') if conversion: records.append((conversion.get('source_path'), conversion.get('source_sha256'))) if conversion.get('sha256') != record.get('sha256'): _add(report, 'issues', 'normal_conversion_mismatch', location) for path, sha in records: if not path or not sha: _add(report, 'unknowns', 'channel_dependency_unknown', location) else: if dependencies.get(path) != sha: _add(report, 'issues', 'channel_dependency_mismatch', location) dependencies.setdefault(path, sha) normal = spec.get('normal_convention') if normal is None: _add(report, 'unknowns', 'normal_convention_unknown', role) elif normal != 'OpenGL': _add(report, 'issues', 'normal_convention_mismatch', role) if not spec.get('normal_convention_provenance'): _add(report, 'unknowns', 'normal_provenance_unknown', role) if not spec.get('uv_policy') or not spec.get('texture_scale_provenance'): _add(report, 'unknowns', 'coordinate_provenance_unknown', role) scale = spec.get('texture_scale_m') if not isinstance(scale, list) or len(scale) != 2 or any(type(v) not in (int, float) or v <= 0 for v in scale): _add(report, 'issues', 'texture_scale_invalid', role) if not dependencies: _add(report, 'unknowns', 'dependency_evidence_unknown', 'source_dependency_sha256') report['dependency_checks'] = [] for name, expected_sha in sorted(dependencies.items()): if not isinstance(expected_sha, str) or not re.fullmatch('[0-9a-fA-F]{64}', expected_sha): _add(report, 'issues', 'dependency_hash_invalid', name) continue path = Path(name) if not path.is_absolute(): if dependency_root is None: _add(report, 'unknowns', 'dependency_unavailable', name) continue path = Path(dependency_root) / path try: actual_sha = _sha(path) except FileNotFoundError: local = dependency_root is not None or path.parent.exists() _add(report, 'issues' if local else 'unknowns', 'dependency_missing' if local else 'dependency_unavailable', name) continue except OSError: _add(report, 'unknowns', 'dependency_unreadable', name) continue report['dependency_checks'].append(dict(source_path=name, sha256=actual_sha, matched=actual_sha == expected_sha.lower())) if actual_sha != expected_sha.lower(): _add(report, 'issues', 'dependency_hash_mismatch', name) _add(report, 'unknowns', 'material_camera_visual_fidelity_unproven', 'rendering', False) return _finish(report)