from __future__ import annotations import hashlib import json import os import re import shlex import shutil import subprocess import sys import uuid from pathlib import Path from typing import Any import yaml # type: ignore[import-untyped] from PIL import Image, ImageDraw from packages.benchmark.portable import ( create_portable_bundle, create_zstd_archive, portable_source_fingerprint, refresh_checksums, verify_portable_bundle, ) from packages.core.files import atomic_write_text from packages.generative import GenerativeClient, RelaySettings from packages.supervisor.models import GateResult, IterationPolicy, QualityReport from packages.supervisor.visual_preflight import evaluate_visual_preflight def _json(path: Path) -> dict[str, Any]: value = json.loads(path.read_text(encoding="utf-8")) if not isinstance(value, dict): raise ValueError(f"expected JSON object: {path}") return value def _asset_ids(value: object) -> set[str]: found: set[str] = set() if isinstance(value, dict): asset_id = value.get("asset_id") if isinstance(asset_id, str): found.add(asset_id) for child in value.values(): found.update(_asset_ids(child)) elif isinstance(value, list): for child in value: found.update(_asset_ids(child)) return found def _global_critic_affected_entities(output: Path, valid_entity_ids: set[str]) -> list[str]: path = output / "scenesmith" / "agent_outputs" / "global-critic__scene.json" if not path.is_file(): return [] try: payload = _json(path) except (OSError, ValueError, json.JSONDecodeError): return [] directive = payload.get("repair_directive") or {} candidates = directive.get("entities") if isinstance(directive, dict) else [] return sorted( {str(entity_id) for entity_id in candidates or [] if str(entity_id) in valid_entity_ids} ) def _robot_release_gates(output: Path) -> list[GateResult]: """Require geometric and visual proof whenever a benchmark contains a robot.""" robot_path = output / "manifests" / "robot.json" if not robot_path.is_file(): return [] placement_path = output / "manifests" / "robot_placement_validation.json" placement = _json(placement_path) if placement_path.is_file() else {} placement_facts = { key: placement.get(key) for key in ( "passed", "footprint_inside_room", "wall_clearance_passed", "obstacle_clearance_passed", "source_approach_passed", "source_facing_passed", ) } placement_passed = placement_path.is_file() and all( value is True for value in placement_facts.values() ) preview_path = output / "scenesmith" / "preview_camera_manifest.json" preview = _json(preview_path) if preview_path.is_file() else {} shots = preview.get("shots") if isinstance(preview, dict) else [] required_shots = [ shot for shot in (shots if isinstance(shots, list) else []) if isinstance(shot, dict) and shot.get("required_robot_full_body") is True ] preview_passed = ( preview_path.is_file() and preview.get("passed") is True and preview.get("robot_detected") is True and bool(required_shots) and all( shot.get("passed") is True and shot.get("robot_full_body_visible") is True for shot in required_shots ) ) critic_path = output / "scenesmith" / "final_composed_critic_views" / "manifest.json" critic = _json(critic_path) if critic_path.is_file() else {} audit = critic.get("robot_visual_audit") if isinstance(critic, dict) else {} audit = audit if isinstance(audit, dict) else {} views = critic.get("views") if isinstance(critic, dict) else {} views = views if isinstance(views, dict) else {} robot_view = views.get("robot_access") resolved_robot_view = None if isinstance(robot_view, str) and robot_view: candidate = Path(robot_view) resolved_robot_view = candidate if candidate.is_absolute() else output / "scenesmith" / candidate critic_passed = ( critic_path.is_file() and audit.get("passed") is True and int(audit.get("detected_mesh_count") or 0) > 0 and audit.get("view_created") is True and resolved_robot_view is not None and resolved_robot_view.is_file() ) return [ GateResult( gate_id="robot_room_placement", passed=placement_passed, message=f"report_present={placement_path.is_file()} facts={placement_facts}", affected_entities=[] if placement_passed else ["robot"], evidence={"report": str(placement_path.relative_to(output))}, ), GateResult( gate_id="robot_preview_visibility", passed=preview_passed, message=( f"report_present={preview_path.is_file()} detected={preview.get('robot_detected')} " f"required_full_body_shots={len(required_shots)}" ), affected_entities=[] if preview_passed else ["robot"], evidence={"report": str(preview_path.relative_to(output))}, ), GateResult( gate_id="robot_global_critic_visibility", passed=critic_passed, message=( f"report_present={critic_path.is_file()} audit={audit} " f"robot_access_present={bool(resolved_robot_view and resolved_robot_view.is_file())}" ), affected_entities=[] if critic_passed else ["robot"], evidence={"report": str(critic_path.relative_to(output))}, ), ] def _usd_python_from_environment() -> str: configured = os.environ.get("RHG_USD_PYTHON", "").strip() if configured: return configured scenesmith_command = os.environ.get("SCENESMITH_COMMAND", "").strip() if scenesmith_command: return shlex.split(scenesmith_command)[0] data_root = os.environ.get("RHG_DATA_ROOT", "").strip() if data_root: candidate = Path(data_root) / "conda-envs/scenesmith-sam3d/bin/python" if candidate.is_file(): return str(candidate) return "" class QualityEvaluator: def __init__(self, policy: IterationPolicy) -> None: self.policy = policy self.config: dict[str, Any] = {} if policy.quality_policy and policy.quality_policy.is_file(): self.config = yaml.safe_load(policy.quality_policy.read_text(encoding="utf-8")) or {} def evaluate(self, output: Path) -> QualityReport: # Author the inexpensive manipulation schema first. Visual rejection is # evaluated before launching Isaac or portable extraction so an obviously # low-fidelity version cannot spend minutes in external validators. self._materialize_manipulation_physics(output) gates: list[GateResult] = [] agent_global_score: float | None = None required = [ "root.usda", "manifests/task.json", "manifests/scene.json", "manifests/episode.json", ] missing = [name for name in required if not (output / name).is_file()] gates.append( GateResult( gate_id="benchmark_contract", passed=not missing, message=f"missing={missing}" ) ) if missing: return self._report(gates, critic_passed=not self.policy.critic_required) task = _json(output / "manifests/task.json") scene = _json(output / "manifests/scene.json") expected = { str(item["entity_id"]) for item in task.get("entities", []) if isinstance(item, dict) and item.get("role") != "ROBOT" } bindings = scene.get("entity_prim_paths", {}) missing_entities = sorted(expected - set(bindings if isinstance(bindings, dict) else {})) duplicate_paths = [] if isinstance(bindings, dict): paths = [str(bindings[item]) for item in expected if item in bindings] duplicate_paths = sorted({path for path in paths if paths.count(path) > 1}) gates.append( GateResult( gate_id="entity_identity", passed=not missing_entities and not duplicate_paths, message=f"missing={missing_entities} duplicate_paths={duplicate_paths}", affected_entities=missing_entities, ) ) gates.extend(_robot_release_gates(output)) stage_path = output / "scenesmith" / "stage_manifest.json" if stage_path.is_file(): stage = _json(stage_path) gates.append( GateResult( gate_id="scenesmith_complete", passed=stage.get("status") == "complete", message=f"status={stage.get('status')}", ) ) graph_files = [ stage.get("scene_dependency_graph"), stage.get("dependency_execution_plan"), ] missing_graph = [ str(name) for name in graph_files if not isinstance(name, str) or not (stage_path.parent / name).is_file() ] gates.append( GateResult( gate_id="dependency_plan_saved", passed=not missing_graph, message=f"missing={missing_graph}", ) ) if stage.get("orchestration_mode") == "dag_agents": ledger_name = stage.get("agent_execution_ledger") ledger_path = stage_path.parent / str(ledger_name or "") ledger = _json(ledger_path) if ledger_name and ledger_path.is_file() else {} records = ledger.get("records") if isinstance(ledger, dict) else {} records = records if isinstance(records, dict) else {} incomplete = sorted( task_id for task_id, record in records.items() if not isinstance(record, dict) or record.get("status") not in {"complete", "reused"} ) global_record = records.get("global-critic:scene", {}) global_result = ( global_record.get("result", {}) if isinstance(global_record, dict) else {} ) global_score = ( global_result.get("critic_score") if isinstance(global_result, dict) else None ) if isinstance(global_score, (int, float)): agent_global_score = float(global_score) publish_gate_path = stage_path.parent / str( stage.get("global_critic_publish_gate") or "" ) publish_gate = ( _json(publish_gate_path) if stage.get("global_critic_publish_gate") and publish_gate_path.is_file() else {} ) # The in-worker global critic is preliminary because the robot # and outer benchmark layers do not exist yet. Release scoring # happens below from the shared final composed contact sheet. dag_passed = ( ledger.get("status") == "complete" and bool(records) and not incomplete and global_result.get("accepted") is True and global_result.get("hard_gates_passed") is True and publish_gate.get("passed") is True ) gates.append( GateResult( gate_id="agent_dag_execution", passed=dag_passed, message=( f"ledger_status={ledger.get('status')} incomplete={incomplete} " f"global_score={global_score} publish_gate={publish_gate.get('passed')}" ), metric=( float(global_score) if isinstance(global_score, (int, float)) else None ), threshold=self.policy.critic_min_score, affected_entities=( [] if dag_passed else _global_critic_affected_entities(output, expected) ), evidence={ "global_failure_signature": ( global_result.get("failure_signature") if isinstance(global_result, dict) else None ) }, ) ) native = stage.get("native_asset_bindings", {}) effective_path = output / "scenesmith" / "effective_selected_assets.json" selected_path = output / "scenesmith" / "selected_assets.json" selected_payload = ( _json(effective_path if effective_path.is_file() else selected_path) if (effective_path.is_file() or selected_path.is_file()) else {} ) selected_ids = _asset_ids(selected_payload) if selected_payload else set() native_ids = ( { str(binding["asset_id"]) for binding in native.values() if isinstance(binding, dict) and binding.get("binding_mode") != "embedded_generated" and isinstance(binding.get("asset_id"), str) } if isinstance(native, dict) else set() ) mismatched = sorted(native_ids - selected_ids) if selected_ids else sorted(native_ids) locked_assets = stage.get("task_asset_overrides", {}) wrong_locked_assets = ( sorted( entity for entity, expected_asset in locked_assets.items() if isinstance(native, dict) and ( not isinstance(native.get(entity), dict) or native[entity].get("binding_mode") == "embedded_generated" or native[entity].get("asset_id") != expected_asset ) ) if isinstance(locked_assets, dict) else [] ) missing_usd = ( sorted( entity for entity, binding in native.items() if isinstance(binding, dict) and ( not isinstance(binding.get("canonical_usd"), str) or not Path(str(binding["canonical_usd"])).is_file() ) ) if isinstance(native, dict) else [] ) gates.append( GateResult( gate_id="canonical_asset_identity", passed=not mismatched and not missing_usd and not wrong_locked_assets, message=( f"unselected_ids={mismatched} missing_usd={missing_usd} " f"wrong_locked_assets={wrong_locked_assets}" ), affected_entities=sorted(set(missing_usd + wrong_locked_assets)), ) ) indexed_task_entities = { str(entity_id) for entity_id, candidates in selected_payload.items() if str(entity_id) in expected and isinstance(candidates, list) and any( isinstance(candidate, dict) and candidate.get("asset_id") for candidate in candidates ) } embedded_indexed_entities = sorted( entity_id for entity_id in indexed_task_entities if not isinstance(native, dict) or not isinstance(native.get(entity_id), dict) or native[entity_id].get("binding_mode") == "embedded_generated" ) gates.append( GateResult( gate_id="indexed_task_asset_binding", passed=not embedded_indexed_entities, message=( "indexed_entities_without_explicit_native_binding=" f"{embedded_indexed_entities}" ), affected_entities=embedded_indexed_entities, ) ) preflight_gate = self._visual_preflight(output) gates.append(preflight_gate) if not preflight_gate.passed: return self._report(gates, critic_passed=False, critic_score=None) critic_passed, supervisor_critic_score = self._critic(output, task) critic_score = supervisor_critic_score supervisor_report_path = output / "supervisor/critic_report.json" supervisor_severe = [] if supervisor_report_path.is_file(): supervisor_result = _json(supervisor_report_path).get("result") or {} if isinstance(supervisor_result, dict): raw_severe = supervisor_result.get("severe_failures") or [] if isinstance(raw_severe, list): supervisor_severe = raw_severe if critic_score is None and agent_global_score is not None: # Preserve preliminary evidence only when final visual review is # disabled; it can never override a final composed-frame rejection. critic_score = agent_global_score if self.policy.critic_required or supervisor_critic_score is not None: shared_evidence = { "report": "scenesmith/final_global_critic_report.json", "shared_final_frames": True, } gates.append( GateResult( gate_id="final_global_visual_critic", passed=critic_passed, message=( f"score={supervisor_critic_score} threshold={self.policy.critic_min_score} " f"severe_failures={len(supervisor_severe)}" ), metric=supervisor_critic_score, threshold=self.policy.critic_min_score, evidence=shared_evidence, ) ) gates.append( GateResult( gate_id="supervisor_visual_critic", passed=critic_passed, message=( f"score={supervisor_critic_score} " f"required={self.policy.critic_required} " "reference_calibrated=" f"{(output / 'supervisor/critic_reference_manifest.json').is_file()} " "shared_final_frames=True " f"severe_failures={len(supervisor_severe)}" ), metric=supervisor_critic_score, threshold=self.policy.critic_min_score, evidence=shared_evidence, ) ) if not critic_passed: return self._report(gates, critic_passed=False, critic_score=critic_score) external_reports = self.config.get("external_reports", []) portable_reports = [ report_config for report_config in external_reports if str(report_config.get("gate_id")) == "portable_bundle_verification" or Path(str(report_config.get("path", ""))).name == "portable_validation.json" ] nonportable_reports = [ report_config for report_config in external_reports if report_config not in portable_reports ] self._materialize_validation_reports(output, include_portable=False) def append_report_gates(report_configs: list[dict[str, Any]]) -> None: for report_config in report_configs: path = output / str(report_config["path"]) required_report = bool(report_config.get("required", True)) payload = _json(path) if path.is_file() else {} passed = ( bool(payload.get(str(report_config.get("pass_field", "passed")))) if payload else not required_report ) gates.append( GateResult( gate_id=str(report_config["gate_id"]), passed=passed, message=f"report={path.relative_to(output)} present={path.is_file()}", ) ) append_report_gates(nonportable_reports) prepublish = self._report( gates, critic_passed=critic_passed, critic_score=critic_score, ) if not prepublish.accepted: return prepublish # The exact frames consumed by the final Critic are now accepted and all # scene/physics hard gates have passed. Only now may a release video exist. from packages.scene_generation.orchestrator import render_accepted_final_preview from packages.supervisor.snapshot import ensure_version_media if ( (output / "scenesmith/stage_manifest.json").is_file() and (output / "scenesmith/global_critic_publish_gate.json").is_file() ): render_accepted_final_preview( output, accepted=True, hard_gates_passed=True, critic_passed=True, ) ensure_version_media(output, force_snapshot=True) self._materialize_validation_reports( output, include_isaac=False, include_portable=True, ) append_report_gates(portable_reports) return self._report(gates, critic_passed=critic_passed, critic_score=critic_score) def _visual_preflight(self, output: Path) -> GateResult: config = self.config.get("visual_preflight") or {} config = config if isinstance(config, dict) else {} manifest_path = output / "scenesmith/final_composed_critic_views/manifest.json" manifest = _json(manifest_path) if manifest_path.is_file() else {} report = evaluate_visual_preflight(manifest, config) report_path = output / "supervisor/visual_preflight_report.json" atomic_write_text( report_path, json.dumps(report, ensure_ascii=False, indent=2) + "\n", ) return GateResult( gate_id="visual_preflight", passed=report["passed"], message=( f"required={report['required']} manifest_present={manifest_path.is_file()} " f"failures={report['failures']}" ), evidence={"report": str(report_path.relative_to(output))}, ) def _materialize_validation_reports( self, output: Path, *, include_isaac: bool = True, include_portable: bool = True, ) -> None: self._materialize_manipulation_physics(output) configured = { str(item.get("gate_id")): item for item in self.config.get("external_reports", []) } isaac = configured.get("isaac_physics_and_support") isaac_report = output / "manifests" / "isaac_validation.json" portable = configured.get("portable_bundle_verification") portable_report = output / "manifests" / "portable_validation.json" if ( include_isaac and isaac and bool(isaac.get("required", True)) and not isaac_report.is_file() ): self._run_isaac_validation(output, isaac_report) if include_portable and portable and bool(portable.get("required", True)): # A prior report does not prove that the bundle still matches the # source version. The validator performs a cheap source-fingerprint # comparison and atomically rebuilds only when evidence changed. self._run_portable_validation(output, portable_report) @staticmethod def _materialize_manipulation_physics(output: Path) -> None: task_path = output / "manifests/task.json" scene_path = output / "manifests/scene.json" root_path = output / "root.usda" report_path = output / "manifests/manipulation_physics.json" if report_path.is_file() or not all( path.is_file() for path in (task_path, scene_path, root_path) ): return task = _json(task_path) if not any( isinstance(entity, dict) and entity.get("role") == "MANIPULATED" for entity in task.get("entities", []) ): return executable = sys.executable try: import pxr # type: ignore[import-not-found] # noqa: F401 except ImportError: executable = os.environ.get("RHG_USD_PYTHON", "").strip() if not executable: scenesmith_command = os.environ.get("SCENESMITH_COMMAND", "").strip() executable = shlex.split(scenesmith_command)[0] if scenesmith_command else "" try: if not executable: raise RuntimeError("no USD-capable Python configured") script = Path(__file__).resolve().parents[2] / "scripts/author_manipulation_physics.py" command = [ *shlex.split(executable), str(script), "--root", str(root_path), "--task", str(task_path), "--scene", str(scene_path), "--report", str(report_path), ] result = subprocess.run(command, capture_output=True, text=True, check=False) if result.returncode: raise RuntimeError((result.stdout + result.stderr)[-4000:]) except Exception as error: atomic_write_text( report_path, json.dumps( { "schema_version": "1.0", "passed": False, "error": f"{type(error).__name__}: {error}", }, indent=2, ) + "\n", ) refresh_checksums(output) def _run_portable_validation(self, output: Path, report_path: Path) -> None: destination = output.parent / "packages" / output.name try: destination.parent.mkdir(parents=True, exist_ok=True) expected_fingerprint = portable_source_fingerprint(output) portable_manifest = destination / "portable_manifest.json" existing_fingerprint = ( str(_json(portable_manifest).get("source_fingerprint") or "") if portable_manifest.is_file() else "" ) portable_is_current = ( destination.is_dir() and existing_fingerprint == expected_fingerprint ) require_pxr = bool(self.config.get("portable_require_pxr", True)) usd_python = _usd_python_from_environment() try: import pxr # type: ignore[import-not-found] # noqa: F401 pxr_available = True except ImportError: pxr_available = False if require_pxr and not pxr_available and usd_python: archive = destination.with_suffix(".tar.zst") packager = ( Path(__file__).resolve().parents[2] / "scripts/package_portable_benchmark.py" ) command = [*shlex.split(usd_python), str(packager)] if destination.exists(): command.extend(["verify", "--bundle", str(destination), "--require-pxr"]) else: command.extend( [ "create", "--source", str(output), "--output", str(destination), ] ) if self.config.get("create_archive", True): command.extend(["--archive", str(archive)]) result = subprocess.run(command, capture_output=True, text=True, check=False) if result.returncode: raise RuntimeError((result.stdout + result.stderr)[-4000:]) payload = json.loads(result.stdout) report = payload.get("verification", payload) if archive.is_file(): report["archive"] = str(archive) else: rebuilt = False if not portable_is_current: token = uuid.uuid4().hex staging = destination.parent / f".{destination.name}.staging-{token}" backup = destination.parent / f".{destination.name}.backup-{token}" try: create_portable_bundle(output, staging) staging_report = verify_portable_bundle( staging, require_pxr=require_pxr ) if not staging_report.get("passed"): raise RuntimeError( "staged portable verification failed: " f"{staging_report.get('failures', [])}" ) if destination.exists(): destination.rename(backup) staging.rename(destination) except Exception: if backup.exists() and not destination.exists(): backup.rename(destination) raise finally: if staging.exists(): shutil.rmtree(staging) if backup.exists(): shutil.rmtree(backup) rebuilt = True report = verify_portable_bundle(destination, require_pxr=require_pxr) if report.get("passed") and self.config.get("create_archive", True): archive = destination.with_suffix(".tar.zst") if rebuilt or not archive.exists(): temporary_archive = archive.with_name(f".{archive.name}.tmp") temporary_archive.unlink(missing_ok=True) create_zstd_archive(destination, temporary_archive) temporary_archive.replace(archive) report["archive"] = str(archive) except Exception as error: report = { "schema_version": "1.0", "passed": False, "error": f"{type(error).__name__}: {error}", } atomic_write_text(report_path, json.dumps(report, ensure_ascii=False, indent=2) + "\n") @staticmethod def _run_isaac_validation(output: Path, report: Path) -> None: repository = Path(__file__).resolve().parents[2] validator = repository / "scripts" / "isaac_validate_benchmark.py" direct = os.environ.get("RHG_ISAAC_PYTHON", "").strip() if not direct: data_root = os.environ.get("RHG_DATA_ROOT", "").strip() local_candidates = [] if data_root: local_candidates.append( Path(data_root) / "conda-envs" / "isaacsim-6.0.1" / "bin" / "python3.12" ) direct = next( (str(candidate) for candidate in local_candidates if candidate.is_file()), "" ) settle_frames = os.environ.get("RHG_ISAAC_SETTLE_FRAMES", "180").strip() if not settle_frames.isdigit() or int(settle_frames) <= 0: raise ValueError("RHG_ISAAC_SETTLE_FRAMES must be a positive integer") if direct: command = [ *shlex.split(direct), str(validator), str(output / "root.usda"), "--report", str(report), "--settle-frames", settle_frames, ] report_root = None elif shutil.which("docker"): report_root = output / "supervisor" / "isaac_reports" cache_root = Path( os.environ.get( "RHG_ISAAC_CACHE_ROOT", str(output.parent.parent / ".cache" / "isaac-sim"), ) ) command = [ sys.executable, str(repository / "scripts" / "isaac_parallel_validate.py"), str(output / "root.usda"), "--scene-root", str(output), "--report-root", str(report_root), "--cache-root", str(cache_root), "--validator", str(validator), "--max-gpus", "1", "--settle-frames", settle_frames, "--image", os.environ.get("RHG_ISAAC_IMAGE", "wholebody-scene-mvp-v0-arena:latest"), ] else: atomic_write_text( report, json.dumps( { "schema_version": "1.0", "passed": False, "error": "neither RHG_ISAAC_PYTHON nor docker is available", }, indent=2, ) + "\n", ) return run_environment = os.environ.copy() run_environment.setdefault("OMNI_KIT_ACCEPT_EULA", "YES") if direct: isaac_executable = Path(shlex.split(direct)[0]).expanduser().resolve() isaac_library = isaac_executable.parent.parent / "lib" inherited_libraries = run_environment.get("LD_LIBRARY_PATH", "") run_environment["LD_LIBRARY_PATH"] = ( f"{isaac_library}:{inherited_libraries}" if inherited_libraries else str(isaac_library) ) configured_gpu = os.environ.get("RHG_ISAAC_GPU_ID", "").strip() if not configured_gpu: configured_gpu = os.environ.get("SCENESMITH_GPU_IDS", "").split(",", 1)[0].strip() if configured_gpu: run_environment["RHG_ISAAC_GPU_ID"] = configured_gpu # Kit's Vulkan device enumeration is independent of CUDA remapping; # mixing the two can make the configured physical index invalid. run_environment.pop("CUDA_VISIBLE_DEVICES", None) vulkan_icd = os.environ.get( "RHG_ISAAC_VULKAN_ICD", "/etc/vulkan/icd.d/nvidia_icd.json" ).strip() if vulkan_icd: run_environment["VK_ICD_FILENAMES"] = vulkan_icd try: result = subprocess.run( command, capture_output=True, text=True, timeout=int(os.environ.get("RHG_ISAAC_VALIDATION_TIMEOUT_S", "1800")), check=False, env=run_environment, ) except (OSError, subprocess.TimeoutExpired) as error: atomic_write_text( report, json.dumps( { "schema_version": "1.0", "passed": False, "error": f"{type(error).__name__}: {error}", }, indent=2, ) + "\n", ) return if report_root is not None and not report.is_file(): candidates = sorted( path for path in report_root.glob("*.json") if path.name != "parallel_validation_summary.json" ) if len(candidates) == 1: atomic_write_text(report, candidates[0].read_text(encoding="utf-8")) if result.returncode and not report.is_file(): atomic_write_text( report, json.dumps( { "schema_version": "1.0", "passed": False, "error": (result.stdout + result.stderr)[-4000:], }, indent=2, ) + "\n", ) def _critic(self, output: Path, task: dict[str, Any]) -> tuple[bool, float | None]: if not self.policy.critic_required: return True, None frame = self._critic_frame(output) if frame is None or not RelaySettings.status_from_env()["configured"]: return False, None rubric = self.config.get( "critic_prompt", "Inspect the final composed benchmark. Score geometry, physical plausibility, " "asset identity, task clarity, and visual quality from 0 to 10. Severe issues " "include floating objects, penetration, duplicated proxies, or wrong asset identity.", ) machine_evidence: dict[str, Any] = {} for name in ("manipulation_physics", "isaac_validation", "portable_validation"): report_path = output / "manifests" / f"{name}.json" if not report_path.is_file(): continue report = _json(report_path) evidence: dict[str, Any] = {"passed": report.get("passed")} if name == "manipulation_physics": evidence["entities"] = report.get("entities", {}) elif name == "isaac_validation": evidence["failed_checks"] = [ item.get("name") for item in report.get("checks", []) if isinstance(item, dict) and not item.get("passed") ] elif name == "portable_validation": evidence["manipulation_physics"] = (report.get("usd") or {}).get( "manipulation_physics", {} ) machine_evidence[name] = evidence stage_manifest_path = output / "scenesmith/stage_manifest.json" if stage_manifest_path.is_file(): stage_manifest = _json(stage_manifest_path) native_bindings = stage_manifest.get("native_asset_bindings") or {} if isinstance(native_bindings, dict): machine_evidence["locked_native_asset_bindings"] = { entity_id: { "asset_id": binding.get("asset_id"), "binding_mode": binding.get("binding_mode"), } for entity_id, binding in native_bindings.items() if isinstance(entity_id, str) and isinstance(binding, dict) } context_assets_path = output / "scenesmith/context_assets_config.json" if context_assets_path.is_file(): context_assets = _json(context_assets_path) support_placements = context_assets.get("task_support_placements") or {} if isinstance(support_placements, dict): machine_evidence["authored_support_placements"] = support_placements preflight_path = output / "supervisor/visual_preflight_report.json" if preflight_path.is_file(): preflight = _json(preflight_path) machine_evidence["final_visual_preflight"] = { "passed": preflight.get("passed"), "checks": { str(item.get("check_id")): { "passed": item.get("passed"), "evidence": item.get("evidence", {}), } for item in preflight.get("checks", []) if isinstance(item, dict) and item.get("check_id") }, } prompt = ( f"{rubric}\nTask: {task.get('natural_language', '')}\n" "The following physics, schema, and portability facts were independently " "machine-validated. Treat passing facts as established and review every labeled " "GENERATED view in the contact sheet. Generated panels are different camera views " "of the same single scene, not separate scenes or simultaneous duplicates: " "an object recurring in multiple quadrants is the same object instance. Never " "report duplicated proxies merely because the same asset is visible in more " "than one quadrant; duplication must be visible within one quadrant or proven " "by machine identity evidence. Do not penalize one view merely for not showing " "hidden schemas or the full action. When an exact native asset binding is " "machine-validated, score shape/detail fidelity against that requested asset " "identity; do not demand replacement by an unrelated higher-poly model. A " "neutral powered-off television screen is intentional and must not be treated " "as a missing texture. Authored support placements identify the actual support " "for each loose prop; do not relabel an integral flush desk insert as a loose " "object when the named object is machine-authored on a different support. " + ( "Panels labeled REFERENCE are user-supplied visual calibration frames, not " "views of the generated scene. Do not evaluate their task semantics or count " "their objects. Score only GENERATED panels, using the REFERENCE panels to " "calibrate rendering realism, material response, and lighting: 7.5 means the " "generated visual quality is at least comparable to that supplied baseline " "while all generated-scene engineering and task requirements remain satisfied. " if (output / "supervisor/critic_reference_manifest.json").is_file() else "" ) + f"sequence: {json.dumps(machine_evidence, ensure_ascii=False)}\n" 'Return JSON only: {"score": number, "severe_failures": [string], ' '"summary": string}' ) raw = GenerativeClient(RelaySettings.from_env()).analyze_image(frame, prompt) match = re.search(r"\{.*\}", raw, re.DOTALL) payload = json.loads(match.group(0) if match else raw) view_manifest = output / "scenesmith/final_composed_critic_views/manifest.json" view_payload = _json(view_manifest) if view_manifest.is_file() else {} view_hashes = { role: hashlib.sha256( (Path(path) if Path(path).is_absolute() else output / "scenesmith" / path).read_bytes() ).hexdigest() for role, path in (view_payload.get("views") or {}).items() if isinstance(role, str) and isinstance(path, str) and (Path(path) if Path(path).is_absolute() else output / "scenesmith" / path).is_file() } shared_report = { "schema_version": "2.0", "consumers": ["final_global_critic", "supervisor"], "source_view_manifest": str(view_manifest.relative_to(output)), "source_view_manifest_sha256": ( hashlib.sha256(view_manifest.read_bytes()).hexdigest() if view_manifest.is_file() else None ), "view_sha256": view_hashes, "frame": str(frame.relative_to(output)), "frame_sha256": hashlib.sha256(frame.read_bytes()).hexdigest(), "threshold": self.policy.critic_min_score, "raw": raw, "result": payload, } serialized = json.dumps(shared_report, ensure_ascii=False, indent=2) + "\n" atomic_write_text(output / "supervisor" / "critic_report.json", serialized) atomic_write_text(output / "scenesmith" / "final_global_critic_report.json", serialized) score = float(payload.get("score", 0)) severe = payload.get("severe_failures") or [] return score >= self.policy.critic_min_score and not severe, score @staticmethod def _critic_frame(output: Path) -> Path | None: target = output / "supervisor" / "critic_frame.jpg" # This contact sheet is derived evidence, not an immutable source artifact. # Always rebuild it from the current critic-view manifest so a rerender or # renderer-profile change cannot be evaluated through a stale JPEG. if target.is_file(): target.unlink() reference_manifest = target.parent / "critic_reference_manifest.json" if reference_manifest.is_file(): reference_manifest.unlink() # Prefer the topology-aware, full-resolution evidence rendered from the # final canonical USD. Video extraction downsamples each view to 480p # before tiling and can make native meshes/materials look like proxies. # Prefer the release-grade composed views: unlike the SceneSmith-internal # DAG views, these include the robot and all outer benchmark layers. view_manifests = [ output / "scenesmith/final_composed_critic_views/manifest.json", output / "scenesmith/final_critic_views/manifest.json", ] view_manifest = next((path for path in view_manifests if path.is_file()), None) if view_manifest is not None: try: raw_views = (_json(view_manifest).get("views") or {}) view_items = [ (str(role), Path(str(path))) for role, path in raw_views.items() if isinstance(role, str) and isinstance(path, str) ] resolved_items = [ (role, path if path.is_absolute() else output / "scenesmith" / path) for role, path in view_items ] if len(resolved_items) >= 4 and all(path.is_file() for _, path in resolved_items): reference_items: list[tuple[str, Path]] = [] reference_root_text = os.environ.get("RHG_CRITIC_REFERENCE_DIR", "").strip() if reference_root_text: reference_root = Path(reference_root_text).resolve() if reference_root.is_dir(): reference_items = [ (f"REFERENCE:{path.stem}", path) for path in sorted(reference_root.iterdir()) if path.suffix.casefold() in {".jpg", ".jpeg", ".png"} ][:4] labeled_items = [ (f"GENERATED:{role}", path) for role, path in resolved_items ] + reference_items target.parent.mkdir(parents=True, exist_ok=True) width, height, label_height = 640, 360, 24 columns = 3 if len(labeled_items) >= 6 else 2 rows = (len(labeled_items) + columns - 1) // columns sheet = Image.new("RGB", (columns * width, rows * (height + label_height)), "white") draw = ImageDraw.Draw(sheet) for index, (role, path) in enumerate(labeled_items): image = Image.open(path).convert("RGB") image.thumbnail((width, height)) x = (index % columns) * width y = (index // columns) * (height + label_height) sheet.paste(image, (x + (width - image.width) // 2, y + label_height)) draw.text((x + 8, y + 5), role, fill="black") sheet.save(target, format="JPEG", quality=94, optimize=True) if reference_items: atomic_write_text( reference_manifest, json.dumps( { "schema_version": "1.0", "calibration_rule": ( "7.5 means generated visual quality is at least " "comparable to the user-supplied reference" ), "generated_views": [role for role, _ in resolved_items], "reference_frames": [ { "label": role, "path": str(path), "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), } for role, path in reference_items ], }, indent=2, ) + "\n", ) elif reference_manifest.exists(): reference_manifest.unlink() return target except (OSError, ValueError, TypeError): pass preview = output / "scenesmith" / "preview.mp4" if preview.is_file() and shutil.which("ffmpeg"): target.parent.mkdir(parents=True, exist_ok=True) result = subprocess.run( [ "ffmpeg", "-y", "-i", str(preview), "-vf", "fps=1,scale=480:270:force_original_aspect_ratio=decrease," "pad=480:270:(ow-iw)/2:(oh-ih)/2,tile=2x2", "-frames:v", "1", str(target), ], capture_output=True, timeout=60, check=False, ) if result.returncode == 0 and target.is_file(): return target candidates = sorted((output / "scenesmith").glob("iteration_frames/*.png")) return candidates[-1] if candidates else None @staticmethod def _report( gates: list[GateResult], *, critic_passed: bool, critic_score: float | None = None ) -> QualityReport: failed = sorted( gate.gate_id for gate in gates if not gate.passed and gate.severity == "severe" ) signature = hashlib.sha256("|".join(failed).encode()).hexdigest()[:16] if failed else None hard_passed = not failed return QualityReport( accepted=hard_passed and critic_passed, hard_gates_passed=hard_passed, critic_passed=critic_passed, critic_score=critic_score, gates=gates, failure_signature=signature, )