from __future__ import annotations import hashlib import json import os import shutil import uuid from pathlib import Path from packages.core.contracts import SceneBundle, canonical_sha256 from packages.core.files import atomic_write_text from packages.robots.profiles import get_robot_profile from packages.runtime.isaac.contracts import RobotInjectionSpec def _sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def _usd_identifier(value: str) -> str: sanitized = "".join( character if character.isalnum() or character == "_" else "_" for character in value ) if not sanitized: raise ValueError("USD identifier cannot be empty") return sanitized if not sanitized[0].isdigit() else f"_{sanitized}" def _usd_path(path: str | Path) -> str: return str(path).replace("\\", "/").replace("@", "%40") def load_and_verify_bundle(bundle_root: Path) -> SceneBundle: bundle_root = bundle_root.resolve() manifest = bundle_root / "manifests" / "scene_bundle.json" if not manifest.is_file(): raise FileNotFoundError(f"SceneBundle manifest is missing: {manifest}") bundle = SceneBundle.model_validate_json(manifest.read_text(encoding="utf-8")) hashes = bundle.provenance.get("artifact_sha256") if not isinstance(hashes, dict) or not hashes: raise ValueError("SceneBundle provenance has no artifact SHA-256 ledger") for relative, expected in hashes.items(): if not isinstance(relative, str) or not isinstance(expected, str): raise ValueError("SceneBundle artifact ledger must map paths to hashes") path = (bundle_root / relative).resolve() if not path.is_relative_to(bundle_root): raise ValueError(f"SceneBundle artifact path escapes bundle root: {relative}") if not path.is_file(): raise FileNotFoundError(f"SceneBundle artifact is missing: {relative}") actual = _sha256(path) if actual != expected: raise ValueError( f"SceneBundle artifact hash differs for {relative}: {actual} != {expected}" ) root = (bundle_root / bundle.layer_uris["root"]).resolve() if not root.is_relative_to(bundle_root) or not root.is_file(): raise ValueError("SceneBundle root layer is missing or escapes bundle root") return bundle def _robot_layer( *, robot_id: str, robot_reference: str, translation_m: tuple[float, float, float], yaw_deg: float, ) -> str: return ( '#usda 1.0\n(\n metersPerUnit = 1\n upAxis = "Z"\n)\n\n' 'over Xform "World" {\n' f' def Xform "Robot" (\n prepend references = @{_usd_path(robot_reference)}@\n' " ) {\n" f' custom string robothousegen_robot_id = "{robot_id}"\n' f" double3 xformOp:translate = ({translation_m[0]:.9g}, " f"{translation_m[1]:.9g}, {translation_m[2]:.9g})\n" f" float xformOp:rotateZ = {yaw_deg:.9g}\n" ' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateZ"]\n' " }\n}\n" ) def _composed_root(robot_layer: str, base_root: str) -> str: return ( '#usda 1.0\n(\n defaultPrim = "World"\n metersPerUnit = 1\n' f" subLayers = [\n @{_usd_path(robot_layer)}@,\n" f" @{_usd_path(base_root)}@\n ]\n" ' upAxis = "Z"\n)\n\nover Xform "World" {}\n' ) class IsaacRobotInjector: version = "1.0" def inject( self, *, bundle_root: Path, output_dir: Path, robot_id: str, robot_asset: Path, robot_asset_sha256: str, stage_robot_asset: bool = True, ) -> RobotInjectionSpec: bundle_root = bundle_root.resolve() output_dir = output_dir.resolve() robot_asset = robot_asset.resolve() if output_dir.exists(): raise FileExistsError(f"refusing to overwrite Isaac injection output: {output_dir}") bundle = load_and_verify_bundle(bundle_root) profile = get_robot_profile(robot_id) missing_capabilities = ( bundle.scene_requirements.required_robot_capabilities - profile.capabilities ) if missing_capabilities: raise ValueError( f"robot {robot_id} lacks required capabilities: {sorted(missing_capabilities)}" ) if not robot_asset.is_file(): raise FileNotFoundError(f"robot asset is missing: {robot_asset}") actual_robot_hash = _sha256(robot_asset) if actual_robot_hash != robot_asset_sha256: raise ValueError( f"robot asset hash differs: {actual_robot_hash} != {robot_asset_sha256}" ) declared_hash = profile.metadata.get("scene_asset_sha256") if isinstance(declared_hash, str) and declared_hash != robot_asset_sha256: raise ValueError( f"robot profile hash differs for {robot_id}: {declared_hash} != " f"{robot_asset_sha256}" ) output_dir.parent.mkdir(parents=True, exist_ok=True) staging = output_dir.parent / f".{output_dir.name}.tmp-{uuid.uuid4().hex[:12]}" layers = staging / "layers" manifests = staging / "manifests" layers.mkdir(parents=True) manifests.mkdir() if stage_robot_asset: asset_root = staging / "assets" / "robots" / _usd_identifier(robot_id) shutil.copytree(robot_asset.parent, asset_root) packaged_robot = asset_root / robot_asset.name if _sha256(packaged_robot) != robot_asset_sha256: raise ValueError("packaged robot asset hash differs after staging") robot_reference = os.path.relpath(packaged_robot, start=layers).replace("\\", "/") else: packaged_robot = robot_asset robot_reference = robot_asset.as_posix() injection_layer = layers / "robot.usda" atomic_write_text( injection_layer, _robot_layer( robot_id=robot_id, robot_reference=robot_reference, translation_m=bundle.robot_start.translation_m, yaw_deg=bundle.robot_start.yaw_deg, ), ) base_root = (bundle_root / bundle.layer_uris["root"]).resolve() relative_base = os.path.relpath(base_root, start=staging).replace("\\", "/") atomic_write_text(staging / "root.usda", _composed_root("layers/robot.usda", relative_base)) spec = RobotInjectionSpec.for_bundle( bundle, robot_id=robot_id, robot_asset_uri=str(packaged_robot), robot_asset_sha256=robot_asset_sha256, robot_profile_version=profile.model_version, injection_layer_uri="layers/robot.usda", ) atomic_write_text( manifests / "robot_injection.json", spec.model_dump_json(indent=2) + "\n", ) atomic_write_text( manifests / "injection_provenance.json", json.dumps( { "schema_version": "1.0", "injector": f"IsaacRobotInjector/{self.version}", "scene_bundle_manifest": str( bundle_root / "manifests" / "scene_bundle.json" ), "scene_bundle_sha256": bundle.content_hash, "robot_injection_sha256": canonical_sha256(spec), "robot_asset_source": str(robot_asset), "robot_asset_staged": stage_robot_asset, "base_bundle_modified": False, }, indent=2, sort_keys=True, ) + "\n", ) if output_dir.exists(): raise FileExistsError( f"Isaac injection destination appeared during build: {output_dir}" ) os.replace(staging, output_dir) return spec