"""Additive task geometry precheck (Python >= 3.9; active geometry needs Shapely >= 2). Public API: evaluate_task(manifest: dict, task: dict | None) -> dict. None or {} means not_requested, with passed=False and no diagnostics. For an active request, manifest['entities'] is a list of records with unique, nonempty string entity_id values. No entity bounding boxes, roles, room bounds, or proxy dimensions are used as usable-surface or workspace evidence. Task contract (all distances in metres): { "support_entity_ids": ["table"], "target_dimensions_m": [0.4, 0.3, 0.2], "support_height_range_m": [0.5, 0.95], # optional, inclusive "minimum_approach_width_m": 0.8, # optional, nonnegative "measured_supports": [{ "entity_id": "table", "surface": { "xy_m": [0.0, 0.0], # placement anchor, NOT size "height_m": 0.75, # measured world Z "region": {"type": "Polygon", "coordinates": [ [[-0.5, -0.4], [0.5, -0.4], [0.5, 0.4], [-0.5, 0.4], [-0.5, -0.4]] ]} }, "approach_clearance_width_m": 0.9 # optional measured workspace }] } The optional task schema is frontier.task-geometry-request.v1. Unknown task keys raise ValueError so unsupported constraints cannot silently pass. Missing required request fields or measured evidence produce insufficient_evidence; supplied malformed fields, nonfinite numbers, booleans in numeric fields, and duplicate/unknown IDs raise ValueError. Native target x/y/z sizes must all be positive. Z is validated but supplies no vertical-headroom or reach evidence. Measurement rows reuse the existing measured_supports.py receipt['supports'] format: surface.xy_m, height_m, and region from support_surface.measure_surface. Extra measurement metadata is allowed. region is a world-XY GeoJSON Polygon or MultiPolygon with closed, simple rings; holes are supported. The full target x/y rectangle, at the supplied anchor with axes aligned to world X/Y, must fit inside one component, excluding hole interiors. Boundary contact is allowed; there is no implicit margin, scaling, yaw search, or placement search. Rejection only describes this declared pose, never all possible poses. This deliberately does not reproduce the existing triangle-ray/contact qualification pipeline. approach_clearance_width_m is a caller-supplied measured unobstructed approach width to this support, in the SAME scene/pose as the surface. It is required only when minimum_approach_width_m is requested. No clearance is inferred from room/entity bounds. The caller must bind evidence to the current scene and verify its provenance; this pure function does not open files or verify hashes. Candidates are alternatives. At least one fully evidenced passing candidate gives geometry_feasible and passed=True. With none eligible, any missing required evidence gives insufficient_evidence, otherwise geometry_rejected. Eligible IDs preserve request order; diagnostics contain code/entity_ids/message and optional observed/required values. passed refers ONLY to these cheap checks. physical_qualified, native_preflight_queried, and whole_task_acceptance are always False. No native physics, robot IK, path planning, or reach certificate is run. Inputs are never mutated and outputs share no mutable input objects. Shapely/GEOS is imported lazily when a measured region is supplied. Module import, not_requested audits, and requests without region evidence use only the stdlib. A missing or incompatible dependency raises an explicit RuntimeError; there is no geometry fallback. Polygon validity and containment use Shapely shape, is_valid, box, and covers, without geometry repair or tolerance buffering. GEOS uses float64 coordinates. Computed footprint spans must match native sizes within 1e-12 relative tolerance (zero absolute tolerance), allowing ordinary subtraction roundoff at translated decimal anchors. This is only a numerical validation tolerance: it never buffers, rescales, or changes the footprint, and Shapely covers remains the containment authority. Nonfinite/zero areas, collapsed bounds, larger span distortions, and GEOS numerical errors raise ValueError. These guards reject extreme coordinate/size ratios and area underflow/overflow; supported predicates follow GEOS double-precision semantics. Schema grounding: entity IDs/native dimensions follow the authoritative copy at source/scripts/internal/scene_generation/real_assets/joint_layout.py. Measurement rows follow the separately supplied random_supported_20261022_01 helpers; they are an input contract, not an assertion those helpers match the latest source. There are no runtime imports from either source tree. """ import math import warnings from typing import Optional _TASK_FIELDS = {"schema", "support_entity_ids", "target_dimensions_m", "support_height_range_m", "minimum_approach_width_m", "measured_supports"} def _number(value, field): if type(value) not in (int, float): raise ValueError(field + " must be a finite number (not bool)") try: result = float(value) except (OverflowError, ValueError): raise ValueError(field + " must be finite") from None if not math.isfinite(result): raise ValueError(field + " must be finite") return result def _vector(value, length, field): if not isinstance(value, (list, tuple)) or len(value) != length: raise ValueError(field + " has the wrong vector shape") return [_number(item, field) for item in value] def _identifier(value): if not isinstance(value, str) or not value.strip(): raise ValueError("entity_id must be a nonempty string") return value def _index(rows, field): if not isinstance(rows, list): raise ValueError(field + " must be a list") result = {} for row in rows: if not isinstance(row, dict): raise ValueError(field + " must contain dictionaries") identifier = _identifier(row.get("entity_id")) if identifier in result: raise ValueError("Duplicate entity_id in " + field + ": " + identifier) result[identifier] = row return result def _geometry(): try: from shapely import is_valid from shapely.errors import ShapelyError from shapely.geometry import box, shape except (ImportError, OSError) as error: raise RuntimeError( "Task geometry precheck requires Shapely >= 2 with a compatible GEOS build" ) from error return shape, box, is_valid, ShapelyError def _ring(raw): if not isinstance(raw, (list, tuple)) or len(raw) < 4: raise ValueError("region rings must contain at least four closed XY points") ring = [tuple(_vector(point, 2, "region XY")) for point in raw] if ring[0] != ring[-1] or len(set(ring[:-1])) != len(ring) - 1: raise ValueError("region rings must be closed with distinct vertices") return ring def _region(value): if not isinstance(value, dict): raise ValueError("surface.region must be a GeoJSON dictionary") kind, coordinates = value.get("type"), value.get("coordinates") if kind not in ("Polygon", "MultiPolygon"): raise ValueError("surface.region requires Polygon or MultiPolygon") polygons = [coordinates] if kind == "Polygon" else coordinates if not isinstance(polygons, (list, tuple)) or not polygons: raise ValueError("surface.region must have at least one polygon") normalized = [] for polygon in polygons: if not isinstance(polygon, (list, tuple)) or not polygon: raise ValueError("surface.region polygon must have an exterior ring") normalized.append([_ring(raw) for raw in polygon]) shape, _, is_valid, geometry_error = _geometry() try: with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) region = shape({"type": kind, "coordinates": normalized[0] if kind == "Polygon" else normalized}) components = (region,) if kind == "Polygon" else tuple(region.geoms) if not is_valid(region) or any( component.is_empty or not math.isfinite(component.area) or component.area <= 0 for component in components): raise ValueError("surface.region requires valid positive-area float64 polygons") except (geometry_error, RuntimeWarning, OverflowError) as error: raise ValueError("surface.region exceeds supported float64 geometry") from error return components def _fits(polygons, anchor, dimensions): lower = [anchor[i] - dimensions[i] / 2 for i in (0, 1)] upper = [anchor[i] + dimensions[i] / 2 for i in (0, 1)] if (not all(math.isfinite(v) for v in lower + upper) or any(lower[i] >= upper[i] or not math.isfinite(upper[i] - lower[i]) or not math.isclose(upper[i] - lower[i], dimensions[i], rel_tol=1e-12, abs_tol=0.0) for i in (0, 1))): raise ValueError("Native footprint bounds cannot preserve dimensions in float64") _, box, is_valid, geometry_error = _geometry() try: with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) footprint = box(*lower, *upper) if (not is_valid(footprint) or footprint.is_empty or not math.isfinite(footprint.area) or footprint.area <= 0): raise ValueError("Native footprint requires valid positive-area float64 geometry") return any(polygon.covers(footprint) for polygon in polygons) except (geometry_error, RuntimeWarning, OverflowError) as error: raise ValueError("Native footprint exceeds supported float64 geometry") from error def evaluate_task(manifest: dict, task: Optional[dict]) -> dict: """Evaluate only the declared fixed-pose geometry; see module input contract.""" result = {"schema": "frontier.task-geometry-precheck.v1", "status": "not_requested", "passed": False, "eligible_support_entity_ids": [], "diagnostics": [], "physical_qualified": False, "native_preflight_queried": False, "whole_task_acceptance": False} if task is None or (isinstance(task, dict) and not task): return result if not isinstance(task, dict): raise ValueError("task must be a dictionary or None") if set(task) - _TASK_FIELDS: raise ValueError("Unsupported task fields") if "schema" in task and task["schema"] != "frontier.task-geometry-request.v1": raise ValueError("Unsupported task request schema") if not isinstance(manifest, dict): raise ValueError("manifest must be a dictionary") entities = _index(manifest.get("entities"), "manifest.entities") identifiers = task.get("support_entity_ids", []) if not isinstance(identifiers, list): raise ValueError("support_entity_ids must be a list") ids = [_identifier(value) for value in identifiers] if len(set(ids)) != len(ids): raise ValueError("Duplicate support_entity_ids") measured = _index(task.get("measured_supports", []), "measured_supports") if (set(ids) | set(measured)) - set(entities): raise ValueError("Unknown support entity_id") dimensions = None if "target_dimensions_m" in task: dimensions = _vector(task["target_dimensions_m"], 3, "target_dimensions_m") if any(v <= 0 for v in dimensions): raise ValueError("target_dimensions_m must be positive native sizes") height_range = None if "support_height_range_m" in task: height_range = _vector(task["support_height_range_m"], 2, "support_height_range_m") if height_range[0] > height_range[1]: raise ValueError("support_height_range_m must be ordered") approach_minimum = None if "minimum_approach_width_m" in task: approach_minimum = _number(task["minimum_approach_width_m"], "minimum_approach_width_m") if approach_minimum < 0: raise ValueError("minimum_approach_width_m must be nonnegative") evidence = {} for identifier, row in measured.items(): surface = row.get("surface", {}) if not isinstance(surface, dict): raise ValueError("surface must be a dictionary") parsed = {} for field, length in (("xy_m", 2), ("height_m", None)): if field in surface: parsed[field] = (_vector(surface[field], length, field) if length else _number(surface[field], field)) if "region" in surface: parsed["region"] = _region(surface["region"]) if "approach_clearance_width_m" in row: parsed["approach_clearance_width_m"] = _number( row["approach_clearance_width_m"], "approach_clearance_width_m") if parsed["approach_clearance_width_m"] < 0: raise ValueError("approach_clearance_width_m must be nonnegative") evidence[identifier] = parsed def diagnostic(code, entity_ids, message, **details): result["diagnostics"].append(dict(code=code, entity_ids=list(entity_ids), message=message, **details)) if not ids: diagnostic("missing_support_entity_ids", [], "Explicit support candidates are required.") if dimensions is None: diagnostic("missing_target_dimensions", ids, "Positive native target dimensions are required.") missing = not ids or dimensions is None for identifier in ids: row = evidence.get(identifier) if row is None: diagnostic("missing_measured_support", [identifier], "No measured support evidence was supplied.") missing = True continue incomplete, rejected = dimensions is None, False for field, code in (("xy_m", "missing_surface_anchor"), ("height_m", "missing_surface_height"), ("region", "missing_surface_region")): if field not in row: diagnostic(code, [identifier], "Measured surface requires " + field + ".") incomplete = True if dimensions is not None and "xy_m" in row and "region" in row: if not _fits(row["region"], row["xy_m"], dimensions): diagnostic("support_footprint_outside_region", [identifier], "Native footprint at the declared anchor is outside the measured region.") rejected = True if height_range is not None and "height_m" in row: if not height_range[0] <= row["height_m"] <= height_range[1]: diagnostic("support_height_out_of_range", [identifier], "Measured height is outside the requested range.", observed_m=row["height_m"], required_range_m=list(height_range)) rejected = True if approach_minimum is not None: width = row.get("approach_clearance_width_m") if width is None: diagnostic("missing_approach_clearance", [identifier], "Requested approach width needs measured workspace evidence.") incomplete = True elif width < approach_minimum: diagnostic("approach_width_below_minimum", [identifier], "Measured approach width is below the requested minimum.", observed_m=width, required_minimum_m=approach_minimum) rejected = True missing = missing or incomplete if not incomplete and not rejected: result["eligible_support_entity_ids"].append(identifier) result["passed"] = bool(result["eligible_support_entity_ids"]) result["status"] = ("geometry_feasible" if result["passed"] else "insufficient_evidence" if missing else "geometry_rejected") return result