Skip to content

Instantly share code, notes, and snippets.

@akirilyuk
Last active May 17, 2026 08:46
Show Gist options
  • Select an option

  • Save akirilyuk/f293903d3612ec466b7b01c9203c0ef1 to your computer and use it in GitHub Desktop.

Select an option

Save akirilyuk/f293903d3612ec466b7b01c9203c0ef1 to your computer and use it in GitHub Desktop.
How to work with multiple agent session and cursor agent via the shell

Multi-Agent Git Worktree Workflow

A workflow for cloning a repo into a parent directory and using git worktrees to run multiple Cursor CLI agents on separate tasks simultaneously.

Note: This guide is written for the Cursor CLI agent (the terminal-based cursor command), not the Cursor IDE. All examples assume you are working in a terminal.

Directory Structure

repo-root-dir/                # parent container (you create this)
├── main/                     # the actual git clone (main worktree)
├── feature-auth/             # worktree → feature/auth branch
├── fix-crash-on-login/       # worktree → fix/crash-on-login branch
└── refactor-db-layer/        # worktree → refactor/db-layer branch

Every worktree is a full working directory that shares the same .git object store. Cheap to create, instant to switch, no duplicate clones.

Setup

1. Create the parent directory and clone

mkdir my-project
cd my-project
git clone git@github.com:org/repo.git main

2. Add worktrees for each task

cd main

# Create worktrees as siblings in the parent directory
git worktree add ../feature-auth    -b feature/auth
git worktree add ../fix-crash       -b fix/crash-on-login
git worktree add ../refactor-db     -b refactor/db-layer

# To check out an existing remote branch instead:
git fetch origin
git worktree add ../hotfix-prod     origin/hotfix/prod

3. Verify

git worktree list
# /Users/you/my-project/main              abc1234 [main]
# /Users/you/my-project/feature-auth      abc1234 [feature/auth]
# /Users/you/my-project/fix-crash         abc1234 [fix/crash-on-login]
# /Users/you/my-project/refactor-db       abc1234 [refactor/db-layer]

Cleanup

cd main
git worktree remove ../feature-auth    # after merging / done
git worktree prune                     # clean up stale entries

Running Multiple Agents

There are three approaches, each with different trade-offs.

Approach A: best-of-n-runner subagents (single CLI session)

Cursor's CLI agent has a built-in best-of-n-runner subagent type that automatically creates isolated git worktrees. You launch multiple from one parent session and they run in parallel.

How it works: From a single Cursor CLI session open in main/, you ask the agent to launch parallel tasks. The agent uses the Task tool with best-of-n-runner, which creates a worktree per subagent behind the scenes. Each subagent gets its own branch and working directory.

When to use:

  • You have well-defined, independent tasks that don't need interactive guidance
  • You want one place to see all results
  • You want the agent to decide how to break work apart

Limitations:

  • Subagents run autonomously — you can't interactively steer each one mid-flight
  • Each subagent starts with only the prompt you give it (no shared conversation history)
  • Results come back as text summaries to the parent agent

Example prompt to a Cursor CLI agent:

I need three things done in parallel:

  1. Add JWT authentication middleware to the Express app
  2. Fix the crash in src/db/connection.ts when the pool is exhausted
  3. Refactor the user service to use the repository pattern

Run each as a separate best-of-n-runner subagent.

The agent will launch three parallel subagents, each in its own worktree and branch, and report back with results.


Approach B: Dedicated CLI sessions per worktree (interactive)

Open a separate Cursor CLI session in each worktree directory. Each session is fully interactive — you can guide, iterate, and debug with each agent independently.

Setup:

# Terminal 1
cd my-project/main
cursor

# Terminal 2
cd my-project/feature-auth
cursor

# Terminal 3
cd my-project/fix-crash
cursor

Each session sees its own working directory, its own branch, its own changes. No conflicts, no lock contention — git worktrees handle the isolation.

When to use:

  • Tasks need interactive back-and-forth (debugging, design decisions)
  • You want full control over each agent's context and direction
  • Tasks have dependencies or need human judgment at decision points

Tips:

  • Use a terminal multiplexer (tmux, zellij, or just multiple terminal tabs)
  • Name your tmux windows after the task for easy switching
  • Each agent can commit independently to its branch
# tmux example
tmux new-session -s agents
tmux new-window -n auth    "cd ~/my-project/feature-auth && cursor"
tmux new-window -n bugfix  "cd ~/my-project/fix-crash && cursor"
tmux new-window -n refactor "cd ~/my-project/refactor-db && cursor"

Approach C: Cursor SDK (programmatic orchestration)

For fully automated pipelines — CI, nightly jobs, batch processing — use the Cursor TypeScript SDK to programmatically create and manage multiple agents.

import { Agent } from "@cursor/sdk";

const tasks = [
  { cwd: "/Users/you/my-project/feature-auth", prompt: "Implement JWT auth middleware" },
  { cwd: "/Users/you/my-project/fix-crash",    prompt: "Fix the DB pool exhaustion crash" },
  { cwd: "/Users/you/my-project/refactor-db",  prompt: "Refactor user service to repository pattern" },
];

const results = await Promise.all(
  tasks.map((task) =>
    Agent.prompt(task.prompt, {
      apiKey: process.env.CURSOR_API_KEY!,
      model: { id: "composer-2" },
      local: { cwd: task.cwd },
    })
  )
);

for (const r of results) {
  console.log(r.status, r.result);
}

When to use:

  • Fully automated workflows (CI/CD, scheduled jobs)
  • You need programmatic control over agent lifecycle
  • You want to integrate with other tooling (Slack notifications, dashboards)

Limitations:

  • Requires CURSOR_API_KEY and the @cursor/sdk npm package
  • Local runtime only — agents run on the machine executing the script
  • No interactive steering (but you can use Agent.create() + agent.send() for multi-turn)

Which Approach Should You Use?

Criteria A: Subagents B: Dedicated Sessions C: SDK
Setup effort None (built-in) Low (open terminals) Medium (write script)
Interactive control No Yes Limited
Parallel execution Yes Yes Yes
Single pane of glass Yes No (switch terminals) Yes (script output)
Task independence required Yes No Yes
Good for debugging No Yes No
Good for well-defined tasks Yes Yes Yes
Automatable No No Yes

Recommendation:

  • Start with Approach B (dedicated sessions) when you're actively developing and need to guide the agents. This is the most flexible and gives you full control.
  • Use Approach A (subagents) when you have clear, independent tasks and want to fire them off from a single session without switching terminals.
  • Use Approach C (SDK) when you want to automate the workflow end-to-end, e.g. a script that sets up worktrees, launches agents, and collects results.

Combining Approaches

A practical daily workflow might combine A and B:

  1. Open a Cursor CLI session in main/ as your "command center"
  2. For simple, well-scoped tasks → launch best-of-n-runner subagents from there
  3. For complex tasks that need guidance → open a dedicated session in the worktree
  4. Review all branches in main/ when done:
cd main
git log --oneline --graph --all    # see all branches at a glance

Git Worktree Cheat Sheet

# List all worktrees
git worktree list

# Add a worktree with a new branch
git worktree add ../dirname -b branch-name

# Add a worktree tracking an existing remote branch
git worktree add ../dirname origin/branch-name

# Remove a worktree
git worktree remove ../dirname

# Clean up stale worktree references
git worktree prune

# Lock a worktree (prevent accidental removal)
git worktree lock ../dirname

# Move a worktree to a new path
git worktree move ../old-path ../new-path

Using This Process in the Cursor IDE

The workflow above is written for the terminal-based CLI agent, but the same worktree strategy works in the Cursor IDE (the desktop app). Here's what changes:

Setup is the same. Create the parent directory, clone, and add worktrees using the terminal commands in the Setup section.

Opening worktrees: Instead of running cursor in each worktree directory, open each worktree as a separate Cursor IDE window:

  • File → Open Folder → select the worktree directory (e.g. my-project/feature-auth)
  • Or from a terminal: cursor my-project/feature-auth (this opens the IDE, not the CLI agent)

Each window gets its own branch, its own file tree, and its own agent context.

Running agents: Use the agent panel (Cmd+I / Ctrl+I) in each window. This is the IDE equivalent of Approach B — one interactive agent per worktree, each with full access to its own working directory.

Background agents: The IDE also supports launching background agents from the agent panel. You can kick off a task and continue working in another window while it runs — similar in spirit to Approach A, but within the IDE's UI.

Reviewing results: When tasks are done, use the IDE's built-in Source Control panel (or the terminal in any window) to review branches, diffs, and create PRs.

TL;DR: Open one Cursor IDE window per worktree. Everything else — branch isolation, parallel work, independent commits — works exactly the same.


Caveats

  • One branch per worktree. Git enforces that no two worktrees can have the same branch checked out simultaneously.
  • Shared object store. All worktrees share .git objects. Running git gc in any worktree affects all of them.
  • Submodules. If the repo uses submodules, you need to run git submodule update --init in each new worktree.
  • Agent state. Each Cursor CLI agent session in a different worktree has its own .cursor/ context. Rules and settings from the main worktree won't automatically apply to sibling worktrees unless you symlink or copy them.
  • File watchers. Multiple worktrees = multiple sets of file watchers. On macOS this is usually fine; on Linux you may need to raise inotify limits.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment