File size: 8,786 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
"""Score outbound location/stop/observation metadata without opening images."""
import json
import math
from return_endpoint import valid_xyz


MOVEMENT = {'navigate_forward', 'go_to', 'go_to_route_anchor', 'navigate', 'move'}


def collect_stops(result, target):
    """Join model tool calls to returned events by exact sequence, name and args.

    Do not compare naive local wall-clock strings with epoch pose timestamps.
    A fresh translation separates stop episodes; mere turning does not.
    """
    raw = result.get('tool_events', [])
    llms = result.get('llm_events', [])
    calls = [c for e in llms for c in e.get('tool_calls', [])]
    if len(calls) != len(raw):
        return [], False, 'tool_call_and_result_count_mismatch'
    for c, r in zip(calls, raw):
        f = c.get('function', {})
        try: args = json.loads(f.get('arguments', '{}'))
        except (TypeError, ValueError): return [], False, 'unparseable_tool_arguments'
        if f.get('name') != r.get('tool') or args != r.get('args'):
            return [], False, 'tool_call_and_result_identity_mismatch'
    stops = {}; epoch = 0; cursor = 0; complete = True
    def add(pose, settled, observed, ref, order):
        if settled is not True or not valid_xyz(pose): return
        stops.setdefault(epoch, []).append({'pose': pose, 'observed': observed,
            'evidence_id': ref, 'order': order, 'stop_id': epoch})
    for i, llm in enumerate(llms):
        vi = llm.get('visual_input')
        if not isinstance(vi, dict) or not isinstance(vi.get('provided'), bool):
            complete = False
        elif vi.get('provided'):
            if not valid_xyz(vi.get('pose')) or not isinstance(vi.get('settled'), bool): complete = False
            add(vi.get('pose'), vi.get('settled'), True, f'llm_events/{i}/visual_input', cursor * 10)
        for _ in llm.get('tool_calls', []):
            index = cursor; event = raw[index]; cursor += 1
            data = event.get('data') or {}; name = event.get('tool')
            if name in {'talk_to_npc', 'report_to_npc'} and event.get('success') is True and data.get('alias') == target:
                add(data.get('pose'), data.get('settled'), False, f'tool_events/{index}/data', index * 10 + 5)
                return list(stops.values()), complete, 'outbound_until_target_interaction'
            if name == 'finish_task' and data.get('finished') is True:
                return list(stops.values()), complete, 'outbound_until_completion'
            if name in MOVEMENT and not data.get('blocked_by_task_profile'):
                before = data.get('before'); after = (data.get('after_settle') or {}).get('pose') or data.get('after')
                # navmesh_toolset.navigate_forward returns this exact shape
                # before starting navigation when all candidate paths fail.
                # It is a recorded no-op, not a hole in movement evidence.
                if (name == 'navigate_forward' and event.get('success') is False
                        and data.get('collision_or_blocked') is True
                        and isinstance(data.get('candidates'), list)
                        and valid_xyz(before) and after is None and 'nav_result' not in data):
                    continue
                if not valid_xyz(before) or not valid_xyz(after):
                    complete = False; epoch += 1
                elif math.dist(before[:3], after[:3]) > 2:
                    epoch += 1
                settled = (data.get('after_settle') or {}).get('settled', data.get('settled'))
                add(after, settled, False, f'tool_events/{index}/data/post_navigation', index * 10 + 5)
            if name == 'observe_sweep' and event.get('success') is True:
                for j, direction in enumerate(data.get('directions', [])):
                    turn = direction.get('turn') or {}; pre = turn.get('settle_before_turn') or {}
                    pose = direction.get('pose'); prior = pre.get('pose')
                    observed = (direction.get('image') or {}).get('provided') is True
                    stable = (pre.get('settled') is True and direction.get('turn_success') is True
                              and valid_xyz(pose) and valid_xyz(prior) and math.dist(pose[:3], prior[:3]) <= 2)
                    add(pose, stable, observed, f'tool_events/{index}/data/directions/{j}', index * 10 + 5)
            elif name not in MOVEMENT:
                add(data.get('pose'), data.get('settled'), False, f'tool_events/{index}/data', index * 10 + 5)
    normal = result.get('status') in {'success', 'max_steps_exceeded', 'idle_no_tool_call'} and not result.get('environment_error')
    return list(stops.values()), complete and normal, 'normal_end' if normal else 'episode_not_complete'


def within(pose, center, params):
    return (math.dist(pose[:2], center[:2]) <= params['horizontal_radius_cm']
            and abs(pose[2] - center[2]) <= params['height_tolerance_cm'])


def evaluate_outbound(definition, result, initial):
    units = [u for u in definition['milestones'] if u['parameters'].get('action') == 'numeric_route_stop']
    target = next(u for u in definition['milestones'] if u['parameters'].get('action') == 'return_endpoint')['parameters']['npc_target']
    stops, complete, reason = collect_stops(result, target)
    state = initial.get('state', {}) if isinstance(initial, dict) else {}
    start_ok = (isinstance(initial,dict) and initial.get('route_initial') is True and state.get('ready') is True
                and state.get('task_id') == result.get('task_id') and bool(state.get('session_id')) and valid_xyz(state.get('pose')))
    options = {}; binding_missing = set()
    for u in units:
        p = u['parameters']; options[u['id']] = []
        if p['actual_start_override'] and not start_ok:
            binding_missing.add(u['id']); continue
        center = state['pose'][:3] if p['actual_start_override'] else p['location']
        for samples in stops:
            sid = samples[0]['stop_id']
            if p['actual_start_override'] and sid != 0: continue
            matched = [x for x in samples if within(x['pose'], center, p) and
                       (x['observed'] or not p['observation_required'])]
            if not matched: continue
            if p['observation_mode'] == 'look_around':
                yaws = [x['pose'][4] for x in matched if len(x['pose']) >= 5]
                if not any(abs((a-b+180)%360-180)>1e-6 for a in yaws for b in yaws): continue
            options[u['id']].append({'stop_id':sid,'order':min(x['order'] for x in matched),
                'evidence_ids':[x['evidence_id'] for x in matched],
                'minimum_horizontal_distance_cm':min(math.dist(x['pose'][:2],center[:2]) for x in matched)})
        options[u['id']].sort(key=lambda x:(x['minimum_horizontal_distance_cm'],x['order']))
    # Maximum matching: overlapping radii cannot turn one stop into several stops.
    # Required route order is reported separately, never used for prefix-zeroing.
    owner = {}; selected = {}
    def assign(uid, seen):
        for candidate in options[uid]:
            sid = candidate['stop_id']
            if sid in seen: continue
            seen.add(sid)
            if sid not in owner or assign(owner[sid], seen):
                owner[sid] = uid; selected[uid] = candidate; return True
        return False
    for u in sorted(units,key=lambda x:len(options[x['id']])): assign(u['id'],set())
    rows = []
    for u in units:
        uid = u['id']; hit = selected.get(uid)
        status = 'completed' if hit else 'failed' if complete and uid not in binding_missing else 'evidence_insufficient'
        rows.append({'unit_id':uid,'status':status,'evidence':hit,
                     'reason':'matched_numeric_stop' if hit else 'no_distinct_qualifying_stop' if status=='failed' else 'log_metadata_or_initial_pose_missing',
                     'candidate_count':len(options[uid])})
    # For route-order diagnostics use any valid distinct chronology, not the
    # arbitrary maximum matching selected for independent partial progress.
    ordered=[]; previous=-1; used=set()
    for u in units:
        candidates=[x for x in options[u['id']] if x['order']>previous and x['stop_id'] not in used]
        if not candidates: break
        c=min(candidates,key=lambda x:x['order']);previous=c['order'];used.add(c['stop_id']);ordered.append(u['id'])
    return {'units':rows,'metadata_complete':complete,'phase_evidence':reason,
            'ordered_outbound_units':ordered,'ordered_outbound_complete':len(ordered)==len(units),
            'order_affects_independent_progress':False,'images_opened':0,
            'meaning':'Reference-position coverage, stopping and delivered observation metadata; no scene-content recognition.'}