"""Recorded evidence extraction and independent progress predicates.""" import bisect import copy import datetime import json import math from pathlib import Path import progress_scoring as fair import route_numeric import return_endpoint import task_scoring import grounded_constraint_route as grounded NORMAL = {"success", "max_steps_exceeded", "idle_no_tool_call"} def read(p):return json.loads(Path(p).read_text()) def jlines(p): if Path(p).exists(): with Path(p).open() as f: for i,line in enumerate(f): if line.strip(): yield i,json.loads(line) def xyz(p):return return_endpoint.valid_xyz(p) def stamp(value): try:return datetime.datetime.fromisoformat(value).replace(tzinfo=datetime.timezone.utc).timestamp() except (ValueError,TypeError):return None def compact(value): if isinstance(value,dict): return {k:compact(v) for k,v in value.items() if not (k=="acceptable_answers" and v==[value.get("expected_answer")])} if isinstance(value,list):return [compact(v) for v in value] return value def load_evidence(definition,row): a=Path(row["attempt"]);rpath=a/"result.json" partial=not rpath.exists() if not partial: r=read(rpath);assert r["task_id"]==definition["task_id"] else: assert row.get("evaluation_disposition")=="task_failure",("Missing result without declared terminal policy",row["task_id"]) events=[] for line,e in jlines(a/"agent_events.jsonl"): if e.get("phase")!="tool":continue event={k:e.get(k) for k in ["time","tool","args","success","output"]} event["data"]={};event["_agent_event_line"]=line;event["_metadata_partial"]=True if event["tool"] in {"talk_to_npc","report_to_npc"} and event["success"] is True: # Runtime messages use an NPC alias, a localized reply label, and the reply. prefix,sep,answer=(event.get("output") or "").partition(": ") alias,label_sep,label=prefix.rpartition(" ") reply_label=label.lower() in {"replies","reply"} or (len(label)==2 and all(not c.isascii() and c.isalpha() for c in label)) if sep and label_sep and alias and reply_label: event["data"]={"alias":alias,"response":{"alias":alias,"answer":answer},"parsed_server_reply_text":True} events.append(event) r={"task_id":definition["task_id"],"status":"api_input_limit_exceeded", "answer":"","tool_events":events,"llm_events":[]} raw=r.get("tool_events",[]);assert isinstance(raw,list) complete=(not partial and r.get("status") in NORMAL and not r.get("environment_error")) or partial samples=[];initial=None;offset=None;trajectory_count=0 for n,line in jlines(a/"trajectory.jsonl"): if initial is None:initial=line trajectory_count+=1;s=line.get("state") or {} if offset is None and stamp(s.get("updated_at")) is not None and isinstance(line.get("time"),(int,float)): offset=round((line["time"]-stamp(s["updated_at"]))/3600)*3600 if s.get("ready") is True and s.get("task_id")==definition["task_id"] and xyz(s.get("pose")): samples.append(dict(pose=s["pose"],time=line.get("time"),id=f"trajectory/{n}/state.pose")) def event_time(e): t=stamp(e.get("time"));return t+offset if t is not None and offset is not None else None for i,e in enumerate(raw): data=e.get("data") or {} post=data.get("after_settle") or {} pose=post.get("pose") if xyz(post.get("pose")) else data.get("after") if xyz(data.get("after")) else data.get("pose") if xyz(pose):samples.append(dict(pose=pose,time=data.get("pose_observed_at") or event_time(e),id=f"tool_events/{i}/actual_pose",index=i)) if e.get("tool")=="observe_sweep": for j,direction in enumerate(data.get("directions",[])): if xyz(direction.get("pose")):samples.append(dict(pose=direction["pose"],time=event_time(e),id=f"tool_events/{i}/directions/{j}/pose",index=i)) for i,e in enumerate(r.get("llm_events",[])): vi=e.get("visual_input") or {} if vi.get("provided") is True and xyz(vi.get("pose")): samples.append(dict(pose=vi["pose"],time=vi.get("observed_at"),id=f"llm_events/{i}/visual_input.pose")) finish_indices=[i for i,e in enumerate(raw) if e.get("tool")=="finish_task" and e.get("success") is True and not (e.get("data") or {}).get("finish_reflection")] cutoff=finish_indices[-1] if finish_indices else len(raw)-1 answer=r.get("answer") or "" answer_id="result.answer" if not answer and finish_indices: e=raw[finish_indices[-1]];answer=(e.get("args") or {}).get("summary") or e.get("output") or "";answer_id=f"tool_events/{finish_indices[-1]}" source=read(Path(definition["_source_path"]))["tasks"][0] known={"definition","log_end","result.answer"} brief=[] for i,e in enumerate(raw): data=e.get("data") or {};args=e.get("args") or {};tool=e.get("tool") item=dict(id=f"tool_events/{i}",index=i,tool=tool,success=e.get("success"),args=args,time=e.get("time"),epoch_time=event_time(e)) known.add(item["id"]) fields=["alias","point","label","pose","settled","distance","interaction_radius_cm","height_tolerance_cm","height_difference_cm", "station","profile","pose_observed_at","finished","finish_reflection","mode","navigation_mode","blocked_by_task_profile"] item["data"]={k:data[k] for k in fields if k in data} if isinstance(data.get("response"),dict):item["data"]["response"]={k:data["response"].get(k) for k in ["alias","answer","question"]} if tool=="cross_nearby_door": item["data"].update({k:data.get(k) for k in ["ok","executed","plan","before","after","arrival_tolerance_cm"]}) if tool in {"talk_to_npc","report_to_npc","go_to","finish_task","confirm_station","cross_nearby_door"}: if e.get("_metadata_partial"):item["returned_text"]=e.get("output") if tool in {"observation","observe_sweep"}: item["returned_text"]=e.get("output") brief.append(item) return dict(result=r,attempt=a,partial=partial,complete=complete,raw=raw,cutoff=cutoff,answer=answer,answer_id=answer_id, samples=samples,initial=initial,offset=offset,source=source,known=known,brief=brief,trajectory_count=trajectory_count) def interactions(ev,target,tool=None): return [(i,e) for i,e in enumerate(ev["raw"][:ev["cutoff"]+1]) if e.get("success") is True and e.get("tool") in ({tool} if tool else {"talk_to_npc","report_to_npc"}) and (e.get("data") or {}).get("alias")==target and isinstance((e.get("data") or {}).get("response"),dict) and (e["data"]["response"].get("alias",target)==target)] def final_text(ev,params): spec=params.get("final_evidence_source") or {} channel=spec.get("channel",params.get("channel","answer")) if channel in {"answer","final_answer"}:return ev["answer"],[ev["answer_id"]] if ev["answer"] else [],None target=spec.get("target",params.get("target")) hits=interactions(ev,target,"report_to_npc") if not hits:return "",[],None i,e=hits[-1];return (e.get("args") or {}).get("message") or "",[f"tool_events/{i}"],i def outcome(status,ids,reason,**details): return dict(status=status,evidence_ids=ids,reason=reason,**details) def negative(ev,reason,uncertain=False): return outcome("evidence_insufficient" if uncertain or not ev["complete"] else "failed", [] if uncertain else ["log_end"],reason) def find_check(task,kind): for unit in task.get("evaluator",{}).get("evaluation_units",[]): check=unit.get("check",{}) if check.get("type")==kind:return check return {} def first_interaction(ev,target): hits=interactions(ev,target,"talk_to_npc");return hits[0][0] if hits else None def phase_bounds(unit,definition,ev): p=unit["parameters"];phase=p.get("phase",p.get("instruction_phase")) check=find_check(ev["source"],"instruction_revision") aliases=[u.get("parameters",{}).get("target") for u in definition["milestones"] if u["unit_type"]=="A"] issuer=check.get("issuer") or p.get("after_actual_instruction_from") if not issuer and aliases:issuer=aliases[0] start=first_interaction(ev,issuer) if issuer else None update=first_interaction(ev,check.get("update_issuer")) if check.get("update_issuer") else None if phase in {"after_initial_before_first_update","before_update"}: return start,update if update is not None else math.inf,start is not None if phase in {"after_first_update","after_update"}: return update,math.inf,update is not None if phase=="any_after_initial" or p.get("after_actual_instruction_from"): return start,math.inf,start is not None if unit["unit_type"]=="C" and not p.get("action") and definition["task_type"] in {"multi_stage_route","instruction_revision"}: return start,math.inf,start is not None return -1,math.inf,True def deterministic(definition,ev): fixed={};occurrences={};pending=[];candidates={};used_doors=set() endpoint_units=[u for u in definition["milestones"] if u.get("parameters",{}).get("action")=="return_endpoint"] numeric=None if endpoint_units: r=copy.copy(ev["result"]);r["route_initial_sample"]=ev["initial"] if not ev["partial"]: numeric=route_numeric.evaluate_outbound(definition,r,ev["initial"]) endpoint=endpoint_units[0];p=endpoint["parameters"] verdict=return_endpoint.evaluate_route_return({"npc_target":p["npc_target"]},r,ev["source"],None) status="evidence_insufficient" if verdict.detail.get("evidence_missing") else "completed" if verdict.complete else "failed" if ev["partial"] and ev["complete"] and not any(e.get("tool")=="finish_task" and e.get("success") is True for e in ev["raw"]): status="failed" verdict.detail.update(evidence_missing=False,reason="Declared terminal image-limit task failure with complete tool log and no successful finish_task; absence is proven, not missing terminal evidence",terminal_policy="task_failure") fixed[endpoint["id"]]=outcome(status,["return_endpoint"] if status=="completed" else ["log_end"],verdict.detail.get("reason"),detail=verdict.detail) ev["known"].add("return_endpoint") if verdict.detail.get("finish_event") is not None:occurrences[endpoint["id"]]=[verdict.detail["finish_event"]] if numeric: for x in numeric["units"]: evidence=(x.get("evidence") or {}).get("evidence_ids",[]) fixed[x["unit_id"]]=outcome(x["status"],evidence,x["reason"],detail=x) ev["known"].update(evidence) if x.get("evidence"):occurrences[x["unit_id"]]=[x["evidence"]["order"]/10-0.5] else: for u in definition["milestones"]: if u["parameters"].get("action")=="numeric_route_stop":fixed[u["id"]]=negative(ev,"Structured route metadata absent in terminal image-limit log",True) for u in definition["milestones"]: uid=u["id"];p=u["parameters"];kind=u["unit_type"];action=p.get("action") if uid in fixed:continue if kind=="A": hits=interactions(ev,p.get("target"),"talk_to_npc") occurrences[uid]=[i for i,_ in hits] if not hits: uncertain=any(e.get("success") is True and e.get("tool")=="talk_to_npc" and not (e.get("data") or {}).get("alias") for e in ev["raw"]) fixed[uid]=negative(ev,"No successful returned reply from the required source",uncertain);continue expected=p.get("expected_response") exact=[(i,e) for i,e in hits if expected and (e["data"]["response"].get("answer") or "").strip()==expected.strip()] if exact: i,e=exact[0];fixed[uid]=outcome("completed",[f"tool_events/{i}"],"Successful server-resolved source returned the complete expected response") else: pending.append(u);candidates[uid]=dict(replies=[{"evidence_id":f"tool_events/{i}","alias":e["data"]["alias"],"answer":e["data"]["response"].get("answer")} for i,e in hits]) elif kind in {"B","D","E"}: text,ids,index=final_text(ev,p) if kind=="E" and not p.get("final_evidence_source") and p.get("channel")=="report_to_npc": hits=interactions(ev,p.get("target"),"report_to_npc") occurrences[uid]=[i for i,_ in hits] elif index is not None:occurrences[uid]=[index] else:occurrences[uid]=[ev["cutoff"]+1] if text else [] candidates[uid]=dict(text=text,evidence_ids=ids,selector=p.get("final_evidence_source") or {"channel":p.get("channel","answer")},one_selected_message=True) if not text:fixed[uid]=negative(ev,"Required final output channel is absent in the recorded episode") else:pending.append(u) elif kind=="C": if action=="visit_inspection_site": lower,upper,phase_ok=phase_bounds(u,definition,ev) after_time=None if lower is not None and lower>=0 and ev["offset"] is not None: wall=stamp(ev["raw"][lower].get("time"));after_time=wall+ev["offset"] if wall is not None else None if not phase_ok:fixed[uid]=negative(ev,"Required actual instruction was not received");continue hits=[] for sample in ev["samples"]: if p.get("after_actual_instruction_from"): if "index" in sample: if sample["index"]<=lower:continue elif after_time is None or sample.get("time") is None or sample["time"]<=after_time:continue if math.dist(sample["pose"][:2],p["location"][:2])<=p["horizontal_radius_cm"] and abs(sample["pose"][2]-p["location"][2])<=p["height_tolerance_cm"]: hits.append(sample) if hits: hits.sort(key=lambda x:x.get("time") or 0) h=hits[0];ev["known"].add(h["id"]) fixed[uid]=outcome("completed",[h["id"]],"Actual recorded position covers the reference region",pose=h["pose"],time=h.get("time")) event_times=[stamp(e.get("time"))+ev["offset"] for e in ev["raw"] if stamp(e.get("time")) is not None] if ev["offset"] is not None else [] orders=set() for hit in hits: order=hit.get("index") if order is None and hit.get("time") is not None and len(event_times)==len(ev["raw"]): order=bisect.bisect_right(event_times,hit["time"])-0.5 if order is not None:orders.add(order) occurrences[uid]=sorted(orders) else:fixed[uid]=negative(ev,"No recorded actual position in reference region",not ev["samples"]) elif action=="confirm_station": hits=[];uncertain=False for i,e in enumerate(ev["raw"][:ev["cutoff"]+1]): data=e.get("data") or {} if e.get("tool")!="confirm_station" or e.get("success") is not True:continue if data.get("station")!=p.get("claimed_station",p["target"]):continue if not xyz(data.get("pose")) or data.get("settled") is not True: uncertain=True;continue if data.get("profile")!="constraint_route_v2" or data.get("station")!=(e.get("args") or {}).get("station"):continue geometry=p["geometry"];metric={"arrival_radius_cm":p["arrival_radius_cm"],"height_tolerance_cm":p["height_tolerance_cm"]} if grounded.station_inside(data["pose"],geometry,metric):hits.append(i) occurrences[uid]=hits fixed[uid]=outcome("completed",[f"tool_events/{hits[0]}"],"Settled station confirmation satisfies the specified union-of-regions geometry") if hits else negative(ev,"No geometrically valid settled station confirmation",uncertain) elif action=="cross_door": hits=[];uncertain=False for i,e in enumerate(ev["raw"][:ev["cutoff"]+1]): if e.get("tool")!="cross_nearby_door" or e.get("success") is not True:continue event={"index":i,"data":e.get("data") or {}} crossing=task_scoring.verified_crossing(event) if crossing is None:uncertain=True;continue if crossing["pair_id"]==p["door_pair"] and crossing["source_side"]==p["source_side"]:hits.append(i) distinct=[i for i in hits if i not in used_doors] occurrences[uid]=hits if distinct: i=distinct[0];used_doors.add(i);fixed[uid]=outcome("completed",[f"tool_events/{i}"],"Verified distinct executed door transaction has correct pair, source side and measured endpoints") else:fixed[uid]=negative(ev,"No distinct verified crossing for required door and direction",uncertain) else: # Registered visits require successful map registration and an actual pose. lower,upper,ok=phase_bounds(u,definition,ev) hits=[];uncertain=False if ok: for i,e in enumerate(ev["raw"][:ev["cutoff"]+1]): if not (lower