惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
The GitHub Blog
The GitHub Blog
博客园_首页
T
The Blog of Author Tim Ferriss
H
Hackread – Cybersecurity News, Data Breaches, AI and More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
腾讯CDC
I
InfoQ
量子位
J
Java Code Geeks
P
Proofpoint News Feed
有赞技术团队
有赞技术团队
Webroot Blog
Webroot Blog
Martin Fowler
Martin Fowler
D
Docker
F
Fortinet All Blogs
云风的 BLOG
云风的 BLOG
V
Vulnerabilities – Threatpost
罗磊的独立博客
P
Proofpoint News Feed
T
The Exploit Database - CXSecurity.com
Cyberwarzone
Cyberwarzone
P
Privacy & Cybersecurity Law Blog
Last Week in AI
Last Week in AI
爱范儿
爱范儿
The Hacker News
The Hacker News
S
SegmentFault 最新的问题
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 三生石上(FineUI控件)
V
V2EX
Simon Willison's Weblog
Simon Willison's Weblog
AI
AI
Y
Y Combinator Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
GbyAI
GbyAI
V
Visual Studio Blog
H
Heimdal Security Blog
S
Secure Thoughts
B
Blog RSS Feed
雷峰网
雷峰网
T
Tenable Blog
C
Check Point Blog
G
Google Developers Blog
大猫的无限游戏
大猫的无限游戏
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
About on SuperTechFans
Recent Commits to openclaw:main
Recent Commits to openclaw:main

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Parallel AI Coding with Git Worktrees: Run Multiple Agents Without Conflicts
jsmanifest · 2026-06-12 · via DEV Community

Parallel AI Coding with Git Worktrees: Run Multiple Agents Without Conflicts

Most parallel AI development problems stem from a single architectural mistake: multiple agents sharing the same working directory. Teams spin up three Claude Code instances, point them at the same project folder, and watch as file writes collide, branch checkouts interrupt each other, and lock files corrupt. The symptom looks like a race condition. The root cause is filesystem design.

Git worktrees solve this by giving each agent its own isolated working directory while sharing a single .git repository. This distinction is critical. Developers get parallel execution without the storage overhead of full clones, and agents operate on separate branches without stepping on each other's file handles. The pattern has existed since Git 2.5, but AI coding workflows finally make it essential infrastructure.

The Collision Problem: Why Multiple AI Agents Can't Share a Working Directory

When you run git checkout feature-A in a directory where another process is reading files, the filesystem state changes underneath that reader. The other process doesn't see atomic transitions—it sees partial writes, missing files, and inconsistent dependency graphs. TypeScript compilers fail with "Cannot find module" errors. Dev servers crash because watched files disappeared mid-read. Lock files from package managers become corrupted when two agents run npm install simultaneously on different branches with different dependency trees.

The obvious solution—staggering agent execution so only one runs at a time—defeats the purpose of parallel development. Teams that try this pattern end up with AI agents waiting in queue, each one blocking the next until it finishes. The bottleneck shifts from human typing speed to serial execution, and the productivity gains evaporate.

Full repository clones work but waste disk space. A 2GB monorepo cloned five times for five agents consumes 10GB of redundant Git objects. Sparse checkouts reduce working directory size but don't eliminate the duplication. The failure mode here is subtle but expensive: teams hit storage limits on CI runners, local SSDs fill up, and clone times dominate agent startup latency.

What Are Git Worktrees and How They Solve Agent Isolation

A worktree is a working directory linked to a shared .git folder. Run git worktree add ../feature-A feature-A and Git creates a new directory at ../feature-A checked out to the feature-A branch. Both the original working directory and the new worktree share the same object database, refs, and history. Disk usage increases only by the size of checked-out files, not the entire repository.

Git worktrees sharing a single repository while maintaining isolated working directories

Git worktrees sharing a single repository while maintaining isolated working directories

Each worktree maintains its own HEAD, index, and working directory state. Changes in one worktree don't affect the others. An agent working in feature-A/ can modify src/api.ts, run tests, and commit—all while another agent in feature-B/ edits the same file on a different branch. The filesystem-level isolation prevents the collision patterns that break shared-directory workflows.

The implication here is that worktrees enable true parallel execution without coordination overhead. Agents don't need semaphores, file locks, or message queues to avoid conflicts. The operating system's directory structure provides the isolation boundary. This matters because coordination logic is the first thing AI agents get wrong when racing for shared resources.

Setting Up Your First Parallel Agent Workflow with Worktrees

Parallel agent workflow with Git worktrees managing isolated development environments

Parallel agent workflow with Git worktrees managing isolated development environments

Start with a base repository in ~/projects/app. Create worktrees for each agent task:

import { execSync } from 'child_process';
import { mkdirSync, existsSync } from 'fs';
import { join } from 'path';

interface WorktreeConfig {
  name: string;
  branch: string;
  agentTask: string;
}

function setupParallelAgents(baseRepo: string, configs: WorktreeConfig[]): string[] {
  const worktreePaths: string[] = [];

  for (const config of configs) {
    const worktreePath = join(baseRepo, '..', config.name);

    // Create worktree on new branch from main
    execSync(
      `git worktree add -b ${config.branch} ${worktreePath} origin/main`,
      { cwd: baseRepo, stdio: 'inherit' }
    );

    // Install dependencies in isolated environment
    execSync('npm install', { cwd: worktreePath, stdio: 'inherit' });

    worktreePaths.push(worktreePath);
    console.log(`✓ Worktree ready for: ${config.agentTask}`);
  }

  return worktreePaths;
}

// Usage
const agents = setupParallelAgents('~/projects/app', [
  { name: 'agent-api', branch: 'refactor/api-layer', agentTask: 'Refactor API routes' },
  { name: 'agent-tests', branch: 'test/integration-suite', agentTask: 'Add integration tests' },
  { name: 'agent-docs', branch: 'docs/api-reference', agentTask: 'Update API docs' }
]);

Each worktree gets its own node_modules, .env.local, and build artifacts. When Agent 1 runs npm install to update a dependency, it doesn't trigger file watchers in Agent 2's worktree. Build tools like tsc or vite write to separate output directories. The isolation is complete at the filesystem level.

The critical detail here is that you must run npm install per worktree. Symlinking node_modules breaks the isolation—multiple agents end up sharing the same dependency tree, and version conflicts resurface. Disk space is cheap. Race conditions are expensive.

Related setup patterns are covered in Claude Code plugin packaging guide, which details dependency isolation for AI coding tools.

Beyond File Conflicts: Database Branching and Port Isolation

File-level isolation solves half the problem. The other half is runtime resources: database connections, dev server ports, and background services. An agent running npm run dev in one worktree defaults to localhost:3000. If another agent starts a dev server in a different worktree, the port collision crashes both processes.

Port and database isolation strategy for parallel agent execution

The solution is environment-specific configuration. Each worktree gets its own .env.local file with unique port assignments and database URLs:

import { writeFileSync } from 'fs';
import { join } from 'path';

interface AgentEnv {
  worktreePath: string;
  port: number;
  dbName: string;
}

function configureAgentEnvironment(config: AgentEnv): void {
  const envContent = `
PORT=${config.port}
DATABASE_URL=postgresql://localhost:5432/${config.dbName}
REDIS_URL=redis://localhost:6379/${config.port - 3000}
NODE_ENV=development
  `.trim();

  const envPath = join(config.worktreePath, '.env.local');
  writeFileSync(envPath, envContent);

  // Create isolated database
  execSync(`createdb ${config.dbName}`, { stdio: 'inherit' });

  // Run migrations in isolated DB
  execSync('npm run db:migrate', {
    cwd: config.worktreePath,
    stdio: 'inherit'
  });
}

// Configure three agents with isolated resources
[
  { worktreePath: '../agent-api', port: 3000, dbName: 'app_agent1' },
  { worktreePath: '../agent-tests', port: 3001, dbName: 'app_agent2' },
  { worktreePath: '../agent-docs', port: 3002, dbName: 'app_agent3' }
].forEach(configureAgentEnvironment);

Database branching tools like Neon's branching feature or PlanetScale's deploy requests extend this pattern to production-like databases. Each agent gets a copy-on-write database branch with production data, runs migrations independently, and merges schema changes back to main. The storage overhead is minimal—only changed rows consume space.

This approach scales to background workers, Redis instances, and message queues. The key is deterministic resource naming: worker-${port}, queue-agent-${id}, cache-key-prefix-${branch}. Collisions become impossible when resource identifiers embed the isolation boundary.

Managing Multiple Worktrees: Lifecycle Patterns and Cleanup

Worktrees accumulate. After three weeks of parallel development, developers end up with 20 stale worktrees consuming disk space and cluttering git worktree list output. The cleanup pattern is straightforward but requires discipline:

import { execSync } from 'child_process';
import { rmSync } from 'fs';

interface WorktreeInfo {
  path: string;
  branch: string;
  commit: string;
}

function listWorktrees(baseRepo: string): WorktreeInfo[] {
  const output = execSync('git worktree list --porcelain', {
    cwd: baseRepo,
    encoding: 'utf8'
  });

  const worktrees: WorktreeInfo[] = [];
  const lines = output.split('\n');
  let current: Partial<WorktreeInfo> = {};

  for (const line of lines) {
    if (line.startsWith('worktree ')) {
      current.path = line.replace('worktree ', '');
    } else if (line.startsWith('branch ')) {
      current.branch = line.replace('branch refs/heads/', '');
    } else if (line.startsWith('HEAD ')) {
      current.commit = line.replace('HEAD ', '');
      worktrees.push(current as WorktreeInfo);
      current = {};
    }
  }

  return worktrees;
}

function cleanupMergedWorktrees(baseRepo: string): void {
  const worktrees = listWorktrees(baseRepo);
  const merged = execSync('git branch --merged main', {
    cwd: baseRepo,
    encoding: 'utf8'
  }).split('\n').map(b => b.trim().replace('* ', ''));

  for (const wt of worktrees) {
    if (merged.includes(wt.branch)) {
      console.log(`Removing merged worktree: ${wt.branch}`);
      execSync(`git worktree remove ${wt.path}`, { cwd: baseRepo });
      execSync(`git branch -d ${wt.branch}`, { cwd: baseRepo });
    }
  }
}

Run this after every merge to main. The pattern prevents the "zombie worktree" problem where directories exist but the branches were deleted remotely. Git's worktree prune command cleans up metadata, but it doesn't remove the directories—teams need explicit filesystem cleanup.

For long-running worktrees, periodic rebasing keeps them current:

cd ../agent-api
git fetch origin
git rebase origin/main
npm install  # Update dependencies after rebase

The implication here is that worktrees aren't fire-and-forget. They require lifecycle management equivalent to long-lived feature branches. Teams that treat worktrees as ephemeral often find themselves with merge conflicts and outdated dependencies.

Managing worktree lifecycle and cleanup across multiple parallel development streams

Managing worktree lifecycle and cleanup across multiple parallel development streams

Worktrees vs Full Clones vs Docker Containers for Agent Isolation

Three patterns exist for isolating parallel AI agents. Each has specific tradeoffs that matter at scale.

Comparison of isolation strategies for parallel AI agent development

Comparison of isolation strategies for parallel AI agent development

Full clones provide maximum isolation but consume 3-5x more disk space. A 2GB repository cloned five times uses 10GB. Fetch operations pull from remote for each clone independently. The benefit is simplicity—no shared state means no coordination logic. The cost is I/O overhead when agents need to sync with upstream. Use full clones when disk space is abundant and fetch latency doesn't matter.

Docker containers isolate at the runtime level. Mount the repository as a volume, run one container per agent, and leverage Docker's filesystem layering. Containers get process isolation, network namespaces, and resource limits. The downside is orchestration complexity. Teams need Docker Compose configs, health checks, and log aggregation. Storage overhead sits between worktrees and full clones—shared base images reduce duplication, but each container maintains its own writable layer.

Worktrees optimize for disk efficiency and Git operation speed. Fetch once, and all worktrees see the new refs. Disk usage grows linearly with checked-out files, not repository size. The tradeoff is Git-level coupling—you can't check out the same branch in multiple worktrees simultaneously, and deleting a worktree requires coordination with the shared .git folder.

The decision matrix: worktrees for local development with 3-10 agents, containers for CI/CD pipelines needing strict isolation, full clones when storage is cheaper than coordination complexity. Most production systems use a hybrid—worktrees for developers, containers for agents running in cloud environments.

Context window limitations for AI agents are explored in 2 million token context windows for real web apps.

Production Patterns: From 3 Agents to N-Way Parallel Execution

Scaling from three worktrees to N requires automation and orchestration. The manual setup script breaks when N exceeds 10. Teams need dynamic worktree allocation, health monitoring, and failure recovery.

Dynamic worktree allocation and orchestration for N-way parallel agent execution

Dynamic worktree allocation and orchestration for N-way parallel agent execution

A task queue (Redis, RabbitMQ, or SQS) holds pending work items. A worktree allocator service creates worktrees on demand, assigns them to agents, and tracks lifecycle state. When an agent completes a task and merges its branch, the cleanup worker removes the worktree and returns resources to the pool.

The critical failure mode is leaked worktrees. If an agent crashes mid-task, its worktree becomes orphaned—still consuming disk space but no longer processing work. Health checks must detect this state and trigger cleanup:

interface ActiveWorktree {
  path: string;
  branch: string;
  agentId: string;
  lastHeartbeat: number;
}

function detectOrphanedWorktrees(
  active: ActiveWorktree[],
  timeoutMs: number = 300000 // 5 minutes
): string[] {
  const now = Date.now();
  return active
    .filter(wt => now - wt.lastHeartbeat > timeoutMs)
    .map(wt => wt.path);
}

Port allocation becomes dynamic. Instead of hardcoded PORT=3000, the allocator assigns a free port from a range:

function allocatePort(usedPorts: Set<number>): number {
  const minPort = 3000;
  const maxPort = 4000;

  for (let port = minPort; port <= maxPort; port++) {
    if (!usedPorts.has(port)) {
      usedPorts.add(port);
      return port;
    }
  }

  throw new Error('No available ports in range');
}

Database branching follows the same pattern. Services like Neon's API create branches programmatically. Each worktree gets a fresh database branch, runs its migrations, and merges schema changes when the task completes. The isolation extends to the data layer.

This pattern supports N-way parallelism limited only by machine resources. A 64-core server with 256GB RAM can run 50+ agents concurrently if each task is compute-bound. I/O-bound tasks (network calls, database queries) can scale to 200+ agents with careful resource tuning.

Autonomous PR workflows that integrate with this setup are detailed in AI coding agents creating autonomous PRs in 2026.

When Worktrees Aren't Enough: Combining with CI/CD and Review Workflows

Worktrees solve local parallel execution. Production systems need integration with CI/CD pipelines and code review tools. The pattern is straightforward: worktrees create branches, CI systems test them, review tools surface results.

Each worktree's branch triggers a CI run when pushed. GitHub Actions, GitLab CI, and Jenkins all support per-branch pipelines. The key is ensuring each agent's work gets independent test runs. Collisions in CI happen when multiple branches touch the same test database or shared staging environment. The solution mirrors local isolation—unique database branches, isolated preview deployments, and separate resource namespaces per CI run.

Review workflows benefit from worktree context. When Agent 1 finishes refactoring the API layer, its worktree contains the diff, test results, and build artifacts. Pull request descriptions can include worktree-specific logs, performance benchmarks from that environment, and links to preview deployments running on that branch's port.

The limitation is shared repository state. You can't test conflicting schema migrations simultaneously—one agent's migration might break another's tests even though their worktrees are isolated. The resolution is sequential integration testing on main after merges. Parallel development is local; integration verification is sequential. This tradeoff is fundamental to any parallel workflow.

That covers the essential patterns for running parallel AI agents with Git worktrees. Apply these in production and the difference will be immediate—no more file conflicts, no more crashed dev servers, and no more waiting for agents to finish before starting the next task. The isolation boundary is filesystem-level, the overhead is minimal, and the scalability is limited only by your hardware.