RoboHome / code /robohome /src /engine /feedback.py
RoboParty Release
Unify robohome source, assets and scenes delivery
3f15e9f
Raw History Blame Contribute Delete
62.8 kB
"""Structured, execution-free local repair planning (Python >= 3.9, stdlib only). Schema references are the separately copied ``source/`` snapshot's ``real_assets/joint_layout.py``, ``requested_shell.py``, ``functional_layout.py`` and ``packages/scene_generation/dependency_graph.py``. Nothing imports or edits those scripts. Requests use ``rhg.scene_request.v1``, exhaustive ``furniture`` and optional exhaustive ``entities`` rows; manifests use ``entities`` and ``floor_plan.rooms``. Unknown extra JSON fields are retained. Dependencies must be structured: support aliases (supported_by_entity_id, support_entity_id, parent_entity_id), front entity/slot targets, compiled layout parents/targets, attributes.depends_on, and relations with kind/subject/object (optionally target). Callers must materialize any additional solver-inferred relations into the request. Prose is never parsed for IDs. Non-null support aliases must agree within and across manifest/request rows; normalization is internal and does not rewrite those rows. Repair requests include solver locks and joint failure exclusions. Planning alone does not certify enforcement; the native report and verifier do that. The default verifier permits only affected center_xy_m/yaw_deg/base_z_m changes. Plans for final native joint bindings explicitly select native_joint_binding_v1: request hashes and two execution paths may change, and known pose-derived fields must agree with the new pose. Contact-dependent repairs fail closed. Task data, policies, source identities, dimensions and unrelated records remain frozen. """ import copy import hashlib import json import math from collections import deque __all__ = ["plan_repair", "verify_preservation", "geometry_scope_supported"] _PLAN_SCHEMA = "rhg.frontier.repair-plan.v1" _VERIFY_SCHEMA = "rhg.frontier.preservation-verification.v1" _PREFERENCES = ("preferred_center_xy_m", "preferred_yaw_deg", "installation_height_m") _SUPPORT_ALIASES = ("supported_by_entity_id", "support_entity_id", "parent_entity_id") _MANIFEST_POSE = frozenset(("center_xy_m", "yaw_deg", "base_z_m")) _LOCK_PROVENANCE_SCHEMA = "rhg.repair-lock-provenance.v1" _NATIVE_PROFILE = "native_joint_binding_v1" _STATUSES = frozenset(("repair_planned", "manual_review_required", "budget_exhausted", "no_repair_needed")) _PRESERVATION_NOTE = ( "Preserved IDs are requested preservation only; solver enforcement and " "post-repair verification are required. No repair has been executed." ) def _json_data(value): """Reject non-JSON objects and nonfinite numbers before copying or hashing.""" def check(item): kind = type(item) if kind is dict: for key, child in item.items(): if type(key) is not str: raise ValueError("JSON object keys must be strings") check(child) elif kind is list: for child in item: check(child) elif kind is float: if not math.isfinite(item): raise ValueError("JSON numbers must be finite") elif kind not in (str, int, bool, type(None)): raise ValueError("Inputs must contain only JSON data") try: check(value) except RecursionError as exc: raise ValueError("JSON data must be acyclic and within nesting limits") from exc def _encoded(value, *, canonical=False): return json.dumps(value, sort_keys=canonical, separators=(",", ":"), allow_nan=False).encode("utf-8") def _fingerprint(value): return hashlib.sha256(_encoded(value, canonical=True)).hexdigest() def _text(value, label): if type(value) is not str or not value.strip(): raise ValueError(label + " must be a nonempty string") return value def _object(value, label): if type(value) is not dict: raise ValueError(label + " must be an object") return value def _id_list(value, label, *, unique=True): if type(value) is not list: raise ValueError(label + " must be a list of entity IDs") for item in value: _text(item, label + " item") if unique and len(value) != len(set(value)): raise ValueError(label + " must contain unique IDs") return value def _rows(value, label, *, id_key="entity_id"): if type(value) is not list or not value: raise ValueError(label + " must be a nonempty inventory list") indexed = {} for row in value: _object(row, label + " row") entity_id = _text(row.get(id_key), label + "." + id_key) if entity_id in indexed: raise ValueError("Duplicate " + label + " ID: " + entity_id) indexed[entity_id] = row return indexed def _numeric(value, label): if type(value) not in (int, float) or (type(value) is float and not math.isfinite(value)): raise ValueError(label + " must be finite numeric data") def _vector(value, length, label, *, positive=False): if type(value) is not list or len(value) != length: raise ValueError(label + " must have " + str(length) + " numeric components") for number in value: _numeric(number, label) if positive and number <= 0: raise ValueError(label + " components must be positive") def _geometry(row): for key in ("center_xy_m", "preferred_center_xy_m"): if key in row: _vector(row[key], 2, key) for key in ("dimensions_m", "source_dimensions_m"): if key in row: _vector(row[key], 3, key, positive=True) for key in ("yaw_deg", "base_z_m", "preferred_yaw_deg", "installation_height_m", "uniform_scale"): if key in row: _numeric(row[key], key) if "uniform_scale" in row and row["uniform_scale"] <= 0: raise ValueError("uniform_scale must be positive") if "asset_id" in row: _text(row["asset_id"], "asset_id") def _manifest(manifest): _object(manifest, "manifest") _json_data(manifest) floor_plan = _object(manifest.get("floor_plan"), "manifest.floor_plan") rooms = _rows(floor_plan.get("rooms"), "floor_plan.rooms", id_key="room_id") for room in rooms.values(): if "bounds_m" in room: bounds = room["bounds_m"] _vector(bounds, 4, "room.bounds_m") if bounds[0] >= bounds[2] or bounds[1] >= bounds[3]: raise ValueError("Room bounds must enclose positive area") entities = _rows(manifest.get("entities"), "manifest.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) _geometry(row) return entities def _request(request, manifest, entities): _object(request, "request") _json_data(request) if request.get("schema") != "rhg.scene_request.v1": raise ValueError("Expected request schema rhg.scene_request.v1") if request.get("mode") not in ("locked", "pool"): raise ValueError("Request mode must be locked or pool") _text(request.get("task_text"), "request.task_text") furniture = _rows(request.get("furniture"), "request.furniture") collections = [entities, furniture] if "entities" in request: if request.get("task_kind") != "scene_generation": raise ValueError("Projected entities require task_kind=scene_generation") collections.append(_rows(request["entities"], "request.entities")) for collection in collections[1:]: if collection.keys() != entities.keys(): raise ValueError("Full request entity inventory must match manifest") for entity_id, row in collection.items(): _geometry(row) if "room_id" in row and row["room_id"] != entities[entity_id]["room_id"]: raise ValueError("Request entity room differs from manifest: " + entity_id) for row in furniture.values(): if request["mode"] == "locked": _text(row.get("asset_id"), "locked asset_id") else: candidates = _id_list(row.get("candidate_asset_ids"), "candidate_asset_ids") if not candidates: raise ValueError("candidate_asset_ids must be a nonempty domain") if ("floor_plan_sha256" in request and request["floor_plan_sha256"] != _fingerprint(manifest["floor_plan"])): raise ValueError("Request floor_plan_sha256 differs from manifest floor_plan") if "floor_plan" in request and _encoded(request["floor_plan"]) != _encoded(manifest["floor_plan"]): raise ValueError("Request floor_plan differs from manifest floor_plan") return collections def _dependencies(entities, collections, manifest, request): downstream = {entity_id: set() for entity_id in entities} slots = {} support_parents = {} for collection in collections: for entity_id, row in collection.items(): for key in _SUPPORT_ALIASES: parent = row.get(key) if parent is None: continue _text(parent, key) if entity_id in support_parents and support_parents[entity_id] != parent: raise ValueError("Contradictory support aliases for entity: " + entity_id) support_parents[entity_id] = parent if row.get("layout_slot_id") is not None: slot_id = _text(row["layout_slot_id"], "layout_slot_id") slot_key = (entities[entity_id]["room_id"], slot_id) slots.setdefault(slot_key, set()).add(entity_id) def add(parent, subject, label, *, same_room=True): _text(parent, label) if parent not in entities: raise ValueError("Unknown " + label + " entity ID: " + parent) if parent == subject: raise ValueError("Self dependency in " + label + ": " + subject) if same_room and entities[parent]["room_id"] != entities[subject]["room_id"]: raise ValueError("Cross-room " + label + " requires manual reconciliation") downstream[parent].add(subject) for entity_id, parent in support_parents.items(): add(parent, entity_id, "support relation") for collection in collections: for entity_id, row in collection.items(): for key in ("front_target_entity_id", "_layout_parent_id"): if key in row and row[key] not in (None, ""): add(row[key], entity_id, key) if row.get("face_target_slot_id") not in (None, ""): slot_id = _text(row["face_target_slot_id"], "face_target_slot_id") targets = slots.get((entities[entity_id]["room_id"], slot_id), set()) if len(targets) != 1: raise ValueError("Unknown or ambiguous face_target_slot_id: " + slot_id) add(next(iter(targets)), entity_id, "face_target_slot_id") if "_layout_targets" in row: for target in _id_list(row["_layout_targets"], "_layout_targets"): add(target, entity_id, "_layout_targets") if row.get("attributes") is not None: attributes = _object(row["attributes"], "attributes") for parent in _id_list(attributes.get("depends_on", []), "attributes.depends_on"): add(parent, entity_id, "attributes.depends_on", same_room=False) for source in (manifest, request): relations = source.get("relations", []) if type(relations) is not list: raise ValueError("relations must be a list") for relation in relations: _object(relation, "relation") _text(relation.get("kind"), "relation.kind") subject = _text(relation.get("subject"), "relation.subject") if subject not in entities: raise ValueError("Unknown relation subject: " + subject) parent = relation.get("object") add(parent, subject, "relation.object") if "target" in relation: target = relation["target"] add(target, subject, "relation.target") add(target, parent, "relation.target") return downstream def _diagnostics(diagnostics, entities): _json_data(diagnostics) if type(diagnostics) is not list: raise ValueError("diagnostics must be a list of objects") direct = set() for diagnostic in diagnostics: _object(diagnostic, "diagnostic") _text(diagnostic.get("code"), "diagnostic.code") _text(diagnostic.get("message"), "diagnostic.message") for entity_id in _id_list(diagnostic.get("entity_ids"), "diagnostic.entity_ids", unique=False): if entity_id not in entities: raise ValueError("Unknown diagnostic entity ID: " + entity_id) direct.add(entity_id) return [entity_id for entity_id in entities if entity_id in direct] def _sha256(value): return (type(value) is str and len(value) == 64 and all(c in "0123456789abcdefABCDEF" for c in value)) def _native_manifest(manifest): binding = manifest.get("fixed_layout_real_asset_binding") joint = manifest.get("joint_request") return (isinstance(binding, dict) and binding.get("final_binding_passed") is True and binding.get("binding_phase") == "final" and binding.get("uniform_scale_only") is True and binding.get("preserve_source_materials") is True and isinstance(joint, dict) and _sha256(joint.get("sha256")) and joint.get("mode") in ("locked", "pool") and isinstance(joint.get("task_text"), str) and bool(joint["task_text"].strip()) and isinstance(joint.get("relations"), list) and isinstance(joint.get("effective_policies"), dict)) def _native_metadata(manifest): metadata = copy.deepcopy({k: v for k, v in manifest.items() if k not in ("entities", "floor_plan")}) metadata["joint_request"].pop("sha256") binding = metadata["fixed_layout_real_asset_binding"] _text(binding.get("source_scene"), "native binding source_scene") binding.pop("source_scene") shell = metadata.get("joint_layout_constraint_evidence") if isinstance(shell, dict) and shell.get("shell_input_path") is not None: _text(shell["shell_input_path"], "native shell_input_path") if not _sha256(shell.get("shell_input_sha256")): raise ValueError("Native shell path requires its immutable content SHA256") shell.pop("shell_input_path") return metadata def _close(actual, expected, label): _numeric(actual, label) if not math.isclose(actual, expected, rel_tol=0., abs_tol=1e-6): raise ValueError("Stale or inconsistent native pose evidence: " + label) def _close_vector(actual, expected, label): _vector(actual, len(expected), label) for a, b in zip(actual, expected): _close(a, b, label) def _bound_seam_measurement(row, contact, summary, evidence): """Bind reconciliation to the independent worker's unchanged measurement. Pipeline implementation pins already include feedback.py. Geometry and its seam helper are additionally pinned by the saved geometry producer itself. """ from pathlib import Path if __package__: from .geometry_validation import _file_sha256 else: from geometry_validation import _file_sha256 try: pins = evidence['input_sha256'] result_path = evidence['result_path'] if type(pins) is not dict or type(result_path) is not str or not Path(result_path).is_absolute(): return False audit_path = Path(result_path).parent / 'solid_audit.json' implementations = [Path(__file__).resolve().with_name(name) for name in ('geometry_validation.py', 'saved_mesh_seams.py')] for path in [*implementations, audit_path]: expected = pins.get(str(path)) if not _sha256(expected) or _file_sha256(path) != expected: return False audit = json.loads(audit_path.read_text()) provenance = evidence['provenance'] for path_key, hash_key in (('scene_path','scene_sha256'), ('mesh_path','mesh_sha256')): path, digest = provenance.get(path_key), provenance.get(hash_key) if (type(path) is not str or not Path(path).is_absolute() or not _sha256(digest) or pins.get(path) != digest): return False if (provenance['scene_sha256'] != evidence.get('scene_sha256') or not _sha256(provenance.get('mesh_fingerprint')) or any(audit.get('provenance', {}).get(key) != provenance.get(key) for key in ('scene_sha256', 'mesh_sha256', 'mesh_path', 'mesh_fingerprint'))): return False contacts = [c for c in audit['contact_checks'] if c.get('entity_id') == row['entity_id']] return (len(contacts) == 1 and contacts[0] == contact and audit['entity_checks'][row['entity_id']] == summary) except (OSError, ValueError, KeyError, TypeError, AttributeError): return False def _measured_seam(row, entities, contact, summary, evidence, tolerance): """Reconcile a rigid seam's typed raw measurements, never a receipt pass.""" seam = contact.get('seam_bridging') parent = entities.get(contact.get('support_entity_id')) if (type(seam) is not dict or not parent or row.get('layout_slot_id') != 'kitchen_cooktop' or row.get('role') not in ('oven','cooktop') or parent.get('layout_slot_id') != 'kitchen_counter' or (row.get('supported_by_entity_id') or row.get('support_entity_id')) != parent['entity_id'] or row.get('uniform_scale', 1.) != 1. or contact.get('entity_id') != row['entity_id'] or contact.get('passed') is not True or summary.get('contact_passed') is not True or summary.get('solid_complete') is not True or summary.get('contact_complete') is not True or contact.get('complete') is not True or contact.get('status') != 'measured' or contact.get('pending_fields') != [] or contact.get('flat_contact_region_checked') is not True or seam.get('policy') != 'rigid_cooktop_counter_interior_seam_v1' or seam.get('method') != 'saved_actual_flat_triangles_parallel_exterior_edges' or seam.get('physical_stability') != 'unknown_not_simulated' or any(seam.get(key) is not False for key in ('source_region_modified', 'physical_qualified', 'whole_task_acceptance'))): return False fields = ('maximum_allowed_width_m', 'maximum_unsupported_width_m', 'minimum_actual_support_fraction', 'actual_support_fraction', 'actual_support_area_m2', 'unsupported_projection_area_m2', 'bottom_area_m2', 'actual_contact_tolerance_m', 'minimum_actual_contact_gap_m', 'maximum_actual_contact_gap_m') if any(type(seam.get(key)) not in (int,float) or not math.isfinite(seam[key]) for key in fields): return False total, supported, missing = (seam[key] for key in ('bottom_area_m2','actual_support_area_m2','unsupported_projection_area_m2')) fraction = seam['actual_support_fraction'] gap_low, gap_high = seam['minimum_actual_contact_gap_m'], seam['maximum_actual_contact_gap_m'] strict_tolerance = min(tolerance, 1e-5) if (seam['maximum_allowed_width_m'] != .01 or not 0 < seam['maximum_unsupported_width_m'] <= .01+1e-12 or seam['minimum_actual_support_fraction'] != .95 or not .95 <= fraction < 1. or total <= 1e-12 or supported <= 0 or missing <= max(1e-12,total*1e-10) or seam['actual_contact_tolerance_m'] != strict_tolerance or not 0 <= gap_low <= gap_high <= strict_tolerance): return False area_epsilon = max(1e-12,total*1e-10) if (not math.isclose(supported+missing,total,rel_tol=0.,abs_tol=area_epsilon) or not math.isclose(fraction,1-missing/total,rel_tol=0.,abs_tol=1e-10) or not math.isclose(contact['unsupported_area_m2'],missing,rel_tol=0.,abs_tol=area_epsilon) or not math.isclose(contact['support_coverage'],fraction,rel_tol=0.,abs_tol=1e-10)): return False gaps = contact['gaps_m'] indices = seam.get('unsupported_sample_indices') supported_count, unsupported_count = seam.get('supported_sample_count'), seam.get('unsupported_sample_count') if (type(indices) is not list or any(type(i) is not int or not 0 <= i < len(gaps) for i in indices) or len(indices) != len(set(indices)) or type(supported_count) is not int or supported_count <= 0 or type(unsupported_count) is not int or unsupported_count != len(indices) or supported_count+unsupported_count != len(gaps) or any(g is not None and g < 0 for g in gaps)): return False unsupported = set(indices) for index, gap in enumerate(gaps): if index not in unsupported and (gap is None or not 0 <= gap <= strict_tolerance or gap < gap_low-1e-10 or gap > gap_high+1e-10): return False polygons = seam.get('seam_polygons_world_xy_m') if type(polygons) is not list or not polygons: return False widths = [] for ring in polygons: if (type(ring) is not list or len(ring) != 5 or any(type(p) is not list or len(p) != 2 or any(type(v) not in (int,float) or not math.isfinite(v) for v in p) for p in ring) or ring[0] != ring[-1]): return False # Translate before the shoelace sum to avoid world-offset cancellation. points = [(p[0]-ring[0][0],p[1]-ring[0][1]) for p in ring] area = abs(sum(a[0]*b[1]-a[1]*b[0] for a,b in zip(points,points[1:])))/2 if not math.isfinite(area) or area <= 1e-12: return False a,b,c,d = points[:4] length, other = math.dist(a,b), math.dist(c,d) if min(length,other) <= 1e-8: return False ux,uy = (b[0]-a[0])/length, (b[1]-a[1])/length vx,vy = (d[0]-c[0])/other, (d[1]-c[1])/other distances = [-uy*(p[0]-a[0])+ux*(p[1]-a[1]) for p in (c,d)] width = max(abs(v) for v in distances) if (abs(ux*vy-uy*vx)>1e-6 or ux*vx+uy*vy>=0 or distances[0]*distances[1]<=0 or not 1e-9<width<=.01+1e-12): return False widths.append(width) if not math.isclose(max(widths),seam['maximum_unsupported_width_m'],rel_tol=0.,abs_tol=1e-10): return False if 'expected_gap_m' in contact and (type(contact['expected_gap_m']) not in (int,float) or not math.isfinite(contact['expected_gap_m']) or contact['expected_gap_m'] != 0.): return False if contact['method'] == 'saved_triangle_extreme_vertices_and_face_centroids_rays': for key,length in (('direction',3),('accepted_gap_range_m',2)): value = contact.get(key) if (type(value) is not list or len(value)!=length or any(type(v) not in (int,float) or not math.isfinite(v) for v in value)): return False if (contact.get('direction') != [0.,0.,-1.] or contact.get('target_selection') != 'first_facing' or contact.get('accepted_gap_range_m') != [0.,tolerance] or contact.get('measurement_backend') != 'trimesh.ray_triangle+rtree' or contact.get('evidence_scope') != 'sampled_surface_contact_only' or contact.get('physical_qualified') is not False or contact.get('whole_task_acceptance') is not False): return False return _bound_seam_measurement(row, contact, summary, evidence) def _measured_contact(row, entities, contact, summary, evidence): """Reconcile typed saved-contact measurements with their pass summaries.""" if __package__: from .support_contract import resolve_support_contract, wall_gap_accepted else: from support_contract import resolve_support_contract, wall_gap_accepted tolerance = evidence.get('contact_tolerance_m') if type(tolerance) not in (int, float) or not math.isfinite(tolerance) or not 0 < tolerance <= 1e-4: return False contract = resolve_support_contract(row, entities) kind = contract['support_type'] seam_present = 'seam_bridging' in contact if seam_present and kind != 'surface': return False pending = contract['pending_fields'] if pending and pending != ['installation_evidence:' + row['entity_id']]: return False if (contact.get('support_type') != kind or contact.get('support_entity_id') != contract['support_entity_id'] or summary.get('contact_passed') is not contact['passed']): return False nominal = 0. if 'installation_gap' in row: from pathlib import Path gap, receipt = row['installation_gap'], contact.get('installation_evidence') if (kind != 'wall' or not isinstance(gap, dict) or not isinstance(receipt, dict) or type(gap.get('gap_m')) not in (int, float) or not math.isfinite(gap['gap_m']) or gap['gap_m'] < 0): return False path = Path(gap['evidence_path']).resolve(strict=True) provenance = evidence['provenance'] if (receipt.get('evidence_path') != str(path) or receipt.get('evidence_sha256') != gap.get('evidence_sha256') or evidence['input_sha256'].get(str(path)) != gap.get('evidence_sha256') or any(receipt.get(k) != provenance.get(k) or not receipt.get(k) for k in ('scene_sha256', 'mesh_fingerprint'))): return False source = json.loads(path.read_text()) expected = dict(schema='rhg.source-installation-gap.v1', entity_id=row['entity_id'], support_type=kind, wall_anchor=row.get('wall_anchor'), gap_m=gap['gap_m'], scene_sha256=receipt['scene_sha256'], mesh_fingerprint=receipt['mesh_fingerprint'], source_identity={k: row.get(k) for k in ('asset_id', 'asset_sha256', 'runtime_sha256', 'canonical_transform')}) names = source.get('target_mesh_names') if (any(source.get(k) != v for k, v in expected.items()) or not isinstance(names, list) or not names or len(names) != len(set(names)) or any(not isinstance(n, str) or not n for n in names) or contact.get('target_mesh_names') != names): return False nominal = gap['gap_m'] if kind == 'inset': gap = contact.get('gap_m') if (contact.get('method') != 'declared_installation_surface_distance' or type(gap) not in (int, float) or not math.isfinite(gap) or gap < 0): return False passed = gap <= tolerance elif kind in ('floor', 'surface', 'wall'): expected_method = ('declared_wall_direction_back_surface_rays' if kind == 'wall' else 'bottom_vertices_and_face_centroids') if seam_present and contact.get('method') == 'saved_triangle_extreme_vertices_and_face_centroids_rays': expected_method = contact['method'] gaps = contact.get('gaps_m') if (contact.get('method') != expected_method 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(g is not None and (type(g) not in (int, float) or not math.isfinite(g)) for g in gaps)): return False if kind == 'wall': if (contact.get('wall_anchor') != row.get('wall_anchor') or type(contact.get('expected_gap_m')) not in (int, float) or contact['expected_gap_m'] != nominal): return False if (contact.get('accepted_gap_range_m') != contract['accepted_gap_range_m'] or contact.get('gap_acceptance') != contract['gap_acceptance']): return False nominal_match = all(g is not None and abs(g-nominal) <= tolerance for g in gaps) if contact.get('nominal_gap_match') is not nominal_match: return False elif contact.get('expected_gap_m', 0.) != 0.: return False passed = (all(wall_gap_accepted(g) for g in gaps) if kind == 'wall' else all(g is not None and abs(g-nominal) <= tolerance for g in gaps)) footprint_fields = ('flat_contact_region_checked', 'unsupported_area_m2', 'support_coverage') if any(k in contact for k in footprint_fields): area, coverage = contact.get('unsupported_area_m2'), contact.get('support_coverage') if (kind == 'wall' or contact.get('flat_contact_region_checked') is not True or type(area) not in (int, float) or not math.isfinite(area) or area < 0 or type(coverage) not in (int, float) or not math.isfinite(coverage) or not 0 <= coverage <= 1 or area == 0 and coverage != 1): return False if not seam_present: passed = passed and (area <= 1e-12 or coverage >= 1-1e-10) if seam_present: if not all(k in contact for k in footprint_fields) or not _measured_seam( row, entities, contact, summary, evidence, tolerance): return False passed = True else: return False return contact['passed'] is passed def geometry_scope_supported(manifest, evidence, entity_ids, *, diagnostics=()): """Require current readbacks, measured contacts and exact failing checks. Callers supply the entire explicit dependency closure, never just the directly diagnosed entities. Unknown coverage cannot authorize a pose edit. """ try: if __package__: from .geometry_validation import scoped_evidence else: from geometry_validation import scoped_evidence entities = _manifest(manifest) scope = set(_id_list(list(entity_ids), 'geometry scope')) if not scope or not scope <= entities.keys(): return False measured = scoped_evidence(manifest, evidence, sorted(scope)) if measured is None: return False contacts = {} for check in measured.get('contact_checks', []): eid = check['entity_id'] if eid in contacts: return False contacts[eid] = check for eid in scope: row, readback = entities[eid], measured['entity_readbacks'][eid] checks = measured['entity_checks'][eid] if (not isinstance(checks, dict) or checks.get('solid_complete') is not True or checks.get('contact_complete') is not True or eid not in contacts or type(contacts[eid].get('passed')) is not bool or contacts[eid].get('status') != 'measured' or contacts[eid].get('complete') is not True or contacts[eid].get('pending_fields')): return False if not _measured_contact(row, entities, contacts[eid], checks, evidence): return False parents = {row[k] for k in _SUPPORT_ALIASES if row.get(k) is not None} if len(parents) > 1 or contacts[eid].get('support_entity_id') != next(iter(parents), None): return False _close_vector(readback['center_xy_m'], row.get('actual_center_xy_m') or row['center_xy_m'], 'readback center') _close_vector(readback['dimensions_m'], row['dimensions_m'], 'readback dimensions') _close(readback['yaw_deg'], row['yaw_deg'], 'readback yaw') bbox = readback['world_bbox_m'] if not isinstance(bbox, list) or len(bbox) != 2: return False for point in bbox: _vector(point, 3, 'readback bbox') if any(bbox[0][i] >= bbox[1][i] for i in range(3)): return False _close(readback['base_z_m'], bbox[0][2], 'readback base') if 'world_bbox_m' in row: for actual, expected in zip(bbox, row['world_bbox_m']): _close_vector(actual, expected, 'readback bbox') pairs = {} for check in measured.get('pair_checks', []): left, right = check.get('left'), check.get('right') if not isinstance(left, str) or not isinstance(right, str) or left == right: return False key = frozenset((left, right)) if key in pairs: return False pairs[key] = check for diagnostic in diagnostics: ids = diagnostic['entity_ids'] if (not ids or not set(ids) <= scope or diagnostic not in measured.get('diagnostics', [])): return False code = diagnostic['code'] if code == 'collision': matched = [] for check in pairs.values(): volume = check.get('overlap_volume_m3') if (check.get('passed') is False and check.get('complete') is True and check.get('status') == 'measured' and check.get('method') == 'manifold3d_solid_intersection' and type(volume) in (int, float) and math.isfinite(volume) and volume > 1e-15 and {check.get('left'), check.get('right')} & entities.keys() == set(ids) and check.get('right') == diagnostic.get('collision_object') and volume == diagnostic.get('overlap_volume_m3')): matched.append(check) if len(matched) != 1: return False elif code in ('support_contact_invalid', 'support_footprint_outside_region'): if len(ids) != 1: return False contact = contacts[ids[0]] if (contact['passed'] is not False or contact.get('support_entity_id') != diagnostic.get('support_entity_id')): return False if code == 'support_footprint_outside_region': area = contact.get('unsupported_area_m2') if (contact.get('flat_contact_region_checked') is not True or type(area) not in (int, float) or not math.isfinite(area) or area <= 0 or area != diagnostic.get('unsupported_area_m2')): return False else: return False return True except (OSError, ValueError, KeyError, TypeError, ArithmeticError): return False def _rigid_point(point, old, new): angle = math.radians(new["yaw_deg"] - old["yaw_deg"]) x, y = [point[i] - old["center_xy_m"][i] for i in (0, 1)] return [new["center_xy_m"][0] + math.cos(angle)*x - math.sin(angle)*y, new["center_xy_m"][1] + math.sin(angle)*x + math.cos(angle)*y] def _same_pose_wall_measurement_refresh(original, current, manifest, evidence): """A new baseline may reset only the measured wall correction to zero. All source, policy, pose and wall identity fields remain byte-equivalent. The refreshed entity needs its own current saved-mesh contact/readback; evidence for the resampled entities alone cannot authorize this change. """ old, new = original.get('measured_wall_mount'), current.get('measured_wall_mount') if not isinstance(old, dict) or not isinstance(new, dict): return False old_delta, new_delta = old.get('layout_delta_m'), new.get('layout_delta_m') if (type(old_delta) not in (int, float) or not math.isfinite(old_delta) or type(new_delta) not in (int, float) or not math.isfinite(new_delta) or new_delta != 0. or new.get('evidence') != 'frozen_shell_mesh_readback' or new.get('side') != current.get('wall_anchor')): return False normalized = copy.deepcopy(current) normalized['measured_wall_mount']['layout_delta_m'] = old_delta if _encoded(original, canonical=True) != _encoded(normalized, canonical=True): return False eid = current['entity_id'] if not geometry_scope_supported(manifest, evidence, [eid]): return False contact = next(c for c in evidence['contact_checks'] if c.get('entity_id') == eid) clearance = new.get('clearance_m') return (contact.get('support_type') == 'wall' and contact.get('passed') is True and type(clearance) in (int, float) and math.isfinite(clearance) and all(math.isclose(gap, clearance, rel_tol=0., abs_tol=evidence['contact_tolerance_m']) for gap in contact['gaps_m'])) def _native_row_fixed(original, current, *, fresh_geometry=False): """Only known binder fields with independently checkable pose updates vary.""" mutable = set(_MANIFEST_POSE) if not fresh_geometry and all(original.get(key) == current.get(key) for key in _MANIFEST_POSE): return ({k: v for k, v in original.items() if k not in mutable}, {k: v for k, v in current.items() if k not in mutable}) # Validate rigid readback derivatives; equality alone can hide stale geometry. angle = math.radians(current["yaw_deg"] - original["yaw_deg"]) for key in ("world_bbox_m", "visual_footprint_polygon_xy_m", "actual_center_xy_m", "applied_world_front_vector_xy"): old, new = original.get(key), current.get(key) if old is None and new is None: continue if fresh_geometry and key in ('world_bbox_m', 'visual_footprint_polygon_xy_m', 'actual_center_xy_m'): mutable.add(key) continue if key == "world_bbox_m": if not math.isclose(math.remainder(current["yaw_deg"] - original["yaw_deg"], 360.), 0., rel_tol=0., abs_tol=1e-6): raise ValueError("Native AABB rotation needs fresh Blender geometry verification") if type(old) is not list or len(old) != 2 or type(new) is not list or len(new) != 2: raise ValueError("Native world bbox must contain min/max XYZ vectors") for point in old: _vector(point, 3, key) if any(old[0][i] >= old[1][i] for i in range(3)): raise ValueError("Native world bbox must enclose positive volume") delta = [current["center_xy_m"][i] - original["center_xy_m"][i] for i in (0, 1)] delta.append(current.get("base_z_m", 0.) - original.get("base_z_m", 0.)) for previous, point in zip(old, new): _close_vector(point, [previous[i] + delta[i] for i in range(3)], key) elif key == "visual_footprint_polygon_xy_m": if (type(old) is not list or len(old) < 3 or type(new) is not list or len(old) != len(new)): raise ValueError("Native visual footprint must retain its ordered polygon vertices") for previous, point in zip(old, new): _vector(previous, 2, key) _close_vector(point, _rigid_point(previous, original, current), key) elif key == "actual_center_xy_m": _vector(old, 2, key) _close_vector(new, _rigid_point(old, original, current), key) else: _vector(old, 2, key) _close_vector(new, [math.cos(angle)*old[0] - math.sin(angle)*old[1], math.sin(angle)*old[0] + math.cos(angle)*old[1]], key) mutable.add(key) for key in ("measured_wall_mount", "selected_support_surface", "derived_support_relation", "floor_cover_contact_evidence", "floor_cover_ancestor_height_delta_m", "supported_prop_fit_correction", "support_contact_layout_correction"): if original.get(key) or current.get(key): if not fresh_geometry: raise ValueError("Native pose change needs fresh contact verification: " + key) mutable.add(key) axis = current.get("canonical_front_axis") if axis not in ("+X", "+Y", "-X", "-Y"): raise ValueError("Native derived pose requires its canonical front axis") front = {"+X": 0, "+Y": 90, "-X": 180, "-Y": -90}[axis] contract = current["yaw_deg"] + front - 90 if "contract_yaw_deg" in original or "contract_yaw_deg" in current: _close(current.get("contract_yaw_deg"), contract, "contract_yaw_deg") mutable.add("contract_yaw_deg") if "world_front_vector_xy" in original or "world_front_vector_xy" in current: angle = math.radians(current["yaw_deg"] + front) _close_vector(current.get("world_front_vector_xy"), [math.cos(angle), math.sin(angle)], "world_front_vector_xy") mutable.add("world_front_vector_xy") for field in ("operation_space_xy_m", "front_clearance_box_xy_m"): old_box, new_box = original.get(field), current.get(field) if old_box is None and new_box is None: continue _vector(old_box, 4, field) corners = [_rigid_point([x, y], original, current) for x in (old_box[0], old_box[2]) for y in (old_box[1], old_box[3])] expected = [min(p[0] for p in corners), min(p[1] for p in corners), max(p[0] for p in corners), max(p[1] for p in corners)] _close_vector(new_box, expected, field) mutable.add(field) if "real_dimension_layout" in original or "real_dimension_layout" in current: old = _object(original.get("real_dimension_layout"), "original native layout") new = _object(current.get("real_dimension_layout"), "current native layout") if old.get("schema") != "rhg.joint_native_pose.v1" or new.get("schema") != old["schema"]: raise ValueError("Unsupported native placement evidence schema") for field in ("center_xy_m", "dimensions_m"): _close_vector(new.get(field), current[field], "native layout " + field) _close(new.get("yaw_deg"), current["yaw_deg"], "native layout yaw_deg") _close(new.get("contract_yaw_deg"), contract, "native layout contract_yaw_deg") _close(new.get("uniform_scale"), 1., "native layout uniform_scale") _vector(old.get("delta_xy_m"), 2, "original native delta") delta = [old["delta_xy_m"][i] + current["center_xy_m"][i] - original["center_xy_m"][i] for i in (0, 1)] _close_vector(new.get("delta_xy_m"), delta, "native layout delta_xy_m") _close_vector(current.get("wall_fit_correction_xy_m"), delta, "wall_fit_correction_xy_m") access = current.get("operation_space_xy_m") if new.get("access_box_xy_m") != access: raise ValueError("Native layout access box differs from current operation space") if new.get("wall_anchor") != current.get("wall_anchor"): raise ValueError("Native layout wall anchor differs from current placement") if current.get("placement_side") != current.get("wall_anchor"): raise ValueError("Native placement side differs from its wall anchor") changed = {"center_xy_m", "yaw_deg", "contract_yaw_deg", "delta_xy_m", "wall_anchor", "access_box_xy_m"} if _encoded({k: v for k, v in old.items() if k not in changed}, canonical=True) != _encoded( {k: v for k, v in new.items() if k not in changed}, canonical=True): raise ValueError("Immutable native placement evidence changed") mutable.update(("real_dimension_layout", "wall_fit_correction_xy_m", "wall_anchor", "placement_side")) if {k for k in original if k in mutable - _MANIFEST_POSE} != {k for k in current if k in mutable - _MANIFEST_POSE}: raise ValueError("Native derived evidence fields cannot be added or deleted") return ({k: v for k, v in original.items() if k not in mutable}, {k: v for k, v in current.items() if k not in mutable}) def _authored_fixed(request, constraints, entities): fixed = constraints.get("fixed_entities", []) indexed = _rows(fixed, "fixed_entities") if fixed else {} if type(fixed) is not list or set(indexed) - set(entities): raise ValueError("Fixed locks must name known, unique entities") for row in fixed: _geometry(row) marker = constraints.get("repair_lock_provenance") if marker is None: return indexed _object(marker, "repair_lock_provenance") repair = _object(request.get("repair"), "repair lock metadata") if (marker.get("schema") != _LOCK_PROVENANCE_SCHEMA or marker.get("source_manifest_sha256") != repair.get("source_manifest_sha256") or marker.get("fixed_entities_sha256") != _fingerprint(fixed) or repair.get("repair_lock_provenance_sha256") != _fingerprint(marker)): raise ValueError("Repair lock provenance does not bind the previous plan/locks") authored = marker.get("authored_fixed_entities") if type(authored) is not list: raise ValueError("Authored fixed locks must be a list") authored = _rows(authored, "authored_fixed_entities") if authored else {} generated = _id_list(marker.get("generated_fixed_entity_ids"), "generated fixed IDs") preserved = _id_list(repair.get("requested_preserved_entity_ids"), "previous preserved IDs") if (set(authored) & set(generated) or set(authored) | set(generated) != set(indexed) or set(generated) != set(preserved) - set(authored) or any(_encoded(row, canonical=True) != _encoded(indexed.get(eid), canonical=True) for eid, row in authored.items())): raise ValueError("Authored/generated fixed lock partition changed") return authored def plan_repair(manifest: dict, request: dict, diagnostics: list[dict], *, attempt_index: int = 1, max_attempts: int = 3) -> dict: """Plan a new attempt; never mutate inputs, execute, or certify a solution. Invalid JSON/schema/inventories/references raise ValueError. Each diagnostic requires nonempty code/message strings and an explicit entity_ids list. Lists are deterministic in manifest inventory order. Edges point from a support/functional target to its dependent subject; closure tolerates cycles. attempt_index counts attempts already made (including the diagnosed one). Empty diagnostics => no_repair_needed. Any diagnostic without IDs requires manual_review_required, including at the attempt limit. Otherwise a spent budget => budget_exhausted, else repair_planned. The three nonplanning statuses return next_request/next_attempt_index=None, an empty resample list and request preservation of the entire inventory. No status proves mathematical infeasibility or whole-task acceptance. A repair_planned next_request is an independent deepcopy, with only the affected rows' three _PREFERENCES removed from entities/furniture and a new repair metadata object. All domains, task data, relations and other fields remain intact. Row byte preservation means deterministic JSON serialization with insertion order and numeric types retained; original file whitespace cannot be represented by this dict API. Existing repair metadata is replaced. SHA-256 provenance uses sorted-key compact JSON, matching source checkpoints. Authored fixed locks are never relaxed; generated locks carry bound provenance. One joint no-good excludes the complete union of localized failed assignments. """ for label, value in (("attempt_index", attempt_index), ("max_attempts", max_attempts)): if type(value) is not int or value < 1: raise ValueError(label + " must be a positive integer") entities = _manifest(manifest) collections = _request(request, manifest, entities) prior_constraints = request.get("search_constraints", {}) if (not isinstance(prior_constraints, dict) or prior_constraints and prior_constraints.get("schema") != "rhg.search-constraints.v1"): raise ValueError("Unsupported search_constraints schema") downstream = _dependencies(entities, collections, manifest, request) direct = _diagnostics(diagnostics, entities) authored = _authored_fixed(request, prior_constraints, entities) if not diagnostics: status, reason = "no_repair_needed", "No failure diagnostics were supplied." elif any(not item["entity_ids"] for item in diagnostics): status, reason = "manual_review_required", "At least one diagnostic has no explicit entity IDs." elif attempt_index >= max_attempts: status, reason = "budget_exhausted", "Attempt budget exhausted; no infeasibility proof." else: status, reason = "repair_planned", "Plan one new attempt for explicit downstream dependencies." closure = set() if status == "repair_planned": closure.update(direct) queue = deque(direct) while queue: for dependent in sorted(downstream[queue.popleft()]): if dependent not in closure: closure.add(dependent) queue.append(dependent) conflicts = [eid for eid, row in authored.items() if any(key not in entities[eid] or value != entities[eid][key] for key, value in row.items())] if conflicts or closure.intersection(authored): status, reason = "manual_review_required", "Repair cannot relax or rebase authored fixed locks." closure.clear() resample = [entity_id for entity_id in entities if entity_id in closure] preserved = [entity_id for entity_id in entities if entity_id not in closure] plan = { "schema": _PLAN_SCHEMA, "status": status, "reason": reason, "attempt_index": attempt_index, "max_attempts": max_attempts, "attempt_budget_exhausted": attempt_index >= max_attempts, "next_attempt_index": attempt_index + 1 if status == "repair_planned" else None, "directly_conflicting_entity_ids": direct, "resample_entity_ids": resample, "preserved_entity_ids": preserved, "next_request": None, "diagnostics": copy.deepcopy(diagnostics), "source_manifest_sha256": _fingerprint(manifest), "source_request_sha256": _fingerprint(request), "floor_plan_sha256": _fingerprint(manifest["floor_plan"]), "preservation_profile": _NATIVE_PROFILE if _native_manifest(manifest) else "strict", "dependency_coverage": "explicit_structured_fields_only", "preservation_note": _PRESERVATION_NOTE, "preservation_enforced": False, "preservation_verified": False, "mathematical_infeasibility_proven": False, "physical_execution": "not_run", "physical_qualified": False, "whole_task_acceptance": False, } if status == "repair_planned": next_request = copy.deepcopy(request) for name in ("entities", "furniture"): for row in next_request.get(name, []): if row["entity_id"] in closure: for key in _PREFERENCES: row.pop(key, None) constraints = copy.deepcopy(prior_constraints) constraints.update(schema="rhg.search-constraints.v1", fixed_entities=[copy.deepcopy(authored.get(eid, entities[eid])) for eid in preserved], asset_locks=[copy.deepcopy(row) for row in entities.values()]) marker = dict(schema=_LOCK_PROVENANCE_SCHEMA, source_manifest_sha256=plan["source_manifest_sha256"], authored_fixed_entities=copy.deepcopy(list(authored.values())), generated_fixed_entity_ids=[eid for eid in preserved if eid not in authored], fixed_entities_sha256=_fingerprint(constraints["fixed_entities"])) constraints["repair_lock_provenance"] = marker cuts = constraints.setdefault("nogoods", []) if not isinstance(cuts, list): raise ValueError("search_constraints.nogoods must be a list") codes = list(dict.fromkeys(diagnostic["code"] for diagnostic in diagnostics)) cut = dict(code=codes[0] if len(codes) == 1 else "localized_output_failure", entities=[ {key: copy.deepcopy(entities[eid][key]) for key in ("entity_id", "asset_id", "center_xy_m", "yaw_deg", "base_z_m", "dimensions_m") if key in entities[eid]} for eid in direct]) if cut not in cuts: cuts.append(cut) constraints.setdefault("reservations", []) next_request["search_constraints"] = constraints metadata = {key: copy.deepcopy(value) for key, value in plan.items() if key not in ("next_request", "preserved_entity_ids")} metadata["requested_preserved_entity_ids"] = list(preserved) metadata["dropped_pose_preferences"] = list(_PREFERENCES) metadata["repair_lock_provenance_sha256"] = _fingerprint(marker) next_request["repair"] = metadata plan["next_request"] = next_request return plan def _plan_partition(plan, before): _object(plan, "plan") _json_data(plan) status = _text(plan.get("status"), "plan.status") if plan.get("schema") != _PLAN_SCHEMA or status not in _STATUSES: raise ValueError("Unsupported plan schema or status") resample = set(_id_list(plan.get("resample_entity_ids"), "plan.resample_entity_ids")) preserved = set(_id_list(plan.get("preserved_entity_ids"), "plan.preserved_entity_ids")) direct = set(_id_list(plan.get("directly_conflicting_entity_ids"), "plan.directly_conflicting_entity_ids")) if resample & preserved or resample | preserved != set(before) or not direct <= set(before): raise ValueError("Plan IDs must partition the complete before inventory") if plan["status"] == "repair_planned": if not direct or not direct <= resample: raise ValueError("Repair plan must include all directly conflicting IDs") elif resample: raise ValueError("Nonplanning statuses cannot authorize any entity changes") return resample, preserved def verify_preservation(before_manifest: dict, after_manifest: dict, plan: dict, *, defer_geometry=False, geometry_evidence=None) -> dict: """Return a preservation-only receipt, never execution/task acceptance. Returns schema, passed, preservation_verified, inventory_preserved, floor_plan_preserved, preserved_entity_records_unchanged, source_assets_and_dimensions_preserved, changed_entity_ids, errors and permanently false physical_qualified/whole_task_acceptance. Each error has code/entity_ids/message. Malformed payloads/plans produce passed=False. The before fingerprint must match the plan. IDs must partition its full inventory. Inventory additions/deletions/duplicates fail; floor_plan and all other top-level metadata are frozen. Unrelated entity records must serialize identically, including key order and numeric types. Affected records may differ only in the three actual manifest pose fields by default. An explicit native_joint_binding_v1 plan additionally permits the binder's request hash, source-scene path, hash-bound shell path, and validated rigid placement derivatives. Native record comparisons ignore object key order. Same-pose wall measurement deltas may reset to zero only with current saved-mesh evidence covering that entity; their IDs are explicitly recorded in refreshed_measurement_entity_ids. All other preserved fields stay exact. World readback must follow rigid derivatives. Rotated AABBs and measured contacts require fresh saved-mesh evidence. defer_geometry checks only preservation constraints before this evidence exists and never grants preservation_verified. Even affected asset, dimension, scale and dependency changes fail. Entity list reordering is allowed because inventory identity is keyed by entity_id. This is a comparison of supplied records, not proof of physical geometry. """ result = { "schema": _VERIFY_SCHEMA, "passed": False, "preservation_verified": False, "inventory_preserved": False, "floor_plan_preserved": False, "preserved_entity_records_unchanged": False, "source_assets_and_dimensions_preserved": False, "changed_entity_ids": [], "refreshed_measurement_entity_ids": [], "errors": [], "physical_qualified": False, "whole_task_acceptance": False, "geometry_pending": False, } def error(code, message, entity_ids=()): result["errors"].append({"code": code, "entity_ids": list(entity_ids), "message": message}) try: if type(defer_geometry) is not bool: raise ValueError('defer_geometry must be boolean') before = _manifest(before_manifest) after = _manifest(after_manifest) resample, preserved = _plan_partition(plan, before) fresh_geometry = False if geometry_evidence is not None: if __package__: from .geometry_validation import evidence_matches, evidence_current else: from geometry_validation import evidence_matches, evidence_current complete = (evidence_matches(after_manifest, geometry_evidence) and evidence_current(after_manifest, geometry_evidence)) if defer_geometry or not (complete or geometry_scope_supported( after_manifest, geometry_evidence, sorted(resample))): raise ValueError('Fresh geometry evidence does not cover this repair scope') fresh_geometry = True result['geometry_scope_entity_ids'] = sorted(resample) result['geometry_complete'] = complete profile = plan.get("preservation_profile", "strict") if profile not in ("strict", _NATIVE_PROFILE): raise ValueError("Unknown preservation profile") native = profile == _NATIVE_PROFILE if native and not (_native_manifest(before_manifest) and _native_manifest(after_manifest)): raise ValueError("Native preservation requires final joint-bound manifests") except ValueError as exc: error("invalid_preservation_input", str(exc)) return result if plan.get("source_manifest_sha256") != _fingerprint(before_manifest): error("baseline_mismatch", "Before manifest does not match the plan source fingerprint.") result["inventory_preserved"] = before.keys() == after.keys() if not result["inventory_preserved"]: error("inventory_changed", "Entity inventory additions or deletions are forbidden.", sorted(set(before) ^ set(after))) result["floor_plan_preserved"] = ( _encoded(before_manifest["floor_plan"]) == _encoded(after_manifest["floor_plan"])) if not result["floor_plan_preserved"]: error("floor_plan_changed", "The frozen floor plan changed.") before_metadata = {k: v for k, v in before_manifest.items() if k not in ("entities", "floor_plan")} after_metadata = {k: v for k, v in after_manifest.items() if k not in ("entities", "floor_plan")} if native: try: before_metadata, after_metadata = _native_metadata(before_manifest), _native_metadata(after_manifest) except ValueError as exc: error("invalid_native_provenance", str(exc)) return result metadata_unchanged = _encoded(before_metadata, canonical=native) == _encoded(after_metadata, canonical=native) if not metadata_unchanged: error("manifest_metadata_changed", "Manifest metadata and source asset inventories must remain exact.") unrelated_ok = True immutable_ok = metadata_unchanged for entity_id, original in before.items(): if entity_id not in after: if entity_id in preserved: unrelated_ok = False immutable_ok = False continue current = after[entity_id] if _encoded(original, canonical=native) != _encoded(current, canonical=native): result["changed_entity_ids"].append(entity_id) refreshed = (native and fresh_geometry and _same_pose_wall_measurement_refresh( original, current, after_manifest, geometry_evidence)) if refreshed: result['refreshed_measurement_entity_ids'].append(entity_id) current = copy.deepcopy(current) current['measured_wall_mount']['layout_delta_m'] = original['measured_wall_mount']['layout_delta_m'] elif entity_id in preserved: unrelated_ok = False error("preserved_entity_changed", "Requested preserved entity record changed.", [entity_id]) old_fixed = {k: v for k, v in original.items() if k not in _MANIFEST_POSE} new_fixed = {k: v for k, v in current.items() if k not in _MANIFEST_POSE} if native and entity_id in resample: try: old_fixed, new_fixed = _native_row_fixed(original, current, fresh_geometry=fresh_geometry or defer_geometry) except (ValueError, KeyError, TypeError, ArithmeticError) as exc: immutable_ok = False error("invalid_native_pose_evidence", str(exc), [entity_id]) if _encoded(old_fixed, canonical=native) != _encoded(new_fixed, canonical=native): immutable_ok = False error("immutable_entity_record_changed", "Only affected pose fields may change; assets and dimensions are frozen.", [entity_id]) if entity_id in resample and any(key in original and key not in current for key in _MANIFEST_POSE): immutable_ok = False error("pose_field_deleted", "Existing pose fields cannot be silently deleted.", [entity_id]) result["preserved_entity_records_unchanged"] = unrelated_ok result["source_assets_and_dimensions_preserved"] = immutable_ok and result["inventory_preserved"] result["passed"] = not result["errors"] result["geometry_pending"] = defer_geometry and result["passed"] result["preservation_verified"] = result["passed"] and not defer_geometry return result
"""Structured, execution-free local repair planning (Python >= 3.9, stdlib only).
Schema references are the separately copied ``source/`` snapshot's
``real_assets/joint_layout.py``, ``requested_shell.py``, ``functional_layout.py``
and ``packages/scene_generation/dependency_graph.py``. Nothing imports or edits
those scripts. Requests use ``rhg.scene_request.v1``, exhaustive ``furniture``
and optional exhaustive ``entities`` rows; manifests use ``entities`` and
``floor_plan.rooms``. Unknown extra JSON fields are retained.
Dependencies must be structured: support aliases (supported_by_entity_id,
support_entity_id, parent_entity_id), front entity/slot targets,
compiled layout parents/targets, attributes.depends_on, and relations with
kind/subject/object (optionally target). Callers must materialize any additional
solver-inferred relations into the request. Prose is never parsed for IDs.
Non-null support aliases must agree within and across manifest/request rows;
normalization is internal and does not rewrite those rows.
Repair requests include solver locks and joint failure exclusions. Planning
alone does not certify enforcement; the native report and verifier do that.
The default verifier permits only affected center_xy_m/yaw_deg/base_z_m changes.
Plans for final native joint bindings explicitly select native_joint_binding_v1:
request hashes and two execution paths may change, and known pose-derived fields
must agree with the new pose. Contact-dependent repairs fail closed. Task data,
policies, source identities, dimensions and unrelated records remain frozen.
"""
import copy
import hashlib
import json
import math
from collections import deque
__all__ = ["plan_repair", "verify_preservation", "geometry_scope_supported"]
_PLAN_SCHEMA = "rhg.frontier.repair-plan.v1"
_VERIFY_SCHEMA = "rhg.frontier.preservation-verification.v1"
_PREFERENCES = ("preferred_center_xy_m", "preferred_yaw_deg", "installation_height_m")
_SUPPORT_ALIASES = ("supported_by_entity_id", "support_entity_id", "parent_entity_id")
_MANIFEST_POSE = frozenset(("center_xy_m", "yaw_deg", "base_z_m"))
_LOCK_PROVENANCE_SCHEMA = "rhg.repair-lock-provenance.v1"
_NATIVE_PROFILE = "native_joint_binding_v1"
_STATUSES = frozenset(("repair_planned", "manual_review_required", "budget_exhausted",
"no_repair_needed"))
_PRESERVATION_NOTE = (
"Preserved IDs are requested preservation only; solver enforcement and "
"post-repair verification are required. No repair has been executed."
)
def _json_data(value):
"""Reject non-JSON objects and nonfinite numbers before copying or hashing."""
def check(item):
kind = type(item)
if kind is dict:
for key, child in item.items():
if type(key) is not str:
raise ValueError("JSON object keys must be strings")
check(child)
elif kind is list:
for child in item:
check(child)
elif kind is float:
if not math.isfinite(item):
raise ValueError("JSON numbers must be finite")
elif kind not in (str, int, bool, type(None)):
raise ValueError("Inputs must contain only JSON data")
try:
check(value)
except RecursionError as exc:
raise ValueError("JSON data must be acyclic and within nesting limits") from exc
def _encoded(value, *, canonical=False):
return json.dumps(value, sort_keys=canonical, separators=(",", ":"),
allow_nan=False).encode("utf-8")
def _fingerprint(value):
return hashlib.sha256(_encoded(value, canonical=True)).hexdigest()
def _text(value, label):
if type(value) is not str or not value.strip():
raise ValueError(label + " must be a nonempty string")
return value
def _object(value, label):
if type(value) is not dict:
raise ValueError(label + " must be an object")
return value
def _id_list(value, label, *, unique=True):
if type(value) is not list:
raise ValueError(label + " must be a list of entity IDs")
for item in value:
_text(item, label + " item")
if unique and len(value) != len(set(value)):