Skip to content

GH#2941: fix multi-repo worktree auto-cleanup in pulse-wrapper.sh#2944

Merged
marcusquinn merged 1 commit intomainfrom
chore/worktree-auto-cleanup
Mar 6, 2026
Merged

GH#2941: fix multi-repo worktree auto-cleanup in pulse-wrapper.sh#2944
marcusquinn merged 1 commit intomainfrom
chore/worktree-auto-cleanup

Conversation

@marcusquinn
Copy link
Owner

@marcusquinn marcusquinn commented Mar 6, 2026

Summary

  • Fix broken jq query in cleanup_worktrees() that prevented multi-repo worktree cleanup from ever running — .[] iterated top-level JSON keys instead of .initialized_repos[]
  • Add defensive improvements: whitespace-safe wc output, null-safe local_only check, total cleanup summary logging
  • Enhance function documentation to describe the full cleanup pipeline (git fetch --prune → refs check → squash-merge detection → removal)

Root Cause

repos.json structure is {"git_parent_dirs": [...], "initialized_repos": [...]}. The old query jq -r '.[] | select(.local_only != true) | .path' iterated the two top-level values (an array and an array), not the repo entries inside initialized_repos. This silently returned no paths, so the function always fell through to the single-repo fallback — meaning only the aidevops repo itself was ever cleaned, not the other managed repos.

Testing

  • ShellCheck passes with no new violations
  • The fix aligns the jq query with the pattern used by prefetch_state(), update_health_issues(), and run_daily_quality_sweep() in the same file

Closes #2941

Summary by CodeRabbit

  • Bug Fixes

    • Improved worktree cleanup functionality with more precise detection and counting logic.
    • Enhanced filtering to focus on initialized repositories while excluding local-only repos.
    • Expanded logging to display per-repository removal counts and comprehensive total summary.
  • Chores

    • Updated variable naming and logging consistency.

The jq query in cleanup_worktrees() used '.[]' to iterate repos.json,
but repos.json has top-level keys 'git_parent_dirs' and
'initialized_repos' — not a top-level array. This caused the query to
silently return no results, falling through to the single-repo fallback
every time. Multi-repo worktree cleanup has been broken since it was
added.

Fix: use '.initialized_repos[]' matching the pattern used by
prefetch_state() and other functions in the same file.

Also: defensive wc whitespace trimming, null-safe local_only check,
total cleanup summary logging, and enhanced function documentation.
@gemini-code-assist
Copy link

Summary of Changes

Hello, 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 resolves a critical bug in the pulse-wrapper.sh script that hindered the automatic cleanup of stale Git worktrees across multiple managed repositories. The fix ensures that the system can now correctly identify and remove unused worktrees, thereby preventing resource accumulation and maintaining a cleaner development environment. It also introduces robustness enhancements and clearer documentation for the cleanup process.

Highlights

  • Fix Multi-Repo Worktree Cleanup: Corrected a broken jq query in the cleanup_worktrees() function that previously prevented multi-repository worktree cleanup from executing correctly.
  • Defensive Improvements: Implemented several defensive improvements, including making wc output whitespace-safe, adding a null-safe check for local_only properties, and introducing total cleanup summary logging.
  • Enhanced Documentation: Updated the documentation for the cleanup_worktrees() function to provide a comprehensive description of its full cleanup pipeline, including git fetch --prune, refs checks, squash-merge detection, and removal.
Changelog
  • .agents/scripts/pulse-wrapper.sh
    • Fixed the jq query to correctly iterate over initialized_repos[] for multi-repo worktree cleanup.
    • Improved the worktree counting logic by making wc -l output whitespace-safe and added a null-safe check for the local_only property.
    • Enhanced the cleanup_worktrees function's documentation to detail its internal steps.
    • Added a final log message to summarize the total number of worktrees removed across all repositories.
Activity
  • The pull request addresses and closes issue chore: auto-cleanup worktrees after PR merge #2941.
  • The author, marcusquinn, identified and fixed a jq query issue that prevented multi-repo worktree cleanup.
  • Defensive coding practices were introduced to improve script robustness.
  • Documentation for the cleanup_worktrees function was significantly expanded.
  • Testing confirmed ShellCheck compliance and consistency with existing patterns in the 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.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 6, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: edf42287-1995-4df1-a59e-88d9e7eeab38

📥 Commits

Reviewing files that changed from the base of the PR and between 9d7523a and a0cbb5f.

📒 Files selected for processing (1)
  • .agents/scripts/pulse-wrapper.sh

Walkthrough

The cleanup_worktrees function in pulse-wrapper.sh is restructured to iterate exclusively over initialized repositories, count worktrees per repo, execute cleanup operations in per-repo subshells, and aggregate removal counts into a single total summary log.

Changes

Cohort / File(s) Summary
Worktree Cleanup Logic
.agents/scripts/pulse-wrapper.sh
Enhanced cleanup_worktrees function to filter repositories to initialized_repos[], exclude local_only repos, count worktrees via wt_count variable, skip repos with ≤1 worktree, execute cleanup in per-repo subshells with proper working directory context, aggregate per-repo removal counts, and emit unified total_removed summary log.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

bug

Poem

🌳 Worktrees once sprawled, forgotten and wild,
Now cleanup sweeps through, repo by repo mild,
Per-branch accounting, totals precise,
Disk space reclaimed—automation's device! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: fixing multi-repo worktree auto-cleanup in pulse-wrapper.sh, with issue reference GH#2941.
Linked Issues check ✅ Passed The PR implements all core requirements from issue #2941: multi-repo cleanup logic, git fetch --prune integration, detection of stale worktrees via remote ref checks, and safe removal with logging.
Out of Scope Changes check ✅ Passed All changes are directly aligned with issue #2941 objectives: fixing the jq query for multi-repo iteration, adding defensive improvements, and enhancing documentation for the cleanup pipeline.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/worktree-auto-cleanup

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.

@github-actions
Copy link

github-actions bot commented Mar 6, 2026

🔍 Code Quality Report

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

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

�[0;34m[INFO]�[0m Recent monitoring activity:
Fri Mar 6 01:50:07 UTC 2026: Code review monitoring started
Fri Mar 6 01:50:07 UTC 2026: SonarCloud - Bugs: 0, Vulnerabilities: 0, Code Smells: 108

📈 Current Quality Metrics

  • BUGS: 0
  • CODE SMELLS: 108
  • VULNERABILITIES: 0

Generated on: Fri Mar 6 01:50:10 UTC 2026


Generated by AI DevOps Framework Code Review Monitoring

@sonarqubecloud
Copy link

sonarqubecloud bot commented Mar 6, 2026

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 effectively fixes a bug in the multi-repo worktree cleanup logic by correcting the jq query. The added defensive improvements, suchs as the null-safe local_only check and whitespace-safe wc output, enhance the script's robustness. The expanded documentation is also a great addition for clarity. I have a couple of minor suggestions to improve debuggability by removing unnecessary error suppression, in line with the repository's general guidelines.

Note: Security Review did not run due to the size of the PR.

# worktree-helper.sh uses gh pr list for squash-merge detection.
local repo_paths
repo_paths=$(jq -r '.[] | select(.local_only != true) | .path' "$repos_json" 2>/dev/null || echo "")
repo_paths=$(jq -r '.initialized_repos[] | select((.local_only // false) == false) | .path' "$repos_json" 2>/dev/null || echo "")

Choose a reason for hiding this comment

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

medium

While the || echo "" correctly handles potential jq command failures when set -e is active, suppressing stderr with 2>/dev/null can hide valuable diagnostic information. If the repos.json file is malformed or there are permission issues, those errors would be silenced. It's better to let these errors be visible for easier debugging.

As per the repository's general rules, it's preferable to avoid blanket error suppression.

Suggested change
repo_paths=$(jq -r '.initialized_repos[] | select((.local_only // false) == false) | .path' "$repos_json" 2>/dev/null || echo "")
repo_paths=$(jq -r '.initialized_repos[] | select((.local_only // false) == false) | .path' "$repos_json" || echo "")
References
  1. In shell scripts with 'set -e' enabled, use '|| true' to prevent the script from exiting when a command like 'jq' fails on an optional lookup. Do not suppress stderr with '2>/dev/null' so that actual syntax or system errors remain visible for debugging.

local cleaned_output
cleaned_output=$(git -C "$repo_path" worktree list 2>/dev/null | wc -l)
local wt_count
wt_count=$(git -C "$repo_path" worktree list 2>/dev/null | wc -l | tr -d ' ')

Choose a reason for hiding this comment

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

medium

Similar to the jq command, suppressing stderr for this git command with 2>/dev/null is not ideal. Although you check for the existence of the .git directory beforehand, other issues like file permissions could cause git worktree list to fail. Allowing these errors to be reported would make debugging easier.

The repository's general rules advise against suppressing stderr when a file's existence has already been checked, as it can mask other important issues.

Suggested change
wt_count=$(git -C "$repo_path" worktree list 2>/dev/null | wc -l | tr -d ' ')
wt_count=$(git -C "$repo_path" worktree list | wc -l | tr -d ' ')
References
  1. Avoid using 2>/dev/null to suppress errors on file operations if the file's existence has already been verified by a preceding check (e.g., [[ -f "$file" ]] or an early return). This practice is redundant for 'file not found' errors and can mask other important issues like permissions problems.

@marcusquinn marcusquinn merged commit bf6fda2 into main Mar 6, 2026
34 of 36 checks passed
@marcusquinn marcusquinn deleted the chore/worktree-auto-cleanup branch March 6, 2026 02:16
marcusquinn added a commit that referenced this pull request Mar 6, 2026
Remove 2>/dev/null from jq and git worktree list commands in
cleanup_worktrees() — both had prior existence checks making the
suppression redundant for file-not-found errors, while masking
permission issues and malformed JSON diagnostics.

Addresses review feedback from Gemini on PR #2944.

Closes #2946
marcusquinn added a commit that referenced this pull request Mar 6, 2026
Remove 2>/dev/null from jq and git worktree list commands in
cleanup_worktrees() — both had prior existence checks making the
suppression redundant for file-not-found errors, while masking
permission issues and malformed JSON diagnostics.

Addresses review feedback from Gemini on PR #2944.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

chore: auto-cleanup worktrees after PR merge

1 participant