chore: import upstream snapshot with attribution
Component Security Validation / Security Audit (push) Has been cancelled
Deploy to Cloudflare Pages / deploy (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 12:38:58 +08:00
commit bb5c75ce05
8824 changed files with 1946442 additions and 0 deletions
@@ -0,0 +1,180 @@
---
allowed-tools: Bash(git branch:*), Bash(git checkout:*), Bash(git push:*), Bash(git merge:*), Bash(gh:*), Read, Grep
argument-hint: [--dry-run] | [--force] | [--remote-only] | [--local-only]
description: Use PROACTIVELY to clean up merged branches, stale remotes, and organize branch structure
---
# Git Branch Cleanup & Organization
Clean up merged branches and organize repository structure: $ARGUMENTS
## Current Repository State
- All branches: !`git branch -a`
- Recent branches: !`git for-each-ref --count=10 --sort=-committerdate refs/heads/ --format='%(refname:short) - %(committerdate:relative)'`
- Remote branches: !`git branch -r`
- Merged branches: !`git branch --merged main 2>/dev/null || git branch --merged master 2>/dev/null || echo "No main/master branch found"`
- Current branch: !`git branch --show-current`
## Task
Perform comprehensive branch cleanup and organization based on the repository state and provided arguments.
## Cleanup Operations
### 1. Identify Branches for Cleanup
- **Merged branches**: Find local branches already merged into main/master
- **Stale remote branches**: Identify remote-tracking branches that no longer exist
- **Old branches**: Detect branches with no recent activity (>30 days)
- **Feature branches**: Organize feature/* hotfix/* release/* branches
### 2. Safety Checks Before Deletion
- Verify branches are actually merged using `git merge-base`
- Check if branches have unpushed commits
- Confirm branches aren't the current working branch
- Validate against protected branch patterns
### 3. Branch Categories to Handle
- **Safe to delete**: Merged feature branches, old hotfix branches
- **Needs review**: Unmerged branches with old commits
- **Keep**: Main branches (main, master, develop), active feature branches
- **Archive**: Long-running branches that might need preservation
### 4. Remote Branch Synchronization
- Remove remote-tracking branches for deleted remotes
- Prune remote references with `git remote prune origin`
- Update branch tracking relationships
- Clean up remote branch references
## Command Modes
### Default Mode (Interactive)
1. Show branch analysis with recommendations
2. Ask for confirmation before each deletion
3. Provide summary of actions taken
4. Offer to push deletions to remote
### Dry Run Mode (`--dry-run`)
1. Show what would be deleted without making changes
2. Display branch analysis and recommendations
3. Provide cleanup statistics
4. Exit without modifying repository
### Force Mode (`--force`)
1. Delete merged branches without confirmation
2. Clean up stale remotes automatically
3. Provide summary of all actions taken
4. Use with caution - no undo capability
### Remote Only (`--remote-only`)
1. Only clean up remote-tracking branches
2. Synchronize with actual remote state
3. Remove stale remote references
4. Keep all local branches intact
### Local Only (`--local-only`)
1. Only clean up local branches
2. Don't affect remote-tracking branches
3. Keep remote synchronization intact
4. Focus on local workspace organization
## Safety Features
### Pre-cleanup Validation
- Ensure working directory is clean
- Check for uncommitted changes
- Verify current branch is safe (not target for deletion)
- Create backup references if requested
### Protected Branches
Never delete branches matching these patterns:
- `main`, `master`, `develop`, `staging`, `production`
- `release/*` (unless explicitly confirmed)
- Current working branch
- Branches with unpushed commits (unless forced)
### Recovery Information
- Display git reflog references for deleted branches
- Provide commands to recover accidentally deleted branches
- Show SHA hashes for branch tips before deletion
- Create recovery script if multiple branches deleted
## Branch Organization Features
### Naming Convention Enforcement
- Suggest renaming branches to follow team conventions
- Organize branches by type (feature/, bugfix/, hotfix/)
- Identify branches that don't follow naming patterns
- Provide batch renaming suggestions
### Branch Tracking Setup
- Set up proper upstream tracking for feature branches
- Configure push/pull behavior for new branches
- Identify branches missing upstream configuration
- Fix broken tracking relationships
## Output and Reporting
### Cleanup Summary
```
Branch Cleanup Summary:
✅ Deleted 3 merged feature branches
✅ Removed 5 stale remote references
✅ Cleaned up 2 old hotfix branches
⚠️ Found 1 unmerged branch requiring attention
📊 Repository now has 8 active branches (was 18)
```
### Recovery Instructions
```
Branch Recovery Commands:
git checkout -b feature/user-auth 1a2b3c4d # Recover feature/user-auth
git push origin feature/user-auth # Restore to remote
```
## Best Practices
### Regular Maintenance Schedule
- Run cleanup weekly for active repositories
- Use `--dry-run` first to review changes
- Coordinate with team before major cleanups
- Document any non-standard branches to preserve
### Team Coordination
- Communicate branch deletion plans with team
- Check if anyone has work-in-progress on old branches
- Use GitHub/GitLab branch protection rules
- Maintain shared documentation of branch policies
### Branch Lifecycle Management
- Delete feature branches immediately after merge
- Keep release branches until next major release
- Archive long-term experimental branches
- Use tags to mark important branch states before deletion
## Example Usage
```bash
# Safe interactive cleanup
/branch-cleanup
# See what would be cleaned without changes
/branch-cleanup --dry-run
# Clean only remote tracking branches
/branch-cleanup --remote-only
# Force cleanup of merged branches
/branch-cleanup --force
# Clean only local branches
/branch-cleanup --local-only
```
## Integration with GitHub/GitLab
If GitHub CLI or GitLab CLI is available:
- Check PR status before deleting branches
- Verify branches are actually merged in web interface
- Clean up both local and remote branches consistently
- Update branch protection rules if needed
@@ -0,0 +1,166 @@
---
allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*), Bash(git diff:*), Bash(git log:*)
argument-hint: [message] | --no-verify | --amend
description: Create well-formatted commits with conventional commit format and emoji
---
# Smart Git Commit
Create well-formatted commit: $ARGUMENTS
## Current Repository State
- Git status: !`git status --porcelain`
- Current branch: !`git branch --show-current`
- Staged changes: !`git diff --cached --stat`
- Unstaged changes: !`git diff --stat`
- Recent commits: !`git log --oneline -5`
## What This Command Does
1. Unless specified with `--no-verify`, automatically runs pre-commit checks:
- `pnpm lint` to ensure code quality
- `pnpm build` to verify the build succeeds
- `pnpm generate:docs` to update documentation
2. Checks which files are staged with `git status`
3. If 0 files are staged, automatically adds all modified and new files with `git add`
4. Performs a `git diff` to understand what changes are being committed
5. Analyzes the diff to determine if multiple distinct logical changes are present
6. If multiple distinct changes are detected, suggests breaking the commit into multiple smaller commits
7. For each commit (or the single commit if not split), creates a commit message using emoji conventional commit format
## Best Practices for Commits
- **Verify before committing**: Ensure code is linted, builds correctly, and documentation is updated
- **Atomic commits**: Each commit should contain related changes that serve a single purpose
- **Split large changes**: If changes touch multiple concerns, split them into separate commits
- **Conventional commit format**: Use the format `<type>: <description>` where type is one of:
- `feat`: A new feature
- `fix`: A bug fix
- `docs`: Documentation changes
- `style`: Code style changes (formatting, etc)
- `refactor`: Code changes that neither fix bugs nor add features
- `perf`: Performance improvements
- `test`: Adding or fixing tests
- `chore`: Changes to the build process, tools, etc.
- **Present tense, imperative mood**: Write commit messages as commands (e.g., "add feature" not "added feature")
- **Concise first line**: Keep the first line under 72 characters
- **Emoji**: Each commit type is paired with an appropriate emoji:
-`feat`: New feature
- 🐛 `fix`: Bug fix
- 📝 `docs`: Documentation
- 💄 `style`: Formatting/style
- ♻️ `refactor`: Code refactoring
- ⚡️ `perf`: Performance improvements
-`test`: Tests
- 🔧 `chore`: Tooling, configuration
- 🚀 `ci`: CI/CD improvements
- 🗑️ `revert`: Reverting changes
- 🧪 `test`: Add a failing test
- 🚨 `fix`: Fix compiler/linter warnings
- 🔒️ `fix`: Fix security issues
- 👥 `chore`: Add or update contributors
- 🚚 `refactor`: Move or rename resources
- 🏗️ `refactor`: Make architectural changes
- 🔀 `chore`: Merge branches
- 📦️ `chore`: Add or update compiled files or packages
- `chore`: Add a dependency
- `chore`: Remove a dependency
- 🌱 `chore`: Add or update seed files
- 🧑‍💻 `chore`: Improve developer experience
- 🧵 `feat`: Add or update code related to multithreading or concurrency
- 🔍️ `feat`: Improve SEO
- 🏷️ `feat`: Add or update types
- 💬 `feat`: Add or update text and literals
- 🌐 `feat`: Internationalization and localization
- 👔 `feat`: Add or update business logic
- 📱 `feat`: Work on responsive design
- 🚸 `feat`: Improve user experience / usability
- 🩹 `fix`: Simple fix for a non-critical issue
- 🥅 `fix`: Catch errors
- 👽️ `fix`: Update code due to external API changes
- 🔥 `fix`: Remove code or files
- 🎨 `style`: Improve structure/format of the code
- 🚑️ `fix`: Critical hotfix
- 🎉 `chore`: Begin a project
- 🔖 `chore`: Release/Version tags
- 🚧 `wip`: Work in progress
- 💚 `fix`: Fix CI build
- 📌 `chore`: Pin dependencies to specific versions
- 👷 `ci`: Add or update CI build system
- 📈 `feat`: Add or update analytics or tracking code
- ✏️ `fix`: Fix typos
- ⏪️ `revert`: Revert changes
- 📄 `chore`: Add or update license
- 💥 `feat`: Introduce breaking changes
- 🍱 `assets`: Add or update assets
- ♿️ `feat`: Improve accessibility
- 💡 `docs`: Add or update comments in source code
- 🗃️ `db`: Perform database related changes
- 🔊 `feat`: Add or update logs
- 🔇 `fix`: Remove logs
- 🤡 `test`: Mock things
- 🥚 `feat`: Add or update an easter egg
- 🙈 `chore`: Add or update .gitignore file
- 📸 `test`: Add or update snapshots
- ⚗️ `experiment`: Perform experiments
- 🚩 `feat`: Add, update, or remove feature flags
- 💫 `ui`: Add or update animations and transitions
- ⚰️ `refactor`: Remove dead code
- 🦺 `feat`: Add or update code related to validation
- ✈️ `feat`: Improve offline support
## Guidelines for Splitting Commits
When analyzing the diff, consider splitting commits based on these criteria:
1. **Different concerns**: Changes to unrelated parts of the codebase
2. **Different types of changes**: Mixing features, fixes, refactoring, etc.
3. **File patterns**: Changes to different types of files (e.g., source code vs documentation)
4. **Logical grouping**: Changes that would be easier to understand or review separately
5. **Size**: Very large changes that would be clearer if broken down
## Examples
Good commit messages:
- ✨ feat: add user authentication system
- 🐛 fix: resolve memory leak in rendering process
- 📝 docs: update API documentation with new endpoints
- ♻️ refactor: simplify error handling logic in parser
- 🚨 fix: resolve linter warnings in component files
- 🧑‍💻 chore: improve developer tooling setup process
- 👔 feat: implement business logic for transaction validation
- 🩹 fix: address minor styling inconsistency in header
- 🚑️ fix: patch critical security vulnerability in auth flow
- 🎨 style: reorganize component structure for better readability
- 🔥 fix: remove deprecated legacy code
- 🦺 feat: add input validation for user registration form
- 💚 fix: resolve failing CI pipeline tests
- 📈 feat: implement analytics tracking for user engagement
- 🔒️ fix: strengthen authentication password requirements
- ♿️ feat: improve form accessibility for screen readers
Example of splitting commits:
- First commit: ✨ feat: add new solc version type definitions
- Second commit: 📝 docs: update documentation for new solc versions
- Third commit: 🔧 chore: update package.json dependencies
- Fourth commit: 🏷️ feat: add type definitions for new API endpoints
- Fifth commit: 🧵 feat: improve concurrency handling in worker threads
- Sixth commit: 🚨 fix: resolve linting issues in new code
- Seventh commit: ✅ test: add unit tests for new solc version features
- Eighth commit: 🔒️ fix: update dependencies with security vulnerabilities
## Command Options
- `--no-verify`: Skip running the pre-commit checks (lint, build, generate:docs)
## Important Notes
- By default, pre-commit checks (`pnpm lint`, `pnpm build`, `pnpm generate:docs`) will run to ensure code quality
- If these checks fail, you'll be asked if you want to proceed with the commit anyway or fix the issues first
- If specific files are already staged, the command will only commit those files
- If no files are staged, it will automatically stage all modified and new files
- The commit message will be constructed based on the changes detected
- Before committing, the command will review the diff to identify if multiple commits would be more appropriate
- If suggesting multiple commits, it will help you stage and commit the changes separately
- Always reviews the commit diff to ensure the message matches the changes
@@ -0,0 +1,19 @@
# Create Pull Request Command
Create a new branch, commit changes, and submit a pull request.
## Behavior
- Creates a new branch based on current changes
- Formats modified files using Biome
- Analyzes changes and automatically splits into logical commits when appropriate
- Each commit focuses on a single logical change or feature
- Creates descriptive commit messages for each logical unit
- Pushes branch to remote
- Creates pull request with proper summary and test plan
## Guidelines for Automatic Commit Splitting
- Split commits by feature, component, or concern
- Keep related file changes together in the same commit
- Separate refactoring from feature additions
- Ensure each commit can be understood independently
- Multiple unrelated changes should be split into separate commits
@@ -0,0 +1,126 @@
# How to Create a Pull Request Using GitHub CLI
This guide explains how to create pull requests using GitHub CLI in our project.
## Prerequisites
1. Install GitHub CLI if you haven't already:
```bash
# macOS
brew install gh
# Windows
winget install --id GitHub.cli
# Linux
# Follow instructions at https://github.com/cli/cli/blob/trunk/docs/install_linux.md
```
2. Authenticate with GitHub:
```bash
gh auth login
```
## Creating a New Pull Request
1. First, prepare your PR description following the template in `.github/pull_request_template.md`
2. Use the `gh pr create` command to create a new pull request:
```bash
# Basic command structure
gh pr create --title "✨(scope): Your descriptive title" --body "Your PR description" --base main --draft
```
For more complex PR descriptions with proper formatting, use the `--body-file` option with the exact PR template structure:
```bash
# Create PR with proper template structure
gh pr create --title "✨(scope): Your descriptive title" --body-file <(echo -e "## Issue\n\n- resolve:\n\n## Why is this change needed?\nYour description here.\n\n## What would you like reviewers to focus on?\n- Point 1\n- Point 2\n\n## Testing Verification\nHow you tested these changes.\n\n## What was done\npr_agent:summary\n\n## Detailed Changes\npr_agent:walkthrough\n\n## Additional Notes\nAny additional notes.") --base main --draft
```
## Best Practices
1. **PR Title Format**: Use conventional commit format with emojis
- Always include an appropriate emoji at the beginning of the title
- Use the actual emoji character (not the code representation like `:sparkles:`)
- Examples:
- `✨(supabase): Add staging remote configuration`
- `🐛(auth): Fix login redirect issue`
- `📝(readme): Update installation instructions`
2. **Description Template**: Always use our PR template structure from `.github/pull_request_template.md`:
- Issue reference
- Why the change is needed
- Review focus points
- Testing verification
- PR-Agent sections (keep `pr_agent:summary` and `pr_agent:walkthrough` tags intact)
- Additional notes
3. **Template Accuracy**: Ensure your PR description precisely follows the template structure:
- Don't modify or rename the PR-Agent sections (`pr_agent:summary` and `pr_agent:walkthrough`)
- Keep all section headers exactly as they appear in the template
- Don't add custom sections that aren't in the template
4. **Draft PRs**: Start as draft when the work is in progress
- Use `--draft` flag in the command
- Convert to ready for review when complete using `gh pr ready`
### Common Mistakes to Avoid
1. **Incorrect Section Headers**: Always use the exact section headers from the template
2. **Modifying PR-Agent Sections**: Don't remove or modify the `pr_agent:summary` and `pr_agent:walkthrough` placeholders
3. **Adding Custom Sections**: Stick to the sections defined in the template
4. **Using Outdated Templates**: Always refer to the current `.github/pull_request_template.md` file
### Missing Sections
Always include all template sections, even if some are marked as "N/A" or "None"
## Additional GitHub CLI PR Commands
Here are some additional useful GitHub CLI commands for managing PRs:
```bash
# List your open pull requests
gh pr list --author "@me"
# Check PR status
gh pr status
# View a specific PR
gh pr view <PR-NUMBER>
# Check out a PR branch locally
gh pr checkout <PR-NUMBER>
# Convert a draft PR to ready for review
gh pr ready <PR-NUMBER>
# Add reviewers to a PR
gh pr edit <PR-NUMBER> --add-reviewer username1,username2
# Merge a PR
gh pr merge <PR-NUMBER> --squash
```
## Using Templates for PR Creation
To simplify PR creation with consistent descriptions, you can create a template file:
1. Create a file named `pr-template.md` with your PR template
2. Use it when creating PRs:
```bash
gh pr create --title "feat(scope): Your title" --body-file pr-template.md --base main --draft
```
## Related Documentation
- [PR Template](.github/pull_request_template.md)
- [Conventional Commits](https://www.conventionalcommits.org/)
- [GitHub CLI documentation](https://cli.github.com/manual/)
@@ -0,0 +1,174 @@
# Git Worktree Commands
## Create Worktrees for All Open PRs
This command fetches all open pull requests using GitHub CLI, then creates a git worktree for each PR's branch in the `./tree/<BRANCH_NAME>` directory.
```bash
# Ensure GitHub CLI is installed and authenticated
gh auth status || (echo "Please run 'gh auth login' first" && exit 1)
# Create the tree directory if it doesn't exist
mkdir -p ./tree
# List all open PRs and create worktrees for each branch
gh pr list --json headRefName --jq '.[].headRefName' | while read branch; do
# Handle branch names with slashes (like "feature/foo")
branch_path="./tree/${branch}"
# For branches with slashes, create the directory structure
if [[ "$branch" == */* ]]; then
dir_path=$(dirname "$branch_path")
mkdir -p "$dir_path"
fi
# Check if worktree already exists
if [ ! -d "$branch_path" ]; then
echo "Creating worktree for $branch"
git worktree add "$branch_path" "$branch"
else
echo "Worktree for $branch already exists"
fi
done
# Display all created worktrees
echo "\nWorktree list:"
git worktree list
```
### Example Output
```
Creating worktree for fix-bug-123
HEAD is now at a1b2c3d Fix bug 123
Creating worktree for feature/new-feature
HEAD is now at e4f5g6h Add new feature
Worktree for documentation-update already exists
Worktree list:
/path/to/repo abc1234 [main]
/path/to/repo/tree/fix-bug-123 a1b2c3d [fix-bug-123]
/path/to/repo/tree/feature/new-feature e4f5g6h [feature/new-feature]
/path/to/repo/tree/documentation-update d5e6f7g [documentation-update]
```
### Cleanup Stale Worktrees (Optional)
You can add this to remove stale worktrees for branches that no longer exist:
```bash
# Get current branches
current_branches=$(git branch -a | grep -v HEAD | grep -v main | sed 's/^[ *]*//' | sed 's|remotes/origin/||' | sort | uniq)
# Get existing worktrees (excluding main worktree)
worktree_paths=$(git worktree list | tail -n +2 | awk '{print $1}')
for path in $worktree_paths; do
# Extract branch name from path
branch_name=$(basename "$path")
# Skip special cases
if [[ "$branch_name" == "main" ]]; then
continue
fi
# Check if branch still exists
if ! echo "$current_branches" | grep -q "^$branch_name$"; then
echo "Removing stale worktree for deleted branch: $branch_name"
git worktree remove --force "$path"
fi
done
```
## Create New Branch and Worktree
This interactive command creates a new git branch and sets up a worktree for it:
```bash
#!/bin/bash
# Ensure we're in a git repository
if ! git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
echo "Error: Not in a git repository"
exit 1
fi
# Get the repository root
repo_root=$(git rev-parse --show-toplevel)
# Prompt for branch name
read -p "Enter new branch name: " branch_name
# Validate branch name (basic validation)
if [[ -z "$branch_name" ]]; then
echo "Error: Branch name cannot be empty"
exit 1
fi
if git show-ref --verify --quiet "refs/heads/$branch_name"; then
echo "Warning: Branch '$branch_name' already exists"
read -p "Do you want to use the existing branch? (y/n): " use_existing
if [[ "$use_existing" != "y" ]]; then
exit 1
fi
fi
# Create branch directory
branch_path="$repo_root/tree/$branch_name"
# Handle branch names with slashes (like "feature/foo")
if [[ "$branch_name" == */* ]]; then
dir_path=$(dirname "$branch_path")
mkdir -p "$dir_path"
fi
# Make sure parent directory exists
mkdir -p "$(dirname "$branch_path")"
# Check if a worktree already exists
if [ -d "$branch_path" ]; then
echo "Error: Worktree directory already exists: $branch_path"
exit 1
fi
# Create branch and worktree
if git show-ref --verify --quiet "refs/heads/$branch_name"; then
# Branch exists, create worktree
echo "Creating worktree for existing branch '$branch_name'..."
git worktree add "$branch_path" "$branch_name"
else
# Create new branch and worktree
echo "Creating new branch '$branch_name' and worktree..."
git worktree add -b "$branch_name" "$branch_path"
fi
echo "Success! New worktree created at: $branch_path"
echo "To start working on this branch, run: cd $branch_path"
```
### Example Usage
```
$ ./create-branch-worktree.sh
Enter new branch name: feature/user-authentication
Creating new branch 'feature/user-authentication' and worktree...
Preparing worktree (creating new branch 'feature/user-authentication')
HEAD is now at abc1234 Previous commit message
Success! New worktree created at: /path/to/repo/tree/feature/user-authentication
To start working on this branch, run: cd /path/to/repo/tree/feature/user-authentication
```
### Creating a New Branch from a Different Base
If you want to start your branch from a different base (not the current HEAD), you can modify the script:
```bash
read -p "Enter new branch name: " branch_name
read -p "Enter base branch/commit (default: HEAD): " base_commit
base_commit=${base_commit:-HEAD}
# Then use the specified base when creating the worktree
git worktree add -b "$branch_name" "$branch_path" "$base_commit"
```
This will allow you to specify any commit, tag, or branch name as the starting point for your new branch.
@@ -0,0 +1,13 @@
Please analyze and fix the GitHub issue: $ARGUMENTS.
Follow these steps:
1. Use `gh issue view` to get the issue details
2. Understand the problem described in the issue
3. Search the codebase for relevant files
4. Implement the necessary changes to fix the issue
5. Write and run tests to verify the fix
6. Ensure code passes linting and type checking
7. Create a descriptive commit message
Remember to use the GitHub CLI (`gh`) for all GitHub-related tasks.
@@ -0,0 +1,293 @@
---
allowed-tools: Bash(gh:*), Read, Grep, TodoWrite, Edit, MultiEdit
argument-hint: [pr-number] | --analyze-only | --preview | --priority high|medium|low
description: Transform Gemini Code Assist PR reviews into prioritized TodoLists with automated execution
model: claude-sonnet-4-5-20250929
---
# Gemini PR Review Automation
## Why This Command Exists
**The Problem**: Gemini Code Assist provides free, automated PR reviews on GitHub. But AI-generated reviews often get ignored because they lack the urgency of human feedback.
**The Pain Point**: Manually asking Claude Code to:
1. "Analyze PR #42's Gemini review"
2. "Prioritize the issues"
3. "Create a TodoList"
4. "Start working on them"
...gets tedious fast.
**The Solution**: One command that automatically fetches Gemini's review, analyzes severity, creates prioritized TodoLists, and optionally starts execution.
## What Makes This Different
| | Code Analysis | Code Improvement | Gemini Review |
|---|---|---|---|
| **Trigger** | When you want analysis | When you want improvements | **When Gemini already reviewed** |
| **Input** | Local codebase | Local codebase | **GitHub PR's Gemini comments** |
| **Purpose** | General analysis | General improvements | **Convert AI review → actionable TODOs** |
| **Output** | Analysis report | Applied improvements | **TodoList + Priority + Execution** |
## Triggers
- PR has Gemini Code Assist review comments waiting to be addressed
- Need to convert AI feedback into structured action items
- Want to systematically process automated review feedback
- Reduce manual context switching between GitHub and development
## Usage
```bash
/gemini-review [pr-number] [--analyze-only] [--preview] [--priority high|medium|low]
```
## Behavioral Flow
1. **Fetch**: Retrieve PR details and Gemini review comments using GitHub CLI
2. **Analyze**: Parse and categorize review comments by type and severity
3. **Prioritize**: Assess each comment for refactoring necessity and impact
4. **TodoList**: Generate structured TodoList with priority ordering
5. **Execute**: (Optional) Start working on high-priority items with user confirmation
Key behaviors:
- Intelligent comment categorization (critical, improvement, suggestion, style)
- Impact assessment for each review item with effort estimation
- Automatic TodoList creation with priority matrix (must-fix, should-fix, nice-to-have)
- Code location mapping and dependency analysis
- Implementation strategy with phased approach
## Tool Coordination
- **Bash**: GitHub CLI operations for PR and review data fetching
- **Sequential Thinking**: Multi-step reasoning for complex refactoring decisions
- **Grep**: Code pattern analysis and issue location identification
- **Read**: Source code inspection for context understanding
- **TodoWrite**: Automatic TodoList generation with priorities
- **Edit/MultiEdit**: Code modifications when executing fixes
## Key Patterns
- **Review Parsing**: Gemini comments → structured analysis data
- **Severity Classification**: Comment type → priority level assignment (Must-fix/Should-fix/Nice-to-have/Skip)
- **TodoList Generation**: Analysis results → TodoWrite with prioritized items
- **Impact Analysis**: Code changes → ripple effect assessment
- **Execution Planning**: Strategy → actionable implementation steps
## Examples
### Analyze Current Branch's PR
```bash
/gemini-review
# Automatically detects current branch's PR
# Generates prioritized TodoList from Gemini review
# Ready to execute after user confirmation
```
### Analyze Specific PR
```bash
/gemini-review 42
# Analyzes Gemini review comments on PR #42
# Creates prioritized TodoList with effort estimates
```
### Preview Mode (Safe Execution)
```bash
/gemini-review --preview
# Shows what would be fixed without applying changes
# Creates TodoList for manual execution
# Allows review before implementation
```
## Real Workflow Example
**Before (Manual, Tedious)**:
```bash
1. Open GitHub PR page
2. Read Gemini review (often skipped because "AI generated")
3. Tell Claude: "Analyze PR #42 Gemini review"
4. Tell Claude: "Prioritize these issues"
5. Tell Claude: "Create TodoList"
6. Tell Claude: "Start working on them"
```
**After (Automated)**:
```bash
/gemini-review 42
# → TodoList automatically created
# → Priorities set based on severity
# → Ready to execute immediately
```
## Analysis Output Structure
### 1. Review Summary
- Total comments count by severity
- Severity distribution (critical/improvement/suggestion/style)
- Common themes and patterns identified
- Overall review sentiment and key focus areas
- Estimated total effort required
### 2. Categorized Analysis
For each review comment:
- **Category**: Critical | Improvement | Suggestion | Style
- **Location**: File path and line numbers with context
- **Issue**: Description of the problem from Gemini
- **Impact**: Potential consequences if unaddressed
- **Decision**: Must-fix | Should-fix | Nice-to-have | Skip
- **Reasoning**: Why this priority was assigned
- **Effort**: Estimated implementation time (Small/Medium/Large)
### 3. TodoList Generation
**Automatically creates TodoList with user confirmation before execution**
```
High Priority (Must-Fix):
✓ Fix SQL injection in auth.js:45 (15 min)
✓ Remove exposed API key in config.js:12 (5 min)
Medium Priority (Should-Fix):
○ Refactor UserService complexity (45 min)
○ Add error handling to payment flow (30 min)
Low Priority (Nice-to-Have):
○ Update JSDoc comments (20 min)
○ Rename variable for clarity (5 min)
Skipped:
- Style suggestion conflicts with project standards
- Already addressed in different approach
```
*Note: User reviews and confirms TodoList before any code modifications are made*
### 4. Execution Plan
- **Phase 1 - Critical Fixes**: Security and breaking issues (immediate)
- **Phase 2 - Important Improvements**: Maintainability and performance (same PR)
- **Phase 3 - Optional Enhancements**: Style and documentation (future PR)
- **Dependencies**: Order of implementation based on code dependencies
- **Testing Strategy**: Required test updates for each phase
### 5. Decision Record
- **Accepted Changes**: What will be implemented and why
- **Deferred Changes**: What will be addressed in future iterations
- **Rejected Changes**: What won't be implemented and reasoning
- **Trade-offs**: Analyzed costs vs. benefits for each decision
## Boundaries
**Will:**
- Fetch and analyze Gemini Code Assist review comments from GitHub PRs
- Categorize and prioritize review feedback systematically
- Generate TodoLists with priority ordering and effort estimates
- Provide decision reasoning and trade-off analysis
- Map review comments to specific code locations
- Execute fixes with user confirmation in preview mode
**Will Not:**
- Automatically implement changes without user review (unless explicitly requested)
- Dismiss Gemini suggestions without analysis and documentation
- Make architectural decisions without considering project context
- Modify code outside the scope of review comments
- Work with non-Gemini review systems (GitHub Copilot, CodeRabbit, etc.)
## Decision Criteria
### Must-Fix (Critical) - High Priority
- Security vulnerabilities and data exposure
- Data integrity issues and potential corruption
- Breaking changes or runtime errors
- Critical performance problems (>100ms delay, memory leaks)
- Violations of core architecture principles
### Should-Fix (Improvement) - Medium Priority
- Code maintainability issues and technical debt
- Moderate performance improvements (10-100ms gains)
- Important best practice violations
- Significant readability and documentation gaps
- Error handling and resilience improvements
### Nice-to-Have (Suggestion) - Low Priority
- Code style improvements and formatting
- Minor optimizations (<10ms gains)
- Optional refactoring opportunities
- Enhanced error messages and logging
- Additional code comments and documentation
### Skip (Not Applicable)
- Conflicts with established project standards
- Out of scope for current iteration
- Low ROI improvements (high effort, low impact)
- Overly opinionated suggestions without clear benefit
- Already addressed by other means or different approach
## Integration with Git Workflow
### Recommended Flow
```bash
1. Create PR → Gemini reviews automatically
2. Run /gemini-review to generate TodoList
3. Review TodoList priorities and adjust if needed
4. Execute fixes systematically (Phase 1 → Phase 2 → Phase 3)
5. Commit changes with conventional commit messages
6. Update PR and re-request Gemini review if needed
```
### Commit Strategy
- Group related refactoring changes by category
- Use conventional commit messages referencing review items
- `fix(auth): resolve SQL injection vulnerability (Gemini PR#42)`
- `refactor(services): reduce UserService complexity (Gemini PR#42)`
- `docs: update JSDoc comments (Gemini PR#42)`
- Create separate commits for critical vs. improvement changes
- Document decision rationale in commit messages
## Advanced Usage
### Interactive Mode (Recommended for Complex Reviews)
```
/gemini-review --interactive
# Step through each review comment with decision prompts
# Allows manual priority adjustment
# Shows code context for each issue
```
### Export Analysis
```
/gemini-review --export gemini-analysis.md
# Export comprehensive analysis to markdown file
# Useful for team review and documentation
# Includes all decisions and reasoning
```
### Dry Run (No TodoList Creation)
```
/gemini-review --dry-run
# Shows analysis and priorities without creating TodoList
# Useful for understanding scope before committing
# No changes to workflow state
```
## Tool Requirements
- **GitHub CLI** (`gh`) installed and authenticated
- **Repository** must have Gemini Code Assist configured as PR reviewer
- **Current branch** must have associated PR or provide PR number explicitly
## Setup Gemini Code Assist
If you haven't set up Gemini Code Assist yet:
1. Visit [Gemini Code Assist GitHub App](https://developers.google.com/gemini-code-assist/docs/set-up-code-assist-github)
2. Install the app on your organization/account
3. Select repositories for integration
4. Gemini will automatically review PRs with `/gemini` tag or auto-review
**Why Gemini?**
- **Free**: No cost for automated PR reviews
- **Comprehensive**: Covers security, performance, best practices
- **GitHub Native**: Integrated directly into PR workflow
- **Automated**: No manual review requests needed
## Limitations
- Only supports Gemini Code Assist reviews (not GitHub Copilot, CodeRabbit, etc.)
- Requires GitHub CLI access and authentication
- Analysis quality depends on Gemini review quality
- Cannot modify reviews or re-trigger Gemini analysis
@@ -0,0 +1,260 @@
---
allowed-tools: Bash(git bisect:*), Bash(git log:*), Bash(git show:*), Bash(git checkout:*), Bash(npm:*), Bash(yarn:*), Bash(pnpm:*), Read, Edit, Grep
argument-hint: [good-commit] [bad-commit] | --auto [test-command] | --reset | --continue
description: Use PROACTIVELY to guide automated git bisect sessions for finding regression commits with smart test execution
---
# Git Bisect Helper & Automation
Automated git bisect session to find regression commits: $ARGUMENTS
## Current Repository State
- Current branch: !`git branch --show-current`
- Recent commits: !`git log --oneline -10`
- Git status: !`git status --porcelain`
- Bisect status: !`git bisect log 2>/dev/null || echo "No active bisect session"`
- Available tags: !`git tag --sort=-version:refname | head -10`
## Task
Set up and manage an intelligent git bisect session to identify the exact commit that introduced a regression or bug.
## Bisect Session Management
### 1. Session Initialization
- Analyze commit history to suggest good/bad commit candidates
- Set up bisect session with appropriate range
- Validate that the range actually contains the regression
- Create backup branch before starting bisect
### 2. Automatic Test Execution
- Run specified test command at each bisect point
- Interpret test results (exit codes, output patterns)
- Automatically mark commits as good/bad based on test outcomes
- Handle test environment setup/teardown
### 3. Manual Verification Support
- Provide clear instructions for manual testing at each step
- Show relevant changes in current commit
- Guide user through good/bad decision process
- Maintain bisect log with detailed reasoning
### 4. Smart Commit Analysis
- Analyze commit messages for relevant keywords
- Show file changes that might be related to the issue
- Highlight suspicious patterns or large changes
- Skip obviously unrelated commits when possible
## Bisect Modes
### Automatic Bisect (`--auto [test-command]`)
```bash
# Automatically bisect using test command
/git-bisect-helper --auto "npm test"
/git-bisect-helper --auto "python -m pytest tests/test_regression.py"
/git-bisect-helper --auto "./scripts/check-performance.sh"
```
**Process:**
1. Run test command at each bisect point
2. Mark commit as good (exit code 0) or bad (non-zero)
3. Continue until regression commit is found
4. Provide detailed report of findings
### Manual Guided Bisect
```bash
# Interactive bisect with guidance
/git-bisect-helper v1.2.0 HEAD
/git-bisect-helper abc123 def456
```
**Process:**
1. Show current commit details and changes
2. Provide testing suggestions
3. Wait for user input (good/bad)
4. Continue to next bisect point
5. Offer insights about current commit
### Continue Existing Session (`--continue`)
```bash
# Resume interrupted bisect session
/git-bisect-helper --continue
```
**Process:**
1. Analyze current bisect state
2. Show progress and remaining steps
3. Continue with appropriate mode
4. Provide context from previous steps
### Reset Session (`--reset`)
```bash
# Clean up and reset bisect session
/git-bisect-helper --reset
```
**Process:**
1. End current bisect session
2. Return to original branch
3. Clean up temporary files
4. Provide session summary
## Intelligent Test Execution
### Test Environment Detection
- **Node.js**: Detect package.json and run appropriate package manager
- **Python**: Identify requirements.txt, setup.py, pyproject.toml
- **Ruby**: Look for Gemfile and use bundler
- **Java**: Detect Maven (pom.xml) or Gradle (build.gradle)
- **Go**: Identify go.mod and use go test
- **Rust**: Detect Cargo.toml and use cargo test
### Build System Integration
- Run build process before testing if needed
- Handle dependency installation for older commits
- Manage environment variable requirements
- Skip build for commits that don't compile (mark as bad)
### Test Result Interpretation
- Parse test output for meaningful error patterns
- Distinguish between test failures and environment issues
- Handle flaky tests with retry logic
- Provide confidence levels for automated decisions
## Commit Analysis Features
### Change Impact Assessment
```bash
# Analyze current bisect commit
Files changed: !`git show --name-only --pretty="" HEAD`
Commit message: !`git log -1 --pretty=format:"%s"`
Author and date: !`git log -1 --pretty=format:"%an (%ar)"`
```
### Regression Pattern Detection
- Identify commits touching critical areas
- Flag commits with suspicious change patterns
- Highlight performance-related modifications
- Detect dependency or configuration changes
### Context Preservation
- Maintain detailed log of bisect decisions
- Record reasoning for each good/bad marking
- Save test outputs for later analysis
- Document environmental factors
## Advanced Bisect Strategies
### Skip Strategy for Build Issues
- Automatically skip commits that don't compile
- Handle dependency version conflicts
- Skip commits with known build system issues
- Focus bisect on functional commits only
### Performance Regression Detection
- Use performance benchmarks instead of pass/fail tests
- Set acceptable performance thresholds
- Track performance trends across commits
- Identify performance cliff points
### Multi-criteria Bisecting
- Test multiple aspects simultaneously
- Handle cases where good/bad isn't binary
- Support complex regression scenarios
- Provide weighted decision making
## Bisect Session Reporting
### Progress Tracking
```
Bisect Progress:
🎯 Target: Find regression in user authentication
📊 Commits remaining: ~4 (out of 127)
⏱️ Estimated time: 8 minutes
🔍 Current commit: abc123 - "refactor auth middleware"
```
### Final Report
```
🎉 Regression Found!
Bad Commit: def456
Author: John Doe
Date: 2024-01-15 14:30:00
Message: "optimize database queries"
Files Changed:
- src/auth/database.js
- src/middleware/auth.js
- tests/auth.test.js
Bisect Log: 15 steps, 3 manual verifications
Total Time: 12 minutes
Recovery Commands:
git revert def456 # Revert the problematic commit
git cherry-pick def456^..def456~1 # Cherry-pick the good parts
```
## Integration with Development Workflow
### CI/CD Integration
- Use same test commands as CI pipeline
- Respect CI environment variables
- Handle containerized test environments
- Integrate with existing quality gates
### Team Collaboration
- Share bisect sessions with team members
- Document findings in issue tracking
- Create reproducible bisect scripts
- Establish team bisect best practices
### Debugging Enhancement
- Generate debug reports for problematic commits
- Create minimal reproduction cases
- Suggest fix approaches based on regression type
- Link to relevant documentation or similar issues
## Safety and Recovery
### Session Backup
- Create backup branch before starting
- Save original HEAD position
- Maintain recovery information
- Handle interrupted sessions gracefully
### Error Handling
- Recover from corrupted bisect state
- Handle repository state conflicts
- Manage disk space issues during long bisects
- Provide clear error messages and solutions
## Example Workflows
### Performance Regression
```bash
# Find when tests became slower
/git-bisect-helper --auto "timeout 30s npm test"
```
### Feature Regression
```bash
# Find when feature X broke
/git-bisect-helper --auto "./test-feature-x.sh"
```
### Build Regression
```bash
# Find when build started failing
/git-bisect-helper --auto "npm run build"
```
### Manual Investigation
```bash
# Interactive bisect for complex issues
/git-bisect-helper v2.1.0 HEAD
```
The bisect helper provides intelligent automation while maintaining full control over the debugging process, making regression hunting efficient and systematic.
@@ -0,0 +1,76 @@
# PR Review
**PR Link/Number**: $ARGUMENTS
> **Instructions**: Execute each task in the order given to conduct a thorough code review. Update GitHub with this review.
> **Important**: The future is now—any improvements or “future” recommendations must be addressed **immediately**.
---
## Task 1: Product Manager Review
**Objective**: Assess from a product management perspective, focusing on:
- **Business Value**: Does this PR clearly advance our core product goals and deliver immediate ROI?
- **User Experience**: Is the change intuitive and delightful for users right now? If not, make fixes immediately.
- **Strategic Alignment**: Does the PR align with current (and long-term, i.e., now) strategic objectives?
**Action**: Provide clear directives on how to ensure maximum user and business impact. All “future” suggestions must be implemented now.
---
## Task 2: Developer Review
**Objective**: Evaluate the code thoroughly from a senior lead engineer perspective:
1. **Code Quality & Maintainability**: Is the code structured for readability and easy maintenance? If not, refactor now.
2. **Performance & Scalability**: Will these changes operate efficiently at scale? If not, optimize immediately.
3. **Best Practices & Standards**: Note any deviation from coding standards and correct it now.
**Action**: Leave a concise yet complete review comment, ensuring all improvements happen immediately—no deferrals.
---
## Task 3: Quality Engineer Review
**Objective**: Verify the overall quality, testing strategy, and reliability of the solution:
1. **Test Coverage**: Are there sufficient tests (unit, integration, E2E)? If not, add them now.
2. **Potential Bugs & Edge Cases**: Have all edge cases been considered? If not, address them immediately.
3. **Regression Risk**: Confirm changes dont undermine existing functionality. If risk is identified, mitigate now with additional checks or tests.
**Action**: Provide a detailed QA assessment, insisting any “future” improvements be completed right away.
---
## Task 4: Security Engineer Review
**Objective**: Ensure robust security practices and compliance:
1. **Vulnerabilities**: Could these changes introduce security vulnerabilities? If so, fix them right away.
2. **Data Handling**: Are we properly protecting sensitive data (e.g., encryption, sanitization)? Address all gaps now.
3. **Compliance**: Confirm alignment with any relevant security or privacy standards (e.g., OWASP, GDPR, HIPAA). Implement missing requirements immediately.
**Action**: Provide a security assessment. Any recommended fixes typically scheduled for “later” must be addressed now.
---
## Task 5: DevOps Review
**Objective**: Evaluate build, deployment, and monitoring considerations:
1. **CI/CD Pipeline**: Validate that the PR integrates smoothly with existing build/test/deploy processes. If not, fix it now.
2. **Infrastructure & Configuration**: Check whether the code changes require immediate updates to infrastructure or configs.
3. **Monitoring & Alerts**: Identify new monitoring needs or potential improvements and implement them immediately.
**Action**: Provide a DevOps-centric review, insisting that any improvements or tweaks be executed now.
---
## Task 6: UI/UX Designer Review
**Objective**: Ensure optimal user-centric design:
1. **Visual Consistency**: Confirm adherence to brand/design guidelines. If not, adjust now.
2. **Usability & Accessibility**: Validate that the UI is intuitive and compliant with accessibility standards. Make any corrections immediately.
3. **Interaction Flow**: Assess whether the user flow is seamless. If friction exists, refine now.
**Action**: Provide a detailed UI/UX evaluation. Any enhancements typically set for “later” must be done immediately.
---
**End of PR Review**
@@ -0,0 +1,9 @@
# Update Branch Name
Follow these steps to update the current branch name:
1. Check differences between current branch and main branch HEAD using `git diff main...HEAD`
2. Analyze the changed files to understand what work is being done
3. Determine an appropriate descriptive branch name based on the changes
4. Update the current branch name using `git branch -m [new-branch-name]`
5. Verify the branch name was updated with `git branch`
@@ -0,0 +1,59 @@
---
allowed-tools: Bash(git:*), Bash(cat:*), Bash(pwd:*), Bash(ls:*)
description: Check current worktree status, branch, and assigned task
---
# Worktree Status Check
Verify the current worktree environment and show task details.
## Instructions
You are inside a worktree (or the main repo). Gather and display the current status clearly.
### Step 1: Detect Worktree
1. Get the current directory: `pwd`
2. List all worktrees: `git worktree list`
3. Determine if the current directory is a worktree (not the main working tree). The main working tree is listed first in `git worktree list` output — if the current path matches the first entry, this is the main repo, not a worktree.
If this is **not** a worktree, inform the user:
> You're in the main repository, not a worktree. Use `/worktree-init` to create worktrees.
Then list any existing worktrees and exit.
### Step 2: Show Branch Info
1. Get current branch: `git branch --show-current`
2. Verify it follows the `claude/*`, `claude-daniel/*`, or `review/*` naming convention
3. Show how many commits ahead of origin/main: `git rev-list --count origin/main..HEAD`
### Step 3: Read Task
1. Check if `.worktree-task.md` exists in the worktree root
2. If it exists, read and display its contents
3. If it doesn't exist, note that no task file was found (may have been created manually)
### Step 4: Show Working Status
Run and display:
1. `git status --short` — show modified, staged, and untracked files
2. `git diff --stat` — show a summary of unstaged changes
### Step 5: Display Summary
Present a clean summary:
```
Worktree Status
──────────────────────────────────
Branch: claude/<name>
Task: <task description from .worktree-task.md>
Commits: <N> ahead of main
Modified: <N> files
Staged: <N> files
Untracked: <N> files
──────────────────────────────────
```
If there are changes ready to deliver, suggest: "Run `/worktree-deliver` when you're ready to commit, push, and create a PR."
@@ -0,0 +1,124 @@
---
allowed-tools: Bash(git:*), Bash(rm:*), Bash(ls:*), Bash(pwd:*), Bash(grep:*)
argument-hint: --all | --branch claude/name | --dry-run
description: Clean up merged worktrees and their branches
---
# Worktree Cleanup
Remove worktrees and branches that have been merged: $ARGUMENTS
## Instructions
You are in the **main repository** (not a worktree). Clean up finished worktrees.
### Branch Patterns
This project uses the following branch prefixes for worktrees:
- `claude/*` — Claude Code auto-created worktrees
- `claude-daniel/*` — User-created worktrees
- `review/*` — Component review worktrees
All three prefixes must be checked in every step below.
### Step 1: Validate Environment
1. Verify this is the main working tree (first entry in `git worktree list`)
2. If inside a worktree, warn: "Run `/worktree-cleanup` from the main repo, not from a worktree."
3. Fetch latest from origin: `git fetch origin --prune`
4. Get the main branch name (main or master)
### Step 2: Parse Arguments
Parse `$ARGUMENTS` for options:
- `--all` — clean up ALL merged worktrees and branches
- `--branch <prefix>/<name>` — clean up a specific worktree/branch
- `--dry-run` — show what would be cleaned up without doing anything
- `--force-all` — remove ALL worktrees regardless of merge status (asks confirmation per worktree)
- No arguments — list worktrees and ask which to clean up
### Step 3: Identify Worktrees
1. List all worktrees: `git worktree list`
2. List all matching branches:
```bash
git branch --list 'claude/*' 'claude-daniel/*' 'review/*'
```
3. For each matching branch, check if it's been merged into main:
```bash
git branch --merged origin/<main-branch> | grep -E '^\s+(claude/|claude-daniel/|review/)'
```
4. Also check remote branches:
```bash
git branch -r --merged origin/<main-branch> | grep -E 'origin/(claude/|claude-daniel/|review/)'
```
5. For squash-merged branches (not detected by `--merged`), check if the branch diff is empty against main:
```bash
# A branch is effectively merged if its changes already exist in main
git diff origin/main...<branch> --stat
```
If the diff is empty or very small (only whitespace), consider it merged.
### Step 4: Display Status
Show a table of all worktrees/branches:
```
| # | Worktree | Branch | Merged? | Dirty? | Action |
|---|---------|--------|---------|--------|--------|
| 1 | eager-mendeleev | claude/eager-mendeleev | Yes | Clean | Will remove |
| 2 | agent-a7e312d0 | review/code-reviewer-2026-04-01 | No | Clean | Skipped |
```
### Step 5: Confirm and Execute
If `--dry-run` was specified, show the table and stop.
Otherwise, use AskUserQuestion to confirm cleanup (unless `--all` was specified with only merged branches).
For each worktree/branch to clean up:
1. Remove the worktree:
```bash
git worktree remove <path>
```
If that fails (dirty worktree), warn and skip — **never force-remove**.
2. Delete the local branch:
```bash
git branch -d <branch>
```
Use `-d` (not `-D`) for merged branches. For `--force-all` unmerged branches, use `-D` only after explicit user confirmation.
3. Delete the remote branch (if it exists):
```bash
git push origin --delete <branch>
```
If the remote branch doesn't exist, ignore the error silently.
### Step 6: Prune
After all removals:
```bash
git worktree prune
```
### Step 7: Summary
Show what was cleaned up:
```
Cleanup Complete
──────────────────────────────────
Removed: <N> worktree(s)
Deleted: <N> local branch(es)
Deleted: <N> remote branch(es)
Skipped: <N> unmerged branch(es)
──────────────────────────────────
```
If any unmerged branches were skipped, list them and suggest:
- Merge the PR first, then run cleanup again
- Or use `git worktree remove <path>` and `git branch -D <branch>` manually if the work is truly abandoned
@@ -0,0 +1,127 @@
---
allowed-tools: Bash(git:*), Bash(gh:*), Bash(rm:*), Bash(cat:*), Bash(pwd:*), Bash(ls:*)
description: Commit, push, and create PR from the current worktree
---
# Worktree Deliver
Commit all work, push, and create a pull request from the current worktree.
## Instructions
You are inside a worktree. Package up the work and deliver it as a PR.
### Step 1: Validate Environment
1. Verify this is a worktree (not the main working tree) using `git worktree list`
2. Get current branch: `git branch --show-current`
3. Verify branch follows `claude/*`, `claude-daniel/*`, or `review/*` pattern. If not, warn the user and ask if they want to continue.
4. Read `.worktree-task.md` if it exists to get the original task description
### Step 2: Review Changes
1. Run `git diff --stat` and `git diff --cached --stat` to show all changes
2. Run `git status --short` to show the full picture
3. If there are no changes at all (clean working tree, no commits ahead of main), inform the user there's nothing to deliver and stop.
### Step 3: Clean Up Task File
Before staging anything, remove the worktree task file so it doesn't end up in the commit:
```bash
rm -f .worktree-task.md
```
### Step 4: Confirm Files to Commit
Use AskUserQuestion to show the user what will be committed and ask for confirmation. List all modified, added, and untracked files.
Options:
- "Stage all changes" — stage everything
- "Let me choose" — user will specify which files to include
If the user wants to choose, ask them which files to stage.
### Step 5: Stage and Commit
1. Stage the confirmed files with `git add`
2. Generate a commit message following conventional commits format
**Commit Message Strategy:**
1. **Analyze the diff** to determine the conventional commit type:
- `feat:` — New functionality, new files, new exports, new API endpoints
- `fix:` — Bug fixes, error corrections, fixing broken behavior
- `refactor:` — Code restructuring without changing behavior
- `docs:` — Documentation only changes
- `test:` — Adding or modifying tests
- `chore:` — Build scripts, configs, maintenance tasks
2. **Generate a commit message** based on:
- The task description from `.worktree-task.md` (if it was found)
- A brief summary of what the diff actually changed
- Format: `<type>: <subject>` (max 72 characters)
3. **Show the proposed message** to the user with AskUserQuestion:
- Display the generated message clearly
- Options: "Use this message" / "Let me write my own"
4. **If user chooses to write their own:**
- Ask them to provide their commit message
- Validate it follows conventional commits format (warn if not, but allow)
5. **Always include body and co-author:**
- Add a brief body summarizing what changed (2-3 bullet points if multiple changes)
- Include the standard co-author line
3. Create the commit with the message using a HEREDOC:
```bash
git commit -m "$(cat <<'EOF'
<commit message here>
EOF
)"
```
### Step 6: Push
Push the branch to origin:
```bash
git push -u origin HEAD
```
If push fails due to no upstream, the `-u` flag should handle it. If it fails for another reason, show the error and suggest fixes.
### Step 7: Create Pull Request
1. Determine the base branch (main or master) using the same detection as worktree-init
2. Create the PR using `gh pr create`:
```bash
gh pr create --base <main-branch> --title "<PR title>" --body "$(cat <<'EOF'
## Summary
<bullet points describing the changes based on task description and diff>
## Original Task
<task description from .worktree-task.md>
## Changes
<git diff --stat summary>
---
Created from worktree `claude/<name>` using `/worktree-deliver`
EOF
)"
```
3. Display the PR URL prominently
### Step 8: Next Steps
Tell the user:
- PR is ready for review at `<URL>`
- After merging, run `/worktree-cleanup` from the main repo to clean up
- They can close this terminal panel
@@ -0,0 +1,88 @@
---
allowed-tools: Bash(git:*), Bash(mkdir:*), Bash(ls:*), Bash(cat:*), Bash(basename:*), Bash(pwd:*), Bash(sed:*)
argument-hint: task 1 | task 2 | task 3
description: Create parallel worktrees for multi-task development with Ghostty panels
---
# Worktree Parallel Init
Create multiple git worktrees for parallel development: $ARGUMENTS
## Instructions
You are setting up parallel worktrees so the user can work on multiple tasks simultaneously in separate Ghostty terminal panels, each running its own Claude instance.
### Step 1: Validate Environment
1. Check this is a git repository: `git rev-parse --is-inside-work-tree`
2. Get the repo name: `basename $(git rev-parse --show-toplevel)`
3. Get the main branch name (check for `main` or `master`): `git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@'` — if that fails, default to `main`
4. Ensure working tree is clean: `git status --porcelain`. If dirty, warn the user and ask if they want to continue.
5. Fetch latest: `git fetch origin`
### Step 2: Parse Tasks
Parse tasks from `$ARGUMENTS`. Tasks are separated by `|` (pipe character).
If `$ARGUMENTS` is empty, use AskUserQuestion to ask the user to describe their tasks (they can provide multiple separated by `|`).
For each task description:
- Trim whitespace
- Generate a kebab-case branch name: `claude/<kebab-case-task>` (max 50 chars, alphanumeric and hyphens only)
- Generate a worktree directory path: `../worktrees/<repo-name>/claude-<kebab-case-task>`
### Step 3: Create Worktrees
For each task:
1. Create the parent directory if needed: `mkdir -p ../worktrees/<repo-name>`
2. Create the worktree:
```bash
git worktree add -b claude/<name> ../worktrees/<repo-name>/claude-<name> origin/<main-branch>
```
3. Write a `.worktree-task.md` file inside the new worktree with this content:
```markdown
# Worktree Task
**Branch:** claude/<name>
**Task:** <original task description>
**Created:** <ISO date>
**Source repo:** <path to main repo>
```
### Step 4: Check for Dependencies
If a `package.json` exists in the repo root, note that each worktree may need `npm install` (or the appropriate package manager).
Check for:
- `package-lock.json` → npm install
- `yarn.lock` → yarn install
- `pnpm-lock.yaml` → pnpm install
- `bun.lockb` → bun install
### Step 5: Output Summary
Display a clear summary table:
```
| # | Task | Branch | Path |
|---|------|--------|------|
| 1 | ... | claude/... | ../worktrees/repo/claude-... |
```
Then display ready-to-copy commands for Ghostty panels. For each worktree:
```
# Panel <N>: <task description>
cd <absolute-path-to-worktree> && claude
```
If dependencies were detected, add a note:
```
# Note: Run <package-manager> install in each worktree before starting
```
Finally, remind the user:
- Open a new Ghostty panel with `Cmd+D` (split right) or `Cmd+Shift+D` (split down)
- When done with a task, use `/worktree-deliver` to commit, push, and create a PR
- After merging all PRs, use `/worktree-cleanup --all` from the main repo