diff --git a/AGENTS.md b/AGENTS.md index 5583be0..419adcf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -116,7 +116,7 @@ cmd_editor() → resolve_target() → load_editor_adapter() → editor_open() **`init` command**: Outputs shell functions for `gtr cd ` navigation. Output is cached to `~/.cache/gtr/` and auto-invalidates on version change. Users source the cache file directly in their shell rc for fast startup (see `git gtr help init`). -**`clean --merged` / `clean --closed`**: Removes worktrees whose PRs/MRs are merged or closed and deletes their branches. Auto-detects GitHub (`gh`) or GitLab (`glab`) from the `origin` remote URL. Override with `gtr.provider` config for self-hosted instances. `clean` also unlocks and prunes locked registry entries whose directories no longer exist. +**`clean --merged` / `clean --closed`**: Removes worktrees whose PRs/MRs are merged or closed, retaining local branches, reflogs, and branch config even with `--force`. Git has no combined expected-tip deletion and worktree-reservation guard; snapshot checks or a gtr-only mutex cannot protect against concurrent raw Git checkouts. Auto-detects GitHub (`gh`) or GitLab (`glab`) from the `origin` remote URL. Override with `gtr.provider` config for self-hosted instances. `clean` also unlocks and prunes locked registry entries whose directories no longer exist. **`pr `** (lib/commands/pr.sh): Creates a worktree from a GitHub pull request via `gh`. Uses `gh pr checkout --worktree` when the installed `gh` supports it, otherwise fetches `refs/pull//head` through a compatibility path. diff --git a/README.md b/README.md index ddd1322..6a846e1 100644 --- a/README.md +++ b/README.md @@ -404,8 +404,8 @@ git gtr clean --merged --force --yes # Force-clean and auto-confirm **Options:** -- `--merged`: Remove worktrees whose branches have merged PRs/MRs (also deletes the branch) -- `--closed`: Remove worktrees whose branches have closed PRs/MRs (also deletes the branch) +- `--merged`: Remove worktrees whose branches have merged PRs/MRs (keeps the branch) +- `--closed`: Remove worktrees whose branches have closed PRs/MRs (keeps the branch) - `--to `: Limit PR/MR cleanup to PRs/MRs targeting the given base ref - `--dry-run`, `-n`: Preview changes without removing - `--yes`, `-y`: Non-interactive mode (skip confirmation prompts) @@ -413,6 +413,8 @@ git gtr clean --merged --force --yes # Force-clean and auto-confirm **Note:** The `--merged`/`--closed` mode auto-detects your hosting provider (GitHub or GitLab) from the `origin` remote URL and requires the corresponding CLI tool (`gh` or `glab`) to be installed and authenticated. For self-hosted instances, set the provider explicitly: `git gtr config set gtr.provider gitlab`. +**Branch retention:** PR/MR cleanup keeps local branches, reflogs, and branch configuration, including with `--force`. Git's [expected-tip ref deletion](https://git-scm.com/docs/git-update-ref) cannot also guard against a concurrent checkout or new worktree reserving the same branch. Checking worktrees first leaves a race; using [`git branch -D`](https://git-scm.com/docs/git-branch) instead loses the expected-tip check. Cleanup therefore removes eligible worktrees and reports each retained branch. Delete retained branches separately after reviewing their tips and coordinating other Git operations. `--force` still only bypasses dirty-worktree checks; provider-tip and active-worktree protections remain in place. + **Note:** `clean` also detects registry entries that are locked but whose directories no longer exist (for example, a crashed agent session that deleted its worktree directory). `git worktree prune` skips locked entries by design, so these linger and keep their branches checked out. `clean` offers to unlock and prune them; `--force` or `--yes` confirms automatically. ### `git gtr trust` diff --git a/lib/commands/clean.sh b/lib/commands/clean.sh index d1fa7ce..d11ecfd 100644 --- a/lib/commands/clean.sh +++ b/lib/commands/clean.sh @@ -140,21 +140,21 @@ _clean_branch_matches_pr_state() { return 1 } -# Delete only the exact tip authorized by the provider. A separate tip read -# followed by `git branch -D` would still race a concurrent branch update. -# Usage: _clean_delete_validated_branch repo_root branch branch_tip -_clean_delete_validated_branch() { +# Explain why PR cleanup retains the branch after removing its worktree. +# These reads are diagnostics, not authorization to delete: reservations can +# change after any snapshot without changing the provider-validated tip. +# Usage: _clean_report_retained_branch repo_root branch branch_tip +_clean_report_retained_branch() { local repo_root="$1" branch="$2" branch_tip="$3" - local branch_ref="refs/heads/$branch" worktrees delete_output + local branch_ref="refs/heads/$branch" worktrees current_tip - # update-ref does not provide git branch's checked-out branch protection. if ! worktrees=$(git -C "$repo_root" worktree list --porcelain 2>/dev/null); then log_warn "Kept branch $branch (could not verify remaining worktrees)" - return 1 + return 0 fi if printf '%s\n' "$worktrees" | grep -Fxq "branch $branch_ref"; then log_warn "Kept branch $branch (still checked out in another worktree)" - return 1 + return 0 fi # Rebase/bisect can detach HEAD while still reserving the original branch. @@ -163,7 +163,7 @@ _clean_delete_validated_branch() { if ! common_dir=$(git -C "$repo_root" rev-parse --git-common-dir 2>/dev/null) || \ [ -z "$common_dir" ]; then log_warn "Kept branch $branch (could not verify rebase/bisect state)" - return 1 + return 0 fi case "$common_dir" in /*) ;; *) common_dir="$repo_root/$common_dir" ;; esac for state_file in "$common_dir"/rebase-merge/head-name \ @@ -173,26 +173,30 @@ _clean_delete_validated_branch() { [ -e "$state_file" ] || continue if ! state_branch=$(cat "$state_file" 2>/dev/null) || [ -z "$state_branch" ]; then log_warn "Kept branch $branch (could not verify rebase/bisect state)" - return 1 + return 0 fi if [ "$state_branch" = "$branch_ref" ] || [ "$state_branch" = "$branch" ]; then log_warn "Kept branch $branch (rebase or bisect in progress)" - return 1 + return 0 fi done - # --no-deref also prevents deleting a different branch if this ref becomes - # symbolic between validation and deletion. Never retry without the old tip. - if ! delete_output=$(git -C "$repo_root" update-ref --no-deref -d \ - "$branch_ref" "$branch_tip" 2>&1); then - log_warn "Kept branch $branch (tip changed or deletion failed): $delete_output" - return 1 + if git -C "$repo_root" symbolic-ref --quiet "$branch_ref" >/dev/null 2>&1; then + log_warn "Kept branch $branch (branch ref is symbolic)" + return 0 + fi + if ! current_tip=$(git -C "$repo_root" rev-parse --verify "$branch_ref^{commit}" 2>/dev/null) || \ + [ "$current_tip" != "$branch_tip" ]; then + log_warn "Kept branch $branch (tip changed or could not be verified)" + return 0 fi - # Match git branch's metadata cleanup only after successful ref deletion. - # A missing section is normal; metadata cleanup must not abort postRemove. - git -C "$repo_root" config --local --remove-section "branch.$branch" 2>/dev/null || true - log_info "Branch deleted: $branch" + # update-ref's expected old OID protects the tip, but not a concurrent raw + # git checkout/worktree add. git branch -D cannot take an expected old OID, + # and a gtr-only mutex would not coordinate those raw Git commands. Keep the + # ref, reflog and config even with --force until Git offers both protections + # in one operation. Never clean branch metadata without deleting its ref. + log_warn "Kept branch $branch (automatic deletion cannot safely exclude concurrent checkouts)" } # Remove worktrees whose PRs/MRs match requested cleanup states (handles squash merges) @@ -253,9 +257,9 @@ _clean_prs() { # Check if branch has a PR/MR matching any requested state if _clean_branch_matches_pr_state "$provider" "$branch" "$target_ref" "$branch_tip" "$merged_mode" "$closed_mode"; then if [ "$dry_run" -eq 1 ]; then - log_info "[dry-run] Would remove: $branch ($dir)" + log_info "[dry-run] Would remove: $branch ($dir); branch retained" removed=$((removed + 1)) - elif [ "$yes_mode" -eq 1 ] || prompt_yes_no "Remove worktree and delete branch '$branch'?"; then + elif [ "$yes_mode" -eq 1 ] || prompt_yes_no "Remove worktree for '$branch' (keep branch)?"; then log_step "Removing worktree: $branch" if ! run_hooks_in preRemove "$dir" \ @@ -280,7 +284,7 @@ _clean_prs() { fi if remove_worktree "$dir" "$force"; then - _clean_delete_validated_branch "$repo_root" "$branch" "$branch_tip" || true + _clean_report_retained_branch "$repo_root" "$branch" "$branch_tip" removed=$((removed + 1)) if ! run_hooks postRemove \ diff --git a/lib/commands/help.sh b/lib/commands/help.sh index 3a5e7f4..9f591a1 100644 --- a/lib/commands/help.sh +++ b/lib/commands/help.sh @@ -367,6 +367,10 @@ Removes empty worktree directories and optionally removes worktrees whose PRs/MRs have been merged or closed. Auto-detects GitHub (gh) or GitLab (glab) from the remote URL. +PR/MR cleanup keeps local branches and their metadata, even with --force, +to protect concurrent checkouts. Review and delete retained branches +separately after coordinating other Git operations. + Also detects registry entries that are locked but whose directories no longer exist (git worktree prune skips locked entries) and offers to unlock and prune them. Confirmed automatically with --force or --yes. @@ -687,6 +691,7 @@ SETUP & MAINTENANCE: clean [options] Remove stale/prunable worktrees and empty directories + PR/MR cleanup retains branches and metadata, even with --force --merged: also remove worktrees with merged PRs/MRs --closed: also remove worktrees with closed PRs/MRs --to : limit PR cleanup to PRs/MRs targeting diff --git a/tests/cmd_clean.bats b/tests/cmd_clean.bats index 6b78873..24ff163 100644 --- a/tests/cmd_clean.bats +++ b/tests/cmd_clean.bats @@ -410,8 +410,8 @@ assert_cleanup_preserves_hook_commit() { [ "$(command git rev-parse refs/heads/validated-tip)" = "$CLEAN_VALIDATED_TIP" ] } -@test "cmd_clean removes unchanged validated tips and metadata after hooks" { - local mode +@test "cmd_clean removes validated worktrees but retains branches and metadata after hooks" { + local mode branch_config branch_reflog for mode in --merged --closed; do setup_validated_tip_candidate git config branch.validated-tip.remote origin @@ -419,42 +419,35 @@ assert_cleanup_preserves_hook_commit() { git config gtr.hook.preRemove \ 'test -d "$WORKTREE_PATH" && printf "pre\n" > "$REPO_ROOT/hook-order"' git config gtr.hook.postRemove \ - 'test ! -d "$WORKTREE_PATH" && ! git show-ref --verify --quiet "refs/heads/$BRANCH" && printf "post\n" >> "$REPO_ROOT/hook-order"' + 'test ! -d "$WORKTREE_PATH" && git show-ref --verify --quiet "refs/heads/$BRANCH" && printf "post\n" >> "$REPO_ROOT/hook-order"' + branch_config=$(git config --get-regexp '^branch\.validated-tip\.') + branch_reflog=$(git reflog show refs/heads/validated-tip) run run_clean_with_errexit "$mode" --yes [ "$status" -eq 0 ] [ ! -d "$TEST_WT_PATH" ] - if git show-ref --verify --quiet refs/heads/validated-tip; then - false - fi - if git config --get-regexp '^branch\.validated-tip\.' >/dev/null; then - false - fi + [ "$(git rev-parse refs/heads/validated-tip)" = "$CLEAN_VALIDATED_TIP" ] + [ "$(git config --get-regexp '^branch\.validated-tip\.')" = "$branch_config" ] + [ "$(git reflog show refs/heads/validated-tip)" = "$branch_reflog" ] [ "$(cat "$TEST_REPO/hook-order")" = $'pre\npost' ] [[ "$output" == *"Removed: 1, Skipped: 0"* ]] [[ "$output" != *"Post-remove hook failed"* ]] + [[ "$output" == *"Kept branch validated-tip (automatic deletion cannot safely exclude concurrent checkouts)"* ]] + git branch -D validated-tip done } -# Inject an update immediately before branch deletion, then assert cleanup keeps +# Inject an update after worktree removal, then assert cleanup keeps # the new tip and metadata for the supplied cleanup mode/flags. assert_cleanup_preserves_racing_tip() { setup_validated_tip_candidate local new_tip new_tip=$(printf "Concurrent work\n" | git commit-tree "$CLEAN_VALIDATED_TIP^{tree}" -p "$CLEAN_VALIDATED_TIP") git config gtr.hook.preRemove 'printf "pre\n" > "$REPO_ROOT/hook-order"' - # Inject the update at the final deletion command, after all validation and - # worktree removal. Run the actual Git deletion to exercise its atomic check. - git() { - local args=" $* " - case "$args" in - *" update-ref "*" -d refs/heads/validated-tip "*|*" branch -d validated-tip "*|*" branch -D validated-tip "*) - command git -C "$TEST_REPO" update-ref refs/heads/validated-tip "$new_tip" - printf "raced\n" > "$TEST_REPO/race-injected" - ;; - esac - command git "$@" + cleanup_race() { + command git -C "$TEST_REPO" update-ref refs/heads/validated-tip "$new_tip" } + inject_after_cleanup_snapshot run run_clean_with_errexit "$@" --yes [ "$status" -eq 0 ] @@ -463,17 +456,102 @@ assert_cleanup_preserves_racing_tip() { [ "$(command git rev-parse refs/heads/validated-tip)" = "$new_tip" ] [ -n "$(command git config branch.validated-tip.description)" ] [ "$(cat "$TEST_REPO/hook-order")" = $'pre\npost' ] - [[ "$output" == *"Kept branch validated-tip"* ]] + [[ "$output" == *"Kept branch validated-tip (tip changed or could not be verified)"* ]] } -@test "cmd_clean preserves an update racing the final branch deletion" { +@test "cmd_clean preserves a tip update after the reservation snapshot" { assert_cleanup_preserves_racing_tip --merged } -@test "cmd_clean --closed --force cannot bypass the atomic tip check" { +@test "cmd_clean --closed --force preserves a tip update after the reservation snapshot" { assert_cleanup_preserves_racing_tip --closed --force } +@test "cmd_clean dry-run describes branch retention without changing the candidate" { + setup_validated_tip_candidate + + run run_clean_with_errexit --merged --closed --force --dry-run --yes + [ "$status" -eq 0 ] + [ -d "$TEST_WT_PATH" ] + [ "$(git rev-parse refs/heads/validated-tip)" = "$CLEAN_VALIDATED_TIP" ] + [ -n "$(git config branch.validated-tip.description)" ] + [ ! -e "$TEST_REPO/hook-order" ] + [[ "$output" == *"Would remove: validated-tip ($TEST_WT_PATH); branch retained"* ]] +} + +@test "cmd_clean confirmation describes removal while keeping the branch" { + setup_validated_tip_candidate + prompt_yes_no() { printf '%s\n' "$1"; } + + run run_clean_with_errexit --closed --force + [ "$status" -eq 0 ] + [[ "$output" == *"Remove worktree for 'validated-tip' (keep branch)?"* ]] + [ ! -d "$TEST_WT_PATH" ] + [ "$(git rev-parse refs/heads/validated-tip)" = "$CLEAN_VALIDATED_TIP" ] + [ -n "$(git config branch.validated-tip.description)" ] + [ "$(cat "$TEST_REPO/hook-order")" = post ] +} + +# Return a genuine worktree snapshot, then run a real Git operation before the +# caller can use it. No sleeps: the operation is guaranteed to miss the snapshot. +# Define cleanup_race before invoking this helper. +inject_after_cleanup_snapshot() { + git() { + if [ "$1" = -C ] && [ "$2" = "$TEST_REPO" ] && \ + [ "$3 $4" = "worktree list" ] && [ ! -d "$TEST_WT_PATH" ] && \ + [ ! -e "$TEST_REPO/race-injected" ]; then + command git "$@" || return $? + cleanup_race >&2 || return $? + printf "raced\n" > "$TEST_REPO/race-injected" + return 0 + fi + command git "$@" + } +} + +assert_cleanup_preserves_racing_checkout() { + local checkout_path="$1" + shift + inject_after_cleanup_snapshot + + run run_clean_with_errexit "$@" --yes + [ "$status" -eq 0 ] + [ -e "$TEST_REPO/race-injected" ] + [ ! -d "$TEST_WT_PATH" ] + [ -d "$checkout_path" ] + [ "$(command git -C "$checkout_path" symbolic-ref HEAD)" = refs/heads/validated-tip ] + [ "$(command git -C "$checkout_path" rev-parse HEAD)" = "$CLEAN_VALIDATED_TIP" ] + [ "$(command git rev-parse refs/heads/validated-tip)" = "$CLEAN_VALIDATED_TIP" ] + [ -n "$(command git config branch.validated-tip.description)" ] + [ "$(cat "$TEST_REPO/hook-order")" = post ] + [[ "$output" == *"Kept branch validated-tip"* ]] +} + +@test "cmd_clean preserves a raw worktree add after the reservation snapshot" { + setup_validated_tip_candidate + cleanup_race() { + command git -C "$TEST_REPO" worktree add --quiet "$TEST_WORKTREES_DIR/racing" validated-tip + } + assert_cleanup_preserves_racing_checkout "$TEST_WORKTREES_DIR/racing" --merged +} + +@test "cmd_clean --closed --force preserves a raw checkout after the reservation snapshot" { + setup_validated_tip_candidate + git worktree add --quiet --detach "$TEST_WORKTREES_DIR/racing" "$CLEAN_VALIDATED_TIP" + cleanup_race() { + command git -C "$TEST_WORKTREES_DIR/racing" checkout --quiet validated-tip + } + assert_cleanup_preserves_racing_checkout "$TEST_WORKTREES_DIR/racing" --closed --force +} + +@test "cmd_clean preserves a main worktree checkout after the reservation snapshot" { + setup_validated_tip_candidate + cleanup_race() { + command git -C "$TEST_REPO" checkout --quiet validated-tip + } + assert_cleanup_preserves_racing_checkout "$TEST_REPO" --merged --closed --force +} + @test "cmd_clean keeps a validated branch still checked out in another worktree" { setup_validated_tip_candidate git worktree add --quiet --force "$TEST_WORKTREES_DIR/still-active" validated-tip @@ -541,25 +619,22 @@ assert_cleanup_preserves_in_progress_branch() { assert_cleanup_preserves_in_progress_branch BISECT_START validated-tip } -@test "cmd_clean never follows a symbolic branch ref during final deletion" { +@test "cmd_clean preserves a symbolic branch ref introduced after the reservation snapshot" { setup_validated_tip_candidate git branch other-tip "$CLEAN_VALIDATED_TIP" - # Replace the branch with a symbolic ref at the final deletion command. - git() { - case " $* " in - *" update-ref "*" -d refs/heads/validated-tip "*) - command git -C "$TEST_REPO" symbolic-ref refs/heads/validated-tip refs/heads/other-tip - printf "raced\n" > "$TEST_REPO/race-injected" - ;; - esac - command git "$@" + cleanup_race() { + command git -C "$TEST_REPO" symbolic-ref refs/heads/validated-tip refs/heads/other-tip } + inject_after_cleanup_snapshot run run_clean_with_errexit --merged --force --yes [ "$status" -eq 0 ] [ -e "$TEST_REPO/race-injected" ] [ ! -d "$TEST_WT_PATH" ] [ "$(command git rev-parse refs/heads/other-tip)" = "$CLEAN_VALIDATED_TIP" ] + [ "$(command git symbolic-ref refs/heads/validated-tip)" = refs/heads/other-tip ] + [ -n "$(command git config branch.validated-tip.description)" ] + [[ "$output" == *"Kept branch validated-tip (branch ref is symbolic)"* ]] } # Fail only the candidate's tip lookup; all other Git operations remain real. @@ -664,7 +739,7 @@ assert_unresolved_tip_is_preserved() { [ -d "$TEST_WORKTREES_DIR/unresolved-tip" ] command git show-ref --verify --quiet refs/heads/unresolved-tip [ ! -d "$TEST_WORKTREES_DIR/valid-tip" ] - ! command git show-ref --verify --quiet refs/heads/valid-tip + command git show-ref --verify --quiet refs/heads/valid-tip [[ "$output" == *"Removed: 1, Skipped: 1"* ]] } @@ -683,10 +758,10 @@ assert_unresolved_tip_is_preserved() { [[ "$output" != *"provider lookup should not run"* ]] } -# Exercise the real provider predicate and branch deletion in disposable repos. +# Exercise the real provider predicate and branch retention in disposable repos. # Usage: assert_gitlab_cleanup # Creates eligible and ineligible MR fixtures, runs cleanup with errexit, and -# asserts that only the requested unambiguous state loses its worktree and branch. +# asserts that only the requested unambiguous state loses its worktree. assert_gitlab_cleanup() { local requested_state="$1" parser="$2" branch tip for branch in merged-tip closed-tip opened-tip mixed-tip unknown-tip duplicate-tip; do @@ -724,11 +799,10 @@ assert_gitlab_cleanup() { for branch in merged-tip closed-tip opened-tip mixed-tip unknown-tip duplicate-tip; do if [ "$branch" = "$requested_state-tip" ]; then [ ! -d "$TEST_WORKTREES_DIR/$branch" ] - ! git show-ref --verify --quiet "refs/heads/$branch" else [ -d "$TEST_WORKTREES_DIR/$branch" ] - git show-ref --verify --quiet "refs/heads/$branch" fi + git show-ref --verify --quiet "refs/heads/$branch" done }