"""Closed contract and offline scorer for visually grounded station check-ins. Geometry is evaluator-only. Runtime records a settled pose without answering whether the station identity, location, or precedence is correct. """ import math PROFILE = "constraint_route_v2" CHECK = "grounded_constraint_route" FIELDS = {"type", "stations", "required_stations", "forbidden_stations", "precedence", "arrival_radius_cm", "height_tolerance_cm", "anchor_clearance_cm", "allow_region_overlap"} def xyz(value): return (isinstance(value, (list, tuple)) and len(value) >= 3 and all(type(v) in (int, float) and math.isfinite(v) for v in value[:3])) def positive(value): return type(value) in (int, float) and math.isfinite(value) and value > 0 def names(value, minimum=0): return (isinstance(value, list) and len(value) >= minimum and all(isinstance(s, str) and s.strip() for s in value) and len(set(value)) == len(value)) def inside(pose, location, check, margin=0): return (math.dist(pose[:2], location[:2]) <= check["arrival_radius_cm"] + margin and abs(pose[2] - location[2]) <= check["height_tolerance_cm"]) def station_positions(station): return [station] + station.get("additional_positions", []) def station_inside(pose, station, check, margin=0): """A union of reviewed standing points, clipped to the legal floor strip. Bounds are evaluator-only XY coordinates, never inferred from a rollout. A margin is used only for keeping public anchors clear of arrival regions. """ bounds = station.get("arrival_bounds_xy") if bounds and not (bounds[0] - margin <= pose[0] <= bounds[2] + margin and bounds[1] - margin <= pose[1] <= bounds[3] + margin): return False return any(inside(pose, p["location"], check, margin) for p in station_positions(station)) def contract_errors(check): errors = [] if set(check) - FIELDS: errors.append("grounded route contains unsupported fields") if "allow_region_overlap" in check and type(check["allow_region_overlap"]) is not bool: errors.append("allow_region_overlap must be a boolean") required = check.get("required_stations") forbidden = check.get("forbidden_stations") if not names(required, 3): errors.append("required_stations needs >=3 distinct names") if not names(forbidden): errors.append("forbidden_stations must contain distinct names") if not names(required, 3) or not names(forbidden): return errors if set(required) & set(forbidden): errors.append("required and forbidden stations overlap") stations = check.get("stations") valid_stations = isinstance(stations, dict) and set(stations) == set(required + forbidden) if valid_stations: for station in stations.values(): if (not isinstance(station, dict) or set(station) - {"point_name", "location", "additional_positions", "arrival_bounds_xy"} or not isinstance(station.get("point_name"), str) or not station["point_name"].strip() or not xyz(station.get("location")) or len(station["location"]) != 3): valid_stations = False break additional = station.get("additional_positions", []) if (not isinstance(additional, list) or any(not isinstance(p, dict) or set(p) != {"point_name", "location"} or not isinstance(p["point_name"], str) or not p["point_name"].strip() or not xyz(p["location"]) or len(p["location"]) != 3 for p in additional)): valid_stations = False break bounds = station.get("arrival_bounds_xy") if bounds is not None: if (not isinstance(bounds, list) or len(bounds) != 4 or not all(type(v) in (int, float) and math.isfinite(v) for v in bounds) or bounds[0] >= bounds[2] or bounds[1] >= bounds[3] or any(not (bounds[0] <= p["location"][0] <= bounds[2] and bounds[1] <= p["location"][1] <= bounds[3]) for p in station_positions(station))): valid_stations = False break if not valid_stations: errors.append("stations must map every station to a recorded XYZ point, with valid optional additional_positions and arrival_bounds_xy") for key in ("arrival_radius_cm", "height_tolerance_cm", "anchor_clearance_cm"): if not positive(check.get(key)): errors.append(f"{key} must be positive and finite") edges = check.get("precedence") valid_edges = (isinstance(edges, list) and bool(edges) and all(isinstance(e, list) and len(e) == 2 and all(isinstance(v, str) and v in required for v in e) and e[0] != e[1] for e in edges)) if not valid_edges: errors.append("precedence requires distinct required-station endpoint pairs") else: if len({tuple(e) for e in edges}) != len(edges): errors.append("precedence contains duplicate edges") remaining = set(required) while remaining: roots = {v for v in remaining if not any(b == v and a in remaining for a, b in edges)} if not roots: errors.append("precedence contains a cycle") break remaining -= roots if (valid_stations and not check.get("allow_region_overlap", False) and all(positive(check.get(k)) for k in ("arrival_radius_cm", "height_tolerance_cm"))): entries = list(stations.items()) for i, (a, pa) in enumerate(entries): for b, pb in entries[i + 1:]: if any(math.dist(a_pos["location"][:2], b_pos["location"][:2]) <= 2 * check["arrival_radius_cm"] and abs(a_pos["location"][2] - b_pos["location"][2]) <= 2 * check["height_tolerance_cm"] for a_pos in station_positions(pa) for b_pos in station_positions(pb)): errors.append(f"arrival regions overlap: {a!r}, {b!r}") return errors def reference_errors(check, points_by_name, visible_names, task): if contract_errors(check): return [] errors = [] public = task.get("agent_input", {}).get("station_names") if not names(public) or set(public) != set(check["stations"]): errors.append("agent_input.station_names must list exactly the public station roles") if not visible_names: errors.append("grounded route requires public coarse anchors") for label, station in check["stations"].items(): for position in station_positions(station): name, location = position["point_name"], position["location"] matches = points_by_name.get(name, []) if len(matches) != 1 or not xyz(matches[0].get("location")): errors.append(f"station {label!r} requires a unique recorded point") elif math.dist(matches[0]["location"][:3], location) > 1: errors.append(f"station {label!r} location must match its record") if name in visible_names or label in visible_names: errors.append(f"exact station {label!r} must not be a public go_to target") coarse_and_start = set(visible_names) | {task.get("start", {}).get("point_name")} for name in coarse_and_start: matches = points_by_name.get(name, []) if len(matches) != 1 or not xyz(matches[0].get("location")): errors.append(f"coarse/start point {name!r} must have a unique finite location") continue for label, station in check["stations"].items(): if station_inside(matches[0]["location"], station, check, check["anchor_clearance_cm"]): errors.append(f"coarse/start point {name!r} is too close to station {label!r}") return errors def evaluate(check, result): """Return (complete, detail); never infer arrivals from text or go_to labels.""" detail = {"method": CHECK, "confirmations": [], "precedence_violations": [], "invalid_confirmations": [], "forbidden_confirmations": []} errors = contract_errors(check) if errors: return False, {**detail, "configuration_errors": errors} events = result.get("tool_events") if not isinstance(events, list): return False, {**detail, "evidence_missing": True, "reason": "tool_events missing"} finishes = [i for i, e in enumerate(events) if isinstance(e, dict) and e.get("tool") == "finish_task" and e.get("success") is True and isinstance(e.get("data"), dict) and e["data"].get("finished") is True] if not finishes: terminal_failure = result.get("status") in {"max_steps_exceeded", "idle_no_tool_call"} return False, {**detail, "reason": "task was not explicitly finished", "evidence_missing": not terminal_failure} first_visit = {} evidence_missing = False required = set(check["required_stations"]) forbidden = set(check["forbidden_stations"]) for index, event in enumerate(events[:finishes[0] + 1]): if not isinstance(event, dict) or event.get("tool") != "confirm_station" or event.get("success") is not True: continue data = event.get("data") if isinstance(event.get("data"), dict) else {} args = event.get("args") if isinstance(event.get("args"), dict) else {} label, pose = data.get("station"), data.get("pose") if (data.get("settled") is not True or not xyz(pose) or data.get("profile") != PROFILE or label != args.get("station")): evidence_missing = True detail["invalid_confirmations"].append({"index": index, "reason": "missing or inconsistent runtime pose evidence"}) continue if not isinstance(label, str) or label not in check["stations"]: detail["invalid_confirmations"].append({"index": index, "reason": "unknown station role"}) continue matched = [name for name, station in check["stations"].items() if station_inside(pose, station, check)] row = {"index": index, "station": label, "pose": pose[:3], "geometric_matches": matched} detail["confirmations"].append(row) overlap_allowed = check.get("allow_region_overlap", False) if label in forbidden or (not overlap_allowed and set(matched) & forbidden): detail["forbidden_confirmations"].append(row) if (label not in matched if overlap_allowed else matched != [label]): detail["invalid_confirmations"].append({**row, "reason": "station identity and measured location do not match"}) continue if label in required: first_visit.setdefault(label, index) missing = sorted(required - set(first_visit)) bad = [edge for edge in check["precedence"] if all(label in first_visit for label in edge) and first_visit[edge[0]] > first_visit[edge[1]]] detail.update(missing_stations=missing, first_confirmations=first_visit, precedence_violations=bad) if evidence_missing: detail["evidence_missing"] = True complete = not (missing or bad or detail["invalid_confirmations"] or detail["forbidden_confirmations"]) return complete, detail