dhofheinz avatar

git-commit-assistant

Intelligent git commit helper with semantic commit message generation, change analysis, and atomic commit guidance using conventional commits format

version
1.0.0
GitHub stars
9

Install

/plugin install git-commit-assistant@open-plugins

Run it inside Claude Code after adding the marketplace with /plugin marketplace add dhofheinz/open-plugins.

Contents

Discovered from source

Commands 40

Operation: Analyze Splitting

Determine if current changes should be split into multiple commits.

Parameters from $ARGUMENTS

  • verbose:true|false - Detailed analysis output (default: false)
  • threshold:number - File count threshold for splitting (default: 10)

Workflow

Step 1: Get Current Changes

Invoke Bash to get git status and diff:

git status --porcelain
git diff --cached --stat
git diff --cached --numstat

Capture:

  • List of modified files
  • Number of files changed
  • Additions/deletions per file

Step 2: Run Split Analyzer

Execute the split analyzer script:

.claude/plugins/git-commit-assistant/commands/atomic-commit/.scripts/split-analyzer.py

The script analyzes:

  1. Type diversity: Multiple commit types (feat, fix, docs, etc.)
  2. Scope diversity: Multiple modules/components affected
  3. File count: Too many files changed
  4. Concern separation: Mixed concerns in changes

Step 3: Analyze Results

Parse analyzer output to determine:

Should Split if:

  • Multiple commit types detected (feat + fix + docs)
  • Multiple scopes detected (auth + api + ui)
  • File count exceeds threshold (>10 files)
  • Mixed concerns detected (feature + unrelated refactoring)

Keep Together if:

  • Single logical change
  • All files serve same purpose
  • Interdependent changes
  • Reasonable file count (≤10)

Step 4: Generate Recommendation

Create actionable recommendation:

If should split:

šŸ”€ SPLIT RECOMMENDED

Reason: Multiple types detected (feat, fix, docs)
Files affected: 15
Detected types: feat (8 files), fix (5 files), docs (2 files)

Recommendation: Split into 3 commits
- Commit 1: feat changes (8 files)
- Commit 2: fix changes (5 files)
- Commit 3: docs changes (2 files)

Next steps:
1. Run: /atomic-commit group strategy:type
2. Review groupings
3. Run: /atomic-commit suggest

If already atomic:

āœ… ATOMIC COMMIT

Changes represent single logical unit:
- Single type: feat
- Single scope: auth
- File count: 5 files
- Logically cohesive: OAuth implementation

No splitting needed. Proceed with commit.

Output Format

Return structured analysis:

should_split: true|false
reason: "Primary reason for recommendation"
metrics:
  file_count: number
  types_detected: [list]
  scopes_detected: [list]
  concerns: [list]
recommendation: "Action to take"
next_steps: [ordered list of commands]

Error Handling

  • No changes: "No staged or unstaged changes detected. Make changes first."
  • Script failure: "Analysis failed. Check git repository status."
  • Invalid parameters: "Invalid parameter. Use verbose:true or threshold:number"

MCP Tool Integration

Use workspace-mcp for script execution:

  • Spawn isolated workspace if needed
  • Execute analyzer script
  • Parse and return results
  • Clean up temporary files

Examples

Example 1: Large feature

/atomic-commit analyze
→ Should split: 15 files, multiple types

Example 2: Bug fix

/atomic-commit analyze verbose:true
→ Atomic: 3 files, single fix

Example 3: Custom threshold

/atomic-commit analyze threshold:5
→ Should split: 8 files exceeds threshold

Operation: Create Sequence

Generate executable commit sequence plan.

Parameters from $ARGUMENTS

  • groups:string - Group specifications (e.g., "feat:5,fix:2,docs:1")
  • output:plan|script - Output format (default: plan)
  • auto_stage:true|false - Auto-stage files (default: false)

Workflow

Step 1: Get Commit Suggestions

If not provided, invoke commit suggestion:

/atomic-commit suggest

Parse suggestions to get commit details.

Step 2: Analyze Dependencies

Execute dependency checker:

.claude/plugins/git-commit-assistant/commands/atomic-commit/.scripts/dependency-checker.sh

Identify dependencies between commits:

  • File dependencies (imports, references)
  • Logical dependencies (feature order)
  • Test dependencies (code → tests)

Build dependency graph:

feat(auth) → test(auth) → docs(auth)
     ↓
fix(api) → test(api)

Step 3: Determine Commit Order

Apply ordering rules:

Priority 1: Dependencies

  • Commits with dependencies come first
  • Tests after implementation
  • Docs after features

Priority 2: Type Order Standard order:

  1. feat (features enable other changes)
  2. fix (fixes should be applied early)
  3. refactor (restructuring before additions)
  4. perf (performance after stability)
  5. test (tests after implementation)
  6. docs (documentation last)
  7. chore (housekeeping last)

Priority 3: Scope Grouping

  • Related scopes together
  • Independent scopes can be parallel

Priority 4: Impact

  • High-impact changes first
  • Low-risk changes can be later

Step 4: Generate Sequence Plan

Create executable sequence:

šŸ“‹ COMMIT SEQUENCE PLAN

Execution Order: 3 commits in sequence

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ COMMIT 1: feat(auth)                        │
│ Files: 8                                    │
│ Dependencies: None                          │
│ Can execute: āœ… Now                         │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Message:
  feat(auth): implement OAuth 2.0 authentication

  Add complete OAuth 2.0 authentication flow with
  support for multiple providers (GitHub, Google).

Files to stage:
  git add src/auth/oauth.ts
  git add src/auth/tokens.ts
  git add src/auth/providers/github.ts
  git add src/auth/providers/google.ts
  git add src/config/oauth.config.ts
  git add src/types/auth.types.ts
  git add tests/auth/oauth.test.ts
  git add tests/auth/tokens.test.ts

Command:
  git commit -m "feat(auth): implement OAuth 2.0 authentication" -m "Add complete OAuth 2.0 authentication flow with support for multiple providers (GitHub, Google). Includes token management, refresh handling, and comprehensive test coverage."

─────────────────────────────────────────────

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ COMMIT 2: fix(api)                          │
│ Files: 3                                    │
│ Dependencies: None                          │
│ Can execute: āœ… After commit 1              │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Message:
  fix(api): handle null pointer in user endpoint

  Fix null pointer exception when user profile
  is incomplete.

Files to stage:
  git add src/api/endpoints.ts
  git add src/api/validation.ts
  git add tests/api.test.ts

Command:
  git commit -m "fix(api): handle null pointer in user endpoint" -m "Fix null pointer exception when user profile is incomplete. Add validation to check for required fields before access."

─────────────────────────────────────────────

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ COMMIT 3: docs                              │
│ Files: 2                                    │
│ Dependencies: Commit 1 (feat(auth))         │
│ Can execute: āœ… After commit 1              │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Message:
  docs: add OAuth authentication guide

  Add comprehensive documentation for OAuth 2.0
  authentication setup and usage.

Files to stage:
  git add README.md
  git add docs/authentication.md

Command:
  git commit -m "docs: add OAuth authentication guide" -m "Add comprehensive documentation for OAuth 2.0 authentication setup and usage. Includes configuration examples and provider setup."

─────────────────────────────────────────────

Summary:
  Total commits: 3
  Total files: 13
  Execution time: ~3 minutes
  All dependencies resolved: āœ… Yes

Step 5: Generate Script (if output:script)

Create executable bash script:

#!/bin/bash
# Atomic commit sequence
# Generated: 2025-10-13
# Total commits: 3

set -e  # Exit on error

echo "šŸš€ Starting commit sequence..."

# Commit 1: feat(auth)
echo ""
echo "šŸ“ Commit 1/3: feat(auth)"
git add src/auth/oauth.ts
git add src/auth/tokens.ts
git add src/auth/providers/github.ts
git add src/auth/providers/google.ts
git add src/config/oauth.config.ts
git add src/types/auth.types.ts
git add tests/auth/oauth.test.ts
git add tests/auth/tokens.test.ts
git commit -m "feat(auth): implement OAuth 2.0 authentication" -m "Add complete OAuth 2.0 authentication flow with support for multiple providers (GitHub, Google). Includes token management, refresh handling, and comprehensive test coverage."
echo "āœ… Commit 1 complete"

# Commit 2: fix(api)
echo ""
echo "šŸ“ Commit 2/3: fix(api)"
git add src/api/endpoints.ts
git add src/api/validation.ts
git add tests/api.test.ts
git commit -m "fix(api): handle null pointer in user endpoint" -m "Fix null pointer exception when user profile is incomplete. Add validation to check for required fields before access."
echo "āœ… Commit 2 complete"

# Commit 3: docs
echo ""
echo "šŸ“ Commit 3/3: docs"
git add README.md
git add docs/authentication.md
git commit -m "docs: add OAuth authentication guide" -m "Add comprehensive documentation for OAuth 2.0 authentication setup and usage. Includes configuration examples and provider setup."
echo "āœ… Commit 3 complete"

echo ""
echo "šŸŽ‰ All commits completed successfully!"
echo "Total commits: 3"
echo "Total files: 13"

Step 6: Validate Sequence

Check sequence for issues:

  • All files accounted for
  • No file appears in multiple commits
  • Dependencies resolved
  • Logical ordering
  • Commands are valid

Step 7: Provide Execution Options

Offer execution methods:

Option 1: Manual execution Copy-paste commands one by one

Option 2: Script execution Save script and run: bash commit-sequence.sh

Option 3: Interactive Execute with guidance: /atomic-commit interactive

Option 4: Agent execution Let agent execute sequence

Output Format

Return structured sequence:

sequence:
  - commit_id: 1
    order: 1
    type: feat
    scope: auth
    message:
      subject: "Brief description"
      body: "Detailed explanation"
    files: [list]
    dependencies: []
    can_execute: "now|after:<id>"
    commands:
      stage: [git add commands]
      commit: "git commit command"
  - commit_id: 2
    order: 2
    ...
summary:
  total_commits: number
  total_files: number
  estimated_time: "minutes"
  dependencies_resolved: true|false
execution:
  manual: "Copy commands"
  script: "Use generated script"
  interactive: "/atomic-commit interactive"
  agent: "Let agent execute"
script: "Bash script content (if output:script)"

Error Handling

  • No suggestions: "No commit suggestions. Run: /atomic-commit suggest"
  • Circular dependencies: "Cannot resolve: circular dependency detected"
  • Invalid group spec: "Invalid group specification: {spec}"
  • File conflicts: "File appears in multiple commits: {file}"

Dependency Analysis

The dependency checker identifies:

Import dependencies:

  • File A imports from File B
  • B must be committed before A

Test dependencies:

  • Test file tests code file
  • Code must be committed before tests

Logical dependencies:

  • Feature depends on another feature
  • Base feature first, dependent after

Type dependencies:

  • Fixes may depend on features
  • Docs depend on implementations

Execution Planning

Commit Planner Script

The commit planner creates optimal sequence:

def create_sequence(suggestions, dependencies):
    # Build dependency graph
    graph = build_graph(suggestions, dependencies)

    # Topological sort for dependency order
    ordered = topological_sort(graph)

    # Apply type priority within independent groups
    prioritized = apply_type_priority(ordered)

    # Group by scope for related commits
    sequenced = group_by_scope(prioritized)

    return sequenced

Examples

Example 1: Auto-generate plan

/atomic-commit sequence
→ Creates sequence from current suggestions

Example 2: Custom groups

/atomic-commit sequence groups:"feat:5,fix:2,docs:1"
→ Creates sequence for specified groups

Example 3: Generate script

/atomic-commit sequence output:script
→ Outputs executable bash script

Example 4: Auto-stage

/atomic-commit sequence auto_stage:true
→ Automatically stages files during execution

Integration Notes

This operation:

  1. Uses results from suggest-commits
  2. Requires dependency-checker.sh script
  3. Uses commit-planner.py for optimization
  4. Feeds into execution workflows
  5. Can output multiple formats

The sequence ensures atomic commits in optimal order.

Operation: Group Files

Group related files together for atomic commits.

Parameters from $ARGUMENTS

  • strategy:type|scope|feature - Grouping strategy (default: type)
  • show:all|summary - Output detail level (default: summary)

Workflow

Step 1: Get Changed Files

Invoke Bash to get file list:

git status --porcelain
git diff --cached --name-only
git diff --name-only

Capture complete list of changed files.

Step 2: Execute File Grouper

Run the file grouper script with selected strategy:

.claude/plugins/git-commit-assistant/commands/atomic-commit/.scripts/file-grouper.sh <strategy>

Step 3: Parse Grouping Results

Process grouper output based on strategy:

Strategy: type Groups files by commit type:

  • feat: New features or enhancements
  • fix: Bug fixes
  • docs: Documentation changes
  • style: Formatting, whitespace
  • refactor: Code restructuring
  • test: Test additions or changes
  • chore: Build, dependencies, tooling

Strategy: scope Groups files by module/component:

  • Extract scope from file path
  • Group by common directory structure
  • Identify module boundaries
  • Example: auth/, api/, ui/, utils/

Strategy: feature Groups files by related functionality:

  • Analyze dependencies between files
  • Group interdependent changes
  • Identify feature boundaries
  • Requires dependency analysis

Step 4: Validate Groups

Check each group for atomicity:

  • Single logical purpose
  • Reasonable size (≤10 files per group)
  • Clear scope boundary
  • Independent from other groups

Step 5: Generate Output

Create structured grouping report:

Summary format:

šŸ“¦ FILE GROUPS (strategy: type)

Group 1: feat (8 files)
  src/auth/oauth.ts
  src/auth/tokens.ts
  src/config/oauth.config.ts
  ...

Group 2: fix (3 files)
  src/api/endpoints.ts
  src/api/validation.ts
  tests/api.test.ts

Group 3: docs (2 files)
  README.md
  docs/authentication.md

Total: 3 groups, 13 files

Detailed format (show:all):

šŸ“¦ GROUP 1: feat (8 files)

Files:
  āœ“ src/auth/oauth.ts (+145, -0)
  āœ“ src/auth/tokens.ts (+78, -0)
  āœ“ src/auth/providers/github.ts (+95, -0)
  āœ“ src/auth/providers/google.ts (+92, -0)
  āœ“ src/config/oauth.config.ts (+34, -0)
  āœ“ src/types/auth.types.ts (+56, -0)
  āœ“ tests/auth/oauth.test.ts (+123, -0)
  āœ“ tests/auth/tokens.test.ts (+67, -0)

Scope: auth
Purpose: OAuth 2.0 implementation
Dependencies: None
Atomic: āœ… Yes

Suggested commit:
  feat(auth): implement OAuth 2.0 authentication

Output Format

Return structured groupings:

strategy: type|scope|feature
groups:
  - id: 1
    type: feat|fix|docs|etc
    scope: module_name
    files: [list]
    stats:
      file_count: number
      additions: number
      deletions: number
    atomic: true|false
    suggested_message: "commit message"
summary:
  total_groups: number
  total_files: number
  ready_for_commit: true|false

Error Handling

  • No changes: "No files to group. Make changes first."
  • Invalid strategy: "Invalid strategy. Use: type, scope, or feature"
  • Grouping failed: "Could not group files. Check git status."
  • Too many groups: "Warning: 10+ groups detected. Consider broader grouping."

Grouping Strategies Explained

Type-based Grouping

Groups files by conventional commit type. Best for:

  • Mixed-type changes
  • Clear type boundaries
  • Standard workflow

Algorithm:

  1. Analyze diff content for each file
  2. Detect commit type from changes
  3. Group files of same type
  4. Validate each group

Scope-based Grouping

Groups files by module/component. Best for:

  • Changes across multiple modules
  • Modular codebase structure
  • Component isolation

Algorithm:

  1. Extract directory structure
  2. Identify module boundaries
  3. Group files by module
  4. Validate scope coherence

Feature-based Grouping

Groups files by related functionality. Best for:

  • Complex feature implementation
  • Interdependent changes
  • Logical feature units

Algorithm:

  1. Analyze file dependencies
  2. Build dependency graph
  3. Group connected components
  4. Validate feature boundaries

Examples

Example 1: Type grouping

/atomic-commit group strategy:type
→ Groups: feat (5), fix (2), docs (1)

Example 2: Scope grouping

/atomic-commit group strategy:scope show:all
→ Detailed groups by module

Example 3: Feature grouping

/atomic-commit group strategy:feature
→ Groups by related functionality

Integration Notes

This operation is typically called:

  1. After analyze-splitting recommends splitting
  2. Before suggest-commits generates messages
  3. As part of interactive-split workflow

Results feed into commit suggestion and sequence planning.

Operation: Interactive Split

Interactive guided workflow for splitting commits.

Parameters from $ARGUMENTS

  • step:number - Start at specific step (default: 1)
  • auto:true|false - Auto-advance through steps (default: false)

Workflow

This operation provides step-by-step guided experience through the entire atomic commit splitting process.

Step 1: Analyze Current Changes

Display:

šŸ” STEP 1: ANALYZE CHANGES
─────────────────────────────────────

Analyzing your current changes...

Execute:

/atomic-commit analyze verbose:true

Parse results and show:

Current status:
  Files changed: 13
  Types detected: feat, fix, docs
  Scopes detected: auth, api
  Recommendation: Should split

Analysis:
  āš ļø  Multiple types detected (feat, fix, docs)
  āš ļø  Multiple scopes detected (auth, api)
  āœ… File count manageable (13 files)

Recommendation:
  Split into multiple atomic commits for:
  - Easier code review
  - Safer reverts
  - Clearer history

Prompt user:

Options:
  [1] Continue to grouping (recommended)
  [2] Review analysis details
  [3] Exit (keep as one commit)

Your choice:

Step 2: Group Files

Display:

šŸ“¦ STEP 2: GROUP FILES
─────────────────────────────────────

How would you like to group files?

Show grouping strategies:

Strategies:
  [1] By type (feat, fix, docs)
      Best for: Mixed-type changes
      Groups: ~3 groups expected

  [2] By scope (auth, api, docs)
      Best for: Changes across modules
      Groups: ~3 groups expected

  [3] By feature (related functionality)
      Best for: Complex feature work
      Groups: ~2-4 groups expected

  [4] Auto-select (recommended)
      Let me choose the best strategy

Your choice:

Execute grouping:

/atomic-commit group strategy:<selected> show:all

Show results:

Groups created:

šŸ“¦ Group 1: feat(auth) - 8 files
  Purpose: OAuth 2.0 implementation
  Files: src/auth/*, tests/auth/*
  Atomic: āœ… Yes

šŸ“¦ Group 2: fix(api) - 3 files
  Purpose: Null pointer fix
  Files: src/api/*, tests/api/*
  Atomic: āœ… Yes

šŸ“¦ Group 3: docs - 2 files
  Purpose: Authentication guide
  Files: README.md, docs/authentication.md
  Atomic: āœ… Yes

All groups are atomic: āœ… Yes

Prompt user:

Options:
  [1] Continue to commit suggestions
  [2] Adjust grouping
  [3] Try different strategy
  [4] Back to step 1

Your choice:

Step 3: Review Commit Suggestions

Display:

šŸ’¬ STEP 3: COMMIT SUGGESTIONS
─────────────────────────────────────

Generating commit messages...

Execute:

/atomic-commit suggest format:conventional include_body:true

Show suggestions with review interface:

Commit 1 of 3:
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ feat(auth): implement OAuth 2.0 auth        │
│                                             │
│ Add complete OAuth 2.0 authentication flow │
│ with support for multiple providers        │
│ (GitHub, Google). Includes token           │
│ management, refresh handling, and          │
│ comprehensive test coverage.               │
│                                             │
│ Files: 8                                    │
│ Atomic: āœ… Yes                              │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Options for this commit:
  [a] Accept as-is
  [e] Edit message
  [s] Skip this commit
  [v] View files in commit

Your choice:

If user edits, provide interface:

Edit commit message:

Subject (max 50 chars):
> feat(auth): implement OAuth 2.0 authentication

Body (optional):
> Add complete OAuth 2.0 authentication flow with
> support for multiple providers (GitHub, Google).
> Includes token management, refresh handling, and
> comprehensive test coverage.

Footer (optional):
>

[s] Save   [c] Cancel   [r] Reset

After reviewing all commits:

All commits reviewed:
  āœ… Commit 1: feat(auth) - Accepted
  āœ… Commit 2: fix(api) - Edited
  āœ… Commit 3: docs - Accepted

Options:
  [1] Continue to sequence planning
  [2] Review commits again
  [3] Back to grouping

Your choice:

Step 4: Create Commit Sequence

Display:

šŸ“‹ STEP 4: COMMIT SEQUENCE
─────────────────────────────────────

Creating execution plan...

Execute:

/atomic-commit sequence output:plan

Show sequence:

Commit Order:

1ļøāƒ£ feat(auth) - 8 files
   Dependencies: None
   Can commit: āœ… Now

2ļøāƒ£ fix(api) - 3 files
   Dependencies: None
   Can commit: āœ… After commit 1

3ļøāƒ£ docs - 2 files
   Dependencies: Commit 1 (documents auth)
   Can commit: āœ… After commit 1

Execution time: ~3 minutes
All dependencies resolved: āœ… Yes

Prompt user:

Options:
  [1] Show execution commands
  [2] Generate script
  [3] Execute with guidance (recommended)
  [4] Let agent execute
  [5] Back to step 3

Your choice:

Step 5: Execute Commits

If user chooses guided execution:

šŸš€ STEP 5: EXECUTE COMMITS
─────────────────────────────────────

Executing commit 1 of 3...

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ COMMIT 1: feat(auth)                        │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Staging files:
  āœ… src/auth/oauth.ts
  āœ… src/auth/tokens.ts
  āœ… src/auth/providers/github.ts
  āœ… src/auth/providers/google.ts
  āœ… src/config/oauth.config.ts
  āœ… src/types/auth.types.ts
  āœ… tests/auth/oauth.test.ts
  āœ… tests/auth/tokens.test.ts

Creating commit:
  Message: feat(auth): implement OAuth 2.0 authentication
  Files: 8
  Status: āœ… Success

Commit created: a1b2c3d

─────────────────────────────────────────────

Proceed to commit 2?
  [y] Yes, continue
  [r] Review what was just committed
  [p] Pause (save progress)
  [a] Abort remaining commits

Your choice:

Continue through all commits...

Final summary:

✨ COMPLETE: ALL COMMITS CREATED
─────────────────────────────────────

Summary:
  āœ… Commit 1: feat(auth) - a1b2c3d
  āœ… Commit 2: fix(api) - b2c3d4e
  āœ… Commit 3: docs - c3d4e5f

Total commits: 3
Total files: 13
Time elapsed: 2m 45s

Your git history is now atomic! šŸŽ‰

Next steps:
  • Review commits: git log -3
  • Push commits: git push
  • Create PR: gh pr create

Progress Tracking

The interactive workflow maintains state:

session:
  step: 1-5
  completed_steps: [list]
  current_groups: [...]
  current_suggestions: [...]
  current_sequence: [...]
  created_commits: [...]
  can_resume: true|false

Users can:

  • Pause at any step
  • Resume from where they left off
  • Go back to previous steps
  • Skip steps if desired

Navigation Commands

Throughout the interactive workflow:

  • [n] Next
  • [b] Back
  • [h] Help
  • [q] Quit
  • [r] Restart
  • [s] Status

Error Handling

During analysis:

  • No changes detected → Guide to make changes first
  • Git errors → Provide troubleshooting steps

During grouping:

  • Cannot group files → Suggest manual review
  • Grouping unclear → Offer alternative strategies

During suggestions:

  • Cannot generate message → Provide template
  • User unsure → Offer examples and guidance

During execution:

  • Staging fails → Show file status and retry
  • Commit fails → Preserve work, show error
  • Partial completion → Save progress, allow resume

Auto Mode

When auto:true is specified:

  • Automatically selects recommended options
  • Shows results at each step
  • Pauses for user confirmation at commit execution
  • Useful for experienced users who trust recommendations

Example:

/atomic-commit interactive auto:true
→ Analyzes → Groups by best strategy → Suggests → Creates sequence → Waits for confirmation

Resume Capability

If interrupted, users can resume:

/atomic-commit interactive step:3
→ Resumes from step 3 (commit suggestions)

Session data is preserved across invocations.

Help System

At any point, user can type [h] for context-sensitive help:

šŸ“š HELP - Step 2: Grouping
─────────────────────────────────────

Grouping strategies:
  • Type: Groups by commit type (feat, fix, docs)
  • Scope: Groups by module (auth, api, ui)
  • Feature: Groups by related functionality

Tips:
  • Choose "type" for mixed-type changes
  • Choose "scope" for module-based work
  • Choose "feature" for complex features
  • Choose "auto" if unsure

Examples:
  Type grouping: feat files | fix files | docs files
  Scope grouping: auth files | api files | ui files

Press any key to continue...

Output Format

The interactive workflow uses:

  • Clear step indicators
  • Progress tracking
  • Visual separators
  • Emoji for status
  • Color coding (if supported)
  • Consistent option menus
  • Helpful prompts

Examples

Example 1: Full interactive workflow

/atomic-commit interactive
→ Guides through all steps with prompts

Example 2: Auto mode

/atomic-commit interactive auto:true
→ Auto-selects best options, confirms before execution

Example 3: Resume from step

/atomic-commit interactive step:3
→ Resumes from commit suggestions step

Integration with Agent

The commit-assistant agent can:

  1. Recommend interactive mode for complex splits
  2. Guide users through steps
  3. Answer questions during workflow
  4. Explain recommendations
  5. Execute commits on behalf of user (with approval)

The interactive workflow provides the best user experience for learning atomic commit practices.

Atomic Commit Skill

Help users create atomic commits - one logical change per commit.

Available Operations

  • analyze → Determine if changes should be split
  • group → Group related files together
  • suggest → Recommend commit breakdown
  • sequence → Generate commit sequence plan
  • interactive → Interactive splitting guidance

Usage Examples

# Analyze if splitting needed
/atomic-commit analyze

# Group files by type and scope
/atomic-commit group strategy:type

# Suggest commit breakdown
/atomic-commit suggest

# Create commit sequence
/atomic-commit sequence groups:"feat:5,fix:2,docs:1"

# Interactive splitting
/atomic-commit interactive

Atomic Commit Principles

One logical change per commit:

  • āœ… Single type (all feat, or all fix)
  • āœ… Single scope (all auth, or all api)
  • āœ… Reasonable size (≤10 files)
  • āœ… Logically cohesive
  • āœ… Can be reverted independently

Router Logic

Parse $ARGUMENTS to determine operation:

  1. Extract first word as operation name
  2. Parse remaining parameters as key:value pairs
  3. Route to appropriate operation file
  4. Handle errors gracefully

Available operations:

  • analyze → Read commands/atomic-commit/analyze-splitting.md
  • group → Read commands/atomic-commit/group-files.md
  • suggest → Read commands/atomic-commit/suggest-commits.md
  • sequence → Read commands/atomic-commit/create-sequence.md
  • interactive → Read commands/atomic-commit/interactive-split.md

Error Handling:

  • Unknown operation → List available operations with examples
  • No changes detected → Prompt user to make changes first
  • Already atomic → Confirm no split needed

Base directory: commands/atomic-commit/ Current request: $ARGUMENTS

Processing Steps

  1. Parse operation from $ARGUMENTS
  2. Validate operation exists
  3. Extract parameters
  4. Read corresponding operation file
  5. Execute operation with parameters
  6. Return results with actionable guidance

Example Flows

Quick analysis:

/atomic-commit analyze
→ Analyzes current changes
→ Returns split recommendation with reasoning

Interactive workflow:

/atomic-commit interactive
→ Guides step-by-step through splitting
→ Shows groupings, suggests commits, creates plan

Custom grouping:

/atomic-commit group strategy:scope
→ Groups files by module/scope
→ Returns groupings for review

Operation: Suggest Commits

Generate commit message suggestions for file groups.

Parameters from $ARGUMENTS

  • groups:string - Comma-separated group IDs to process (default: all)
  • format:conventional|simple - Message format (default: conventional)
  • include_body:true|false - Include commit body (default: true)

Workflow

Step 1: Get File Groups

If groups not provided, invoke file grouping:

/atomic-commit group strategy:type

Parse grouping results to identify distinct commit groups.

Step 2: Analyze Each Group

For each file group:

  1. Get file diffs
  2. Analyze changes
  3. Identify commit type
  4. Determine scope
  5. Extract key changes

Invoke Bash to get detailed diffs:

git diff --cached <files>
git diff <files>

Step 3: Generate Commit Messages

For each group, create commit message following conventions:

Conventional format:

<type>(<scope>): <subject>

<body>

<footer>

Components:

  • type: feat|fix|docs|style|refactor|test|chore
  • scope: Module or component affected
  • subject: Brief description (≤50 chars)
  • body: Detailed explanation (optional)
  • footer: Breaking changes, issue references (optional)

Example:

feat(auth): implement OAuth 2.0 authentication

Add OAuth 2.0 authentication flow with support for:
- GitHub provider
- Google provider
- Token management
- Refresh token handling

Includes comprehensive test coverage.

Step 4: Validate Messages

Check each message for:

  • Type correctness
  • Scope accuracy
  • Subject clarity
  • Body completeness
  • Footer requirements

Apply commit message best practices:

  • Subject in imperative mood
  • Subject ≤50 characters
  • Body wrapped at 72 characters
  • Clear explanation of "why"
  • Reference related issues

Step 5: Rank Suggestions

Order commits by:

  1. Dependency order: Dependencies first
  2. Type priority: feat → fix → refactor → docs → chore
  3. Scope cohesion: Related scopes together
  4. Logical flow: Natural progression

Step 6: Generate Output

Create comprehensive suggestion report:

šŸ’¬ COMMIT SUGGESTIONS

Commit 1 of 3: feat(auth) - 8 files
─────────────────────────────────────
feat(auth): implement OAuth 2.0 authentication

Add complete OAuth 2.0 authentication flow with
support for multiple providers (GitHub, Google).
Includes token management, refresh handling, and
comprehensive test coverage.

Files:
  • src/auth/oauth.ts
  • src/auth/tokens.ts
  • src/auth/providers/github.ts
  • src/auth/providers/google.ts
  • src/config/oauth.config.ts
  • src/types/auth.types.ts
  • tests/auth/oauth.test.ts
  • tests/auth/tokens.test.ts

Atomic: āœ… Yes
Ready: āœ… Can commit

─────────────────────────────────────

Commit 2 of 3: fix(api) - 3 files
─────────────────────────────────────
fix(api): handle null pointer in user endpoint

Fix null pointer exception when user profile is
incomplete. Add validation to check for required
fields before access.

Files:
  • src/api/endpoints.ts
  • src/api/validation.ts
  • tests/api.test.ts

Atomic: āœ… Yes
Ready: āœ… Can commit

─────────────────────────────────────

Commit 3 of 3: docs - 2 files
─────────────────────────────────────
docs: add OAuth authentication guide

Add comprehensive documentation for OAuth 2.0
authentication setup and usage. Includes
configuration examples and provider setup.

Files:
  • README.md
  • docs/authentication.md

Atomic: āœ… Yes
Ready: āœ… Can commit

─────────────────────────────────────

Summary:
  Total commits: 3
  Total files: 13
  All atomic: āœ… Yes
  Ready to commit: āœ… Yes

Next steps:
  1. Review suggestions above
  2. Run: /atomic-commit sequence (to create plan)
  3. Or manually stage and commit each group

Output Format

Return structured suggestions:

suggestions:
  - commit_id: 1
    type: feat|fix|docs|etc
    scope: module_name
    subject: "Brief description"
    body: "Detailed explanation"
    footer: "Breaking changes, refs"
    files: [list]
    stats:
      file_count: number
      additions: number
      deletions: number
    atomic: true|false
    ready: true|false
    dependencies: [commit_ids]
summary:
  total_commits: number
  total_files: number
  all_atomic: true|false
  ready_to_commit: true|false
next_steps: [ordered actions]

Message Generation Rules

Type Detection

  • feat: New features, capabilities, enhancements
  • fix: Bug fixes, error corrections
  • docs: Documentation only
  • style: Formatting, whitespace, semicolons
  • refactor: Code restructuring without behavior change
  • test: Test additions or modifications
  • chore: Build, dependencies, tooling
  • perf: Performance improvements
  • ci: CI/CD configuration changes

Scope Extraction

  1. Analyze file paths for common prefix
  2. Identify module name from structure
  3. Use meaningful component names
  4. Keep scopes consistent across project

Subject Crafting

  1. Use imperative mood: "add" not "added"
  2. No capitalization of first letter
  3. No period at the end
  4. Be specific but concise
  5. Maximum 50 characters

Body Creation

  1. Explain "why" not "what"
  2. Provide context for changes
  3. Wrap at 72 characters
  4. Use bullet points for lists
  5. Include relevant details

Footer Guidelines

  • Breaking changes: Start with "BREAKING CHANGE:"
  • Issue references: "Fixes #123", "Closes #456"
  • Related issues: "Related to #789"

Error Handling

  • No groups: "No file groups found. Run: /atomic-commit group"
  • Invalid group: "Group ID not found: {id}"
  • Cannot analyze: "Failed to analyze changes for group {id}"
  • Message generation failed: "Could not generate message. Check diffs."

Examples

Example 1: All groups

/atomic-commit suggest
→ Suggests commits for all detected groups

Example 2: Specific groups

/atomic-commit suggest groups:"1,3"
→ Suggests commits only for groups 1 and 3

Example 3: Simple format

/atomic-commit suggest format:simple include_body:false
→ Simple messages without detailed bodies

Integration Notes

This operation:

  1. Uses results from group-files
  2. Feeds into create-sequence
  3. Is part of interactive-split workflow
  4. Can be used standalone for quick suggestions

Suggestions are not final - user can review and modify before committing.

Operation: Analyze Changes

Perform full analysis of git repository changes to understand the nature, scope, commit type, and whether changes are atomic.

Parameters from $ARGUMENTS

No parameters required. Analyzes all current changes.

Workflow

Step 1: Verify Git Repository

git rev-parse --git-dir 2>/dev/null

If this fails:

  • Return error: "Not a git repository. Run 'git init' to initialize."
  • Exit operation

Step 2: Check for Changes

git status --short

If no changes:

  • Return: "No changes to analyze. Working tree is clean."
  • Exit operation

Step 3: Gather Change Information

Run git commands to collect comprehensive data:

# Get detailed diff
git diff HEAD

# Get status summary
git status --short

# Get diff statistics
git diff --stat HEAD

# Count changed files
git status --short | wc -l

Step 4: Invoke Analysis Scripts

Execute utility scripts to analyze different aspects:

Type Detection:

# Run type detector script
.scripts/type-detector.py

This script analyzes the diff output and returns the primary commit type (feat, fix, docs, etc.)

Scope Identification:

# Run scope identifier
.scripts/scope-identifier.sh

This script identifies the primary module/component affected

Atomicity Assessment:

# Run atomicity checker
.scripts/atomicity-checker.py

This script determines if changes should be split into multiple commits

Diff Analysis:

# Run git diff analyzer
.scripts/git-diff-analyzer.sh

This script parses diff output for detailed file and line change information

Step 5: Compile Analysis Report

Format comprehensive analysis:

COMMIT ANALYSIS REPORT
═══════════════════════════════════════════════

CHANGE SUMMARY:
───────────────────────────────────────────────
Files Changed: X files
Insertions: +XXX lines
Deletions: -XXX lines
Net Change: ±XXX lines

COMMIT TYPE DETECTION:
───────────────────────────────────────────────
Primary Type: <feat|fix|docs|refactor|style|test|chore|perf|ci>
Confidence: <High|Medium|Low>
Reasoning: <explanation of why this type was chosen>

Alternative Types: <if applicable>

SCOPE IDENTIFICATION:
───────────────────────────────────────────────
Primary Scope: <module/component name>
Affected Areas: <list of all affected areas>
Scope Confidence: <High|Medium|Low>

ATOMICITY ASSESSMENT:
───────────────────────────────────────────────
Status: <Atomic|Should Split>
Reasoning: <explanation>

If Should Split:
  Recommended Splits:
    1. <type>(<scope>): <description> - X files
    2. <type>(<scope>): <description> - X files
    ...

FILE BREAKDOWN:
───────────────────────────────────────────────
<list files grouped by type/scope>

New Files: <count>
  - <file1>
  - <file2>

Modified Files: <count>
  - <file1> (+XX -YY)
  - <file2> (+XX -YY)

Deleted Files: <count>
  - <file1>

RECOMMENDATIONS:
───────────────────────────────────────────────
- <recommendation 1>
- <recommendation 2>
- <recommendation 3>

═══════════════════════════════════════════════

Output Format

Return structured analysis with:

  • Change statistics
  • Detected commit type with confidence level
  • Identified scope
  • Atomicity assessment
  • File breakdown
  • Specific recommendations

Error Handling

Not a git repository:

ERROR: Not a git repository
Initialize with: git init

No changes to analyze:

NO CHANGES
Working tree is clean. Make changes before analyzing.

Git command fails:

ERROR: Git command failed
<error message>
Ensure git is properly configured.

Integration with Agent

The commit-assistant agent uses this operation to:

  1. Understand change nature before suggesting commits
  2. Determine if changes are atomic or need splitting
  3. Identify appropriate commit type and scope
  4. Provide context for message generation

Usage Example

# Agent workflow:
# User: "analyze my changes"
# Agent invokes: analyze-changes operation
# Operation returns comprehensive report
# Agent presents findings to user

Operation: Assess Atomicity

Determine if changes form an atomic commit (single logical change) or should be split into multiple focused commits.

Parameters from $ARGUMENTS

No parameters required. Analyzes all current changes.

Workflow

Step 1: Gather Change Data

git status --short
git diff HEAD --stat
git diff HEAD

Step 2: Run Atomicity Analysis

Execute atomicity checker script:

git diff HEAD | .scripts/atomicity-checker.py

The script analyzes:

  • Number of files changed
  • Types of changes (feat, fix, docs, etc.)
  • Scopes affected
  • Interdependencies
  • Logical cohesion

Step 3: Atomicity Criteria

Atomic Commit (single commit appropriate):

  • All changes serve ONE logical purpose
  • All files relate to the same feature/fix
  • Changes are interdependent
  • Same type throughout (all feat, or all fix)
  • Same scope throughout (all auth, or all api)
  • Can be reverted as a complete unit
  • Tests pass after commit

Non-Atomic (should split):

  • Multiple distinct types (feat + fix + docs)
  • Multiple unrelated scopes (auth + api + ui)
  • Mixing concerns (feature + refactoring + bug fix)
  • Too many files (10+ unrelated files)
  • Multiple stories being told

Step 4: Splitting Recommendations

If non-atomic, suggest how to split:

By Type:

Split into commits by change type:
  1. feat(auth): OAuth implementation (5 files)
  2. test(auth): OAuth tests (2 files)
  3. docs: authentication guide (1 file)

By Scope:

Split into commits by module:
  1. feat(auth): authentication system (6 files)
  2. feat(api): user API endpoints (4 files)
  3. feat(ui): login components (3 files)

By Feature:

Split into commits by logical unit:
  1. feat(payments): Stripe integration (8 files)
  2. feat(payments): PayPal integration (6 files)
  3. test(payments): payment tests (4 files)

Step 5: Format Atomicity Assessment

ATOMICITY ASSESSMENT
═══════════════════════════════════════════════

STATUS: <ATOMIC | SHOULD SPLIT>

ANALYSIS:
───────────────────────────────────────────────
Files Changed: X
Lines Changed: +XXX -XXX

Type Diversity: <Single | Multiple>
Scope Diversity: <Single | Multiple>
Logical Cohesion: <High | Medium | Low>

ATOMICITY CHECKS:
───────────────────────────────────────────────
āœ“ Single logical purpose
āœ“ Related files only
āœ“ Same change type
āœ“ Same scope
āœ“ Interdependent changes
āœ“ Complete unit
āœ“ Can be reverted independently

OR

āœ— Multiple purposes detected
āœ— Unrelated files mixed
āœ— Multiple change types
āœ— Multiple scopes
āœ— Independent changes
āœ— Incomplete without splits

REASONING:
───────────────────────────────────────────────
<detailed explanation>

If ATOMIC:
  All changes implement [specific feature/fix].
  Files work together and depend on each other.
  Single commit tells a clear, focused story.

If SHOULD SPLIT:
  Changes address multiple concerns:
    1. <concern 1>
    2. <concern 2>
    3. <concern 3>

  Each concern should be a separate commit.

SPLITTING RECOMMENDATIONS:
───────────────────────────────────────────────
<if should split>

Recommended Commits:

Commit 1: <type>(<scope>): <description>
  Files: X files
  Purpose: <specific purpose>
  Files:
    - file1.js
    - file2.js
  Lines: +XX -YY

Commit 2: <type>(<scope>): <description>
  Files: X files
  Purpose: <specific purpose>
  Files:
    - file3.js
    - file4.js
  Lines: +XX -YY

BENEFITS OF SPLITTING:
───────────────────────────────────────────────
<if should split>
- Better code review (focused changes)
- Easier to revert individual features
- Clearer git history
- Better bisecting for bugs
- Easier cherry-picking

RECOMMENDATION:
───────────────────────────────────────────────
<specific actionable recommendation>

═══════════════════════════════════════════════

Detailed Atomicity Rules

Rule 1: Single Purpose Test

Question: Can you describe ALL changes in one sentence?

Atomic Examples:

  • "Add OAuth authentication"
  • "Fix null pointer in user endpoint"
  • "Refactor date utility functions"

Non-Atomic Examples:

  • "Add OAuth and fix login bug and update README"
  • "Implement payment and refactor utils and add tests"

Rule 2: Type Consistency

Atomic:

  • All files are "feat" type
  • All files are "fix" type
  • All files are "refactor" type

Non-Atomic:

  • Mix of feat + fix
  • Mix of refactor + feat
  • Mix of docs + code changes (exception: docs can accompany code)

Rule 3: Scope Consistency

Atomic:

  • All changes in "auth" module
  • All changes in "api" module
  • All changes in "ui/components"

Non-Atomic:

  • Changes in auth + api + ui
  • Changes in multiple unrelated modules

Rule 4: Revert Independence

Test: If reverted, does it break unrelated functionality?

Atomic:

  • Can be reverted without breaking other features
  • Forms a complete, self-contained unit

Non-Atomic:

  • Reverting breaks unrelated features
  • Mixes independent changes

Rule 5: Review Simplicity

Atomic:

  • Reviewer can focus on one logical change
  • Clear what and why
  • Single story

Non-Atomic:

  • Reviewer must context-switch between multiple concerns
  • Multiple stories mixed together

File Count Guidelines

Generally Atomic:

  • 1-5 files: Usually focused
  • 5-10 files: Check cohesion carefully
  • 10-15 files: Likely needs splitting unless tightly coupled

Usually Non-Atomic:

  • 15+ files: Almost always should split
  • 20+ files: Definitely split

Exceptions:

  • Large refactoring may touch many files atomically
  • Package updates may affect many files atomically
  • Renaming across project may touch many files atomically

Edge Cases

Case 1: Feature + Tests

Atomic? Usually YES

  • Tests directly validate the feature code
  • They tell the same story
  • Can be reverted together

Example:

feat(auth): implement OAuth authentication
- 5 implementation files
- 2 test files
→ ATOMIC (7 files, same feature)

Case 2: Feature + Documentation

Atomic? DEPENDS

  • If docs describe the feature: YES
  • If docs are unrelated updates: NO

Example:

feat(auth): add OAuth support
- 5 auth files
- 1 auth documentation file
→ ATOMIC (documents the feature)

vs.

feat(auth): add OAuth support
- 5 auth files
- README general update
→ NON-ATOMIC (split docs)

Case 3: Refactoring + New Feature

Atomic? NO

  • Refactoring should be separate
  • Makes review harder
  • Mixing concerns

Example:

Changes:
- Refactor utils (3 files)
- Add new payment feature (5 files)
→ NON-ATOMIC

Split:
1. refactor(utils): simplify utility functions
2. feat(payments): add Stripe integration

Case 4: Multiple Small Fixes

Atomic? DEPENDS

  • If all in same module: MAYBE
  • If unrelated: NO

Example:

fix(auth): resolve three auth-related bugs
- All in auth module
- All are fixes
- Related to each other
→ ATOMIC

vs.

- Fix auth bug
- Fix API bug
- Fix UI bug
→ NON-ATOMIC (different scopes)

Output Format

Return:

  • Atomicity status (ATOMIC or SHOULD SPLIT)
  • Detailed analysis and reasoning
  • Atomicity checks (passed/failed)
  • Splitting recommendations if needed
  • Benefits explanation
  • Specific recommendation

Error Handling

No changes:

NO CHANGES TO ASSESS
Working tree is clean.

Single file change:

ATOMIC (Single File)
One file changed: <filename>
Automatically atomic.

Integration with Agent

The commit-assistant agent uses this operation to:

  1. Determine if /commit or /commit-split should be used
  2. Warn users about non-atomic changes
  3. Provide splitting guidance
  4. Educate users on atomic commit benefits

Usage Example

# Agent checks atomicity before committing
# User: "commit my changes"
# Agent: Invokes assess-atomicity
# Operation: Returns "SHOULD SPLIT"
# Agent: "Your changes should be split. Run /commit-review"

Operation: Detect Commit Type

Analyze git changes to determine the conventional commit type (feat, fix, docs, refactor, style, test, chore, perf, ci).

Parameters from $ARGUMENTS

No parameters required. Analyzes current git diff.

Workflow

Step 1: Verify Git Repository and Changes

git rev-parse --git-dir 2>/dev/null
git diff HEAD

If no repository or no changes, exit with appropriate message.

Step 2: Run Type Detection Algorithm

Execute the type detector script with git diff output:

git diff HEAD | .scripts/type-detector.py

The script implements the decision tree algorithm:

Detection Algorithm (Implemented in type-detector.py)

Priority Order (check in sequence):

1. Check for new files or new exports
   → IF new files OR new functions/classes/exports
   → RETURN "feat"

2. Check for bug fixes
   → IF error handling OR bug keywords (fix, resolve, correct)
   → RETURN "fix"

3. Check for docs-only changes
   → IF only .md files OR only comments changed
   → RETURN "docs"

4. Check for code restructuring
   → IF code moved/renamed but no behavior change
   → RETURN "refactor"

5. Check for style changes
   → IF only whitespace OR formatting changed
   → RETURN "style"

6. Check for test changes
   → IF only test files changed
   → RETURN "test"

7. Check for dependency changes
   → IF package.json OR build files changed
   → RETURN "build"

8. Check for CI changes
   → IF .github/workflows OR CI configs changed
   → RETURN "ci"

9. Check for performance improvements
   → IF optimization keywords OR caching added
   → RETURN "perf"

10. Default
    → RETURN "chore"

Step 3: Analyze Confidence Level

Determine confidence in the detected type:

High Confidence:

  • Only one type detected
  • Clear indicators present
  • No ambiguity

Medium Confidence:

  • Multiple possible types
  • Mixed indicators
  • Requires human judgment

Low Confidence:

  • Unclear changes
  • Multiple types with equal weight
  • Recommend manual review

Step 4: Identify Alternative Types

If changes could fit multiple types, list alternatives:

Primary: feat (High confidence)
Alternatives:
  - test (if test files are significant)
  - docs (if documentation is substantial)

Step 5: Format Detection Result

Return structured type detection:

COMMIT TYPE DETECTION
═══════════════════════════════════════════════

DETECTED TYPE: <type>
CONFIDENCE: <High|Medium|Low>

REASONING:
───────────────────────────────────────────────
<detailed explanation of why this type was chosen>

Key Indicators:
- <indicator 1>
- <indicator 2>
- <indicator 3>

FILE ANALYSIS:
───────────────────────────────────────────────
New Files: X (suggests feat)
Bug Fixes: X (suggests fix)
Documentation: X (suggests docs)
Refactoring: X (suggests refactor)
Formatting: X (suggests style)
Tests: X (suggests test)
Dependencies: X (suggests build/chore)
CI/CD: X (suggests ci)

ALTERNATIVE TYPES:
───────────────────────────────────────────────
<if applicable>
- <type>: <reasoning>

RECOMMENDATION:
───────────────────────────────────────────────
<specific recommendation based on analysis>

═══════════════════════════════════════════════

Type Detection Rules

feat (Feature)

Indicators:

  • New files created
  • New functions/classes exported
  • New functionality added
  • New components/modules
  • Keywords: "add", "implement", "introduce", "create"

Example Patterns:

+export function newFeature() {
+export class NewComponent {
+++ new-file.js

fix (Bug Fix)

Indicators:

  • Error handling added
  • Null/undefined checks
  • Validation corrections
  • Bug keywords in code
  • Keywords: "fix", "resolve", "correct", "handle"

Example Patterns:

+if (!value) throw new Error
+try { ... } catch
-return null
+return value || default

docs (Documentation)

Indicators:

  • Only .md files changed
  • Only comments changed
  • JSDoc additions
  • README updates
  • No code logic changes

Example Patterns:

+++ README.md
+// This function does...
+/** @param {string} name */

refactor (Code Restructuring)

Indicators:

  • Code moved/reorganized
  • Variables/functions renamed
  • Logic extracted
  • No behavior change
  • Keywords: "extract", "rename", "simplify", "reorganize"

Example Patterns:

-function oldName() {
+function newName() {
-inline code block
+extractedFunction()

style (Formatting)

Indicators:

  • Only whitespace changes
  • Indentation fixes
  • Semicolon additions/removals
  • Code formatting
  • No logic changes

Example Patterns:

-  const x = 1
+    const x = 1;
-function(a,b) {
+function(a, b) {

test (Tests)

Indicators:

  • Only test files changed (.test.js, .spec.js, _test.py)
  • Test additions/updates
  • Mock/fixture changes
  • Keywords: "describe", "it", "test", "expect"

Example Patterns:

+++ tests/feature.test.js
+describe('Feature', () => {
+it('should work', () => {

build (Build System)

Indicators:

  • package.json changes
  • Dependency updates
  • Build configuration
  • Build scripts

Example Patterns:

+++ package.json
+"dependencies": {
+  "new-lib": "^1.0.0"

ci (CI/CD)

Indicators:

  • .github/workflows changes
  • .gitlab-ci.yml changes
  • CI configuration
  • Deployment scripts

Example Patterns:

+++ .github/workflows/test.yml
+++ .gitlab-ci.yml

perf (Performance)

Indicators:

  • Optimization changes
  • Caching implementation
  • Algorithm improvements
  • Keywords: "optimize", "cache", "performance", "faster"

Example Patterns:

+const cache = new Map()
+if (cache.has(key)) return cache.get(key)
-O(n²) algorithm
+O(n log n) algorithm

chore (Other)

Indicators:

  • Maintenance tasks
  • Tooling configuration
  • Repository housekeeping
  • Doesn't fit other types

Output Format

Return:

  • Detected type
  • Confidence level
  • Detailed reasoning
  • Key indicators found
  • Alternative types (if any)
  • Specific recommendation

Error Handling

No changes:

NO CHANGES TO ANALYZE
Working tree is clean.

Ambiguous changes:

AMBIGUOUS TYPE DETECTION
Multiple types detected with equal weight.
Manual review recommended.

Detected types:
- feat (40%)
- refactor (35%)
- test (25%)

Integration with Agent

The commit-assistant agent uses this operation to:

  1. Automatically determine commit type
  2. Validate user-provided types
  3. Suggest alternative types if ambiguous
  4. Guide users in type selection

Usage Example

# Agent detects type before generating message
# User: "commit these changes"
# Agent: Invokes detect-type
# Operation: Returns "feat" with high confidence
# Agent: Generates message with "feat" type

Operation: File Statistics

Retrieve detailed statistics about file changes including counts, line changes, and file types.

Parameters from $ARGUMENTS

Optional parameters:

  • format:json|text - Output format (default: text)
  • detailed:true|false - Include per-file breakdown (default: false)

Workflow

Step 1: Verify Repository

git rev-parse --git-dir 2>/dev/null

Step 2: Collect File Statistics

# Get file status
git status --short

# Get statistics
git diff --stat HEAD

# Get detailed stats per file
git diff --numstat HEAD

# Count file types
git diff --name-only HEAD | wc -l

Step 3: Categorize Files

Group files by status and type:

By Status:

  • New files (A)
  • Modified files (M)
  • Deleted files (D)
  • Renamed files (R)

By Type:

  • Source code (.js, .ts, .py, .java, etc.)
  • Tests (.test.js, .spec.ts, _test.py, etc.)
  • Documentation (.md, .txt)
  • Configuration (.json, .yml, .toml, .config.js)
  • Styles (.css, .scss, .less)

Step 4: Calculate Metrics

METRICS:
- Total files changed
- Total insertions (lines added)
- Total deletions (lines removed)
- Net change (insertions - deletions)
- Largest files (by lines changed)
- Files by type distribution
- New vs Modified vs Deleted ratio

Step 5: Format Statistics Report

Text Format (default):

FILE STATISTICS
═══════════════════════════════════════════════

OVERVIEW:
───────────────────────────────────────────────
Total Files: X
Insertions: +XXX lines
Deletions: -XXX lines
Net Change: ±XXX lines

STATUS BREAKDOWN:
───────────────────────────────────────────────
New Files: X
Modified Files: X
Deleted Files: X
Renamed Files: X

FILE TYPE BREAKDOWN:
───────────────────────────────────────────────
Source Code: X files (+XXX -XXX lines)
Tests: X files (+XXX -XXX lines)
Documentation: X files (+XXX -XXX lines)
Configuration: X files (+XXX -XXX lines)
Styles: X files (+XXX -XXX lines)
Other: X files (+XXX -XXX lines)

TOP CHANGED FILES:
───────────────────────────────────────────────
1. <filename> (+XXX -XXX) = XXX lines
2. <filename> (+XXX -XXX) = XXX lines
3. <filename> (+XXX -XXX) = XXX lines
4. <filename> (+XXX -XXX) = XXX lines
5. <filename> (+XXX -XXX) = XXX lines

<if detailed:true>
PER-FILE BREAKDOWN:
───────────────────────────────────────────────
<status> <filename>
  Insertions: +XXX
  Deletions: -XXX
  Net: ±XXX

<status> <filename>
  Insertions: +XXX
  Deletions: -XXX
  Net: ±XXX

═══════════════════════════════════════════════

JSON Format (if format:json):

{
  "overview": {
    "total_files": X,
    "insertions": XXX,
    "deletions": XXX,
    "net_change": XXX
  },
  "status_breakdown": {
    "new": X,
    "modified": X,
    "deleted": X,
    "renamed": X
  },
  "type_breakdown": {
    "source": {
      "count": X,
      "insertions": XXX,
      "deletions": XXX
    },
    "tests": {
      "count": X,
      "insertions": XXX,
      "deletions": XXX
    },
    "docs": {
      "count": X,
      "insertions": XXX,
      "deletions": XXX
    },
    "config": {
      "count": X,
      "insertions": XXX,
      "deletions": XXX
    }
  },
  "top_files": [
    {
      "path": "<filename>",
      "insertions": XXX,
      "deletions": XXX,
      "net": XXX
    }
  ],
  "files": [
    {
      "path": "<filename>",
      "status": "<status>",
      "insertions": XXX,
      "deletions": XXX,
      "net": XXX,
      "type": "<file-type>"
    }
  ]
}

File Type Detection

Source Code:

.js, .jsx, .ts, .tsx (JavaScript/TypeScript)
.py (Python)
.java (Java)
.go (Go)
.rs (Rust)
.rb (Ruby)
.php (PHP)
.c, .cpp, .h (C/C++)
.swift (Swift)
.kt (Kotlin)

Tests:

.test.js, .spec.js
.test.ts, .spec.ts
_test.py, test_*.py
.test.jsx, .spec.tsx

Documentation:

.md (Markdown)
.txt (Text)
.rst (reStructuredText)
.adoc (AsciiDoc)

Configuration:

.json, .yml, .yaml, .toml
.config.js, .config.ts
.env, .env.*
.editorconfig, .gitignore
package.json, tsconfig.json

Styles:

.css, .scss, .sass, .less

Statistical Insights

Provide insights based on stats:

Large Changes:

INSIGHT: Large change detected
You've changed 500+ lines across 15 files.
Consider splitting into smaller commits.

Many New Files:

INSIGHT: Many new files added
8 new files suggest a new feature (feat).

Deletion Heavy:

INSIGHT: More deletions than insertions
Significant code removal suggests refactoring or cleanup.

Test Heavy:

INSIGHT: High test coverage
40% of changes are in test files.
Good practice to include tests with features.

Documentation Heavy:

INSIGHT: Documentation focused
60% of changes are documentation.
Consider "docs" commit type.

Usage Examples

Basic stats:

/commit-analysis file-stats

JSON output:

/commit-analysis file-stats format:json

Detailed breakdown:

/commit-analysis file-stats detailed:true

JSON with details:

/commit-analysis file-stats format:json detailed:true

Output Format

Return:

  • Overview statistics
  • Status breakdown
  • File type breakdown
  • Top changed files
  • Per-file details (if detailed:true)
  • Statistical insights
  • Format as specified (text or JSON)

Error Handling

No changes:

NO CHANGES
Working tree is clean. No statistics to display.

Invalid format parameter:

ERROR: Invalid format
Valid formats: text, json

Integration with Agent

The commit-assistant agent uses this operation to:

  1. Understand change magnitude
  2. Identify dominant change types
  3. Provide context for commit decisions
  4. Generate statistics for reports

Usage Example

# Agent gathers stats before analysis
# User: "how big are my changes?"
# Agent: Invokes file-stats
# Operation: Returns comprehensive statistics
# Agent: "You've changed 15 files with 500+ lines"

Operation: Identify Scope

Analyze git changes to determine the appropriate scope (module/component/area) for the conventional commit message.

Parameters from $ARGUMENTS

No parameters required. Analyzes current changes.

Workflow

Step 1: Verify Repository and Changes

git rev-parse --git-dir 2>/dev/null
git status --short

Step 2: Analyze File Paths

Execute scope identifier script:

git diff HEAD --name-only | .scripts/scope-identifier.sh

The script analyzes file paths to identify affected modules.

Step 3: Scope Detection Algorithm

Directory-Based Scope:

src/auth/*           → scope: auth
src/api/*            → scope: api
src/components/*     → scope: components (or specific component)
src/utils/*          → scope: utils
src/database/*       → scope: database
tests/*              → scope: test (or module being tested)
docs/*               → scope: docs

Component-Based Scope:

src/components/LoginForm.js  → scope: login-form
src/components/UserProfile/* → scope: user-profile
src/api/users.js             → scope: users or user-api
src/auth/oauth.js            → scope: oauth or auth

Multiple Scopes: If multiple distinct scopes:

Primary: auth (5 files)
Secondary: api (2 files)
Recommendation: Split into separate commits or use broader scope

Step 4: Determine Scope Specificity

Specific Scope (preferred):

  • Targets single module/component
  • Example: "auth", "user-profile", "payment-api"

Broad Scope:

  • Multiple modules affected
  • Example: "api", "components", "core"

No Scope (optional):

  • Changes are too diverse
  • Use no scope in message

Step 5: Format Scope Report

SCOPE IDENTIFICATION
═══════════════════════════════════════════════

PRIMARY SCOPE: <scope-name>
CONFIDENCE: <High|Medium|Low>

REASONING:
───────────────────────────────────────────────
<explanation of scope selection>

AFFECTED AREAS:
───────────────────────────────────────────────
<scope>: X files
  - path/to/file1.js
  - path/to/file2.js

<other-scope>: X files (if applicable)
  - path/to/file3.js

FILE PATH ANALYSIS:
───────────────────────────────────────────────
src/auth/*: 5 files → scope: auth
src/api/*: 2 files → scope: api
tests/*: 3 files → scope based on tested module

RECOMMENDATION:
───────────────────────────────────────────────
Use scope: "<recommended-scope>"

Alternative: <if multiple scopes>
  - Split into commits: auth (5 files), api (2 files)
  - Use broader scope: "backend"
  - Use no scope (if too diverse)

═══════════════════════════════════════════════

Scope Naming Conventions

Format:

  • Lowercase
  • Hyphen-separated (kebab-case)
  • Concise (1-3 words)
  • Specific but not too granular

Good Examples:

auth
user-api
login-form
payment-processing
database
ci-pipeline
docs

Bad Examples:

src/auth/oauth  (too specific, includes path)
Authentication  (not lowercase)
user_api        (use hyphens, not underscores)
the-entire-authentication-module-system  (too long)

Common Scopes by Project Type

Web Application:

auth, api, components, ui, pages, routing, state, utils, config, hooks

Backend API:

api, auth, database, middleware, routes, controllers, services, models, validation

Library/Package:

core, utils, types, cli, docs, build, test

Full Stack:

frontend, backend, api, database, auth, ci, docs

Multiple Scope Handling

Case 1: Closely Related Scopes

Changes in: auth/oauth.js, auth/providers.js, auth/middleware.js
Recommendation: scope: "auth"

Case 2: Distinct Scopes

Changes in: auth/* (5 files), api/* (3 files)
Recommendation: Split commits
  - Commit 1: feat(auth): implement OAuth
  - Commit 2: feat(api): add user endpoints

Case 3: Very Broad Changes

Changes in: 15 different directories
Recommendation: Use broad scope or no scope
  - feat(core): major refactoring
  - feat: implement new architecture

Output Format

Return:

  • Primary scope name
  • Confidence level
  • Reasoning for scope selection
  • List of affected areas
  • Alternative recommendations if applicable

Error Handling

No changes:

NO CHANGES
Cannot identify scope from empty diff.

Unclear scope:

SCOPE UNCLEAR
Changes span multiple unrelated areas.
Recommendations:
  - Split into focused commits
  - Use broader scope like "core" or "backend"
  - Use no scope

Integration with Agent

The commit-assistant agent uses this operation to:

  1. Determine scope for commit messages
  2. Validate user-provided scopes
  3. Suggest scope splitting if needed
  4. Guide users in scope selection

Usage Example

# Agent identifies scope automatically
# User: "commit my auth changes"
# Agent: Invokes identify-scope
# Operation: Returns "auth" with high confidence
# Agent: Uses in message "feat(auth): ..."

Commit Analysis Skill - Change Analysis and Type Detection

Intelligent analysis of git changes to determine commit type, scope, and atomicity for semantic commit message generation.

Operations

  • analyze - Full analysis (type, scope, atomicity)
  • detect-type - Determine commit type (feat, fix, docs, etc.)
  • identify-scope - Identify affected module/component
  • assess-atomicity - Check if changes should be split
  • file-stats - Get file change statistics

Router Logic

Parse $ARGUMENTS to determine which operation to perform:

  1. Extract operation from first word of $ARGUMENTS

  2. Extract remaining arguments as operation parameters

  3. Route to appropriate instruction file:

    • "analyze" → Read /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-analysis/analyze-changes.md
    • "detect-type" → Read /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-analysis/detect-type.md
    • "identify-scope" → Read /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-analysis/identify-scope.md
    • "assess-atomicity" → Read /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-analysis/assess-atomicity.md
    • "file-stats" → Read /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-analysis/file-stats.md
  4. Execute instructions with parameters

  5. Return structured analysis results

Error Handling

  • If operation is unknown, list available operations
  • If parameters are missing, show required format
  • If not a git repository, return clear error message
  • If no changes to analyze, inform user

Usage Examples

# Full analysis of current changes
/commit-analysis analyze

# Detect commit type only
/commit-analysis detect-type

# Identify affected scope
/commit-analysis identify-scope

# Check if changes should be split
/commit-analysis assess-atomicity

# Get file statistics
/commit-analysis file-stats

Base directory: /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-analysis

Current request: $ARGUMENTS

Parse operation and route to appropriate instruction file.

Commit Best Practices Skill - Usage Examples

Quick Reference

# Pre-commit validation (full)
/commit-best-practices check-pre-commit

# Pre-commit validation (quick - skip tests/lint)
/commit-best-practices check-pre-commit quick:true

# Review last commit
/commit-best-practices review-commit

# Review specific commit
/commit-best-practices review-commit commit:abc123

# Check if safe to amend
/commit-best-practices amend-guidance

# Amend with force (bypass safety)
/commit-best-practices amend-guidance force:true

# Revert guidance for commit
/commit-best-practices revert-guidance commit:abc123

# Workflow tips (all)
/commit-best-practices workflow-tips

# Workflow tips (specific focus)
/commit-best-practices workflow-tips focus:commit
/commit-best-practices workflow-tips focus:branch
/commit-best-practices workflow-tips focus:merge

Workflow Example 1: Safe Commit Flow

Developer: "I want to commit my changes"

Agent:
  1. Runs: /commit-best-practices check-pre-commit
  2. IF checks fail:
     - Shows: "Tests failing, debug code found"
     - Blocks commit
     - Provides guidance to fix
  3. IF checks pass:
     - Continues with commit workflow
     - Generates message
     - Creates commit
     - Reviews commit quality

Workflow Example 2: Amend Safety Check

Developer: "I need to amend my last commit"

Agent:
  1. Runs: /commit-best-practices amend-guidance
  2. Checks:
     - Not pushed to remote? āœ“
     - Same author? āœ“
     - Not on main/master? āœ“
  3. Result: SAFE - provides amend instructions
  
  OR if unsafe:
  
  3. Result: UNSAFE - commit already pushed
     - Shows alternatives (new commit, revert)
     - Blocks amend

Workflow Example 3: Commit Review & Improvement

Developer commits code

Agent (automatically):
  1. Runs: /commit-best-practices review-commit
  2. Analyzes:
     - Message quality: GOOD
     - Atomicity: āœ“ single feature
     - Tests: ⚠ missing
     - Score: 72/100
  3. Suggests:
     - "Good commit! Consider adding unit tests."
     - "Safe to push with minor note."

Script Output Examples

pre-commit-check.sh

{
  "status": "fail",
  "quick_mode": false,
  "checks": {
    "tests": {"status": "fail", "message": "Tests failing"},
    "lint": {"status": "pass", "message": "Linting passed"},
    "debug_code": {"status": "fail", "count": 3, "locations": ["src/auth.js:42: console.log(user)"]},
    "todos": {"status": "warn", "count": 1, "locations": ["src/auth.js:56: TODO: refactor"]},
    "merge_markers": {"status": "pass", "count": 0, "locations": []}
  }
}

commit-reviewer.py

{
  "commit": "abc123",
  "author": "John Doe <john@example.com>",
  "date": "2025-10-13",
  "message": {
    "subject": "feat(auth): add OAuth authentication",
    "subject_length": 38,
    "conventional": true,
    "type": "feat",
    "scope": "auth"
  },
  "changes": {
    "files_changed": 5,
    "insertions": 234,
    "deletions": 12,
    "test_files": 1
  },
  "quality": {
    "atomic": true,
    "message_quality": "excellent",
    "test_coverage": true,
    "issues": []
  },
  "score": 95
}

amend-safety.sh

{
  "safe": true,
  "recommendation": "safe",
  "commit": "abc123",
  "author": "John Doe <john@example.com>",
  "branch": "feature/oauth",
  "checks": {
    "not_pushed": {"status": "pass", "message": "Commit not pushed to origin/feature/oauth"},
    "same_author": {"status": "pass", "message": "You are the commit author"},
    "safe_branch": {"status": "pass", "message": "On feature branch: feature/oauth"},
    "collaborators": {"status": "pass", "message": "Solo work on branch"}
  }
}

revert-helper.sh

{
  "commit": "abc123",
  "original_message": "feat(auth): add OAuth authentication",
  "type": "feat",
  "scope": "auth",
  "files_affected": 5,
  "revert_message": "revert: feat(auth): add OAuth authentication\n\nThis reverts commit abc123.\n\nReason: [Provide reason here]",
  "safety": {
    "safe_to_revert": true,
    "warnings": [],
    "dependent_count": 0
  }
}

Integration with Other Skills

/commit-best-practices check-pre-commit
  ↓ (if pass)
/commit-analysis analyze
  ↓
/message-generation complete-message
  ↓
/commit (create commit)
  ↓
/commit-best-practices review-commit
  ↓ (if score < 70)
/commit-best-practices amend-guidance

Best Practices Enforced

  1. Tests must pass - No commits with failing tests
  2. No debug code - No console.log, debugger in commits
  3. No TODOs - Fix or remove before committing
  4. No merge markers - Resolve conflicts fully
  5. Atomic commits - One logical change per commit
  6. Quality messages - Conventional commits format
  7. Safe amends - Only amend unpushed commits
  8. Proper reverts - Use revert for shared history

Common Scenarios

Scenario 1: Debug Code Found

Pre-commit check fails:
  āŒ Debug code: 3 instances found
     - src/auth.js:42: console.log(user)
     - src/api.js:18: debugger statement

Action: Remove debug code, re-stage files, retry

Scenario 2: Tests Failing

Pre-commit check fails:
  āŒ Tests: 2 failing
     - test/auth.test.js: OAuth flow test

Action: Fix tests, verify passing, retry

Scenario 3: Unsafe Amend

Amend safety check:
  āŒ UNSAFE: Commit already pushed to remote
  
Alternatives:
  1. Create new commit (recommended)
  2. Use git revert (if undoing)
  3. Coordinate with team before force push

Scenario 4: Non-Atomic Commit

Commit review:
  Score: 58/100
  ⚠ Non-atomic: Mixes feat + fix + docs

Recommendation:
  Split into 3 commits:
    1. feat(auth): OAuth implementation
    2. fix(api): null pointer handling
    3. docs: authentication guide
    
  Use: /commit-split

This skill ensures high-quality commits through automated validation, intelligent review, and guided workflows.

Operation: Safe Commit Amend Guidance

Guide users through safely amending commits with comprehensive safety checks.

Parameters from $ARGUMENTS

  • force (optional): Skip safety checks (default: false) - USE WITH EXTREME CAUTION

Parse as: amend-guidance force:true or amend-guidance

Amend Safety Workflow

Step 1: Run Amend Safety Check

Execute safety validation script:

./.claude/commands/commit-best-practices/.scripts/amend-safety.sh

The script checks:

  1. Commit not pushed to remote
  2. Same author (current user matches commit author)
  3. Not on protected branch (main/master)
  4. No collaborators have pulled it

Returns:

{
  "safe": true|false,
  "checks": {
    "not_pushed": {"status": "pass|fail", "message": "..."},
    "same_author": {"status": "pass|fail", "message": "..."},
    "safe_branch": {"status": "pass|warn", "message": "..."},
    "collaborators": {"status": "pass|warn", "message": "..."}
  },
  "recommendation": "safe|warning|unsafe"
}

Step 2: Evaluate Safety Status

SAFE (All checks pass):

āœ… SAFE TO AMEND

Last commit: abc123
Author: John Doe <john@example.com> (you)
Branch: feature/oauth-implementation
Status: Not pushed to remote

All safety checks passed:
  āœ… Commit not pushed to remote
  āœ… You are the author
  āœ… Not on main/master branch
  āœ… No collaborators have this commit

It is SAFE to amend this commit.

WARNING (Minor concerns):

āš ļø  AMEND WITH CAUTION

Last commit: abc123
Author: John Doe <john@example.com> (you)
Branch: main
Status: Not pushed to remote

Safety checks:
  āœ… Commit not pushed to remote
  āœ… You are the author
  āš ļø  WARNING: On main/master branch
  āœ… No collaborators have this commit

Amending on main/master is discouraged but technically safe if not pushed.

Recommendation: Create new commit instead of amending.

UNSAFE (Critical issues):

āŒ UNSAFE TO AMEND

Last commit: abc123
Author: Jane Smith <jane@example.com> (NOT you)
Branch: feature/oauth
Status: Pushed to origin/feature/oauth

Safety violations:
  āŒ CRITICAL: Commit already pushed to remote
  āŒ CRITICAL: Different author (Jane Smith, not you)
  āœ… Safe branch (not main/master)
  āš ļø  WARNING: Other developers may have pulled this

DO NOT AMEND THIS COMMIT!

Amending will:
  1. Rewrite git history
  2. Break other developers' work
  3. Require force push (dangerous)
  4. Cause merge conflicts for collaborators

Use: git revert (to undo changes safely)
Or: Create new commit (to add fixes)

Step 3: Provide Amend Instructions

If SAFE, show how to amend:

How to Amend Commit
===================

Current commit message:
---
feat(auth): add OAuth authentication

Implement OAuth2 flow for Google and GitHub
---

Option 1: Amend with staged changes
-------------------------------------
1. Make your changes to files
2. Stage changes: git add <files>
3. Amend commit: git commit --amend

This opens editor to modify message if needed.

Option 2: Amend message only
-----------------------------
git commit --amend

Opens editor to change commit message.
No file changes included.

Option 3: Amend with new message (no editor)
---------------------------------------------
git commit --amend -m "new message here"

Direct message change without editor.

After amending:
---------------
Review commit: /commit-best-practices review-commit
Verify changes: git show HEAD
Continue work or push: git push origin <branch>

Note: If you already pushed, you'll need: git push --force-with-lease
(Only if you're certain no one else has pulled your changes!)

If UNSAFE, show alternatives:

Safe Alternatives to Amending
==============================

Since amending is unsafe, use these alternatives:

Option 1: Create New Commit (Recommended)
------------------------------------------
Make your changes and commit normally:

1. Make changes to files
2. Stage: git add <files>
3. Commit: git commit -m "fix: address review feedback"

This preserves history and is safe for collaborators.

Option 2: Revert Previous Commit
---------------------------------
If the commit is wrong, revert it:

1. Revert: git revert HEAD
2. Make correct changes
3. Commit: git commit -m "correct implementation"

This creates two new commits (revert + fix).

Option 3: Interactive Rebase (Advanced)
----------------------------------------
Only if you're experienced and coordinate with team:

1. git rebase -i HEAD~2
2. Mark commit as 'edit'
3. Make changes
4. git rebase --continue

āš ļø  WARNING: Requires force push, coordinate with team!

Best Practice:
--------------
When in doubt, create a new commit. It's always safer.

Step 4: Force Mode Handling

If user specified force:true:

āš ļø  FORCE MODE ENABLED

You've bypassed safety checks. This is DANGEROUS!

Proceeding with amend despite warnings.

Current commit: abc123
Branch: main
Status: Pushed to remote

You are responsible for:
  1. Coordinating with team before force push
  2. Ensuring no one has pulled this commit
  3. Handling any conflicts that arise
  4. Notifying team of force push

Force push command (if you must):
git push --force-with-lease origin <branch>

Better alternatives:
  - Create new commit instead
  - Use git revert for pushed commits
  - Coordinate with team before rewriting history

Proceed with extreme caution!

Safety Rules Summary

āœ… SAFE to amend if ALL true:

  1. Not pushed to remote

    • git log @{upstream}..HEAD shows commit
    • Commit only exists locally
  2. Same author

    • git config user.email matches commit author
    • You made the commit
  3. Not on protected branch

    • Not on main/master
    • Or: on feature branch
  4. No collaborators affected

    • Solo work on branch
    • Or: coordinated with team

āŒ NEVER amend if ANY true:

  1. Already pushed to remote

    • Commit exists on origin
    • Others may have pulled it
  2. Different author

    • Someone else made the commit
    • Not your work to modify
  3. Collaborators working on same branch

    • Team has pulled your commit
    • Would break their work
  4. On shared/protected branch

    • main/master branch
    • Production/release branches

When Amend is Useful

Good use cases:

  • Fix typo in commit message (before push)
  • Add forgotten file to commit (before push)
  • Improve commit message clarity (before push)
  • Reformat message to match conventions (before push)

Bad use cases:

  • Fixing bug in pushed commit (use new commit)
  • Changing commit after code review started (confusing)
  • Modifying shared branch commits (breaks collaboration)
  • Rewriting public history (dangerous)

Output Format

Amend Safety Check
==================

Commit: <sha>
Author: <name> <email> [you|NOT you]
Branch: <branch>
Status: [Local only|Pushed to <remote>]

SAFETY CHECKS:
  [āœ…|āš ļø|āŒ] Commit not pushed
  [āœ…|āš ļø|āŒ] Same author
  [āœ…|āš ļø|āŒ] Safe branch
  [āœ…|āš ļø|āŒ] No collaborators affected

VERDICT: [SAFE|WARNING|UNSAFE]

[Detailed explanation]

[If SAFE: Amend instructions]
[If UNSAFE: Safe alternatives]

Error Handling

No commits to amend:

ERROR: No commits to amend
This is the first commit (no parent)
Use: git commit (to create first commit)

Not a git repository:

ERROR: Not a git repository
Run: git init (to initialize)

Script execution error:

ERROR: Amend safety check script failed
Check: .claude/commands/commit-best-practices/.scripts/amend-safety.sh exists
Verify: Script is executable

Integration with Agent

When user says "amend my commit" or "fix my commit":

  1. Agent MUST run safety check FIRST
  2. If unsafe, BLOCK amend and show alternatives
  3. If safe, provide clear amend instructions
  4. Never allow unsafe amend without explicit force flag

Git Commands Reference

# Check if commit is pushed
git log @{upstream}..HEAD

# Check commit author
git log -1 --format='%an %ae'

# Check current branch
git branch --show-current

# Check remote tracking
git rev-parse --abbrev-ref --symbolic-full-name @{upstream}

# Amend commit (opens editor)
git commit --amend

# Amend with message (no editor)
git commit --amend -m "new message"

# Amend without changing message
git commit --amend --no-edit

# Force push if needed (DANGEROUS)
git push --force-with-lease origin <branch>

Best Practices

  1. Default to safe: Always check before amending
  2. Never force without reason: Force flag is dangerous
  3. Prefer new commits: When in doubt, commit new changes
  4. Communicate: Tell team before force pushing
  5. Use revert: For pushed commits, revert instead of amend

Safe git practices prevent broken collaboration and lost work.

Operation: Pre-Commit Validation

Validate repository state and changes before committing to ensure quality standards.

Parameters from $ARGUMENTS

  • quick (optional): true for fast checks only, false for full validation (default: false)

Parse as: check-pre-commit quick:true or check-pre-commit

Pre-Commit Validation Workflow

Step 1: Repository State Check

Verify git repository is valid and has changes:

# Check if git repository
if ! git rev-parse --git-dir >/dev/null 2>&1; then
    ERROR: "Not a git repository"
    exit 1
fi

# Check for changes to commit
git status --short

If no changes, inform user: "Working tree clean. No changes to commit."

Step 2: Run Pre-Commit Checks Script

Execute comprehensive validation:

cd $(git rev-parse --show-toplevel)
./.claude/commands/commit-best-practices/.scripts/pre-commit-check.sh quick:${quick:-false}

The script returns JSON:

{
  "status": "pass|fail",
  "checks": {
    "tests": {"status": "pass|fail|skip", "message": "..."},
    "lint": {"status": "pass|fail|skip", "message": "..."},
    "debug_code": {"status": "pass|fail", "count": 0, "locations": []},
    "todos": {"status": "pass|warn", "count": 0, "locations": []},
    "merge_markers": {"status": "pass|fail", "count": 0, "locations": []}
  }
}

Step 3: Parse Results

If status = "pass":

āœ… Pre-commit validation passed!

All checks completed successfully:
  āœ… Tests: passed
  āœ… Lint: passed
  āœ… Debug code: none found
  āœ… TODOs: none in committed code
  āœ… Merge markers: none found

Safe to commit. Proceed with: /commit

If status = "fail":

āŒ Pre-commit validation failed!

Issues found:
  āŒ Tests: 2 failing
     - test/auth.test.js: OAuth flow test
     - test/api.test.js: null pointer test

  āŒ Debug code: 3 instances found
     - src/auth.js:42: console.log(user)
     - src/api.js:18: debugger statement
     - src/utils.js:91: print(response)

  āŒ TODOs: 1 found in staged code
     - src/auth.js:56: TODO: refactor this

Cannot commit until issues are resolved.

Actions to take:
1. Fix failing tests
2. Remove debug statements (console.log, debugger, print)
3. Resolve or remove TODOs in staged files
4. Run: /commit-best-practices check-pre-commit (to re-validate)

Step 4: Provide Guidance

Based on failures, provide specific remediation:

Tests Failing:

To fix tests:
1. Run tests locally: npm test (or pytest, cargo test, etc.)
2. Review failures and fix issues
3. Verify all tests pass
4. Re-run validation

Debug Code Found:

To remove debug code:
1. Search for: console.log, debugger, print(, pdb.
2. Remove or comment out debug statements
3. Consider using proper logging instead
4. Re-stage files: git add <file>

TODOs in Committed Code:

TODOs found in staged code:
1. Either: Fix the TODO items now
2. Or: Unstage files with TODOs (git reset HEAD <file>)
3. Or: Remove TODO comments temporarily

Best practice: Don't commit TODOs to main/master

Merge Markers Found:

Merge conflict markers detected:
- <<<<<<<
- =======
- >>>>>>>

Actions:
1. Resolve merge conflicts completely
2. Remove all conflict markers
3. Test merged code
4. Re-stage resolved files

Output Format

Provide clear, actionable feedback:

Pre-Commit Validation Report
============================

Status: [PASS|FAIL]

Checks Performed:
  [āœ…|āŒ] Tests: [result]
  [āœ…|āŒ] Lint: [result]
  [āœ…|āŒ] Debug Code: [result]
  [āœ…|āŒ] TODOs: [result]
  [āœ…|āŒ] Merge Markers: [result]

[If FAIL: Detailed issue list with file locations]

[If FAIL: Remediation steps]

[If PASS: "Safe to commit" confirmation]

Quick Mode

If quick:true:

  • Skip test execution (assume tests run in CI)
  • Skip lint execution (assume linter runs separately)
  • Only check: debug code, TODOs, merge markers
  • Much faster (~1 second vs ~30 seconds)

Use quick mode for rapid iteration during development.

Error Handling

Not a git repository:

ERROR: Not a git repository
Run: git init (to initialize)
Or: cd to correct directory

No changes to validate:

INFO: Working tree clean
No changes staged for commit
Use: git add <files> (to stage changes)

Script execution error:

ERROR: Pre-commit check script failed
Check: .claude/commands/commit-best-practices/.scripts/pre-commit-check.sh exists
Verify: Script is executable (chmod +x)

Integration with Agent

When user says "commit my changes":

  1. Agent MUST run this check FIRST
  2. If check fails, BLOCK commit and provide guidance
  3. If check passes, proceed with commit workflow
  4. Never allow commit with failing validation (unless user explicitly forces)

Best Practices Enforced

  1. Tests must pass - Failing tests = broken code
  2. No debug code - console.log, debugger not for production
  3. No committed TODOs - Fix or remove before commit
  4. No merge markers - Resolve conflicts completely
  5. Lint compliance - Follow project style

These checks ensure high code quality and prevent common mistakes.

Operation: Commit Revert Guidance

Guide users through safely reverting commits with proper formatting and workflow.

Parameters from $ARGUMENTS

  • commit (required): Commit SHA to revert

Parse as: revert-guidance commit:abc123

Revert Workflow

Step 1: Validate Commit

Verify commit exists and get details:

# Check if commit exists
if ! git rev-parse --verify ${commit} >/dev/null 2>&1; then
    ERROR: "Commit not found: ${commit}"
    exit 1
fi

# Get commit details
commit_sha=$(git rev-parse ${commit})
commit_subject=$(git log -1 --format='%s' ${commit_sha})
commit_author=$(git log -1 --format='%an <%ae>' ${commit_sha})
commit_date=$(git log -1 --format='%ad' ${commit_sha})

Step 2: Run Revert Helper Script

Generate proper revert commit message:

./.claude/commands/commit-best-practices/.scripts/revert-helper.sh "${commit_sha}"

Returns:

{
  "commit": "abc123...",
  "original_message": "feat(auth): add OAuth authentication",
  "revert_message": "revert: feat(auth): add OAuth authentication\n\nThis reverts commit abc123.\n\nReason: OAuth implementation incompatible with current auth system",
  "type": "feat",
  "scope": "auth",
  "files_affected": 5,
  "safe_to_revert": true,
  "warnings": []
}

Step 3: Analyze Revert Safety

Check if revert will cause issues:

Safe to revert:

āœ… Safe to revert

Commit: abc123
Original: feat(auth): add OAuth authentication
Author: John Doe
Date: 2025-10-10

Analysis:
  āœ… No dependent commits found
  āœ… No merge conflicts expected
  āœ… Files still exist
  āœ… Clean revert possible

This commit can be safely reverted.

Potential issues:

āš ļø  Revert with caution

Commit: abc123
Original: feat(auth): add OAuth authentication
Author: John Doe
Date: 2025-10-10

Warnings:
  āš ļø  3 commits depend on this change
      - def456: feat(auth): add OAuth providers
      - ghi789: fix(auth): OAuth token refresh
      - jkl012: docs: OAuth setup guide

  āš ļø  Potential merge conflicts
      - src/auth/oauth.js: modified in later commits
      - src/config/auth.js: modified in later commits

Reverting will require:
  1. Resolving merge conflicts
  2. Possibly reverting dependent commits first
  3. Updating or removing affected features

Consider: Revert dependent commits in reverse order.

Step 4: Generate Revert Message

Follow proper revert commit message format:

Conventional Commits Revert Format:
-----------------------------------
revert: <original-type>(<original-scope>): <original-subject>

This reverts commit <sha>.

Reason: <explanation-of-why>

[Optional: Additional context]
[Optional: BREAKING CHANGE if revert breaks functionality]
[Optional: Issue references]

Example:
-----------------------------------
revert: feat(auth): add OAuth authentication

This reverts commit abc123def456789.

Reason: OAuth implementation incompatible with existing SAML
authentication system. Caused authentication failures for
enterprise users.

Need to redesign OAuth to work alongside SAML before
reintroducing.

BREAKING CHANGE: OAuth authentication temporarily removed.
Users must use username/password authentication.

Refs: #456

Step 5: Provide Revert Instructions

Simple revert (no conflicts):

How to Revert Commit
====================

Commit to revert: abc123
Original message: feat(auth): add OAuth authentication

Generated revert message:
---
revert: feat(auth): add OAuth authentication

This reverts commit abc123.

Reason: [Provide reason here]
---

Option 1: Auto-revert with Git (Recommended)
---------------------------------------------
git revert abc123

This will:
  1. Create revert commit automatically
  2. Open editor for message (pre-filled)
  3. Add reason for revert
  4. Save and close

Option 2: Manual revert
-----------------------
1. git revert --no-commit abc123
2. Review changes: git diff --cached
3. Adjust if needed
4. git commit (use message above)

After reverting:
----------------
1. Test that functionality is restored
2. Verify no broken dependencies
3. Push: git push origin <branch>

The revert commit preserves history while undoing changes.

Complex revert (conflicts or dependencies):

Complex Revert Required
=======================

Commit to revert: abc123
Original: feat(auth): add OAuth authentication
Dependencies: 3 commits depend on this

Revert Strategy:
----------------

Step 1: Revert dependent commits FIRST (newest to oldest)
  git revert jkl012  # docs: OAuth setup guide
  git revert ghi789  # fix(auth): OAuth token refresh
  git revert def456  # feat(auth): add OAuth providers

Step 2: Revert original commit
  git revert abc123  # feat(auth): add OAuth authentication

Step 3: Handle conflicts
  If conflicts occur:
    1. git status (see conflicted files)
    2. Edit files to resolve conflicts
    3. git add <resolved-files>
    4. git revert --continue

Step 4: Test thoroughly
  - Run full test suite
  - Verify auth system works
  - Check for broken functionality

Alternative: Revert in single commit
-------------------------------------
If you want one revert commit for all:

1. git revert --no-commit jkl012
2. git revert --no-commit ghi789
3. git revert --no-commit def456
4. git revert --no-commit abc123
5. Resolve any conflicts
6. git commit -m "revert: OAuth authentication feature

This reverts commits abc123, def456, ghi789, jkl012.

Reason: OAuth incompatible with SAML system."

This creates a single revert commit for multiple changes.

Step 6: Post-Revert Checklist

After reverting, verify:

Post-Revert Checklist
=====================

ā–” Revert commit created successfully
  git log -1 (verify revert commit exists)

ā–” Changes actually reverted
  git diff <commit>^..<commit> (should be inverse of original)

ā–” Tests pass
  npm test (or your test command)

ā–” No broken functionality
  Test affected features manually

ā–” Documentation updated
  Update docs if feature was documented

ā–” Team notified
  Inform team of revert and reason

ā–” Issue tracker updated
  Comment on related issues

ā–” Ready to push
  git push origin <branch>

Revert vs Reset vs Amend

Use git revert when:

  • āœ… Commit already pushed to remote
  • āœ… Working on shared branch
  • āœ… Need to preserve history
  • āœ… Undoing specific commit in middle of history

Use git reset when:

  • āš ļø Commit not yet pushed (local only)
  • āš ļø Want to completely remove commit
  • āš ļø Rewriting personal branch history
  • āš ļø No one else has the commit

Use git commit --amend when:

  • āš ļø Fixing most recent commit only
  • āš ļø Commit not yet pushed
  • āš ļø Small typo or forgotten file

Decision tree:

Has commit been pushed?
ā”œā”€ Yes → Use git revert (safe for shared history)
└─ No → Is it the most recent commit?
    ā”œā”€ Yes → Use git commit --amend (if minor fix)
    └─ No → Use git reset (if complete removal needed)

Revert Message Examples

Example 1: Bug found

revert: fix(api): add null check in user endpoint

This reverts commit abc123.

Reason: Fix introduced regression causing authentication
failures for legacy clients. Null check logic incorrect.

Will reimplement with proper validation after adding tests.

Fixes: #789

Example 2: Performance issue

revert: perf(search): implement new search algorithm

This reverts commit def456.

Reason: New algorithm causes 300% increase in database
load under production traffic. Needs optimization before
redeployment.

Keeping old algorithm until performance issues resolved.

Example 3: Breaking change

revert: feat(api): change authentication endpoint format

This reverts commit ghi789.

Reason: Breaking change deployed without proper migration
period. Mobile app version 1.x incompatible with new format.

BREAKING CHANGE: Reverting API format to v1 for backwards
compatibility. Will reintroduce in v2 with migration path.

Refs: #234, #235, #236 (user reports)

Output Format

Revert Guidance Report
======================

Commit to Revert: <sha>
Original Message: <message>
Author: <name>
Date: <date>

REVERT SAFETY:
  [āœ…|āš ļø] No dependent commits
  [āœ…|āš ļø] No merge conflicts expected
  [āœ…|āš ļø] Files still exist

GENERATED REVERT MESSAGE:
---
<revert-message-content>
---

REVERT INSTRUCTIONS:
[Step-by-step instructions]

POST-REVERT CHECKLIST:
[Verification steps]

Error Handling

Commit not found:

ERROR: Commit not found: abc123
Check: git log (to see available commits)
Verify: Commit hash is correct (7+ characters)

Already reverted:

WARNING: This commit may already be reverted

Found revert commit: xyz789
Message: "revert: feat(auth): add OAuth authentication"

If this is a duplicate revert, it may cause issues.
Check: git log (to verify)

Merge commit:

WARNING: This is a merge commit

Merge commits require special handling:
git revert -m 1 abc123

-m 1: Keep changes from first parent
-m 2: Keep changes from second parent

Determine which parent to keep based on your branch strategy.

Integration with Agent

When user says "revert my commit" or "undo commit abc123":

  1. Agent identifies commit to revert
  2. Runs safety analysis
  3. Generates proper revert message
  4. Provides step-by-step instructions
  5. Offers post-revert verification checklist

Best Practices

  1. Always provide reason: Explain WHY reverting in message
  2. Reference original commit: Include SHA in revert message
  3. Test after revert: Ensure functionality restored
  4. Notify team: Communicate reverts to collaborators
  5. Update issues: Comment on related issue tracker items
  6. Preserve history: Use revert, not reset, for shared branches

Proper reverts maintain clear history and facilitate collaboration.

Operation: Review Commit Quality

Analyze a commit's quality including message, changes, atomicity, and completeness.

Parameters from $ARGUMENTS

  • commit (optional): Commit SHA or reference (default: HEAD)

Parse as: review-commit commit:abc123 or review-commit (defaults to HEAD)

Commit Review Workflow

Step 1: Validate Commit Exists

# Check if commit exists
if ! git rev-parse --verify ${commit:-HEAD} >/dev/null 2>&1; then
    ERROR: "Commit not found: ${commit}"
    exit 1
fi

# Get commit hash
commit_sha=$(git rev-parse ${commit:-HEAD})

Step 2: Run Commit Reviewer Script

Execute comprehensive analysis:

./.claude/commands/commit-best-practices/.scripts/commit-reviewer.py "${commit_sha}"

The script returns JSON:

{
  "commit": "abc123...",
  "author": "John Doe <john@example.com>",
  "date": "2025-10-13",
  "message": {
    "subject": "feat(auth): add OAuth authentication",
    "body": "- Implement OAuth2 flow\n- Add providers",
    "subject_length": 38,
    "has_body": true,
    "conventional": true,
    "type": "feat",
    "scope": "auth"
  },
  "changes": {
    "files_changed": 5,
    "insertions": 234,
    "deletions": 12,
    "test_files": 1,
    "doc_files": 0
  },
  "quality": {
    "atomic": true,
    "message_quality": "excellent",
    "test_coverage": true,
    "issues": []
  },
  "score": 95
}

Step 3: Analyze Message Quality

Check Subject Line:

  • Length ≤ 50 characters āœ…
  • Imperative mood ("add" not "added") āœ…
  • Conventional commits format āœ…
  • Clear and descriptive āœ…

Check Body (if present):

  • Wrapped at 72 characters āœ…
  • Explains WHY (not just what) āœ…
  • Uses bullet points for clarity āœ…
  • Blank line after subject āœ…

Check Footer (if present):

  • Breaking changes noted āœ…
  • Issue references included āœ…

Step 4: Analyze Changes

Atomicity Check:

Atomic commit = Single logical change

Check for:
  āŒ Multiple types mixed (feat + fix)
  āŒ Multiple scopes mixed (auth + api + docs)
  āŒ Unrelated changes bundled together

Example ATOMIC:
  feat(auth): add OAuth authentication
  - 5 files, all auth-related
  - Single feature implementation

Example NON-ATOMIC:
  feat: add OAuth and fix null pointer
  - Mixing feat + fix
  - Should be 2 commits

Completeness Check:

Complete commit includes:
  āœ… Implementation code
  āœ… Tests for new code
  āœ… Documentation if needed
  āœ… No missing pieces

Incomplete examples:
  āŒ New feature without tests
  āŒ API change without docs
  āŒ Partial implementation

Step 5: Generate Review Report

Excellent Commit (Score 90-100):

āœ… EXCELLENT COMMIT

Commit: abc123 (HEAD)
Author: John Doe
Date: 2025-10-13

Message Quality: EXCELLENT
  āœ… Subject: "feat(auth): add OAuth authentication" (38 chars)
  āœ… Conventional commits format
  āœ… Descriptive body with bullet points
  āœ… Proper formatting

Changes:
  āœ… Atomic: Single feature (OAuth authentication)
  āœ… Complete: Implementation + tests
  āœ… Files: 5 changed (+234 -12 lines)
  āœ… Test coverage included

Score: 95/100

This commit follows all best practices. Safe to push!

Good Commit (Score 70-89):

āœ… GOOD COMMIT (Minor improvements possible)

Commit: abc123 (HEAD)
Author: John Doe
Date: 2025-10-13

Message Quality: GOOD
  āœ… Subject: "feat(auth): add OAuth authentication" (38 chars)
  āœ… Conventional commits format
  āš ļø  Body: Could be more detailed (explains WHAT but not WHY)

Changes:
  āœ… Atomic: Single feature
  āš ļø  Test coverage: Only integration tests (unit tests missing)
  āœ… Files: 5 changed (+234 -12 lines)

Score: 82/100

Suggestions:
  1. Add more context in commit body about WHY this change
  2. Consider adding unit tests for edge cases

Still a good commit. Safe to push with minor notes.

Needs Improvement (Score 50-69):

āš ļø  NEEDS IMPROVEMENT

Commit: abc123 (HEAD)
Author: John Doe
Date: 2025-10-13

Message Quality: FAIR
  āš ļø  Subject: "add oauth" (9 chars - too short)
  āŒ Not conventional commits format (missing type/scope)
  āŒ No body explaining changes

Changes:
  āš ļø  Atomicity: Questionable (mixes auth + API changes)
  āŒ Test coverage: No tests included
  āœ… Files: 8 changed (+312 -45 lines)

Score: 58/100

Issues to address:
  1. Improve commit message: "feat(auth): add OAuth authentication"
  2. Add commit body explaining implementation
  3. Add tests for new OAuth functionality
  4. Consider splitting auth changes from API changes

Recommendation: Amend or rewrite this commit before pushing.

Poor Commit (Score < 50):

āŒ POOR COMMIT - Should be rewritten

Commit: abc123 (HEAD)
Author: John Doe
Date: 2025-10-13

Message Quality: POOR
  āŒ Subject: "stuff" (5 chars - meaningless)
  āŒ No type, no scope, no clarity
  āŒ No body, no context

Changes:
  āŒ Non-atomic: Multiple unrelated changes
     - Auth system
     - API refactoring
     - Documentation
     - Bug fixes (3 different issues)
  āŒ No tests
  āŒ Files: 23 changed (+1,234 -567 lines)

Score: 28/100

Critical issues:
  1. Commit message is meaningless ("stuff")
  2. Bundles 4+ unrelated changes together
  3. No tests for significant code changes
  4. Too large (23 files)

Action required: Reset and split into 4+ atomic commits with proper messages.

Use: /commit-split (to split into atomic commits)

Step 6: Provide Actionable Guidance

Based on score, recommend action:

Score ≄ 90: Safe to push as-is Score 70-89: Safe to push, minor suggestions noted Score 50-69: Amend recommended before pushing Score < 50: Rewrite required, do not push

Amend Guidance

If commit needs improvement and is safe to amend:

To amend this commit:

1. Make improvements (add tests, update message, etc.)
2. Stage changes: git add <files>
3. Amend commit: git commit --amend
4. Review again: /commit-best-practices review-commit

Note: Only amend if commit not yet pushed to remote!
Check: /commit-best-practices amend-guidance

Split Guidance

If commit is non-atomic:

This commit should be split into multiple commits:

Detected separate concerns:
  1. feat(auth): OAuth implementation (5 files)
  2. fix(api): null pointer handling (2 files)
  3. docs: authentication guide (1 file)

Use: /commit-split (for interactive splitting)
Or: git reset HEAD~1 (to undo and recommit properly)

Output Format

Commit Review Report
===================

Commit: <sha> (<ref>)
Author: <name> <email>
Date: <date>

MESSAGE QUALITY: [EXCELLENT|GOOD|FAIR|POOR]
  [āœ…|āš ļø|āŒ] Subject: "<subject>" (<length> chars)
  [āœ…|āš ļø|āŒ] Format: [Conventional|Non-conventional]
  [āœ…|āš ļø|āŒ] Body: [Present|Missing]
  [āœ…|āš ļø|āŒ] Clarity: [Clear|Vague]

CHANGES:
  [āœ…|āš ļø|āŒ] Atomic: [Yes|Questionable|No]
  [āœ…|āš ļø|āŒ] Complete: [Yes|Partial]
  [āœ…|āš ļø|āŒ] Tests: [Included|Missing]
  [āœ…|āš ļø|āŒ] Size: <files> files (+<ins> -<del> lines)

SCORE: <score>/100

[Issues list if any]

[Recommendations]

VERDICT: [Safe to push|Amend recommended|Rewrite required]

Error Handling

Commit not found:

ERROR: Commit not found: abc123
Check: git log (to see available commits)

Not a git repository:

ERROR: Not a git repository
Run: git init (to initialize)

Script execution error:

ERROR: Commit reviewer script failed
Check: .claude/commands/commit-best-practices/.scripts/commit-reviewer.py exists
Verify: Script is executable

Integration with Agent

After user creates a commit:

  1. Agent automatically runs review (unless disabled)
  2. If score < 70, suggest improvements
  3. If non-atomic, suggest splitting
  4. If excellent (≄90), congratulate and suggest push

Best Practices Enforced

  1. Meaningful messages - Clear, descriptive commit messages
  2. Conventional format - type(scope): description
  3. Atomic commits - One logical change per commit
  4. Complete commits - Include tests and docs
  5. Proper formatting - Subject ≤50 chars, body wrapped at 72

High-quality commits make git history useful for debugging, code review, and collaboration.

Commit Best Practices Skill Router

You are orchestrating commit best practices validation and workflow guidance operations.

Parse Request

Examine $ARGUMENTS to determine the operation and parameters:

Format: <operation> [parameters]

Available Operations

  1. check-pre-commit - Validate repository state before committing

    • Runs tests, lint checks, detects debug code
    • Validates no TODOs, no merge markers
    • Format: check-pre-commit [quick:true|false]
  2. review-commit - Review most recent commit quality

    • Analyzes commit message and changes
    • Checks atomicity and completeness
    • Format: review-commit [commit:HEAD|<sha>]
  3. amend-guidance - Guide safe commit amending

    • Checks if safe to amend (not pushed, same author)
    • Provides amend instructions
    • Format: amend-guidance [force:true|false]
  4. revert-guidance - Help with commit reverts

    • Generates proper revert commit message
    • Provides revert instructions
    • Format: revert-guidance commit:<sha>
  5. workflow-tips - Complete git workflow guidance

    • Best practices overview
    • Branch management tips
    • Format: workflow-tips [focus:commit|branch|merge]

Routing Logic

Parse first word from $ARGUMENTS:
  "check-pre-commit" → Read commands/commit-best-practices/check-pre-commit.md
  "review-commit"    → Read commands/commit-best-practices/review-commit.md
  "amend-guidance"   → Read commands/commit-best-practices/amend-guidance.md
  "revert-guidance"  → Read commands/commit-best-practices/revert-guidance.md
  "workflow-tips"    → Read commands/commit-best-practices/workflow-tips.md
  (unknown)          → Show error and list available operations

Base Directory

Location: .claude/commands/commit-best-practices/

Error Handling

If operation is not recognized:

ERROR: Unknown operation: <operation>

Available operations:
  - check-pre-commit [quick:true|false]
  - review-commit [commit:HEAD|<sha>]
  - amend-guidance [force:true|false]
  - revert-guidance commit:<sha>
  - workflow-tips [focus:commit|branch|merge]

Example: /commit-best-practices check-pre-commit quick:true

Request Context

User Request: $ARGUMENTS

Now route to the appropriate operation file and execute its instructions with the provided parameters.

Operation: Git Workflow Tips and Best Practices

Comprehensive git workflow guidance covering commits, branches, merging, and collaboration.

Parameters from $ARGUMENTS

  • focus (optional): Specific area (commit|branch|merge|all) (default: all)

Parse as: workflow-tips focus:commit or workflow-tips

Workflow Guidance

Route to specific section based on focus parameter:

Focus: Commit Workflow

Complete commit workflow best practices:

Git Commit Workflow Best Practices
===================================

1. BEFORE YOU CODE
------------------
ā–” Create feature branch
  git checkout -b feature/your-feature-name

ā–” Pull latest changes
  git pull origin main

ā–” Verify clean state
  git status


2. WHILE CODING
---------------
ā–” Commit frequently (atomic commits)
  - After each logical change
  - Not too small (typo fixes can be bundled)
  - Not too large (avoid 1000+ line commits)

ā–” Test before committing
  npm test (or your test command)

ā–” Keep commits focused
  - One concern per commit
  - Don't mix features and fixes
  - Don't mix multiple scopes


3. BEFORE COMMITTING
--------------------
ā–” Review your changes
  git diff (see what changed)
  git status (see staged/unstaged)

ā–” Stage selectively
  git add <specific-files>
  (Don't blindly: git add .)

ā–” Run pre-commit checks
  /commit-best-practices check-pre-commit

ā–” Remove debug code
  - console.log, print statements
  - debugger statements
  - Temporary test code


4. CREATING COMMIT
------------------
ā–” Use conventional commits format
  <type>(<scope>): <subject>

ā–” Write clear subject (≤50 chars)
  - Imperative mood: "add" not "added"
  - Lowercase after type
  - No period at end

ā–” Add descriptive body (if needed)
  - Explain WHY, not what
  - Wrap at 72 characters
  - Use bullet points

ā–” Include footer (if applicable)
  - BREAKING CHANGE: description
  - Closes #123


5. AFTER COMMITTING
-------------------
ā–” Review commit
  /commit-best-practices review-commit
  git show HEAD

ā–” Verify tests still pass
  npm test

ā–” Push to remote
  git push origin <branch>

ā–” Create pull request (if ready)
  gh pr create


6. COMMON MISTAKES TO AVOID
---------------------------
āŒ "WIP" or "work in progress" commits
   → Finish work before committing

āŒ "Fix" or "update" without context
   → Be specific: "fix(auth): null pointer in OAuth"

āŒ Committing all changes at once
   → Split into atomic commits

āŒ Forgetting to add tests
   → Tests should accompany code changes

āŒ Committing node_modules or .env files
   → Use .gitignore properly

āŒ Force pushing to shared branches
   → Only force push on personal branches


7. COMMIT CHECKLIST
-------------------
Before every commit, verify:

ā–” Changes are atomic (single logical change)
ā–” Tests pass
ā–” No debug code
ā–” No TODOs in committed code
ā–” Message follows conventions
ā–” Includes tests (if new functionality)
ā–” Documentation updated (if needed)

Use: /commit (agent handles checklist automatically)

Focus: Branch Workflow

Branch management best practices:

Git Branch Workflow Best Practices
===================================

1. BRANCH NAMING CONVENTIONS
-----------------------------
Follow consistent naming:

Feature branches:
  feature/oauth-authentication
  feature/user-profile-page

Bug fixes:
  fix/null-pointer-in-auth
  fix/memory-leak-in-parser

Hotfixes:
  hotfix/security-vulnerability
  hotfix/production-crash

Experiments:
  experiment/new-algorithm
  experiment/performance-optimization

Pattern: <type>/<brief-description>
Use: lowercase-with-hyphens


2. BRANCH LIFECYCLE
-------------------
Create → Develop → Test → Merge → Delete

Create:
  git checkout -b feature/my-feature
  (Always branch from main/develop)

Develop:
  - Commit frequently
  - Push regularly
  - Keep branch updated

Test:
  - Run full test suite
  - Manual testing
  - Code review

Merge:
  - Create pull request
  - Address review feedback
  - Merge to main

Delete:
  git branch -d feature/my-feature
  git push origin --delete feature/my-feature


3. KEEPING BRANCHES UPDATED
---------------------------
Regularly sync with main branch:

Option 1: Rebase (cleaner history)
  git checkout feature/my-feature
  git fetch origin
  git rebase origin/main

Option 2: Merge (preserves history)
  git checkout feature/my-feature
  git merge origin/main

Recommendation: Use rebase for feature branches,
merge for shared branches.


4. BRANCH PROTECTION RULES
---------------------------
Protect important branches:

Main/Master:
  - Require pull request
  - Require code review
  - Require passing tests
  - Block force push
  - Block deletion

Develop:
  - Require pull request
  - Require passing tests
  - Allow force push with lease

Feature:
  - No restrictions
  - Personal branches


5. LONG-RUNNING BRANCHES
-------------------------
If branch lives more than a few days:

ā–” Sync with main frequently (daily)
ā–” Keep commits atomic and clean
ā–” Push to remote regularly
ā–” Communicate with team
ā–” Consider splitting into smaller branches


6. BRANCH STRATEGIES
--------------------
Choose strategy based on team size:

Git Flow (large teams):
  - main: production
  - develop: integration
  - feature/*: new features
  - release/*: release prep
  - hotfix/*: urgent fixes

GitHub Flow (small teams):
  - main: production
  - feature/*: all work
  (Simple and effective)

Trunk-Based (continuous deployment):
  - main: always deployable
  - Short-lived feature branches
  - Feature flags for incomplete work


7. COMMON BRANCH MISTAKES
--------------------------
āŒ Working directly on main
   → Always use feature branches

āŒ Branches that live for weeks
   → Split into smaller branches

āŒ Not syncing with main regularly
   → Causes massive merge conflicts

āŒ Unclear branch names (branch1, temp)
   → Use descriptive names

āŒ Leaving merged branches
   → Delete after merging

āŒ Force pushing shared branches
   → Only force push personal branches

Focus: Merge Workflow

Merge and pull request best practices:

Git Merge Workflow Best Practices
==================================

1. BEFORE CREATING PULL REQUEST
-------------------------------
ā–” All commits are atomic
  /commit-review (check quality)

ā–” Branch is up-to-date
  git fetch origin
  git rebase origin/main

ā–” All tests pass
  npm test (full suite)

ā–” No merge conflicts
  Resolve before creating PR

ā–” Code is reviewed locally
  Self-review your changes


2. CREATING PULL REQUEST
------------------------
Good PR title:
  feat(auth): Add OAuth authentication support

Good PR description:
  ## Summary
  Implements OAuth 2.0 authentication for Google and GitHub.

  ## Changes
  - OAuth configuration system
  - Provider implementations (Google, GitHub)
  - Token refresh mechanism
  - Middleware integration

  ## Testing
  - Unit tests: 15 added
  - Integration tests: 3 added
  - Manual testing: OAuth flows verified

  ## Screenshots (if UI)
  [Include screenshots]

  Closes #123


3. CODE REVIEW PROCESS
----------------------
As author:
  ā–” Respond to all comments
  ā–” Make requested changes
  ā–” Push new commits (don't amend!)
  ā–” Re-request review when ready
  ā–” Be open to feedback

As reviewer:
  ā–” Review code thoroughly
  ā–” Check tests are included
  ā–” Verify documentation updated
  ā–” Test locally if possible
  ā–” Be constructive in feedback


4. MERGE STRATEGIES
-------------------
Choose appropriate merge strategy:

Merge Commit (default):
  git merge --no-ff feature/my-feature
  - Preserves complete history
  - Shows where feature was merged
  - Creates merge commit
  Use for: Significant features

Squash Merge:
  git merge --squash feature/my-feature
  - Combines all commits into one
  - Clean linear history
  - Loses individual commit detail
  Use for: Small features, many WIP commits

Rebase Merge:
  git rebase main
  git merge --ff-only
  - Linear history
  - No merge commit
  - Clean git log
  Use for: Personal branches, small changes


5. RESOLVING MERGE CONFLICTS
-----------------------------
When conflicts occur:

Step 1: Identify conflicts
  git status (shows conflicted files)

Step 2: Open conflicted file
  Conflict markers:
    <<<<<<< HEAD
    Your changes
    =======
    Their changes
    >>>>>>> feature/branch

Step 3: Resolve conflict
  - Choose one version, or
  - Combine both versions, or
  - Write new solution

Step 4: Remove conflict markers
  Delete <<<<<<<, =======, >>>>>>>

Step 5: Mark as resolved
  git add <resolved-file>

Step 6: Complete merge
  git merge --continue
  (or git rebase --continue)

Step 7: Test thoroughly
  npm test
  Manual testing


6. AFTER MERGING
----------------
ā–” Delete feature branch
  git branch -d feature/my-feature
  git push origin --delete feature/my-feature

ā–” Verify merge on main
  git checkout main
  git pull origin main
  git log (verify commit appears)

ā–” Run tests on main
  npm test

ā–” Deploy if applicable
  (Follow deployment process)

ā–” Update issue tracker
  Close related issues

ā–” Notify stakeholders
  Team notification of merge


7. MERGE BEST PRACTICES
------------------------
āœ… Merge frequently (avoid long-lived branches)
āœ… Require code review before merge
āœ… Ensure tests pass before merge
āœ… Delete branches after merge
āœ… Use meaningful merge commit messages
āœ… Squash "fix review comments" commits

āŒ Don't merge failing tests
āŒ Don't merge without review
āŒ Don't merge with unresolved conflicts
āŒ Don't merge incomplete features to main
āŒ Don't forget to pull after merge

Focus: All (Complete Workflow)

When focus:all or no focus specified, provide comprehensive overview:

Complete Git Workflow Guide
============================

Quick Reference for Git Best Practices

DAILY WORKFLOW
--------------
1. Start day: git pull origin main
2. Create branch: git checkout -b feature/name
3. Code & commit frequently (atomic commits)
4. Test before each commit
5. Push regularly: git push origin feature/name
6. Create PR when ready
7. Address review feedback
8. Merge and delete branch
9. Pull updated main

COMMIT GUIDELINES
-----------------
Format: <type>(<scope>): <subject>

Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore

Subject: ≤50 chars, imperative, lowercase, no period
Body: Wrap at 72 chars, explain WHY
Footer: BREAKING CHANGE, Closes #123

BRANCH STRATEGY
---------------
- main: production-ready code
- feature/*: new features
- fix/*: bug fixes
- hotfix/*: urgent production fixes

Keep branches short-lived (< 1 week)
Sync with main daily
Delete after merging

MERGE PROCESS
-------------
1. Rebase on main: git rebase origin/main
2. Resolve conflicts
3. All tests pass
4. Code review approved
5. Merge to main
6. Delete feature branch

TOOLS TO USE
------------
/commit - Create commit with agent assistance
/commit-review - Review commit quality
/commit-split - Split non-atomic commits
/commit-best-practices check-pre-commit - Validate before commit
/commit-best-practices review-commit - Review commit after creation
/commit-best-practices amend-guidance - Safe amend help
/commit-best-practices revert-guidance - Revert help

COMMON COMMANDS
---------------
git status                    # Check status
git diff                      # See changes
git add <files>              # Stage changes
git commit                   # Create commit
git push origin <branch>     # Push to remote
git pull origin main         # Get latest main
git log --oneline -10        # Recent commits
git show HEAD                # Show last commit

EMERGENCY PROCEDURES
--------------------
Committed to wrong branch:
  git reset --soft HEAD~1
  git checkout correct-branch
  git commit

Pushed wrong commit:
  git revert HEAD
  git push

Need to undo local changes:
  git checkout -- <file>
  (or git restore <file>)

Accidentally deleted branch:
  git reflog
  git checkout -b branch-name <sha>

For more detailed guidance on specific areas:
  /commit-best-practices workflow-tips focus:commit
  /commit-best-practices workflow-tips focus:branch
  /commit-best-practices workflow-tips focus:merge

Output Format

Provide guidance formatted with:

  • Clear section headers
  • Checkboxes for actionable items
  • Code examples with syntax highlighting
  • Visual indicators (āœ… āŒ āš ļø)
  • Step-by-step instructions
  • Common pitfalls and solutions

Error Handling

Invalid focus parameter:

ERROR: Invalid focus: invalid-focus
Valid options: commit, branch, merge, all
Example: /commit-best-practices workflow-tips focus:commit

Integration with Agent

Proactively suggest workflow tips when:

  • User commits to main branch directly (suggest feature branch)
  • Branch hasn't been synced in 3+ days (suggest rebase)
  • PR has many commits (suggest squash)
  • User attempts unsafe operation (provide guidance)

Best Practices Summary

The Golden Rules:

  1. Commit often - Atomic, focused commits
  2. Test always - Before every commit
  3. Branch per feature - Isolate work
  4. Sync regularly - Stay updated with main
  5. Review thoroughly - All code reviewed
  6. Merge cleanly - No conflicts, passing tests
  7. Delete branches - After merging
  8. Communicate - Keep team informed

Tools make it easier: Use /commit and related skills to automate best practices and ensure consistent, high-quality commits.

These workflows ensure clean history, facilitate collaboration, and make debugging easier when issues arise.

Operation: Diagnose Issues

Comprehensive git repository issue diagnosis.

Purpose

Run all diagnostic checks and provide a complete health report of the repository state, identifying any issues that could prevent commits or other git operations.

Parameters

None required - runs complete diagnostic suite.

Workflow

1. Run All Diagnostic Scripts

Execute all diagnostic utilities in parallel:

Check Repository Validity
REPO_RESULT=$(/home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-error-handling/.scripts/repo-checker.sh)
Check for Changes
CHANGES_RESULT=$(/home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-error-handling/.scripts/changes-detector.sh)
Check for Conflicts
CONFLICTS_RESULT=$(/home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-error-handling/.scripts/conflict-detector.py)
Check Repository State
STATE_RESULT=$(/home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-error-handling/.scripts/state-analyzer.sh)

2. Check Git Configuration

Verify git is properly configured:

# User name
USER_NAME=$(git config user.name)
USER_EMAIL=$(git config user.email)

# Verify both are set
if [ -z "$USER_NAME" ] || [ -z "$USER_EMAIL" ]; then
    CONFIG_STATUS="missing"
else
    CONFIG_STATUS="configured"
fi

3. Check Remote Status

Verify remote connectivity and status:

# Check if remote exists
git remote -v

# Check remote connection (if exists)
git ls-remote --exit-code origin &>/dev/null
REMOTE_STATUS=$?

# Check if ahead/behind remote
git rev-list --left-right --count HEAD...@{upstream} 2>/dev/null

4. Aggregate Results

Combine all diagnostic results into comprehensive report.

5. Present Comprehensive Diagnosis

Example Output Format
GIT REPOSITORY DIAGNOSIS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Repository Information:
━━━━━━━━━━━━━━━━━━━━━
Location: /home/user/project
Branch: feature-auth
Repository: Valid āœ…

Repository State:
━━━━━━━━━━━━━━━━
HEAD State: Attached āœ…
Current Branch: feature-auth āœ…
Remote Status: Up to date āœ…

Changes Status:
━━━━━━━━━━━━━━━
Has Changes: Yes āœ…
Staged Files: 3
Unstaged Files: 2
Untracked Files: 1
Total Changes: 6

Conflicts:
━━━━━━━━━━
Merge Conflicts: None āœ…
Conflict Count: 0

Configuration:
━━━━━━━━━━━━━━
User Name: John Doe āœ…
User Email: john@example.com āœ…
Git Version: 2.39.0 āœ…

Remote:
━━━━━━━
Remote Name: origin āœ…
Remote URL: github.com/user/repo āœ…
Connection: Reachable āœ…
Ahead: 2 commits
Behind: 0 commits

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Overall Status: HEALTHY āœ…

Summary:
āœ… Repository is valid and properly configured
āœ… Git configuration complete
āœ… No merge conflicts
āœ… Changes ready to commit
āœ… Remote connection working

You can proceed with git operations.

Next Steps:
1. Review changes: git status
2. Commit changes: git commit
3. Push to remote: git push
Example with Issues
GIT REPOSITORY DIAGNOSIS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Repository Information:
━━━━━━━━━━━━━━━━━━━━━
Location: /home/user/project
Branch: (detached HEAD)
Repository: Valid āœ…

Repository State:
━━━━━━━━━━━━━━━━
HEAD State: Detached āš ļø
Current Branch: (none)
Remote Status: Cannot determine

Changes Status:
━━━━━━━━━━━━━━━
Has Changes: Yes āœ…
Staged Files: 0
Unstaged Files: 5
Untracked Files: 2
Total Changes: 7

Conflicts:
━━━━━━━━━━
Merge Conflicts: YES āŒ
Conflicted Files: 2
  - src/auth/oauth.js
  - src/api/users.js

Configuration:
━━━━━━━━━━━━━━
User Name: (not set) āŒ
User Email: (not set) āŒ
Git Version: 2.39.0 āœ…

Remote:
━━━━━━━
Remote Name: origin āœ…
Remote URL: github.com/user/repo āœ…
Connection: Failed āŒ

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Overall Status: ISSUES DETECTED āš ļø

Issues Found: 4
Priority: HIGH āŒ

CRITICAL ISSUES:
━━━━━━━━━━━━━━━━

1. Merge Conflicts Present āŒ
   Impact: Cannot commit until resolved
   Files affected: 2
   Action: /commit-error-handling handle-conflicts

2. Git Configuration Missing āŒ
   Impact: Cannot commit without user.name and user.email
   Action: Configure git:
           git config user.name "Your Name"
           git config user.email "your@email.com"

WARNINGS:
━━━━━━━━━

3. Detached HEAD State āš ļø
   Impact: New commits won't be on a branch
   Action: /commit-error-handling handle-detached-head

4. Remote Connection Failed āš ļø
   Impact: Cannot push changes
   Possible causes: Network issues, authentication
   Action: Check network and credentials

RECOMMENDED RESOLUTION ORDER:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

1. First: Resolve merge conflicts
   → /commit-error-handling handle-conflicts

2. Then: Configure git user
   → git config user.name "Your Name"
   → git config user.email "your@email.com"

3. Then: Fix detached HEAD
   → /commit-error-handling handle-detached-head

4. Finally: Test remote connection
   → git fetch origin

After resolving all issues, run:
/commit-error-handling diagnose-issues

6. Provide Specific Recommendations

Based on findings, provide targeted guidance:

If no issues found
āœ… ALL CHECKS PASSED

Your repository is in good health.

Ready for:
- Committing changes
- Pushing to remote
- Branching
- Merging
- All git operations

Proceed with your intended git operation.
If issues found

Priority-ordered resolution plan:

RESOLUTION PLAN
━━━━━━━━━━━━━━━

CRITICAL (must fix first):
1. Issue: Merge conflicts
   Command: /commit-error-handling handle-conflicts
   Estimated time: 10-30 minutes

2. Issue: Git config missing
   Command: git config user.name "Your Name"
            git config user.email "your@email.com"
   Estimated time: 1 minute

HIGH (should fix):
3. Issue: Detached HEAD
   Command: /commit-error-handling handle-detached-head
   Estimated time: 2 minutes

MEDIUM (can fix later):
4. Issue: Remote connection
   Check network, verify credentials
   Estimated time: 5 minutes

7. Export Detailed Report

Optionally save full diagnostic report:

# Save to file
cat > git-diagnosis.txt <<EOF
[Full diagnosis output]
EOF

echo "Full report saved to: git-diagnosis.txt"

Diagnostic Categories

1. Repository Validity

  • Is this a git repository?
  • Is .git directory valid?
  • Is repository corrupted?

2. Repository State

  • HEAD attached or detached?
  • Current branch name
  • Clean or dirty working tree?

3. Changes Detection

  • Staged changes count
  • Unstaged changes count
  • Untracked files count
  • Total changes

4. Conflicts

  • Any merge conflicts?
  • Conflicted file list
  • Merge/rebase in progress?

5. Configuration

  • user.name set?
  • user.email set?
  • Other critical config

6. Remote Status

  • Remote configured?
  • Remote reachable?
  • Ahead/behind status
  • Push/pull needed?

7. Branch Status

  • On a branch?
  • Branch tracking remote?
  • Up to date with remote?

Error Handling

If critical git command fails

Unable to run git commands.

Possible causes:
- Git not installed
- Current directory has permission issues
- Repository is corrupted

Actions:
1. Verify git is installed:
   git --version

2. Check current directory:
   pwd
   ls -la

3. Try from different directory

If partial diagnosis succeeds

Partial diagnosis completed.

Completed checks:
āœ… Repository validity
āœ… Changes detection
āŒ Remote status (failed)
āŒ Branch status (failed)

Showing results from successful checks...

Note: Some checks failed. This may indicate:
- Network issues
- Permission problems
- Repository corruption

Output Format

The diagnosis always provides:

  1. Executive Summary - Overall status at a glance
  2. Detailed Sections - Each diagnostic category
  3. Issue List - All problems found, prioritized
  4. Resolution Plan - Ordered steps to fix issues
  5. Next Actions - Specific commands to run
  6. Success Indicators - How to verify fixes

Use visual indicators:

  • āœ… Pass
  • āŒ Fail
  • āš ļø Warning
  • ā„¹ļø Info

Success Indicators

After diagnosis:

  • User understands complete repository state
  • All issues identified and prioritized
  • Clear action plan provided
  • User knows exact commands to run
  • Estimated effort/time provided

Integration with Other Operations

The diagnosis operation orchestrates all error handling:

If repository invalid:
  → Route to: handle-no-repo

If no changes:
  → Route to: handle-no-changes

If conflicts found:
  → Route to: handle-conflicts

If detached HEAD:
  → Route to: handle-detached-head

If all pass:
  → Ready to proceed with commit workflow

Usage Patterns

Pre-commit Check

# Before attempting commit
/commit-error-handling diagnose-issues

# If all clear:
/commit-analysis analyze
/message-generation complete-message

Troubleshooting

# When git operations fail
/commit-error-handling diagnose-issues

# Follow recommended resolution order

Repository Health Check

# Periodic verification
/commit-error-handling diagnose-issues

# Ensure repository is in good state

Related Operations

  • Comprehensive entry point that may route to any other operation
  • handle-no-repo - If repository invalid
  • handle-no-changes - If no changes detected
  • handle-conflicts - If conflicts found
  • handle-detached-head - If HEAD detached
  • After fixes, re-run diagnose-issues to verify

Operation: Handle Merge Conflicts

Detect and guide resolution of merge conflicts.

Purpose

When merge conflicts are present, provide clear detection, explanation, and step-by-step resolution guidance.

Parameters

None required - automatic detection and analysis.

Workflow

1. Detect Conflicts

Execute the conflict detector script:

/home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-error-handling/.scripts/conflict-detector.py

This will return JSON:

{
  "has_conflicts": true,
  "conflict_count": 3,
  "conflicted_files": [
    "src/auth/oauth.js",
    "src/api/users.js",
    "README.md"
  ],
  "merge_in_progress": true
}

2. Analyze Conflict Context

Determine the merge situation:

# Check merge state
git status

# View merge information
git log --merge --oneline -5

# Check which operation caused conflicts
ls -la .git/MERGE_HEAD 2>/dev/null && echo "Merge in progress"
ls -la .git/REBASE_HEAD 2>/dev/null && echo "Rebase in progress"
ls -la .git/CHERRY_PICK_HEAD 2>/dev/null && echo "Cherry-pick in progress"

3. Present Conflict Report

High-Level Overview
MERGE CONFLICTS DETECTED
━━━━━━━━━━━━━━━━━━━━━━━━━━

You have unresolved merge conflicts.

Conflict Summary:
━━━━━━━━━━━━━━━━
Conflicted files: 3
Operation: merge
Current branch: feature-branch
Merging from: main

Conflicted Files:
━━━━━━━━━━━━━━━━
1. src/auth/oauth.js
2. src/api/users.js
3. README.md

4. Provide Resolution Guidance

Step-by-Step Resolution Process
RESOLUTION STEPS
━━━━━━━━━━━━━━━━━━

Step 1: Understand Conflict Markers
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Conflicts look like this in files:

<<<<<<< HEAD (your changes)
your code here
=======
their code here
>>>>>>> branch-name (incoming changes)

Step 2: Open Each Conflicted File
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Open in your editor:
- src/auth/oauth.js
- src/api/users.js
- README.md

Step 3: Resolve Each Conflict
━━━━━━━━━━━━━━━━━━━━━━━━━━━

For each conflict, decide:

A) Keep your changes (HEAD):
   Remove markers and keep your version

B) Keep their changes:
   Remove markers and keep their version

C) Keep both (merge manually):
   Combine both versions intelligently
   Remove all conflict markers

D) Rewrite completely:
   Replace with new code that integrates both

Important: Remove ALL markers (<<<<<<, =======, >>>>>>>)

Step 4: Mark as Resolved
━━━━━━━━━━━━━━━━━━━━━━━

After editing each file:

git add src/auth/oauth.js
git add src/api/users.js
git add README.md

Step 5: Complete the Merge
━━━━━━━━━━━━━━━━━━━━━━━

After resolving all conflicts:

git commit

This will create a merge commit.
Git will suggest a merge message - accept or customize it.

Step 6: Verify Resolution
━━━━━━━━━━━━━━━━━━━━━━━

git status  # Should show no conflicts
git log --oneline -1  # See merge commit

5. Provide Abort Option

ALTERNATIVE: Abort the Merge
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

If you want to cancel and start over:

git merge --abort

This will:
- Undo the merge attempt
- Return to state before merge
- No changes will be committed

After aborting, you can:
- Prepare your branch better
- Try the merge again later
- Use a different merge strategy

6. Show Conflict Details Per File

For each conflicted file, provide analysis:

File: src/auth/oauth.js
━━━━━━━━━━━━━━━━━━━━━━━

Conflict regions: 2

Region 1 (lines 45-52):
  Your changes: Added new OAuth provider
  Their changes: Refactored existing providers
  Suggestion: Keep both, integrate new provider into refactored code

Region 2 (lines 89-94):
  Your changes: New error handling
  Their changes: Different error handling
  Suggestion: Merge both approaches, keep comprehensive handling

Quick view:
git diff src/auth/oauth.js

7. Provide Merge Tool Suggestions

MERGE TOOLS
━━━━━━━━━━━

For complex conflicts, use a merge tool:

1. Built-in tool:
   git mergetool

2. VS Code:
   code src/auth/oauth.js
   (Look for conflict highlighting)

3. Diff tool:
   git diff --merge

4. Compare with branches:
   git show :1:src/auth/oauth.js  # common ancestor
   git show :2:src/auth/oauth.js  # your version
   git show :3:src/auth/oauth.js  # their version

Error Handling

If no conflicts detected

No conflicts detected.

Checking git status...
[show git status output]

If you expected conflicts:
- Conflicts may have been auto-resolved
- Check git log for merge commits
- Run: git log --merge

If conflicts already resolved

Conflicts were already resolved.

Remaining actions:
1. Verify all changes are correct:
   git diff --cached

2. Complete the merge:
   git commit

3. Or abort if incorrect:
   git merge --abort

If in middle of rebase

Rebase in progress (not merge).

Different resolution process:

1. Resolve conflicts in files
2. Stage resolved files:
   git add <file>
3. Continue rebase:
   git rebase --continue

Or abort:
   git rebase --abort

Output Format

Always provide:

  1. Conflict summary - Count and list of files
  2. Context - What operation caused conflicts
  3. Step-by-step guidance - Clear resolution steps
  4. Per-file analysis - Specific conflict details
  5. Verification steps - How to confirm resolution
  6. Abort option - How to cancel safely

Success Indicators

After resolution:

  • No conflict markers remain in files
  • git status shows no conflicts
  • All changes are staged
  • User can complete merge commit
  • Tests still pass (if applicable)

Best Practices Guidance

CONFLICT RESOLUTION BEST PRACTICES
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

1. Don't rush - Understand both versions first
2. Test after resolving - Ensure code still works
3. Ask for help - If conflict is complex, consult team
4. Keep context - Review what both branches were trying to do
5. Document - If resolution is non-obvious, explain in commit

When in doubt:
- git merge --abort and ask for help
- Don't commit broken code
- Review changes carefully

Related Operations

  • Before resolving, run diagnose-issues for full context
  • After resolving, run commit-analysis/analyze-changes to verify
  • Use commit-best-practices/review-commit before pushing merge

Operation: Handle Detached HEAD State

Handle detached HEAD state and provide solutions.

Purpose

When git is in "detached HEAD" state, explain what this means and provide clear options for resolution.

Parameters

None required - automatic detection and guidance.

Workflow

1. Detect Detached HEAD State

Check HEAD status:

# Check if HEAD is detached
git symbolic-ref HEAD 2>/dev/null || echo "detached"

# Get current commit
git rev-parse --short HEAD

# Check if any branch points here
git branch --contains HEAD

2. Analyze Context

Determine how user got into detached HEAD:

# Check reflog for recent operations
git reflog -10

# Check recent checkouts
git reflog | grep "checkout:" | head -5

# See what branches exist
git branch -a

Common causes:

  • Checked out a specific commit SHA
  • Checked out a tag
  • During rebase or bisect operations
  • After certain git operations that move HEAD

3. Explain Detached HEAD State

Clear Explanation
DETACHED HEAD STATE
━━━━━━━━━━━━━━━━━━━

Current state:
HEAD is at: abc1234
Branch: (none - detached HEAD)

What This Means:
━━━━━━━━━━━━━━━━

You are not on any branch. You're directly on commit abc1234.

Why This Matters:
━━━━━━━━━━━━━━━━

- New commits you make won't be on any branch
- When you switch branches, these commits become hard to find
- You could lose work if you don't create a branch

This is OK for:
āœ… Viewing old commits
āœ… Testing code at a specific point
āœ… Temporary exploration

This is NOT OK for:
āŒ Making new commits you want to keep
āŒ Starting new work
āŒ Continuing development

4. Provide Resolution Options

Option A: Create New Branch Here
SOLUTION A: Create a New Branch Here
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

If you want to keep working from this commit:

1. Create and switch to new branch:
   git checkout -b new-branch-name

   OR (two steps):
   git branch new-branch-name
   git checkout new-branch-name

2. Verify:
   git status
   # Should show "On branch new-branch-name"

3. Continue working:
   Make commits as normal
   They'll be on the new branch

Example:
git checkout -b fix-issue-123
Option B: Return to a Branch
SOLUTION B: Return to Your Branch
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

If you were just exploring and want to go back:

1. Switch to your branch:
   git checkout main

   OR:
   git checkout <your-branch-name>

2. Verify:
   git status
   # Should show "On branch main"

Available branches:
[List branches from git branch -a]

Recent branch:
git checkout -  # Goes to previous branch
Option C: Attach HEAD to Existing Branch
SOLUTION C: Attach HEAD to Existing Branch
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

If a branch already points to this commit:

Current commit: abc1234
Branches at this commit:
[List from git branch --contains]

1. Check out that branch:
   git checkout <branch-name>

2. Verify:
   git branch
   # Should show * next to branch name
Option D: Keep Commits Made in Detached HEAD

If user already made commits in detached HEAD:

SOLUTION D: Preserve Commits Made in Detached HEAD
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

You made commits while in detached HEAD.

Current situation:
- HEAD at: abc1234
- Commits made: 3
- These commits are not on any branch!

To save them:

1. Create branch from current position:
   git checkout -b save-my-work

2. Verify commits are there:
   git log --oneline -5

Your commits are now safe on "save-my-work" branch.

Next steps:
- Continue work on this branch, OR
- Merge into another branch:
  git checkout main
  git merge save-my-work

5. Show Visual Diagram

VISUAL EXPLANATION
━━━━━━━━━━━━━━━━━━

Normal State (on a branch):
━━━━━━━━━━━━━━━━━━━━━━━━━

main → [commit 1] → [commit 2] → [commit 3]
                                      ↑
                                    HEAD

HEAD points to branch "main"
Branch "main" points to commit 3


Detached HEAD State:
━━━━━━━━━━━━━━━━━━━━

main → [commit 1] → [commit 2] → [commit 3]

              [commit X] ← HEAD (detached)

HEAD points directly to commit X
No branch points to commit X


Making Commits in Detached HEAD:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

main → [commit 1] → [commit 2] → [commit 3]

              [commit X] → [commit Y] ← HEAD (detached)

If you checkout main now, commit Y becomes orphaned!


Solution - Create Branch:
━━━━━━━━━━━━━━━━━━━━━━━━

main → [commit 1] → [commit 2] → [commit 3]

new-branch → [commit X] → [commit Y] ← HEAD

Now commits are safe on "new-branch"

6. Interactive Decision Support

Guide user to choose:

What would you like to do?

A) Create a new branch here and continue working
   → Choose this if you want to keep this commit as a starting point

B) Return to a branch (discard position)
   → Choose this if you were just exploring

C) Attach to an existing branch
   → Choose this if a branch already points here

D) Save commits I made while detached
   → Choose this if you already made commits

E) Not sure - need more explanation

Please respond with A, B, C, D, or E.

Error Handling

If not in detached HEAD

Not in detached HEAD state.

Current state:
Branch: main
HEAD: abc1234

You're on a normal branch. No action needed.

If during special operation

Detached HEAD during rebase.

This is temporary and expected.

Actions:
- Complete the rebase: git rebase --continue
- OR abort: git rebase --abort

After completing/aborting, HEAD will reattach automatically.

If commits will be lost

āš ļø  WARNING: Orphaned Commits Detected
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

You made 3 commits in detached HEAD:
- abc1234 "commit message 1"
- def5678 "commit message 2"
- ghi9012 "commit message 3"

If you switch branches now, these will be lost!

REQUIRED ACTION: Create a branch first
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

git checkout -b save-my-commits

Then you can safely work with these commits.

Output Format

Always provide:

  1. Clear state description - What detached HEAD means
  2. Current situation - What commit, how user got here
  3. Multiple solutions - All applicable options
  4. Visual aids - Diagrams if helpful
  5. Specific commands - Exact steps to resolve
  6. Warnings - If commits could be lost

Success Indicators

After resolution:

  • HEAD is attached to a branch
  • git branch shows current branch with *
  • git status shows "On branch "
  • User understands what happened
  • No commits were lost

Best Practices Guidance

AVOIDING DETACHED HEAD
━━━━━━━━━━━━━━━━━━━━━━

Prevention tips:

1. Use branches for work:
   git checkout -b feature-name
   (not: git checkout abc1234)

2. If checking out commits for inspection:
   Remember you're in detached HEAD
   Don't make commits you want to keep

3. If you need to work on an old commit:
   git checkout -b fix-branch abc1234
   (Creates branch at that commit)

4. Use tags for reference points:
   git tag v1.0 abc1234
   git checkout tags/v1.0
   (Still detached, but purpose is clear)

Remember:
Detached HEAD is a valid state for temporary inspection,
but always create a branch before making commits.

Related Operations

  • After resolving, run diagnose-issues to verify state
  • Before creating branches, check with history-analysis for naming conventions
  • After attaching HEAD, continue with normal commit workflow

Operation: Handle No Changes Error

Handle "nothing to commit, working tree clean" errors.

Purpose

When attempting to commit with no staged or unstaged changes, guide users to understand why and what to do next.

Parameters

None required - detection is automatic.

Workflow

1. Verify Changes Status

Execute the changes detector script:

/home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-error-handling/.scripts/changes-detector.sh

This will return JSON:

{
  "has_changes": false,
  "staged_count": 0,
  "unstaged_count": 0,
  "untracked_count": 0,
  "total_changes": 0
}

2. Analyze Git Status

Run comprehensive status check:

git status --porcelain
git status

Determine:

  • Are files modified but not saved?
  • Are all changes already committed?
  • Are changes in a different directory?
  • Are files ignored by .gitignore?

3. Provide Context-Specific Guidance

Scenario A: All Changes Already Committed
NO CHANGES TO COMMIT
━━━━━━━━━━━━━━━━━━━━

Your working tree is clean.

Current Status:
āœ… All changes are already committed
āœ… No modified files
āœ… No untracked files

This means:
- All your changes have been saved to git
- Nothing new to commit

Next Steps:
1. Make some changes to files
2. Create new files
3. Then commit again

Or if you're done:
- Push your commits: git push
- View history: git log --oneline -5
Scenario B: Files Modified But Not Saved
NO CHANGES TO COMMIT
━━━━━━━━━━━━━━━━━━━━

Possible Reason: Files Not Saved
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Git sees no changes because:
- You edited files but didn't save them
- Changes are in your editor buffer

Actions:
1. Save all files in your editor (Ctrl+S or Cmd+S)
2. Check git status again:
   git status
3. If files appear, stage and commit:
   git add .
   git commit
Scenario C: Wrong Directory
NO CHANGES TO COMMIT
━━━━━━━━━━━━━━━━━━━━

Possible Reason: Wrong Directory
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Current directory: /path/to/current
Changes might be elsewhere.

Actions:
1. Verify you're in the right place:
   pwd
   ls

2. Navigate to project root:
   cd /path/to/project

3. Check status there:
   git status
Scenario D: Files Ignored
NO CHANGES TO COMMIT
━━━━━━━━━━━━━━━━━━━━

Possible Reason: Files Ignored by .gitignore
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Git might be ignoring your files.

Check:
1. View ignored patterns:
   cat .gitignore

2. Check if file is ignored:
   git check-ignore -v <filename>

3. Force add ignored files (if needed):
   git add -f <filename>

Note: Be careful adding ignored files - they're usually
ignored for good reason (node_modules, .env, etc.)

4. Detect Edge Cases

Check for:

  • Unstaged changes in subdirectories

    git status --porcelain
    
  • Changes to ignored files only

    git status --ignored
    
  • Accidentally reset changes

    git reflog -5
    

5. Interactive Verification

Guide user to verify:

Let's verify your changes:

1. List all files in directory:
   ls -la

2. Check git status:
   git status

3. Check recent history:
   git log --oneline -3

Do you see the files you expected to commit?

Error Handling

If git status fails

Unable to check git status.
Ensure you're in a git repository.
Run: /commit-error-handling handle-no-repo

If permissions issues

Permission denied reading files.
Check file permissions: ls -la

Output Format

Always provide:

  1. Clear status - What git sees
  2. Explanation - Why there are no changes
  3. Likely causes - Ordered by probability
  4. Specific actions - Commands to verify/fix
  5. Next steps - What to do after resolution

Success Indicators

After user follows guidance:

  • User understands why there were no changes
  • Changes appear in git status
  • User can proceed with commit
  • Or user understands work is already committed

Related Operations

  • Run diagnose-issues for comprehensive check
  • After making changes, verify with commit-analysis/analyze-changes

Operation: Handle No Repository Error

Detect and resolve "not a git repository" errors.

Purpose

When git commands fail with fatal: not a git repository (or any of the parent directories): .git, guide users to resolve the issue.

Parameters

None required - detection is automatic.

Workflow

1. Verify Repository Status

Execute the repository checker script:

/home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-error-handling/.scripts/repo-checker.sh

This will return JSON:

{
  "is_repo": false,
  "git_dir": null,
  "error": "not a git repository"
}

2. Analyze Context

Check the current directory:

pwd
ls -la

Determine if:

  • User is in the wrong directory
  • Repository was never initialized
  • .git directory was deleted
  • User needs to clone a repository

3. Provide Solutions

Present clear, actionable solutions based on the scenario:

Scenario A: Need to Initialize New Repository
ERROR: Not a Git Repository
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Current directory: /path/to/directory
This is not a git repository.

SOLUTION 1: Initialize a New Repository
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

If you want to start version control here:

1. Initialize git:
   git init

2. Add files:
   git add .

3. Create first commit:
   git commit -m "Initial commit"

4. (Optional) Connect to remote:
   git remote add origin <url>
   git push -u origin main
Scenario B: Wrong Directory
SOLUTION 2: Navigate to Your Repository
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

If your git repository is elsewhere:

1. Find your repository:
   find ~ -type d -name ".git" 2>/dev/null

2. Navigate to it:
   cd /path/to/your/repo

3. Try your command again
Scenario C: Clone Existing Repository
SOLUTION 3: Clone an Existing Repository
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

If you need to clone a remote repository:

1. Clone the repository:
   git clone <repository-url>

2. Navigate into it:
   cd <repository-name>

3. Verify:
   git status

4. Interactive Guidance

If context is unclear, ask clarifying questions:

What would you like to do?

A) Initialize a new git repository here
B) Navigate to an existing repository
C) Clone a repository from a URL
D) Not sure, need more help

Please respond with A, B, C, or D.

Error Handling

If pwd fails

Unable to determine current directory.
Please manually navigate to your git repository.

If user has no permissions

Permission denied: Cannot initialize repository here.
Try a directory where you have write permissions.

Output Format

Always provide:

  1. Clear error description - What's wrong
  2. Context - Current directory and state
  3. Multiple solutions - Ordered by likelihood
  4. Specific commands - Copy-pasteable
  5. Next steps - What to do after resolution

Success Indicators

After user follows guidance:

  • git status works without errors
  • User can proceed with git operations
  • .git directory exists and is valid

Related Operations

  • After resolution, run diagnose-issues to verify full repository health
  • Before committing, run handle-no-changes to ensure there are changes

Git Commit Error Handling

You are a git error diagnosis and resolution specialist. Your role is to detect, diagnose, and provide clear guidance for resolving common git issues that prevent successful commits.

Operation Router

Parse the operation from $ARGUMENTS and route to the appropriate handler:

Available Operations:

  1. handle-no-repo - Not a git repository error

    • Usage: handle-no-repo
    • Detects and resolves "not a git repository" errors
  2. handle-no-changes - Working tree clean error

    • Usage: handle-no-changes
    • Handles "nothing to commit, working tree clean" errors
  3. handle-conflicts - Merge conflicts present

    • Usage: handle-conflicts
    • Detects and guides resolution of merge conflicts
  4. handle-detached-head - Detached HEAD state

    • Usage: handle-detached-head
    • Handles detached HEAD state and provides solutions
  5. diagnose-issues - Comprehensive git issue diagnosis

    • Usage: diagnose-issues
    • Runs all checks and provides complete diagnosis

Routing Logic

Extract first word from $ARGUMENTS as operation

IF operation = "handle-no-repo":
    Read .claude/commands/commit-error-handling/handle-no-repo.md
    Execute instructions

ELSE IF operation = "handle-no-changes":
    Read .claude/commands/commit-error-handling/handle-no-changes.md
    Execute instructions

ELSE IF operation = "handle-conflicts":
    Read .claude/commands/commit-error-handling/handle-conflicts.md
    Execute instructions

ELSE IF operation = "handle-detached-head":
    Read .claude/commands/commit-error-handling/handle-detached-head.md
    Execute instructions

ELSE IF operation = "diagnose-issues":
    Read .claude/commands/commit-error-handling/diagnose-issues.md
    Execute instructions

ELSE:
    Show error:
    "Unknown operation: {operation}

    Available operations:
    - handle-no-repo
    - handle-no-changes
    - handle-conflicts
    - handle-detached-head
    - diagnose-issues

    Usage: /commit-error-handling <operation>"

Error Handling Philosophy

  1. Detect Early - Identify issues before attempting operations
  2. Clear Messages - Explain what's wrong in plain language
  3. Actionable Solutions - Provide specific commands to fix
  4. Safe Guidance - Never suggest destructive operations without warnings
  5. Educational - Help users understand the underlying issue

Integration Points

This skill is typically invoked:

  • Before commit operations - Validate repository state
  • On commit failures - Diagnose why commit failed
  • Interactive guidance - Help users resolve git issues
  • Agent workflows - Automated error detection and recovery

Base Directory

All operation files are located in: .claude/commands/commit-error-handling/

Request

Process: $ARGUMENTS

Commit Review - Analyze Changes for Atomic Commits

Review your staged or unstaged changes and receive recommendations on whether to create a single commit or split into multiple atomic commits.

Overview

The /commit-review command provides comprehensive change analysis by orchestrating multiple analytical skills to determine whether your changes should be committed as one atomic commit or split into multiple focused commits.

Skills Orchestrated

This command coordinates:

  1. commit-error-handling - Repository state validation

    • Operation: /commit-error-handling diagnose-issues
    • Ensures repository is ready for analysis
  2. commit-analysis - Multi-dimensional change analysis

    • Operation: /commit-analysis analyze
    • Detects: types, scopes, file changes, atomicity
    • Provides: Comprehensive change breakdown
  3. atomic-commit - Splitting analysis

    • Operations:
      • /atomic-commit analyze - Determine if should split
      • /atomic-commit group strategy:type - Group files by type
      • /atomic-commit suggest - Generate commit breakdown
    • Provides: Detailed splitting recommendations
  4. message-generation - Preview commit messages

    • Operation: /message-generation complete
    • Generates: Suggested messages for each commit group
  5. history-analysis (optional) - Project convention awareness

    • Operation: /history-analysis analyze-style
    • Ensures: Recommendations match project style

Workflow Integration

After /commit-review shows recommendations:

If single commit recommended: → Use /commit to create the commit

If split recommended: → Use /commit-split for interactive splitting → OR use /atomic-commit interactive for granular control → OR manually commit each group

For Granular Control

Analyze specific aspects independently:

  • /commit-analysis detect-type - Just classify change types
  • /commit-analysis assess-atomicity - Just check atomicity
  • /atomic-commit group - Just group files
  • /atomic-commit suggest - Just get commit suggestions

Usage

/commit-review              # Review all changes (staged and unstaged)

What is an Atomic Commit?

An atomic commit is a single, focused commit that:

  • Contains one logical change
  • Can be reverted independently without breaking other functionality
  • Has all tests passing after the commit
  • Is self-contained and complete
  • Has a clear, single purpose

Good Atomic Commits:

  • Add authentication feature (all auth files together)
  • Fix login bug (only the fix, not other changes)
  • Update dependencies (package updates together)

Bad Non-Atomic Commits:

  • Add feature + fix unrelated bug + update docs
  • Refactor + add new functionality
  • Mix of formatting changes and logic changes

Complete Analysis Workflow

User: /commit-review
         ↓
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │ 1. Validate Repository         │
    │ /commit-error-handling         │
    │ diagnose-issues                │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                 ↓
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │ 2. Analyze All Changes         │
    │ /commit-analysis analyze       │
    │ - Detect types                 │
    │ - Identify scopes              │
    │ - Count files/lines            │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                 ↓
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │ 3. Assess Atomicity            │
    │ /atomic-commit analyze         │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                 ↓
           ā”Œā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”
           │ Should     │
           │ Split?     │
           ā””ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                 │
        ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
        │                 │
       YES               NO
        ↓                 ↓
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ 4a. Group     │  │ 4b. Recommend    │
│ Files         │  │ Single Commit    │
│ /atomic-      │  │                  │
│ commit group  │  │ → Use /commit    │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
        ↓
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ 5a. Generate      │
│ Suggestions       │
│ /atomic-commit    │
│ suggest           │
│                   │
│ For each group:   │
│ /message-         │
│ generation        │
│ complete          │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
          ↓
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ 6a. Present Plan            │
│ - Commit breakdown          │
│ - Suggested messages        │
│ - File groups               │
│                             │
│ → Use /commit-split         │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Process

Step 1: Repository Validation

Orchestrates: /commit-error-handling diagnose-issues

Before analyzing changes, verify:

  • Valid git repository
  • Changes present (staged or unstaged)
  • No merge conflicts blocking analysis
  • Repository not in problematic state

This prevents analysis of invalid states.

For detailed diagnostics: /commit-error-handling diagnose-issues

git rev-parse --git-dir 2>/dev/null
git status --short

If not a git repo, show error and exit.

Step 2: Analyze All Changes

Orchestrates: /commit-analysis analyze

Performs multi-dimensional analysis:

File-Level Analysis:

  • Type detection (feat, fix, docs, refactor, test, chore, style, perf, ci)
  • Scope identification (auth, api, ui, database, etc.)
  • Line change statistics (+/- counts)

Change-Level Analysis:

  • Total files modified
  • Insertions and deletions
  • Change complexity assessment

Atomicity Assessment:

  • Single concern vs. multiple concerns
  • Related vs. unrelated changes
  • Interdependencies between files

Grouping Strategy:

  • Type-based grouping (all feat together)
  • Scope-based grouping (all auth together)
  • Feature-based grouping (implementation + tests)

Check both staged and unstaged changes:

# Get status
git status --short

# Get staged changes
git diff --cached --stat
git diff --cached

# Get unstaged changes
git diff --stat
git diff

# Count files by status
git status --short | wc -l

Type Detection Rules:

Analyze the diff output to categorize each file by its primary change type:

  1. feat (New Feature):

    • New files being added
    • New functions/classes/exports
    • New functionality in existing files
    • Look for: export function, export class, export const, new files
  2. fix (Bug Fix):

    • Error handling additions
    • Null/undefined checks
    • Validation fixes
    • Look for: if (!, try/catch, throw, error, null, undefined
  3. refactor (Code Restructuring):

    • Variable/function renaming
    • Code extraction or reorganization
    • Look for: similar logic moved, renamed identifiers
  4. docs (Documentation):

    • README.md changes, documentation files (*.md), JSDoc additions
    • Look for: file extensions .md, comment blocks
  5. style (Formatting):

    • Whitespace changes only, indentation fixes
    • Look for: only whitespace diffs, no logic changes
  6. test (Tests):

    • Test file changes (*.test.js, *.spec.js, *_test.py)
    • Look for: test(, describe(, it(, expect(, file patterns
  7. chore (Build/Config):

    • package.json dependencies, build configuration
    • Look for: package.json, *.config.js, .github/workflows
  8. perf (Performance):

    • Optimization changes, caching implementations
    • Look for: cache, memoize, performance-related comments
  9. ci (CI/CD):

    • GitHub Actions workflows, GitLab CI configs
    • Look for: .github/workflows, .gitlab-ci.yml

For granular analysis:

  • /commit-analysis detect-type file:path - Type for specific file
  • /commit-analysis identify-scope file:path - Scope for specific file
  • /commit-analysis file-stats - Just statistics

Step 3: Determine Split Strategy

Orchestrates: /atomic-commit analyze

Evaluates whether changes should be split:

Split Criteria:

  • Multiple types present (feat + fix + docs)
  • Multiple scopes (auth + api + ui)
  • Too many files (10+ of different types)
  • Mixed concerns (feature + unrelated refactor)

Keep Together Criteria:

  • Single type and scope
  • All files serve same purpose
  • Changes are interdependent
  • Reasonable file count (≤10)

Atomicity Scoring:

  • atomic=true (single commit) → Proceed to /commit
  • atomic=false (split needed) → Continue to grouping

For direct splitting analysis: /atomic-commit analyze

Step 4: Group Related Files

Orchestrates: /atomic-commit group strategy:type

Groups files into logical commit groups:

Grouping Strategies:

  1. Type-Based (default):

    • feat files → Commit 1
    • fix files → Commit 2
    • docs files → Commit 3
    • test files → Commit 4
  2. Scope-Based:

    • auth files → Commit 1
    • api files → Commit 2
    • ui files → Commit 3
  3. Feature-Based:

    • Implementation + Tests → Commit 1
    • Documentation → Commit 2

Create a mapping of files to their change types:

feat:
  - src/auth/oauth.js
  - src/auth/providers.js
  - src/auth/middleware.js

test:
  - tests/auth.test.js
  - tests/oauth.test.js

docs:
  - README.md

refactor:
  - src/utils.js
  - src/helpers.js

For custom grouping:

  • /atomic-commit group strategy:scope - Group by module
  • /atomic-commit group strategy:feature - Group by feature

Step 5: Generate Commit Recommendations

Orchestrates:

  • /atomic-commit suggest - Create commit breakdown
  • /message-generation complete (for each group) - Generate messages

For each group, generates:

  • Commit message: Conventional commits format
  • File list: All files in the group
  • Change summary: What the commit does
  • Line statistics: Insertions/deletions

Message Generation Uses:

  • Detected type (feat, fix, etc.)
  • Identified scope (auth, api, etc.)
  • Change analysis (what was actually done)
  • Project conventions (from history-analysis)

For custom messages:

  • /message-generation subject - Just subject line
  • /message-generation validate - Check message format

Step 6: Present Analysis Results

Analysis Output Format

Split Recommendation

When multiple concerns are detected:

COMMIT REVIEW ANALYSIS
═══════════════════════════════════════════════
Data from: /commit-analysis analyze
           /atomic-commit analyze

RECOMMENDATION: SPLIT INTO ATOMIC COMMITS

Your changes cover multiple concerns:
 ⚠ Multiple types: feat, test, refactor, docs
 ⚠ Multiple scopes or unrelated changes
 ⚠ Better split for clear history

──────────────────────────────────────────────
CURRENT CHANGES SUMMARY:
Data from: /commit-analysis analyze
────────────────────────────────────────────
Total Files: 12
Insertions: 847 (+)
Deletions: 234 (-)

CHANGE TYPE BREAKDOWN:
────────────────────────────────────────────
FEAT (5 files) - New authentication system
  M src/auth/oauth.js (+156 lines)
  M src/auth/providers.js (+89 lines)
  M src/auth/middleware.js (+73 lines)
  M src/auth/config.js (+45 lines)
  M src/auth/index.js (+23 lines)

TEST (2 files) - Authentication tests
  M tests/auth.test.js (+142 lines)
  M tests/oauth.test.js (+98 lines)

REFACTOR (3 files) - Code cleanup
  M src/utils.js (+45 -67 lines)
  M src/helpers.js (+34 -52 lines)
  M src/validators.js (+12 -8 lines)

DOCS (2 files) - Documentation updates
  M README.md (+156 -42 lines)
  M docs/authentication.md (+74 lines)

──────────────────────────────────────────────
SPLITTING PLAN
Generated by: /atomic-commit suggest
Messages from: /message-generation complete

Commit 1 (feat): 5 files, 386 lines
  feat(auth): implement OAuth authentication system

  - Add OAuth2 authentication flow
  - Implement provider support for Google and GitHub
  - Add authentication middleware
  - Include configuration management

  Files:
    src/auth/oauth.js
    src/auth/providers.js
    src/auth/middleware.js
    src/auth/config.js
    src/auth/index.js

────────────────────────────────────────────

Commit 2 (test): 2 files, 240 lines
  test(auth): add comprehensive OAuth authentication tests

  - Add unit tests for OAuth flow
  - Add integration tests for providers
  - Achieve 95% coverage for auth module

  Files:
    tests/auth.test.js
    tests/oauth.test.js

────────────────────────────────────────────

Commit 3 (refactor): 3 files, 24 lines
  refactor: simplify utility functions and improve validation

  - Simplify date/time utilities
  - Improve helper function clarity
  - Enhance validator logic

  Files:
    src/utils.js
    src/helpers.js
    src/validators.js

────────────────────────────────────────────

Commit 4 (docs): 2 files, 188 lines
  docs: add OAuth authentication guide

  - Update README with authentication setup
  - Add detailed authentication documentation
  - Include usage examples

  Files:
    README.md
    docs/authentication.md

──────────────────────────────────────────────

NEXT STEPS:
→ Interactive splitting: /commit-split
→ Granular control: /atomic-commit interactive
→ Manual commits: Use /commit for each group

WHY SPLIT COMMITS?
Atomic commits provide:
 āœ“ Better history browsing (each commit tells a story)
 āœ“ Easier code review (reviewers see logical changes)
 āœ“ Safer reverts (revert one feature without breaking others)
 āœ“ Clearer blame/annotate (understand why changes were made)
 āœ“ Better bisecting (find bugs by commit)
═══════════════════════════════════════════════

Single Commit Recommendation

When changes form a cohesive unit:

COMMIT REVIEW ANALYSIS
═══════════════════════════════════════════════
Data from: /commit-analysis analyze

RECOMMENDATION: SINGLE ATOMIC COMMIT āœ“

Your changes form a cohesive unit:
 āœ“ Single type: feat
 āœ“ Single scope: auth
 āœ“ Logical unit: OAuth authentication
 āœ“ Reasonable size: 5 files, 386 lines

──────────────────────────────────────────────
CURRENT CHANGES SUMMARY:
Data from: /commit-analysis analyze
────────────────────────────────────────────
Total Files: 5
Insertions: 386 (+)
Deletions: 0 (-)

CHANGE TYPE BREAKDOWN:
────────────────────────────────────────────
FEAT (5 files) - Complete authentication feature
  M src/auth/oauth.js
  M src/auth/providers.js
  M src/auth/middleware.js
  M src/auth/config.js
  M src/auth/index.js

──────────────────────────────────────────────
SUGGESTED COMMIT MESSAGE
Generated by: /message-generation complete

feat(auth): implement OAuth authentication system

- Add OAuth2 authentication flow
- Implement provider support for Google and GitHub
- Add authentication middleware
- Include configuration management
──────────────────────────────────────────────

ATOMICITY CHECK: PASSED
 āœ“ All files relate to a single feature (auth)
 āœ“ Changes are cohesive and interdependent
 āœ“ Single commit tells a clear story
 āœ“ Can be reverted as a complete unit

NEXT STEPS:
→ Create commit: /commit
→ Pre-validate: /commit-best-practices check-pre-commit
═══════════════════════════════════════════════

Error Handling

Not a git repository:

ERROR: Not a git repository
Run: git init

No changes to review:

NO CHANGES TO REVIEW

Your working tree is clean.
Make some changes, then run /commit-review again.

All changes already committed:

ALL CHANGES COMMITTED

Great job! Your working tree is clean.
Run git log to see your commits.

Tips for Atomic Commits

DO:

  • Group related changes together
  • Keep features separate from fixes
  • Keep refactoring separate from new features
  • Include tests with the code they test (optional)
  • Make each commit independently buildable

DON'T:

  • Mix formatting changes with logic changes
  • Combine multiple features in one commit
  • Include unrelated bug fixes with features
  • Make "WIP" or "misc changes" commits
  • Bundle everything at the end of the day

Examples

Example 1: Mixed changes (needs splitting)

/commit-review
# Shows: feat (3 files), fix (2 files), docs (1 file)
# Recommends: Split into 3 commits
# Next: /commit-split

Example 2: Clean atomic change

/commit-review
# Shows: fix (2 files) - all related to login bug
# Recommends: Single commit is appropriate
# Next: /commit

Example 3: Large feature

/commit-review
# Shows: feat (15 files) - authentication system
# Recommends: Consider splitting by module/component
# Next: /commit-split or careful manual commits

Related Skills and Commands

Analytical Skills Used

  • commit-analysis: /commit-analysis - Detailed change analysis

    • Operations: analyze, detect-type, identify-scope, assess-atomicity, file-stats
    • Purpose: Multi-dimensional change analysis and type/scope detection
  • atomic-commit: /atomic-commit - Splitting analysis and grouping

    • Operations: analyze, group, suggest, sequence, interactive
    • Purpose: Determine if changes should split and generate commit groups
  • history-analysis: /history-analysis - Project convention analysis

    • Operations: analyze-style, recent-patterns, common-scopes
    • Purpose: Learn project conventions to inform recommendations

Execution Skills Referenced

  • message-generation: /message-generation - Message creation

    • Operations: complete, subject, body, validate
    • Purpose: Generate conventional commit messages for each group
  • commit-best-practices: /commit-best-practices - Validation

    • Operations: check-pre-commit, workflow-tips, validate-message
    • Purpose: Ensure commits follow best practices
  • commit-error-handling: /commit-error-handling - Error diagnosis

    • Operations: diagnose-issues, recover, clean-state
    • Purpose: Validate repository state before analysis

Related Commands

  • /commit - Create single atomic commit

    • Use when: Review recommends single commit
    • Purpose: Execute the commit with generated message
  • /commit-split - Interactively split into atomic commits

    • Use when: Review recommends splitting
    • Purpose: Interactive file-by-file commit creation

Workflow Paths

/commit-review (analysis)
    ↓
    ā”œā”€ Single commit? → /commit (execution)
    │
    └─ Multiple commits? → /commit-split (execution)
                        OR /atomic-commit interactive (granular control)

For Power Users

Access granular operations directly:

Analysis Only:

  • /commit-analysis detect-type - Classify file types
  • /commit-analysis identify-scope - Extract scopes
  • /commit-analysis assess-atomicity - Check if should split

Grouping Only:

  • /atomic-commit group strategy:type - Group by type
  • /atomic-commit group strategy:scope - Group by scope
  • /atomic-commit group strategy:feature - Group by feature

Message Generation Only:

  • /message-generation complete - Generate full message
  • /message-generation subject - Just subject line
  • /message-generation validate message:"text" - Validate format

Documentation References

  • Atomic Commits Guide: See /commit-best-practices workflow-tips
  • Skill Architecture: See .claude/docs/SKILL_ARCHITECTURE.md
  • Agent Reference: See agents/commit-assistant.md
  • Command List: See plugin README.md for all available commands

Commit Split - Interactive Atomic Commit Creation

Overview

The /commit-split command provides an interactive workflow that orchestrates multiple skills to help you split large commits into focused, atomic commits. Each atomic commit represents one logical change that can be independently reviewed, tested, and reverted.

Skills Orchestrated

This command coordinates a complete execution workflow:

  1. commit-error-handling - Pre-flight validation

    • Operation: /commit-error-handling diagnose-issues
    • Ensures: Repository ready for splitting
  2. commit-analysis - Change understanding

    • Operation: /commit-analysis analyze
    • Provides: Type, scope, and file analysis for grouping
  3. atomic-commit - Core splitting logic (PRIMARY)

    • Operation: /atomic-commit interactive
    • Provides: File grouping, suggestions, sequence generation
    • This skill contains the core splitting algorithms
  4. message-generation - Message creation

    • Operation: /message-generation complete (per commit)
    • Generates: Conventional commit message for each group
  5. commit-best-practices - Quality assurance

    • Operation: /commit-best-practices check-pre-commit (optional)
    • Operation: /commit-best-practices review-commit (after each)
    • Validates: Tests pass, quality maintained
  6. history-analysis - Project awareness

    • Operation: /history-analysis analyze-style (cached)
    • Ensures: Messages match project conventions

Interactive Workflow

The /commit-split command provides a guided experience:

1. Analyze changes → Show plan
2. Group files → Present groups
3. For each group:
   - Show files and changes
   - Generate message
   - Get user approval
   - Create commit
   - Review quality
4. Final summary

Alternative Workflows

For more control:

  • /atomic-commit interactive - Same workflow, skill-level access
  • /atomic-commit sequence - Generate script to execute
  • Manual: Use /commit for each group after reviewing

For just analysis:

  • /commit-review - Analysis without execution
  • /atomic-commit suggest - Get suggestions only

Usage

/commit-split               # Start interactive commit splitting

What This Does

This command helps you:

  1. Validate repository state and analyze all changes
  2. Group related files by change type and scope
  3. Generate conventional commit messages for each group
  4. Create multiple focused commits interactively
  5. Ensure each commit is atomic and well-documented

Complete Interactive Workflow

User: /commit-split
         ↓
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ Pre-Flight & Analysis           │
│ /commit-error-handling          │
│ /commit-analysis                │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
             ↓
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ Generate Splitting Plan         │
│ /atomic-commit suggest          │
│   → groups files                │
│   → calls /message-generation   │
│       for each group            │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
             ↓
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ Present Plan & Confirm          │
│ User reviews:                   │
│ - N commits                     │
│ - Files in each                 │
│ - Suggested messages            │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
             ↓
             ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
             │ Ready? │
             ā””ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”˜
                 │
          ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”
         NO            YES
          ↓              ↓
      [Abort]    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
                 │ For Each     │
                 │ Group (1-N)  │
                 ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                        ↓
          ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
          │ Show Group Details          │
          │ - Files                     │
          │ - Message                   │
          │ - Changes                   │
          ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                     ↓
          ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
          │ Get User Action             │
          │ 1. Create                   │
          │ 2. Edit                     │
          │ 3. Skip                     │
          │ 4. Abort                    │
          ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                     ↓
              ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”
         Create          Skip/Abort
              ↓              ↓
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”    │
    │ Pre-Commit Check │    │
    │ (optional)       │    │
    │ /commit-best-    │    │
    │ practices        │    │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜    │
             ↓              │
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”    │
    │ git add <files>  │    │
    │ git commit -m "" │    │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜    │
             ↓              │
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”    │
    │ Post-Commit      │    │
    │ Review           │    │
    │ /commit-best-    │    │
    │ practices        │    │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜    │
             ↓              │
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”    │
    │ Show Progress    │    │
    │ Continue?        │    │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜    │
             │              │
             ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                     ↓
          ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
          │ Final Summary               │
          │ - List commits created      │
          │ - Quality scores            │
          │ - Remaining changes         │
          │ - Verification commands     │
          ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Process

Step 1: Validate Repository and Analyze Changes

Orchestrates:

  1. /commit-error-handling diagnose-issues - Validate state
  2. /commit-analysis analyze - Understand changes

Pre-Flight Checks:

# Verify git repository
git rev-parse --git-dir 2>/dev/null

If not a git repo, show error and exit.

Change Analysis:

# Get all changes
git status --short

# Get detailed diff
git diff HEAD

# Count changes
git status --short | wc -l

Analysis Output:

  • Total files and line changes
  • Type detection for each file
  • Scope identification
  • Initial grouping strategy

This provides the data for intelligent splitting.

Direct access:

  • /commit-error-handling diagnose-issues - Just validation
  • /commit-analysis analyze - Just analysis

If no changes, show message and exit.

Step 2: Generate Splitting Plan

Orchestrates: /atomic-commit suggest

This operation:

  1. Groups related files:

    • Strategy: Type-based (feat, fix, docs, test)
    • Alternative strategies: scope-based, feature-based
  2. Generates commit messages for each group:

    • Uses: /message-generation complete
    • Format: Conventional commits
    • Style: Matches project conventions (from /history-analysis)
  3. Creates execution plan:

    • Commit order (dependencies respected)
    • File → commit mapping
    • Estimated changes per commit

Plan Structure:

Group 1: feat(auth) - 5 files, +386 lines
  feat(auth): implement OAuth authentication system

Group 2: test(auth) - 2 files, +240 lines
  test(auth): add comprehensive OAuth tests

Group 3: docs - 1 file, +128 lines
  docs: add OAuth authentication guide

Direct access:

  • /atomic-commit group - Just grouping
  • /atomic-commit suggest - Suggestions only
  • /atomic-commit sequence - Executable script

Step 3: Present Splitting Plan

Shows the complete plan generated by skill orchestration:

INTERACTIVE COMMIT SPLITTING
═════════════════════════════════════════════

I've analyzed your changes and identified 4 logical
commits to create. I'll guide you through each one.

SPLITTING PLAN:
────────────────────────────────────────────

šŸ“¦ Commit 1: Authentication Feature
   Type: feat(auth)
   Files: 5 files
   Lines: +386 -0

šŸ“¦ Commit 2: Authentication Tests
   Type: test(auth)
   Files: 2 files
   Lines: +240 -0

šŸ“¦ Commit 3: Utility Refactoring
   Type: refactor
   Files: 2 files
   Lines: +79 -119

šŸ“¦ Commit 4: Documentation Updates
   Type: docs
   Files: 2 files
   Lines: +230 -42

════════════════════════════════════════════

Let's create these commits one by one.
You'll review each before it's created.

Ready to start? (y/n)

User reviews and confirms before any commits are created.

This transparency allows users to understand the splitting strategy before execution.

Step 4: Create Commits Iteratively

For each commit group, orchestrates:

Per-Commit Workflow:

For each group (1 to N):
  ↓
  1. Show group details
  2. Present generated message
     (from /message-generation complete)
  ↓
  3. Get user action:
     - Create with message
     - Edit message
     - Skip group
     - Abort
  ↓
  4. If creating:
     a. Stage files: git add <files>
     b. Validate (optional):
        /commit-best-practices check-pre-commit
     c. Create commit: git commit -m "message"
     d. Review quality:
        /commit-best-practices review-commit
  ↓
  5. Show progress
  6. Continue to next group

User Control Points:

  • Review each commit before creation
  • Edit any generated message
  • Skip groups to commit separately
  • Abort if plan needs adjustment

Quality Assurance (optional, configurable):

  • Pre-commit checks before each commit
  • Post-commit review after each commit
  • Rollback guidance if issues found
Detailed Commit Creation Loop

For each group:

  1. Show Group Details
═══════════════════════════════════════════
COMMIT 1 of 4: Authentication Feature
═══════════════════════════════════════════

FILES TO COMMIT (5 files):
────────────────────────────────────────────
 M src/auth/oauth.js                  +156
 M src/auth/providers.js              +89
 M src/auth/middleware.js             +73
 M src/auth/config.js                 +45
 M src/auth/index.js                  +23

CHANGES SUMMARY:
────────────────────────────────────────────
- Implements OAuth2 authentication flow
- Adds provider support (Google, GitHub)
- Includes authentication middleware
- Adds configuration management
- Exports unified auth interface

PROPOSED COMMIT MESSAGE:
────────────────────────────────────────────
feat(auth): implement OAuth authentication system

- Add OAuth2 authentication flow
- Implement provider support for Google and GitHub
- Add authentication middleware
- Include configuration management

════════════════════════════════════════════

What would you like to do?

1. Create commit with this message (recommended)
2. Edit the message
3. Skip this group
4. Abort splitting

Enter choice (1/2/3/4):
  1. Handle User Choice

Choice 1: Create commit

# Stage only the files in this group
git add src/auth/oauth.js src/auth/providers.js src/auth/middleware.js src/auth/config.js src/auth/index.js

# Create the commit
git commit -m "feat(auth): implement OAuth authentication system

- Add OAuth2 authentication flow
- Implement provider support for Google and GitHub
- Add authentication middleware
- Include configuration management"

# Show success
echo "āœ… Commit 1 created successfully"
git log -1 --oneline

Choice 2: Edit message Prompt user for new message:

Enter your commit message:
(Use conventional commits format: <type>(<scope>): <subject>)

> _

Then create commit with user's message.

Choice 3: Skip Skip this group, move to next.

Choice 4: Abort Exit without creating any more commits. Already created commits remain.

  1. Show Progress

After each commit:

PROGRESS: 1 of 4 commits created

āœ… Commit 1: feat(auth) - abc1234

Remaining commits:
 šŸ“¦ Commit 2: test(auth) - 2 files
 šŸ“¦ Commit 3: refactor - 2 files
 šŸ“¦ Commit 4: docs - 2 files

Continue to next commit? (y/n)

Step 5: Complete and Verify

After all commits created:

Final Validation:

  • List all created commits
  • Show remaining uncommitted changes (if any)
  • Provide git commands to verify:
    • git log --oneline -N
    • git log -p -N

Quality Report: For each commit created:

  • Commit hash
  • Message
  • Quality score (from /commit-best-practices review-commit)

Next Steps Guidance:

  • Run full test suite
  • Push commits
  • Create pull request
  • Use /commit-best-practices revert-guidance if needed

Final Summary Display:

═══════════════════════════════════════════
COMMIT SPLITTING COMPLETE
═══════════════════════════════════════════

CREATED COMMITS:
────────────────────────────────────────────
āœ… abc1234 - feat(auth): implement OAuth authentication system
āœ… def5678 - test(auth): add comprehensive OAuth tests
āœ… ghi9012 - refactor: simplify utility functions
āœ… jkl3456 - docs: add OAuth authentication guide

SUMMARY:
────────────────────────────────────────────
Total commits created: 4
Files committed: 12
Remaining changes: 0

═══════════════════════════════════════════

VERIFY YOUR COMMITS:
────────────────────────────────────────────
git log --oneline -4
git log -p -4

NEXT STEPS:
────────────────────────────────────────────
āœ“ Run tests to verify everything works
āœ“ Push commits: git push
āœ“ Create pull request if needed

═══════════════════════════════════════════

Great job creating atomic commits!
Your git history is now clean and logical.

Alternative: If Skipped Groups

If user skipped some groups, show remaining files:

REMAINING UNCOMMITTED CHANGES:
────────────────────────────────────────────
 M src/utils.js
 M README.md

These files were skipped during splitting.
Run /commit to commit them, or /commit-split to try again.

Smart Grouping Strategies

The /atomic-commit skill implements multiple grouping strategies:

Strategy 1: Type-Based Grouping

Group by change type first:

  • All feat changes together (if same scope)
  • All fix changes together
  • All refactor changes together
  • All docs changes together
  • All test changes together

Strategy 2: Scope-Based Grouping

Group by module/component:

  • All auth changes together
  • All api changes together
  • All ui changes together

Strategy 3: Feature-Based Grouping

Group by feature completion:

  • Implementation + Tests together
  • Feature code + Documentation together

Recommendation: Use Type-Based for most cases, Scope-Based for large features.

Direct access: /atomic-commit group strategy:<type|scope|feature>

Commit Message Generation

For each group, the /message-generation skill generates a message:

Template:

<type>(<scope>): <subject>

<body>

Subject Generation:

  • Analyze primary change in the files
  • Use active voice, imperative mood
  • Keep under 50 characters
  • Example: "implement OAuth authentication system"

Body Generation (bullet points):

  • List major changes in the group
  • Keep bullets concise (under 72 chars)
  • Focus on what and why, not how
  • Example:
    - Add OAuth2 authentication flow
    - Implement provider support for Google and GitHub
    - Include authentication middleware
    

Direct access: /message-generation complete files:"<files>" type:<type> scope:<scope>

Edge Cases

Case 1: Single File, Multiple Concerns

If one file has multiple unrelated changes:

WARNING: Complex Changes Detected
────────────────────────────────────────────
File: src/app.js

This file contains multiple types of changes:
- New feature: OAuth integration
- Bug fix: Memory leak fix
- Refactor: Code cleanup

RECOMMENDATION:
Use git add -p to stage changes interactively,
or manually split the file changes.

Cannot automatically split this file.

Case 2: Interdependent Changes

If changes must stay together:

NOTE: Interdependent Changes
────────────────────────────────────────────
These files must be committed together:
- src/auth/oauth.js (defines function)
- src/auth/index.js (exports function)

Keeping them in the same commit: Commit 1

Case 3: Very Large Number of Files

If 20+ files:

LARGE CHANGE SET DETECTED
────────────────────────────────────────────
You have 47 files changed.

This is a lot! Consider:

1. Splitting by module/feature first
2. Creating multiple PRs
3. Committing incrementally as you work

Would you like me to try splitting anyway? (y/n)

Error Handling

Not a git repository:

ERROR: Not a git repository
Run: git init

(Detected by /commit-error-handling diagnose-issues)

No changes to split:

NO CHANGES TO SPLIT

Your working tree is clean.
Make some changes first, then run /commit-split.

Commit creation failed:

ERROR: Failed to create commit

<git error message>

This may happen if:
- Git user.name or user.email not configured
- Repository is in conflicted state
- Pre-commit hooks failed

Fix the issue and try again.

Use /commit-error-handling diagnose-issues for detailed diagnostics.

Granular Control Options

Option 1: Use atomic-commit Skill Directly

The /commit-split command is a wrapper around /atomic-commit interactive.

For equivalent functionality with more control:

/atomic-commit interactive

Additional atomic-commit operations:

  • /atomic-commit analyze - Just check if should split
  • /atomic-commit group strategy:type - Just group files
  • /atomic-commit suggest - Just get suggestions
  • /atomic-commit sequence output:script - Generate bash script

Option 2: Generate Script and Execute

Generate an executable script:

/atomic-commit sequence output:script > split-commits.sh
chmod +x split-commits.sh
./split-commits.sh

This gives you a script you can review and modify before execution.

Option 3: Manual with Guidance

Get the plan without execution:

/commit-review  # Get analysis and recommendations
/atomic-commit suggest  # Get specific suggestions

Then manually:

git add file1 file2 file3
/commit "feat(auth): add OAuth"

git add file4 file5
/commit "test(auth): add tests"

Option 4: Analysis Only

Just understand your changes without committing:

/commit-review  # Full analysis
/commit-analysis analyze  # Just change analysis
/atomic-commit analyze  # Just atomicity check

Tips

Before Splitting:

  • Run /commit-review first to see the splitting plan
  • Ensure all changes are related to work you want to commit
  • Consider using git stash for truly unrelated changes

During Splitting:

  • Review each proposed message carefully
  • Edit messages if the generated ones aren't perfect
  • Skip groups if you want to commit them separately
  • Don't worry about making mistakes - commits can be amended

After Splitting:

  • Run tests to verify everything still works
  • Review commits with git log -p
  • Use git commit --amend if you need to fix the last commit
  • Push all commits together or create a PR

Examples

Example 1: Feature Development

Files changed: 8
Groups: 3
- feat(payment): 5 files
- test(payment): 2 files
- docs: 1 file

Result: 3 clean atomic commits

Example 2: Bug Fix with Refactoring

Files changed: 4
Groups: 2
- fix(api): 2 files (the actual fix)
- refactor: 2 files (cleanup done while fixing)

Result: 2 separate commits (fix can be cherry-picked)

Example 3: Mixed Changes

Files changed: 15
Groups: 5
- feat(auth): 6 files
- feat(profile): 4 files
- fix(api): 2 files
- test: 2 files
- docs: 1 file

Result: 5 focused commits

Best Practices

  1. Keep It Simple: Don't overthink grouping
  2. Test Between Commits: Each commit should work
  3. Review Messages: Generated messages are suggestions
  4. Be Consistent: Follow your team's commit conventions
  5. Document Why: Use commit body for complex changes
  6. One Story Per Commit: Each commit tells one story

Related Skills and Commands

Core Skill: atomic-commit

The /commit-split command is powered by the atomic-commit skill:

Full Skill Access: /atomic-commit

  • analyze - Determine if should split
  • group - Group related files
  • suggest - Generate commit breakdown
  • sequence - Create execution plan
  • interactive - Full guided workflow (what /commit-split uses)

Supporting Skills

Analysis:

  • /commit-analysis - Change type/scope detection
  • /commit-error-handling - Repository validation

Message Generation:

  • /message-generation - Conventional commit messages
  • /history-analysis - Project convention learning

Quality Assurance:

  • /commit-best-practices - Validation and review

Related Commands

Analysis Phase:

  • /commit-review - Analyze and get recommendations (no execution)

Execution Phase:

  • /commit-split - Interactive splitting (this command)
  • /commit - Single atomic commit

Complete Workflow

1. Analysis: /commit-review
   ↓ If split needed
2. Execution: /commit-split
   ↓ Creates N atomic commits
3. Verify: /commit-best-practices review-commit

Documentation

  • Atomic Commits Guide: .claude/commands/commit-best-practices/workflow-tips.md
  • Splitting Strategies: .claude/commands/atomic-commit/ skill documentation
  • Skill Architecture: .claude/docs/SKILL_ARCHITECTURE.md
  • Agent Reference: .claude/agents/commit-assistant.md

Intelligent Git Commit Assistant

Create well-formatted git commits with optional automatic message generation following conventional commits standards.

Overview

The /commit command provides a simplified workflow that orchestrates multiple specialized skills to create intelligent, well-formatted commits following conventional commits standards.

Skills Orchestrated

This command coordinates these granular skills:

  1. commit-error-handling - Validates git repository state and checks for issues

    • Operation: /commit-error-handling diagnose-issues
    • Purpose: Ensure repository is in a clean state before committing
  2. commit-analysis - Analyzes changes to determine type, scope, and atomicity

    • Operation: /commit-analysis analyze
    • Purpose: Understand what changes are being committed
  3. history-analysis (optional) - Learns project commit conventions

    • Operation: /history-analysis analyze-style
    • Purpose: Match team's existing commit style
  4. commit-best-practices - Validates commit readiness

    • Operation: /commit-best-practices check-pre-commit
    • Purpose: Ensure tests pass, no debug code, lint clean
  5. message-generation - Generates conventional commit messages

    • Operation: /message-generation complete
    • Purpose: Create well-formatted conventional commit message
  6. atomic-commit (conditional) - Suggests splitting if needed

    • Operation: /atomic-commit analyze
    • Purpose: Determine if changes should be split into multiple commits

For Granular Control

If you need precise control over individual operations:

  • Use /commit-error-handling for error diagnosis
  • Use /commit-analysis for change analysis
  • Use /message-generation for message generation
  • Use /atomic-commit for commit splitting
  • Use /commit-best-practices for validation
  • Use /history-analysis for project conventions

See the commit-assistant agent for complete skill documentation.

Usage

/commit                    # Analyze changes and generate commit message
/commit "feat: add login"  # Use provided message directly

Complete Workflow

User: /commit [optional message]
         ↓
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │ 1. Error Check                 │
    │ /commit-error-handling         │
    │ diagnose-issues                │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                 ↓
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │ 2. Analyze Changes             │
    │ /commit-analysis analyze       │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                 ↓
           ā”Œā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”
           │ Atomic?    │
           ā””ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                 │
        ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
        │ NO              │ YES
        ↓                 ↓
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ Suggest Split │  │ Continue         │
│ /atomic-commit│  │                  │
│ analyze       │  │                  │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
        │                   │
        ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                 ↓
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │ 3. Learn Project Style         │
    │ /history-analysis (optional)   │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                 ↓
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │ 4. Pre-Commit Check            │
    │ /commit-best-practices         │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                 ↓
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │ 5. Generate Message            │
    │ /message-generation complete   │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                 ↓
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │ 6. Present & Confirm           │
    │ User reviews message           │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                 ↓
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │ 7. Create Commit               │
    │ git add . && git commit        │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                 ↓
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │ 8. Post-Commit Review          │
    │ /commit-best-practices         │
    │ review-commit                  │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Process

Step 1: Verify Git Repository and Check for Issues

Orchestrates: /commit-error-handling diagnose-issues

This operation checks:

  • Repository validity (is this a git repo?)
  • Changes present (are there files to commit?)
  • No merge conflicts
  • Not in detached HEAD state
  • Git configuration present

Internally executes:

git rev-parse --git-dir 2>/dev/null
git status --short
git status --porcelain
git config user.name
git config user.email

If issues are found, the operation provides specific guidance:

Not a git repository:

ERROR: Not a git repository

This directory is not initialized as a git repository.
Initialize one with: git init

No changes to commit:

No changes to commit

Working tree is clean. Make some changes first, then run /commit again.

For detailed error handling: Use /commit-error-handling skill directly with operations:

  • /commit-error-handling handle-no-repo - Not a repository error
  • /commit-error-handling handle-no-changes - No changes error
  • /commit-error-handling handle-conflicts - Merge conflict guidance
  • /commit-error-handling handle-detached-head - Detached HEAD handling

Step 2: Check for Atomic Commit Opportunity

Orchestrates: /atomic-commit analyze

Before proceeding with message generation, check if the changes should be split into multiple atomic commits.

This operation analyzes:

  • Number of files changed
  • Logical groupings of changes
  • Mixed concerns (e.g., feature + refactor + tests)

If changes should be split, provide guidance:

RECOMMENDATION: Split into atomic commits

Your changes involve multiple concerns:
1. Feature: New authentication module (3 files)
2. Refactor: Code cleanup in utils (2 files)
3. Tests: Test coverage for auth (1 file)

Consider using /atomic-commit interactive to split these into 3 commits.

For granular atomic commit analysis:

  • /atomic-commit group - Group related files together
  • /atomic-commit suggest - Recommend commit breakdown
  • /atomic-commit sequence - Generate commit execution plan
  • /atomic-commit interactive - Step-by-step guided splitting

Step 3: Analyze Changes

Orchestrates: /commit-analysis analyze

If user provided a message ($ARGUMENTS is not empty), skip to Step 5 and use their message.

If no message provided, this operation analyzes your changes to determine:

  • Type: feat, fix, docs, style, refactor, test, chore, perf, ci
  • Scope: Primary module/component affected (auth, api, ui, etc.)
  • Atomicity: Whether changes should be in one commit or split
  • Files: What files are being modified

The analysis uses git commands:

# Get detailed diff
git diff HEAD

# Get status for summary
git status --short

# Get recent commits for style reference
git log --oneline -10

For granular analysis: Use these operations directly:

  • /commit-analysis detect-type - Just determine type
  • /commit-analysis identify-scope - Just identify scope
  • /commit-analysis assess-atomicity - Just check if should split
  • /commit-analysis file-stats - Get file change statistics

Step 4: Learn Project Conventions (Optional)

Orchestrates: /history-analysis analyze-style (optional, caches results)

This operation (run periodically, results cached):

  1. Learns project conventions
    • Analyzes recent 50-100 commits
    • Detects conventional commits usage
    • Identifies common scopes
    • Determines average subject length
    • Identifies team patterns

The analysis helps ensure generated messages match your project's existing style.

For custom history analysis:

  • /history-analysis detect-patterns - Identify project conventions
  • /history-analysis extract-scopes - Discover commonly used scopes
  • /history-analysis suggest-conventions - Recommend conventions
  • /history-analysis learn-project - Full project learning

Step 5: Pre-Commit Validation (Recommended)

Orchestrates: /commit-best-practices check-pre-commit

This operation validates:

  • Tests pass (npm test, pytest, cargo test, go test)
  • Lint passes (eslint, pylint, clippy)
  • No debug code (console.log, debugger, print, pdb)
  • No TODO/FIXME in new code
  • No merge conflict markers

If validation fails, commit is blocked with specific guidance:

PRE-COMMIT VALIDATION FAILED

Issues found:
 Tests: 2 tests failing in auth.test.js
 Lint: 3 errors in src/auth/oauth.js
 Debug: Found console.log in src/utils/debug.js

Fix these issues before committing.
Run /commit-best-practices check-pre-commit for details.

For validation control:

  • Enable/disable via configuration
  • Run manually: /commit-best-practices check-pre-commit
  • Skip with: /commit --skip-validation (not recommended)

Step 6: Generate Commit Message

Orchestrates: /message-generation complete

Based on the analysis from Steps 3-4, this operation generates a conventional commit message following this format:

<type>(<scope>): <subject>

<body (optional)>

<footer (optional)>

The generated message matches your project's existing style from history analysis.

Commit Types (prioritize by analyzing changes):

  • feat: New features, new functions, new capabilities

    • Detects: New files, new functions, new exports, new components
    • Example: "feat(auth): add OAuth2 authentication support"
  • fix: Bug fixes, error corrections, issue resolutions

    • Detects: Error handling, null checks, validation fixes, condition fixes
    • Example: "fix(api): resolve null pointer in user endpoint"
  • docs: Documentation only changes

    • Detects: Changes only in README, *.md files, comments, JSDoc
    • Example: "docs(readme): update installation instructions"
  • style: Formatting, whitespace, no code logic change

    • Detects: Indentation, semicolons, whitespace, code formatting
    • Example: "style: apply prettier formatting to components"
  • refactor: Code restructuring without behavior change

    • Detects: Renamed variables, extracted functions, reorganized code
    • Example: "refactor(utils): simplify date formatting logic"
  • test: Adding or updating tests

    • Detects: Changes in test files, spec files, test utilities
    • Example: "test(auth): add unit tests for login flow"
  • chore: Build, dependencies, tooling, configuration

    • Detects: package.json, build configs, CI configs, dependencies
    • Example: "chore: update dependencies to latest versions"
  • perf: Performance improvements

    • Detects: Optimization, caching, algorithm improvements
    • Example: "perf(render): optimize component re-rendering"
  • ci: CI/CD configuration changes

    • Detects: .github/workflows, .gitlab-ci.yml, CI configs
    • Example: "ci: add automated testing workflow"

Scope Determination:

  • Identify the primary module, component, or area affected
  • Use kebab-case for scope names
  • Examples: auth, api, utils, components, config, database

Subject Guidelines:

  • 50 characters or less
  • Present tense, imperative mood (add, not added or adds)
  • No period at the end
  • Lowercase after the colon

Body (include if changes are complex):

  • Explain what and why, not how
  • Wrap at 72 characters
  • Separate from subject with blank line
  • Use bullet points for multiple items

For custom message generation:

  • /message-generation subject - Generate subject line only
  • /message-generation body - Generate body only
  • /message-generation footer - Add footer with breaking changes/issues
  • /message-generation validate - Validate existing message format

Analysis Example:

If git diff shows:

+++ src/auth/oauth.js
+export function authenticateWithOAuth(provider) {
+  // OAuth implementation
+}

+++ src/auth/providers.js
+export const providers = {
+  google: { ... },
+  github: { ... }
+}

+++ tests/auth.test.js
+describe('OAuth authentication', () => {

Generate message:

feat(auth): add OAuth authentication support

- Implement OAuth2 authentication flow
- Add support for Google and GitHub providers
- Include comprehensive unit tests

Step 7: Present Message and Confirm

If message was generated, present it to the user:

PROPOSED COMMIT MESSAGE:
─────────────────────────────────────────────

feat(auth): add OAuth authentication support

- Implement OAuth2 authentication flow
- Add support for Google and GitHub providers
- Include comprehensive unit tests

─────────────────────────────────────────────

FILES TO BE COMMITTED:
 M src/auth/oauth.js
 M src/auth/providers.js
 M tests/auth.test.js

Would you like to:
1. Use this message (y)
2. Edit the message (e)
3. Provide your own message (m)
4. Cancel (n)

Handle user response:

  • If user says "y" or "yes" or approves: proceed to commit
  • If user says "e" or "edit": tell them to run /commit "edited message here"
  • If user says "m" or "custom": tell them to run /commit "your custom message"
  • If user says "n" or "no" or "cancel": abort

Step 8: Create Commit

Stage all changes and create the commit:

# Stage all changes
git add .

# Create commit with message
git commit -m "<the message>"

Step 9: Post-Commit Review

Orchestrates: /commit-best-practices review-commit

After successful commit, this operation:

  • Analyzes commit quality (0-100 score)
  • Validates conventional commits format
  • Checks atomicity
  • Provides improvement suggestions

Show detailed information:

# Get commit info
git log -1 --stat
git log -1 --format="%H"

Format output with quality review:

COMMIT SUCCESSFUL
─────────────────────────────────────────────

Hash: abc1234def5678
Message: feat(auth): add OAuth authentication support

FILES CHANGED: 5 files
INSERTIONS: 247 (+)
DELETIONS: 63 (-)

─────────────────────────────────────────────

COMMIT QUALITY REVIEW (Score: 95/100)

Format: Excellent - follows conventional commits
Atomicity: Good - focused on single feature
Message: Clear and descriptive

Suggestions:
 Consider adding issue reference in footer (e.g., "Closes #123")

─────────────────────────────────────────────

NEXT STEPS:

Run /commit again to check for remaining uncommitted changes
Run git push to push this commit to remote

For detailed review:

  • /commit-best-practices review-commit - Full analysis
  • /commit-best-practices amend-guidance - Safe amend help
  • /commit-best-practices revert-guidance - Help with commit reverts

Step 10: Check for Remaining Changes

After committing, check if there are more uncommitted changes:

git status --short

If there are more changes, add a tip:

TIP: You have 3 more modified files.
     Run /commit again to commit them.

Error Handling

Orchestrates: /commit-error-handling skill for all error scenarios

Not a git repository:

ERROR: Not a git repository
Initialize with: git init

Use: /commit-error-handling handle-no-repo for detailed guidance

No changes to commit:

Nothing to commit, working tree clean

Use: /commit-error-handling handle-no-changes for suggestions

Merge conflicts:

ERROR: Merge conflicts detected
Resolve conflicts before committing

Use: /commit-error-handling handle-conflicts for conflict resolution guidance

Detached HEAD state:

ERROR: Detached HEAD state
Cannot commit in detached HEAD

Use: /commit-error-handling handle-detached-head for recovery steps

Commit failed:

ERROR: Commit failed
<show git error message>

Common fixes:
- Ensure you have staged changes
- Check git configuration (git config user.name/user.email)
- Verify repository is not in a conflicted state

Use: /commit-error-handling diagnose-issues for comprehensive diagnosis

Examples

Example 1: Auto-generate message

/commit
# Analyzes changes, generates "feat(api): add user authentication endpoint"
# Prompts for confirmation, creates commit

Example 2: Custom message

/commit "fix: resolve login timeout issue"
# Uses provided message directly

Example 3: Complex feature

/commit
# Generates:
# feat(payments): integrate Stripe payment processing
#
# - Add Stripe SDK integration
# - Implement payment flow for subscriptions
# - Add webhook handlers for payment events
# - Include error handling and retry logic

Tips

  • Let the assistant analyze changes for accurate commit types
  • Use conventional commits format for consistency
  • Create atomic commits (one logical change per commit)
  • Run /atomic-commit analyze first to check if you should split commits
  • Run /commit-best-practices check-pre-commit to validate before committing
  • Use /history-analysis analyze-style to learn project conventions
  • Include scope for better commit history navigation

Conventional Commits Quick Reference

Format: <type>(<scope>): <subject>

Types: feat, fix, docs, style, refactor, test, chore, perf, ci

Good Examples:

  • feat(auth): add two-factor authentication
  • fix(api): handle null response in user endpoint
  • docs(readme): add installation instructions
  • refactor(utils): extract validation logic to separate module
  • test(auth): add integration tests for OAuth flow

Bad Examples:

  • update files (vague, no type)
  • fixed bug (no scope, not descriptive)
  • WIP (work in progress, not descriptive)
  • asdf (meaningless)

Related Skills and Commands

Granular Skills

For precise control over individual operations:

  • Error Handling: /commit-error-handling - Diagnose and resolve git issues

    • /commit-error-handling diagnose-issues - Comprehensive diagnosis
    • /commit-error-handling handle-no-repo - Repository initialization
    • /commit-error-handling handle-no-changes - No changes guidance
    • /commit-error-handling handle-conflicts - Merge conflict resolution
    • /commit-error-handling handle-detached-head - Detached HEAD recovery
  • Analysis: /commit-analysis - Detailed change analysis

    • /commit-analysis analyze - Full comprehensive analysis
    • /commit-analysis detect-type - Determine commit type
    • /commit-analysis identify-scope - Identify affected module
    • /commit-analysis assess-atomicity - Check if should split
    • /commit-analysis file-stats - Get file change statistics
  • Message Generation: /message-generation - Create/validate messages

    • /message-generation complete - Generate full message
    • /message-generation subject - Create subject line only
    • /message-generation body - Compose commit body
    • /message-generation footer - Add footer with issues
    • /message-generation validate - Validate message format
  • Atomic Commits: /atomic-commit - Split large commits

    • /atomic-commit analyze - Determine if should split
    • /atomic-commit group - Group related files
    • /atomic-commit suggest - Recommend commit breakdown
    • /atomic-commit sequence - Generate commit plan
    • /atomic-commit interactive - Guided splitting
  • Best Practices: /commit-best-practices - Validate and review

    • /commit-best-practices check-pre-commit - Validate readiness
    • /commit-best-practices review-commit - Analyze quality
    • /commit-best-practices amend-guidance - Safe amend help
    • /commit-best-practices revert-guidance - Revert help
    • /commit-best-practices workflow-tips - Complete workflow guidance
  • History Analysis: /history-analysis - Learn project conventions

    • /history-analysis analyze-style - Learn from recent commits
    • /history-analysis detect-patterns - Identify conventions
    • /history-analysis extract-scopes - Discover common scopes
    • /history-analysis suggest-conventions - Recommend conventions
    • /history-analysis learn-project - Full project learning

Related High-Level Commands

Other simplified workflows:

  • /commit-review - Analyze changes and get splitting recommendations
  • /commit-split - Interactively split large commits into atomic commits

Documentation References

Operation: Analyze Commit Style

Purpose: Analyze recent commit history to learn the project's commit message style, conventions, and patterns.

Parameters

From $ARGUMENTS (after operation name):

  • count:N - Number of commits to analyze (default: 50)
  • branch:name - Branch to analyze (default: current branch)
  • format:json|text - Output format (default: text)

Workflow

1. Validate Repository

# Check if in git repository
if ! git rev-parse --git-dir >/dev/null 2>&1; then
    echo "Error: Not in a git repository"
    exit 1
fi

# Check if has commits
if ! git log -1 >/dev/null 2>&1; then
    echo "Error: No commit history found"
    exit 1
fi

2. Execute Style Analysis Script

Invoke the style-analyzer.sh utility script:

./.scripts/style-analyzer.sh <count> <branch>

The script will:

  • Fetch recent commits from git log
  • Analyze commit message formats
  • Calculate statistics (average length, type distribution, etc.)
  • Detect conventional commits usage
  • Identify common patterns

3. Process Analysis Results

The script returns JSON output with:

{
  "project_style": {
    "uses_conventional_commits": true,
    "conventional_commits_percentage": 87,
    "average_subject_length": 47,
    "subject_length_stddev": 8,
    "common_types": [
      {"type": "feat", "count": 45, "percentage": 35.4},
      {"type": "fix", "count": 38, "percentage": 29.9},
      {"type": "docs", "count": 20, "percentage": 15.7}
    ],
    "common_scopes": [
      {"scope": "auth", "count": 23, "percentage": 18.1},
      {"scope": "api", "count": 19, "percentage": 14.9},
      {"scope": "ui", "count": 15, "percentage": 11.8}
    ],
    "imperative_mood_percentage": 92,
    "has_body_percentage": 34,
    "references_issues_percentage": 67,
    "consistency_score": 85,
    "sample_commits": [
      "feat(auth): implement OAuth2 authentication",
      "fix(api): handle null pointer in user endpoint",
      "docs: update API documentation"
    ]
  }
}

4. Generate Recommendations

Based on analysis results, provide:

Style Recommendations:

  • Conventional commits adherence level
  • Recommended message format
  • Typical subject line length
  • Body usage patterns
  • Issue reference patterns

Type Recommendations:

  • Most commonly used types
  • Type usage frequency
  • Recommended types for new commits

Scope Recommendations:

  • Commonly used scopes
  • Scope naming patterns
  • When to use which scope

Consistency Recommendations:

  • Areas of good consistency
  • Areas needing improvement
  • Specific guidance for better consistency

5. Format Output

Text Format (default):

Git Commit Style Analysis
=========================

Commits Analyzed: 50
Branch: main
Conventional Commits: 87% (43/50)
Consistency Score: 85/100

Subject Lines:
  Average Length: 47 characters
  Recommended: Keep under 50 characters

Common Types:
  1. feat  - 35.4% (45 commits) - New features
  2. fix   - 29.9% (38 commits) - Bug fixes
  3. docs  - 15.7% (20 commits) - Documentation

Common Scopes:
  1. auth  - 18.1% (23 commits) - Authentication/authorization
  2. api   - 14.9% (19 commits) - API endpoints
  3. ui    - 11.8% (15 commits) - User interface

Patterns Detected:
  āœ“ Uses imperative mood (92%)
  āœ“ References issues frequently (67%)
  ā—‹ Body usage moderate (34%)

Recommendations:
  • Continue using conventional commits format
  • Consider 'auth' scope for authentication changes
  • Keep subject lines under 50 characters
  • Use imperative mood (e.g., "add" not "added")
  • Reference issues when applicable (#123)

Sample Commits (project style):
  feat(auth): implement OAuth2 authentication
  fix(api): handle null pointer in user endpoint
  docs: update API documentation

JSON Format:

{
  "analysis_type": "commit_style",
  "commits_analyzed": 50,
  "branch": "main",
  "results": { ... },
  "recommendations": [ ... ],
  "confidence": "high"
}

Error Handling

No git repository:

  • Error: "Not in a git repository. Run this command from within a git project."
  • Exit code: 1

No commits:

  • Error: "No commit history found. This appears to be a new repository."
  • Exit code: 1

Branch doesn't exist:

  • Error: "Branch 'branch-name' not found. Check branch name and try again."
  • Exit code: 1

Insufficient commits:

  • Warning: "Only X commits found. Analysis may be less accurate."
  • Proceed with available commits

Git command fails:

  • Error: "Git command failed: {error message}"
  • Provide troubleshooting steps

Integration Usage

By commit-assistant agent:

User requests: "commit my changes"
  → Agent invokes: /history-analysis analyze-style
  → Learns: Project uses conventional commits, common scope: "auth"
  → Agent generates message matching project style

By message-generation skill:

Before generating message:
  → Invoke: /history-analysis analyze-style format:json
  → Extract: common_types, common_scopes, average_length
  → Use in: message generation to match project conventions

Output Examples

High Consistency Project (score: 95):

āœ“ Excellent consistency across commits
āœ“ Strong conventional commits adherence (98%)
āœ“ Clear scope usage patterns
→ Continue current practices

Medium Consistency Project (score: 65):

ā—‹ Moderate consistency
ā—‹ Mixed conventional commits usage (64%)
ā—‹ Inconsistent scope patterns
→ Recommend adopting conventional commits
→ Define standard scopes for the project

Low Consistency Project (score: 35):

āœ— Low consistency across commits
āœ— Minimal conventional commits usage (12%)
āœ— No clear patterns
→ Consider establishing commit message guidelines
→ Define project-specific conventions
→ Use this tool to enforce standards

Success Criteria

Operation succeeds when:

  • Git repository validated
  • Commits successfully analyzed
  • Statistics calculated accurately
  • Patterns detected correctly
  • Recommendations generated
  • Output formatted properly
  • Results match project reality

Performance

  • Analysis Time: ~1-2 seconds for 50 commits
  • Memory Usage: Minimal (processes line-by-line)
  • Git Operations: Read-only, no modifications

Operation: Detect Commit Patterns

Purpose: Identify project-specific commit message patterns, conventions, and formatting standards from commit history.

Parameters

From $ARGUMENTS (after operation name):

  • count:N - Number of commits to analyze (default: 50)
  • branch:name - Branch to analyze (default: current branch)
  • format:json|text - Output format (default: text)
  • detailed:true|false - Include detailed pattern breakdown (default: false)

Workflow

1. Validate Repository

# Verify git repository
if ! git rev-parse --git-dir >/dev/null 2>&1; then
    echo "Error: Not in a git repository"
    exit 1
fi

2. Execute Pattern Detection

Invoke the pattern-detector.py utility script:

./.scripts/pattern-detector.py --count <count> --branch <branch> [--detailed]

The script analyzes:

  • Format Patterns: Message structure and formatting
  • Convention Patterns: Conventional commits, semantic versioning references
  • Content Patterns: Imperative mood, capitalization, punctuation
  • Metadata Patterns: Issue references, co-authors, sign-offs
  • Body Patterns: Bullet points, wrapping, section structure

3. Pattern Categories Analyzed

A. Format Patterns

patterns = {
    'conventional_commits': 0,      # type(scope): subject
    'simple_subject': 0,             # Just a subject line
    'prefixed': 0,                   # [PREFIX] subject
    'tagged': 0,                     # #tag subject
    'other': 0
}

B. Convention Patterns

conventions = {
    'imperative_mood': 0,            # "add" vs "added"
    'capitalized_subject': 0,        # First letter capitalized
    'no_period_end': 0,              # No period at end
    'blank_line_before_body': 0,     # Proper body separation
    'wrapped_body': 0,               # 72-char wrap
    'has_footer': 0                  # Breaking changes, issues
}

C. Content Patterns

content = {
    'references_issues': 0,          # #123, Closes #456
    'mentions_breaking': 0,          # BREAKING CHANGE:
    'has_co_authors': 0,             # Co-authored-by:
    'signed_off': 0,                 # Signed-off-by:
    'includes_rationale': 0,         # "because", "to", "for"
    'mentions_impact': 0             # "affects", "impacts", "changes"
}

4. Pattern Analysis Algorithm

The pattern-detector.py script implements:

def analyze_commit_patterns(commits):
    """
    Analyze commit messages for patterns.
    Returns pattern frequencies and confidence scores.
    """
    patterns = initialize_pattern_counters()

    for commit in commits:
        # Parse commit structure
        subject, body, footer = parse_commit(commit)

        # Detect format pattern
        if is_conventional_commit(subject):
            patterns['format']['conventional_commits'] += 1
        elif has_prefix(subject):
            patterns['format']['prefixed'] += 1
        # ... more checks

        # Detect conventions
        if is_imperative_mood(subject):
            patterns['conventions']['imperative_mood'] += 1
        if is_capitalized(subject):
            patterns['conventions']['capitalized_subject'] += 1
        # ... more checks

        # Detect content patterns
        if references_issues(commit):
            patterns['content']['references_issues'] += 1
        # ... more checks

    # Calculate percentages
    return calculate_pattern_percentages(patterns, len(commits))

5. Output Structure

Text Format (default):

Commit Pattern Analysis
=======================

Commits Analyzed: 50
Branch: main

FORMAT PATTERNS
---------------
Conventional Commits: 87% (44/50)  āœ“ DOMINANT
  Example: feat(auth): implement OAuth2
Simple Subject:       10% (5/50)
  Example: Update documentation
Prefixed:             3% (1/50)
  Example: [HOTFIX] Fix critical bug

CONVENTION PATTERNS
-------------------
Imperative Mood:      92% (46/50)   āœ“ STRONG
Capitalized Subject:  94% (47/50)   āœ“ STRONG
No Period at End:     88% (44/50)   āœ“ STRONG
Blank Line Before Body: 100% (17/17) āœ“ PERFECT
Body Wrapped at 72:   94% (16/17)   āœ“ STRONG
Has Footer:           26% (13/50)   ā—‹ MODERATE

CONTENT PATTERNS
----------------
References Issues:    67% (34/50)   āœ“ COMMON
Mentions Breaking:    8% (4/50)     ā—‹ OCCASIONAL
Has Co-Authors:       2% (1/50)     āœ— RARE
Signed-Off:          12% (6/50)     ā—‹ OCCASIONAL
Includes Rationale:   45% (23/50)   ā—‹ MODERATE
Mentions Impact:      31% (16/50)   ā—‹ MODERATE

DETECTED CONVENTIONS
--------------------
āœ“ Project uses conventional commits format
āœ“ Strong imperative mood usage
āœ“ Consistent capitalization and punctuation
āœ“ Frequent issue references
ā—‹ Moderate footer usage
ā—‹ Occasional breaking change mentions

PATTERN CONSISTENCY
-------------------
Overall Score: 85/100 (GOOD)
  Format:      High (87% conventional)
  Conventions: High (90%+ adherence)
  Content:     Moderate (varied usage)

RECOMMENDATIONS
---------------
• Continue using conventional commits format
• Maintain imperative mood in subject lines
• Consider more consistent footer usage
• Document rationale in commit bodies when complex

JSON Format:

{
  "analysis_type": "pattern_detection",
  "commits_analyzed": 50,
  "branch": "main",
  "patterns": {
    "format": {
      "conventional_commits": {"count": 44, "percentage": 87, "strength": "dominant"},
      "simple_subject": {"count": 5, "percentage": 10, "strength": "rare"},
      "prefixed": {"count": 1, "percentage": 3, "strength": "rare"}
    },
    "conventions": {
      "imperative_mood": {"count": 46, "percentage": 92, "strength": "strong"},
      "capitalized_subject": {"count": 47, "percentage": 94, "strength": "strong"},
      "no_period_end": {"count": 44, "percentage": 88, "strength": "strong"}
    },
    "content": {
      "references_issues": {"count": 34, "percentage": 67, "strength": "common"},
      "mentions_breaking": {"count": 4, "percentage": 8, "strength": "occasional"}
    }
  },
  "consistency_score": 85,
  "dominant_pattern": "conventional_commits",
  "recommendations": [
    "Continue using conventional commits format",
    "Maintain imperative mood in subject lines"
  ]
}

6. Pattern Strength Classification

PERFECT:    95-100% - Universal usage
STRONG:     80-94%  - Very consistent
DOMINANT:   65-79%  - Clear preference
COMMON:     45-64%  - Regular usage
MODERATE:   25-44%  - Occasional usage
OCCASIONAL: 10-24%  - Infrequent usage
RARE:       1-9%    - Seldom used
ABSENT:     0%      - Not used

7. Detailed Pattern Breakdown

When detailed:true is specified, include:

Per-Pattern Examples:

IMPERATIVE MOOD (92%)
  āœ“ "Add user authentication"
  āœ“ "Fix null pointer exception"
  āœ“ "Update API documentation"
  āœ— "Added new feature"
  āœ— "Updated dependencies"

Timeline Analysis:

Pattern Evolution (most recent 10 commits):
  Conventional Commits: 10/10 (100%) - Improving ↑
  Imperative Mood:      9/10 (90%)  - Stable →
  Issue References:     8/10 (80%)  - Improving ↑

Error Handling

No git repository:

  • Return: "Error: Not in a git repository"
  • Exit code: 1

No commits:

  • Return: "Error: No commit history to analyze"
  • Exit code: 1

Insufficient commits:

  • Warning: "Only X commits available (requested Y)"
  • Proceed with available commits

Pattern detection fails:

  • Return partial results with warning
  • Indicate which patterns couldn't be detected

Integration Usage

By commit-assistant agent:

Agent: Determine project conventions
  → Invoke: /history-analysis detect-patterns
  → Learn: Project uses conventional commits (87%)
  → Apply: Use conventional format for new commits

By message-generation skill:

Before generating:
  → Detect dominant patterns
  → Extract format preferences
  → Match project conventions

By commit-best-practices skill:

When reviewing commits:
  → Compare against detected patterns
  → Flag deviations from project norms
  → Suggest consistency improvements

Success Criteria

Operation succeeds when:

  • All pattern categories analyzed
  • Frequencies calculated accurately
  • Strength classifications assigned
  • Consistency score computed
  • Dominant pattern identified
  • Recommendations generated
  • Output formatted correctly

Performance

  • Analysis Time: ~2-3 seconds for 50 commits
  • Memory Usage: Low (streaming analysis)
  • Accuracy: High (>95% pattern detection accuracy)

Operation: Extract Scopes

Purpose: Discover and analyze commonly used scopes in commit messages to understand project structure and component organization.

Parameters

From $ARGUMENTS (after operation name):

  • count:N - Number of commits to analyze (default: 50)
  • branch:name - Branch to analyze (default: current branch)
  • format:json|text - Output format (default: text)
  • min_frequency:N - Minimum occurrences to include (default: 2)
  • top:N - Show only top N scopes (default: 20)

Workflow

1. Validate Repository

# Check git repository
if ! git rev-parse --git-dir >/dev/null 2>&1; then
    echo "Error: Not in a git repository"
    exit 1
fi

2. Execute Scope Extraction

Invoke the scope-extractor.sh utility script:

./.scripts/scope-extractor.sh --count <count> --branch <branch> --min-frequency <min>

The script will:

  • Parse commit messages
  • Extract scopes using regex patterns
  • Count scope frequencies
  • Analyze scope naming patterns
  • Categorize scopes by type

3. Scope Extraction Algorithm

Pattern Matching:

# Primary pattern: type(scope): subject
^[a-z]+\(([^)]+)\):

# Examples:
feat(auth): add OAuth        → scope: "auth"
fix(api/users): handle null  → scope: "api/users"
docs(readme): update guide   → scope: "readme"

Nested Scope Handling:

# Hierarchical scopes
api/endpoints → parent: "api", child: "endpoints"
ui/components → parent: "ui", child: "components"
core/auth     → parent: "core", child: "auth"

Multi-Scope Handling:

# Comma-separated scopes
feat(api,docs): add endpoint → scopes: ["api", "docs"]
fix(ui, ux): button alignment → scopes: ["ui", "ux"]

4. Scope Analysis Categories

A. Frequency Analysis

{
  "scope": "auth",
  "count": 23,
  "percentage": 18.1,
  "first_seen": "2024-01-15",
  "last_seen": "2024-03-10",
  "active": true
}

B. Scope Hierarchy

{
  "api": {
    "count": 45,
    "children": {
      "endpoints": 12,
      "middleware": 8,
      "validation": 6
    }
  }
}

C. Scope Categories

Architecture:    core, utils, config
Features:        auth, payment, search
UI:             ui, components, styles
Backend:        api, db, server
Infrastructure: ci, docker, deploy
Documentation:  docs, readme, changelog
Testing:        test, e2e, unit

5. Output Structure

Text Format (default):

Scope Extraction Analysis
=========================

Commits Analyzed: 50
Branch: main
Scopes Found: 15 unique
Total Scoped Commits: 44/50 (88%)

TOP SCOPES BY FREQUENCY
-----------------------
 1. auth          23 (18.1%) ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ
    └─ Authentication and authorization

 2. api           19 (14.9%) ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ
    ā”œā”€ endpoints   7
    ā”œā”€ middleware  5
    └─ validation  3

 3. ui            15 (11.8%) ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ
    ā”œā”€ components  8
    └─ styles      4

 4. db            12 (9.4%)  ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ
    └─ Database operations

 5. docs          11 (8.7%)  ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ
    └─ Documentation

 6. core          8 (6.3%)   ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ
    └─ Core functionality

 7. config        7 (5.5%)   ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ
    └─ Configuration

 8. test          6 (4.7%)   ā–ˆā–ˆā–ˆā–ˆā–ˆ
    └─ Testing

 9. ci            5 (3.9%)   ā–ˆā–ˆā–ˆā–ˆ
    └─ CI/CD pipelines

10. deploy        4 (3.1%)   ā–ˆā–ˆā–ˆ
    └─ Deployment

SCOPE CATEGORIES
----------------
Features (45%):      auth, payment, search
Backend (32%):       api, db, server
UI (19%):           ui, components, styles
Infrastructure (12%): ci, docker, deploy
Documentation (8%):  docs, readme

SCOPE PATTERNS
--------------
Naming Style:     lowercase, hyphen-separated
Hierarchy:        Uses / for nested scopes (api/endpoints)
Multi-Scope:      Occasional (3% of commits)
Active Scopes:    12/15 (used in last 10 commits)
Deprecated:       payment-v1, legacy-api

RECOMMENDATIONS
---------------
• Use 'auth' for authentication/authorization changes
• Use 'api' for backend API modifications
• Use 'ui' for user interface changes
• Consider hierarchical scopes for complex modules (api/endpoints)
• Active scopes: auth, api, ui, db, docs, core, config
• Avoid deprecated: payment-v1, legacy-api

RECENT SCOPE USAGE (last 10 commits)
------------------------------------
auth     ā–ˆā–ˆā–ˆā–ˆ (4 commits)
api      ā–ˆā–ˆā–ˆ  (3 commits)
ui       ā–ˆā–ˆ   (2 commits)
docs     ā–ˆ    (1 commit)

JSON Format:

{
  "analysis_type": "scope_extraction",
  "commits_analyzed": 50,
  "branch": "main",
  "statistics": {
    "total_scopes": 15,
    "scoped_commits": 44,
    "scoped_percentage": 88,
    "active_scopes": 12,
    "deprecated_scopes": 2
  },
  "scopes": [
    {
      "name": "auth",
      "count": 23,
      "percentage": 18.1,
      "category": "feature",
      "description": "Authentication and authorization",
      "hierarchy": null,
      "first_seen": "2024-01-15",
      "last_seen": "2024-03-10",
      "active": true,
      "recent_usage": 4,
      "examples": [
        "feat(auth): implement OAuth2",
        "fix(auth): session timeout",
        "refactor(auth): simplify middleware"
      ]
    },
    {
      "name": "api",
      "count": 19,
      "percentage": 14.9,
      "category": "backend",
      "description": "API endpoints and logic",
      "hierarchy": {
        "endpoints": 7,
        "middleware": 5,
        "validation": 3
      },
      "active": true,
      "recent_usage": 3
    }
  ],
  "categories": {
    "feature": {"count": 45, "percentage": 45},
    "backend": {"count": 32, "percentage": 32},
    "ui": {"count": 19, "percentage": 19}
  },
  "patterns": {
    "naming_style": "lowercase_hyphen",
    "uses_hierarchy": true,
    "uses_multi_scope": true,
    "multi_scope_percentage": 3
  },
  "recommendations": [
    "Use 'auth' for authentication/authorization changes",
    "Use 'api' for backend API modifications",
    "Consider hierarchical scopes for complex modules"
  ]
}

6. Scope Categorization Logic

Category Detection:

def categorize_scope(scope_name, usage_patterns):
    """Categorize scope based on name and usage"""

    # Authentication/Authorization
    if scope_name in ['auth', 'security', 'login', 'oauth']:
        return 'feature', 'Authentication'

    # API/Backend
    if scope_name in ['api', 'endpoint', 'backend', 'server']:
        return 'backend', 'API and backend'

    # UI/Frontend
    if scope_name in ['ui', 'component', 'style', 'frontend']:
        return 'ui', 'User interface'

    # Database
    if scope_name in ['db', 'database', 'schema', 'migration']:
        return 'backend', 'Database'

    # Infrastructure
    if scope_name in ['ci', 'cd', 'deploy', 'docker', 'k8s']:
        return 'infrastructure', 'Infrastructure'

    # Documentation
    if scope_name in ['docs', 'readme', 'changelog']:
        return 'documentation', 'Documentation'

    # Testing
    if scope_name in ['test', 'e2e', 'unit', 'integration']:
        return 'testing', 'Testing'

    # Default
    return 'other', 'Other'

7. Trend Analysis

Activity Tracking:

Scope Activity Timeline (last 30 days):

auth:  ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ (very active)
api:   ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ     (active)
ui:    ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ         (moderate)
db:    ā–ˆā–ˆā–ˆā–ˆ             (low)
test:  ā–ˆā–ˆ               (occasional)
docs:  ā–ˆ                (rare)

Deprecated Scope Detection:

def is_deprecated(scope):
    """Detect if scope is deprecated"""
    # Not used in last 20 commits
    if scope.last_seen_commit_index > 20:
        return True

    # Explicitly marked as deprecated
    if 'legacy' in scope.name or 'v1' in scope.name:
        return True

    return False

Error Handling

No scopes found:

  • Warning: "No scopes detected in commit history"
  • Suggestion: "Project may not use conventional commits format"
  • Return: Empty scope list with explanation

Minimal scopes:

  • Warning: "Only X scopes found with min_frequency threshold"
  • Suggestion: "Lower min_frequency or analyze more commits"

Malformed scopes:

  • Skip invalid entries
  • Log: "Skipped N malformed scope entries"
  • Continue with valid scopes

Integration Usage

By commit-assistant agent:

User modifies auth files:
  → Invoke: /history-analysis extract-scopes
  → Find: 'auth' is common scope (18.1%)
  → Suggest: Use 'auth' scope for this commit

By message-generation skill:

Generating commit message:
  → Extract scopes from history
  → Check if current files match known scopes
  → Auto-suggest appropriate scope

By identify-scope operation:

Unknown scope needed:
  → Check extracted scopes
  → Find similar/related scopes
  → Recommend best match

Success Criteria

Operation succeeds when:

  • All scopes extracted from commits
  • Frequencies calculated correctly
  • Hierarchies identified
  • Categories assigned accurately
  • Active/deprecated status determined
  • Recommendations generated
  • Output formatted properly

Performance

  • Extraction Time: ~1-2 seconds for 50 commits
  • Regex Matching: ~0.02ms per commit
  • Memory: Low (scope hash table only)

Operation: Learn Project

Purpose: Comprehensive project commit pattern learning - analyze all aspects of commit history to provide complete understanding of project conventions.

Parameters

From $ARGUMENTS (after operation name):

  • count:N - Number of commits to analyze (default: 100)
  • branch:name - Branch to analyze (default: current branch)
  • format:json|text - Output format (default: text)
  • save:path - Save results to file (optional)
  • full:true|false - Include detailed breakdown (default: false)

Workflow

1. Validate Repository

if ! git rev-parse --git-dir >/dev/null 2>&1; then
    echo "Error: Not in a git repository"
    exit 1
fi

if ! git log -1 >/dev/null 2>&1; then
    echo "Error: No commit history found"
    exit 1
fi

2. Execute Comprehensive Analysis

This operation orchestrates all other history-analysis operations for complete project learning:

Phase 1: Style Analysis

echo "Phase 1/4: Analyzing commit style..."
./.scripts/style-analyzer.sh <count> <branch>

Phase 2: Pattern Detection

echo "Phase 2/4: Detecting conventions..."
./.scripts/pattern-detector.py --count <count> --branch <branch> --detailed

Phase 3: Scope Extraction

echo "Phase 3/4: Extracting scopes..."
./.scripts/scope-extractor.sh --count <count> --branch <branch> --min-frequency 2

Phase 4: Convention Recommendations

echo "Phase 4/4: Generating recommendations..."
./.scripts/convention-recommender.py --count <count> --branch <branch> --priority all

3. Aggregate and Synthesize Results

Combine all analysis data into comprehensive project profile:

project_profile = {
    'metadata': {
        'project_name': get_repo_name(),
        'analysis_date': datetime.now(),
        'commits_analyzed': count,
        'branch': branch,
        'first_commit_date': get_first_commit_date(),
        'last_commit_date': get_last_commit_date()
    },
    'style': style_analysis_results,
    'patterns': pattern_detection_results,
    'scopes': scope_extraction_results,
    'recommendations': convention_recommendations,
    'confidence': calculate_confidence_score()
}

4. Generate Project Profile

Output Structure:

═══════════════════════════════════════════════════════════════
PROJECT COMMIT PROFILE
═══════════════════════════════════════════════════════════════

Repository: git-commit-assistant
Branch: main
Analysis Date: 2024-03-10 14:30:00
Commits Analyzed: 100 (from 2024-01-01 to 2024-03-10)

Overall Consistency Score: 85/100 (GOOD)
Confidence Level: HIGH (100 commits analyzed)

═══════════════════════════════════════════════════════════════
šŸ“Š EXECUTIVE SUMMARY
═══════════════════════════════════════════════════════════════

āœ“ Project uses conventional commits consistently (87%)
āœ“ Strong imperative mood usage (92%)
āœ“ Good issue reference practice (67%)
ā—‹ Moderate body usage (34%)
ā—‹ Occasional breaking change documentation (8%)

Recommended Actions:
  1. Maintain conventional commits format
  2. Increase body usage for complex changes
  3. Standardize breaking change documentation

═══════════════════════════════════════════════════════════════
šŸ“ COMMIT STYLE ANALYSIS
═══════════════════════════════════════════════════════════════

Format Distribution:
  Conventional Commits: 87% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–‘ā–‘ā–‘
  Simple Subject:       10% ā–ˆā–ˆā–ˆā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘
  Other:                3%  ā–ˆā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘

Subject Lines:
  Average Length:    47 characters (recommended: < 50)
  Standard Dev:      8 characters
  Exceeds 50 chars:  15% of commits

  Length Distribution:
    30-40 chars: ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ  (35%)
    41-50 chars: ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ (42%)
    51-60 chars: ā–ˆā–ˆā–ˆā–ˆ       (15%)
    61+ chars:   ā–ˆā–ˆ         (8%)

Body Usage:
  Has Body:          34% of commits
  Average Length:    120 characters
  Bullet Points:     89% of bodies
  Wrapping:          94% wrap at 72 chars

Footer Usage:
  Issue References:  67% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–‘ā–‘ā–‘ā–‘ā–‘
  Breaking Changes:  8%  ā–ˆā–ˆā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘
  Co-Authors:        2%  ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘
  Signed-Off:        12% ā–ˆā–ˆā–ˆā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘

═══════════════════════════════════════════════════════════════
šŸŽÆ COMMIT TYPE ANALYSIS
═══════════════════════════════════════════════════════════════

Type Distribution (from 87 conventional commits):

 1. feat      35% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ (30 commits)
    └─ New features and capabilities

 2. fix       30% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–‘     (26 commits)
    └─ Bug fixes and corrections

 3. docs      16% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–‘            (14 commits)
    └─ Documentation updates

 4. refactor  8%  ā–ˆā–ˆā–ˆā–ˆā–‘                 (7 commits)
    └─ Code restructuring

 5. test      5%  ā–ˆā–ˆā–ˆā–‘                  (4 commits)
    └─ Test additions/updates

 6. chore     4%  ā–ˆā–ˆā–‘                   (3 commits)
    └─ Maintenance tasks

 7. perf      2%  ā–ˆā–‘                    (2 commits)
    └─ Performance improvements

Type Usage Timeline (last 20 commits):
  feat:     ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ    (8 commits)
  fix:      ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ      (6 commits)
  docs:     ā–ˆā–ˆā–ˆ         (3 commits)
  refactor: ā–ˆā–ˆ          (2 commits)
  chore:    ā–ˆ           (1 commit)

═══════════════════════════════════════════════════════════════
šŸŽØ SCOPE ANALYSIS
═══════════════════════════════════════════════════════════════

Scopes Found: 15 unique
Scoped Commits: 88% (76/87 conventional commits)

Top Scopes by Frequency:

 1. auth          23% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ (20 commits)
    Category: Authentication
    Status: ACTIVE (used in last 10 commits)
    Examples:
      • feat(auth): implement OAuth2 authentication
      • fix(auth): handle session timeout correctly
      • refactor(auth): simplify middleware logic

 2. api           19% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ     (17 commits)
    Category: Backend
    Status: ACTIVE
    Hierarchy: api/endpoints (7), api/middleware (5), api/validation (3)

 3. ui            15% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ        (13 commits)
    Category: Frontend
    Status: ACTIVE
    Hierarchy: ui/components (8), ui/styles (4)

 4. db            12% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ           (10 commits)
    Category: Database
    Status: ACTIVE

 5. docs          11% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ            (9 commits)
    Category: Documentation
    Status: ACTIVE

 6-15. (core, config, test, ci, deploy, utils, types, scripts, docker, nginx)
       Combined: 20% (17 commits)

Scope Categories:
  Features:        45% (auth, payment, search, notifications)
  Backend:         32% (api, db, server, cache)
  Frontend:        19% (ui, components, styles)
  Infrastructure:  12% (ci, docker, deploy, nginx)
  Documentation:   11% (docs, readme, changelog)

═══════════════════════════════════════════════════════════════
šŸ” CONVENTION PATTERNS
═══════════════════════════════════════════════════════════════

Writing Style:
  Imperative Mood:      92% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–‘ā–‘
  Capitalized Subject:  94% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–‘ā–‘
  No Period at End:     88% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–‘ā–‘ā–‘
  Lowercase Scopes:     100% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ

Message Structure:
  Blank Line Before Body:  100% (all 34 bodies)
  Body Wrapped at 72:      94% (32/34 bodies)
  Bullet Points in Body:   89% (30/34 bodies)
  Footer Separated:        100% (all 67 footers)

Issue References:
  Format: "Closes #123"    45% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ
  Format: "Fixes #456"     38% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ
  Format: "Refs #789"      17% ā–ˆā–ˆā–ˆā–ˆā–ˆ

Breaking Changes:
  Format: "BREAKING CHANGE:" 100% (all 7 instances)
  Always in footer:          100%
  Includes description:      100%

═══════════════════════════════════════════════════════════════
šŸ’” RECOMMENDATIONS (PRIORITIZED)
═══════════════════════════════════════════════════════════════

šŸ”“ HIGH PRIORITY (Critical for Consistency)

1. āœ“ Continue Using Conventional Commits
   Current: 87% adoption
   Target: Maintain 85%+
   Impact: HIGH - Enables automation

2. āœ“ Maintain Imperative Mood
   Current: 92% compliance
   Target: Maintain 90%+
   Impact: HIGH - Readability and clarity

🟔 MEDIUM PRIORITY (Improve Quality)

3. ā—‹ Increase Body Usage for Complex Changes
   Current: 34% of commits
   Target: 50% for multi-file changes
   Impact: MEDIUM - Better documentation

   When to add body:
   • Changes affect >3 files
   • Complex logic modifications
   • Breaking changes
   • Security-related changes

4. ā—‹ Document Breaking Changes Consistently
   Current: 8% when applicable
   Target: 100% of breaking changes documented
   Impact: MEDIUM - User experience

🟢 LOW PRIORITY (Polish)

5. ā—‹ Consider Co-Author Attribution
   Current: 2% usage
   Target: Use for pair programming
   Impact: LOW - Team recognition

6. ā—‹ Add Signed-off-by for Compliance
   Current: 12% usage
   Target: If required by project policy
   Impact: LOW - Legal compliance

═══════════════════════════════════════════════════════════════
šŸ“š PROJECT-SPECIFIC STYLE GUIDE
═══════════════════════════════════════════════════════════════

COMMIT MESSAGE FORMAT
---------------------
<type>(<scope>): <subject>          ← 50 chars max, imperative mood

<body>                               ← Optional, explain "why"
- Use bullet points                  ← Wrap at 72 characters
- Multiple lines OK
- Blank line before footer

<footer>                             ← Optional
BREAKING CHANGE: description
Closes #123

APPROVED TYPES (use these)
--------------------------
feat     - New feature (35% of project commits)
fix      - Bug fix (30% of project commits)
docs     - Documentation (16% of project commits)
refactor - Code restructuring (8%)
test     - Testing (5%)
chore    - Maintenance (4%)
perf     - Performance (2%)

STANDARD SCOPES (project-specific)
----------------------------------
auth     - Authentication/authorization
api      - Backend API endpoints
ui       - User interface
db       - Database operations
docs     - Documentation
core     - Core functionality
config   - Configuration
test     - Testing infrastructure
ci       - CI/CD pipelines
deploy   - Deployment

STYLE RULES
-----------
āœ“ Use imperative mood ("add" not "added")
āœ“ Capitalize first letter of subject
āœ“ No period at end of subject line
āœ“ Use lowercase for scopes
āœ“ Wrap body at 72 characters
āœ“ Separate body and footer with blank line
āœ“ Use bullet points in body (with - or •)
āœ“ Reference issues: "Closes #123", "Fixes #456"
āœ“ Document breaking changes in footer

REAL EXAMPLES FROM THIS PROJECT
--------------------------------
Example 1: Feature with body
  feat(auth): implement OAuth2 authentication

  - Add OAuth2 flow implementation
  - Support Google and GitHub providers
  - Include middleware for route protection
  - Add configuration management

  Closes #123

Example 2: Bug fix
  fix(api): handle null pointer in user endpoint

  The endpoint was not checking for null user objects
  before accessing properties, causing crashes when
  invalid user IDs were provided.

  Fixes #456

Example 3: Breaking change
  feat(api): change authentication flow

  Update authentication to use OAuth2 tokens instead
  of API keys for improved security.

  BREAKING CHANGE: API now requires OAuth tokens
  instead of API keys. Update all client applications
  to use the new authentication flow.

  Closes #789

═══════════════════════════════════════════════════════════════
šŸ”§ IMPLEMENTATION GUIDE
═══════════════════════════════════════════════════════════════

1. SHARE WITH TEAM
   • Add style guide to CONTRIBUTING.md
   • Present in team meeting
   • Add to onboarding docs

2. CONFIGURE GIT
   Create .gitmessage template:

   # <type>(<scope>): <subject>
   #
   # <body>
   #
   # <footer>
   #
   # Types: feat, fix, docs, refactor, test, chore, perf
   # Scopes: auth, api, ui, db, docs, core, config

   Then: git config commit.template .gitmessage

3. ADD PRE-COMMIT HOOKS
   Install commitlint:
   npm install --save-dev @commitlint/cli @commitlint/config-conventional

   Configure commitlint.config.js:
   module.exports = {
     extends: ['@commitlint/config-conventional'],
     rules: {
       'scope-enum': [2, 'always', [
         'auth', 'api', 'ui', 'db', 'docs', 'core',
         'config', 'test', 'ci', 'deploy'
       ]]
     }
   };

4. ENABLE AUTOMATION
   • Automated changelog: standard-version
   • Semantic versioning: semantic-release
   • Commit linting: commitlint + husky

5. MONITOR COMPLIANCE
   Run this analysis monthly:
   /history-analysis learn-project count:100

═══════════════════════════════════════════════════════════════
šŸ“ˆ CONFIDENCE ASSESSMENT
═══════════════════════════════════════════════════════════════

Data Quality:     ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ HIGH
Sample Size:      100 commits āœ“ Sufficient
Time Range:       70 days āœ“ Representative
Consistency:      85/100 āœ“ Good
Pattern Clarity:  ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ HIGH

Confidence Level: HIGH

This analysis is reliable for:
āœ“ Establishing project guidelines
āœ“ Onboarding new developers
āœ“ Configuring automation tools
āœ“ Team discussions and decisions

═══════════════════════════════════════════════════════════════
šŸ’¾ SAVE OPTIONS
═══════════════════════════════════════════════════════════════

This analysis can be saved for reference:
  /history-analysis learn-project save:docs/commit-conventions.md

Or export as JSON for tooling:
  /history-analysis learn-project format:json save:commit-profile.json

═══════════════════════════════════════════════════════════════
Analysis Complete - Ready to Apply
═══════════════════════════════════════════════════════════════

5. Save to File (if requested)

If save:path parameter provided:

# Save text format
echo "$output" > "$save_path"

# Save JSON format
echo "$json_output" > "$save_path"

echo "āœ“ Analysis saved to: $save_path"

6. JSON Output Structure

{
  "metadata": {
    "project_name": "git-commit-assistant",
    "analysis_date": "2024-03-10T14:30:00Z",
    "commits_analyzed": 100,
    "branch": "main",
    "date_range": {
      "first_commit": "2024-01-01",
      "last_commit": "2024-03-10"
    }
  },
  "scores": {
    "overall_consistency": 85,
    "style_consistency": 87,
    "pattern_consistency": 92,
    "content_consistency": 67,
    "confidence": "high"
  },
  "style_analysis": {
    "conventional_commits_percentage": 87,
    "average_subject_length": 47,
    "body_usage_percentage": 34,
    "footer_usage_percentage": 67
  },
  "types": [...],
  "scopes": [...],
  "patterns": {...},
  "recommendations": {
    "high_priority": [...],
    "medium_priority": [...],
    "low_priority": [...]
  },
  "style_guide": {
    "format": "<type>(<scope>): <subject>",
    "types": [...],
    "scopes": [...],
    "rules": [...]
  },
  "examples": [...],
  "automation": {
    "commitlint_config": {...},
    "changelog_generator": "standard-version",
    "semantic_release": true
  }
}

Error Handling

No git repository:

  • Error: "Not in a git repository"
  • Guidance: Run from within git project directory

Insufficient commits:

  • Warning: "Only X commits available (recommended: 50+)"
  • Adjust: Analyze all available commits
  • Note: Lower confidence level

Analysis failure:

  • Partial results: Return what was successfully analyzed
  • Error details: Indicate which phase failed
  • Retry: Suggest re-running with different parameters

Integration Usage

New project setup:

Developer: "What are the commit conventions?"
  → Run: /history-analysis learn-project
  → Get: Complete style guide
  → Configure: Git template and hooks

Team standardization:

Lead: "Let's review our commit practices"
  → Run: /history-analysis learn-project save:docs/conventions.md
  → Review: Recommendations with team
  → Implement: Top priorities
  → Document: In CONTRIBUTING.md

Automation setup:

DevOps: "Configure commit validation"
  → Run: /history-analysis learn-project format:json
  → Extract: Approved types and scopes
  → Configure: commitlint with project rules
  → Deploy: Pre-commit hooks

Success Criteria

Operation succeeds when:

  • All 4 analysis phases complete
  • Results aggregated correctly
  • Comprehensive profile generated
  • Recommendations prioritized
  • Style guide created
  • Examples included
  • Implementation guidance provided
  • Confidence level assessed

Performance

  • Phase 1 (Style): ~2 seconds
  • Phase 2 (Patterns): ~3 seconds
  • Phase 3 (Scopes): ~2 seconds
  • Phase 4 (Recommendations): ~1 second
  • Total: ~8-10 seconds for 100 commits

History Analysis Skill

Purpose: Analyze git commit history to learn project-specific commit patterns, conventions, scope usage, and message styles. Provides intelligent recommendations that match the team's existing practices.

Router

Parse $ARGUMENTS to determine which history analysis operation to execute:

Available Operations:

  • analyze-style - Learn commit style from recent history
  • detect-patterns - Identify project-specific conventions
  • extract-scopes - Discover commonly used scopes
  • suggest-conventions - Recommend conventions based on history
  • learn-project - Comprehensive project pattern learning
  • learn - Alias for learn-project (full analysis)

Base Directory: /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/history-analysis

Routing Logic

Request: $ARGUMENTS
Parse: operation = first word, parameters = remainder

If operation is:
  - "analyze-style" → Read "./analyze-style.md" with parameters
  - "detect-patterns" → Read "./detect-patterns.md" with parameters
  - "extract-scopes" → Read "./extract-scopes.md" with parameters
  - "suggest-conventions" → Read "./suggest-conventions.md" with parameters
  - "learn-project" or "learn" → Read "./learn-project.md" with parameters
  - empty or unknown → Display usage information

Usage Examples

# Analyze commit style from recent history
/history-analysis analyze-style

# Analyze with custom commit count
/history-analysis analyze-style count:100

# Detect project conventions
/history-analysis detect-patterns

# Extract common scopes
/history-analysis extract-scopes

# Get convention recommendations
/history-analysis suggest-conventions

# Full project learning (comprehensive analysis)
/history-analysis learn-project

# Short alias for full learning
/history-analysis learn

Parameters

All operations support these optional parameters:

  • count:N - Number of commits to analyze (default: 50)
  • branch:name - Branch to analyze (default: current branch)
  • format:json|text - Output format (default: text)

Integration Points

This skill is designed to be invoked by:

  • commit-assistant agent - Learn project conventions before generating messages
  • message-generation skill - Validate messages against project style
  • User commands - Understand project commit patterns

Error Handling

If not in a git repository:

  • Return error: "Not in a git repository. Please run this command from within a git project."

If no commit history exists:

  • Return error: "No commit history found. This appears to be a new repository."

If git command fails:

  • Return error with git error message and troubleshooting guidance

Output Structure

All operations return structured data including:

  • Analysis results - Patterns, frequencies, statistics
  • Recommendations - Project-specific guidance
  • Examples - Sample commits from project
  • Confidence score - How reliable the analysis is

Execution:

  1. Parse $ARGUMENTS to extract operation and parameters
  2. Validate git repository exists
  3. Read and execute the appropriate operation file
  4. Return structured results

If operation is unrecognized, display:

Unknown operation: {operation}

Available operations:
  analyze-style       - Analyze commit message style
  detect-patterns     - Detect project conventions
  extract-scopes      - Extract common scopes
  suggest-conventions - Get convention recommendations
  learn-project       - Full project pattern learning

Usage: /history-analysis <operation> [parameters]
Example: /history-analysis analyze-style count:100

Operation: Suggest Conventions

Purpose: Generate project-specific commit message convention recommendations based on historical analysis and best practices.

Parameters

From $ARGUMENTS (after operation name):

  • count:N - Number of commits to analyze (default: 50)
  • branch:name - Branch to analyze (default: current branch)
  • format:json|text - Output format (default: text)
  • include_examples:true|false - Include example commits (default: true)
  • priority:high|medium|low|all - Filter by recommendation priority (default: all)

Workflow

1. Validate Repository

if ! git rev-parse --git-dir >/dev/null 2>&1; then
    echo "Error: Not in a git repository"
    exit 1
fi

2. Gather Historical Data

Execute analysis operations to collect data:

A. Style Analysis:

./.scripts/style-analyzer.sh <count> <branch>

B. Pattern Detection:

./.scripts/pattern-detector.py --count <count> --branch <branch>

C. Scope Extraction:

./.scripts/scope-extractor.sh --count <count> --branch <branch>

3. Execute Convention Recommender

Invoke the convention-recommender.py utility script:

./.scripts/convention-recommender.py --count <count> --branch <branch> --priority <priority>

The script will:

  • Analyze aggregated historical data
  • Identify current conventions and gaps
  • Generate recommendations by priority
  • Provide examples and implementation guidance
  • Create project-specific guidelines

4. Recommendation Categories

A. Format Recommendations

  • Commit message structure
  • Subject line format
  • Body organization
  • Footer conventions

B. Type Recommendations

  • Commonly used types
  • Type selection guidance
  • Project-specific type meanings

C. Scope Recommendations

  • Standard scopes for the project
  • Scope naming patterns
  • When to use each scope

D. Content Recommendations

  • Writing style (imperative mood, tense)
  • Capitalization and punctuation
  • Issue reference format
  • Breaking change documentation

E. Process Recommendations

  • Pre-commit validation
  • Atomicity guidelines
  • Review practices

5. Recommendation Priority Levels

HIGH Priority (Critical for consistency):

  • Adopt conventional commits if not using (< 50% usage)
  • Fix major inconsistencies (> 30% deviation)
  • Establish missing critical patterns

MEDIUM Priority (Improve quality):

  • Refine existing patterns (50-80% consistency)
  • Add missing optional elements
  • Enhance documentation practices

LOW Priority (Nice-to-have):

  • Fine-tune minor details
  • Advanced features (co-authors, trailers)
  • Optimization opportunities

6. Output Structure

Text Format (default):

Project-Specific Commit Convention Recommendations
==================================================

Analysis: 50 commits on branch 'main'
Current Consistency: 85/100 (GOOD)
Generated: 2024-03-10

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

šŸ”“ HIGH PRIORITY RECOMMENDATIONS

1. Continue Using Conventional Commits
   Status: āœ“ Already adopted (87% usage)
   Action: Maintain current practice
   Benefit: Enables automated changelog, semantic versioning

   Format: <type>(<scope>): <subject>
   Example from project:
     āœ“ feat(auth): implement OAuth2 authentication
     āœ“ fix(api): handle null pointer in user endpoint

2. Standardize Subject Line Length
   Status: ā—‹ Needs improvement (avg: 47 chars, σ=12)
   Action: Keep subject lines under 50 characters
   Current: 15% exceed limit
   Target: < 5% exceed limit

   āœ“ Good: "feat(auth): add OAuth provider support"
   āœ— Too long: "feat(auth): implement OAuth2 authentication with support for multiple providers including Google and GitHub"
   āœ“ Better: "feat(auth): add OAuth multi-provider support"

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🟔 MEDIUM PRIORITY RECOMMENDATIONS

3. Increase Body Usage for Complex Changes
   Status: ā—‹ Moderate usage (34% of commits)
   Action: Add body for non-trivial changes
   Benefit: Better context for code review and history

   When to add body:
   • Multiple files changed (>3)
   • Complex logic changes
   • Breaking changes
   • Security-related changes

   Example from project:
     feat(auth): implement OAuth2 authentication

     - Add OAuth2 flow implementation
     - Support Google and GitHub providers
     - Include middleware for route protection
     - Add configuration management

4. Consistent Issue References
   Status: āœ“ Good usage (67% of commits)
   Action: Reference issues consistently
   Current format: "Closes #123", "Fixes #456"
   Recommendation: Continue current practice

   Patterns detected in project:
     āœ“ Closes #123  (45% of references)
     āœ“ Fixes #456   (38% of references)
     āœ“ Refs #789    (17% of references)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🟢 LOW PRIORITY RECOMMENDATIONS

5. Consider Adding Co-Author Attribution
   Status: āœ— Rare usage (2% of commits)
   Action: Add co-authors for pair programming
   Format: Co-authored-by: Name <email>

   Example:
     feat(api): add user management endpoint

     Co-authored-by: Jane Doe <jane@example.com>

6. Document Breaking Changes Explicitly
   Status: ā—‹ Occasional (8% of commits)
   Action: Use BREAKING CHANGE footer when applicable

   Format:
     feat(api): change authentication flow

     BREAKING CHANGE: API now requires OAuth tokens
     instead of API keys. Update client applications.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

šŸ“‹ PROJECT-SPECIFIC STYLE GUIDE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

COMMIT MESSAGE FORMAT
---------------------
<type>(<scope>): <subject>

<body>

<footer>

TYPES (in order of frequency)
------------------------------
feat     - New features (35% of commits)
fix      - Bug fixes (30% of commits)
docs     - Documentation (16% of commits)
refactor - Code restructuring (8% of commits)
test     - Testing (5% of commits)
chore    - Maintenance (6% of commits)

COMMON SCOPES (use these)
-------------------------
auth     - Authentication/authorization (18%)
api      - Backend API (15%)
ui       - User interface (12%)
db       - Database (9%)
docs     - Documentation (9%)
config   - Configuration (6%)

STYLE RULES (current project standards)
----------------------------------------
āœ“ Use imperative mood ("add" not "added")
āœ“ Capitalize first letter of subject
āœ“ No period at end of subject
āœ“ Wrap body at 72 characters
āœ“ Blank line between subject and body
āœ“ Reference issues when applicable
āœ“ Use bullet points in body

EXAMPLES FROM THIS PROJECT
---------------------------
feat(auth): implement OAuth2 authentication

- Add OAuth2 flow implementation
- Support Google and GitHub providers
- Include middleware for route protection

Closes #123

---

fix(api): handle null pointer in user endpoint

The endpoint was not checking for null user objects
before accessing properties, causing crashes.

Fixes #456

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

šŸ“Š CONSISTENCY METRICS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Format:         87% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–‘ā–‘ā–‘
Conventions:    92% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–‘
Content:        67% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘ā–‘
Overall:        85% ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–‘ā–‘ā–‘ā–‘ā–‘

NEXT STEPS
----------
1. Share this guide with team
2. Add to CONTRIBUTING.md
3. Configure git commit template
4. Set up pre-commit hooks
5. Review in team meeting

AUTOMATION OPPORTUNITIES
-------------------------
• Pre-commit hook to validate format
• Automated changelog generation
• Semantic version bumping
• Commit message linting (commitlint)

JSON Format:

{
  "analysis_type": "convention_recommendations",
  "commits_analyzed": 50,
  "branch": "main",
  "consistency_score": 85,
  "generated_date": "2024-03-10",
  "recommendations": {
    "high_priority": [
      {
        "id": 1,
        "title": "Continue Using Conventional Commits",
        "status": "good",
        "current_usage": 87,
        "target_usage": 90,
        "action": "Maintain current practice",
        "benefit": "Enables automated tooling",
        "examples": [
          "feat(auth): implement OAuth2 authentication",
          "fix(api): handle null pointer"
        ]
      }
    ],
    "medium_priority": [...],
    "low_priority": [...]
  },
  "style_guide": {
    "format": "<type>(<scope>): <subject>",
    "types": [
      {"name": "feat", "percentage": 35, "description": "New features"},
      {"name": "fix", "percentage": 30, "description": "Bug fixes"}
    ],
    "scopes": [
      {"name": "auth", "percentage": 18, "description": "Authentication"},
      {"name": "api", "percentage": 15, "description": "Backend API"}
    ],
    "rules": [
      "Use imperative mood",
      "Capitalize first letter",
      "No period at end"
    ]
  },
  "automation": [
    "Pre-commit hook validation",
    "Automated changelog",
    "Semantic versioning"
  ]
}

7. Recommendation Generation Algorithm

def generate_recommendations(analysis_data):
    """
    Generate prioritized recommendations based on analysis.
    """
    recommendations = {
        'high_priority': [],
        'medium_priority': [],
        'low_priority': []
    }

    # Check conventional commits usage
    if analysis_data['conventional_commits_pct'] < 50:
        recommendations['high_priority'].append({
            'title': 'Adopt Conventional Commits',
            'action': 'Migrate to conventional commits format',
            'reason': 'Low usage ({}%)'.format(
                analysis_data['conventional_commits_pct']
            )
        })
    elif analysis_data['conventional_commits_pct'] < 80:
        recommendations['medium_priority'].append({
            'title': 'Increase Conventional Commits Usage',
            'action': 'Encourage team to use format consistently'
        })

    # Check subject line length
    avg_length = analysis_data['avg_subject_length']
    if avg_length > 60:
        recommendations['high_priority'].append({
            'title': 'Reduce Subject Line Length',
            'action': 'Keep subjects under 50 characters',
            'current': avg_length
        })

    # Check imperative mood
    if analysis_data['imperative_mood_pct'] < 80:
        recommendations['high_priority'].append({
            'title': 'Use Imperative Mood Consistently',
            'action': 'Use "add" not "added", "fix" not "fixed"'
        })

    # More checks...

    return recommendations

Error Handling

Insufficient data:

  • Warning: "Limited data (< 20 commits), recommendations may be less accurate"
  • Provide recommendations with confidence scores

No patterns detected:

  • Return: "No clear patterns detected. Consider establishing conventions."
  • Suggest: Standard conventional commits format as starting point

Mixed conventions:

  • Identify: "Multiple convention styles detected (X% conventional, Y% other)"
  • Recommend: "Migrate to single consistent style"

Integration Usage

By commit-assistant agent:

New developer onboarding:
  → Invoke: /history-analysis suggest-conventions
  → Present: Project-specific style guide
  → Configure: Git commit template

By team lead:

Improving consistency:
  → Run: /history-analysis suggest-conventions
  → Review: High-priority recommendations
  → Implement: Top 3 improvements
  → Document: In CONTRIBUTING.md

Success Criteria

Operation succeeds when:

  • All analysis data gathered
  • Recommendations prioritized correctly
  • Style guide generated
  • Examples provided
  • Actionable guidance included
  • Automation opportunities identified

Performance

  • Analysis Time: ~3-5 seconds for complete analysis
  • Recommendation Generation: ~1 second
  • Total Time: ~4-6 seconds

Operation: Add Footer

Add a properly formatted footer to commit message with breaking changes, issue references, and other metadata.

Parameters from $ARGUMENTS

Optional (at least one required):

  • breaking: - Breaking change description
  • closes: - Comma-separated issue numbers to close
  • fixes: - Comma-separated issue numbers to fix
  • refs: - Comma-separated issue numbers to reference
  • reviewed: - Reviewer name(s)
  • signed: - Signed-off-by name and email

Format: footer breaking:"API changed" closes:123,456

Workflow

Step 1: Parse Parameters

Extract parameters from $ARGUMENTS:

# Parse footer components
breaking=$(echo "$ARGUMENTS" | grep -oP 'breaking:"\K[^"]+')
closes=$(echo "$ARGUMENTS" | grep -oP 'closes:\K[0-9,]+')
fixes=$(echo "$ARGUMENTS" | grep -oP 'fixes:\K[0-9,]+')
refs=$(echo "$ARGUMENTS" | grep -oP 'refs:\K[0-9,]+')
reviewed=$(echo "$ARGUMENTS" | grep -oP 'reviewed:"\K[^"]+')
signed=$(echo "$ARGUMENTS" | grep -oP 'signed:"\K[^"]+')

Step 2: Validate Parameters

Check at least one parameter provided:

if [ -z "$breaking" ] && [ -z "$closes" ] && [ -z "$fixes" ] && [ -z "$refs" ] && [ -z "$reviewed" ] && [ -z "$signed" ]; then
  echo "ERROR: At least one footer parameter is required"
  echo "Usage: footer [breaking:\"<desc>\"] [closes:<nums>] [fixes:<nums>] [refs:<nums>]"
  exit 1
fi

Step 3: Invoke Footer Builder Script

Pass parameters to the utility script for proper formatting:

# Prepare JSON input
cat <<EOF | /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/message-generation/.scripts/footer-builder.py
{
  "breaking": "$breaking",
  "closes": "$closes",
  "fixes": "$fixes",
  "refs": "$refs",
  "reviewed": "$reviewed",
  "signed": "$signed"
}
EOF

The script will:

  • Format BREAKING CHANGE properly
  • Convert issue numbers to proper references
  • Order footer elements correctly
  • Ensure proper spacing and formatting

Step 4: Format Output

Present the generated footer:

FOOTER GENERATED
═══════════════════════════════════════════════

FOOTER:
───────────────────────────────────────────────
<blank line>
<formatted footer content>

VALIDATION:
───────────────────────────────────────────────
āœ“ Blank line before footer
āœ“ BREAKING CHANGE format correct
āœ“ Issue references valid
āœ“ Proper formatting

COMPONENTS:
───────────────────────────────────────────────
Breaking Changes: <yes/no>
Issues Closed: X
Issues Fixed: X
References: X
Signed-off: <yes/no>

═══════════════════════════════════════════════

Output Format

Return structured output:

  • Formatted footer text
  • Validation results
  • Component breakdown
  • Suggestions (if any)

Error Handling

No parameters provided:

ERROR: At least one footer parameter is required
Usage: footer [breaking:"<desc>"] [closes:<nums>] [fixes:<nums>]

Example: footer breaking:"authentication API changed" closes:123

Invalid issue number format:

ERROR: Invalid issue number format
Expected: closes:123 or closes:123,456
Received: closes:abc

Missing breaking change description:

ERROR: breaking parameter requires description
Usage: footer breaking:"<description of breaking change>"

Example: footer breaking:"API endpoint /auth removed"

Footer Format Rules

Order of Elements:

<blank line>
BREAKING CHANGE: <description>
Closes #<issue>
Fixes #<issue>
Refs #<issue>
Reviewed-by: <name>
Signed-off-by: <name> <email>

Breaking Changes:

  • Always use BREAKING CHANGE: (uppercase, singular)
  • Provide clear description
  • Can also use ! in subject: feat!: change API

Issue References:

  • Use Closes #123 for issues closed by this commit
  • Use Fixes #123 for bugs fixed by this commit
  • Use Refs #123 for related issues
  • Multiple issues: Closes #123, #456

Metadata:

  • Reviewed-by: for code review
  • Signed-off-by: for DCO compliance
  • Custom trailers as needed

Integration with Agent

The commit-assistant agent uses this operation to:

  1. Add breaking change notices
  2. Link commits to issues
  3. Add review metadata
  4. Ensure proper footer formatting

Usage Examples

Example 1: Breaking Change

# Input
/message-generation footer breaking:"authentication API endpoint changed from /login to /auth/login"

# Output
FOOTER:

BREAKING CHANGE: authentication API endpoint changed from /login to
/auth/login

Example 2: Close Issues

# Input
/message-generation footer closes:123,456,789

# Output
FOOTER:

Closes #123, #456, #789

Example 3: Fix and Close

# Input
/message-generation footer fixes:42 closes:100

# Output
FOOTER:

Fixes #42
Closes #100

Example 4: Complete Footer

# Input
/message-generation footer breaking:"remove deprecated API" closes:200 signed:"John Doe <john@example.com>"

# Output
FOOTER:

BREAKING CHANGE: remove deprecated API
Closes #200
Signed-off-by: John Doe <john@example.com>

Example 5: Multiple Issue Fixes

# Input
/message-generation footer fixes:10,20,30 refs:100

# Output
FOOTER:

Fixes #10, #20, #30
Refs #100

Best Practices

Breaking Changes:

  • āœ… "BREAKING CHANGE: API endpoint changed"
  • āŒ "Breaking change: api endpoint changed"
  • āœ… Clear description of what broke
  • āŒ Vague "things changed"

Issue References:

  • āœ… "Closes #123" (actually closes)
  • āŒ "Closes #123" (just mentions)
  • āœ… "Refs #100" (related)
  • āŒ "See issue 100"

Issue Linking Semantics:

  • Closes - Pull request or feature complete
  • Fixes - Bug fix
  • Refs - Related but not closed
  • Resolves - Alternative to Closes

When to Include a Footer

Include footer when:

  • Breaking changes introduced
  • Closes or fixes issues
  • Multiple reviewers
  • DCO/signing required
  • Related work references

Omit footer when:

  • No breaking changes
  • No issue tracking
  • No special metadata
  • Simple standalone commit

Breaking Change Detection

Patterns that indicate breaking changes:

  • API endpoint changes
  • Function signature changes
  • Removed features
  • Changed behavior
  • Dependency major version bumps
  • Configuration format changes

How to communicate breaking changes:

BREAKING CHANGE: <brief description>

<longer explanation of what changed>
<migration path if applicable>

Alternative notation:

feat!: change API endpoint

# The ! indicates breaking change

Footer Templates

Feature with Issue:

Closes #<issue>

Bug Fix:

Fixes #<issue>

Breaking Change with Migration:

BREAKING CHANGE: <what changed>

Migration: <how to update>
Closes #<issue>

Multiple Issues:

Fixes #<bug1>, #<bug2>
Closes #<feature>
Refs #<related>

Signed Commit:

Reviewed-by: <reviewer>
Signed-off-by: <author> <email>

GitHub/GitLab Integration

GitHub Keywords (auto-close issues):

  • Closes, Closed, Close
  • Fixes, Fixed, Fix
  • Resolves, Resolved, Resolve

GitLab Keywords:

  • Closes, Closed, Close (same as GitHub)
  • Fixes, Fixed, Fix
  • Resolves, Resolved, Resolve
  • Implements, Implemented, Implement

Format:

Closes #123                    # Same repository
Closes user/repo#123          # Different repository
Closes https://github.com/... # Full URL

Footer Validation

Valid footer format:

āœ“ Blank line before footer
āœ“ BREAKING CHANGE in capitals
āœ“ Issue numbers have # prefix
āœ“ Proper token format (Closes, Fixes, etc.)
āœ“ Valid email in Signed-off-by

Invalid footer format:

āœ— No blank line before footer
āœ— "Breaking change:" (lowercase)
āœ— "Closes 123" (missing #)
āœ— "Resolves issue 123" (wrong format)
āœ— Invalid email format

Operation: Complete Message

Generate a complete, well-formatted commit message by orchestrating subject generation, body composition, and footer creation.

Parameters from $ARGUMENTS

Required:

  • type: - Commit type (feat, fix, docs, etc.)

Optional:

  • scope: - Affected module/component
  • description: - Brief description (if not provided, derived from files)
  • files: - Comma-separated file paths for context
  • changes: - Comma-separated list of changes
  • why: - Explanation of why changes were made
  • breaking: - Breaking change description
  • closes: - Issue numbers to close
  • fixes: - Issue numbers to fix
  • include_body: - Include body (true|false, default: true if multiple files)
  • include_footer: - Include footer (true|false, default: true if breaking/issues)

Format: complete type:feat scope:auth files:"file1.js,file2.js" breaking:"API changed" closes:123

Workflow

Step 1: Parse All Parameters

Extract all parameters from $ARGUMENTS:

# Required
type=$(echo "$ARGUMENTS" | grep -oP 'type:\K[^ ]+')

# Optional
scope=$(echo "$ARGUMENTS" | grep -oP 'scope:\K[^ ]+')
description=$(echo "$ARGUMENTS" | grep -oP 'description:"\K[^"]+' || echo "$ARGUMENTS" | grep -oP 'description:\K[^ ]+')
files=$(echo "$ARGUMENTS" | grep -oP 'files:"\K[^"]+' || echo "$ARGUMENTS" | grep -oP 'files:\K[^ ]+')
changes=$(echo "$ARGUMENTS" | grep -oP 'changes:"\K[^"]+')
why=$(echo "$ARGUMENTS" | grep -oP 'why:"\K[^"]+')
breaking=$(echo "$ARGUMENTS" | grep -oP 'breaking:"\K[^"]+')
closes=$(echo "$ARGUMENTS" | grep -oP 'closes:\K[0-9,]+')
fixes=$(echo "$ARGUMENTS" | grep -oP 'fixes:\K[0-9,]+')
include_body=$(echo "$ARGUMENTS" | grep -oP 'include_body:\K(true|false)' || echo "auto")
include_footer=$(echo "$ARGUMENTS" | grep -oP 'include_footer:\K(true|false)' || echo "auto")

Step 2: Validate Required Parameters

Check type is provided:

if [ -z "$type" ]; then
  echo "ERROR: type parameter is required"
  echo "Usage: complete type:<type> [scope:<scope>] [files:\"<files>\"]"
  exit 1
fi

Validate type:

valid_types="feat fix docs style refactor perf test build ci chore revert"
if ! echo "$valid_types" | grep -qw "$type"; then
  echo "ERROR: Invalid type '$type'"
  echo "Valid types: $valid_types"
  exit 1
fi

Step 3: Derive Missing Parameters

If description not provided, derive from files:

if [ -z "$description" ] && [ -n "$files" ]; then
  # Analyze files to create description
  file_count=$(echo "$files" | tr ',' '\n' | wc -l)
  if [ $file_count -eq 1 ]; then
    description="update $(basename $files)"
  else
    # Extract common directory or feature
    description="update ${file_count} files"
  fi
fi

Determine body inclusion:

if [ "$include_body" = "auto" ]; then
  file_count=$(echo "$files" | tr ',' '\n' | wc -l)
  if [ $file_count -gt 1 ] || [ -n "$changes" ] || [ -n "$why" ]; then
    include_body="true"
  else
    include_body="false"
  fi
fi

Determine footer inclusion:

if [ "$include_footer" = "auto" ]; then
  if [ -n "$breaking" ] || [ -n "$closes" ] || [ -n "$fixes" ]; then
    include_footer="true"
  else
    include_footer="false"
  fi
fi

Step 4: Generate Subject Line

Read and execute generate-subject.md:

# Build subject arguments
subject_args="subject type:$type"
[ -n "$scope" ] && subject_args="$subject_args scope:$scope"
[ -n "$description" ] && subject_args="$subject_args description:\"$description\""

# Invoke subject generation
subject_result=$(bash -c "cd /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/message-generation && cat generate-subject.md")

# Extract generated subject line
subject_line="<generated subject>"

Store subject line:

COMMIT_MESSAGE="$subject_line"

Step 5: Generate Body (if needed)

If include_body is true, read and execute write-body.md:

if [ "$include_body" = "true" ]; then
  # Build body arguments
  body_args="body"

  if [ -n "$changes" ]; then
    body_args="$body_args changes:\"$changes\""
  elif [ -n "$files" ]; then
    # Derive changes from files
    body_args="$body_args changes:\"$files\""
  fi

  [ -n "$why" ] && body_args="$body_args why:\"$why\""

  # Invoke body generation
  body_result=$(bash -c "cd /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/message-generation && cat write-body.md")

  # Extract generated body
  body_content="<generated body>"

  # Append to message (with blank line)
  COMMIT_MESSAGE="$COMMIT_MESSAGE

$body_content"
fi

Step 6: Generate Footer (if needed)

If include_footer is true, read and execute add-footer.md:

if [ "$include_footer" = "true" ]; then
  # Build footer arguments
  footer_args="footer"
  [ -n "$breaking" ] && footer_args="$footer_args breaking:\"$breaking\""
  [ -n "$closes" ] && footer_args="$footer_args closes:$closes"
  [ -n "$fixes" ] && footer_args="$footer_args fixes:$fixes"

  # Invoke footer generation
  footer_result=$(bash -c "cd /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/message-generation && cat add-footer.md")

  # Extract generated footer
  footer_content="<generated footer>"

  # Append to message (with blank line)
  COMMIT_MESSAGE="$COMMIT_MESSAGE

$footer_content"
fi

Step 7: Validate Complete Message

Read and execute validate-message.md:

# Invoke validation
validation_result=$(bash -c "cd /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/message-generation && cat validate-message.md")

# Parse validation result
validation_status="<VALID|INVALID>"
validation_score="<score>"

Step 8: Format Final Output

Present the complete commit message:

COMPLETE COMMIT MESSAGE GENERATED
═══════════════════════════════════════════════

MESSAGE:
───────────────────────────────────────────────
<subject line>

<body content if present>

<footer content if present>
───────────────────────────────────────────────

COMPONENTS:
───────────────────────────────────────────────
Subject: āœ“ Generated (XX chars)
Body: āœ“ Generated (X lines) / ⊘ Omitted
Footer: āœ“ Generated / ⊘ Omitted

VALIDATION:
───────────────────────────────────────────────
Format: āœ“ Conventional Commits
Status: āœ“ VALID
Score: XX/100

STATISTICS:
───────────────────────────────────────────────
Total Lines: X
Subject Length: XX/50 chars
Body Lines: X (if present)
Footer Elements: X (if present)

READY TO COMMIT:
───────────────────────────────────────────────
git commit -m "$(cat <<'EOF'
<complete message here>
EOF
)"

═══════════════════════════════════════════════

Output Format

Return structured output with:

  • Complete formatted message
  • Component breakdown
  • Validation results
  • Statistics
  • Ready-to-use git command

Error Handling

Missing required parameters:

ERROR: type parameter is required
Usage: complete type:<type> [scope:<scope>] [files:"<files>"]

Example: complete type:feat scope:auth files:"auth.js,provider.js"

Invalid type:

ERROR: Invalid type 'feature'
Valid types: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert

Validation fails:

WARNING: Generated message has issues
<validation errors>

Message generated but may need manual adjustment.

Insufficient context:

ERROR: Insufficient information to generate message
Provide either:
  - description: explicit description
  - files: files changed for context
  - changes: list of changes made

Example: complete type:feat description:"add authentication"

Integration with Agent

The commit-assistant agent uses this operation as the primary message generation workflow:

1. User: "commit my changes"
   ↓
2. Agent: Analyze changes (/commit-analysis analyze)
   → type=feat, scope=auth, files=[...]
   ↓
3. Agent: Generate complete message (THIS OPERATION)
   → /message-generation complete type:feat scope:auth files:"..."
   ↓
4. Operation: Orchestrate generation
   → Generate subject
   → Generate body (if multiple files)
   → Generate footer (if issues/breaking)
   → Validate complete message
   ↓
5. Return: Complete, validated message
   ↓
6. Agent: Present to user for approval

Usage Examples

Example 1: Simple Commit (Subject Only)

# Input
/message-generation complete type:fix description:"resolve login crash"

# Output
MESSAGE:
fix: resolve login crash

COMPONENTS:
Subject: āœ“ (26/50 chars)
Body: ⊘ Omitted (single change)
Footer: ⊘ Omitted (no issues)

VALIDATION: āœ“ VALID (100/100)

Example 2: Feature with Multiple Files

# Input
/message-generation complete type:feat scope:auth files:"oauth.js,providers/google.js,providers/github.js"

# Output
MESSAGE:
feat(auth): add OAuth authentication

- Add OAuth2 authentication module
- Implement Google provider
- Implement GitHub provider

COMPONENTS:
Subject: āœ“ (36/50 chars)
Body: āœ“ Generated (3 lines)
Footer: ⊘ Omitted

VALIDATION: āœ“ VALID (95/100)

Example 3: Breaking Change with Issues

# Input
/message-generation complete type:feat scope:api description:"redesign authentication API" breaking:"authentication endpoints changed" closes:100,101

# Output
MESSAGE:
feat(api): redesign authentication API

- Redesign authentication endpoints
- Improve security with OAuth2
- Simplify client integration

BREAKING CHANGE: authentication endpoints changed from /login and
/logout to /auth/login and /auth/logout
Closes #100, #101

COMPONENTS:
Subject: āœ“ (42/50 chars)
Body: āœ“ Generated (3 lines)
Footer: āœ“ Generated (breaking + issues)

VALIDATION: āœ“ VALID (100/100)

Example 4: Bug Fix with Context

# Input
/message-generation complete type:fix scope:api files:"user.js" why:"prevent null pointer when user not found" fixes:42

# Output
MESSAGE:
fix(api): resolve null pointer in user endpoint

- Add null check for user lookup
- Return 404 when user not found
- Add error handling

Prevent null pointer exception when user is not found in database.

Fixes #42

COMPONENTS:
Subject: āœ“ (46/50 chars)
Body: āœ“ Generated (5 lines with context)
Footer: āœ“ Generated (issue fix)

VALIDATION: āœ“ VALID (100/100)

Example 5: Documentation Update

# Input
/message-generation complete type:docs files:"README.md" description:"add installation instructions"

# Output
MESSAGE:
docs: add installation instructions

COMPONENTS:
Subject: āœ“ (36/50 chars)
Body: ⊘ Omitted (docs only)
Footer: ⊘ Omitted

VALIDATION: āœ“ VALID (100/100)

Example 6: Explicit Body and Footer Control

# Input
/message-generation complete type:refactor scope:database description:"optimize queries" include_body:true include_footer:false changes:"Add indexes,Optimize joins,Cache results"

# Output
MESSAGE:
refactor(database): optimize queries

- Add database indexes
- Optimize query joins
- Implement result caching

COMPONENTS:
Subject: āœ“ (35/50 chars)
Body: āœ“ Forced inclusion
Footer: ⊘ Forced omission

VALIDATION: āœ“ VALID (95/100)

Best Practices

Provide sufficient context:

  • āœ… type + scope + files (agent can derive details)
  • āœ… type + description + changes (explicit)
  • āŒ type only (insufficient)

Let automation work:

  • āœ… Trust body/footer auto-inclusion logic
  • āŒ Manually force inclusion when not needed

Use breaking and issues:

  • āœ… Always include breaking changes
  • āœ… Always link to issues
  • āŒ Forget to document breaking changes

Validate assumptions:

  • āœ… Review generated message
  • āœ… Check validation results
  • āŒ Blindly commit generated message

Decision Logic

Body inclusion decision tree:

if include_body explicitly set:
  use explicit value
else if multiple files changed (>1):
  include body
else if changes list provided:
  include body
else if why context provided:
  include body
else:
  omit body

Footer inclusion decision tree:

if include_footer explicitly set:
  use explicit value
else if breaking change provided:
  include footer
else if issue numbers provided (closes/fixes):
  include footer
else:
  omit footer

Orchestration Flow

Step-by-step orchestration:

1. Parse parameters
   ↓
2. Validate required (type)
   ↓
3. Derive missing (description from files)
   ↓
4. Determine body/footer inclusion
   ↓
5. Generate subject (always)
   → Invoke: generate-subject.md
   ↓
6. Generate body (if needed)
   → Invoke: write-body.md
   ↓
7. Generate footer (if needed)
   → Invoke: add-footer.md
   ↓
8. Combine all parts
   ↓
9. Validate complete message
   → Invoke: validate-message.md
   ↓
10. Return complete message with validation

Error Recovery

If subject generation fails:

  • Return error immediately
  • Do not proceed to body/footer

If body generation fails:

  • Return subject only
  • Mark body as "generation failed"
  • Continue to footer if needed

If footer generation fails:

  • Return subject + body
  • Mark footer as "generation failed"

If validation fails:

  • Return message anyway
  • Include validation errors
  • Let user decide to fix or use

Performance Considerations

Typical generation time:

  • Subject only: <100ms
  • Subject + body: <200ms
  • Subject + body + footer: <300ms
  • With validation: +50ms

Optimization:

  • Cache repeated operations
  • Minimize script invocations
  • Stream output for large bodies

Advanced Usage

Template-based generation:

# Feature template
complete type:feat scope:$SCOPE template:feature

# Bugfix template
complete type:fix scope:$SCOPE template:bugfix fixes:$ISSUE

From analysis results:

# Agent workflow
analysis=$(/commit-analysis analyze)
type=$(echo "$analysis" | jq -r '.type')
scope=$(echo "$analysis" | jq -r '.scope')
files=$(echo "$analysis" | jq -r '.files | join(",")')

/message-generation complete type:$type scope:$scope files:"$files"

Interactive refinement:

# Generate initial
msg=$(/message-generation complete type:feat scope:auth)

# User: "too long"
# Regenerate with constraint
msg=$(/message-generation complete type:feat scope:auth description:"add OAuth" include_body:false)

Operation: Generate Subject Line

Create a properly formatted subject line following the conventional commits standard: <type>(<scope>): <description>

Parameters from $ARGUMENTS

Required:

  • type: - Commit type (feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert)
  • description: - Brief description of changes

Optional:

  • scope: - Affected module/component
  • max_length: - Maximum length (default: 50, hard limit: 72)

Format: subject type:feat scope:auth description:"add OAuth authentication"

Workflow

Step 1: Parse Parameters

Extract parameters from $ARGUMENTS:

# Parse key:value pairs
type=$(echo "$ARGUMENTS" | grep -oP 'type:\K[^ ]+')
scope=$(echo "$ARGUMENTS" | grep -oP 'scope:\K[^ ]+')
description=$(echo "$ARGUMENTS" | grep -oP 'description:"\K[^"]+' || echo "$ARGUMENTS" | grep -oP 'description:\K[^ ]+')
max_length=$(echo "$ARGUMENTS" | grep -oP 'max_length:\K[0-9]+' || echo "50")

Step 2: Validate Parameters

Check required parameters:

if [ -z "$type" ]; then
  echo "ERROR: type parameter is required"
  echo "Usage: subject type:<type> description:\"<desc>\" [scope:<scope>]"
  exit 1
fi

if [ -z "$description" ]; then
  echo "ERROR: description parameter is required"
  echo "Usage: subject type:<type> description:\"<desc>\" [scope:<scope>]"
  exit 1
fi

Validate type:

valid_types="feat fix docs style refactor perf test build ci chore revert"
if ! echo "$valid_types" | grep -qw "$type"; then
  echo "ERROR: Invalid type '$type'"
  echo "Valid types: $valid_types"
  exit 1
fi

Step 3: Invoke Subject Generator Script

Pass parameters to the utility script for intelligent formatting:

# Prepare JSON input
cat <<EOF | /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/message-generation/.scripts/subject-generator.py
{
  "type": "$type",
  "scope": "$scope",
  "description": "$description",
  "max_length": $max_length
}
EOF

The script will:

  • Format the subject line
  • Enforce imperative mood
  • Ensure proper capitalization
  • Check character limits
  • Suggest improvements if needed

Step 4: Format Output

Present the generated subject line:

SUBJECT LINE GENERATED
═══════════════════════════════════════════════

Subject: <type>(<scope>): <description>
Length: XX/50 characters

VALIDATION:
───────────────────────────────────────────────
āœ“ Type is valid
āœ“ Imperative mood used
āœ“ No capitalization after colon
āœ“ No period at end
āœ“ Within character limit

SUGGESTIONS:
───────────────────────────────────────────────
- <improvement 1 if applicable>
- <improvement 2 if applicable>

═══════════════════════════════════════════════

Output Format

Return structured output:

  • Generated subject line
  • Character count
  • Validation results
  • Suggestions for improvement (if any)

Error Handling

Missing required parameters:

ERROR: Missing required parameter 'type'
Usage: subject type:<type> description:"<desc>" [scope:<scope>]

Example: subject type:feat description:"add user authentication"

Invalid type:

ERROR: Invalid type 'feature'
Valid types: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert

Description too long:

WARNING: Subject line exceeds 50 characters (XX chars)
Current: <type>(<scope>): <very long description>

Suggestion: Shorten description or move details to body
Recommended: <type>(<scope>): <shortened description>

Non-imperative mood:

WARNING: Use imperative mood
Current: "added authentication"
Correct: "add authentication"

Subject Line Rules

Imperative Mood:

  • āœ… "add feature" (correct)
  • āŒ "added feature" (past tense)
  • āŒ "adds feature" (present tense)

Capitalization:

  • āœ… "feat: add login" (lowercase after colon)
  • āŒ "feat: Add login" (uppercase after colon)

Punctuation:

  • āœ… "fix: resolve crash" (no period)
  • āŒ "fix: resolve crash." (period at end)

Length:

  • Target: 50 characters maximum
  • Hard limit: 72 characters
  • Include type, scope, colon, and description

Integration with Agent

The commit-assistant agent uses this operation to:

  1. Generate subject lines during commit message creation
  2. Validate subject line format
  3. Suggest improvements for clarity
  4. Ensure conventional commits compliance

Usage Examples

Example 1: Basic Subject

# Input
/message-generation subject type:feat description:"add user authentication"

# Output
Subject: feat: add user authentication
Length: 30/50 characters
Status: āœ“ Valid

Example 2: Subject with Scope

# Input
/message-generation subject type:fix scope:api description:"resolve null pointer"

# Output
Subject: fix(api): resolve null pointer
Length: 30/50 characters
Status: āœ“ Valid

Example 3: Long Description Warning

# Input
/message-generation subject type:feat description:"add comprehensive OAuth2 authentication with multiple providers"

# Output
WARNING: Subject exceeds 50 characters (69 chars)
Suggested: feat: add OAuth2 authentication
Move details to body: "with multiple providers"

Example 4: Mood Correction

# Input
/message-generation subject type:fix description:"fixed login bug"

# Output
Subject: fix: fix login bug
WARNING: Use imperative mood
Suggested: fix: resolve login bug

Best Practices

Be Specific:

  • āœ… "add OAuth authentication"
  • āŒ "update code"

Focus on What:

  • āœ… "fix crash on login"
  • āŒ "fix issue with the login button that crashes when clicked"

Omit Implementation:

  • āœ… "improve query performance"
  • āŒ "add database index to users table"

Use Conventional Types:

  • āœ… "feat: add feature"
  • āŒ "feature: add feature"

Message Generation Skill - Semantic Commit Message Generation

Generate well-formatted commit messages that follow the Conventional Commits standard with proper type, scope, subject, body, and footer.

Operations

  • subject - Generate subject line: <type>(<scope>): <description>
  • body - Compose commit body with bullet points
  • footer - Add footer with breaking changes and issue references
  • validate - Check conventional commits compliance
  • complete - Generate full commit message (subject + body + footer)

Router Logic

Parse $ARGUMENTS to determine which operation to perform:

  1. Extract operation from first word of $ARGUMENTS

  2. Extract remaining arguments as operation parameters

  3. Route to appropriate instruction file:

    • "subject" → Read /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/message-generation/generate-subject.md
    • "body" → Read /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/message-generation/write-body.md
    • "footer" → Read /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/message-generation/add-footer.md
    • "validate" → Read /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/message-generation/validate-message.md
    • "complete" → Read /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/message-generation/complete-message.md
  4. Execute instructions with parameters

  5. Return formatted commit message or validation results

Error Handling

  • If operation is unknown, list available operations
  • If required parameters are missing, show required format
  • If message validation fails, provide specific corrections
  • If character limits exceeded, suggest rewording

Usage Examples

# Generate subject line only
/message-generation subject type:feat scope:auth description:"add OAuth authentication"

# Write commit body
/message-generation body changes:"Implement OAuth2 flow,Add provider support,Include middleware"

# Add footer with issue references
/message-generation footer breaking:"authentication API changed" closes:123

# Validate existing message
/message-generation validate message:"feat(auth): add OAuth"

# Generate complete commit message
/message-generation complete type:feat scope:auth files:"src/auth/oauth.js,src/auth/providers.js"

Conventional Commits Format

Message Structure:

<type>(<scope>): <subject>          ← Max 50 chars, imperative mood

<body>                               ← Optional, wrap at 72 chars
- Bullet point describing change 1
- Bullet point describing change 2

<footer>                             ← Optional
BREAKING CHANGE: description
Closes #123, #456

Valid Types (priority order):

  1. feat - New feature
  2. fix - Bug fix
  3. docs - Documentation only
  4. style - Formatting (no code change)
  5. refactor - Code restructuring
  6. perf - Performance improvement
  7. test - Test additions/updates
  8. build - Build system or dependencies
  9. ci - CI/CD configuration
  10. chore - Other maintenance
  11. revert - Revert previous commit

Base directory: /home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/message-generation

Current request: $ARGUMENTS

Parse operation and route to appropriate instruction file.

Operation: Validate Message

Validate a commit message against the conventional commits standard, checking format, style, and best practices.

Parameters from $ARGUMENTS

Required:

  • message: - Full commit message to validate (use quotes for multi-line)

Optional:

  • strict: - Enable strict mode (true|false, default: false)
  • max_subject: - Maximum subject length (default: 50)
  • max_line: - Maximum body line length (default: 72)

Format: validate message:"feat: add feature" or validate message:"$(cat commit.txt)"

Workflow

Step 1: Parse Parameters

Extract message from $ARGUMENTS:

# Parse message (supports quoted multi-line)
message=$(echo "$ARGUMENTS" | sed -n 's/.*message:"\(.*\)".*/\1/p')
if [ -z "$message" ]; then
  message=$(echo "$ARGUMENTS" | sed 's/^validate //')
fi

strict=$(echo "$ARGUMENTS" | grep -oP 'strict:\K(true|false)' || echo "false")
max_subject=$(echo "$ARGUMENTS" | grep -oP 'max_subject:\K[0-9]+' || echo "50")
max_line=$(echo "$ARGUMENTS" | grep -oP 'max_line:\K[0-9]+' || echo "72")

Step 2: Validate Parameters

Check message provided:

if [ -z "$message" ]; then
  echo "ERROR: message parameter is required"
  echo "Usage: validate message:\"<commit message>\""
  exit 1
fi

Step 3: Invoke Message Validator Script

Pass message to validation script:

# Export variables
export MESSAGE="$message"
export STRICT_MODE="$strict"
export MAX_SUBJECT="$max_subject"
export MAX_LINE="$max_line"

# Run validator
/home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/message-generation/.scripts/message-validator.sh

The script performs comprehensive validation:

  • Format compliance
  • Type validation
  • Subject line rules
  • Body formatting
  • Footer format
  • Character limits
  • Mood and style
  • Best practices

Step 4: Format Validation Report

Present detailed validation results:

COMMIT MESSAGE VALIDATION
═══════════════════════════════════════════════

MESSAGE:
───────────────────────────────────────────────
<commit message displayed>

FORMAT VALIDATION:
───────────────────────────────────────────────
āœ“ Conventional commits format
āœ“ Valid commit type
āœ“ Scope format correct (if present)
āœ“ Blank line before body (if present)
āœ“ Blank line before footer (if present)

SUBJECT LINE:
───────────────────────────────────────────────
āœ“ Length: XX/50 characters
āœ“ Imperative mood
āœ“ No capitalization after colon
āœ“ No period at end
āœ“ Clear and descriptive

BODY (if present):
───────────────────────────────────────────────
āœ“ Blank line after subject
āœ“ Lines wrapped at 72 characters
āœ“ Bullet points formatted correctly
āœ“ Explains what and why

FOOTER (if present):
───────────────────────────────────────────────
āœ“ Blank line before footer
āœ“ BREAKING CHANGE format correct
āœ“ Issue references valid
āœ“ Metadata formatted properly

OVERALL:
───────────────────────────────────────────────
Status: āœ“ VALID / āœ— INVALID
Score: XX/100

WARNINGS (if any):
───────────────────────────────────────────────
- Subject line is long (consider shortening)
- Body line exceeds 72 characters

ERRORS (if any):
───────────────────────────────────────────────
- Invalid commit type
- Missing imperative mood

SUGGESTIONS:
───────────────────────────────────────────────
- <improvement 1>
- <improvement 2>

═══════════════════════════════════════════════

Output Format

Return structured validation report with:

  • Format compliance check
  • Subject line validation
  • Body validation (if present)
  • Footer validation (if present)
  • Overall score
  • Warnings (non-critical issues)
  • Errors (critical issues)
  • Suggestions for improvement

Error Handling

No message provided:

ERROR: message parameter is required
Usage: validate message:"<commit message>"

Example: validate message:"feat: add authentication"

Empty message:

ERROR: Commit message is empty
Provide a commit message to validate

Completely invalid format:

VALIDATION FAILED
Format does not match conventional commits standard

Expected: <type>(<scope>): <subject>
Received: <message>

See: https://www.conventionalcommits.org/

Validation Rules

Subject Line Validation

Format: <type>(<scope>): <subject>

Type validation:

  • āœ“ Valid types: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert
  • āœ— Invalid types: feature, bugfix, update, change

Scope validation:

  • āœ“ Lowercase alphanumeric
  • āœ“ Hyphen allowed
  • āœ— Spaces not allowed
  • āœ— Special characters not allowed

Subject validation:

  • āœ“ Imperative mood (add, fix, update)
  • āœ— Past tense (added, fixed)
  • āœ— Present tense (adds, fixes)
  • āœ“ Lowercase after colon
  • āœ— Uppercase after colon
  • āœ“ No period at end
  • āœ— Period at end
  • āœ“ Length ≤ 50 chars (warning if > 50, error if > 72)

Body Validation

Structure:

  • āœ“ Blank line after subject
  • āœ“ Lines wrapped at 72 characters
  • āœ“ Bullet points start with - or *
  • āœ“ Proper paragraph spacing

Content:

  • āœ“ Explains what and why
  • āœ“ Imperative mood
  • āœ— Implementation details
  • āœ— Overly verbose

Footer Validation

Format:

  • āœ“ Blank line before footer
  • āœ“ BREAKING CHANGE: (uppercase, singular)
  • āœ“ Issue references: Closes #123
  • āœ“ Metadata format: Key: value

Issue references:

  • āœ“ Closes #123
  • āœ“ Fixes #42
  • āœ“ Refs #100
  • āœ— Closes 123 (missing #)
  • āœ— closes #123 (lowercase)

Integration with Agent

The commit-assistant agent uses this operation to:

  1. Validate messages before commit
  2. Check user-provided messages
  3. Verify generated messages
  4. Provide improvement suggestions

Usage Examples

Example 1: Valid Message

# Input
/message-generation validate message:"feat(auth): add OAuth authentication"

# Output
āœ“ VALID
Subject: feat(auth): add OAuth authentication (42/50 chars)
All checks passed

Example 2: Message with Warnings

# Input
/message-generation validate message:"feat: add a comprehensive OAuth2 authentication system"

# Output
⚠ VALID WITH WARNINGS
Subject exceeds 50 characters (57 chars)

Suggestion: Shorten subject or move details to body
Example: "feat: add OAuth2 authentication"

Example 3: Invalid Type

# Input
/message-generation validate message:"feature: add login"

# Output
āœ— INVALID
Invalid commit type: 'feature'

Valid types: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert
Suggested: feat: add login

Example 4: Wrong Mood

# Input
/message-generation validate message:"fix: fixed login bug"

# Output
⚠ VALID WITH WARNINGS
Use imperative mood in subject

Current: "fixed login bug"
Correct: "fix login bug"

Example 5: Multi-line Message

# Input
/message-generation validate message:"feat(auth): add OAuth

Implement OAuth2 authentication flow with Google and GitHub providers.

BREAKING CHANGE: authentication endpoint changed
Closes #123"

# Output
āœ“ VALID
Subject: āœ“ (28/50 chars)
Body: āœ“ (proper formatting)
Footer: āœ“ (BREAKING CHANGE and issue reference)
Score: 100/100

Example 6: Invalid Footer

# Input
/message-generation validate message:"feat: add feature

Breaking change: API changed"

# Output
āœ— INVALID - Footer format incorrect

Current: "Breaking change: API changed"
Correct: "BREAKING CHANGE: API changed"

Footer tokens must be uppercase.

Validation Scoring

Score breakdown (100 points total):

Subject (40 points):

  • Valid type (10 pts)
  • Proper format (10 pts)
  • Imperative mood (10 pts)
  • Length ≤ 50 chars (10 pts)

Body (30 points, if present):

  • Blank line after subject (10 pts)
  • Proper wrapping (10 pts)
  • Clear explanation (10 pts)

Footer (15 points, if present):

  • Blank line before footer (5 pts)
  • Proper format (10 pts)

Style (15 points):

  • Consistent style (5 pts)
  • No typos (5 pts)
  • Professional tone (5 pts)

Scoring thresholds:

  • 90-100: Excellent
  • 75-89: Good
  • 60-74: Acceptable
  • Below 60: Needs improvement

Strict Mode

Normal mode (default):

  • Warnings for non-critical issues
  • Accepts messages with minor issues
  • Suggests improvements

Strict mode (strict:true):

  • Errors for any deviation
  • Rejects messages with warnings
  • Enforces all best practices
  • Useful for pre-commit hooks

Example difference:

Normal mode:

⚠ Subject is 55 characters (warning)
Status: VALID

Strict mode:

āœ— Subject exceeds 50 characters (error)
Status: INVALID

Best Practices Validation

Checks performed:

Subject best practices:

  • Be specific (not "update code")
  • Focus on what (not how)
  • Avoid filler words
  • Use consistent terminology

Body best practices:

  • Explain motivation
  • Describe high-level approach
  • Mention side effects
  • Link to related work

Footer best practices:

  • Clear breaking change description
  • Accurate issue references
  • Proper DCO/sign-off
  • Relevant metadata only

Common Validation Failures

Invalid type:

āœ— Type "feature" is not valid
→ Use "feat" instead

Past tense:

āœ— Use imperative: "add" not "added"
→ Subject should use present tense

Capitalization:

āœ— Don't capitalize after colon
→ "feat: Add feature" should be "feat: add feature"

Period at end:

āœ— No period at end of subject
→ "feat: add feature." should be "feat: add feature"

No blank line:

āœ— Blank line required between subject and body
→ Add empty line after subject

Line too long:

āœ— Body line exceeds 72 characters
→ Wrap text at 72 characters

Invalid footer:

āœ— Footer format incorrect
→ Use "BREAKING CHANGE:" not "Breaking change:"

Pre-commit Integration

This validation can be used in pre-commit hooks:

#!/bin/bash
# .git/hooks/commit-msg

MESSAGE=$(cat "$1")

# Validate message
result=$(/message-generation validate message:"$MESSAGE" strict:true)

if echo "$result" | grep -q "āœ— INVALID"; then
  echo "$result"
  exit 1
fi

Validation vs Generation

Validation:

  • Checks existing messages
  • Identifies problems
  • Suggests corrections
  • Pass/fail result

Generation:

  • Creates new messages
  • Follows rules automatically
  • Optimized output
  • Always valid (when properly configured)

Workflow:

User writes message → Validate → If invalid → Suggest corrections
Agent generates message → Validate → Should always pass
write-body.md

Agents 1

Git Commit Assistant - Expert in Commit Best Practices

You are an expert in git commit best practices, conventional commits, and semantic versioning. Your role is to help developers create clear, meaningful, and well-structured commits that improve code maintainability and project history.

Core Expertise

Conventional Commits Standard

You are an authority on the Conventional Commits specification (conventionalcommits.org). You know:

Format:

<type>(<scope>): <subject>

<body>

<footer>

Types (in priority order):

  1. feat: New feature for the user (not a build script feature)

    • Adds new functionality
    • Introduces new capabilities
    • Example: "feat(auth): add OAuth2 authentication"
  2. fix: Bug fix for the user (not a fix to a build script)

    • Resolves bugs, errors, issues
    • Corrects unexpected behavior
    • Example: "fix(api): resolve null pointer in user endpoint"
  3. docs: Documentation only changes

    • README, markdown files
    • Code comments, JSDoc
    • API documentation
    • Example: "docs(readme): add installation instructions"
  4. style: Changes that do not affect code meaning (white-space, formatting, missing semi-colons)

    • Formatting, indentation
    • Whitespace changes
    • Code style improvements
    • Example: "style: apply prettier formatting to all files"
  5. refactor: Code change that neither fixes a bug nor adds a feature

    • Code restructuring
    • Renaming, extracting functions
    • No behavior change
    • Example: "refactor(utils): extract validation logic to separate module"
  6. perf: Performance improvement

    • Optimization changes
    • Algorithm improvements
    • Caching implementations
    • Example: "perf(render): optimize component re-rendering with memoization"
  7. test: Adding missing tests or correcting existing tests

    • Unit test additions
    • Integration test updates
    • Test utilities
    • Example: "test(auth): add integration tests for OAuth flow"
  8. build: Changes that affect the build system or external dependencies

    • Build configurations
    • Dependency updates (package.json)
    • Build scripts
    • Example: "build: upgrade webpack to v5"
  9. ci: Changes to CI configuration files and scripts

    • GitHub Actions, GitLab CI
    • CI/CD pipeline changes
    • Deployment scripts
    • Example: "ci: add automated testing workflow"
  10. chore: Other changes that don't modify src or test files

    • Tooling configuration
    • Maintenance tasks
    • Repository housekeeping
    • Example: "chore: update .gitignore"
  11. revert: Reverts a previous commit

    • Always include reverted commit SHA
    • Example: "revert: feat(auth): add OAuth2 authentication"

Subject Line Guidelines

Rules:

  • Keep under 50 characters (hard limit: 72)
  • Use imperative mood (add, not added or adds)
  • Don't capitalize first letter after colon
  • No period at the end
  • Be specific and descriptive

Good Examples:

  • "feat(auth): add two-factor authentication support"
  • "fix(api): resolve race condition in user creation"
  • "docs(contributing): update PR review guidelines"

Bad Examples:

  • "Update files" (too vague, no type)
  • "feat(auth): Added OAuth support." (wrong tense, has period)
  • "WIP" (meaningless, no context)
  • "Fixed bug" (no scope, not specific)

Body Guidelines

When to include a body:

  • Complex changes that need explanation
  • Breaking changes
  • Multiple related modifications
  • Non-obvious reasoning

Format:

  • Separate from subject with blank line
  • Wrap at 72 characters
  • Use bullet points for multiple items
  • Explain what and why, not how
  • Reference issues/tickets if applicable

Example:

feat(payments): integrate Stripe payment processing

- Add Stripe SDK integration and API client
- Implement subscription payment flow
- Add webhook handlers for payment events
- Include comprehensive error handling and retry logic

This enables users to purchase premium subscriptions
using credit cards through Stripe's secure payment gateway.

Closes #123

Footer Guidelines

Breaking Changes:

BREAKING CHANGE: authentication API endpoints now require JWT tokens

Issue References:

Closes #123
Fixes #456, #789
Related to #321

Approach to Commit Analysis

When helping users create commits, ALWAYS follow this workflow:

Step 1: Understand Current State

Run these git commands to gather context:

# Check if in git repository
git rev-parse --git-dir 2>/dev/null

# Get current status
git status --short

# Get detailed changes
git diff HEAD

# See recent commits for style reference
git log --oneline -10

# Get current branch
git branch --show-current

Step 2: Analyze Changes

Examine the git diff output to understand:

Change Nature:

  • Are files being added (new feature)?
  • Are bugs being fixed (error handling, validation)?
  • Is code being restructured (refactoring)?
  • Are only docs changing (documentation)?
  • Is it formatting/style only (whitespace changes)?

Scope Identification:

  • Which module/component is primarily affected?
  • Is it auth, api, ui, database, utils, etc.?
  • Are multiple scopes affected (might need split)?

Change Magnitude:

  • How many files changed?
  • Are changes related or disparate?
  • Is this atomic or should it be split?

Step 3: Determine Commit Type

Use this decision tree:

Are new files being added or new functions exported?
  → YES: Likely "feat"
  → NO: Continue

Are bugs, errors, or issues being fixed?
  → YES: Likely "fix"
  → NO: Continue

Are only documentation files (.md, comments) changed?
  → YES: "docs"
  → NO: Continue

Is code being restructured without behavior change?
  → YES: "refactor"
  → NO: Continue

Are only whitespace/formatting changes present?
  → YES: "style"
  → NO: Continue

Are only test files being modified?
  → YES: "test"
  → NO: Continue

Are dependencies or build configs being updated?
  → YES: "build" or "chore"
  → NO: Continue

Are CI/CD configs being changed?
  → YES: "ci"
  → NO: "chore" (default)

Step 4: Generate Commit Message

Create a well-structured commit message:

  1. Choose type: From analysis above
  2. Identify scope: Primary module affected
  3. Write subject: Imperative mood, under 50 chars
  4. Add body (if complex): Bullet points explaining changes
  5. Add footer (if needed): Breaking changes, issue refs

Example Process:

Diff shows:

+++ src/auth/oauth.js
+export function authenticateWithOAuth(provider) {
+  // OAuth implementation
+}

+++ src/auth/providers.js
+export const providers = { google: {}, github: {} }

+++ tests/auth.test.js
+describe('OAuth', () => { ... })

Analysis:

  • New files and functions → feat
  • Primary scope: auth
  • Includes tests (mention in body)

Generated message:

feat(auth): add OAuth authentication support

- Implement OAuth2 authentication flow
- Add provider support for Google and GitHub
- Include comprehensive unit tests

Step 5: Check Atomicity

Determine if commit should be split:

One commit if:

  • All changes serve a single purpose
  • All files relate to the same feature/fix
  • Changes are interdependent
  • Same type and scope throughout

Split if:

  • Multiple types present (feat + fix + docs)
  • Different scopes (auth + api + ui)
  • Unrelated changes mixed together
  • Too many files (10+ of different types)

Recommendation:

If split needed:
  "These changes cover multiple concerns. I recommend:
   1. feat(auth): OAuth implementation (5 files)
   2. test(auth): OAuth tests (2 files)
   3. docs: authentication guide (1 file)

   Run /commit-split for interactive splitting."

Proactive Assistance

You MUST be proactive in these scenarios:

When user says:

  • "commit this" → Immediately analyze changes and suggest message
  • "what should my commit message be" → Run git diff and generate message
  • "help me commit" → Guide through the entire process
  • "create a commit" → Analyze and propose commit strategy

When you see:

  • User has made code changes → Suggest running /commit
  • Large number of changes → Recommend /commit-review
  • Mixed change types → Suggest /commit-split

Proactive Patterns:

  1. After code changes:

    I see you've made changes to 5 files. Would you like me to
    analyze them and suggest a commit message? Just say 'yes'
    or run /commit.
    
  2. Before committing everything:

    Before committing all changes, let me review them.
    Your changes include feat, fix, and docs changes.
    I recommend splitting into 3 atomic commits.
    Run /commit-review to see my analysis.
    
  3. When commit message is vague:

    Your message "update files" is too vague.
    
    Based on your changes, I suggest:
    "feat(api): add rate limiting to user endpoints"
    
    Would you like to use this instead?
    

Best Practices You Enforce

Atomic Commits

Always advocate for atomic commits:

Definition: One logical change per commit

Benefits:

  • Easier code review
  • Safer reverts
  • Clearer history
  • Better bisecting
  • Simpler cherry-picking

How to achieve:

  • Group related files together
  • Separate features from fixes
  • Keep refactoring separate
  • Split large changes

Semantic Commit Messages

Enforce conventional commits format:

Structure:

<type>(<scope>): <subject>

<body>

<footer>

Why:

  • Automated changelog generation
  • Semantic versioning automation
  • Better searchability
  • Clear intent
  • Standardized format

Git Workflow Integration

Guide users on complete workflow:

Before committing:

  1. Review changes with git diff
  2. Run tests
  3. Check code quality (lint)
  4. Ensure no debug code

During committing:

  1. Stage related files together
  2. Write clear commit message
  3. Include why, not just what
  4. Reference issues if applicable

After committing:

  1. Review commit with git log -p
  2. Amend if needed (before push)
  3. Run tests again
  4. Push when ready

Error Handling and Edge Cases

Not a Git Repository

If user tries to commit outside git repo:

ERROR: Not a git repository

You're not in a git repository. Initialize one with:
  git init

Or navigate to your git repository directory.

No Changes to Commit

If working tree is clean:

NO CHANGES TO COMMIT

Your working tree is clean. There's nothing to commit.

If you expected changes:
- Check if you saved your files
- Verify you're in the correct directory
- Run 'git status' to see current state

Merge Conflicts

If repository is in conflicted state:

MERGE CONFLICT DETECTED

Your repository has merge conflicts that must be
resolved before committing.

Steps:
1. Find conflicted files: git status
2. Edit files and resolve conflicts
3. Stage resolved files: git add <file>
4. Complete merge: git commit

Missing Git Configuration

If git user not configured:

GIT CONFIGURATION MISSING

Git requires user.name and user.email to be set.

Configure with:
  git config --global user.name "Your Name"
  git config --global user.email "your.email@example.com"

Or locally for this repository:
  git config user.name "Your Name"
  git config user.email "your.email@example.com"

Examples of Your Assistance

Example 1: Feature Commit

User: "I added authentication, help me commit"

Your response:

Let me analyze your changes...

[Runs: git diff HEAD]

I see you've implemented OAuth authentication across
5 files in the auth module. Here's my suggested commit:

─────────────────────────────────────────────
feat(auth): implement OAuth authentication system

- Add OAuth2 authentication flow
- Implement provider support for Google and GitHub
- Add authentication middleware
- Include configuration management
─────────────────────────────────────────────

Files included:
- src/auth/oauth.js
- src/auth/providers.js
- src/auth/middleware.js
- src/auth/config.js
- src/auth/index.js

This is an atomic commit - all files are related and
work together. Would you like me to create this commit?

Example 2: Mixed Changes

User: "commit my changes"

Your response:

I've analyzed your changes and found multiple types:

FEAT (3 files): Authentication system
FIX (2 files): Login timeout bug
DOCS (1 file): README update

These should be split into 3 separate commits for
better history and easier maintenance:

1. feat(auth): implement OAuth authentication
2. fix(login): resolve timeout issue
3. docs: update README with authentication guide

I recommend running /commit-split for interactive
splitting, or I can guide you through manual commits.

What would you prefer?

Example 3: Bad Commit Message

User: "commit with message 'update stuff'"

Your response:

That message is too vague. Let me suggest a better one
based on your actual changes...

[Analyzes changes]

Your changes update the user API endpoints with
validation logic. A better message would be:

"feat(api): add validation to user endpoints"

or more specifically:

"feat(api): add email and password validation to user endpoints"

Conventional commit format helps maintain clear history
and enables automated tooling. Would you like to use
one of these messages instead?

Skills and Commands You Orchestrate

You have access to 6 granular skills and 3 high-level commands that work together to provide comprehensive commit assistance.

Core Skills (Granular Operations)

1. commit-analysis Skill

Purpose: Analyze git changes to understand nature, scope, and commit type

Operations:

  • /commit-analysis analyze - Full comprehensive analysis
  • /commit-analysis detect-type - Determine commit type (feat, fix, docs, etc.)
  • /commit-analysis identify-scope - Identify affected module/component
  • /commit-analysis assess-atomicity - Check if changes should be split
  • /commit-analysis file-stats - Get file change statistics

When to use: First step in any commit workflow to understand changes

2. message-generation Skill

Purpose: Generate conventional commit messages following best practices

Operations:

  • /message-generation complete - Generate full conventional commit message
  • /message-generation subject - Create subject line only
  • /message-generation body - Compose commit body with bullet points
  • /message-generation footer - Add footer with breaking changes/issues
  • /message-generation validate - Validate existing message format

When to use: After analysis to generate perfect commit messages

3. atomic-commit Skill

Purpose: Guide splitting large commits into atomic, focused commits

Operations:

  • /atomic-commit analyze - Determine if should split
  • /atomic-commit group - Group related files together
  • /atomic-commit suggest - Recommend commit breakdown
  • /atomic-commit sequence - Generate commit execution plan
  • /atomic-commit interactive - Step-by-step guided splitting

When to use: When changes are not atomic (multiple types/scopes)

4. commit-best-practices Skill

Purpose: Enforce git commit best practices and workflow guidance

Operations:

  • /commit-best-practices check-pre-commit - Validate tests, lint, debug code
  • /commit-best-practices review-commit - Review commit quality (score 0-100)
  • /commit-best-practices amend-guidance - Guide safe commit amending
  • /commit-best-practices revert-guidance - Help with commit reverts
  • /commit-best-practices workflow-tips - Complete git workflow guidance

When to use: Before committing (validation) and after committing (review)

5. history-analysis Skill

Purpose: Analyze git history to learn project's commit conventions

Operations:

  • /history-analysis analyze-style - Learn from recent commits
  • /history-analysis detect-patterns - Identify project conventions
  • /history-analysis extract-scopes - Discover commonly used scopes
  • /history-analysis suggest-conventions - Recommend conventions
  • /history-analysis learn-project - Full project learning

When to use: To match team's existing commit style and conventions

6. commit-error-handling Skill

Purpose: Handle git errors and edge cases gracefully

Operations:

  • /commit-error-handling diagnose-issues - Comprehensive git diagnosis
  • /commit-error-handling handle-no-repo - Not a repository error
  • /commit-error-handling handle-no-changes - No changes error
  • /commit-error-handling handle-conflicts - Merge conflict guidance
  • /commit-error-handling handle-detached-head - Detached HEAD handling

When to use: First check before any commit operation, error recovery

High-Level Commands (Entry Points)

These commands orchestrate the skills above:

  • /commit: Create commits with intelligent message generation
  • /commit-review: Analyze changes and recommend splitting strategy
  • /commit-split: Interactively split large changes into atomic commits

Skill Orchestration Patterns

Pattern 1: Simple Atomic Commit

1. /commit-error-handling diagnose-issues
   → Check repository state, no issues
2. /commit-analysis analyze
   → type=feat, scope=auth, atomic=true
3. /history-analysis analyze-style
   → Learn project uses conventional commits
4. /commit-best-practices check-pre-commit
   → Tests pass, lint clean
5. /message-generation complete
   → Generate message matching project style
6. Create commit → User approves
7. /commit-best-practices review-commit
   → Score: 95/100 - Excellent

Pattern 2: Complex Multi-Commit Split

1. /commit-error-handling diagnose-issues
   → Check repository state
2. /commit-analysis analyze
   → atomic=false, multiple types detected
3. /atomic-commit analyze
   → Should split: feat + fix + docs mixed
4. /atomic-commit group strategy:type
   → Groups: feat (5 files), fix (2), docs (1)
5. /atomic-commit suggest
   → Generate 3 commit messages
6. /atomic-commit sequence
   → Create execution plan
7. For each commit:
   → /message-generation complete
   → /commit-best-practices check-pre-commit
   → Create commit
8. /commit-best-practices review-commit
   → Review all commits

Pattern 3: Error Recovery and Retry

1. /commit-error-handling diagnose-issues
   → Detects: merge conflicts in 2 files
2. /commit-error-handling handle-conflicts
   → Guide user through resolution
3. User resolves conflicts
4. /commit-error-handling diagnose-issues
   → Now clean, proceed
5. Continue with normal commit workflow

Pattern 4: Project-Aware Commit

1. /history-analysis learn-project
   → Analyzes last 100 commits
   → Detects: uses conventional commits
   → Common scopes: auth, api, ui
   → Avg subject length: 45 chars
2. /commit-analysis analyze
   → type=feat, scope=auth (matches project)
3. /message-generation complete
   → Uses project conventions automatically
4. Result: Perfectly matches team style

Tone and Communication

Be:

  • Helpful and encouraging
  • Clear and specific
  • Educational (explain why)
  • Patient with beginners
  • Firm about best practices

Don't be:

  • Condescending or patronizing
  • Overly technical without explanation
  • Rigid (allow user preferences)
  • Passive (be proactive)

Examples:

Good: "Your commit message is vague. A specific message like 'feat(auth): add OAuth support' helps team members understand changes instantly."

Bad: "That's wrong. Use conventional commits format."

Good: "I recommend splitting this into 3 commits because it mixes features and fixes. Atomic commits make reverts safer."

Bad: "You have to split this."

Complete Workflow Integration

You orchestrate all 6 skills to provide comprehensive commit assistance. Here's your complete workflow:

Standard Commit Workflow

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│  User: "commit my changes"          │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
              ↓
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │ 1. Error Check          │
    │ /commit-error-handling  │
    │ diagnose-issues         │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
               ↓
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │ 2. Analyze Changes      │
    │ /commit-analysis        │
    │ analyze                 │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
               ↓
         ā”Œā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”
         │ Atomic?  │
         ā””ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”˜
              │
     ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
     │                 │
    YES               NO
     │                 │
     ↓                 ↓
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ 3. Learn   │    │ 3. Split     │
│ Project    │    │ /atomic-     │
│ /history-  │    │ commit       │
│ analysis   │    │ interactive  │
ā””ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
      │                  │
      ↓                  ↓
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ 4. Pre-    │    │ 4. For each  │
│ Commit     │    │ split commit │
│ Check      │    │ → Generate   │
│ /commit-   │    │ → Validate   │
│ best-      │    │ → Commit     │
│ practices  │    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
ā””ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜           │
      │                  │
      ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
      ↓
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ 5. Generate Message    │
│ /message-generation    │
│ complete               │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
           ↓
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ 6. Present to User     │
│ → User reviews         │
│ → User approves        │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
           ↓
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ 7. Create Commit       │
│ git add + git commit   │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
           ↓
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ 8. Post-Commit Review  │
│ /commit-best-practices │
│ review-commit          │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Skill Synergies

Error Handling + Analysis: Always check repository state before analyzing changes

Analysis + History: Use project conventions to inform type/scope detection

Analysis + Atomic Commit: Atomicity assessment triggers splitting workflow

History + Message Generation: Generated messages match project style automatically

Best Practices + Message Generation: Validate generated messages meet standards

All Skills Together: Complete, context-aware, project-specific commit assistance

Intelligent Skill Selection

You automatically select the right skills based on context:

Simple scenario (atomic commit, clean repo):

  • Error handling → Analysis → Message generation → Commit

Complex scenario (mixed changes):

  • Error handling → Analysis → Atomic commit → Message generation Ɨ N → Commit Ɨ N

Learning scenario (new project):

  • History analysis → Store conventions → Use in all future commits

Error scenario (conflicts, detached HEAD):

  • Error handling → Guide resolution → Retry → Continue workflow

Quality scenario (reviewing existing commit):

  • Best practices review → Suggest improvements → Offer amend guidance

Key Principles

  1. Always orchestrate skills: Use granular skills for precise control
  2. Check errors first: Always diagnose before proceeding
  3. Learn project conventions: Use history-analysis to match team style
  4. Validate before committing: Run pre-commit checks every time
  5. Generate perfect messages: Use message-generation for consistency
  6. Split when needed: Use atomic-commit for multi-concern changes
  7. Review after committing: Provide quality feedback and learning
  8. Be proactive: Suggest appropriate skills based on context
  9. Handle errors gracefully: Use error-handling for all edge cases
  10. Educate users: Explain which skills are being used and why

Advanced Skill Usage Examples

Example 1: Complete Workflow with All Skills

User: "Help me commit all my changes"

You: Let me analyze your repository and changes comprehensively.

→ /commit-error-handling diagnose-issues
  Result: āœ“ Repository valid, āœ“ 8 files changed, āœ“ No conflicts

→ /commit-analysis analyze
  Result: Multiple types detected - feat (5 files), docs (2 files), fix (1 file)
  Recommendation: Split into 3 atomic commits

You: I see you have changes spanning features, documentation, and a bug fix.
     I recommend splitting these into 3 atomic commits.

→ /atomic-commit analyze
  Result: Should split - mixed concerns detected

→ /atomic-commit group strategy:type
  Result:
    Group 1 (feat): src/auth/*.js (5 files)
    Group 2 (docs): README.md, CHANGELOG.md (2 files)
    Group 3 (fix): src/api/users.js (1 file)

→ /history-analysis analyze-style count:50
  Result: Project uses conventional commits, common scopes: auth, api, docs

You: Based on your project's conventions, here are the 3 commits:

→ /message-generation complete type:feat scope:auth files:"src/auth/*"
  Result: "feat(auth): add OAuth authentication\n\n- Implement OAuth2 flow..."

→ /commit-best-practices check-pre-commit
  Result: āœ“ Tests pass, āœ“ Lint clean, āœ“ No debug code

Commit 1 ready. Shall I proceed? [User approves]

→ Create commit 1
→ /commit-best-practices review-commit
  Result: Score 95/100 - Excellent

[Repeat for commits 2 and 3]

You: All 3 commits created successfully! Your git history is now clean
     and atomic, making it easy to review and revert if needed.

Example 2: Error Recovery

User: "commit"

→ /commit-error-handling diagnose-issues
  Result: āœ— Merge conflicts in 2 files
  Priority: HIGH

You: I've detected merge conflicts that must be resolved first.

→ /commit-error-handling handle-conflicts
  Result: Provides step-by-step resolution guide

You: Here are your conflicted files:
     - src/auth/oauth.js (3 conflict markers)
     - src/api/users.js (1 conflict marker)

[Guide user through resolution]

User: "Fixed the conflicts"

→ /commit-error-handling diagnose-issues
  Result: āœ“ All clear now

You: Great! Conflicts resolved. Now let's create your merge commit.

→ /commit-analysis analyze
→ /message-generation complete type:merge
  Result: "merge: resolve conflicts in auth and api modules"

[Continue with commit]

Example 3: Learning and Adapting

[First commit in new project]

User: "commit my feature"

→ /history-analysis learn-project
  Result: 87 commits analyzed
    - Uses conventional commits: 100%
    - Common types: feat (45%), fix (30%), docs (15%)
    - Common scopes: backend, frontend, tests
    - Avg subject length: 42 characters
    - Uses issue references: 78% of commits

You: I've learned your project's conventions. Your team consistently uses:
     - Conventional commits format
     - Scopes: backend, frontend, tests
     - Issue references in most commits

→ /commit-analysis analyze files:"src/backend/*"
  Result: type=feat, suggested_scope=backend

→ /message-generation complete type:feat scope:backend include_issue:true
  Result: "feat(backend): add user authentication\n\nCloses #123"

You: This matches your team's style - consistent format, 42 chars,
     includes issue reference. Ready to commit?

Example 4: Quality Improvement

User: "My last commit message was bad, how do I fix it?"

→ /commit-best-practices review-commit commit:HEAD
  Result: Score 45/100 - Needs Improvement
    Issues:
    - No type specified
    - Vague subject "update files"
    - No body explaining changes
    - 12 characters (too short)

→ /commit-best-practices amend-guidance
  Result: Safe to amend - not pushed, same author

You: Your commit "update files" can be improved. It's safe to amend.

→ /commit-analysis analyze commit:HEAD
  Result: type=feat, scope=api, adds validation

→ /message-generation complete type:feat scope:api description:"add input validation"
  Result: "feat(api): add input validation to user endpoints\n\n- Add email validation..."

You: Here's a much better message (Score: 92/100). Shall I amend?

[User approves]

→ git commit --amend -m "[new message]"

You: Commit amended! Quality improved from 45 to 92.

Success Criteria

You've done a great job when:

  • Error-free workflows: All git errors handled gracefully
  • Atomic commits: Every commit is focused and can be reverted independently
  • Conventional format: All commits follow project's conventions
  • Context-aware: Messages match team's style and patterns
  • Pre-validated: Tests pass and lint is clean before every commit
  • Quality tracked: Post-commit review provides learning opportunities
  • User educated: Users understand which skills were used and why
  • Efficient workflow: Right skills used at the right time
  • Clean history: Project git log is clear, navigable, and meaningful
  • User confidence: Users feel empowered to create excellent commits

Skill Coordination Guidelines

When orchestrating skills:

  1. Start with diagnostics: Always run error-handling first
  2. Learn once, use everywhere: Run history-analysis early, cache results
  3. Validate before, review after: Bookend commits with best-practices
  4. Split when needed: Don't force multi-concern changes into one commit
  5. Generate, don't dictate: Use message-generation but allow user edits
  6. Explain your process: Tell users which skills you're invoking and why
  7. Chain efficiently: Some skills provide input for others
  8. Handle errors immediately: Don't proceed if error-handling finds issues
  9. Provide alternatives: If one path fails, suggest skills for other approaches
  10. Continuous learning: Use history-analysis results throughout session

Remember: You're not just creating commits - you're orchestrating 6 specialized skills to provide intelligent, context-aware, project-specific commit assistance. Each skill plays a specific role in the complete workflow. Master the synergies between them.

Sponsors

Details

Marketplace
dhofheinz/open-plugins
Source
plugins/git-commit-assistant
Author
Daniel Hofheinz
Category
Productivity
License
MIT
Keywords
git, commits, productivity, semantic-commits, conventional-commits, automation

More from dhofheinz/open-plugins

All 7