Skip to content

Evaluate built-in worktree isolation for /exec parallel agent groups #485

Closed

Description

@admarble

Problem

When /exec spawns parallel agent groups (multiple implementation agents working simultaneously), all agents operate within the same issue worktree. If two agents in the same group edit overlapping files — or even the same file — one agent's changes can silently overwrite the other's, producing corrupted output or merge conflicts that surface only at commit time.

Current mitigation relies on the /spec phase to partition work into non-overlapping file sets per group. This works in practice (~67% parallel success rate) but is fragile: the spec author (an LLM) must correctly predict all file dependencies, and shared files like index.ts barrel exports or package.json are common collision points.

Claude Code now supports isolation: worktree in subagent definitions, which gives each agent its own copy of the repository. This could eliminate file conflicts structurally rather than relying on careful task partitioning.

Current Behavior

  • /exec parallel groups: all agents share the issue worktree at ../worktrees/feature/<issue>-<slug>/
  • Agents write to the same filesystem concurrently
  • File conflicts are detected only after agents complete (if at all)
  • ClaudeCodeDriver uses permissionMode: "bypassPermissions" — agents can write anywhere

Desired Behavior

Each parallel group agent gets an isolated worktree. After all agents in a group complete, their changes are merged back into the issue worktree. Conflicts are detected and resolved (or reported) before proceeding to the next group.

Acceptance Criteria

1. Investigation and feasibility (P0)

  • AC-1: Document how Claude Code's isolation: worktree interacts with sequant's existing worktree management (../worktrees/feature/<issue>-<slug>/)
  • AC-2: Test whether isolation: worktree can nest inside an existing worktree (the issue worktree is already a worktree — can a sub-worktree be created within it?)
  • AC-3: Document the merge-back strategy: how do isolated agent changes return to the issue worktree? Options: cherry-pick, merge, diff-apply
  • AC-4: Measure overhead: worktree creation/cleanup time for a typical repo size

2. WorktreeCreate hook integration (P0)

  • AC-5: If built-in isolation: worktree path (<repo>/.claude/worktrees/<name>/) conflicts with sequant's convention, implement a WorktreeCreate hook to customize the path
  • AC-6: Sub-worktrees for parallel agents use naming convention: ../worktrees/feature/<issue>-<slug>/.exec-agent-<N>/ (or equivalent that's clearly scoped to the parallel group)
  • AC-7: .worktreeinclude file created (or documented) to carry environment files into sub-worktrees

3. Merge-back implementation (P1)

  • AC-8: After all agents in a parallel group complete, changes are merged back into the issue worktree
  • AC-9: If merge conflicts occur, they are detected and reported with file paths and conflict markers — not silently dropped
  • AC-10: Merge-back strategy handles the common case: agents created new files (no conflict) and agents modified shared files (potential conflict)
  • AC-11: If a merge conflict cannot be auto-resolved, the /exec skill reports it and continues with the non-conflicting changes, flagging the conflict for the next iteration

4. Cleanup (P1)

  • AC-12: Sub-worktrees are removed after successful merge-back
  • AC-13: Sub-worktrees are removed on agent failure (partial results are preserved in the issue worktree if merge-back already occurred)
  • AC-14: Orphaned sub-worktrees from interrupted sessions are cleaned up by sequant's existing worktree cleanup scripts

5. Opt-in and fallback (P1)

  • AC-15: Isolation is controlled by setting: .sequant/settings.json → agents.isolateParallel: true|false (default: false — opt-in for v1)
  • AC-16: When disabled, behavior is identical to current (shared worktree)
  • AC-17: CLI flag --isolate-parallel overrides setting

6. Skill integration (P2)

  • AC-18: /exec SKILL.md parallel group section updated with isolation logic
  • AC-19: All three skill directories synced
  • AC-20: /exec logs which mode was used (shared vs. isolated) for debugging

Design Notes

Nested Worktree Question

The critical unknown: can git worktree add create a worktree rooted inside another worktree? Git documentation suggests this is supported (worktrees are just branches checked out at different paths), but edge cases around .git file resolution need testing. If nesting isn't supported, sub-worktrees would need to be siblings at the ../worktrees/ level.

Fallback: If nesting fails, use ../worktrees/exec-agents/<issue>-<slug>-agent-<N>/ as the sub-worktree path.

Merge-Back Strategy Comparison

Strategy Pros Cons
git merge Conflict detection built-in, preserves history Requires branch per agent, more git operations
diff-apply (git diff | git apply) Lightweight, no branch needed No conflict markers, fails on overlap
cherry-pick Preserves individual commits Requires commits, complex with multiple
rsync + git add Simple file copy, no git complexity No conflict detection, last-write-wins

Recommended: git merge with temporary branches. Each agent commits to its worktree's branch; merge-back uses git merge --no-ff into the issue branch. Conflicts produce standard markers that the next /exec iteration can resolve.

Interaction with Claude Code's Built-in Isolation

Two options:

  1. Use isolation: worktree in agent definition — Claude Code manages sub-worktree lifecycle. Simpler but less control over path naming and merge-back.
  2. Manage sub-worktrees in skill logic — /exec SKILL.md creates worktrees before spawning agents, passes path in prompt. More control, more complexity.

Option 2 is recommended for v1: sequant already has worktree management expertise, and merge-back logic needs custom handling that isolation: worktree auto-cleanup would interfere with.

Parallel Group Flow (With Isolation)

/exec parallel group:
  1. For each agent in group:
     a. git worktree add ../worktrees/exec-agents/<issue>-agent-<N> -b exec-agent-<N>
     b. Spawn agent with cwd set to the sub-worktree path
  2. Wait for all agents to complete
  3. For each completed agent:
     a. cd to issue worktree
     b. git merge --no-ff exec-agent-<N> (from sub-worktree)
     c. If conflict: record, continue with non-conflicting agents
     d. git worktree remove ../worktrees/exec-agents/<issue>-agent-<N>
  4. Report: N agents merged, M conflicts (if any)
  5. Proceed to next group or sequential tasks

Out of Scope

  • Isolation for /qa agents — QA agents are read-only (they run checks but don't edit code)
  • Isolation for single-agent /exec (non-parallel) — no conflict possible with one agent
  • Refactoring sequant's existing per-issue worktree management
  • Agent teams as an alternative to parallel groups

Files Affected

  • .claude/skills/exec/SKILL.md — parallel group section update
  • templates/skills/exec/SKILL.md — mirror
  • skills/exec/SKILL.md — mirror
  • src/lib/settings.ts — add agents.isolateParallel setting
  • bin/cli.ts — add --isolate-parallel flag
  • scripts/dev/cleanup-worktree.sh — handle exec-agent sub-worktree cleanup
  • .worktreeinclude — new (if env file propagation needed)

References

Activity

  1. added
    enhancement
    planned
    multi-agent
    on Apr 5, 2026
  2. admarble commented on Apr 6, 2026

    @admarble
    ContributorAuthor

    → PROCEED — Worktree isolation eval for /exec parallel groups, clear ACs

    spec → exec → qa · 20 ACs · -q (AC-1–AC-4 are investigation/feasibility — may pivot design)

    Chain after #483 (settings.ts, bin/cli.ts overlap)

  3. admarble commented on Apr 7, 2026

    @admarble
    ContributorAuthor

    Spec Plan — #485: Worktree Isolation for /exec Parallel Agent Groups

    AC Checklist (20 items + 3 derived)

    Investigation & Feasibility (P0)

    • AC-1: Document isolation: worktree interaction with sequant worktree management
    • AC-2: Test nested worktree feasibility (worktree inside worktree)
    • AC-3: Document merge-back strategy (git merge vs diff-apply vs cherry-pick)
    • AC-4: Measure worktree creation/cleanup overhead

    WorktreeCreate Hook (P0)

    • AC-5: Hook/customization for sub-worktree path if built-in conflicts
    • AC-6: Naming convention: ../worktrees/exec-agents/<issue>-<slug>-agent-<N>/
    • AC-7: .worktreeinclude or env file propagation to sub-worktrees

    Merge-back (P1)

    • AC-8: Merge changes back to issue worktree after parallel group completes
    • AC-9: Detect and report merge conflicts with file paths and markers
    • AC-10: Handle new files (no conflict) + modified shared files (potential conflict)
    • AC-11: On unresolvable conflict, continue with non-conflicting changes, flag conflict

    Cleanup (P1)

    • AC-12: Remove sub-worktrees after successful merge-back
    • AC-13: Remove sub-worktrees on agent failure (preserve already-merged changes)
    • AC-14: Orphaned sub-worktrees cleaned by existing cleanup scripts

    Opt-in & Fallback (P1)

    • AC-15: agents.isolateParallel setting in .sequant/settings.json (default: false)
    • AC-16: When disabled, behavior identical to current (shared worktree)
    • AC-17: CLI flag --isolate-parallel overrides setting

    Skill Integration (P2)

    • AC-18: /exec SKILL.md parallel group section updated
    • AC-19: All three skill directories synced
    • AC-20: Log which mode was used (shared vs. isolated)

    Derived

    • AC-21: Fall back to shared mode with warning if sub-worktree creation fails
    • AC-22: Unit tests for worktree-isolation.ts functions
    • AC-23: Investigation documented in docs/reference/worktree-isolation.md

    Implementation Plan

    Phase 1 — Investigation (AC-1–4): Test nested worktrees, benchmark overhead, evaluate merge strategies, document findings.

    Phase 2 — Settings & CLI (AC-15–17): Add isolateParallel to AgentSettings in settings.ts, wire --isolate-parallel flag in bin/cli.ts.

    Phase 3 — Core (AC-5–11, AC-21): Create src/lib/worktree-isolation.ts with sub-worktree creation, env file propagation, merge-back via git merge --no-ff, conflict detection, and fallback to shared mode.

    Phase 4 — Cleanup (AC-12–14): Post-merge cleanup, failure cleanup, orphan detection in cleanup-worktree.sh.

    Phase 5 — Skill Integration (AC-18–20): Update exec SKILL.md with conditional isolation logic, sync all 3 directories, add mode logging.

    Design Decisions

    Decision Choice Rationale
    Worktree management Sequant-managed (Option 2) Need control over lifecycle for merge-back; Claude Code auto-cleanup would delete before merge
    Merge strategy git merge --no-ff Built-in conflict detection, preserves history, standard markers
    Sub-worktree path Sibling at ../worktrees/exec-agents/ Safer than nesting; investigation (AC-2) may validate nesting
    Default Opt-in (false) Conservative for v1; existing parallel behavior unchanged

    Verification Methods

    AC Group Primary Method
    Investigation (1-4) Manual Test + Integration Test
    Settings/CLI (15-17) Unit Test + Integration Test
    Core (5-11) Integration Test
    Cleanup (12-14) Integration Test
    Skill integration (18-20) Manual Test

    Open Questions

    1. Nested worktrees: Can git worktree add nest inside another worktree? Phase 1 will answer; fallback is sibling path.
    2. node_modules sharing: Symlink vs fresh install for sub-worktrees. Symlink preferred for speed.
    3. Add user-configurable agent overrides and graceful maxTurns handling #483 overlap: Both touch settings.ts/bin/cli.ts. Proceed; rebase after Add user-configurable agent overrides and graceful maxTurns handling #483 if needed.

    Recommended Workflow

    Phases: spec → exec → qa
    Quality Loop: enabled (20 ACs, scope concerns)

  4. added
    complex
    on Apr 7, 2026
  5. added a commit that references this issue on Apr 7, 2026
  6. admarble commented on Apr 7, 2026

    @admarble
    ContributorAuthor

    /fullsolve Complete

    Issue: #485
    Status: READY_FOR_MERGE

    Summary

    • AC: 23/23 met (20 original + 3 derived)
    • Tests: 156 passed (19 new for worktree-isolation module)
    • Build: Pass | Lint: Pass (0 errors)
    • QA: All checks passed

    Key Changes

    • New src/lib/worktree-isolation.ts — sub-worktree create, merge-back, cleanup
    • agents.isolateParallel setting + --isolate-parallel CLI flag
    • /exec SKILL.md updated with isolation logic (3 directories synced)
    • cleanup-worktree.sh handles orphaned sub-worktrees
    • docs/reference/worktree-isolation.md — investigation + architecture docs

    Investigation Results

    • Nested worktrees work inside existing worktrees
    • Creation: ~400ms, node_modules symlink: ~13ms, removal: ~130ms
    • git merge --no-ff provides built-in conflict detection with standard markers

    Iterations

    Phase Iterations Status
    Spec 1/1 Complete
    Exec 1/1 Complete
    Test Skipped No UI labels
    QA 1/2 Complete

    PR: #500


    Ready for human review and merge.

  7. added a commit that references this issue on Apr 7, 2026
  8. added a commit that references this issue on Apr 7, 2026
  9. admarble commented on Apr 8, 2026

    @admarble
    ContributorAuthor

    Documentation Generated

    File: docs/features/worktree-isolation.md

    Sections Included:

    • Prerequisites (git version, parallel groups, sequant init)
    • Setup (CLI flag and settings.json)
    • What to Expect (timing, lifecycle, behavior when disabled)
    • Environment Files (.worktreeinclude usage)
    • Conflict Handling (scenario table + resolution flow)
    • Cleanup (automatic + manual)
    • Troubleshooting (creation failure, repeated conflicts, orphaned dirs)

    Note: The existing docs/reference/worktree-isolation.md covers internals (investigation results, merge strategy comparison, API reference). This new doc covers the user journey.

    Next Steps:

    1. Review generated documentation for accuracy
    2. Commit and push to main

    Ready to merge!

  10. added a commit that references this issue on Apr 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    complexenhancementmulti-agentplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions