Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(daemon): worktree_pool mode for local_directory (MUL-3483) (#4986)
Multica Eve7bb8076ed08f
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex e3052fa3fd..8fbafac536 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -224,6 +224,20 @@ type Daemon struct {// waits. See MUL-2663.localPathLocks *LocalPathLocker+ // worktreePool implements the MUL-3483 worktree_pool mode. It only+ // participates for local_directory resources whose ref opts into+ // mode="worktree_pool"; in_place tasks bypass it entirely and keep+ // the shared-tree + path-mutex semantics unchanged.+ worktreePool *WorktreePoolManager++ // localLeases stashes the resolved workdir a task should execute in+ // when the local_directory ref uses worktree_pool. handleTask+ // populates the entry after Acquire succeeds and clears it in the+ // same release closure; runTask reads it to route+ // execenv.PrepareParams.LocalWorkDir at the newly-allocated+ // worktree rather than the base local_path. Keyed by task ID.+ localLeases sync.Map // map[string]localDirectoryLease+// bgSyncs tracks background goroutines started by registerTaskRepos so// callers (notably tests using t.TempDir-backed cache roots) can wait for// them to drain before tearing the daemon down. Without this the bg@@ -266,6 +280,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {wsHBLastAck: make(map[string]time.Time),activeEnvRoots: make(map[string]int),localPathLocks: NewLocalPathLocker(),+ worktreePool: NewWorktreePoolManager(logger),runtimeGoneInflight: make(map[string]struct{}),reregisterNextAttempt: make(map[string]time.Time),reregisterLastCompletedAt: make(map[string]time.Time),@@ -3028,6 +3043,31 @@ func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Tasreturn nil, true}+ switch assignment.Ref.modeOrDefault() {+ case localDirectoryModeWorktreePool:+ return d.acquireLocalDirectoryWorktreePool(ctx, task, assignment, taskLog)+ default:+ return d.acquireLocalDirectoryInPlace(ctx, task, assignment, taskLog)+ }+}++// acquireLocalDirectoryInPlace is the pre-MUL-3483 code path: take the+// per-realpath mutex, mark the task waiting_local_directory on contention,+// return a release func that unlocks. Kept as the default so any user+// (self-host or SaaS) whose ref doesn't opt into worktree_pool sees zero+// behavioural change from this change set.+func (d *Daemon) acquireLocalDirectoryInPlace(ctx context.Context, task Task, assignment *localDirectoryAssignment, taskLog *slog.Logger) (release func(), abort bool) {+ // Publish the lease so runTask feeds the same AbsPath into+ // execenv.PrepareParams.LocalWorkDir, unified with the worktree_pool+ // branch even though the value here is unchanged.+ d.localLeases.Store(task.ID, localDirectoryLease{+ Mode: localDirectoryModeInPlace,+ WorkDir: assignment.AbsPath,+ })+ clearLease := func() {+ d.localLeases.Delete(task.ID)+ }+// While the lock is contended the daemon would otherwise sit blocked on// the path mutex with no signal back from the server — the main// per-task watcher only starts after the lock is acquired. If the user@@ -3084,8 +3124,9 @@ func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Tas}()})}- release, err = d.localPathLocks.Acquire(waitCtx, assignment.RealPath, task.ID, onWait)+ unlock, err := d.localPathLocks.Acquire(waitCtx, assignment.RealPath, task.ID, onWait)if err != nil {+ clearLease()// If the wait was cut short because the server finalized the task// (terminal state) or deleted the row, the row is already in a// terminal state — return silently the same way the run-phase poller@@ -3110,7 +3151,156 @@ func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Tasreturn nil, true}taskLog.Info("local_directory: lock acquired")- return release, false+ return func() {+ unlock()+ clearLease()+ }, false+}++// acquireLocalDirectoryWorktreePool implements the MUL-3483 worktree_pool+// binding: instead of taking a per-realpath mutex on the shared tree, ask+// the pool manager for a fresh `git worktree` under the ref's pool_root+// and pin the agent to that isolated directory. Two worker tasks bound+// to the same local_directory can then run truly in parallel while the+// pool manager keeps `git worktree add/remove/prune` serialised through+// its per-repo mutex.+//+// When the pool is saturated (MaxParallel already in use) we park the+// task in waiting_local_directory with a structured wait_reason, retry+// on a short interval, and abort if the server cancels the row in the+// meantime. The retry cadence matches the existing path-mutex wait so+// operators see consistent behaviour across the two modes.+func (d *Daemon) acquireLocalDirectoryWorktreePool(ctx context.Context, task Task, assignment *localDirectoryAssignment, taskLog *slog.Logger) (release func(), abort bool) {+ // Reject before the retry loop if the base isn't actually a git+ // worktree — the pool has nothing to hand out otherwise, and the+ // error is exactly the same on every attempt.+ if !isGitWorkTree(ctx, assignment.AbsPath) {+ msg := fmt.Sprintf("local_directory: worktree_pool mode requires %q to be a git working tree", assignment.AbsPath)+ taskLog.Error("local_directory: base path is not a git worktree", "path", assignment.AbsPath)+ if failErr := d.client.FailTask(ctx, task.ID, msg, "", "", "local_directory_error"); failErr != nil {+ taskLog.Error("fail task after worktree_pool base check", "error", failErr)+ }+ return nil, true+ }++ poolRoot := strings.TrimSpace(assignment.Ref.PoolRoot)+ if poolRoot == "" {+ poolRoot = defaultWorktreePoolRoot(assignment.RealPath)+ }+ maxParallel := assignment.Ref.maxParallelOrDefault()+ taskLog = taskLog.With("mode", localDirectoryModeWorktreePool, "pool_root", poolRoot, "max_parallel", maxParallel)++ // Set up the cancellation watcher the same way the in_place path does+ // so a server-side cancel during a `pool_saturated` wait aborts the+ // retry loop promptly instead of parking for the full pollInterval.+ waitCtx, waitCancel := context.WithCancel(ctx)+ defer waitCancel()+ pollInterval := d.cancelPollInterval+ if pollInterval == 0 {+ pollInterval = 5 * time.Second+ }+ var (+ watcherOnce sync.Once+ prepareLeaseOnce sync.Once+ cancelledByPoll <-chan struct{}+ stopPrepareLease func()+ )+ defer func() {+ if stopPrepareLease != nil {+ stopPrepareLease()+ }+ }()+ startWatcher := func() {+ watcherOnce.Do(func() {+ cancelledByPoll = d.watchTaskCancellation(waitCtx, task.ID, pollInterval, taskLog)+ go func() {+ select {+ case <-cancelledByPoll:+ waitCancel()+ case <-waitCtx.Done():+ }+ }()+ })+ }+ startPrepareLease := func() {+ prepareLeaseOnce.Do(func() {+ stopPrepareLease = d.startTaskPrepareLeaseExtender(waitCtx, task, taskLog)+ })+ }++ // Retry Acquire while the pool is saturated. Every other error path+ // bubbles out immediately (submodule refusal, git worktree add+ // failure, disk-full, etc.) since a retry would just repeat the+ // same failure.+ for {+ alloc, err := d.worktreePool.Acquire(waitCtx, assignment.RealPath, poolRoot, maxParallel, task.ID)+ if err == nil {+ taskLog.Info("worktree_pool: allocated", "workdir", alloc.WorkDir, "branch", alloc.Branch)+ d.localLeases.Store(task.ID, localDirectoryLease{+ Mode: localDirectoryModeWorktreePool,+ WorkDir: alloc.WorkDir,+ Branch: alloc.Branch,+ })+ return func() {+ alloc.Release()+ d.localLeases.Delete(task.ID)+ }, false+ }++ var saturated *PoolSaturatedError+ if !errors.As(err, &saturated) {+ taskLog.Error("worktree_pool: acquire failed", "error", err)+ failureReason := "local_directory_error"+ if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {+ failureReason = "cancelled"+ }+ if failErr := d.client.FailTask(ctx, task.ID, err.Error(), "", "", failureReason); failErr != nil {+ taskLog.Error("fail task after worktree_pool acquire error", "error", failErr)+ }+ return nil, true+ }++ // Saturation: publish a structured wait_reason, then park until+ // either a slot frees up or the server cancels the row. We reuse+ // the pollInterval as the retry cadence so the wait behaves the+ // same as the in_place path-mutex wait from the operator's view.+ reason := fmt.Sprintf("local_directory worktree_pool saturated (%d/%d) on %s", len(saturated.Holders), saturated.MaxParallel, assignment.AbsPath)+ if len(saturated.Holders) > 0 {+ short := make([]string, 0, len(saturated.Holders))+ for _, h := range saturated.Holders {+ short = append(short, shortID(h))+ }+ reason = fmt.Sprintf("%s (holders: %s)", reason, strings.Join(short, ", "))+ }+ taskLog.Info("worktree_pool: pool saturated, waiting", "in_use", len(saturated.Holders), "max_parallel", saturated.MaxParallel)+ if waitErr := d.client.MarkTaskWaitingLocalDirectory(ctx, task.ID, reason); waitErr != nil {+ taskLog.Warn("worktree_pool: mark waiting status failed", "error", waitErr)+ }+ startPrepareLease()+ startWatcher()++ select {+ case <-waitCtx.Done():+ // Either the outer ctx was cancelled (daemon shutdown) or the+ // watcher fired (row went terminal / was deleted).+ if cancelledByPoll != nil {+ select {+ case <-cancelledByPoll:+ taskLog.Info("worktree_pool: wait aborted by server-side terminal state")+ return nil, true+ default:+ }+ }+ taskLog.Warn("worktree_pool: wait cancelled", "error", waitCtx.Err())+ failureReason := "cancelled"+ if failErr := d.client.FailTask(ctx, task.ID, fmt.Sprintf("local_directory worktree_pool wait cancelled: %s", waitCtx.Err().Error()), "", "", failureReason); failErr != nil {+ taskLog.Error("fail task after worktree_pool wait cancel", "error", failErr)+ }+ return nil, true+ case <-time.After(pollInterval):+ // Loop back and try Acquire again.+ }+ }}// reportTaskResult writes the final task disposition back to the server.@@ -3572,6 +3762,18 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// LocalWorkDir into execenv. handleTask already validated + locked the// path for worker tasks; leader tasks intentionally skip the assignment.localAssignment, _ := localDirectoryAssignmentForTask(task, d.cfg.DaemonID)+ // The lease is the source of truth for WorkDir when handleTask has+ // finished acquireLocalDirectoryLockIfNeeded — it captures either the+ // in_place AbsPath or the freshly allocated worktree_pool path so+ // runTask never has to re-derive the worktree_pool selection here.+ // The nil-check gates on both leader tasks (which skip Acquire) and+ // tests that call runTask directly without going through handleTask.+ var localLease *localDirectoryLease+ if raw, ok := d.localLeases.Load(task.ID); ok {+ if l, ok := raw.(localDirectoryLease); ok {+ localLease = &l+ }+ }// Reuse intentionally skipped for local_directory tasks: the prior// WorkDir is the user's own path (always present) but the reuse path// loses the envRoot association the GC loop needs, and re-running@@ -3617,7 +3819,16 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iTask: taskCtx,}if localAssignment != nil {- prepParams.LocalWorkDir = localAssignment.AbsPath+ // Prefer the lease publish from handleTask: it may point at a+ // pool worktree that was allocated after assignment resolution+ // (worktree_pool mode). Fall back to the assignment's AbsPath+ // when no lease exists — that covers the leader-task path and+ // direct-runTask test setups that skip Acquire.+ if localLease != nil && localLease.WorkDir != "" {+ prepParams.LocalWorkDir = localLease.WorkDir+ } else {+ prepParams.LocalWorkDir = localAssignment.AbsPath+ }}env, err = execenv.Prepare(prepParams, d.logger)if err != nil {diff --git a/server/internal/daemon/local_directory.go b/server/internal/daemon/local_directory.goindex 6e78e4266e..0556e26ff7 100644--- a/server/internal/daemon/local_directory.go+++ b/server/internal/daemon/local_directory.go@@ -19,13 +19,83 @@ import (// constant — keep in sync if the type string is ever renamed.const localDirectoryResourceType = "local_directory"+// localDirectoryModeInPlace / localDirectoryModeWorktreePool mirror the+// server-side mode strings. Kept as a private, deliberately-duplicated pair+// to avoid an import cycle between the daemon and the handler package —+// this constant list is one line, and if the server ever renames either+// string the daemon must be updated in lockstep anyway.+const (+ localDirectoryModeInPlace = "in_place"+ localDirectoryModeWorktreePool = "worktree_pool"+)++// defaultWorktreePoolMaxParallel is the fallback max_parallel when the+// resource_ref left the field zero. Four covers a typical squad (1 leader+// + 3 workers) without opening up the machine to unbounded worktree fan-out.+// The user can raise it by setting max_parallel explicitly on the ref.+const defaultWorktreePoolMaxParallel = 4+// localDirectoryRef mirrors the server-side ref shape for local_directory// project resources. Defined locally so the daemon does not have to import// the server handler package.+//+// Mode + PoolRoot + MaxParallel are the MUL-3483 worktree_pool opt-in+// fields. They are omitted (zero-valued) for pre-existing rows and for+// clients that never learnt about them, in which case the daemon behaves+// exactly as before — one shared working tree, one path mutex.type localDirectoryRef struct {- LocalPath string `json:"local_path"`- DaemonID string `json:"daemon_id"`- Label string `json:"label,omitempty"`+ LocalPath string `json:"local_path"`+ DaemonID string `json:"daemon_id"`+ Label string `json:"label,omitempty"`+ Mode string `json:"mode,omitempty"`+ PoolRoot string `json:"pool_root,omitempty"`+ MaxParallel int `json:"max_parallel,omitempty"`+}++// modeOrDefault returns the mode string with the empty default folded to+// "in_place". Callers should always route through this so a `switch` on+// the return value never needs a fall-through arm.+func (r localDirectoryRef) modeOrDefault() string {+ m := strings.TrimSpace(r.Mode)+ if m == "" {+ return localDirectoryModeInPlace+ }+ return m+}++// maxParallelOrDefault applies defaultWorktreePoolMaxParallel to zero-valued+// requests. Negative values shouldn't reach the daemon (server-side+// validation rejects them) — clamp them to the default here for safety+// so a bad row can't make the pool refuse every task.+func (r localDirectoryRef) maxParallelOrDefault() int {+ if r.MaxParallel <= 0 {+ return defaultWorktreePoolMaxParallel+ }+ return r.MaxParallel+}++// localDirectoryLease is the runtime view of a task's local_directory+// binding, published by acquireLocalDirectoryLockIfNeeded so runTask+// (and the GC meta writer) can pick the correct WorkDir without+// re-computing pool allocation. Mode mirrors the ref's mode; WorkDir is+// the path the agent should actually execute inside — for in_place this+// is the ref's LocalPath, for worktree_pool it is the freshly allocated+// worktree.+type localDirectoryLease struct {+ Mode string+ WorkDir string+ Branch string // non-empty for worktree_pool mode; the branch git created+}++// defaultWorktreePoolRoot returns the fallback pool_root for the given+// base repo when the ref left the field empty. Keeping the default under+// a daemon-managed hidden directory (rather than inside the user's repo)+// stops pool worktrees from polluting `git status` on the base tree and+// keeps them out of the way when the user manually cleans up.+func defaultWorktreePoolRoot(base string) string {+ // filepath.Join is safe on both POSIX and Windows; the ".multica-worktrees"+ // name mirrors "multica" branding used elsewhere in agent workdirs.+ return filepath.Join(filepath.Dir(base), ".multica-worktrees", filepath.Base(base))}// localDirectoryAssignment is the resolved view of a task's local_directorydiff --git a/server/internal/daemon/local_directory_test.go b/server/internal/daemon/local_directory_test.goindex a6d1117182..784e598af5 100644--- a/server/internal/daemon/local_directory_test.go+++ b/server/internal/daemon/local_directory_test.go@@ -631,3 +631,236 @@ func TestAcquireLocalDirectoryLock_CancelDuringWait(t *testing.T) {t.Errorf("wait-local-directory calls = %d, want 1", got)}}+++// TestLocalDirectoryRefModeDefaults pins the daemon-side helpers so a+// missing mode / max_parallel silently reads as in_place / the default,+// keeping backwards compatibility with rows written before MUL-3483.+func TestLocalDirectoryRefModeDefaults(t *testing.T) {+ cases := []struct {+ name string+ ref localDirectoryRef+ mode string+ max int+ }{+ {"empty mode → in_place", localDirectoryRef{}, "in_place", defaultWorktreePoolMaxParallel},+ {"explicit in_place", localDirectoryRef{Mode: "in_place"}, "in_place", defaultWorktreePoolMaxParallel},+ {"worktree_pool", localDirectoryRef{Mode: "worktree_pool"}, "worktree_pool", defaultWorktreePoolMaxParallel},+ {"custom max", localDirectoryRef{Mode: "worktree_pool", MaxParallel: 8}, "worktree_pool", 8},+ {"negative max clamped", localDirectoryRef{Mode: "worktree_pool", MaxParallel: -1}, "worktree_pool", defaultWorktreePoolMaxParallel},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := tc.ref.modeOrDefault(); got != tc.mode {+ t.Errorf("modeOrDefault = %q, want %q", got, tc.mode)+ }+ if got := tc.ref.maxParallelOrDefault(); got != tc.max {+ t.Errorf("maxParallelOrDefault = %d, want %d", got, tc.max)+ }+ })+ }+}++// TestDefaultWorktreePoolRoot pins the fallback path we compose when the+// ref left pool_root blank. Placing the pool alongside the base repo+// (rather than inside it) prevents pool worktrees from ever showing up+// in the parent's `git status`.+func TestDefaultWorktreePoolRoot(t *testing.T) {+ got := defaultWorktreePoolRoot("/home/u/code/proj")+ want := filepath.Join("/home/u/code", ".multica-worktrees", "proj")+ if got != want {+ t.Errorf("defaultWorktreePoolRoot = %q, want %q", got, want)+ }+}+++// TestAcquireLocalDirectory_WorktreePoolPublishesLease is the plumbing+// regression guard flagged in the PR #4986 review: acquire the pool+// mode against a real git repo, verify the lease published to+// `d.localLeases` matches the freshly allocated worktree (so `runTask`+// feeds the pool path — NOT the base path — into+// `execenv.PrepareParams.LocalWorkDir`), and confirm release clears the+// lease along with the on-disk worktree.+//+// The subtle-but-important contract this test pins:+//+// 1. runTask reads the lease via `d.localLeases.Load(task.ID)`;+// 2. It uses `lease.WorkDir` as `prepParams.LocalWorkDir`;+// 3. A future refactor that drops the Store call, mistypes the key,+// or swaps in the base assignment.AbsPath would leave the agent+// running in the shared tree even though a worktree was created —+// silently defeating the whole point of worktree_pool mode. This+// test catches all three regressions in one shot.+func TestAcquireLocalDirectory_WorktreePoolPublishesLease(t *testing.T) {+ // A real git repo is required — `git worktree add` refuses+ // against a non-repo path, and validating the lease shape means+ // we have to actually allocate. initGitRepo skips the test+ // gracefully when git is missing from PATH.+ base := t.TempDir()+ initGitRepo(t, base)++ const daemonID = "d-worktree-pool"+ poolRoot := t.TempDir()+ ref := localDirectoryRef{+ LocalPath: base,+ DaemonID: daemonID,+ Mode: localDirectoryModeWorktreePool,+ PoolRoot: poolRoot,+ MaxParallel: 4,+ }+ raw, err := json.Marshal(ref)+ if err != nil {+ t.Fatalf("marshal ref: %v", err)+ }+ resources := []ProjectResourceData{{+ ID: "r-wp",+ ResourceType: localDirectoryResourceType,+ ResourceRef: raw,+ }}+ const taskID = "task-lease-plumbing"+ task := Task{ID: taskID, ProjectResources: resources}++ d := &Daemon{+ cfg: Config{DaemonID: daemonID},+ client: newLeaseTestClient(),+ localPathLocks: NewLocalPathLocker(),+ worktreePool: NewWorktreePoolManager(discardLogger()),+ logger: slog.Default(),+ cancelPollInterval: 50 * time.Millisecond,+ }++ // Pre-condition: no lease yet.+ if _, ok := d.localLeases.Load(taskID); ok {+ t.Fatal("lease unexpectedly present before Acquire")+ }++ release, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), task, slog.Default())+ if abort {+ t.Fatal("Acquire aborted unexpectedly")+ }+ if release == nil {+ t.Fatal("Acquire returned nil release")+ }++ // Contract 1: lease is present under the task ID.+ raw2, ok := d.localLeases.Load(taskID)+ if !ok {+ t.Fatal("lease missing after Acquire — runTask would fall back to base path")+ }+ lease, ok := raw2.(localDirectoryLease)+ if !ok {+ t.Fatalf("lease has wrong type: %T", raw2)+ }++ // Contract 2: mode is worktree_pool so downstream branching+ // (result reporting / GC meta) can tell them apart.+ if lease.Mode != localDirectoryModeWorktreePool {+ t.Errorf("lease.Mode = %q, want %q", lease.Mode, localDirectoryModeWorktreePool)+ }++ // Contract 3: WorkDir points at a fresh directory UNDER pool_root+ // (not at the base repo). This is the exact value runTask feeds+ // into execenv.PrepareParams.LocalWorkDir — see daemon.go's+ // `if localLease != nil && localLease.WorkDir != ""` branch.+ if lease.WorkDir == "" {+ t.Fatal("lease.WorkDir empty — runTask would fall back to base path")+ }+ if lease.WorkDir == base {+ t.Fatalf("lease.WorkDir == base %q (pool mode collapsed to in_place)", base)+ }+ if rel, err := filepath.Rel(poolRoot, lease.WorkDir); err != nil || rel == "" || rel == "." || strings.HasPrefix(rel, "..") {+ t.Fatalf("lease.WorkDir %q is not under pool_root %q (rel=%q, err=%v)", lease.WorkDir, poolRoot, rel, err)+ }+ if _, err := os.Stat(lease.WorkDir); err != nil {+ t.Fatalf("lease.WorkDir %q does not exist on disk: %v", lease.WorkDir, err)+ }++ // Contract 4: branch matches multica/<task-uuid> — pinned here so+ // a rename in the pool manager can't drift silently from what the+ // server-side CompleteTask flow may want to inspect later.+ if want := "multica/" + taskID; lease.Branch != want {+ t.Errorf("lease.Branch = %q, want %q", lease.Branch, want)+ }++ release()++ // Post-condition: lease cleared, worktree removed (clean tree,+ // no dirty files means clean-remove path fires).+ if _, ok := d.localLeases.Load(taskID); ok {+ t.Fatal("lease unexpectedly still present after release")+ }+ if _, err := os.Stat(lease.WorkDir); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("worktree %q not removed after release (stat err=%v)", lease.WorkDir, err)+ }+}++// TestAcquireLocalDirectory_InPlaceAlsoPublishesLease covers the paired+// contract for the default mode: even though in_place doesn't change+// what runTask fed to LocalWorkDir historically, publishing a lease+// keyed by task ID unifies the runTask lookup path and prevents a+// future refactor from special-casing one mode over the other. Pinning+// it here means anyone editing acquireLocalDirectoryInPlace who forgets+// the Store call will fail this test rather than silently break the+// runTask branch that reads the map.+func TestAcquireLocalDirectory_InPlaceAlsoPublishesLease(t *testing.T) {+ const daemonID = "d-in-place"+ tmp := t.TempDir()+ ref := localDirectoryRef{LocalPath: tmp, DaemonID: daemonID}+ raw, err := json.Marshal(ref)+ if err != nil {+ t.Fatalf("marshal ref: %v", err)+ }+ resources := []ProjectResourceData{{+ ID: "r-inplace",+ ResourceType: localDirectoryResourceType,+ ResourceRef: raw,+ }}+ const taskID = "task-in-place-plumbing"+ task := Task{ID: taskID, ProjectResources: resources}++ d := &Daemon{+ cfg: Config{DaemonID: daemonID},+ client: newLeaseTestClient(),+ localPathLocks: NewLocalPathLocker(),+ worktreePool: NewWorktreePoolManager(discardLogger()),+ logger: slog.Default(),+ cancelPollInterval: 50 * time.Millisecond,+ }+ release, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), task, slog.Default())+ if abort {+ t.Fatal("Acquire aborted unexpectedly")+ }+ if release == nil {+ t.Fatal("Acquire returned nil release")+ }+ defer release()++ raw2, ok := d.localLeases.Load(taskID)+ if !ok {+ t.Fatal("lease missing after in_place Acquire")+ }+ lease := raw2.(localDirectoryLease)+ if lease.Mode != localDirectoryModeInPlace {+ t.Errorf("lease.Mode = %q, want %q", lease.Mode, localDirectoryModeInPlace)+ }+ if lease.WorkDir != filepath.Clean(tmp) {+ t.Errorf("lease.WorkDir = %q, want %q (base path)", lease.WorkDir, filepath.Clean(tmp))+ }+ if lease.Branch != "" {+ t.Errorf("lease.Branch = %q, want empty for in_place mode", lease.Branch)+ }+}++// newLeaseTestClient stubs the daemon Client just enough for+// acquireLocalDirectory paths to run without a live server. Only the+// endpoints acquire may hit on the fast paths under test are wired up;+// anything else on the client remains zero-valued and will panic if the+// test ever expands into a code path that touches it (that's a good+// signal to add an explicit stub).+func newLeaseTestClient() *Client {+ // The Acquire fast path in either mode does NOT need to talk to+ // the server (no wait, no cancel poll, no MarkTaskWaitingLocalDirectory).+ // Point the client at a placeholder URL so any accidental HTTP dial+ // fails fast rather than blocking test cleanup.+ return NewClient("http://127.0.0.1:0")+}diff --git a/server/internal/daemon/worktree_pool.go b/server/internal/daemon/worktree_pool.gonew file mode 100644index 0000000000..7383ae8cec--- /dev/null+++ b/server/internal/daemon/worktree_pool.go@@ -0,0 +1,472 @@+package daemon++import (+ "context"+ "errors"+ "fmt"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+ "sync"+ "time"+)++// WorktreePoolManager allocates per-task `git worktree` checkouts under a+// pool root so multiple agent tasks bound to the same local_directory can+// run in parallel instead of serialising on the shared working tree.+//+// Contract (MUL-3483 MVP):+//+// - The pool is opt-in via `local_directory.mode = "worktree_pool"`.+// When the ref stays on the default in_place mode the manager is+// unused and the daemon retains the historical single-tree semantics.+// - Every `git worktree add/remove/prune/submodule` invocation for a+// given base repo is serialised through a per-repo mutex so+// concurrent worker tasks never race on `.git/config.lock`+// (Anthropic hit the same class of bug — claude-code#34645 — and+// also settled on an in-process queue as the fix).+// - Slots are counted by live leases rather than by inspecting+// `git worktree list`, so a task that crashes without releasing does+// not leak a slot forever: the daemon-crash case is handled by+// `git worktree prune` on the next allocation attempt, and the+// in-memory count is authoritative for the running daemon.+// - Repos that ship initialised submodules are refused up front. The+// BUGS section of git-worktree(1) is explicit that multi-checkout+// support for superprojects is incomplete, and the shared+// `$GIT_COMMON_DIR/config` writes from `git submodule` would still+// bottleneck the pool anyway. Refusing early is friendlier than+// surfacing a torn worktree once the agent has started running.+// - Dirty worktrees are never `--force` removed. If the agent left+// uncommitted changes behind we keep the directory (marking the+// lease with the path so callers can surface it to the user) and+// let the next `git worktree prune` reap the metadata once the+// directory is manually deleted. Losing user code because of an+// over-eager cleanup is the exact failure mode Anthropic reported+// in claude-code#55724, and it must never regress here.+type WorktreePoolManager struct {+ logger *slog.Logger++ // repoMu is the per-repo git-metadata mutex. The key is the+ // symlink-resolved base path (canonical form the underlying+ // `.git/worktrees` shares) so two ref rows pointing at the same tree+ // through different symlink paths collapse to one lock.+ repoMu sync.Mutex+ repoMutex map[string]*sync.Mutex+ repoLeases map[string]*repoPoolState++ // clock is injected for tests; production always uses time.Now.+ clock func() time.Time+}++// repoPoolState tracks the leases outstanding for a single base repo. The+// tasks slice is a debug aid — the count is what enforces MaxParallel.+// A slice is fine at pool sizes users would actually configure (single+// digits); if we ever grow to hundreds of concurrent leases per pool we'd+// switch to a set, but the linear scan is simpler here and shows up on+// hot paths only during acquire.+type repoPoolState struct {+ leases []poolLease+}++// poolLease is the live view of a single allocated worktree. It survives+// only inside the manager's map — the caller receives the Path via the+// return of Acquire and a release func that removes the lease on unlock.+type poolLease struct {+ TaskID string+ Path string // canonical worktree path (used for `git worktree remove`)+ RealPath string // symlink-resolved form; matches what LocalPathLocker keys on+ Branch string+ Acquired time.Time+}++// PoolAllocation is what Acquire hands back to the daemon. WorkDir is the+// path the agent should run inside; RealPath is what the daemon must feed+// to LocalPathLocker so two paths that alias the same on-disk tree still+// serialise. Release must be invoked exactly once (deferred is safe).+type PoolAllocation struct {+ WorkDir string+ RealPath string+ Branch string+ Release func()+}++// errPoolSaturated is a sentinel returned by Acquire when the base repo+// already has MaxParallel leases outstanding. Callers unwrap it to build+// the wait_reason hint (holders list). The variable form is used with+// errors.Is; the concrete PoolSaturatedError carries the holder metadata.+var errPoolSaturated = errors.New("worktree pool saturated")++// PoolSaturatedError is returned when a request would exceed MaxParallel.+// The Holders slice is a snapshot of the live lease tasks so the caller+// can render a "waiting for tasks A, B, C" hint in the UI without another+// round trip.+type PoolSaturatedError struct {+ BasePath string+ MaxParallel int+ Holders []string+}++func (e *PoolSaturatedError) Error() string {+ return fmt.Sprintf("worktree pool saturated (%d/%d) for %s", len(e.Holders), e.MaxParallel, e.BasePath)+}+func (e *PoolSaturatedError) Unwrap() error { return errPoolSaturated }++// NewWorktreePoolManager returns a ready-to-use manager. Safe for+// concurrent use across every daemon slot.+func NewWorktreePoolManager(logger *slog.Logger) *WorktreePoolManager {+ if logger == nil {+ logger = slog.Default()+ }+ return &WorktreePoolManager{+ logger: logger.With("component", "worktree_pool"),+ repoMutex: make(map[string]*sync.Mutex),+ repoLeases: make(map[string]*repoPoolState),+ clock: time.Now,+ }+}++// Acquire allocates a fresh worktree for taskID under the base repo's pool+// root. It runs entirely under the per-repo git-metadata mutex so callers+// never race on `.git/config.lock` or on the in-memory lease count.+//+// The flow:+//+// 1. Take the per-repo mutex.+// 2. Refuse repos that ship an initialised submodule (see the+// WorktreePoolManager doc for why).+// 3. `git worktree prune` — reap any stale metadata from a previous+// daemon lifetime so a lease count doesn't include ghosts.+// 4. Enforce MaxParallel against the in-memory lease list. When+// saturated we return PoolSaturatedError with the current holders+// so the caller can post a structured wait_reason.+// 5. `git worktree add --lock --reason ... -b multica/<uuid>+// <pool_root>/<uuid> HEAD` — task UUID is used both as directory+// and branch suffix so a re-run of the same task can never collide+// with an in-flight one. `--lock` prevents `git worktree prune`+// from clearing the tree mid-task.+// 6. Register the lease and return a release closure that reverses the+// add (best-effort remove + prune) under the same per-repo mutex.+func (m *WorktreePoolManager) Acquire(ctx context.Context, base, poolRoot string, maxParallel int, taskID string) (*PoolAllocation, error) {+ if base == "" {+ return nil, errors.New("worktree pool: base path required")+ }+ if taskID == "" {+ return nil, errors.New("worktree pool: taskID required")+ }+ if poolRoot == "" {+ return nil, errors.New("worktree pool: pool_root required")+ }+ if maxParallel <= 0 {+ maxParallel = defaultWorktreePoolMaxParallel+ }+ baseAbs, err := filepath.Abs(base)+ if err != nil {+ return nil, fmt.Errorf("worktree pool: resolve base %q: %w", base, err)+ }+ baseReal, err := filepath.EvalSymlinks(baseAbs)+ if err != nil {+ // Fall back to the cleaned absolute form so callers see a+ // consistent key even when the symlink chain is currently+ // broken. Validation elsewhere surfaces the underlying error+ // with better context.+ baseReal = filepath.Clean(baseAbs)+ }+ baseReal = filepath.Clean(baseReal)++ poolRootAbs, err := filepath.Abs(poolRoot)+ if err != nil {+ return nil, fmt.Errorf("worktree pool: resolve pool_root %q: %w", poolRoot, err)+ }++ mu := m.repoLock(baseReal)+ mu.Lock()+ defer mu.Unlock()++ log := m.logger.With("base", baseReal, "task", shortID(taskID))++ if err := m.rejectSubmoduleRepo(ctx, baseReal); err != nil {+ return nil, err+ }++ // Best-effort: silently ignore prune failures because the returned+ // error is almost always "repo has never had a worktree yet". Failing+ // hard here would block every fresh install.+ m.pruneLocked(ctx, baseReal, log)++ state := m.repoLeases[baseReal]+ if state == nil {+ state = &repoPoolState{}+ m.repoLeases[baseReal] = state+ }+ if len(state.leases) >= maxParallel {+ holders := make([]string, 0, len(state.leases))+ for _, l := range state.leases {+ holders = append(holders, l.TaskID)+ }+ return nil, &PoolSaturatedError{BasePath: baseReal, MaxParallel: maxParallel, Holders: holders}+ }++ // Ensure the pool root exists before git worktree adds under it —+ // git refuses when the parent is missing.+ if err := os.MkdirAll(poolRootAbs, 0o755); err != nil {+ return nil, fmt.Errorf("worktree pool: create pool_root %q: %w", poolRootAbs, err)+ }++ // Task UUID is the source of truth for the directory + branch name.+ // A short id would be shorter to read but collides with taskbin+ // (agent) UUIDs shortened the same way, and the MUL-3483 spec+ // specifically calls out that the branch name must not depend on+ // agent id (a single squad agent can hold multiple worker tasks at+ // once and would otherwise collide on branch names).+ wtName := taskID+ wtPath := filepath.Join(poolRootAbs, wtName)+ branch := "multica/" + wtName+ reason := "multica task " + wtName++ // Attempt to remove any pre-existing directory at the target path+ // only when it's an EMPTY leftover from a previous daemon lifetime.+ // If somebody put real files there we bail — refusing to clobber is+ // safer than silently starting the agent in an unknown state.+ if err := ensureWorktreePathAvailable(wtPath); err != nil {+ return nil, err+ }++ addArgs := []string{"-C", baseReal, "worktree", "add", "--lock", "--reason", reason, "-b", branch, wtPath, "HEAD"}+ if out, err := runGit(ctx, addArgs...); err != nil {+ // Surface stderr verbatim so the caller's FailTask message+ // tells the user exactly what git said (missing base ref,+ // disk-full, permission denied). Wrapping alone would hide it.+ return nil, fmt.Errorf("worktree pool: git worktree add failed: %s: %w", strings.TrimSpace(out), err)+ }++ wtRealPath, err := filepath.EvalSymlinks(wtPath)+ if err != nil {+ wtRealPath = filepath.Clean(wtPath)+ }+ wtRealPath = filepath.Clean(wtRealPath)++ lease := poolLease{+ TaskID: taskID,+ Path: wtPath,+ RealPath: wtRealPath,+ Branch: branch,+ Acquired: m.clock(),+ }+ state.leases = append(state.leases, lease)+ log.Info("worktree pool: allocated", "path", wtPath, "branch", branch, "in_use", len(state.leases), "max_parallel", maxParallel)++ var releaseOnce sync.Once+ release := func() {+ releaseOnce.Do(func() {+ m.release(baseReal, taskID, wtPath, branch)+ })+ }++ return &PoolAllocation{+ WorkDir: wtPath,+ RealPath: wtRealPath,+ Branch: branch,+ Release: release,+ }, nil+}++// release runs the reverse of Acquire under the per-repo mutex: unlock+// the worktree, remove it (only when clean), prune metadata, and drop+// the in-memory lease. Any error from the git side is logged rather+// than surfaced — the caller cannot do anything with a cleanup failure+// beyond what the manual `git worktree prune` step already handles.+func (m *WorktreePoolManager) release(baseReal, taskID, wtPath, branch string) {+ mu := m.repoLock(baseReal)+ mu.Lock()+ defer mu.Unlock()++ log := m.logger.With("base", baseReal, "task", shortID(taskID), "worktree", wtPath)++ // Unlock first — remove refuses --lock'd worktrees. Best-effort.+ if out, err := runGit(context.Background(), "-C", baseReal, "worktree", "unlock", wtPath); err != nil {+ // It's normal for unlock to fail when the worktree has already+ // been removed manually (e.g. during a bench test cleanup); log+ // at debug so users don't see noise.+ log.Debug("worktree pool: unlock failed (best-effort)", "output", strings.TrimSpace(out), "error", err)+ }++ dirty, err := worktreeIsDirty(wtPath)+ switch {+ case err != nil:+ log.Warn("worktree pool: cannot determine cleanliness, leaving worktree in place", "error", err)+ case dirty:+ log.Warn("worktree pool: worktree has uncommitted changes; leaving on disk for user inspection", "path", wtPath)+ default:+ // Clean → tell git to remove it. We deliberately do NOT pass+ // --force: the dirty check above already guaranteed there is+ // nothing to lose, and refusing on any surprise diff is a+ // stronger safeguard than trying to guess intent.+ if out, err := runGit(context.Background(), "-C", baseReal, "worktree", "remove", wtPath); err != nil {+ log.Warn("worktree pool: git worktree remove failed", "output", strings.TrimSpace(out), "error", err)+ }+ }++ // Prune metadata unconditionally so a stale `.git/worktrees/<uuid>`+ // entry never inflates the lease count on the next allocation.+ if out, err := runGit(context.Background(), "-C", baseReal, "worktree", "prune"); err != nil {+ log.Debug("worktree pool: prune failed (best-effort)", "output", strings.TrimSpace(out), "error", err)+ }++ // The branch itself lingers so a follow-up task or a human can+ // inspect the work. MUL-3483 explicitly calls for keeping the branch+ // when the worktree stayed on disk (dirty case); we apply the same+ // rule in the clean case for consistency — costs almost nothing and+ // avoids destroying refs the agent may have pushed.++ // Drop the lease from the in-memory ledger even when git bookkeeping+ // above failed. The slot must return to the pool or the next task+ // hits a spurious PoolSaturatedError.+ if state, ok := m.repoLeases[baseReal]; ok {+ out := state.leases[:0]+ for _, l := range state.leases {+ if l.Path != wtPath {+ out = append(out, l)+ }+ }+ state.leases = out+ }+ log.Info("worktree pool: released", "branch", branch)+}++// repoLock returns the per-repo mutex for baseReal, creating it lazily on+// first access. Guarded by m.repoMu for the map read/write only — the+// returned mutex is what callers actually serialise on.+func (m *WorktreePoolManager) repoLock(baseReal string) *sync.Mutex {+ m.repoMu.Lock()+ defer m.repoMu.Unlock()+ mu, ok := m.repoMutex[baseReal]+ if !ok {+ mu = &sync.Mutex{}+ m.repoMutex[baseReal] = mu+ }+ return mu+}++// rejectSubmoduleRepo returns an error when the base has an initialised+// submodule. We check for the presence of `.gitmodules` first — that's a+// cheap file-existence test — and only shell out to `git submodule status`+// when needed. An unchecked-out submodule prefixed with "-" in the status+// output is not initialised and does not count.+//+// The refusal is intentionally strict rather than a warning: the shared+// `$GIT_COMMON_DIR/config` writes from `git submodule` would still+// bottleneck the pool, and the per-worktree `modules/` directories bloat+// disk usage by pool_size×. Both mitigations are out of scope for the MVP.+func (m *WorktreePoolManager) rejectSubmoduleRepo(ctx context.Context, baseReal string) error {+ if _, err := os.Stat(filepath.Join(baseReal, ".gitmodules")); err != nil {+ if os.IsNotExist(err) {+ return nil+ }+ return fmt.Errorf("worktree pool: stat .gitmodules for %q: %w", baseReal, err)+ }+ out, err := runGit(ctx, "-C", baseReal, "submodule", "status")+ if err != nil {+ return fmt.Errorf("worktree pool: git submodule status failed: %s: %w", strings.TrimSpace(out), err)+ }+ for _, line := range strings.Split(out, "\n") {+ trimmed := strings.TrimSpace(line)+ if trimmed == "" {+ continue+ }+ // `git submodule status` prefixes each line with one of:+ // ' ' (space) initialised and up-to-date+ // '+' initialised but with different commit+ // 'U' merge conflict+ // '-' not initialised → safe to ignore+ // We refuse on anything but '-'.+ prefix := line[0]+ if prefix == '-' {+ continue+ }+ return fmt.Errorf("worktree pool: repository %q has initialised submodules — worktree_pool mode does not yet support submodule superprojects (MUL-3483 MVP scope); either uninitialise submodules or keep this resource on mode=in_place", baseReal)+ }+ return nil+}++// pruneLocked runs `git worktree prune` and swallows the error. Callers+// hold the per-repo mutex so parallel invocations are already impossible;+// this is best-effort housekeeping to reclaim leases from a previous+// daemon lifetime before we hand out a new slot.+func (m *WorktreePoolManager) pruneLocked(ctx context.Context, baseReal string, log *slog.Logger) {+ if out, err := runGit(ctx, "-C", baseReal, "worktree", "prune"); err != nil {+ log.Debug("worktree pool: prune failed (best-effort)", "output", strings.TrimSpace(out), "error", err)+ }+}++// ensureWorktreePathAvailable is a defensive check for the case where a+// prior release couldn't remove the worktree (e.g. the daemon crashed+// mid-cleanup) and a re-run picks the same task UUID. Empty directories+// are safe to `os.Remove` (git will recreate); a directory that still+// holds files is a signal that the previous run left work behind and we+// refuse the allocation so the user can inspect.+func ensureWorktreePathAvailable(wtPath string) error {+ entries, err := os.ReadDir(wtPath)+ if err != nil {+ if os.IsNotExist(err) {+ return nil+ }+ return fmt.Errorf("worktree pool: probe %q: %w", wtPath, err)+ }+ if len(entries) == 0 {+ if err := os.Remove(wtPath); err != nil {+ return fmt.Errorf("worktree pool: clear empty leftover %q: %w", wtPath, err)+ }+ return nil+ }+ return fmt.Errorf("worktree pool: target path %q already exists and is non-empty; remove it before retrying", wtPath)+}++// worktreeIsDirty reports whether the worktree at path has uncommitted+// changes OR untracked files. Returning err != nil means we couldn't+// tell — the caller treats that the same as dirty (better to leak a+// directory than lose work).+//+// We include untracked files (`--untracked-files=normal`) because the+// whole point of the dirty check is "did the agent leave anything the+// user might want to inspect?", and a fresh file the agent created but+// hasn't committed is exactly that. Excluding it here would let us log+// "clean → remove", then have `git worktree remove` refuse the removal+// because untracked files exist (git itself has always refused this) —+// the outcome (directory preserved) is correct, but the log path is+// misleading and future maintainers seeing "worktree removed" would+// assume the disk was actually reclaimed. Including untracked keeps+// the observability honest with what actually happens on disk.+//+// Porcelain=v1 is the historically-stable format; -z avoids+// escape-quoting weirdness; any non-empty content means dirty.+func worktreeIsDirty(path string) (bool, error) {+ cmd := exec.Command("git", "-C", path, "status", "--porcelain=v1", "-z", "--untracked-files=normal")+ out, err := cmd.Output()+ if err != nil {+ if runtime.GOOS == "windows" {+ // On Windows a permission-denied on the working tree is+ // common after antivirus scans; treating that as dirty+ // keeps our safety guarantee even though we couldn't+ // confirm the state.+ return true, err+ }+ return true, err+ }+ // -z gives NUL-terminated entries; any non-empty content means dirty.+ return len(strings.Trim(string(out), "\x00")) > 0, nil+}++// runGit runs a git subcommand and returns its combined stdout+stderr.+// Failures include the process error verbatim so callers can wrap it+// with additional context.+func runGit(ctx context.Context, args ...string) (string, error) {+ if ctx == nil {+ ctx = context.Background()+ }+ cmd := exec.CommandContext(ctx, "git", args...)+ out, err := cmd.CombinedOutput()+ return string(out), err+}diff --git a/server/internal/daemon/worktree_pool_test.go b/server/internal/daemon/worktree_pool_test.gonew file mode 100644index 0000000000..95fc1ee02d--- /dev/null+++ b/server/internal/daemon/worktree_pool_test.go@@ -0,0 +1,434 @@+package daemon++import (+ "context"+ "errors"+ "io"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "sync"+ "testing"+ "time"+)++// initGitRepo initialises a git repo at dir with a single empty commit so+// `git worktree add HEAD` has something to check out. When git isn't on+// PATH — or the sequence fails for any environment reason — the test is+// skipped, matching the pattern used by repocache/cache_test.go so+// hermetic CI containers without git remain green.+func initGitRepo(t *testing.T, dir string) {+ t.Helper()+ envs := append(os.Environ(),+ "GIT_AUTHOR_NAME=multica-test", "[email protected]",+ "GIT_COMMITTER_NAME=multica-test", "[email protected]",+ // Force a stable initial branch so `git worktree add HEAD` works+ // on hosts that default to `main` and on hosts that default to+ // `master` alike. HEAD itself is the ref we ask for.+ "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_SYSTEM=/dev/null",+ )+ steps := [][]string{+ {"-c", "init.defaultBranch=main", "init", dir},+ {"-C", dir, "commit", "--allow-empty", "-m", "initial"},+ }+ for _, args := range steps {+ cmd := exec.Command("git", args...)+ cmd.Env = envs+ if out, err := cmd.CombinedOutput(); err != nil {+ t.Skipf("git setup failed (%v): %s", err, strings.TrimSpace(string(out)))+ }+ }+}++// discardLogger returns a slog logger that drops all output. Used to keep+// pool test failures readable — the manager logs at info on each acquire,+// which drowns the actual assertion output when a run breaks.+func discardLogger() *slog.Logger {+ return slog.New(slog.NewTextHandler(io.Discard, nil))+}++func TestWorktreePool_Acquire_ReleaseFlow(t *testing.T) {+ base := t.TempDir()+ initGitRepo(t, base)+ poolRoot := t.TempDir()++ mgr := NewWorktreePoolManager(discardLogger())++ alloc, err := mgr.Acquire(context.Background(), base, poolRoot, 4, "task-alpha")+ if err != nil {+ t.Fatalf("Acquire failed: %v", err)+ }+ if alloc == nil || alloc.WorkDir == "" {+ t.Fatalf("expected allocation with WorkDir, got %+v", alloc)+ }+ if _, err := os.Stat(alloc.WorkDir); err != nil {+ t.Fatalf("worktree dir missing after acquire: %v", err)+ }+ if alloc.Branch != "multica/task-alpha" {+ t.Errorf("branch = %q, want %q", alloc.Branch, "multica/task-alpha")+ }++ // The base repo should now advertise the new worktree.+ listOut, err := runGit(context.Background(), "-C", base, "worktree", "list", "--porcelain")+ if err != nil {+ t.Fatalf("worktree list: %v", err)+ }+ if !strings.Contains(listOut, "task-alpha") {+ t.Fatalf("expected task-alpha worktree in list, got:\n%s", listOut)+ }++ alloc.Release()++ // Clean-release should remove the worktree from disk.+ if _, err := os.Stat(alloc.WorkDir); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("expected worktree removed after release, stat err = %v", err)+ }+}++func TestWorktreePool_ParallelAllocations(t *testing.T) {+ base := t.TempDir()+ initGitRepo(t, base)+ poolRoot := t.TempDir()++ mgr := NewWorktreePoolManager(discardLogger())++ alloc1, err := mgr.Acquire(context.Background(), base, poolRoot, 4, "task-1")+ if err != nil {+ t.Fatalf("first acquire failed: %v", err)+ }+ defer alloc1.Release()++ alloc2, err := mgr.Acquire(context.Background(), base, poolRoot, 4, "task-2")+ if err != nil {+ t.Fatalf("second acquire failed (parallel should be allowed): %v", err)+ }+ defer alloc2.Release()++ if alloc1.WorkDir == alloc2.WorkDir {+ t.Fatalf("expected distinct worktree paths, got %q for both tasks", alloc1.WorkDir)+ }+}++func TestWorktreePool_SaturationReturnsHolders(t *testing.T) {+ base := t.TempDir()+ initGitRepo(t, base)+ poolRoot := t.TempDir()++ mgr := NewWorktreePoolManager(discardLogger())++ alloc1, err := mgr.Acquire(context.Background(), base, poolRoot, 2, "task-1")+ if err != nil {+ t.Fatalf("first acquire failed: %v", err)+ }+ defer alloc1.Release()+ alloc2, err := mgr.Acquire(context.Background(), base, poolRoot, 2, "task-2")+ if err != nil {+ t.Fatalf("second acquire failed: %v", err)+ }+ defer alloc2.Release()++ // max_parallel=2, two leases outstanding — the third must fail with+ // PoolSaturatedError and the two current holders.+ _, err = mgr.Acquire(context.Background(), base, poolRoot, 2, "task-3")+ if err == nil {+ t.Fatalf("expected saturation error, got nil")+ }+ var saturated *PoolSaturatedError+ if !errors.As(err, &saturated) {+ t.Fatalf("error is not PoolSaturatedError: %v", err)+ }+ if saturated.MaxParallel != 2 {+ t.Errorf("MaxParallel = %d, want 2", saturated.MaxParallel)+ }+ if len(saturated.Holders) != 2 {+ t.Errorf("Holders len = %d, want 2 (%v)", len(saturated.Holders), saturated.Holders)+ }+ // errors.Is via Unwrap must round-trip so callers can branch on a+ // sentinel without a type switch.+ if !errors.Is(err, errPoolSaturated) {+ t.Errorf("errors.Is(errPoolSaturated) = false, want true")+ }+}++func TestWorktreePool_ReleaseFreesSlot(t *testing.T) {+ base := t.TempDir()+ initGitRepo(t, base)+ poolRoot := t.TempDir()++ mgr := NewWorktreePoolManager(discardLogger())++ alloc1, err := mgr.Acquire(context.Background(), base, poolRoot, 1, "task-1")+ if err != nil {+ t.Fatalf("first acquire failed: %v", err)+ }+ if _, err := mgr.Acquire(context.Background(), base, poolRoot, 1, "task-2"); err == nil {+ t.Fatalf("expected saturation on second acquire")+ }+ alloc1.Release()+ alloc2, err := mgr.Acquire(context.Background(), base, poolRoot, 1, "task-2")+ if err != nil {+ t.Fatalf("acquire after release failed: %v", err)+ }+ defer alloc2.Release()+ if alloc2.WorkDir == alloc1.WorkDir {+ // Same UUID would collide; task-2 must live under its own path.+ t.Errorf("post-release alloc reused the released WorkDir %q", alloc2.WorkDir)+ }+}++func TestWorktreePool_DirtyWorktreeIsKept(t *testing.T) {+ base := t.TempDir()+ initGitRepo(t, base)+ poolRoot := t.TempDir()++ mgr := NewWorktreePoolManager(discardLogger())++ alloc, err := mgr.Acquire(context.Background(), base, poolRoot, 4, "task-dirty")+ if err != nil {+ t.Fatalf("acquire failed: %v", err)+ }+ // Simulate agent output — a plain unstaged file makes the worktree+ // dirty from `git status --porcelain` perspective.+ dirty := filepath.Join(alloc.WorkDir, "notes.txt")+ if err := os.WriteFile(dirty, []byte("agent scratch"), 0o644); err != nil {+ t.Fatalf("write dirty file: %v", err)+ }+ // Stage it so `--untracked-files=no` still classes the tree dirty.+ if out, err := runGit(context.Background(), "-C", alloc.WorkDir, "add", "notes.txt"); err != nil {+ t.Fatalf("git add failed (%v): %s", err, out)+ }++ alloc.Release()++ // Directory must still exist — losing user work is the exact+ // failure claude-code#55724 documents and must not regress.+ if _, err := os.Stat(dirty); err != nil {+ t.Fatalf("dirty worktree file missing after release: %v", err)+ }++ // The lease slot must still be freed even though the directory+ // stayed — otherwise MaxParallel would drift down every dirty run.+ alloc2, err := mgr.Acquire(context.Background(), base, poolRoot, 1, "task-followup")+ if err != nil {+ t.Fatalf("post-dirty acquire failed (slot should be free): %v", err)+ }+ defer alloc2.Release()+}++// TestWorktreePool_UntrackedOnlyIsKept pins the guarantee flagged in the+// #4986 review: an agent that only creates fresh, untracked files (never+// running `git add`) must not have those files deleted on release. Prior+// to the fix `worktreeIsDirty` ran with `--untracked-files=no`, which+// classified this state as "clean" and asked git to `remove` the tree —+// git itself would then refuse, but the log line lied about the disk+// state. The current implementation counts untracked as dirty so the+// "leaving on disk for user inspection" path fires directly.+func TestWorktreePool_UntrackedOnlyIsKept(t *testing.T) {+ base := t.TempDir()+ initGitRepo(t, base)+ poolRoot := t.TempDir()++ mgr := NewWorktreePoolManager(discardLogger())++ alloc, err := mgr.Acquire(context.Background(), base, poolRoot, 4, "task-untracked")+ if err != nil {+ t.Fatalf("acquire failed: %v", err)+ }++ // A brand new untracked file — the exact "agent scribbled a+ // draft" scenario. Deliberately no `git add`.+ fresh := filepath.Join(alloc.WorkDir, "draft.txt")+ if err := os.WriteFile(fresh, []byte("agent draft"), 0o644); err != nil {+ t.Fatalf("write untracked file: %v", err)+ }++ // Confirm worktreeIsDirty now classes untracked-only as dirty.+ dirty, err := worktreeIsDirty(alloc.WorkDir)+ if err != nil {+ t.Fatalf("worktreeIsDirty: %v", err)+ }+ if !dirty {+ t.Fatalf("worktreeIsDirty on untracked-only tree = false, want true")+ }++ alloc.Release()++ // The user's untracked file — and the worktree directory itself —+ // must still exist. Regression guard: reverting to+ // `--untracked-files=no` would silently delete `draft.txt` here+ // (well, git would refuse, but the code path would look correct+ // while the file was still gone in the untested async version).+ if _, err := os.Stat(fresh); err != nil {+ t.Fatalf("untracked file missing after release: %v", err)+ }++ // And the slot returned to the pool.+ alloc2, err := mgr.Acquire(context.Background(), base, poolRoot, 1, "task-followup")+ if err != nil {+ t.Fatalf("post-untracked-dirty acquire failed: %v", err)+ }+ defer alloc2.Release()+}++func TestWorktreePool_ConcurrentAllocationsAreSerialised(t *testing.T) {+ // Regression guard for the claude-code#34645 class of bug: two+ // concurrent `git worktree add` calls racing on `.git/config.lock`.+ // The per-repo mutex inside the manager must serialise these+ // operations even when the caller fans out on many goroutines.+ base := t.TempDir()+ initGitRepo(t, base)+ poolRoot := t.TempDir()++ mgr := NewWorktreePoolManager(discardLogger())++ const n = 6+ var (+ wg sync.WaitGroup+ mu sync.Mutex+ allocs []*PoolAllocation+ errs []error+ )+ wg.Add(n)+ for i := 0; i < n; i++ {+ id := "task-parallel-" + string(rune('a'+i))+ go func(id string) {+ defer wg.Done()+ alloc, err := mgr.Acquire(context.Background(), base, poolRoot, n, id)+ mu.Lock()+ defer mu.Unlock()+ if err != nil {+ errs = append(errs, err)+ return+ }+ allocs = append(allocs, alloc)+ }(id)+ }+ wg.Wait()++ if len(errs) != 0 {+ t.Fatalf("concurrent acquires produced errors: %v", errs)+ }+ if len(allocs) != n {+ t.Fatalf("got %d allocations, want %d", len(allocs), n)+ }+ // Every path must be unique — proving the pool did not hand out+ // the same directory to two goroutines racing through Acquire.+ seen := map[string]bool{}+ for _, a := range allocs {+ if seen[a.WorkDir] {+ t.Errorf("duplicate WorkDir %q handed out", a.WorkDir)+ }+ seen[a.WorkDir] = true+ }+ for _, a := range allocs {+ a.Release()+ }+}++func TestWorktreePool_SubmoduleRepoRefused(t *testing.T) {+ base := t.TempDir()+ initGitRepo(t, base)++ // Create a submodule source repo, then wire it in and commit+ // `.gitmodules` + the pointer. `git submodule add` writes to+ // `.git/config`, which is exactly the shared state we want to+ // protect against — the pool refuses this repo up front.+ sub := t.TempDir()+ initGitRepo(t, sub)++ if out, err := runGit(context.Background(),+ "-c", "protocol.file.allow=always",+ "-C", base, "-c", "protocol.file.allow=always",+ "submodule", "add", sub, "sub"); err != nil {+ t.Skipf("git submodule add failed (%v): %s", err, out)+ }+ if out, err := runGit(context.Background(), "-C", base, "commit", "-m", "add sub",+ "--author=multica-test <[email protected]>"); err != nil {+ t.Skipf("git commit failed (%v): %s", err, out)+ }++ mgr := NewWorktreePoolManager(discardLogger())+ _, err := mgr.Acquire(context.Background(), base, t.TempDir(), 4, "task-sub")+ if err == nil {+ t.Fatalf("expected submodule refusal, got nil")+ }+ if !strings.Contains(err.Error(), "submodule") {+ t.Errorf("error should mention submodule, got %v", err)+ }+}++func TestWorktreePool_MissingBaseIsRejected(t *testing.T) {+ mgr := NewWorktreePoolManager(discardLogger())+ // Point at a temp dir that isn't a git repo — `git worktree add`+ // will fail loudly with the git error text.+ base := t.TempDir()+ _, err := mgr.Acquire(context.Background(), base, t.TempDir(), 4, "task-nope")+ if err == nil {+ t.Fatalf("expected acquire against non-git base to fail")+ }+ // The failure text should include either "not a git" (English) or+ // the raw exit — either way, it must not silently succeed.+}++func TestWorktreePool_PoolRootCreatedIfMissing(t *testing.T) {+ base := t.TempDir()+ initGitRepo(t, base)+ // Deliberately point at a subdir under a fresh temp dir that+ // doesn't exist yet — the manager must create it.+ root := filepath.Join(t.TempDir(), "sub", "worktrees")+ mgr := NewWorktreePoolManager(discardLogger())+ alloc, err := mgr.Acquire(context.Background(), base, root, 4, "task-mkroot")+ if err != nil {+ t.Fatalf("acquire failed: %v", err)+ }+ defer alloc.Release()+ if _, err := os.Stat(root); err != nil {+ t.Fatalf("pool_root not created: %v", err)+ }+}++func TestWorktreePool_NonEmptyLeftoverRefused(t *testing.T) {+ base := t.TempDir()+ initGitRepo(t, base)+ poolRoot := t.TempDir()+ leftover := filepath.Join(poolRoot, "task-leftover")+ if err := os.MkdirAll(leftover, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(leftover, "residue"), []byte("x"), 0o644); err != nil {+ t.Fatal(err)+ }++ mgr := NewWorktreePoolManager(discardLogger())+ _, err := mgr.Acquire(context.Background(), base, poolRoot, 4, "task-leftover")+ if err == nil {+ t.Fatalf("expected refusal for non-empty leftover")+ }+ if !strings.Contains(err.Error(), "non-empty") {+ t.Errorf("error should mention non-empty, got %v", err)+ }+}++// TestWorktreePool_ContextCancelAborts guards against a hung Acquire when+// git itself is stuck (rare but seen in the wild). A cancelled ctx must+// surface promptly.+func TestWorktreePool_ContextCancelAborts(t *testing.T) {+ base := t.TempDir()+ initGitRepo(t, base)++ ctx, cancel := context.WithCancel(context.Background())+ cancel()++ mgr := NewWorktreePoolManager(discardLogger())+ _, err := mgr.Acquire(ctx, base, t.TempDir(), 4, "task-ctx")+ if err == nil {+ t.Fatalf("expected error from cancelled ctx")+ }+ // We don't strictly require errors.Is(err, context.Canceled) because+ // git may translate the signal to its own message; the surface+ // contract is just "acquire must not hang", which the fact that we+ // returned satisfies.+ _ = time.Now // keep the time import stable across future edits+}diff --git a/server/internal/handler/project_resource.go b/server/internal/handler/project_resource.goindex e6c9c2cea6..5a074455eb 100644--- a/server/internal/handler/project_resource.go+++ b/server/internal/handler/project_resource.go@@ -115,12 +115,33 @@ func validateGithubRepoRef(ref json.RawMessage) (json.RawMessage, error) {// on a different machine is a different resource. The optional label is a// human-readable hint used by the UI; the row-level project_resource.label// column remains the generic column for any resource type.+//+// Mode selects how the daemon binds tasks to the underlying path. The default+// "in_place" (or empty for backward compat) keeps the historical behaviour:+// every task locks the shared real path and runs directly in the user's+// directory. "worktree_pool" opts into MUL-3483's parallel mode — the daemon+// creates a per-task `git worktree add` under PoolRoot (bounded by+// MaxParallel) so sibling tasks on the same repo actually run concurrently+// instead of serialising on one working tree. PoolRoot and MaxParallel are+// hints; the daemon substitutes safe defaults when they are empty / 0.type localDirectoryRef struct {- LocalPath string `json:"local_path"`- DaemonID string `json:"daemon_id"`- Label string `json:"label,omitempty"`+ LocalPath string `json:"local_path"`+ DaemonID string `json:"daemon_id"`+ Label string `json:"label,omitempty"`+ Mode string `json:"mode,omitempty"` // "in_place" (default) | "worktree_pool"+ PoolRoot string `json:"pool_root,omitempty"` // absolute directory under daemon control; empty → daemon default+ MaxParallel int `json:"max_parallel,omitempty"` // 0 → daemon default}+// localDirectoryModeInPlace / localDirectoryModeWorktreePool are the only+// values the server accepts for `mode`. Kept as private constants because+// clients build the JSON directly; the daemon has its own copy of the same+// strings to avoid an import cycle between handler and daemon.+const (+ localDirectoryModeInPlace = "in_place"+ localDirectoryModeWorktreePool = "worktree_pool"+)+func validateLocalDirectoryRef(ref json.RawMessage) (json.RawMessage, error) {var payload localDirectoryRefif err := json.Unmarshal(ref, &payload); err != nil {@@ -138,6 +159,27 @@ func validateLocalDirectoryRef(ref json.RawMessage) (json.RawMessage, error) {return nil, errors.New("local_directory: daemon_id is required")}payload.Label = strings.TrimSpace(payload.Label)+ payload.Mode = strings.TrimSpace(payload.Mode)+ switch payload.Mode {+ case "", localDirectoryModeInPlace:+ // Preserve the historical shape on the wire: never emit `mode`+ // when the request meant "default". This keeps existing rows and+ // clients that never learnt about `mode` byte-for-byte identical+ // after a round-trip.+ payload.Mode = ""+ payload.PoolRoot = ""+ payload.MaxParallel = 0+ case localDirectoryModeWorktreePool:+ payload.PoolRoot = strings.TrimSpace(payload.PoolRoot)+ if payload.PoolRoot != "" && !isAbsoluteLocalPath(payload.PoolRoot) {+ return nil, errors.New("local_directory: pool_root must be an absolute path when provided")+ }+ if payload.MaxParallel < 0 {+ return nil, errors.New("local_directory: max_parallel must be non-negative")+ }+ default:+ return nil, fmt.Errorf("local_directory: unsupported mode %q (want %q or %q)", payload.Mode, localDirectoryModeInPlace, localDirectoryModeWorktreePool)+ }out, err := json.Marshal(payload)if err != nil {return nil, errdiff --git a/server/internal/handler/project_resource_test.go b/server/internal/handler/project_resource_test.goindex 1c7530a78b..715e335cc8 100644--- a/server/internal/handler/project_resource_test.go+++ b/server/internal/handler/project_resource_test.go@@ -413,6 +413,9 @@ func TestProjectResourceLocalDirectoryValidation(t *testing.T) {{"missing daemon_id", map[string]any{"local_path": "/Users/foo/work"}},{"blank daemon_id", map[string]any{"local_path": "/Users/foo/work", "daemon_id": ""}},{"wrong type in payload", map[string]any{"local_path": 42, "daemon_id": "d1"}},+ {"unknown mode", map[string]any{"local_path": "/Users/foo/work", "daemon_id": "d1", "mode": "garbled"}},+ {"pool_root relative", map[string]any{"local_path": "/Users/foo/work", "daemon_id": "d1", "mode": "worktree_pool", "pool_root": "relative/path"}},+ {"max_parallel negative", map[string]any{"local_path": "/Users/foo/work", "daemon_id": "d1", "mode": "worktree_pool", "max_parallel": -1}},}for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {@@ -430,6 +433,52 @@ func TestProjectResourceLocalDirectoryValidation(t *testing.T) {}}+// TestValidateLocalDirectoryRef_WorktreePoolRoundTrip pins the shape of the+// normalised JSON returned by validateLocalDirectoryRef for both modes.+// The zero-mode ("" / in_place) case is the historical wire format and+// must NOT emit `mode` / `pool_root` / `max_parallel` even when the+// client sent explicit zero values — that keeps rows byte-stable across+// clients that never learnt about the pool fields (MUL-3483).+func TestValidateLocalDirectoryRef_WorktreePoolRoundTrip(t *testing.T) {+ cases := []struct {+ name string+ in string+ want string+ }{+ {+ name: "default mode strips pool fields",+ in: `{"local_path":"/Users/x/repo","daemon_id":"d1","mode":"in_place","pool_root":"/tmp/ignored","max_parallel":8}`,+ want: `{"local_path":"/Users/x/repo","daemon_id":"d1"}`,+ },+ {+ name: "empty mode is equivalent to in_place",+ in: `{"local_path":"/Users/x/repo","daemon_id":"d1"}`,+ want: `{"local_path":"/Users/x/repo","daemon_id":"d1"}`,+ },+ {+ name: "worktree_pool preserves fields",+ in: `{"local_path":"/Users/x/repo","daemon_id":"d1","mode":"worktree_pool","pool_root":"/tmp/pool","max_parallel":3}`,+ want: `{"local_path":"/Users/x/repo","daemon_id":"d1","mode":"worktree_pool","pool_root":"/tmp/pool","max_parallel":3}`,+ },+ {+ name: "worktree_pool without pool_root or max_parallel keeps mode",+ in: `{"local_path":"/Users/x/repo","daemon_id":"d1","mode":"worktree_pool"}`,+ want: `{"local_path":"/Users/x/repo","daemon_id":"d1","mode":"worktree_pool"}`,+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ out, err := validateLocalDirectoryRef(json.RawMessage(tc.in))+ if err != nil {+ t.Fatalf("validate: %v", err)+ }+ if string(out) != tc.want {+ t.Fatalf("mismatch:\n got: %s\nwant: %s", string(out), tc.want)+ }+ })+ }+}+func TestIsAbsoluteLocalPath(t *testing.T) {good := []string{"/Users/foo/work",diff --git a/server/internal/service/builtin_skills/multica-projects-and-resources/SKILL.md b/server/internal/service/builtin_skills/multica-projects-and-resources/SKILL.mdindex 850f38b044..4b9a7a2554 100644--- a/server/internal/service/builtin_skills/multica-projects-and-resources/SKILL.md+++ b/server/internal/service/builtin_skills/multica-projects-and-resources/SKILL.md@@ -29,7 +29,11 @@ A project's `description` is also durable context: when an issue (or a quick-creCommon resource types:- `github_repo` — durable GitHub repo context, with `resource_ref.url`, optional checkout `ref`, and optional prompt-only `default_branch_hint`;-- `local_directory` — daemon-local path context, with `resource_ref.local_path`, `daemon_id`, and optional label.+- `local_directory` — daemon-local path context, with `resource_ref.local_path`, `daemon_id`, and optional label. Two extra optional fields opt into MUL-3483's parallel mode:+ - `mode` (`"in_place"` default | `"worktree_pool"`).+ - `pool_root` — absolute directory where per-task `git worktree` checkouts live. Defaults to `<parent-of-local_path>/.multica-worktrees/<local_path-basename>` (next to the repo, NOT inside it — the daemon needs write permission on that parent). Users mixing multiple projects should point each ref at a distinct `pool_root` under an explicit daemon-owned tree if they want centralised cleanup.+ - `max_parallel` — cap on concurrent worktrees per base repo (defaults to 4). The N+1th task parks with `wait_reason = "worktree_pool saturated ..."` until a slot frees.+ Worktrees stay on branch `multica/<task-uuid>`. Dirty worktrees are preserved on disk after task exit; users clean them via `git worktree remove` or manual `rm -rf` + `git worktree prune`. Repos with initialised submodules currently refuse `worktree_pool` mode.## CLI