wenjieshu's picture
Add files using upload-large-folder tool
b8ea052 verified
Raw History Blame Contribute Delete
116 kB
"""Compile atomic PVR checks into typed, cacheable tool calls. The evidence planner emits rich human-readable plans. Those plans are useful for auditing, but their free-form ``tool_sequence`` entries are not an executable API. This module is the strict bridge between a resolved contract and runtime tools: * every call is owned by one or more atomic ``check_id`` values; * detector prompts are scoped to one check, never unioned across a case; * identical physical calls may be cached without losing check provenance; * unsupported checker/tool requirements are explicit and route to fallback. """ from __future__ import annotations import hashlib import json import re from dataclasses import dataclass, field, replace from typing import Any, Iterable, Mapping from pvr_eval.core.schema import AtomicCheckSpec, EvalContract from pvr_eval.agent.contract_metric_binding import ( PRESERVATION_RULE_TYPES, REGISTERED_RULE_TYPES, canonical_rule_type, metric_capability, ) from pvr_eval.agent.detector_fusion import semantic_class from pvr_eval.agent.evidence_program import DEFAULT_AVAILABLE_OPERATIONS, EvidenceProgram, compile_evidence_program from pvr_eval.agent.executable_predicate import validate_executable_predicate from pvr_eval.contracts.metric_profiles import ( human_pose_profile_parameters, local_correspondence_profile_parameters, ) from pvr_eval.contracts.region_materializer_registry import executable_region_materializer TOOL_PLAN_SCHEMA_VERSION = "pvr.agent_tool_plan.v2" MAX_DETECTOR_QUERIES_PER_CALL = 8 # Operations with a real executor or a fixed checker implementation in this # runtime. Text alignment/quality remain excluded: current OCR checkers do not # actually compare input/output strings or emit calibrated legibility metrics. RUNTIME_AVAILABLE_OPERATIONS = frozenset(DEFAULT_AVAILABLE_OPERATIONS - {"text_alignment", "text_quality"}) _SUPPORTED_EXPLICIT_COLORS = frozenset( {"red", "orange", "yellow", "green", "cyan", "blue", "purple", "pink", "black", "white", "gray", "grey", "brown"} ) @dataclass(frozen=True) class ToolCallSpec: """One physical tool invocation that may serve several atomic checks.""" call_id: str cache_key: str tool: str case_key: str image_role: str image_identity: str check_ids: tuple[str, ...] queries: tuple[str, ...] = () region_ids: tuple[str, ...] = () depends_on: tuple[str, ...] = () params: dict[str, Any] = field(default_factory=dict) def to_dict(self) -> dict[str, Any]: return { "call_id": self.call_id, "cache_key": self.cache_key, "tool": self.tool, "case_key": self.case_key, "image_role": self.image_role, "image_identity": self.image_identity, "check_ids": list(self.check_ids), "queries": list(self.queries), "region_ids": list(self.region_ids), "depends_on": list(self.depends_on), "params": self.params, } @dataclass(frozen=True) class CheckToolPlan: check_id: str checker: str tool_call_ids: tuple[str, ...] fallback: str status: str reasons: tuple[str, ...] = () declared_tool_families: tuple[str, ...] = () unrecognized_declared_tools: tuple[str, ...] = () evidence_program: dict[str, Any] = field(default_factory=dict) def to_dict(self) -> dict[str, Any]: return { "check_id": self.check_id, "checker": self.checker, "tool_call_ids": list(self.tool_call_ids), "fallback": self.fallback, "status": self.status, "reasons": list(self.reasons), "declared_tool_families": list(self.declared_tool_families), "unrecognized_declared_tools": list(self.unrecognized_declared_tools), "evidence_program": self.evidence_program, } _STATE_PREFIXES = { "moved", "move", "relocated", "relocate", "original", "output", "input", "remaining", "required", "matching", "distinct", "visible", "detected", } def _clean_query(value: Any) -> str: text = re.sub(r"[_/]+", " ", str(value or "").strip().lower()) text = re.sub(r"\s+", " ", text).strip(" ,.;:-") words = text.split() while words and words[0] in _STATE_PREFIXES: words.pop(0) return " ".join(words) def _query_tokens(value: str) -> set[str]: stop = {"a", "an", "the", "of", "or", "and", "from", "on", "in", "at", "to", "with", "belonging"} return {word for word in re.findall(r"[a-z0-9]+", value.lower()) if word not in stop} def _same_concept(left: str, right: str) -> bool: a, b = _query_tokens(left), _query_tokens(right) if not a or not b: return False # A shared source anchor can dominate token overlap. Explicitly different # colours still denote different inventory members and must never be # collapsed into one detector query. left_colours = a & _SUPPORTED_EXPLICIT_COLORS right_colours = b & _SUPPORTED_EXPLICIT_COLORS if left_colours and right_colours and left_colours != right_colours: return False # A target and its support/location often share several words (for # example, "bird on robot left shoulder" and "robot left shoulder"). # They are not aliases: collapsing them removes the target noun and makes # an absence search incapable of looking for the object that may have # moved. Known coarse entity classes are therefore a hard merge gate. known_classes = { "appliance", "backpack", "bird", "bottle", "cat", "chair", "computer", "container", "document", "dog", "furniture", "person", "phone", "printer", "snack", "table", "television", } left_class = semantic_class({"query_text": left}) right_class = semantic_class({"query_text": right}) if left_class != right_class and (left_class in known_classes or right_class in known_classes): return False overlap = len(a & b) if overlap >= 2 and (a <= b or b <= a): return True return overlap >= 2 and overlap / len(a | b) >= 0.5 def canonical_detector_queries(values: Iterable[Any]) -> tuple[str, ...]: """Collapse obvious per-check aliases without merging distinct entities.""" clusters: list[list[str]] = [] for raw in values: query = _clean_query(raw) if not query: continue target = next((cluster for cluster in clusters if any(_same_concept(query, item) for item in cluster)), None) if target is None: clusters.append([query]) elif query not in target: target.append(query) representatives = [] for cluster in clusters: # Short noun phrases are generally more stable for DINO/YOLO-World. representatives.append(min(cluster, key=lambda item: (len(_query_tokens(item)), len(item), item))) return tuple(dict.fromkeys(representatives)) def _registered_subject_detector_aliases( predicate: Mapping[str, Any], values: Sequence[str], ) -> tuple[str, ...]: """Add narrow visual aliases for registered repeated-object profiles. These aliases improve proposal recall only. They do not change the physical subject cardinality, and downstream repeated-component geometry must still certify a unique group before any fact can be emitted. """ rule_type = str(predicate.get("source_rule_type") or "") semantic = " ".join(values).casefold() if rule_type == "supported_nonintersecting_placement" and "binder" in semantic: return ("file folders matching the input shelf binders",) return () _REGION_ACTION_WORDS = frozenset( { "align", "apply", "classify", "compare", "compute", "construct", "define", "detect", "divide", "estimate", "evaluate", "exclude", "expand", "fit", "form", "identify", "include", "infer", "inspect", "mark", "match", "measure", "perform", "position", "preserve", "preserving", "refine", "register", "retain", "reuse", "segment", "select", "subtract", "transfer", "use", } ) _HARD_DERIVED_REGION_TOKENS = frozenset( { "all", "allowed", "audit", "band", "boundary", "compare", "comparison", "corridor", "edge", "footprint", "inventory", "union", } ) _REGION_PROCEDURAL_TOKENS = frozenset( {"downstream", "extrapolation", "geometry", "legal", "movement", "orientation", "upstream"} ) _DERIVED_REGION_TOKENS = frozenset( { "all", "allowed", "audit", "band", "boundary", "components", "context", "correspondence", "corridor", "crop", "crops", "edge", "footprint", "invariant", "locations", "margin", "scene", "search", "union", } ) _REGION_ID_GENERIC_TOKENS = frozenset( { "after", "anchor", "area", "areas", "as", "before", "both", "by", "component", "components", "context", "correspondence", "crop", "crops", "entities", "entity", "evidence", "exact", "for", "from", "id", "identity", "input", "instance", "instances", "interior", "invariant", "item", "items", "landing", "mask", "masks", "match", "neatness", "object", "objects", "of", "output", "reference", "references", "region", "regions", "roi", "set", "source", "structure", "target", "template", "templates", "to", "using", "vacancy", "writing", "zone", "zones", } ) _REGION_DESCRIPTOR_ONLY_TOKENS = frozenset( { "all", "background", "bottom", "center", "color", "delicate", "duplicate", "estimated", "exact", "five", "forbidden", "four", "global", "grounded", "irrelevant", "left", "lower", "middle", "morphed", "original", "relocated", "right", "solid", "specific", "suspected", "three", "top", "upper", } | _SUPPORTED_EXPLICIT_COLORS ) def _sanitize_region_entity_phrase(value: str) -> str: """Keep an object noun phrase and discard tool/procedure language.""" phrase = re.sub(r"[_/]+", " ", str(value or "").lower()) phrase = re.sub(r"\bsam[- ]?(?:segment(?:ation)?|refine)\b", "sam", phrase) phrase = re.sub( r"^(?:followed by|aided by|edge-guided|after|before|repeat(?: the)? same|obtain|add)\s+", "", phrase, ) phrase = re.sub(r"^(?:seed\s+)?sam\s+(?:from|for|to separate|as)?\s*", "", phrase) phrase = re.sub(r"^re-segment\s+", "", phrase) phrase = re.sub(r"^(?:separate boxes for|search for)\s+", "", phrase) phrase = re.split( r"\b(?:using|after registration|before registration|followed by sam|aided by|" r"as identity|for identity|matching source identity|identity cues?|identity descriptors?|" r"identity reference|identity template|identity set|registration|segmentation|sam prompts?|sam evidence)\b", phrase, maxsplit=1, )[0] phrase = re.sub(r"\b(?:identity|registration|segmentation|detection|sam)\b", " ", phrase) phrase = re.sub(r"\bdetector boxes?\b", " ", phrase) phrase = re.sub(r"\s+", " ", phrase).strip(" .:-") words = phrase.split() if not words or len(words) > 6: return "" if any(word in _REGION_ACTION_WORDS or word in _REGION_PROCEDURAL_TOKENS for word in words): return "" if any( word in { "are", "consolidate", "derive", "descriptor", "descriptors", "dilated", "exclusion", "geometric", "matches", "multi-scale", "outside", "polygon", "prompts", "reject", "whose", } for word in words ): return "" if set(words) <= _REGION_DESCRIPTOR_ONLY_TOKENS: return "" if phrase in {"image", "item", "items", "object", "objects", "scene", "scenes", "them"}: return "" return phrase def _split_region_id_entities(region_id: str) -> tuple[str, ...]: text = re.sub(r"[_/]+", " ", region_id.lower()).strip() # Preserve useful compound color descriptions such as ``black_and_white_cat``. if re.search( rf"\b(?:{'|'.join(sorted(_SUPPORTED_EXPLICIT_COLORS))})\s+and\s+" rf"(?:{'|'.join(sorted(_SUPPORTED_EXPLICIT_COLORS))})\b", text, ): return (text,) return tuple(item.strip() for item in re.split(r"\b(?:and|or)\b", text) if item.strip()) def _region_id_fallback(region_id: str) -> tuple[str, ...]: """Return a conservative object phrase encoded by a region id. Derived geometry such as an edit corridor or a boundary is not an object detector target. Returning no query forces an explicit parser/VLM fallback instead of manufacturing a plausible-looking but meaningless DINO box. """ tokens = [item for item in re.findall(r"[a-z0-9]+", region_id.lower()) if item] normalized_tokens = {item[:-1] if item.endswith("s") and len(item) > 3 else item for item in tokens} if normalized_tokens & _DERIVED_REGION_TOKENS: return () phrases: list[str] = [] for entity in _split_region_id_entities(region_id): words = [ item for item in re.findall(r"[a-z0-9]+", entity.lower()) if item not in _REGION_ID_GENERIC_TOKENS ] phrase = _sanitize_region_entity_phrase(" ".join(words)) if phrase: phrases.append(phrase) return canonical_detector_queries(phrases) def region_detector_queries(value: str, region_id: str, limit: int = 8) -> tuple[str, ...]: """Compile resolver prose into short, entity-only DINO/YOLO prompts. This is intentionally conservative. Detector prompts are object or container noun phrases; instructions about unions, matching, topology, boundaries, or image comparison remain typed downstream operations. """ text = re.sub(r"[_/]+", " ", str(value or "").lower()) # Resolver prose often names the proposal tool inline. Normalize compound # verbs before clause splitting so ``SAM-segment X`` and # ``identity-match X`` yield the entity X, never a detector prompt that # still contains the tool instruction. text = re.sub( r"\b(?:sam(?:[- ]?(?:segment(?:ation)?|refine))?|identity[- ]?match(?:ing)?|input[- ]?output[- ]?match(?:ing)?)\b", "detect", text, ) raw_region_tokens = set(re.findall(r"[a-z0-9]+", region_id.lower())) region_tokens = {item[:-1] if item.endswith("s") and len(item) > 3 else item for item in raw_region_tokens} if region_tokens & _HARD_DERIVED_REGION_TOKENS: return () if re.search(r"\bmatch\b.*\b(?:paired )?(?:input output )?crops?\b", text) or re.search( r"\bfor (?:each|every) matched\b.*\bgenerate (?:a )?crop\b", text ): return () text = re.split(r"\b(?:exclude|excluding|do not count|never count)\b", text, maxsplit=1)[0] procedural = bool(re.search(r"\b(?:union|subtract|difference|boundary|corridor|footprint|exact mapped slots)\b", text)) fragments = re.split(r"[,;]|\band\b|\bor\b|\bthen\b", text) cleaned: list[str] = [] for fragment in fragments: fragment = re.sub( r"^(?:in|from|on) the (?:input|output),?\s*|^(?:for every|for each)\s+|" r"^after\s+(?:selecting|detecting|locating)\s+|^(?:including|retaining|especially|for)\s+", "", fragment.strip(), ) # Strip detector/segmenter imperatives independently for every clause. fragment = re.sub( r"^(?:(?:individually\s+)?(?:locate|detect|ground|segment|propose|find|enumerate|generate|" r"include|extract|fit|apply|estimate|align|register|preserve|reuse)\s+)+", "", fragment, ) fragment = re.sub(r"^(?:for|from|as|using)\s+", "", fragment) fragment = re.sub( r"\b(?:in|into|from|on)\s+(?:the\s+)?(?:input|output)(?:\s+image)?\b", " ", fragment, ) fragment = re.split( r"\b(?:where|whose|that|which|as one|intended to|associated with|resting on|to identify|to compute|to find)\b", fragment, maxsplit=1, )[0] fragment = re.sub( r"\b(?:the|a|an|its|their|this|those|any other|visible|full|complete|relevant|nearby|original|" r"output|input|each|every|distinct|estimated|matched|relocated|pre existing|already orderly)\b", " ", fragment, ) fragment = re.sub(r"\b(?:with|around|within|across|between|through|while|except|against|under|beneath|behind|beside|near)\b.*$", "", fragment) fragment = re.sub(r"\b(?:instance|instances|area|region|roi|masks?|crop|context|margin|locations?)\b", " ", fragment) fragment = re.sub(r"\b(?:immediately|portion|but)\b", " ", fragment) fragment = re.sub(r"\bwhite paper writing\b", "white paper", fragment) fragment = re.sub( r"\b(?:horizontal )?top surface of (?:large )?(?:foreground )?(?:wooden )?desk\b", "desk surface", fragment, ) fragment = re.sub( r"\b(?:small )?(?:dark )?(?:standing )?(?:rectangular )?frame slate\b", "standing frame slate", fragment, ) fragment = re.sub(r"\b(?:wall )?window perspective lines?\b", "", fragment) fragment = _sanitize_region_entity_phrase(fragment) fragment = re.sub(r"\b(?:in|into|from|on|to)$", "", fragment).strip() words = fragment.split() if ( not words or len(words) > 6 or any(word in _REGION_ACTION_WORDS for word in words) or any(word in _REGION_PROCEDURAL_TOKENS for word in words) ): continue if fragment in {"image", "item", "items", "objects", "scenes", "them"}: continue cleaned.append(fragment) queries = canonical_detector_queries(cleaned) core_tokens = { token for token in re.findall(r"[a-z0-9]+", region_id.lower()) if token not in { "all", "area", "exact", "id", "instance", "mask", "output", "input", "region", "roi", "source", "target", "zone", } } semantic_core_tokens = core_tokens - {"left", "right", "top", "bottom", "front", "back", "middle", "center"} matching = tuple(query for query in queries if semantic_core_tokens & _query_tokens(query)) fallback = _region_id_fallback(region_id) if matching: queries = matching elif fallback: # Region ids are contract-owned and usually name the intended object # more reliably than a procedural resolver sentence. Prefer that # entity-only phrase when no extracted phrase agrees with the id. queries = fallback if len(queries) == 1 and len(queries[0].split()) == 1: queries = fallback or queries if not queries and "entry" in region_tokens and re.search(r"\b(?:lane|lanes|crosswalk|road|arrow)\b", text): return () if not queries or procedural: # Procedural derived regions must not be reduced to a single detector # box merely because their id happens to contain an object word. if procedural and not fallback: return () queries = fallback normalized_region_id = region_id.lower() if any(token in normalized_region_id for token in ("inventory", "original_clutter_instances")): generic_inventory = { "loose inanimate item", "loose inanimate items", "coherent stack", "coherent stacks", "assign stable ids", "stable ids", } if queries and all(query in generic_inventory for query in queries): return () if "decor" in normalized_region_id: queries = tuple(query for query in queries if query not in {"wall", "walls", "shelf", "shelves"}) return queries def _singular_head(value: str) -> str: words = [word for word in re.findall(r"[a-z0-9-]+", value.lower()) if word] words = [word for word in words if word not in {"all", "each", "every", "four", "five", "six", "distinct"}] if not words: return "object" head = " ".join(words[-2:]) if head.endswith("ies"): return head[:-3] + "y" if head.endswith("s") and not head.endswith("ss"): return head[:-1] return head def expand_detector_query(value: Any) -> tuple[str, ...]: """Split explicit entity lists while retaining single-object descriptions. DINO should receive one semantic entity per query. Detailed attributes of one object stay together, while comma-separated inventories and colon lists become separate queries. The caller batches every emitted query, so expansion never causes silent truncation. """ text = _clean_query(value) if not text: return () if ":" in text: prefix, raw_items = text.split(":", 1) parts = [re.sub(r"^(?:and|or)\s+", "", item.strip(" ,")) for item in raw_items.split(",")] parts = [item for item in parts if item] if len(parts) >= 2: head = _singular_head(prefix) return tuple(f"{item} {head}" for item in parts) if "," not in text: return (text,) first_comma = text.index(",") descriptor = re.search(r"\b(?:with|including|containing|depicting|bearing)\b", text) if descriptor and descriptor.start() < first_comma: return (text,) parts = [re.sub(r"^(?:and|or)\s+", "", item.strip(" ,")) for item in text.split(",")] parts = [item for item in parts if item] if len(parts) < 2: return (text,) location = "" match = re.search( r"\b(?:on|in|at|near|beside|inside|within|under|above|behind|across|from)\b.+$", parts[-1], ) if match: location = match.group(0) parts[-1] = parts[-1][: match.start()].strip() expanded = [] for part in parts: part = re.sub(r"^(?:all|each|every|new)\s+", "", part).strip() if not part: continue if location and not re.search(r"\b(?:on|in|at|near|beside|inside|within|under|above|behind|across|from)\b", part): part = f"{part} {location}" expanded.append(part) return tuple(expanded) or (text,) def _values(params: dict[str, Any], key: str) -> list[Any]: value = params.get(key) if value is None or value == "": return [] if isinstance(value, (list, tuple, set)): return list(value) return [value] def _explicit_colors(params: dict[str, Any]) -> tuple[str, ...]: values: list[Any] = [] for key in ("line_color", "wire_color", "route_color", "expected_color", "target_color", "color", "colors"): values.extend(_values(params, key)) return tuple( dict.fromkeys( str(value).lower().strip() for value in values if str(value).lower().strip() in _SUPPORTED_EXPLICIT_COLORS ) ) def _has_structured_cells(params: dict[str, Any]) -> bool: return any( isinstance(params.get(key), list) and bool(params[key]) and all(isinstance(item, dict) for item in params[key]) for key in ("expected_cells", "cells", "slots", "expected_slots", "cell_states") ) def detector_queries_for_check(spec: AtomicCheckSpec) -> tuple[str, ...]: params = dict(spec.params or {}) # Reviewed object_queries are the detector interface. Legacy ``object`` # prose often repeats the whole question and must not broaden it with # region nouns or parenthetical examples. raw = _values(params, "object_queries") if not raw: raw = [] for key in ("labels", "objects", "object"): raw.extend(_values(params, key)) expanded = [query for value in raw for query in expand_detector_query(value)] return canonical_detector_queries(expanded) def _checker_base(checker: str) -> str: return str(checker).split("|", 1)[0].split(":", 1)[0].strip() def _region_ids(spec: AtomicCheckSpec) -> tuple[str, ...]: params = dict(spec.params or {}) regions = params.get("planned_regions", []) out = [] if isinstance(regions, list): for item in regions: if isinstance(item, dict): value = item.get("region_id") or item.get("id") if value: out.append(str(value)) for key in ("zone", "zone_id", "target_zone", "source_zone", "forbidden_zone"): value = params.get(key) if isinstance(value, str) and value: out.append(value) return tuple(dict.fromkeys(out)) def normalize_declared_tool(value: Any) -> str | None: text = re.sub(r"[^a-z0-9]+", "_", str(value or "").lower()).strip("_") if not text: return None if "vlm" in text: return "vlm_fallback" if any(token in text for token in ("grounding", "dino", "yolo", "open_vocabulary", "object_detection", "person_detection")): return "open_vocabulary_detector" if "sam" in text or "segmentation" in text: return "mask_refiner" if "ocr" in text or "text_recognition" in text or "text_detection" in text: return "ocr" if any(token in text for token in ("registration", "homography", "alignment", "feature_matching")): return "image_registration" if any(token in text for token in ("change_mask", "difference", "similarity", "perceptual", "edge_comparison")): return "change_analysis" if any(token in text for token in ("route", "path", "skeleton", "centerline", "connectivity")): return "route_parser" if any(token in text for token in ("grid", "slot", "board", "rack", "shelf", "cell_parser")): return "state_parser" if any(token in text for token in ("color", "symbol", "checkbox", "glyph")): return "visual_attribute_parser" if any(token in text for token in ("pose", "keypoint", "skeleton")): return "human_pose_parser" if any(token in text for token in ("geometry", "containment", "overlap", "distance", "counting", "matching", "comparison")): return "checker_internal" return None def _declared_tool_audit(spec: AtomicCheckSpec) -> tuple[tuple[str, ...], tuple[str, ...]]: raw = spec.params.get("tool_sequence", []) if isinstance(spec.params, dict) else [] raw = raw if isinstance(raw, list) else [raw] families, unknown = [], [] for item in raw: family = normalize_declared_tool(item) if family: families.append(family) elif str(item).strip(): unknown.append(str(item).strip()) return tuple(dict.fromkeys(families)), tuple(dict.fromkeys(unknown)) def _cache_key( *, case_key: str, tool: str, image_role: str, image_identity: str, queries: tuple[str, ...], region_ids: tuple[str, ...], depends_on: tuple[str, ...], params: dict[str, Any], ) -> str: payload = { "case_key": case_key, "tool": tool, "image_role": image_role, "image_identity": image_identity, "queries": list(queries), "region_ids": list(region_ids), "depends_on": list(depends_on), "params": params, } return hashlib.sha256(json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest() def _call(*, case_key: str, check_id: str, tool: str, image_role: str, image_identity: str, queries: tuple[str, ...] = (), region_ids: tuple[str, ...] = (), depends_on: tuple[str, ...] = (), params: dict[str, Any] | None = None) -> ToolCallSpec: call_params = dict(params or {}) cache_key = _cache_key( case_key=case_key, tool=tool, image_role=image_role, image_identity=image_identity, queries=queries, region_ids=region_ids, depends_on=depends_on, params=call_params, ) return ToolCallSpec( call_id=f"call_{cache_key[:20]}", cache_key=cache_key, tool=tool, case_key=case_key, image_role=image_role, image_identity=image_identity, check_ids=(check_id,), queries=queries, region_ids=region_ids, depends_on=depends_on, params=call_params, ) def _chunks(values: tuple[str, ...], size: int) -> list[tuple[str, ...]]: return [values[index : index + size] for index in range(0, len(values), size)] def _region_zone_kind( region_id: str, region_queries: tuple[str, ...], target_queries: tuple[str, ...], rule_type: str ) -> str: """Separate spatial support surfaces from regions that are object instances. Both kinds are region-resolver inputs, but only an independent spatial region may arbitrate a target detector conflict. Treating a second box for the target object as a destination zone makes every false positive self-validating, which is exactly the role leakage this typed plan is intended to prevent. """ tokens = set(re.findall(r"[a-z0-9]+", region_id.lower())) instance_tokens = { "instance", "instances", "item", "items", "object", "objects", "inventory", "mask", "masks", "entity", "entities", "relocated", "moved", "binder", "binders", } same_as_target = any( _same_concept(region_query, target_query) for region_query in region_queries for target_query in target_queries ) if tokens & instance_tokens or same_as_target: return "instance_reference" positive_zone_rules = {"destination_zone_containment", "source_zone_vacancy", "desk_clutter_residual_count"} negative_tokens = {"forbidden", "protected", "exclusion", "exclude", "tray", "invariant"} if rule_type in positive_zone_rules and not tokens & negative_tokens: return "spatial_constraint" return "context_region" def _calls_for_executable_predicate( case_key: str, spec: AtomicCheckSpec, predicate: Mapping[str, Any], image_identities: dict[str, str], program: EvidenceProgram | None = None, ) -> tuple[list[ToolCallSpec], list[str]]: """Lower one authoritative predicate without consulting legacy prose.""" validation = validate_executable_predicate(predicate) if not validation.valid or predicate.get("status") != "executable": return [], list(dict.fromkeys(("executable_predicate_not_executable", *validation.reasons))) family = str(predicate.get("family") or "") if family == "registered_metric_bridge": if program is None: return [], ["registered_metric_bridge_missing_evidence_program"] return _calls_for_program( case_key, spec, program, image_identities, authoritative_lowering=False, ) if family == "structured_case_parser": if program is None: return [], ["structured_case_parser_missing_evidence_program"] return _calls_for_program( case_key, spec, program, image_identities, authoritative_lowering=False, ) supported_families = { "source_region_clearance", "surface_residual_inventory", "destination_membership", "relocation_transition", "cross_image_inventory_integrity", "source_region_restoration", "source_instance_displacement", "fixed_location_instance_preservation", "fixed_location_entity_preservation", "registered_invariant_region_preservation", "relocated_entity_integrity", "registered_structural_state", "group_pose_arrangement", "contract_family_all_of", } if family not in supported_families: return [], [f"predicate_family_has_no_lowerer:{predicate.get('family') or 'missing'}"] operations = [item for item in predicate.get("operations", []) if isinstance(item, Mapping)] operation_kinds = {str(item.get("kind") or "") for item in operations} runtime_unavailable_regions = [ str(region.get("region_id") or region.get("id") or "missing") for region in predicate.get("regions", []) if isinstance(region, Mapping) and not executable_region_materializer( str( (region.get("materializer") or {}).get("kind") if isinstance(region.get("materializer"), Mapping) else "" ) ) ] if predicate.get("capability_versions") and runtime_unavailable_regions: return [], [ "predicate_region_materializer_runtime_unavailable:" + ",".join(runtime_unavailable_regions) ] semantic_families = { str(item) for item in predicate.get("target_families", []) if str(item) } or {family} required = {"object_detection", "mask_refinement", "predicate_decision"} if family in {"source_region_clearance", "source_region_restoration", "relocation_transition", "source_instance_displacement"}: required.add("source_state_classification") if family == "fixed_location_instance_preservation" or "fixed_location_entity_preservation" in semantic_families: required.update({"instance_matching", "image_registration"}) if predicate.get("parameters", {}).get("source_instance_annotations"): required.add("instance_matching") if predicate.get("parameters", {}).get("source_selector_profile"): required.add("source_instance_selection") if family in {"surface_residual_inventory", "destination_membership", "relocation_transition"}: required.update({"region_resolution", "spatial_geometry", "counting"}) if family == "relocation_transition": required.discard("counting") missing = sorted(required - operation_kinds) if missing: return [], ["predicate_missing_required_operations:" + ",".join(missing)] def subject_queries(role: str) -> tuple[str, ...]: roster_queries = tuple(dict.fromkeys( str(item.get("query_text") or "").strip() for item in predicate.get("parameters", {}).get("source_instance_annotations", []) if isinstance(item, Mapping) and str(item.get("query_text") or "").strip() )) if roster_queries: # Human-verified annotations define distinct source instances. # Do not semantic-dedupe location-qualified queries here: two # raccoons on different trunks or two yellow birds on different # branches are separate roster members, not detector aliases. return roster_queries values: list[str] = [] for item in predicate.get("subjects", []): if isinstance(item, Mapping): plural_key = "input_queries" if role == "input" else "output_queries" plural_values = item.get(plural_key) if isinstance(plural_values, (list, tuple)): values.extend(str(value) for value in plural_values if str(value or "").strip()) continue key = "input_query" if role == "input" else "output_query" value = item.get(key) or item.get("identity_query") else: value = item if str(value or "").strip(): values.append(str(value)) if predicate.get("parameters", {}).get("articulated_entity_preservation_profile"): values.extend( str(value) for value in predicate.get("component_queries", []) if str(value or "").strip() ) if role == "pred" and family == "group_pose_arrangement": # Group-pose predicates deliberately separate the aggregate # subject (for example, a relocated binder row) from its physical # components (individual binder spines). The terminal adapter # measures PCA and spacing on the components, so omitting these # queries makes an otherwise executable predicate impossible to # satisfy at runtime. values.extend( str(value) for value in predicate.get("component_queries", []) if str(value or "").strip() ) if role == "pred" and "crop_classification" in operation_kinds: values.extend( str(value) for value in predicate.get("parameters", {}).get( "classification_proposal_queries", [] ) if str(value or "").strip() ) values.extend(_registered_subject_detector_aliases(predicate, values)) return canonical_detector_queries(values) identity_queries = subject_queries("pred") if not identity_queries: return [], ["executable_predicate_has_no_detector_queries"] calls: list[ToolCallSpec] = [] detectors_by_role: dict[str, list[ToolCallSpec]] = {} for role in ("input", "pred"): role_declared = any( item.get("kind") == "object_detection" and role in item.get("image_roles", []) for item in operations ) if not role_declared: continue role_queries = subject_queries(role) role_calls = [ _call( case_key=case_key, check_id=spec.check_id, tool="open_vocabulary_detector", image_role=role, image_identity=image_identities[role], queries=batch, params={ "evidence_role": "target_instance", "purpose": "target_detection", "predicate_family": family, "predicate_schema_version": predicate["schema_version"], }, ) for batch in _chunks(role_queries, MAX_DETECTOR_QUERIES_PER_CALL) ] detectors_by_role[role] = role_calls calls.extend(role_calls) masks_by_role: dict[str, ToolCallSpec] = {} for role in ("input", "pred"): role_declared = any( item.get("kind") == "mask_refinement" and role in item.get("image_roles", []) for item in operations ) dependencies = detectors_by_role.get(role, []) if role_declared and not dependencies: return [], [f"predicate_mask_refinement_has_no_detector_dependency:{role}"] if not role_declared: continue mask = _call( case_key=case_key, check_id=spec.check_id, tool="mask_refiner", image_role=role, image_identity=image_identities[role], queries=subject_queries(role), depends_on=tuple(item.call_id for item in dependencies), params={ "detection_scope": "dependency_call_ids_v1", "source_zone_policy": "per_instance_input_mask_or_bbox", "predicate_family": family, }, ) masks_by_role[role] = mask calls.append(mask) source_selector_call: ToolCallSpec | None = None source_selector_parameters = predicate.get("parameters", {}).get("source_selector") if "source_instance_selection" in operation_kinds: if not isinstance(source_selector_parameters, Mapping): return [], ["source_instance_selector_parameters_missing"] input_target_mask = masks_by_role.get("input") selector_identity_queries = canonical_detector_queries( source_selector_parameters.get("identity_queries", []) ) anchor_queries = canonical_detector_queries( source_selector_parameters.get("anchor_queries", []) ) if input_target_mask is None or not selector_identity_queries or not anchor_queries: return [], ["source_instance_selector_dependencies_incomplete"] # A selector may identify an allowed-edit support object (for example # a shoulder bird) while the predicate roster is a different entity # (the robot). In that case it receives its own question-scoped # detector/mask lineage instead of reusing the roster mask. if tuple(selector_identity_queries) != tuple(subject_queries("input")): identity_detectors = [ _call( case_key=case_key, check_id=spec.check_id, tool="open_vocabulary_detector", image_role="input", image_identity=image_identities["input"], queries=batch, params={ "evidence_role": "source_selector_identity", "purpose": "source_selector_identity_detection", "predicate_family": family, "predicate_schema_version": predicate["schema_version"], }, ) for batch in _chunks(selector_identity_queries, MAX_DETECTOR_QUERIES_PER_CALL) ] calls.extend(identity_detectors) input_target_mask = _call( case_key=case_key, check_id=spec.check_id, tool="mask_refiner", image_role="input", image_identity=image_identities["input"], queries=selector_identity_queries, depends_on=tuple(item.call_id for item in identity_detectors), params={ "detection_scope": "dependency_call_ids_v1", "evidence_role": "source_selector_identity", "predicate_family": family, }, ) calls.append(input_target_mask) anchor_detectors = [ _call( case_key=case_key, check_id=spec.check_id, tool="open_vocabulary_detector", image_role="input", image_identity=image_identities["input"], queries=batch, params={ "evidence_role": "source_selector_anchor", "purpose": "source_selector_anchor_detection", "predicate_family": family, "predicate_schema_version": predicate["schema_version"], }, ) for batch in _chunks(anchor_queries, MAX_DETECTOR_QUERIES_PER_CALL) ] calls.extend(anchor_detectors) anchor_mask = _call( case_key=case_key, check_id=spec.check_id, tool="mask_refiner", image_role="input", image_identity=image_identities["input"], queries=anchor_queries, depends_on=tuple(item.call_id for item in anchor_detectors), params={ "detection_scope": "dependency_call_ids_v1", "evidence_role": "source_selector_anchor", "predicate_family": family, }, ) calls.append(anchor_mask) source_selector_call = _call( case_key=case_key, check_id=spec.check_id, tool="source_instance_selector", image_role="input", image_identity=image_identities["input"], queries=selector_identity_queries, depends_on=(input_target_mask.call_id, anchor_mask.call_id), params={ **dict(source_selector_parameters), "identity_mask_call_id": input_target_mask.call_id, "anchor_mask_call_id": anchor_mask.call_id, "lineage_policy": "raw_fused_mask_content_sha256_v1", }, ) calls.append(source_selector_call) region_resolvers_by_role: dict[str, ToolCallSpec] = {} zone_masks_by_role: dict[str, ToolCallSpec] = {} labeled_zone_ids: list[str] = [] labeled_zone_ocr: ToolCallSpec | None = None special_region_specs: list[dict[str, Any]] = [] if "region_resolution" in operation_kinds: region_calls_by_role: dict[str, list[ToolCallSpec]] = {} region_specs_by_role: dict[str, list[dict[str, Any]]] = {} regions_to_propose: list[dict[str, Any]] = [] for raw_region in predicate.get("regions", []): if not isinstance(raw_region, Mapping): continue region = dict(raw_region) region_id = str(region.get("region_id") or region.get("id") or "").strip() materializer = region.get("materializer") if isinstance(region.get("materializer"), Mapping) else {} if materializer.get("kind") == "input_target_mask_transfer": continue materializer_kind = str(materializer.get("kind") or "") if materializer_kind in {"input_ocr_color_zone", "ocr_container_layout"}: labeled_zone_ids.append(region_id) continue if materializer_kind == "registered_change_derivation": special_region_specs.append(region) continue if materializer_kind in { "anchor_relative_zone", "shelf_grid_parser", "planar_free_space_parser", "derived_free_space_zone", "architecture_region_parser", }: special_region_specs.append(region) # Special regions are derived from independently detected # support geometry. Give every support query its own region # ID so a union cannot silently confuse a shelf with a tray, # a robot with the ground, or an anchor with the moved item. roles = [str(item) for item in region.get("image_roles", []) if str(item) in {"input", "pred"}] roles = roles or ["pred"] for support_index, query in enumerate( canonical_detector_queries(materializer.get("queries", [])), 1 ): support_id = f"{region_id}__support_{support_index:02d}" regions_to_propose.append( { "region_id": support_id, "parent_materialized_region_id": region_id, "semantic_role": "materializer_support", "image_roles": roles, "source_image": "both" if set(roles) == {"input", "pred"} else roles[0], "proposal_method": "grounding_dino_box", "query_or_rule": query, "materializer": { "kind": "detector_segmenter", "queries": [query], "selection_policy": "top1_then_segment", }, "geometry_policy": "support_mask_required", } ) continue regions_to_propose.append(region) for region in regions_to_propose: region_id = str(region.get("region_id") or region.get("id") or "").strip() materializer = region.get("materializer") if isinstance(region.get("materializer"), Mapping) else {} materializer_kind = str(materializer.get("kind") or "") region_queries = canonical_detector_queries(materializer.get("queries", [])) roles = [str(item) for item in region.get("image_roles", []) if str(item)] if materializer_kind not in {"open_vocabulary_detector", "detector_segmenter"}: return [], [f"predicate_region_materializer_not_registered:{region_id or 'missing'}:{materializer_kind or 'missing'}"] if not region_id or not region_queries or not roles: return [], [f"predicate_region_not_materializable:{region_id or 'missing'}"] for role in roles: role_calls = [ _call( case_key=case_key, check_id=spec.check_id, tool="open_vocabulary_detector", image_role=role, image_identity=image_identities[role], queries=batch, region_ids=(region_id,), params={ "purpose": "region_proposal", "evidence_role": "zone_support_instance", "zone_kind": "spatial_constraint", "region_id": region_id, "proposal_method": region.get("proposal_method", "grounding_dino_box"), "selection_policy": materializer.get("selection_policy", "dino_first_top1_per_query"), "predicate_family": family, "semantic_role": region.get("semantic_role", ""), }, ) for batch in _chunks(region_queries, MAX_DETECTOR_QUERIES_PER_CALL) ] region_calls_by_role.setdefault(role, []).extend(role_calls) region_specs_by_role.setdefault(role, []).append(region) calls.extend(role_calls) for role, proposal_calls in sorted(region_calls_by_role.items()): specs = region_specs_by_role[role] # Both resolvers must advertise the same cross-role policy. The # region materializer first records the input reference and then # transfers it to ``pred`` only when both rows are marked stable. # Marking only the pred row silently prevented the reference from # ever being recorded. stable_cross_role = any( {"input", "pred"}.issubset(set(item.get("image_roles", []))) for item in specs ) resolver = _call( case_key=case_key, check_id=spec.check_id, tool="region_resolver", image_role=role, image_identity=image_identities[role], region_ids=tuple(dict.fromkeys(str(item["region_id"]) for item in specs)), depends_on=tuple(item.call_id for item in proposal_calls), params={ "regions": specs, "min_score": 0.15, "selection_policy": "dino_first_top1_per_query", "cross_role_policy": "stable_input_reference" if stable_cross_role else "independent", "max_candidates": 8, "nms_iou": 0.70, "min_area_fraction": 0.0005, "max_area_fraction": 0.90, "predicate_family": family, }, ) region_resolvers_by_role[role] = resolver calls.append(resolver) zone_mask = _call( case_key=case_key, check_id=spec.check_id, tool="zone_mask_refiner", image_role=role, image_identity=image_identities[role], region_ids=resolver.region_ids, depends_on=(resolver.call_id,), params={ "geometry_policy": "strict_sam_or_fastsam_mask_v1", "predicate_family": family, }, ) zone_masks_by_role[role] = zone_mask calls.append(zone_mask) if labeled_zone_ids: labeled_zone_ocr = _call( case_key=case_key, check_id=spec.check_id, tool="ocr", image_role="pred", image_identity=image_identities["pred"], region_ids=tuple(dict.fromkeys(labeled_zone_ids)), params={ "purpose": "ocr_container_layout_materialization", "ocr_scope": "full_frame", "materializer_backend": "ocr_container_layout_v1", "predicate_family": family, }, ) calls.append(labeled_zone_ocr) matcher = None if "instance_matching" in operation_kinds: input_mask = masks_by_role.get("input") pred_mask = masks_by_role.get("pred") if input_mask is None or pred_mask is None: return [], ["predicate_instance_matching_requires_input_and_pred_masks"] protected_subject_queries = [ str(value) for value in predicate.get("parameters", {}).get("protected_subject_queries", []) if str(value or "").strip() ] source_instance_annotations = list( predicate.get("parameters", {}).get("source_instance_annotations", []) ) roster_queries = [ str(item.get("query_text") or "") for item in source_instance_annotations if isinstance(item, Mapping) and str(item.get("query_text") or "").strip() ] target_subject_queries = list(dict.fromkeys(roster_queries or ( str(value) for subject in predicate.get("subjects", []) if isinstance(subject, Mapping) and str(subject.get("id") or "") != "protected_subjects" for value in ( subject.get("output_queries") or subject.get("aliases") or [subject.get("identity_query")] ) if str(value or "").strip() ))) matcher = _call( case_key=case_key, check_id=spec.check_id, tool="instance_matcher", image_role="input_pred", image_identity=image_identities["input_pred"], queries=identity_queries, depends_on=(input_mask.call_id, pred_mask.call_id), params={ "minimum_confidence": float( predicate.get("parameters", {}).get("minimum_match_confidence", 0.55) ), "ambiguity_margin": 0.04, "minimum_detector_score": float( predicate.get("parameters", {}).get("minimum_detection_confidence", 0.15) ), "spatial_consistency": family == "fixed_location_instance_preservation" or "fixed_location_entity_preservation" in semantic_families, "spatial_weight": 0.30 if family == "fixed_location_instance_preservation" or "fixed_location_entity_preservation" in semantic_families else 0.0, "required_matching_features": list( predicate.get("parameters", {}).get("required_matching_features", []) ), "mask_shape_weight": ( 0.10 if "mask shape" in { str(value).strip().lower() for value in predicate.get("parameters", {}).get("required_matching_features", []) } else 0.0 ), "source_instance_annotations": source_instance_annotations, **( { "source_annotation_mask_profile": str( predicate.get("parameters", {}).get("source_annotation_mask_profile") or "fastsam_bbox_prompt_or_color_component_v2" ) } if source_instance_annotations else {} ), "classification_labels": list( predicate.get("parameters", {}).get("matching_classification_labels", []) ), # A matcher may depend on masks for both the target inventory # and protected context subjects. Keep those semantic roles # explicit so the executor never forces a bear/robot/moose # crop into the target closed set. "target_subject_queries": target_subject_queries, "protected_subject_queries": protected_subject_queries, **( { "protected_subject_source_annotations": list( predicate.get("parameters", {}).get( "protected_subject_source_annotations", [] ) ), "protected_subject_source_mask_profile": str( predicate.get("parameters", {}).get( "protected_subject_source_mask_profile" ) or "" ), "protected_subject_minimum_identity_confidence": float( predicate.get("parameters", {}).get( "protected_subject_minimum_identity_confidence", 0.45 ) ), "protected_classification_minimum_margin": float( predicate.get("parameters", {}).get( "protected_classification_minimum_margin", 0.0 ) ), "protected_classification_minimum_probability": float( predicate.get("parameters", {}).get( "protected_classification_minimum_probability", 0.25 ) ), } if protected_subject_queries else {} ), "use_segmenter_proposals": bool( predicate.get("parameters", {}).get("matching_use_segmenter_proposals", False) ), "segmenter_min_area_fraction": float( predicate.get("parameters", {}).get("matching_segmenter_min_area_fraction", 0.00003) ), "segmenter_max_area_fraction": float( predicate.get("parameters", {}).get("matching_segmenter_max_area_fraction", 0.08) ), "segmenter_max_proposals": int( predicate.get("parameters", {}).get("matching_segmenter_max_proposals", 128) ), "classification_minimum_margin": float( predicate.get("parameters", {}).get("matching_classification_minimum_margin", 0.06) ), "classification_minimum_probability": float( predicate.get("parameters", {}).get("matching_classification_minimum_probability", 0.25) ), "localized_source_residual_enabled": bool( predicate.get("parameters", {}).get("localized_source_residual_enabled", False) ), "localized_source_residual_minimum_correlation": float( predicate.get("parameters", {}).get("localized_source_residual_minimum_correlation", 0.85) ), "localized_source_residual_maximum_mean_absolute_error": float( predicate.get("parameters", {}).get("localized_source_residual_maximum_mean_absolute_error", 0.10) ), "verified_roster_profile": str( predicate.get("parameters", {}).get("verified_roster_profile") or "" ), "verified_roster_assignment_mode": str( predicate.get("parameters", {}).get("verified_roster_assignment_mode") or "identity_exact" ), "verified_roster_expected_counts": dict( predicate.get("parameters", {}).get("verified_roster_expected_counts", {}) ), "verified_roster_minimum_area_ratio": float( predicate.get("parameters", {}).get("verified_roster_minimum_area_ratio", 0.10) ), "verified_roster_maximum_area_ratio": float( predicate.get("parameters", {}).get("verified_roster_maximum_area_ratio", 6.0) ), **( { "identity_agnostic_target_coverage_profile": str( predicate.get("parameters", {}).get( "identity_agnostic_target_coverage_profile" ) ), "target_coverage_minimum_probability": float( predicate.get("parameters", {}).get( "target_coverage_minimum_probability", 0.50 ) ), "target_coverage_minimum_margin": float( predicate.get("parameters", {}).get( "target_coverage_minimum_margin", 0.15 ) ), "target_coverage_minimum_animal_probability": float( predicate.get("parameters", {}).get( "target_coverage_minimum_animal_probability", 0.75 ) ), "target_coverage_minimum_animal_margin": float( predicate.get("parameters", {}).get( "target_coverage_minimum_animal_margin", 0.50 ) ), "target_coverage_maximum_protected_overlap": float( predicate.get("parameters", {}).get( "target_coverage_maximum_protected_overlap", 0.10 ) ), "target_coverage_neighborhood_fraction_of_diagonal": float( predicate.get("parameters", {}).get( "target_coverage_neighborhood_fraction_of_diagonal", 0.08 ) ), } if predicate.get("parameters", {}).get( "identity_agnostic_target_coverage_profile" ) else {} ), "algorithm": "hungarian_clip_colour_shape_maskshape_semantic_spatial_group_roster_v5", "predicate_family": family, }, ) calls.append(matcher) classifier = None if "crop_classification" in operation_kinds: pred_mask = masks_by_role.get("pred") if pred_mask is None: return [], ["predicate_crop_classification_requires_pred_masks"] classifier = _call( case_key=case_key, check_id=spec.check_id, tool="instance_classifier", image_role="pred", image_identity=image_identities["pred"], queries=identity_queries, depends_on=(pred_mask.call_id,), params={ "labels": list(predicate.get("parameters", {}).get("classification_labels", [])), "minimum_margin": float( predicate.get("parameters", {}).get("classification_minimum_margin", 0.02) ), "minimum_probability": float( predicate.get("parameters", {}).get("classification_minimum_probability", 0.25) ), "minimum_detector_score": float( predicate.get("parameters", {}).get( "classification_proposal_minimum_score", predicate.get("parameters", {}).get("minimum_detection_confidence", 0.15), ) ), "use_segmenter_proposals": bool( predicate.get("parameters", {}).get("classification_use_segmenter_proposals", False) ), "proposal_zone_ids": list( predicate.get("parameters", {}).get("classification_proposal_zone_ids", []) ), "segmenter_min_area_fraction": float( predicate.get("parameters", {}).get("classification_segmenter_min_area_fraction", 0.00005) ), "segmenter_max_area_fraction": float( predicate.get("parameters", {}).get("classification_segmenter_max_area_fraction", 0.08) ), "segmenter_max_proposals": int( predicate.get("parameters", {}).get("classification_segmenter_max_proposals", 128) ), "algorithm": "clip_closed_set_crop_classifier_v1", "predicate_family": family, }, ) calls.append(classifier) registration = None if "image_registration" in operation_kinds: registration = _call( case_key=case_key, check_id=spec.check_id, tool="image_registration", image_role="input_pred", image_identity=image_identities["input_pred"], params={ "registration_method": predicate.get("parameters", {}).get( "registration_method", "robust_static_background_alignment" ), "registration_tolerance_pixels": int( predicate.get("parameters", {}).get("registration_tolerance_pixels", 0) ), "predicate_family": family, }, ) calls.append(registration) parser_calls: list[ToolCallSpec] = [] if "change_analysis" in operation_kinds: change = _call( case_key=case_key, check_id=spec.check_id, tool="change_analysis", image_role="input_pred", image_identity=image_identities["input_pred"], region_ids=tuple( str(item.get("region_id") or "") for item in predicate.get("regions", []) if isinstance(item, Mapping) and str(item.get("region_id") or "") ), depends_on=tuple(dict.fromkeys( ([registration.call_id] if registration is not None else []) + [item.call_id for item in region_resolvers_by_role.values()] + [item.call_id for item in zone_masks_by_role.values()] )), params={ "predicate_family": family, "target_families": sorted(semantic_families), "region_specs": list(predicate.get("regions", [])), "rule_parameters": dict(predicate.get("parameters", {})), }, ) calls.append(change) parser_calls.append(change) def single_image_roles(operation_kind: str) -> set[str]: """Return only roles accepted by the single-image CV executors.""" return { str(role) for operation in operations if str(operation.get("kind") or "") == operation_kind for role in operation.get("image_roles", []) if str(role) in {"input", "pred"} } if "state_parsing" in operation_kinds or special_region_specs: state_roles = single_image_roles("state_parsing") state_roles.update( str(role) for region in special_region_specs for role in region.get("image_roles", []) if str(role) in {"input", "pred"} ) # A special output materializer from an older typed predicate may not # carry image_roles. Preserve the historical output-first default, # but never send a paired role to a single-image parser. if not state_roles: state_roles.add("pred") for role in sorted(state_roles): role_regions = [ item for item in predicate.get("regions", []) if isinstance(item, Mapping) and ( not item.get("image_roles") or role in {str(value) for value in item.get("image_roles", [])} ) ] role_special_regions = [ item for item in special_region_specs if not item.get("image_roles") or role in {str(value) for value in item.get("image_roles", [])} ] state_dependencies = [] if role in region_resolvers_by_role: state_dependencies.append(region_resolvers_by_role[role].call_id) if registration is not None: state_dependencies.append(registration.call_id) state = _call( case_key=case_key, check_id=spec.check_id, tool="state_parser", image_role=role, image_identity=image_identities[role], region_ids=tuple( str(item.get("region_id") or "") for item in role_regions if str(item.get("region_id") or "") ), depends_on=tuple(dict.fromkeys(state_dependencies)), params={ "parser_mode": "typed_contract_materializers_v1", "predicate_family": family, "target_families": sorted(semantic_families), "region_specs": role_special_regions, "rule_parameters": dict(predicate.get("parameters", {})), "obligation_bindings": list(predicate.get("parameter_bindings", [])), }, ) calls.append(state) parser_calls.append(state) if "visual_attribute" in operation_kinds: attribute_roles = single_image_roles("visual_attribute") or {"pred"} for role in sorted(attribute_roles): mask = masks_by_role.get(role) attribute = _call( case_key=case_key, check_id=spec.check_id, tool="visual_attribute_parser", image_role=role, image_identity=image_identities[role], queries=subject_queries(role), depends_on=(mask.call_id,) if mask is not None else (), params={ "parser_mode": "typed_contract_attributes_v1", "predicate_family": family, "target_families": sorted(semantic_families), "rule_parameters": dict(predicate.get("parameters", {})), "obligation_bindings": list(predicate.get("parameter_bindings", [])), }, ) calls.append(attribute) parser_calls.append(attribute) if "pose_estimation" in operation_kinds: pose_roles = single_image_roles("pose_estimation") or {"input", "pred"} pose_profile = str(predicate.get("parameters", {}).get("pose_profile") or "") try: pose_parameters = human_pose_profile_parameters(pose_profile) except ValueError: return [], ["pose_estimation_requires_registered_pose_profile"] for role in sorted(pose_roles): detector_dependencies = tuple( item.call_id for item in detectors_by_role.get(role, []) ) pose = _call( case_key=case_key, check_id=spec.check_id, tool="human_pose_parser", image_role=role, image_identity=image_identities[role], queries=subject_queries(role), depends_on=detector_dependencies, params={ "parser_mode": "coco17_human_pose_v1", "predicate_family": family, "rule_parameters": dict(predicate.get("parameters", {})), **pose_parameters, }, ) calls.append(pose) parser_calls.append(pose) if "local_correspondence" in operation_kinds: if matcher is None or registration is None: return [], ["local_correspondence_requires_matcher_and_registration"] local_profile = str( predicate.get("parameters", {}).get("local_correspondence_profile") or "" ) try: local_parameters = local_correspondence_profile_parameters(local_profile) except ValueError: return [], ["local_correspondence_requires_registered_profile"] local = _call( case_key=case_key, check_id=spec.check_id, tool="local_correspondence", image_role="input_pred", image_identity=image_identities["input_pred"], queries=identity_queries, depends_on=(matcher.call_id, registration.call_id), params={ "parser_mode": "sift_mutual_ransac_affine_v1", "predicate_family": family, "rule_parameters": dict(predicate.get("parameters", {})), **local_parameters, }, ) calls.append(local) parser_calls.append(local) dependencies = [*masks_by_role.values()] if source_selector_call is not None: dependencies.append(source_selector_call) if matcher is not None: dependencies.append(matcher) if classifier is not None: dependencies.append(classifier) if registration is not None: dependencies.append(registration) dependencies.extend(detectors_by_role.get("pred", [])) dependencies.extend(region_resolvers_by_role.values()) dependencies.extend(zone_masks_by_role.values()) if labeled_zone_ocr is not None: dependencies.append(labeled_zone_ocr) dependencies.extend(parser_calls) source_rule_type = str(predicate.get("source_rule_type") or "") reviewed_predicate = bool( family in { "fixed_location_entity_preservation", "registered_invariant_region_preservation", "relocated_entity_integrity", "destination_membership", "registered_structural_state", "group_pose_arrangement", "contract_family_all_of", } and predicate.get("capability_versions") ) metric = _call( case_key=case_key, check_id=spec.check_id, tool="contract_metric_binding", image_role="input_pred", image_identity=image_identities["input_pred"], queries=identity_queries, depends_on=tuple(dict.fromkeys(item.call_id for item in dependencies)), params={ # Reviewed contracts retain their exact source rule because their # typed clauses, rather than a legacy canonical alias, define the # executable semantics. Legacy bridges continue to use the # canonical registry key. "metric_binding": ( source_rule_type if reviewed_predicate else canonical_rule_type(source_rule_type) ), "source_rule_type": source_rule_type, "executable_predicate": dict(predicate), "negative_evidence_policy": "fail_closed_unknown", "rule_parameters": dict(predicate.get("parameters", {})), }, ) calls.append(metric) return calls, [] def _calls_for_program( case_key: str, spec: AtomicCheckSpec, program: EvidenceProgram, image_identities: dict[str, str], *, authoritative_lowering: bool = True, ) -> tuple[list[ToolCallSpec], list[str]]: """Lower one semantic evidence program into physical tool calls.""" predicate = ( program.checker_params.get("executable_predicate") if isinstance(program.checker_params.get("executable_predicate"), Mapping) else None ) if program.checker_params.get("require_executable_predicate") and authoritative_lowering: if predicate is None: return [], ["missing_executable_predicate"] return _calls_for_executable_predicate(case_key, spec, predicate, image_identities, program) compiled_spec = replace(spec, params=program.checker_params) queries = list(detector_queries_for_check(compiled_spec)) regions = tuple(item.region_id for item in program.regions) requirements = [item for item in program.requirements if not item.optional and item.status == "supported"] operations = {item.operation for item in requirements} roles_by_operation: dict[str, set[str]] = {} for requirement in requirements: roles_by_operation.setdefault(requirement.operation, set()).update(requirement.image_roles) calls: list[ToolCallSpec] = [] reasons: list[str] = [] call_params = dict(program.checker_params) detector_by_role: dict[str, list[ToolCallSpec]] = {} target_detector_by_role: dict[str, list[ToolCallSpec]] = {} masks_by_role: dict[str, ToolCallSpec] = {} parser_calls_by_operation: dict[str, list[ToolCallSpec]] = {} checker_semantics = " ".join( [ str(spec.checker), str(program.checker_params.get("evidence_type", "")), str((program.checker_params.get("decision_rule") or {}).get("type", "")) if isinstance(program.checker_params.get("decision_rule"), dict) else "", ] ).lower() decision_rule = call_params.get("decision_rule") if isinstance(call_params.get("decision_rule"), dict) else {} source_rule_type = str(decision_rule.get("type") or "") rule_type = canonical_rule_type(source_rule_type) # A reviewed referring expression can be valuable for localization but # too brittle for exhaustive absence search (for example, "small bird # perched on the robot's left shoulder"). When a source-vacancy contract # also supplies one short object identity, keep that identity as an # additional detector query. The support/location expression remains in # the named-region stream and must not be the only way to find the target. if rule_type == "source_zone_vacancy": short_object_queries = canonical_detector_queries( query for value in _values(call_params, "object") for query in expand_detector_query(value) if 0 < len(re.findall(r"[a-z0-9]+", query.lower())) <= 3 ) queries = list(dict.fromkeys((*short_object_queries, *queries))) stable_cross_role_regions = any( token in checker_semantics for token in ("preservation", "integrity", "invariant") ) or rule_type in {"desk_clutter_residual_count"} stable_instance_locations = any( token in checker_semantics for token in ("preservation", "integrity", "invariant") ) target_evidence_role = "invariant_instance" if stable_instance_locations else "target_instance" # Runtime availability is parameter-sensitive. A generic parser binary # existing on disk is not enough to call a check executable when the # contract omits the schema that parser actually consumes. unmaterialized_regions = [ item.region_id for item in program.regions if item.status == "auto_resolvable" and item.resolver_operation != "object_detection" ] if unmaterialized_regions: reasons.append("region_backend_has_no_named_zone_materializer:" + ",".join(unmaterialized_regions)) if "visual_attribute" in operations and not _explicit_colors(call_params): reasons.append("visual_attribute_parser_requires_explicit_supported_color") if "route_extraction" in operations and not _explicit_colors(call_params): reasons.append("route_parser_requires_explicit_route_color_or_typed_model") if "state_parsing" in operations and not _has_structured_cells(call_params): reasons.append("state_parser_requires_explicit_cells_with_geometry_and_color") detector_requirements = [ item for item in requirements if item.operation == "object_detection" and item.source != "planned_regions" ] detector_queries = canonical_detector_queries(queries) detector_roles = {role for item in detector_requirements for role in item.image_roles} if detector_roles and not detector_queries: reasons.append("detector_checker_has_no_check_scoped_queries") for role in sorted(detector_roles): detector_calls = [ _call( case_key=case_key, check_id=spec.check_id, tool="open_vocabulary_detector", image_role=role, image_identity=image_identities[role], queries=query_batch, params={"evidence_role": target_evidence_role, "purpose": "target_detection"}, ) for query_batch in _chunks(detector_queries, MAX_DETECTOR_QUERIES_PER_CALL) ] detector_by_role[role] = detector_calls target_detector_by_role[role] = list(detector_calls) calls.extend(detector_calls) # Region proposals are separate typed calls so their detections can be # materialized back into named checker zones instead of being confused # with the target-object detections for the same question. region_proposals_by_role: dict[str, list[ToolCallSpec]] = {} region_specs_by_role: dict[str, list[Any]] = {} region_resolvers_by_role: dict[str, ToolCallSpec] = {} spatial_region_ids_by_role: dict[str, list[str]] = {} for region in program.regions: if region.status != "auto_resolvable" or region.resolver_operation != "object_detection": continue for role in region.image_roles: region_query = region_detector_queries(region.query_or_rule, region.region_id) if not region_query: # Inventory/source regions name a set of target instances, not # a new scene surface. Reuse the check-scoped object queries # and materialize their union instead of inventing a generic # detector prompt such as "inventory". if any(token in region.region_id.lower() for token in ("inventory", "sources", "instances")): region_query = detector_queries if not region_query: reasons.append(f"region_proposal_has_no_detector_query:{region.region_id}") continue if role == "pred" and any(_same_concept(region_query[0], query) for query in detector_queries): reasons.append(f"region_query_not_independent_of_target_object:{region.region_id}") zone_kind = _region_zone_kind(region.region_id, region_query, detector_queries, rule_type) if zone_kind == "spatial_constraint": spatial_region_ids_by_role.setdefault(role, []).append(region.region_id) region_calls = [ _call( case_key=case_key, check_id=spec.check_id, tool="open_vocabulary_detector", image_role=role, image_identity=image_identities[role], queries=query_batch, region_ids=(region.region_id,), params={ "purpose": "region_proposal", "evidence_role": "zone_support_instance", "zone_kind": zone_kind, "region_id": region.region_id, "proposal_method": region.proposal_method, "selection_policy": "dino_first_top1_per_query", }, ) for query_batch in _chunks(region_query, MAX_DETECTOR_QUERIES_PER_CALL) ] detector_by_role.setdefault(role, []).extend(region_calls) region_proposals_by_role.setdefault(role, []).extend(region_calls) region_specs_by_role.setdefault(role, []).append(region) calls.extend(region_calls) # Materialization has its own terminal status. A successful detector call # with zero boxes is valid negative detector evidence, but not a usable # checker zone. for role, proposal_calls in sorted(region_proposals_by_role.items()): resolver_call = _call( case_key=case_key, check_id=spec.check_id, tool="region_resolver", image_role=role, image_identity=image_identities[role], region_ids=tuple(item.region_id for item in region_specs_by_role[role]), depends_on=tuple(item.call_id for item in proposal_calls), params={ "regions": [item.to_dict() for item in region_specs_by_role[role]], "min_score": float(program.checker_params.get("region_min_score", 0.15)), "selection_policy": "dino_first_top1_per_query", "cross_role_policy": "stable_input_reference" if stable_cross_role_regions else "independent", "max_candidates": int(program.checker_params.get("region_max_candidates", 6)), "nms_iou": float(program.checker_params.get("region_nms_iou", 0.70)), "min_area_fraction": float(program.checker_params.get("region_min_area_fraction", 0.0005)), "max_area_fraction": float(program.checker_params.get("region_max_area_fraction", 0.90)), }, ) region_resolvers_by_role[role] = resolver_call calls.append(resolver_call) # A detector box only prompts the zone segmenter; it is not itself valid # containment geometry. Make this refinement an explicit physical call # so its success/failure and provenance are represented in the execution # ledger rather than appearing as anonymous derived evidence. zone_masks_by_role: dict[str, ToolCallSpec] = {} for role, region_ids_for_role in sorted(spatial_region_ids_by_role.items()): resolver = region_resolvers_by_role.get(role) if resolver is None: reasons.append(f"zone_mask_refinement_has_no_region_dependency:{role}") continue zone_mask_call = _call( case_key=case_key, check_id=spec.check_id, tool="zone_mask_refiner", image_role=role, image_identity=image_identities[role], region_ids=tuple(dict.fromkeys(region_ids_for_role)), depends_on=(resolver.call_id,), params={"geometry_policy": "strict_sam_or_fastsam_mask_v1"}, ) zone_masks_by_role[role] = zone_mask_call calls.append(zone_mask_call) for role in sorted(roles_by_operation.get("mask_refinement", set())): # Region-proposal detections must never become target instances. The # region resolver consumes those calls separately; mask refinement is # seeded only by the check's target-object detector calls. dependencies = target_detector_by_role.get(role, []) if not dependencies: reasons.append(f"mask_refinement_has_no_detector_dependency:{role}") continue mask_call = _call( case_key=case_key, check_id=spec.check_id, tool="mask_refiner", image_role=role, image_identity=image_identities[role], queries=detector_queries, region_ids=regions, depends_on=tuple(item.call_id for item in dependencies), params={"detection_scope": "dependency_call_ids_v1"}, ) masks_by_role[role] = mask_call calls.append(mask_call) matcher_call = None if "instance_matching" in operations: input_mask = masks_by_role.get("input") pred_mask = masks_by_role.get("pred") if input_mask is None or pred_mask is None: reasons.append("instance_matching_requires_input_and_pred_masks") else: predicate_parameters = ( predicate.get("parameters", {}) if isinstance(predicate, Mapping) and isinstance(predicate.get("parameters"), Mapping) else {} ) protected_subject_queries = [ str(value) for value in predicate_parameters.get("protected_subject_queries", []) if str(value or "").strip() ] source_instance_annotations = list( predicate_parameters.get("source_instance_annotations", []) ) roster_queries = [ str(item.get("query_text") or "") for item in source_instance_annotations if isinstance(item, Mapping) and str(item.get("query_text") or "").strip() ] target_subject_queries = list(dict.fromkeys(roster_queries or ( str(value) for subject in (predicate.get("subjects", []) if isinstance(predicate, Mapping) else []) if isinstance(subject, Mapping) and str(subject.get("id") or "") != "protected_subjects" for value in ( subject.get("output_queries") or subject.get("aliases") or [subject.get("identity_query")] ) if str(value or "").strip() ))) matcher_call = _call( case_key=case_key, check_id=spec.check_id, tool="instance_matcher", image_role="input_pred", image_identity=image_identities["input_pred"], queries=detector_queries, depends_on=(input_mask.call_id, pred_mask.call_id), params={ "minimum_confidence": float( predicate_parameters.get( "minimum_match_confidence", call_params.get("min_match_confidence", call_params.get("minimum_match_confidence", 0.55)), ) ), "ambiguity_margin": float(call_params.get("match_ambiguity_margin", 0.04)), "minimum_detector_score": float( predicate_parameters.get( "minimum_detector_confidence", predicate_parameters.get( "minimum_detection_confidence", call_params.get("minimum_detector_score", 0.15), ), ) ), "spatial_consistency": stable_instance_locations, "spatial_weight": float(call_params.get("match_spatial_weight", 0.30 if stable_instance_locations else 0.0)), "required_matching_features": list( predicate_parameters.get("required_matching_features", []) ), "mask_shape_weight": ( 0.10 if "mask shape" in { str(value).strip().lower() for value in predicate_parameters.get("required_matching_features", []) } else 0.0 ), "source_instance_annotations": source_instance_annotations, **( { "source_annotation_mask_profile": str( predicate_parameters.get("source_annotation_mask_profile") or "fastsam_bbox_prompt_or_color_component_v2" ) } if source_instance_annotations else {} ), "classification_labels": list( predicate_parameters.get("matching_classification_labels", []) ), "target_subject_queries": target_subject_queries, "protected_subject_queries": protected_subject_queries, **( { "protected_subject_source_annotations": list( predicate_parameters.get( "protected_subject_source_annotations", [] ) ), "protected_subject_source_mask_profile": str( predicate_parameters.get( "protected_subject_source_mask_profile" ) or "" ), "protected_subject_minimum_identity_confidence": float( predicate_parameters.get( "protected_subject_minimum_identity_confidence", 0.45 ) ), "protected_classification_minimum_margin": float( predicate_parameters.get( "protected_classification_minimum_margin", 0.0 ) ), "protected_classification_minimum_probability": float( predicate_parameters.get( "protected_classification_minimum_probability", 0.25 ) ), } if protected_subject_queries else {} ), "use_segmenter_proposals": bool( predicate_parameters.get("matching_use_segmenter_proposals", False) ), "segmenter_min_area_fraction": float( predicate_parameters.get("matching_segmenter_min_area_fraction", 0.00003) ), "segmenter_max_area_fraction": float( predicate_parameters.get("matching_segmenter_max_area_fraction", 0.08) ), "segmenter_max_proposals": int( predicate_parameters.get("matching_segmenter_max_proposals", 128) ), "classification_minimum_margin": float( predicate_parameters.get("matching_classification_minimum_margin", 0.06) ), "classification_minimum_probability": float( predicate_parameters.get("matching_classification_minimum_probability", 0.25) ), "localized_source_residual_enabled": bool( predicate_parameters.get("localized_source_residual_enabled", False) ), "localized_source_residual_minimum_correlation": float( predicate_parameters.get("localized_source_residual_minimum_correlation", 0.85) ), "localized_source_residual_maximum_mean_absolute_error": float( predicate_parameters.get("localized_source_residual_maximum_mean_absolute_error", 0.10) ), "verified_roster_profile": str( predicate_parameters.get("verified_roster_profile") or "" ), "verified_roster_assignment_mode": str( predicate_parameters.get("verified_roster_assignment_mode") or "identity_exact" ), "verified_roster_expected_counts": dict( predicate_parameters.get("verified_roster_expected_counts", {}) ), "verified_roster_minimum_area_ratio": float( predicate_parameters.get("verified_roster_minimum_area_ratio", 0.10) ), "verified_roster_maximum_area_ratio": float( predicate_parameters.get("verified_roster_maximum_area_ratio", 6.0) ), **( { "identity_agnostic_target_coverage_profile": str( predicate_parameters.get( "identity_agnostic_target_coverage_profile" ) ), "target_coverage_minimum_probability": float( predicate_parameters.get( "target_coverage_minimum_probability", 0.50 ) ), "target_coverage_minimum_margin": float( predicate_parameters.get( "target_coverage_minimum_margin", 0.15 ) ), "target_coverage_minimum_animal_probability": float( predicate_parameters.get( "target_coverage_minimum_animal_probability", 0.75 ) ), "target_coverage_minimum_animal_margin": float( predicate_parameters.get( "target_coverage_minimum_animal_margin", 0.50 ) ), "target_coverage_maximum_protected_overlap": float( predicate_parameters.get( "target_coverage_maximum_protected_overlap", 0.10 ) ), "target_coverage_neighborhood_fraction_of_diagonal": float( predicate_parameters.get( "target_coverage_neighborhood_fraction_of_diagonal", 0.08 ) ), } if predicate_parameters.get( "identity_agnostic_target_coverage_profile" ) else {} ), "algorithm": "hungarian_clip_colour_shape_maskshape_semantic_spatial_group_roster_v5", }, ) calls.append(matcher_call) registration = None if "image_registration" in operations: registration = _call( case_key=case_key, check_id=spec.check_id, tool="image_registration", image_role="input_pred", image_identity=image_identities["input_pred"], region_ids=regions, params=call_params, ) calls.append(registration) if "change_analysis" in operations: if registration is None: reasons.append("change_analysis_has_no_registration_dependency") calls.append( _call( case_key=case_key, check_id=spec.check_id, tool="change_analysis", image_role="input_pred", image_identity=image_identities["input_pred"], region_ids=regions, depends_on=tuple( dict.fromkeys( [ *([registration.call_id] if registration else []), *(item.call_id for _, item in sorted(region_resolvers_by_role.items())), ] ) ), params=call_params, ) ) tool_by_operation = { "ocr": "ocr", "route_extraction": "route_parser", "state_parsing": "state_parser", "visual_attribute": "visual_attribute_parser", "pose_estimation": "human_pose_parser", "local_correspondence": "local_correspondence", } for operation, tool in tool_by_operation.items(): for role in sorted(roles_by_operation.get(operation, set())): resolver = region_resolvers_by_role.get(role) parser_params = dict(call_params) if operation == "pose_estimation": rule_parameters = decision_rule.get("parameters") if isinstance(decision_rule.get("parameters"), Mapping) else {} try: parser_params.update(human_pose_profile_parameters(str(rule_parameters.get("pose_profile") or ""))) except ValueError: reasons.append("pose_estimation_requires_registered_pose_profile") continue if operation == "local_correspondence": rule_parameters = decision_rule.get("parameters") if isinstance(decision_rule.get("parameters"), Mapping) else {} try: parser_params.update( local_correspondence_profile_parameters( str(rule_parameters.get("local_correspondence_profile") or "") ) ) except ValueError: reasons.append("local_correspondence_requires_registered_profile") continue parser_dependencies = (resolver.call_id,) if resolver else () if operation == "local_correspondence": if matcher_call is None or registration is None: reasons.append("local_correspondence_requires_matcher_and_registration") continue parser_dependencies = (matcher_call.call_id, registration.call_id) parser_call = _call( case_key=case_key, check_id=spec.check_id, tool=tool, image_role=role, image_identity=image_identities[role], region_ids=regions, depends_on=parser_dependencies, params=parser_params, ) calls.append(parser_call) parser_calls_by_operation.setdefault(operation, []).append(parser_call) if "structured_check" in operations: # The structured checker is the terminal parser for one reviewed # atomic rule. It runs after every upstream evidence producer owned # by the check and consumes the merged observations plus raw images. # Keeping it as an explicit physical call makes parser failures and # insufficient evidence visible in the execution ledger. # The versioned adapter receives raw input/output images and the # already-merged observation document. It reports ``insufficient`` # itself when evidence it actually consumes is missing. Making every # exploratory OCR/detector call a hard dependency would incorrectly # suppress conclusive image-parser results. structured_dependencies: tuple[str, ...] = () calls.append( _call( case_key=case_key, check_id=spec.check_id, tool="structured_checker", image_role="input_pred", image_identity=image_identities["input_pred"], queries=detector_queries, region_ids=regions, depends_on=structured_dependencies, params={ **call_params, "structured_adapter": "pvr_structured_contract_v1", "source_rule_type": source_rule_type, }, ) ) if rule_type in REGISTERED_RULE_TYPES: # This is a terminal decision call, so it depends only on evidence the # registered metric handler actually reads. Unrelated parser calls # remain auditable but cannot invalidate a conclusive metric. capability = metric_capability(rule_type) metric_dependencies: list[ToolCallSpec] = [] operation_calls = { "instance_matching": [matcher_call] if matcher_call is not None else [], "mask_refinement": [item for _, item in sorted(masks_by_role.items())], "ocr": list(parser_calls_by_operation.get("ocr", [])), "image_registration": [registration] if registration is not None else [], } if capability is not None: for requirement in capability.evidence: if requirement.terminal_dependency: metric_dependencies.extend(operation_calls.get(requirement.operation, [])) for region_requirement in capability.regions: matching_regions = [ region for region in program.regions if (not region_requirement.image_role or region_requirement.image_role in region.image_roles) and any(token in region.region_id.lower() for token in region_requirement.tokens) ] if not matching_regions: static_zone_ids = ( tuple(str(zone_id) for zone_id in call_params.get("zones", {})) if isinstance(call_params.get("zones"), dict) else () ) if not any( token in zone_id.lower() for zone_id in static_zone_ids for token in region_requirement.tokens ): reasons.append( "metric_required_region_not_declared:" + "|".join(region_requirement.tokens) ) continue if any(region.status == "auto_resolvable" for region in matching_regions): resolver = region_resolvers_by_role.get(region_requirement.image_role) if resolver is not None: metric_dependencies.append(resolver) required_ids = {region.region_id for region in matching_regions} if required_ids & set(spatial_region_ids_by_role.get(region_requirement.image_role, [])): zone_mask = zone_masks_by_role.get(region_requirement.image_role) if zone_mask is not None: metric_dependencies.append(zone_mask) metric_dependency_ids = tuple(dict.fromkeys(item.call_id for item in metric_dependencies)) calls.append( _call( case_key=case_key, check_id=spec.check_id, tool="contract_metric_binding", image_role="input_pred", image_identity=image_identities["input_pred"], queries=detector_queries, region_ids=regions, depends_on=metric_dependency_ids, params={ "metric_binding": rule_type, "source_rule_type": source_rule_type, "rule_parameters": dict(decision_rule.get("parameters") or {}), "decision_conditions": { key: str(decision_rule.get(key) or "") for key in ("pass_condition", "partial_condition", "fail_condition") }, "enforce_contract_compliance": True, "zones": dict(call_params.get("zones") or {}) if isinstance(call_params.get("zones"), dict) else {}, "negative_evidence_policy": "fail_closed_unknown", "executable_predicate": dict(predicate) if predicate is not None else None, }, ) ) if not calls and program.executable: reasons.append("executable_program_has_no_external_tool_calls") return calls, reasons def build_case_tool_plan( contract: EvalContract, *, case_key: str, input_image_id: str | None = None, pred_image_id: str | None = None, ) -> dict[str, Any]: """Return one executable, cache-aware plan for a case.""" image_identities = { "input": input_image_id or f"{case_key}:input", "pred": pred_image_id or f"{case_key}:pred", } image_identities["input_pred"] = f"{image_identities['input']}|{image_identities['pred']}" physical: dict[str, ToolCallSpec] = {} check_plans: list[CheckToolPlan] = [] compiled_checks: dict[str, dict[str, Any]] = {} for spec in contract.atomic_checks: program = compile_evidence_program( spec, contract_zones=contract.zones, available_operations=RUNTIME_AVAILABLE_OPERATIONS, ) compiled_checks[spec.check_id] = { "params": program.checker_params, "evidence_program": program.to_dict(), } calls, reasons = _calls_for_program(case_key, spec, program, image_identities) call_ids = [] for call in calls: existing = physical.get(call.cache_key) if existing is None: physical[call.cache_key] = call existing = call elif spec.check_id not in existing.check_ids: physical[call.cache_key] = ToolCallSpec( **{**existing.__dict__, "check_ids": tuple((*existing.check_ids, spec.check_id))} ) existing = physical[call.cache_key] call_ids.append(existing.call_id) authoritative_predicate = ( program.checker_params.get("executable_predicate") if program.checker_params.get("require_executable_predicate") and isinstance(program.checker_params.get("executable_predicate"), Mapping) else None ) if authoritative_predicate is not None: families = tuple( dict.fromkeys( str(item.get("tool_family") or item.get("kind") or "") for item in authoritative_predicate.get("operations", []) if isinstance(item, Mapping) and (item.get("tool_family") or item.get("kind")) ) ) unknown = () else: families, unknown = _declared_tool_audit(spec) reasons.extend(program.reasons) if "resolved_plan_has_unresolved_facts" in reasons: reasons.append("resolved_plan_has_unresolved_fact") semantic_fact_requirements = ( list(authoritative_predicate.get("semantic_fact_requirements", []) or []) if authoritative_predicate is not None else [] ) requires_predicate = bool(program.checker_params.get("require_executable_predicate")) predicate_status = str((authoritative_predicate or {}).get("status") or "blocked_uncompiled") # An uncompiled predicate has no executable evidence path to hand to a # fallback model. Advertising ``vlm_audit`` here made strict-zero-VLM # plans look as if a blocked rule had a legitimate physical route. # Keep it blocked and empty; only an executable predicate with an # explicit semantic obligation may request the separately gated audit. if requires_predicate and predicate_status != "executable": fallback = "" elif semantic_fact_requirements: fallback = "vlm_audit" elif requires_predicate: fallback = "" else: fallback = str(program.checker_params.get("fallback_checker") or "") if semantic_fact_requirements: reasons.extend( "semantic_fact_requires_vlm:" + str(item.get("fact") or "missing") for item in semantic_fact_requirements if isinstance(item, Mapping) ) # A terminal metric may make a non-preservation check executable when # its own typed dependency contract is complete. Preservation rules # cannot discard unsupported appearance/integrity evidence merely # because a matcher-only terminal node exists. terminal_calls = [call for call in calls if call.tool == "contract_metric_binding"] terminal_rule = str(terminal_calls[0].params.get("metric_binding") or "") if terminal_calls else "" terminal_blockers = ( "metric_required_region_not_declared:", "mask_refinement_has_no_detector_dependency:", "instance_matching_requires_input_and_pred_masks", "resolved_plan_has_unresolved_fact", ) terminal_complete = bool( terminal_calls and terminal_rule not in PRESERVATION_RULE_TYPES and not any(str(reason).startswith(terminal_blockers) for reason in reasons) ) if semantic_fact_requirements and calls: # Objective producers still run first and their evidence is passed # into the semantic verifier. The check is deliberately not # advertised as fully objective while a reviewed prose obligation # lacks a deterministic fact producer. status = "fallback_required" elif terminal_complete or (program.executable and not reasons and calls): status = "executable" elif program.checker_params.get("require_executable_predicate"): predicate_status = str((authoritative_predicate or {}).get("status") or "blocked_uncompiled") status = ( predicate_status if predicate_status.startswith("blocked_") or predicate_status == "manual_review_required" else "blocked_uncompiled" ) else: status = "fallback_required" check_plans.append( CheckToolPlan( check_id=spec.check_id, checker=spec.checker, tool_call_ids=tuple(dict.fromkeys(call_ids)), fallback=fallback, status=status, reasons=tuple(dict.fromkeys(reasons)), declared_tool_families=families, unrecognized_declared_tools=unknown, evidence_program=program.to_dict(), ) ) calls = sorted(physical.values(), key=lambda item: (item.tool, item.image_role, item.call_id)) return { "schema_version": TOOL_PLAN_SCHEMA_VERSION, "case_key": case_key, "case_id": contract.case_id, "check_plans": [item.to_dict() for item in check_plans], "compiled_checks": compiled_checks, "tool_calls": [item.to_dict() for item in calls], "summary": { "atomic_checks": len(check_plans), "executable_checks": sum(item.status == "executable" for item in check_plans), "fallback_required_checks": sum(item.status != "executable" for item in check_plans), "manual_review_required_checks": sum(item.status == "manual_review_required" for item in check_plans), "blocked_uncompiled_checks": sum(item.status.startswith("blocked_") for item in check_plans), "physical_tool_calls": len(calls), "detector_calls": sum(item.tool == "open_vocabulary_detector" for item in calls), "max_detector_queries_per_call": max((len(item.queries) for item in calls if item.tool == "open_vocabulary_detector"), default=0), }, }
"""Compile atomic PVR checks into typed, cacheable tool calls.
The evidence planner emits rich human-readable plans. Those plans are useful
for auditing, but their free-form ``tool_sequence`` entries are not an
executable API. This module is the strict bridge between a resolved contract
and runtime tools:
* every call is owned by one or more atomic ``check_id`` values;
* detector prompts are scoped to one check, never unioned across a case;
* identical physical calls may be cached without losing check provenance;
* unsupported checker/tool requirements are explicit and route to fallback.
"""
from __future__ import annotations
import hashlib
import json
import re
from dataclasses import dataclass, field, replace
from typing import Any, Iterable, Mapping
from pvr_eval.core.schema import AtomicCheckSpec, EvalContract
from pvr_eval.agent.contract_metric_binding import (
PRESERVATION_RULE_TYPES,
REGISTERED_RULE_TYPES,
canonical_rule_type,
metric_capability,
)
from pvr_eval.agent.detector_fusion import semantic_class
from pvr_eval.agent.evidence_program import DEFAULT_AVAILABLE_OPERATIONS, EvidenceProgram, compile_evidence_program
from pvr_eval.agent.executable_predicate import validate_executable_predicate
from pvr_eval.contracts.metric_profiles import (
human_pose_profile_parameters,
local_correspondence_profile_parameters,
)
from pvr_eval.contracts.region_materializer_registry import executable_region_materializer
TOOL_PLAN_SCHEMA_VERSION = "pvr.agent_tool_plan.v2"
MAX_DETECTOR_QUERIES_PER_CALL = 8
# Operations with a real executor or a fixed checker implementation in this
# runtime. Text alignment/quality remain excluded: current OCR checkers do not
# actually compare input/output strings or emit calibrated legibility metrics.
RUNTIME_AVAILABLE_OPERATIONS = frozenset(DEFAULT_AVAILABLE_OPERATIONS - {"text_alignment", "text_quality"})
_SUPPORTED_EXPLICIT_COLORS = frozenset(
{"red", "orange", "yellow", "green", "cyan", "blue", "purple", "pink", "black", "white", "gray", "grey", "brown"}
)
@dataclass(frozen=True)
class ToolCallSpec:
"""One physical tool invocation that may serve several atomic checks."""
call_id: str
cache_key: str
tool: str
case_key: str
image_role: str
image_identity: str
check_ids: tuple[str, ...]
queries: tuple[str, ...] = ()
region_ids: tuple[str, ...] = ()
depends_on: tuple[str, ...] = ()
params: dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> dict[str, Any]:
return {
"call_id": self.call_id,
"cache_key": self.cache_key,
"tool": self.tool,
"case_key": self.case_key,
"image_role": self.image_role,
"image_identity": self.image_identity,
"check_ids": list(self.check_ids),
"queries": list(self.queries),
"region_ids": list(self.region_ids),
"depends_on": list(self.depends_on),
"params": self.params,
}
@dataclass(frozen=True)
class CheckToolPlan:
check_id: str
checker: str
tool_call_ids: tuple[str, ...]
fallback: str
status: str
reasons: tuple[str, ...] = ()
declared_tool_families: tuple[str, ...] = ()
unrecognized_declared_tools: tuple[str, ...] = ()
evidence_program: dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> dict[str, Any]:
return {
"check_id": self.check_id,
"checker": self.checker,
"tool_call_ids": list(self.tool_call_ids),
"fallback": self.fallback,