import re import time from pathlib import Path from typing import Optional from git import Repo from git.exc import GitCommandError, InvalidGitRepositoryError, NoSuchPathError class GitManager: def __init__(self, project_dir: Path, *, branch_namespace: str = ""): self.project_dir = project_dir self.branch_namespace = self._sanitize_branch(branch_namespace) try: self.repo = Repo(str(project_dir)) except (InvalidGitRepositoryError, NoSuchPathError): self.repo = self._init_repository(project_dir) except Exception: raise ValueError("Not a git repository. Initialize with 'git init' first.") if self.repo.bare: raise ValueError("Bare repository not supported") @staticmethod def _init_repository(project_dir: Path) -> Repo: """Initialize a fresh repository with an initial commit. A brand-new project directory -- the normal ``grillme`` starting point -- has no ``.git`` yet. Branch/worktree isolation needs at least one commit to branch from, so this creates one immediately instead of leaving every task in the run without git-based isolation or rollback. """ repo = Repo.init(str(project_dir), initial_branch="main") with repo.config_writer() as config: config.set_value("user", "name", "AFK Developer") config.set_value("user", "email", "afk-developer@localhost") repo.git.add("--all") repo.git.commit("--allow-empty", "-m", "Initial commit (AFK Developer)") return repo def _sanitize_branch(self, name: str) -> str: sanitized = re.sub(r"[^a-zA-Z0-9_-]", "-", name.lower()) sanitized = re.sub(r"-+", "-", sanitized) sanitized = sanitized.strip("-") return sanitized[:50] def task_branch_name(self, task_id: str) -> str: """Return the stable branch name used for a task within this plan.""" task_name = self._sanitize_branch(task_id) return ( f"afk/{self.branch_namespace}/{task_name}" if self.branch_namespace else f"afk/{task_name}" ) @property def current_branch(self) -> str: return self.repo.active_branch.name def is_clean(self) -> bool: return not self.repo.is_dirty(untracked_files=True) def create_task_branch(self, task_id: str, *, start_point: str | None = None) -> str: branch_name = self.task_branch_name(task_id) try: new_branch = ( self.repo.create_head(branch_name, self.repo.commit(start_point)) if start_point else self.repo.create_head(branch_name) ) new_branch.checkout() return branch_name except GitCommandError as e: raise RuntimeError(f"Failed to create branch {branch_name}: {e}") except OSError as e: # GitPython raises a plain OSError (not GitCommandError) when the ref # already exists pointing at a different commit -- e.g. a prior failed # attempt left this same task branch behind (discard_branch_on_failure # defaults to False) and the base branch has since moved on. Callers # that might be re-attempting an existing task should use # checkout_or_create_task_branch instead; this still turns the raw # OSError into the same catchable RuntimeError as the GitCommandError # case above, instead of crashing the whole process. raise RuntimeError(f"Failed to create branch {branch_name}: {e}") def checkout_or_create_task_branch( self, task_id: str, *, start_point: str | None = None ) -> str: """Resume a task branch, or create it from a clean start point. A provider outage can interrupt a task after it has written a partial, reviewable diff. Retrying must resume that branch rather than start a different branch or overwrite the retained worktree state. A new implementation branch can be anchored to a retained red-test branch. """ branch_name = self.task_branch_name(task_id) if self.current_branch == branch_name: return branch_name if self.has_changes(): raise RuntimeError( "Cannot switch to a task branch while the current branch has uncommitted changes." ) try: branch = self.repo.heads[branch_name] except IndexError: return self.create_task_branch(task_id, start_point=start_point) if start_point is not None and not self._is_ancestor(start_point, branch_name): # A retained red-regression predecessor is an immutable part of # the implementation contract. Never resume a same-named stale # branch that predates it: that would let a retry review/merge # implementation without the witnesses it is required to repair. self.repo.delete_head(branch_name, force=True) return self.create_task_branch(task_id, start_point=start_point) branch.checkout() return branch_name def primary_contains_files(self, paths: list[str]) -> bool: """Return whether every project-relative path exists on the primary branch. Finalization and retry shortcuts use this rather than the current worktree so a task cannot be marked passed merely because stale branch files happen to be present locally. """ target = next( (name for name in ("main", "master", "trunk") if name in self.repo.heads), None, ) if target is None: return False for path in paths: try: self.repo.git.cat_file("-e", f"{target}:{path}") except GitCommandError: return False return True def _is_ancestor(self, ancestor: str, descendant: str) -> bool: try: self.repo.git.merge_base("--is-ancestor", ancestor, descendant) return True except GitCommandError: return False def worktree_path_for(self, task_id: str, worktree_root: Path) -> Path: """Return the deterministic isolated worktree directory for a task ID.""" task_name = self._sanitize_branch(task_id) return ( worktree_root / f"{self.branch_namespace}-{task_name}" if self.branch_namespace else worktree_root / task_name ) def create_task_worktree( self, task_id: str, worktree_root: Path, *, start_point: str | None = None ) -> tuple[str, Path]: """Create (or resume) an isolated worktree checked out to the task's own branch. Unlike ``create_task_branch``/``checkout_or_create_task_branch``, this never checks the branch out in the shared primary working tree, so another task's branch can stay checked out there at the same time. The branch is created fresh if it does not already exist; an existing worktree directory is resumed as-is (mirrors the retained-branch resume semantics of ``checkout_or_create_task_branch``). """ branch_name = self.task_branch_name(task_id) path = self.worktree_path_for(task_id, worktree_root) if ( start_point is not None and branch_name in self.repo.heads and not self._is_ancestor(start_point, branch_name) ): # A linked worktree can retain the same stale branch as the # in-place path above. Remove it before deleting/recreating the # ref, otherwise Git refuses to replace a checked-out branch. if path.exists() and not self.remove_task_worktree(path, force=True): raise RuntimeError(f"Could not remove stale worktree for {branch_name}.") self.delete_branch(branch_name) if path.exists(): return branch_name, path worktree_root.mkdir(parents=True, exist_ok=True) try: if branch_name in self.repo.heads: self.repo.git.worktree("add", str(path), branch_name) else: args = ["add", str(path), "-b", branch_name] if start_point: args.append(start_point) self.repo.git.worktree(*args) except GitCommandError as e: raise RuntimeError(f"Failed to create worktree for {branch_name}: {e}") return branch_name, path def remove_task_worktree(self, path: Path, *, force: bool = False) -> bool: """Remove a linked worktree. Safe to call on an already-removed path. Retries briefly: a worktree just used for a commit can still have a file lock held (observed on Windows) for a moment after the operation that touched it returns. """ if not path.exists(): self.prune_worktrees() return True args = ["remove"] if force: args.append("--force") args.append(str(path)) for attempt in range(3): try: self.repo.git.worktree(*args) return True except GitCommandError: if attempt == 2: return False time.sleep(0.3) return False def discard_task_worktree(self, path: Path, branch_name: str) -> bool: """Remove an unaccepted task's worktree and delete its branch from the primary repo.""" if not self.remove_task_worktree(path, force=True): return False self.delete_branch(branch_name) return True def prune_worktrees(self) -> None: """Clean up administrative worktree metadata for manually deleted directories.""" try: self.repo.git.worktree("prune") except GitCommandError: pass def commit_changes(self, message: str, files: Optional[list[str]] = None) -> bool: try: if files: self.repo.index.add(files) else: # Use Git's normal staging semantics so .gitignore protects cache files, # virtual environments, and other generated artifacts created by test runs. self.repo.git.add("--all") self.repo.index.commit(message) return True except GitCommandError: return False def has_changes(self) -> bool: return self.repo.is_dirty(untracked_files=True) def worktree_files(self) -> list[str]: """Return existing project-relative files changed from ``HEAD``. Agent completion messages are advisory and can include disposable helper scripts that were deleted before review. Review ownership must instead come from Git's current worktree, including untracked artifacts that are still present. Deleted paths are deliberately omitted because they cannot be formatted or linted as task-owned files. """ changed = set(self.repo.git.diff("--name-only", "HEAD").splitlines()) changed.update(self.repo.untracked_files) files: list[str] = [] root = self.project_dir.resolve() for raw_path in changed: candidate = (root / raw_path).resolve() if candidate.is_relative_to(root) and candidate.is_file(): files.append(candidate.relative_to(root).as_posix()) return sorted(set(files)) def merge_branch_into(self, branch_name: str, target_branch: str = "main") -> bool: """Merge a named branch — possibly checked out only in a linked worktree — into target.""" try: target = getattr(self.repo.heads, target_branch, None) if target is None: target = self.repo.active_branch default_names = ["main", "master", "trunk"] for name in default_names: if name in self.repo.heads: target = self.repo.heads[name] break target.checkout() self.repo.git.merge(branch_name, "--no-ff", "-m", f"Merge task branch '{branch_name}'") return True except GitCommandError: self.repo.git.merge("--abort", with_exceptions=False) return False def merge_to_branch(self, target_branch: str = "main") -> bool: return self.merge_branch_into(self.repo.active_branch.name, target_branch) def delete_branch(self, branch_name: Optional[str] = None): try: if branch_name: self.repo.delete_head(branch_name, force=True) else: branch_name = self.repo.active_branch.name if branch_name.startswith("afk/"): self.repo.delete_head(branch_name, force=True) except GitCommandError: pass def discard_changes(self): try: self.repo.git.checkout("--", ".") except GitCommandError: pass def discard_task_branch(self, branch_name: str) -> bool: """Remove an unaccepted task branch and restore a clean default branch.""" try: self.repo.git.reset("--hard") self.repo.git.clean("-fd") target = next( (name for name in ("main", "master", "trunk") if name in self.repo.heads), None, ) if target is None: raise RuntimeError("No default branch is available for task cleanup.") self.repo.heads[target].checkout() self.repo.git.clean("-fd") if branch_name in self.repo.heads: self.repo.delete_head(branch_name, force=True) return self.is_clean() except (GitCommandError, RuntimeError): return False