
git-workflow
Git workflow skills with enforcement hooks for commits, PRs, and code review
- version
- 0.1.0
Install
/plugin install git-workflow@claude-devcontainerRun it inside Claude Code after adding the marketplace with /plugin marketplace add zookanalytics/claude-devcontainer.
Contents
Discovered from sourceSkills 2
Creating Commits
Use before ANY commit - never skip for "simple" changes.
MANDATORY FIRST STEP
STOP: Create TodoWrite checklist BEFORE running any commands.
Correct pattern:
- Load this skill ✓
- TodoWrite with 6 checklist items (see below) → FIRST response
- Execute steps, updating todos (step 1 runs two operations in parallel)
Wrong pattern (will fail):
- Load skill
- Run git commands without TodoWrite
- Forget a step
- Hook blocks commit ❌
Workflow Checklist
Create these TodoWrite items as your FIRST action, ALL steps are required:
- ☐ Run
pnpm pre-commit(if available) AND Readdocs/commit_specification.md(PARALLEL) - ☐ Run
git diffand analyze staging (see below) - ☐
git add <files>(stage atomic unit of related files) - ☐
git diff --staged(preview commit) - ☐ Write
.claude/.commit-state.json(signals workflow completion) - ☐
git commit -m "type(scope): description"
Parallel optimization: Step 1 runs pnpm pre-commit (if the script exists) and reads docs/commit_specification.md simultaneously since they have no dependencies.
Steps 2-3: Staging Analysis
Before running git add, check current staging state:
Never stage files containing secrets (.env, credentials.json, *.pem, *_key, etc.) - warn user if these appear in diff.
Some files already staged? User pre-selected - verify staged files form atomic unit.
No files staged? After reviewing git diff, evaluate what constitutes an atomic unit:
- If all changes form one logical unit → stage all files and proceed
- If multiple logical changes detected → use AskUserQuestion to ask which atomic unit to commit first, then suggest splitting rest into separate commits
Multiple logical changes? See Atomic Commits section below for how to identify and split.
Step 5: Write Commit State File
Write this file after steps 1-4 and before step 6:
GIT_ROOT=$(git rev-parse --show-toplevel) && \
mkdir -p "$GIT_ROOT/.claude" && \
cat > "$GIT_ROOT/.claude/.commit-state.json" <<'EOF'
{
"workflow_completed": true
}
EOF
Important: This command:
- Gets the git repository root (fails safely if not in a git repo)
- Creates
.claude/directory if it doesn't exist - Writes the state file at the correct location regardless of working directory
This signals the pre-commit hook that you followed the workflow. Considered stale after 5 minutes. If the commit fails (e.g., git's pre-commit hook rejects it), you can retry immediately without rewriting this file.
Commit Message Format
type(scope): description - see docs/commit_specification.md
Focus on PURPOSE, not process:
- ✅ "add creating-commits skill for git workflow"
- ❌ "create skill and refactor for efficiency"
Review FULL diff - message describes collective change, not just latest conversation.
Atomic Commits
One logical change per commit. If multiple concerns (mixed types, different scopes, unrelated files) → suggest splitting.
Breaking Changes
If breaking backward compatibility → use feat(api)!: description and include BREAKING CHANGE: footer.
Common Rationalizations (STOP)
If you think any of these, STOP and follow checklist:
- "Just a comment, skip checks" → Comments have syntax errors
- "User gave message, skip preview" → Can't see what's staged
- "Too simple for
pnpm pre-commit" → Hooks fail on "simple" changes - "One extra file won't hurt" → Breaks atomic commits
When Checks Fail
pnpm pre-commit fails on your changes? Fix before committing.
pnpm pre-commit fails on unrelated code? Ask user:
- Fix unrelated error first
- Commit anyway (requires their decision)
- Investigate error
Never assume "error is unrelated, skip check" - ask.
Never Use --no-verify
Never use git commit --no-verify without explicitly asking user permission first in bold text.
Pull Request Conventions
Branch Naming Convention
Format: <type>/<issue-number>-<description> or <type>/<description>
Types (must match conventional commit types):
feat- New featurefix- Bug fixdocs- Documentation onlychore- Maintenance tasksrefactor- Code restructuringtest- Adding or updating testsbuild- Build system changesci- CI configurationperf- Performance improvementsstyle- Code style changes (formatting, etc.)
Examples:
feat/123-user-authfix/login-errordocs/api-guiderefactor/simplify-validation
PR Title Convention
PR titles must follow Conventional Commits format.
Format: <type>[optional scope]: <description>
Why: PR title becomes the squash merge commit message on main.
Examples:
feat(auth): add JWT validationfix: resolve login errordocs(api): update endpoint documentation
Deriving PR Title
Primary source: commits. The PR title should reflect what the changes actually accomplish, not just the branch name.
Process:
- Review commit history to understand the changes
- Identify the primary type (
feat,fix,refactor, etc.) - Summarize the changes concisely
- Add scope if clearly scoped to a specific area
Branch name as fallback: If starting from branch name (e.g., when branch already exists), use it as a hint:
- Extract type from prefix:
feat/...→feat - Remove issue number if present:
feat/123-user-auth→user auth - Convert hyphens to spaces
Scope is optional - add when the change is clearly scoped to a specific area:
feat/auth-jwt-validation→feat(auth): jwt validationfix/login-error→fix: login error(no obvious scope)
Important: The branch name may diverge from actual changes during development. Always verify the title accurately reflects what the PR contains.
PR Description Requirements
Foundational principle: Description must be 100% accurate.
Required Sections
## Summary
<1-3 bullet points describing what changed and why>
## Test plan
<How to verify the changes work>
Accuracy Rules
The description must reflect the final state of changes, not the journey:
- If code was added then removed: don't mention it
- If approach changed mid-development: describe final approach only
- If features were split to other PRs: don't reference them
Common Red Flags
When reviewing PR descriptions, watch for:
- Mentions features that were removed
- Describes approach that was changed
- References safeguards that were removed
- Contains code examples that don't match final implementation
Commands 6
Claude Command: Git Cleanup
Performs comprehensive git repository synchronization and cleanup while preserving local work.
Usage
/git:cleanup
Process
This command performs a safe sync and cleanup of your git repository by:
- Pre-flight checks (parallel) - Check uncommitted changes and stash simultaneously
- Fetching and pruning - Syncs with remote and removes stale references
- Categorizing branches (parallel) - Check each branch's merge status concurrently
- Cleaning up merged branches - Removes local branches that were merged/deleted remotely
- Preserving new work - Keeps branches with commits not yet pushed
- Reporting status - Provides clear summary of actions taken
Steps 1-2: Pre-flight Checks (PARALLEL)
Run these commands in parallel (no dependencies between them):
git status --porcelain # Check for uncommitted changes
git stash list # Check for stashed changes
After both complete:
- If
git status --porcelainshows changes: STOP and notify user concisely- Report what files/directories have changes
- State that cleanup cannot proceed until changes are committed or stashed
- Do NOT provide options or suggestions - just state the facts
- Count stash entries for final report (informational only)
- User should be made aware of forgotten stashed work
Step 3: Fetch and Prune
Sync with remote and remove stale remote-tracking branches:
git fetch --all --prune
What this does:
- Downloads latest commits from all remotes
- Removes remote-tracking branches that no longer exist on remote
- Does not modify local branches or working tree
Step 4: Identify Stale Branches
Find local branches whose remote counterparts are gone:
git branch -vv
Analysis:
- Parse output for branches marked
[origin/...: gone] - These are candidates for deletion (likely merged PRs)
- Extract branch names for review
Step 5: Categorize Branches (PARALLEL)
For each candidate branch with [origin/...: gone], determine if it's safe to delete.
Understanding merged PRs:
- When a PR is merged via GitHub (squash or rebase merge), the remote branch is deleted
- The local branch shows
[origin/branch-name: gone] - Squash/rebase merges create new commits, so the branch won't appear in
git branch --merged - Git ancestry checks (
git merge-base --is-ancestor) don't work for squash merges - We must check if a PR associated with the branch was merged on GitHub
Parallel categorization strategy:
# First, get shared context (run these in parallel):
git branch --show-current # Current branch (protected)
git branch --merged origin/main # All traditionally merged branches
# Then, for ALL candidate branches simultaneously, check GitHub PR status:
# Launch these in parallel - each is independent:
gh pr list --state merged --head BRANCH_1 --json number,title
gh pr list --state merged --head BRANCH_2 --json number,title
gh pr list --state merged --head BRANCH_3 --json number,title
# ... one call per candidate branch, ALL IN PARALLEL
# For branches with no merged PR, check unique commits (can also be parallel):
git rev-list origin/main..BRANCH_NAME --count
Why parallel: Each gh pr list call takes 1-2 seconds.
With 5 branches:
- Sequential: 5-10 seconds
- Parallel: 1-2 seconds total
Categorization logic per branch:
- Skip if it's the current branch or main (protected)
- Check if
gh pr list --state merged --head BRANCHreturns a PR → safe to delete - Check if branch appears in
git branch --merged origin/main→ safe to delete - Check
git rev-list origin/main..BRANCH --count:- 0 = no unique commits → safe to delete
-
0 = has unpushed work → preserve
Categories:
- Safe to delete:
- Branch has a merged PR on GitHub (primary indicator), OR
- Branch appears in
git branch --merged origin/main(traditional merge), OR - Branch has no unique commits compared to origin/main (empty branch)
- Has new work:
- No merged PR found AND
- Branch has commits not in origin/main AND
- Branch not in merged list
- Protected:
- Current branch (never delete)
- Main branch (never delete)
Step 6: Clean Up Safe Branches
Delete branches that are safe to remove:
# Use -d flag for safe deletion (will fail if truly unmerged)
git branch -d BRANCH_NAME
# If -d fails but we verified it's merged via PR:
# This WILL happen with squash/rebase merges
git branch -D BRANCH_NAME
Deletion strategy:
- If branch has merged PR on GitHub:
- Try
git branch -dfirst (may succeed for traditional merges) - If fails, use
git branch -D(expected for squash/rebase merges) - Safe because GitHub confirms the PR was merged
- Try
- If branch appears in
git branch --merged origin/main:- Use
git branch -d(will succeed)
- Use
- If branch has zero unique commits:
- Use
git branch -d(will succeed, branch is empty)
- Use
- Otherwise:
- Do NOT delete
- Report to user as preserved branch with unpushed work
Rules:
- Only delete if
[origin/...: gone]AND one of:- Has merged PR on GitHub (checked via
gh pr list), OR - Appears in
git branch --merged origin/main, OR - Has zero unique commits
- Has merged PR on GitHub (checked via
- Use
-Donly when PR is confirmed merged but-dfails (squash/rebase case) - Always protect current branch and main branch
- Report any branches that couldn't be safely categorized
Step 7: Report Results
Provide comprehensive status report:
If everything is clean:
✅ Repository is fully synced with remote
Summary:
- No uncommitted changes
- No stashed changes
- Deleted X merged branches: [list]
- All local branches are up to date
If local work exists:
⚠️ Repository synced with local work preserved
Summary:
- Uncommitted changes: [files list]
Action needed: Commit or stash these changes
- Stashed changes: X entries found
Reminder: You have stashed work that may need attention
Run 'git stash list' to review
- Deleted X merged branches: [list]
- Branches with unpushed work: [list]
These branches were kept because they have commits not yet pushed to remote
How Merged PR Detection Works
The Challenge: When you merge a PR on GitHub using "Squash and merge" or "Rebase and merge", GitHub:
- Creates new commit(s) on main with different SHAs
- Deletes the remote branch
- Your local branch shows
[origin/branch-name: gone] - BUT
git branch --mergedwon't show it as merged (different commit SHAs) - AND
git merge-base --is-ancestorreturns false (branch not in main's history)
The Solution: This command uses a three-tiered approach to safely identify merged branches:
-
GitHub PR Check (
gh pr list --state merged --head BRANCH)- PRIMARY METHOD - Checks if GitHub has a merged PR for this branch
- Works perfectly for squash/rebase merges (the standard workflow)
- Most reliable method because GitHub is the source of truth
- Handles all merge strategies (squash, rebase, traditional merge)
-
Traditional Merge Check (
git branch --merged origin/main)- Standard git merge detection
- Works for traditional merge commits
- Backup method if no PR found (direct commits to main)
-
Unique Commit Count (
git rev-list origin/main..BRANCH --count)- Counts commits in branch not in main
- If zero, branch adds nothing new (safe to delete)
- Catches empty branches or work already cherry-picked
Why git ancestry checks don't work:
git merge-base --is-ancestorchecks if commits are in the history tree- Squash merge creates a NEW commit, discarding the branch's commit history
- The branch's commits are never added to main's history
- Therefore ancestry check returns false even though changes were merged
Result: Branches from merged PRs are safely deleted even with GitHub's squash/rebase merge strategies by checking GitHub's PR state directly.
Safety Features
- Smart merge detection: Properly identifies merged PRs even with squash/rebase merges
- Ancestor verification: Uses
git merge-base --is-ancestorto confirm merges - Pre-flight checks: Validates working tree before making changes
- Conservative deletion: Only removes branches confirmed safe through multiple checks
- Protected branches: Never deletes current branch or main
- Clear reporting: Always explains what was kept and why
Error Handling
- Dirty working tree: Stop with concise message listing uncommitted changes only
- Failed deletions: Report which branches couldn't be deleted and why
- Network issues: Report fetch failures clearly
- Protected branches: Never attempt to delete main or current branch
Output Style
Concise error reporting:
- State the blocker clearly and briefly
- List affected files/directories
- No suggestions, options, or explanations unless cleanup proceeds
- Example: "Cannot proceed - uncommitted changes detected: .claude/commands/git/"
Example Output
Checking for uncommitted changes...
✓ Working tree is clean
Checking stash...
✓ Found 2 stashed entries
Fetching from remote and pruning stale references...
✓ Synced with origin
✓ Pruned 5 stale remote-tracking branches
Analyzing local branches...
Found 4 branches with deleted remotes:
- feat/user-auth [gone] - checking merge status...
✓ Found merged PR #45 on GitHub (squash merged)
- fix/login-bug [gone] - checking merge status...
✓ Found in git merged branches (traditional merge)
- docs/update-readme [gone] - checking merge status...
✓ No unique commits (empty branch)
- feat/new-feature [gone] - checking merge status...
⚠️ No merged PR found, has 3 unique commits (preserving)
Cleaning up merged branches...
✓ Deleted feat/user-auth (merged PR #45)
✓ Deleted fix/login-bug (traditional merge)
✓ Deleted docs/update-readme (no unique commits)
✅ Repository cleanup complete
Summary:
- Deleted 3 merged branches
- Kept 1 branch with unpushed work: feat/new-feature (3 unique commits)
- Current branch 'main' is up to date with origin/main
- Stashed changes: 2 entries (run 'git stash list' to review)
Commit
Use and follow the creating-commits skill exactly as written.
User-provided context: $ARGUMENTS
Incorporate user context into the commit message body when crafting the final commit.
Create Pull Request
User-provided context: $ARGUMENTS
Arguments
--ready- Create PR as ready for review (not draft). Triggers CI immediately.
By default, PRs are created as drafts to conserve GitHub Action minutes during iteration.
Use --ready when confident the PR is ready for CI and review.
Pre-flight Check and Current State (PARALLEL)
Run these commands in parallel (no dependencies between them):
git status --porcelain # Check for uncommitted changes
git branch --show-current # Determine current branch
After both complete:
- If
git status --porcelainshows changes: STOP.- Report: "Cannot create PR - uncommitted or untracked changes detected"
- List the files with changes
- Do not proceed until changes are committed
- If on main: Proceed to branch creation.
- If on another branch: Skip to push step.
Branch Creation (if on main)
Fetch Latest Remote State
Always fetch before checking for divergence:
git fetch origin
Check for Divergence (PARALLEL)
Run both merge-base commands in parallel:
git merge-base --is-ancestor origin/main HEAD && echo "AHEAD_OR_EQUAL"
git merge-base --is-ancestor HEAD origin/main && echo "BEHIND_OR_EQUAL"
Interpretation:
| Result | Meaning | Action |
|---|---|---|
| Both succeed | HEAD and origin/main are equal | STOP - nothing to PR |
| First only (AHEAD) | origin/main is ancestor of HEAD | Normal flow - create branch |
| Second only (BEHIND) | HEAD is ancestor of origin/main | STOP - fast-forward first |
| Neither (DIVERGED) | Branches have diverged | Create branch, then rebase |
Handle Diverged Main
If origin/main has commits not in local main:
This happens when commits were merged to main remotely while you worked locally. Local commits on main are always WIP intended for a PR, never direct pushes.
Resolution:
-
Create feature branch from current HEAD (preserving your work):
git checkout -b <branch-name> -
Rebase onto updated origin/main:
git rebase origin/main -
If rebase conflicts occur:
- Analyze both sides of each conflict
- Resolve automatically when intent is clear:
- Changes to different logical sections
- Additive changes that don't contradict
- One side is clearly the "updated" version
- After resolving, run
git add <file>andgit rebase --continue - Only STOP for user resolution when:
- Both sides modify the same logic with different intent
- Semantic conflict where correct resolution is ambiguous
- Report what the conflict is and why it needs human judgment
-
After successful rebase, continue with push step
-
If rebase fails completely (too many conflicts, cannot resolve):
- Abort rebase:
git rebase --abort - Fall back to merge:
git merge origin/main - Resolve merge conflicts if any
- This preserves work but creates a merge commit
- Report to user that merge was used instead of rebase
- Abort rebase:
Analyze Commits
Get commits that will be included:
git log origin/main..HEAD --oneline
If no commits ahead of origin/main: STOP.
- Report: "No commits to create PR from"
- Nothing to do
Determine Branch Name
Use the pull-request-conventions skill for naming format.
Analyze the commits to determine:
- Type - What kind of change? (
feat,fix,docs,chore,refactor,test,build,ci,perf,style) - Description - Brief summary of the change (2-4 words, hyphenated)
Format: <type>/<description>
Examples based on commits:
- "Add user authentication" →
feat/user-authentication - "Fix login validation bug" →
fix/login-validation - "Update API documentation" →
docs/api-updates
Create and Switch to Branch
git checkout -b <branch-name>
Push to Remote
Check if branch is already pushed:
git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null
If tracking branch exists: Check if up to date. If no tracking branch: Push with upstream:
git push -u origin <branch-name>
Open GitHub Pull Request
Check for Existing PR
gh pr list --head <branch-name> --json number,url --jq '.[0]'
If PR already exists:
- Report: "PR already exists:
url" - Return the existing PR URL
- Do not create a new one
Derive PR Title
Reference the pull-request-conventions skill for title format.
Derive from commits, not branch name. The branch name is a short handle that may have diverged from the actual changes. Analyze the commits to determine the appropriate title.
Process:
- Review commits:
git log origin/main..HEAD --oneline - Identify the primary type of change (
feat,fix,refactor, etc.) - Summarize what the changes accomplish
- Add scope if changes are clearly scoped to a specific area
Examples:
- Commits add authentication →
feat(auth): add user authentication - Commits fix validation bug →
fix: resolve login validation error - Commits update docs →
docs(api): update endpoint documentation - Branch
feat/123-user-authwith commits that add JWT →feat(auth): add JWT-based authentication
Generate PR Description
Analyze commits to create description:
git log origin/main..HEAD --pretty=format:"- %s"
Description format:
## Summary
<1-3 bullet points summarizing the changes>
## Test plan
<How to verify - infer from changes or use "Tested locally">
Create the PR
If --ready flag provided (create as ready for review):
gh pr create --title "<title>" --body "$(cat <<'EOF'
## Summary
<bullet points>
## Test plan
<verification steps>
EOF
)"
Otherwise (default - create as draft):
gh pr create --draft --title "<title>" --body "$(cat <<'EOF'
## Summary
<bullet points>
## Test plan
<verification steps>
EOF
)"
Output
After successful creation, report:
For draft PRs:
Created draft PR #<number>: <title>
<url>
CI is skipped for draft PRs. When ready for CI and review:
- Run: /git:orchestrate --ready
- Or manually: gh pr ready <number>
For ready PRs:
Created PR #<number>: <title>
<url>
Edge Cases
Branch Already Pushed, No PR
- Create PR for existing branch
- Use branch name for title derivation
PR Creation Fails
Common failures:
- No commits - "Pull request has no commits"
- Verify commits exist between branch and main
- Auth issues - Check
gh auth status - Repository permissions - User may not have push access
Report the error clearly and stop.
Merge Pull Request
User-provided context: $ARGUMENTS
Determine PR Number
If user provided a PR number in arguments: Use that PR number.
If no PR number provided: Automatically determine from current branch:
git branch --show-current
gh pr list --head <branch-name> --json number --jq '.[0].number'
- If found: use that PR number
- If not found: "No PR found for branch
branch-name" - If multiple PRs: show list and ask user which one
Pre-Merge Validation
Use TodoWrite to create todos for EACH validation step.
Step 1: Gather All Data (PARALLEL)
Run both queries in parallel (no dependencies between them):
# Query 1: Get all PR data in one call (includes headRefName for branch)
gh pr view <number> --json number,title,body,statusCheckRollup,mergeable,headRefName
# Query 2: Get commit history for description verification
# Use PR branch name (headRefName) to ensure correct history regardless of current branch
git log origin/main..origin/<headRefName> --oneline
Step 2: Verify PR Title
Reference the pull-request-conventions skill for title format.
Check format: <type>[optional scope]: <description>
The title becomes the squashed commit message on main.
Step 3: Verify PR Description
Foundational principle: Description must be 100% accurate. No exceptions.
Use the body from Step 1 and commit history from Step 1.
If description mentions specific features, approaches, or code changes, verify with diff:
gh pr diff <number>
Reference the pull-request-conventions skill for description requirements.
Red flags that block merge:
- Removed features: Description mentions "Added X" but X was removed
- Changed approaches: Description says "Using Y" but implementation uses Z
- Removed safeguards: Description claims safeguard that was removed
- Outdated code examples: Snippets don't match final implementation
If ANY red flags found - DO NOT MERGE:
- Update description first:
gh pr edit <number> --body "$(cat <<'EOF'
## Summary
<corrected description reflecting actual changes>
## Test plan
<verification steps>
EOF
)"
- Verify description is now accurate
- Only then proceed to merge
Step 4: Verify CI Checks
Use statusCheckRollup from Step 1.
All checks must show one of:
"conclusion": "SUCCESS"and"status": "COMPLETED"(passed)"conclusion": nulland"status": "SKIPPED"(legitimately skipped)
If any checks show SKIPPED: Verify it's intentional (conditional workflows, platform-specific tests).
If any checks failed:
- Flaky test: Rerun the check
- Real failure: DO NOT MERGE
- If fix needs code changes: STOP, inform user
- Never push unreviewed fixes to pass CI
Step 5: Verify Mergeable Status
CRITICAL: GitHub computes mergeability asynchronously. Always verify before merge.
Use mergeable from Step 1.
Expected states:
"mergeable": "MERGEABLE"- Ready to merge"mergeable": "CONFLICTING"- Has conflicts, cannot merge"mergeable": "UNKNOWN"- GitHub still computing, must wait
If status is UNKNOWN:
GitHub hasn't computed mergeability yet. This commonly happens after:
- Recent pushes to the PR branch
- Recent changes to the base branch
- PR just created or reopened
Wait and retry (up to 3 attempts, 5 seconds apart):
# Check status
gh pr view <number> --json mergeable --jq '.mergeable'
# If UNKNOWN, wait 5 seconds and check again
sleep 5
gh pr view <number> --json mergeable --jq '.mergeable'
If still UNKNOWN after 3 attempts:
- Inform user: "GitHub hasn't computed merge status yet. Try again in a moment."
- DO NOT attempt merge with UNKNOWN status. It will fail with misleading errors.
If CONFLICTING:
- Inform user: "PR has merge conflicts - needs resolution"
- User decides approach (rebase, merge main, manual resolution)
Merge the PR
Always use squash merge:
gh pr merge <number> --squash
Why squash merge:
- Clean, linear history - one commit per PR on main
- PR title becomes commit message
- Individual commits preserved in closed PR if needed
If Merge Fails
gh pr view <number> --json mergeable,mergeStateStatus
Common failures:
-
Merge conflicts -
"mergeable": "CONFLICTING"- Inform user: "PR has merge conflicts - needs resolution"
- User decides approach (rebase, merge main, manual resolution)
- After resolved, return to Step 1
-
Branch protection violations
- Check failed status checks, required reviews
- Re-verify Step 4
-
Insufficient permissions
- Inform user of permission issue
DO NOT attempt to resolve merge failures without user input.
Post-Merge Cleanup
After successful merge, IMMEDIATELY clean up:
# 1. Verify merge succeeded
gh pr view <number> --json state,mergedAt
# 2. Switch to main and pull (sequential - must complete before cleanup)
git checkout main
git pull origin main
# 3. Clean up local and remote refs (PARALLEL - run both simultaneously)
git branch -D <branch-name> # Delete local branch (-D required for squash merges)
git fetch --prune # Prune stale remote-tracking references
# 4. Verify remote branch was deleted
git branch -r | grep <branch-name> || echo "Remote branch deleted"
# 5. Update session purpose to indicate completion
# First, read the current purpose
cat .claude-metadata.json | jq -r '.purpose'
# Then update with completion prefix
./scripts/claude-instance purpose "COMPLETED: <previous-purpose>"
Note: Read the current purpose from .claude-metadata.json first, then replace
<previous-purpose> in the command with the actual value.
This marks the session as having completed its primary objective.
If remote branch still exists after verified merge: STOP.
- This shouldn't happen (GitHub auto-deletes)
- Inform user: "Remote branch still exists - check GitHub PR page"
- May indicate repository settings issue
Why cleanup immediately:
- Prevents accidentally adding commits to merged branch
- Keeps local git clean
- "I'll clean up later" never happens
Process Violations (Never Do These)
- Manually merge PR changes with
git mergeto main - Cherry-pick commits from PR branch directly
- Copy code changes without closing the PR
- Leave PRs open after manually incorporating changes
- Merge with outdated description
- Push code changes to fix CI without re-review
- Skip branch cleanup after merge
- Continue working on branch after it's been merged
Common Rationalizations (STOP)
If you think any of these, stop and follow the process:
| Thought | Reality |
|---|---|
| "PR title is what matters" | Description is permanent record. Both must be accurate. |
| "Description can be updated later" | Can't edit after merge. Do it now. |
| "Production urgency" | 5 min now saves hours debugging later. |
| "It's probably fine" | Run the commands. Takes 30 seconds. |
| "I'll clean up later" | You won't. Cleanup now. |
Orchestrate PR Workflow
User-provided context: $ARGUMENTS
Arguments
--ready- Mark PR as ready for review and trigger CI. Without this flag, PRs remain as drafts.
By default, PRs are created and kept as drafts to conserve GitHub Action minutes during iteration.
Use --ready when confident the PR is ready for CI and review.
Overview
This command orchestrates the complete pull request workflow as an idempotent state machine. Run it multiple times - it detects current state and continues from where you left off.
Phases (without --ready): Self-Review → Draft PR Creation → Report (CI skipped)
Phases (with --ready): Self-Review → PR Creation → Mark Ready → CI + Copilot → External Feedback → Ready for Sign-off
Key loop: After addressing feedback, return to Phase 3 (CI + Copilot) for re-validation.
State Detection
Use TodoWrite to create a checklist tracking workflow progress.
Example checklist items:
- Uncommitted changes addressed
- Commits ready
- Self-review completed
- PR opened
- CI and Copilot checks passed
- Feedback addressed
- Ready for sign-off
Parallel State Detection
Run these commands in parallel (no dependencies between them):
# Group 1: Independent queries (run all in parallel)
git status --porcelain # Uncommitted changes
git branch --show-current # Current branch
git fetch origin # Fetch latest remote state
After fetch completes, run these in parallel:
# Group 2: Depends on fetch (run all in parallel)
git log origin/main..HEAD --oneline # Commits ahead of main
git merge-base --is-ancestor origin/main HEAD && echo "AHEAD_OR_EQUAL"
git merge-base --is-ancestor HEAD origin/main && echo "BEHIND_OR_EQUAL"
# Interpretation: both succeed = EQUAL, first only = AHEAD, second only = BEHIND, neither = DIVERGED
If on a feature branch, also run:
# Group 3: PR status (run in parallel with Group 2 if branch known)
gh pr list --head <branch-name> --json number,state,isDraft --jq '.[0]'
gh pr view <number> --json statusCheckRollup,reviews,comments,isDraft # If PR exists
State determination:
| Condition | State | Action |
|---|---|---|
| Uncommitted changes exist | uncommitted | Run /git:commit, then continue |
| No commits ahead of main | nothing-to-do | STOP - nothing to review |
| On main with commits, branches have diverged | needs-branch | Start at Phase 1 |
| On feature branch, no PR exists | needs-review | Start at Phase 1 |
PR exists, is draft, no --ready flag | draft | Self-review only, report draft status |
PR exists, is draft, --ready flag provided | draft-ready | Mark ready, proceed to Phase 3 |
| PR exists, not draft, CI/Copilot pending | checks-pending | Wait for CI and Copilot |
| PR exists, not draft, CI failed | ci-failed | Fix failures |
| PR exists, checks passed, unresolved threads | merge-blocked | Address ALL threads |
| PR exists, checks passed, no unresolved threads | ready | Report completion |
CRITICAL: The
merge-blockedstate means unresolved review threads block the merge. This is NOT about "requiring approving review" - it's about ALL review comments being resolved. GitHub branch protection rules require all Copilot (and other reviewer) threads to be resolved before merge is allowed.
Validate Session Purpose
After state detection, validate the session purpose matches the work being orchestrated.
Sources for purpose (in priority order):
- PR title (if PR exists) - e.g., "feat(app): add Automerge CRDT integration" → "Automerge CRDT Integration"
- Branch name - e.g.,
feat/automerge-crdt-integration→ "Automerge CRDT Integration" - First commit message summary
Check and update:
# Read current purpose
cat .claude-metadata.json 2>/dev/null | jq -r '.purpose // empty'
# If purpose is empty, stale, or doesn't match the work, update it
./scripts/claude-instance purpose "<derived-purpose>"
Keep purpose broad - describes the overall goal, not specific steps. Examples:
- ✅ "Automerge CRDT Integration"
- ✅ "JWT Authentication"
- ❌ "Processing Copilot feedback" (too specific)
- ❌ "Phase 3 CI checks" (workflow step, not purpose)
Handling uncommitted State
When uncommitted changes exist (staged or unstaged):
- Run
/git:committo commit the changes- Follows the creating-commits skill workflow
- Runs
pnpm fix, analyzes staging, creates atomic commit
- After successful commit, re-detect state and continue workflow
- If commit fails (lint errors, user intervention needed), report and STOP
This allows orchestrate to take over from any working state - user doesn't need to manually commit before running orchestrate.
Handling needs-branch State
When on main with local commits and origin/main has diverged:
- Local commits on main are always WIP - never intended to be pushed directly
- Proceed to Phase 1 (Self-Review) - review changes before creating PR
- Then Phase 2 (
/git:create-pull-request) handles branch creation and rebase
The needs-branch state does NOT skip self-review.
Phase 2 will:
- Detect the divergence
- Create an appropriately named feature branch
- Rebase onto origin/main (or merge if rebase fails)
- Push and create the PR
Handling draft State (no --ready flag)
When PR is draft and --ready flag not provided:
- Run self-review (Phase 1 equivalent for existing PR)
- Skip Phases 3-5 (CI wait, feedback, sign-off)
- Report completion:
Self-review complete. PR remains in draft mode.
PR: #<number> - <title>
URL: <url>
CI is skipped for draft PRs to conserve GitHub Action minutes.
When ready for CI and review:
- Run: /git:orchestrate --ready
- Or manually: gh pr ready <number>
Rationale: Allows frequent self-review cycles without burning CI minutes.
Handling draft-ready State (--ready flag provided)
When PR is draft and --ready flag provided:
- Run self-review (Phase 1 equivalent for existing PR)
- Mark PR as ready:
gh pr ready <number> - Proceed to Phase 3 (Wait for CI and Copilot)
Phase 1: Local Self-Review
Entry: State is needs-review or needs-branch (committed but no PR yet)
Goal: Catch issues before external reviewers see them.
Use the slash command, not just a skill. The
/superpowers:review-branchcommand executes the full review workflow. You MUST run the command.
Run /superpowers:review-branch which will:
- Review all branch changes against main
- Identify code quality issues, bugs, missing tests
- Generate fixes for problems found
Exit criteria:
- All self-review issues addressed
- Changes committed (if any fixes made)
- Ready for PR creation
Transition: → Phase 2
Phase 2: Create Pull Request
Entry: Self-review complete, no PR exists
If --ready flag provided:
Run /git:create-pull-request --ready to:
- Create feature branch if on main
- Push to remote
- Open PR as ready for review (not draft)
Otherwise (default - create as draft):
Run /git:create-pull-request to:
- Create feature branch if on main
- Push to remote
- Open PR as draft (CI skipped)
Capture PR number and URL for tracking.
Transition:
- If
--readyflag: → Phase 3 (Wait for CI) - If no
--readyflag: → Report draft status and STOP
Phase 3: Wait for CI and Copilot
Entry: PR exists, awaiting CI completion and Copilot review
Detect Copilot Review Status
Use the timeline and requested_reviewers APIs to accurately detect Copilot status:
# Get Copilot events from timeline (review_requested and reviewed)
gh api repos/{owner}/{repo}/issues/{pr}/timeline --jq '
[.[] | select(
(.event == "review_requested" and .requested_reviewer.login == "Copilot") or
(.event == "reviewed" and .user.login == "Copilot")
)] | sort_by(if .event == "reviewed" then .submitted_at else .created_at end)'
# Check if Copilot is in pending reviewers
gh api repos/{owner}/{repo}/pulls/{pr}/requested_reviewers --jq '
.users[] | select(.login == "Copilot")'
Copilot Status Determination:
| Condition | Status | Action |
|---|---|---|
Copilot in requested_reviewers | In Progress | Wait for completion |
review_requested after latest reviewed | Re-reviewing | Wait for completion |
reviewed exists, not in requested_reviewers | Complete | Check for feedback |
No review_requested for Copilot | Not Triggered | Wait up to 5 min |
Polling Strategy
Poll CI and Copilot status every 30 seconds:
-
Get current PR state:
gh pr view <number> --json headRefOid,statusCheckRollup,reviews -
Check CI status:
- All checks
SUCCESSorSKIPPED→ CI passed - Any check
FAILURE→ CI failed - Otherwise → CI pending
- All checks
-
Check Copilot status (using timeline + requested_reviewers as above)
Note:
statusCheckRollupcontainsCheckRun(.conclusion) andStatusContext(.state) - use.conclusion // .stateto handle both.
Timeouts:
- Copilot triggered: 10 minutes from
review_requested(typical: 30s-5min) - Copilot not triggered: 5 minutes grace period to see if auto-triggered
- CI: No timeout (wait indefinitely)
Decision Matrix:
| CI Status | Copilot Status | Timeout? | Action |
|---|---|---|---|
| ✅ Passed | ✅ Complete | Any | → Phase 4 (check feedback) |
| ✅ Passed | ⏳ In Progress | No | Continue waiting |
| ✅ Passed | ⏳ In Progress | Yes | → Phase 4 (proceed anyway) |
| ✅ Passed | ❓ Not Triggered | < 5 min | Wait for auto-trigger |
| ✅ Passed | ❓ Not Triggered | ≥ 5 min | → Phase 4 (no review expected) |
| ⏳ Pending | Any | Any | Continue waiting for CI |
| ❌ Failed | Any | Any | → Handle CI Failure |
Exit: CI passed AND (Copilot complete OR in-progress timeout OR not-triggered grace period)
If Copilot in-progress timeout reached:
- Report: "CI passed but Copilot hasn't completed after 10 minutes (unusual)"
- Offer to wait longer or proceed without Copilot review
If Copilot never triggered:
- After 5 minute grace period with no
review_requestedevent - Proceed to Phase 4 - no Copilot feedback expected
- Note: Auto-review may be disabled or not configured for this repo
Handle CI Failure
- Fetch failure logs:
gh run view <run-id> --log-failed - Analyze root cause and fix the issue
- Commit fix:
/git:commit - Push:
git push - → Restart Phase 3 (wait for new CI run)
Retry limit: 3 attempts per unique failure type. After limit: STOP and report to user.
Phase 4: Process External Feedback
Entry: CI passed and Copilot reviewed (or timeout)
Check for Unresolved Threads
Query GitHub for unresolved review threads:
gh api graphql -f query='...' --jq '...' # See /git:receiving-code-review for full query
If Unresolved Threads Exist
CRITICAL: Unresolved threads block PR merges. You MUST resolve ALL threads before the PR can be merged.
Run /git:receiving-code-review <pr-number> to:
- Fetch all unresolved review threads
- Evaluate each using parallel subagents
- Implement valid suggestions
- Reply to AND resolve each thread
- Generate summary report
See /git:receiving-code-review for complete workflow details.
After command completes:
-
Verify all threads resolved (command should do this, but double-check):
gh api graphql ... | jq '[.data.repository.pullRequest.reviewThreads.nodes[] | select(.isResolved == false)] | length' -
If threads remain unresolved:
- Re-run
/git:receiving-code-reviewOR - Manually address remaining threads
- Re-run
-
Commit any changes:
/git:commit -
Push to update PR:
git push -
→ Return to Phase 3 (wait for CI and Copilot to re-review)
Common mistake: Claiming work is "done" without verifying threads are resolved. Check unresolved thread count FIRST before diagnosing merge blocks.
If No Unresolved Threads
Proceed to Phase 5 (Ready for Sign-off).
Phase 5: Ready for Sign-off
Entry: CI passing, all feedback addressed (or none received)
Final verification:
gh pr view <number> --json state,statusCheckRollup,reviews,mergeable
Completion criteria:
| Check | Required |
|---|---|
| PR state | OPEN |
| All CI checks | SUCCESS or SKIPPED |
| Mergeable | MERGEABLE |
| Unresolved threads | 0 (or escalated to user) |
Final Report:
## PR Ready for Sign-off
**PR:** #<number> - <title>
**URL:** <url>
**Branch:** <branch-name> → main
### Verification Complete
| Phase | Status |
| ----------------- | --------------------------- |
| Self-Review | ✓ Complete |
| CI + Copilot | ✓ All passing |
| External Feedback | ✓ Addressed / None received |
### Changes Summary
<1-3 sentence summary of what the PR accomplishes>
### Commits
<list of commits in PR>
### Escalated Items
<list any items that need human decision, or "None">
### Next Steps
Human review and approval, then:
- Merge: `/git:merge-pull-request`
Iteration Limits
Prevent infinite loops:
| Limit | Value | On Exceed |
|---|---|---|
| CI fix attempts | 3 per failure type | Ask user |
| Feedback cycles | 5 round-trips | Ask user |
| Copilot wait | 10 minutes | Proceed without |
| CI wait | None | Wait indefinitely |
Resume Capability
This command is idempotent - run it multiple times safely.
On re-run:
- Detect current state (see State Detection)
- Skip completed phases
- Continue from current state
- Preserve all previous work
Example re-run scenarios:
- "CI or Copilot pending" → Continue waiting from Phase 3
- "New comments appeared" → Process them in Phase 4
- "Everything green" → Report ready state
Error Handling
Merge Blocked
If PR merge fails, diagnose in priority order:
- Unresolved threads (most common) → Return to Phase 4
- CI failing/pending → Return to Phase 3 or fix failures
- Branch protection rules → Check repository settings
- Merge conflicts → Resolve conflicts with main
Common mistake: Assuming "requires approving review" without checking unresolved threads first. Copilot review comments are the most common merge blocker.
CI Repeatedly Fails
After 3 fix attempts for same failure:
CI continues to fail after 3 fix attempts.
Failure: <check name>
Error: <error summary>
Options:
1. Show full error log
2. I'll investigate manually
3. Skip this check (not recommended)
Cannot Address Feedback
If feedback requires architectural decisions:
- Escalate to user with context
- Do NOT guess or make assumptions
- Mark as "Needs Discussion" in report
- Continue with other actionable items
API/Network Errors
- Retry transient errors (3 attempts with backoff)
- Report persistent failures clearly
- Preserve local state (never lose work)
Key Principles
- Idempotent - Safe to run multiple times
- State-aware - Detects where you are, continues from there
- Transparent - Reports what it's doing and why
- Escalates honestly - Uncertain items need human judgment
- Never blocks indefinitely - Timeouts and user prompts prevent hangs
Receiving Code Review
User-provided context: $ARGUMENTS
Overview
Process review comments on a GitHub PR using parallel subagent orchestration.
Use Skill tool to load superpowers:receiving-code-review for evaluation criteria.
Get Context (PARALLEL)
If no PR number provided, run both queries in parallel:
# Query 1: Get repository info
gh repo view --json owner,name --jq '{owner: .owner.login, repo: .name}'
# Query 2: Detect PR from current branch
gh pr list --head "$(git branch --show-current)" --json number --jq '.[0].number'
If PR number is provided: Only run Query 1 (repo info).
Use owner/repo values in all API calls below.
Fetch Unresolved Threads
gh api graphql -f query='
query($owner: String!, $repo: String!, $number: Int!) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $number) {
reviewThreads(first: 50) {
nodes {
id
isResolved
comments(first: 10) {
nodes { id, author { login }, body, path, line }
}
}
}
}
}
}
' -f owner="$OWNER" -f repo="$REPO" -F number=$PR_NUMBER
Filter to isResolved: false only.
Parallel Processing Architecture
Phase 1: Parallel Evaluation
Dispatch one Task per thread with subagent_type: "general-purpose":
Evaluate review thread. Context: repo={owner}/{repo}, PR={number}, thread_id={id}, file={path}, line={line}.
Comment: <body>
Evaluation criteria (from receiving-code-review skill):
1. Technically correct for THIS codebase?
2. Breaks existing functionality?
3. Reason for current implementation?
4. Reviewer has full context?
Read the file. Categorize: implement|decline|escalate.
Return JSON only:
{"thread_id":"<id>","comment_id":"<comment_id>","category":"implement|decline|escalate","affected_files":["<path>"],"response":"<explanation>","fix":"<description or null>"}
Launch ALL evaluation subagents in a single message (parallel Task invocations).
Phase 2: Group Results
| Category | Action |
|---|---|
implement | Check file overlap → dispatch fixes |
decline | Reply + resolve (parallel API calls) |
escalate | Reply only, report to user |
Phase 3: Decline/Escalate (Parallel API Calls)
No subagents needed—just parallel gh api calls:
# Reply to comment thread
gh api repos/<owner>/<repo>/pulls/<pr>/comments \
-f body="<response>" \
-F in_reply_to=<comment_id>
# Resolve thread (decline only)
gh api graphql -f query='
mutation($threadId: ID!) {
resolveReviewThread(input: {threadId: $threadId}) {
thread { isResolved }
}
}
' -f threadId="<thread_id>"
Phase 4: Smart Implementation
Group by file overlap:
- Non-overlapping → parallel Task dispatch
- Overlapping → sequential within group
Implementation subagent prompt:
Implement fix. Context: repo={owner}/{repo}, PR={number}, thread_id={id}, file={path}.
Feedback: <comment body>
Fix required: <description from evaluation>
Read file. Make ONLY the required change. Return JSON:
{"thread_id":"<id>","status":"fixed|failed","changes":"<description>","files":["<path>"]}
Phase 5: Reply and Resolve Each Thread
After implementations complete, for EVERY thread:
-
Reply directly to the thread (not a standalone PR comment):
gh api repos/<owner>/<repo>/pulls/<pr>/comments \ -f body="<response>" \ -F in_reply_to=<comment_id> -
Resolve the thread (mark it closed in GitHub):
gh api graphql -f query=' mutation($threadId: ID!) { resolveReviewThread(input: {threadId: $threadId}) { thread { isResolved } } } ' -f threadId="<thread_id>"
Response templates:
- Fixed: "Fixed. {description of changes}"
- Declined: "Declined. {reasoning why current approach is correct}"
- Escalated: "Escalating. {why this needs human decision}"
Phase 6: Verify All Threads Resolved
BLOCKING: Do NOT report completion until this passes.
UNRESOLVED=$(gh api graphql -f query='
query($owner: String!, $repo: String!, $pr: Int!) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $pr) {
reviewThreads(first: 100) {
nodes { isResolved }
}
}
}
}
' -f owner="<owner>" -f repo="<repo>" -F pr=<number> \
--jq '[.data.repository.pullRequest.reviewThreads.nodes[] | select(.isResolved == false)] | length')
echo "Unresolved threads: $UNRESOLVED"
If UNRESOLVED > 0: Go back and resolve remaining threads before proceeding.
Summary Report
| # | Comment | Response | Status |
| --- | ------- | ------------ | ----------- |
| 1 | desc | what changed | ✓ Fixed |
| 2 | desc | reasoning | ✓ Declined |
| 3 | desc | uncertainty | Needs input |
Rationalization Counters
Do NOT skip parallelization because:
| Excuse | Reality |
|---|---|
| "Only 2 threads, not worth it" | Parallel dispatch has no overhead. Use it. |
| "I'll evaluate as I go" | Sequential = slower. Parallel evaluation first. |
| "File overlap is complex" | Simple set intersection. Check affected_files. |
| "Subagents add latency" | Parallel subagents are faster than sequential agent. |
Do NOT skip thread processing because:
| Excuse | Reality |
|---|---|
| "This one seems minor" | Every comment deserves acknowledgment. |
| "I'll batch similar ones" | Each thread gets its own reply. No batch. |
| "Already addressed by another fix" | Still reply explaining this. |
Important Notes
- Never skip threads — every comment deserves acknowledgment
- Reply directly to thread — use
in_reply_toparameter, not standalone comments - Resolve every thread — unresolved threads block PR merge
- Verify before claiming done — run Phase 6 check, confirm 0 unresolved
- Escalate honestly — if uncertain, say so (but still resolve the thread)
- Commit after implementing — use
creating-commitsskill - Maximize parallelism — only serialize for file overlap
Completion means UNRESOLVED = 0. If any threads remain open, you have NOT completed this command.
Hooks 1
Sponsors
Details
- Marketplace
- zookanalytics/claude-devcontainer
- Source
- packages/git-workflow
- Category
- Community