"""Private deterministic grading runtime. Never emit a task reward for grader errors.""" import json,math,shutil,subprocess,hashlib from pathlib import Path class VerifierInfrastructureError(RuntimeError):pass def preflight(assets,access): for command in ['ffmpeg','ffprobe','filmcraft-cli','fc-match']: if not shutil.which(command):raise VerifierInfrastructureError('Required grading tool missing: '+command) for package in ['numpy','PIL']: try:__import__(package) except ImportError as e:raise VerifierInfrastructureError('Required grading dependency missing: '+package) from e trace=assets/'operator-trajectory.json' if not trace.is_file():raise VerifierInfrastructureError('Private operator trajectory missing') data=json.loads(trace.read_text()) if not isinstance(data.get('steps'),list):raise VerifierInfrastructureError('Invalid private trajectory schema') if access=='gui': try:__import__('cv2') except ImportError as e:raise VerifierInfrastructureError('Required GUI grading dependency missing: cv2') from e if not shutil.which('tesseract'):raise VerifierInfrastructureError('Required GUI grading tool missing: tesseract') missing=[] for step in data['steps']: for result in step.get('observation',{}).get('results',[]): for part in result.get('content',[]): if part.get('type')=='image' and part.get('source',{}).get('path'): name=Path(part['source']['path']).name if not (assets/'operator-screenshots'/name).is_file():missing.append(name) if missing:raise VerifierInfrastructureError('Missing private delivered screenshots: '+', '.join(sorted(set(missing))[:10])) ready=assets/'operator-evidence-ready.json' if ready.exists(): declared=json.loads(ready.read_text()) if declared.get('trajectory_sha256')!=hashlib.sha256(trace.read_bytes()).hexdigest() or not declared.get('screenshots_complete'):raise VerifierInfrastructureError('Private evidence ready marker does not match supplied trajectory') return {'trajectory_sha256':hashlib.sha256(trace.read_bytes()).hexdigest(),'access':access} def validate_report(result): total=earned=0 for key,row in result['rubric'].items(): weights=sum(c['possible'] for c in row['checks']) if not math.isclose(weights,row['possible'],abs_tol=1e-5):raise VerifierInfrastructureError('Rubric weight mismatch: '+key) for c in row['checks']: if c['state'] not in ['met','unmet']:raise VerifierInfrastructureError('Unresolved weighted criterion: '+key+'/'+c['id']) if not str(c.get('evidence','')).strip():raise VerifierInfrastructureError('Missing check evidence: '+key+'/'+c['id']) points=sum(c['possible'] for c in row['checks'] if c['state']=='met') if not math.isclose(points,row['earned'],abs_tol=1e-5):raise VerifierInfrastructureError('Earned points mismatch: '+key) total+=row['possible'];earned+=points if not math.isclose(total,100,abs_tol=1e-5) or not math.isclose(earned,result['resolved_score'],abs_tol=1e-5):raise VerifierInfrastructureError('Score/weight total mismatch') if result.get('unresolved_points')!=0:raise VerifierInfrastructureError('Final reward cannot contain unresolved weighted checks') return result def select_project(required): if required.is_file():return required # Exact stem without the app suffix is a filename error, not absent editing work. alternate=required.with_suffix('') if alternate.is_file(): try: if json.loads(alternate.read_text()).get('format')=='filmcraft.project':return alternate except (ValueError,OSError):pass return required def cli_main(evaluate,default_assets): import argparse p=argparse.ArgumentParser();p.add_argument('--workspace',type=Path,required=True);p.add_argument('--report-dir',type=Path,required=True);p.add_argument('--assets',type=Path,default=default_assets);p.add_argument('--access',choices=['gui','terminal']);a=p.parse_args();a.report_dir.mkdir(parents=True,exist_ok=True) for name in ['reward.json','reward.txt','infrastructure-error.json']:(a.report_dir/name).unlink(missing_ok=True) try: access=a.access or json.loads((a.assets/'access.json').read_text())['access'];receipt=preflight(a.assets,access) result=validate_report(evaluate(a.workspace,a.report_dir,a.assets,access));result['grading_runtime']={'version':'20261016.2',**receipt} (a.report_dir/'rubric.json').write_text(json.dumps(result,indent=2)+'\n') (a.report_dir/'reward.json').write_text(json.dumps({'reward':result['resolved_score']/100,'score_points':result['resolved_score'],'unresolved_points':0})+'\n') print(json.dumps({'score_range':result['score_range'],'policy':result.get('policy')})) except Exception as e: for name in ['reward.json','reward.txt']:(a.report_dir/name).unlink(missing_ok=True) (a.report_dir/'infrastructure-error.json').write_text(json.dumps({'classification':'verifier_error','error_type':type(e).__name__,'error':str(e),'task_reward_published':False},indent=2)) raise