Git worktrees 虽然看似能为 AI 编码代理提供隔离环境,但实际存在重大安全缺陷[1]。代理可以通过 worktrees 共享的 .git 目录中的 refs、config、stash 和 hooks 等组件,突破隔离限制[1]。具体而言,攻击者可通过安装 hooks 在宿主仓库执行任意代码,或修改 git config 中的 user.email 和 user.name 篡改提交身份[1]。
使用独立 clone 作为替代方案能提供更好的隔离保障,性能成本基本相同[1]。独立 clone 和 worktrees 的创建耗时均为约 1 秒,占用空间均为 58-59 MB[1]。其中 git clone --shared 模式仅需 660 KB 的元数据,而 git clone --hardlink 则需 318 MB[1]。在无需协调的多进程写入场景下,采用独立 clone 是更安全的选择,而 worktrees 仅适用于单人在 2-3 个分支间切换的简单场景[1]。
Git worktrees, while appearing to offer isolation for multiple development branches, share critical components of the underlying repository that can be exploited by automated coding agents.[1] Specifically, worktrees provide shared access to refs in the .git directory, including refs/heads, packed-refs, the .git/config file, refs/stash, and .git/hooks.[1] This shared architecture creates significant security vulnerabilities: agents can install hooks to execute arbitrary code in the host repository, modify git configuration parameters such as user.email and user.name, and perform operations across multiple worktrees without coordination.[1]
Rather than relying on worktrees for isolation in multi-agent or untrusted execution contexts, independent repository clones provide equivalent or superior protection with comparable performance costs.[1] Testing demonstrates that both independent clones and worktrees consume approximately 58–59 MB of storage and require roughly one second to set up, making the performance argument for worktrees moot in these scenarios.[1] While git clone --shared uses only 660 KB of metadata and git clone --hardlink requires 318 MB, the standard clone approach maintains genuine isolation boundaries.[1] Worktrees remain appropriate for single-user workflows involving temporary switching between two or three branches, but independent clones are the preferable option when multiple processes operate on repositories without centralized coordination.[1]