Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): reuse checkout when repo checkout runs from inside it (MUL-9099) (#10465)
Jiayuan Zhangee7416bbf4f1
diff --git a/server/cmd/multica/cmd_repo.go b/server/cmd/multica/cmd_repo.goindex 8736436846..1456089176 100644--- a/server/cmd/multica/cmd_repo.go+++ b/server/cmd/multica/cmd_repo.go@@ -51,6 +51,9 @@ var repoCheckoutCmd = &cobra.Command{Use: "checkout <url>",Short: "Check out a repository into the working directory",Long: "Creates a git worktree from the daemon's bare clone cache. Used by agents to check out repos on demand.\n\n" ++ "The checkout goes in a subdirectory of the current directory named after the repository. Run from inside " ++ "an existing checkout of the same repository, it targets that checkout instead of nesting a second one in it; " ++ "a different repository is still placed inside the current directory.\n\n" +"Running it again where the repository is already checked out never silently discards work: a checkout " +"that has uncommitted changes, untracked files, or unpushed commits, or is already on this task's branch, " +"is kept as it is and only its remote refs are fetched. Pass --fresh to discard its uncommitted changes and " +diff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.goindex 9122beb275..43b6abf691 100644--- a/server/internal/daemon/health.go+++ b/server/internal/daemon/health.go@@ -287,25 +287,62 @@ func (d *Daemon) writeRepoCheckoutAuthError(w http.ResponseWriter, result repoCh// resolved is refused; the error says which side and why, because the caller// surfaces it instead of a bare "not owned".func authorizeRepoCheckoutWorkDir(activeRoot, requested string) (string, error) {- root, err := filepath.Abs(activeRoot)+ _, workdir, err := resolveRepoCheckoutWorkDir(activeRoot, requested)+ return workdir, err+}++// resolveRepoCheckoutWorkDir is authorizeRepoCheckoutWorkDir that also returns+// the resolved task root.+func resolveRepoCheckoutWorkDir(activeRoot, requested string) (root, workdir string, err error) {+ root, err = filepath.Abs(activeRoot)if err == nil {root, err = util.ResolveSymlinks(root)}if err != nil {- return "", fmt.Errorf("resolve active task workdir: %w", err)+ return "", "", fmt.Errorf("resolve active task workdir: %w", err)}- workdir, err := filepath.Abs(requested)+ workdir, err = filepath.Abs(requested)if err == nil {workdir, err = util.ResolveSymlinks(workdir)}if err != nil {- return "", fmt.Errorf("resolve requested workdir: %w", err)+ return "", "", fmt.Errorf("resolve requested workdir: %w", err)}rel, err := filepath.Rel(root, workdir)if err != nil || !filepath.IsLocal(rel) {- return "", fmt.Errorf("%s is outside the active task workdir %s", workdir, root)+ return "", "", fmt.Errorf("%s is outside the active task workdir %s", workdir, root)}- return workdir, nil+ return root, workdir, nil+}++// checkoutWorkDirOutsideOwnCheckout returns the directory a checkout of the+// repository cached at barePath, requested from workdir, belongs in: the+// parent of the outermost checkout of that same repository between root+// (exclusive) and workdir (inclusive), or workdir itself when it is not inside+// one. The CLI sends the agent's shell directory, which persists across+// commands, so re-running checkout from inside an existing checkout would+// otherwise create a second worktree nested in it — one a later `git add -A`+// in the outer checkout commits as an embedded repository (MUL-9099).+// Climbing out makes the re-run land on the existing checkout and reuse it.+// Checkouts of other repositories are not climbed out of, so checking one+// repository out inside another still places it there.+// Both paths must already be resolved, with workdir inside root.+func checkoutWorkDirOutsideOwnCheckout(ctx context.Context, root, workdir, barePath string) string {+ rel, err := filepath.Rel(root, workdir)+ if err != nil || rel == "." || barePath == "" {+ return workdir+ }+ dir := root+ for _, part := range strings.Split(rel, string(filepath.Separator)) {+ dir = filepath.Join(dir, part)+ if _, err := os.Lstat(filepath.Join(dir, ".git")); err != nil {+ continue+ }+ if repocache.CheckoutBelongsTo(ctx, barePath, dir) {+ return filepath.Dir(dir)+ }+ }+ return workdir}const (@@ -470,7 +507,7 @@ func (d *Daemon) repoCheckoutHandler() http.HandlerFunc {http.Error(w, "repo checkout task context does not match the active task", http.StatusForbidden)return}- authorizedWorkDir, authErr := authorizeRepoCheckoutWorkDir(activeTask.WorkDir, req.WorkDir)+ taskRoot, authorizedWorkDir, authErr := resolveRepoCheckoutWorkDir(activeTask.WorkDir, req.WorkDir)if authErr != nil {// The reason goes to both the agent and daemon.log: a refusal that// says only "not owned" sent #8946 looking at ownership when the@@ -491,7 +528,6 @@ func (d *Daemon) repoCheckoutHandler() http.HandlerFunc {req.WorkspaceID = activeTask.WorkspaceIDreq.TaskID = activeTask.TaskIDreq.AgentName = activeTask.AgentName- req.WorkDir = authorizedWorkDirif d.repoCache == nil {http.Error(w, "repo cache not initialized", http.StatusInternalServerError)@@ -512,6 +548,15 @@ func (d *Daemon) repoCheckoutHandler() http.HandlerFunc {return}+ req.WorkDir = checkoutWorkDirOutsideOwnCheckout(r.Context(), taskRoot, authorizedWorkDir, d.repoCache.Lookup(req.WorkspaceID, req.URL))+ if req.WorkDir != authorizedWorkDir {+ d.logger.Info("repo checkout: requested workdir is inside a checkout of this repository, using its parent",+ "task_id", activeTask.TaskID,+ "requested", authorizedWorkDir,+ "workdir", req.WorkDir,+ )+ }+checkoutRef := strings.TrimSpace(req.Ref)if checkoutRef == "" {checkoutRef = d.taskRepoDefaultRef(req.WorkspaceID, req.TaskID, req.URL)@@ -551,6 +596,11 @@ func (d *Daemon) repoCheckoutHandler() http.HandlerFunc {d.logger.Debug("repo checkout cancelled", "url", req.URL, "error", err)return}+ if errors.Is(err, repocache.ErrCheckoutPathTaken) {+ d.logger.Warn("repo checkout rejected", "reason", "path_taken", "url", req.URL, "error", err)+ http.Error(w, err.Error(), http.StatusConflict)+ return+ }d.logger.Error("repo checkout failed", "url", req.URL, "error", err)http.Error(w, err.Error(), http.StatusInternalServerError)returndiff --git a/server/internal/daemon/health_test.go b/server/internal/daemon/health_test.goindex 502612d7ad..15c1a40677 100644--- a/server/internal/daemon/health_test.go+++ b/server/internal/daemon/health_test.go@@ -5,11 +5,13 @@ import ("context""encoding/json""errors"+ "fmt""io""log/slog""net/http""net/http/httptest""os"+ "os/exec""path/filepath""runtime""strings"@@ -667,6 +669,199 @@ func TestRepoCheckoutRejectsUnresolvableWorkdirWithTheReason(t *testing.T) {}}+// repoCheckoutHarness drives the /repo/checkout handler against a real repo+// cache holding every repository in urls, for one task rooted at root.+type repoCheckoutHarness struct {+ d *Daemon+ root string+ isolated bool+}++func newRepoCheckoutHarness(t *testing.T, isolated bool, urls ...string) *repoCheckoutHarness {+ t.Helper()+ const workspaceID = "ws-1"+ repos := make([]RepoData, 0, len(urls))+ infos := make([]repocache.RepoInfo, 0, len(urls))+ for _, url := range urls {+ repos = append(repos, RepoData{URL: url})+ infos = append(infos, repocache.RepoInfo{URL: url})+ }+ d := newRepoReadyTestDaemon(t, func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet || r.URL.Path != "/api/daemon/workspaces/"+workspaceID+"/repos" {+ http.NotFound(w, r)+ return+ }+ json.NewEncoder(w).Encode(WorkspaceReposResponse{WorkspaceID: workspaceID, Repos: repos, ReposVersion: "v1"})+ })+ if err := d.repoCache.Sync(workspaceID, infos); err != nil {+ t.Fatalf("seed repo cache: %v", err)+ }+ d.workspaces[workspaceID] = newWorkspaceState(workspaceID, nil, "v1", repos, nil)+ root := t.TempDir()+ d.registerActiveRepoCheckoutTask("mat_repo_checkout_test", activeRepoCheckoutTask{+ WorkspaceID: workspaceID,+ TaskID: "task-1",+ AgentName: "Test Agent",+ WorkDir: root,+ })+ return &repoCheckoutHarness{d: d, root: root, isolated: isolated}+}++func (h *repoCheckoutHarness) checkout(t *testing.T, url, from string, fresh bool) (int, repocache.WorktreeResult, string) {+ t.Helper()+ req := repoCheckoutRequest{URL: url, WorkspaceID: "ws-1", WorkDir: from, TaskID: "task-1", Fresh: fresh}+ if h.isolated {+ req.CheckoutMode = repoCheckoutModeIsolated+ }+ body, err := json.Marshal(req)+ if err != nil {+ t.Fatalf("encode request: %v", err)+ }+ rec := httptest.NewRecorder()+ h.d.repoCheckoutHandler().ServeHTTP(rec, authorizedRepoCheckoutRequest(bytes.NewReader(body)))+ var result repocache.WorktreeResult+ if rec.Code == http.StatusOK {+ if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {+ t.Fatalf("decode checkout result: %v", err)+ }+ }+ return rec.Code, result, rec.Body.String()+}++func (h *repoCheckoutHarness) mustCheckout(t *testing.T, url, from string) repocache.WorktreeResult {+ t.Helper()+ status, result, body := h.checkout(t, url, from, false)+ if status != http.StatusOK {+ t.Fatalf("checkout of %s from %s: expected 200, got %d: %s", url, from, status, body)+ }+ return result+}++func runDaemonTestGit(t *testing.T, args ...string) string {+ t.Helper()+ cmd := exec.Command("git", args...)+ cmd.Env = append(os.Environ(),+ "GIT_AUTHOR_NAME=test", "[email protected]",+ "GIT_COMMITTER_NAME=test", "[email protected]",+ )+ out, err := cmd.CombinedOutput()+ if err != nil {+ t.Fatalf("git %v: %s: %v", args, out, err)+ }+ return strings.TrimSpace(string(out))+}++// createNamedDaemonTestRepo creates a repository whose directory, and so whose+// checkout directory, is named "repo", holding identity.txt = label.+func createNamedDaemonTestRepo(t *testing.T, label string) string {+ t.Helper()+ path := filepath.Join(t.TempDir(), "repo")+ runDaemonTestGit(t, "init", "-b", "main", path)+ if err := os.WriteFile(filepath.Join(path, "identity.txt"), []byte(label), 0o644); err != nil {+ t.Fatalf("write identity: %v", err)+ }+ runDaemonTestGit(t, "-C", path, "add", "identity.txt")+ runDaemonTestGit(t, "-C", path, "commit", "-m", label)+ return path+}++var repoCheckoutModes = []struct {+ name string+ isolated bool+}{+ {name: "linked", isolated: false},+ {name: "isolated", isolated: true},+}++// Re-running checkout from inside the checkout it created, as an agent whose+// shell stayed there does, reuses that checkout instead of nesting a new+// worktree on a new branch inside it (MUL-9099).+func TestRepoCheckoutFromInsideExistingCheckoutReusesIt(t *testing.T) {+ t.Parallel()++ for _, mode := range repoCheckoutModes {+ t.Run(mode.name, func(t *testing.T) {+ t.Parallel()++ sourceRepo := createDaemonTestRepo(t)+ h := newRepoCheckoutHarness(t, mode.isolated, sourceRepo)+ first := h.mustCheckout(t, sourceRepo, h.root)+ subdir := filepath.Join(first.Path, "server")+ if err := os.Mkdir(subdir, 0o755); err != nil {+ t.Fatalf("mkdir inside checkout: %v", err)+ }++ for _, from := range []string{first.Path, subdir} {+ again := h.mustCheckout(t, sourceRepo, from)+ if again.Path != first.Path || again.BranchName != first.BranchName {+ t.Fatalf("checkout from %s = %s on %s, want the existing %s on %s", from, again.Path, again.BranchName, first.Path, first.BranchName)+ }+ if again.Kept != repocache.KeptTaskBranch {+ t.Fatalf("checkout from %s: Kept = %q, want %q", from, again.Kept, repocache.KeptTaskBranch)+ }+ }+ if _, err := os.Lstat(filepath.Join(first.Path, filepath.Base(first.Path))); !os.IsNotExist(err) {+ t.Fatalf("a checkout was nested inside the existing one (lstat err = %v)", err)+ }+ })+ }+}++// A different repository whose checkout directory has the same name — an+// upstream and its fork — requested from inside the first one's checkout is+// placed inside it as before, and never retargets, resets, or cleans it.+// Re-running either one later, from anywhere inside, reuses its own checkout.+func TestRepoCheckoutOfSameNamedRepoInsideCheckoutLeavesItAlone(t *testing.T) {+ t.Parallel()++ for _, mode := range repoCheckoutModes {+ for _, fresh := range []bool{false, true} {+ t.Run(fmt.Sprintf("%s/fresh=%t", mode.name, fresh), func(t *testing.T) {+ t.Parallel()++ a, b := createNamedDaemonTestRepo(t, "repo-A"), createNamedDaemonTestRepo(t, "repo-B")+ h := newRepoCheckoutHarness(t, mode.isolated, a, b)+ first := h.mustCheckout(t, a, h.root)+ originBefore := runDaemonTestGit(t, "-C", first.Path, "remote", "get-url", "origin")+ headBefore := runDaemonTestGit(t, "-C", first.Path, "rev-parse", "HEAD")+ note := filepath.Join(first.Path, "local-work.txt")+ if err := os.WriteFile(note, []byte("keep repo A work"), 0o644); err != nil {+ t.Fatalf("write local work: %v", err)+ }++ status, second, body := h.checkout(t, b, first.Path, fresh)+ if status != http.StatusOK {+ t.Fatalf("checkout of B from inside A: expected 200, got %d: %s", status, body)+ }+ if got := runDaemonTestGit(t, "-C", first.Path, "remote", "get-url", "origin"); got != originBefore {+ t.Errorf("requesting B changed A's origin: %q -> %q", originBefore, got)+ }+ if got := runDaemonTestGit(t, "-C", first.Path, "rev-parse", "HEAD"); got != headBefore {+ t.Errorf("requesting B moved A's HEAD: %s -> %s", headBefore, got)+ }+ if data, err := os.ReadFile(note); err != nil || string(data) != "keep repo A work" {+ t.Errorf("requesting B discarded A's local work: %q %v", data, err)+ }+ if want := filepath.Join(first.Path, "repo"); second.Path != want {+ t.Fatalf("B checkout path = %s, want it placed inside A at %s", second.Path, want)+ }+ if data, err := os.ReadFile(filepath.Join(second.Path, "identity.txt")); err != nil || string(data) != "repo-B" {+ t.Fatalf("B checkout holds the wrong repository: %q %v", data, err)+ }++ // B's checkout sits inside A's; each re-run climbs only out of+ // its own repository's checkout.+ if again := h.mustCheckout(t, b, second.Path); again.Path != second.Path {+ t.Errorf("re-running B from its checkout = %s, want %s", again.Path, second.Path)+ }+ if again := h.mustCheckout(t, a, second.Path); again.Path != first.Path {+ t.Errorf("re-running A from inside B's checkout = %s, want %s", again.Path, first.Path)+ }+ })+ }+ }+}+func TestRepoCheckoutExplicitRefOverridesProjectDefault(t *testing.T) {t.Parallel()diff --git a/server/internal/daemon/repocache/cache.go b/server/internal/daemon/repocache/cache.goindex 29031739a0..c12f66ef2f 100644--- a/server/internal/daemon/repocache/cache.go+++ b/server/internal/daemon/repocache/cache.go@@ -188,6 +188,11 @@ type Cache struct {// transport deadline expires.var ErrRepoBusy = errors.New("repository is busy")+// ErrCheckoutPathTaken means the checkout's target path already holds a+// Multica checkout of a different repository with the same directory name.+// CreateWorktree reports it before touching that checkout.+var ErrCheckoutPathTaken = errors.New("checkout path holds another repository")+// Activity is the path-free repository coordination state exposed through the// daemon health endpoint. It is diagnostic only.type Activity struct {@@ -898,6 +903,14 @@ func (c *Cache) CreateWorktreeContext(ctx context.Context, params WorktreeParams)}+ // Two repositories with the same basename map to the same path. Every+ // branch below rewrites what it finds there — origin, reset, clean — so+ // another repository's checkout must be refused before any of them runs.+ if other := otherRepoCheckout(ctx, barePath, worktreePath); other != "" {+ return nil, fmt.Errorf("%w: %s already holds %s, not %s; run the checkout from a different directory",+ ErrCheckoutPathTaken, worktreePath, other, redact.Text(params.RepoURL))+ }+// Once a workdir has moved to isolated metadata, keep using that safer// shape even if a later task comes from an older CLI or a different runtime// that omits the mode hint. This also makes provider transitions on a reused@@ -1107,15 +1120,74 @@ func (c *Cache) createOrUpdateIsolatedCheckoutContext(ctx context.Context, barePreturn &WorktreeResult{Path: checkoutPath, BranchName: actualBranch}, nil}-func removeLinkedWorktreeContext(ctx context.Context, barePath, checkoutPath string) error {+// CheckoutBelongsTo reports whether path holds a Multica checkout of the+// repository cached at barePath: a linked worktree of that cache, or an+// isolated checkout whose origin is cached there.+func CheckoutBelongsTo(ctx context.Context, barePath, path string) bool {+ if isGitWorktree(path) {+ commonDir, err := linkedWorktreeCommonDirContext(ctx, path)+ return err == nil && sameResolvedPath(commonDir, barePath)+ }+ if isIsolatedCheckoutContext(ctx, path) {+ origin, err := isolatedCheckoutOriginContext(ctx, path)+ return err == nil && isolatedOriginCachedAt(origin, barePath)+ }+ return false+}++// otherRepoCheckout describes the repository a Multica checkout at path+// belongs to when that is not the one cached at barePath. It returns "" when+// the checkout is this repository's, when path holds no Multica checkout, or+// when its owner cannot be read — the update path then fails on its own.+func otherRepoCheckout(ctx context.Context, barePath, path string) string {+ if isGitWorktree(path) {+ commonDir, err := linkedWorktreeCommonDirContext(ctx, path)+ if err == nil && !sameResolvedPath(commonDir, barePath) {+ return "a worktree of the cache at " + commonDir+ }+ return ""+ }+ if isIsolatedCheckoutContext(ctx, path) {+ origin, err := isolatedCheckoutOriginContext(ctx, path)+ if err == nil && !isolatedOriginCachedAt(origin, barePath) {+ return "a checkout of " + redact.Text(origin)+ }+ }+ return ""+}++func isolatedCheckoutOriginContext(ctx context.Context, path string) (string, error) {+ out, err := runGitOutputContext(ctx, "-C", path, "config", "--get", "remote.origin.url")+ if err != nil {+ return "", err+ }+ return strings.TrimSpace(string(out)), nil+}++// isolatedOriginCachedAt reports whether origin is a URL whose bare cache is+// barePath. Caches are keyed by bareDirName, so URL spellings that share a+// cache count as the same repository.+func isolatedOriginCachedAt(origin, barePath string) bool {+ return origin != "" && bareDirName(origin) == filepath.Base(barePath)+}++func linkedWorktreeCommonDirContext(ctx context.Context, checkoutPath string) (string, error) {out, err := runGitOutputContext(ctx, "-C", checkoutPath, "rev-parse", "--git-common-dir")if err != nil {- return fmt.Errorf("resolve linked worktree common dir: %w", err)+ return "", err}commonDir := strings.TrimSpace(string(out))if !filepath.IsAbs(commonDir) {commonDir = filepath.Join(checkoutPath, commonDir)}+ return commonDir, nil+}++func removeLinkedWorktreeContext(ctx context.Context, barePath, checkoutPath string) error {+ commonDir, err := linkedWorktreeCommonDirContext(ctx, checkoutPath)+ if err != nil {+ return fmt.Errorf("resolve linked worktree common dir: %w", err)+ }if !sameResolvedPath(commonDir, barePath) {return fmt.Errorf("linked worktree common dir %s does not match cache %s", commonDir, barePath)}diff --git a/server/internal/daemon/repocache/existing_checkout_test.go b/server/internal/daemon/repocache/existing_checkout_test.goindex 1938414aea..937e4f812f 100644--- a/server/internal/daemon/repocache/existing_checkout_test.go+++ b/server/internal/daemon/repocache/existing_checkout_test.go@@ -1,6 +1,9 @@package repocacheimport (+ "context"+ "errors"+ "fmt""os""path/filepath""strings"@@ -411,6 +414,80 @@ func TestFreshMigrationCarriesUnpushedBranch(t *testing.T) {}}+// Two repositories whose checkout directories share a name — an upstream and+// its fork — target the same path. The second checkout is refused before it+// retargets, resets, cleans, or migrates the first one, whatever the modes+// and fresh flag (MUL-9099).+func TestCheckoutRefusesPathHoldingAnotherRepository(t *testing.T) {+ t.Parallel()+ for _, existing := range checkoutModes {+ for _, requested := range checkoutModes {+ for _, fresh := range []bool{false, true} {+ t.Run(fmt.Sprintf("%s-then-%s/fresh=%t", existing.name, requested.name, fresh), func(t *testing.T) {+ t.Parallel()+ sources := make([]string, 2)+ for i := range sources {+ dir := filepath.Join(t.TempDir(), "repo")+ if err := os.Mkdir(dir, 0o755); err != nil {+ t.Fatalf("mkdir source: %v", err)+ }+ sources[i] = createTestRepoAt(t, dir)+ }+ a, b := sources[0], sources[1]+ cache := New(t.TempDir(), testLogger())+ if err := cache.Sync("ws-1", []RepoInfo{{URL: a}, {URL: b}}); err != nil {+ t.Fatalf("sync failed: %v", err)+ }+ workDir := t.TempDir()+ checkout := func(url string, isolated, fresh bool) (*WorktreeResult, error) {+ return cache.CreateWorktree(WorktreeParams{+ WorkspaceID: "ws-1",+ RepoURL: url,+ WorkDir: workDir,+ AgentName: "Agent",+ TaskID: firstTaskID,+ IsolatedGitMetadata: isolated,+ Fresh: fresh,+ })+ }+ first, err := checkout(a, existing.isolated, false)+ if err != nil {+ t.Fatalf("checkout of A failed: %v", err)+ }+ if !CheckoutBelongsTo(context.Background(), cache.Lookup("ws-1", a), first.Path) {+ t.Fatal("A's checkout does not belong to A's cache")+ }+ if CheckoutBelongsTo(context.Background(), cache.Lookup("ws-1", b), first.Path) {+ t.Fatal("A's checkout belongs to B's cache")+ }+ originBefore, _ := runGitOutput("-C", first.Path, "config", "--get", "remote.origin.url")+ headBefore := gitHead(t, first.Path)+ note := filepath.Join(first.Path, "local-work.txt")+ if err := os.WriteFile(note, []byte("keep\n"), 0o644); err != nil {+ t.Fatalf("write local work: %v", err)+ }++ if _, err := checkout(b, requested.isolated, fresh); !errors.Is(err, ErrCheckoutPathTaken) {+ t.Fatalf("checkout of B into A's path: err = %v, want ErrCheckoutPathTaken", err)+ }+ if got, _ := runGitOutput("-C", first.Path, "config", "--get", "remote.origin.url"); string(got) != string(originBefore) {+ t.Errorf("A's origin changed: %q -> %q", originBefore, got)+ }+ if got := gitHead(t, first.Path); got != headBefore {+ t.Errorf("A's HEAD moved: %s -> %s", headBefore, got)+ }+ if got := readFile(t, note); got != "keep\n" {+ t.Errorf("A's local work = %q, want it kept", got)+ }+ if isIsolatedCheckout(first.Path) != existing.isolated {+ t.Error("A's checkout was migrated to another metadata shape")+ }+ })+ }+ }+ }+}+func TestIsTaskBranch(t *testing.T) {t.Parallel()const branch = "agent/agent/111111111111"