Skip to content
Back to skills

Github Worktree Cleanup

ASecurity

Use when the user says the work is already merged or otherwise complete and wants to safely clean up the local feature branch and worktree that were used for that task in the current repository.

  • 2 stars
  • 0 votes
  • 0 copies
  • 5 views
  • Added November 11, 2026
businessrustgonoderailsgitapi

Works with

  • api

Security analysis

A100/100

Scanned November 26, 2026

npx -y skills add daisukekobayashi/dotfiles --skill github-worktree-cleanup --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Github Worktree Cleanup?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Github Worktree Cleanup
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/daisukekobayashi-github-worktree-cleanup/badge)](https://www.skillsdirectory.com/skills/daisukekobayashi-github-worktree-cleanup)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: github-worktree-cleanup
description: Use when the user says the work is already merged or otherwise complete and wants to safely clean up the local feature branch and worktree that were used for that task in the current repository.
---

# GitHub Worktree Cleanup

## Workflow

1. Resolve the cleanup target.
   - To resume a standalone cleanup interrupted after `git worktree remove`
     and before step 8, recover the original branch, exact PR, confirmed
     manifest, and explicit confirmation. Use a surviving checkout of the
     same local repository and the original runtime environment. Use that
     branch as the target and look up that exact PR in step 5. Recover the
     exact SHA-256 included with the targets in the original trusted
     confirmation. Use the original confirmed path. Never compute the
     expected digest from the file on resume or read it from storage beside
     the manifest. If the original context, confirmation, or digest cannot
     be established, stop and report the reason.
   - Prefer an explicitly named branch.
   - Otherwise use the current feature branch.
   - If the current branch is the default branch and no target is specified, stop and ask for the branch to clean up.
   - Stop and report the branch unless it is a **safe branch name** before running any command with it: run `node <script> -- '<branch>'`, where `<script>` is [`check-branch-name.mjs`](../delivery-common/scripts/check-branch-name.mjs) resolved from this skill's directory, and continue only on exit 0. Write a name into this or any command only when it uses solely ASCII letters, digits, `/`, `.`, `_`, and `-`; any other name is not safe, without running the check.
2. Detect whether the target checkout has an associated git worktree and record the path if present.
3. Verify that cleanup is safe from the PR's merge evidence, never from the local default branch, which can lag its remote: the local branch counts as merged only when step 5's PR lookup reports `MERGED` and the local branch tip equals its `headRefOid`, for any merge method. Step 6's manifest checks this and exits 3 with the reason otherwise.
4. If the branch is not merged, its local tip differs from the PR head, or completion is unclear, stop and explain why cleanup is unsafe.
5. Run the **remote branch deletion check**. Look up the PR for this branch
   (the PR number from the caller's merge evidence when given) with
   `gh pr view <number> --json number,state,headRefName,headRefOid,isCrossRepository,headRepository,headRepositoryOwner,url`,
   the default branch with `gh repo view --json defaultBranchRef`, whether the
   branch is protected with `gh api --paginate 'repos/<owner>/<repo>/branches?protected=true' --jq '.[].name'`,
   and the other open PRs with `gh pr list --head <branch> --state open --json number`;
   if any lookup fails, stop the whole cleanup. In standalone cleanup, before
   looking up the PR, resolve its host and base repository from the current
   repository context.
   Before constructing commands, allow only ASCII letters, digits, `.` and `-`
   in the host, those characters and `_` in each repository component, and
   ASCII letters, digits, `/`, `.`, `_`, and `-` in the remote name or private
   JSON file path. Stop on any other character. Run
   `node <cleanup-script> github-source --github '<host>' '<base-owner>/<base-repo>' --branch <branch>`,
   adding `--remote '<name>'` only when the user names it. Continue only on
   exit 0 with one source `<owner>/<repo>` from the selected local remote.
   When only the branch is given, read its exact local tip and list closed
   PRs in the resolved base using the source owner returned by the check:
   `gh api --hostname '<host>' --method GET --paginate 'repos/<base-owner>/<base-repo>/pulls' -f 'head=<source-owner>:<branch>' -f state=closed --jq '.[] | select(.merged_at != null) | {number, ref: .head.ref, sha: .head.sha, repository: .head.repo.full_name}'`.
   A head filter identifies a branch even when its name is numeric. Use only
   a unique PR number whose source repository, branch and SHA match the local
   evidence. Compare the repository with case ignored and the branch and SHA
   exactly. If that does not identify one PR, stop and report that an
   explicit PR number is needed. Require a positive decimal PR number. Pass
   `--repo '<host>/<base-owner>/<base-repo>'` to the PR and open-PR lookups above.
   Read the default branch with
   `gh repo view '<host>/<base-owner>/<base-repo>' --json defaultBranchRef`.
   For the protection lookup, use that base repository in the API path and
   pass `--hostname '<host>'`.
   Save the PR response to a private file outside the worktree. Before the remote check, run
   `node <cleanup-script> verify-merge --github '<host>' '<base-owner>/<base-repo>' --branch <branch> < '<pr-json>'`,
   adding `--remote '<name>'` before the redirection only when the user names it.
   Any non-zero exit stops the whole cleanup before confirmation. The check
   binds the PR source to the user-named remote, the exact branch upstream,
   or the only local remote independently of the PR response. Use the same
   response for all PR facts without printing its raw JSON. A verified fork
   may establish local merge evidence, and its remote branch is kept. A
   caller's verified merge evidence and Caller preview use the existing
   lookup by PR number. Then run `node <cleanup-script> remote <facts>`, where
   `<facts>` is `--github '<host>' '<owner>/<repo>' --branch <branch> --pr-state <state> --pr-head <headRefOid> --cross-repo <isCrossRepository> --default-branch '<default branch>' --protected <true|false> --open-prs <other open PRs>`
   with the PR URL's host and its head repository, plus `--remote '<name>'`
   when the user names one, writing each value into the command only when it
   uses solely ASCII letters, digits, `/`, `:`, `.`, `_`, and `-` (otherwise
   stop and report), and `<cleanup-script>` is
   [`check-cleanup-targets.mjs`](../delivery-common/scripts/check-cleanup-targets.mjs)
   resolved from this skill's directory. Exit 0 proposes deleting the remote
   branch or reports it absent; exit 3 keeps it, so report the reason and
   continue without it; any other status stops the whole cleanup.
6. Build the **cleanup target manifest** and require explicit confirmation of it: run `node <cleanup-script> manifest <facts> --worktree '<path>' --out '<file>'` (`--no-worktree` when there is none), adding `--temp '<path>'` for each run-owned temporary file `../worktree-runtime-cleanup/SKILL.md` identifies, with `<file>` a new path in agent-work storage or `/tmp` outside the worktree, and show the targets it prints, including any `unverified` section; any non-zero status stops the cleanup. Under a caller's combined confirmation, skip this build: the Caller preview manifest is the confirmed manifest. A caller's combined confirmation from Caller preview counts only when the user gave it in their own message and explicitly accepted these resources, and they match the preview as Caller preview defines; otherwise show them and ask again.
   For standalone cleanup, include the exact `manifest sha256` value from the
   manifest command's output with the targets in the original confirmation
   request. Obtain explicit confirmation of that set. Retain the value in
   the original trusted confirmation context, without writing it to a
   separate file. For the manifest, create a private directory with
   `mktemp -d` and choose a canonical absolute path outside the worktree.
   Keep the mode-600 manifest at that path in private storage to protect its
   inventory. For post-removal standalone resume, skip rebuilding and
   reconfirming only when the original confirmation and its digest are
   available. Use the original file in step 7.
7. Remove the local worktree first when one exists. If you are inside it, change to a safe location before removal.
   - For the post-removal standalone resume, use the fresh step 5 facts and
     the original confirmed worktree path, manifest, and digest. Run
     `node <cleanup-script> compare <facts> --worktree '<confirmed canonical path>' --confirmed '<file>' --after-worktree-removal --confirmed-sha256 '<original digest>'`
     with the same `--temp` targets. The compare verifies the original SHA-256
     before using the manifest. It checks that the path and Git registration
     are gone, and requires verifiable runtime listings at confirmation and
     now. It checks for remaining processes, Compose projects
     or volumes due for removal, and other changes before issuing branch
     authorization. Exit 0 continues directly to step 8 using the new compare
     output. On any non-zero exit, stop and report the exact reason. Keep the
     original manifest and the evidence that the compare found. Do not
     restart at step 6 with `--no-worktree` or use an earlier compare's
     output. Investigate the reported condition. Any separate cleanup needs
     an accurate inventory of the remaining targets and fresh confirmation
     for those targets. On the post-removal path, skip the runtime stop and
     worktree removal. For an interrupted cleanup dispatched by a delivery
     workflow, return to the caller for its reconfirmation procedure.
   - On a fresh cleanup, where no part of the confirmed runtime stop has run, before any removal, run `node <cleanup-script> compare <facts> <targets> --confirmed '<file>'` with step 5's facts, the same `--worktree` or `--no-worktree` and `--temp` targets as the confirmed manifest, and that manifest. Exit 0 continues; exit 3 means the targets changed, so remove nothing and confirm the new targets at step 6; any other status stops the cleanup.
   - On a resumed cleanup, where any part of the confirmed runtime stop already ran, skip that strict compare: before any further stop or removal, run the same compare with `--resume-stop` and the same exit handling. This permits outstanding, still-eligible confirmed volume removals.
   - Before removal, follow `../worktree-runtime-cleanup/SKILL.md` for the worktree path and pass it the same confirmed manifest, after that compare. If that file is absent, say so in the summary.
   - After the confirmed runtime stop, run the same compare with `--after-stop` right before `git worktree remove`. It expects confirmed processes, Compose projects, and temporary paths that the stop removed, once a fresh check shows each process exited and each project left none of the volumes it should delete and no new one, and prints each as `stopped as confirmed`; exit 3 on any other difference means remove nothing and confirm the new targets at step 6, and any other status stops the cleanup. The last compare's `local` and `lease` lines decide steps 8 and 9: use each only when that compare exited 0 and printed exactly one such line, and the `local` line only when it names the step 1 branch. Confirmed volume removals must be complete. Volumes listed for retention may remain. A legacy inventory-only manifest needs a fresh preview and confirmation at step 6. A confirmed process gone from the listing holds while any process has its PID, even a reused one, and a listing that cannot run holds when it was listed at confirmation, while one already unverified then stays unverified and continues. A confirmed target still listed unchanged passes: a failed stop is caught by the survivor check of `../worktree-runtime-cleanup/SKILL.md`, and a process that returns to the worktree after that check and before removal is an accepted residual. A fresh confirmation at step 6 re-lists the worktree's processes and continues, and a process that has left the worktree is no longer listed there, an accepted residual.
8. Delete the local branch after the worktree is removed, only with compare's `local <branch> <sha>` line; without that line, delete none. Immediately before deleting, run `node <cleanup-script> local <facts>` with step 5's facts: continue only on exit 0 with `proposed <sha>` at that SHA; exit 3 means the branch moved, another spelling of its name is in use, which git's exact-name guards miss on a case-insensitive ref store, or it is otherwise not deletable, so keep it and report the reason; any other status stops the cleanup. Then run `git branch -D <branch>`, which refuses a branch that any checkout still uses (checked out, rebasing including with `--update-refs`, or bisecting) and removes the branch's configuration with it. If it refuses, keep the branch and report the reason; never fall back to `git update-ref`. Never use `git branch -d`, which judges against the local default branch and refuses a squash merge. A commit that lands on the branch between the recheck and `git branch -D` is not detected, the same window `git branch -d` leaves.
9. Delete the confirmed remote branch last, conditioned on the SHA in compare's `lease <remote> <sha>` line; without that line, delete none:
   `git push --force-with-lease=refs/heads/<branch>:<sha> <remote> :refs/heads/<branch>`.
   If the lease is rejected, keep the branch and report that it changed.
10. Summarize what was removed and what remains.

## Caller preview

When a delivery caller combines the merge and cleanup confirmations, it asks for a preview before the merge. Run steps 1-2 and step 5's lookups, then run step 6's `manifest` command with `--preview`, which checks step 5's conditions other than the merged state with the PR head SHA to be merged as the expected remote SHA and local branch tip, and lists each process's PID, start time, and cwd as `list-processes.sh` reports them, each Compose project with its `working_dir` and volumes, and each temporary file path. Return the printed targets and the manifest path; on any non-zero status return no preview, so cleanup keeps its own confirmation. Remove and stop nothing.

After the merge, run the full workflow; step 7's compare against the preview manifest decides whether the targets match the preview. One tolerated difference is a previewed remote branch that no longer exists, such as one the host deleted on merge: compare drops it and reports it as already deleted by the host. Compare also accepts a previewed local branch that no longer exists, reporting it as already deleted, and, with `--after-stop`, previewed runtime resources the confirmed stop removed. A combined confirmation authorizes stopping or removing only runtime resources whose identifiers match the preview; any new or different resource needs its own confirmation.

## Guardrails

- Treat cleanup as destructive and require explicit confirmation.
- Never delete an unmerged branch. Decide merged from the PR's merge evidence, never from the local default branch.
- Remove a remote branch only when step 5 proposed it and the user confirmed it, or when the user explicitly asks.
- This skill cleans up only the local branch, the local worktree, the remote branch confirmed in step 6, and confirmed runtime resources covered by `../worktree-runtime-cleanup/SKILL.md`.
- Never assume the current branch is disposable just because the prompt says "merged."
- If git refuses removal because the worktree is busy or dirty, stop and report the exact blocker.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in business →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.