"""Score completed scene_recorder episodes with the released SR and GcS contracts.""" import argparse import copy import json import os from pathlib import Path import shlex from aggregate import aggregate from common import ROOT, canonical_id, definitions, digest, read, write import progress_judge as progress import progress_scoring import task_scoring def load_config(path): env = dict(os.environ) if path: for line in path.read_text().splitlines(): line = line.strip() if not line or line.startswith('#'): continue if line.startswith('export '): line = line[7:] key, sep, value = line.partition('=') if not sep: raise ValueError('Invalid configuration line') tokens = shlex.split(value, comments=True) env[key.strip()] = ' '.join(tokens) return env def judge_config(env): required = ['SCENE_RECORDER_EVAL_API_KEY', 'SCENE_RECORDER_EVAL_API_BASE', 'SCENE_RECORDER_EVAL_LLM_MODEL'] if any(not env.get(k) for k in required): raise ValueError('Configure SCENE_RECORDER_EVAL_API_KEY, SCENE_RECORDER_EVAL_API_BASE, and SCENE_RECORDER_EVAL_LLM_MODEL') return dict(model=env[required[2]], api_base=env[required[1]], api_key=env[required[0]], timeout=float(env.get('SCENE_RECORDER_EVAL_TIMEOUT', '300')), max_tokens=int(env.get('SCENE_RECORDER_EVAL_MAX_TOKENS', '8192')), temperature=0, min_confidence=0.7, trust_env_proxy=False) class EpisodeJudge: def __init__(self, config): self.config = config self.sr = None def client(self): if self.sr is None: self.sr = task_scoring.SemanticJudge(**self.config) return self.sr def judge(self, **kwargs): return self.client().judge(**kwargs) def close(self): if self.sr is not None: self.sr.client.close() def evaluate_progress(definition, episode, judge): d = copy.deepcopy(definition) # Match recorded IDs without changing the trajectory or its event references. d['task_id'] = read(episode / 'result.json')['task_id'] d['_source_path'] = str(ROOT / 'data' / (definition['task_id'] + '.json')) ev = progress.load_evidence(d, {'attempt': str(episode)}) fixed, pending, candidates, occurrences, numeric = progress.deterministic(d, ev) review = {'units': []} if pending: context = progress.context(d, ev, fixed, pending, candidates, occurrences, numeric) error = None for attempt in range(3): messages = [{'role': 'system', 'content': progress.SYSTEM}, {'role': 'user', 'content': json.dumps(context, ensure_ascii=False)}] if error: messages.append({'role': 'user', 'content': 'Correct the rejected JSON review: ' + error}) try: response = judge.client().client.chat.completions.create( model=judge.config['model'], messages=messages, temperature=0, max_tokens=judge.config['max_tokens'], response_format={'type': 'json_object'}, extra_body={'enable_thinking': False}) if response.choices[0].finish_reason == 'length': raise ValueError('Judge response exceeded output budget') parsed = json.loads(response.choices[0].message.content or '') requested = {u['id'] for u in pending} extra = {u['id'] for u in parsed['units']} - requested if not extra <= set(fixed): raise ValueError('Unrecognized unit IDs in review') parsed['units'] = [u for u in parsed['units'] if u['id'] in requested] review = progress.validate(parsed, pending, ev) break except (ValueError, KeyError, AssertionError, TypeError) as exc: error = str(exc) else: raise ValueError('Semantic review validation failed: ' + str(error)) units = {k: v['status'] for k, v in fixed.items()} by_id = {u['id']: u for u in review['units']} for unit in pending: units[unit['id']] = progress_scoring.reduce_predicates(unit['unit_type'], by_id[unit['id']]['predicates']) summary = progress_scoring.summarize_task(definition, units) return dict(units=units, progress=summary['progress'], progress_evidence=dict(deterministic=fixed, semantic=review)) def check_snapshot(episode, tid): snapshot = read(episode / 'task.json') current = read(ROOT / 'data' / (tid + '.json')) task = snapshot['tasks'][0] if len(snapshot['tasks']) != 1 or canonical_id(task['task_id']) != tid: raise ValueError('Episode task snapshot does not match the selected task') if snapshot['env_id'] != current['env_id']: raise ValueError('Episode environment differs from the released task') # Task IDs and authoring metadata were normalized for release. # All instructions, visibility, NPC behavior and route obligations must match. for key in ['language', 'agent_input', 'start', 'environment_setup', 'npc_setup', 'subtasks', 'dynamic_instruction']: if task.get(key) != current['tasks'][0].get(key): raise ValueError('Episode task content differs in ' + key) if snapshot.get('npc_appearance_catalog') != current.get('npc_appearance_catalog'): def without_evidence(items): return [{k: v for k, v in item.items() if k != 'evidence_image'} for item in items or []] if without_evidence(snapshot.get('npc_appearance_catalog')) != without_evidence(current.get('npc_appearance_catalog')): raise ValueError('Episode NPC appearances differ from the released task') def sr_errors(value): if isinstance(value, dict): if value.get('error_type') or value.get('evidence_missing') is True: return True if value.get('valid_complete_boolean') is False or value.get('valid_confidence_range') is False: return True return any(sr_errors(v) for v in value.values()) if isinstance(value, list): return any(sr_errors(v) for v in value) return False def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--episodes', type=Path, required=True, help='One model run or a single episode directory.') parser.add_argument('--output', type=Path, required=True) parser.add_argument('--env-file', type=Path) parser.add_argument('--mode', choices=['sr', 'gcs', 'both'], default='both') parser.add_argument('--task-id', action='append') parser.add_argument('--sr-scores', type=Path, help='Reuse audited SR from an existing rows/score.task_success summary.') parser.add_argument('--resume', action='store_true', help='Reuse results only when inputs and judge settings match.') args = parser.parse_args() if not args.episodes.is_dir(): parser.error('--episodes must be an existing directory') defs = definitions() selected = set(defs) if not args.task_id else {canonical_id(t) for t in args.task_id} results = {} for path in args.episodes.rglob('result.json'): raw = read(path) tid = canonical_id(raw.get('task_id')) if tid not in selected: continue if tid not in results or path.stat().st_mtime_ns > results[tid].stat().st_mtime_ns: results[tid] = path config = judge_config(load_config(args.env_file)) judge = EpisodeJudge(config) original_sr = {} if args.sr_scores: data = read(args.sr_scores) for row in data['rows'] if isinstance(data, dict) else data: tid = canonical_id(row['task_id']) value = row.get('task_success', (row.get('score') or {}).get('task_success')) if isinstance(value, bool) and (not row.get('runtime_error') or row.get('evaluation_disposition') == 'task_failure'): if tid in original_sr: raise ValueError('Duplicate imported task success: ' + tid) original_sr[tid] = value cached = {} if args.resume and args.output.exists(): cached = {r['task_id']: r for r in read(args.output)['rows']} rows = [] for tid in sorted((set(original_sr) & selected) - set(results)): rows.append(dict(task_id=tid, task_success=original_sr[tid], units={}, error='Recorded episode missing; only audited SR is available')) try: for tid in sorted(results): path = results[tid] signature = dict(task=digest(ROOT / 'data' / (tid + '.json')), definition=digest(ROOT / 'subtasks' / (tid + '.json')), inputs={p.name: digest(p) for p in [path, path.with_name('task.json'), path.with_name('trajectory.jsonl')] if p.exists()}, implementation={p.name: digest(p) for p in Path(__file__).parent.glob('*.py')}, judge={k: v for k, v in config.items() if k != 'api_key'}, mode=args.mode, imported_task_success=original_sr.get(tid)) if tid in cached and cached[tid].get('signature') == signature and not cached[tid].get('error'): rows.append(cached[tid]) continue row = dict(task_id=tid, signature=signature, task_success=original_sr.get(tid), units={}) try: check_snapshot(path.parent, tid) raw = read(path) if raw.get('status') not in progress.NORMAL or raw.get('environment_error'): raise ValueError('Episode is incomplete or has an execution error') if args.mode in {'sr', 'both'} and tid not in original_sr: task = read(ROOT / 'data' / (tid + '.json'))['tasks'][0] score = task_scoring.score_task(task, path, judge) row['score'] = score if score['configuration_errors'] or sr_errors(score): raise ValueError('Task scoring lacks required evidence or a judge request failed') row['task_success'] = score['task_success'] if args.mode in {'gcs', 'both'}: row.update(evaluate_progress(defs[tid], path.parent, judge)) except Exception as exc: # API failures remain unscored; they never become task failures. row['error'] = type(exc).__name__ + ': ' + str(exc)[:500] rows.append(row) report = aggregate(rows, selected) report['rows'] = rows write(args.output, report) print(json.dumps(dict(task_id=tid, task_success=row['task_success'], progress=row.get('progress'), error=row.get('error')), ensure_ascii=False), flush=True) finally: judge.close() report = aggregate(rows, selected) report['rows'] = rows write(args.output, report) print(json.dumps(report['summary'], indent=2)) if __name__ == '__main__': main()