diff --git a/docs/AI_POLYGON_ROUTE_PLANNING.md b/docs/AI_POLYGON_ROUTE_PLANNING.md index ab3b5771..31990d94 100644 --- a/docs/AI_POLYGON_ROUTE_PLANNING.md +++ b/docs/AI_POLYGON_ROUTE_PLANNING.md @@ -100,7 +100,12 @@ SOG-кэш используется редактором и локальным `advisory` снимает жёсткое удержание корпуса в капсуле линии. Локальные цели и объезды по наблюдаемой поверхности разрешены вне неё, явные `no_go` продолжают действовать. Соседний участок засчитывается только при фактическом -продвижении и текущем положительном whole-body receipt. Финальная точка +продвижении и текущем положительном whole-body receipt. Для Nav2 отдельный +`route_transition_target` запрашивает `route_support`: текущую геометрическую +опору по положительно наблюдённой семантической поверхности. Этот ответ +привязан к pose, времени мира, цели и SHA входов; он не означает прибытие и +не даёт команду движения. Устаревшая транзакция не переносит старый ответ. +Финальная точка сохраняет отдельное подтверждение прибытия. Локальная цель рядом с промежуточным advisory-ориентиром после отказа native-планировщика исключается из кандидатов; она не сохраняется как обязательный финиш. Финальная цель и обязательный diff --git a/simulation/ai-polygon/nav2/route_support.py b/simulation/ai-polygon/nav2/route_support.py new file mode 100644 index 00000000..ce0d392f --- /dev/null +++ b/simulation/ai-polygon/nav2/route_support.py @@ -0,0 +1,24 @@ +"""Current observed body support for an intent transition, never a drive goal.""" +import math + +import numpy as np + + +def route_support(monitor, observed, value, inputs): + target = value.get("route_transition_target") + if target is None: + return None + pose = np.asarray(value["pose"], dtype=float) + target = np.asarray(target, dtype=float) + if (target.shape != (2,) or not np.isfinite(target).all() + or math.dist(pose[:2], target) > 3.5 + or value["execution_inputs_sha256"] != inputs["sha256"]): + raise ValueError("Invalid route transition observation") + support = observed["permitted_terrain"] + receipt = monitor.assess_pose(observed["terrain"], pose, + value["body_contact_height_m"], support_terrain=support) + return {**receipt, "positive_surface_required": True, + "authority": "current-body; intent-transition-only", + "observation": dict(pose=pose.tolist(), target_xy=target.tolist(), + simulation_time_seconds=value["simulation_time_seconds"], + execution_inputs_sha256=inputs["sha256"])} diff --git a/simulation/ai-polygon/nav2/server.py b/simulation/ai-polygon/nav2/server.py index 50674804..1545e841 100644 --- a/simulation/ai-polygon/nav2/server.py +++ b/simulation/ai-polygon/nav2/server.py @@ -27,6 +27,7 @@ from navigation.route_observation import route_observation from navigation.support_policy import SupportPolicy from observed_collision import ObservedCollision from rig_collision import collision_geometry +from route_support import route_support from ros_navigation import RosNavigation, yaw_of from std_srvs.srv import Trigger from terrain_process import TerrainProcess @@ -98,6 +99,12 @@ class Navigation: return None def plan(self, value): + # Transaction-local metadata cannot survive a stale/failed observation. + receipts = {} + result = self._plan(value, receipts) + return {**result, **receipts} + + def _plan(self, value, receipts): entered = time.monotonic() if self.failure: raise RuntimeError(self.failure) @@ -130,6 +137,9 @@ class Navigation: detected=observed['detected']): return self.reply('stale-range') route = route_observation(terrain, pose, value, self.monitor.max_step) + support = route_support(self.monitor, observed, value, self.inputs) + if support is not None: + receipts["route_support"] = support orientation = validate_orientation(value.get('orientation_target')) target = value.get('arrival_target') if target is not None: diff --git a/simulation/ai-polygon/nav2/terrain_observation.py b/simulation/ai-polygon/nav2/terrain_observation.py index e417f028..e3a7945f 100644 --- a/simulation/ai-polygon/nav2/terrain_observation.py +++ b/simulation/ai-polygon/nav2/terrain_observation.py @@ -133,6 +133,8 @@ class TerrainObservation: points, forbidden = self.semantics.apply(points, time.monotonic()) search, _ = self.support_obstacles.apply(points, pose=pose, monitor=self.monitor) return dict(terrain=points, search_terrain=search, physical_terrain=physical, detected=detected, + permitted_terrain=(self.semantics.permitted_terrain(points, time.monotonic()) + if request.get("route_transition_target") is not None else None), current_points=current, metrics=dict(detection_candidates=len(candidates), detection_ground_returns=len(candidates)-len(detected), diff --git a/simulation/ai-polygon/navigation_client.py b/simulation/ai-polygon/navigation_client.py index fb0f03ea..920d50fc 100644 --- a/simulation/ai-polygon/navigation_client.py +++ b/simulation/ai-polygon/navigation_client.py @@ -831,6 +831,8 @@ class ComposedInference: "arrival_target": arrival_target if arrival_candidate or body_goal_query else None, + "route_transition_target": arrival_target + if nearby and isinstance(self.mission, RoutedMission) else None, "max_speed_mps": min(self.max_speed, 0.1) if intent["state"] == "reversing" or intent.get("corner_approach") else min(self.max_speed, inputs.get("source.crossing-admission", {}).get("speed_limit_mps") or self.max_speed), @@ -931,7 +933,8 @@ class ComposedInference: intent = self.mission.intent(self.mission.state) elif isinstance(self.mission, RoutedMission) and revision is None: transition = self.mission.confirm_corridor_transition( - pose, inputs["source.simulation-time"], result.get("arrival") or {} + pose, inputs["source.simulation-time"], + result.get("route_support") or result.get("arrival") or {} ) if transition is not None: result.update( diff --git a/src/k1link/simulation/ai_polygon/composition.py b/src/k1link/simulation/ai_polygon/composition.py index 04e829b0..d35879f9 100644 --- a/src/k1link/simulation/ai_polygon/composition.py +++ b/src/k1link/simulation/ai_polygon/composition.py @@ -344,7 +344,7 @@ def registry(adapter_root: Path) -> ModuleRegistry: "detection_obstacles.py", "route_observation.py", "arrival_approach.py", "pcl_ground.py") runtime = ("configuration.py", "nodes.py", "observed_collision.py", "ros_navigation.py", "server.py", "terrain_node.py", "terrain_observation.py", "terrain_process.py", - "detector_exclusion.py", "differential_motion.py") + "detector_exclusion.py", "differential_motion.py", "route_support.py") files = [adapter_root/"nav2"/name for name in runtime] files += [adapter_root/"navigation"/name for name in shared] files += [adapter_root/name for name in ("model_stack.py", "navigation_client.py", "rig_collision.py")] diff --git a/tests/test_nav2_differential_motion.py b/tests/test_nav2_differential_motion.py index 359ff934..b9655a09 100644 --- a/tests/test_nav2_differential_motion.py +++ b/tests/test_nav2_differential_motion.py @@ -102,7 +102,7 @@ def test_unknown_future_track_ground_does_not_select_an_incomplete_turn(motion): assert alignment_angle(pose(),[0.,2.,0.],hole,[],monitor,.37) is None -@pytest.mark.parametrize('helper',['detector_exclusion.py','differential_motion.py']) +@pytest.mark.parametrize('helper',['detector_exclusion.py','differential_motion.py','route_support.py']) def test_native_module_identity_includes_behavior_helpers(monkeypatch,helper): from k1link.simulation.ai_polygon.composition import registry diff --git a/tests/test_nav2_route_support.py b/tests/test_nav2_route_support.py new file mode 100644 index 00000000..8527f6e5 --- /dev/null +++ b/tests/test_nav2_route_support.py @@ -0,0 +1,80 @@ +"""Real Nav2 plan entry returns bound current support without declaring arrival.""" +import ast +import copy +import math +from pathlib import Path +from types import SimpleNamespace +import time + +import numpy as np +import pytest + + +@pytest.fixture +def bridge(monkeypatch): + root = Path(__file__).parents[1] / 'simulation/ai-polygon' + monkeypatch.syspath_prepend(str(root)) + monkeypatch.syspath_prepend(str(root / 'nav2')) + from navigation.footprint import Footprint + from navigation.route_observation import route_observation + from route_support import route_support + # Load the actual adapter class without unavailable ROS imports on the Mac. + tree = ast.parse((root / 'nav2/server.py').read_text()) + cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Navigation') + scope = dict(np=np, math=math, time=time, route_support=route_support, + route_observation=route_observation, validate_orientation=lambda _: None, + alignment_angle=lambda *args: None) + exec(compile(ast.Module(body=[cls], type_ignores=[]), str(root / 'nav2/server.py'), 'exec'), scope) + navigation = scope['Navigation'].__new__(scope['Navigation']) + navigation.failure = None + navigation.active = navigation.activating = True + navigation.action_key = navigation.attempted_alignment = None + navigation.inputs = dict(sha256='a'*64, behavior={'max_speed_mps': 1.}, + mission={'arrival_radius_m': .4}) + navigation.monitor = Footprint(dict(length_m=1., width_m=.6, max_step_m=.1, max_slope_degrees=25.)) + navigation.node = SimpleNamespace(pose=(time.monotonic(), None, [0., 0., 0.]), stop=lambda: None) + navigation.control = SimpleNamespace(observe=lambda _: None) + navigation.collision = SimpleNamespace(publish=lambda *args, **kwargs: True) + floor = np.array([[x, y, 0., 0.] for x in np.arange(-2, 2.01, .05) + for y in np.arange(-2, 2.01, .05)]) + observed = dict(terrain=floor, permitted_terrain=floor, search_terrain=floor, + detected=np.empty((0, 3))) + navigation.terrain = SimpleNamespace(observe=lambda _: observed) + value = dict(pose=[0., 0., .37, 0., 0., 0., 1.], goal=[1., 0., 0.], + geometry_age_seconds=0., detection_age_seconds=0., max_speed_mps=1., + allow_reverse=False, translation_allowed=False, observation_id='sample-1', + route_transition_target=[1., 0.], arrival_target=None, + body_contact_height_m=.37, simulation_time_seconds=4., + execution_inputs_sha256='a'*64) + return navigation, observed, value + + +@pytest.mark.parametrize('condition', ['permitted', 'unknown', 'obstacle']) +def test_support_is_current_and_positive_but_does_not_grant_a_path_or_arrival(bridge, condition): + navigation, observed, value = bridge + if condition == 'unknown': + observed['permitted_terrain'] = np.empty((0, 4)) + if condition == 'obstacle': + observed['terrain'] = np.vstack((observed['terrain'], [[.3, 0., .4, 1.]])) + result = navigation.plan(value) + receipt = result['route_support'] + assert receipt['admitted'] is (condition == 'permitted') + assert receipt['positive_surface_required'] is True + assert receipt['observation'] == dict(pose=value['pose'], target_xy=[1., 0.], + simulation_time_seconds=4., execution_inputs_sha256='a'*64) + assert result['status'] == 'blocked' and 'arrival' not in result + assert result['speed_mps'] == result['yaw_rate_rps'] == 0. + # A stale or unrelated next request must not inherit the previous receipt. + stale = copy.deepcopy(value) + stale['geometry_age_seconds'] = .9 + assert 'route_support' not in navigation.plan(stale) + unrelated = copy.deepcopy(value) + unrelated.pop('route_transition_target') + assert 'route_support' not in navigation.plan(unrelated) + + +def test_route_support_rejects_remote_or_wrongly_bound_target(bridge): + navigation, _, value = bridge + for change in ({'route_transition_target': [4., 0.]}, {'execution_inputs_sha256': 'b'*64}): + with pytest.raises(ValueError, match='transition observation'): + navigation.plan({**value, **change})