"""Strict compiler from one atomic contract check to an evidence program. The resolver's prose is an audit artifact, not an executable interface. This module turns the fields retained on :class:`AtomicCheckSpec` into a typed, per-check program and refuses to call it executable when a required operation or region cannot actually be resolved. The compiler deliberately does not create physical model calls. It is the semantic layer immediately before ``tool_plan``: executors may batch/cache the typed requirements later, while preserving ``check_id`` provenance. """ from __future__ import annotations from copy import deepcopy from dataclasses import dataclass, field import re from typing import Any, Iterable, Mapping from pvr_eval.core.schema import AtomicCheckSpec from pvr_eval.agent.contract_metric_binding import canonical_rule_type, metric_capability EVIDENCE_PROGRAM_SCHEMA_VERSION = "pvr.evidence_program.v1" # These are operations for which the repository has an objective execution # path. Callers should pass their runtime capability set when it differs. DEFAULT_AVAILABLE_OPERATIONS = frozenset( { "crop", "object_detection", "mask_refinement", "instance_matching", "source_instance_selection", "crop_classification", "image_registration", "change_analysis", "ocr", "text_alignment", "text_quality", "route_extraction", "state_parsing", "structured_check", "visual_attribute", "pose_estimation", "local_correspondence", "spatial_geometry", "counting", "region_resolution", "source_state_classification", "predicate_decision", } ) @dataclass(frozen=True) class RegionDependency: region_id: str image_roles: tuple[str, ...] proposal_method: str resolver_operation: str status: str query_or_rule: str = "" geometry: Any = None reasons: tuple[str, ...] = () def to_dict(self) -> dict[str, Any]: return { "region_id": self.region_id, "image_roles": list(self.image_roles), "proposal_method": self.proposal_method, "resolver_operation": self.resolver_operation, "status": self.status, "query_or_rule": self.query_or_rule, "geometry": self.geometry, "reasons": list(self.reasons), } @dataclass(frozen=True) class EvidenceRequirement: requirement_id: str operation: str tool_family: str image_roles: tuple[str, ...] region_ids: tuple[str, ...] = () depends_on: tuple[str, ...] = () source: str = "inferred" raw: str = "" optional: bool = False status: str = "supported" reasons: tuple[str, ...] = () def to_dict(self) -> dict[str, Any]: return { "requirement_id": self.requirement_id, "operation": self.operation, "tool_family": self.tool_family, "image_roles": list(self.image_roles), "region_ids": list(self.region_ids), "depends_on": list(self.depends_on), "source": self.source, "raw": self.raw, "optional": self.optional, "status": self.status, "reasons": list(self.reasons), } @dataclass(frozen=True) class EvidenceArtifact: artifact_id: str description: str producer_operations: tuple[str, ...] status: str reasons: tuple[str, ...] = () def to_dict(self) -> dict[str, Any]: return { "artifact_id": self.artifact_id, "description": self.description, "producer_operations": list(self.producer_operations), "status": self.status, "reasons": list(self.reasons), } @dataclass(frozen=True) class ParameterPromotion: checker_params: dict[str, Any] promoted: dict[str, str] conflicts: tuple[str, ...] @dataclass(frozen=True) class EvidenceProgram: check_id: str checker: str status: str checker_params: dict[str, Any] promoted_parameters: dict[str, str] parameter_conflicts: tuple[str, ...] regions: tuple[RegionDependency, ...] requirements: tuple[EvidenceRequirement, ...] evidence_artifacts: tuple[EvidenceArtifact, ...] unsupported_requirements: tuple[str, ...] reasons: tuple[str, ...] @property def executable(self) -> bool: return self.status == "executable" def to_dict(self) -> dict[str, Any]: return { "schema_version": EVIDENCE_PROGRAM_SCHEMA_VERSION, "check_id": self.check_id, "checker": self.checker, "status": self.status, "executable": self.executable, "checker_params": self.checker_params, "promoted_parameters": self.promoted_parameters, "parameter_conflicts": list(self.parameter_conflicts), "regions": [item.to_dict() for item in self.regions], "requirements": [item.to_dict() for item in self.requirements], "evidence_artifacts": [item.to_dict() for item in self.evidence_artifacts], "unsupported_requirements": list(self.unsupported_requirements), "reasons": list(self.reasons), } _PARAM_ALIASES = { "required_anchor_strings": "expected_all", "pass_mask_containment": "min_mask_containment", "partial_mask_containment": "partial_min_mask_containment", "slot_expand_px_for_detection": "slot_expand_px", "min_detector_score": "min_score", "normalized_edit_similarity_min": "min_text_similarity", "output_ocr_confidence_min": "min_ocr_confidence", "minimum_match_confidence": "min_match_confidence", "minimum_start_zone_intersection": "min_start_zone_intersection", "minimum_end_zone_intersection": "min_end_zone_intersection", "maximum_normalized_skeleton_gap": "max_normalized_skeleton_gap", "minimum_route_corridor_coverage": "min_route_corridor_coverage", "maximum_invariant_changed_area_ratio": "pass_max_changed", "maximum_unexplained_architectural_change_fraction": "pass_max_changed", "maximum_unexplained_region_change_ratio": "pass_max_changed", } def _checker_base(checker: str) -> str: return str(checker).split("|", 1)[0].split(":", 1)[0].strip() def _decision_parameters(params: Mapping[str, Any]) -> dict[str, Any]: rule = params.get("decision_rule", {}) if isinstance(rule, Mapping): nested = rule.get("parameters", {}) return dict(nested) if isinstance(nested, Mapping) else {} return {} def promote_checker_parameters(spec: AtomicCheckSpec) -> ParameterPromotion: """Promote decision parameters without overwriting explicit checker data.""" original = deepcopy(dict(spec.params or {})) promoted: dict[str, str] = {} conflicts: list[str] = [] for source_key, value in _decision_parameters(original).items(): target_key = _PARAM_ALIASES.get(str(source_key), str(source_key)) if target_key not in original: original[target_key] = deepcopy(value) promoted[str(source_key)] = target_key elif original[target_key] != value: conflicts.append(f"decision_parameter_conflict:{source_key}->{target_key}") # Materialize concrete regions in the schema consumed by current checkers. zones = deepcopy(original.get("zones")) if isinstance(original.get("zones"), Mapping) else {} slot = str(original.get("slot", "")).strip() slot_bbox = original.get("slot_bbox") if slot and _is_bbox(slot_bbox) and slot not in zones: zones[slot] = {"id": slot, "bbox": list(slot_bbox)} promoted["slot_bbox"] = f"zones.{slot}" for item in _planned_regions(original): region_id = str(item.get("region_id") or item.get("id") or "").strip() geometry = _region_geometry(item) if region_id and geometry is not None and region_id not in zones: zones[region_id] = {"id": region_id, **geometry} promoted[f"planned_regions.{region_id}"] = f"zones.{region_id}" if zones: original["zones"] = zones return ParameterPromotion(original, promoted, tuple(conflicts)) def _slug(value: str) -> str: return re.sub(r"[^a-z0-9]+", "_", value.lower()).strip("_") or "requirement" def _roles(value: Any) -> tuple[str, ...]: text = str(value or "pred").strip().lower() if text in {"both", "input_output", "input+output", "input_pred"}: return ("input", "pred") if text in {"output", "prediction", "model_output", "pred"}: return ("pred",) if text == "input": return ("input",) return () def _is_bbox(value: Any) -> bool: return isinstance(value, (list, tuple)) and len(value) == 4 and all(isinstance(v, (int, float)) for v in value) def _region_geometry(item: Mapping[str, Any]) -> dict[str, Any] | None: for key in ("bbox", "bbox_xyxy", "polygon", "mask", "rect"): value = item.get(key) if value not in (None, [], {}, ""): return {"bbox" if key in {"bbox_xyxy", "rect"} else key: deepcopy(value)} return None def _bbox_from_rule(value: Any) -> list[float] | None: """Read an explicitly supplied bbox from resolver prose. Resolved plans sometimes keep a frozen zone as ``Use supplied bbox [x0,y0,x1,y1]`` instead of duplicating it into a separate geometry field. That is still contract geometry and must not be replaced by a detector guess. """ match = re.search( r"\bbbox\s*\[\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*,\s*" r"(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*\]", str(value or ""), flags=re.IGNORECASE, ) if not match: return None bbox = [float(item) for item in match.groups()] if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]: return None return bbox def _planned_regions(params: Mapping[str, Any]) -> list[dict[str, Any]]: raw = params.get("planned_regions", []) return [dict(item) for item in raw if isinstance(item, Mapping)] if isinstance(raw, list) else [] _REGION_METHODS = { "grounding_dino_box": "object_detection", "dino_box": "object_detection", "yolo_box": "object_detection", "yolo_world_box": "object_detection", # DINO proposes a concrete box first; SAM may refine it downstream. "sam_mask": "object_detection", "ocr_layout": "ocr", "route_mask": "route_extraction", "grid_parser": "state_parsing", "color_blob_parser": "visual_attribute", "cv_segmentation": "state_parsing", # Region proposal is objective-tool first. A VLM remains the fallback if # open-vocabulary detection cannot materialize the requested region. "vlm_region_box": "object_detection", "vlm_box": "object_detection", "manual": "object_detection", "manual_annotation": "object_detection", } def _compile_regions(params: Mapping[str, Any], available: frozenset[str]) -> tuple[RegionDependency, ...]: result: list[RegionDependency] = [] decision = _decision_parameters(params) for index, item in enumerate(_planned_regions(params)): region_id = str(item.get("region_id") or item.get("id") or f"region_{index}").strip() method = _slug(str(item.get("proposal_method") or "")) materializer = item.get("materializer") if isinstance(item.get("materializer"), Mapping) else {} materializer_kind = str(materializer.get("kind") or "") roles = _roles(item.get("source_image")) query = str(item.get("query_or_rule") or "").strip() geometry = _region_geometry(item) if geometry is None and method == "existing_zone": supplied_bbox = _bbox_from_rule(query) if supplied_bbox is not None: geometry = {"bbox": supplied_bbox} reasons: list[str] = [] resolver = "" if geometry is None and region_id == str(decision.get("slot", params.get("slot", ""))) and _is_bbox(decision.get("slot_bbox", params.get("slot_bbox"))): geometry = {"bbox": list(decision.get("slot_bbox", params.get("slot_bbox")))} elif geometry is None and region_id.endswith("_exact") and _is_bbox(decision.get("slot_bbox", params.get("slot_bbox"))): geometry = {"bbox": list(decision.get("slot_bbox", params.get("slot_bbox")))} if not roles: reasons.append("unknown_region_image_role") if geometry is not None: status = "concrete" if roles else "blocked" resolver = "existing_geometry" elif method == "existing_zone": resolver = "object_detection" query = query or region_id.replace("_", " ") status = "auto_resolvable" if resolver in available else "blocked" if resolver not in available: reasons.append(f"unavailable_region_resolver:{resolver}") else: resolver = { "detector_segmenter": "object_detection", "registered_change_derivation": "change_analysis", "ocr_container_layout": "ocr", "anchor_relative_zone": "state_parsing", "shelf_grid_parser": "state_parsing", "planar_free_space_parser": "state_parsing", "derived_free_space_zone": "state_parsing", "architecture_region_parser": "state_parsing", }.get(materializer_kind, _REGION_METHODS.get(method, "")) if not resolver: status = "blocked" reasons.append(f"unsupported_region_proposal_method:{method or 'missing'}") elif resolver not in available: status = "blocked" reasons.append(f"unavailable_region_resolver:{resolver}") elif not query: if resolver == "object_detection": query = region_id.replace("_", " ") status = "auto_resolvable" else: status = "blocked" reasons.append("auto_region_has_no_query_or_rule") else: status = "auto_resolvable" result.append( RegionDependency( region_id=region_id, image_roles=roles, proposal_method=method, resolver_operation=resolver, status=status, query_or_rule=query, geometry=geometry, reasons=tuple(reasons), ) ) return tuple(result) def normalize_tool_operation(value: Any) -> tuple[str, str, bool] | None: """Return ``(operation, family, optional)`` for a resolver tool phrase.""" text = _slug(str(value or "")) if not text: return None optional = any(token in text for token in ("fallback", "audit_if", "targeted_vlm", "uncertain", "low_confidence")) if "vlm" in text: return ("vlm_audit", "vlm", True) if any(token in text for token in ("grounding", "dino", "yolo", "open_vocabulary", "object_detection", "person_detection")): return ("object_detection", "detector", optional) if any(token in text for token in ("artifact_detection", "artifact_localization", "piece_detection", "card_detection", "cassette_detector", "tray_localization", "shelving_unit_detection", "calendar_region_detection")): return ("object_detection", "detector", optional) if "sam" in text or "instance_segmentation" in text or "mask_refin" in text: return ("mask_refinement", "segmenter", optional) if any(token in text for token in ("registration", "homography", "alignment_by_feature")): return ("image_registration", "registration", optional) if any(token in text for token in ("instance_matching", "appearance_matching", "identity_matching", "embedding_comparison")): return ("instance_matching", "matcher", optional) if any(token in text for token in ("ocr_string_alignment", "string_edit", "string_alignment")): return ("text_alignment", "ocr_postprocess", optional) if any(token in text for token in ("sharpness", "text_contrast", "legibility")): return ("text_quality", "image_metrics", optional) if "ocr" in text or "text_recognition" in text or "text_detection" in text: return ("ocr", "ocr", optional) if any(token in text for token in ("route_skeleton", "route_graph", "endpoint_matching", "connectivity", "centerline")): return ("route_topology", "route_parser", optional) if any(token in text for token in ("lane_arrow", "direction_classification", "movement_classification")): return ("route_movement_classification", "route_parser", optional) if any(token in text for token in ("route_line", "route_mask", "path_mask", "change_mask")): operation = "change_analysis" if "change_mask" in text else "route_extraction" return (operation, "change_analyzer" if operation == "change_analysis" else "route_parser", optional) if any(token in text for token in ("lane_boundary", "crosswalk", "stop_line", "waiting_box_segmentation")): return ("road_layout_parsing", "state_parser", optional) if any(token in text for token in ("grid", "slot_parser", "board_parser", "rack_parser", "shelf_parser", "state_parser")): return ("state_parsing", "state_parser", optional) if any(token in text for token in ("color", "attribute_class", "symbol", "checkbox", "glyph", "transparency")): return ("visual_attribute", "attribute_parser", optional) if any(token in text for token in ("difference", "perceptual", "image_similarity", "edge_comparison", "residual_occupancy", "vacancy_comparison")): return ("change_analysis", "change_analyzer", optional) if any(token in text for token in ("preservation", "residual_edge", "residual_texture", "source_zone_residual", "allowed_edit_mask")): return ("change_analysis", "change_analyzer", optional) if any(token in text for token in ("containment", "overlap", "support_geometry", "distance", "centroid", "geometry")): return ("spatial_geometry", "checker_internal", optional) if any(token in text for token in ("counting", "residual_count", "enumerate")): return ("counting", "checker_internal", optional) if any(token in text for token in ("connected_component", "instance_deduplication", "duplicate_detection_suppression")): return ("counting", "checker_internal", optional) if any(token in text for token in ("source_zone_construction", "existing_zone_loader")): return ("region_resolution", "checker_internal", optional) if text.startswith("crop") or "roi_upscaling" in text: return ("crop", "image_preprocess", optional) return None def _checker_requirements(spec: AtomicCheckSpec, params: Mapping[str, Any]) -> list[tuple[str, str, tuple[str, ...]]]: checker = _checker_base(spec.checker) rule = params.get("decision_rule", {}) decision_type = str(rule.get("type", "")) if isinstance(rule, Mapping) else "" canonical_type = canonical_rule_type(decision_type) out: list[tuple[str, str, tuple[str, ...]]] = [] if checker in {"object_presence_checker", "distance_checker"}: out.append(("object_detection", "detector", ("pred",))) if checker in {"object_zone_checker", "source_vacated_checker", "vehicle_slot_checker", "vehicle_penalty_checker"}: out.extend( [ ("object_detection", "detector", ("pred",)), ("mask_refinement", "segmenter", ("pred",)), ("spatial_geometry", "checker_internal", ("pred",)), ] ) if checker in {"object_preservation_checker", "source_vacated_checker"}: out.extend([("object_detection", "detector", ("input", "pred")), ("instance_matching", "matcher", ("input", "pred"))]) if checker in {"vehicle_slot_checker", "vehicle_penalty_checker", "color_classifier"}: out.append(("visual_attribute", "attribute_parser", ("pred",))) if checker in {"text_ocr_checker", "date_window_digit_checker"}: roles = ("input", "pred") if any(token in decision_type for token in ("preserv", "unchanged", "all_text")) else ("pred",) out.append(("ocr", "ocr", roles)) if checker in {"route_mask_checker", "endpoint_checker", "forbidden_overlap", "line_connectivity_checker"}: out.extend([("route_extraction", "route_parser", ("input", "pred")), ("route_topology", "route_parser", ("pred",))]) if _decision_parameters(params).get("expected_movements"): out.append(("route_movement_classification", "route_parser", ("input", "pred"))) if checker in {"state_checker", "state_image_proxy_checker", "grid_state_parser", "watch_hand_angle_parser"}: out.append(("state_parsing", "state_parser", ("pred",))) if checker in {"preservation", "preservation_checker", "change_mask_zone", "input_output_similarity_guard"}: out.extend([("image_registration", "registration", ("input", "pred")), ("change_analysis", "change_analyzer", ("input", "pred"))]) capability = metric_capability(canonical_type) if capability is not None: out.extend( (item.operation, item.tool_family, item.image_roles) for item in capability.evidence ) return out def _artifact_operations(text: str) -> tuple[str, ...]: normalized = text.lower() operations: list[str] = [] is_text_evidence = any(token in normalized for token in ("ocr", "string", "text", "line order")) groups = [ (("ocr", "string", "text", "line order"), "ocr"), (("detector", "detection", "label"), "object_detection"), (("sam", "mask"), "mask_refinement"), (("register", "corresponding roi"), "image_registration"), (("match", "identity", "appearance embedding"), "instance_matching"), (("containment", "overlap", "support-contact", "distance", "centroid"), "spatial_geometry"), (("route", "skeleton", "graph", "path", "endpoint"), "route_topology"), (("color", "transparency", "attribute"), "visual_attribute"), (("count", "inventory"), "counting"), (("sharpness", "contrast", "legibility"), "text_quality"), (("difference", "changed", "residual occupancy"), "change_analysis"), (("region", "zone", "polygon", "roi"), "region_resolution"), ] for needles, operation in groups: if any(needle in normalized for needle in needles): operations.append(operation) if "box" in normalized and not is_text_evidence: operations.append("object_detection") return tuple(dict.fromkeys(operations)) def _dedupe_requirements(items: Iterable[EvidenceRequirement]) -> tuple[EvidenceRequirement, ...]: result: list[EvidenceRequirement] = [] seen: set[tuple[Any, ...]] = set() for item in items: key = (item.operation, item.image_roles, item.region_ids, item.optional, item.source) if key not in seen: seen.add(key) result.append(item) return tuple(result) def compile_evidence_program( spec: AtomicCheckSpec, *, available_operations: Iterable[str] | None = None, contract_zones: Mapping[str, Any] | None = None, ) -> EvidenceProgram: """Compile one check and expose every objective execution blocker.""" available = frozenset(available_operations) if available_operations is not None else DEFAULT_AVAILABLE_OPERATIONS promotion = promote_checker_parameters(spec) params = deepcopy(promotion.checker_params) predicate = params.get("executable_predicate") if isinstance(params.get("executable_predicate"), Mapping) else None predicate_required = bool(params.get("require_executable_predicate")) if predicate_required and (predicate is None or predicate.get("status") != "executable"): predicate_reasons = ( ["missing_executable_predicate"] if predicate is None else [str(item) for item in predicate.get("reasons", [])] ) return EvidenceProgram( check_id=spec.check_id, checker=spec.checker, status="blocked", checker_params=params, promoted_parameters=promotion.promoted, parameter_conflicts=promotion.conflicts, regions=(), requirements=(), evidence_artifacts=(), unsupported_requirements=("executable_predicate",), reasons=tuple(dict.fromkeys(("executable_predicate_not_compiled", *predicate_reasons))), ) predicate_authoritative = bool(predicate_required and predicate is not None) authoritative_conflicts = ( () if predicate_authoritative and str(predicate.get("family") or "") == "structured_case_parser" else promotion.conflicts ) if predicate_authoritative: # Tool operations and derived-region semantics now come from the # executable predicate. Legacy prose remains in the contract only as # review provenance and must not be reinterpreted by this compiler. params["planned_regions"] = [ deepcopy(dict(item)) for item in predicate.get("regions", []) if isinstance(item, Mapping) and (item.get("region_id") or item.get("id")) ] # Top-level contract zones are part of the executable contract even though # AtomicCheckSpec only carries per-check params. Make them visible to the # region compiler and, later, to the fixed checker. if contract_zones: zones = deepcopy(dict(contract_zones)) zones.update(dict(params.get("zones", {})) if isinstance(params.get("zones"), Mapping) else {}) params["zones"] = zones planned = [] for item in _planned_regions(params): region = deepcopy(item) region_id = str(region.get("region_id") or region.get("id") or "").strip() zone = zones.get(region_id) if _region_geometry(region) is None and isinstance(zone, Mapping): geometry = _region_geometry(zone) if geometry: region.update(geometry) planned.append(region) if planned: params["planned_regions"] = planned regions = _compile_regions(params, available) # Geometry recovered by the strict region compiler must also reach the # fixed checker/CV executor. Keeping it only on RegionDependency would # make the plan look concrete while the runtime still saw a prose-only # placeholder. concrete_regions = {item.region_id: item.geometry for item in regions if item.geometry is not None} if concrete_regions: zones = deepcopy(dict(params.get("zones", {}))) if isinstance(params.get("zones"), Mapping) else {} for region_id, geometry in concrete_regions.items(): if region_id not in zones: zones[region_id] = {"id": region_id, **deepcopy(dict(geometry))} params["zones"] = zones planned = [] for item in _planned_regions(params): region = deepcopy(item) region_id = str(region.get("region_id") or region.get("id") or "").strip() geometry = concrete_regions.get(region_id) if geometry is not None and _region_geometry(region) is None: region.update(deepcopy(dict(geometry))) planned.append(region) if planned: params["planned_regions"] = planned region_ids = tuple(item.region_id for item in regions) requirements: list[EvidenceRequirement] = [] def add(operation: str, family: str, roles: tuple[str, ...], *, source: str, raw: str = "", optional: bool = False) -> None: index = len(requirements) blocked_regions = tuple(item.region_id for item in regions if item.status == "blocked") reasons: list[str] = [] if operation not in available: reasons.append(f"unavailable_operation:{operation}") if operation == "region_resolution": if not region_ids: reasons.append("region_resolution_has_no_typed_regions") elif blocked_regions: reasons.append("blocked_region_dependencies:" + ",".join(blocked_regions)) if region_ids and operation in {"spatial_geometry", "route_topology", "route_movement_classification", "change_analysis", "crop"} and blocked_regions: reasons.append("blocked_region_dependencies:" + ",".join(blocked_regions)) status = "optional" if optional else ("supported" if not reasons else "unsupported") uses_regions = operation in {"spatial_geometry", "route_topology", "route_movement_classification", "change_analysis", "crop", "region_resolution"} requirements.append( EvidenceRequirement( requirement_id=f"req_{index:02d}_{_slug(operation)}", operation=operation, tool_family=family, image_roles=roles, region_ids=region_ids if uses_regions else (), depends_on=tuple(f"region:{region_id}" for region_id in region_ids) if uses_regions else (), source=source, raw=raw, optional=optional, status=status, reasons=tuple(reasons), ) ) if predicate_authoritative: for operation in predicate.get("operations", []): if not isinstance(operation, Mapping): continue add( str(operation.get("kind") or ""), str(operation.get("tool_family") or "predicate_interpreter"), tuple(str(item) for item in operation.get("image_roles", []) if str(item)), source="executable_predicate", raw=str(operation.get("id") or ""), optional=bool(operation.get("optional")), ) requirements_tuple = _dedupe_requirements(requirements) unsupported = [ item.requirement_id for item in requirements_tuple if not item.optional and item.status != "supported" ] reasons = list(authoritative_conflicts) reasons.extend( reason for item in requirements_tuple if not item.optional and item.status != "supported" for reason in item.reasons ) return EvidenceProgram( check_id=spec.check_id, checker=spec.checker, status="executable" if not unsupported and not authoritative_conflicts else "blocked", checker_params=params, promoted_parameters=promotion.promoted, parameter_conflicts=authoritative_conflicts, regions=regions, requirements=requirements_tuple, evidence_artifacts=(), unsupported_requirements=tuple(unsupported), reasons=tuple(dict.fromkeys(reasons)), ) for operation, family, roles in _checker_requirements(spec, params): add(operation, family, roles, source="checker_and_decision_rule") raw_tools = params.get("tool_sequence", []) raw_tools = raw_tools if isinstance(raw_tools, list) else [raw_tools] for raw in raw_tools: normalized = normalize_tool_operation(raw) if normalized is None: add("unknown_declared_operation", "unknown", (), source="tool_sequence", raw=str(raw)) else: operation, family, optional = normalized roles = ("input", "pred") if operation in {"image_registration", "change_analysis", "instance_matching", "text_alignment", "text_quality"} else ("pred",) add(operation, family, roles, source="tool_sequence", raw=str(raw), optional=optional) # Region proposal jobs are first-class requirements, not invisible setup. for region in regions: if region.status == "auto_resolvable": add(region.resolver_operation, "region_proposer", region.image_roles, source="planned_regions", raw=region.region_id) raw_artifacts = params.get("evidence_required", []) raw_artifacts = raw_artifacts if isinstance(raw_artifacts, list) else [raw_artifacts] artifact_families = { "object_detection": "detector", "mask_refinement": "segmenter", "image_registration": "registration", "instance_matching": "matcher", "spatial_geometry": "checker_internal", "route_topology": "route_parser", "visual_attribute": "attribute_parser", "pose_estimation": "human_pose_parser", "local_correspondence": "local_correspondence", "counting": "checker_internal", "text_quality": "image_metrics", "change_analysis": "change_analyzer", "ocr": "ocr", "region_resolution": "checker_internal", } # evidence_required is executable input, not documentation. Promote every # typed producer it names into a first-class requirement so the runtime # cannot omit a tool merely because tool_sequence forgot to repeat it. for value in raw_artifacts: description = str(value).strip() if not description: continue lower = description.lower() for operation in _artifact_operations(description): if operation in {"image_registration", "instance_matching", "change_analysis", "text_quality"}: roles = ("input", "pred") elif "input" in lower and ("output" in lower or "pred" in lower): roles = ("input", "pred") else: roles = ("pred",) add(operation, artifact_families.get(operation, "unknown"), roles, source="evidence_required", raw=description) requirements_tuple = _dedupe_requirements(requirements) required_ops = {item.operation for item in requirements_tuple if not item.optional and item.status == "supported"} if regions and all(item.status != "blocked" for item in regions): required_ops.add("region_resolution") artifacts: list[EvidenceArtifact] = [] for index, value in enumerate(raw_artifacts): description = str(value).strip() if not description: continue producer_ops = _artifact_operations(description) missing = [op for op in producer_ops if op not in required_ops] reasons = [] if not producer_ops: reasons.append("evidence_artifact_has_no_typed_producer") if missing: reasons.append("missing_supported_producers:" + ",".join(missing)) artifacts.append( EvidenceArtifact( artifact_id=f"evidence_{index:02d}", description=description, producer_operations=producer_ops, status="supported" if not reasons else "unsupported", reasons=tuple(reasons), ) ) unsupported = [item.requirement_id for item in requirements_tuple if not item.optional and item.status != "supported"] unsupported.extend(item.artifact_id for item in artifacts if item.status != "supported") reasons: list[str] = list(promotion.conflicts) reasons.extend(reason for item in regions if item.status == "blocked" for reason in item.reasons) reasons.extend(reason for item in requirements_tuple if not item.optional and item.status != "supported" for reason in item.reasons) reasons.extend(reason for item in artifacts if item.status != "supported" for reason in item.reasons) plan_unresolved = params.get("plan_unresolved", []) if plan_unresolved: reasons.append("resolved_plan_has_unresolved_facts") unsupported.append("resolved_plan_unresolved") if not requirements_tuple: reasons.append("no_typed_evidence_requirements") unsupported.append("no_requirements") status = "executable" if not unsupported and not promotion.conflicts else "blocked" return EvidenceProgram( check_id=spec.check_id, checker=spec.checker, status=status, checker_params=params, promoted_parameters=promotion.promoted, parameter_conflicts=promotion.conflicts, regions=regions, requirements=requirements_tuple, evidence_artifacts=tuple(artifacts), unsupported_requirements=tuple(dict.fromkeys(unsupported)), reasons=tuple(dict.fromkeys(reasons)), )