Agent skill

Worktree Switching

by marcus in marcus/sidecar

Git worktree support in sidecar: worktree detection, switching between worktrees, worktree state management, and plugin reinitialization.

MITAuto-check passedDevelopment

Install Worktree Switching

skills CLI
$ npx skills add marcus/sidecar --skill worktree-switching -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install marcus/sidecar worktree-switching --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/marcus/sidecar.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.claude/skills/worktree-switching .claude/skills/worktree-switching && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
worktree-switching
GitHub stars
1.1k
Token cost
~1.6k tokens
SKILL.md length
448 words
Files
1
Skills in repo
19
Repo updated
First seen
Licence
MIT

At a glance

Git worktree support in sidecar: worktree detection, switching between worktrees, worktree state management, and plugin reinitialization.

  • Works in 4 steps: All plugins are stopped, reinitialized… → Per-worktree state (active plugin,… → Project-specific themes are applied → …
  • Working on git worktree features
  • SKILL.md covers Core Mechanism, Plugin Responsibilities on…, Deleted Worktree Detection and Git Helpers, plus 3 more sections
  • Calls git

What it does

Worktree Switching is an agent skill from marcus/sidecar. Git worktree support in sidecar: worktree detection, switching between worktrees, worktree state management, and plugin reinitialization. Covers the full lifecycle of worktree context switching including registry reinit, per-worktree state persistence, deleted worktree detection and fallback. Use when working on git worktree features or worktree-related functionality.

Its SKILL.md is about 1.6k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Development, covering Git worktrees. It works with Git. The repository describes itself as: Use sidecar next to CLI agents for diffs, file trees, conversation history, and task management with td. The licence is MIT.

When your agent uses it

  • Working on git worktree features
  • Worktree-related functionality

Example prompts

  • “/worktree-switching”

Workflow steps

4 steps, taken from the first numbered list in SKILL.md.

  1. All plugins are stopped, reinitialized with the new WorkDir, and restarted
  2. Per-worktree state (active plugin, sidebar selections) is saved/restored
  3. Project-specific themes are applied
  4. If a worktree is deleted externally, sidecar gracefully falls back to main

What it can do on your machine

Read from SKILL.md and the folder at commit 3792a4e. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • git

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md. Its commands use git, which can reach the network depending on how they are called.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Worktree Switching loads about 1.6k tokens when it runs. Until then it costs about 97 tokens; SKILL.md has 448 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~97
When it runs · the whole SKILL.md, loaded when a task matches
~1.6k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from marcus/sidecar at commit 3792a4e, republished under its MIT licence (© marcus). 448 words, ~1,594 tokens.

Download SKILL.mdSave it as .claude/skills/worktree-switching/SKILL.md (or your agent's skills folder).
name
worktree-switching
description
Git worktree support in sidecar: worktree detection, switching between worktrees, worktree state management, and plugin reinitialization. Covers the full lifecycle of worktree context switching including registry reinit, per-worktree state persistence, deleted worktree detection and fallback. Use when working on git worktree features or worktree-related functionality.

Worktree Switching

Sidecar supports seamless switching between git worktrees. When switching:

  1. All plugins are stopped, reinitialized with the new WorkDir, and restarted
  2. Per-worktree state (active plugin, sidebar selections) is saved/restored
  3. Project-specific themes are applied
  4. If a worktree is deleted externally, sidecar gracefully falls back to main

Core Mechanism

Project Switching

Worktree switching uses Model.switchProject() in internal/app/model.go:

go
m.switchProject(worktreePath)

This triggers in order:

  1. Save active plugin for old WorkDir
  2. Update m.ui.WorkDir to new path
  3. Apply resolved theme for new path
  4. Call registry.Reinit(newWorkDir) -- stops all plugins, updates context, reinits all
  5. Send WindowSizeMsg to all plugins for layout recalculation
  6. Restore saved active plugin for new WorkDir
  7. Show toast notification
Registry Reinitialization

Registry.Reinit() in internal/plugin/registry.go:

go
func (r *Registry) Reinit(newWorkDir string) []tea.Cmd {
    // Stop all plugins (reverse order)
    for i := len(r.plugins) - 1; i >= 0; i-- {
        r.safeStop(r.plugins[i])
    }
    // Update context
    r.ctx.WorkDir = newWorkDir
    // Reinit all plugins
    for _, p := range r.plugins {
        r.safeInit(p)
    }
    // Collect and return start commands
    return startCmds
}

Plugin Responsibilities on Worktree Switch

Handle Reinitialization Cleanly

Your plugin will be stopped and reinitialized on worktree switch. Ensure:

  1. Stop() releases all resources (watchers, goroutines, channels)
  2. Init(ctx) resets state and reads from new ctx.WorkDir
  3. Start() kicks off fresh async work for the new context
go
func (p *Plugin) Stop() {
    p.stopOnce.Do(func() {
        if p.watcher != nil {
            p.watcher.Close()
        }
        close(p.done)
    })
}

func (p *Plugin) Init(ctx *plugin.Context) error {
    p.ctx = ctx
    p.items = nil            // Reset state
    p.stopOnce = sync.Once{} // Reset stop guard
    p.done = make(chan struct{})
    return nil
}
Handle WindowSizeMsg After Switch

After reinitialization, the app sends tea.WindowSizeMsg. Handle it in Update:

go
case tea.WindowSizeMsg:
    p.width = msg.Width
    p.height = msg.Height
    return p, nil
Persist Per-Worktree State

Use internal/state to save/restore preferences keyed by WorkDir:

go
// Restore state in Init or Start
saved := state.GetMyPluginState(p.ctx.WorkDir)
if saved.Selection != "" {
    p.selection = saved.Selection
}

// Save state on user action
state.SetMyPluginState(p.ctx.WorkDir, MyPluginState{
    Selection: p.selection,
})

Add state struct and accessors following internal/state/state.go:

go
type MyPluginState struct {
    Selection string `json:"selection,omitempty"`
}

func GetMyPluginState(workdir string) MyPluginState {
    mu.RLock()
    defer mu.RUnlock()
    if current == nil || current.MyPlugin == nil {
        return MyPluginState{}
    }
    return current.MyPlugin[workdir]
}

State is saved to ~/.config/sidecar/state.json keyed by absolute WorkDir path. State is automatically per-worktree when you pass p.ctx.WorkDir.

Deleted Worktree Detection

When a worktree is deleted externally, plugins should detect this and request fallback to main.

App-Level Commands

Defined in internal/app/commands.go:

  • SwitchWorktreeMsg{WorktreePath} -- requests switching to a specific worktree
  • SwitchWorktree(path) tea.Cmd -- helper to create the above
  • SwitchToMainWorktreeMsg{MainWorktreePath} -- requests fallback to main worktree
  • SwitchToMainWorktree(mainPath) tea.Cmd -- helper to create the above
Show full SKILL.md (181 more words)Show less
Detection Pattern (from workspace plugin)

1. Define plugin-local message (internal/plugins/workspace/worktree.go):

go
type WorkDirDeletedMsg struct {
    MainWorktreePath string
}

2. Detect deletion in refresh command:

go
func (p *Plugin) refreshWorktrees() tea.Cmd {
    workDir := p.ctx.WorkDir
    return func() tea.Msg {
        if _, err := os.Stat(workDir); os.IsNotExist(err) {
            mainPath := findMainWorktreeFromDeleted(workDir)
            if mainPath != "" {
                return WorkDirDeletedMsg{MainWorktreePath: mainPath}
            }
        }
        return RefreshDoneMsg{Worktrees: worktrees, Err: err}
    }
}

3. Handle message, return app command:

go
case WorkDirDeletedMsg:
    p.refreshing = false
    if msg.MainWorktreePath != "" {
        return p, app.SwitchToMainWorktree(msg.MainWorktreePath)
    }
    return p, nil

Git Helpers

internal/app/git.go provides:

FunctionPurpose
GetWorktrees(workDir)List all worktrees for the repo
GetMainWorktreePath(workDir)Get path to main worktree
WorktreeNameForPath(workDir, path)Derive display name for a worktree
GetAllRelatedPaths(workDir)Get all paths sharing the same repo

Per-WorkDir State Keys

KeyPurpose
ActivePluginWhich plugin tab was focused
FileBrowserFile browser selections and view state
WorkspaceWorkspace/shell selections

Best Practices

  1. Reset all state in Init() -- do not carry over stale data from previous worktree
  2. Use sync.Once for Stop() -- prevents double-close panics during rapid switching
  3. Validate WorkDir exists before expensive operations
  4. Store WorkDir at command creation time -- closures may execute after switch
  5. Keep Start() non-blocking -- return commands that do async work

Testing Worktree Switching

  1. Create a worktree: git worktree add ../my-feature feature-branch
  2. Switch to it via project switcher or workspace plugin
  3. Verify your plugin reinitializes with correct data
  4. Delete the worktree externally and trigger a refresh
  5. Verify graceful fallback to main repo

© marcus, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in .claude/skills/worktree-switching of marcus/sidecar.

Open the folder on GitHubat commit 3792a4e

Compare with similar skills

Worktree Switching next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Worktree Switching compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Worktree Switching this skillmarcus/sidecar1.1k—~1.6kAutomated safety check: PassMIT
Finishing a Development Branchobra/superpowers296k5 repos~1.9kAutomated safety check: PassMIT
Finishing A Development Branchfarm-fe/farm5.6k34 repos~1.8kAutomated safety check: PassMIT
Git Worktree Cleanuplobehub/lobehub83k—~2.8kAutomated safety check: PassCustom licence
Pre-Release PR Triagejamiepine/voicebox57k—~3.1kAutomated safety check: PassMIT
Ccmanager Configkbwo/ccmanager1.3k—~1.5kAutomated safety check: PassMIT

Similar skills

  • Walks the last step of a branch: confirm tests pass, detect the git environment, ask how to integrate, carry out your choice and clean up the worktree.

    296k GitHub starsUsed in 5 repos~1.9k tokens
    DevelopmentAuto-check passed
  • A skill your agent uses when implementation is complete, all tests pass, and you need to decide how to integrate the work - guides completion of development work by presenting structured options for…

    5.6k GitHub starsUsed in 34 repos~1.8k tokens
    DevelopmentAuto-check passed
  • Git Worktree Cleanup

    lobehub/lobehub

    Audits stale Git worktrees and branches with a bundled script, classifies each one, and deletes only after you approve the exact candidates.

    83k GitHub stars~2.8k tokensUpdated today
    DevelopmentAuto-check passed
  • Pre-Release PR Triage

    jamiepine/voicebox

    Sorts a backlog of open pull requests into must-merge, candidate, superseded and deferred, writes a triage doc and works the merge loop before a release.

    57k GitHub stars~3.1k tokensUpdated yesterday
    DevelopmentAuto-check passed
  • Ccmanager Config

    kbwo/ccmanager

    Set up, review, or repair a CCManager config — .ccmanager.json at a git repository root, or the global ~/.config/ccmanager/config.json.

    1.3k GitHub stars~1.5k tokensUpdated yesterday
    DevelopmentAuto-check passed
  • Builds a Cap feature in an isolated Git worktree with disposable dev resources, verification, a recorded demo and a neutral pull request, started with /building.

    23k GitHub stars~2.5k tokensUpdated today
    DevelopmentAuto-check: warnings

More from marcus/sidecar

All 19 skills in this repo
  • Create Adapter

    marcus/sidecar

    Create conversation adapters for importing AI chat history from different tools (Claude Code, Cursor, Warp, Codex, etc.).

    1.1k GitHub stars~4.8k tokensUpdated 2 days ago
    Auto-check passed
  • Create Modal

    marcus/sidecar

    Create declarative modals using the modal library API. An agent skill from marcus/sidecar.

    1.1k GitHub stars~2.6k tokensUpdated 2 days ago
    Auto-check passed
  • Create Plugin

    marcus/sidecar

    Create new sidecar plugins implementing the plugin.Plugin interface, rendering views with Bubble Tea, handling keyboard input via keymap contexts, and integrating with the app shell (footer hints…

    1.1k GitHub stars~2.3k tokensUpdated 2 days ago
    Auto-check passed
  • Project Switching

    marcus/sidecar

    Project switching implementation in sidecar: project discovery, state management, UI flow, modal rendering, filtering, theme preview, and plugin reinitialization.

    1.1k GitHub stars~1.8k tokensUpdated 2 days ago
    Auto-check passed
  • Shell Integration

    marcus/sidecar

    Interactive shell/TTY integration with tmux session management, shell command execution, control-mode output capture with polling fallback, native cursor rendering, lazy scrollback, selection, paste…

    1.1k GitHub stars~3.6k tokensUpdated 2 days ago
    Auto-check passed
  • Sidecar Website

    marcus/sidecar

    Writing and maintaining the Sidecar Docusaurus documentation site, including page structure, doc authoring, blog posts, styling, images, and deployment workflow.

    1.1k GitHub stars~1.7k tokensUpdated 2 days ago
    Auto-check passed

Works with

Categories

Questions about Worktree Switching

What does Worktree Switching do?

Git worktree support in sidecar: worktree detection, switching between worktrees, worktree state management, and plugin reinitialization. Worktree Switching is an agent skill from marcus/sidecar. Git worktree support in sidecar: worktree detection, switching between worktrees, worktree state management, and plugin reinitialization.

When should I use Worktree Switching?

Worktree Switching fits situations like: working on git worktree features; worktree-related functionality.

How do I install Worktree Switching in Claude Code?

Run `npx skills add marcus/sidecar --skill worktree-switching -a claude-code`. Or copy the skill folder (.claude/skills/worktree-switching in marcus/sidecar) into .claude/skills/worktree-switching in your project. Claude Code loads it when a task matches its description.

How do I install Worktree Switching in Codex?

Run `npx skills add marcus/sidecar --skill worktree-switching -a codex`. Or copy the skill folder (.claude/skills/worktree-switching in marcus/sidecar) into .agents/skills/worktree-switching in your project. Codex loads it when a task matches its description.

Can I use Worktree Switching in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add marcus/sidecar --skill worktree-switching -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/worktree-switching, .gemini/skills/worktree-switching, .github/skills/worktree-switching and .opencode/skills/worktree-switching in your project.

What does Worktree Switching need to run?

Going by SKILL.md and its folder, Worktree Switching needs the command-line tools its instructions call (git).

Does Worktree Switching access the network?

SKILL.md contains no URLs. Its commands use git, which can reach the network depending on how they are called. This is read from the text; nothing was executed.

Is Worktree Switching safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Worktree Switching use?

Worktree Switching is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Worktree Switching use?

About 1.6k tokens (SKILL.md is roughly 6.4k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Worktree Switching?

Skills that share tags, products or a category with Worktree Switching: Finishing a Development Branch (obra/superpowers, 296k stars), Finishing A Development Branch (farm-fe/farm, 5.6k stars), Git Worktree Cleanup (lobehub/lobehub, 83k stars) and Pre-Release PR Triage (jamiepine/voicebox, 57k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Worktree Switching?

marcus (a GitHub user) maintains it in marcus/sidecar, which has 1,085 GitHub stars. The repository holds 19 skills in this directory. The repository was last updated on October 5, 2026.

Source: marcus/sidecar on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.