Git workflows: worktrees, branches, and commit organization

version
1.0.0

Install

/plugin install commit@dot-claude

Run it inside Claude Code after adding the marketplace with /plugin marketplace add pproenca/dot-claude-old.

Contents

Discovered from source

Skills 1

Git Commit

Always use the commit script or heredoc format. Never use -m "..." with newlines.

Single-line commit

$CLAUDE_PLUGIN_ROOT/scripts/commit.sh "type: description"

Multi-line commit

$CLAUDE_PLUGIN_ROOT/scripts/commit.sh "type: description" "Body explaining WHY.

Additional context if needed."

Alternative: Direct heredoc

git commit -F - <<'EOF'
type: description

Body explaining WHY.
EOF

Never do this

# WRONG - causes shell parsing issues with multiline messages
git commit -m "type: description
body text"

Commands 3

Create New Commit

Announce at start: "Creating a commit from staged changes."


Step 1: Check Staged Changes

Run this command NOW:

git diff --cached --stat

If no output: STOP. Tell user: "No staged changes. Run git add <files> first."

If output exists: Continue.


Step 2: Analyze and Draft

Run these commands:

git diff --cached
git diff --cached --name-only

Determine Type

PatternType
Only test files (*_test.*, test_*.*, tests/, __tests__/)test
Only docs (*.md, docs/, README*)docs
Only CI files (.github/, .gitlab-ci*, Jenkinsfile)ci
Only build configs (Makefile, *config.*, package.json deps)build
Bug fix patterns (error handling, null checks, edge cases)fix
Files renamed/moved, no new exportsrefactor
New files in source directories, new exports/functionsfeat

Pick the best-fit type. Only ask the user if two types are genuinely equally valid (e.g., changes both add a feature AND fix a bug).

Check Breaking Changes

Scan for these patterns:

  • Removed function/method definitions
  • Changed function signatures (added required parameters)
  • Removed exports or public APIs
  • Changed return types

If detected, mark as breaking change (add ! and footer). Do not ask—show in the message.

Draft Message

Format: type[!]: description

Rules:

  • Type prefix required (feat, fix, docs, etc.)
  • ! before colon for breaking changes
  • Imperative mood ("add", not "adding")
  • Lowercase description
  • 50-72 chars ideal, max 100
  • No period at end

Body (for non-trivial changes):

  • Explains WHY, not WHAT
  • What issue prompted this
  • Why this approach

Step 3: Confirm and Execute

Present the complete commit message and ask:

  • Header: "Commit"
  • Question: "Ready to commit with this message?"
  • Options:
    • Commit: Execute this commit now
    • Edit: I'll provide corrections
    • Split: Break into multiple commits
    • Cancel: Abort without committing
  • multiSelect: false

If "Commit"

Single-line:

git commit -F - <<'EOF'
type: description
EOF

Multi-line:

git commit -F - <<'EOF'
type: subject

Body text.
EOF

Breaking changes:

git commit -F - <<'EOF'
feat!: remove deprecated API

BREAKING CHANGE: description.
EOF

Verify with:

git log -1 --format='%B'

If "Edit"

Apply user's corrections and re-present.

If "Split"

Tell user:

  • To split: git reset HEAD <files> to unstage some files, then run /commit:new for each logical commit
  • For complex reorganization: use /commit:reset

If "Cancel"

Stop without committing.


Notes

  • Use heredoc with quoted delimiter (<<'EOF') for commit messages (prevents all shell expansion including !)
  • Validation hooks will check the format

Generate PR Description

Create a PR title and description from branch commits following Conventional Commits format.

Workflow

  1. Analyze branch commits
  2. Determine dominant commit type
  3. Generate PR title
  4. Generate PR description
  5. Present for review

Step 1: Analyze Branch Commits

Determine base branch (default: origin/main or origin/master):

# Get default branch
DEFAULT_BRANCH=$(git remote show origin 2>/dev/null | grep 'HEAD branch' | cut -d' ' -f5)
BASE_BRANCH="${1:-$DEFAULT_BRANCH}"

# Get branch point
BRANCH_POINT=$(git merge-base HEAD origin/$BASE_BRANCH 2>/dev/null || git merge-base HEAD $BASE_BRANCH)

# Get current branch
CURRENT_BRANCH=$(git branch --show-current)

echo "Current branch: $CURRENT_BRANCH"
echo "Base branch: $BASE_BRANCH"
echo "Branch point: $BRANCH_POINT"

Get all commits on this branch:

git log --oneline $BRANCH_POINT..HEAD

Get combined diff stats:

git diff --stat $BRANCH_POINT..HEAD

Read each commit message to understand the full scope of changes:

git log --format='%B---' $BRANCH_POINT..HEAD

Step 2: Determine Dominant Commit Type

Analyze the commits to determine the primary type for the PR title.

Type priority (use the most significant):

  1. feat - Any new feature makes this a feature PR
  2. fix - Bug fixes if no features
  3. refactor - Restructuring if no features/fixes
  4. perf - Performance improvements
  5. docs - Documentation changes
  6. test - Test additions
  7. build/ci - Build/CI changes
  8. chore - Maintenance

Breaking change: If ANY commit has ! or BREAKING CHANGE:, the PR title should include !.

Single commit: Use that commit's type and subject directly.

Multiple commits with same type: Use that type, summarize the changes.

Multiple commits with different types: Use the highest priority type, describe the overall change.


Step 3: Generate PR Title

The PR title should follow Conventional Commits format:

<type>: <summary of changes>

Add ! before the colon for breaking changes (e.g., feat!: remove API).

Rules:

  • Use dominant type from Step 2
  • Include ! if any commit is a breaking change
  • Imperative mood ("add", not "adding")
  • 50-72 chars ideal
  • No period at end

Examples:

CommitsPR Title
Single feat: add user preferencesfeat: add user preferences
feat: add auth, feat: add sessionsfeat: add authentication system
feat: add API, fix: handle errorsfeat: add API with error handling
refactor: extract service, test: add testsrefactor: extract service with tests
feat!: remove v1 APIfeat!: remove v1 API

Step 4: Generate PR Description

Structure the description following this template:

## Summary

[1-3 sentences explaining WHAT this PR does and WHY]

## Changes

[Bullet list of commits/changes, grouped logically by type]

### Features
- [feat commits]

### Bug Fixes
- [fix commits]

### Other Changes
- [refactor/chore/etc commits]

## Context

[Background that helps reviewers understand the change]

- Problem being solved
- Why this approach was chosen
- Any tradeoffs or limitations

## Breaking Changes

[If any commits have breaking changes, list them here]

- [Description of breaking change and migration path]

## Test Plan

[How to verify this works]

- [ ] Unit tests pass
- [ ] Integration tests pass
- [ ] Manual testing: [steps if applicable]

Note: Omit empty sections (e.g., if no breaking changes, omit that section).


Step 5: Present for Review

Present the generated title and description, then validate with AskUserQuestion:

PR Validation

  • Header: "PR"
  • Question: "Does this PR title and description accurately describe your changes?"
  • Options:
    • Looks good: Use this title and description as-is
    • Edit title: I want to adjust the PR title
    • Edit description: I want to modify the description or test plan
    • Major changes: Significant rewrites needed to both

Output the final PR content formatted for copy-paste:

## PR Title
[title]

## PR Description
[full description]

Notes

  • This command generates PR content but does NOT create the PR
  • Use gh pr create --title "..." --body "..." to create the PR
  • If branch has unorganized commits, suggest running /commit:reset first
  • The description should provide enough context that links may become inaccessible
  • PR title must follow Conventional Commits format for release-please compatibility

Commit History Reset and Organization

Reorganize git commits following Conventional Commits specification.

Commit message validation runs automatically via hooks.

Workflow

  1. Safety check and backup
  2. Dispatch commit-organizer agent for analysis
  3. Review and approve proposed organization
  4. Execute commits
  5. Verify

Step 1: Safety Check and Backup

git rev-parse --git-dir && git branch --show-current && git status --porcelain

If uncommitted changes: STOP - user must commit or stash first.

Create backup:

BACKUP_BRANCH="backup/$(git branch --show-current)-$(date +%Y%m%d-%H%M%S)"
git branch $BACKUP_BRANCH
echo "Backup: $BACKUP_BRANCH"

Step 2: Dispatch Commit-Organizer Agent

Use the Task tool with subagent_type="commit:commit-organizer" to analyze the branch.

The agent will:

  • Run ${CLAUDE_PLUGIN_ROOT}/scripts/analyze-branch.sh to get full diffs
  • Read ALL diffs holistically (cumulative change, not individual commits)
  • Classify changes (refactoring/fix/feature/config)
  • Apply Conventional Commits rules (separation, size limits, self-containment)
  • Propose commit organization with draft messages

Prompt for the agent:

Analyze this branch and propose a commit organization following Conventional Commits specification.

For each proposed commit, provide:
- Files and line count
- Proposed subject (passes "Git Log Test")
- Proposed body (Problem/Solution format)
- Reasoning for this grouping

The agent will return a detailed commit organization plan.


Step 3: Review Agent's Proposal

Present the agent's proposed commit organization to the user.

Use AskUserQuestion to confirm the proposed organization:

Organization Approval

  • Header: "Plan"
  • Question: "Do you approve this commit organization?"
  • Options:
    • Approve: Proceed with this organization
    • Adjust groupings: I want to change how files are grouped into commits
    • Edit messages: The groupings are fine but I want to adjust commit messages
    • Rethink: Start over with different organization criteria

DO NOT proceed until user approves the plan.


Step 4: Execute Commits

  1. Create TodoWrite list with each commit as an item

  2. Soft reset to branch point:

git reset --soft $BRANCH_POINT
  1. For EACH commit in the approved plan:
# Stage ONLY the files for this commit
git add [specific files]
git status  # Verify only intended files staged

# Create commit with agent's proposed message
git commit -m "$(cat <<'EOF'
[Agent's proposed subject]

[Agent's proposed body]
EOF
)"
  1. Mark todo complete ONLY after commit succeeds and passes validation hooks

Step 5: Verify

git log --oneline $BRANCH_POINT..HEAD
git log --stat $BRANCH_POINT..HEAD
git status

Check that:

  • Each commit is self-contained
  • Commit order makes sense (dependencies first)
  • Messages explain WHY, not just WHAT

Recovery

If anything goes wrong:

git reset --hard $BACKUP_BRANCH

Notes

  • Do not push automatically - let user review first
  • Safety hooks block dangerous operations without backup
  • Commit validation happens automatically via PostToolUse hooks
  • Guidelines - refer to cheatsheet for Conventional Commits details

Agents 1

Commit Organization Specialist

Announce at start: "Analyzing branch for commit organization."

Progress Tracking

Create TodoWrite todos NOW:

  • Run branch analysis script
  • Reason through changes (chain-of-thought)
  • Classify changes by type
  • Apply Conventional Commits rules
  • Propose commit organization
  • Validate and present to user

Mark each as in_progress when starting, completed when done.


When NOT to Use

Skip when:

  • Single commit with clear message
  • Just need to stage and commit (use git directly)
  • Commits already follow Conventional Commits format

Still use when:

  • Multiple messy commits need reorganization
  • Need to split large commits logically
  • Preparing PR with clean history

FIRST ACTION (Mandatory)

Run this script NOW before doing anything else:

python3 -S ${CLAUDE_PLUGIN_ROOT}/scripts/analyze_branch.py

This outputs JSON with:

  • Branch point commit
  • All changed files with FULL DIFF CONTENT
  • Line counts per file

Error Handling

ScenarioAction
"error": "Not a git repository"STOP - inform user they must be in a git repo
"error": "Could not find branch point"Ask user for the base branch name
Empty files arraySTOP - inform user there are no changes to organize
Script execution errorFall back to manual git diff commands
Binary files in diffNote them separately; they go with their logical commit
Single file with all changesStill apply splitting if >400 lines; explain single-file limitation

CRITICAL: Read ALL diffs. Understand the cumulative change from branch point to HEAD.


Step 2: Reason Through Changes

Work through these questions NOW and write out your reasoning explicitly:

2.1 Primary Goal Analysis

  1. "What is the PRIMARY goal of this branch?" - The main feature, fix, or refactoring
  2. "How would I describe this branch in one sentence to a colleague?"

2.2 Secondary Change Detection

  1. "Are there SECONDARY changes mixed in?" - Cleanup, formatting, unrelated fixes
  2. "Were any refactorings done to ENABLE the main work?" - These should be separate commits

2.3 File Relationship Mapping

  1. "Which files are CORE to the goal vs SUPPORTING?"
    • Core: Files that implement the main change
    • Supporting: Tests, configs, documentation
  2. "Which files changed together logically?" - Same feature, same layer, same concern

2.4 Dependency Analysis

  1. "What order must these changes be applied?" - Types before implementations, interfaces before consumers
  2. "Could a reviewer understand Commit N without reading Commits 1..N-1?"

Write out your reasoning before proceeding.


Step 3: Classify Changes

For each changed file/section, classify NOW using Conventional Commits types:

TypeDescriptionExampleTriggers Release
featNew functionality being addedNew endpoint, UI componentYes (MINOR)
fixSpecific problem being correctedFix null pointer, race conditionYes (PATCH)
refactorMoves, renames, extractions with NO behavior changeExtract method, rename variableNo
perfPerformance improvementOptimize query, add cachingNo
docsDocumentation changesUpdate README, add commentsNo
testAdding or updating testsAdd unit tests, fix flaky testNo
buildBuild system, dependenciesUpdate deps, CI configNo
ciCI/CD configuration changesGitHub Actions, JenkinsNo
choreOther maintenanceCleanup, formattingNo

Breaking Change Detection

Mark commits as breaking (feat!:, fix!:) if they:

  • Remove or rename public API/exports
  • Change function signatures (add required params)
  • Remove environment variables or config keys
  • Change default behavior in incompatible way

Verification Checkpoint

Verify NOW before proceeding:

  • Every file assigned exactly one primary type
  • Any file marked "unclear" has a question queued for user
  • No file left unclassified
  • Refactoring vs feature distinction is clear (behavior change = not refactoring)
  • Breaking changes identified and marked

Step 4: Apply Conventional Commits Rules

These are NON-NEGOTIABLE:

RuleEnforcement
Every commit has type prefixMUST include feat/fix/refactor/etc
Refactoring NEVER mixed with features/fixesMUST separate
Tests go WITH their feature/fixSame commit
Each commit is self-containedMust work independently
~100 lines idealBest for review
200-400 linesAcceptable with justification
400+ linesMUST split unless single-file

Step 5: Apply Splitting Strategies

When changes exceed 200 lines, apply these strategies:

Stacking (Sequential Dependencies)

Commit 1: refactor: add interface/types for new feature
Commit 2: feat: implement core logic
Commit 3: feat: migrate consumers to new implementation

Horizontal (By Layer)

Commit 1: feat: add shared types/interfaces
Commit 2: feat: implement backend logic
Commit 3: feat: add frontend integration

Vertical (By Feature)

Commit 1: feat: add multiplication operator
Commit 2: feat: add division operator
(NOT: "feat: add arithmetic operators")

Step 6: Propose Commit Organization

For each proposed commit, provide this format NOW:

Commit N: [type]: [Brief description]
  Confidence: [HIGH/MODERATE/LOW]
  Files: [list of files]
  Lines: ~[count]
  Why grouped: [explanation based on actual code you read]

  Proposed message:
  [type][!]: [description in imperative mood, lowercase]

  [Body explaining WHY - context, rationale, limitations]

  [BREAKING CHANGE: description if applicable]

  Dependencies: [none / Commit N-1 because...]

  [If MODERATE/LOW confidence, add:]
  Alternative: [Different grouping option and why it might be preferred]

Confidence Levels

LevelMeaningAction
HIGHClear single purpose, obvious groupingProceed confidently
MODERATEReasonable grouping, valid alternatives existPresent alternative
LOWJudgment call, multiple valid approachesAsk user preference

The "Git Log Test"

Every proposed subject must pass: A developer skimming git log --oneline should understand what this commit does without clicking into it.


Step 7: Validate Before Presenting

Verify each commit NOW:

  • Has valid type prefix (feat/fix/refactor/etc)
  • Single concern (one logical change)
  • Standalone (understandable without reading other commits)
  • Complete (includes tests if behavior changes)
  • Functional (codebase works after this commit alone)
  • Searchable subject (future devs can grep for it)
  • WHY explained (body explains rationale, not just what)
  • Breaking changes marked with exclamation mark (!) or footer

Step 8: Present to User

Use AskUserQuestion to present your analysis:

If questions needed first

Use AskUserQuestion with these parameters:

  • Header: "Clarify"
  • Question: "[Specific question about intent or grouping]"
  • Options:
  • multiSelect: false

Present proposal

Output in this order:

  1. Branch Summary - 1-2 sentences: What this branch accomplishes
  2. Proposed Commits - Use format from Step 6
  3. Splitting Rationale - WHY you grouped changes this way
  4. Warnings - Any concerns (size, mixed types, unclear intent)

Then use AskUserQuestion with these parameters:

  • Header: "Organization"
  • Question: "Does this commit organization look right?"
  • Options:
    • Looks good: Proceed with this organization
    • Modify grouping: I want to adjust how changes are grouped
    • Different approach: Let's discuss alternative organization
  • multiSelect: false

Important Guidelines

  1. Ask questions BEFORE proposing if intent is unclear
  2. Be specific - reference actual file names and line ranges
  3. Explain your reasoning - why this grouping makes sense
  4. Show alternatives for MODERATE/LOW confidence decisions
  5. Draft real messages - provide copy-paste-ready commit messages
  6. Always include type prefix - mandatory for release-please
  7. Mark breaking changes - use exclamation mark (!) and/or BREAKING CHANGE footer

Sponsors

Details

Marketplace
pproenca/dot-claude-old
Source
plugins/essential/commit
Category
Community
License
MIT
Keywords
git, worktrees, branches, commits

More from pproenca/dot-claude-old

All 12