#!/usr/bin/env python3 """Run tutorial verifier diagnostics on frozen submissions. A complete grade writes reward.txt. An unresolved grade writes explicit bounds and no scalar. Installing the pilot alongside the old grader preserves reward. """ import argparse import importlib import json import subprocess import sys from pathlib import Path from artifacts import freeze from media import probe, sha256 from report import summarize, write from tasks.engine import load_rubric ALLOWED = {'t19'} | {f't{i}' for i in range(44, 53)} def native_observation(project, inspector=None, output=None): if not Path(project).is_file(): return {'status': 'missing', 'editable': False, 'assets_resolved': False, 'capabilities': {}, 'reason': 'Required native project missing'} if inspector: # Inspector is a verifier-owned executable; no shell interpretation. try: if Path(output).exists(): Path(output).unlink() process = subprocess.run([str(inspector), '--project', str(project), '--output', str(output)], capture_output=True, text=True, timeout=300) if not Path(output).is_file(): return {'status': 'verifier_error', 'capabilities': {}, 'reason': process.stderr[-2000:] or 'Inspector produced no JSON'} from native_bridge import normalize dump=json.loads(Path(output).read_text()) dump['inspector_exit_code']=process.returncode result = normalize(dump, Path(output).parent) if process.returncode: result['inspection_error'] = process.stderr[-2000:] or 'Inspector incomplete or failed' return result except (OSError, ValueError, subprocess.TimeoutExpired) as exc: diagnostic={'status':'verifier_error','capabilities':{},'reason':str(exc)} if output is not None: Path(output).write_text(json.dumps(diagnostic,indent=2)+'\n') return diagnostic # Header parsing is useful evidence; never equivalent to a complete load. sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from inspect_header import inspect, InspectionError try: data = inspect(Path(project).read_bytes()) return {'status': 'unsupported', 'capabilities': data['capabilities'], 'scenes': data['scenes'], 'header': data, 'reason': 'Only scene header inspected; full loader unavailable'} except InspectionError as exc: return {'status': 'unsupported', 'capabilities': {}, 'reason': str(exc)} def run(task_id, project, desktop, out, reference=None, inspector=None): task_id = task_id.split('/')[-1].split('-')[0] if task_id not in ALLOWED: raise ValueError('Only the ten authorized tasks may use this verifier; t18 is protected') rubric = load_rubric(task_id) contract = rubric['contract'] videos = {f'video-{i}': Path(desktop) / name for i, name in enumerate(contract['videos'])} out = Path(out) manifest = freeze(project, videos, out / 'submission') native_entry = manifest[0] native = native_observation(native_entry.get('path', project), inspector, out / 'native.json') media_files = [probe(row.get('path', videos[row['role']])) for row in manifest[1:]] media = dict(media_files[0]) if media_files else {'decoded': False, 'status': 'missing'} media.update(files=media_files, exports=media_files, filenames=[Path(v).name for v in videos.values()]) observations = {'native': native, 'media': media, 'metrics': {}, 'project_present': native_entry['status'] == 'ok'} reference_data = json.loads(Path(reference).read_text()) if reference else {} # Map each export to a declared native scene; never choose the best scene. scene_map = reference_data.get('scene_exports', {}) if reference_data.get('single_scene_mapping') and len(native.get('scenes',[]))!=1: scene_map={} observations['scene_mapping_error']='Single-scene contract cannot identify an export among multiple scenes' if native.get('status') == 'loaded' and scene_map: from render_match import compare scene_list = native.get('scenes', []) scenes = {s['id']: s for s in scene_list} observations['render_comparisons'] = {} for name, scene_id in scene_map.items(): # Reference packages use an explicit zero-based scene index; the # inspector emits stable string IDs. Resolve either representation. if isinstance(scene_id, int) and not isinstance(scene_id, bool): scene_id = scene_list[scene_id]['id'] if 0 <= scene_id < len(scene_list) else None matching = [m for m in media_files if Path(m['path']).name == name] if matching and scene_id in scenes: comparison = compare(matching[0]['path'], scenes[scene_id], out) observations['render_comparisons'][name] = comparison comparisons = list(observations['render_comparisons'].values()) calibrated = reference_data.get('render_correspondence', {}) if comparisons and all(c.get('status') == 'measured' for c in comparisons): error = max(c['maximum_frame_error'] for c in comparisons) observations['metrics']['render_correspondence'] = {'maximum_frame_error': error} if calibrated.get('validated') is True and isinstance(calibrated.get('maximum_frame_error'), (int, float)): media['project_match'] = error <= calibrated['maximum_frame_error'] # Dense feature extraction is optional only when adapter lacks an extractor. module = importlib.import_module(f'tasks.{task_id}') if hasattr(module, 'collect'): observations = module.collect(observations, reference_data) else: from metrics import collect_observations observations = collect_observations(task_id, observations, reference_data) checks_result = module.evaluate(task_id, observations, reference_data) checks = checks_result.get('criteria', checks_result.get('checks')) result = summarize(task_id, checks, {'rubric_version': rubric['version'], 'rubric_sha256': sha256(Path(__file__).parent / 'rubrics' / f'{task_id}.json'), 'submission': manifest, 'reference_sha256': sha256(reference) if reference else None, 'mode': 'pilot', 'native_inspector_available': bool(inspector)}) stored=dict(observations) stored['native']={k:v for k,v in native.items() if k!='scenes'} stored['native']['evidence_json']=str(out/'native.json') stored['native']['scenes']=[{k:v for k,v in scene.items() if k not in ('frames','structure')} | {'frame_count':len(scene.get('frames',[]))} for scene in native.get('scenes',[])] (out / 'observations.json').write_text(json.dumps(stored, indent=2) + '\n') write(result, out) return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--task', required=True) parser.add_argument('--project', type=Path, default=Path('/root/edit/project.friction')) parser.add_argument('--desktop', type=Path, default=Path('/root/Desktop')) parser.add_argument('--out', type=Path, required=True) parser.add_argument('--reference', type=Path) parser.add_argument('--inspector', type=Path) args = parser.parse_args() result = run(args.task, args.project, args.desktop, args.out, args.reference, args.inspector) print(json.dumps({k: result[k] for k in ('task_id', 'status', 'score', 'score_bounds', 'assessed_weight')}, indent=2)) if __name__ == '__main__': main()