From 3196b5e6f5a8b1bb18bd7e53cfaa942c83022b4e Mon Sep 17 00:00:00 2001 From: Richard Levasseur Date: Fri, 13 Nov 2026 09:15:07 -0800 Subject: [PATCH] agents: remove worktree last and handle read-only output base files Read-only directories in Bazel output bases caused cleanup removal to fail, while removing the Git worktree before branch deletion left the workspace directory gone even when cleanup failed partway through. Grant owner read/write/execute permissions across output base trees without following symlinks before recursive removal, and reorder cleanup to remove the Bazel output base, remote branch, and local branch (detaching HEAD first) before deleting the Git worktree only when all prior steps succeed. --- .agents/skills/conversation-done/SKILL.md | 13 +- .../conversation-done/scripts/BUILD.bazel | 6 + .../conversation-done/scripts/cleanup.py | 523 ++++++++++------ .../conversation-done/scripts/cleanup_test.py | 214 ------- tests/agents/BUILD.bazel | 19 + tests/agents/cleanup_test.py | 577 ++++++++++++++++++ 6 files changed, 963 insertions(+), 389 deletions(-) create mode 100644 .agents/skills/conversation-done/scripts/BUILD.bazel delete mode 100755 .agents/skills/conversation-done/scripts/cleanup_test.py create mode 100644 tests/agents/BUILD.bazel create mode 100644 tests/agents/cleanup_test.py diff --git a/.agents/skills/conversation-done/SKILL.md b/.agents/skills/conversation-done/SKILL.md index 21b6285a5c..4edfd6e191 100644 --- a/.agents/skills/conversation-done/SKILL.md +++ b/.agents/skills/conversation-done/SKILL.md @@ -18,10 +18,11 @@ conversation directory (`~/.gemini/jetski/brain/`) are created: 1. **Bazel Output Base(s)**: Intermediate build artifacts, execroot trees, and running Bazel server and persistent worker processes (consuming tens of gigabytes of disk and substantial RAM). -2. **Git Worktree**: The checked-out directory on disk. -3. **Local Git Branch**: The feature branch associated with the worktree. -4. **Remote Git Branch**: The feature branch pushed to the user's fork +2. **Remote Git Branch**: The feature branch pushed to the user's fork (e.g., `origin`). +3. **Local Git Branch**: The feature branch associated with the worktree. +4. **Git Worktree**: The checked-out directory on disk (removed last, and only + if all other cleanup steps succeed). 5. **Conversation Name**: Once cleanup completes without errors, the active conversation title is prefixed with `"done "` (without duplicating an existing `"done "` prefix, capped at 70 characters). @@ -97,6 +98,8 @@ Fine-tune what gets cleaned up using selective leave flags: * **Upstream Remote Protection**: Never deletes branches on `upstream`. * **No Expunge Rule**: Never runs `bazel clean --expunge`; shuts down servers gracefully and deletes the specific output base directory directly. +* **Worktree Deleted Last**: Removes the Git worktree only after all other + cleanup steps succeed, keeping the working directory intact on failure. ## Reporting Results @@ -104,9 +107,9 @@ After running the cleanup script, always report to the user what resources were deleted (or would be deleted in `--dry-run` mode), including: * **Bazel Output Base(s)**: Paths and reclaimed disk space sizes. -* **Git Worktree**: Removed worktree directory path. -* **Local Git Branch**: Deleted local branch name. * **Remote Git Branch**: Deleted remote branch (`/`). +* **Local Git Branch**: Deleted local branch name. +* **Git Worktree**: Removed worktree directory path. * **Conversation Name**: Updated conversation title (prefixed with `"done "` after successful cleanup). diff --git a/.agents/skills/conversation-done/scripts/BUILD.bazel b/.agents/skills/conversation-done/scripts/BUILD.bazel new file mode 100644 index 0000000000..199204599e --- /dev/null +++ b/.agents/skills/conversation-done/scripts/BUILD.bazel @@ -0,0 +1,6 @@ +package(default_visibility = ["//tests:__subpackages__"]) + +exports_files( + ["cleanup.py"], + visibility = ["//tests:__subpackages__"], +) diff --git a/.agents/skills/conversation-done/scripts/cleanup.py b/.agents/skills/conversation-done/scripts/cleanup.py index e68f3d8c39..974bc2a694 100755 --- a/.agents/skills/conversation-done/scripts/cleanup.py +++ b/.agents/skills/conversation-done/scripts/cleanup.py @@ -41,14 +41,39 @@ import sys import urllib.error import urllib.request - -PROTECTED_BRANCHES = frozenset({"main", "master", "HEAD"}) -PROTECTED_REMOTES = frozenset({"upstream"}) +from collections.abc import Sequence + +_PROTECTED_BRANCHES = frozenset( + { + # keep-sorted start + "HEAD", + "main", + "master", + # keep-sorted end + } +) +_PROTECTED_REMOTES = frozenset( + { + # keep-sorted start + "upstream", + # keep-sorted end + } +) # Maximum conversation title length displayed by the UI. _CONVERSATION_TITLE_MAX_LENGTH = 70 _DONE_TITLE_PREFIX = "done " -# Local loopback Language Server RPC timeout in seconds. +# Bound urllib.request.urlopen (which has no default timeout) on local loopback RPCs. _LS_RPC_TIMEOUT_SECONDS = 5 +# Cap git ls-remote so unreachable remotes do not stall cleanup. +_GIT_LS_REMOTE_TIMEOUT_SECONDS = 10 +# Bound du -sk so large output bases do not stall informational size reporting. +_DU_TIMEOUT_SECONDS = 5 +# Bound graceful bazel shutdown before falling back to SIGTERM/SIGKILL. +_BAZEL_SHUTDOWN_TIMEOUT_SECONDS = 10 +# Grace period for a lingering Bazel JVM server to exit on SIGTERM before SIGKILL. +_SIGTERM_GRACE_SECONDS = 0.5 +# Allow network round-trips when deleting a remote branch via git push. +_GIT_PUSH_DELETE_TIMEOUT_SECONDS = 30 _GET_TRAJECTORIES_METHOD = ( "exa.language_server_pb.LanguageServerService/GetAllCascadeTrajectories" ) @@ -57,26 +82,67 @@ ) -@dataclasses.dataclass -class WorktreeInfo: - """Information about a Git worktree.""" - - path: str - head: str - branch: str | None - is_main: bool - - -@dataclasses.dataclass -class CleanupTarget: - """Target resources identified for cleanup.""" - - worktree_path: str | None = None - branch: str | None = None - remote: str | None = None - remote_branch_exists: bool = False - bazel_output_bases: list[str] = dataclasses.field(default_factory=list) - is_main_worktree: bool = False +def parse_args(argv: Sequence[str]) -> argparse.Namespace: + """Parses command-line arguments.""" + parser = argparse.ArgumentParser( + description="Clean up agent workspace resources (Bazel output base, worktree, branches)." + ) + parser.add_argument( + "--worktree", + type=str, + default=None, + help="Path to the Git worktree to clean up.", + ) + parser.add_argument( + "--branches", + nargs="+", + default=[], + help="One or more branch names to clean up.", + ) + parser.add_argument( + "--remote", + type=str, + default=None, + help="Remote name for remote branch deletion (default: pushRemote or origin).", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Preview resources to delete without making changes.", + ) + # -f is the standard short alias for non-interactive confirmation when invoked by scripts. + parser.add_argument( + "-f", + "--force", + action="store_true", + help="Proceed with cleanup without interactive confirmation.", + ) + parser.add_argument( + "--list", + action="store_true", + help="List worktrees, branches, and associated Bazel output bases.", + ) + parser.add_argument( + "--leave-bazel-output-base", + action="store_true", + help="Leave Bazel output bases and build caches intact.", + ) + parser.add_argument( + "--leave-worktree", + action="store_true", + help="Leave Git worktree directory on disk.", + ) + parser.add_argument( + "--leave-branch", + action="store_true", + help="Keep local Git branch.", + ) + parser.add_argument( + "--leave-remote", + action="store_true", + help="Do not delete branch from remote fork.", + ) + return parser.parse_args(argv) def log(msg: str) -> None: @@ -100,7 +166,7 @@ async def run_command( capture_output: bool = True, timeout: float | None = None, ) -> subprocess.CompletedProcess[str]: - """Executes a subprocess command asynchronously and safely.""" + """Executes a subprocess command and returns its completed result.""" stdout_pipe = asyncio.subprocess.PIPE if capture_output else None stderr_pipe = asyncio.subprocess.PIPE if capture_output else None try: @@ -156,7 +222,7 @@ async def get_main_repo(cwd: str | None = None) -> str: if res.returncode == 0 and res.stdout.strip(): return os.path.abspath(res.stdout.strip()) - raise RuntimeError("Not inside a Git repository.") + raise CleanupError("Not inside a Git repository.") async def get_current_worktree(cwd: str | None = None) -> str | None: @@ -171,8 +237,7 @@ async def get_worktrees(main_repo: str) -> list[WorktreeInfo]: """Returns all Git worktrees registered in the repository.""" res = await run_command(["git", "-C", main_repo, "worktree", "list", "--porcelain"]) if res.returncode != 0: - log_error(f"Failed to list Git worktrees: {res.stderr.strip()}") - return [] + raise CleanupError(f"Failed to list Git worktrees: {res.stderr.strip()}") worktrees: list[WorktreeInfo] = [] current_wt: str | None = None @@ -216,7 +281,7 @@ def is_protected_branch(branch: str | None) -> bool: """Checks if a branch is protected from deletion.""" if not branch: return True - if branch in PROTECTED_BRANCHES: + if branch in _PROTECTED_BRANCHES: return True if branch.startswith("release/") or branch.startswith("release-"): return True @@ -236,7 +301,7 @@ async def get_push_remote_for_branch(main_repo: str, branch: str) -> str: ["git", "-C", main_repo, "config", f"branch.{branch}.remote"] ) remote = res.stdout.strip() - if remote and remote not in PROTECTED_REMOTES: + if remote and remote not in _PROTECTED_REMOTES: return remote return "origin" @@ -244,11 +309,11 @@ async def get_push_remote_for_branch(main_repo: str, branch: str) -> str: async def remote_branch_exists(main_repo: str, remote: str, branch: str) -> bool: """Checks whether a branch exists on the specified remote.""" - if remote in PROTECTED_REMOTES or is_protected_branch(branch): + if remote in _PROTECTED_REMOTES or is_protected_branch(branch): return False res = await run_command( ["git", "-C", main_repo, "ls-remote", "--heads", remote, branch], - timeout=10, + timeout=_GIT_LS_REMOTE_TIMEOUT_SECONDS, ) return res.returncode == 0 and bool(res.stdout.strip()) @@ -285,7 +350,7 @@ async def get_path_size_human(path: str) -> str: """Returns human-readable size of a directory path.""" if not os.path.exists(path): return "0 B" - res = await run_command(["du", "-sk", path], timeout=5) + res = await run_command(["du", "-sk", path], timeout=_DU_TIMEOUT_SECONDS) if res.returncode == 0 and res.stdout.strip(): try: kb = int(res.stdout.split()[0]) @@ -315,7 +380,7 @@ async def shutdown_and_remove_bazel_output_base( # 1. Graceful shutdown command await run_command( ["bazel", f"--output_base={output_base}", "shutdown"], - timeout=10, + timeout=_BAZEL_SHUTDOWN_TIMEOUT_SECONDS, ) # 2. Check for running server process from server.pid.txt @@ -327,7 +392,7 @@ async def shutdown_and_remove_bazel_output_base( os.kill(pid, 0) log(f" Terminating lingering Bazel server process (PID: {pid})...") os.kill(pid, signal.SIGTERM) - await asyncio.sleep(0.5) + await asyncio.sleep(_SIGTERM_GRACE_SECONDS) try: os.kill(pid, signal.SIGKILL) except OSError: @@ -369,30 +434,103 @@ def terminate_processes_under_path(path: str) -> None: continue +def _ensure_writable(entry_path: str) -> None: + """Grants owner access on regular files and directories without following symlinks. + + Args: + entry_path: Filesystem path whose owner permission bits should be ensured. + """ + try: + st = os.lstat(entry_path) + except OSError: + return + if stat.S_ISDIR(st.st_mode): + needed = stat.S_IRWXU + elif stat.S_ISREG(st.st_mode): + needed = stat.S_IRUSR | stat.S_IWUSR + else: + return + current = stat.S_IMODE(st.st_mode) + if (current & needed) != needed: + try: + os.chmod(entry_path, current | needed) + except OSError: + pass + + +def _make_tree_writable(path: str) -> None: + """Grants owner traversal and write permissions across a directory tree. + + Args: + path: Root directory path to make writable and traversable. + """ + _ensure_writable(path) + for dirpath, dirnames, filenames in os.walk(path, topdown=True, followlinks=False): + for dirname in dirnames: + _ensure_writable(os.path.join(dirpath, dirname)) + for filename in filenames: + _ensure_writable(os.path.join(dirpath, filename)) + + +def _rmtree_with_permissions(path: str) -> None: + """Removes a directory tree after fixing read-only permissions. + + Args: + path: Directory path to remove. + """ + _make_tree_writable(path) + errors: list[tuple[str, BaseException]] = [] + + def _record_exc(_func: object, fpath: str, exc: BaseException) -> None: + if isinstance(exc, FileNotFoundError): + return + errors.append((fpath, exc)) + + if sys.version_info >= (3, 12): + shutil.rmtree(path, onexc=_record_exc) + else: + + def _record_err( + func: object, + fpath: str, + exc_info: tuple[object, BaseException, object], + ) -> None: + _record_exc(func, fpath, exc_info[1]) + + shutil.rmtree(path, onerror=_record_err) + + if errors: + sorted_errors = sorted(errors, key=lambda item: item[0]) + details = "\n".join(f" {fpath}: {exc}" for fpath, exc in sorted_errors) + log_warn(f"Failed to completely remove {path}:\n{details}") + + async def remove_directory_safely(path: str) -> bool: - """Recursively removes a directory tree, making read-only files writable.""" - if not os.path.exists(path) and not os.path.islink(path): + """Removes a directory tree, making read-only entries writable. + + Args: + path: Directory or symlink path to remove. + + Returns: + True if the path no longer exists on disk, False otherwise. + """ + if os.path.islink(path): + try: + os.unlink(path) + return True + except OSError as exc: + log_warn(f"Failed to remove symlink {path}: {exc}") + return False + + if not os.path.exists(path): return True res = await run_command(["rm", "-rf", path]) - if res.returncode == 0 and not os.path.exists(path): + if res.returncode == 0 and not os.path.lexists(path): return True - def _sync_rmtree(): - def _make_writable_and_retry(func, fpath, unused_exc_info): - try: - os.chmod(fpath, stat.S_IWRITE | stat.S_IWUSR | stat.S_IRUSR) - func(fpath) - except OSError: - pass - - try: - shutil.rmtree(path, onerror=_make_writable_and_retry) - except Exception as exc: - log_warn(f"Failed to completely remove {path}: {exc}") - - await asyncio.to_thread(_sync_rmtree) - return not os.path.exists(path) + await asyncio.to_thread(_rmtree_with_permissions, path) + return not os.path.lexists(path) async def remove_git_worktree( @@ -419,6 +557,7 @@ async def remove_git_worktree( os.chdir(real_main) log(f" Removing Git worktree: {worktree_path}") + # --force discards untracked or uncommitted edits left in the finished worktree. res = await run_command( ["git", "-C", real_main, "worktree", "remove", "--force", real_wt] ) @@ -433,24 +572,71 @@ async def remove_git_worktree( async def delete_local_branch( - main_repo: str, branch: str, dry_run: bool = False + main_repo: str, + branch: str, + worktree_path: str | None = None, + dry_run: bool = False, ) -> tuple[bool, str]: - """Deletes a local Git branch.""" + """Deletes a local Git branch, detaching HEAD in its target worktree first. + + Args: + main_repo: Path to the primary Git repository. + branch: Local branch name to delete. + worktree_path: Target worktree path whose HEAD may be detached before + deleting the branch, or None if no worktree is targeted. + dry_run: If True, preview without mutating Git state. + + Returns: + Tuple of (succeeded, status_message). + """ if is_protected_branch(branch): return False, f"Branch '{branch}' is protected and will not be deleted." + branch_check = await run_command( + [ + "git", + "-C", + main_repo, + "show-ref", + "--verify", + "--quiet", + f"refs/heads/{branch}", + ] + ) + if branch_check.returncode != 0: + return True, f"Local branch '{branch}' does not exist." + if dry_run: return True, f"[Dry Run] Would delete local branch '{branch}'." - # Verify branch is not checked out in another worktree + real_main = os.path.realpath(main_repo) + real_target_wt = os.path.realpath(worktree_path) if worktree_path else None + + # Verify branch is not checked out in another worktree; detach target worktree. worktrees = await get_worktrees(main_repo) for wt in worktrees: - if wt.branch == branch and os.path.exists(wt.path): + if wt.branch != branch or not os.path.exists(wt.path): + continue + real_wt = os.path.realpath(wt.path) + is_target_wt = real_wt == real_target_wt and real_wt != real_main + if not is_target_wt: return ( False, f"Branch '{branch}' is still checked out in active worktree: {wt.path}", ) + # Rewrite the HEAD symref directly to its resolved commit SHA (--no-deref) so + # git branch -D can delete the branch without touching dirty worktree files. + detach_res = await run_command( + ["git", "-C", real_wt, "update-ref", "--no-deref", "HEAD", "HEAD"] + ) + if detach_res.returncode != 0: + return ( + False, + f"Failed to detach HEAD in worktree '{wt.path}': " + f"{detach_res.stderr.strip()}", + ) + # -D force-deletes squash-merged or abandoned branches not ancestor-merged into main. res = await run_command(["git", "-C", main_repo, "branch", "-D", branch]) if res.returncode == 0: return True, f"Deleted local branch '{branch}'." @@ -467,7 +653,7 @@ async def delete_remote_branch( if is_protected_branch(branch): return False, f"Branch '{branch}' is protected and will not be deleted." - if remote in PROTECTED_REMOTES: + if remote in _PROTECTED_REMOTES: return ( False, f"Remote '{remote}' is protected (canonical upstream). Branch will not be deleted.", @@ -485,7 +671,7 @@ async def delete_remote_branch( res = await run_command( ["git", "-C", main_repo, "push", remote, "--delete", branch], - timeout=30, + timeout=_GIT_PUSH_DELETE_TIMEOUT_SECONDS, ) if res.returncode == 0: return True, f"Deleted remote branch '{branch}' from '{remote}'." @@ -517,7 +703,7 @@ async def build_cleanup_target( if branch: if not target.remote: target.remote = await get_push_remote_for_branch(main_repo, branch) - if target.remote and target.remote not in PROTECTED_REMOTES: + if target.remote and target.remote not in _PROTECTED_REMOTES: target.remote_branch_exists = await remote_branch_exists( main_repo, target.remote, branch ) @@ -560,43 +746,15 @@ async def execute_cleanup_target( else: log("1. No associated Bazel output bases found.") - # 2. Clean up Git worktree - if not leave_worktree and target.worktree_path: - log("2. Cleaning up Git worktree:") - if await remove_git_worktree(main_repo, target.worktree_path, dry_run=dry_run): - deleted.append(f"Git worktree: {target.worktree_path}") - else: - succeeded = False - elif leave_worktree: - log("2. Leaving Git worktree directory on disk.") - else: - log("2. No worktree directory to remove.") - - # 3. Clean up local Git branch - if not leave_branch and target.branch: - log(f"3. Cleaning up local branch '{target.branch}':") - success, msg = await delete_local_branch( - main_repo, target.branch, dry_run=dry_run - ) - if success: - log(f" {msg}") - deleted.append(f"Local branch: {target.branch}") - else: - log_warn(f" {msg}") - succeeded = False - elif leave_branch: - log("3. Leaving local branch intact.") - else: - log("3. No local branch specified.") - - # 4. Clean up remote Git branch + # 2. Clean up remote Git branch before detaching/deleting local branch + remote_succeeded = True if ( not leave_remote and target.branch and target.remote and target.remote_branch_exists ): - log(f"4. Cleaning up remote branch '{target.branch}' on '{target.remote}':") + log(f"2. Cleaning up remote branch '{target.branch}' on '{target.remote}':") success, msg = await delete_remote_branch( main_repo, target.branch, target.remote, dry_run=dry_run ) @@ -605,11 +763,55 @@ async def execute_cleanup_target( deleted.append(f"Remote branch: {target.remote}/{target.branch}") else: log_warn(f" {msg}") + remote_succeeded = False succeeded = False elif leave_remote: - log("4. Leaving remote branch intact.") + log("2. Leaving remote branch intact.") elif target.branch and target.remote: - log(f"4. Remote branch '{target.branch}' not present on '{target.remote}'.") + log(f"2. Remote branch '{target.branch}' not present on '{target.remote}'.") + + # 3. Clean up local Git branch + if not leave_branch and target.branch: + log(f"3. Cleaning up local branch '{target.branch}':") + if not remote_succeeded and target.worktree_path: + log_warn( + " Skipping local branch deletion because remote branch cleanup failed." + ) + else: + success, msg = await delete_local_branch( + main_repo, + target.branch, + worktree_path=target.worktree_path, + dry_run=dry_run, + ) + if success: + log(f" {msg}") + deleted.append(f"Local branch: {target.branch}") + else: + log_warn(f" {msg}") + succeeded = False + elif leave_branch: + log("3. Leaving local branch intact.") + else: + log("3. No local branch specified.") + + # 4. Clean up Git worktree last, and only if all other cleanup succeeded + if not leave_worktree and target.worktree_path: + log("4. Cleaning up Git worktree:") + if not succeeded: + log_warn( + " Skipping Git worktree removal because earlier cleanup steps failed." + ) + elif await remove_git_worktree( + main_repo, target.worktree_path, dry_run=dry_run + ): + deleted.append(f"Git worktree: {target.worktree_path}") + else: + succeeded = False + elif leave_worktree: + log("4. Leaving Git worktree directory on disk.") + else: + log("4. No worktree directory to remove.") return deleted, succeeded @@ -707,71 +909,45 @@ async def list_resources(main_repo: str) -> None: log(" - No Bazel output base found.") -def parse_args() -> argparse.Namespace: - """Parses command-line arguments.""" - parser = argparse.ArgumentParser( - description="Clean up agent workspace resources (Bazel output base, worktree, branches)." - ) - parser.add_argument( - "--worktree", - type=str, - default=None, - help="Path to the Git worktree to clean up.", - ) - parser.add_argument( - "--branches", - nargs="+", - default=[], - help="One or more branch names to clean up.", - ) - parser.add_argument( - "--remote", - type=str, - default=None, - help="Remote name for remote branch deletion (default: pushRemote or origin).", - ) - parser.add_argument( - "--dry-run", - action="store_true", - help="Preview resources to delete without making changes.", - ) - parser.add_argument( - "-f", - "--force", - action="store_true", - help="Proceed with cleanup without interactive confirmation.", - ) - parser.add_argument( - "--list", - action="store_true", - help="List worktrees, branches, and associated Bazel output bases.", - ) - parser.add_argument( - "--leave-bazel-output-base", - action="store_true", - help="Leave Bazel output bases and build caches intact.", - ) - parser.add_argument( - "--leave-worktree", - action="store_true", - help="Leave Git worktree directory on disk.", - ) - parser.add_argument( - "--leave-branch", - action="store_true", - help="Keep local Git branch.", - ) - parser.add_argument( - "--leave-remote", - action="store_true", - help="Do not delete branch from remote fork.", - ) - return parser.parse_args() +class CleanupError(Exception): + """Raised when workspace or Git discovery fails.""" -async def async_main() -> None: - """Async CLI entrypoint.""" - args = parse_args() +@dataclasses.dataclass +class WorktreeInfo: + """Information about a Git worktree.""" + + # Absolute filesystem path to the worktree root. + path: str + # Commit SHA currently at HEAD in the worktree. + head: str + # Checked-out short branch name, or None when HEAD is detached. + branch: str | None + # Whether this entry represents the primary Git repository worktree. + is_main: bool + + +@dataclasses.dataclass +class CleanupTarget: + """Target resources identified for cleanup.""" + + # Filesystem path to the target Git worktree, or None for branch-only cleanup. + worktree_path: str | None = None + # Local Git branch name associated with the target, if any. + branch: str | None = None + # Git remote name used for remote branch cleanup, if any. + remote: str | None = None + # Whether the target branch currently exists on the configured remote. + remote_branch_exists: bool = False + # Bazel output base directories linked to the target worktree. + bazel_output_bases: list[str] = dataclasses.field(default_factory=list) + # Whether worktree_path points to the primary Git repository worktree. + is_main_worktree: bool = False + + +async def async_main(argv: Sequence[str]) -> None: + """Runs the workspace cleanup CLI workflow.""" + args = parse_args(argv) main_repo = await get_main_repo() if args.list: @@ -852,10 +1028,10 @@ async def async_main() -> None: log(f" Bazel output base: {ob} ({size_str})") else: log(" Bazel output base: None found") - if target.branch: - log(f" Local branch: {target.branch}") if target.remote and target.remote_branch_exists: log(f" Remote branch: {target.remote}/{target.branch}") + if target.branch: + log(f" Local branch: {target.branch}") if not args.force and not args.dry_run and sys.stdin.isatty(): confirm = input("\nProceed with cleanup? [y/N]: ").strip() @@ -891,24 +1067,31 @@ async def async_main() -> None: else: log(" None") - if all_succeeded: - conversation_id = os.environ.get("ANTIGRAVITY_CONVERSATION_ID", "").strip() - ls_address = os.environ.get("ANTIGRAVITY_LS_ADDRESS", "").strip() - csrf_header_value = os.environ.get("ANTIGRAVITY_CSRF_TOKEN", "").strip() - if conversation_id and ls_address and csrf_header_value: - prefix_conversation_title( - conversation_id=conversation_id, - ls_address=ls_address, - csrf_header_value=csrf_header_value, - dry_run=args.dry_run, - ) + if not all_succeeded: + log_error("Cleanup finished with errors.") + sys.exit(1) + + conversation_id = os.environ.get("ANTIGRAVITY_CONVERSATION_ID", "").strip() + ls_address = os.environ.get("ANTIGRAVITY_LS_ADDRESS", "").strip() + csrf_header_value = os.environ.get("ANTIGRAVITY_CSRF_TOKEN", "").strip() + if conversation_id and ls_address and csrf_header_value: + prefix_conversation_title( + conversation_id=conversation_id, + ls_address=ls_address, + csrf_header_value=csrf_header_value, + dry_run=args.dry_run, + ) log("\nCleanup completed.") def main() -> None: """Main CLI entrypoint.""" - asyncio.run(async_main()) + try: + asyncio.run(async_main(sys.argv[1:])) + except CleanupError as exc: + log_error(str(exc)) + sys.exit(1) if __name__ == "__main__": diff --git a/.agents/skills/conversation-done/scripts/cleanup_test.py b/.agents/skills/conversation-done/scripts/cleanup_test.py deleted file mode 100755 index 52285ee493..0000000000 --- a/.agents/skills/conversation-done/scripts/cleanup_test.py +++ /dev/null @@ -1,214 +0,0 @@ -#!/usr/bin/env python3 -"""Unit tests for the async cleanup script.""" - -import os -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -# Ensure scripts dir is in sys.path -sys_path = os.path.dirname(os.path.abspath(__file__)) -if sys_path not in sys.path: - sys.path.insert(0, sys_path) - -import cleanup # noqa: E402 - - -class CleanupScriptTest(unittest.IsolatedAsyncioTestCase): - """Tests for cleanup.py async logic and safety guards.""" - - def test_is_protected_branch(self): - """Verifies protected branches cannot be deleted.""" - self.assertTrue(cleanup.is_protected_branch("main")) - self.assertTrue(cleanup.is_protected_branch("master")) - self.assertTrue(cleanup.is_protected_branch("HEAD")) - self.assertTrue(cleanup.is_protected_branch("release/1.0")) - self.assertTrue(cleanup.is_protected_branch("release/2026-08")) - self.assertTrue(cleanup.is_protected_branch("release-1.0")) - self.assertTrue(cleanup.is_protected_branch("release-2026-08")) - self.assertTrue(cleanup.is_protected_branch(None)) - self.assertFalse(cleanup.is_protected_branch("feature/my-cool-branch")) - self.assertFalse(cleanup.is_protected_branch("bugfix-1234")) - - async def test_worktrees_parsing(self): - """Verifies parsing git worktree list porcelain output.""" - sample_output = """worktree /path/to/main/repo -HEAD 03f212c3f3b590a7103d512650ce09818d30d218 -branch refs/heads/main - -worktree /path/to/worktrees/feat1 -HEAD f130aea7fa0eab7d558897ed0ad915a1057e065c -branch refs/heads/feat1 - -worktree /path/to/worktrees/detached -HEAD 21e9bd5b3b069d4057abac69adf985b7907308f8 -detached -""" - with mock.patch("cleanup.run_command") as mock_run: - mock_run.return_value = subprocess.CompletedProcess( - args=[], returncode=0, stdout=sample_output, stderr="" - ) - worktrees = await cleanup.get_worktrees("/path/to/main/repo") - - self.assertEqual(len(worktrees), 3) - self.assertEqual(worktrees[0].path, "/path/to/main/repo") - self.assertTrue(worktrees[0].is_main) - self.assertEqual(worktrees[0].branch, "main") - - self.assertEqual(worktrees[1].path, "/path/to/worktrees/feat1") - self.assertFalse(worktrees[1].is_main) - self.assertEqual(worktrees[1].branch, "feat1") - - self.assertEqual(worktrees[2].path, "/path/to/worktrees/detached") - self.assertFalse(worktrees[2].is_main) - self.assertIsNone(worktrees[2].branch) - - def test_find_bazel_output_bases(self): - """Verifies finding Bazel output bases matching target workspace.""" - with tempfile.TemporaryDirectory() as temp_dir: - user_dir = os.path.join(temp_dir, "_bazel_testuser") - os.makedirs(user_dir) - - # Output base 1: matches main worktree - ob1 = os.path.join(user_dir, "hash1") - os.makedirs(ob1) - with open(os.path.join(ob1, "DO_NOT_BUILD_HERE"), "w") as f: - f.write("/home/user/worktrees/my_feature\n") - - # Output base 2: matches nested integration workspace - ob2 = os.path.join(user_dir, "hash2") - os.makedirs(ob2) - with open(os.path.join(ob2, "DO_NOT_BUILD_HERE"), "w") as f: - f.write("/home/user/worktrees/my_feature/tests/integration/nested\n") - - # Output base 3: unrelated workspace - ob3 = os.path.join(user_dir, "hash3") - os.makedirs(ob3) - with open(os.path.join(ob3, "DO_NOT_BUILD_HERE"), "w") as f: - f.write("/home/user/worktrees/different_feature\n") - - with mock.patch("os.path.expanduser", return_value=temp_dir): - bases = cleanup.find_bazel_output_bases( - "/home/user/worktrees/my_feature" - ) - - self.assertEqual(sorted(bases), sorted([ob1, ob2])) - - async def test_main_repo_safety(self): - """Verifies refusal to remove main repository worktree.""" - main_repo = "/repo/main" - target = cleanup.CleanupTarget( - worktree_path="/repo/main", - branch="main", - is_main_worktree=True, - ) - with mock.patch("cleanup.remove_git_worktree") as mock_rm_wt, mock.patch( - "cleanup.log_error" - ) as mock_log_err: - deleted, succeeded = await cleanup.execute_cleanup_target(main_repo, target) - self.assertEqual(deleted, []) - self.assertFalse(succeeded) - mock_rm_wt.assert_not_called() - mock_log_err.assert_called_with( - "Target is the main repository! Refusing to clean up main repository." - ) - - async def test_protected_branch_safety(self): - """Verifies refusal to delete protected branch.""" - success, msg = await cleanup.delete_local_branch("/repo/main", "main") - self.assertFalse(success) - self.assertIn("protected", msg) - - success, msg = await cleanup.delete_remote_branch( - "/repo/main", "main", "origin" - ) - self.assertFalse(success) - self.assertIn("protected", msg) - - async def test_upstream_remote_safety(self): - """Verifies refusal to delete branch on upstream remote.""" - success, msg = await cleanup.delete_remote_branch( - "/repo/main", "feature-x", "upstream" - ) - self.assertFalse(success) - self.assertIn("protected", msg) - - async def test_build_cleanup_target_branches(self): - """Verifies building cleanup target for a branch.""" - with mock.patch( - "cleanup.get_push_remote_for_branch", return_value="origin" - ), mock.patch("cleanup.remote_branch_exists", return_value=True): - target = await cleanup.build_cleanup_target( - "/repo/main", - "/repo/worktrees/feat1", - "feat1", - ) - self.assertEqual(target.worktree_path, "/repo/worktrees/feat1") - self.assertEqual(target.branch, "feat1") - self.assertEqual(target.remote, "origin") - self.assertTrue(target.remote_branch_exists) - - async def test_execute_cleanup_target_reports_deleted_resources(self): - """Verifies execute_cleanup_target returns the list of deleted resources.""" - target = cleanup.CleanupTarget( - worktree_path="/repo/worktrees/feat1", - branch="feat1", - remote="origin", - remote_branch_exists=True, - bazel_output_bases=["/cache/bazel/ob1"], - is_main_worktree=False, - ) - with mock.patch( - "cleanup.get_path_size_human", return_value="1.50 GB" - ), mock.patch( - "cleanup.shutdown_and_remove_bazel_output_base", return_value=True - ), mock.patch("cleanup.remove_git_worktree", return_value=True), mock.patch( - "cleanup.delete_local_branch", - return_value=(True, "Deleted local branch 'feat1'."), - ), mock.patch( - "cleanup.delete_remote_branch", - return_value=( - True, - "Deleted remote branch 'feat1' from 'origin'.", - ), - ): - deleted, succeeded = await cleanup.execute_cleanup_target( - "/repo/main", target - ) - - self.assertTrue(succeeded) - self.assertEqual( - deleted, - [ - "Bazel output base: /cache/bazel/ob1 (1.50 GB)", - "Git worktree: /repo/worktrees/feat1", - "Local branch: feat1", - "Remote branch: origin/feat1", - ], - ) - - def test_format_done_title(self): - """Verifies prepending 'done ' without duplication and 70-char truncation.""" - self.assertEqual( - cleanup.format_done_title("Fix flaky upload test"), - "done Fix flaky upload test", - ) - self.assertEqual( - cleanup.format_done_title("done Fix flaky upload test"), - "done Fix flaky upload test", - ) - self.assertEqual( - cleanup.format_done_title("DONE Fix flaky upload test"), - "done Fix flaky upload test", - ) - self.assertEqual(cleanup.format_done_title(" "), "done") - long_title = "a" * 80 - formatted = cleanup.format_done_title(long_title) - self.assertEqual(len(formatted), 70) - self.assertTrue(formatted.startswith("done ")) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/agents/BUILD.bazel b/tests/agents/BUILD.bazel new file mode 100644 index 0000000000..2b241781c4 --- /dev/null +++ b/tests/agents/BUILD.bazel @@ -0,0 +1,19 @@ +load("//python:py_library.bzl", "py_library") +load("//python:py_test.bzl", "py_test") +load("//tests/support:support.bzl", "NOT_WINDOWS") + +py_library( + name = "cleanup_lib", + testonly = True, + srcs = ["//.agents/skills/conversation-done/scripts:cleanup.py"], + imports = ["../../.agents/skills/conversation-done/scripts"], + target_compatible_with = NOT_WINDOWS, +) + +py_test( + name = "cleanup_test", + size = "small", + srcs = ["cleanup_test.py"], + target_compatible_with = NOT_WINDOWS, + deps = [":cleanup_lib"], +) diff --git a/tests/agents/cleanup_test.py b/tests/agents/cleanup_test.py new file mode 100644 index 0000000000..a17edfec7c --- /dev/null +++ b/tests/agents/cleanup_test.py @@ -0,0 +1,577 @@ +"""Unit tests for the conversation-done workspace cleanup script.""" + +from __future__ import annotations + +import asyncio +import os +import stat +import subprocess +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +import cleanup + + +class CleanupScriptTest(unittest.IsolatedAsyncioTestCase): + """Tests for cleanup.py workspace resource discovery, ordering, and safety.""" + + def test_is_protected_branch(self) -> None: + """Verifies protected branches cannot be deleted.""" + self.assertTrue(cleanup.is_protected_branch("main")) + self.assertTrue(cleanup.is_protected_branch("master")) + self.assertTrue(cleanup.is_protected_branch("HEAD")) + self.assertTrue(cleanup.is_protected_branch("release/1.0")) + self.assertTrue(cleanup.is_protected_branch("release/2026-08")) + self.assertTrue(cleanup.is_protected_branch("release-1.0")) + self.assertTrue(cleanup.is_protected_branch("release-2026-08")) + self.assertTrue(cleanup.is_protected_branch(None)) + self.assertFalse(cleanup.is_protected_branch("feature/my-cool-branch")) + self.assertFalse(cleanup.is_protected_branch("bugfix-1234")) + + async def test_worktrees_parsing(self) -> None: + """Verifies parsing git worktree list porcelain output.""" + sample_output = """worktree /path/to/main/repo +HEAD 03f212c3f3b590a7103d512650ce09818d30d218 +branch refs/heads/main + +worktree /path/to/worktrees/feat1 +HEAD f130aea7fa0eab7d558897ed0ad915a1057e065c +branch refs/heads/feat1 + +worktree /path/to/worktrees/detached +HEAD 21e9bd5b3b069d4057abac69adf985b7907308f8 +detached +""" + with mock.patch("cleanup.run_command") as mock_run: + mock_run.return_value = subprocess.CompletedProcess( + args=[], returncode=0, stdout=sample_output, stderr="" + ) + worktrees = await cleanup.get_worktrees("/path/to/main/repo") + + self.assertEqual(len(worktrees), 3) + self.assertEqual(worktrees[0].path, "/path/to/main/repo") + self.assertTrue(worktrees[0].is_main) + self.assertEqual(worktrees[0].branch, "main") + + self.assertEqual(worktrees[1].path, "/path/to/worktrees/feat1") + self.assertFalse(worktrees[1].is_main) + self.assertEqual(worktrees[1].branch, "feat1") + + self.assertEqual(worktrees[2].path, "/path/to/worktrees/detached") + self.assertFalse(worktrees[2].is_main) + self.assertIsNone(worktrees[2].branch) + + async def test_worktrees_failure_raises(self) -> None: + """Verifies get_worktrees raises CleanupError when git worktree list fails.""" + with mock.patch("cleanup.run_command") as mock_run: + mock_run.return_value = subprocess.CompletedProcess( + args=[], returncode=128, stdout="", stderr="fatal: not a git repository" + ) + with self.assertRaisesRegex( + cleanup.CleanupError, "Failed to list Git worktrees" + ): + await cleanup.get_worktrees("/bad/repo") + + def test_find_bazel_output_bases(self) -> None: + """Verifies finding Bazel output bases matching target workspace.""" + with tempfile.TemporaryDirectory() as temp_dir: + user_dir = os.path.join(temp_dir, "_bazel_testuser") + os.makedirs(user_dir) + + ob1 = os.path.join(user_dir, "hash1") + os.makedirs(ob1) + with open( + os.path.join(ob1, "DO_NOT_BUILD_HERE"), "w", encoding="utf-8" + ) as f: + f.write("/home/user/worktrees/my_feature\n") + + ob2 = os.path.join(user_dir, "hash2") + os.makedirs(ob2) + with open( + os.path.join(ob2, "DO_NOT_BUILD_HERE"), "w", encoding="utf-8" + ) as f: + f.write("/home/user/worktrees/my_feature/tests/integration/nested\n") + + ob3 = os.path.join(user_dir, "hash3") + os.makedirs(ob3) + with open( + os.path.join(ob3, "DO_NOT_BUILD_HERE"), "w", encoding="utf-8" + ) as f: + f.write("/home/user/worktrees/different_feature\n") + + with mock.patch("os.path.expanduser", return_value=temp_dir): + bases = cleanup.find_bazel_output_bases( + "/home/user/worktrees/my_feature" + ) + + self.assertEqual(sorted(bases), sorted([ob1, ob2])) + + async def test_main_repo_safety(self) -> None: + """Verifies refusal to remove main repository worktree.""" + main_repo = "/repo/main" + target = cleanup.CleanupTarget( + worktree_path="/repo/main", + branch="main", + is_main_worktree=True, + ) + with mock.patch("cleanup.remove_git_worktree") as mock_rm_wt, mock.patch( + "cleanup.log_error" + ) as mock_log_err: + deleted, succeeded = await cleanup.execute_cleanup_target(main_repo, target) + self.assertEqual(deleted, []) + self.assertFalse(succeeded) + mock_rm_wt.assert_not_called() + mock_log_err.assert_called_with( + "Target is the main repository! Refusing to clean up main repository." + ) + + async def test_protected_branch_safety(self) -> None: + """Verifies refusal to delete protected branch.""" + success, msg = await cleanup.delete_local_branch("/repo/main", "main") + self.assertFalse(success) + self.assertIn("protected", msg) + + success, msg = await cleanup.delete_remote_branch( + "/repo/main", "main", "origin" + ) + self.assertFalse(success) + self.assertIn("protected", msg) + + async def test_missing_local_branch_succeeds(self) -> None: + """Verifies delete_local_branch treats an already-deleted ref as success.""" + with mock.patch("cleanup.run_command") as mock_run, mock.patch( + "cleanup.get_worktrees" + ) as mock_get_wt: + mock_run.return_value = subprocess.CompletedProcess( + args=[], returncode=1, stdout="", stderr="" + ) + ok, msg = await cleanup.delete_local_branch("/repo/main", "feat1") + + self.assertTrue(ok) + self.assertEqual(msg, "Local branch 'feat1' does not exist.") + mock_get_wt.assert_not_called() + mock_run.assert_called_once_with( + [ + "git", + "-C", + "/repo/main", + "show-ref", + "--verify", + "--quiet", + "refs/heads/feat1", + ] + ) + + async def test_delete_local_branch_refusal_guards(self) -> None: + """Verifies delete_local_branch refuses active worktrees and detach failures.""" + with tempfile.TemporaryDirectory() as temp_dir: + root = Path(temp_dir) + main_repo = root / "main" + target_wt = root / "wt_target" + other_wt = root / "wt_other" + main_repo.mkdir() + target_wt.mkdir() + other_wt.mkdir() + worktrees = [ + cleanup.WorktreeInfo(str(main_repo), "abc", "feat_main", True), + cleanup.WorktreeInfo(str(target_wt), "def", "feat_target", False), + cleanup.WorktreeInfo(str(other_wt), "ghi", "feat_other", False), + ] + + show_ref_ok = subprocess.CompletedProcess( + args=[], returncode=0, stdout="", stderr="" + ) + detach_fail = subprocess.CompletedProcess( + args=[], returncode=128, stdout="", stderr="cannot lock ref 'HEAD'" + ) + + with mock.patch( + "cleanup.get_worktrees", return_value=worktrees + ), mock.patch("cleanup.run_command", return_value=show_ref_ok) as mock_run: + ok, msg = await cleanup.delete_local_branch( + str(main_repo), "feat_other", worktree_path=str(target_wt) + ) + self.assertFalse(ok) + self.assertIn("still checked out in active worktree", msg) + + ok, msg = await cleanup.delete_local_branch( + str(main_repo), "feat_main", worktree_path=str(main_repo) + ) + self.assertFalse(ok) + self.assertIn("still checked out in active worktree", msg) + for call in mock_run.call_args_list: + self.assertNotIn("branch", call.args[0]) + + with mock.patch( + "cleanup.get_worktrees", return_value=worktrees + ), mock.patch( + "cleanup.run_command", side_effect=[show_ref_ok, detach_fail] + ) as mock_run: + ok, msg = await cleanup.delete_local_branch( + str(main_repo), "feat_target", worktree_path=str(target_wt) + ) + self.assertFalse(ok) + self.assertIn("Failed to detach HEAD", msg) + self.assertEqual(mock_run.call_count, 2) + + async def test_upstream_remote_safety(self) -> None: + """Verifies refusal to delete branch on upstream remote.""" + success, msg = await cleanup.delete_remote_branch( + "/repo/main", "feature-x", "upstream" + ) + self.assertFalse(success) + self.assertIn("protected", msg) + + async def test_build_cleanup_target_branches(self) -> None: + """Verifies building cleanup target for a branch.""" + with mock.patch( + "cleanup.get_push_remote_for_branch", return_value="origin" + ), mock.patch("cleanup.remote_branch_exists", return_value=True): + target = await cleanup.build_cleanup_target( + "/repo/main", + "/repo/worktrees/feat1", + "feat1", + ) + self.assertEqual(target.worktree_path, "/repo/worktrees/feat1") + self.assertEqual(target.branch, "feat1") + self.assertEqual(target.remote, "origin") + self.assertTrue(target.remote_branch_exists) + + async def test_execute_cleanup_target_reports_deleted_resources(self) -> None: + """Verifies execute_cleanup_target deletes worktree last and reports order.""" + target = cleanup.CleanupTarget( + worktree_path="/repo/worktrees/feat1", + branch="feat1", + remote="origin", + remote_branch_exists=True, + bazel_output_bases=["/cache/bazel/ob1"], + is_main_worktree=False, + ) + call_order: list[str] = [] + + async def fake_rm_ob(*_args: object, **_kwargs: object) -> bool: + call_order.append("bazel_output_base") + return True + + async def fake_del_remote( + *_args: object, **_kwargs: object + ) -> tuple[bool, str]: + call_order.append("remote_branch") + return True, "Deleted remote branch 'feat1' from 'origin'." + + async def fake_del_local(*_args: object, **_kwargs: object) -> tuple[bool, str]: + call_order.append("local_branch") + return True, "Deleted local branch 'feat1'." + + async def fake_rm_wt(*_args: object, **_kwargs: object) -> bool: + call_order.append("git_worktree") + return True + + with mock.patch( + "cleanup.get_path_size_human", return_value="1.50 GB" + ), mock.patch( + "cleanup.shutdown_and_remove_bazel_output_base", + side_effect=fake_rm_ob, + ), mock.patch( + "cleanup.delete_remote_branch", + side_effect=fake_del_remote, + ), mock.patch( + "cleanup.delete_local_branch", + side_effect=fake_del_local, + ) as mock_del_local, mock.patch( + "cleanup.remove_git_worktree", + side_effect=fake_rm_wt, + ): + deleted, succeeded = await cleanup.execute_cleanup_target( + "/repo/main", target + ) + + self.assertTrue(succeeded) + self.assertEqual( + call_order, + [ + "bazel_output_base", + "remote_branch", + "local_branch", + "git_worktree", + ], + ) + mock_del_local.assert_called_once_with( + "/repo/main", + "feat1", + worktree_path="/repo/worktrees/feat1", + dry_run=False, + ) + self.assertEqual( + deleted, + [ + "Bazel output base: /cache/bazel/ob1 (1.50 GB)", + "Remote branch: origin/feat1", + "Local branch: feat1", + "Git worktree: /repo/worktrees/feat1", + ], + ) + + async def test_skips_worktree_removal_on_earlier_failure(self) -> None: + """Verifies worktree is not removed when any earlier cleanup step fails.""" + target = cleanup.CleanupTarget( + worktree_path="/repo/worktrees/feat1", + branch="feat1", + remote="origin", + remote_branch_exists=True, + bazel_output_bases=["/cache/bazel/ob1"], + is_main_worktree=False, + ) + cases = [ + ( + "bazel_output_base", + False, + (True, "Deleted remote branch 'feat1' from 'origin'."), + (True, "Deleted local branch 'feat1'."), + True, + ), + ( + "remote_branch", + True, + (False, "Failed to delete remote branch."), + (True, "Deleted local branch 'feat1'."), + False, + ), + ( + "local_branch", + True, + (True, "Deleted remote branch 'feat1' from 'origin'."), + (False, "Failed to delete local branch."), + True, + ), + ] + for name, ob_ok, remote_res, local_res, expect_local_called in cases: + with self.subTest(failed_step=name), mock.patch( + "cleanup.get_path_size_human", return_value="1.50 GB" + ), mock.patch( + "cleanup.shutdown_and_remove_bazel_output_base", + return_value=ob_ok, + ), mock.patch( + "cleanup.delete_remote_branch", + return_value=remote_res, + ), mock.patch( + "cleanup.delete_local_branch", + return_value=local_res, + ) as mock_del_local, mock.patch( + "cleanup.remove_git_worktree" + ) as mock_rm_wt: + deleted, succeeded = await cleanup.execute_cleanup_target( + "/repo/main", target + ) + self.assertFalse(succeeded) + self.assertEqual(mock_del_local.called, expect_local_called) + mock_rm_wt.assert_not_called() + self.assertNotIn("Git worktree: /repo/worktrees/feat1", deleted) + + async def test_exits_nonzero_when_cleanup_fails(self) -> None: + """Verifies async_main exits with code 1 and skips renaming on failure.""" + target = cleanup.CleanupTarget( + worktree_path="/repo/worktrees/feat1", + branch="feat1", + ) + with mock.patch("cleanup.get_main_repo", return_value="/repo/main"), mock.patch( + "cleanup.get_worktrees", return_value=[] + ), mock.patch("cleanup.build_cleanup_target", return_value=target), mock.patch( + "cleanup.execute_cleanup_target", return_value=([], False) + ), mock.patch("cleanup.prefix_conversation_title") as mock_rename: + with self.assertRaises(SystemExit) as cm: + await cleanup.async_main(["--branches", "feat1", "--force"]) + + self.assertEqual(cm.exception.code, 1) + mock_rename.assert_not_called() + + async def test_remove_readonly_output_base_entries(self) -> None: + """Verifies read-only files/dirs are removed without mutating symlink targets.""" + for force_python_fallback in (False, True): + with self.subTest( + force_python_fallback=force_python_fallback + ), tempfile.TemporaryDirectory() as temp_dir: + root = Path(temp_dir) + external_file = root / "external_ro.txt" + external_file.write_text("keep me\n", encoding="utf-8") + external_file.chmod(0o444) + + external_dir = root / "external_ro_dir" + external_dir.mkdir() + external_dir.chmod(0o555) + + ob = root / "output_base" + try: + ro_sandbox = ob / "sandbox" / "linux-sandbox" / "1" + ro_sandbox.mkdir(parents=True) + ro_file = ro_sandbox / "readonly.txt" + ro_file.write_text("artifact\n", encoding="utf-8") + ro_file.chmod(0o444) + (ro_sandbox / "file_link").symlink_to(external_file) + (ro_sandbox / "dir_link").symlink_to(external_dir) + ro_sandbox.chmod(0o555) + (ob / "sandbox").chmod(0o555) + + no_exec_dir = ob / "no_exec" + no_exec_dir.mkdir() + (no_exec_dir / "inside.txt").write_text("x\n", encoding="utf-8") + no_exec_dir.chmod(0o600) + + no_perm_dir = ob / "no_perm" + no_perm_dir.mkdir() + no_perm_file = no_perm_dir / "locked.txt" + no_perm_file.write_text("y\n", encoding="utf-8") + no_perm_file.chmod(0o000) + no_perm_dir.chmod(0o000) + + if force_python_fallback: + rm_failed = subprocess.CompletedProcess( + args=["rm", "-rf", str(ob)], + returncode=1, + stdout="", + stderr="Permission denied", + ) + with mock.patch("cleanup.run_command", return_value=rm_failed): + removed = await cleanup.remove_directory_safely(str(ob)) + else: + removed = await cleanup.remove_directory_safely(str(ob)) + + self.assertTrue(removed) + self.assertFalse(ob.exists()) + self.assertTrue(external_file.exists()) + self.assertEqual(stat.S_IMODE(external_file.stat().st_mode), 0o444) + self.assertTrue(external_dir.exists()) + self.assertEqual(stat.S_IMODE(external_dir.stat().st_mode), 0o555) + finally: + cleanup._make_tree_writable(str(root)) + + async def test_end_to_end_worktree_last_and_readonly_output_base(self) -> None: + """Verifies real Git worktree/branch deletion and read-only output base cleanup.""" + with tempfile.TemporaryDirectory() as temp_dir: + root = Path(temp_dir) + main_repo = root / "main" + wt_dir = root / "wt_feat" + bazel_cache = root / "bazel_cache" + ob = bazel_cache / "_bazel_testuser" / "ob_hash" + + def setup_fixtures() -> None: + remote_repo = root / "remote.git" + subprocess.run( + ["git", "init", "--bare", str(remote_repo)], + check=True, + capture_output=True, + ) + main_repo.mkdir() + (main_repo / "README.md").write_text("init\n", encoding="utf-8") + for cmd in ( + ["git", "init", "-b", "main"], + ["git", "config", "user.email", "test@example.com"], + ["git", "config", "user.name", "Test"], + ["git", "remote", "add", "origin", str(remote_repo)], + ["git", "add", "README.md"], + ["git", "commit", "-m", "init"], + ["git", "worktree", "add", "-b", "feat", str(wt_dir), "main"], + ): + subprocess.run(cmd, cwd=main_repo, check=True, capture_output=True) + subprocess.run( + ["git", "push", "origin", "feat"], + cwd=wt_dir, + check=True, + capture_output=True, + ) + (wt_dir / "dirty.txt").write_text("uncommitted\n", encoding="utf-8") + + ro_dir = ob / "external" / "ro_pkg" + ro_dir.mkdir(parents=True) + (ob / "DO_NOT_BUILD_HERE").write_text(f"{wt_dir}\n", encoding="utf-8") + ro_file = ro_dir / "pkg.bzl" + ro_file.write_text("X = 1\n", encoding="utf-8") + ro_file.chmod(0o444) + ro_dir.chmod(0o555) + + try: + await asyncio.to_thread(setup_fixtures) + real_run_command = cleanup.run_command + + async def run_without_bazel_server( + cmd: list[str], + cwd: str | None = None, + capture_output: bool = True, + timeout: float | None = None, + ) -> subprocess.CompletedProcess[str]: + if cmd and cmd[0] == "bazel": + return subprocess.CompletedProcess( + args=cmd, returncode=0, stdout="", stderr="" + ) + return await real_run_command( + cmd, + cwd=cwd, + capture_output=capture_output, + timeout=timeout, + ) + + with mock.patch( + "os.path.expanduser", return_value=str(bazel_cache) + ), mock.patch( + "cleanup.run_command", side_effect=run_without_bazel_server + ), mock.patch("cleanup.terminate_processes_under_path"): + target = await cleanup.build_cleanup_target( + str(main_repo), str(wt_dir), "feat" + ) + deleted, succeeded = await cleanup.execute_cleanup_target( + str(main_repo), target + ) + + self.assertTrue(succeeded) + self.assertFalse(ob.exists()) + self.assertFalse(wt_dir.exists()) + self.assertEqual(len(deleted), 4) + self.assertTrue(deleted[0].startswith("Bazel output base:")) + self.assertEqual(deleted[1], "Remote branch: origin/feat") + self.assertEqual(deleted[2], "Local branch: feat") + self.assertEqual(deleted[3], f"Git worktree: {wt_dir}") + + branches = await real_run_command( + ["git", "-C", str(main_repo), "branch", "--list", "feat"] + ) + self.assertEqual(branches.stdout.strip(), "") + remote_branches = await real_run_command( + [ + "git", + "-C", + str(main_repo), + "ls-remote", + "--heads", + "origin", + "feat", + ] + ) + self.assertEqual(remote_branches.stdout.strip(), "") + finally: + cleanup._make_tree_writable(str(root)) + + def test_format_done_title(self) -> None: + """Verifies prepending 'done ' without duplication and 70-char truncation.""" + self.assertEqual( + cleanup.format_done_title("Fix flaky upload test"), + "done Fix flaky upload test", + ) + self.assertEqual( + cleanup.format_done_title("done Fix flaky upload test"), + "done Fix flaky upload test", + ) + self.assertEqual( + cleanup.format_done_title("DONE Fix flaky upload test"), + "done Fix flaky upload test", + ) + self.assertEqual(cleanup.format_done_title(" "), "done") + long_title = "a" * 80 + formatted = cleanup.format_done_title(long_title) + self.assertEqual(len(formatted), 70) + self.assertTrue(formatted.startswith("done ")) + + +if __name__ == "__main__": + unittest.main()