Skip to content

t1060: Detect stale remote branches before creating new local branch#1567

Merged
marcusquinn merged 2 commits intomainfrom
feature/t1060
Feb 17, 2026
Merged

t1060: Detect stale remote branches before creating new local branch#1567
marcusquinn merged 2 commits intomainfrom
feature/t1060

Conversation

@marcusquinn
Copy link
Owner

@marcusquinn marcusquinn commented Feb 17, 2026

Summary

  • Detect stale remote branches (refs/remotes/origin/$branch) before creating new local branches in worktree-helper.sh
  • Interactive mode: warn user and offer to delete (merged) or abort (unmerged)
  • Headless mode: auto-delete merged stale refs, warn-and-proceed for unmerged

Ref #1506

Summary by CodeRabbit

  • New Features

    • Added stale remote branch detection and handling during worktree creation
    • Interactive mode allows user control; headless mode auto-deletes merged branches
    • Unmerged branches trigger warnings in headless mode
  • Documentation

    • Updated help output with stale remote branch behavior details

…t1060)

When worktree-helper.sh creates a new branch, it now checks refs/remotes/origin/$branch
for stale remote tracking refs. Interactive mode offers choices (delete/continue/abort).
Headless mode auto-deletes merged stale refs and warns-but-proceeds for unmerged ones.
Chose tty detection (-t 0) for headless vs interactive — matches existing codebase pattern.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 17, 2026

Warning

Rate limit exceeded

@marcusquinn has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 25 minutes and 13 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Walkthrough

The PR adds stale remote branch detection and handling to the worktree helper script. New functions check if remote branches lack local counterparts and determine merge status, with integration into the add workflow. Both interactive and headless mode behaviors are supported.

Changes

Cohort / File(s) Summary
Stale Remote Branch Detection & Handling
.agents/scripts/worktree-helper.sh
Introduces check_stale_remote_branch() and handle_stale_remote_branch() functions to detect remote-only branches, determine merge status, and orchestrate user interaction or automatic cleanup. Integrates into add workflow prior to worktree creation. Enhances help documentation and output formatting consistency across add, list, status, remove, switch, clean, registry, and help commands.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Poem

🌿 Stale branches wither on the remote vine,
Now our script detects their tangled line,
Merged or unmerged—we know the score,
Auto-prune or ask—the choice is yours! 🧹✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.55% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and specifically summarizes the main change: detecting stale remote branches before creating local branches, directly referencing the ticket (t1060) and the core functionality added.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/t1060

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@marcusquinn marcusquinn marked this pull request as ready for review February 17, 2026 18:36
@github-actions
Copy link

🔍 Code Quality Report

�[0;35m[MONITOR]�[0m Code Review Monitoring Report

�[0;34m[INFO]�[0m Latest Quality Status:
SonarCloud: 0 bugs, 0 vulnerabilities, 16 code smells

�[0;34m[INFO]�[0m Recent monitoring activity:
Tue Feb 17 18:36:13 UTC 2026: Code review monitoring started
Tue Feb 17 18:36:14 UTC 2026: SonarCloud - Bugs: 0, Vulnerabilities: 0, Code Smells: 16

📈 Current Quality Metrics

  • BUGS: 0
  • CODE SMELLS: 16
  • VULNERABILITIES: 0

Generated on: Tue Feb 17 18:36:17 UTC 2026


Generated by AI DevOps Framework Code Review Monitoring

@gemini-code-assist
Copy link

Summary of Changes

Hello @marcusquinn, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances the worktree-helper.sh script by introducing a mechanism to proactively identify and manage stale remote branches when a user attempts to create a new local branch. This prevents potential confusion or unintended behavior by addressing remote references that no longer correspond to active local development, providing clear options for resolution based on the branch's merge status and the execution environment.

Highlights

  • Stale Remote Branch Detection: Implemented logic to detect stale remote branches (where refs/remotes/origin/$branch exists but no local branch does) before creating a new local branch using worktree-helper.sh add.
  • Interactive Mode Handling: In interactive mode, if a stale remote branch is detected, the user is warned and offered options: to delete the remote ref (if merged), or to abort the branch creation (if unmerged to prevent data loss).
  • Headless Mode Handling: In headless environments, merged stale remote refs are automatically deleted, while unmerged stale refs trigger a warning but allow the process to continue, preserving potential unmerged work.
  • New Helper Functions: Added check_stale_remote_branch to determine if a remote branch is stale and its merge status, and handle_stale_remote_branch to manage user interaction and automated actions based on the stale status.
  • Documentation Update: Updated the cmd_help output to include a new section detailing the 'STALE REMOTE DETECTION' feature and its behavior in both interactive and headless modes.
Changelog
  • .agents/scripts/worktree-helper.sh
    • Added check_stale_remote_branch function to identify stale remote branches and their merge status.
    • Added handle_stale_remote_branch function to prompt users or automatically manage stale remote branches based on interactive or headless mode.
    • Modified cmd_add to integrate the handle_stale_remote_branch check before creating new local branches.
    • Updated cmd_help documentation with a new section explaining stale remote detection behavior.
Activity
  • marcusquinn created this pull request to implement stale remote branch detection in the worktree-helper.sh script.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a valuable feature for detecting and handling stale remote branches before creating a new worktree. The implementation is robust, correctly handling interactive and headless modes, and differentiating between merged and unmerged branches with safe defaults. The code is clear and the documentation is updated accordingly. I have one suggestion to refactor some duplicated code to improve maintainability.

Extract _delete_stale_remote_ref() helper to DRY up the 3 repeated instances of stale remote branch deletion logic in handle_stale_remote_branch().
coderabbitai[bot]
coderabbitai bot previously requested changes Feb 17, 2026
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (1)
.agents/scripts/worktree-helper.sh (1)

137-226: Extract repeated delete-and-prune logic into a helper function.

The git push origin --delete + git fetch --prune + success message block is duplicated three times (lines 161–164, 180–183, 200–204). A small helper like _delete_stale_ref() would centralize this, reduce copy-paste risk, and make it easier to update the deletion strategy (per the concern above).

♻️ Example extraction
+# Delete a stale remote tracking ref (and optionally the remote branch)
+_delete_stale_ref() {
+	local branch="$1"
+	echo -e "${BLUE}Deleting stale remote ref...${NC}"
+	git update-ref -d "refs/remotes/origin/$branch" 2>/dev/null || true
+	git fetch --prune origin 2>/dev/null || true
+	echo -e "${GREEN}Deleted origin/$branch${NC}"
+}

Then replace each of the three inline blocks with _delete_stale_ref "$branch".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.agents/scripts/worktree-helper.sh around lines 137 - 226,
handle_stale_remote_branch repeats the "git push origin --delete ...; git fetch
--prune ...; echo Deleted" sequence in three places; create a helper function
(e.g., _delete_stale_ref) that accepts the branch name and runs the deletion,
prune, and success message, then replace the three inline blocks inside
handle_stale_remote_branch with calls to _delete_stale_ref "$branch" to
centralize behavior and reduce duplication (ensure the helper mirrors
suppression of errors with "2>/dev/null || true" and the same colored success
message).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.agents/scripts/worktree-helper.sh:
- Around line 160-164: Replace the destructive remote-delete step that runs git
push origin --delete "$branch" (seen in the stale-ref cleanup block) with a safe
local-only removal: delete the local remote-tracking ref using git update-ref -d
"refs/remotes/origin/$branch" and then run git fetch --prune origin to clean up;
alternatively, if removing the remote branch is intentional, add a pre-check
using git ls-remote --heads origin "$branch" and log/confirm before calling git
push origin --delete "$branch". Apply the same change to the repeated
occurrences that currently call git push origin --delete (the blocks later in
the script).
- Around line 494-498: The rmdir call is using the wrong directory name
(".agent" singular) so it never removes the intended directory; update the rmdir
invocations that reference "$path_to_remove/.agent" to use
"$path_to_remove/.agents" instead (fix both occurrences where rmdir
"$path_to_remove/.agent" is used in this script) so the cleanup of the .agents
directory will actually succeed while keeping the existing 2>/dev/null || true
behavior and only removing when empty.
- Around line 653-657: cmd_clean currently calls read -r response
unconditionally which will fail under set -euo pipefail in headless/non-tty
environments; update cmd_clean to guard the interactive prompt by checking if
stdin is a TTY (use [[ -t 0 ]]) before calling read -r response and otherwise
set response to a safe default (e.g., "N" or skip prompting) so the script won’t
exit on EOF; locate the prompt block in cmd_clean and apply the same t1060-style
non-interactive guard used in handle_stale_remote_branch.
- Line 125: The merge-check uses grep with a regex which misinterprets branch
names containing regex metacharacters; update the checks that use grep -q
"origin/$branch$" (seen in the git merged check and the cmd_list and cmd_clean
usages) to use fixed-string matching (e.g., grep -Fq or grep -qF with the
literal "origin/$branch") or escape the branch name before grepping so branch
names like feature/v2.0 don’t produce false matches; apply the same change to
all occurrences in the script (the git branch -r --merged check and the cmd_list
and cmd_clean references).

---

Nitpick comments:
In @.agents/scripts/worktree-helper.sh:
- Around line 137-226: handle_stale_remote_branch repeats the "git push origin
--delete ...; git fetch --prune ...; echo Deleted" sequence in three places;
create a helper function (e.g., _delete_stale_ref) that accepts the branch name
and runs the deletion, prune, and success message, then replace the three inline
blocks inside handle_stale_remote_branch with calls to _delete_stale_ref
"$branch" to centralize behavior and reduce duplication (ensure the helper
mirrors suppression of errors with "2>/dev/null || true" and the same colored
success message).

@marcusquinn
Copy link
Owner Author

Addressed the Gemini review feedback on .agents/scripts/worktree-helper.sh:226: extracted _delete_stale_remote_ref() internal helper to DRY up the 3 repeated instances of the delete+prune+echo pattern in handle_stale_remote_branch(). All three call sites now use the helper. ShellCheck clean. See commit 799a558.

@github-actions
Copy link

🔍 Code Quality Report

�[0;35m[MONITOR]�[0m Code Review Monitoring Report

�[0;34m[INFO]�[0m Latest Quality Status:
SonarCloud: 0 bugs, 0 vulnerabilities, 16 code smells

�[0;34m[INFO]�[0m Recent monitoring activity:
Tue Feb 17 18:41:33 UTC 2026: Code review monitoring started
Tue Feb 17 18:41:33 UTC 2026: SonarCloud - Bugs: 0, Vulnerabilities: 0, Code Smells: 16

📈 Current Quality Metrics

  • BUGS: 0
  • CODE SMELLS: 16
  • VULNERABILITIES: 0

Generated on: Tue Feb 17 18:41:36 UTC 2026


Generated by AI DevOps Framework Code Review Monitoring

@sonarqubecloud
Copy link

@marcusquinn marcusquinn dismissed coderabbitai[bot]’s stale review February 17, 2026 18:44

Auto-dismissed: bot review does not block autonomous pipeline

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

code-reviews-actioned All review feedback has been actioned

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant