Isolated git worktree workflow for coding agents. Handles worktree creation, atomic commits, branch publishing, optional PR creation, and cleanup. Use when implementing code changes that need branch isolation. Trigger terms - worktree, isolated workspace, branch isolation, atomic commits, code changes in isolation, parallel agent work.
Creates isolated git worktrees for safe code changes, then atomically commits and pushes branches with validation. Use when you need branch isolation for implementing features, fixes, or refactors without affecting the main workspace.
/plugin marketplace add rp1-run/rp1/plugin install rp1-dev@rp1-runThis skill inherits all available tools. When active, it can use any tool Claude has access to.
WORKFLOWS.mdThis skill provides a complete workflow for performing coding work in isolated git worktrees. It enables agents to make changes without affecting the main working directory, commit atomically with conventional format, and optionally create pull requests.
rp1 agent-tools worktree create--head flag (no branch checkout required)The invoking agent provides these parameters:
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
task_slug | string | Yes | - | 2-4 word slug for branch naming (e.g., fix-auth-bug) |
agent_prefix | string | No | quick-build | Branch prefix (e.g., feature, fix, refactor) |
create_pr | boolean | No | false | Whether to create a PR after pushing the branch |
pr_title | string | No | - | PR title (required if create_pr=true) |
pr_body | string | No | - | PR body content (markdown supported) |
Prepare the isolated worktree workspace before any coding work.
Store the current working directory for later restoration:
# Store current directory (MUST be done before any cd operations)
original_cwd=$(pwd)
Record original_cwd in your working memory. You will need this value in Phase 4 before cleanup.
Run the worktree creation command with the provided parameters:
rp1 agent-tools worktree create {task_slug} --prefix {agent_prefix}
The command returns JSON. Parse and extract these values:
{
"path": "/path/to/worktree",
"branch": "agent-prefix/task-slug-abc123",
"basedOn": "abc1234"
}
Store these values in working memory:
worktree_path: The full path to the worktree directorybranch: The branch name created for this worktreebasedOn: The commit hash the branch was created fromIf the command fails, STOP and report the error to the user. Do not proceed with partial state.
Common failure: Gitignore validation error
If you see an error like:
Worktree directory "..." is not gitignored. Creating worktrees in tracked directories can cause repository corruption.
This means the .rp1/work/worktrees/ directory is not in .gitignore. To fix:
.rp1/* to your .gitignore (with exceptions like !.rp1/context/ if needed).gitignore changesChange to the worktree directory:
cd {worktree_path}
Verify you are in the correct directory before proceeding.
CRITICAL: Verify the worktree is properly initialized before any git operations. This prevents corrupted PRs.
Check 1: Verify history exists
git log --oneline -3
Expected: At least 3 commits should be visible. If the output shows fewer commits or an error about missing history, the worktree is corrupted.
Check 2: Verify basedOn commit is in history
The basedOn commit from Step 1.2 must appear in the recent history. Run:
git log --oneline | grep {basedOn}
Or visually confirm the commit hash appears in the git log --oneline -3 output. The basedOn commit should be the HEAD commit at this point.
Check 3: Verify branch name
git branch --show-current
Expected: Output matches the branch value from Step 1.2 exactly.
If ANY verification check fails:
cd {original_cwd} && rp1 agent-tools worktree cleanup {worktree_path}Once all verifications pass, you are ready to begin implementation work in Phase 2. The worktree is isolated and has valid history.
Perform your coding work with atomic commits using conventional commit format.
Before making changes, ensure dependencies are installed if the project requires them. See WORKFLOWS.md for dependency detection and installation by project type.
Common patterns:
package.json present: run bun install or npm installCargo.toml present: run cargo buildrequirements.txt or pyproject.toml present: run pip install -r requirements.txt or appropriate commandSkip this step if dependencies are already installed or not required.
As you implement changes, commit after each logical unit of work. A "logical unit" is a cohesive change that could stand alone:
Commit Command Pattern:
git add -A && git commit -m "type(scope): description"
All commits MUST use conventional commit format:
| Type | When to Use |
|---|---|
feat | New feature or capability |
fix | Bug fix |
refactor | Code restructuring without behavior change |
docs | Documentation only changes |
test | Adding or modifying tests |
chore | Maintenance tasks (deps, config) |
style | Formatting, whitespace (no code change) |
perf | Performance improvements |
Format: type(scope): short description
Examples:
git commit -m "feat(auth): add JWT token validation"
git commit -m "fix(api): handle null response from endpoint"
git commit -m "refactor(utils): extract date formatting to helper"
git commit -m "test(auth): add unit tests for login flow"
git commit -m "docs(readme): update installation instructions"
Rules:
CRITICAL: Never leave the worktree in a dirty state between work sessions.
Before pausing or ending work:
git status to check for uncommitted changeschore(wip): work in progress on {description}Rationale: Dirty state at cleanup time requires user intervention and complicates the workflow. Frequent atomic commits prevent this and create clear git history.
Keep a mental count of commits made during this session. This count will be validated in Phase 3 before pushing. Example tracking:
feat(skill): add parameter tablefeat(skill): implement phase 1 setupdocs(skill): add verification failure protocolThis count helps verify commit ownership before publishing.
When implementation is complete:
Before pushing commits to remote, validate that all commits were created during this session. This prevents corrupted PRs with orphan commits or unexpected authors.
Run the following command to list all commits that will be pushed:
git log {basedOn}..HEAD --oneline --format="%h %an <%ae> %s"
Replace {basedOn} with the commit hash stored from Phase 1, Step 1.2.
Example output:
abc1234 Claude <noreply@anthropic.com> feat(skill): add parameter table
def5678 Claude <noreply@anthropic.com> feat(skill): implement phase 1 setup
Count the commits in the output from Step 3.1. This count MUST match the number of commits you tracked during Phase 2.
Validation check:
If the counts do not match, this indicates orphan commits that were not created by this session.
All commits listed in Step 3.1 MUST descend from the basedOn commit. The git log {basedOn}..HEAD command inherently filters to only show commits reachable from HEAD that are not reachable from basedOn.
If the command returns commits you did not create, or returns an unexpectedly large number of commits, this indicates corrupted history.
Red flags:
Review the author information in the git log output from Step 3.1. All commits should have:
Claude (or the agent's configured identity)noreply@anthropic.com (or configured agent email)Suspicious authors (STOP if you see these):
Test User <test@test.com> - test suite contaminationuser@example.comIf ANY validation check fails:
git log --oneline -20 and git show {commit_hash}See WORKFLOWS.md for detailed recovery procedures for each failure type.
After all validation checks pass, push the branch to the remote:
git push -u origin {branch}
Replace {branch} with the branch name stored from Phase 1, Step 1.2.
Expected output: Branch pushed successfully with tracking set up.
If push fails (network error, authentication, etc.), see WORKFLOWS.md for error recovery procedures.
This step only applies when create_pr=true parameter was provided.
If create_pr=false or not specified, skip to Phase 4: Cleanup.
CRITICAL: Create the PR using --head flag. Do NOT checkout the branch. The worktree workflow maintains isolation by never switching branches in the main working directory.
gh pr create --head {branch} --base main --title "{pr_title}" --body "{pr_body}"
Replace:
{branch} with the branch name from Phase 1{pr_title} with the provided PR title parameter{pr_body} with the provided PR body parameter (can be multi-line markdown)For multi-line body, use heredoc: --body "$(cat <<'EOF' ... EOF)"
Expected output: PR created successfully with URL displayed.
If PR creation fails (gh not authenticated, permissions, etc.), see WORKFLOWS.md for error recovery.
At this point:
Proceed to Phase 4: Cleanup.
Finalize the workflow by cleaning up the worktree. This phase ensures no work is lost and restores the original working directory.
Before cleanup, check for uncommitted changes:
git status --porcelain
If output is empty: The worktree is clean. Proceed to Step 4.3.
If output is non-empty: Uncommitted changes exist. You MUST resolve them before cleanup. Proceed to Step 4.2.
CRITICAL: Do NOT proceed with cleanup while uncommitted changes exist. Prompt the user for resolution.
Present these options to the user:
UNCOMMITTED CHANGES DETECTED
The worktree has uncommitted changes:
{output from git status --porcelain}
Options:
1. COMMIT - Stage and commit changes with a message you provide
2. DISCARD - Discard all uncommitted changes (cannot be undone)
3. ABORT - Preserve worktree for manual resolution (cleanup skipped)
Which option? [1/2/3]:
Option 1: COMMIT
If user selects commit:
Ask user for a commit message (must follow conventional format)
Run:
git add -A && git commit -m "{user_provided_message}"
Push the new commit:
git push origin {branch}
Log: "User chose to commit remaining changes: {message}"
Proceed to Step 4.3
Option 2: DISCARD
If user selects discard:
Confirm with user: "This will permanently delete uncommitted changes. Type DISCARD to confirm:"
If confirmed, run:
git checkout -- . && git clean -fd
Log: "User chose to discard uncommitted changes"
Proceed to Step 4.3
Option 3: ABORT
If user selects abort:
Log: "User chose to abort cleanup. Worktree preserved at: {worktree_path}"
Report to user:
CLEANUP ABORTED
Worktree preserved at: {worktree_path}
Branch: {branch}
To resume work: cd {worktree_path}
To manually cleanup later: rp1 agent-tools worktree cleanup {worktree_path} --keep-branch
STOP - Do NOT proceed with cleanup
See WORKFLOWS.md for detailed dirty state decision tree and edge cases.
CRITICAL: You MUST return to the original working directory before cleanup. The cleanup command will fail if your current working directory is inside the worktree (cannot delete a directory you're standing in).
cd {original_cwd}
Replace {original_cwd} with the value stored in Phase 1, Step 1.1.
Verify you are no longer in the worktree:
pwd
Expected output should match {original_cwd}, NOT {worktree_path}.
Run the cleanup command to remove the worktree while preserving the branch on remote:
rp1 agent-tools worktree cleanup {worktree_path} --keep-branch
Replace {worktree_path} with the path stored from Phase 1, Step 1.2.
Flags:
--keep-branch: Preserves the branch on remote (default behavior for pushed branches)Expected output: Worktree removed successfully, branch retained on remote.
If cleanup fails, verify:
pwd)The worktree workflow is complete. Summary:
create_pr=true was specified)Final Status Report:
WORKTREE WORKFLOW COMPLETE
Branch: {branch}
Commits: {commit_count} commits pushed
PR: {pr_url if created, otherwise "Not requested"}
Worktree: Cleaned up
WARNING: These git operations are PROHIBITED. They can corrupt history and cause PR incidents (PRs showing massive unexpected deletions).
| Command | Rationale |
|---|---|
git init | Creates orphan repo inside worktree, severing parent history. Commits appear to delete all files. |
git rebase | Rewrites commit history. Can corrupt shared history and create unresolvable conflicts. |
git reset --hard | Permanently discards commits. On shared commits, loses work and corrupts history. |
git push --force | Overwrites remote history. Can destroy other contributors' work permanently. |
git checkout {branch} | Switches branches, breaking worktree isolation. Use a new worktree instead. |
git switch {branch} | Same as checkout - breaks worktree isolation. Each worktree has one branch. |
Why dangerous: These commands corrupt the commit graph.
Safe alternatives: Use git merge instead of rebase. Use git checkout -- . instead of reset --hard (discards uncommitted changes only). Create new worktree instead of switching branches. Fix issues locally instead of force pushing.
This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins.
This skill should be used when the user asks to "create a slash command", "add a command", "write a custom command", "define command arguments", "use command frontmatter", "organize commands", "create command with file references", "interactive command", "use AskUserQuestion in command", or needs guidance on slash command structure, YAML frontmatter fields, dynamic arguments, bash execution in commands, user interaction patterns, or command development best practices for Claude Code.
This skill should be used when the user asks to "create a hook", "add a PreToolUse/PostToolUse/Stop hook", "validate tool use", "implement prompt-based hooks", "use ${CLAUDE_PLUGIN_ROOT}", "set up event-driven automation", "block dangerous commands", or mentions hook events (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification). Provides comprehensive guidance for creating and implementing Claude Code plugin hooks with focus on advanced prompt-based hooks API.