@@ -83,14 +83,51 @@ Only attempt branch deletion if `$BRANCH` equals `<name>` (meaning we created it
8383via ` /worktree-new <name> ` without a base-ref). If the branch is something else
8484(e.g., ` feature/existing-branch ` ), skip deletion — the user didn't create it.
8585
86+ #### 6a. Fetch origin (best-effort)
87+
88+ ``` bash
89+ git fetch origin --quiet 2> /dev/null || true
90+ ```
91+
92+ This updates tracking refs so ` git branch -d ` has better merge detection. Scoped
93+ to ` origin ` to avoid fetching all remotes. Fails silently if offline or no remote.
94+
95+ ** If this step hangs** (network issues), Ctrl-C and continue — it is not required.
96+
97+ #### 6b. Check GitHub PR status
98+
8699``` bash
87- git branch -d -- " $BRANCH "
100+ gh pr list --head " $BRANCH " --state merged --json number --jq ' .[0].number ' 2> /dev/null
88101```
89102
90- Let the output print naturally:
91- - If the branch was merged, it will be deleted and git prints a confirmation.
92- - If not fully merged, git prints a warning — relay that to the user
93- (suggest ` git branch -D -- "$BRANCH" ` if they want to force-delete).
103+ Note: ` gh pr list --head ` queries by branch name, avoiding the ` gh pr view ` pitfall
104+ where numeric branch names (e.g., ` 1234 ` ) are interpreted as PR numbers.
105+
106+ Using ` --state merged ` directly queries for merged PRs, avoiding ambiguity when
107+ multiple PRs share the same head branch (e.g., one open and one merged).
108+
109+ Interpret by checking the ** exit code first** , then the output:
110+
111+ 1 . Command ** exits non-zero** (gh not installed, auth/network error) → ` PR_MERGED=false `
112+ 2 . Command ** exits zero** and output is ** non-empty** (a merged PR exists) → ` PR_MERGED=true `
113+ 3 . Command ** exits zero** and output is ** empty** (no merged PR for this branch) → ` PR_MERGED=false `
114+
115+ #### 6c. Delete the branch
116+
117+ - ** ` PR_MERGED=true ` ** : Check for unpushed local commits before force-deleting:
118+ ``` bash
119+ UPSTREAM=$( git rev-parse --abbrev-ref " $BRANCH @{u}" 2> /dev/null)
120+ ```
121+ - If upstream exists, compute ` AHEAD=$(git rev-list --count "$UPSTREAM..$BRANCH") ` .
122+ - ` AHEAD == 0 ` : Force-delete with ` git branch -D -- "$BRANCH" ` .
123+ Report: "Branch ` $BRANCH ` deleted (PR was merged on GitHub)."
124+ - ` AHEAD > 0 ` : Safe-delete with ` git branch -d -- "$BRANCH" ` . If it fails,
125+ warn about unpushed local commits and suggest ` git branch -D -- "$BRANCH" ` .
126+ - If no upstream: Safe-delete with ` git branch -d -- "$BRANCH" ` . If it fails,
127+ warn about unpushed local commits and suggest ` git branch -D -- "$BRANCH" ` .
128+ - ** ` PR_MERGED=false ` ** : Safe-delete with ` git branch -d -- "$BRANCH" ` .
129+ If it fails because the branch is not fully merged, relay the warning and
130+ suggest ` git branch -D -- "$BRANCH" ` if they want to force-delete.
94131
95132### 7. Report
96133
0 commit comments