Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon/repocache): unstick stale cache from initial snapshot
gyh16216e475b95212e
diff --git a/server/internal/daemon/repocache/cache.go b/server/internal/daemon/repocache/cache.goindex 3d59b412e3..90ac2d7ff7 100644--- a/server/internal/daemon/repocache/cache.go+++ b/server/internal/daemon/repocache/cache.go@@ -31,7 +31,12 @@ type CachedRepo struct {type Cache struct {root string // base directory for all caches (e.g. ~/multica_workspaces/.repos)logger *slog.Logger- mu sync.Mutex+ // repoLocks maps bare repo path → dedicated mutex. Any mutating operation+ // on a given bare repo (clone, fetch, worktree add, ref update) must+ // hold its lock — git's own lockfiles (packed-refs.lock, config.lock,+ // worktree admin dirs) don't tolerate parallel mutations on the same+ // repo. Separate repos are independent and run concurrently.+ repoLocks sync.Map // barePath -> *sync.Mutex}// New creates a new repo cache rooted at the given directory.@@ -39,13 +44,26 @@ func New(root string, logger *slog.Logger) *Cache {return &Cache{root: root, logger: logger}}+// lockForRepo returns the mutex dedicated to the given bare repo path. See+// the Cache.repoLocks field comment for semantics.+func (c *Cache) lockForRepo(barePath string) *sync.Mutex {+ if l, ok := c.repoLocks.Load(barePath); ok {+ return l.(*sync.Mutex)+ }+ newLock := &sync.Mutex{}+ actual, _ := c.repoLocks.LoadOrStore(barePath, newLock)+ return actual.(*sync.Mutex)+}+// Sync ensures all repos for a workspace are cloned (or fetched if already cached).// Repos no longer in the list are left in place (cheap to keep, avoids re-cloning// if a repo is temporarily removed and re-added).+//+// Per-repo mutation serializes against CreateWorktree on the same bare path+// via lockForRepo. Different repos run sequentially within a single Sync call+// but concurrent Sync calls (different workspaces, or the same workspace+// re-synced while checkouts are running) do not block each other.func (c *Cache) Sync(workspaceID string, repos []RepoInfo) error {- c.mu.Lock()- defer c.mu.Unlock()-wsDir := filepath.Join(c.root, workspaceID)if err := os.MkdirAll(wsDir, 0o755); err != nil {return fmt.Errorf("create workspace cache dir: %w", err)@@ -58,6 +76,8 @@ func (c *Cache) Sync(workspaceID string, repos []RepoInfo) error {}barePath := filepath.Join(wsDir, bareDirName(repo.URL))+ repoLock := c.lockForRepo(barePath)+ repoLock.Lock()if isBareRepo(barePath) {// Already cached — fetch latest.c.logger.Info("repo cache: fetching", "url", repo.URL, "path", barePath)@@ -77,6 +97,7 @@ func (c *Cache) Sync(workspaceID string, repos []RepoInfo) error {}}}+ repoLock.Unlock()}return firstErr}@@ -127,6 +148,13 @@ func isBareRepo(path string) bool {return err == nil}+// modernFetchRefspec is the remote-tracking refspec that keeps fetched heads+// out of the bare repo's refs/heads/* namespace. That namespace is reserved+// for per-task worktree branches created by `git worktree add -b ...`, and any+// mirror-style fetch that targets refs/heads/* can collide with those locked+// refs and abort the entire fetch.+const modernFetchRefspec = "+refs/heads/*:refs/remotes/origin/*"+func gitCloneBare(url, dest string) error {cmd := exec.Command("git", "clone", "--bare", url, dest)if out, err := cmd.CombinedOutput(); err != nil {@@ -134,16 +162,46 @@ func gitCloneBare(url, dest string) error {os.RemoveAll(dest)return fmt.Errorf("git clone --bare: %s: %w", strings.TrimSpace(string(out)), err)}- // Ensure fetch refspec is configured so `git fetch` updates local branches.- // `git clone --bare` doesn't set this by default.- cmd = exec.Command("git", "-C", dest, "config", "remote.origin.fetch", "+refs/heads/*:refs/heads/*")- if out, err := cmd.CombinedOutput(); err != nil {- return fmt.Errorf("configure fetch refspec: %s: %w", strings.TrimSpace(string(out)), err)+ // `git clone --bare` populates refs/heads/* as a snapshot and defaults to+ // a mirror-style fetch refspec. Convert the bare repo to the standard+ // remote-tracking layout immediately so subsequent fetches write to+ // refs/remotes/origin/* and can't conflict with worktree-locked heads.+ if err := ensureRemoteTrackingLayout(dest); err != nil {+ os.RemoveAll(dest)+ return fmt.Errorf("configure fetch refspec: %w", err)}return nil}+// gitFetch runs `git fetch origin` on a bare cache, migrating its fetch+// refspec to the remote-tracking layout first if it's still using the legacy+// mirror-style layout from an older version of this package. After a+// successful fetch it also refreshes refs/remotes/origin/HEAD so a remote+// default-branch change (e.g. master→main on an existing repo) actually+// takes effect in getRemoteDefaultBranch. Plain `git fetch origin` never+// touches that symref on its own, so without this call an existing cache+// would keep basing new worktrees on the original default branch forever+// after the remote flipped.func gitFetch(barePath string) error {+ if err := ensureRemoteTrackingLayout(barePath); err != nil {+ return fmt.Errorf("ensure refspec: %w", err)+ }+ if err := runGitFetch(barePath); err != nil {+ return err+ }+ // Refresh refs/remotes/origin/HEAD after every successful fetch.+ // set-head --auto is lightweight (a single ls-remote HEAD round-trip)+ // and non-fatal: if it fails we still have the step 2-5 fallbacks in+ // getRemoteDefaultBranch, but the modern-cache default-branch-change+ // path (the only path that can't be recovered any other way) relies+ // on this call.+ _ = exec.Command("git", "-C", barePath, "remote", "set-head", "origin", "--auto").Run()+ return nil+}++// runGitFetch is the raw `git fetch origin` wrapper. Callers should go through+// gitFetch, which migrates legacy caches first.+func runGitFetch(barePath string) error {cmd := exec.Command("git", "-C", barePath, "fetch", "origin")if out, err := cmd.CombinedOutput(); err != nil {return fmt.Errorf("git fetch: %s: %w", strings.TrimSpace(string(out)), err)@@ -151,6 +209,58 @@ func gitFetch(barePath string) error {return nil}+// ensureRemoteTrackingLayout upgrades a bare repo from the legacy mirror+// refspec (+refs/heads/*:refs/heads/*) to the standard remote-tracking refspec+// (+refs/heads/*:refs/remotes/origin/*). It's idempotent: on an already-modern+// cache it's a single `git config --get` call. On legacy caches it rewrites+// the refspec, performs a backfill fetch to populate refs/remotes/origin/*,+// and runs `git remote set-head origin --auto` so getRemoteDefaultBranch can+// resolve the remote's default branch.+func ensureRemoteTrackingLayout(barePath string) error {+ cur, err := readFetchRefspec(barePath)+ if err != nil {+ return err+ }+ if cur == modernFetchRefspec || cur == strings.TrimPrefix(modernFetchRefspec, "+") {+ return nil // already modern+ }+ if err := setFetchRefspec(barePath, modernFetchRefspec); err != nil {+ return err+ }+ // Backfill refs/remotes/origin/* by fetching with the new refspec. This+ // writes to the origin/* namespace, so even worktree-locked refs/heads/*+ // branches can't collide.+ if err := runGitFetch(barePath); err != nil {+ return fmt.Errorf("backfill fetch after refspec migration: %w", err)+ }+ // Set refs/remotes/origin/HEAD so getRemoteDefaultBranch can read it.+ // Non-fatal: if this fails we fall back to origin/main, origin/master.+ _ = exec.Command("git", "-C", barePath, "remote", "set-head", "origin", "--auto").Run()+ return nil+}++// readFetchRefspec returns the current remote.origin.fetch config value, or+// the empty string if it's not set. Distinguishes "missing" (exit 1) from+// real git errors.+func readFetchRefspec(barePath string) (string, error) {+ out, err := exec.Command("git", "-C", barePath, "config", "--get", "remote.origin.fetch").Output()+ if err != nil {+ if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() == 1 {+ return "", nil // key missing, not an error+ }+ return "", fmt.Errorf("read remote.origin.fetch: %w", err)+ }+ return strings.TrimSpace(string(out)), nil+}++func setFetchRefspec(barePath, refspec string) error {+ out, err := exec.Command("git", "-C", barePath, "config", "remote.origin.fetch", refspec).CombinedOutput()+ if err != nil {+ return fmt.Errorf("set remote.origin.fetch: %s: %w", strings.TrimSpace(string(out)), err)+ }+ return nil+}+// WorktreeParams holds inputs for creating a worktree from a cached bare clone.type WorktreeParams struct {WorkspaceID string // workspace that owns the repo@@ -176,13 +286,37 @@ func (c *Cache) CreateWorktree(params WorktreeParams) (*WorktreeResult, error) {return nil, fmt.Errorf("repo not found in cache: %s (workspace: %s)", params.RepoURL, params.WorkspaceID)}- // Fetch latest from origin.+ // Serialize concurrent CreateWorktree calls on the same bare repo. Git's+ // own lockfiles (packed-refs.lock, config.lock, worktree admin dirs)+ // can't tolerate parallel fetch + worktree mutations on the same repo.+ repoLock := c.lockForRepo(barePath)+ repoLock.Lock()+ defer repoLock.Unlock()++ // Fetch latest from origin. This also migrates the bare cache's refspec+ // to the modern remote-tracking layout on first run, so subsequent fetches+ // never collide with the refs/heads/agent/* branches that worktree creation+ // locks in this same bare repo.if err := gitFetch(barePath); err != nil {- c.logger.Warn("repo checkout: fetch failed (continuing with cached state)", "url", params.RepoURL, "error", err)+ // Non-fatal: preserve cached state and continue, but make the warning+ // loud enough that it's findable in the daemon log. The agent will+ // receive an older snapshot than the remote head.+ c.logger.Warn("repo checkout: fetch failed, agent will see possibly stale code",+ "url", params.RepoURL,+ "error", err,+ )}- // Determine the default branch to base the worktree on.+ // Determine the default branch to base the worktree on. getRemoteDefaultBranch+ // walks origin/HEAD → origin/main, origin/master → bare-HEAD hint into+ // origin/<same> → single-entry scan of origin/* → bare HEAD (only if+ // origin/* is empty). Reaching "" here means the cache is in a state we+ // refuse to guess from (no origin/HEAD, no main/master, bare HEAD doesn't+ // match any origin/* entry, and origin/* has multiple candidates).baseRef := getRemoteDefaultBranch(barePath)+ if baseRef == "" {+ return nil, fmt.Errorf("cannot resolve default branch for %s: bare cache at %s has no usable refs (origin/* is empty or ambiguous and bare HEAD has no match). The cache may be corrupted; delete it and retry", params.RepoURL, barePath)+ }// Build branch name: agent/{sanitized-name}/{short-task-id}branchName := fmt.Sprintf("agent/%s/%s", sanitizeName(params.AgentName), shortID(params.TaskID))@@ -216,8 +350,10 @@ func (c *Cache) CreateWorktree(params WorktreeParams) (*WorktreeResult, error) {}, nil}- // Create a new worktree.- if err := createWorktree(barePath, worktreePath, branchName, baseRef); err != nil {+ // Create a new worktree. createWorktree may rename the branch to avoid+ // collisions with stale per-task refs left over from previous runs.+ actualBranch, err := createWorktree(barePath, worktreePath, branchName, baseRef)+ if err != nil {return nil, fmt.Errorf("create worktree: %w", err)}@@ -229,25 +365,39 @@ func (c *Cache) CreateWorktree(params WorktreeParams) (*WorktreeResult, error) {c.logger.Info("repo checkout: worktree created","url", params.RepoURL,"path", worktreePath,- "branch", branchName,+ "branch", actualBranch,"base", baseRef,)return &WorktreeResult{Path: worktreePath,- BranchName: branchName,+ BranchName: actualBranch,}, nil}// createWorktree creates a git worktree at the given path with a new branch.-func createWorktree(gitRoot, worktreePath, branchName, baseRef string) error {+// Returns the actual branch name used — which may differ from the requested+// branchName if a collision was resolved by appending a timestamp suffix.+func createWorktree(gitRoot, worktreePath, branchName, baseRef string) (string, error) {+ // Pre-check: if the worktree path already exists we would get a confusing+ // "already exists" error from `git worktree add` — which used to be+ // misclassified as a branch collision, causing the retry to leak branches+ // into the bare repo. Fail cleanly here instead. The caller is expected+ // to route reused workdirs through updateExistingWorktree via isGitWorktree.+ if _, err := os.Stat(worktreePath); err == nil {+ return "", fmt.Errorf("worktree path already exists and is not a valid git worktree: %s", worktreePath)+ }+err := runWorktreeAdd(gitRoot, worktreePath, branchName, baseRef)- if err != nil && strings.Contains(err.Error(), "already exists") {+ if err != nil && isBranchCollisionError(err) {// Branch name collision: append timestamp and retry once.branchName = fmt.Sprintf("%s-%d", branchName, time.Now().Unix())err = runWorktreeAdd(gitRoot, worktreePath, branchName, baseRef)}- return err+ if err != nil {+ return "", err+ }+ return branchName, nil}func runWorktreeAdd(gitRoot, worktreePath, branchName, baseRef string) error {@@ -258,6 +408,20 @@ func runWorktreeAdd(gitRoot, worktreePath, branchName, baseRef string) error {return nil}+// isBranchCollisionError returns true if err is specifically about a branch+// name already existing. Git's other "already exists" messages (notably path+// collisions from `git worktree add`) must NOT be treated as branch+// collisions, or the retry-with-timestamp logic will leak branches while+// still failing on the original path collision.+func isBranchCollisionError(err error) bool {+ if err == nil {+ return false+ }+ msg := strings.ToLower(err.Error())+ // Git's message is "fatal: a branch named 'X' already exists".+ return strings.Contains(msg, "a branch named")+}+// isGitWorktree checks if a path is an existing git worktree.// Worktrees have a .git *file* (not directory) that points to the main repo.func isGitWorktree(path string) bool {@@ -282,51 +446,144 @@ func updateExistingWorktree(worktreePath, branchName, baseRef string) (string, ereturn "", fmt.Errorf("git clean -fd: %s: %w", strings.TrimSpace(string(out)), err)}- // Create a new branch from the latest default branch and switch to it.- // Use baseRef directly (not origin/baseRef) — the bare clone's fetch refspec- // maps remote branches to local refs, so remote-tracking refs may not exist.+ // Create a new branch from the resolved default-branch ref and switch to+ // it. baseRef is a ref path returned by getRemoteDefaultBranch — usually+ // "refs/remotes/origin/<branch>" but may be "refs/heads/<branch>" on a+ // legacy/migration-pending cache. Either form is valid as a checkout+ // startpoint.checkoutCmd := exec.Command("git", "-C", worktreePath, "checkout", "-b", branchName, baseRef)- if out, err := checkoutCmd.CombinedOutput(); err != nil {- // Branch name collision: append timestamp and retry once.- if strings.Contains(string(out), "already exists") {- branchName = fmt.Sprintf("%s-%d", branchName, time.Now().Unix())- checkoutCmd = exec.Command("git", "-C", worktreePath, "checkout", "-b", branchName, baseRef)- if out2, err2 := checkoutCmd.CombinedOutput(); err2 != nil {- return "", fmt.Errorf("git checkout -b (retry): %s: %w", strings.TrimSpace(string(out2)), err2)- }- return branchName, nil- }- return "", fmt.Errorf("git checkout -b: %s: %w", strings.TrimSpace(string(out)), err)+ out, err := checkoutCmd.CombinedOutput()+ if err == nil {+ return branchName, nil+ }+ wrapped := fmt.Errorf("git checkout -b: %s: %w", strings.TrimSpace(string(out)), err)+ if !isBranchCollisionError(wrapped) {+ return "", wrapped+ }+ // Branch name collision: append timestamp and retry once.+ branchName = fmt.Sprintf("%s-%d", branchName, time.Now().Unix())+ checkoutCmd = exec.Command("git", "-C", worktreePath, "checkout", "-b", branchName, baseRef)+ if out2, err2 := checkoutCmd.CombinedOutput(); err2 != nil {+ return "", fmt.Errorf("git checkout -b (retry): %s: %w", strings.TrimSpace(string(out2)), err2)}return branchName, nil}-// getRemoteDefaultBranch returns the default branch ref for a bare repo.-// Tries HEAD, then falls back to "main", then "master".+// getRemoteDefaultBranch returns a ref path (e.g. "refs/remotes/origin/main")+// that points at the remote's default branch in a bare cache. The return value+// is usable directly as a `git worktree add` / `git checkout -b` startpoint.+//+// Resolution order:+// 1. refs/remotes/origin/HEAD (verified; set by `git remote set-head origin --auto`)+// 2. refs/remotes/origin/main, refs/remotes/origin/master (common defaults)+// 3. The bare repo's own HEAD mapped into refs/remotes/origin/<same name> —+// `git clone --bare` sets HEAD to the remote's default, so this is a+// reliable hint for custom default branches (trunk, develop, …) when+// `git remote set-head --auto` failed to populate refs/remotes/origin/HEAD.+// 4. Scan refs/remotes/origin/* — returns a result ONLY when exactly one+// non-HEAD ref exists. Multiple refs cannot be disambiguated from refname+// order alone (git for-each-ref sorts alphabetically), so we refuse to+// guess; returning a wrong default would silently base new agent work on+// an arbitrary feature branch.+// 5. Legacy last-resort: the bare repo's own HEAD as a plain refs/heads/*+// ref, for caches that haven't populated refs/remotes/origin/* at all+// yet (e.g. a migration-pending cache whose backfill fetch failed).+// Gated on refs/remotes/origin/* being completely empty so we don't fall+// back to a stale snapshot when the cache has real remote-tracking refs+// but we just can't pick between them.+//+// Returns "" only when none of the above resolve — which the caller treats+// as a hard error with a clear "cache has no usable refs" message.func getRemoteDefaultBranch(barePath string) string {- // In a bare repo, HEAD points to the default branch.- cmd := exec.Command("git", "-C", barePath, "symbolic-ref", "HEAD")- if out, err := cmd.Output(); err == nil {+ // 1) Primary: refs/remotes/origin/HEAD set by `git remote set-head+ // origin --auto` during ensureRemoteTrackingLayout. Verify the+ // target actually exists — a partial set-head or a manually-broken+ // repo can leave a symref pointing at a deleted ref, and returning+ // it here would later fail in `git worktree add` with a confusing+ // "invalid reference" error.+ if out, err := exec.Command("git", "-C", barePath, "symbolic-ref", "refs/remotes/origin/HEAD").Output(); err == nil {ref := strings.TrimSpace(string(out))- // ref looks like "refs/heads/main" — return just the branch name.- if strings.HasPrefix(ref, "refs/heads/") {- return strings.TrimPrefix(ref, "refs/heads/")+ if ref != "" {+ if err := exec.Command("git", "-C", barePath, "rev-parse", "--verify", ref).Run(); err == nil {+ return ref+ }}- return ref}-- // Fallback: check if main branch exists.- cmd = exec.Command("git", "-C", barePath, "rev-parse", "--verify", "main")- if err := cmd.Run(); err == nil {- return "main"+ // 2) Common default branch names under the origin namespace.+ for _, candidate := range []string{"refs/remotes/origin/main", "refs/remotes/origin/master"} {+ if err := exec.Command("git", "-C", barePath, "rev-parse", "--verify", candidate).Run(); err == nil {+ return candidate+ }}-- cmd = exec.Command("git", "-C", barePath, "rev-parse", "--verify", "master")- if err := cmd.Run(); err == nil {- return "master"+ // 3) Use the bare repo's own HEAD as a hint. `git clone --bare` sets HEAD+ // to the remote's default branch, so this reliably identifies custom+ // default branch names (trunk, develop, ...) when set-head --auto+ // didn't populate refs/remotes/origin/HEAD. We only return when the+ // matching origin/<name> exists, so we still pick up up-to-date code+ // rather than a stale local head.+ bareRef := bareHeadBranch(barePath)+ if bareRef != "" {+ originRef := "refs/remotes/origin/" + strings.TrimPrefix(bareRef, "refs/heads/")+ if err := exec.Command("git", "-C", barePath, "rev-parse", "--verify", originRef).Run(); err == nil {+ return originRef+ }+ }+ // 4) Scan refs/remotes/origin/* — return a result ONLY when there's+ // exactly one non-HEAD candidate. Multiple candidates cannot be+ // disambiguated from refname order alone; returning the alphabetically-+ // first entry would silently base new agent work on a feature branch+ // instead of the real default. Count entries here so step 5 can tell+ // "legacy empty" apart from "ambiguous".+ originCount := 0+ var singleton string+ if out, err := exec.Command("git", "-C", barePath, "for-each-ref", "--format=%(refname)", "refs/remotes/origin/").Output(); err == nil {+ for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {+ line = strings.TrimSpace(line)+ if line == "" || line == "refs/remotes/origin/HEAD" {+ continue+ }+ originCount+++ if singleton == "" {+ singleton = line+ }+ }+ if originCount == 1 {+ return singleton+ }}+ // 5) Last-resort fallback: legacy / migration-pending caches still have+ // refs/heads/* and a bare HEAD from the mirror-style layout. Gate this+ // on refs/remotes/origin/* being completely empty — if origin/* has+ // multiple refs but none match bare HEAD, the cache is in an+ // ambiguous state and returning the local head would mask the+ // problem with a stale snapshot. Let the caller fail loudly instead.+ if originCount == 0 && bareRef != "" {+ return bareRef+ }+ return ""+}- return "HEAD"+// bareHeadBranch returns the bare repo's local HEAD ref (e.g.+// "refs/heads/main") if HEAD is a symbolic ref to an existing branch.+// Returns "" if HEAD is detached, missing, or points at a non-existent ref.+//+// Only used by getRemoteDefaultBranch as a last-resort fallback for caches+// that haven't successfully populated refs/remotes/origin/* yet. Healthy+// modern caches should never reach this path because origin/* resolution+// succeeds first.+func bareHeadBranch(barePath string) string {+ out, err := exec.Command("git", "-C", barePath, "symbolic-ref", "HEAD").Output()+ if err != nil {+ return ""+ }+ ref := strings.TrimSpace(string(out))+ if ref == "" {+ return ""+ }+ if err := exec.Command("git", "-C", barePath, "rev-parse", "--verify", ref).Run(); err != nil {+ return ""+ }+ return ref}// excludeFromGit adds a pattern to the worktree's .git/info/exclude file.diff --git a/server/internal/daemon/repocache/cache_test.go b/server/internal/daemon/repocache/cache_test.goindex 6be2147053..bf0a8ba392 100644--- a/server/internal/daemon/repocache/cache_test.go+++ b/server/internal/daemon/repocache/cache_test.go@@ -117,19 +117,15 @@ func TestSyncFetchesExisting(t *testing.T) {t.Fatalf("first sync failed: %v", err)}- // Record the HEAD commit hash in the cache.+ // Record the remote-tracking default head in the cache. Under the modern+ // refspec layout, fetches write to refs/remotes/origin/*, not the bare+ // repo's own refs/heads/*, so reading the bare HEAD would return the+ // fossil snapshot from initial clone.barePath := cache.Lookup("ws-1", sourceRepo)- oldHead := gitHead(t, barePath)+ oldHead := gitRefCommit(t, barePath, getRemoteDefaultBranch(barePath))// Add a commit to source.- cmd := exec.Command("git", "-C", sourceRepo, "commit", "--allow-empty", "-m", "second")- cmd.Env = append(os.Environ(),- "GIT_AUTHOR_NAME=test", "[email protected]",- "GIT_COMMITTER_NAME=test", "[email protected]",- )- if out, err := cmd.CombinedOutput(); err != nil {- t.Fatalf("add commit failed: %s: %v", out, err)- }+ addEmptyCommit(t, sourceRepo, "second")sourceHead := gitHead(t, sourceRepo)if sourceHead == oldHead {t.Fatal("source HEAD should differ after new commit")@@ -140,13 +136,13 @@ func TestSyncFetchesExisting(t *testing.T) {t.Fatalf("second sync failed: %v", err)}- // Verify the cache HEAD was updated.- newHead := gitHead(t, barePath)+ // Verify the cache remote-tracking ref was updated.+ newHead := gitRefCommit(t, barePath, getRemoteDefaultBranch(barePath))if newHead == oldHead {- t.Fatal("expected cache HEAD to be updated after fetch")+ t.Fatal("expected cache remote-tracking head to be updated after fetch")}if newHead != sourceHead {- t.Fatalf("expected cache HEAD %s to match source HEAD %s", newHead, sourceHead)+ t.Fatalf("expected cache head %s to match source head %s", newHead, sourceHead)}}@@ -260,3 +256,464 @@ func TestCreateWorktreeNotCached(t *testing.T) {func trimLine(s string) string {return strings.TrimSpace(s)}++// gitRefCommit resolves a git ref to its commit SHA in repoPath.+func gitRefCommit(t *testing.T, repoPath, ref string) string {+ t.Helper()+ if ref == "" {+ t.Fatalf("empty ref in %s", repoPath)+ }+ cmd := exec.Command("git", "-C", repoPath, "rev-parse", ref)+ out, err := cmd.Output()+ if err != nil {+ t.Fatalf("git rev-parse %s failed in %s: %v", ref, repoPath, err)+ }+ return strings.TrimSpace(string(out))+}++// addEmptyCommit adds an empty commit on the current branch of repoPath.+func addEmptyCommit(t *testing.T, repoPath, message string) {+ t.Helper()+ cmd := exec.Command("git", "-C", repoPath, "commit", "--allow-empty", "-m", message)+ cmd.Env = append(os.Environ(),+ "GIT_AUTHOR_NAME=test", "[email protected]",+ "GIT_COMMITTER_NAME=test", "[email protected]",+ )+ if out, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("git commit failed in %s: %s: %v", repoPath, out, err)+ }+}++// runGitAuthored runs `git -C repoPath <args...>` with the test author env set.+func runGitAuthored(t *testing.T, repoPath string, args ...string) {+ t.Helper()+ full := append([]string{"-C", repoPath}, args...)+ cmd := exec.Command("git", full...)+ cmd.Env = append(os.Environ(),+ "GIT_AUTHOR_NAME=test", "[email protected]",+ "GIT_COMMITTER_NAME=test", "[email protected]",+ )+ if out, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("git %v in %s: %s: %v", args, repoPath, out, err)+ }+}++// TestCreateWorktreeFetchesDespiteAgentBranchOnRemote reproduces the original+// stale-cache bug. Under the legacy mirror refspec (+refs/heads/*:refs/heads/*)+// the sequence below would break on the second CreateWorktree because `git+// fetch` tries to overwrite refs/heads/agent/... which is locked by the first+// worktree, and the whole fetch aborts — silently discarding the main-branch+// update too. Under the modern remote-tracking refspec, fetched heads land in+// refs/remotes/origin/* and no longer collide with worktree-locked refs.+func TestCreateWorktreeFetchesDespiteAgentBranchOnRemote(t *testing.T) {+ t.Parallel()+ sourceRepo := createTestRepo(t)+ // Capture the default branch BEFORE any detach/commit/checkout dance — we+ // need its name later to add new commits to the correct branch.+ defaultBranch := currentBranchName(t, sourceRepo)++ // Put source repo on a detached HEAD so the first worktree's agent branch+ // can be pushed back to it as a regular update (non-bare repos refuse to+ // push to the currently checked-out branch).+ runGitAuthored(t, sourceRepo, "checkout", "--detach", "HEAD")++ cacheRoot := t.TempDir()+ cache := New(cacheRoot, testLogger())+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {+ t.Fatalf("sync failed: %v", err)+ }++ // First worktree creates refs/heads/agent/... inside the bare cache.+ workDir1 := t.TempDir()+ result1, err := cache.CreateWorktree(WorktreeParams{+ WorkspaceID: "ws-1",+ RepoURL: sourceRepo,+ WorkDir: workDir1,+ AgentName: "agent",+ TaskID: "t1111111-0000-0000-0000-000000000000",+ })+ if err != nil {+ t.Fatalf("first CreateWorktree failed: %v", err)+ }++ // Simulate the agent pushing its branch back to origin (i.e. opening a PR).+ // Now sourceRepo has refs/heads/agent/... matching the locked ref in the+ // bare cache, which is the condition that triggered the legacy bug.+ if err := os.WriteFile(filepath.Join(result1.Path, "hello.txt"), []byte("hi\n"), 0o644); err != nil {+ t.Fatalf("write file: %v", err)+ }+ runGitAuthored(t, result1.Path, "add", ".")+ runGitAuthored(t, result1.Path, "commit", "-m", "first task")+ runGitAuthored(t, result1.Path, "push", "origin", result1.BranchName)++ // Add a new commit to source's default branch (not the agent branch we+ // just pushed). Then re-detach so future pushes to other branches still work.+ runGitAuthored(t, sourceRepo, "checkout", defaultBranch)+ addEmptyCommit(t, sourceRepo, "new commit on default branch")+ sourceHead := gitRefCommit(t, sourceRepo, "refs/heads/"+defaultBranch)+ runGitAuthored(t, sourceRepo, "checkout", "--detach", "HEAD")++ // Second worktree: CreateWorktree fetches first. Under the legacy refspec+ // this fetch would fail (refusing to fetch into locked refs/heads/agent/...)+ // and the worktree would be based on the stale snapshot. Under the modern+ // refspec this succeeds and the new worktree sees sourceHead.+ workDir2 := t.TempDir()+ result2, err := cache.CreateWorktree(WorktreeParams{+ WorkspaceID: "ws-1",+ RepoURL: sourceRepo,+ WorkDir: workDir2,+ AgentName: "agent",+ TaskID: "t2222222-0000-0000-0000-000000000000",+ })+ if err != nil {+ t.Fatalf("second CreateWorktree failed: %v", err)+ }++ if got := gitHead(t, result2.Path); got != sourceHead {+ t.Fatalf("second worktree HEAD = %s, want %s (remote default head after new commit)", got, sourceHead)+ }+}++// currentBranchName returns the branch name that HEAD points at in repoPath.+// Fails the test if HEAD is detached.+func currentBranchName(t *testing.T, repoPath string) string {+ t.Helper()+ out, err := exec.Command("git", "-C", repoPath, "symbolic-ref", "--short", "HEAD").Output()+ if err != nil {+ t.Fatalf("symbolic-ref --short HEAD in %s: %v", repoPath, err)+ }+ name := strings.TrimSpace(string(out))+ if name == "" {+ t.Fatalf("empty branch name in %s", repoPath)+ }+ return name+}++// TestEnsureRemoteTrackingLayoutMigratesLegacyCache verifies that a cache+// created with the legacy mirror refspec is migrated in place on next use:+// the refspec is rewritten to the modern remote-tracking layout and+// refs/remotes/origin/* gets backfilled so getRemoteDefaultBranch can resolve+// the remote default.+func TestEnsureRemoteTrackingLayoutMigratesLegacyCache(t *testing.T) {+ t.Parallel()+ sourceRepo := createTestRepo(t)+ cacheRoot := t.TempDir()+ cache := New(cacheRoot, testLogger())+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {+ t.Fatalf("sync failed: %v", err)+ }+ barePath := cache.Lookup("ws-1", sourceRepo)++ // Reset to the legacy mirror refspec to simulate a cache created by an+ // older version of the daemon.+ if err := setFetchRefspec(barePath, "+refs/heads/*:refs/heads/*"); err != nil {+ t.Fatalf("set legacy refspec: %v", err)+ }+ // Wipe any refs/remotes/origin/* that may have been populated by the initial clone.+ _ = exec.Command("git", "-C", barePath, "update-ref", "-d", "refs/remotes/origin/HEAD").Run()+ if err := exec.Command("sh", "-c", "rm -rf '"+filepath.Join(barePath, "refs", "remotes")+"'").Run(); err != nil {+ t.Fatalf("wipe refs/remotes: %v", err)+ }++ // Sanity check: we've successfully forced the cache into legacy state.+ if cur, _ := readFetchRefspec(barePath); cur != "+refs/heads/*:refs/heads/*" {+ t.Fatalf("precondition failed: refspec is %q, want legacy mirror", cur)+ }++ // ensureRemoteTrackingLayout should migrate: rewrite refspec, backfill+ // refs/remotes/origin/*, and set origin HEAD.+ if err := ensureRemoteTrackingLayout(barePath); err != nil {+ t.Fatalf("ensureRemoteTrackingLayout failed: %v", err)+ }++ cur, err := readFetchRefspec(barePath)+ if err != nil {+ t.Fatalf("read refspec after migration: %v", err)+ }+ if cur != modernFetchRefspec {+ t.Errorf("refspec = %q, want %q", cur, modernFetchRefspec)+ }++ // getRemoteDefaultBranch should now return a refs/remotes/origin/<branch>.+ ref := getRemoteDefaultBranch(barePath)+ if !strings.HasPrefix(ref, "refs/remotes/origin/") {+ t.Errorf("getRemoteDefaultBranch = %q, want refs/remotes/origin/*", ref)+ }+}++// TestCreateWorktreePathCollisionDoesNotLeakBranch verifies the secondary bug+// fix: when the worktree path already exists as a non-worktree (e.g. a plain+// directory), createWorktree must fail cleanly without leaking a branch into+// the bare repo. Previously the "already exists" retry logic would+// misclassify path collisions as branch collisions and create a second+// timestamp-suffixed branch before hitting the same path error.+func TestCreateWorktreePathCollisionDoesNotLeakBranch(t *testing.T) {+ t.Parallel()+ sourceRepo := createTestRepo(t)+ cacheRoot := t.TempDir()+ cache := New(cacheRoot, testLogger())+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {+ t.Fatalf("sync failed: %v", err)+ }+ barePath := cache.Lookup("ws-1", sourceRepo)++ // Pre-create the target worktree path as a plain non-empty directory.+ workDir := t.TempDir()+ dirName := repoNameFromURL(sourceRepo)+ worktreePath := filepath.Join(workDir, dirName)+ if err := os.MkdirAll(worktreePath, 0o755); err != nil {+ t.Fatalf("pre-create worktree path: %v", err)+ }+ if err := os.WriteFile(filepath.Join(worktreePath, "stray.txt"), []byte("x"), 0o644); err != nil {+ t.Fatalf("write stray file: %v", err)+ }++ _, err := cache.CreateWorktree(WorktreeParams{+ WorkspaceID: "ws-1",+ RepoURL: sourceRepo,+ WorkDir: workDir,+ AgentName: "agent",+ TaskID: "t1111111-0000-0000-0000-000000000000",+ })+ if err == nil {+ t.Fatal("expected CreateWorktree to fail when path exists as non-worktree")+ }++ // No agent/* branches should have been created in the bare repo as a+ // side effect of the failed call.+ out, runErr := exec.Command("git", "-C", barePath, "for-each-ref", "--format=%(refname)", "refs/heads/agent").Output()+ if runErr != nil {+ t.Fatalf("for-each-ref failed: %v", runErr)+ }+ if leaked := strings.TrimSpace(string(out)); leaked != "" {+ t.Errorf("branch leaked into bare repo after path-collision failure:\n%s", leaked)+ }+}++// TestGetRemoteDefaultBranchScansForCustomDefault verifies fallback (3) of+// getRemoteDefaultBranch: when the cache has refs/remotes/origin/<custom>+// (e.g. develop, trunk) but no refs/remotes/origin/HEAD and no main/master,+// the function picks the custom branch instead of returning empty.+func TestGetRemoteDefaultBranchScansForCustomDefault(t *testing.T) {+ t.Parallel()+ sourceRepo := createTestRepo(t)+ cacheRoot := t.TempDir()+ cache := New(cacheRoot, testLogger())+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {+ t.Fatalf("sync failed: %v", err)+ }+ barePath := cache.Lookup("ws-1", sourceRepo)++ // Resolve the existing default branch's commit so we can repoint a+ // custom-named ref at it, then wipe the standard refs to force the+ // fallback path.+ existing := getRemoteDefaultBranch(barePath)+ if existing == "" {+ t.Fatalf("precondition: cache should have a default branch right after sync")+ }+ commit := gitRefCommit(t, barePath, existing)++ // Create refs/remotes/origin/develop pointing at that commit.+ runGitAuthored(t, barePath, "update-ref", "refs/remotes/origin/develop", commit)+ // Now wipe origin/HEAD (symbolic-ref -d removes the symref file itself)+ // and the common defaults so steps 1 and 2 of the resolver miss and we+ // fall through to the for-each-ref scan.+ _ = exec.Command("git", "-C", barePath, "symbolic-ref", "-d", "refs/remotes/origin/HEAD").Run()+ _ = exec.Command("git", "-C", barePath, "update-ref", "-d", "refs/remotes/origin/main").Run()+ _ = exec.Command("git", "-C", barePath, "update-ref", "-d", "refs/remotes/origin/master").Run()++ got := getRemoteDefaultBranch(barePath)+ if got != "refs/remotes/origin/develop" {+ t.Fatalf("getRemoteDefaultBranch = %q, want refs/remotes/origin/develop", got)+ }+}++// TestGetRemoteDefaultBranchFallsBackToBareHead verifies fallback (5):+// a legacy / migration-pending cache that has no refs/remotes/origin/* at all+// but still has its bare HEAD pointing at refs/heads/<branch> (the snapshot+// from the original mirror clone) should resolve to that local head instead+// of failing. This protects against transient backfill-fetch failures during+// the legacy → modern refspec migration. Gated on refs/remotes/origin/* being+// completely empty — with any modern remote-tracking refs present, the+// resolver refuses to reach back into the stale bare heads.+func TestGetRemoteDefaultBranchFallsBackToBareHead(t *testing.T) {+ t.Parallel()+ sourceRepo := createTestRepo(t)+ cacheRoot := t.TempDir()+ cache := New(cacheRoot, testLogger())+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {+ t.Fatalf("sync failed: %v", err)+ }+ barePath := cache.Lookup("ws-1", sourceRepo)++ // Force the cache into a state that mimics "legacy mirror clone whose+ // post-migration backfill fetch failed":+ // - bare HEAD still points at refs/heads/<default>+ // - refs/remotes/origin/* is empty+ if err := exec.Command("sh", "-c", "rm -rf '"+filepath.Join(barePath, "refs", "remotes")+"'").Run(); err != nil {+ t.Fatalf("wipe refs/remotes: %v", err)+ }++ // Sanity: origin/* is gone, HEAD is still a symbolic ref to refs/heads/*.+ if out, err := exec.Command("git", "-C", barePath, "for-each-ref", "refs/remotes/origin/").Output(); err == nil && strings.TrimSpace(string(out)) != "" {+ t.Fatalf("precondition failed: refs/remotes/origin/* should be empty, got %s", out)+ }++ got := getRemoteDefaultBranch(barePath)+ if !strings.HasPrefix(got, "refs/heads/") {+ t.Fatalf("getRemoteDefaultBranch = %q, want refs/heads/* fallback", got)+ }++ // And the resolved ref must actually exist — verifying bareHeadBranch's+ // rev-parse guard kicked in correctly.+ if err := exec.Command("git", "-C", barePath, "rev-parse", "--verify", got).Run(); err != nil {+ t.Fatalf("resolved ref %q does not exist: %v", got, err)+ }+}++// TestGitFetchRefreshesOriginHeadAfterDefaultChange verifies that an+// already-modern cache picks up a remote default-branch change. Plain `git+// fetch` never refreshes refs/remotes/origin/HEAD on its own, so without+// gitFetch's explicit `git remote set-head origin --auto` call the resolver+// would keep returning the original default branch forever after the+// upstream flipped (e.g. master → main on a long-lived repo). This guards+// against the "already-modern cache never refreshes origin/HEAD" regression.+func TestGitFetchRefreshesOriginHeadAfterDefaultChange(t *testing.T) {+ t.Parallel()+ sourceRepo := createTestRepo(t)+ initialBranch := currentBranchName(t, sourceRepo)++ cacheRoot := t.TempDir()+ cache := New(cacheRoot, testLogger())+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {+ t.Fatalf("sync failed: %v", err)+ }+ barePath := cache.Lookup("ws-1", sourceRepo)++ // Precondition: cache is already modern and origin/HEAD points at the+ // source's initial default branch.+ if got := getRemoteDefaultBranch(barePath); got != "refs/remotes/origin/"+initialBranch {+ t.Fatalf("precondition: getRemoteDefaultBranch = %q, want refs/remotes/origin/%s", got, initialBranch)+ }++ // Flip the source's default: create a new branch, commit on it, stay+ // checked out on it so the source's HEAD reflects the new default. A+ // subsequent `git ls-remote` against the source advertises this new+ // HEAD, which is what set-head --auto consumes.+ runGitAuthored(t, sourceRepo, "checkout", "-b", "new-default")+ addEmptyCommit(t, sourceRepo, "new-default commit")++ // Fetch via the cache's code path. Without the set-head call, origin/HEAD+ // would still point at the old default here.+ if err := gitFetch(barePath); err != nil {+ t.Fatalf("gitFetch failed: %v", err)+ }++ // refs/remotes/origin/HEAD must now point at the new default branch.+ out, err := exec.Command("git", "-C", barePath, "symbolic-ref", "refs/remotes/origin/HEAD").Output()+ if err != nil {+ t.Fatalf("symbolic-ref origin/HEAD after fetch: %v", err)+ }+ if got := strings.TrimSpace(string(out)); got != "refs/remotes/origin/new-default" {+ t.Fatalf("origin/HEAD after fetch = %q, want refs/remotes/origin/new-default", got)+ }++ // And getRemoteDefaultBranch must resolve through step 1 (verified+ // origin/HEAD) to the new default — not through step 2 where origin/main+ // or origin/master could accidentally match the old branch.+ if got := getRemoteDefaultBranch(barePath); got != "refs/remotes/origin/new-default" {+ t.Fatalf("getRemoteDefaultBranch after fetch = %q, want refs/remotes/origin/new-default", got)+ }+}++// TestGetRemoteDefaultBranchUsesBareHeadHintForCustomDefault verifies step 3+// of the resolver: when the cache has a non-standard default branch name+// (trunk, develop, …) and `git remote set-head origin --auto` didn't+// populate refs/remotes/origin/HEAD, the resolver must use the bare repo's+// own HEAD as a hint to pick refs/remotes/origin/<same name> — NOT fall+// through to a refname-order scan that would pick the wrong branch.+func TestGetRemoteDefaultBranchUsesBareHeadHintForCustomDefault(t *testing.T) {+ t.Parallel()+ sourceRepo := createTestRepo(t)+ cacheRoot := t.TempDir()+ cache := New(cacheRoot, testLogger())+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {+ t.Fatalf("sync failed: %v", err)+ }+ barePath := cache.Lookup("ws-1", sourceRepo)++ existing := getRemoteDefaultBranch(barePath)+ if existing == "" {+ t.Fatalf("precondition: cache should have a default branch right after sync")+ }+ commit := gitRefCommit(t, barePath, existing)++ // Simulate a custom default branch: create refs/heads/trunk in the bare+ // repo and point HEAD at it. `git clone --bare` would do the equivalent+ // when the remote's default was "trunk", so this matches real-world+ // state for such remotes.+ runGitAuthored(t, barePath, "update-ref", "refs/heads/trunk", commit)+ runGitAuthored(t, barePath, "symbolic-ref", "HEAD", "refs/heads/trunk")++ // Populate two refs/remotes/origin/* entries. "feature-alpha" is+ // alphabetically earlier than "trunk" — a refname-order scan (the old+ // bug) would return feature-alpha, not trunk.+ runGitAuthored(t, barePath, "update-ref", "refs/remotes/origin/trunk", commit)+ runGitAuthored(t, barePath, "update-ref", "refs/remotes/origin/feature-alpha", commit)++ // Knock out the ahead-of-step-3 fallbacks so resolution must rely on+ // the bare-HEAD hint.+ _ = exec.Command("git", "-C", barePath, "symbolic-ref", "-d", "refs/remotes/origin/HEAD").Run()+ _ = exec.Command("git", "-C", barePath, "update-ref", "-d", "refs/remotes/origin/main").Run()+ _ = exec.Command("git", "-C", barePath, "update-ref", "-d", "refs/remotes/origin/master").Run()++ got := getRemoteDefaultBranch(barePath)+ if got != "refs/remotes/origin/trunk" {+ t.Fatalf("getRemoteDefaultBranch = %q, want refs/remotes/origin/trunk (via bare-HEAD hint)", got)+ }+}++// TestGetRemoteDefaultBranchAmbiguousOriginReturnsEmpty verifies step 4's+// safe-scan gating: when the cache has multiple refs/remotes/origin/*+// entries, none match the common defaults, and none match the bare HEAD+// either, the resolver must refuse to guess and return "". The caller+// surfaces this as a hard error instead of silently basing new agent work+// on an arbitrary refname-order-first candidate.+func TestGetRemoteDefaultBranchAmbiguousOriginReturnsEmpty(t *testing.T) {+ t.Parallel()+ sourceRepo := createTestRepo(t)+ cacheRoot := t.TempDir()+ cache := New(cacheRoot, testLogger())+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {+ t.Fatalf("sync failed: %v", err)+ }+ barePath := cache.Lookup("ws-1", sourceRepo)++ existing := getRemoteDefaultBranch(barePath)+ if existing == "" {+ t.Fatalf("precondition: cache should have a default branch right after sync")+ }+ commit := gitRefCommit(t, barePath, existing)++ // Populate two unrelated origin branches (none of which match any of+ // the step 1-3 fallbacks).+ runGitAuthored(t, barePath, "update-ref", "refs/remotes/origin/feature-a", commit)+ runGitAuthored(t, barePath, "update-ref", "refs/remotes/origin/feature-b", commit)++ // Wipe every ref a step 1-3 fallback could pick up:+ // step 1: origin/HEAD+ // step 2: origin/main, origin/master+ // step 3: the origin/<bareHEAD-name> bridge+ _ = exec.Command("git", "-C", barePath, "symbolic-ref", "-d", "refs/remotes/origin/HEAD").Run()+ _ = exec.Command("git", "-C", barePath, "update-ref", "-d", "refs/remotes/origin/main").Run()+ _ = exec.Command("git", "-C", barePath, "update-ref", "-d", "refs/remotes/origin/master").Run()+ if bareRef := bareHeadBranch(barePath); bareRef != "" {+ sameName := strings.TrimPrefix(bareRef, "refs/heads/")+ _ = exec.Command("git", "-C", barePath, "update-ref", "-d", "refs/remotes/origin/"+sameName).Run()+ }++ got := getRemoteDefaultBranch(barePath)+ if got != "" {+ t.Fatalf("getRemoteDefaultBranch = %q, want \"\" (ambiguous origin/* must not guess)", got)+ }+}