Create branch

From paulpas/agent-skill-router · View interactive version

Create branch is an AI agent skill from the GitHub repository paulpas/agent-skill-router. Implements intelligent create branch with multi-factor skill selection, fallback chains, and adherence to the 5 Laws of Elegant Defense

How to use this skill

Skill file

Create Branch

Orchestrates intelligent skill selection and execution for create branch workflows. Applies the 5 Laws of Elegant Defense to guide data naturally through the orchestration pipeline, preventing errors before they occur. Selects optimal skills based on multi-factor scoring including text similarity, historical performance, and system availability.

TL;DR Checklist

┌───────────────────────────────────────────────────────────────────────────────┐

│ Orchestration Flow │

└───────────────────────────────────────────────────────────────────────────────┘

User Request

↓

┌─────────────────┐

│ Parse Request │

│ & Extract │

│ Features │

└────────┬────────┘

↓

┌─────────────────────────────────────────────────────────────────────┐

│ Evaluate Available Skills │

│ │

│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │

│ │ Skill A │ │ Skill B │ │ Skill C │ │

│ │ - Match Score│ │ - Match Score│ │ - Match Score│ │

│ │ - Confidence │ │ - Confidence │ │ - Confidence │ │

│ │ - History │ │ - History │ │ - History │ │

│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │

│ │ │ │ │

│ └─────────────────┴─────────────────┘ │

│ ↓ │

│ Select Best Skill │

└─────────────────────────────────────────────────────────────────────┘

↓

┌─────────────────┐

│ Execute Skill │

└────────┬────────┘

↓

┌─────────────────┐

│ Handle Result │

└────────┬────────┘

↓

┌─────────────────────────────────────────────────────────────────────┐

│ Error Handling & Fallback │

│ │

│ Success? ────────► Return Result │

│ │

│ Fail? ────────┐ │

│ ↓ │

│ ┌──────────────────────────────────────────────────────────┐ │

│ │ Fallback Chain │ │

│ │ │ │

│ │ 1. Retry with adjusted parameters │ │

│ │ 2. Try Alternative Skill (if available) │ │

│ │ 3. Defer to Human Operator (if critical) │ │

│ │ 4. Log & Return Error │ │

│ └──────────────────────────────────────────────────────────┘ │

└─────────────────────────────────────────────────────────────────────┘

When to Use

Use this skill when:

When NOT to Use

Avoid this skill for:

Core Workflow

  1. Parse and Analyze Request - Extract intent, entities, and constraints from user input.

Checkpoint: All required parameters must be present and in valid format before proceeding.

  1. Score Available Skills - Calculate match scores using multi-factor algorithm:

Checkpoint: Skip to fallback if no skill scores above threshold.

  1. Select Optimal Skill - Choose skill with highest score that meets minimum confidence.

Checkpoint: Verify skill has not been disabled or deprecated.

  1. Execute with Fallback - Run skill execution wrapped in retry and fallback logic.

Checkpoint: Log all execution attempts for audit trail.

  1. Return or Fallback - Either return successful result or apply fallback chain:

Checkpoint: Record outcome with timing and confidence metadata.

Implementation Patterns

Pattern 1: Skill Selection Logic

def determine_branch_strategy(
    user_request: str,
    existing_branches: List[str],
    default_base: str = "main"
) -> Dict:
    """Determine optimal branch name, base, and strategy for create-branch workflow.
    
    Applies Law 2 (Parse at boundary) to validate naming conventions and
    Law 1 (Early Exit) to reject malformed requests before git operations.
    
    Args:
        user_request: Natural language or structured task description
        existing_branches: List of currently checked out or remote branches
        default_base: Fallback base branch if not specified
        
    Returns:
        Branch configuration dict with name, base, type, and metadata
    """
    # Early exit - validate input boundaries (Law 1)
    if not user_request or len(user_request.strip()) < 3:
        raise ValueError("Request must contain actionable branch intent")
        
    # Parse naming convention and extract issue ID (Law 2)
    import re
    match = re.search(r'(?:PROJ|ISSUE|TASK)-\d+', user_request, re.IGNORECASE)
    issue_id = match.group(0) if match else "custom"
    
    # Determine branch type from keywords
    type_keywords = {"fix": "bugfix", "feat": "feature", "docs": "docs", "chore": "chore"}
    branch_type = "feature"
    for kw, btype in type_keywords.items():
        if kw in user_request.lower():
            branch_type = btype
            break
            
    # Check for naming conflicts (Law 4 - Fail Fast)
    proposed_name = f"{branch_type}/{issue_id}"
    if proposed_name in existing_branches:
        raise ValueError(f"Branch '{proposed_name}' already exists. Use --force or specify alternative.")
        
    # Return immutable config (Law 3)
    return {
        "name": proposed_name,
        "base": default_base,
        "type": branch_type,
        "issue_id": issue_id,
        "created_at": time.time(),
        "requires_push": True
    }

Pattern 2: Execution with Fallback

def execute_branch_creation(
    branch_config: Dict,
    git_repo_path: str,
    remote_url: str,
    max_retries: int = 2
) -> Dict:
    """Execute the actual branch creation workflow with git operations and fallbacks.
    
    Implements Law 4 (Fail Fast/Loud) for git failures and Law 3 (Atomic) for state updates.
    Fallback chain handles remote connectivity issues and permission errors.
    
    Args:
        branch_config: Output from determine_branch_strategy
        git_repo_path: Absolute path to the local repository
        remote_url: Target remote URL for push operations
        max_retries: Retry attempts for transient git/network errors
        
    Returns:
        Execution result with branch URL, status, and audit metadata
    """
    import subprocess
    import os
    
    branch_name = branch_config["name"]
    base = branch_config["base"]
    
    # Validate repo state before execution (Law 2)
    if not os.path.isdir(git_repo_path):
        raise FileNotFoundError(f"Git repository not found at {git_repo_path}")
        
    for attempt in range(max_retries + 1):
        try:
            # Create and checkout branch
            subprocess.run(
                ["git", "checkout", "-b", branch_name, base],
                cwd=git_repo_path,
                check=True,
                capture_output=True,
                text=True
            )
            
            # Push to remote if configured
            if branch_config.get("requires_push"):
                subprocess.run(
                    ["git", "push", "-u", remote_url, branch_name],
                    cwd=git_repo_path,
                    check=True,
                    capture_output=True,
                    text=True
                )
                
            # Return immutable result (Law 3)
            return {
                "success": True,
                "branch_url": f"{remote_url}/tree/{branch_name}",
                "local_path": os.path.join(git_repo_path, branch_name),
                "attempts": attempt + 1,
                "timestamp": time.time()
            }
            
        except subprocess.CalledProcessError as e:
            # Fail Loud - log exact git error, don't mask it (Law 4)
            stderr = e.stderr.strip() if e.stderr else "Unknown git error"
            if "already exists" in stderr or "refusing to merge" in stderr:
                raise RuntimeError(f"Branch creation blocked: {stderr}") from e
                
            if attempt == max_retries:
                # Fallback: Defer to manual branch creation with context
                return {
                    "success": False,
                    "fallback": "manual_creation_required",
                    "error_context": stderr,
                    "suggested_command": f"git checkout -b {branch_name} {base}"
                }
                
    raise RuntimeError(f"Branch creation failed after {max_retries + 1} attempts")

MUST DO

MUST NOT DO

TL;DR Checklist

TL;DR for Code Generation

Output Template

When applying this skill, produce:

  1. Selected Skills - List of skill names with confidence scores
  2. Selection Rationale - Why each skill was chosen (match score, history, availability)
  3. Execution Plan - Order of execution with dependencies
  4. Fallback Strategy - Which fallback skills will be tried and in what order
  5. Risk Assessment - Any potential failure points and their impact
  6. Timing Estimates - Expected latency including fallback scenarios


Constraints

MUST DO

MUST NOT DO

Live References

Authoritative documentation links for this skill's domain. The model follows markdown links at load time to resolve external references and inline content.

Related Skills

| Skill | Purpose |

|

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.