File size: 6,675 Bytes
832f0f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
"""Score the required NPC interaction and settled return within 200 cm."""
from __future__ import annotations

import math
from dataclasses import dataclass
from typing import Any


@dataclass
class UnitResult:
    complete: bool
    detail: dict


def nonempty_text(value: Any) -> bool:
    return isinstance(value, str) and bool(value.strip())


def positive_number(value: Any) -> bool:
    return (not isinstance(value, bool) and isinstance(value, (int, float))
            and math.isfinite(value) and value > 0)


def valid_xyz(value: Any) -> bool:
    return (isinstance(value, (list, tuple)) and len(value) >= 3
            and all(not isinstance(v, bool) and isinstance(v, (int, float))
                    and math.isfinite(v) for v in value[:3]))


def missing_completion_result(detail, result):
    """A recorded normal stop is a failure, not a lost completion record."""
    status = result.get("status")
    reasons = {
        "max_steps_exceeded": ("step_limit_reached", "step limit reached without completing finish_task"),
        "idle_no_tool_call": ("stopped_without_finish", "agent stopped issuing tool calls without completing finish_task"),
    }
    if status in reasons and not result.get("environment_error"):
        code, reason = reasons[status]
        return UnitResult(False, {**detail, "evidence_missing": False,
                                  "result_status": status, "reason_code": code, "reason": reason})
    return UnitResult(False, {**detail, "evidence_missing": True,
                              "result_status": status,
                              "reason": "no successful finish_task event; normal episode termination is not established"})


def evaluate_route_return(check, result, task, judge):
    """Successful target interaction followed by a settled return within 200 cm."""
    detail = {"method": "route_return", "profile": "spatial_memory_return_v2",
              "scoring_contract": "interaction_and_return_200cm_v1", "evidence_missing": False}

    def fail(reason, missing=False, **extra):
        return UnitResult(False, {**detail, **extra, "reason": reason, "evidence_missing": missing})

    raw = result.get("tool_events")
    if not isinstance(raw, list):
        return fail("tool_events must be a list", True)
    finishes = [(i, e) for i, e in enumerate(raw) if isinstance(e, dict) and e.get("tool") == "finish_task"
                and e.get("success") is True and not (isinstance(e.get("data"), dict) and e["data"].get("finish_reflection"))]
    if not finishes:
        return missing_completion_result(detail, result)
    finish_index, finish = finishes[-1]
    final = finish.get("data") if isinstance(finish.get("data"), dict) else {}
    finish_time = final.get("pose_observed_at")
    if final.get("finished") is not True or final.get("settled") is not True or not valid_xyz(final.get("pose")) or not positive_number(finish_time):
        return fail("completion requires a synchronized settled pose and timestamp", True)
    detail["finish_event"] = finish_index
    allowed = {"navigate_forward", "turn_left", "turn_right", "look_left", "look_right", "look_back", "look_forward",
               "adjust_view", "reset_view", "set_yaw", "observe_sweep", "observation", "get_pos", "talk_to_npc", "report_to_npc", "finish_task"}
    # Check failed events as well: a failed navigation can already have moved.
    for i, event in enumerate(raw[:finish_index]):
        if not isinstance(event, dict):
            return fail("malformed tool event", True)
        data = event.get("data") if isinstance(event.get("data"), dict) else {}
        if data.get("blocked_by_task_profile") == "spatial_memory_return_v2" and event.get("success") is False:
            continue  # Runtime prevented execution; a mistaken request may be corrected.
        if event.get("tool") not in allowed or data.get("mode") == "teleport":
            return fail("unsupported movement or shortcut tool in route-return episode", tool_event=i)
        if event.get("tool") == "navigate_forward" and (event.get("success") is True or "after" in data) and data.get("navigation_mode") != "navmesh":
            return fail("missing NavMesh movement provenance", True, tool_event=i)
    # Runtime already enforces interaction distance. Trust only the returned
    # alias and successful tool event, never the agent's requested target.
    interaction = None
    for index, event in enumerate(raw[:finish_index]):
        if event.get("success") is not True or event.get("tool") not in {"talk_to_npc", "report_to_npc"}:
            continue
        data = event.get("data") if isinstance(event.get("data"), dict) else {}
        alias = data.get("alias")
        response = data.get("response")
        if not nonempty_text(alias) or (isinstance(response, dict) and
                "alias" in response and response["alias"] != alias):
            return fail("successful NPC event lacks consistent server-resolved identity", True, tool_event=index)
        if alias == check["npc_target"]:
            interaction = {"event_index": index, "tool": event["tool"], "alias": alias}
            break
    if interaction is None:
        return fail("no successful interaction with the configured NPC before completion")
    detail["interaction"] = interaction

    # Only the synchronous initial sample is needed: no corridor, checkpoint,
    # visual-input, sampling-density or distance-along-trajectory checks.
    initial = result.get("route_initial_sample")
    if not isinstance(initial, dict) or initial.get("route_initial") is not True:
        return fail("synchronized episode-start sample is missing", True)
    state = initial.get("state")
    if not isinstance(state, dict) or state.get("ready") is not True or not valid_xyz(state.get("pose")):
        return fail("episode-start sample lacks a ready finite pose", True)
    if state.get("task_id") != task.get("task_id") or not nonempty_text(state.get("session_id")):
        return fail("episode-start sample has missing or mismatched identity", True)
    if not positive_number(initial.get("time")) or initial["time"] >= finish_time:
        return fail("episode-start sample must precede completion", True)
    start_pose = state["pose"][:3]
    distance = math.dist(final["pose"][:3], start_pose)
    detail.update(actual_start_pose=start_pose, final_pose=final["pose"][:3],
                  return_distance_cm=distance, arrival_radius_cm=200.0)
    if distance > 200.0:
        return fail("final pose is more than 200 cm from the actual episode spawn")
    return UnitResult(True, {**detail, "reason": "successful NPC interaction followed by return within 200 cm"})