Skip to content
Development
Command

/agent-prep-merge

Prepare branches for merging across multiple worktrees and coordinate integration

From plugin
claude-cmd
313180 skills180 commands

How it fires

How this command gets triggered: by you, by Claude, or both.

  • Fires itselfClaude auto-loads it when your prompt matches the work.
  • You can call itInvoke it directly when you want it.
  • Slash command/agent-prep-merge

Context preview

What this command does when you run it.

Prepare branches for merging across multiple worktrees and coordinate integration

Command definition

agent-prep-merge.md
allowed-tools: Bash(git:*), Bash(gh:*), Bash(rg:*), Bash(fd:*), Bash(jq:*), Read, Grep, Write, TodoWrite
name: "Agent Prep Merge"
description: "Prepare branches for merging across multiple worktrees and coordinate integration"
author: "wcygan"
tags: ["agent","merge"]
version: "1.0.0"
created_at: "2025-07-14T00:00:00Z"
updated_at: "2025-07-14T00:00:00Z"

/agent-prep-merge

Prepares branches from multiple worktrees for clean merging by checking for conflicts, running tests across affected code, generating merge strategies, and creating integration checklists. Essential for multi-agent development workflows.

Context

  • **Session ID**: !`gdate +%s%N 2>/dev/null || date +%s000000000`
  • **Current branch**: !`git branch --show-current`
  • **Active worktrees**: !`git worktree list | rg -v "bare" | wc -l | xargs -I {} echo "{} active worktrees"`
  • **Worktree details**: !`git worktree list | rg -v "bare" | awk '{print $1 " โ†’ " $3}' | sed 's/\[//g' | sed 's/\]//g'`
  • **Uncommitted changes**: !`git status --porcelain | wc -l | xargs -I {} echo "{} files"`
  • **Behind/ahead main**: !`git rev-list --left-right --count origin/main...HEAD 2>/dev/null | awk '{print "Behind: " $1 ", Ahead: " $2}' || echo "No upstream"`
  • **Project name**: !`basename "$(git rev-parse --show-toplevel)"`
  • **Coordination files**: !`PROJECT=$(basename "$(git rev-parse --show-toplevel)"); if [ -d "/tmp/$PROJECT" ]; then fd -t f "\.json$" "/tmp/$PROJECT" | wc -l | xargs -I {} echo "{} JSON files"; else echo "None"; fi`
  • **Active PRs**: !`gh pr list --state open --limit 10 --json number,title,headRefName | jq -r '.[] | "#\(.number): \(.title) (\(.headRefName))"' | head -5`

Usage

# Prepare current branch for merging with main
/agent-prep-merge

# Prepare specific branches for integration
/agent-prep-merge feature-auth feature-api

# Prepare all worktree branches for coordinated merge
/agent-prep-merge --all-worktrees

# Generate integration plan without making changes
/agent-prep-merge --dry-run

Arguments

$ARGUMENTS

Your Task

STEP 1: Initialize session and parse arguments

const SESSION_ID = await $`gdate +%s%N 2>/dev/null || date +%s000000000`.text().trim();
const PROJECT = await $`basename "$(git rev-parse --show-toplevel)"`.text();
const STATE_FILE = `/tmp/${PROJECT}/merge-prep-state-${SESSION_ID}.json`;
const COORDINATION_DIR = `/tmp/${PROJECT}`;

// Parse command arguments
let targetBranches: string[] = [];
let options = {
  allWorktrees: false,
  dryRun: false,
  createPRs: false
};

IF ($ARGUMENTS.includes("--all-worktrees")) {
  options.allWorktrees = true;
} ELSE IF ($ARGUMENTS.includes("--dry-run")) {
  options.dryRun = true;
} ELSE IF ($ARGUMENTS.includes("--create-prs")) {
  options.createPRs = true;
} ELSE IF ($ARGUMENTS && !$ARGUMENTS.startsWith("--")) {
  targetBranches = $ARGUMENTS.split(" ");
} ELSE {
  targetBranches = [await $`git branch --show-current`.text().trim()];
}

// Initialize state
const initialState = {
  sessionId: SESSION_ID,
  project: PROJECT,
  timestamp: new Date().toISOString(),
  targetBranches,
  options,
  phase: "initializing",
  worktreeAnalysis: {},
  conflictAnalysis: {},
  testPlan: null,
  mergeStrategy: null
};

await $`mkdir -p ${COORDINATION_DIR}`;
await Deno.writeTextFile(STATE_FILE, JSON.stringify(initialState, null, 2));

STEP 2: Discover and analyze worktrees

# Get all active worktrees and their branches
WORKTREES_JSON=$(git worktree list --porcelain | awk '
BEGIN { print "[" }
/^worktree / { path = $2; printf "%s{\"path\":\"%s\",", (NR>1?",":""), path }
/^branch / { gsub(/^refs\/heads\//, "", $2); printf "\"branch\":\"%s\"}", $2 }
END { print "]" }
')

# Save worktree information
echo "$WORKTREES_JSON" | jq '.' > "/tmp/$PROJECT/worktrees-${SESSION_ID}.json"

# Update target branches based on options
IF [[ "$ALL_WORKTREES" == "true" ]]; then
  TARGET_BRANCHES=$(echo "$WORKTREES_JSON" | jq -r '.[].branch' | tr '\n' ' ')
fi

echo "๐Ÿ“‹ Analyzing worktrees for branches: $TARGET_BRANCHES"

STEP 3: Validate branch states (FOR EACH target branch)

FOR BRANCH in $TARGET_BRANCHES; do
  echo "๐Ÿ” Validating branch: $BRANCH"
  
  # Find worktree path for this branch
  WORKTREE_PATH=$(echo "$WORKTREES_JSON" | jq -r ".[] | select(.branch==\"$BRANCH\") | .path")
  
  IF [[ -z "$WORKTREE_PATH" ]]; then
    echo "โš ๏ธ  Branch $BRANCH not found in any worktree"
    continue
  fi
  
  cd "$WORKTREE_PATH" || continue
  
  # Initialize branch analysis
  BRANCH_STATE="{
    \"branch\": \"$BRANCH\",
    \"worktreePath\": \"$WORKTREE_PATH\",
    \"status\": {
      \"hasUncommittedChanges\": false,
      \"isBehindMain\": false,
      \"needsPush\": false,
      \"isClean\": true
    },
    \"issues\": []
  }"
  
  # Check for uncommitted changes
  UNCOMMITTED=$(git status --porcelain | wc -l)
  IF [[ $UNCOMMITTED -gt 0 ]]; then
    echo "โš ๏ธ  Branch $BRANCH has $UNCOMMITTED uncommitted changes"
    BRANCH_STATE=$(echo "$BRANCH_STATE" | jq '.status.hasUncommittedChanges = true | .status.isClean = false | .issues += ["Uncommitted changes"]')
  fi
  
  # Check if branch is behind main
  git fetch origin main >/dev/null 2>&1
  BEHIND=$(git rev-list --count HEAD..origin/main 2>/dev/null || echo "0")
  IF [[ $BEHIND -gt 0 ]]; then
    echo "โš ๏ธ  Branch $BRANCH is $BEHIND commits behind main"
    BRANCH_STATE=$(echo "$BRANCH_STATE" | jq --arg behind "$BEHIND" '.status.isBehindMain = true | .status.isClean = false | .issues += ["Behind main by \($behind) commits"]')
  fi
  
  # Check if branch needs to be pushed
  LOCAL=$(git rev-parse HEAD)
  REMOTE=$(git rev-parse "origin/$BRANCH" 2>/dev/null || echo "")
  IF [[ "$LOCAL" != "$REMOTE" && -n "$REMOTE" ]]; then
    echo "โš ๏ธ  Branch $BRANCH differs from origin"
    BRANCH_STATE=$(echo "$BRANCH_STATE" | jq '.status.needsPush = true | .issues += ["Local differs from remote"]')
  fi
  
  # Save branch analysis
  echo "$BRANCH_STATE" > "/tmp/$PROJECT/branch-analysis-$BRANCH-${SESSION_ID}.jso
Read more
Ships withclaude-cmd

A lightweight (~46kB) and comprehensive CLI tool for managing Claude commands, configurations, and workflows.

Get the whole plugin