Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:20:25 +08:00
commit 0d6226e0d8
69 changed files with 20934 additions and 0 deletions

View File

@@ -0,0 +1,70 @@
#!/usr/bin/env bash
# ================================================================
# Script: changes-detector.sh
# Purpose: Check for changes to commit (staged, unstaged, untracked)
# Version: 1.0.0
# Usage: ./changes-detector.sh
# Returns: JSON with change counts
# Exit Codes:
# 0 = Success (with or without changes)
# 1 = Not a git repository
# 2 = Script error
# ================================================================
set -euo pipefail
# Function to output JSON
output_json() {
local has_changes=$1
local staged=$2
local unstaged=$3
local untracked=$4
local total=$5
cat <<EOF
{
"has_changes": $has_changes,
"staged_count": $staged,
"unstaged_count": $unstaged,
"untracked_count": $untracked,
"total_changes": $total,
"checked_at": "$(date -Iseconds)"
}
EOF
}
# Main logic
main() {
# Verify we're in a git repository
if ! git rev-parse --git-dir &>/dev/null; then
output_json false 0 0 0 0
exit 1
fi
# Count staged changes (added to index)
STAGED_COUNT=$(git diff --cached --numstat | wc -l)
# Count unstaged changes (modified but not staged)
UNSTAGED_COUNT=$(git diff --numstat | wc -l)
# Count untracked files
UNTRACKED_COUNT=$(git ls-files --others --exclude-standard | wc -l)
# Total changes
TOTAL=$((STAGED_COUNT + UNSTAGED_COUNT + UNTRACKED_COUNT))
# Determine if there are any changes
if [ "$TOTAL" -gt 0 ]; then
HAS_CHANGES=true
else
HAS_CHANGES=false
fi
# Output JSON
output_json "$HAS_CHANGES" "$STAGED_COUNT" "$UNSTAGED_COUNT" "$UNTRACKED_COUNT" "$TOTAL"
exit 0
}
# Run main function
main "$@"

View File

@@ -0,0 +1,173 @@
#!/usr/bin/env python3
"""
================================================================
Script: conflict-detector.py
Purpose: Detect and report merge conflicts
Version: 1.0.0
Usage: ./conflict-detector.py
Returns: JSON with conflict information
Exit Codes:
0 = Success (conflicts may or may not exist)
1 = Not a git repository
2 = Script error
================================================================
"""
import json
import subprocess
import sys
from datetime import datetime
from pathlib import Path
def run_git_command(command):
"""Run a git command and return output."""
try:
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
check=False
)
return result.returncode, result.stdout.strip(), result.stderr.strip()
except Exception as e:
return -1, "", str(e)
def check_repo_validity():
"""Check if current directory is a git repository."""
returncode, _, _ = run_git_command("git rev-parse --git-dir")
return returncode == 0
def get_conflicted_files():
"""Get list of files with merge conflicts."""
# Files with conflicts show up with 'U' status (unmerged)
returncode, stdout, _ = run_git_command("git ls-files -u")
if returncode != 0 or not stdout:
return []
# Extract unique filenames (git ls-files -u shows each stage)
conflicted_files = set()
for line in stdout.split('\n'):
if line.strip():
# Format: <mode> <object> <stage> <filename>
parts = line.split('\t')
if len(parts) > 1:
filename = parts[1]
conflicted_files.add(filename)
return sorted(conflicted_files)
def check_merge_in_progress():
"""Check if a merge operation is in progress."""
git_dir_code, git_dir, _ = run_git_command("git rev-parse --git-dir")
if git_dir_code != 0:
return False, None
git_dir_path = Path(git_dir)
# Check for various merge/rebase states
if (git_dir_path / "MERGE_HEAD").exists():
return True, "merge"
elif (git_dir_path / "REBASE_HEAD").exists():
return True, "rebase"
elif (git_dir_path / "CHERRY_PICK_HEAD").exists():
return True, "cherry-pick"
elif (git_dir_path / "REVERT_HEAD").exists():
return True, "revert"
return False, None
def get_conflict_details(files):
"""Get detailed information about conflicts in each file."""
details = []
for filepath in files:
try:
# Count conflict markers in file
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
conflict_count = content.count('<<<<<<<')
details.append({
"file": filepath,
"conflict_regions": conflict_count
})
except Exception:
# If can't read file, just include filename
details.append({
"file": filepath,
"conflict_regions": 0
})
return details
def main():
"""Main execution function."""
# Check if in git repository
if not check_repo_validity():
result = {
"has_conflicts": False,
"conflict_count": 0,
"conflicted_files": [],
"merge_in_progress": False,
"operation_type": None,
"error": "not a git repository",
"checked_at": datetime.now().isoformat()
}
print(json.dumps(result, indent=2))
sys.exit(1)
# Get conflicted files
conflicted_files = get_conflicted_files()
conflict_count = len(conflicted_files)
has_conflicts = conflict_count > 0
# Check merge status
merge_in_progress, operation_type = check_merge_in_progress()
# Get detailed conflict information
conflict_details = []
if has_conflicts:
conflict_details = get_conflict_details(conflicted_files)
# Build result
result = {
"has_conflicts": has_conflicts,
"conflict_count": conflict_count,
"conflicted_files": conflicted_files,
"conflict_details": conflict_details,
"merge_in_progress": merge_in_progress,
"operation_type": operation_type,
"error": "",
"checked_at": datetime.now().isoformat()
}
# Output JSON
print(json.dumps(result, indent=2))
sys.exit(0)
if __name__ == "__main__":
try:
main()
except Exception as e:
# Handle unexpected errors
result = {
"has_conflicts": False,
"conflict_count": 0,
"conflicted_files": [],
"merge_in_progress": False,
"operation_type": None,
"error": f"script error: {str(e)}",
"checked_at": datetime.now().isoformat()
}
print(json.dumps(result, indent=2))
sys.exit(2)

View File

@@ -0,0 +1,54 @@
#!/usr/bin/env bash
# ================================================================
# Script: repo-checker.sh
# Purpose: Verify git repository validity
# Version: 1.0.0
# Usage: ./repo-checker.sh
# Returns: JSON with repository status
# Exit Codes:
# 0 = Valid repository
# 1 = Not a repository
# 2 = Script error
# ================================================================
set -euo pipefail
# Function to output JSON
output_json() {
local is_repo=$1
local git_dir=$2
local error=$3
cat <<EOF
{
"is_repo": $is_repo,
"git_dir": $git_dir,
"error": "$error",
"checked_at": "$(date -Iseconds)"
}
EOF
}
# Main logic
main() {
# Check if git is installed
if ! command -v git &>/dev/null; then
output_json false "null" "git not installed"
exit 2
fi
# Try to get git directory
if GIT_DIR=$(git rev-parse --git-dir 2>/dev/null); then
# Valid repository
ABSOLUTE_GIT_DIR=$(cd "$GIT_DIR" && pwd)
output_json true "\"$ABSOLUTE_GIT_DIR\"" ""
exit 0
else
# Not a repository
output_json false "null" "not a git repository"
exit 1
fi
}
# Run main function
main "$@"

View File

@@ -0,0 +1,183 @@
#!/usr/bin/env bash
# ================================================================
# Script: state-analyzer.sh
# Purpose: Analyze repository state (HEAD, branch, remote status)
# Version: 1.0.0
# Usage: ./state-analyzer.sh
# Returns: JSON with repository state information
# Exit Codes:
# 0 = Success
# 1 = Not a git repository
# 2 = Script error
# ================================================================
set -euo pipefail
# Function to check HEAD state
check_head_state() {
if git symbolic-ref HEAD &>/dev/null; then
echo "attached"
else
echo "detached"
fi
}
# Function to get current branch
get_current_branch() {
local branch
branch=$(git branch --show-current 2>/dev/null)
if [ -z "$branch" ]; then
echo "null"
else
echo "\"$branch\""
fi
}
# Function to get current commit SHA
get_current_commit() {
git rev-parse --short HEAD 2>/dev/null || echo "unknown"
}
# Function to check remote status
check_remote_status() {
# Check if remote exists
if ! git remote &>/dev/null || [ -z "$(git remote)" ]; then
echo "no_remote"
return
fi
# Check if branch tracks remote
if ! git rev-parse --abbrev-ref @{upstream} &>/dev/null; then
echo "no_upstream"
return
fi
# Compare with upstream
local local_commit remote_commit
local_commit=$(git rev-parse HEAD 2>/dev/null)
remote_commit=$(git rev-parse @{upstream} 2>/dev/null)
if [ "$local_commit" = "$remote_commit" ]; then
echo "up_to_date"
else
# Check ahead/behind
local ahead behind
ahead=$(git rev-list --count @{upstream}..HEAD 2>/dev/null || echo "0")
behind=$(git rev-list --count HEAD..@{upstream} 2>/dev/null || echo "0")
if [ "$ahead" -gt 0 ] && [ "$behind" -gt 0 ]; then
echo "diverged"
elif [ "$ahead" -gt 0 ]; then
echo "ahead"
elif [ "$behind" -gt 0 ]; then
echo "behind"
else
echo "up_to_date"
fi
fi
}
# Function to get ahead/behind counts
get_ahead_behind_counts() {
if ! git rev-parse --abbrev-ref @{upstream} &>/dev/null; then
echo "0" "0"
return
fi
local ahead behind
ahead=$(git rev-list --count @{upstream}..HEAD 2>/dev/null || echo "0")
behind=$(git rev-list --count HEAD..@{upstream} 2>/dev/null || echo "0")
echo "$ahead" "$behind"
}
# Function to get remote name
get_remote_name() {
local remote
remote=$(git remote 2>/dev/null | head -1)
if [ -z "$remote" ]; then
echo "null"
else
echo "\"$remote\""
fi
}
# Function to get remote URL
get_remote_url() {
local remote_name
remote_name=$(git remote 2>/dev/null | head -1)
if [ -z "$remote_name" ]; then
echo "null"
return
fi
local url
url=$(git remote get-url "$remote_name" 2>/dev/null)
if [ -z "$url" ]; then
echo "null"
else
echo "\"$url\""
fi
}
# Function to check if working tree is clean
check_working_tree() {
if git diff-index --quiet HEAD -- 2>/dev/null; then
echo "clean"
else
echo "dirty"
fi
}
# Main function
main() {
# Verify we're in a git repository
if ! git rev-parse --git-dir &>/dev/null; then
cat <<EOF
{
"error": "not a git repository",
"is_repo": false
}
EOF
exit 1
fi
# Collect all state information
local head_state current_branch current_commit remote_status
local ahead behind remote_name remote_url working_tree
head_state=$(check_head_state)
current_branch=$(get_current_branch)
current_commit=$(get_current_commit)
remote_status=$(check_remote_status)
read -r ahead behind < <(get_ahead_behind_counts)
remote_name=$(get_remote_name)
remote_url=$(get_remote_url)
working_tree=$(check_working_tree)
# Output JSON
cat <<EOF
{
"is_repo": true,
"head_state": "$head_state",
"current_branch": $current_branch,
"current_commit": "$current_commit",
"remote_status": "$remote_status",
"ahead_by": $ahead,
"behind_by": $behind,
"remote_name": $remote_name,
"remote_url": $remote_url,
"working_tree": "$working_tree",
"checked_at": "$(date -Iseconds)"
}
EOF
exit 0
}
# Run main function
main "$@"

View File

@@ -0,0 +1,466 @@
# 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
```bash
REPO_RESULT=$(/home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-error-handling/.scripts/repo-checker.sh)
```
#### Check for Changes
```bash
CHANGES_RESULT=$(/home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-error-handling/.scripts/changes-detector.sh)
```
#### Check for Conflicts
```bash
CONFLICTS_RESULT=$(/home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-error-handling/.scripts/conflict-detector.py)
```
#### Check Repository State
```bash
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:
```bash
# 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:
```bash
# 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:
```bash
# 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
```bash
# Before attempting commit
/commit-error-handling diagnose-issues
# If all clear:
/commit-analysis analyze
/message-generation complete-message
```
### Troubleshooting
```bash
# When git operations fail
/commit-error-handling diagnose-issues
# Follow recommended resolution order
```
### Repository Health Check
```bash
# 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

View File

@@ -0,0 +1,310 @@
# 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:
```bash
/home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-error-handling/.scripts/conflict-detector.py
```
This will return JSON:
```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:
```bash
# 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

View File

@@ -0,0 +1,366 @@
# 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:
```bash
# 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:
```bash
# 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 <name>"
- 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

View File

@@ -0,0 +1,220 @@
# 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:
```bash
/home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-error-handling/.scripts/changes-detector.sh
```
This will return JSON:
```json
{
"has_changes": false,
"staged_count": 0,
"unstaged_count": 0,
"untracked_count": 0,
"total_changes": 0
}
```
### 2. Analyze Git Status
Run comprehensive status check:
```bash
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**
```bash
git status --porcelain
```
- **Changes to ignored files only**
```bash
git status --ignored
```
- **Accidentally reset changes**
```bash
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**

View File

@@ -0,0 +1,161 @@
# 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:
```bash
/home/danie/projects/plugins/architect/open-plugins/plugins/git-commit-assistant/commands/commit-error-handling/.scripts/repo-checker.sh
```
This will return JSON:
```json
{
"is_repo": false,
"git_dir": null,
"error": "not a git repository"
}
```
### 2. Analyze Context
Check the current directory:
```bash
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

View File

@@ -0,0 +1,96 @@
---
description: Handle git errors and edge cases gracefully
---
# 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