Git workflow skills with enforcement hooks for commits, PRs, and code review

version
0.1.0

Install

/plugin install git-workflow@claude-devcontainer

Run it inside Claude Code after adding the marketplace with /plugin marketplace add zookanalytics/claude-devcontainer.

Contents

Discovered from source

Skills 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:

  1. Load this skill ✓
  2. TodoWrite with 6 checklist items (see below) → FIRST response
  3. Execute steps, updating todos (step 1 runs two operations in parallel)

Wrong pattern (will fail):

  1. Load skill
  2. Run git commands without TodoWrite
  3. Forget a step
  4. Hook blocks commit ❌

Workflow Checklist

Create these TodoWrite items as your FIRST action, ALL steps are required:

  1. ☐ Run pnpm pre-commit (if available) AND Read docs/commit_specification.md (PARALLEL)
  2. ☐ Run git diff and analyze staging (see below)
  3. ☐ git add <files> (stage atomic unit of related files)
  4. ☐ git diff --staged (preview commit)
  5. ☐ Write .claude/.commit-state.json (signals workflow completion)
  6. ☐ 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:

  1. Gets the git repository root (fails safely if not in a git repo)
  2. Creates .claude/ directory if it doesn't exist
  3. 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:

  1. Fix unrelated error first
  2. Commit anyway (requires their decision)
  3. 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 feature
  • fix - Bug fix
  • docs - Documentation only
  • chore - Maintenance tasks
  • refactor - Code restructuring
  • test - Adding or updating tests
  • build - Build system changes
  • ci - CI configuration
  • perf - Performance improvements
  • style - Code style changes (formatting, etc.)

Examples:

  • feat/123-user-auth
  • fix/login-error
  • docs/api-guide
  • refactor/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 validation
  • fix: resolve login error
  • docs(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:

  1. Review commit history to understand the changes
  2. Identify the primary type (feat, fix, refactor, etc.)
  3. Summarize the changes concisely
  4. 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:

  1. Extract type from prefix: feat/... → feat
  2. Remove issue number if present: feat/123-user-auth → user auth
  3. 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 validation
  • fix/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:

  1. Pre-flight checks (parallel) - Check uncommitted changes and stash simultaneously
  2. Fetching and pruning - Syncs with remote and removes stale references
  3. Categorizing branches (parallel) - Check each branch's merge status concurrently
  4. Cleaning up merged branches - Removes local branches that were merged/deleted remotely
  5. Preserving new work - Keeps branches with commits not yet pushed
  6. 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 --porcelain shows 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:

  1. Skip if it's the current branch or main (protected)
  2. Check if gh pr list --state merged --head BRANCH returns a PR → safe to delete
  3. Check if branch appears in git branch --merged origin/main → safe to delete
  4. 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:

  1. If branch has merged PR on GitHub:
    • Try git branch -d first (may succeed for traditional merges)
    • If fails, use git branch -D (expected for squash/rebase merges)
    • Safe because GitHub confirms the PR was merged
  2. If branch appears in git branch --merged origin/main:
    • Use git branch -d (will succeed)
  3. If branch has zero unique commits:
    • Use git branch -d (will succeed, branch is empty)
  4. 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
  • Use -D only when PR is confirmed merged but -d fails (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:

  1. Creates new commit(s) on main with different SHAs
  2. Deletes the remote branch
  3. Your local branch shows [origin/branch-name: gone]
  4. BUT git branch --merged won't show it as merged (different commit SHAs)
  5. AND git merge-base --is-ancestor returns false (branch not in main's history)

The Solution: This command uses a three-tiered approach to safely identify merged branches:

  1. 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)
  2. 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)
  3. 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-ancestor checks 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-ancestor to 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 --porcelain shows 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:

ResultMeaningAction
Both succeedHEAD and origin/main are equalSTOP - nothing to PR
First only (AHEAD)origin/main is ancestor of HEADNormal flow - create branch
Second only (BEHIND)HEAD is ancestor of origin/mainSTOP - fast-forward first
Neither (DIVERGED)Branches have divergedCreate 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:

  1. Create feature branch from current HEAD (preserving your work):

    git checkout -b <branch-name>
    
  2. Rebase onto updated origin/main:

    git rebase origin/main
    
  3. 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> and git 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
  4. After successful rebase, continue with push step

  5. 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

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:

  1. Type - What kind of change? (feat, fix, docs, chore, refactor, test, build, ci, perf, style)
  2. 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:

  1. Review commits: git log origin/main..HEAD --oneline
  2. Identify the primary type of change (feat, fix, refactor, etc.)
  3. Summarize what the changes accomplish
  4. 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-auth with 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:

  1. No commits - "Pull request has no commits"
    • Verify commits exist between branch and main
  2. Auth issues - Check gh auth status
  3. 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:

  1. Update description first:
gh pr edit <number> --body "$(cat <<'EOF'
## Summary
<corrected description reflecting actual changes>

## Test plan
<verification steps>
EOF
)"
  1. Verify description is now accurate
  2. 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": null and "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:

  1. 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
  2. Branch protection violations

    • Check failed status checks, required reviews
    • Re-verify Step 4
  3. 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 merge to 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:

ThoughtReality
"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:

ConditionStateAction
Uncommitted changes existuncommittedRun /git:commit, then continue
No commits ahead of mainnothing-to-doSTOP - nothing to review
On main with commits, branches have divergedneeds-branchStart at Phase 1
On feature branch, no PR existsneeds-reviewStart at Phase 1
PR exists, is draft, no --ready flagdraftSelf-review only, report draft status
PR exists, is draft, --ready flag provideddraft-readyMark ready, proceed to Phase 3
PR exists, not draft, CI/Copilot pendingchecks-pendingWait for CI and Copilot
PR exists, not draft, CI failedci-failedFix failures
PR exists, checks passed, unresolved threadsmerge-blockedAddress ALL threads
PR exists, checks passed, no unresolved threadsreadyReport completion

CRITICAL: The merge-blocked state 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):

  1. PR title (if PR exists) - e.g., "feat(app): add Automerge CRDT integration" → "Automerge CRDT Integration"
  2. Branch name - e.g., feat/automerge-crdt-integration → "Automerge CRDT Integration"
  3. 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):

  1. Run /git:commit to commit the changes
    • Follows the creating-commits skill workflow
    • Runs pnpm fix, analyzes staging, creates atomic commit
  2. After successful commit, re-detect state and continue workflow
  3. 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:

  1. Local commits on main are always WIP - never intended to be pushed directly
  2. Proceed to Phase 1 (Self-Review) - review changes before creating PR
  3. 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:

  1. Run self-review (Phase 1 equivalent for existing PR)
  2. Skip Phases 3-5 (CI wait, feedback, sign-off)
  3. 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:

  1. Run self-review (Phase 1 equivalent for existing PR)
  2. Mark PR as ready: gh pr ready <number>
  3. 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-branch command 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 --ready flag: → Phase 3 (Wait for CI)
  • If no --ready flag: → 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:

ConditionStatusAction
Copilot in requested_reviewersIn ProgressWait for completion
review_requested after latest reviewedRe-reviewingWait for completion
reviewed exists, not in requested_reviewersCompleteCheck for feedback
No review_requested for CopilotNot TriggeredWait up to 5 min

Polling Strategy

Poll CI and Copilot status every 30 seconds:

  1. Get current PR state:

    gh pr view <number> --json headRefOid,statusCheckRollup,reviews
    
  2. Check CI status:

    • All checks SUCCESS or SKIPPED → CI passed
    • Any check FAILURE → CI failed
    • Otherwise → CI pending
  3. Check Copilot status (using timeline + requested_reviewers as above)

Note: statusCheckRollup contains CheckRun (.conclusion) and StatusContext (.state) - use .conclusion // .state to 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 StatusCopilot StatusTimeout?Action
✅ Passed✅ CompleteAny→ Phase 4 (check feedback)
✅ Passed⏳ In ProgressNoContinue waiting
✅ Passed⏳ In ProgressYes→ Phase 4 (proceed anyway)
✅ Passed❓ Not Triggered< 5 minWait for auto-trigger
✅ Passed❓ Not Triggered≥ 5 min→ Phase 4 (no review expected)
⏳ PendingAnyAnyContinue waiting for CI
❌ FailedAnyAny→ 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_requested event
  • Proceed to Phase 4 - no Copilot feedback expected
  • Note: Auto-review may be disabled or not configured for this repo

Handle CI Failure

  1. Fetch failure logs: gh run view <run-id> --log-failed
  2. Analyze root cause and fix the issue
  3. Commit fix: /git:commit
  4. Push: git push
  5. → 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:

  1. Fetch all unresolved review threads
  2. Evaluate each using parallel subagents
  3. Implement valid suggestions
  4. Reply to AND resolve each thread
  5. Generate summary report

See /git:receiving-code-review for complete workflow details.

After command completes:

  1. Verify all threads resolved (command should do this, but double-check):

    gh api graphql ... | jq '[.data.repository.pullRequest.reviewThreads.nodes[] | select(.isResolved == false)] | length'
    
  2. If threads remain unresolved:

    • Re-run /git:receiving-code-review OR
    • Manually address remaining threads
  3. Commit any changes: /git:commit

  4. Push to update PR: git push

  5. → 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:

CheckRequired
PR stateOPEN
All CI checksSUCCESS or SKIPPED
MergeableMERGEABLE
Unresolved threads0 (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:

LimitValueOn Exceed
CI fix attempts3 per failure typeAsk user
Feedback cycles5 round-tripsAsk user
Copilot wait10 minutesProceed without
CI waitNoneWait indefinitely

Resume Capability

This command is idempotent - run it multiple times safely.

On re-run:

  1. Detect current state (see State Detection)
  2. Skip completed phases
  3. Continue from current state
  4. 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:

  1. Unresolved threads (most common) → Return to Phase 4
  2. CI failing/pending → Return to Phase 3 or fix failures
  3. Branch protection rules → Check repository settings
  4. 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

CategoryAction
implementCheck file overlap → dispatch fixes
declineReply + resolve (parallel API calls)
escalateReply 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:

  1. 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>
    
  2. 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:

ExcuseReality
"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:

ExcuseReality
"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_to parameter, 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-commits skill
  • 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

More from zookanalytics/claude-devcontainer

All 3