|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import re |
| 4 | +import subprocess |
| 5 | +from dataclasses import dataclass |
| 6 | +from datetime import UTC, datetime |
| 7 | +from pathlib import Path, PurePosixPath |
| 8 | + |
| 9 | + |
| 10 | +_SAFE_ID = re.compile(r"^[A-Za-z0-9_-]+$") |
| 11 | +_BLOCKED_PARTS = {".git", ".env", "secrets", "credentials", "state"} |
| 12 | + |
| 13 | + |
| 14 | +@dataclass(frozen=True) |
| 15 | +class MutationContract: |
| 16 | + goal_id: str |
| 17 | + work_item_id: str |
| 18 | + repo_root: Path |
| 19 | + worktree_path: Path |
| 20 | + base_ref: str |
| 21 | + deadline: datetime |
| 22 | + path_allowlist: tuple[str, ...] |
| 23 | + idempotency_key: str |
| 24 | + implementation_owner: str |
| 25 | + |
| 26 | + def validate(self, *, now: datetime | None = None) -> None: |
| 27 | + current = now or datetime.now(UTC) |
| 28 | + if not _SAFE_ID.fullmatch(self.goal_id) or not _SAFE_ID.fullmatch(self.work_item_id): |
| 29 | + raise ValueError("Goal and work-item IDs must be path-safe") |
| 30 | + if not self.idempotency_key.strip() or not self.implementation_owner.strip(): |
| 31 | + raise ValueError("Idempotency key and implementation owner are required") |
| 32 | + if not self.path_allowlist: |
| 33 | + raise ValueError("At least one allowed path pattern is required") |
| 34 | + if self.deadline.tzinfo is None or self.deadline <= current: |
| 35 | + raise TimeoutError("Mutation work item deadline has expired") |
| 36 | + repo = self.repo_root.resolve() |
| 37 | + worktree = self.worktree_path.resolve() |
| 38 | + if repo == worktree or repo in worktree.parents: |
| 39 | + raise ValueError("Mutation worktree must be distinct from and outside the source repository") |
| 40 | + |
| 41 | + |
| 42 | +@dataclass(frozen=True) |
| 43 | +class SandboxManifest: |
| 44 | + goal_id: str |
| 45 | + work_item_id: str |
| 46 | + worktree_path: str |
| 47 | + branch: str |
| 48 | + base_sha: str |
| 49 | + idempotency_key: str |
| 50 | + implementation_owner: str |
| 51 | + |
| 52 | + |
| 53 | +@dataclass(frozen=True) |
| 54 | +class ArtifactManifest: |
| 55 | + goal_id: str |
| 56 | + work_item_id: str |
| 57 | + idempotency_key: str |
| 58 | + changed_files: tuple[str, ...] |
| 59 | + worktree_path: str |
| 60 | + |
| 61 | + |
| 62 | +class GitWorktreeSandbox: |
| 63 | + def __init__(self, contract: MutationContract) -> None: |
| 64 | + self.contract = contract |
| 65 | + self._manifest: SandboxManifest | None = None |
| 66 | + |
| 67 | + def create(self) -> SandboxManifest: |
| 68 | + self.contract.validate() |
| 69 | + if self.contract.worktree_path.exists(): |
| 70 | + raise FileExistsError(f"Worktree already exists: {self.contract.worktree_path}") |
| 71 | + self.contract.worktree_path.parent.mkdir(parents=True, exist_ok=True) |
| 72 | + base_sha = self._git_source("rev-parse", self.contract.base_ref).stdout.strip() |
| 73 | + branch = f"codex/{self.contract.goal_id}-{self.contract.work_item_id}" |
| 74 | + self._git_source("worktree", "add", "-b", branch, str(self.contract.worktree_path), base_sha) |
| 75 | + self._manifest = SandboxManifest( |
| 76 | + self.contract.goal_id, |
| 77 | + self.contract.work_item_id, |
| 78 | + str(self.contract.worktree_path.resolve()), |
| 79 | + branch, |
| 80 | + base_sha, |
| 81 | + self.contract.idempotency_key, |
| 82 | + self.contract.implementation_owner, |
| 83 | + ) |
| 84 | + return self._manifest |
| 85 | + |
| 86 | + def authorize_mutation(self, actor: str) -> None: |
| 87 | + self.contract.validate() |
| 88 | + if actor != self.contract.implementation_owner: |
| 89 | + raise PermissionError(f"Mutation owner is {self.contract.implementation_owner}, not {actor}") |
| 90 | + |
| 91 | + def resolve_write_path(self, relative_path: str) -> Path: |
| 92 | + self.contract.validate() |
| 93 | + if self._manifest is None: |
| 94 | + raise RuntimeError("Sandbox has not been created") |
| 95 | + normalized = relative_path.replace("\\", "/").lstrip("./") |
| 96 | + pure = PurePosixPath(normalized) |
| 97 | + if not normalized or pure.is_absolute() or ".." in pure.parts or any(part.lower() in _BLOCKED_PARTS for part in pure.parts): |
| 98 | + raise ValueError(f"Write path is blocked: {relative_path}") |
| 99 | + if not any(pure.match(pattern) for pattern in self.contract.path_allowlist): |
| 100 | + raise ValueError(f"Write path is outside the allowlist: {relative_path}") |
| 101 | + target = (self.contract.worktree_path / Path(*pure.parts)).resolve() |
| 102 | + if self.contract.worktree_path.resolve() not in target.parents: |
| 103 | + raise ValueError(f"Write path escapes the worktree: {relative_path}") |
| 104 | + return target |
| 105 | + |
| 106 | + def capture_artifacts(self) -> ArtifactManifest: |
| 107 | + if self._manifest is None: |
| 108 | + raise RuntimeError("Sandbox has not been created") |
| 109 | + result = subprocess.run( |
| 110 | + ["git", "-C", str(self.contract.worktree_path), "status", "--porcelain", "--untracked-files=all"], |
| 111 | + check=True, |
| 112 | + capture_output=True, |
| 113 | + text=True, |
| 114 | + ) |
| 115 | + changed = tuple(sorted(line[3:].strip() for line in result.stdout.splitlines() if len(line) >= 4)) |
| 116 | + return ArtifactManifest( |
| 117 | + self.contract.goal_id, |
| 118 | + self.contract.work_item_id, |
| 119 | + self.contract.idempotency_key, |
| 120 | + changed, |
| 121 | + str(self.contract.worktree_path.resolve()), |
| 122 | + ) |
| 123 | + |
| 124 | + def _git_source(self, *args: str) -> subprocess.CompletedProcess[str]: |
| 125 | + return subprocess.run(["git", "-C", str(self.contract.repo_root), *args], check=True, capture_output=True, text=True) |
0 commit comments