Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6567 fix(execenv): lock a local_directory repo's git section across processes (#7462)
Bohan Jiang0a54725fe61a
diff --git a/server/internal/daemon/execenv/gitroot_lock.go b/server/internal/daemon/execenv/gitroot_lock.gonew file mode 100644index 0000000000..6536eb7b1d--- /dev/null+++ b/server/internal/daemon/execenv/gitroot_lock.go@@ -0,0 +1,249 @@+package execenv++import (+ "errors"+ "fmt"+ "log/slog"+ "os"+ "path/filepath"+ "sync"+ "time"+)++// Serialising git admin work on one repository is a CROSS-PROCESS problem.+//+// A daemon never prepares a task in its own process: PrepareIsolated runs the+// preparation in a short-lived helper (see isolation.go), so N concurrent+// tasks on one local_directory are N separate processes, all issuing git+// commands against the SAME repository. Worktree mode deliberately skips the+// per-path task mutex — sibling tasks running concurrently is the whole point+// of the mode — so nothing above this layer serialises them either.+//+// An in-process sync.Mutex therefore protected nothing in production: each+// helper held its own copy and none of them ever contended. `git stash create`+// (which needs the repository's index lock) lost that race routinely, and git+// reports the loss as a bare exit status 1 with no stderr at all, so the task+// failed with nothing to diagnose it by.+//+// The mutex is kept for the in-process callers — Finalize and Discard run in+// the daemon parent — and an advisory file lock in the repository's common git+// dir extends the same exclusion across every process that touches the repo,+// including two resources bound to two linked worktrees of it.++const (+ // gitRootLockFileName lives in the repository's COMMON git dir, which is+ // what makes one lock cover one repository.+ //+ // The section it guards spans both scopes a repo has: `git stash create`+ // contends for the per-working-tree index.lock, while `worktree add` /+ // `prune` / `remove` and `branch -D` write refs and worktrees/ in the+ // common dir, which every linked worktree shares. Keying on the+ // per-worktree git dir would hand two resources pointing at two linked+ // worktrees of one repo two different locks while they still raced on that+ // shared state; the common dir is the coarser key that covers both.+ //+ // Git ignores files it does not know about under $GIT_DIR, and nothing+ // here is visible from a working tree — `git status` never sees it, and+ // `git ls-files --others` cannot list it.+ gitRootLockFileName = "multica-worktree.lock"++ // gitRootLockPoll is the retry interval while waiting. flock has no+ // portable timed variant, so the wait is a poll over the non-blocking+ // primitive shared with the env-root claim (envlock_unix.go /+ // envlock_windows.go).+ gitRootLockPoll = 25 * time.Millisecond+)++// errGitRootLockBusy reports that another process held the repository lock for+// longer than gitRootLockWait. Distinct from a setup failure: busy means the+// exclusion worked and we chose not to wait any longer, so the caller must+// fail rather than proceed unprotected.+var errGitRootLockBusy = errors.New("execenv: git repository lock is held by another task")++// gitRootLockWait bounds the wait for a sibling's git section. That section is+// a handful of local git commands plus the bounded untracked-file replay, so a+// wait this long means the holder is wedged rather than busy: failing with a+// message that says who to wait for beats occupying a daemon slot forever.+//+// A var only so tests can shrink it; nothing at runtime writes it.+var gitRootLockWait = 3 * time.Minute++// gitRootLocks serialises git admin operations per repository within one+// process. Concurrent `git worktree add` / `remove` / `prune` on one repo race+// on the same lockfiles (worktrees/, packed-refs.lock, config.lock), and+// unlike a fetch these are fast, so a plain mutex costs nothing. Keyed by the+// repo root so tasks on different repos never wait on each other.+var gitRootLocks sync.Map // gitRoot -> *sync.Mutex++// gitDirCache memoises the git dir per repo root. Resolving it costs a git+// invocation and the answer cannot change for the life of a process: a repo+// root's git dir is fixed once the repo exists.+var gitDirCache sync.Map // gitRoot -> string++// gitDirFor returns the absolute git dir backing gitRoot's working tree.+//+// Not filepath.Join(gitRoot, ".git"): in a linked worktree .git is a FILE+// pointing at $COMMON/.git/worktrees/<name>, and that directory — not the+// common one — is where this working tree's index and index.lock live. Asking+// git keeps the lock in the same place as the contention in both layouts.+func gitDirFor(gitRoot string) (string, error) {+ if v, ok := gitDirCache.Load(gitRoot); ok {+ return v.(string), nil+ }+ dir, err := runGitTrimmed(gitRoot, "rev-parse", "--absolute-git-dir")+ if err != nil {+ return "", fmt.Errorf("execenv: resolve git dir for %q: %w", gitRoot, err)+ }+ if dir == "" {+ return "", fmt.Errorf("execenv: resolve git dir for %q: empty result", gitRoot)+ }+ // git reports paths with forward slashes on every platform, including+ // Windows. Normalise before this becomes a filesystem path, so the lock+ // file and every path derived from it are native.+ dir = filepath.Clean(filepath.FromSlash(dir))+ gitDirCache.Store(gitRoot, dir)+ return dir, nil+}++// gitCommonDirCache memoises the common git dir per repo root, for the same+// reason gitDirCache does: one git invocation, an answer that cannot change.+var gitCommonDirCache sync.Map // gitRoot -> string++// gitCommonDirFor returns the git dir shared by every working tree of the+// repository behind gitRoot. For a main worktree that is its own git dir; for+// a linked one it is the main repo's, where the refs and worktrees/ admin+// state they both write actually live.+func gitCommonDirFor(gitRoot string) (string, error) {+ if v, ok := gitCommonDirCache.Load(gitRoot); ok {+ return v.(string), nil+ }+ dir, err := runGitTrimmed(gitRoot, "rev-parse", "--git-common-dir")+ if err != nil {+ return "", fmt.Errorf("execenv: resolve common git dir for %q: %w", gitRoot, err)+ }+ if dir == "" {+ return "", fmt.Errorf("execenv: resolve common git dir for %q: empty result", gitRoot)+ }+ dir = filepath.FromSlash(dir)+ // git answers this one relative to the cwd it ran in when the working tree+ // IS the main one (plain ".git"), and absolute from a linked worktree.+ // --path-format=absolute would settle it but only exists since git 2.31,+ // and resolving it here costs nothing.+ if !filepath.IsAbs(dir) {+ dir = filepath.Join(gitRoot, dir)+ }+ dir = filepath.Clean(dir)+ gitCommonDirCache.Store(gitRoot, dir)+ return dir, nil+}++// gitRootLockPath is where the advisory lock for gitRoot's repository lives.+func gitRootLockPath(gitRoot string) (string, error) {+ commonDir, err := gitCommonDirFor(gitRoot)+ if err != nil {+ return "", err+ }+ return filepath.Join(commonDir, gitRootLockFileName), nil+}++// acquireGitRootFileLock takes the cross-process lock for gitRoot, waiting up+// to gitRootLockWait for a current holder to finish.+func acquireGitRootFileLock(gitRoot string, logger *slog.Logger) (*os.File, error) {+ path, err := gitRootLockPath(gitRoot)+ if err != nil {+ return nil, err+ }+ f, err := openLockFile(path)+ if err != nil {+ return nil, fmt.Errorf("execenv: open git repository lock %s: %w", path, err)+ }++ deadline := time.Now().Add(gitRootLockWait)+ announced := false+ for {+ ok, lockErr := lockFileExclusiveNonBlocking(f)+ if lockErr != nil {+ f.Close()+ return nil, fmt.Errorf("execenv: lock %s: %w", path, lockErr)+ }+ if ok {+ return f, nil+ }+ if !announced {+ announced = true+ if logger != nil {+ logger.Info("execenv: waiting for another task's git section on this repository",+ "git_root", gitRoot, "lock", path)+ }+ }+ if time.Now().After(deadline) {+ f.Close()+ // Deliberately NOT "delete the lock file if nothing is running".+ // The lock binds to an open file description, not to a path:+ // unlinking it leaves the holder locking the old inode while the+ // next task creates and locks a NEW file at the same name, and+ // both then believe they hold it — the exact overlap this lock+ // exists to prevent. The kernel already releases it when the+ // holding process exits, so an idle lock file is never stale.+ return nil, fmt.Errorf("%w: %q was still locked after %s by another Multica task (%s) — "++ "wait for that task to finish or stop it, then retry; the lock is released "++ "automatically when the holding process exits, so the file itself is never stale "++ "and deleting it would let two tasks into this section at once",+ errGitRootLockBusy, gitRoot, gitRootLockWait, path)+ }+ time.Sleep(gitRootLockPoll)+ }+}++// lockGitRoot takes exclusive ownership of gitRoot's git admin state for this+// task, across processes, and returns the release func.+//+// Setup failures are NOT fatal. A repo whose git dir cannot hold a lock file+// (read-only mount, an exotic filesystem) still gets the in-process mutex,+// which is exactly the protection this code had before — a task that refuses+// to start is worse than one that races on a millisecond window it can also+// retry out of. A BUSY lock is different: the exclusion worked, we waited, and+// proceeding anyway would defeat it, so that one is returned to the caller.+func lockGitRoot(gitRoot string, logger *slog.Logger) (func(), error) {+ // The file lock comes FIRST, before the mutex. Waiting on it while holding+ // the mutex would serialise the waits themselves: three queued goroutines+ // would each start their own gitRootLockWait only after the one ahead gave+ // up, so the last of them could block for three times the bound it was+ // promised. Waiting on the file lock directly lets them all wait at once,+ // each bounded by gitRootLockWait.+ //+ // Both platforms' primitives already exclude within a process — flock+ // treats separate open file descriptions independently, and so does+ // LockFileEx with separate handles — so this ordering loses nothing.+ f, err := acquireGitRootFileLock(gitRoot, logger)+ if err != nil {+ if errors.Is(err, errGitRootLockBusy) {+ return nil, err+ }+ if logger != nil {+ logger.Warn("execenv: cross-process git lock unavailable; falling back to the in-process lock",+ "git_root", gitRoot, "error", err)+ }+ return lockGitRootInProcess(gitRoot), nil+ }++ // The mutex is redundant while the file lock holds and is what protects+ // this repo if the file lock ever falls back mid-flight. Uncontended in+ // the normal case, since no sibling goroutine can be past the file lock.+ unlockLocal := lockGitRootInProcess(gitRoot)+ return func() {+ unlockLocal()+ if unlockErr := unlockFile(f); unlockErr != nil && logger != nil {+ logger.Warn("execenv: release git repository lock failed", "git_root", gitRoot, "error", unlockErr)+ }+ f.Close()+ }, nil+}++// lockGitRootInProcess takes the per-repo mutex and returns its release func.+func lockGitRootInProcess(gitRoot string) func() {+ v, _ := gitRootLocks.LoadOrStore(gitRoot, &sync.Mutex{})+ mu := v.(*sync.Mutex)+ mu.Lock()+ return mu.Unlock+}diff --git a/server/internal/daemon/execenv/gitroot_lock_test.go b/server/internal/daemon/execenv/gitroot_lock_test.gonew file mode 100644index 0000000000..948e0585f4--- /dev/null+++ b/server/internal/daemon/execenv/gitroot_lock_test.go@@ -0,0 +1,338 @@+package execenv++import (+ "context"+ "errors"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "sync"+ "testing"+ "time"+)++// gitRootLockHolderMode re-execs this test binary as a process that takes the+// repository lock and holds it. A second process is the only way to test what+// broke here: the previous lock was an in-process mutex, which is exactly the+// scope that does NOT cover production, where every prepare runs in its own+// helper process.+const gitRootLockHolderMode = "execenv-gitroot-lock-holder"++// TestGitRootLockHolderProcess is a no-op in the parent and the lock holder in+// the child.+func TestGitRootLockHolderProcess(t *testing.T) {+ if len(os.Args) == 0 || os.Args[len(os.Args)-1] != gitRootLockHolderMode {+ return+ }+ repo := os.Getenv("MULTICA_TEST_LOCK_REPO")+ readyPath := os.Getenv("MULTICA_TEST_LOCK_READY")+ releasePath := os.Getenv("MULTICA_TEST_LOCK_RELEASE")++ unlock, err := lockGitRoot(repo, worktreeTestLogger())+ if err != nil {+ os.Exit(3)+ }+ if err := os.WriteFile(readyPath, []byte("held"), 0o644); err != nil {+ os.Exit(4)+ }+ deadline := time.Now().Add(60 * time.Second)+ for {+ if _, err := os.Stat(releasePath); err == nil {+ break+ }+ if time.Now().After(deadline) {+ os.Exit(5)+ }+ time.Sleep(10 * time.Millisecond)+ }+ unlock()+ os.Exit(0)+}++func waitForFile(t *testing.T, path string, within time.Duration) {+ t.Helper()+ deadline := time.Now().Add(within)+ for {+ if _, err := os.Stat(path); err == nil {+ return+ }+ if time.Now().After(deadline) {+ t.Fatalf("timed out waiting for %s", path)+ }+ time.Sleep(10 * time.Millisecond)+ }+}++// startLockHolder runs another PROCESS that takes repo's lock and holds it+// until the returned release func is called. Another process is the only scope+// that tests what broke here: the previous lock was an in-process mutex, and+// production never has two contenders inside one process.+func startLockHolder(t *testing.T, repo string) (release func()) {+ t.Helper()+ signals := t.TempDir()+ readyPath := filepath.Join(signals, "ready")+ releasePath := filepath.Join(signals, "release")++ child := exec.Command(os.Args[0], "-test.run=^TestGitRootLockHolderProcess$", "--", gitRootLockHolderMode)+ child.Env = append(os.Environ(),+ "MULTICA_TEST_LOCK_REPO="+repo,+ "MULTICA_TEST_LOCK_READY="+readyPath,+ "MULTICA_TEST_LOCK_RELEASE="+releasePath,+ )+ if err := child.Start(); err != nil {+ t.Fatalf("start lock holder: %v", err)+ }+ var once sync.Once+ stop := func() {+ once.Do(func() {+ _ = os.WriteFile(releasePath, []byte("go"), 0o644)+ _ = child.Wait()+ })+ }+ t.Cleanup(stop)+ waitForFile(t, readyPath, 30*time.Second)+ return stop+}++// The lock must exclude ANOTHER PROCESS, not just another goroutine. Against+// the in-process mutex this test fails immediately: lockGitRoot returned while+// the child still held the repository, which is the state that let two+// prepares run `git stash create` on one index.+func TestLockGitRootExcludesOtherProcesses(t *testing.T) {+ repo := newTestRepo(t)+ release := startLockHolder(t, repo)++ acquired := make(chan error, 1)+ go func() {+ unlock, err := lockGitRoot(repo, worktreeTestLogger())+ if unlock != nil {+ unlock()+ }+ acquired <- err+ }()++ // The holder is alive and has not released, so this must not come back.+ select {+ case err := <-acquired:+ t.Fatalf("lockGitRoot returned (err=%v) while another process held the repository lock", err)+ case <-time.After(500 * time.Millisecond):+ }++ release()+ select {+ case err := <-acquired:+ if err != nil {+ t.Fatalf("lockGitRoot after release: %v", err)+ }+ case <-time.After(30 * time.Second):+ t.Fatal("lockGitRoot never acquired the lock after the holder released it")+ }+}++// One repository, one lock — including across its linked worktrees.+//+// The section under this lock writes refs and worktrees/ in the COMMON git+// dir, which every working tree of a repo shares. Keying on the per-worktree+// git dir gives two resources bound to two linked worktrees two different+// locks while they still race on that shared state.+func TestGitRootLockPathIsRepoWide(t *testing.T) {+ repo := newTestRepo(t)+ path, err := gitRootLockPath(repo)+ if err != nil {+ t.Fatalf("gitRootLockPath: %v", err)+ }+ want := filepath.Join(repo, ".git", gitRootLockFileName)+ if path != want {+ t.Fatalf("lock path = %q, want %q", path, want)+ }++ linked := filepath.Join(t.TempDir(), "linked")+ gitRun(t, repo, "worktree", "add", "-b", "linked-branch", linked)+ if resolved, evalErr := filepath.EvalSymlinks(linked); evalErr == nil {+ linked = resolved+ }+ linkedPath, err := gitRootLockPath(linked)+ if err != nil {+ t.Fatalf("gitRootLockPath(linked): %v", err)+ }+ if linkedPath != path {+ t.Fatalf("linked worktree locks %q, want the repository's single lock %q", linkedPath, path)+ }+ // The per-worktree git dir is still what the index.lock hint must read:+ // that is where a linked worktree's own index lives.+ linkedGitDir, err := gitDirFor(linked)+ if err != nil {+ t.Fatalf("gitDirFor(linked): %v", err)+ }+ if !strings.Contains(filepath.ToSlash(linkedGitDir), "/worktrees/") {+ t.Fatalf("linked worktree git dir = %q, want it under worktrees/", linkedGitDir)+ }+}++// A held lock file is never stale: the kernel drops the lock when the holder+// exits, and the leftover file means nothing on its own. Telling the user to+// delete it would undo this whole change — the lock binds to an open file+// description, not to the path, so unlinking it lets the next task create and+// lock a NEW file while the holder still owns the old inode, and both then+// believe they are alone in the section.+func TestGitRootLockTimeoutDoesNotAdviseDeletingTheLock(t *testing.T) {+ repo := newTestRepo(t)+ original := gitRootLockWait+ gitRootLockWait = 200 * time.Millisecond+ t.Cleanup(func() { gitRootLockWait = original })++ startLockHolder(t, repo)++ unlock, err := lockGitRoot(repo, worktreeTestLogger())+ if unlock != nil {+ unlock()+ }+ if err == nil {+ t.Fatal("lockGitRoot succeeded while another process held the lock")+ }+ if !errors.Is(err, errGitRootLockBusy) {+ t.Fatalf("error is not errGitRootLockBusy: %v", err)+ }++ msg := err.Error()+ for _, banned := range []string{"can be deleted", "stale lock", "delete the lock"} {+ if strings.Contains(msg, banned) {+ t.Errorf("timeout message advises %q, which breaks the exclusion: %v", banned, err)+ }+ }+ if !strings.Contains(msg, "wait for that task to finish or stop it") {+ t.Errorf("timeout message does not say what to actually do: %v", err)+ }+}++// Losing the index-lock race used to end the task. It is a millisecond-scale+// condition owned by the user's own tools, so the capture rides it out.+func TestCaptureDirtyStateRetriesUntilTheIndexLockClears(t *testing.T) {+ repo := newTestRepo(t)+ writeFile(t, filepath.Join(repo, "tracked.txt"), "edited by the user\n")++ lock := filepath.Join(repo, ".git", "index.lock")+ if err := os.WriteFile(lock, nil, 0o644); err != nil {+ t.Fatalf("hold index.lock: %v", err)+ }+ cleared := make(chan struct{})+ go func() {+ time.Sleep(150 * time.Millisecond)+ _ = os.Remove(lock)+ close(cleared)+ }()++ sha, err := captureDirtyState(repo, worktreeTestLogger())+ <-cleared+ if err != nil {+ t.Fatalf("captureDirtyState: %v", err)+ }+ if sha == "" {+ t.Fatal("captured no stash commit for a dirty tree")+ }+ // The capture must be readable as a real commit carrying the user's edit.+ if got := gitRun(t, repo, "show", sha+":tracked.txt"); got != "edited by the user" {+ t.Fatalf("stash commit content = %q, want the user's edit", got)+ }+}++// git reports this failure as a bare exit status 1 with NOTHING on stderr, so+// the error has to name the index lock itself or there is nothing to act on.+func TestCaptureDirtyStateNamesTheIndexLockHolder(t *testing.T) {+ repo := newTestRepo(t)+ writeFile(t, filepath.Join(repo, "tracked.txt"), "edited by the user\n")++ lock := filepath.Join(repo, ".git", "index.lock")+ if err := os.WriteFile(lock, nil, 0o644); err != nil {+ t.Fatalf("hold index.lock: %v", err)+ }+ defer os.Remove(lock)++ _, err := captureDirtyState(repo, worktreeTestLogger())+ if err == nil {+ t.Fatal("captureDirtyState succeeded while index.lock was held")+ }+ msg := err.Error()+ if !strings.Contains(msg, "index.lock") {+ t.Errorf("error does not name the index lock, so it is not actionable: %v", err)+ }+ if !strings.Contains(msg, "times") {+ t.Errorf("error does not report that the capture was retried: %v", err)+ }+}++// Every failure through runGitStdout used to arrive as "exit status 1": stderr+// was captured by cmd.Output() and then dropped on the floor.+func TestRunGitSurfacesStderrInTheError(t *testing.T) {+ repo := newTestRepo(t)+ _, err := runGitTrimmed(repo, "rev-parse", "--verify", "definitely-not-a-ref")+ if err == nil {+ t.Fatal("rev-parse of a bogus ref succeeded")+ }+ if !strings.Contains(err.Error(), "fatal:") {+ t.Errorf("error dropped git's stderr: %v", err)+ }+}++// The production shape: two tasks on one local_directory, each preparing in+// its own helper process. Both must get a worktree; before the cross-process+// lock one of them routinely died in `git stash create`.+func TestConcurrentIsolatedPreparesOnOneRepo(t *testing.T) {+ repo := newTestRepo(t)+ writeFile(t, filepath.Join(repo, "tracked.txt"), "user work in progress\n")+ writeFile(t, filepath.Join(repo, "untracked.txt"), "new file\n")++ workspacesRoot := t.TempDir()+ logger := worktreeTestLogger()+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)+ defer cancel()++ type result struct {+ env *Environment+ err error+ }+ taskIDs := []string{+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaa1",+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaa2",+ }+ results := make(chan result, len(taskIDs))+ for _, taskID := range taskIDs {+ go func(taskID string) {+ env, err := PrepareIsolated(ctx, preparationHelperTestCommand(), PrepareParams{+ WorkspacesRoot: workspacesRoot,+ WorkspaceID: "ws-concurrent-worktree",+ TaskID: taskID,+ Provider: "claude",+ AgentName: "J",+ Task: TaskContextForEnv{IssueID: "issue-" + taskID},+ LocalWorktree: &LocalWorktreeParams{LocalPath: repo},+ }, logger)+ results <- result{env: env, err: err}+ }(taskID)+ }++ branches := map[string]bool{}+ for range taskIDs {+ got := <-results+ if got.err != nil {+ t.Fatalf("concurrent PrepareIsolated failed: %v", got.err)+ }+ wt := got.env.LocalWorktree+ if wt == nil {+ t.Fatal("prepared environment has no worktree")+ }+ if branches[wt.Branch] {+ t.Fatalf("two concurrent tasks landed on branch %q", wt.Branch)+ }+ branches[wt.Branch] = true+ // Each task must see the user's uncommitted state, which is precisely+ // what the lost capture would have silently replaced with a clean HEAD.+ if content := readFile(t, filepath.Join(wt.Path, "tracked.txt")); content != "user work in progress\n" {+ t.Fatalf("worktree %s missing the user's edit: %q", wt.Path, content)+ }+ if content := readFile(t, filepath.Join(wt.Path, "untracked.txt")); content != "new file\n" {+ t.Fatalf("worktree %s missing the user's untracked file: %q", wt.Path, content)+ }+ }+}diff --git a/server/internal/daemon/execenv/local_worktree.go b/server/internal/daemon/execenv/local_worktree.goindex 7c42898658..ff259edeb5 100644--- a/server/internal/daemon/execenv/local_worktree.go+++ b/server/internal/daemon/execenv/local_worktree.go@@ -9,7 +9,6 @@ import ("os/exec""path/filepath""strings"- "sync""time")@@ -51,21 +50,16 @@ const (// multi-gigabyte copy.maxUntrackedFiles = 2000maxUntrackedBytes = 200 << 20 // 200 MiB-)-// gitRootLocks serialises git admin operations per repository. Concurrent-// `git worktree add` / `remove` / `prune` on one repo race on the same-// lockfiles (worktrees/, packed-refs.lock, config.lock), and unlike a fetch-// these are fast, so a plain mutex costs nothing. Keyed by the repo root so-// tasks on different repos never wait on each other.-var gitRootLocks sync.Map // gitRoot -> *sync.Mutex--func lockGitRoot(gitRoot string) func() {- v, _ := gitRootLocks.LoadOrStore(gitRoot, &sync.Mutex{})- mu := v.(*sync.Mutex)- mu.Lock()- return mu.Unlock-}+ // stashCaptureAttempts / stashCaptureRetryDelay bound the retry on the+ // dirty-state capture. The contention this rides out is a user tool+ // holding .git/index.lock for the length of one git command, so the total+ // window (0.1s + 0.2s + 0.4s + 0.8s ≈ 1.5s) is sized for that and not for+ // a wedged lock — a stale index.lock is a repo the user has to fix, and+ // waiting minutes on it would only delay telling them so.+ stashCaptureAttempts = 5+ stashCaptureRetryDelay = 100 * time.Millisecond+)// LocalWorktreeParams describes the worktree Prepare should build for a// local_directory task running in worktree mode.@@ -169,10 +163,17 @@ func PrepareLocalWorktree(params LocalWorktreeParams, logger *slog.Logger) (*LocworktreePath := filepath.Join(params.EnvRoot, localWorktreeDirName)- // Everything below mutates the repo's worktree admin state, so take the- // per-repo lock first — including the stale-path cleanup, which runs `git- // worktree remove` and would otherwise race a sibling task's `worktree add`.- unlock := lockGitRoot(gitRoot)+ // Everything below either mutates the repo's worktree admin state or needs+ // its index lock, so take the per-repo lock first. That covers the+ // stale-path cleanup, which runs `git worktree remove` and would otherwise+ // race a sibling task's `worktree add`, and the `git stash create` capture+ // below — the step that actually lost this race in production, because the+ // lock used to be in-process only while every prepare runs in its own+ // helper process (#7434).+ unlock, err := lockGitRoot(gitRoot, logger)+ if err != nil {+ return nil, err+ }defer unlock()if _, statErr := os.Stat(worktreePath); statErr == nil {@@ -202,7 +203,7 @@ func PrepareLocalWorktree(params LocalWorktreeParams, logger *slog.Logger) (*Loc// a repo with no user.email configured: writing a commit object needs a// committer, and without them the user's uncommitted work would be dropped// on a technicality.- stashSHA, stashErr := runGitTrimmed(gitRoot, append(commitIdentityArgs(gitRoot), "stash", "create")...)+ stashSHA, stashErr := captureDirtyState(gitRoot, logger)if stashErr != nil {// Fail closed. The promise of this mode is that the agent reasons about// the code the user actually has; silently starting from HEAD instead@@ -339,11 +340,20 @@ func (w *LocalWorktree) Finalize(logger *slog.Logger) (LocalWorktreeOutcome, errif w == nil {return LocalWorktreeOutcome{}, nil}- unlock := lockGitRoot(w.GitRoot)- defer unlock()-outcome := LocalWorktreeOutcome{Branch: w.Branch}+ unlock, err := lockGitRoot(w.GitRoot, logger)+ if err != nil {+ // Nothing has been committed or removed yet, so the agent's work is+ // still sitting in the worktree. Report it as preserved rather than+ // naming a branch that does not carry it.+ outcome.Branch = ""+ outcome.PreservedPath = w.Path+ return outcome, fmt.Errorf("could not lock %q to finalize branch %s: %w; "++ "the work is preserved in the worktree at %s", w.GitRoot, w.Branch, err, w.Path)+ }+ defer unlock()+// Something before the commit went wrong in a way that would make the// delivered branch misleading. Commit nothing and keep the worktree: the// agent's work is still in it, and so is whatever the caller could not@@ -428,7 +438,17 @@ func (w *LocalWorktree) Discard(logger *slog.Logger) {if w == nil {return}- unlock := lockGitRoot(w.GitRoot)+ unlock, err := lockGitRoot(w.GitRoot, logger)+ if err != nil {+ // Best-effort by contract: every step below only logs on failure. The+ // registration this leaves behind is pruned by the next prepare on+ // this repo, which is the same self-heal path a crashed daemon uses.+ if logger != nil {+ logger.Warn("execenv: could not lock the repository to discard the task worktree",+ "git_root", w.GitRoot, "path", w.Path, "branch", w.Branch, "error", err)+ }+ return+ }defer unlock()removeLocalWorktreeDir(w.GitRoot, w.Path, logger)deleteBranch(w.GitRoot, w.Branch, logger)@@ -586,6 +606,75 @@ func resolveGitRoot(dir string) (string, error) {return filepath.Clean(root), nil}+// captureDirtyState builds the commit object that carries the user's tracked+// edits, retrying a lost index-lock race instead of failing the task over it.+//+// lockGitRoot already excludes Multica's own tasks, but the repository belongs+// to the user: an editor's auto-fetch, a git hook, a `git status` in another+// terminal or a background `git gc` can hold .git/index.lock at any moment,+// and the window is milliseconds. That is a transient condition worth waiting+// out — before this retry it ended the whole task, and nothing re-dispatched+// it.+//+// Retrying is safe because `stash create` has no side effects to repeat: it+// writes a commit object and returns its sha, leaving the index, the refs and+// the working tree exactly as they were. A failed attempt leaves nothing+// behind, and a repeated one just writes an identical object.+func captureDirtyState(gitRoot string, logger *slog.Logger) (string, error) {+ args := append(commitIdentityArgs(gitRoot), "stash", "create")+ started := time.Now()+ delay := stashCaptureRetryDelay++ var lastErr error+ for attempt := 1; attempt <= stashCaptureAttempts; attempt++ {+ sha, err := runGitTrimmed(gitRoot, args...)+ if err == nil {+ if attempt > 1 && logger != nil {+ logger.Info("execenv: captured the uncommitted changes after retrying",+ "git_root", gitRoot, "attempts", attempt, "elapsed", time.Since(started))+ }+ return sha, nil+ }+ lastErr = err+ if attempt == stashCaptureAttempts {+ break+ }+ if logger != nil {+ logger.Debug("execenv: capture attempt failed, retrying",+ "git_root", gitRoot, "attempt", attempt, "error", err)+ }+ time.Sleep(delay)+ delay *= 2+ }++ return "", fmt.Errorf("git stash create failed %d times over %s%s: %w",+ stashCaptureAttempts, time.Since(started).Round(time.Millisecond), indexLockHint(gitRoot), lastErr)+}++// indexLockHint names the index lock when it is what blocked us.+//+// git is silent on this failure — losing the index lock in `stash create`+// produces exit status 1 with NOTHING on stderr — so surfacing git's output is+// not enough on its own, and the bare exit status is what made this class of+// failure undiagnosable in the field. Looking for the lock file gives the+// message the one fact that actually points somewhere.+//+// Advisory only: the holder may have released it between git's attempt and+// ours, in which case we say nothing extra and the wrapped error still carries+// whatever git did report.+func indexLockHint(gitRoot string) string {+ gitDir, err := gitDirFor(gitRoot)+ if err != nil {+ return ""+ }+ lock := filepath.Join(gitDir, "index.lock")+ if _, statErr := os.Stat(lock); statErr != nil {+ return ""+ }+ return fmt.Sprintf(" (another process is holding %s — usually an editor, a git hook,"++ " or a git command running in that repository)", lock)+}+// addLocalWorktree creates the worktree, retrying once under a suffixed branch// name when the branch already exists (a re-dispatched task keeps its id, so// its branch can survive from the previous run).@@ -759,7 +848,25 @@ func runGitStdout(dir string, args ...string) (string, error) {cmd.WaitDelay = 5 * time.Secondout, err := cmd.Output()if err != nil {- return "", err+ return "", withGitStderr(err)}return string(out), nil}++// withGitStderr renders git's stderr into the error.+//+// cmd.Output() already captures stderr into ExitError.Stderr, but nothing ever+// read it back out, so every failure from this path reached the user as a bare+// "exit status 1" — git's own explanation was collected and then thrown away+// at the point it was needed. Discarding stderr from the RESULT is deliberate+// (see runGitTrimmed: a diagnostic line must never be mistaken for a value);+// discarding it from the error was not.+func withGitStderr(err error) error {+ var exitErr *exec.ExitError+ if errors.As(err, &exitErr) {+ if msg := strings.TrimSpace(string(exitErr.Stderr)); msg != "" {+ return fmt.Errorf("%s: %w", msg, err)+ }+ }+ return err+}