"""Deterministic lowering from reviewed predicate IR to executable programs. The natural-language layer may propose a candidate, but this module is the only promotion path for the six reviewed contract families. It preserves every parameter and region, selects only registered materializers, and emits synthetic witnesses proving that decision parameters are live. """ from __future__ import annotations from copy import deepcopy import re from typing import Any, Mapping, Sequence from pvr_eval.contracts.change_spec import compile_change_spec from pvr_eval.contracts.contract_obligations import ( build_binding_witnesses, compile_parameter_bindings, ) from pvr_eval.contracts.fact_producer_registry import ( objective_obligation_producer, objective_producer_for_binding, ) from pvr_eval.contracts.metric_profiles import ( ARCHITECTURE_QUALITATIVE_FAILURE_CERTIFICATE_VERSION, ARTICULATED_ENTITY_PRESERVATION_EXECUTOR_VERSION, ARTICULATED_ENTITY_PRESERVATION_PROFILE, HUMAN_POSE_PROFILE, LOCAL_CORRESPONDENCE_PROFILE, REGISTERED_ARCHITECTURE_PRESERVATION_EXECUTOR_VERSION, REGISTERED_ARCHITECTURE_PRESERVATION_PROFILE, articulated_entity_preservation_profile_parameters, registered_architecture_preservation_profile_parameters, registered_grid_structure_profile_parameters, support_contact_geometry_profile_parameters, ) from pvr_eval.contracts.predicate_ir_candidate import ( FAMILY_OPERATION_TEMPLATES, RULE_FAMILY_TARGETS, compile_predicate_ir_candidate, validate_predicate_ir_candidate, ) LOWERED_FAMILIES = frozenset(FAMILY_OPERATION_TEMPLATES) COMPOSITE_FAMILY = "contract_family_all_of" LOWERER_VERSION = "pvr.reviewed_contract_lowerer.v12" ALLOWED_EDIT_QUERY_SCOPE_POLICY = "reviewed_exclusion_clause_subject_intersection_v1" ROSTER_ALLOWED_EDIT_QUERY_SCOPE_POLICY = "question_support_roster_queries_v1" VERIFIED_GROUP_ROSTER_PROFILE = "verified_group_roster_assignment_v1" # A source rule name alone is not a type. These signatures prevent an LLM or # stale resolver from attaching unrelated parameters to a registered family # and receiving an executable status merely because the name is recognized. RULE_REQUIRED_PARAMETERS: dict[str, frozenset[str]] = { "multi_region_strict_preservation": frozenset({"maximum_changed_pixel_fraction", "minimum_region_ssim"}), "architecture_and_decor_preservation": frozenset({"registration_residual_tolerance_pixels", "minimum_edge_preservation"}), "masked_entity_structure_preservation": frozenset({"minimum_major_part_match_rate", "major_parts"}), "instance_and_background_preservation": frozenset({"required_original_bird_match_rate", "maximum_background_changed_fraction"}), "masked_object_pose_and_appearance_preservation": frozenset({"minimum_robot_mask_iou", "maximum_centroid_shift_fraction_of_image_diagonal"}), "masked_environment_structure_preservation": frozenset({"minimum_invariant_region_ssim", "maximum_unexplained_change_area_fraction"}), "matched_instance_integrity": frozenset({"appearance_similarity_warning_threshold", "mask_shape_change_warning_threshold"}), "protected_subject_invariance": frozenset({"centroid_shift_max", "bbox_scale_ratio"}), "registered_structure_preservation": frozenset({"maximum_normalized_boundary_displacement", "compare_drawer_state"}), "multi_instance_furniture_preservation": frozenset({"minimum_mask_iou_after_registration", "require_equal_chair_count"}), "registered_object_pose_preservation": frozenset({"registered_mask_iou_min", "expected_instance_count"}), "all_landmarks_preserved": frozenset({"registered_mask_iou_min", "require_one_to_one_instance_matching"}), "movable_inventory_integrity": frozenset({"expected_counts", "appearance_embedding_similarity_min"}), "all_instances_strict_preservation": frozenset({"minimum_mask_iou_after_registration", "expected_magazine_count"}), "strict_person_instance_preservation": frozenset({"minimum_mask_iou_after_registration", "minimum_appearance_similarity"}), "all_furniture_structures_preserved": frozenset({"minimum_boundary_iou", "minimum_unaffected_feature_match_ratio"}), "architectural_structure_preservation": frozenset({"minimum_door_mask_iou", "minimum_wall_feature_similarity"}), "multi_region_invariant_preservation": frozenset({"minimum_man_mask_iou", "minimum_board_feature_inlier_ratio"}), "structure_and_tray_preservation": frozenset({"minimum_structural_line_correspondence", "minimum_tray_shape_iou"}), "relocated_object_in_air_zone": frozenset({"minimum_air_zone_containment", "maximum_solid_mask_overlap_for_pass"}), "categorized_group_completeness": frozenset({"expected_counts", "minimum_group_members_for_clear_group"}), "dual_category_grouping": frozenset({"personal_care_expected", "medical_expected"}), "document_group_completeness": frozenset({"expected_counts", "use_title_or_color_identity"}), "remote_pair_on_table_surface": frozenset({"required_instances", "minimum_mask_containment"}), "paired_relocation_beside_dispenser": frozenset({"destination_reference", "require_cart_and_chair"}), "same_unit_different_compartment_placement": frozenset({"pass_min_containment", "pass_max_tray_overlap"}), "supported_nonintersecting_placement": frozenset({ "pass_max_support_gap_ratio", "partial_max_support_gap_ratio", "pass_min_supported_bottom_fraction", "fail_below_supported_bottom_fraction", "pass_max_structural_overlap", "partial_max_structural_overlap", }), "open_shelf_state_preserved": frozenset({"reference_state", "minimum_visible_recess_fraction"}), "flat_tabletop_structure_preserved": frozenset({"forbidden_surface_features", "minimum_forbidden_feature_confidence"}), "upright_group_arrangement": frozenset({"upright_angle_tolerance_degrees", "pass_min_upright_fraction"}), } def _mapping(value: Any) -> dict[str, Any]: return deepcopy(dict(value)) if isinstance(value, Mapping) else {} def _list(value: Any) -> list[Any]: return list(value) if isinstance(value, (list, tuple)) else [] def _dedupe(values: Sequence[Any]) -> list[str]: result: list[str] = [] seen: set[str] = set() for item in values: value = str(item or "").strip() if value and value not in seen: seen.add(value) result.append(value) return result def _configure_verified_group_roster( parameters: dict[str, Any], reasons: list[str], ) -> None: """Promote a complete reviewed roster to shared group matching runtime config.""" annotations = [ item for item in _list(parameters.get("source_instance_annotations")) if isinstance(item, Mapping) ] expected_raw = parameters.get("source_roster_expected_counts") if not annotations or not isinstance(expected_raw, Mapping): return observed: dict[str, int] = {} instance_ids: set[str] = set() labels: list[str] = [] animal_terms = { "animal", "bird", "birds", "cat", "deer", "doe", "dog", "fawn", "fox", "raccoon", "squirrel", "wildlife", } animal_roster = True for index, annotation in enumerate(annotations): group = str(annotation.get("group_id") or "").strip() instance_id = str(annotation.get("instance_id") or "").strip() if not group: reasons.append(f"verified_source_roster_group_missing:{index}") continue if not instance_id or instance_id in instance_ids: reasons.append(f"verified_source_roster_instance_id_invalid:{index}") instance_ids.add(instance_id) observed[group] = observed.get(group, 0) + 1 label = str(annotation.get("label") or group).strip() if label.endswith("s") and not label.endswith("ss"): label = label[:-1] if label and label not in labels: labels.append(label) animal_roster = animal_roster and bool( set(re.findall(r"[a-z]+", f"{group} {label}".casefold())) & animal_terms ) try: expected = {str(group): int(count) for group, count in expected_raw.items()} except (TypeError, ValueError): reasons.append("verified_source_roster_expected_counts_invalid") return if expected != observed: reasons.append("verified_source_roster_expected_counts_mismatch") return if parameters.get("source_roster_complete") is not True: reasons.append("verified_source_roster_not_declared_complete") return if str(parameters.get("source_inventory_provenance") or "") not in { "contract_source_annotations", "manual_source_annotations", "certified_source_inventory", }: reasons.append("verified_source_roster_provenance_uncertified") return distractor = "other animal" if animal_roster else "other object" parameters.setdefault("source_annotation_mask_profile", "fastsam_bbox_prompt_or_color_component_v2") parameters.setdefault("matching_classification_labels", [*labels, distractor]) parameters.setdefault("matching_use_segmenter_proposals", True) parameters.setdefault("matching_segmenter_min_area_fraction", 0.00003) parameters.setdefault("matching_segmenter_max_area_fraction", 0.08) parameters.setdefault("matching_segmenter_max_proposals", 160) parameters.setdefault("matching_classification_minimum_margin", 0.0) parameters.setdefault("matching_classification_minimum_probability", 0.25) parameters.setdefault("minimum_match_confidence", 0.55) parameters.setdefault( "required_matching_features", ["verified group label", "appearance embedding", "relative size", "mask shape"], ) parameters.setdefault("verified_roster_profile", VERIFIED_GROUP_ROSTER_PROFILE) question_support = parameters.get("question_support_roster") question_support_purpose = ( str(question_support.get("purpose") or "") if isinstance(question_support, Mapping) else "" ) parameters.setdefault( "verified_roster_assignment_mode", ( "question_support_allowed_edit_coverage_v1" if "allowed_edit" in question_support_purpose else "identity_exact" ), ) parameters.setdefault("verified_roster_expected_counts", expected) parameters.setdefault("verified_roster_minimum_area_ratio", 0.10) parameters.setdefault("verified_roster_maximum_area_ratio", 6.0) _QUERY_STOPWORDS = frozenset( { "all", "and", "central", "every", "input", "output", "the", "with", } ) _QUERY_PREPOSITIONS = frozenset( {"at", "beside", "by", "from", "in", "inside", "near", "on", "onto", "under", "with"} ) _QUERY_STATE_WORDS = frozenset({"lying", "perched", "relocated", "resting", "standing", "upright"}) def _query_token(value: str) -> str: token = value.lower() return token[:-1] if token.endswith("s") and len(token) > 3 else token def _semantic_query_head(query: str) -> str: tokens = [ token for token in re.findall(r"[a-z0-9]+", query.lower()) if token not in _QUERY_STOPWORDS ] for index, token in enumerate(tokens): if token in _QUERY_PREPOSITIONS: tokens = tokens[:index] break while tokens and tokens[-1] in _QUERY_STATE_WORDS: tokens.pop() return _query_token(tokens[-1]) if tokens else "" def _explicit_mask_heads(text: str) -> set[str]: """Return entity words explicitly used to construct an edit mask.""" heads: set[str] = set() for match in re.finditer( r"([a-z0-9]+(?:[ -]+[a-z0-9]+){0,4})[ -]+masks?\b", text.lower(), ): tokens = [ token for token in re.findall(r"[a-z0-9]+", match.group(1)) if token not in _QUERY_STOPWORDS and token not in { "allowed", "destination", "edit", "input", "matched", "movable", "original", "output", "relocated", "source", } ] heads.update(_query_token(token) for token in tokens[-2:]) if re.search(r"\b(?:its|their)\s+masks?\b", text.lower()): for match in re.finditer( r"\bsegment\s+(?:the\s+)?(.+?)(?=\s+(?:and|from|in|inside|near|on|perched|with)\b|[,;.])", text.lower(), ): action_tokens = [ token for token in re.findall(r"[a-z0-9]+", match.group(1)) if token not in _QUERY_STOPWORDS and token not in {"every"} ] if action_tokens: heads.add(_query_token(action_tokens[-1])) if "animal" in heads: heads.update({"wildlife", "bird"}) if "wildlife" in heads: heads.add("animal") return heads def _allowed_edit_queries( region: Mapping[str, Any], *, subjects: Sequence[str], related_regions: Sequence[Mapping[str, Any]], ) -> list[str]: """Select only subject queries explicitly named as edit exclusions. Reviewed checks often use one broad ``object_queries`` list for both the protected scene and the editable foreground. Copying that whole list to an allowed-edit mask can hide real damage (for example by subtracting the forest ground and rocks). The editable query set is therefore derived from the exclusion clauses themselves. If no reviewed subject matches, the region remains unsupported instead of inventing a foreground class. """ texts = [str(region.get("query_or_rule") or "")] for other in related_regions: if other is region: continue rule = str(other.get("query_or_rule") or "") if re.search(r"\b(exclud\w*|minus|subtract\w*)\b", rule.lower()): texts.append(rule.split(";", 1)[0]) explicit_heads: set[str] = set() for text in texts: explicit_heads.update(_explicit_mask_heads(text)) reviewed_support = _dedupe(_list(region.get("reviewed_support_queries"))) candidates = reviewed_support or _dedupe(subjects) selected: list[str] = [] for subject in candidates: # Only a noun explicitly attached to a reviewed mask is eligible. # Merely appearing as an anchor ("bird on robot shoulder") must not # make the robot itself editable. head = _semantic_query_head(subject) reviewed_tokens = { _query_token(token) for token in re.findall(r"[a-z0-9]+", subject.lower()) if token not in _QUERY_STOPWORDS } if ( head in explicit_heads or bool(reviewed_support and reviewed_tokens.intersection(explicit_heads)) ): selected.append(subject) return selected def _scope_allowed_edit_regions( regions: list[dict[str, Any]], subjects: Sequence[str], *, roster_queries: Sequence[str] = (), ) -> None: """Remove protected/context queries from detector-backed edit masks.""" for region in regions: if str(region.get("semantic_role") or "") != "allowed_edit_exclusion": continue materializer = region.get("materializer") if not isinstance(materializer, dict): continue if str(materializer.get("kind") or "") != "detector_segmenter": continue if roster_queries: materializer["queries"] = _dedupe(roster_queries) materializer["query_scope_policy"] = ROSTER_ALLOWED_EDIT_QUERY_SCOPE_POLICY else: materializer["queries"] = _allowed_edit_queries( region, subjects=subjects, related_regions=regions, ) materializer["query_scope_policy"] = ALLOWED_EDIT_QUERY_SCOPE_POLICY def _exclusion_parameter_requested(parameters: Mapping[str, Any]) -> bool: """Return whether a reviewed config explicitly requires an exclusion.""" # Occlusion can be a destination-relation fact (for example a chair # legitimately hidden behind a cart) without authorizing pixels to be # removed from a preservation comparison. Only mask/exemption wording # that actually requests subtraction activates the exclusion gate. return any( ( str(key).casefold().startswith("exclude_") or "exemption" in str(key).casefold() or "allowed_mask" in str(key).casefold() or "occlusion_mask" in str(key).casefold() ) and value not in (False, None, "", [], {}) for key, value in parameters.items() ) def _append_parameter_allowed_edit_region( regions: list[dict[str, Any]], parameters: Mapping[str, Any], reasons: list[str], *, require_complete: bool, ) -> None: """Lower an exclusion config only from explicit reviewed object queries. A boolean such as ``exclude_verified_new_furniture_occlusion`` says that an exclusion is required, but it does not identify the pixels. The objective executor therefore requires a separate ``allowed_edit_queries`` list and refuses to invent one from protected subjects or sibling evidence. Semantic-fallback-only rules remain fallback candidates. """ if not _exclusion_parameter_requested(parameters): return if any(region.get("semantic_role") == "allowed_edit_exclusion" for region in regions): return queries = _dedupe(_list(parameters.get("allowed_edit_queries"))) if not queries: if require_complete: reasons.append("exclusion_operation_missing_allowed_edit_region_or_queries") return mask_phrases = [f"{query} masks" for query in queries] regions.append( { "region_id": "contract_allowed_edit_exclusion", "semantic_role": "allowed_edit_exclusion", "image_roles": ["pred"], "source_image": "pred", "proposal_method": "sam_mask", "query_or_rule": ( "Union " + " and ".join(mask_phrases) + " as the allowed output occlusion." ), "reviewed_support_queries": queries, "materializer": { "kind": "detector_segmenter", "queries": queries, "selection_policy": "reviewed_query_topk_then_sam", "cardinality": "contract_defined", "region_rule": ( "Union " + " and ".join(mask_phrases) + " as the allowed output occlusion." ), }, "geometry_policy": "mask_or_polygon_required", "provenance": "derived from reviewed allowed_edit_queries operation config", } ) def _configure_multi_region_protected_regions( regions: list[dict[str, Any]], source_rule_type: str, ) -> None: """Make every named invariant ROI measurable for strict multi-region rules.""" if source_rule_type != "multi_region_strict_preservation": return for region in regions: if region.get("semantic_role") in { "allowed_edit_exclusion", "comparison_context_exclusion", }: continue region["semantic_role"] = "protected_region" region["image_roles"] = ["input", "pred"] region["source_image"] = "both" def _configure_registered_architecture_regions( regions: list[dict[str, Any]], parameters: Mapping[str, Any], reasons: list[str], ) -> None: """Compile one architecture/decor contract into strict component masks.""" component_queries = _dedupe(_list(parameters.get("architecture_component_queries"))) decor_queries = _dedupe(_list(parameters.get("tidy_decor_queries"))) allowed_queries = _dedupe(_list(parameters.get("allowed_edit_queries"))) for key, values in ( ("architecture_component_queries", component_queries), ("tidy_decor_queries", decor_queries), ("allowed_edit_queries", allowed_queries), ): if not values: reasons.append(f"registered_architecture_{key}_missing") configured_roles: set[str] = set() for region in regions: region_id = str(region.get("region_id") or "") semantic_role = str(region.get("semantic_role") or "") lowered_id = region_id.casefold() component_role = "" queries: list[str] = [] if semantic_role == "allowed_edit_exclusion" or "allowed" in lowered_id: component_role, queries = "allowed_edit", allowed_queries region["semantic_role"] = "allowed_edit_exclusion" elif "decor" in lowered_id: component_role, queries = "tidy_decor", decor_queries region["semantic_role"] = "context_region" elif semantic_role == "protected_region" or any( token in lowered_id for token in ("architecture", "structure", "invariant") ): component_role, queries = "major_structure", component_queries region["semantic_role"] = "protected_region" if not component_role: continue configured_roles.add(component_role) region["image_roles"] = ["input", "pred"] region["source_image"] = "both" region["materializer"] = { "kind": "architecture_region_parser", "profile": REGISTERED_ARCHITECTURE_PRESERVATION_PROFILE, "component_role": component_role, "queries": queries, "strict_component_masks": True, "selection_policy": "one_reviewed_query_top1_then_strict_mask", "geometry_policy": "strict_mask_union_with_component_certificate", "region_rule": str(region.get("query_or_rule") or ""), } region["geometry_policy"] = "strict_mask_union_with_component_certificate" for role in ("major_structure", "tidy_decor", "allowed_edit"): if role not in configured_roles: reasons.append(f"registered_architecture_region_missing:{role}") def _append_explicit_comparison_context_exclusion( regions: list[dict[str, Any]], *, subjects: Sequence[str], roster_queries: Sequence[str], ) -> None: """Materialize non-question foreground explicitly excluded by the contract. For background-preservation questions, a fixed foreground anchor such as a robot may be outside the question while still being named in the reviewed ``full frame minus ... mask`` rule. It is a comparison-context exclusion, never an editable roster member. """ heads: set[str] = set() for region in regions: if str(region.get("semantic_role") or "") != "protected_region": continue rule = str(region.get("query_or_rule") or "") if re.search(r"\b(exclud\w*|minus|subtract\w*)\b", rule.lower()): heads.update(_explicit_mask_heads(rule)) roster_heads = {_semantic_query_head(query) for query in roster_queries} if "animal" in roster_heads or any( re.search(r"\b(?:animal|bird|deer|doe|fawn|fox|raccoon|squirrel|wildlife)\b", query.lower()) for query in roster_queries ): roster_heads.update({"animal", "wildlife"}) queries = [ subject for subject in _dedupe(subjects) if _semantic_query_head(subject) in heads and _semantic_query_head(subject) not in roster_heads ] if not queries: return regions.append( { "region_id": "question_context_exclusion", "semantic_role": "comparison_context_exclusion", "image_roles": ["input", "pred"], "source_image": "both", "proposal_method": "derived_from_reviewed_exclusion_clause", "query_or_rule": "Exclude only explicitly named non-question foreground from background comparison.", "materializer": { "kind": "detector_segmenter", "queries": queries, "selection_policy": "reviewed_query_topk_then_sam", "cardinality": "contract_defined", "query_scope_policy": "reviewed_comparison_context_exclusion_v1", }, "geometry_policy": "mask_or_polygon_required", "provenance": "derived from reviewed protected-region exclusion clause", } ) def reviewed_region_policy_reasons(predicate: Mapping[str, Any]) -> list[str]: """Validate lowering policies whose semantics are not covered by JSON shape. A previously compiled predicate can remain schema-valid after the lowerer is fixed. In particular, old allowed-edit masks copied every object query and could subtract protected background from the preservation comparison. The compilation gate calls this validator so such stale artifacts cannot enter a new run silently. """ provenance = _mapping(predicate.get("provenance")) if provenance.get("compiler") != "pvr_eval.contracts.predicate_lowering.lower_reviewed_predicate": return [] regions = [ deepcopy(dict(item)) for item in _list(predicate.get("regions")) if isinstance(item, Mapping) ] subjects = _dedupe( str(item.get("identity_query") or "") for item in _list(predicate.get("subjects")) if isinstance(item, Mapping) ) parameters = _mapping(predicate.get("parameters")) roster_queries = _dedupe( str(item.get("query_text") or "") for item in _list(parameters.get("source_instance_annotations")) if isinstance(item, Mapping) ) reasons: list[str] = [] capabilities = predicate.get("capability_versions") if isinstance(predicate.get("capability_versions"), Mapping) else {} if capabilities.get("lowerer") != LOWERER_VERSION: reasons.append("stale_reviewed_lowerer_version") if ( parameters.get("articulated_entity_preservation_profile") == ARTICULATED_ENTITY_PRESERVATION_PROFILE and parameters.get("articulated_entity_preservation_executor_version") != ARTICULATED_ENTITY_PRESERVATION_EXECUTOR_VERSION ): reasons.append("stale_articulated_entity_preservation_executor_version") if parameters.get("registered_architecture_profile") == REGISTERED_ARCHITECTURE_PRESERVATION_PROFILE: if parameters.get("registered_architecture_executor_version") != ( REGISTERED_ARCHITECTURE_PRESERVATION_EXECUTOR_VERSION ): reasons.append("stale_registered_architecture_executor_version") expected_by_role = { "major_structure": _dedupe(_list(parameters.get("architecture_component_queries"))), "tidy_decor": _dedupe(_list(parameters.get("tidy_decor_queries"))), "allowed_edit": _dedupe(_list(parameters.get("allowed_edit_queries"))), } seen_roles: set[str] = set() for region in regions: materializer = _mapping(region.get("materializer")) component_role = str(materializer.get("component_role") or "") if component_role not in expected_by_role: continue seen_roles.add(component_role) if materializer.get("kind") != "architecture_region_parser": reasons.append(f"registered_architecture_materializer_mismatch:{component_role}") if materializer.get("strict_component_masks") is not True: reasons.append(f"registered_architecture_strict_mask_policy_missing:{component_role}") if _dedupe(_list(materializer.get("queries"))) != expected_by_role[component_role]: reasons.append(f"registered_architecture_query_scope_mismatch:{component_role}") for component_role, expected in expected_by_role.items(): if not expected or component_role not in seen_roles: reasons.append(f"registered_architecture_component_role_missing:{component_role}") if any( str(region.get("semantic_role") or "") == "comparison_context_exclusion" for region in regions ): reasons.append("registered_architecture_decor_must_not_be_comparison_exclusion") if ( objective_obligation_producer( str(predicate.get("family") or ""), str(predicate.get("source_rule_type") or ""), ) and _exclusion_parameter_requested(parameters) and not any( str(region.get("semantic_role") or "") == "allowed_edit_exclusion" for region in regions ) ): reasons.append("exclusion_operation_missing_allowed_edit_region") for region in regions: if str(region.get("semantic_role") or "") != "allowed_edit_exclusion": continue materializer = _mapping(region.get("materializer")) if str(materializer.get("kind") or "") != "detector_segmenter": continue region_id = str(region.get("region_id") or "missing") expected_policy = ( ROSTER_ALLOWED_EDIT_QUERY_SCOPE_POLICY if roster_queries else ALLOWED_EDIT_QUERY_SCOPE_POLICY ) if materializer.get("query_scope_policy") != expected_policy: reasons.append(f"stale_allowed_edit_query_scope_policy:{region_id}") continue expected = roster_queries or _allowed_edit_queries( region, subjects=subjects, related_regions=regions, ) actual = _dedupe(_list(materializer.get("queries"))) if actual != expected: reasons.append(f"allowed_edit_query_scope_mismatch:{region_id}") return reasons def reviewed_source_check_projection(check: Mapping[str, Any]) -> dict[str, Any]: """Reconstruct the exact check hashed before compiler artifacts were embedded.""" source = deepcopy(dict(check)) source.pop("predicate_ir_candidate", None) source.pop("executable_predicate", None) params = _mapping(source.get("params")) params.pop("predicate_ir_candidate", None) params.pop("executable_predicate", None) params.pop("require_executable_predicate", None) source["params"] = params return source def reviewed_source_check_sha256(check: Mapping[str, Any]) -> str: """Return the canonical hash used by reviewed predicate artifacts.""" candidate = compile_predicate_ir_candidate(reviewed_source_check_projection(check)) return str(candidate.get("source_check_sha256") or "") def _roles(region: Mapping[str, Any]) -> list[str]: explicit = _list(region.get("image_roles")) if explicit: return _dedupe(explicit) source = str(region.get("source_image") or region.get("image_role") or "pred").lower() if source in {"both", "input_pred", "input/output"}: return ["input", "pred"] if source in {"output", "prediction", "pred"}: return ["pred"] return ["input"] def _special_vlm_replacement(region_id: str) -> tuple[str, list[str], str]: """Replace the four reviewed VLM boxes with deterministic backends.""" if region_id == "airborne_flock_zone": return "derived_free_space_zone", ["robot", "ground", "tree trunk", "tree branch"], "air_above_solid_exclusions" if region_id == "central_walkway": return "planar_free_space_parser", ["rug", "open floor", "sofa", "TV stand"], "floor_corridor_between_furniture" if region_id == "map_pinboard": return "detector_segmenter", ["wall pinboard", "map board with pinned notes"], "top1_then_segment" if region_id == "house_structure_mask": return "architecture_region_parser", ["house walls", "windows", "eaves", "building facade"], "fixed_architecture_union" return "", [], "" def _materialize_region( raw: Mapping[str, Any], *, subjects: Sequence[str], ) -> tuple[dict[str, Any], list[str]]: region = deepcopy(dict(raw)) region_id = str(region.get("region_id") or region.get("id") or "").strip() method = str(region.get("proposal_method") or "").strip() query_or_rule = str(region.get("query_or_rule") or "").strip() roles = _roles(region) reasons: list[str] = [] queries: list[str] = [] raw_materializer = ( region.get("materializer") if isinstance(region.get("materializer"), Mapping) else {} ) reviewed_support_queries = _dedupe( _list( region.get("object_queries") or region.get("queries") or region.get("reviewed_support_queries") or raw_materializer.get("queries") ) ) materializer: dict[str, Any] if method in {"grounding_dino_box", "dino_box"}: queries = reviewed_support_queries or _dedupe(subjects) materializer = { "kind": "detector_segmenter", "queries": queries, "selection_policy": "reviewed_query_topk_then_sam", "cardinality": "contract_defined", } elif method == "sam_mask": # SAM is never invoked from prose alone. The reviewed subject queries # are its explicit detector seed; the region rule only filters/merges. queries = reviewed_support_queries or _dedupe(subjects) materializer = { "kind": "detector_segmenter", "queries": queries, "seed": "check_scoped_detector_boxes", "selection_policy": "detector_seed_then_rule_filtered_sam", "region_rule": query_or_rule, } if not queries: reasons.append(f"region_seed_queries_missing:{region_id}") elif method == "change_mask": materializer = { "kind": "registered_change_derivation", "registration": "robust_static_background_alignment", "operation": "union_subtract_clip", "region_rule": query_or_rule, } elif method == "ocr_layout": materializer = { "kind": "ocr_container_layout", "ocr_scope": "full_frame_then_nearest_container", "region_rule": query_or_rule, } elif method == "existing_zone": materializer = { "kind": "anchor_relative_zone", "queries": ["water dispenser"], "geometry_policy": "anchor_side_polygon_with_forbidden_subtraction", "region_rule": query_or_rule, } elif method == "grid_parser": materializer = { "kind": "shelf_grid_parser", "queries": reviewed_support_queries or ["shelving unit", "shelf compartment"], "geometry_policy": "registered_rectified_compartment_grid", "region_rule": query_or_rule, } elif method == "vlm_region_box": kind, queries, policy = _special_vlm_replacement(region_id) if not kind: reasons.append(f"zero_vlm_materializer_missing:{region_id}") materializer = {"kind": "unsupported"} else: materializer = { "kind": kind, "queries": queries, "geometry_policy": policy, "region_rule": query_or_rule, } else: reasons.append(f"unregistered_region_materializer:{region_id}:{method or 'missing'}") materializer = {"kind": "unsupported"} semantic_role = "context_region" lowered_id = region_id.lower() if any(token in lowered_id for token in ("allowed", "edit", "exemption")): semantic_role = "allowed_edit_exclusion" elif any(token in lowered_id for token in ("destination", "target_compartment", "storage", "airborne", "table_top")): semantic_role = "destination_region" elif any(token in lowered_id for token in ("invariant", "preservation", "structure", "surface")): semantic_role = "protected_region" lowered = { "region_id": region_id, "semantic_role": semantic_role, "image_roles": roles, "source_image": "both" if set(roles) == {"input", "pred"} else roles[0], "proposal_method": method, "query_or_rule": query_or_rule, "materializer": materializer, "geometry_policy": str(materializer.get("geometry_policy") or "mask_or_polygon_required"), "provenance": "reviewed planned_regions", } if reviewed_support_queries: lowered["reviewed_support_queries"] = reviewed_support_queries return lowered, reasons def _configure_registered_grid_structure_regions( regions: list[dict[str, Any]], subjects: Sequence[str], ) -> None: """Route a reviewed shelf structure through the shared grid parser.""" shelf_queries = [ value for value in _dedupe(subjects) if "shel" in value.casefold() and "unit" in value.casefold() ] if not shelf_queries: shelf_queries = [ value for value in _dedupe(subjects) if "shel" in value.casefold() ][:1] for region in regions: if str(region.get("region_id") or "") != "shelving_unit_structure": continue region["image_roles"] = ["input", "pred"] region["source_image"] = "both" region["materializer"] = { "kind": "shelf_grid_parser", "queries": shelf_queries or ["shelving unit"], "geometry_policy": "registered_rectified_compartment_grid", "region_rule": str(region.get("query_or_rule") or ""), "profile": "registered_grid_structure_preservation_v1", } region["geometry_policy"] = "registered_rectified_compartment_grid" def _operation( operation_id: str, kind: str, tool_family: str, image_roles: Sequence[str], *, depends_on: Sequence[str] = (), produces: Sequence[str] = (), ) -> dict[str, Any]: return { "id": operation_id, "kind": kind, "tool_family": tool_family, "image_roles": list(image_roles), "depends_on": list(depends_on), "parameters": {}, "produces": list(produces), } def _operations(families: Sequence[str], parameters: Mapping[str, Any] | None = None) -> list[dict[str, Any]]: parameters = parameters or {} local_facts_requested = any( key in parameters for key in ("max_rotation_change_degrees", "maximum_rotation_change_degrees", "minimum_local_feature_match_ratio") ) and bool(parameters.get("local_correspondence_profile")) needs_fixed = "fixed_location_entity_preservation" in families articulated_profile = ( str(parameters.get("articulated_entity_preservation_profile") or "") == ARTICULATED_ENTITY_PRESERVATION_PROFILE ) needs_region = articulated_profile or any(family in families for family in ( "registered_invariant_region_preservation", "destination_membership", "registered_structural_state", )) needs_match = any(family in families for family in ( "fixed_location_entity_preservation", "relocated_entity_integrity", "destination_membership", )) or bool(parameters.get("source_instance_annotations")) or local_facts_requested needs_registration = needs_fixed or any(family in families for family in ( "registered_invariant_region_preservation", "registered_structural_state", )) or local_facts_requested needs_change = articulated_profile or "registered_invariant_region_preservation" in families needs_state = any(family in families for family in ( "destination_membership", "registered_structural_state", "group_pose_arrangement", )) needs_attribute = any(family in families for family in ( "fixed_location_entity_preservation", "relocated_entity_integrity", "group_pose_arrangement", )) operations = [ _operation("detect_input", "object_detection", "detector", ("input",), produces=("input_boxes",)), _operation("detect_pred", "object_detection", "detector", ("pred",), produces=("pred_boxes",)), _operation("segment_input", "mask_refinement", "segmenter", ("input",), depends_on=("detect_input",), produces=("input_masks",)), _operation("segment_pred", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_pred",), produces=("pred_masks",)), ] terminal: list[str] = ["segment_input", "segment_pred"] if needs_match: operations.append(_operation( "match_instances", "instance_matching", "matcher", ("input", "pred"), depends_on=("segment_input", "segment_pred"), produces=("instance_matches",), )) terminal.append("match_instances") if needs_registration: operations.append(_operation( "register_frames", "image_registration", "registration", ("input", "pred"), produces=("registered_transform", "registration_quality"), )) terminal.append("register_frames") if needs_region: region_deps = ("register_frames",) if needs_registration else () operations.append(_operation( "materialize_regions", "region_resolution", "typed_region_materializer", ("input", "pred"), depends_on=region_deps, produces=("typed_regions", "materializer_status"), )) operations.append(_operation( "refine_region_geometry", "spatial_geometry", "segmenter", ("input", "pred"), depends_on=("materialize_regions",), produces=("region_masks", "zone_geometry"), )) terminal.append("refine_region_geometry") if needs_change: deps = ["register_frames"] if needs_region: deps.append("refine_region_geometry") operations.append(_operation( "measure_registered_change", "change_analysis", "change_analyzer", ("input", "pred"), depends_on=deps, produces=("change_metrics", "structure_metrics"), )) terminal.append("measure_registered_change") if needs_state: deps = ["segment_pred"] + (["refine_region_geometry"] if needs_region else []) operations.append(_operation( "parse_visual_state", "state_parsing", "state_parser", ("input", "pred"), depends_on=deps, produces=("state_facts", "pose_facts", "layout_facts"), )) terminal.append("parse_visual_state") if "destination_membership" in families: operations.append(_operation( "count_destination_instances", "counting", "checker_internal", ("pred",), depends_on=("segment_pred",), produces=("count_facts",), )) terminal.append("count_destination_instances") if needs_attribute: operations.append(_operation( "measure_visual_attributes", "visual_attribute", "attribute_parser", ("input", "pred"), depends_on=("segment_input", "segment_pred"), produces=("attribute_facts", "appearance_facts"), )) terminal.append("measure_visual_attributes") if "maximum_normalized_keypoint_error" in parameters: operations.append(_operation( "measure_human_pose", "pose_estimation", "human_pose_parser", ("input", "pred"), depends_on=("detect_input", "detect_pred"), produces=("human_pose_keypoints",), )) terminal.append("measure_human_pose") if local_facts_requested: operations.append(_operation( "measure_local_correspondence", "local_correspondence", "local_correspondence", ("input", "pred"), depends_on=("match_instances", "register_frames"), produces=("rotation_change_degrees", "local_feature_match_ratio", "local_correspondence_certificate"), )) terminal.append("measure_local_correspondence") if parameters.get("source_selector_profile"): operations.append(_operation( "select_allowed_edit_source", "source_instance_selection", "source_instance_selector", ("input",), depends_on=("segment_input",), produces=("source_selector_certificate",), )) terminal.append("select_allowed_edit_source") operations.append(_operation( "decide", "predicate_decision", "contract_metric_binding", ("input", "pred"), depends_on=tuple(dict.fromkeys(terminal)), produces=("check_result",), )) return operations def _subject_spec( index: int, aliases: Sequence[str], *, expected_count: int = 1, provenance: str = "reviewed object_queries", subject_id: str = "", component_queries: Sequence[str] = (), part_schema: Mapping[str, Any] | None = None, ) -> dict[str, Any]: clean_aliases = _dedupe(aliases) spec: dict[str, Any] = { "id": subject_id or f"subject_{index + 1}", "identity_query": clean_aliases[0], "input_queries": clean_aliases, "output_queries": clean_aliases, "aliases": clean_aliases, "expected_count": max(1, int(expected_count)), "cardinality_mode": "exact", "provenance": provenance, } clean_components = _dedupe(component_queries) if clean_components: spec["component_queries"] = clean_components if isinstance(part_schema, Mapping) and part_schema: spec["part_schema"] = deepcopy(dict(part_schema)) return spec def _explicit_physical_subject_specs( subjects: Sequence[str], parameters: Mapping[str, Any], ) -> tuple[list[dict[str, Any]], list[str]] | None: """Compile optional contract-authored query-to-physical-slot ownership. ``object_queries`` are detector prompts, not an entity roster. A contract may therefore group several prompts as aliases of one physical subject or attach an exact cardinality to one aggregate prompt. Every authored query must be owned exactly once; malformed or lossy groupings block lowering. """ raw_groups = parameters.get("physical_subject_groups") if raw_groups is None: return None if not isinstance(raw_groups, (list, tuple)) or not raw_groups: return [], ["physical_subject_groups_missing_or_invalid"] source_values = _dedupe(subjects) source_set = set(source_values) consumed: list[str] = [] specs: list[dict[str, Any]] = [] reasons: list[str] = [] for index, raw in enumerate(raw_groups): if not isinstance(raw, Mapping): reasons.append(f"physical_subject_group_not_object:{index}") continue aliases = _dedupe( _list(raw.get("aliases")) or [raw.get("identity_query")] ) unknown = sorted(set(aliases) - source_set) if not aliases: reasons.append(f"physical_subject_group_aliases_missing:{index}") continue if unknown: reasons.append( f"physical_subject_group_unreviewed_alias:{index}:" + ",".join(unknown) ) duplicates = sorted(set(aliases) & set(consumed)) if duplicates: reasons.append( f"physical_subject_query_multiply_owned:{index}:" + ",".join(duplicates) ) try: expected_count = int(raw.get("expected_count", 1)) except (TypeError, ValueError): expected_count = 0 if expected_count < 1: reasons.append(f"physical_subject_expected_count_invalid:{index}") expected_count = 1 consumed.extend(aliases) specs.append( _subject_spec( index, aliases, expected_count=expected_count, subject_id=str(raw.get("id") or ""), component_queries=_list(raw.get("component_queries")), part_schema=_mapping(raw.get("part_schema")), provenance="reviewed decision_rule.parameters.physical_subject_groups", ) ) unowned = [value for value in source_values if value not in set(consumed)] if unowned: reasons.append("physical_subject_queries_unowned:" + ",".join(unowned)) return specs, reasons def _inventory_subject_specs( subjects: Sequence[str], parameters: Mapping[str, Any], ) -> tuple[list[dict[str, Any]], list[str]]: """Turn aggregate inventory prompts into exact physical cardinalities.""" expected_raw = parameters.get("expected_counts") if not isinstance(expected_raw, Mapping): return [], ["inventory_expected_counts_missing"] expected = { str(key): int(value) for key, value in expected_raw.items() if str(key) != "total" and isinstance(value, (int, float)) and not isinstance(value, bool) and int(value) > 0 } values = _dedupe(subjects) category_queries: dict[str, list[str]] = {key: [] for key in expected} unmatched: list[str] = [] for query in values: query_tokens = set(re.findall(r"[a-z0-9]+", query.casefold().replace("_", " "))) ranked: list[tuple[int, str]] = [] for category in expected: category_tokens = { _query_token(token) for token in re.findall(r"[a-z0-9]+", category.casefold().replace("_", " ")) } overlap = len(category_tokens & {_query_token(token) for token in query_tokens}) if overlap: ranked.append((overlap, category)) if ranked: ranked.sort(key=lambda row: (-row[0], row[1])) category_queries[ranked[0][1]].append(query) else: unmatched.append(query) empty_categories = [key for key, queries in category_queries.items() if not queries] if unmatched and len(empty_categories) == 1: category_queries[empty_categories[0]] = unmatched unmatched = [] specs: list[dict[str, Any]] = [] reasons: list[str] = [] for category, count in expected.items(): queries = category_queries.get(category, []) if not queries: reasons.append(f"inventory_category_queries_missing:{category}") continue if len(queries) == count: for query in queries: specs.append( _subject_spec( len(specs), [query], provenance=( "reviewed object_queries + " "decision_rule.parameters.expected_counts" ), ) ) elif len(queries) == 1: specs.append( _subject_spec( len(specs), queries, expected_count=count, provenance=( "reviewed aggregate object_query + " "decision_rule.parameters.expected_counts" ), ) ) else: reasons.append(f"inventory_category_cardinality_ambiguous:{category}") if unmatched: reasons.append("inventory_queries_unassigned:" + ",".join(unmatched)) expected_total = expected_raw.get("total") physical_total = sum(int(item["expected_count"]) for item in specs) if isinstance(expected_total, (int, float)) and int(expected_total) != physical_total: reasons.append( f"inventory_total_mismatch:expected={int(expected_total)}:compiled={physical_total}" ) return specs, reasons def _subject_specs( subjects: Sequence[str], source_rule_type: str, parameters: Mapping[str, Any], ) -> tuple[list[dict[str, Any]], list[str], list[str], list[str]]: values = _dedupe(subjects) context: list[str] = [] component_queries: list[str] = [] reasons: list[str] = [] explicit = _explicit_physical_subject_specs(values, parameters) if explicit is not None: specs, explicit_reasons = explicit return specs, context, component_queries, explicit_reasons if source_rule_type == "strict_person_instance_preservation": specs = [ _subject_spec( 0, values, provenance="singular reviewed person rule; object_queries are aliases", ) ] if values else [] return specs, context, component_queries, reasons if source_rule_type == "all_instances_strict_preservation": magazine_queries = [ value for value in values if "magazine" in { _query_token(token) for token in re.findall(r"[a-z0-9]+", value.casefold()) } ] other_queries = [value for value in values if value not in set(magazine_queries)] specs: list[dict[str, Any]] = [] expected_parts = parameters.get("expected_magazine_count") if magazine_queries: part_schema = { "kind": "stack_members", "entity_type": "magazine", "expected_count": int(expected_parts), "count_provenance": "decision_rule.parameters.expected_magazine_count", } if isinstance(expected_parts, (int, float)) else {} specs.append( _subject_spec( len(specs), magazine_queries, component_queries=magazine_queries, part_schema=part_schema, provenance="reviewed magazine-stack aliases", ) ) specs.extend( _subject_spec(len(specs) + index, [value]) for index, value in enumerate(other_queries) ) return specs, context, component_queries, reasons if source_rule_type == "movable_inventory_integrity": specs, inventory_reasons = _inventory_subject_specs(values, parameters) return specs, context, component_queries, inventory_reasons groups: list[list[str]] = [[item] for item in values] if source_rule_type == "relocated_object_in_air_zone": groups, context = ([values[:2]] if values else []), values[2:] elif source_rule_type == "remote_pair_on_table_surface": groups, context = [[item] for item in values[:2]], values[2:] elif source_rule_type == "paired_relocation_beside_dispenser": groups, context = [[item] for item in values[:2]], values[2:] elif source_rule_type == "same_unit_different_compartment_placement": groups, context = ([values[:1]] if values else []), values[1:] elif source_rule_type == "supported_nonintersecting_placement": groups, context = ([values[:1]] if values else []), values[1:] elif source_rule_type == "structure_and_tray_preservation": # These queries name components of one registered structural system, # not four independent physical instances. groups = [values] if values else [] elif source_rule_type == "architecture_and_decor_preservation": component_queries = _dedupe(_list(parameters.get("architecture_component_queries"))) decor_queries = _dedupe(_list(parameters.get("tidy_decor_queries"))) aliases = component_queries + decor_queries specs = [ _subject_spec( 0, aliases, component_queries=aliases, part_schema={ "kind": "registered_architecture_and_decor_component_roster_v1", "major_structure_queries": component_queries, "tidy_decor_queries": decor_queries, "count_provenance": "reviewed decision_rule.parameters component query rosters", }, provenance="reviewed registered architecture/decor component system", ) ] if aliases else [] return specs, context, aliases, reasons elif source_rule_type == "upright_group_arrangement": # The first query names the aggregate group whose ownership/location # must be certified. Remaining queries describe components to parse # *inside* that group; treating them as additional physical subjects # incorrectly made one binder row plus one binder spine the expected # roster and allowed unrelated shelf proposals into the pose metric. groups = [values[:1]] if values else [] component_queries = values[1:] elif source_rule_type == "masked_entity_structure_preservation": # Detector prompts for head/torso/limbs describe components of one # articulated entity. They are not five independent roster slots. root = min(values, key=lambda value: (len(value.split()), len(value))) if values else "" components = [value for value in values if value != root] required_parts = _dedupe(parameters.get("major_parts") or []) specs = [ _subject_spec( 0, [root], component_queries=components, part_schema={ "kind": "normalized_humanoid_six_part_support_v1", "required_parts": required_parts, "component_queries": components, "count_provenance": "decision_rule.parameters.major_parts", }, provenance="reviewed articulated root query + component schema", ) ] if root else [] return specs, context, components, reasons specs = [ _subject_spec(index, aliases) for index, aliases in enumerate(groups) if aliases ] return specs, context, component_queries, reasons def lower_reviewed_predicate(check: Mapping[str, Any]) -> dict[str, Any] | None: """Lower one of the 29 reviewed source rules, or return ``None``.""" params = _mapping(check.get("params")) decision_rule = _mapping(params.get("decision_rule")) source_rule_type = str(decision_rule.get("type") or "").strip() if source_rule_type not in RULE_FAMILY_TARGETS: return None candidate_value = check.get("predicate_ir_candidate") or params.get("predicate_ir_candidate") candidate_source = reviewed_source_check_projection(check) candidate = _mapping(candidate_value) or compile_predicate_ir_candidate(candidate_source) candidate_validation = validate_predicate_ir_candidate( candidate, source_check=candidate_source, ) # A generated candidate is cacheable only for the exact authored check. # Regenerate it deterministically after criteria, thresholds, regions, or # subject queries change; never let a schema-valid stale candidate force # the new check into an old predicate program. if "source_check_hash_mismatch" in candidate_validation.reasons: candidate = compile_predicate_ir_candidate(candidate_source) candidate_validation = validate_predicate_ir_candidate( candidate, source_check=candidate_source, ) expected_families = list(RULE_FAMILY_TARGETS[source_rule_type]) if [str(item) for item in candidate.get("target_families", [])] != expected_families: candidate = compile_predicate_ir_candidate(candidate_source) candidate_validation = validate_predicate_ir_candidate( candidate, source_check=candidate_source, ) # Candidate IR is a cache, never authority. A rule that gains a reviewed # deterministic lowering must not remain manual merely because an older # candidate recorded it as unmapped. if not candidate_validation.valid: regenerated = compile_predicate_ir_candidate(candidate_source) regenerated_validation = validate_predicate_ir_candidate( regenerated, source_check=candidate_source, ) if regenerated_validation.valid: candidate = regenerated candidate_validation = regenerated_validation check_id = str(check.get("id") or check.get("check_id") or "").strip() families = [str(item) for item in candidate.get("target_families", [])] subjects = _dedupe(params.get("object_queries") or candidate.get("subjects") or []) reasons: list[str] = [] if not candidate_validation.valid: reasons.extend("candidate_invalid:" + item for item in candidate_validation.reasons) if not families or any(family not in LOWERED_FAMILIES for family in families): reasons.append("candidate_family_not_lowerable") family = families[0] if len(families) == 1 else COMPOSITE_FAMILY regions: list[dict[str, Any]] = [] for raw in _list(params.get("planned_regions")): if not isinstance(raw, Mapping): continue region, region_reasons = _materialize_region(raw, subjects=subjects) if ( source_rule_type == "supported_nonintersecting_placement" and str((region.get("materializer") or {}).get("kind") or "") == "shelf_grid_parser" ): # Support is certified against an input/output registered grid, # even when the authored region names only the output cell. region["image_roles"] = ["input", "pred"] region["source_image"] = "both" regions.append(region) reasons.extend(region_reasons) source_parameters = _mapping(decision_rule.get("parameters")) runtime_parameters = deepcopy(source_parameters) if source_rule_type == "supported_nonintersecting_placement": runtime_parameters.update(support_contact_geometry_profile_parameters()) if source_rule_type == "structure_and_tray_preservation": runtime_parameters.update(registered_grid_structure_profile_parameters()) _configure_registered_grid_structure_regions(regions, subjects) if source_rule_type == "architecture_and_decor_preservation": runtime_parameters.update(registered_architecture_preservation_profile_parameters()) _configure_registered_architecture_regions(regions, runtime_parameters, reasons) _configure_verified_group_roster(runtime_parameters, reasons) if source_rule_type == "masked_entity_structure_preservation": runtime_parameters.update(articulated_entity_preservation_profile_parameters()) root_query = min(subjects, key=lambda value: (len(value.split()), len(value))) protected = next( (region for region in regions if region.get("semantic_role") == "protected_region"), None, ) if isinstance(protected, dict): protected["image_roles"] = ["input", "pred"] protected["source_image"] = "both" protected["materializer"] = { "kind": "detector_segmenter", "queries": [root_query], "seed": "check_scoped_detector_boxes", "selection_policy": "top1_whole_entity_then_sam", "region_rule": str(protected.get("query_or_rule") or ""), } allowed = next( (region for region in regions if region.get("semantic_role") == "allowed_edit_exclusion"), None, ) support_queries = _dedupe((allowed or {}).get("reviewed_support_queries") or []) selector_identity = _semantic_query_head(support_queries[0]) if support_queries else "" selector_text = " ".join( [str((allowed or {}).get("query_or_rule") or ""), *support_queries] ).casefold() anchor_part = ( "viewer_right_shoulder" if "viewer" in selector_text and "right" in selector_text else "viewer_left_shoulder" if "viewer" in selector_text and "left" in selector_text else "" ) if isinstance(allowed, dict) and selector_identity and anchor_part: allowed["image_roles"] = ["input"] allowed["source_image"] = "input" allowed["materializer"] = { "kind": "registered_change_derivation", "operation": "source_selector_registered_projection", "projection_policy": "source_mask_to_registered_comparison_v1", "source_selector_profile": "anchor_relative_source_instance_v1", "region_rule": str(allowed.get("query_or_rule") or ""), } runtime_parameters["source_selector_profile"] = "anchor_relative_source_instance_v1" runtime_parameters["source_selector"] = { "profile": "anchor_relative_source_instance_v1", "identity_queries": [selector_identity], "anchor_queries": [root_query], "anchor_part": anchor_part, "relation": "contact_or_near", "expected_count": 1, "minimum_identity_score": 0.05, "minimum_anchor_score": 0.10, "minimum_selection_margin": 0.12, "purpose": "allowed_edit_exclusion", } else: reasons.append("articulated_allowed_edit_source_selector_not_derivable") _configure_multi_region_protected_regions(regions, source_rule_type) _append_parameter_allowed_edit_region( regions, source_parameters, reasons, require_complete=bool( objective_obligation_producer(family, source_rule_type) ), ) roster_queries = _dedupe( str(item.get("query_text") or "") for item in _list(source_parameters.get("source_instance_annotations")) if isinstance(item, Mapping) ) _scope_allowed_edit_regions(regions, subjects, roster_queries=roster_queries) if source_rule_type != "architecture_and_decor_preservation": _append_explicit_comparison_context_exclusion( regions, subjects=subjects, roster_queries=roster_queries, ) for region in regions: materializer = region.get("materializer") if ( str(region.get("semantic_role") or "") == "allowed_edit_exclusion" and isinstance(materializer, Mapping) and str(materializer.get("kind") or "") == "detector_segmenter" and not materializer.get("queries") ): reasons.append( "allowed_edit_subject_queries_missing:" + str(region.get("region_id") or "missing") ) required_parameters = RULE_REQUIRED_PARAMETERS.get(source_rule_type, frozenset()) missing_required_parameters = sorted(required_parameters - set(source_parameters)) if missing_required_parameters: reasons.append("source_rule_parameter_schema_mismatch:" + ",".join(missing_required_parameters)) if "maximum_normalized_keypoint_error" in source_parameters: pose_profile = str(source_parameters.get("pose_profile") or "") if pose_profile != HUMAN_POSE_PROFILE: reasons.append("normalized_keypoint_error_requires_registered_pose_profile") local_facts_requested = any( key in source_parameters for key in ("max_rotation_change_degrees", "maximum_rotation_change_degrees", "minimum_local_feature_match_ratio") ) local_profile = str(source_parameters.get("local_correspondence_profile") or "") if local_facts_requested and local_profile and local_profile != LOCAL_CORRESPONDENCE_PROFILE: reasons.append("local_correspondence_profile_unsupported") bindings = compile_parameter_bindings(source_parameters) for binding in bindings: if binding.get("consumer") == "decision_clause": objective_producer = objective_producer_for_binding(family, binding, runtime_parameters) if objective_producer: binding["producer"] = objective_producer binding["producer_mode"] = "objective" else: binding["producer"] = "reviewed_semantic_vlm" binding["producer_mode"] = "semantic_vlm" binding["source_text"] = ( "No registered deterministic runtime producer for reviewed parameter " + str(binding.get("source_key") or binding.get("fact") or "") ) if source_rule_type == "architecture_and_decor_preservation": fail_text = str(decision_rule.get("fail_condition") or "").casefold() broad_decor_failure = bool( "decor" in fail_text and any(token in fail_text for token in ("broad", "large-scale", "majority")) ) if broad_decor_failure: bindings.append( { "source_key": "derived:fail_condition:broad_tidy_decor_removal", "consumer": "decision_clause", "clause_id": "derived:architecture_broad_tidy_decor_removal", "branch": "fail", "fact": "tidy_decor_unmatched_fraction", "op": "ge", "expected": float( runtime_parameters[ "architecture_broad_decor_removal_minimum_fraction" ] ), "producer": "reviewed_typed_evidence_adapter", "producer_mode": "objective", "source_text": str(decision_rule.get("fail_condition") or ""), "certificate_version": ( ARCHITECTURE_QUALITATIVE_FAILURE_CERTIFICATE_VERSION ), "threshold_provenance": ( "shared lexical certificate: broad removal means a strict " "majority of the reviewed registered decor mask" ), } ) obligation_producer = objective_obligation_producer(family, source_rule_type) for obligation in _list(candidate.get("obligations")): if not isinstance(obligation, Mapping): continue branch = str(obligation.get("branch") or "pass") bindings.append( { "source_key": str(obligation.get("id") or ""), "consumer": "decision_clause", "clause_id": "obligation:" + str(obligation.get("id") or ""), "branch": branch, "fact": "obligation:" + str(obligation.get("id") or ""), "op": "eq", "expected": True, "source_text": str(obligation.get("source_text") or ""), # Free-form pass/fail prose is semantic by default. Promotion # is allowed only through the runtime-aligned registry above, # after a rule-specific executor proves the exact branch from # complete objective measurements. "producer": obligation_producer or "reviewed_semantic_vlm", "producer_mode": "objective" if obligation_producer else "semantic_vlm", } ) witnesses = build_binding_witnesses(bindings) if not witnesses or any(not bool(item.get("passed")) for item in witnesses): reasons.append("parameter_witness_failure") if not check_id: reasons.append("missing_check_id") if not subjects: reasons.append("missing_subject_queries") subject_specs, context_queries, component_queries, subject_reasons = _subject_specs( subjects, source_rule_type, runtime_parameters, ) reasons.extend(subject_reasons) decision_bindings = [ item for item in bindings if item.get("consumer") == "decision_clause" ] semantic_fact_requirements = [ { "fact": str(item.get("fact") or ""), "clause_id": str(item.get("clause_id") or ""), "branch": str(item.get("branch") or "pass"), "source_text": str(item.get("source_text") or ""), "producer": str(item.get("producer") or ""), } for item in decision_bindings if item.get("producer_mode") == "semantic_vlm" ] predicate = { "schema_version": "pvr.executable_predicate.v1", "check_id": check_id, "status": "executable" if not reasons else "blocked_uncompiled", "family": family, "target_families": families, "source_rule_type": source_rule_type, "source_check_sha256": candidate.get("source_check_sha256"), "subjects": subject_specs, "context_queries": context_queries, "component_queries": component_queries, "regions": regions, "operations": _operations(families, runtime_parameters), "state_schema": { "unit": "typed_contract_obligation", "states": ["pass", "partial", "fail", "unknown"], "facts": sorted({str(item.get("fact")) for item in bindings if item.get("consumer") == "decision_clause"}), }, "decision": { "aggregation": "ALL_OF" if len(families) > 1 else "SINGLE_FAMILY", "allowed_outcomes": ["pass", "partial", "fail", "unknown"], "unknown_policy": "missing_or_ambiguous_required_fact_is_unknown", }, "parameters": deepcopy(runtime_parameters), "parameter_bindings": bindings, "fact_producers": [ { "fact": str(item.get("fact") or ""), "clause_id": str(item.get("clause_id") or ""), "producer": str(item.get("producer") or ""), "mode": str(item.get("producer_mode") or ""), } for item in decision_bindings ], "semantic_fact_requirements": semantic_fact_requirements, "parameter_provenance": { str(item.get("source_key")): "reviewed decision_rule.parameters" for item in bindings if not str(item.get("source_key") or "").startswith(check_id + ":") } | { key: "derived:registered_support_contact_geometry_profile" for key in set(runtime_parameters) - set(source_parameters) if source_rule_type == "supported_nonintersecting_placement" } | { key: "derived:registered_grid_structure_preservation_profile" for key in set(runtime_parameters) - set(source_parameters) if source_rule_type == "structure_and_tray_preservation" } | { key: "derived:registered_architecture_preservation_profile" for key in set(runtime_parameters) - set(source_parameters) if source_rule_type == "architecture_and_decor_preservation" }, "obligations": deepcopy(_list(candidate.get("obligations"))), "coverage_map": { "parameter_keys": list(source_parameters), "region_ids": [str(item.get("region_id") or "") for item in regions], "obligation_ids": [str(item.get("id") or "") for item in _list(candidate.get("obligations")) if isinstance(item, Mapping)], }, "witness_results": witnesses, "capability_versions": { "lowerer": LOWERER_VERSION, "decision_evaluator": "pvr.contract_obligations.v1", "metric_binding": "pvr.contract_metric.v7", "fact_producer_registry": "pvr.runtime_fact_producers.v1", "semantic_fallback": "pvr.reviewed_semantic_vlm.v1", }, "unmapped_contract_parameters": [], "reasons": list(dict.fromkeys(reasons)), "provenance": { "compiler": "pvr_eval.contracts.predicate_lowering.lower_reviewed_predicate", "candidate_schema": candidate.get("schema_version"), "conversion": "reviewed_golden_ir_then_deterministic_lowering", }, } change_spec = compile_change_spec(predicate) if change_spec: predicate["change_spec"] = change_spec predicate["capability_versions"]["visual_change_spec"] = "pvr.visual_change_spec.v1" return predicate