Skip to main content

Git Workflow Automation Skill

Git Workflow Automation Skill

How to Use This Skill

  1. Review the patterns and examples below
  2. Apply the relevant patterns to your implementation
  3. Follow the best practices outlined in this skill

Automated git operations for common workflows: status checks, branch management, commits with conventional format, and pull request creation.

Git Operation Boundaries

Operation Scope Limits:

OperationSafeCautionDangerous
git status✅ Always--
git add✅ Specific files⚠️ git add .-
git commit✅ Conventional⚠️ --amend--amend on pushed
git push✅ Feature branch⚠️ Main branch--force on main
git pull--rebase⚠️ Merge commits❌ On dirty worktree
git reset--soft⚠️ --mixed--hard
git rebase✅ Local only⚠️ Interactive❌ On pushed commits
git branch -D✅ Merged branch⚠️ Unmerged❌ Current branch

Branch Operation Boundaries:

ActionAllowed BranchesBlocked Branches
Createfeature/, fix/, docs/*, etc.main, master
DeleteMerged feature branchesmain, master, current
Force pushNevermain, master, protected
RebaseLocal unpushedPushed, shared branches

Quick Decision: Safe vs Dangerous

Is this operation safe?
├── Read-only (status, log, diff) → ✅ Always safe
├── Local changes (add, commit) → ✅ Safe (check status first)
├── Push to feature branch → ✅ Safe
├── Push to main/master → ⚠️ Requires explicit confirmation
├── Force operations (--force) → ❌ Block without user approval
├── Reset operations → ⚠️ Check for uncommitted changes first
└── History rewrite (rebase pushed) → ❌ Dangerous, avoid

Task Isolation Operation Limits:

Task StateAllowed OperationsBlocked Operations
PENDINGcreate, statusmerge, discard
RUNNINGcommit, status, updatecreate new on same branch
COMPLETEDmerge, discard, statuscommit, run
MERGEDcleanup, statusany modifications
FAILEDretry, discard, statusmerge

Maximum Parallel Worktrees:

SystemMax WorktreesReason
Development laptop5Disk space, memory
CI runner3Container limits
Build server10Resource constraints

When to Use This Skill

Use this skill when:

  • Need to check git status across multiple files
  • Creating feature branches with standardized naming (feature/, fix/, docs/*)
  • Committing changes with conventional commit format (feat, fix, docs, refactor, test, chore)
  • Creating pull requests with auto-generated descriptions
  • Syncing with remote (fetch, pull, rebase)
  • Running parallel agent tasks with isolated worktrees
  • Multi-agent orchestration requiring code isolation
  • Need time savings: 8 min per workflow (10→2 min)
  • Proven pattern: Used 20+ times across Build #15-19

Don't use this skill when:

  • Simple git status check (use git directly)
  • Non-conventional commit messages preferred
  • gh CLI not installed (PR creation will fail)
  • Working on detached HEAD (branch operations unsafe)

Task Isolation via Git Worktrees

Overview

Git worktrees enable parallel agent execution by creating isolated copies of your codebase, each on a separate branch. This allows multiple Claude instances to work simultaneously without interference.

Key Benefits:

  • Parallelization: Run 4-5 agents simultaneously on different tasks
  • Isolation: Each worktree has independent file state
  • Efficiency: Complete hours of work in minutes
  • No context switching: Never lose work from branch switching

Architecture

my-repo/                          # Main working directory (main branch)
├── .coditect/
│ └── worktrees/
│ ├── task_state.json # Persisted task state
│ ├── task-abc123/ # Task 1 worktree (isolated)
│ ├── task-def456/ # Task 2 worktree (isolated)
│ └── task-ghi789/ # Task 3 worktree (isolated)

Python API

from pathlib import Path
from skills.git_workflow_automation.core.task_isolation import (
TaskIsolationManager, TaskStatus
)

# Initialize manager
manager = TaskIsolationManager(Path.cwd())

# Create isolated task environments
task1 = manager.create_task_environment(
"implement-user-auth",
base_branch="main",
agent_name="backend-development"
)
task2 = manager.create_task_environment(
"add-api-endpoints",
base_branch="main"
)

# Each task has an isolated worktree
print(f"Task 1 worktree: {task1.worktree_path}")
print(f"Task 1 branch: {task1.branch_name}")

# Update task status (integrates with multi-agent-workflow FSM)
manager.update_task_status(task1.task_id, TaskStatus.RUNNING)

# Commit changes in task worktree
commit_hash = manager.commit_task_changes(
task1.task_id,
"Add user authentication",
commit_type="feat",
scope="auth"
)

# Merge task back to main
manager.merge_task(task1.task_id, target_branch="main")

# Clean up completed tasks
manager.cleanup_completed()

CLI Usage

# Create a new task environment
python3 core/task_isolation.py create -d "implement-feature" -b main

# List all tasks
python3 core/task_isolation.py list

# Get status report
python3 core/task_isolation.py status

# Clean up completed tasks
python3 core/task_isolation.py cleanup

Task Lifecycle States

StateDescription
PENDINGTask created, worktree ready, work not started
RUNNINGAgent actively working in worktree
COMPLETEDWork done, ready for merge
MERGEDSuccessfully merged to target branch
FAILEDTask encountered errors
DISCARDEDTask cancelled, worktree removed

Integration with multi-agent-workflow

The task isolation system integrates with the multi-agent-workflow skill FSM:

# When orchestrator spawns parallel agents
from skills.git_workflow_automation.core.task_isolation import TaskIsolationManager

manager = TaskIsolationManager(repo_root)

# Create environments for each agent
agents = [
("backend-development", "implement-api"),
("frontend-development", "build-ui"),
("testing-specialist", "write-tests")
]

tasks = []
for agent_name, description in agents:
task = manager.create_task_environment(
description,
agent_name=agent_name
)
tasks.append(task)

# Each agent works in its isolated worktree
# No interference, parallel execution enabled

Checkpoint/Resume

Task state is automatically persisted to .coditect/worktrees/task_state.json:

{
"version": "1.0.0",
"tasks": [
{
"task_id": "task-abc123",
"branch_name": "coditect/task-abc123/implement-auth",
"worktree_path": ".coditect/worktrees/task-abc123",
"status": "running",
"created_at": "2025-12-18T10:30:00Z",
"metadata": {
"description": "implement-auth",
"agent": "backend-development"
}
}
]
}

Resume after session restart:

# State automatically loaded from task_state.json
manager = TaskIsolationManager(Path.cwd())
active_tasks = manager.list_active_tasks()
for task in active_tasks:
print(f"Resuming: {task.task_id} in {task.worktree_path}")

What It Automates

Before: (10+ minutes, 8+ commands)

# Check status
git status

# Create branch
git checkout -b feature/new-feature

# Stage and commit
git add .
git status
git commit -m "feat: add new feature"

# Push and create PR
git push -u origin feature/new-feature
gh pr create --title "Add new feature" --body "..."

# Sync with main
git fetch origin
git pull --rebase origin main

After: (2 minutes, 1-2 commands)

# Quick commit
./core/git-helper.sh --commit --message="Add new feature" --type=feat

# Create PR
./core/git-helper.sh --pr --title="Add new feature"

# Sync with main
./core/git-helper.sh --sync

Usage

Check Status

cd .claude/skills/git-workflow-automation
./core/git-helper.sh --status

Create Feature Branch

./core/git-helper.sh --branch --name="user-profile-editing" --type=feature

Commit Changes (Conventional Format)

./core/git-helper.sh --commit \
--message="Add user profile editing" \
--type=feat \
--scope=frontend

Commit Types:

  • feat - New feature
  • fix - Bug fix
  • docs - Documentation only
  • style - Formatting, missing semi-colons, etc.
  • refactor - Code change that neither fixes a bug nor adds a feature
  • test - Adding tests
  • chore - Updating build tasks, package manager configs, etc.

Create Pull Request

./core/git-helper.sh --pr \
--title="Add user profile editing" \
--body="Implements user profile editing with validation"

Sync with Remote

# Fetch and pull
./core/git-helper.sh --sync

# Rebase on main
./core/git-helper.sh --sync --rebase

Dry Run (Preview Changes)

./core/git-helper.sh --commit --message="Test" --type=feat --dry-run

Workflow Examples

Full Feature Workflow

# 1. Create feature branch
./core/git-helper.sh --branch --name="user-profile" --type=feature

# 2. Make changes...

# 3. Commit with conventional format
./core/git-helper.sh --commit \
--message="Add user profile editing component" \
--type=feat \
--scope=frontend

# 4. Push and create PR
./core/git-helper.sh --pr \
--title="User Profile Editing" \
--body="Implements profile editing with validation and error handling"

Quick Commit and Push

./core/git-helper.sh --commit \
--message="Fix JWT token expiration" \
--type=fix \
--scope=backend \
--push

Documentation Update

./core/git-helper.sh --commit \
--message="Update deployment checklist" \
--type=docs

Safety Checks

Automatic validations:

  1. ✅ Check for uncommitted changes before branch operations
  2. ✅ Verify branch doesn't already exist
  3. ✅ Conventional commit format validation
  4. ✅ Check remote connection before push
  5. ✅ Verify gh CLI installed for PR operations
  6. ✅ Prevent force push to main/master

Conventional Commit Format

Generated commit message format:

<type>(<scope>): <message>

<body (optional)>

🤖 Automated via git-workflow-automation skill

Co-Authored-By: Claude <noreply@anthropic.com>

Example:

feat(frontend): Add user profile editing

Implements profile editing with:
- Form validation
- Error handling
- Auto-save functionality

🤖 Automated via git-workflow-automation skill

Co-Authored-By: Claude <noreply@anthropic.com>

Branch Naming Convention

Enforced patterns:

  • feature/{name} - New features
  • fix/{name} - Bug fixes
  • docs/{name} - Documentation
  • refactor/{name} - Code refactoring
  • test/{name} - Test additions
  • chore/{name} - Maintenance tasks

Examples:

  • feature/user-profile-editing
  • fix/jwt-token-expiration
  • docs/deployment-guide
  • refactor/session-management

Pull Request Templates

Auto-generated PR body:

## Summary
[Commit messages from branch]

## Changes
- [Auto-extracted from git diff]

## Test Plan
- [ ] Unit tests pass
- [ ] Integration tests pass
- [ ] Manual testing complete

## Checklist
- [ ] Code follows project style
- [ ] Documentation updated
- [ ] Tests added/updated
- [ ] No breaking changes

🤖 Generated via git-workflow-automation skill

Implementation

See: core/git-helper.sh for complete implementation

Key functions:

  • check_status() - Show detailed git status
  • create_branch() - Create feature branch with naming convention
  • commit_changes() - Stage, commit with conventional format, optionally push
  • create_pr() - Generate PR with gh CLI and auto-generated body
  • sync_remote() - Fetch, pull, optionally rebase
  • validate_commit_message() - Ensure conventional format

Validation Checklist

  • Test 1: Status shows all modified files
  • Test 2: Branch created with correct naming convention
  • Test 3: Commit message follows conventional format
  • Test 4: PR created with auto-generated description
  • Test 5: Sync operations work correctly
  • Test 6: Dry-run mode previews changes

Metrics

Usage Statistics:

  • Times used: 20+ (Builds #15-19, documentation updates, cleanup)
  • Time saved per workflow: 8 minutes (10 min → 2 min)
  • Total time saved: 160+ minutes
  • Errors prevented: 5 (wrong commit format, missing PR descriptions)

Success criteria:

  • ✅ 100% conventional commit compliance
  • ✅ Zero failed pushes due to branch issues
  • ✅ 80%+ time savings vs manual git workflows

Real-World Examples

Example 1: Build #19 Deployment (Oct 19, 2025)

Command:

./core/git-helper.sh --commit \
--message="Add Build #19 to deployment checklist" \
--type=docs \
--body="Backend: 3489e960
Combined: 8860dda8
Changes: Billing fields + skills cleanup"

Generated commit:

docs: Add Build #19 to deployment checklist

Backend: 3489e960
Combined: 8860dda8
Changes: Billing fields + skills cleanup

🤖 Automated via git-workflow-automation skill

Co-Authored-By: Claude <noreply@anthropic.com>

Example 2: MONITOR-CODI Documentation (Oct 19, 2025)

Command:

./core/git-helper.sh --commit \
--message="Add MONITOR-CODI container provisioning strategy" \
--type=docs \
--scope=analysis

Example 3: Legacy V2 Cleanup (Oct 19, 2025)

Command:

./core/git-helper.sh --commit \
--message="Delete legacy V2 API and Cloud Run services" \
--type=chore \
--body="GKE: Deleted coditect-api-v2 deployment + service
Cloud Run: Deleted 8 orphaned services
Cost savings: $50-100/month"

Troubleshooting

Error: "Uncommitted changes"

  • Check: git status
  • Fix: Commit or stash changes before branch operations
  • Override: Use --force (not recommended)

Error: "Branch already exists"

  • Check: git branch -a
  • Fix: Use different branch name or delete old branch
  • Override: Use --delete-existing (dangerous)

Error: "gh CLI not found"

  • Check: which gh
  • Fix: Install GitHub CLI: sudo apt install gh or brew install gh
  • Skip: Use manual PR creation

Error: "Remote connection failed"

  • Check: git remote -v
  • Check: Network connectivity
  • Fix: Verify git remote URL is correct

Error: "Invalid commit type"

  • Valid types: feat, fix, docs, style, refactor, test, chore
  • Check: Commit type matches conventional format
  • Fix: Use correct type from the list

See Also

  • build-deploy-workflow - Full build/deploy automation
  • cross-file-documentation-update - Documentation synchronization
  • Git Workflow Guide: docs/GIT-WORKFLOW.md

Multi-Context Window Support

This skill supports long-running git workflow operations across multiple context windows using Claude 4.5's enhanced state management capabilities.

State Tracking

Git Workflow State (JSON):

{
"checkpoint_id": "ckpt_20251129_155000",
"git_operations": [
{"type": "branch", "name": "feature/user-profile", "status": "complete"},
{"type": "commit", "message": "Add profile editor", "status": "complete"},
{"type": "pr", "number": 42, "status": "in_progress"}
],
"sync_status": {
"last_fetch": "2025-11-29T15:50:00Z",
"behind_remote": 0,
"ahead_remote": 3
},
"uncommitted_changes": {
"modified": ["src/App.tsx", "backend/Cargo.toml"],
"untracked": []
},
"token_usage": 8000,
"created_at": "2025-11-29T15:50:00Z"
}

Progress Notes (Markdown):

# Git Workflow Progress - 2025-11-29

## Completed
- Created feature/user-profile branch
- Committed profile editor changes (conventional format)
- Pushed to remote

## In Progress
- PR #42 created, awaiting review
- CI/CD pipeline running

## Next Actions
- Address PR review comments
- Merge after approval
- Sync main branch

Session Recovery

When starting a fresh context window after git operations:

  1. Load Checkpoint State: Read .coditect/checkpoints/git-workflow-latest.json
  2. Review Progress Notes: Check git-workflow-progress.md for context
  3. Verify Git Status: Run git status to check current state
  4. Check Remote Sync: Verify sync status with remote
  5. Resume Workflow: Continue from last incomplete operation

Recovery Commands:

# 1. Check latest checkpoint
cat .coditect/checkpoints/git-workflow-latest.json | jq '.git_operations'

# 2. Review progress
tail -30 git-workflow-progress.md

# 3. Check git status
git status

# 4. Check remote sync
git fetch origin
git status

# 5. Resume from last operation
# Continue workflow

State Management Best Practices

Checkpoint Files (JSON Schema):

  • Store in .coditect/checkpoints/git-workflow-{timestamp}.json
  • Track uncommitted changes for quick recovery
  • Record sync status with remote branches
  • Include PR numbers and CI/CD status

Progress Tracking (Markdown Narrative):

  • Maintain git-workflow-progress.md with operation history
  • Document commit messages and rationale
  • Note PR feedback and resolutions
  • List next git operations planned

Git Integration:

  • Create checkpoint before major operations (merge, rebase)
  • Tag milestones: git tag feature-complete-v1.0
  • Use conventional commits consistently

Progress Checkpoints

Natural Breaking Points:

  1. After each successful commit
  2. After PR created
  3. After remote sync completed
  4. Before merge operations
  5. After feature branch cleanup

Checkpoint Creation Pattern:

# Automatic checkpoint after git operations
if commits_made >= 3 || pr_created {
create_checkpoint({
"operations": git_history,
"sync": remote_status,
"changes": uncommitted_files,
"tokens": current_tokens
})
}

Example: Multi-Context Feature Development

Context Window 1: Branch & Commits

{
"checkpoint_id": "ckpt_git_feature_start",
"phase": "commits_complete",
"operations": ["branch", "commit", "push"],
"commits": 3,
"next_action": "Create PR",
"token_usage": 2000
}

Context Window 2: PR & Merge

# Load checkpoint
cat .coditect/checkpoints/ckpt_git_feature_start.json

# Continue with PR creation and merge
# Token savings: ~5000 tokens (git history cached)

Token Savings Analysis:

  • Without checkpoint: 8000 tokens (re-check all git operations)
  • With checkpoint: 3000 tokens (resume from known state)
  • Savings: 63% reduction (8000 → 3000 tokens)

Success Output

When this skill completes successfully, output:

✅ SKILL COMPLETE: git-workflow-automation

Completed Git Operations:
- [x] Git status checked and validated
- [x] Branch created/switched: [branch-name]
- [x] Changes committed with conventional format: [commit-hash]
- [x] Pushed to remote: [remote-name]/[branch-name]
- [x] PR created: #[pr-number] (if applicable)
- [x] Remote sync completed (if applicable)

Outputs:
- Commit: [commit-hash] - [commit-message]
- Branch: [branch-name]
- PR URL: [url] (if created)
- Task worktrees: [count] active, [count] completed

Workflow time: [duration] (target: <2 min)

Completion Checklist

Before marking this skill as complete, verify:

  • Git status shows expected state (clean or intentional uncommitted changes)
  • Branch naming follows convention (feature/, fix/, docs/*, etc.)
  • Commit message follows conventional format (type(scope): message)
  • Remote push succeeded (if applicable)
  • PR created successfully with auto-generated description (if applicable)
  • Task worktrees cleaned up (if used)
  • No git errors or warnings in output
  • All safety checks passed (no force push to main/master)

Failure Indicators

This skill has FAILED if:

  • ❌ Git command returns non-zero exit code
  • ❌ Uncommitted changes prevent branch operations
  • ❌ Branch already exists (without --force flag)
  • ❌ Commit message validation fails
  • ❌ Remote connection failed during push
  • gh CLI not found when creating PR
  • ❌ Push to protected branch (main/master) attempted
  • ❌ Worktree creation failed due to existing directory
  • ❌ Merge conflicts during task merge
  • ❌ Task isolation state corruption

When NOT to Use

Do NOT use this skill when:

  • Single git command suffices (use git directly)
    • Example: Just need git status → run git status
    • Example: Simple git add . → run git add .
  • Non-conventional commit messages are required by project
    • Solution: Use git directly with custom message format
  • GitHub CLI (gh) not available and PR creation needed
    • Solution: Install gh first or create PR manually
  • Working on detached HEAD state
    • Solution: Check out a branch first
  • Git repository not initialized
    • Solution: Run git init first
  • Complex rebase/merge operations needed
    • Solution: Use git-workflow-orchestrator agent instead
  • Custom git hooks conflict with automation
    • Solution: Disable hooks temporarily or adjust skill usage

Anti-Patterns (Avoid)

Anti-PatternProblemSolution
Running without git status checkMay commit/push unintended changesAlways check status first with --status
Using --force flags carelesslyCan overwrite remote changesOnly use with explicit user confirmation
Skipping dry-run for batch operationsMass changes without previewAlways use --dry-run first for bulk operations
Creating PR without reviewing diffMay submit incomplete/incorrect codeReview git diff before PR creation
Not cleaning up task worktreesDisk space waste, confusionRun cleanup after task completion
Ignoring safety check warningsDangerous operations may proceedAddress all warnings before continuing
Force pushing to main/masterBreaks team workflowUse feature branches exclusively
Parallel worktrees without coordinationMerge conflicts, state confusionUse TaskIsolationManager properly
Committing without testingBroken code in historyRun tests before commit
Overly long commit messagesPoor git log readabilityKeep first line <72 chars, body <100 chars

Principles

This skill embodies the following CODITECT principles:

#1 Recycle → Extend → Re-Use → Create

  • Reuses existing git commands rather than reimplementing
  • Extends git workflow with conventional commits and task isolation
  • Creates automation layer without replacing git fundamentals

#2 Automation with Minimal Human Intervention

  • 80% time savings: 10 min → 2 min workflows
  • Automatic safety checks prevent errors
  • Self-provisioning: Creates branches, worktrees, backups automatically
  • No manual steps once workflow initiated

#3 Separation of Concerns

  • Git operations isolated in dedicated script (git-helper.sh)
  • Task isolation separated in TaskIsolationManager
  • Each operation independently testable and reusable

#5 Eliminate Ambiguity

  • Conventional commit format enforces clarity
  • Branch naming convention prevents confusion
  • Explicit status checks before operations
  • Clear success/failure markers in output

#6 Clear, Understandable, Explainable

  • Every git operation logged and visible
  • Dry-run mode previews changes
  • Detailed error messages guide troubleshooting
  • Progress tracking for multi-step workflows

#8 No Assumptions

  • Validates git repo exists before operations
  • Checks remote connection before push
  • Verifies gh CLI available before PR creation
  • Confirms branch doesn't exist before creation