"""Gradio-independent challenge generation services.""" from __future__ import annotations import json import hashlib import io import shutil import stat import zipfile from collections.abc import Callable from datetime import datetime from pathlib import Path from pathlib import PurePosixPath from uuid import UUID, uuid4 from architect.private_artifacts import ensure_private_workspace_dir, private_workspace_dir _ROUND_PRIVATE_FILES = ( "challenge_state.json", "challenge_run_public.py", "challenge_run_secret.py", "secret_tests.json", ) _STUDENT_STATE_FIELDS = { "github_url", "workspace_path", "challenge_created_at", "target_file", "sabotaged_code", "sabotaged_files", "nesting_level", "refactoring_enabled", "debug_mode", "challenge_summary", "challenge_round_id", } _MAX_ROUND_ARCHIVE_BYTES = 45 * 1024 * 1024 _MAX_ROUND_UNPACKED_BYTES = 100 * 1024 * 1024 def _rounds_root() -> Path: from architect.repo_cloner import WORKSPACES_DIR return Path(WORKSPACES_DIR).resolve() / ".rounds" def _round_hashes(workspace: Path, private_dir: Path) -> tuple[str, str]: artifact_digest = hashlib.sha256() for path in sorted(file for file in workspace.rglob("*") if file.is_file()): relative = path.relative_to(workspace).as_posix() artifact_digest.update(relative.encode("utf-8")) artifact_digest.update(b"\0") artifact_digest.update(path.read_bytes()) artifact_digest.update(b"\0") tests_digest = hashlib.sha256() for name in _ROUND_PRIVATE_FILES: path = private_dir / name if not path.is_file(): raise FileNotFoundError(f"Round test artifact is missing: {name}") tests_digest.update(name.encode("utf-8")) tests_digest.update(b"\0") tests_digest.update(path.read_bytes()) tests_digest.update(b"\0") return artifact_digest.hexdigest(), tests_digest.hexdigest() def _copy_round_private_files(source_workspace: Path, target_workspace: Path) -> None: source_dir = private_workspace_dir(source_workspace) target_dir = ensure_private_workspace_dir(target_workspace) for name in _ROUND_PRIVATE_FILES: source = source_dir / name if name == "challenge_state.json" and not source.is_file(): source = source_workspace / name if not source.is_file(): raise FileNotFoundError(f"Round test artifact is missing: {name}") target = target_dir / name shutil.copyfile(source, target) target.chmod(0o600) def _student_visible_state(state: dict[str, object]) -> dict[str, object]: return {key: value for key, value in state.items() if key in _STUDENT_STATE_FIELDS} def create_challenge_round_archive(round_id: str) -> bytes: safe_round_id = str(UUID(round_id)) round_dir = _rounds_root() / safe_round_id template = round_dir / "workspace" manifest_path = round_dir / "round.json" if not template.is_dir() or not manifest_path.is_file(): raise FileNotFoundError("Challenge round was not found") buffer = io.BytesIO() with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive: for path in sorted(template.rglob("*")): if not path.is_file(): continue if path.is_symlink(): raise ValueError("Challenge round contains a symlink") archive.write(path, f"workspace/{path.relative_to(template).as_posix()}") private_dir = private_workspace_dir(template) for name in _ROUND_PRIVATE_FILES: path = private_dir / name if not path.is_file(): raise FileNotFoundError(f"Round test artifact is missing: {name}") archive.write(path, f"private/{name}") bundle = buffer.getvalue() if len(bundle) > _MAX_ROUND_ARCHIVE_BYTES: raise ValueError("Challenge round archive exceeds the 45 MiB storage limit") return bundle def delete_challenge_round(round_id: str) -> None: safe_round_id = str(UUID(round_id)) round_dir = _rounds_root() / safe_round_id template = round_dir / "workspace" shutil.rmtree(round_dir, ignore_errors=True) shutil.rmtree(private_workspace_dir(template), ignore_errors=True) def _restore_challenge_round_archive( round_id: str, manifest: dict[str, str | int], archive_bytes: bytes, ) -> Path: from architect.repo_cloner import WORKSPACES_DIR safe_round_id = str(UUID(round_id)) if manifest.get("round_id") != safe_round_id or len(archive_bytes) > _MAX_ROUND_ARCHIVE_BYTES: raise ValueError("Challenge round metadata or archive is invalid") rounds_root = _rounds_root() rounds_root.mkdir(parents=True, exist_ok=True) round_dir = rounds_root / safe_round_id if round_dir.exists(): cached_template = round_dir / "workspace" if cached_template.is_dir() and (round_dir / "round.json").is_file(): return cached_template shutil.rmtree(round_dir, ignore_errors=True) staging_dir = rounds_root / f".restore-{uuid4()}" template = staging_dir / "workspace" staged_private_dir: Path | None = None try: staging_dir.mkdir(mode=0o700) total_size = 0 seen_names: set[str] = set() with zipfile.ZipFile(io.BytesIO(archive_bytes), "r") as bundle: for entry in bundle.infolist(): member = PurePosixPath(entry.filename) if member.is_absolute() or ".." in member.parts or not member.parts: raise ValueError("Challenge round archive contains an unsafe path") if entry.is_dir(): continue if entry.filename in seen_names: raise ValueError("Challenge round archive contains duplicate paths") seen_names.add(entry.filename) total_size += entry.file_size if total_size > _MAX_ROUND_UNPACKED_BYTES: raise ValueError("Challenge round archive expands beyond the 100 MiB limit") mode = (entry.external_attr >> 16) & 0o170000 if mode == stat.S_IFLNK: raise ValueError("Challenge round archive contains a symlink") if member.parts[0] == "workspace" and len(member.parts) > 1: if any(part in {".private", ".rounds"} for part in member.parts[1:]): raise ValueError("Challenge round archive contains a reserved path") destination = template.joinpath(*member.parts[1:]) elif member.parts[0] == "private" and len(member.parts) == 2 and member.parts[1] in _ROUND_PRIVATE_FILES: if staged_private_dir is None: staged_private_dir = ensure_private_workspace_dir(template) destination = staged_private_dir / member.parts[1] else: raise ValueError("Challenge round archive contains an unsupported path") destination.parent.mkdir(parents=True, exist_ok=True) with bundle.open(entry, "r") as source, destination.open("wb") as target: shutil.copyfileobj(source, target) destination.chmod(0o600) if staged_private_dir is None: raise ValueError("Challenge round archive is missing private test artifacts") archive_hash, tests_hash = _round_hashes(template, staged_private_dir) if archive_hash != manifest.get("artifact_hash") or tests_hash != manifest.get("tests_hash"): raise ValueError("Challenge round integrity check failed") (staging_dir / "round.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") staging_dir.chmod(0o700) staging_dir.rename(round_dir) restored_template = round_dir / "workspace" restored_private = ensure_private_workspace_dir(restored_template) for name in _ROUND_PRIVATE_FILES: shutil.copyfile(staged_private_dir / name, restored_private / name) (restored_private / name).chmod(0o600) restored_hashes = _round_hashes(restored_template, restored_private) if restored_hashes != (manifest.get("artifact_hash"), manifest.get("tests_hash")): raise ValueError("Restored challenge round failed integrity verification") shutil.rmtree(private_workspace_dir(template), ignore_errors=True) return restored_template except Exception: shutil.rmtree(round_dir, ignore_errors=True) shutil.rmtree(staging_dir, ignore_errors=True) if staged_private_dir: shutil.rmtree(staged_private_dir, ignore_errors=True) raise def create_challenge_round( workspace_path: str | Path, timer_minutes: int = 0, chat_messages_per_student: int = 5, ) -> dict[str, str | int]: """Publish the current challenge and private tests as an immutable local round.""" from architect.repo_cloner import WORKSPACES_DIR if isinstance(chat_messages_per_student, bool) or not isinstance(chat_messages_per_student, int): raise ValueError("Round chat message limit must be an integer") if not 0 <= chat_messages_per_student <= 100: raise ValueError("Round chat message limit must be between 0 and 100 per student") source_workspace = Path(workspace_path).resolve() challenge = ChallengeWorkspace(source_workspace) round_id = str(uuid4()) round_dir = _rounds_root() / round_id template = round_dir / "workspace" round_dir.mkdir(parents=True, mode=0o700) round_dir.chmod(0o700) shutil.copytree(source_workspace, template) state_path = template / "challenge_state.json" state = json.loads(state_path.read_text(encoding="utf-8")) target_file = Path(state.get("target_file", "")) if target_file.is_absolute(): try: target_file = target_file.resolve().relative_to(source_workspace) except ValueError as exc: shutil.rmtree(round_dir, ignore_errors=True) raise ValueError("Challenge target is outside the source workspace") from exc state["target_file"] = target_file.as_posix() state["workspace_path"] = str(template.resolve()) state_path.write_text(json.dumps(state, indent=2, ensure_ascii=False), encoding="utf-8") _copy_round_private_files(source_workspace, template) private_state_path = private_workspace_dir(template) / "challenge_state.json" private_state = json.loads(private_state_path.read_text(encoding="utf-8")) private_state["target_file"] = target_file.as_posix() private_state["workspace_path"] = str(template.resolve()) private_state_path.write_text(json.dumps(private_state, indent=2, ensure_ascii=False), encoding="utf-8") private_state_path.chmod(0o600) state_path.write_text(json.dumps(_student_visible_state(private_state), indent=2, ensure_ascii=False), encoding="utf-8") round_workspace = ChallengeWorkspace(template) if challenge.sabotaged_files: for relative_path, received_code in challenge.sabotaged_files.items(): round_workspace.write_file(relative_path, received_code) else: round_workspace.reset_target() (template / "detailed_explanation.txt").unlink(missing_ok=True) artifact_hash, tests_hash = _round_hashes(template, private_workspace_dir(template)) manifest: dict[str, str | int] = { "round_id": round_id, "github_url": challenge.github_url, "target_file": challenge.target_file, "artifact_hash": artifact_hash, "tests_hash": tests_hash, "timer_minutes": max(0, min(int(timer_minutes), 120)), "quota_units_per_student": chat_messages_per_student + 2, "chat_messages_per_student": chat_messages_per_student, } (round_dir / "round.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") return manifest def create_challenge_from_round( round_id: str, workspace_id: str, course_id: str = "local" ) -> tuple[str, dict[str, str | int]]: """Create an isolated participant workspace from a verified round snapshot.""" from architect.repo_cloner import WORKSPACES_DIR safe_round_id = str(UUID(round_id)) safe_workspace_id = str(UUID(workspace_id)) round_dir = _rounds_root() / safe_round_id manifest_path = round_dir / "round.json" template = round_dir / "workspace" if not manifest_path.is_file() or not template.is_dir(): from supabase_challenge_rounds import ChallengeRoundStoreError, load_challenge_round try: stored_round = load_challenge_round(safe_round_id, course_id) except ChallengeRoundStoreError as exc: raise FileNotFoundError(f"Could not load this shared round from persistent storage: {exc}") from exc if stored_round is None: raise FileNotFoundError("Challenge round was not found") stored_manifest, archive_bytes = stored_round template = _restore_challenge_round_archive(safe_round_id, stored_manifest, archive_bytes) round_dir = template.parent manifest_path = round_dir / "round.json" try: manifest = json.loads(manifest_path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise FileNotFoundError("Challenge round was not found") from exc if manifest.get("round_id") != safe_round_id or not template.is_dir(): raise FileNotFoundError("Challenge round was not found") actual_hashes = _round_hashes(template, private_workspace_dir(template)) if actual_hashes != (manifest.get("artifact_hash"), manifest.get("tests_hash")): raise ValueError("Challenge round integrity check failed") workspace_path = Path(WORKSPACES_DIR).resolve() / safe_workspace_id if workspace_path.exists(): raise FileExistsError("Challenge workspace already exists") shutil.copytree(template, workspace_path) try: _copy_round_private_files(template, workspace_path) state_path = workspace_path / "challenge_state.json" private_state_path = private_workspace_dir(workspace_path) / "challenge_state.json" state = json.loads(private_state_path.read_text(encoding="utf-8")) state["workspace_path"] = str(workspace_path) state["challenge_round_id"] = safe_round_id private_state_path.write_text(json.dumps(state, indent=2, ensure_ascii=False), encoding="utf-8") private_state_path.chmod(0o600) state_path.write_text(json.dumps(_student_visible_state(state), indent=2, ensure_ascii=False), encoding="utf-8") (workspace_path / "detailed_explanation.txt").unlink(missing_ok=True) except Exception: shutil.rmtree(workspace_path, ignore_errors=True) shutil.rmtree(private_workspace_dir(workspace_path), ignore_errors=True) raise return str(workspace_path), manifest def create_challenge( github_url: str, nesting_level: int, num_bugs: int, refactoring_enabled: bool = False, debug_mode: bool = False, workspace_id: str | None = None, progress_callback: Callable[[int, str], None] | None = None, generation_id: str | None = None, ) -> str: """Run the architect graph and persist its result into a challenge workspace.""" from architect.bug_first_pipeline import build_selected_graph, get_challenge_pipeline_variant from architect.repo_cloner import WORKSPACES_DIR clone_path = "" if workspace_id: safe_workspace_id = str(UUID(workspace_id)) clone_path = str(Path(WORKSPACES_DIR) / safe_workspace_id) from supabase_generation_prompts import load_generation_prompt_supplements pipeline_variant = get_challenge_pipeline_variant() graph = build_selected_graph(progress_callback=progress_callback) initial_state = { "github_url": github_url, "nesting_level": nesting_level, "refactoring_enabled": refactoring_enabled, "debug_mode": debug_mode, "num_bugs": num_bugs, "clone_path": clone_path, "target_file": "", "original_code": "", "sabotaged_code": "", "function_name": "", "test_args": "", "expected_output": "", "actual_output": "", "bug_description": "", "detailed_explanation": "", "challenge_summary": "", "test_cases": [], "public_tests": [], "secret_tests": [], "candidate_files": [], "bug_func_name": "", "bug_func_source": "", "call_chain": {}, "generation_id": generation_id or str(uuid4()), "generation_progress_callback": progress_callback, "prompt_supplements": load_generation_prompt_supplements(), "generation_failures": [], "generation_usage": {}, } result = graph.invoke(initial_state) try: from supabase_generation_prompts import record_generation_event record_generation_event(generation_id or "", "generation_benchmark", "node_timings", payload=result.get("node_timings") or {}) except Exception: pass workspace_path = result["clone_path"] workspace_root = Path(workspace_path).resolve() target_file_rel = "" target_file_value = str(result.get("target_file") or "") if target_file_value: target_path = Path(target_file_value) if not target_path.is_absolute(): target_path = workspace_root / target_path try: target_path = target_path.resolve(strict=True) target_file_rel = target_path.relative_to(workspace_root).as_posix() except (FileNotFoundError, OSError, ValueError) as exc: raise ValueError("Generated challenge target file is outside the workspace or unavailable") from exc actual_sabotaged_code = result.get("sabotaged_code", "") workspace_root = Path(workspace_path).resolve() if target_file_rel: target_path = Path(workspace_path) / target_file_rel if target_path.exists(): actual_sabotaged_code = target_path.read_text(encoding="utf-8") sabotaged_files: dict[str, str] = {} if target_file_rel and actual_sabotaged_code: try: relative_path = Path(target_file_rel).resolve().relative_to(workspace_root).as_posix() except (ValueError, OSError): relative_path = Path(target_file_rel).as_posix() sabotaged_files[relative_path] = actual_sabotaged_code challenge_state = { "github_url": github_url, "workspace_path": workspace_path, "challenge_created_at": datetime.now().isoformat(), "target_file": target_file_rel, "original_code": result.get("original_code", ""), "sabotaged_code": actual_sabotaged_code, "sabotaged_files": sabotaged_files, "function_name": result.get("function_name", ""), "bug_func_name": result.get("bug_func_name", ""), "bug_func_source": result.get("bug_func_source", ""), "original_bug_func_source": result.get("original_bug_func_source", ""), "bug_func_names": result.get("bug_func_names", []), "bug_func_sources_list": result.get("bug_func_sources_list", []), "original_bug_func_sources_list": result.get("original_bug_func_sources_list", []), "test_cases": result.get("test_cases", []), "public_tests": result.get("public_tests", []), "nesting_level": nesting_level, "refactoring_enabled": refactoring_enabled, "debug_mode": debug_mode, "pipeline_variant": pipeline_variant, "bug_description": result.get("bug_description", ""), "detailed_explanation": result.get("detailed_explanation", ""), "challenge_summary": result.get("challenge_summary", ""), } state_path = Path(workspace_path) / "challenge_state.json" private_state_path = ensure_private_workspace_dir(workspace_path) / "challenge_state.json" private_state_path.write_text(json.dumps(challenge_state, indent=2, ensure_ascii=False), encoding="utf-8") private_state_path.chmod(0o600) state_path.write_text(json.dumps(_student_visible_state(challenge_state), indent=2, ensure_ascii=False), encoding="utf-8") (Path(workspace_path) / "detailed_explanation.txt").unlink(missing_ok=True) if progress_callback: progress_callback(99, "Finalizing challenge workspace") return workspace_path class ChallengeWorkspace: """Read and edit only student-visible Python files in a challenge workspace.""" _HIDDEN_NAMES = {"challenge_run.py", "challenge_run_secret.py"} def __init__(self, workspace_path: str | Path) -> None: from architect.repo_cloner import WORKSPACES_DIR self.workspace = Path(workspace_path).resolve() workspaces_root = Path(WORKSPACES_DIR).resolve() try: self.workspace.relative_to(workspaces_root) except ValueError as exc: raise ValueError("Workspace must be inside the workspaces directory") from exc state_path = self.workspace / "challenge_state.json" if not state_path.is_file(): raise FileNotFoundError("Challenge state was not found") private_dir = ensure_private_workspace_dir(self.workspace) private_state_path = private_dir / "challenge_state.json" visible_data = json.loads(state_path.read_text(encoding="utf-8")) if private_state_path.is_file(): self.data = json.loads(private_state_path.read_text(encoding="utf-8")) else: self.data = visible_data private_state_path.write_text(json.dumps(self.data, ensure_ascii=False), encoding="utf-8") private_state_path.chmod(0o600) legacy_secret_tests = self.data.pop("secret_tests", None) secret_data_path = private_dir / "secret_tests.json" if legacy_secret_tests is not None and not secret_data_path.is_file(): secret_data_path.write_text( json.dumps({"secret_tests": legacy_secret_tests}, ensure_ascii=False), encoding="utf-8", ) secret_data_path.chmod(0o600) private_runners = { "challenge_run.py": private_dir / "challenge_run_public.py", "challenge_run_secret.py": private_dir / "challenge_run_secret.py", } legacy_runners = tuple( (self.workspace / runner_name, private_runner) for runner_name, private_runner in private_runners.items() ) + ( (self.workspace / ".metadata" / "challenge_run_secret.py", private_runners["challenge_run_secret.py"]), ) for legacy_runner, private_runner in legacy_runners: if not private_runner.is_file() and legacy_runner.is_file(): shutil.copyfile(legacy_runner, private_runner) private_runner.chmod(0o600) migrated = legacy_secret_tests is not None for legacy_runner, _private_runner in legacy_runners: if legacy_runner.is_file(): try: legacy_runner.chmod(stat.S_IRUSR | stat.S_IWUSR) legacy_runner.unlink() migrated = True except OSError: pass if migrated or visible_data != _student_visible_state(self.data): state_path.write_text(json.dumps(_student_visible_state(self.data), indent=2, ensure_ascii=False), encoding="utf-8") if migrated: private_state_path.write_text(json.dumps(self.data, indent=2, ensure_ascii=False), encoding="utf-8") private_state_path.chmod(0o600) target = Path(self.data.get("target_file", "")) if target.is_absolute(): try: target = target.resolve().relative_to(self.workspace) except ValueError as exc: raise ValueError("Challenge target is outside its workspace") from exc self.target_file = target.as_posix() self.github_url = str(self.data.get("github_url", "")) self.original_code = str(self.data.get("original_code", "")) self.sabotaged_code = str(self.data.get("sabotaged_code", "")) self.bug_func_source = str(self.data.get("bug_func_source", "")) self.original_bug_func_source = str(self.data.get("original_bug_func_source", "")) self.sabotaged_files = dict(self.data.get("sabotaged_files", {})) self.bug_description = str(self.data.get("bug_description", "")) self.challenge_summary = str(self.data.get("challenge_summary", "")) self.function_name = str(self.data.get("function_name", "")) self.bug_func_name = str(self.data.get("bug_func_name", "")) self.bug_func_names = list(self.data.get("bug_func_names", [])) self.bug_func_sources_list = list(self.data.get("bug_func_sources_list", [])) self.original_bug_func_sources_list = list(self.data.get("original_bug_func_sources_list", [])) self.public_tests = list(self.data.get("public_tests", [])) try: secret_path = private_dir / "secret_tests.json" private_data = json.loads(secret_path.read_text(encoding="utf-8")) self.secret_tests = list(private_data.get("secret_tests", [])) except (OSError, ValueError, json.JSONDecodeError): self.secret_tests = [] self.nesting_level = int(self.data.get("nesting_level", 3)) self.refactoring_enabled = bool(self.data.get("refactoring_enabled", False)) self.debug_mode = bool(self.data.get("debug_mode", False)) @property def target_path(self) -> Path: return self._resolve_python_file(self.target_file) def _resolve_python_file(self, rel_path: str) -> Path: if not isinstance(rel_path, str) or not rel_path.strip(): raise ValueError("A relative Python file path is required") normalized = rel_path.replace("\\", "/") pure_path = PurePosixPath(normalized) if pure_path.is_absolute() or ".." in pure_path.parts or ".metadata" in pure_path.parts: raise ValueError("File path is not available") if pure_path.name in self._HIDDEN_NAMES or pure_path.suffix != ".py": raise ValueError("File path is not available") full_path = (self.workspace / Path(*pure_path.parts)).resolve() try: full_path.relative_to(self.workspace) except ValueError as exc: raise ValueError("File path is outside the challenge workspace") from exc return full_path def list_python_files(self) -> list[str]: files = sorted(self.workspace.rglob("*.py")) return [ file.relative_to(self.workspace).as_posix() for file in files if file.is_file() and ".metadata" not in file.relative_to(self.workspace).parts and file.name not in self._HIDDEN_NAMES ] def read_file(self, rel_path: str) -> str: file_path = self._resolve_python_file(rel_path) if not file_path.is_file(): raise FileNotFoundError("Python file was not found") return file_path.read_text(encoding="utf-8") def write_file(self, rel_path: str, content: str) -> None: if not isinstance(content, str): raise ValueError("File contents must be text") file_path = self._resolve_python_file(rel_path) if not file_path.is_file(): raise FileNotFoundError("Python file was not found") file_path.write_text(content, encoding="utf-8") def reset_target(self) -> str: self.write_file(self.target_file, self.sabotaged_code) return self.sabotaged_code def readme(self) -> str: readme_path = self.workspace / "STUDENT_README.md" return readme_path.read_text(encoding="utf-8") if readme_path.is_file() else "" def challenge_info(self) -> dict: return { "function_name": self.function_name, "bug_func_name": self.bug_func_name, "target_file": self.target_file, "nesting_level": self.nesting_level, "refactoring_enabled": self.refactoring_enabled, "debug_mode": self.debug_mode, "bug_func_names": self.bug_func_names, "bug_func_sources_list": self.bug_func_sources_list, "original_bug_func_sources_list": self.original_bug_func_sources_list, }