
workflows
Operational tooling for development workflows - git worktree management with AI context tracking
- GitHub stars
- 7
Install
/plugin install workflows@waypoint-marketplaceRun it inside Claude Code after adding the marketplace with /plugin marketplace add poindexter12/waypoint.
Contents
Discovered from sourceSkills 4
Issue Lifecycle
State machine for GitHub issues and how they connect to code.
State Diagram
┌─────────────────┐
│ needs-triage │ ← New issue created
└────────┬────────┘
│ triage
┌────────▼────────┐
┌───────────│ accepted │ ← In backlog
│ └────────┬────────┘
│ │ start work
│ ┌────────▼────────┐
│ ┌──────│ in-progress │ ← Active development
│ │ └────────┬────────┘
│ │ │ PR merged
│ │ ┌────────▼────────┐
│ │ │ completed │ ← Issue resolved
│ │ └─────────────────┘
│ │
│ │ blocked
│ │ ┌─────────────────┐
│ └─────►│ blocked │ ← Waiting on dependency
│ └─────────────────┘
│
│ needs-info
│ ┌─────────────────┐
└──────────►│ needs-info │ ← Waiting for clarification
└─────────────────┘
State Definitions
Open States
| State | Label | Meaning |
|---|---|---|
| New | needs-triage | Just created, not reviewed |
| Clarification | needs-info | Waiting on reporter |
| Backlog | accepted | Triaged, waiting for work |
| Active | in-progress | Someone is working on it |
| Blocked | blocked | Can't proceed |
Closed States
| State | Reason | Comment |
|---|---|---|
| Completed | Fixed/implemented | Via PR or manual |
| Duplicate | Same as another | "Duplicate of #N" |
| Won't Fix | Out of scope | Explain why |
| Invalid | Not a real issue | Cannot reproduce |
| Stale | No activity | Auto-closed after warning |
Linking Issues to Code
Branch Naming
When starting work on issue #123:
feat/123-short-description # feature
fix/123-short-description # bug fix
chore/123-short-description # maintenance
docs/123-short-description # documentation
i18n/locale-code # internationalization (e.g., i18n/zh-CN, i18n/ja-JP)
i18n/123-locale-code # i18n with issue (e.g., i18n/42-es-MX)
Examples:
feat/42-add-dark-modefix/123-login-timeoutchore/99-update-depsi18n/zh-CN- Chinese (Simplified) translationsi18n/42-ja-JP- Japanese translations for issue #42
PR Title
Include issue number in PR title:
feat: add dark mode (#42)
fix: resolve login timeout (#123)
chore: update dependencies (#99)
PR Description
Use closing keywords in PR body:
| Keyword | Effect |
|---|---|
Closes #123 | Auto-closes when merged |
Fixes #123 | Same as Closes |
Resolves #123 | Same as Closes |
Example PR description:
## Summary
Add dark mode toggle to settings page.
Closes #42
## Changes
- Add theme context
- Create toggle component
- Update color variables
Linking Without Closing
Reference issues without auto-close:
Related to #45
See also #67
Depends on #89
Manual Close Reasons
When closing without PR, always comment:
Duplicate
gh issue close 123 --comment "Duplicate of #456"
Won't Fix
gh issue close 123 --comment "Closing as won't fix: [reason]"
Invalid / Cannot Reproduce
gh issue close 123 --comment "Cannot reproduce with provided steps. Please reopen with more details if issue persists."
Stale
gh issue close 123 --comment "Closing due to inactivity. Please reopen if still relevant."
Stale Issue Handling
Detection
Issues with no activity for N days (typically 90):
# Find stale issues
gh issue list --search "updated:<$(date -v-90d +%Y-%m-%d)"
Warning Process
- Add
stalelabel - Comment:
This issue has been inactive for 90 days. It will be closed in 30 days if there's no further activity. Please comment if this is still relevant. - Close after 30 more days if no response
Automation (GitHub Action)
name: Stale Issues
on:
schedule:
- cron: '0 0 * * *'
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
with:
stale-issue-message: 'This issue has been inactive for 90 days.'
days-before-stale: 90
days-before-close: 30
stale-issue-label: 'stale'
Bulk Operations
Close Multiple Issues
# Close all issues with label
gh issue list --label "stale" --json number --jq '.[].number' | \
xargs -I {} gh issue close {} --comment "Closing stale issue"
Relabel Issues
# Add label to all issues matching query
gh issue list --search "is:open label:bug" --json number --jq '.[].number' | \
xargs -I {} gh issue edit {} --add-label "needs-review"
Transfer Issues
# Move issue to another repo
gh issue transfer 123 owner/other-repo
Workflow Commands
Start Work on Issue
# Create branch from issue
gh issue develop 123 --checkout
# Or manually
git checkout -b fix/123-description main
gh issue edit 123 --add-label "in-progress"
Complete Issue via PR
# Create PR that closes issue
gh pr create --title "fix: resolve issue (#123)" --body "Closes #123"
Mark as Blocked
gh issue edit 123 \
--remove-label "in-progress" \
--add-label "blocked"
gh issue comment 123 --body "Blocked on #456"
Integration with Other Components
Full Issue Workflow
- Create: Use gh-issue-templates to format issue
- Triage: Use gh-issue-triage to add type/priority labels
- Start Work: Use this skill's branch naming patterns (feat/123-desc)
- Link to Code: Reference issue in PR using
Closes #123 - Close: Use gh-wrangler agent with this skill's close patterns
- Cleanup: PR merge auto-closes issue via GitHub
State Transitions
This skill defines how issues move through states:
needs-triage→ Initial state (set by gh-issue-templates)accepted→ After triage (applied by gh-wrangler using gh-issue-triage)in-progress→ Work started (manual or via branch creation)blocked→ Can't proceed (set manually with comment)- Closed → Via PR merge or manual close
Branch and PR Integration
When starting work on an issue:
# Branch naming from this skill
git checkout -b feat/123-description
# PR creation with linking
gh pr create --title "feat: description (#123)" --body "Closes #123"
Related
- Skill:
gh-issue-templates- Creating well-formatted issues - Skill:
gh-issue-triage- Labeling and prioritization - Agent:
gh-wrangler- Interactive lifecycle management
Issue Templates
Standardized formats for creating GitHub issues with consistent structure.
Quick Reference
| Type | Title Prefix | Key Sections |
|---|---|---|
| Bug | bug: | Describe, Expected, Steps, Environment |
| Feature | feat: | Problem, Solution, Alternatives, Acceptance |
| Task | task: or chore: | Description, Checklist, Context |
Bug Report Format
Title: bug: <short description>
Body:
## Describe the bug
<!-- What happened? -->
## Expected behavior
<!-- What should have happened? -->
## Steps to reproduce
1.
2.
3.
## Environment
- OS:
- Version:
- Relevant config:
## Logs/Screenshots
<!-- If applicable -->
Bug Examples
Good:
bug: login fails with expired OAuth tokenbug: dashboard crashes when filter is empty
Bad:
bug: it's brokenbug: doesn't work
Feature Request Format
Title: feat: <short description>
Body:
## Problem
<!-- What problem does this solve? -->
## Proposed solution
<!-- How should it work? -->
## Alternatives considered
<!-- Other approaches you thought of -->
## Acceptance criteria
<!-- How do we know it's done? -->
- [ ] Criterion 1
- [ ] Criterion 2
Feature Examples
Good:
feat: add CSV export for reportsfeat: support dark mode in settings
Bad:
feat: make it betterfeat: new feature
Task Format
Title: task: <short description> or chore: <short description>
Use task: for project work, chore: for maintenance/deps/infra.
Body:
## Description
<!-- What needs to be done? -->
## Checklist
- [ ] Step 1
- [ ] Step 2
- [ ] Step 3
## Context
<!-- Why is this needed? -->
Task Examples
Good:
task: set up CI pipelinechore: upgrade React to v19chore: update dependencies
Bad:
task: do the thingchore: stuff
Template Selection Guide
Is something broken?
YES → Bug Report
NO → Continue
Is this new functionality?
YES → Feature Request
NO → Continue
Is this maintenance/infrastructure?
YES → Task (chore:)
NO → Task (task:)
Template Files
See templates/ for copy-paste ready files:
bug.md- Bug report templatefeature.md- Feature request templatetask.md- Task/chore template
Integration with Other Components
After Creating Issue
After using this skill to create an issue, use:
- gh-issue-triage skill to apply appropriate labels and priority
- gh-wrangler agent to create the issue via gh CLI
Workflow
- Use gh-issue-templates (this skill) to format the issue
- Use gh-issue-triage to determine labels and priority
- Use gh-wrangler to create the issue with
gh issue create - Use gh-issue-lifecycle to manage state transitions
Related
- Skill:
gh-issue-triage- Labeling and prioritization rules - Skill:
gh-issue-lifecycle- State transitions and linking - Agent:
gh-wrangler- Interactive issue management
Issue Triage
Rules and workflows for categorizing, labeling, and prioritizing GitHub issues.
Quick Reference
| Label Type | Purpose | Mutually Exclusive? |
|---|---|---|
| Type | What kind of issue | Yes |
| Priority | How urgent | Yes |
| Status | Current state | Yes |
| Area | Which component | No |
Label Taxonomy
Type Labels (mutually exclusive)
| Label | Description | Color |
|---|---|---|
bug | Something is broken | #d73a4a (red) |
feature | New functionality | #a2eeef (cyan) |
enhancement | Improvement to existing feature | #84b6eb (blue) |
docs | Documentation only | #0075ca (dark blue) |
chore | Maintenance, deps, infra | #fef2c0 (yellow) |
Priority Labels (mutually exclusive)
| Label | Description | Response |
|---|---|---|
priority: critical | Drop everything, fix now | Immediate |
priority: high | Next up after current work | This sprint |
priority: medium | Normal backlog | Scheduled |
priority: low | Nice to have, someday | Backlog |
Status Labels (mutually exclusive)
| Label | Description |
|---|---|
needs-triage | New, not yet categorized |
needs-info | Waiting for reporter clarification |
accepted | Triaged and in backlog |
in-progress | Someone is working on it |
blocked | Can't proceed, waiting on something |
Area Labels (project-specific, not exclusive)
Define based on your project structure:
area: apiarea: cliarea: docsarea: uiarea: auth
Triage Workflow
Step 1: New Issues
Every new issue gets needs-triage label automatically (via GitHub Actions or manually).
Step 2: Initial Review
Is this a duplicate?
YES → Close with "Duplicate of #N", link original
NO → Continue
Is this spam/invalid?
YES → Close without label
NO → Continue
Is the issue clear enough to act on?
YES → Continue to Step 3
NO → Add `needs-info`, comment asking for clarification
Step 3: Categorization
Apply type label:
- Broken functionality → `bug`
- New capability → `feature`
- Improve existing → `enhancement`
- Documentation → `docs`
- Maintenance → `chore`
Apply area label(s):
- Based on affected component
- Can have multiple areas
Step 4: Prioritization
Apply priority:
- Production down / security issue → `priority: critical`
- Major impact, many users → `priority: high`
- Normal request → `priority: medium`
- Nice to have → `priority: low`
Step 5: Finalize
1. Remove `needs-triage`
2. Add `accepted`
3. Assign to milestone (if applicable)
4. Suggest assignee (if known)
Priority Guidelines
Critical
- Production is down
- Security vulnerability
- Data loss occurring
- Blocks all users
High
- Major feature broken
- Significant user impact
- Blocks important workflow
- Time-sensitive deadline
Medium
- Normal bug reports
- Feature requests
- Improvements
- Most issues land here
Low
- Minor cosmetic issues
- Edge case bugs
- Nice-to-have features
- "Someday" items
Common Patterns
Insufficient Information
Issue: "It doesn't work"
Action:
1. Add `needs-info`
2. Comment: "Can you provide steps to reproduce and your environment?"
3. Wait for response
Duplicate Detection
Issue: Similar to existing #123
Action:
1. Close issue
2. Comment: "Duplicate of #123"
3. Add any new context to #123
Critical Security Issue
Issue: Security vulnerability
Action:
1. Add `priority: critical`, `bug`
2. Assign immediately
3. Consider private discussion
Feature Without Acceptance Criteria
Issue: "Add dark mode"
Action:
1. Add `feature`, `needs-info`
2. Comment: "Great idea! Can you describe acceptance criteria?"
Reference Files
See references/ for:
label-taxonomy.md- Complete label reference with colors
Integration with Other Components
Typical Triage Workflow
- Issue created using gh-issue-templates (gets
needs-triagelabel) - Use gh-issue-triage (this skill) to determine type and priority
- Apply labels using gh-wrangler agent
- Track state changes using gh-issue-lifecycle
Label Setup
Use references/label-taxonomy.md to:
- Create labels with correct colors:
gh label create "bug" --color "d73a4a" - Maintain consistent taxonomy across repositories
- Setup new repositories with standard labels
Priority Assignment
Consult "Priority Guidelines" section in this skill:
- Critical: Production down, security, data loss
- High: Major features broken, significant impact
- Medium: Normal bugs and features (most issues)
- Low: Nice-to-have, cosmetic, edge cases
Related
- Skill:
gh-issue-templates- Creating well-formatted issues - Skill:
gh-issue-lifecycle- State transitions and linking - Agent:
gh-wrangler- Interactive triage workflow
Git Worktree Guide
Quick reference and templates for git worktree workflows with AI metadata integration.
Progressive Disclosure
Initial Response
Quick Overview:
Git worktrees let you checkout multiple branches simultaneously in separate directories. Each worktree has AI metadata (.ai-context.json) that helps tools understand context.
Quick Start:
- Create worktree:
/working-tree:new <branch-name> - List worktrees:
/working-tree:list - Check status:
/working-tree:status - Remove worktree:
/working-tree:destroy <path> - Add metadata:
/working-tree:adopt
What would you like to know more about?
- Mode semantics (main, feature, bugfix, experiment, review)
- Metadata file structure and templates
- Comprehensive best practices guide
- Strategic organization patterns
On Request
Based on what you ask for, I can show you:
Mode Semantics → Detailed explanation of each mode Templates → Ready-to-use metadata templates Best Practices → Full reference guide (REFERENCE.md) Examples → Specific workflow examples
Mode Semantics Quick Reference
main
Purpose: Stable, production-ready code Restrictions: Minimal changes only, no experimentation Use For: Hotfixes, urgent production changes, stable baseline AI Behavior: Conservative suggestions, focus on safety
feature
Purpose: Active development of new features Restrictions: None, experimentation encouraged Use For: New features, enhancements, active work AI Behavior: Helpful, suggests improvements freely
bugfix
Purpose: Isolated, surgical bug fixes Restrictions: Minimal scope, no unrelated changes Use For: Specific bug fixes, targeted corrections AI Behavior: Focused on fix only, warns about scope creep
experiment
Purpose: Prototypes, spikes, research Restrictions: None, can be messy, expect to discard Use For: POCs, trying new technologies, A/B testing AI Behavior: Aggressive suggestions, OK with rough code
review
Purpose: Code review, auditing, documentation Restrictions: Read-only mindset, analysis only Use For: PR review, security audits, documentation work AI Behavior: Analytical, suggests improvements, no execution
Metadata File Structure
.ai-context.json
{
"worktree": "directory-name",
"branch": "branch-name",
"mode": "main|feature|bugfix|experiment|review",
"created": "2025-11-23T12:34:56Z",
"description": "Purpose of this worktree"
}
Fields:
worktree: Directory name (not full path)branch: Git branch namemode: One of the 5 modes abovecreated: ISO 8601 UTC timestampdescription: Freeform text explaining purpose
README.working-tree.md
Generated automatically with worktree details, mode semantics, and paths.
Templates
Available Templates
Located in templates/ directory:
ai-context.json.template- Metadata file template with examplesREADME.working-tree.template- README template with placeholders
To view templates:
- Ask "show me the metadata template"
- Ask "show me the README template"
Common Patterns
Pattern 1: Feature Development
/working-tree:new feature/user-auth --mode feature --description "Implement OAuth2"
Work in isolation, merge when ready.
Pattern 2: Production Hotfix
/working-tree:new bugfix/critical-security-fix --mode bugfix
Quick surgical fix, minimizes risk.
Pattern 3: Experimentation
/working-tree:new exp/try-new-framework --mode experiment
Prototype freely, discard if needed.
Pattern 4: Code Review
/working-tree:new review/pr-123 --mode review --description "Review user auth PR"
Review without disrupting current work.
Pattern 5: Internationalization
/working-tree:new i18n/zh-CN --description "Chinese Simplified translations"
/working-tree:new i18n/42-ja-JP --description "Japanese translations for issue #42"
Isolated i18n work for specific locale.
Supporting Files
- references/best-practices.md: Comprehensive guide with detailed best practices, naming conventions, workflows, and advanced patterns
- templates/ai-context.json.template: Copy-paste template for manual metadata creation
- templates/README.working-tree.template: Template for worktree README
Quick Tips
DO:
- Use descriptive branch names:
feature/user-dashboard - Add descriptions to worktrees:
--description "User settings page" - Run
/working-tree:listregularly to see active work - Choose appropriate mode for context
DON'T:
- Create worktree for same branch twice
- Use generic names:
test,temp,new - Use branch names that match existing project folders (e.g.,
workflows,src,backend) - Forget to clean up:
/working-tree:destroywhen done - Ignore uncommitted changes before destroying
For More Detail
Comprehensive Guide:
Ask to see references/best-practices.md for:
- Detailed mode usage guidelines
- Naming conventions and patterns
- Multi-worktree organization strategies
- Troubleshooting common issues
- Team collaboration workflows
- CI/CD integration patterns
Strategic Consulting:
For complex worktree organization questions, invoke the working-tree-consultant agent:
- "Help me organize my worktrees"
- "Review my worktree strategy"
- "Migrate to worktree workflow"
Examples
Example 1: Quick Mode Check
User: What mode should I use for a prototype?
Skill: For prototypes, use **experiment** mode.
Experiment mode:
- No restrictions, can be messy
- AI will be aggressive with suggestions
- Expect to discard if prototype fails
- Good for POCs and spikes
Command:
/working-tree:new exp/prototype-name --mode experiment --description "Testing new approach"
Example 2: Template Request
User: Show me the metadata template
Skill: Here's the .ai-context.json template:
[Shows content of templates/ai-context.json.template]
You can create this manually or use:
- /working-tree:new to auto-generate when creating
- /working-tree:adopt to auto-generate for existing worktree
Example 3: Best Practices Request
User: What are worktree best practices?
Skill: **Quick Best Practices:**
1. **Naming**: Use clear, structured names (myapp-feature-user-auth)
2. **Modes**: Choose mode based on work type (see mode semantics above)
3. **Cleanup**: Remove worktrees when done (/working-tree:destroy)
4. **Metadata**: Always add descriptions
5. **Organization**: One feature = one worktree
**Want more detail?**
- See REFERENCE.md for comprehensive guide
- Invoke working-tree-consultant for strategic advice
Related
- Commands:
/working-tree:new,/working-tree:list,/working-tree:status,/working-tree:destroy,/working-tree:adopt - Agent:
working-tree-consultantfor strategic guidance - Documentation: See REFERENCE.md for comprehensive coverage
Commands 5
/adopt:working-tree
Generate .ai-context.json and README.working-tree.md for existing worktree lacking metadata.
ARGUMENT SPECIFICATION
SYNTAX: /adopt:working-tree [--mode <mode>] [--description "<text>"]
OPTIONAL:
--mode <mode>
Type: enum[main, feature, bugfix, experiment, review]
Default: inferred from branch-name (see MODE_INFERENCE_ALGORITHM)
Validation: must match exactly one of the enum values
--description "<text>"
Type: string (quoted if contains spaces)
Default: "" (empty string)
Validation: any string, no restrictions
MODE_INFERENCE_ALGORITHM
APPLY rules sequentially, first match wins:
def infer_mode(branch_name: str) -> str:
if branch_name.startswith("feature/"):
return "feature"
elif branch_name.startswith(("bugfix/", "fix/")):
return "bugfix"
elif branch_name.startswith(("exp/", "experiment/")):
return "experiment"
elif branch_name.startswith("review/"):
return "review"
elif branch_name.startswith("i18n/"):
return "feature" # i18n work is feature-type work
elif branch_name in ("main", "master"):
return "main"
else:
return "feature" # DEFAULT
DETERMINISTIC: Given same branch_name, always produces same mode.
EXECUTION PROTOCOL
Execute steps sequentially. Each step must complete successfully before proceeding.
STEP 1: DETECT REPOSITORY INFO
EXECUTE:
REPO_ROOT=$(git rev-parse --show-toplevel 2>&1)
EXIT_CODE_ROOT=$?
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>&1)
EXIT_CODE_BRANCH=$?
VALIDATION:
- IF EXIT_CODE_ROOT != 0 → ERROR PATTERN "not-in-git-repo"
- IF EXIT_CODE_BRANCH != 0 → ERROR PATTERN "git-command-failed"
- REPO_ROOT must be absolute path starting with /
DATA EXTRACTION:
WORKTREE_NAME=$(basename "$REPO_ROOT")
NEXT:
- On success → STEP 2
- On failure → ABORT
STEP 2: CHECK EXISTING METADATA
EXECUTE:
METADATA_PATH="$REPO_ROOT/.ai-context.json"
test -f "$METADATA_PATH"
EXISTS=$?
VALIDATION:
- EXISTS is 0 (exists) or 1 (does not exist)
ACTION:
- IF EXISTS == 0 → STEP 3 (check for overwrite)
- IF EXISTS == 1 → STEP 4 (proceed with creation)
NEXT:
- Conditional based on EXISTS value
STEP 3: HANDLE EXISTING METADATA
EXECUTE:
EXISTING_JSON=$(cat "$METADATA_PATH" 2>&1)
EXISTING_MODE=$(echo "$EXISTING_JSON" | jq -r '.mode // "unknown"' 2>&1)
EXISTING_DESC=$(echo "$EXISTING_JSON" | jq -r '.description // ""' 2>&1)
EXISTING_CREATED=$(echo "$EXISTING_JSON" | jq -r '.created // ""' 2>&1)
DISPLAY TO USER:
Current worktree already has metadata:
Directory: {WORKTREE_NAME}
Branch: {CURRENT_BRANCH}
Mode: {EXISTING_MODE}
Created: {EXISTING_CREATED}
Description: {EXISTING_DESC or "None"}
Do you want to overwrite this metadata?
USER DECISION (use AskUserQuestion):
- Option 1: "Keep existing metadata" → TERMINATE (no changes)
- Option 2: "Overwrite with new metadata" → STEP 4 (proceed)
- Option 3: "Cancel" → TERMINATE (no changes)
NEXT:
- IF user selects overwrite → STEP 4
- IF user selects keep/cancel → TERMINATE
STEP 4: PARSE AND VALIDATE ARGUMENTS
PARSE:
# Parse --mode flag (if present)
if [[ "$@" =~ --mode[[:space:]]+([a-z]+) ]]; then
MODE_ARG="${BASH_REMATCH[1]}"
else
MODE_ARG=""
fi
# Parse --description flag (if present)
if [[ "$@" =~ --description[[:space:]]+\"([^\"]+)\" ]]; then
DESCRIPTION="${BASH_REMATCH[1]}"
elif [[ "$@" =~ --description[[:space:]]+([^[:space:]]+) ]]; then
DESCRIPTION="${BASH_REMATCH[1]}"
else
DESCRIPTION=""
fi
VALIDATION:
- IF MODE_ARG not empty AND MODE_ARG not in [main, feature, bugfix, experiment, review] → ERROR PATTERN "invalid-mode"
NEXT:
- On success → STEP 5
- On failure → ABORT
STEP 5: DETERMINE MODE
EXECUTE:
if [ -n "$MODE_ARG" ]; then
# Explicit mode provided
MODE="$MODE_ARG"
else
# Infer from branch name using MODE_INFERENCE_ALGORITHM
case "$CURRENT_BRANCH" in
feature/*)
MODE="feature"
;;
bugfix/*|fix/*)
MODE="bugfix"
;;
exp/*|experiment/*)
MODE="experiment"
;;
review/*)
MODE="review"
;;
i18n/*)
MODE="feature" # i18n work is feature-type work
;;
main|master)
MODE="main"
;;
*)
MODE="feature"
;;
esac
fi
VALIDATION:
- MODE must be exactly one of: main, feature, bugfix, experiment, review
- MODE must not be empty
DATA:
- MODE = final determined mode (explicit or inferred)
NEXT:
- On success → STEP 6
- On failure → ABORT (should not occur if STEP 4 validation passed)
STEP 6: GENERATE TIMESTAMP
EXECUTE:
CREATED_TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
FORMAT: ISO 8601 UTC (example: 2025-11-23T12:34:56Z)
VALIDATION:
- CREATED_TIMESTAMP must match pattern: ^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$
NEXT:
- On success → STEP 7
- No failure case
STEP 7: GENERATE .ai-context.json
CONTENT TEMPLATE:
{
"worktree": "{WORKTREE_NAME}",
"branch": "{CURRENT_BRANCH}",
"mode": "{MODE}",
"created": "{CREATED_TIMESTAMP}",
"description": "{DESCRIPTION}"
}
SUBSTITUTIONS:
- {WORKTREE_NAME} = from STEP 1
- {CURRENT_BRANCH} = from STEP 1
- {MODE} = from STEP 5
- {CREATED_TIMESTAMP} = from STEP 6
- {DESCRIPTION} = from STEP 4 (empty string if not provided)
EXECUTE:
cat > "$REPO_ROOT/.ai-context.json" <<EOF
{
"worktree": "$WORKTREE_NAME",
"branch": "$CURRENT_BRANCH",
"mode": "$MODE",
"created": "$CREATED_TIMESTAMP",
"description": "$DESCRIPTION"
}
EOF
VALIDATION:
- File must be created at exact path: $REPO_ROOT/.ai-context.json
- File must contain valid JSON
- Verify with:
jq empty "$REPO_ROOT/.ai-context.json" - IF jq fails → ERROR PATTERN "metadata-write-failed"
NEXT:
- On success → STEP 8
- On failure → ABORT
STEP 8: GENERATE README.working-tree.md (IF MISSING)
CHECK:
README_PATH="$REPO_ROOT/README.working-tree.md"
test -f "$README_PATH"
README_EXISTS=$?
ACTION:
- IF README_EXISTS == 0 (exists) → SKIP to STEP 9 (don't overwrite)
- IF README_EXISTS == 1 (missing) → Create README
CONTENT TEMPLATE:
# Worktree: {WORKTREE_NAME}
**Branch:** `{CURRENT_BRANCH}`
**Mode:** `{MODE}`
**Created:** {CREATED_TIMESTAMP}
## Purpose
{DESCRIPTION_OR_DEFAULT}
## Mode Semantics
- **main**: Minimal changes, stable work only
- **feature**: Active development, larger changes allowed
- **bugfix**: Isolated, surgical fixes only
- **experiment**: Prototypes, large swings, unsafe changes allowed
- **review**: Documentation, analysis, audits
## About This Worktree
This directory is an independent Git worktree attached to the main repository.
- Main repo: {REPO_ROOT}
- Worktree path: {REPO_ROOT}
- Branch: {CURRENT_BRANCH}
See `.ai-context.json` for machine-readable metadata.
SUBSTITUTIONS:
- {WORKTREE_NAME} = from STEP 1
- {CURRENT_BRANCH} = from STEP 1
- {MODE} = from STEP 5
- {CREATED_TIMESTAMP} = from STEP 6
- {DESCRIPTION_OR_DEFAULT} = DESCRIPTION if not empty, else "No description provided"
- {REPO_ROOT} = from STEP 1
EXECUTE (only if README_EXISTS == 1):
DESCRIPTION_TEXT="${DESCRIPTION:-No description provided}"
cat > "$REPO_ROOT/README.working-tree.md" <<EOF
# Worktree: $WORKTREE_NAME
**Branch:** \`$CURRENT_BRANCH\`
**Mode:** \`$MODE\`
**Created:** $CREATED_TIMESTAMP
## Purpose
$DESCRIPTION_TEXT
## Mode Semantics
- **main**: Minimal changes, stable work only
- **feature**: Active development, larger changes allowed
- **bugfix**: Isolated, surgical fixes only
- **experiment**: Prototypes, large swings, unsafe changes allowed
- **review**: Documentation, analysis, audits
## About This Worktree
This directory is an independent Git worktree attached to the main repository.
- Main repo: $REPO_ROOT
- Worktree path: $REPO_ROOT
- Branch: $CURRENT_BRANCH
See \`.ai-context.json\` for machine-readable metadata.
EOF
VALIDATION:
- IF created, file must exist at: $REPO_ROOT/README.working-tree.md
- IF file creation failed → Warning (not fatal)
NEXT:
- On success or skip → STEP 9
- On failure → Warning (continue)
STEP 9: OUTPUT SUCCESS SUMMARY
OUTPUT FORMAT (exact):
Adopted worktree successfully!
Directory: {WORKTREE_NAME}
Branch: {CURRENT_BRANCH}
Mode: {MODE}
Description: {DESCRIPTION_OR_NONE}
Metadata files created:
✓ .ai-context.json
{README_STATUS}
Use /status:working-tree to view metadata anytime.
SUBSTITUTIONS:
- {WORKTREE_NAME} = from STEP 1
- {CURRENT_BRANCH} = from STEP 1
- {MODE} = from STEP 5
- {DESCRIPTION_OR_NONE} = DESCRIPTION if not empty, else "None"
- {README_STATUS} = "✓ README.working-tree.md (created)" if created, "- README.working-tree.md (already exists)" if skipped
NEXT:
- TERMINATE (success)
ERROR PATTERNS
PATTERN: not-in-git-repo
DETECTION:
- TRIGGER: git rev-parse --show-toplevel exit code != 0
- INDICATORS: stderr contains "not a git repository"
RESPONSE (exact):
Error: Not in a git repository
Run this command from within a git repository.
To create a new worktree with metadata:
/create:working-tree <branch-name>
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
PATTERN: git-command-failed
DETECTION:
- TRIGGER: Any git command (except rev-parse --show-toplevel) returns non-zero exit code
- CAPTURE: stderr from git command
RESPONSE (exact):
Error: Failed to read git information
Git error: {GIT_STDERR}
Check that:
- You're in a git repository
- Git is installed and working
TEMPLATE SUBSTITUTIONS:
- {GIT_STDERR} = captured stderr
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
PATTERN: invalid-mode
DETECTION:
- TRIGGER: MODE_ARG provided but not in [main, feature, bugfix, experiment, review]
RESPONSE (exact):
Error: Invalid mode '{MODE_ARG}'
Valid modes: main, feature, bugfix, experiment, review
Example:
/adopt:working-tree --mode feature --description "new feature work"
TEMPLATE SUBSTITUTIONS:
- {MODE_ARG} = the invalid mode provided
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
PATTERN: metadata-write-failed
DETECTION:
- TRIGGER: .ai-context.json write fails or invalid JSON (STEP 7)
- CHECK: jq validation fails
RESPONSE (exact):
Error: Failed to write .ai-context.json
Write error: {ERROR_MESSAGE}
Check that:
- You have write permission in this directory
- Disk space is available
- No file conflicts exist
TEMPLATE SUBSTITUTIONS:
- {ERROR_MESSAGE} = error message from write operation
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
PATTERN: readme-write-failed
DETECTION:
- TRIGGER: README.working-tree.md write fails (STEP 8)
RESPONSE (exact):
Warning: Failed to write README.working-tree.md
The .ai-context.json was created successfully.
You can manually create the README if needed.
CONTROL FLOW:
- ABORT: false (warning, not critical)
- CLEANUP: none
- FALLBACK: Continue without README
TOOL PERMISSION MATRIX
| Tool | Pattern | Permission | Pre-Check | Post-Check | On-Deny-Action |
|---|---|---|---|---|---|
| Bash | git:* | ALLOW | command_safe | validate_output | N/A |
| Bash | date:* | ALLOW | N/A | N/A | N/A |
| Bash | test:* | ALLOW | N/A | N/A | N/A |
| Bash | basename:* | ALLOW | N/A | N/A | N/A |
| Bash | cat > *.json | ALLOW | dir_writable | valid_json | N/A |
| Bash | cat > *.md | ALLOW | dir_writable | N/A | N/A |
| Bash | jq:* | ALLOW | N/A | N/A | N/A |
| Bash | rm:* | DENY | N/A | N/A | ABORT "Destructive operation" |
| Bash | sudo:* | DENY | N/A | N/A | ABORT "Elevated privileges" |
| Write | $REPO_ROOT/.ai-context.json | ALLOW | dir_exists | valid_json | N/A |
| Write | $REPO_ROOT/README.working-tree.md | ALLOW | dir_exists | N/A | N/A |
| Write | */.env | DENY | N/A | N/A | ABORT "Secrets file" |
| Read | $REPO_ROOT/.ai-context.json | ALLOW | file_exists | N/A | N/A |
SECURITY CONSTRAINTS:
- Can only write to current worktree directory (REPO_ROOT)
- Cannot modify files outside current worktree
- Cannot execute destructive operations
- All file writes must be to metadata files only
TEST CASES
TC001: Adopt worktree without metadata
PRECONDITIONS:
- In git repository at /Users/dev/myapp
- Current branch: feature/login
- File does NOT exist: /Users/dev/myapp/.ai-context.json
INPUT:
/adopt:working-tree
EXPECTED EXECUTION FLOW:
- STEP 1 → REPO_ROOT="/Users/dev/myapp", WORKTREE_NAME="myapp", CURRENT_BRANCH="feature/login"
- STEP 2 → EXISTS=1 (no metadata)
- STEP 4 → MODE_ARG="", DESCRIPTION=""
- STEP 5 → MODE="feature" (inferred from "feature/" prefix)
- STEP 6 → Generate timestamp
- STEP 7 → Write .ai-context.json
- STEP 8 → README_EXISTS=1, create README
- STEP 9 → Output summary
EXPECTED OUTPUT:
Adopted worktree successfully!
Directory: myapp
Branch: feature/login
Mode: feature
Description: None
Metadata files created:
✓ .ai-context.json
✓ README.working-tree.md (created)
Use /status:working-tree to view metadata anytime.
VALIDATION COMMANDS:
# Verify .ai-context.json created
test -f /Users/dev/myapp/.ai-context.json && echo "PASS" || echo "FAIL"
jq -r '.mode' /Users/dev/myapp/.ai-context.json | grep "feature" && echo "PASS" || echo "FAIL"
# Verify README created
test -f /Users/dev/myapp/README.working-tree.md && echo "PASS" || echo "FAIL"
TC002: Adopt with explicit mode and description
PRECONDITIONS:
- In git repository at /Users/dev/myapp
- Current branch: main
- No existing metadata
INPUT:
/adopt:working-tree --mode main --description "Primary development branch"
EXPECTED EXECUTION FLOW: 1-2. Standard detection 3. STEP 4 → MODE_ARG="main", DESCRIPTION="Primary development branch" 4. STEP 5 → MODE="main" (explicit, not inferred) 5-8. Standard flow
EXPECTED .ai-context.json:
{
"worktree": "myapp",
"branch": "main",
"mode": "main",
"created": "2025-11-23T12:34:56Z",
"description": "Primary development branch"
}
VALIDATION:
jq -r '.mode' .ai-context.json | grep "main" && echo "PASS" || echo "FAIL"
jq -r '.description' .ai-context.json | grep "Primary development branch" && echo "PASS" || echo "FAIL"
TC003: Metadata already exists - user keeps existing
PRECONDITIONS:
- In git repository at /Users/dev/myapp
- File exists: /Users/dev/myapp/.ai-context.json with valid data
INPUT:
/adopt:working-tree --mode experiment
EXPECTED EXECUTION FLOW:
- STEP 1 → Detect repo
- STEP 2 → EXISTS=0 (metadata exists)
- STEP 3 → Display existing metadata, ask user
- USER SELECTS "Keep existing metadata"
- TERMINATE (no changes)
EXPECTED OUTPUT:
Current worktree already has metadata:
Directory: myapp
Branch: feature/login
Mode: feature
Created: 2025-11-20T10:00:00Z
Description: Original description
Do you want to overwrite this metadata?
POSTCONDITIONS:
- .ai-context.json unchanged
- No files modified
TC004: Metadata already exists - user overwrites
PRECONDITIONS:
- In git repository with existing .ai-context.json
INPUT:
/adopt:working-tree --mode experiment --description "New description"
EXPECTED EXECUTION FLOW: 1-2. Detect repo, metadata exists 3. STEP 3 → Display existing, ask user 4. USER SELECTS "Overwrite with new metadata" 5-9. Continue with creation (new timestamp, new mode, new description)
EXPECTED OUTPUT:
Current worktree already has metadata:
[existing data shown]
Do you want to overwrite this metadata?
[User confirms overwrite]
Adopted worktree successfully!
Directory: myapp
Branch: feature/login
Mode: experiment
Description: New description
Metadata files created:
✓ .ai-context.json
- README.working-tree.md (already exists)
Use /status:working-tree to view metadata anytime.
TC005: README already exists
PRECONDITIONS:
- No .ai-context.json
- README.working-tree.md already exists
INPUT:
/adopt:working-tree
EXPECTED EXECUTION FLOW: 1-7. Standard flow, create .ai-context.json 8. STEP 8 → README_EXISTS=0 (exists), skip creation 9. STEP 9 → Output shows README skipped
EXPECTED OUTPUT:
Adopted worktree successfully!
Directory: myapp
Branch: feature/login
Mode: feature
Description: None
Metadata files created:
✓ .ai-context.json
- README.working-tree.md (already exists)
Use /status:working-tree to view metadata anytime.
USE CASES
UC001: Adopting main repository
When working in main repo without worktrees:
cd ~/myapp
/adopt:working-tree --mode main --description "Primary development branch"
UC002: Adopting manually created worktree
If worktree created without /create:working-tree:
cd ../myapp-feature-something
/adopt:working-tree
UC003: Adding description later
If worktree created without description:
/adopt:working-tree --description "Working on user authentication refactor"
(Will prompt to overwrite existing metadata)
UC004: Correcting mode
If mode was inferred incorrectly:
/adopt:working-tree --mode experiment
(Will prompt to overwrite existing metadata)
RELATED COMMANDS
- /status:working-tree - View current metadata after adoption
- /create:working-tree - Create new worktree with metadata from start
- /list:working-tree - See all worktrees and their metadata status
DELEGATION
For organizing worktree adoption strategy:
Task(
subagent_type='working-tree-consultant',
description='Worktree adoption strategy',
prompt='[question about when/how to adopt worktrees]'
)
/destroy:working-tree
Safely remove git worktree directory and metadata files. Branch is preserved.
ARGUMENT SPECIFICATION
SYNTAX: /destroy:working-tree <worktree-path>
REQUIRED:
<worktree-path>
Type: path (absolute or relative)
Validation: Must be registered git worktree
Examples: "../myapp-feature-login", "/Users/dev/myapp-feature-login"
EXECUTION PROTOCOL
Execute steps sequentially. Each step must complete successfully before proceeding.
STEP 1: VALIDATE AND RESOLVE WORKTREE PATH
EXECUTE:
# Resolve to absolute path
if [[ "$WORKTREE_PATH_ARG" = /* ]]; then
WORKTREE_PATH="$WORKTREE_PATH_ARG"
else
WORKTREE_PATH=$(cd "$(dirname "$WORKTREE_PATH_ARG")" && pwd)/$(basename "$WORKTREE_PATH_ARG")
fi
VALIDATION:
- IF WORKTREE_PATH_ARG is empty → ERROR PATTERN "missing-path"
- WORKTREE_PATH must be absolute after resolution
NEXT:
- On success → STEP 2
- On failure → ABORT
STEP 2: CHECK PATH EXISTS
EXECUTE:
test -e "$WORKTREE_PATH"
EXISTS=$?
VALIDATION:
- IF EXISTS != 0 → ERROR PATTERN "path-not-exist"
NEXT:
- On EXISTS == 0 → STEP 3
- On EXISTS != 0 → ABORT
STEP 3: GET ALL WORKTREES AND VALIDATE
EXECUTE:
WORKTREE_LIST=$(git worktree list --porcelain 2>&1)
EXIT_CODE=$?
VALIDATION:
- IF EXIT_CODE != 0 → ERROR PATTERN "git-command-failed"
PARSE WORKTREE_LIST:
# Extract all worktree paths and branches
# Format: worktree /path\nHEAD hash\nbranch refs/heads/name\n\n
CURRENT_MAIN=$(echo "$WORKTREE_LIST" | head -1 | cut -d' ' -f2)
IS_MAIN_REPO=false
if [ "$WORKTREE_PATH" = "$CURRENT_MAIN" ]; then
IS_MAIN_REPO=true
fi
# Find worktree entry for target path
WORKTREE_ENTRY=$(echo "$WORKTREE_LIST" | grep -A 3 "^worktree $WORKTREE_PATH$")
IS_REGISTERED=$(echo "$WORKTREE_ENTRY" | wc -l)
VALIDATION:
- IF IS_MAIN_REPO == true → ERROR PATTERN "cannot-destroy-main"
- IF IS_REGISTERED == 0 → ERROR PATTERN "not-a-worktree"
DATA EXTRACTION:
BRANCH_REF=$(echo "$WORKTREE_ENTRY" | grep "^branch " | cut -d' ' -f2)
BRANCH_NAME=$(echo "$BRANCH_REF" | sed 's|refs/heads/||')
NEXT:
- On success → STEP 4
- On failure → ABORT
STEP 4: CHECK FOR UNCOMMITTED CHANGES
EXECUTE:
cd "$WORKTREE_PATH"
GIT_STATUS=$(git status --porcelain 2>&1)
STATUS_EXIT=$?
VALIDATION:
- IF STATUS_EXIT != 0 → Warning (worktree may be corrupted, allow removal)
DETECTION:
if [ -n "$GIT_STATUS" ]; then
HAS_CHANGES=true
else
HAS_CHANGES=false
fi
ACTION:
- IF HAS_CHANGES == false → STEP 5 (proceed directly)
- IF HAS_CHANGES == true → Display warning, ask user confirmation
USER DECISION (if HAS_CHANGES == true):
⚠ Warning: Uncommitted changes detected
Modified files:
{GIT_STATUS output}
These changes will be lost if you proceed.
Recommendations:
1. Commit changes: cd {WORKTREE_PATH} && git commit -am "message"
2. Stash changes: cd {WORKTREE_PATH} && git stash
3. Proceed anyway (changes will be lost)
Proceed with removal? (This will permanently delete uncommitted work)
Use AskUserQuestion:
- Option 1: "Cancel removal" → TERMINATE (no changes)
- Option 2: "Proceed with removal (discard changes)" → STEP 5
NEXT:
- IF user cancels → TERMINATE
- IF user proceeds OR no changes → STEP 5
STEP 5: REMOVE WORKTREE
EXECUTE:
git worktree remove --force "$WORKTREE_PATH" 2>&1
EXIT_CODE=$?
VALIDATION:
- IF EXIT_CODE != 0 → ERROR PATTERN "worktree-removal-failed"
NEXT:
- On success → STEP 6
- On failure → ABORT
STEP 6: PRUNE STALE REFERENCES
EXECUTE:
git worktree prune 2>&1
EXIT_CODE=$?
VALIDATION:
- IF EXIT_CODE != 0 → Warning (not fatal, removal succeeded)
NEXT:
- On success → STEP 7
- On warning → STEP 7 (continue)
STEP 7: OUTPUT SUCCESS SUMMARY
OUTPUT FORMAT (exact):
✓ Worktree removed successfully
Path: {WORKTREE_PATH}
Branch: {BRANCH_NAME}
Branch '{BRANCH_NAME}' has been preserved.
To delete the branch as well:
git branch -d {BRANCH_NAME} # Safe delete (only if merged)
git branch -D {BRANCH_NAME} # Force delete (even if unmerged)
To delete remote branch:
git push origin --delete {BRANCH_NAME}
SUBSTITUTIONS:
- {WORKTREE_PATH} = from STEP 1
- {BRANCH_NAME} = from STEP 3
NEXT:
- TERMINATE (success)
ERROR PATTERNS
PATTERN: missing-path
DETECTION:
- TRIGGER: WORKTREE_PATH_ARG is empty (no argument provided)
RESPONSE (exact):
Error: Missing worktree path
Usage:
/destroy:working-tree <worktree-path>
Example:
/destroy:working-tree ../myapp-feature-login
To see all worktrees:
/list:working-tree
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
PATTERN: path-not-exist
DETECTION:
- TRIGGER: Provided path does not exist (STEP 2)
RESPONSE (exact):
Error: Path does not exist
Path: {WORKTREE_PATH}
The specified path doesn't exist. Check for typos.
To list existing worktrees:
/list:working-tree
TEMPLATE SUBSTITUTIONS:
- {WORKTREE_PATH} = provided path
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
PATTERN: git-command-failed
DETECTION:
- TRIGGER: git worktree list command fails (STEP 3)
- CAPTURE: stderr from git command
RESPONSE (exact):
Error: Failed to list worktrees
Git error: {GIT_STDERR}
Check that:
- You're in a git repository
- Git is installed and working
TEMPLATE SUBSTITUTIONS:
- {GIT_STDERR} = captured stderr
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
PATTERN: cannot-destroy-main
DETECTION:
- TRIGGER: Target path matches main repository path (STEP 3)
RESPONSE (exact):
Error: Cannot destroy main repository
The path '{WORKTREE_PATH}' is the main repository, not a worktree.
To remove worktrees, use paths like:
/destroy:working-tree ../myapp-feature-branch
/destroy:working-tree ../myapp-bugfix-something
To see all worktrees:
/list:working-tree
TEMPLATE SUBSTITUTIONS:
- {WORKTREE_PATH} = main repository path
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
PATTERN: not-a-worktree
DETECTION:
- TRIGGER: Path exists but is not registered as git worktree (STEP 3)
RESPONSE (exact):
Error: Not a registered git worktree
Path: {WORKTREE_PATH}
This path is not a git worktree. To see all worktrees:
/list:working-tree
Valid worktree paths look like:
/Users/dev/myapp-feature-login
../myapp-bugfix-auth
TEMPLATE SUBSTITUTIONS:
- {WORKTREE_PATH} = provided path
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
PATTERN: worktree-removal-failed
DETECTION:
- TRIGGER: git worktree remove fails (STEP 5)
- CAPTURE: stderr from git worktree remove
RESPONSE (exact):
Error: Failed to remove worktree
Git error: {GIT_STDERR}
This can happen if:
- Worktree is locked
- Permission issues
- Worktree is corrupted
Try:
- Check file permissions
- Run: git worktree prune
- Manually remove directory and run: git worktree prune
TEMPLATE SUBSTITUTIONS:
- {GIT_STDERR} = captured stderr
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
TOOL PERMISSION MATRIX
| Tool | Pattern | Permission | Pre-Check | Post-Check | On-Deny-Action |
|---|---|---|---|---|---|
| Bash | git worktree:* | ALLOW | command_safe | validate_output | N/A |
| Bash | git status:* | ALLOW | command_safe | N/A | N/A |
| Bash | git branch:* | DENY | N/A | N/A | ABORT "Cannot delete branches automatically" |
| Bash | cd:* | ALLOW | N/A | N/A | N/A |
| Bash | test:* | ALLOW | N/A | N/A | N/A |
| Bash | pwd:* | ALLOW | N/A | N/A | N/A |
| Bash | dirname:* | ALLOW | N/A | N/A | N/A |
| Bash | basename:* | ALLOW | N/A | N/A | N/A |
| Bash | grep:* | ALLOW | N/A | N/A | N/A |
| Bash | sed:* | ALLOW | N/A | N/A | N/A |
| Bash | cut:* | ALLOW | N/A | N/A | N/A |
| Bash | wc:* | ALLOW | N/A | N/A | N/A |
| Bash | head:* | ALLOW | N/A | N/A | N/A |
| Bash | rm:* | DENY | N/A | N/A | ABORT "Use git worktree remove" |
| Bash | sudo:* | DENY | N/A | N/A | ABORT "Elevated privileges" |
| Read | * | DENY | N/A | N/A | ABORT "Destroy is read-only except git" |
| Write | * | DENY | N/A | N/A | ABORT "Destroy does not write files" |
SECURITY CONSTRAINTS:
- Can ONLY remove worktrees via git worktree remove
- CANNOT delete branches (user must do manually)
- CANNOT use rm/rmdir (git manages removal)
- MUST check for uncommitted changes
- MUST prevent main repository deletion
TEST CASES
TC001: Remove worktree with no uncommitted changes
PRECONDITIONS:
- Worktree exists at /Users/dev/myapp-feature-login
- Branch: feature/login
- No uncommitted changes
- Not the main repository
INPUT:
/destroy:working-tree /Users/dev/myapp-feature-login
EXPECTED EXECUTION FLOW:
- STEP 1 → WORKTREE_PATH="/Users/dev/myapp-feature-login"
- STEP 2 → EXISTS=0 (path exists)
- STEP 3 → IS_MAIN_REPO=false, IS_REGISTERED>0, BRANCH_NAME="feature/login"
- STEP 4 → HAS_CHANGES=false (no uncommitted changes)
- STEP 5 → git worktree remove succeeds
- STEP 6 → git worktree prune succeeds
- STEP 7 → Output summary
EXPECTED OUTPUT:
✓ Worktree removed successfully
Path: /Users/dev/myapp-feature-login
Branch: feature/login
Branch 'feature/login' has been preserved.
To delete the branch as well:
git branch -d feature/login # Safe delete (only if merged)
git branch -D feature/login # Force delete (even if unmerged)
To delete remote branch:
git push origin --delete feature/login
VALIDATION COMMANDS:
# Verify worktree no longer exists
test ! -e /Users/dev/myapp-feature-login && echo "PASS" || echo "FAIL"
# Verify branch still exists
git show-ref --verify refs/heads/feature/login && echo "PASS" || echo "FAIL"
# Verify not in worktree list
git worktree list | grep -v "feature-login" && echo "PASS" || echo "FAIL"
TC002: Remove worktree with uncommitted changes - user proceeds
PRECONDITIONS:
- Worktree exists at /Users/dev/myapp-bugfix-auth
- Has uncommitted changes: Modified src/auth.ts
INPUT:
/destroy:working-tree /Users/dev/myapp-bugfix-auth
EXPECTED EXECUTION FLOW: 1-3. Standard detection 4. STEP 4 → HAS_CHANGES=true 5. Display warning with git status output 6. USER SELECTS "Proceed with removal (discard changes)" 7. STEP 5 → git worktree remove --force succeeds 8. STEP 6-7 → Standard cleanup and output
EXPECTED OUTPUT (includes warning):
⚠ Warning: Uncommitted changes detected
Modified files:
M src/auth.ts
These changes will be lost if you proceed.
Recommendations:
1. Commit changes: cd /Users/dev/myapp-bugfix-auth && git commit -am "message"
2. Stash changes: cd /Users/dev/myapp-bugfix-auth && git stash
3. Proceed anyway (changes will be lost)
Proceed with removal? (This will permanently delete uncommitted work)
[User confirms]
✓ Worktree removed successfully
Path: /Users/dev/myapp-bugfix-auth
Branch: bugfix/auth
Branch 'bugfix/auth' has been preserved.
To delete the branch as well:
git branch -d bugfix/auth # Safe delete (only if merged)
git branch -D bugfix/auth # Force delete (even if unmerged)
To delete remote branch:
git push origin --delete bugfix/auth
TC003: Remove worktree with uncommitted changes - user cancels
PRECONDITIONS:
- Worktree with uncommitted changes
INPUT:
/destroy:working-tree /Users/dev/myapp-feature-test
EXPECTED EXECUTION FLOW: 1-4. Detect changes 5. Display warning 6. USER SELECTS "Cancel removal" 7. TERMINATE (no changes)
EXPECTED OUTPUT:
⚠ Warning: Uncommitted changes detected
[warning displayed]
Proceed with removal?
[User cancels]
Removal cancelled. No changes made.
POSTCONDITIONS:
- Worktree still exists
- No files modified
TC004: Attempt to destroy main repository
PRECONDITIONS:
- Main repository at /Users/dev/myapp
INPUT:
/destroy:working-tree /Users/dev/myapp
EXPECTED EXECUTION FLOW:
- STEP 1 → Resolve path
- STEP 2 → Path exists
- STEP 3 → IS_MAIN_REPO=true
- ERROR PATTERN "cannot-destroy-main"
- ABORT
EXPECTED OUTPUT:
Error: Cannot destroy main repository
The path '/Users/dev/myapp' is the main repository, not a worktree.
To remove worktrees, use paths like:
/destroy:working-tree ../myapp-feature-branch
/destroy:working-tree ../myapp-bugfix-something
To see all worktrees:
/list:working-tree
POSTCONDITIONS:
- Main repository untouched
- No changes made
TC005: Path does not exist
PRECONDITIONS:
- Path /Users/dev/nonexistent does not exist
INPUT:
/destroy:working-tree /Users/dev/nonexistent
EXPECTED EXECUTION FLOW:
- STEP 1 → Resolve path
- STEP 2 → EXISTS=1 (does not exist)
- ERROR PATTERN "path-not-exist"
- ABORT
EXPECTED OUTPUT:
Error: Path does not exist
Path: /Users/dev/nonexistent
The specified path doesn't exist. Check for typos.
To list existing worktrees:
/list:working-tree
TC006: Not a git worktree
PRECONDITIONS:
- Directory /Users/dev/random-dir exists but is not a git worktree
INPUT:
/destroy:working-tree /Users/dev/random-dir
EXPECTED EXECUTION FLOW: 1-2. Resolve and verify path exists 3. STEP 3 → IS_REGISTERED=0 (not in worktree list) 4. ERROR PATTERN "not-a-worktree" 5. ABORT
EXPECTED OUTPUT:
Error: Not a registered git worktree
Path: /Users/dev/random-dir
This path is not a git worktree. To see all worktrees:
/list:working-tree
Valid worktree paths look like:
/Users/dev/myapp-feature-login
../myapp-bugfix-auth
SAFETY FEATURES
PROTECTED OPERATIONS
- CANNOT remove main repository
- WARNS about uncommitted changes
- REQUIRES confirmation for destructive operations
- PRESERVES branch by default
BRANCH DELETION GUIDANCE
Command provides guidance but NEVER auto-deletes branches:
Safe delete (only if merged):
git branch -d <branch-name>
Force delete (even if unmerged):
git branch -D <branch-name>
Remote branch delete:
git push origin --delete <branch-name>
RELATED COMMANDS
- /list:working-tree - See all worktrees before deciding what to remove
- /status:working-tree - Check current worktree before removing
- /create:working-tree - Create new worktree after removal
DELEGATION
For guidance on when to remove worktrees:
Task(
subagent_type='working-tree-consultant',
description='Worktree removal strategy',
prompt='[question about when/how to safely remove worktrees]'
)
/list:working-tree
Enumerate all git worktrees and display metadata from .ai-context.json.
ARGUMENT SPECIFICATION
SYNTAX: /list:working-tree
NO ARGUMENTS
EXECUTION PROTOCOL
Execute steps sequentially. Each step must complete successfully before proceeding.
STEP 1: GET CURRENT WORKTREE
EXECUTE:
CURRENT_ROOT=$(git rev-parse --show-toplevel 2>&1)
EXIT_CODE=$?
VALIDATION:
- IF EXIT_CODE != 0 → ERROR PATTERN "not-in-git-repo"
NEXT:
- On success → STEP 2
- On failure → ABORT
STEP 2: LIST ALL WORKTREES
EXECUTE:
WORKTREE_LIST=$(git worktree list --porcelain 2>&1)
EXIT_CODE=$?
VALIDATION:
- IF EXIT_CODE != 0 → ERROR PATTERN "git-command-failed"
NEXT:
- On success → STEP 3
- On failure → ABORT
STEP 3: PARSE WORKTREES
PARSE FORMAT:
worktree /path/to/worktree
HEAD commit-hash
branch refs/heads/branch-name
worktree /another/path
HEAD commit-hash
branch refs/heads/another-branch
PARSING ALGORITHM:
worktrees = []
current_entry = {}
for line in WORKTREE_LIST.split("\n"):
if line.startswith("worktree "):
if current_entry:
worktrees.append(current_entry)
current_entry = {"path": line.split(" ", 1)[1]}
elif line.startswith("branch refs/heads/"):
current_entry["branch"] = line.split("/")[-1]
elif line == "":
if current_entry:
worktrees.append(current_entry)
current_entry = {}
if current_entry:
worktrees.append(current_entry)
DATA EXTRACTED:
- List of worktree entries, each with:
- path: absolute path to worktree
- branch: branch name (without refs/heads/)
NEXT:
- On success → STEP 4
- No failure case (empty list is valid)
STEP 4: READ METADATA FOR EACH WORKTREE
FOR EACH worktree in worktrees:
METADATA_PATH="$worktree_path/.ai-context.json"
test -f "$METADATA_PATH"
HAS_METADATA=$?
if [ $HAS_METADATA -eq 0 ]; then
METADATA=$(cat "$METADATA_PATH" 2>&1)
MODE=$(echo "$METADATA" | jq -r '.mode // "(invalid)"' 2>&1)
DESCRIPTION=$(echo "$METADATA" | jq -r '.description // ""' 2>&1)
# Validate JSON
if [ $? -ne 0 ]; then
MODE="(invalid json)"
DESCRIPTION=""
fi
else
MODE="(no metadata)"
DESCRIPTION="-"
fi
DATA STRUCTURE:
worktree_data = [
{
"path": "/path/to/worktree",
"branch": "feature/login",
"mode": "feature",
"description": "OAuth refactor",
"is_current": true/false,
"has_metadata": true/false
},
...
]
CURRENT DETECTION:
- IF worktree_path == CURRENT_ROOT → is_current = true
NEXT:
- On success → STEP 5
- Continue even if individual metadata reads fail
STEP 5: FORMAT AND DISPLAY TABLE
TABLE FORMAT:
Git Worktrees
═══════════════════════════════════════════════════════════════════════════════
Path Branch Mode Description
───────────────────────────────────────────────────────────────────────────────
{INDICATOR} {PATH} {BRANCH} {MODE} {DESCRIPTION}
...
═══════════════════════════════════════════════════════════════════════════════
Total: {COUNT} worktrees ({WITH_META} with metadata, {WITHOUT_META} without)
{TIP_IF_MISSING_METADATA}
FORMATTING RULES:
- INDICATOR: "→" if is_current, else " " (2 spaces)
- PATH: Truncate to 30 chars if longer, add "..." suffix
- BRANCH: Truncate to 20 chars if longer
- MODE: Truncate to 12 chars
- DESCRIPTION: Truncate to 40 chars if longer, add "..."
- Align columns with padding
PADDING ALGORITHM:
def pad_column(text, width):
if len(text) > width:
return text[:width-3] + "..."
return text + " " * (width - len(text))
TIP LOGIC:
- IF any worktree has has_metadata == false:
- Display: "Tip: Use /adopt:working-tree to add metadata to worktrees that lack it"
NEXT:
- On success → STEP 6
- No failure case
STEP 6: COUNT AND SUMMARIZE
COUNTS:
TOTAL=$(echo "$worktrees" | wc -l)
WITH_META=$(count worktrees where has_metadata == true)
WITHOUT_META=$(count worktrees where has_metadata == false)
SUMMARY LINE:
Total: {TOTAL} worktrees ({WITH_META} with metadata, {WITHOUT_META} without)
SPECIAL CASES:
- IF TOTAL == 1 AND WITHOUT_META == 1:
- Summary: "Total: 1 worktree (main repository only)"
- Tip: "To create a new worktree: /create:working-tree "
NEXT:
- TERMINATE (success)
ERROR PATTERNS
PATTERN: not-in-git-repo
DETECTION:
- TRIGGER: git rev-parse --show-toplevel exit code != 0
- INDICATORS: stderr contains "not a git repository"
RESPONSE (exact):
Error: Not in a git repository
Run this command from within a git repository.
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
PATTERN: git-command-failed
DETECTION:
- TRIGGER: git worktree list command fails (STEP 2)
- CAPTURE: stderr from git command
RESPONSE (exact):
Error: Failed to list worktrees
Git error: {GIT_STDERR}
Check that:
- You're in a git repository
- Git is installed and working
TEMPLATE SUBSTITUTIONS:
- {GIT_STDERR} = captured stderr
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
PATTERN: invalid-metadata-json
DETECTION:
- TRIGGER: jq fails to parse .ai-context.json (STEP 4)
- OCCURS: per-worktree, not fatal
RESPONSE:
Warning: Invalid .ai-context.json in {WORKTREE_PATH}
Displaying worktree without metadata. Consider:
- Fixing the JSON manually
- Running /adopt:working-tree in that worktree to regenerate
CONTROL FLOW:
- ABORT: false (warning only)
- DISPLAY: Show worktree with MODE="(invalid json)"
- CONTINUE: Process remaining worktrees
TOOL PERMISSION MATRIX
| Tool | Pattern | Permission | Pre-Check | Post-Check | On-Deny-Action |
|---|---|---|---|---|---|
| Bash | git worktree:* | ALLOW | command_safe | N/A | N/A |
| Bash | git rev-parse:* | ALLOW | command_safe | N/A | N/A |
| Bash | test:* | ALLOW | N/A | N/A | N/A |
| Bash | cat:* | ALLOW | N/A | N/A | N/A |
| Bash | jq:* | ALLOW | N/A | N/A | N/A |
| Bash | wc:* | ALLOW | N/A | N/A | N/A |
| Bash | grep:* | ALLOW | N/A | N/A | N/A |
| Bash | cut:* | ALLOW | N/A | N/A | N/A |
| Bash | sed:* | ALLOW | N/A | N/A | N/A |
| Bash | head:* | ALLOW | N/A | N/A | N/A |
| Bash | sudo:* | DENY | N/A | N/A | ABORT "Elevated privileges" |
| Read | */.ai-context.json | ALLOW | N/A | N/A | N/A |
| Write | * | DENY | N/A | N/A | ABORT "List is read-only" |
| Edit | * | DENY | N/A | N/A | ABORT "List is read-only" |
SECURITY CONSTRAINTS:
- Command is READ-ONLY
- Cannot modify any files
- Cannot execute destructive operations
- Safe to run multiple times
TEST CASES
TC001: Multiple worktrees with metadata
PRECONDITIONS:
- Main repository at /Users/dev/myapp
- Worktree at /Users/dev/myapp-feature-api with metadata (mode: feature, description: "New API")
- Worktree at /Users/dev/myapp-bugfix-auth with metadata (mode: bugfix, description: "Fix auth")
- Currently in /Users/dev/myapp
INPUT:
/list:working-tree
EXPECTED EXECUTION FLOW:
- STEP 1 → CURRENT_ROOT="/Users/dev/myapp"
- STEP 2 → Get worktree list
- STEP 3 → Parse 3 worktrees
- STEP 4 → Read metadata for each
- STEP 5-6 → Format and display
EXPECTED OUTPUT:
Git Worktrees
═══════════════════════════════════════════════════════════════════════════════
Path Branch Mode Description
───────────────────────────────────────────────────────────────────────────────
→ /Users/dev/myapp main main Main development
/Users/dev/myapp-feature... feature/api feature New API
/Users/dev/myapp-bugfix-... bugfix/auth bugfix Fix auth
═══════════════════════════════════════════════════════════════════════════════
Total: 3 worktrees (3 with metadata)
VALIDATION:
- Current worktree marked with →
- All columns aligned
- Counts correct
TC002: Mixed metadata status
PRECONDITIONS:
- Main repository without metadata
- One worktree with metadata
- One worktree without metadata
INPUT:
/list:working-tree
EXPECTED OUTPUT:
Git Worktrees
═══════════════════════════════════════════════════════════════════════════════
Path Branch Mode Description
───────────────────────────────────────────────────────────────────────────────
/Users/dev/myapp main (no metadata) -
→ /Users/dev/myapp-feature... feature/new feature New feature work
/Users/dev/old-checkout feature/abandoned (no metadata) -
═══════════════════════════════════════════════════════════════════════════════
Total: 3 worktrees (1 with metadata, 2 without)
Tip: Use /adopt:working-tree to add metadata to worktrees that lack it
VALIDATION:
- Tip displayed because some worktrees lack metadata
- (no metadata) shown for worktrees without .ai-context.json
TC003: Only main repository
PRECONDITIONS:
- Main repository only, no additional worktrees
- No metadata file
INPUT:
/list:working-tree
EXPECTED OUTPUT:
Git Worktrees
═══════════════════════════════════════════════════════════════════════════════
Path Branch Mode Description
───────────────────────────────────────────────────────────────────────────────
→ /Users/dev/myapp main (no metadata) -
═══════════════════════════════════════════════════════════════════════════════
Total: 1 worktree (main repository only)
To create a new worktree: /create:working-tree <branch-name>
VALIDATION:
- Special message for single worktree
- Tip suggests creating worktree
TC004: Invalid JSON in metadata file
PRECONDITIONS:
- Worktree at /Users/dev/myapp-test
- File exists: /Users/dev/myapp-test/.ai-context.json
- File contains invalid JSON:
{invalid
INPUT:
/list:working-tree
EXPECTED EXECUTION FLOW: 1-3. Standard flow 4. STEP 4 → jq fails on invalid JSON 5. Display warning 6. Show worktree with MODE="(invalid json)" 7. Continue with other worktrees
EXPECTED OUTPUT:
Warning: Invalid .ai-context.json in /Users/dev/myapp-test
Displaying worktree without metadata. Consider:
- Fixing the JSON manually
- Running /adopt:working-tree in that worktree to regenerate
Git Worktrees
═══════════════════════════════════════════════════════════════════════════════
Path Branch Mode Description
───────────────────────────────────────────────────────────────────────────────
→ /Users/dev/myapp-test feature/test (invalid json) -
═══════════════════════════════════════════════════════════════════════════════
Total: 1 worktree (0 with metadata, 1 without)
Tip: Use /adopt:working-tree to add metadata to worktrees that lack it
TC005: Long paths and descriptions
PRECONDITIONS:
- Worktree with very long path: /Users/dev/myapp-feature-really-long-branch-name-that-exceeds-column-width
- Description: "This is a very long description that exceeds the maximum column width and should be truncated"
INPUT:
/list:working-tree
EXPECTED OUTPUT:
Git Worktrees
═══════════════════════════════════════════════════════════════════════════════
Path Branch Mode Description
───────────────────────────────────────────────────────────────────────────────
→ /Users/dev/myapp-feature... feature/really-lo... feature This is a very long description that...
═══════════════════════════════════════════════════════════════════════════════
Total: 1 worktree (1 with metadata)
VALIDATION:
- Long path truncated with "..."
- Long branch truncated with "..."
- Long description truncated with "..."
- Columns remain aligned
DISPLAY NOTES
COLUMN WIDTHS
Fixed widths for consistent alignment:
- Indicator: 2 chars ("→ " or " ")
- Path: 30 chars
- Branch: 20 chars
- Mode: 13 chars
- Description: remaining width (or 40 chars minimum)
TRUNCATION STRATEGY
def truncate(text, max_width):
if len(text) <= max_width:
return text
return text[:max_width-3] + "..."
BOX DRAWING
Use consistent box-drawing characters:
- Top/bottom:
═(double horizontal) - Separator:
─(single horizontal) - No vertical bars (cleaner appearance)
RELATED COMMANDS
- /status:working-tree - Show current worktree details
- /create:working-tree - Create new worktree with metadata
- /adopt:working-tree - Add metadata to existing worktree
- /destroy:working-tree - Remove worktree
DELEGATION
For organizing multiple worktrees strategically:
Task(
subagent_type='working-tree-consultant',
description='Worktree organization strategy',
prompt='[question about managing multiple worktrees]'
)
/working-tree:new
Create new branch (if needed), attach git worktree, generate AI metadata files for isolated development.
Important: The command validates that the worktree name will not conflict with existing top-level directories in your project. If a conflict is detected, creation will be blocked and alternative naming patterns will be suggested.
ARGUMENT SPECIFICATION
SYNTAX: /working-tree:new <branch-name> [--mode <mode>] [--description "<text>"]
REQUIRED:
<branch-name>
Type: string
Position: 1
Validation: ^[a-zA-Z0-9/_-]+$
Examples: "feature/login", "bugfix/timeout", "main"
OPTIONAL:
--mode <mode>
Type: enum[main, feature, bugfix, experiment, review]
Default: inferred from branch-name (see MODE_INFERENCE_ALGORITHM)
Validation: must match exactly one of the enum values
--description "<text>"
Type: string (quoted if contains spaces)
Default: "" (empty string)
Validation: any string, no restrictions
MODE_INFERENCE_ALGORITHM
APPLY rules sequentially, first match wins:
def infer_mode(branch_name: str) -> str:
if branch_name.startswith("feature/"):
return "feature"
elif branch_name.startswith(("bugfix/", "fix/")):
return "bugfix"
elif branch_name.startswith(("exp/", "experiment/")):
return "experiment"
elif branch_name.startswith("review/"):
return "review"
elif branch_name.startswith("i18n/"):
return "feature" # i18n work is feature-type work
elif branch_name in ("main", "master"):
return "main"
else:
return "feature" # DEFAULT
DETERMINISTIC: Given same branch_name, always produces same mode.
EXECUTION PROTOCOL
Execute steps sequentially. Each step must complete successfully before proceeding.
STEP 1: DETECT REPOSITORY INFO
EXECUTE:
REPO_ROOT=$(git rev-parse --show-toplevel 2>&1)
EXIT_CODE_ROOT=$?
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>&1)
EXIT_CODE_BRANCH=$?
VALIDATION:
- IF EXIT_CODE_ROOT != 0 → ERROR PATTERN "not-in-git-repo"
- IF EXIT_CODE_BRANCH != 0 → ERROR PATTERN "git-command-failed"
- REPO_ROOT must be absolute path starting with /
DATA EXTRACTION:
REPO_NAME=$(basename "$REPO_ROOT")
PARENT_DIR=$(dirname "$REPO_ROOT")
NEXT:
- On success → STEP 2
- On failure → ABORT
STEP 2: PARSE AND VALIDATE ARGUMENTS
PARSE:
# Extract branch name (first positional argument)
BRANCH_NAME="$1"
# Parse --mode flag (if present)
if [[ "$@" =~ --mode[[:space:]]+([a-z]+) ]]; then
MODE_ARG="${BASH_REMATCH[1]}"
else
MODE_ARG=""
fi
# Parse --description flag (if present)
if [[ "$@" =~ --description[[:space:]]+\"([^\"]+)\" ]]; then
DESCRIPTION="${BASH_REMATCH[1]}"
elif [[ "$@" =~ --description[[:space:]]+([^[:space:]]+) ]]; then
DESCRIPTION="${BASH_REMATCH[1]}"
else
DESCRIPTION=""
fi
VALIDATION:
- IF BRANCH_NAME is empty → ERROR PATTERN "missing-branch-name"
- IF BRANCH_NAME !~ ^[a-zA-Z0-9/_-]+$ → ERROR PATTERN "invalid-branch-name"
- IF MODE_ARG not empty AND MODE_ARG not in [main, feature, bugfix, experiment, review] → ERROR PATTERN "invalid-mode"
NEXT:
- On success → STEP 3
- On failure → ABORT
STEP 3: DETERMINE MODE
EXECUTE:
if [ -n "$MODE_ARG" ]; then
# Explicit mode provided
MODE="$MODE_ARG"
else
# Infer from branch name using MODE_INFERENCE_ALGORITHM
case "$BRANCH_NAME" in
feature/*)
MODE="feature"
;;
bugfix/*|fix/*)
MODE="bugfix"
;;
exp/*|experiment/*)
MODE="experiment"
;;
review/*)
MODE="review"
;;
i18n/*)
MODE="feature" # i18n work is feature-type work
;;
main|master)
MODE="main"
;;
*)
MODE="feature"
;;
esac
fi
VALIDATION:
- MODE must be exactly one of: main, feature, bugfix, experiment, review
- MODE must not be empty
DATA:
- MODE = final determined mode (explicit or inferred)
NEXT:
- On success → STEP 4
- On failure → ABORT (should not occur if STEP 2 validation passed)
STEP 4: CHECK BRANCH EXISTENCE
EXECUTE:
git show-ref --verify --quiet refs/heads/$BRANCH_NAME
BRANCH_EXISTS=$?
BRANCH_EXISTS values:
- 0 = branch exists
- 1 = branch does not exist
- Other = error
VALIDATION:
- IF BRANCH_EXISTS not in [0, 1] → ERROR PATTERN "git-command-failed"
ACTION:
- IF BRANCH_EXISTS == 1 (does not exist) → Create branch in STEP 5
- IF BRANCH_EXISTS == 0 (exists) → Use existing branch, skip to STEP 6
NEXT:
- On BRANCH_EXISTS == 0 → STEP 6
- On BRANCH_EXISTS == 1 → STEP 5
- On error → ABORT
STEP 5: CREATE NEW BRANCH
EXECUTE (only if BRANCH_EXISTS == 1):
git branch "$BRANCH_NAME" 2>&1
EXIT_CODE=$?
VALIDATION:
- IF EXIT_CODE != 0 → ERROR PATTERN "branch-creation-failed"
NEXT:
- On success → STEP 6
- On failure → ABORT
STEP 6: DERIVE WORKTREE DIRECTORY NAME
EXECUTE:
# Normalize branch name: replace / and _ with -, convert to lowercase
NORMALIZED_BRANCH=$(echo "$BRANCH_NAME" | tr '/_' '-' | tr '[:upper:]' '[:lower:]')
WORKTREE_NAME="${REPO_NAME}-${NORMALIZED_BRANCH}"
WORKTREE_PATH="${PARENT_DIR}/${WORKTREE_NAME}"
NORMALIZATION RULES:
- Replace
/with- - Replace
_with- - Convert to lowercase
EXAMPLES:
- myapp + feature/login → myapp-feature-login
- api-server + bugfix/SESSION_timeout → api-server-bugfix-session-timeout
DATA:
- WORKTREE_NAME = derived directory name
- WORKTREE_PATH = absolute path to worktree location
NEXT:
- On success → STEP 7
- No validation needed (pure transformation)
STEP 7: CHECK FOR TOP-LEVEL DIRECTORY NAME CONFLICTS
EXECUTE:
# Get list of top-level directories in the repository
TOP_LEVEL_DIRS=$(cd "$REPO_ROOT" && ls -d */ 2>/dev/null | sed 's|/||g')
# Check if the normalized branch name matches any top-level directory
CONFLICT_DIR=""
for dir in $TOP_LEVEL_DIRS; do
if [ "$NORMALIZED_BRANCH" = "$dir" ]; then
CONFLICT_DIR="$dir"
break
fi
done
VALIDATION:
- IF CONFLICT_DIR not empty → ERROR PATTERN "worktree-name-conflicts-with-directory"
CONTEXT:
- This prevents creating worktrees with names that match existing project folders
- Such conflicts can cause confusion during git operations and rebases
- Example: branch "workflows" would create "myapp-workflows" which conflicts with "workflows/" directory
NEXT:
- On CONFLICT_DIR empty → STEP 8
- On CONFLICT_DIR not empty → ABORT
STEP 8: CHECK FOR EXISTING WORKTREE ON BRANCH
EXECUTE:
EXISTING_WORKTREE=$(git worktree list --porcelain | grep -A 3 "^branch refs/heads/$BRANCH_NAME$" | grep "^worktree " | cut -d' ' -f2)
VALIDATION:
- IF EXISTING_WORKTREE not empty → ERROR PATTERN "branch-has-worktree" with path=$EXISTING_WORKTREE
NEXT:
- On EXISTING_WORKTREE empty → STEP 9
- On EXISTING_WORKTREE not empty → ABORT
STEP 9: CHECK TARGET DIRECTORY DOESN'T EXIST
EXECUTE:
test -e "$WORKTREE_PATH"
DIR_EXISTS=$?
VALIDATION:
- IF DIR_EXISTS == 0 (directory exists) → ERROR PATTERN "directory-exists"
NEXT:
- On DIR_EXISTS != 0 (does not exist) → STEP 10
- On DIR_EXISTS == 0 (exists) → ABORT
STEP 10: CREATE WORKTREE
EXECUTE:
git worktree add "$WORKTREE_PATH" "$BRANCH_NAME" 2>&1
EXIT_CODE=$?
VALIDATION:
- IF EXIT_CODE != 0 → ERROR PATTERN "worktree-creation-failed"
NEXT:
- On success → STEP 11
- On failure → ABORT
STEP 11: GENERATE TIMESTAMP
EXECUTE:
CREATED_TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
FORMAT: ISO 8601 UTC (example: 2025-11-23T12:34:56Z)
VALIDATION:
- CREATED_TIMESTAMP must match pattern: ^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$
NEXT:
- On success → STEP 12
- No failure case
STEP 12: GENERATE .ai-context.json
CONTENT TEMPLATE:
{
"worktree": "{WORKTREE_NAME}",
"branch": "{BRANCH_NAME}",
"mode": "{MODE}",
"created": "{CREATED_TIMESTAMP}",
"description": "{DESCRIPTION}"
}
SUBSTITUTIONS:
- {WORKTREE_NAME} = from STEP 6
- {BRANCH_NAME} = from STEP 2
- {MODE} = from STEP 3
- {CREATED_TIMESTAMP} = from STEP 10
- {DESCRIPTION} = from STEP 2 (empty string if not provided)
EXECUTE:
cat > "$WORKTREE_PATH/.ai-context.json" <<EOF
{
"worktree": "$WORKTREE_NAME",
"branch": "$BRANCH_NAME",
"mode": "$MODE",
"created": "$CREATED_TIMESTAMP",
"description": "$DESCRIPTION"
}
EOF
VALIDATION:
- File must be created at exact path: $WORKTREE_PATH/.ai-context.json
- File must contain valid JSON
- Verify with:
jq empty "$WORKTREE_PATH/.ai-context.json" - IF jq fails → ERROR PATTERN "metadata-write-failed"
NEXT:
- On success → STEP 13
- On failure → ABORT (and cleanup worktree)
STEP 13: GENERATE README.working-tree.md
CONTENT TEMPLATE:
# Worktree: {WORKTREE_NAME}
**Branch:** `{BRANCH_NAME}`
**Mode:** `{MODE}`
**Created:** {CREATED_TIMESTAMP}
## Purpose
{DESCRIPTION_OR_DEFAULT}
## Mode Semantics
- **main**: Minimal changes, stable work only
- **feature**: Active development, larger changes allowed
- **bugfix**: Isolated, surgical fixes only
- **experiment**: Prototypes, large swings, unsafe changes allowed
- **review**: Documentation, analysis, audits
## About This Worktree
This directory is an independent Git worktree attached to the main repository.
- Main repo: {REPO_ROOT}
- Worktree path: {WORKTREE_PATH}
- Branch: {BRANCH_NAME}
See `.ai-context.json` for machine-readable metadata.
SUBSTITUTIONS:
- {WORKTREE_NAME} = from STEP 6
- {BRANCH_NAME} = from STEP 2
- {MODE} = from STEP 3
- {CREATED_TIMESTAMP} = from STEP 10
- {DESCRIPTION_OR_DEFAULT} = DESCRIPTION if not empty, else "No description provided"
- {REPO_ROOT} = from STEP 1
- {WORKTREE_PATH} = from STEP 6
EXECUTE:
DESCRIPTION_TEXT="${DESCRIPTION:-No description provided}"
cat > "$WORKTREE_PATH/README.working-tree.md" <<EOF
# Worktree: $WORKTREE_NAME
**Branch:** \`$BRANCH_NAME\`
**Mode:** \`$MODE\`
**Created:** $CREATED_TIMESTAMP
## Purpose
$DESCRIPTION_TEXT
## Mode Semantics
- **main**: Minimal changes, stable work only
- **feature**: Active development, larger changes allowed
- **bugfix**: Isolated, surgical fixes only
- **experiment**: Prototypes, large swings, unsafe changes allowed
- **review**: Documentation, analysis, audits
## About This Worktree
This directory is an independent Git worktree attached to the main repository.
- Main repo: $REPO_ROOT
- Worktree path: $WORKTREE_PATH
- Branch: $BRANCH_NAME
See \`.ai-context.json\` for machine-readable metadata.
EOF
VALIDATION:
- File must exist at: $WORKTREE_PATH/README.working-tree.md
- IF file creation failed → ERROR PATTERN "readme-write-failed"
NEXT:
- On success → STEP 14
- On failure → ABORT (and cleanup)
STEP 14: OUTPUT SUCCESS SUMMARY
OUTPUT FORMAT (exact):
Created worktree successfully!
Path: {WORKTREE_PATH}
Branch: {BRANCH_NAME}
Mode: {MODE}
Description: {DESCRIPTION_OR_NONE}
Metadata files created:
✓ .ai-context.json
✓ README.working-tree.md
To switch to this worktree:
cd {WORKTREE_PATH}
SUBSTITUTIONS:
- {WORKTREE_PATH} = from STEP 6
- {BRANCH_NAME} = from STEP 2
- {MODE} = from STEP 3
- {DESCRIPTION_OR_NONE} = DESCRIPTION if not empty, else "None"
NEXT:
- TERMINATE (success)
ERROR PATTERNS
PATTERN: not-in-git-repo
DETECTION:
- TRIGGER: git rev-parse --show-toplevel exit code != 0
- INDICATORS: stderr contains "not a git repository"
RESPONSE (exact):
Error: Not in a git repository
Run this command from within a git repository.
CONTROL FLOW:
- ABORT: true
- CLEANUP: none needed
- RETRY: false
PATTERN: missing-branch-name
DETECTION:
- TRIGGER: BRANCH_NAME is empty string after parsing
RESPONSE (exact):
Error: Missing required argument <branch-name>
Usage:
/working-tree:new <branch-name> [--mode <mode>] [--description "<text>"]
Example:
/working-tree:new feature/my-feature
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
PATTERN: invalid-branch-name
DETECTION:
- TRIGGER: BRANCH_NAME does not match ^[a-zA-Z0-9/_-]+$
- INDICATORS: Contains invalid characters
RESPONSE (exact):
Error: Invalid branch name '{BRANCH_NAME}'
Branch names must contain only:
- Letters (a-z, A-Z)
- Numbers (0-9)
- Forward slashes (/)
- Hyphens (-)
- Underscores (_)
Example valid names:
feature/login
bugfix/timeout-issue
exp/ai_integration
TEMPLATE SUBSTITUTIONS:
- {BRANCH_NAME} = the invalid branch name provided
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
PATTERN: invalid-mode
DETECTION:
- TRIGGER: MODE_ARG provided but not in [main, feature, bugfix, experiment, review]
RESPONSE (exact):
Error: Invalid mode '{MODE_ARG}'
Valid modes: main, feature, bugfix, experiment, review
Example:
/working-tree:new my-branch --mode feature
TEMPLATE SUBSTITUTIONS:
- {MODE_ARG} = the invalid mode provided
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
PATTERN: git-command-failed
DETECTION:
- TRIGGER: Any git command (except specific patterns) returns non-zero exit code
- CAPTURE: stderr from git command
RESPONSE (exact):
Error: Git command failed
Git error: {GIT_STDERR}
Check that:
- You're in a git repository
- Git is installed and working
- You have necessary permissions
TEMPLATE SUBSTITUTIONS:
- {GIT_STDERR} = captured stderr
CONTROL FLOW:
- ABORT: true
- CLEANUP: Remove worktree if created
- RETRY: false
PATTERN: branch-creation-failed
DETECTION:
- TRIGGER: git branch command fails (STEP 5)
- CAPTURE: stderr from git branch
RESPONSE (exact):
Error: Failed to create branch '{BRANCH_NAME}'
Git error: {GIT_STDERR}
Check that:
- Branch name is valid
- You're not in detached HEAD state
- You have permission to create branches
TEMPLATE SUBSTITUTIONS:
- {BRANCH_NAME} = attempted branch name
- {GIT_STDERR} = captured stderr
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
PATTERN: worktree-name-conflicts-with-directory
DETECTION:
- TRIGGER: NORMALIZED_BRANCH matches an existing top-level directory name (STEP 7)
- CAPTURE: CONFLICT_DIR = the conflicting directory name
RESPONSE (exact):
Error: Worktree name conflicts with existing project directory '{CONFLICT_DIR}/'
The proposed worktree name '{WORKTREE_NAME}' would conflict with the existing
'{CONFLICT_DIR}/' directory in your project.
This can cause confusion during git operations and rebases.
Suggested alternatives:
- Use a prefix: /working-tree:new feat/{BRANCH_NAME}
- Use a suffix: /working-tree:new {BRANCH_NAME}-update
- Be more specific: /working-tree:new feature/{BRANCH_NAME}-refactor
Current branch name: {BRANCH_NAME}
Proposed worktree: {WORKTREE_NAME}
Conflicting directory: {CONFLICT_DIR}/
TEMPLATE SUBSTITUTIONS:
- {CONFLICT_DIR} = the directory name that conflicts
- {WORKTREE_NAME} = the full proposed worktree name
- {BRANCH_NAME} = the branch name provided by user
CONTROL FLOW:
- ABORT: true
- CLEANUP: none (nothing created yet)
- RETRY: false (user must choose different name)
PATTERN: branch-has-worktree
DETECTION:
- TRIGGER: git worktree list shows branch already has attached worktree (STEP 8)
- CAPTURE: EXISTING_WORKTREE path
RESPONSE (exact):
Error: Branch '{BRANCH_NAME}' already has a worktree at {EXISTING_WORKTREE}
Use one of:
- /working-tree:list to see all worktrees
- cd {EXISTING_WORKTREE} to use the existing worktree
- /working-tree:destroy {EXISTING_WORKTREE} to remove it first
TEMPLATE SUBSTITUTIONS:
- {BRANCH_NAME} = branch with existing worktree
- {EXISTING_WORKTREE} = path to existing worktree
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
PATTERN: directory-exists
DETECTION:
- TRIGGER: Target directory already exists (STEP 9)
- CHECK: test -e "$WORKTREE_PATH" returns 0
RESPONSE (exact):
Error: Directory '{WORKTREE_PATH}' already exists
Choose a different branch name or remove the existing directory.
To remove:
rm -rf {WORKTREE_PATH}
(Be careful - this will delete all contents)
TEMPLATE SUBSTITUTIONS:
- {WORKTREE_PATH} = path that already exists
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: false
PATTERN: worktree-creation-failed
DETECTION:
- TRIGGER: git worktree add fails (STEP 10)
- CAPTURE: stderr from git worktree add
RESPONSE (exact):
Error: Failed to create worktree
Git error: {GIT_STDERR}
Check that:
- Parent directory is writable
- Branch name is valid
- No permission issues
TEMPLATE SUBSTITUTIONS:
- {GIT_STDERR} = captured stderr
CONTROL FLOW:
- ABORT: true
- CLEANUP: Attempt to remove partially created worktree
- RETRY: false
PATTERN: metadata-write-failed
DETECTION:
- TRIGGER: .ai-context.json write fails or invalid JSON (STEP 12)
- CHECK: jq validation fails
RESPONSE (exact):
Error: Failed to write .ai-context.json
The worktree was created but metadata file generation failed.
Worktree location: {WORKTREE_PATH}
You can:
1. Manually create .ai-context.json
2. Use /working-tree:adopt to regenerate metadata
3. Remove worktree with /working-tree:destroy {WORKTREE_PATH}
TEMPLATE SUBSTITUTIONS:
- {WORKTREE_PATH} = worktree path
CONTROL FLOW:
- ABORT: false (worktree exists, metadata failed)
- CLEANUP: none (leave worktree intact)
- FALLBACK: User can manually fix or adopt
PATTERN: readme-write-failed
DETECTION:
- TRIGGER: README.working-tree.md write fails (STEP 13)
RESPONSE (exact):
Warning: Failed to write README.working-tree.md
The worktree and .ai-context.json were created successfully.
Worktree location: {WORKTREE_PATH}
You can manually create the README if needed.
TEMPLATE SUBSTITUTIONS:
- {WORKTREE_PATH} = worktree path
CONTROL FLOW:
- ABORT: false (warning, not critical)
- CLEANUP: none
- FALLBACK: Continue without README
TOOL PERMISSION MATRIX
| Tool | Pattern | Permission | Pre-Check | Post-Check | On-Deny-Action |
|---|---|---|---|---|---|
| Bash | git:* | ALLOW | command_safe | validate_output | N/A |
| Bash | date:* | ALLOW | N/A | N/A | N/A |
| Bash | test:* | ALLOW | N/A | N/A | N/A |
| Bash | basename:* | ALLOW | N/A | N/A | N/A |
| Bash | dirname:* | ALLOW | N/A | N/A | N/A |
| Bash | tr:* | ALLOW | N/A | N/A | N/A |
| Bash | grep:* | ALLOW | N/A | N/A | N/A |
| Bash | cat > *.json | ALLOW | parent_dir_writable | valid_json | N/A |
| Bash | cat > *.md | ALLOW | parent_dir_writable | N/A | N/A |
| Bash | jq:* | ALLOW | N/A | N/A | N/A |
| Bash | rm -rf:* | DENY | N/A | N/A | ABORT "Destructive operation not allowed" |
| Bash | sudo:* | DENY | N/A | N/A | ABORT "Elevated privileges" |
| Write | $WORKTREE_PATH/.ai-context.json | ALLOW | dir_exists | valid_json | N/A |
| Write | $WORKTREE_PATH/README.working-tree.md | ALLOW | dir_exists | N/A | N/A |
| Write | */.env | DENY | N/A | N/A | ABORT "Secrets file" |
| Read | * | DENY | N/A | N/A | ABORT "Command is write-only" |
SECURITY CONSTRAINTS:
- Can only write to newly created worktree directory
- Cannot modify existing files
- Cannot remove directories (even on cleanup)
- Git worktree add is safe (git manages cleanup)
TEST CASES
TC001: Create new feature branch worktree
PRECONDITIONS:
- In git repository at /Users/dev/myapp
- Current branch: main
- Branch "feature/login-refactor" does not exist
- Directory /Users/dev/myapp-feature-login-refactor does not exist
INPUT:
/working-tree:new feature/login-refactor
EXPECTED EXECUTION FLOW:
- STEP 1 → REPO_ROOT="/Users/dev/myapp", REPO_NAME="myapp", PARENT_DIR="/Users/dev"
- STEP 2 → BRANCH_NAME="feature/login-refactor", MODE_ARG="", DESCRIPTION=""
- STEP 3 → MODE="feature" (inferred from "feature/" prefix)
- STEP 4 → BRANCH_EXISTS=1 (does not exist)
- STEP 5 → Create branch "feature/login-refactor"
- STEP 6 → WORKTREE_NAME="myapp-feature-login-refactor", WORKTREE_PATH="/Users/dev/myapp-feature-login-refactor"
- STEP 7 → No directory conflict
- STEP 8 → No existing worktree
- STEP 9 → Directory does not exist
- STEP 10 → Create worktree
- STEP 11 → Generate timestamp
- STEP 12 → Write .ai-context.json
- STEP 13 → Write README.working-tree.md
- STEP 14 → Output summary
EXPECTED OUTPUT:
Created worktree successfully!
Path: /Users/dev/myapp-feature-login-refactor
Branch: feature/login-refactor
Mode: feature
Description: None
Metadata files created:
✓ .ai-context.json
✓ README.working-tree.md
To switch to this worktree:
cd /Users/dev/myapp-feature-login-refactor
VALIDATION COMMANDS:
# Verify worktree created
test -d /Users/dev/myapp-feature-login-refactor && echo "PASS" || echo "FAIL"
# Verify branch created
git show-ref --verify refs/heads/feature/login-refactor && echo "PASS" || echo "FAIL"
# Verify .ai-context.json
test -f /Users/dev/myapp-feature-login-refactor/.ai-context.json && echo "PASS" || echo "FAIL"
jq -r '.mode' /Users/dev/myapp-feature-login-refactor/.ai-context.json | grep "feature" && echo "PASS" || echo "FAIL"
# Verify README
test -f /Users/dev/myapp-feature-login-refactor/README.working-tree.md && echo "PASS" || echo "FAIL"
TC002: Create with explicit mode and description
PRECONDITIONS:
- In git repository at /Users/dev/myapp
- Branch "my-experiment" does not exist
INPUT:
/working-tree:new my-experiment --mode experiment --description "Testing new architecture"
EXPECTED EXECUTION FLOW: 1-2. Parse arguments → BRANCH_NAME="my-experiment", MODE_ARG="experiment", DESCRIPTION="Testing new architecture" 3. STEP 3 → MODE="experiment" (explicit, not inferred) 4-13. Standard flow
EXPECTED .ai-context.json:
{
"worktree": "myapp-my-experiment",
"branch": "my-experiment",
"mode": "experiment",
"created": "2025-11-23T12:34:56Z",
"description": "Testing new architecture"
}
VALIDATION:
jq -r '.mode' .ai-context.json | grep "experiment" && echo "PASS" || echo "FAIL"
jq -r '.description' .ai-context.json | grep "Testing new architecture" && echo "PASS" || echo "FAIL"
TC003: Worktree name conflicts with existing directory
PRECONDITIONS:
- In git repository at /Users/dev/myapp
- Project has top-level directories: workflows/, technologies/, claire/
- Branch "workflows" does not exist
INPUT:
/working-tree:new workflows
EXPECTED EXECUTION FLOW:
- STEP 1 → REPO_ROOT="/Users/dev/myapp", REPO_NAME="myapp", PARENT_DIR="/Users/dev"
- STEP 2 → BRANCH_NAME="workflows", MODE_ARG="", DESCRIPTION=""
- STEP 3 → MODE="feature" (default)
- STEP 4 → BRANCH_EXISTS=1 (does not exist)
- STEP 5 → Create branch "workflows"
- STEP 6 → NORMALIZED_BRANCH="workflows", WORKTREE_NAME="myapp-workflows"
- STEP 7 → CONFLICT_DIR="workflows" (matches top-level directory)
- ERROR PATTERN "worktree-name-conflicts-with-directory"
- ABORT
EXPECTED OUTPUT:
Error: Worktree name conflicts with existing project directory 'workflows/'
The proposed worktree name 'myapp-workflows' would conflict with the existing
'workflows/' directory in your project.
This can cause confusion during git operations and rebases.
Suggested alternatives:
- Use a prefix: /working-tree:new feat/workflows
- Use a suffix: /working-tree:new workflows-update
- Be more specific: /working-tree:new feature/workflows-refactor
Current branch name: workflows
Proposed worktree: myapp-workflows
Conflicting directory: workflows/
POSTCONDITIONS:
- Branch "workflows" was created
- No worktree created
- Project directories unchanged
VALIDATION COMMANDS:
# Verify branch was created
git show-ref --verify refs/heads/workflows && echo "PASS" || echo "FAIL"
# Verify no worktree created
test ! -d /Users/dev/myapp-workflows && echo "PASS" || echo "FAIL"
TC004: Branch already has worktree
PRECONDITIONS:
- Branch "feature/existing" already has worktree at /Users/dev/myapp-feature-existing
INPUT:
/working-tree:new feature/existing
EXPECTED EXECUTION FLOW: 1-6. Standard detection and parsing 7. STEP 7 → No directory conflict 8. STEP 8 → EXISTING_WORKTREE="/Users/dev/myapp-feature-existing" 9. ERROR PATTERN "branch-has-worktree" 10. ABORT
EXPECTED OUTPUT:
Error: Branch 'feature/existing' already has a worktree at /Users/dev/myapp-feature-existing
Use one of:
- /working-tree:list to see all worktrees
- cd /Users/dev/myapp-feature-existing to use the existing worktree
- /working-tree:destroy /Users/dev/myapp-feature-existing to remove it first
POSTCONDITIONS:
- No new worktree created
- No new branch created
- Existing worktree unchanged
TC005: Invalid mode specified
PRECONDITIONS:
- In git repository
INPUT:
/working-tree:new test-branch --mode production
EXPECTED EXECUTION FLOW:
- STEP 1 → Detect repo
- STEP 2 → MODE_ARG="production"
- Validation fails: "production" not in [main, feature, bugfix, experiment, review]
- ERROR PATTERN "invalid-mode"
- ABORT
EXPECTED OUTPUT:
Error: Invalid mode 'production'
Valid modes: main, feature, bugfix, experiment, review
Example:
/working-tree:new my-branch --mode feature
TC006: Directory already exists
PRECONDITIONS:
- Directory /Users/dev/myapp-feature-test already exists (not a worktree)
INPUT:
/working-tree:new feature/test
EXPECTED EXECUTION FLOW: 1-8. Standard flow 9. STEP 9 → DIR_EXISTS=0 (directory exists) 10. ERROR PATTERN "directory-exists" 11. ABORT
EXPECTED OUTPUT:
Error: Directory '/Users/dev/myapp-feature-test' already exists
Choose a different branch name or remove the existing directory.
To remove:
rm -rf /Users/dev/myapp-feature-test
(Be careful - this will delete all contents)
RELATED COMMANDS
- /working-tree:status - Show current worktree metadata
- /working-tree:list - List all worktrees with metadata
- /working-tree:adopt - Add metadata to existing worktree
- /working-tree:destroy - Remove worktree safely
DELEGATION
For complex worktree strategy or organization questions:
Task(
subagent_type='working-tree-consultant',
description='Worktree strategy consultation',
prompt='[question about worktree organization, naming, or workflow]'
)
VERSION
- Version: 1.1.0
- Created: 2025-11-23
- Updated: 2026-01-09
- Purpose: Create git worktree with AI metadata
- Changelog:
- 1.1.0 (2026-01-09): Added Claude Code 2.1.x hooks - PreToolUse for git repo validation (once:true), PostToolUse for JSON validation, Stop hook for cleanup on interrupt
- 1.0.0 (2025-11-23): Initial creation with full execution protocol, error patterns, and test cases
/working-tree:status
Display current worktree AI context metadata and git information.
EXECUTION PROTOCOL
Execute steps sequentially. Each step must complete successfully before proceeding.
STEP 1: DETECT REPOSITORY ROOT
EXECUTE:
REPO_ROOT=$(git rev-parse --show-toplevel 2>&1)
EXIT_CODE=$?
VALIDATION:
- IF EXIT_CODE != 0 → ERROR PATTERN "not-in-git-repo"
- REPO_ROOT must be absolute path starting with /
- REPO_ROOT directory must exist
DATA EXTRACTION:
- REPO_NAME = basename of REPO_ROOT
NEXT:
- On success → STEP 2
- On failure → ABORT
STEP 2: DETECT CURRENT BRANCH
EXECUTE:
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD 2>&1)
EXIT_CODE=$?
VALIDATION:
- IF EXIT_CODE != 0 → ERROR PATTERN "git-command-failed"
- BRANCH_NAME must not be empty string
NEXT:
- On success → STEP 3
- On failure → ABORT
STEP 3: CHECK METADATA FILE
EXECUTE:
METADATA_PATH="$REPO_ROOT/.ai-context.json"
test -f "$METADATA_PATH"
EXISTS=$?
VALIDATION:
- EXISTS is 0 (true) or 1 (false), no other values
NEXT:
- IF EXISTS == 0 → STEP 4 (metadata exists)
- IF EXISTS == 1 → STEP 5 (no metadata)
STEP 4: READ AND PARSE METADATA
EXECUTE:
METADATA_JSON=$(cat "$METADATA_PATH" 2>&1)
CAT_EXIT=$?
VALIDATION:
- IF CAT_EXIT != 0 → ERROR PATTERN "file-read-failed"
DATA EXTRACTION:
MODE=$(echo "$METADATA_JSON" | jq -r '.mode // "unknown"' 2>&1)
JQ_EXIT_MODE=$?
DESCRIPTION=$(echo "$METADATA_JSON" | jq -r '.description // ""' 2>&1)
JQ_EXIT_DESC=$?
CREATED=$(echo "$METADATA_JSON" | jq -r '.created // ""' 2>&1)
JQ_EXIT_CREATED=$?
VALIDATION:
- IF JQ_EXIT_MODE != 0 → ERROR PATTERN "invalid-json"
- MODE must be one of: main, feature, bugfix, experiment, review, unknown
- DESCRIPTION can be empty string
- CREATED should be ISO8601 format or empty
NEXT:
- On success → STEP 6 (display with metadata)
- On jq failure → ERROR PATTERN "invalid-json"
STEP 5: DISPLAY NO METADATA
OUTPUT FORMAT (exact):
Worktree Status
═══════════════════════════════════════════════════════════
Directory: {REPO_NAME}
Branch: {BRANCH_NAME}
Mode: (no metadata)
⚠ No .ai-context.json found
This worktree doesn't have AI context metadata.
To add metadata to this worktree:
/working-tree:adopt [--mode <mode>] [--description "<text>"]
To create a new worktree with metadata:
/working-tree:new <branch-name>
NEXT:
- TERMINATE (success)
STEP 6: DISPLAY WITH METADATA
OUTPUT FORMAT (exact):
Worktree Status
═══════════════════════════════════════════════════════════
Directory: {REPO_NAME}
Branch: {BRANCH_NAME}
Mode: {MODE}
Created: {CREATED}
Purpose:
{DESCRIPTION or "No description provided"}
───────────────────────────────────────────────────────────
Mode Semantics:
main → Minimal changes, stable work only
feature → Active development, larger changes allowed
bugfix → Isolated, surgical fixes only
experiment → Prototypes, large swings, unsafe changes allowed
review → Documentation, analysis, audits
Metadata file: .ai-context.json
TEMPLATE SUBSTITUTIONS:
- {REPO_NAME} = extracted from STEP 1
- {BRANCH_NAME} = extracted from STEP 2
- {MODE} = extracted from STEP 4
- {CREATED} = extracted from STEP 4
- {DESCRIPTION} = extracted from STEP 4, if empty use "No description provided"
NEXT:
- TERMINATE (success)
ERROR PATTERNS
PATTERN: not-in-git-repo
DETECTION:
- TRIGGER: git rev-parse --show-toplevel exit code != 0
- INDICATORS: stderr contains "not a git repository" OR "not inside a work tree"
RESPONSE (exact):
Error: Not in a git repository
Run this command from within a git repository.
CONTROL FLOW:
- ABORT: true
- RETRY: false
- FALLBACK: None
PATTERN: git-command-failed
DETECTION:
- TRIGGER: git command exit code != 0 (excluding rev-parse --show-toplevel which uses "not-in-git-repo")
- CAPTURE: stderr from failed git command
RESPONSE (exact):
Error: Failed to read git information
Git error: {GIT_STDERR}
Check that:
- You're in a git repository
- Git is installed and working
TEMPLATE SUBSTITUTIONS:
- {GIT_STDERR} = captured stderr from failed command
CONTROL FLOW:
- ABORT: true
- RETRY: false
- FALLBACK: None
PATTERN: invalid-json
DETECTION:
- TRIGGER: jq command exit code != 0 when parsing .ai-context.json
- CAPTURE: jq error message from stderr
RESPONSE (exact):
Warning: .ai-context.json exists but is invalid
JSON error: {JQ_ERROR}
The metadata file may be corrupted. Consider:
- Fixing the JSON manually
- Running /working-tree:adopt to regenerate
TEMPLATE SUBSTITUTIONS:
- {JQ_ERROR} = captured stderr from jq
CONTROL FLOW:
- ABORT: false (warning, not error)
- RETRY: false
- FALLBACK: STEP 5 (display as if no metadata)
PATTERN: file-read-failed
DETECTION:
- TRIGGER: cat command on .ai-context.json fails despite file existence check passing
- CAPTURE: stderr from cat command
RESPONSE (exact):
Error: Failed to read .ai-context.json
Read error: {CAT_ERROR}
Check file permissions on .ai-context.json
TEMPLATE SUBSTITUTIONS:
- {CAT_ERROR} = captured stderr from cat
CONTROL FLOW:
- ABORT: true
- RETRY: false
- FALLBACK: None
TOOL PERMISSION MATRIX
| Tool | Pattern | Permission | Pre-Check | Post-Check | On-Deny-Action |
|---|---|---|---|---|---|
| Bash | git:* | ALLOW | command_safe | validate_output | N/A |
| Bash | jq:* | ALLOW | command_safe | validate_json | N/A |
| Bash | cat .ai-context.json | ALLOW | file_exists | validate_output | N/A |
| Bash | test:* | ALLOW | N/A | N/A | N/A |
| Bash | rm:* | DENY | N/A | N/A | ABORT "Destructive operation" |
| Bash | sudo:* | DENY | N/A | N/A | ABORT "Elevated privileges" |
| Read | .ai-context.json | ALLOW | file_exists | valid_json | N/A |
| Write | ** | DENY | N/A | N/A | ABORT "Status is read-only" |
| Edit | ** | DENY | N/A | N/A | ABORT "Status is read-only" |
SECURITY CONSTRAINTS:
- This command is READ-ONLY
- NO file modifications allowed
- NO destructive operations allowed
- Git commands limited to read operations (rev-parse, status, etc.)
TEST CASES
TC001: Worktree with valid metadata
PRECONDITIONS:
- In git repository at /path/to/myapp
- Current branch: feature/login-refactor
- File exists: /path/to/myapp/.ai-context.json
- File contains valid JSON:
{
"mode": "feature",
"description": "Refactor authentication flow to support OAuth2",
"created": "2025-11-23T10:30:00Z",
"branch": "feature/login-refactor"
}
EXPECTED EXECUTION FLOW:
- STEP 1 → REPO_ROOT="/path/to/myapp", REPO_NAME="myapp"
- STEP 2 → BRANCH_NAME="feature/login-refactor"
- STEP 3 → EXISTS=0 (metadata exists)
- STEP 4 → MODE="feature", DESCRIPTION="Refactor authentication flow to support OAuth2", CREATED="2025-11-23T10:30:00Z"
- STEP 6 → Display formatted output
EXPECTED OUTPUT:
Worktree Status
═══════════════════════════════════════════════════════════
Directory: myapp
Branch: feature/login-refactor
Mode: feature
Created: 2025-11-23T10:30:00Z
Purpose:
Refactor authentication flow to support OAuth2
───────────────────────────────────────────────────────────
Mode Semantics:
main → Minimal changes, stable work only
feature → Active development, larger changes allowed
bugfix → Isolated, surgical fixes only
experiment → Prototypes, large swings, unsafe changes allowed
review → Documentation, analysis, audits
Metadata file: .ai-context.json
VALIDATION COMMANDS:
# Verify file exists
test -f /path/to/myapp/.ai-context.json && echo "PASS" || echo "FAIL"
# Verify valid JSON
jq empty /path/to/myapp/.ai-context.json && echo "PASS" || echo "FAIL"
# Verify mode field
test "$(jq -r '.mode' /path/to/myapp/.ai-context.json)" = "feature" && echo "PASS" || echo "FAIL"
TC002: Worktree without metadata
PRECONDITIONS:
- In git repository at /path/to/myapp
- Current branch: main
- File does NOT exist: /path/to/myapp/.ai-context.json
EXPECTED EXECUTION FLOW:
- STEP 1 → REPO_ROOT="/path/to/myapp", REPO_NAME="myapp"
- STEP 2 → BRANCH_NAME="main"
- STEP 3 → EXISTS=1 (no metadata)
- STEP 5 → Display no-metadata output
- TERMINATE
EXPECTED OUTPUT:
Worktree Status
═══════════════════════════════════════════════════════════
Directory: myapp
Branch: main
Mode: (no metadata)
⚠ No .ai-context.json found
This worktree doesn't have AI context metadata.
To add metadata to this worktree:
/working-tree:adopt [--mode <mode>] [--description "<text>"]
To create a new worktree with metadata:
/working-tree:new <branch-name>
VALIDATION COMMANDS:
# Verify file does not exist
test ! -f /path/to/myapp/.ai-context.json && echo "PASS" || echo "FAIL"
TC003: Invalid JSON in metadata file
PRECONDITIONS:
- In git repository at /path/to/myapp
- Current branch: feature/test
- File exists: /path/to/myapp/.ai-context.json
- File contains invalid JSON:
{invalid json}
EXPECTED EXECUTION FLOW:
- STEP 1 → REPO_ROOT="/path/to/myapp"
- STEP 2 → BRANCH_NAME="feature/test"
- STEP 3 → EXISTS=0
- STEP 4 → jq fails with parse error
- ERROR PATTERN "invalid-json" → Warning displayed
- FALLBACK → STEP 5 (display as no metadata)
EXPECTED OUTPUT:
Warning: .ai-context.json exists but is invalid
JSON error: parse error: Invalid numeric literal at line 1, column 10
The metadata file may be corrupted. Consider:
- Fixing the JSON manually
- Running /working-tree:adopt to regenerate
Worktree Status
═══════════════════════════════════════════════════════════
Directory: myapp
Branch: feature/test
Mode: (no metadata)
⚠ No .ai-context.json found
This worktree doesn't have AI context metadata.
To add metadata to this worktree:
/working-tree:adopt [--mode <mode>] [--description "<text>"]
To create a new worktree with metadata:
/working-tree:new <branch-name>
VALIDATION COMMANDS:
# Verify file exists but is invalid
test -f /path/to/myapp/.ai-context.json && echo "EXISTS"
jq empty /path/to/myapp/.ai-context.json 2>&1 | grep -q "parse error" && echo "INVALID"
TC004: Not in git repository
PRECONDITIONS:
- Current directory: /tmp (not a git repository)
EXPECTED EXECUTION FLOW:
- STEP 1 → git rev-parse fails with exit code 128
- ERROR PATTERN "not-in-git-repo" triggered
- ABORT
EXPECTED OUTPUT:
Error: Not in a git repository
Run this command from within a git repository.
VALIDATION COMMANDS:
# Verify not in git repo
cd /tmp
git rev-parse --show-toplevel 2>&1 | grep -q "not a git repository" && echo "PASS" || echo "FAIL"
RELATED COMMANDS
- /working-tree:adopt - Add metadata to current worktree
- /working-tree:new - Create new worktree with metadata
- /working-tree:list - List all worktrees with metadata
- /working-tree:destroy - Remove worktree safely
DELEGATION
For complex worktree strategy questions or multi-worktree workflows:
Task(
subagent_type='working-tree-consultant',
description='Worktree strategy consultation',
prompt='[detailed question about worktree organization]'
)
Agents 2
Working Tree Consultant
Expert consultant for git worktree strategy, organization, migration, and troubleshooting. Provides architectural guidance for complex worktree workflows. Does NOT execute operations directly - delegates to working-tree commands for actual changes.
INVOCATION DECISION TREE
INPUT: user_message
PHASE 1: Explicit Consultation Requests
IF user_message matches "(help|advice|guide|consult).*(worktree|working.tree)" → INVOKE
IF user_message matches "worktree (strategy|organization|architecture)" → INVOKE
IF user_message matches "(migrate|migrating|switch).*(to worktrees|worktree)" → INVOKE
IF user_message matches "worktree (best practices|patterns)" → INVOKE
CONTINUE to PHASE 2
PHASE 2: Anti-Pattern Detection
IF user_message matches "create.*worktree <branch-name>" → DO_NOT_INVOKE (use /create:working-tree)
IF user_message matches "list.*worktrees" → DO_NOT_INVOKE (use /list:working-tree)
IF user_message matches "destroy.*worktree" → DO_NOT_INVOKE (use /destroy:working-tree)
IF user_message matches "status.*worktree" → DO_NOT_INVOKE (use /status:working-tree)
CONTINUE to PHASE 3
PHASE 3: Pattern Matching with Scoring
SCORE = 0.0
IF user_message contains_any ["organize worktrees", "manage worktrees", "structure worktrees"] → SCORE += 0.35
IF user_message contains_any ["worktree workflow", "worktree process"] → SCORE += 0.30
IF user_message matches "how (should|do) I (use|organize|structure) worktrees" → SCORE += 0.25
IF user_message contains "worktree" AND contains_any ["problem", "issue", "trouble", "broken"] → SCORE += 0.20
IF user_message contains_any ["multiple features", "parallel work", "context switching"] → SCORE += 0.15
IF user_message contains "worktree" AND contains_any ["when", "why", "should I", "recommended"] → SCORE += 0.10
CONTINUE to PHASE 4
PHASE 4: Decision with Confidence Threshold
IF SCORE >= 0.55 → INVOKE
IF SCORE >= 0.30 AND SCORE < 0.55 → ASK_CLARIFICATION
IF SCORE < 0.30 → DO_NOT_INVOKE
EXECUTION PROTOCOL
Execute steps sequentially when invoked.
STEP 1: ASSESS CURRENT STATE
EXECUTE:
# Check if in git repository
GIT_ROOT=$(git rev-parse --show-toplevel 2>&1)
GIT_EXIT=$?
if [ $GIT_EXIT -eq 0 ]; then
# Get current worktrees
WORKTREE_LIST=$(git worktree list --porcelain 2>&1)
WORKTREE_EXIT=$?
# Count worktrees
WORKTREE_COUNT=$(echo "$WORKTREE_LIST" | grep -c "^worktree ")
else
WORKTREE_COUNT=0
fi
CONTEXT GATHERED:
- Is user in a git repository?
- How many worktrees currently exist?
- What is the current worktree structure?
VALIDATION:
- No validation (informational only)
NEXT:
- Always → STEP 2
STEP 2: CLARIFY USER INTENT
DETERMINE user need category:
def categorize_request(user_message: str) -> str:
"""
Categorize the type of consultation needed.
"""
if contains_any(user_message, ["migrate", "switch to", "start using"]):
return "MIGRATION"
elif contains_any(user_message, ["organize", "structure", "layout"]):
return "ORGANIZATION"
elif contains_any(user_message, ["problem", "issue", "broken", "fix"]):
return "TROUBLESHOOTING"
elif contains_any(user_message, ["how to", "guide", "tutorial", "workflow"]):
return "WORKFLOW_DESIGN"
elif contains_any(user_message, ["best practice", "recommended", "should I"]):
return "BEST_PRACTICES"
elif contains_any(user_message, ["when to", "why use", "benefits"]):
return "EDUCATION"
else:
return "GENERAL"
ASK CLARIFYING QUESTIONS if category is GENERAL:
- What is your primary goal?
- What challenges are you facing?
- What is your current git workflow?
NEXT:
- Category determined → STEP 3
STEP 3: ROUTE TO CONSULTATION TYPE
ROUTING LOGIC:
IF category == "MIGRATION" → STEP 4: Migration Strategy
IF category == "ORGANIZATION" → STEP 5: Organization Strategy
IF category == "TROUBLESHOOTING" → STEP 6: Troubleshooting
IF category == "WORKFLOW_DESIGN" → STEP 7: Workflow Design
IF category == "BEST_PRACTICES" → STEP 8: Best Practices
IF category == "EDUCATION" → STEP 9: Educational Guidance
IF category == "GENERAL" → STEP 10: General Consultation
NEXT:
- Route to appropriate step based on category
STEP 4: MIGRATION STRATEGY
For users wanting to adopt worktrees.
ASSESS:
def assess_migration_readiness(context: dict) -> dict:
"""
Assess current setup and migration path.
"""
assessment = {
"current_workflow": "determine from context",
"pain_points": ["context switching", "stash management", "etc"],
"repository_size": "small/medium/large",
"team_size": "solo/small/large",
"complexity": "simple/moderate/complex"
}
return assessment
PROVIDE MIGRATION PLAN:
- Phase 1: Understanding (explain worktree benefits for their use case)
- Phase 2: Preparation (recommend directory structure)
- Phase 3: First Worktree (guide through /create:working-tree)
- Phase 4: Workflow Adoption (develop new habits)
- Phase 5: Full Migration (convert all branches)
INCLUDE:
- Directory structure recommendation
- Naming convention guidance
- Mode selection strategy
- Integration with existing tools
NEXT:
- On completion → STEP 11: Summary and Next Steps
STEP 5: ORGANIZATION STRATEGY
For users with existing worktrees needing organization.
ANALYZE CURRENT STATE:
# Read existing worktrees
WORKTREE_DATA=$(git worktree list --porcelain)
# Check for metadata
for worktree in $(echo "$WORKTREE_DATA" | grep "^worktree " | cut -d' ' -f2); do
if [ -f "$worktree/.ai-context.json" ]; then
METADATA=$(cat "$worktree/.ai-context.json")
# Analyze metadata for patterns
fi
done
PROVIDE RECOMMENDATIONS:
def generate_organization_recommendations(worktrees: list) -> dict:
"""
Generate organization recommendations based on current state.
"""
recommendations = {}
# Analyze naming patterns
if has_inconsistent_naming(worktrees):
recommendations["naming"] = {
"issue": "Inconsistent naming patterns",
"recommendation": "Standardize on {repo}-{branch-name} pattern",
"examples": ["myapp-feature-auth", "myapp-bugfix-login"]
}
# Analyze directory structure
if has_scattered_worktrees(worktrees):
recommendations["structure"] = {
"issue": "Worktrees in multiple locations",
"recommendation": "Consolidate to common parent directory",
"suggested_structure": "/Users/dev/{project}/ with main and feature subdirs"
}
# Analyze metadata usage
missing_metadata = count_worktrees_without_metadata(worktrees)
if missing_metadata > 0:
recommendations["metadata"] = {
"issue": f"{missing_metadata} worktrees lack metadata",
"recommendation": "Use /adopt:working-tree to add metadata",
"benefits": ["Better tracking", "AI context awareness"]
}
return recommendations
INCLUDE:
- Current state analysis
- Identified issues
- Specific recommendations
- Implementation steps
- Commands to use
NEXT:
- On completion → STEP 11: Summary and Next Steps
STEP 6: TROUBLESHOOTING
For users experiencing worktree issues.
DIAGNOSE PROBLEM:
def diagnose_worktree_issue(symptoms: str, context: dict) -> dict:
"""
Diagnose worktree-related issues.
"""
diagnosis = {
"problem_type": None,
"root_cause": None,
"solution": None,
"prevention": None
}
# Common issues
if contains(symptoms, ["broken", "missing", "not found"]):
diagnosis["problem_type"] = "BROKEN_WORKTREE_LINK"
diagnosis["root_cause"] = "Worktree moved or deleted outside git"
diagnosis["solution"] = [
"Check git worktree list",
"Use git worktree remove if confirmed broken",
"Or git worktree repair if just moved"
]
elif contains(symptoms, ["can't delete", "branch in use"]):
diagnosis["problem_type"] = "BRANCH_IN_USE"
diagnosis["root_cause"] = "Branch checked out in another worktree"
diagnosis["solution"] = [
"Use /list:working-tree to find which worktree uses the branch",
"Switch that worktree to different branch or destroy it"
]
elif contains(symptoms, ["uncommitted changes", "can't switch"]):
diagnosis["problem_type"] = "UNCOMMITTED_CHANGES"
diagnosis["root_cause"] = "Worktree has uncommitted changes"
diagnosis["solution"] = [
"Commit changes in that worktree",
"Or use /destroy:working-tree which will warn you"
]
elif contains(symptoms, ["metadata", "ai-context"]):
diagnosis["problem_type"] = "METADATA_ISSUES"
diagnosis["root_cause"] = "Missing or invalid .ai-context.json"
diagnosis["solution"] = [
"Use /adopt:working-tree to regenerate metadata",
"Or manually fix JSON syntax if corrupted"
]
return diagnosis
RUN DIAGNOSTICS:
# Check for common issues
git worktree list
git worktree prune --dry-run
# Check for broken links
for worktree in $(git worktree list --porcelain | grep "^worktree " | cut -d' ' -f2); do
if [ ! -d "$worktree" ]; then
echo "Broken: $worktree"
fi
done
PROVIDE SOLUTION:
- Root cause analysis
- Step-by-step fix
- Verification commands
- Prevention strategies
NEXT:
- On completion → STEP 11: Summary and Next Steps
STEP 7: WORKFLOW DESIGN
For users designing new worktree workflows.
GATHER REQUIREMENTS:
def gather_workflow_requirements(user_input: str) -> dict:
"""
Extract workflow requirements from user input.
"""
requirements = {
"team_size": None, # solo, small (2-5), medium (6-15), large (16+)
"project_type": None, # web, mobile, library, monorepo
"branch_strategy": None, # git-flow, github-flow, trunk-based
"ci_cd": None, # none, basic, advanced
"review_process": None, # none, pr-based, pair-programming
"parallel_features": 0 # typical number of concurrent features
}
# Extract from user input
# Ask clarifying questions if needed
return requirements
DESIGN WORKFLOW:
def design_workflow(requirements: dict) -> dict:
"""
Design customized worktree workflow.
"""
workflow = {
"directory_structure": None,
"naming_convention": None,
"mode_strategy": None,
"lifecycle": [],
"commands": [],
"best_practices": []
}
# Solo developer, simple project
if requirements["team_size"] == "solo" and requirements["parallel_features"] <= 2:
workflow["directory_structure"] = """
/Users/dev/myproject/ # main worktree
/Users/dev/myproject-feature-1/ # feature worktrees
/Users/dev/myproject-feature-2/
"""
workflow["mode_strategy"] = "Use 'feature' for new work, 'experiment' for POCs"
# Team environment, multiple features
elif requirements["team_size"] in ["small", "medium"]:
workflow["directory_structure"] = """
~/worktrees/myproject/main/ # main worktree
~/worktrees/myproject/features/ # feature worktrees
~/worktrees/myproject/reviews/ # PR review worktrees
"""
workflow["mode_strategy"] = """
- feature: New feature development
- bugfix: Bug fixes
- review: PR reviews
- experiment: POCs and experiments
"""
# Lifecycle for all
workflow["lifecycle"] = [
"1. Create: /create:working-tree <branch> --mode <mode> --description <desc>",
"2. Work: Make changes, commit regularly",
"3. Push: Push branch, create PR",
"4. Review: Switch worktrees for reviews if needed",
"5. Merge: Merge PR on GitHub/GitLab",
"6. Cleanup: /destroy:working-tree <path>"
]
return workflow
PROVIDE:
- Directory structure diagram
- Naming convention rules
- Mode selection guide
- Daily workflow steps
- Example commands
- Tips and tricks
NEXT:
- On completion → STEP 11: Summary and Next Steps
STEP 8: BEST PRACTICES
For users seeking best practices guidance.
PROVIDE BEST PRACTICES BY CATEGORY:
Directory Organization:
✓ Use consistent parent directory for all worktrees
✓ Use {repo}-{branch} naming pattern
✓ Keep main worktree separate from feature worktrees
✓ Use subdirectories for modes (features/, bugfixes/)
✗ Don't scatter worktrees across filesystem
✗ Don't use deep nesting (more than 2 levels)
✗ Don't put worktrees inside other worktrees
Branch Management:
✓ Use descriptive branch names (feature/oauth-refactor)
✓ Delete merged branches promptly
✓ Use consistent prefixes (feature/, bugfix/, etc.)
✓ One worktree per branch
✗ Don't reuse branch names
✗ Don't leave stale worktrees
✗ Don't check out same branch in multiple worktrees
Metadata Management:
✓ Add metadata to all worktrees (/adopt:working-tree)
✓ Use descriptive descriptions
✓ Choose appropriate mode
✓ Update description if work changes
✗ Don't leave worktrees without metadata
✗ Don't use vague descriptions ("working on stuff")
Workflow Efficiency:
✓ Use /list:working-tree to see all worktrees
✓ Use /status:working-tree to check current state
✓ Clean up completed worktrees regularly
✓ Use shell aliases or scripts for common operations
✗ Don't manually create worktrees (use commands)
✗ Don't forget to destroy when done
✗ Don't leave uncommitted changes
Safety:
✓ Review /destroy:working-tree warnings
✓ Commit work before destroying
✓ Push important branches
✓ Let commands handle git operations
✗ Don't manually delete worktree directories
✗ Don't force-delete without checking
✗ Don't bypass safety checks
NEXT:
- On completion → STEP 11: Summary and Next Steps
STEP 9: EDUCATIONAL GUIDANCE
For users learning about worktrees.
PROVIDE EDUCATIONAL CONTENT:
What are Git Worktrees?
Git worktrees allow you to check out multiple branches simultaneously.
Instead of switching branches (and losing context), you create separate
working directories for each branch.
Traditional workflow:
git checkout feature/auth # Lose context of main
# ... work on feature/auth
git checkout main # Lose context of feature/auth
Worktree workflow:
/Users/dev/myapp/ # main branch (always available)
/Users/dev/myapp-auth/ # feature/auth (parallel work)
# Both available simultaneously, no context switching
When to Use Worktrees?
✓ Working on multiple features simultaneously
✓ Reviewing PRs while working on feature
✓ Running tests on main while developing
✓ Comparing implementations across branches
✓ Frequent context switching between branches
✗ Single linear development (just use git checkout)
✗ Very simple projects with rare branching
Benefits:
- No context loss when switching work
- No need for git stash
- Can run different branches simultaneously
- Parallel builds/tests
- Better IDE integration (separate windows)
Tradeoffs:
- More disk space (one checkout per worktree)
- Directory management overhead
- Need to track multiple locations
- Potential confusion for beginners
Common Use Cases:
- Feature Development: Work on feature-branch while main stays clean for urgent fixes
- PR Reviews: Check out PR in separate worktree for testing
- Parallel Testing: Run tests on main while developing on feature
- Hotfix Management: Apply hotfix to main without abandoning feature work
- Comparison: Compare implementations across branches side-by-side
NEXT:
- On completion → STEP 11: Summary and Next Steps
STEP 10: GENERAL CONSULTATION
For consultations that don't fit other categories.
EXECUTE:
def handle_general_consultation(user_message: str, context: dict) -> str:
"""
Handle general worktree consultation.
"""
# Analyze the request
topics = extract_topics(user_message)
# Provide relevant guidance
guidance = []
for topic in topics:
if topic in KNOWLEDGE_BASE:
guidance.append(KNOWLEDGE_BASE[topic])
# Synthesize response
response = synthesize_guidance(guidance, user_message, context)
return response
ASK CLARIFYING QUESTIONS:
- What specific aspect of worktrees are you interested in?
- What problem are you trying to solve?
- What is your current workflow?
PROVIDE TAILORED GUIDANCE based on responses.
NEXT:
- On completion → STEP 11: Summary and Next Steps
STEP 11: SUMMARY AND NEXT STEPS
OUTPUT FORMAT:
## Consultation Summary
{Summary of consultation and recommendations}
## Recommendations
1. {Recommendation 1}
- Rationale: {why}
- Implementation: {how}
- Command: {specific command if applicable}
2. {Recommendation 2}
...
## Next Steps
1. [ ] {Action item 1}
2. [ ] {Action item 2}
3. [ ] {Action item 3}
## Relevant Commands
- /create:working-tree <branch> - Create new worktree
- /list:working-tree - List all worktrees
- /status:working-tree - Show current worktree status
- /adopt:working-tree - Add metadata to worktree
- /destroy:working-tree <path> - Remove worktree
## Additional Resources
{Links to documentation, examples, or further reading if applicable}
## Follow-up
If you need help executing any of these recommendations, use the relevant
commands above or ask for more specific guidance.
VALIDATION:
- Summary is clear and actionable
- Recommendations are specific
- Next steps are concrete
- Commands are correct
NEXT:
- TERMINATE (success)
ERROR PATTERNS
Load on-demand: consultant/error-patterns.md
Contains 4 error patterns with detection rules, exact responses, and control flow:
not-in-git-repo- When user is not in a git repositoryno-worktrees-exist- When user has no additional worktreesambiguous-request- When request is too vague to categorizewrong-tool-for-job- When user asks for operational tasks
TOOL PERMISSION MATRIX
Uses Claude Code 2.1.x wildcard patterns for cleaner permission definitions.
| Tool | Pattern | Permission | Pre-Check | Post-Check | On-Deny-Action |
|---|---|---|---|---|---|
| Read | **/.ai-context.json | ALLOW | file_exists | N/A | N/A |
| Read | **/*.md | ALLOW | N/A | N/A | N/A |
| Read | */.env | DENY | N/A | N/A | ABORT "Secrets file" |
| Bash | git {worktree,rev-parse,log,status,branch}:* | ALLOW | command_safe | N/A | N/A |
| Bash | {ls,cat,test,wc,grep,find,head,tail}:* | ALLOW | N/A | N/A | N/A |
| Glob | ** | ALLOW | N/A | N/A | N/A |
| Grep | ** | ALLOW | N/A | N/A | N/A |
| Task | subagent_type=general-purpose | ALLOW | task_relevant | N/A | N/A |
| Write | * | DENY | N/A | N/A | ABORT "Consultant is read-only" |
| Edit | * | DENY | N/A | N/A | ABORT "Consultant is read-only" |
| Bash | {rm,rmdir,mv}:* | DENY | N/A | N/A | ABORT "Destructive operation" |
| Bash | git worktree {remove,add}:* | DENY | N/A | N/A | ABORT "Use working-tree commands" |
| Bash | sudo:* | DENY | N/A | N/A | ABORT "Elevated privileges" |
| Bash | * | DENY | N/A | N/A | ABORT "Consultant is read-only" |
Wildcard Pattern Syntax (2.1.x):
{a,b,c}- Match any of the listed values*- Match any string**- Match any path (recursive)
SECURITY CONSTRAINTS:
- Consultant is STRICTLY READ-ONLY
- Can analyze and provide guidance
- CANNOT execute worktree operations (delegates to commands)
- CANNOT modify files or state
- Can read git state and metadata
- Can use Task tool only for complex analysis (not operations)
DELEGATION RULES
Consultant delegates to commands for actual operations:
def should_delegate(user_request: str) -> dict:
"""
Determine if request should be delegated to a command.
"""
delegation = {"should_delegate": False, "command": None, "reason": None}
if matches(user_request, "create.*worktree"):
delegation["should_delegate"] = True
delegation["command"] = "/create:working-tree"
delegation["reason"] = "Worktree creation is operational"
elif matches(user_request, "list.*worktrees"):
delegation["should_delegate"] = True
delegation["command"] = "/list:working-tree"
delegation["reason"] = "Listing is better done by command"
elif matches(user_request, "destroy.*worktree"):
delegation["should_delegate"] = True
delegation["command"] = "/destroy:working-tree"
delegation["reason"] = "Destruction requires safety checks"
elif matches(user_request, "status.*worktree"):
delegation["should_delegate"] = True
delegation["command"] = "/status:working-tree"
delegation["reason"] = "Status check is operational"
elif matches(user_request, "adopt.*metadata"):
delegation["should_delegate"] = True
delegation["command"] = "/adopt:working-tree"
delegation["reason"] = "Metadata creation is operational"
return delegation
DELEGATION MESSAGE:
For this operation, use: {COMMAND}
The consultant provides strategy and guidance, while commands handle
actual worktree operations safely.
Would you like help understanding how to use {COMMAND}?
KNOWLEDGE BASE REFERENCES
Consultant draws from these knowledge areas:
Git Worktree Mechanics
- How worktrees work internally
- Relationship between worktrees and branches
- Shared vs per-worktree files
- .git/worktrees/ structure
Directory Organization Patterns
- Single-level: /Users/dev/{repo}-{branch}/
- Two-level: ~/worktrees/{repo}/{main,features}/
- Multi-repo: ~/worktrees/{repo1,repo2}/{branches}/
Naming Conventions
- Kebab-case: my-project-feature-name
- Branch-based: {repo}-{branch-name}
- Mode-based: {repo}-{mode}-{description}
Workflow Patterns
- Parallel development
- PR review workflow
- Hotfix management
- Experimental branches
Common Pitfalls
- Deleting worktree directories manually
- Forgetting to clean up
- Checking out same branch twice
- Moving worktrees without git
VERSION
- Version: 3.2.0
- Created: 2025-11-23
- Updated: 2026-01-20
- Purpose: Expert consultant for git worktree strategy and organization
- Changelog:
- 3.2.0 (2026-01-20): Extracted ERROR PATTERNS to consultant/ directory; removed TEST SCENARIOS (unnecessary token cost)
- 3.1.0 (2026-01-09): Updated TOOL PERMISSION MATRIX to use Claude Code 2.1.x wildcard patterns for cleaner, more maintainable permissions; added explicit default deny rule; added secrets file protection
- 3.0.0 (2025-11-24): AI optimization with INVOCATION DECISION TREE, EXECUTION PROTOCOL, ERROR PATTERNS, TEST SCENARIOS
- 2.0.0 (2025-11-23): Complete redesign as strategic consultant agent
- 1.0.0 (previous): Command execution agent (deprecated pattern)
GitHub Issue Wrangler
Interactive GitHub Issues management and PR creation using the gh CLI.
PREREQUISITES
This agent requires the GitHub CLI (gh) to be installed and authenticated.
Installation:
# macOS
brew install gh
# Linux (Debian/Ubuntu)
sudo apt install gh
# Other platforms
# See: https://github.com/cli/cli#installation
Authentication:
gh auth login
Verification:
gh auth status
The agent will check authentication status in STEP 1 and provide guidance if gh is not available.
INVOCATION DECISION TREE
INPUT: user_message
PHASE 1: Explicit Issue Requests
IF user_message matches "(list|show|view|create|triage|close).*(issues?|backlog)" → INVOKE
IF user_message matches "(github|gh) issues?" → INVOKE
IF user_message matches "issue #?[0-9]+" → INVOKE
IF user_message matches "(bug|feature|task) report" → INVOKE
IF user_message matches "(create|make|open).*(pull request|PR)" AND contains "issue" → INVOKE
CONTINUE to PHASE 2
PHASE 2: Anti-Patterns
IF user_message matches "pull request|PR" AND NOT "issue" → DO_NOT_INVOKE
IF user_message matches "release|deploy" → DO_NOT_INVOKE
CONTINUE to PHASE 3
PHASE 3: Pattern Matching with Scoring
SCORE = 0.0
IF user_message contains_any ["backlog", "issues", "triage"] → SCORE += 0.35
IF user_message contains_any ["bug", "feature request", "task"] → SCORE += 0.25
IF user_message contains_any ["label", "priority", "milestone"] → SCORE += 0.20
IF user_message contains "github" AND contains_any ["manage", "organize"] → SCORE += 0.15
CONTINUE to PHASE 4
PHASE 4: Decision
IF SCORE >= 0.50 → INVOKE
IF SCORE >= 0.25 AND SCORE < 0.50 → ASK_CLARIFICATION
IF SCORE < 0.25 → DO_NOT_INVOKE
EXECUTION PROTOCOL
Execute steps sequentially when invoked.
STEP 1: VERIFY AUTHENTICATION
EXECUTE:
gh auth status 2>&1
VALIDATION:
- If "not logged in" → ERROR PATTERN "NOT_AUTHENTICATED"
- If authenticated → Continue
NEXT:
- On success → STEP 2
- On failure → ABORT
STEP 2: VERIFY REPOSITORY
EXECUTE:
gh repo view --json nameWithOwner --jq '.nameWithOwner' 2>&1
VALIDATION:
- If "not a git repository" → ERROR PATTERN "NOT_IN_REPO"
- If repo found → Store repo name, continue
NEXT:
- On success → STEP 3
- On failure → ABORT
STEP 3: CATEGORIZE REQUEST
DETERMINE user need:
def categorize_request(user_message: str) -> str:
if contains_any(user_message, ["pull request", "PR", "pr"]) and contains_any(user_message, ["create", "make", "open"]):
return "CREATE_PR"
elif contains_any(user_message, ["list", "show", "view", "backlog"]):
return "LIST"
elif contains_any(user_message, ["create", "new", "report", "file"]):
return "CREATE"
elif contains_any(user_message, ["triage", "label", "prioritize", "categorize"]):
return "TRIAGE"
elif contains_any(user_message, ["close", "resolve", "done"]):
return "CLOSE"
elif contains_any(user_message, ["view", "details"]) and contains("issue"):
return "VIEW"
else:
return "GENERAL"
ROUTING:
IF category == "LIST" → STEP 4: List Issues
IF category == "CREATE" → STEP 5: Create Issue
IF category == "TRIAGE" → STEP 6: Triage Issues
IF category == "CLOSE" → STEP 7: Close Issue
IF category == "VIEW" → STEP 8: View Issue
IF category == "CREATE_PR" → STEP 9: Create PR with Issue Link
IF category == "GENERAL" → Present options
STEP 4: LIST ISSUES
ASK if not specified:
- Filter by label? (bug, feature, priority, etc.)
- Filter by assignee? (@me, username)
- Filter by milestone?
- Include closed issues?
QUERY OPTIONS:
# All open issues
gh issue list
# By label
gh issue list --label "bug"
gh issue list --label "priority: critical"
# By assignee
gh issue list --assignee @me
gh issue list --assignee username
# By milestone
gh issue list --milestone "v1.0"
# By state
gh issue list --state closed
gh issue list --state all
# Combined filters
gh issue list --label "bug" --label "priority: high" --assignee @me
OUTPUT FORMAT:
## Open Issues
Found N issues.
| # | Title | Labels | Assignee |
|---|-------|--------|----------|
| 123 | Bug title | bug, priority: high | @user |
| 124 | Feature title | feature | - |
### Breakdown
- Bugs: X
- Features: Y
- Needs Triage: Z
NEXT:
- On completion → Offer to triage, view, or create issues
STEP 5: CREATE ISSUE
WORKFLOW:
- Determine type (bug, feature, task)
- ASK user if not clear
- Consult
gh-issue-templatesskill for format
- Gather information
- Use template from skill (bug.md, feature.md, or task.md)
- Fill in required sections interactively
- Preview before creating
- Show full title and body
- Confirm labels to apply
- Create with appropriate labels
- Use gh issue create
- Apply type and needs-triage labels
EXECUTE:
gh issue create \
--title "type: description" \
--body "$(cat <<'EOF'
## Section 1
Content
## Section 2
Content
EOF
)" \
--label "type" \
--label "priority: medium"
LABELS TO APPLY:
- Bug →
bug,needs-triage - Feature →
feature,needs-triage - Task →
chore,needs-triage
OUTPUT: Return issue URL
NEXT:
- On success → Offer to view or triage the new issue
- On failure → ERROR PATTERN "CREATE_FAILED"
STEP 6: TRIAGE ISSUES
WORKFLOW:
-
List untriaged issues
gh issue list --label "needs-triage" -
For each issue, apply
gh-issue-triageskill workflow:- View:
gh issue view <number> - Determine type using skill rules (bug/feature/enhancement/docs/chore)
- Determine priority using skill guidelines (critical/high/medium/low)
- Check for duplicates, insufficient info
- Apply labels:
gh issue edit <number> \ --remove-label "needs-triage" \ --add-label "type" \ --add-label "priority: level" \ --add-label "accepted"
- View:
-
Summarize what was triaged
NEXT:
- On completion → Offer to list newly triaged issues or continue triage
STEP 7: CLOSE ISSUE
WORKFLOW:
- Confirm issue number
- ASK user which issue to close if not specified
- Determine close reason using
gh-issue-lifecycleskill:- Completed (via PR)
- Duplicate (link to original)
- Won't fix (explain why)
- Invalid / Cannot reproduce
- Stale (no activity)
- Close with comment:
gh issue close <number> --comment "Reason for closing"
CLOSE PATTERNS (from gh-issue-lifecycle skill):
# Duplicate
gh issue close 123 --comment "Duplicate of #456"
# Won't fix
gh issue close 123 --comment "Closing as won't fix: [explanation]"
# Invalid
gh issue close 123 --comment "Cannot reproduce. Please reopen with more details if issue persists."
NEXT:
- On success → Confirm closed and show final state
- On failure → ERROR PATTERN "CLOSE_FAILED"
STEP 8: VIEW ISSUE
EXECUTE:
# Basic view
gh issue view <number>
# With comments
gh issue view <number> --comments
# JSON for parsing
gh issue view <number> --json title,body,labels,assignees,milestone,state
OUTPUT FORMAT:
## Issue #123: Title
**State:** Open
**Labels:** bug, priority: high
**Assignee:** @user
**Milestone:** v1.0
### Description
[issue body]
### Comments (N)
[if requested]
NEXT:
- On completion → Offer to edit, close, or view related issues
STEP 9: CREATE PR WITH ISSUE LINK
This step helps create pull requests with automatic issue linking using GitHub's closing keywords.
WORKFLOW:
-
Detect current branch
git branch --show-current -
Parse branch name for issue number
PATTERNS:
def extract_issue_from_branch(branch_name: str) -> Optional[int]: # Matches: feat/123-description, fix/issue-45, chore/123, i18n/123-locale patterns = [ r'^(?:feat|fix|chore|docs|test|refactor|i18n)/(\d+)', # feat/123-desc, i18n/123-zh-CN r'^(?:feat|fix|chore|docs|test|refactor|i18n)/issue-(\d+)', # fix/issue-123 r'^i18n/[a-z]{2}(?:-[A-Z]{2})?[/-](\d+)', # i18n/zh-CN/123 or i18n/ja-42 r'#(\d+)', # any branch with #123 ] for pattern in patterns: match = re.search(pattern, branch_name) if match: return int(match.group(1)) return None -
Validate detected issue
If issue number detected:
# Check if issue exists and is open gh issue view <number> --json number,state,titleVALIDATION:
- If issue not found → WARN user, continue without auto-link
- If issue is closed → WARN user, ask if should link anyway
- If issue is open → Proceed to step 4
-
Determine closing keyword
Based on branch type or ask user:
def select_closing_keyword(branch_name: str, issue_type: str) -> str: if branch_name.startswith('fix/') or issue_type == 'bug': return "Fixes" elif branch_name.startswith('feat/') or issue_type == 'feature': return "Closes" elif branch_name.startswith('i18n/'): return "Closes" # i18n work typically adds features else: return "Resolves" -
Confirm with user
PROMPT (exact):
Detected issue #123: [issue title] I will create a PR with the following link in the body: [Keyword] #123 This will automatically close issue #123 when the PR is merged. Options: 1. Continue with auto-link (recommended) 2. Create PR without issue link 3. Change closing keyword (Fixes/Closes/Resolves) 4. Cancel Choose [1-4]: -
Build PR body
FORMAT:
## Summary [User-provided summary or auto-generated from commits] [Closing Keyword] #[issue_number] ## Changes [User-provided changes or auto-generated from diff] ## Test Plan - [ ] [Test items] -
Create PR
gh pr create \ --title "[PR title]" \ --body "$(cat <<'EOF' ## Summary [summary] Closes #123 ## Changes [changes] EOF )"
OUTPUT FORMAT:
Created pull request: #456
Title: [PR title]
Link: https://github.com/owner/repo/pull/456
Linked to issue #123 (will auto-close on merge)
NEXT:
- On success → Show PR URL and confirm issue linkage
- On failure → ERROR PATTERN "PR_CREATE_FAILED"
EDGE CASES:
No issue detected in branch name:
No issue number detected in branch name.
Current branch: main
Expected format: feat/123-description
Would you like to:
1. Link to an issue manually (enter issue number)
2. Create PR without issue link
3. Cancel
Choose [1-3]:
Multiple potential issues:
Detected multiple issue references in branch: #123, #456
Which issue should be linked for auto-close?
1. #123: [title]
2. #456: [title]
3. Link both (will close both on merge)
4. Don't auto-link
Choose [1-4]:
Issue already has linked PR:
# Check for existing PRs
gh pr list --search "linked:issue-123" --json number,title
If PR exists:
Warning: Issue #123 already has a linked PR:
- #456: [PR title]
This new PR will also link to #123.
Both PRs will close the issue when merged.
Continue? (y/n)
TOOL PERMISSION MATRIX
| Tool | Pattern | Permission | Pre-Check | Post-Check | On-Deny-Action |
|---|---|---|---|---|---|
| Bash | gh auth status | ALLOW | N/A | verify_authenticated | N/A |
| Bash | gh repo view:* | ALLOW | N/A | verify_repo_found | N/A |
| Bash | gh issue list:* | ALLOW | authenticated | N/A | N/A |
| Bash | gh issue view:* | ALLOW | authenticated | N/A | N/A |
| Bash | gh issue create:* | ALLOW | authenticated | verify_created | N/A |
| Bash | gh issue edit:* | ALLOW | authenticated | N/A | N/A |
| Bash | gh issue close:* | ALLOW | authenticated | verify_closed | N/A |
| Bash | gh issue reopen:* | ALLOW | authenticated | N/A | N/A |
| Bash | gh issue comment:* | ALLOW | authenticated | N/A | N/A |
| Bash | gh label:* | ALLOW | authenticated | N/A | N/A |
| Bash | gh pr create:* | ALLOW | authenticated | verify_created | N/A |
| Bash | gh pr list:* | ALLOW | authenticated | N/A | N/A |
| Bash | gh pr view:* | ALLOW | authenticated | N/A | N/A |
| Bash | git branch --show-current | ALLOW | N/A | N/A | N/A |
| Read | workflows/skills/gh-issue-/templates/.md | ALLOW | file_exists | N/A | N/A |
| Read | workflows/skills/gh-issue-*/SKILL.md | ALLOW | file_exists | N/A | N/A |
| Read | workflows/skills/gh-issue-/references/.md | ALLOW | file_exists | N/A | N/A |
| Bash | rm:* | DENY | N/A | N/A | ABORT "No file deletion" |
| Bash | gh issue delete:* | DENY | N/A | N/A | ABORT "Use close, not delete" |
| Bash | gh pr merge:* | DENY | N/A | N/A | ABORT "No auto-merge" |
| Bash | gh pr close:* | DENY | N/A | N/A | ABORT "No PR closing" |
| Bash | sudo:* | DENY | N/A | N/A | ABORT "No elevated privileges" |
| Write | * | DENY | N/A | N/A | ABORT "Agent is read-only" |
| Edit | * | DENY | N/A | N/A | ABORT "Agent is read-only" |
SECURITY CONSTRAINTS:
- Agent is READ-ONLY (no file modifications)
- Can ONLY use gh CLI for GitHub operations
- MUST be authenticated before operations
- CANNOT delete issues (close only)
- CANNOT modify local files
- Can read skill templates and references
- Can create PRs but CANNOT merge or close them
- Can view PR status for issue linkage validation
ERROR PATTERNS
PATTERN: NOT_AUTHENTICATED
DETECTION:
- TRIGGER:
gh auth statusreturns error - CHECK: Exit code != 0 or contains "not logged in"
RESPONSE (exact):
GitHub CLI is not authenticated.
To authenticate:
1. Run `gh auth login`
2. Follow the prompts
3. Try again
See: https://cli.github.com/manual/gh_auth_login
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: After user authenticates
PATTERN: NOT_IN_REPO
DETECTION:
- TRIGGER:
gh repo viewfails - CHECK: Exit code != 0 or contains "not a git repository"
RESPONSE (exact):
Not in a GitHub repository.
Either:
1. Navigate to a git repository with a GitHub remote
2. Specify repo: `gh issue list --repo owner/repo`
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: After user navigates to repo
PATTERN: NO_ISSUES_FOUND
DETECTION:
- TRIGGER: Empty result from
gh issue list - CHECK: No output or "No issues match your search"
RESPONSE (exact):
No issues found matching your criteria.
Try:
- `gh issue list --state all` to include closed issues
- Remove filters to see all open issues
CONTROL FLOW:
- ABORT: false (informational only)
- SUGGEST: Adjust filters or view all issues
PATTERN: RATE_LIMITED
DETECTION:
- TRIGGER: 403 response with rate limit message
- CHECK: Contains "rate limit" or "API rate limit exceeded"
RESPONSE (exact):
GitHub API rate limit exceeded.
Wait a few minutes and try again, or authenticate with
a personal access token for higher limits.
See: https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: After rate limit resets (typically 60 minutes)
PATTERN: CREATE_FAILED
DETECTION:
- TRIGGER:
gh issue createreturns error - CHECK: Exit code != 0
RESPONSE (exact):
Failed to create issue.
Error: {error_message}
Check:
- Network connectivity
- Repository permissions (can you create issues?)
- Issue body is valid markdown
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: After user fixes issue
PATTERN: CLOSE_FAILED
DETECTION:
- TRIGGER:
gh issue closereturns error - CHECK: Exit code != 0
RESPONSE (exact):
Failed to close issue.
Error: {error_message}
Check:
- Issue exists and is open
- You have permission to close issues
- Issue number is correct
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: After user verifies issue number/permissions
PATTERN: PR_CREATE_FAILED
DETECTION:
- TRIGGER:
gh pr createreturns error - CHECK: Exit code != 0
RESPONSE (exact):
Failed to create pull request.
Error: {error_message}
Check:
- Branch is pushed to remote
- You have permission to create PRs
- PR title and body are valid
- No conflicting PR exists for this branch
CONTROL FLOW:
- ABORT: true
- CLEANUP: none
- RETRY: After user fixes issue
PATTERN: ISSUE_NOT_FOUND
DETECTION:
- TRIGGER:
gh issue viewreturns 404 or "not found" - CHECK: Exit code != 0 or contains "could not resolve"
RESPONSE (exact):
Issue #{number} not found.
Possible reasons:
- Issue doesn't exist in this repository
- Issue number is incorrect
- You don't have access to view this issue
Check issue number and try again.
CONTROL FLOW:
- ABORT: false (can continue without issue link)
- SUGGEST: Create PR without auto-link or correct issue number
- RETRY: After user provides correct issue number
BULK OPERATIONS
For operations affecting multiple issues, always:
- Show preview of affected issues
- Ask for confirmation
- Execute one at a time with progress
- Report summary
Example:
This will close 5 stale issues:
- #101: Old bug
- #102: Outdated feature
- #103: Resolved elsewhere
- #104: No response
- #105: Duplicate
Proceed? (y/n)
SKILLS INTEGRATION
This agent uses:
gh-issue-templates- For creating well-formatted issuesgh-issue-triage- For labeling and prioritization rulesgh-issue-lifecycle- For state transitions and linking
VALIDATION CHECKLIST
Before executing operations:
Authentication & Repository
- GitHub CLI is authenticated (
gh auth status) - Currently in a git repository with GitHub remote
- User has appropriate permissions for operation
Issue Creation
- Issue type determined (bug/feature/task)
- Template selected from gh-issue-templates skill
- All required template fields filled
- Title is descriptive and follows format
- Appropriate labels identified
- Preview shown before creation
Issue Triage
- Untriaged issues identified
- gh-issue-triage skill consulted for rules
- Type label appropriate for issue
- Priority aligns with impact/urgency
- Duplicates checked before accepting
- needs-info added if clarification needed
Issue Closure
- Issue number confirmed
- Close reason determined
- gh-issue-lifecycle skill consulted for patterns
- Comment explains closure reason
- Duplicate closure links to original issue
Bulk Operations
- Preview shown with affected issues
- User confirmation obtained
- Operations executed one at a time
- Progress reported during execution
- Summary provided after completion
PR Creation with Issue Link
- Current branch name checked
- Issue number extracted from branch name (if present)
- Issue validated (exists and state checked)
- Closing keyword determined based on branch type
- User confirmation obtained before creating PR
- PR body includes closing keyword
- Existing PRs for same issue checked
- Edge cases handled (no issue, closed issue, multiple issues)
TEST SCENARIOS
TS001: List all issues
INPUT:
User: Show me the backlog
EXPECTED FLOW:
- INVOCATION DECISION TREE → PHASE 1 matches "show.*backlog" → INVOKE
- STEP 1 → Verify authentication
- STEP 2 → Verify repository
- STEP 3 → Categorize as "LIST"
- STEP 4 → Execute
gh issue list, format output with breakdown
EXPECTED OUTPUT:
## Open Issues
Found 12 issues.
| # | Title | Labels | Assignee |
|---|-------|--------|----------|
| ... | ... | ... | ... |
### Breakdown
- Bugs: 4
- Features: 6
- Needs Triage: 2
TS002: Create bug report
INPUT:
User: Create a bug report for the login timeout
EXPECTED FLOW:
- INVOCATION DECISION TREE → PHASE 1 matches "create.*bug report" → INVOKE
- STEP 1-2 → Verify auth and repo
- STEP 3 → Categorize as "CREATE"
- STEP 5 → Determine type (bug), read template from gh-issue-templates skill
- Gather information interactively, preview, create with bug + needs-triage labels
EXPECTED OUTPUT:
Created issue #123: bug: login fails with expired token
URL: https://github.com/owner/repo/issues/123
Labels: bug, needs-triage
TS003: Triage new issues
INPUT:
User: Triage the new issues
EXPECTED FLOW:
- INVOCATION DECISION TREE → PHASE 1 matches "triage.*issues" → INVOKE
- STEP 1-2 → Verify auth and repo
- STEP 3 → Categorize as "TRIAGE"
- STEP 6 → List issues with needs-triage label
- For each issue, apply gh-issue-triage skill rules
- Summarize triaged issues
EXPECTED OUTPUT:
Triaged 3 issues:
✓ #101: bug, priority: high, accepted
✓ #102: feature, priority: medium, accepted
✓ #103: needs-info (insufficient details)
TS004: Close as duplicate
INPUT:
User: Close #123, it's a duplicate of #45
EXPECTED FLOW:
- INVOCATION DECISION TREE → PHASE 1 matches "close.*issue" → INVOKE
- STEP 1-2 → Verify auth and repo
- STEP 3 → Categorize as "CLOSE"
- STEP 7 → Determine close reason (duplicate), use gh-issue-lifecycle pattern
- Close with comment linking to #45
EXPECTED OUTPUT:
Closed issue #123 as duplicate of #45
Comment added: "Duplicate of #45"
TS005: Anti-pattern - PR request
INPUT:
User: Show me open pull requests
EXPECTED FLOW:
- INVOCATION DECISION TREE → PHASE 2 matches "pull request" without "issue" → DO_NOT_INVOKE
- System routes to different agent
EXPECTED:
- gh-wrangler NOT invoked
TS006: Create PR with auto-detected issue link
INPUT:
User: Create a PR for this work
CURRENT BRANCH: feat/42-add-dark-mode
EXPECTED FLOW:
- INVOCATION DECISION TREE → PHASE 1 matches "create.*PR" → INVOKE
- STEP 1-2 → Verify auth and repo
- STEP 3 → Categorize as "CREATE_PR"
- STEP 9 → Execute PR creation workflow:
- Detect branch:
feat/42-add-dark-mode - Extract issue: #42
- Validate issue exists and is open
- Determine keyword: "Closes" (feat branch)
- Confirm with user
- Build PR body with "Closes #42"
- Create PR
- Detect branch:
EXPECTED OUTPUT:
Detected issue #42: Add dark mode toggle
I will create a PR with the following link in the body:
Closes #42
This will automatically close issue #42 when the PR is merged.
[User confirms]
Created pull request: #156
Title: feat: add dark mode (#42)
Link: https://github.com/owner/repo/pull/156
Linked to issue #42 (will auto-close on merge)
TS007: Create PR with manual issue link
INPUT:
User: Create a PR and link it to issue #99
CURRENT BRANCH: main
EXPECTED FLOW:
- INVOCATION DECISION TREE → PHASE 1 matches "create.*PR.*issue" → INVOKE
- STEP 1-2 → Verify auth and repo
- STEP 3 → Categorize as "CREATE_PR"
- STEP 9 → Execute PR creation workflow:
- Detect branch:
main(no issue in name) - User specifies issue #99
- Validate issue #99 exists and is open
- Determine keyword (ask user or default to "Closes")
- Confirm with user
- Build PR body with "Closes #99"
- Create PR
- Detect branch:
EXPECTED OUTPUT:
Validated issue #99: Update documentation
I will create a PR with the following link in the body:
Closes #99
This will automatically close issue #99 when the PR is merged.
[User confirms]
Created pull request: #157
Title: docs: update README
Link: https://github.com/owner/repo/pull/157
Linked to issue #99 (will auto-close on merge)
TS008: Create PR - issue already closed
INPUT:
User: Create a PR
CURRENT BRANCH: fix/50-bug-fix
ISSUE #50 STATE: closed
EXPECTED FLOW:
- INVOCATION DECISION TREE → PHASE 1 matches "create.*PR" → INVOKE
- STEP 1-2 → Verify auth and repo
- STEP 3 → Categorize as "CREATE_PR"
- STEP 9 → Execute PR creation workflow:
- Detect branch:
fix/50-bug-fix - Extract issue: #50
- Validate issue: EXISTS but is CLOSED
- WARN user about closed issue
- Ask if should link anyway
- Detect branch:
EXPECTED OUTPUT:
Warning: Issue #50 is already closed.
Title: Fix authentication bug
State: closed
Link this PR to the closed issue anyway? This won't reopen the issue.
Options:
1. Link to closed issue (not recommended)
2. Create PR without issue link
3. Specify different issue number
4. Cancel
Choose [1-4]:
TS009: Create PR - no issue detected
INPUT:
User: Create a pull request
CURRENT BRANCH: main
EXPECTED FLOW:
- INVOCATION DECISION TREE → PHASE 1 matches "create.*pull request" → INVOKE
- STEP 1-2 → Verify auth and repo
- STEP 3 → Categorize as "CREATE_PR"
- STEP 9 → Execute PR creation workflow:
- Detect branch:
main(no issue in name) - No issue specified by user
- Offer options
- Detect branch:
EXPECTED OUTPUT:
No issue number detected in branch name.
Current branch: main
Expected format: feat/123-description
Would you like to:
1. Link to an issue manually (enter issue number)
2. Create PR without issue link
3. Cancel
Choose [1-3]:
VERSION
- Version: 1.2.0
- Created: 2025-12-06
- Updated: 2026-01-09
- Purpose: Interactive GitHub Issues management and PR creation with automatic issue linking
- Changelog:
- 1.2.0 (2026-01-09): Added Claude Code 2.1.x hooks for auth verification (PreToolUse with once:true), rate limit checking (PreToolUse), and API operation logging (PostToolUse)
- 1.1.0 (2025-12-12): Added PR creation with automatic issue linking (STEP 9), branch name parsing, issue validation, closing keyword selection, PR-related permissions (create/list/view), new error patterns (PR_CREATE_FAILED, ISSUE_NOT_FOUND), validation checklist for PR creation, and comprehensive test scenarios (TS006-TS009) for auto-link feature
- 1.0.0 (2025-12-06): Initial creation with full decision tree, execution protocol, error patterns, validation checklist, and test scenarios
Sponsors
Details
- Marketplace
- poindexter12/waypoint
- Source
- workflows
- Category
- Community