from __future__ import annotations import hashlib import json import re import shutil from collections.abc import Iterator from contextlib import contextmanager from datetime import UTC, datetime from pathlib import Path from typing import Any from packages.benchmark.artifact_lifecycle import ( replace_major_copy, replace_major_from_portable, ) from packages.benchmark.portable import create_zstd_archive, portable_source_fingerprint from packages.core.file_lock import lock_file, unlock_file from packages.core.files import atomic_write_text from packages.supervisor.models import AttemptManifest, QualityReport VERSION_PATTERN = re.compile(r"^v(?P[1-9][0-9]*)-(?P[0-9]{8})$") LEGACY_PATTERN = re.compile( r"^(?:scenesmith-)?(?P.+?)-v(?P[1-9][0-9]*)-(?P[0-9]{8})(?:-portable)?$" ) def derive_case_id(prompt: str) -> str: words = re.findall(r"[a-z0-9]+", prompt.casefold()) ignored = {"a", "an", "the", "to", "from", "and", "with", "in", "on", "of"} slug = "-".join(word for word in words if word not in ignored)[:64].strip("-") if slug: return slug return f"case-{hashlib.sha256(prompt.encode('utf-8')).hexdigest()[:12]}" def _sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def _world_certificate_allows_downstream_validation(certificate: dict[str, Any]) -> bool: """Accept either a completed USD check or an explicitly deferred upstream binding. ``upstream_root_binding`` is emitted when deterministic placement is disabled. It proves the immutable SceneSmith root and its geometry evidence were bound, while the required portable and Isaac validators below provide the actual stage-open, prim, bounds, collision, and stability checks. Other certificate modes must continue to carry their own successful USD validation result. """ return certificate.get("hard_gates_passed") is True and ( certificate.get("usd_validation_passed") is True or certificate.get("validation_mode") == "upstream_root_binding" ) def _requires_scenesmith_world_certificate(scenesmith_root: Path) -> bool: """Media fallback alone must not make a deterministic run look SceneSmith-owned.""" return (scenesmith_root / "stage_manifest.json").is_file() or ( scenesmith_root / "scene.usdc" ).is_file() class CaseManager: def __init__(self, root: Path, *, allow_non_isaac_portable: bool = False) -> None: self.root = root.resolve() self.allow_non_isaac_portable = allow_non_isaac_portable @contextmanager def locked(self) -> Iterator[None]: self.root.mkdir(parents=True, exist_ok=True) lock_path = self.root / ".case.lock" with lock_path.open("a+", encoding="utf-8") as handle: lock_file(handle) try: yield finally: unlock_file(handle) @contextmanager def campaign_locked(self) -> Iterator[None]: """Serialize Supervisors for one case while still allowing parallel inner stages.""" self.root.mkdir(parents=True, exist_ok=True) lock_path = self.root / ".campaign.lock" with lock_path.open("a+", encoding="utf-8") as handle: lock_file(handle) try: yield finally: unlock_file(handle) def initialize(self, *, case_id: str, prompt: str, robot: str, seed: int) -> None: payload = { "schema_version": "1.0", "case_id": case_id, "prompt": prompt, "prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(), "robot": robot, "seed": seed, "created_at": datetime.now(UTC).isoformat(), } with self.locked(): path = self.root / "case.json" if path.is_file(): existing = json.loads(path.read_text(encoding="utf-8")) identity = ("case_id", "prompt_sha256", "robot", "seed") if any(existing.get(key) != payload[key] for key in identity): raise ValueError(f"case identity differs from existing {path}") return atomic_write_text(path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n") def allocate_attempt(self, *, parent_version: str | None) -> tuple[Path, AttemptManifest]: with self.locked(): numbers = [ int(match.group("number")) for child in self.root.iterdir() if child.is_dir() and (match := VERSION_PATTERN.fullmatch(child.name)) ] version = f"v{max(numbers, default=0) + 1}-{datetime.now().strftime('%Y%m%d')}" output = self.root / version output.mkdir() started = datetime.now(UTC).isoformat() design_contract: str | None = None fixed_dag_sha256: str | None = None fixed_graph_id: str | None = None contract_path = self.root / "case_design" / "contract.json" if contract_path.is_file(): contract = json.loads(contract_path.read_text(encoding="utf-8")) design_contract = "../../case_design/contract.json" fixed_dag_sha256 = str(contract.get("dependency_graph_sha256") or "") or None fixed_graph_id = str(contract.get("graph_id") or "") or None manifest = AttemptManifest( version=version, status="running", parent_version=parent_version, design_contract=design_contract, fixed_dag_sha256=fixed_dag_sha256, fixed_graph_id=fixed_graph_id, started_at=started, ) self.write_attempt(output, manifest) return output, manifest def write_attempt(self, output: Path, manifest: AttemptManifest) -> None: path = output / "supervisor" / "attempt_manifest.json" atomic_write_text(path, manifest.model_dump_json(indent=2) + "\n") def read_attempt(self, output: Path) -> AttemptManifest: path = output / "supervisor" / "attempt_manifest.json" return AttemptManifest.model_validate_json(path.read_text(encoding="utf-8")) def append_attempt(self, manifest: AttemptManifest) -> None: with self.locked(): path = self.root / "attempts.jsonl" with path.open("a", encoding="utf-8") as handle: handle.write(manifest.model_dump_json() + "\n") handle.flush() def update_campaign(self) -> None: attempts = [] for child in sorted(self.root.iterdir()): if not child.is_dir() or VERSION_PATTERN.fullmatch(child.name) is None: continue path = child / "supervisor" / "attempt_manifest.json" if path.is_file(): attempts.append(json.loads(path.read_text(encoding="utf-8"))) payload = { "schema_version": "1.0", "updated_at": datetime.now(UTC).isoformat(), "attempt_count": len(attempts), "attempts": attempts, } atomic_write_text( self.root / "campaign_manifest.json", json.dumps(payload, ensure_ascii=False, indent=2) + "\n", ) def release(self, output: Path, report: QualityReport) -> Path: if not report.accepted or not report.hard_gates_passed or not report.critic_passed: raise ValueError("refusing to release an attempt that did not pass all gates") major_manifest_path = self.root / "major" / "major_manifest.json" major_manifest = ( json.loads(major_manifest_path.read_text(encoding="utf-8")) if major_manifest_path.is_file() else {} ) if ( major_manifest.get("source_version") != output.name or not self._portable_matches_source(self.root / "major", output) ): self.consider_for_major(output, report) major_manifest = ( json.loads(major_manifest_path.read_text(encoding="utf-8")) if major_manifest_path.is_file() else {} ) if ( major_manifest.get("source_version") != output.name or not self._portable_matches_source(self.root / "major", output) ): raise ValueError("refusing release because portable major was not materialized") portable_path = self._portable_release_path(output) portable_file = self.root / portable_path if portable_path else None if portable_file is None or not portable_file.exists(): raise ValueError("refusing release because portable package is missing") portable_sha256 = ( _sha256_file(portable_file) if portable_file is not None and portable_file.is_file() else None ) payload = { "schema_version": "1.0", "released_at": datetime.now(UTC).isoformat(), "version": output.name, "run_dir": output.name, "quality_report": f"{output.name}/supervisor/quality_report.json", "portable_package": portable_path, "portable_sha256": portable_sha256, "major_dir": "major", "certification_level": ( "portable_contract" if self.allow_non_isaac_portable else "isaac_validated_portable" ), } path = self.root / "release.json" atomic_write_text(path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n") (self.root / "blocked.json").unlink(missing_ok=True) return path def consider_for_major(self, output: Path, report: QualityReport) -> bool: """Promote only a version accepted by every final publication gate.""" if not ( report.accepted and report.hard_gates_passed and report.critic_passed ): return False output = output.resolve() minimum_major_files = ( output / "root.usda", output / "snapshot.jpg", output / "preview.mp4", output / "iteration_history.mp4", ) minimum_major_ready = all(path.is_file() for path in minimum_major_files) portable = self.root / "packages" / output.name validation_path = output / "manifests" / "portable_validation.json" validation: dict[str, Any] | None = None portable_ready = False if portable.is_dir() and validation_path.is_file(): try: validation = json.loads(validation_path.read_text(encoding="utf-8")) task_path = output / "manifests/task.json" if not task_path.is_file(): task_path = portable / "manifests/task.json" task = json.loads(task_path.read_text(encoding="utf-8")) manipulated_ids = { str(entity.get("entity_id")) for entity in task.get("entities", []) if isinstance(entity, dict) and entity.get("role") == "MANIPULATED" } physics = (validation.get("usd") or {}).get("manipulation_physics") or {} portable_ready = bool( validation.get("passed") and self._portable_matches_source(portable, output) and not any( not isinstance(physics.get(entity_id), dict) or not physics[entity_id].get("rigid_body_api") or not physics[entity_id].get("collision_prim_paths") for entity_id in manipulated_ids ) ) except (OSError, ValueError, json.JSONDecodeError): portable_ready = False scenesmith_root = output / "scenesmith" if portable_ready and _requires_scenesmith_world_certificate(scenesmith_root): world_certificate_path = scenesmith_root / "world_geometry_certificate.json" try: world_certificate = json.loads( world_certificate_path.read_text(encoding="utf-8") ) except (OSError, json.JSONDecodeError): portable_ready = False else: portable_ready = _world_certificate_allows_downstream_validation( world_certificate ) if not portable_ready and not minimum_major_ready: return False candidate_rank = self._quality_rank(report) manifest_path = self.root / "major.json" with self.locked(): current: dict[str, Any] | None = None if manifest_path.is_file(): current = json.loads(manifest_path.read_text(encoding="utf-8")) current_rank = tuple(current.get("quality_rank", [])) if current else () rank_migrated = False if current and len(current_rank) != len(candidate_rank): source_version = current.get("source_version") source_quality = ( self.root / str(source_version) / "supervisor" / "quality_report.json" ) if source_quality.is_file(): try: incumbent_report = QualityReport.model_validate_json( source_quality.read_text(encoding="utf-8") ) except (OSError, ValueError): pass else: current_rank = self._quality_rank(incumbent_report) current["quality_rank"] = list(current_rank) rank_migrated = True major_manifest_path = self.root / "major/major_manifest.json" major_manifest = ( json.loads(major_manifest_path.read_text(encoding="utf-8")) if major_manifest_path.is_file() else {} ) already_portable_major = major_manifest.get("materialization_version") == "5.0" same_source_needs_upgrade = bool( portable_ready and current and current.get("source_version") == output.name and ( not already_portable_major or not self._portable_matches_source(self.root / "major", output) ) ) major_missing = not (self.root / "major").is_dir() if ( current_rank and candidate_rank <= current_rank and not same_source_needs_upgrade and not major_missing ): if rank_migrated and current is not None: atomic_write_text( manifest_path, json.dumps(current, ensure_ascii=False, indent=2) + "\n", ) return False if portable_ready: lifecycle = replace_major_from_portable( portable, self.root / "major", source_version=output ) certification_level = ( "portable_contract" if self.allow_non_isaac_portable else "isaac_validated_portable" ) else: lifecycle = replace_major_copy(output, self.root / "major") certification_level = "best_effort_attempt" archive = self.root / "packages" / "major.tar.zst" archive.parent.mkdir(parents=True, exist_ok=True) temporary_archive = archive.with_name(f".{archive.name}.tmp") temporary_archive.unlink(missing_ok=True) create_zstd_archive(self.root / "major", temporary_archive) temporary_archive.replace(archive) payload = { "schema_version": "1.0", "updated_at": datetime.now(UTC).isoformat(), "source_version": output.name, "quality_rank": list(candidate_rank), "accepted": report.accepted, "hard_gates_passed": report.hard_gates_passed, "critic_passed": report.critic_passed, "critic_score": report.critic_score, "major_dir": "major", "snapshot": "major/snapshot.jpg", "preview": "major/preview.mp4", "iteration_history": "major/iteration_history.mp4", "portable_archive": "packages/major.tar.zst", "portable_archive_sha256": _sha256_file(archive), "portable_verification": validation if portable_ready else None, "artifact_lifecycle": lifecycle, "certification_level": certification_level, } atomic_write_text( manifest_path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n" ) return True def _portable_matches_source(self, portable: Path, source: Path) -> bool: manifest_path = portable / "portable_manifest.json" isaac_path = portable / "manifests" / "isaac_validation.json" if not manifest_path.is_file() or ( not self.allow_non_isaac_portable and not isaac_path.is_file() ): return False try: manifest = json.loads(manifest_path.read_text(encoding="utf-8")) isaac = ( json.loads(isaac_path.read_text(encoding="utf-8")) if isaac_path.is_file() else {} ) expected_fingerprint = portable_source_fingerprint(source) except (OSError, ValueError, json.JSONDecodeError): return False runtime = manifest.get("runtime_requirements") or {} return bool( manifest.get("source_fingerprint") == expected_fingerprint and ( self.allow_non_isaac_portable or ( isaac.get("passed") is True and runtime.get("simulator") == "Isaac Sim 6.0.1" ) ) ) @staticmethod def _quality_rank( report: QualityReport, ) -> tuple[int, int, int, int, float, int, int]: severe = [gate for gate in report.gates if gate.severity == "severe"] severe_passed = sum(gate.passed for gate in severe) observed_critic_scores = [ float(match) for gate in report.gates for match in re.findall( r"critic_below_threshold:([0-9]+(?:\.[0-9]+)?)", gate.message ) ] completion_stage = ( 2 if report.critic_score is not None else 1 if observed_critic_scores else 0 ) effective_critic_score = ( report.critic_score if report.critic_score is not None else min(observed_critic_scores) if observed_critic_scores else -1.0 ) return ( int(report.accepted), int(report.hard_gates_passed), int(report.critic_passed), completion_stage, effective_critic_score, severe_passed, -len(severe), ) def _portable_release_path(self, output: Path) -> str | None: archive = self.root / "packages" / f"{output.name}.tar.zst" if archive.is_file(): return archive.relative_to(self.root).as_posix() directory = self.root / "packages" / output.name return directory.relative_to(self.root).as_posix() if directory.is_dir() else None def block(self, *, reason: str, elapsed_s: float, last_version: str | None) -> Path: payload = { "schema_version": "1.0", "blocked_at": datetime.now(UTC).isoformat(), "reason": reason, "elapsed_s": round(elapsed_s, 3), "last_version": last_version, "resumable": True, } path = self.root / "blocked.json" atomic_write_text(path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n") return path def plan_legacy_migration(source_root: Path) -> list[dict[str, Any]]: plan: list[dict[str, Any]] = [] for child in sorted(source_root.iterdir()): if not child.is_dir() or not (match := LEGACY_PATTERN.fullmatch(child.name)): continue case_id = re.sub(r"[^a-z0-9]+", "-", match.group("case").casefold()).strip("-") version = f"v{match.group('number')}-{match.group('date')}" plan.append({"source": str(child), "destination": str(source_root / case_id / version)}) return plan def apply_legacy_migration(plan: list[dict[str, Any]]) -> None: for item in plan: source = Path(str(item["source"])) destination = Path(str(item["destination"])) if destination.exists(): raise FileExistsError(destination) destination.parent.mkdir(parents=True, exist_ok=True) shutil.move(str(source), str(destination))