"""Pinned logical-task/source mappings and private packed-scenario handling.""" from __future__ import annotations import hashlib import json import shutil import stat import subprocess import tempfile import zipfile from contextlib import contextmanager from pathlib import Path, PurePosixPath from .vendor import PINNED_REVISION SHARING = "sharing_and_seeking_information" DIMENSIONS = (SHARING, "keeping_the_team_on_track", "taking_initiative", "taking_over") ALIASES = {"sharing": SHARING, "tracking": "keeping_the_team_on_track", "initiative": "taking_initiative", "takeover": "taking_over"} SOURCE_PROTOCOL = "ci-harbor-v2" GPQA_ARCHIVE = "benchmark/gpqa_scenarios.zip" # This is the public distribution password specified by the pinned release, # not a provider credential. Packed release data stay encrypted in task files. GPQA_PASSWORD = b"deserted-untie-orchid" def scenario_digest(path: Path) -> str: result = hashlib.sha256() for file in sorted(path.rglob("*")): if file.is_symlink(): raise ValueError(f"Symlinks are not portable scenario inputs: {file}") if file.is_file() and "__pycache__" not in file.parts: result.update(file.relative_to(path).as_posix().encode() + b"\0") result.update(file.read_bytes() + b"\0") return result.hexdigest() def normalized_dimension(value: str) -> str: result = ALIASES.get(value, value) if result not in DIMENSIONS: raise ValueError("Unsupported selected dimension") return result def checked_relative(value: str) -> PurePosixPath: if not isinstance(value, str): raise ValueError("Unsafe benchmark source path") path = PurePosixPath(value) if (not value or path.is_absolute() or ".." in path.parts or "\\" in value or "\0" in value or str(path) != value): raise ValueError("Unsafe benchmark source path") return path def verify_git_file(upstream: Path, relative: str) -> bytes: path = upstream / checked_relative(relative) if path.is_symlink() or any(parent.is_symlink() for parent in path.parents if parent != upstream.parent): raise ValueError("Pinned source cannot follow symlinks") data = path.read_bytes() original = subprocess.run(["git", "-C", str(upstream), "show", f"{PINNED_REVISION}:{relative}"], check=True, capture_output=True).stdout if data != original: raise ValueError(f"Source differs from pinned release: {relative}") return data def release_spec(upstream: Path) -> dict: return json.loads(verify_git_file(upstream, "benchmark/final_set.json")) def role_source(entry: dict, variant: str) -> tuple[str, str]: """Map a logical gate/test/baseline to the original source and version.""" if variant == "solo": return entry.get("gate_path") or entry["path"], "solo" if variant == "manipulation": return entry["path"], "manipulation" if variant == "control": return entry.get("control_path") or entry["path"], entry.get("control_version", "control") raise ValueError("Unknown logical task role") def item_digest(entry: dict) -> str: return hashlib.sha256(json.dumps(entry, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest() def source_run_ref(source_path: str, source_variant: str, seed: int, scenario_sha256: str, source_revision: str = PINNED_REVISION) -> str: """One physical gate/baseline run may support several logical states.""" return item_digest({"source_path": source_path, "source_variant": source_variant, "seed": seed, "scenario_sha256": scenario_sha256, "source_revision": source_revision}) def _extract_selected(archive: Path, relative: str, destination: Path) -> Path: source = checked_relative(relative) if source.parts[:2] != ("benchmark", "scenarios") or len(source.parts) != 4: raise ValueError("Packed source must name one benchmark scenario") prefix = relative + "/" total, count = 0, 0 with zipfile.ZipFile(archive) as packed: for entry in packed.infolist(): if not entry.filename.startswith(prefix) or entry.is_dir(): continue member = checked_relative(entry.filename) if stat.S_ISLNK(entry.external_attr >> 16): raise ValueError("Packed scenario contains a symlink") total += entry.file_size count += 1 if total > 64 * 1024 * 1024 or entry.file_size > 16 * 1024 * 1024 or count > 256: raise ValueError("Packed scenario exceeds extraction bounds") target = destination / member target.parent.mkdir(parents=True, exist_ok=True) target.write_bytes(packed.read(entry, pwd=GPQA_PASSWORD)) result = destination / source if not (result / "episode.yaml").is_file(): raise ValueError("Requested scenario is absent from the pinned archive") return result @contextmanager def staged_source(upstream: Path, relative: str): """Read pinned inputs without changing checkout or releasing packed text.""" upstream = Path(upstream).resolve() source = upstream / checked_relative(relative) if (source / "episode.yaml").is_file(): for file in sorted(source.rglob("*")): if file.is_file() and "__pycache__" not in file.parts: verify_git_file(upstream, file.relative_to(upstream).as_posix()) yield source, {"kind": "git", "path": relative, "revision": PINNED_REVISION} else: data = verify_git_file(upstream, GPQA_ARCHIVE) with tempfile.TemporaryDirectory(prefix="ci-packed-source-") as temporary: source = _extract_selected(upstream / GPQA_ARCHIVE, relative, Path(temporary)) yield source, {"kind": "packed", "path": relative, "revision": PINNED_REVISION, "archive_path": GPQA_ARCHIVE, "archive_sha256": hashlib.sha256(data).hexdigest()} @contextmanager def runtime_source(default: Path, descriptor: dict | None): """Extract only one packed scenario privately, for this process lifetime.""" if descriptor is None: yield Path(default) return archive = Path(descriptor["archive"]) if hashlib.sha256(archive.read_bytes()).hexdigest() != descriptor["archive_sha256"]: raise ValueError("Packed runtime archive differs from the task source") with tempfile.TemporaryDirectory(prefix="ci-private-scenario-") as temporary: source = _extract_selected(archive, descriptor["path"], Path(temporary)) if scenario_digest(source) != descriptor["scenario_sha256"]: raise ValueError("Packed runtime scenario differs from the task identity") yield source def copy_private_source(source: Path, provenance: dict, destination: Path, upstream: Path, *, runtime_archive: str): """Return runtime archive descriptor; plaintext normal sources stay pinned.""" if provenance["kind"] == "git": shutil.copytree(source, destination / "scenario", ignore=shutil.ignore_patterns("__pycache__")) return None shutil.copyfile(upstream / provenance["archive_path"], destination / "scenario.zip") return {"archive": runtime_archive, "archive_sha256": provenance["archive_sha256"], "path": provenance["path"], "scenario_sha256": scenario_digest(source)}