Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-4925: fix Linux Codex Git metadata writes (#5575)

Multica Eve90ee83e10a96
diff --git a/server/cmd/multica/cmd_repo.go b/server/cmd/multica/cmd_repo.go
index a396be74a2..e1907273c1 100644
--- a/server/cmd/multica/cmd_repo.go
+++ b/server/cmd/multica/cmd_repo.go
@@ -350,12 +350,13 @@ func runRepoCheckout(cmd *cobra.Command, args []string) error {
}
reqBody := map[string]string{
- "url": repoURL,
- "workspace_id": workspaceID,
- "workdir": workDir,
- "ref": repoCheckoutRef,
- "agent_name": agentName,
- "task_id": taskID,
+ "url": repoURL,
+ "workspace_id": workspaceID,
+ "workdir": workDir,
+ "ref": repoCheckoutRef,
+ "agent_name": agentName,
+ "task_id": taskID,
+ "checkout_mode": strings.TrimSpace(os.Getenv("MULTICA_REPO_CHECKOUT_MODE")),
}
data, err := json.Marshal(reqBody)
diff --git a/server/cmd/multica/cmd_repo_test.go b/server/cmd/multica/cmd_repo_test.go
index f4fcc726b2..8a77f38291 100644
--- a/server/cmd/multica/cmd_repo_test.go
+++ b/server/cmd/multica/cmd_repo_test.go
@@ -188,3 +188,41 @@ func TestRunRepoRemoveRejectsMissingRepoWithoutPatch(t *testing.T) {
t.Fatalf("patchCount = %d, want 0", patchCount)
}
}
+
+func TestRunRepoCheckoutForwardsManagedCheckoutMode(t *testing.T) {
+ var body map[string]string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.URL.Path != "/repo/checkout" {
+ http.NotFound(w, r)
+ return
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatalf("decode checkout body: %v", err)
+ }
+ json.NewEncoder(w).Encode(map[string]string{
+ "path": "/work/repo",
+ "branch_name": "agent/test/task",
+ })
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_DAEMON_PORT", strings.TrimPrefix(srv.URL, "http://127.0.0.1:"))
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_AGENT_NAME", "Test Agent")
+ t.Setenv("MULTICA_TASK_ID", "task-1")
+ t.Setenv("MULTICA_REPO_CHECKOUT_MODE", "isolated")
+
+ previousRef := repoCheckoutRef
+ repoCheckoutRef = "release/v2"
+ defer func() { repoCheckoutRef = previousRef }()
+
+ if err := runRepoCheckout(&cobra.Command{}, []string{"https://github.com/org/repo.git"}); err != nil {
+ t.Fatalf("runRepoCheckout: %v", err)
+ }
+ if got := body["checkout_mode"]; got != "isolated" {
+ t.Fatalf("checkout_mode = %q, want isolated", got)
+ }
+ if got := body["ref"]; got != "release/v2" {
+ t.Fatalf("ref = %q, want release/v2", got)
+ }
+}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index b317a8e4ab..6f5e13e14d 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -11,6 +11,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "runtime"
"sort"
"strconv"
"strings"
@@ -48,10 +49,19 @@ var ErrRepoNotConfigured = errors.New("repo is not configured for this workspace
var ErrNoRuntimesToRegister = errors.New("no agent runtimes could be registered")
const (
- taskSlotWaitTimeout = 2 * time.Second
- taskSlotCapacityBackoff = 5 * time.Second
+ taskSlotWaitTimeout = 2 * time.Second
+ taskSlotCapacityBackoff = 5 * time.Second
+ repoCheckoutModeEnv = "MULTICA_REPO_CHECKOUT_MODE"
+ repoCheckoutModeIsolated = "isolated"
)
+func repoCheckoutModeFor(provider, goos string) string {
+ if provider == "codex" && goos == "linux" {
+ return repoCheckoutModeIsolated
+ }
+ return ""
+}
+
var (
taskPrepareLeaseRefresh = 15 * time.Second
taskPrepareLeaseTimeout = 10 * time.Second
@@ -4180,6 +4190,9 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
"TMP": taskTempDir,
"TEMP": taskTempDir,
}
+ if checkoutMode := repoCheckoutModeFor(provider, runtime.GOOS); checkoutMode != "" {
+ agentEnv[repoCheckoutModeEnv] = checkoutMode
+ }
if task.AutopilotRunID != "" {
agentEnv["MULTICA_AUTOPILOT_RUN_ID"] = task.AutopilotRunID
}
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index dd26c173aa..e1fd4b392d 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -240,6 +240,26 @@ func TestLayerCustomEnvAndHermesHome(t *testing.T) {
}
}
+func TestRepoCheckoutModeFor(t *testing.T) {
+ t.Parallel()
+ tests := []struct {
+ name, provider, goos, want string
+ }{
+ {name: "Linux Codex isolates Git metadata", provider: "codex", goos: "linux", want: repoCheckoutModeIsolated},
+ {name: "macOS Codex keeps worktree", provider: "codex", goos: "darwin"},
+ {name: "Windows Codex keeps worktree", provider: "codex", goos: "windows"},
+ {name: "Linux Claude keeps worktree", provider: "claude", goos: "linux"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ if got := repoCheckoutModeFor(tt.provider, tt.goos); got != tt.want {
+ t.Fatalf("repoCheckoutModeFor(%q, %q) = %q, want %q", tt.provider, tt.goos, got, tt.want)
+ }
+ })
+ }
+}
+
func TestConfigureCodexTaskShellEnvironment(t *testing.T) {
t.Parallel()
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 52a75b5386..643a57a985 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -208,7 +208,7 @@ func writeAvailableCommands(b *strings.Builder) {
b.WriteString("- `multica issue metadata list <issue-id> [--output json]` — list KV metadata.\n")
b.WriteString("- `multica issue metadata set <issue-id> --key <k> --value <v> [--type string|number|bool]` — pin or overwrite a key.\n")
b.WriteString("- `multica issue metadata delete <issue-id> --key <k>` — remove a key.\n")
- b.WriteString("- `multica repo checkout <url> [--ref <branch-or-sha>]` — git worktree on a dedicated branch.\n\n")
+ b.WriteString("- `multica repo checkout <url> [--ref <branch-or-sha>]` — repository checkout on a dedicated branch.\n\n")
b.WriteString("### Squad maintenance\n")
b.WriteString("- `multica squad member set-role <squad-id> --member-id <id> --member-type <agent|member> --role <role> [--output json]` — change role in place (use this instead of remove+add).\n\n")
}
@@ -244,7 +244,7 @@ func writeRepositories(b *strings.Builder, ctx TaskContextForEnv) {
return
}
b.WriteString("## Repositories\n\n")
- b.WriteString("Available in this workspace — `multica repo checkout <url> [--ref <branch-or-sha>]` to fetch (creates a git worktree on a dedicated branch).\n\n")
+ b.WriteString("Available in this workspace — `multica repo checkout <url> [--ref <branch-or-sha>]` to fetch (creates a repository checkout on a dedicated branch).\n\n")
for _, repo := range ctx.Repos {
if repo.Description != "" {
fmt.Fprintf(b, "- %s — %s\n", repo.URL, repo.Description)
diff --git a/server/internal/daemon/execenv/task_home.go b/server/internal/daemon/execenv/task_home.go
index 89145deee1..3490da6f6b 100644
--- a/server/internal/daemon/execenv/task_home.go
+++ b/server/internal/daemon/execenv/task_home.go
@@ -34,12 +34,11 @@ import (
// permissions), so neither needs — nor should get — a redirected HOME. Other
// providers are not sandboxed either.
//
-// NOT covered here: `git commit` inside a checked-out worktree. Codex's
-// workspace-write reads the worktree's `.git` pointer file, resolves the real
-// gitdir, and keeps that gitdir read-only even when it sits inside a
-// writable_root (see codex-rs default_read_only_subpaths_for_writable_root), so
-// `writable_roots` cannot unblock it. That needs a Codex metadata-write
-// permission path and is tracked separately (GitHub multica-ai/multica#2925).
+// `git commit` inside a linked worktree has the same root sandbox constraint:
+// Codex resolves the worktree's `.git` pointer and keeps the external gitdir
+// read-only even inside a writable_root. The repo checkout path handles that
+// separately by giving Linux Codex tasks an isolated, task-local `.git`
+// directory instead of widening this writable-root grant (#2925).
// taskHomeSeedEntries are top-level entries symlinked from the user's real home
// into the per-task HOME so credential/identity reads keep resolving after HOME
diff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.go
index ff1b0e6624..e62da8164e 100644
--- a/server/internal/daemon/health.go
+++ b/server/internal/daemon/health.go
@@ -54,12 +54,13 @@ func (d *Daemon) listenHealth() (net.Listener, error) {
// repoCheckoutRequest is the body of a POST /repo/checkout request.
type repoCheckoutRequest struct {
- URL string `json:"url"`
- WorkspaceID string `json:"workspace_id"`
- WorkDir string `json:"workdir"`
- Ref string `json:"ref,omitempty"`
- AgentName string `json:"agent_name"`
- TaskID string `json:"task_id"`
+ URL string `json:"url"`
+ WorkspaceID string `json:"workspace_id"`
+ WorkDir string `json:"workdir"`
+ Ref string `json:"ref,omitempty"`
+ AgentName string `json:"agent_name"`
+ TaskID string `json:"task_id"`
+ CheckoutMode string `json:"checkout_mode,omitempty"`
}
// healthHandler returns the /health HTTP handler. Extracted from serveHealth
@@ -179,6 +180,10 @@ func (d *Daemon) repoCheckoutHandler() http.HandlerFunc {
http.Error(w, "workdir is required", http.StatusBadRequest)
return
}
+ if req.CheckoutMode != "" && req.CheckoutMode != repoCheckoutModeIsolated {
+ http.Error(w, "invalid checkout_mode", http.StatusBadRequest)
+ return
+ }
if d.repoCache == nil {
http.Error(w, "repo cache not initialized", http.StatusInternalServerError)
@@ -208,6 +213,7 @@ func (d *Daemon) repoCheckoutHandler() http.HandlerFunc {
AgentName: req.AgentName,
TaskID: req.TaskID,
CoAuthoredByEnabled: d.workspaceCoAuthoredByEnabled(req.WorkspaceID),
+ IsolatedGitMetadata: req.CheckoutMode == repoCheckoutModeIsolated,
})
if err != nil {
d.logger.Error("repo checkout failed", "url", req.URL, "error", err)
diff --git a/server/internal/daemon/health_test.go b/server/internal/daemon/health_test.go
index 620d8aec5f..5c5c31e6ed 100644
--- a/server/internal/daemon/health_test.go
+++ b/server/internal/daemon/health_test.go
@@ -270,6 +270,46 @@ func TestRepoCheckoutExplicitRefOverridesProjectDefault(t *testing.T) {
}
}
+func TestRepoCheckoutForwardsIsolatedMode(t *testing.T) {
+ t.Parallel()
+
+ const workspaceID = "ws-checkout"
+ const repoURL = "https://github.com/org/repo.git"
+ cache := &recordingRepoCache{lookupPath: "/cache/org/repo.git"}
+ d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, cache)
+
+ rec := httptest.NewRecorder()
+ body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"/tmp/work","task_id":"task-1","checkout_mode":"isolated"}`)
+ d.repoCheckoutHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/repo/checkout", body))
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
+ }
+ if !cache.lastCreateParams().IsolatedGitMetadata {
+ t.Fatal("isolated checkout_mode was not forwarded to repo cache")
+ }
+}
+
+func TestRepoCheckoutRejectsUnknownMode(t *testing.T) {
+ t.Parallel()
+
+ const workspaceID = "ws-checkout"
+ const repoURL = "https://github.com/org/repo.git"
+ cache := &recordingRepoCache{lookupPath: "/cache/org/repo.git"}
+ d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, cache)
+
+ rec := httptest.NewRecorder()
+ body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"/tmp/work","task_id":"task-1","checkout_mode":"unsafe"}`)
+ d.repoCheckoutHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/repo/checkout", body))
+
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400, got %d: %s", rec.Code, rec.Body.String())
+ }
+ if got := cache.lastCreateParams(); got != (repocache.WorktreeParams{}) {
+ t.Fatalf("invalid checkout mode reached repo cache: %+v", got)
+ }
+}
+
func newRepoCheckoutTestDaemon(t *testing.T, workspaceID, repoURL string, cache *recordingRepoCache) *Daemon {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
diff --git a/server/internal/daemon/repocache/cache.go b/server/internal/daemon/repocache/cache.go
index 20e8576d23..c479943bf9 100644
--- a/server/internal/daemon/repocache/cache.go
+++ b/server/internal/daemon/repocache/cache.go
@@ -432,6 +432,12 @@ type WorktreeParams struct {
AgentName string // for branch naming
TaskID string // for branch naming uniqueness
CoAuthoredByEnabled bool // install prepare-commit-msg hook for Co-authored-by trailer
+ // IsolatedGitMetadata creates a local clone whose .git directory lives
+ // inside WorkDir instead of a linked worktree whose gitdir lives under the
+ // shared cache. Linux Codex tasks need this because workspace-write keeps a
+ // resolved external worktree gitdir read-only even when it is explicitly
+ // listed as a writable root (multica-ai/multica#2925).
+ IsolatedGitMetadata bool
}
// WorktreeResult describes a successfully created worktree.
@@ -500,6 +506,44 @@ func (c *Cache) CreateWorktree(params WorktreeParams) (*WorktreeResult, error) {
dirName := repoNameFromURL(params.RepoURL)
worktreePath := filepath.Join(params.WorkDir, dirName)
+ // 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
+ // workdir backward compatible.
+ if params.IsolatedGitMetadata || isIsolatedCheckout(worktreePath) {
+ actualBranch, err := c.createOrUpdateIsolatedCheckout(
+ barePath,
+ params.RepoURL,
+ worktreePath,
+ branchName,
+ baseRef,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("create isolated checkout: %w", err)
+ }
+
+ for _, pattern := range agentGitExcludePatterns {
+ _ = excludeFromGit(worktreePath, pattern)
+ }
+ if params.CoAuthoredByEnabled {
+ if err := installCoAuthoredByHook(worktreePath); err != nil {
+ c.logger.Warn("repo checkout: install co-authored-by hook failed (non-fatal)", "error", err)
+ }
+ } else {
+ if err := removeCoAuthoredByHook(worktreePath); err != nil {
+ c.logger.Warn("repo checkout: remove co-authored-by hook failed (non-fatal)", "error", err)
+ }
+ }
+
+ c.logger.Info("repo checkout: isolated checkout ready",
+ "url", params.RepoURL,
+ "path", worktreePath,
+ "branch", actualBranch,
+ "base", baseRef,
+ )
+ return &WorktreeResult{Path: worktreePath, BranchName: actualBranch}, nil
+ }
+
// If worktree already exists (reused environment from a prior task),
// update it to the latest remote code instead of creating a new one.
if isGitWorktree(worktreePath) {
@@ -578,6 +622,237 @@ func (c *Cache) CreateWorktree(params WorktreeParams) (*WorktreeResult, error) {
}, nil
}
+const (
+ isolatedCheckoutConfigKey = "multica.checkout-mode"
+ isolatedCheckoutConfigValue = "isolated"
+ isolatedCacheRemoteName = "multica-cache"
+)
+
+// createOrUpdateIsolatedCheckout keeps Git metadata inside the task workdir.
+// The fresh path uses a same-filesystem local clone, so immutable Git objects
+// are hard-linked from the daemon's cache while refs, index, logs, config, and
+// new objects remain private to the task checkout. The temporary cache remote
+// is then replaced with the real repository URL so an agent's normal fetch /
+// push commands still target GitHub rather than the daemon-owned bare cache.
+func (c *Cache) createOrUpdateIsolatedCheckout(barePath, repoURL, checkoutPath, branchName, baseRef string) (string, error) {
+ baseCommit, err := resolveCommit(barePath, baseRef)
+ if err != nil {
+ return "", err
+ }
+
+ if isIsolatedCheckout(checkoutPath) {
+ if err := setIsolatedCheckoutOrigin(checkoutPath, repoURL); err != nil {
+ return "", err
+ }
+ if err := syncIsolatedCheckoutRefs(barePath, checkoutPath, baseRef); err != nil {
+ return "", err
+ }
+ actualBranch, err := updateExistingWorktree(checkoutPath, branchName, baseCommit)
+ if err != nil {
+ return "", err
+ }
+ // Drop earlier tasks' agent/* heads so a reused workdir doesn't grow a
+ // new local branch on every checkout. Non-fatal: leftover branches are
+ // harmless clutter and must never fail the checkout.
+ if err := deleteStaleAgentBranches(checkoutPath, actualBranch); err != nil {
+ c.logger.Warn("repo checkout: prune stale branches failed (non-fatal)", "error", err)
+ }
+ return actualBranch, nil
+ }
+ // A daemon upgrade can resume a pre-fix Linux Codex workdir that still has
+ // a linked worktree. Remove it through Git (so the shared admin record is
+ // cleaned too), then recreate the same checkout path with local metadata.
+ if isGitWorktree(checkoutPath) {
+ if err := removeLinkedWorktree(barePath, checkoutPath); err != nil {
+ return "", err
+ }
+ }
+ if _, err := os.Stat(checkoutPath); err == nil {
+ return "", fmt.Errorf("checkout path already exists and is not a Multica isolated checkout: %s", checkoutPath)
+ } else if !os.IsNotExist(err) {
+ return "", fmt.Errorf("stat checkout path: %w", err)
+ }
+
+ return createIsolatedCheckout(barePath, repoURL, checkoutPath, branchName, baseRef, baseCommit)
+}
+
+func removeLinkedWorktree(barePath, checkoutPath string) error {
+ out, err := runGitOutput("-C", checkoutPath, "rev-parse", "--git-common-dir")
+ if err != nil {
+ return fmt.Errorf("resolve linked worktree common dir: %w", err)
+ }
+ commonDir := strings.TrimSpace(string(out))
+ if !filepath.IsAbs(commonDir) {
+ commonDir = filepath.Join(checkoutPath, commonDir)
+ }
+ if !sameResolvedPath(commonDir, barePath) {
+ return fmt.Errorf("linked worktree common dir %s does not match cache %s", commonDir, barePath)
+ }
+ if out, err := runGitCombinedOutput("-C", barePath, "worktree", "remove", "--force", checkoutPath); err != nil {
+ return fmt.Errorf("remove linked worktree: %s: %w", strings.TrimSpace(string(out)), err)
+ }
+ return nil
+}
+
+// sameResolvedPath reports whether a and b denote the same location after
+// resolving to absolute, symlink-free, cleaned form. It is a path-equality
+// check (not a same-device check): the migration guard uses it to confirm a
+// linked worktree's git-common-dir really points at this cache bare repo
+// before removing the worktree.
+func sameResolvedPath(a, b string) bool {
+ clean := func(path string) string {
+ abs, err := filepath.Abs(path)
+ if err == nil {
+ path = abs
+ }
+ if resolved, err := filepath.EvalSymlinks(path); err == nil {
+ path = resolved
+ }
+ return filepath.Clean(path)
+ }
+ return clean(a) == clean(b)
+}
+
+func createIsolatedCheckout(barePath, repoURL, checkoutPath, branchName, baseRef, baseCommit string) (_ string, retErr error) {
+ if out, err := runGitCombinedOutput(
+ "clone", "--local", "--no-checkout", "--no-tags",
+ "--origin", isolatedCacheRemoteName,
+ barePath, checkoutPath,
+ ); err != nil {
+ // Do not remove checkoutPath here. A different repository with the
+ // same basename could have won the path race after our pre-check; Git
+ // then fails safely, and deleting the path would destroy its checkout.
+ return "", fmt.Errorf("git clone --local: %s: %w", strings.TrimSpace(string(out)), err)
+ }
+ cleanup := true
+ defer func() {
+ if cleanup {
+ _ = os.RemoveAll(checkoutPath)
+ }
+ }()
+
+ if out, err := runGitCombinedOutput("-C", checkoutPath, "checkout", "--detach", baseCommit); err != nil {
+ return "", fmt.Errorf("git checkout --detach: %s: %w", strings.TrimSpace(string(out)), err)
+ }
+ if out, err := runGitCombinedOutput("-C", checkoutPath, "remote", "remove", isolatedCacheRemoteName); err != nil {
+ return "", fmt.Errorf("remove cache remote: %s: %w", strings.TrimSpace(string(out)), err)
+ }
+ if err := deleteAllLocalBranches(checkoutPath); err != nil {
+ return "", err
+ }
+ if out, err := runGitCombinedOutput("-C", checkoutPath, "remote", "add", "origin", repoURL); err != nil {
+ return "", fmt.Errorf("add origin remote: %s: %w", strings.TrimSpace(string(out)), err)
+ }
+ if err := syncIsolatedCheckoutRefs(barePath, checkoutPath, baseRef); err != nil {
+ return "", err
+ }
+ if out, err := runGitCombinedOutput("-C", checkoutPath, "config", isolatedCheckoutConfigKey, isolatedCheckoutConfigValue); err != nil {
+ return "", fmt.Errorf("mark isolated checkout: %s: %w", strings.TrimSpace(string(out)), err)
+ }
+
+ actualBranch, err := checkoutNewBranch(checkoutPath, branchName, baseCommit)
+ if err != nil {
+ return "", err
+ }
+ cleanup = false
+ return actualBranch, nil
+}
+
+func resolveCommit(repoPath, ref string) (string, error) {
+ out, err := runGitOutput("-C", repoPath, "rev-parse", "--verify", ref+"^{commit}")
+ if err != nil {
+ return "", fmt.Errorf("resolve checkout base %q: %w", ref, err)
+ }
+ commit := strings.TrimSpace(string(out))
+ if commit == "" {
+ return "", fmt.Errorf("resolve checkout base %q: empty commit", ref)
+ }
+ return commit, nil
+}
+
+func isIsolatedCheckout(path string) bool {
+ info, err := os.Stat(filepath.Join(path, ".git"))
+ if err != nil || !info.IsDir() {
+ return false
+ }
+ out, err := runGitOutput("-C", path, "config", "--get", isolatedCheckoutConfigKey)
+ return err == nil && strings.TrimSpace(string(out)) == isolatedCheckoutConfigValue
+}
+
+func setIsolatedCheckoutOrigin(path, repoURL string) error {
+ out, err := runGitCombinedOutput("-C", path, "remote", "set-url", "origin", repoURL)
+ if err != nil {
+ return fmt.Errorf("set origin remote: %s: %w", strings.TrimSpace(string(out)), err)
+ }
+ return nil
+}
+
+// syncIsolatedCheckoutRefs mirrors the cache's real origin/* and tag refs into
+// the task-local repository. It also fetches the selected base ref directly so
+// a reused checkout can move to a newly-fetched commit without depending on
+// the cache after this function returns.
+func syncIsolatedCheckoutRefs(barePath, checkoutPath, baseRef string) error {
+ refspecs := []string{
+ "+refs/remotes/origin/*:refs/remotes/origin/*",
+ "+refs/tags/*:refs/tags/*",
+ }
+ args := []string{"-C", checkoutPath, "fetch", "--force", "--no-tags", barePath}
+ args = append(args, refspecs...)
+ if out, err := runGitCombinedOutput(args...); err != nil {
+ return fmt.Errorf("sync cache refs: %s: %w", strings.TrimSpace(string(out)), err)
+ }
+ if out, err := runGitCombinedOutput("-C", checkoutPath, "fetch", "--force", "--no-tags", barePath, baseRef); err != nil {
+ return fmt.Errorf("fetch checkout base: %s: %w", strings.TrimSpace(string(out)), err)
+ }
+ return nil
+}
+
+// deleteAllLocalBranches removes the heads copied from the bare cache into a
+// fresh local clone. The clone is detached and has no task-created branches to
+// preserve yet.
+func deleteAllLocalBranches(repoPath string) error {
+ return deleteLocalBranchesUnder(repoPath, "refs/heads/", "")
+}
+
+// deleteStaleAgentBranches prunes branches left by earlier Multica tasks while
+// preserving the current task branch and every user-created local branch.
+func deleteStaleAgentBranches(repoPath, keepBranch string) error {
+ return deleteLocalBranchesUnder(repoPath, "refs/heads/agent/", "refs/heads/"+keepBranch)
+}
+
+func deleteLocalBranchesUnder(repoPath, namespace, keepRef string) error {
+ out, err := runGitOutput("-C", repoPath, "for-each-ref", "--format=%(refname)", namespace)
+ if err != nil {
+ return fmt.Errorf("list local branches: %w", err)
+ }
+ for _, ref := range strings.Split(strings.TrimSpace(string(out)), "\n") {
+ ref = strings.TrimSpace(ref)
+ if ref == "" || ref == keepRef {
+ continue
+ }
+ if out, err := runGitCombinedOutput("-C", repoPath, "update-ref", "-d", ref); err != nil {
+ return fmt.Errorf("delete local branch %s: %s: %w", ref, strings.TrimSpace(string(out)), err)
+ }
+ }
+ return nil
+}
+
+func checkoutNewBranch(repoPath, branchName, baseRef string) (string, error) {
+ out, err := runGitCombinedOutput("-C", repoPath, "checkout", "-b", branchName, baseRef)
+ if err == nil {
+ return branchName, nil
+ }
+ wrapped := fmt.Errorf("git checkout -b: %s: %w", strings.TrimSpace(string(out)), err)
+ if !isBranchCollisionError(wrapped) {
+ return "", wrapped
+ }
+ branchName = fmt.Sprintf("%s-%d", branchName, time.Now().Unix())
+ if out2, err2 := runGitCombinedOutput("-C", repoPath, "checkout", "-b", branchName, baseRef); err2 != nil {
+ return "", fmt.Errorf("git checkout -b (retry): %s: %w", strings.TrimSpace(string(out2)), err2)
+ }
+ return branchName, nil
+}
+
func resolveBaseRef(barePath, requestedRef string) (string, error) {
ref := strings.TrimSpace(requestedRef)
if ref == "" {
diff --git a/server/internal/daemon/repocache/cache_test.go b/server/internal/daemon/repocache/cache_test.go
index f9ed897553..0e6dc92b6a 100644
--- a/server/internal/daemon/repocache/cache_test.go
+++ b/server/internal/daemon/repocache/cache_test.go
@@ -514,6 +514,192 @@ func TestCreateWorktree(t *testing.T) {
}
}
+func TestCreateWorktreeWithIsolatedGitMetadata(t *testing.T) {
+ t.Parallel()
+ sourceRepo := createTestRepo(t)
+ cache := New(t.TempDir(), testLogger())
+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {
+ t.Fatalf("sync failed: %v", err)
+ }
+
+ barePath := cache.Lookup("ws-1", sourceRepo)
+ baseRef := getRemoteDefaultBranch(barePath)
+ baseCommit := gitRefCommit(t, barePath, baseRef)
+ workDir := t.TempDir()
+ result, err := cache.CreateWorktree(WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: sourceRepo,
+ WorkDir: workDir,
+ AgentName: "Linux Codex",
+ TaskID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
+ IsolatedGitMetadata: true,
+ })
+ if err != nil {
+ t.Fatalf("CreateWorktree failed: %v", err)
+ }
+
+ gitInfo, err := os.Stat(filepath.Join(result.Path, ".git"))
+ if err != nil || !gitInfo.IsDir() {
+ t.Fatalf("isolated checkout .git must be a directory, info=%v err=%v", gitInfo, err)
+ }
+ if !isIsolatedCheckout(result.Path) {
+ t.Fatal("isolated checkout marker missing")
+ }
+ if _, err := os.Stat(filepath.Join(result.Path, ".git", "objects", "info", "alternates")); !os.IsNotExist(err) {
+ t.Fatalf("isolated checkout must not depend on cache alternates, err=%v", err)
+ }
+
+ origin, err := runGitOutput("-C", result.Path, "remote", "get-url", "origin")
+ if err != nil {
+ t.Fatalf("get origin URL: %v", err)
+ }
+ if got := strings.TrimSpace(string(origin)); got != sourceRepo {
+ t.Fatalf("origin URL = %q, want %q", got, sourceRepo)
+ }
+ if got := gitHead(t, result.Path); got != baseCommit {
+ t.Fatalf("checkout HEAD = %s, want %s", got, baseCommit)
+ }
+ if err := runGit("-C", result.Path, "rev-parse", "--verify", baseRef); err != nil {
+ t.Fatalf("isolated checkout missing cache ref %s: %v", baseRef, err)
+ }
+ if err := runGit("-C", barePath, "show-ref", "--verify", "refs/heads/"+result.BranchName); err == nil {
+ t.Fatalf("isolated branch %s leaked into shared bare cache", result.BranchName)
+ }
+
+ if err := os.WriteFile(filepath.Join(result.Path, "isolated.txt"), []byte("writable\n"), 0o644); err != nil {
+ t.Fatalf("write isolated file: %v", err)
+ }
+ runGitAuthored(t, result.Path, "add", "isolated.txt")
+ runGitAuthored(t, result.Path, "commit", "-m", "isolated commit")
+ if got := gitHead(t, result.Path); got == baseCommit {
+ t.Fatal("git commit did not advance isolated checkout")
+ }
+ if got := gitRefCommit(t, barePath, baseRef); got != baseCommit {
+ t.Fatalf("isolated commit mutated shared cache base: got %s, want %s", got, baseCommit)
+ }
+}
+
+func TestCreateWorktreeReusesIsolatedGitMetadata(t *testing.T) {
+ t.Parallel()
+ sourceRepo := createTestRepo(t)
+ cache := New(t.TempDir(), testLogger())
+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {
+ t.Fatalf("initial sync failed: %v", err)
+ }
+
+ workDir := t.TempDir()
+ first, err := cache.CreateWorktree(WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: sourceRepo,
+ WorkDir: workDir,
+ AgentName: "Linux Codex",
+ TaskID: "11111111-1111-1111-1111-111111111111",
+ IsolatedGitMetadata: true,
+ })
+ if err != nil {
+ t.Fatalf("first CreateWorktree failed: %v", err)
+ }
+ const userBranch = "feature/keep-me"
+ runGitAuthored(t, first.Path, "checkout", "-b", userBranch)
+ addEmptyCommit(t, first.Path, "unpublished feature work")
+ userCommit := gitHead(t, first.Path)
+
+ addEmptyCommit(t, sourceRepo, "upstream advance")
+ wantHead := gitHead(t, sourceRepo)
+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {
+ t.Fatalf("refresh sync failed: %v", err)
+ }
+
+ second, err := cache.CreateWorktree(WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: sourceRepo,
+ WorkDir: workDir,
+ AgentName: "Linux Codex",
+ TaskID: "22222222-2222-2222-2222-222222222222",
+ IsolatedGitMetadata: true,
+ })
+ if err != nil {
+ t.Fatalf("second CreateWorktree failed: %v", err)
+ }
+ if second.Path != first.Path {
+ t.Fatalf("reused checkout path = %q, want %q", second.Path, first.Path)
+ }
+ if second.BranchName == first.BranchName {
+ t.Fatalf("reused checkout kept old branch %q", first.BranchName)
+ }
+ if got := gitHead(t, second.Path); got != wantHead {
+ t.Fatalf("reused checkout HEAD = %s, want refreshed upstream %s", got, wantHead)
+ }
+
+ // Reuse must not accumulate earlier tasks' agent/* branches, but it must
+ // preserve user-created branches and commits that may not exist remotely.
+ if err := runGit("-C", second.Path, "show-ref", "--verify", "refs/heads/"+first.BranchName); err == nil {
+ t.Fatalf("stale branch %s survived reuse", first.BranchName)
+ }
+ if got := gitRefCommit(t, second.Path, "refs/heads/"+userBranch); got != userCommit {
+ t.Fatalf("preserved user branch commit = %s, want %s", got, userCommit)
+ }
+ heads, err := runGitOutput("-C", second.Path, "for-each-ref", "--format=%(refname)", "refs/heads/")
+ if err != nil {
+ t.Fatalf("list local heads: %v", err)
+ }
+ wantHeads := "refs/heads/" + second.BranchName + "\nrefs/heads/" + userBranch
+ if got := strings.TrimSpace(string(heads)); got != wantHeads {
+ t.Fatalf("reused checkout local heads = %q, want %q", got, wantHeads)
+ }
+}
+
+func TestCreateWorktreeMigratesLinkedWorktreeToIsolatedMetadata(t *testing.T) {
+ t.Parallel()
+ sourceRepo := createTestRepo(t)
+ cache := New(t.TempDir(), testLogger())
+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {
+ t.Fatalf("sync failed: %v", err)
+ }
+
+ workDir := t.TempDir()
+ linked, err := cache.CreateWorktree(WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: sourceRepo,
+ WorkDir: workDir,
+ AgentName: "Linux Codex",
+ TaskID: "11111111-1111-1111-1111-111111111111",
+ })
+ if err != nil {
+ t.Fatalf("linked CreateWorktree failed: %v", err)
+ }
+ if !isGitWorktree(linked.Path) {
+ t.Fatal("test setup did not create a linked worktree")
+ }
+
+ isolated, err := cache.CreateWorktree(WorktreeParams{
+ WorkspaceID: "ws-1",
+ RepoURL: sourceRepo,
+ WorkDir: workDir,
+ AgentName: "Linux Codex",
+ TaskID: "22222222-2222-2222-2222-222222222222",
+ IsolatedGitMetadata: true,
+ })
+ if err != nil {
+ t.Fatalf("isolated CreateWorktree failed: %v", err)
+ }
+ if isolated.Path != linked.Path {
+ t.Fatalf("migrated checkout path = %q, want %q", isolated.Path, linked.Path)
+ }
+ if !isIsolatedCheckout(isolated.Path) {
+ t.Fatal("linked worktree was not migrated to isolated metadata")
+ }
+
+ barePath := cache.Lookup("ws-1", sourceRepo)
+ out, err := runGitOutput("-C", barePath, "worktree", "list", "--porcelain")
+ if err != nil {
+ t.Fatalf("list cache worktrees: %v", err)
+ }
+ if strings.Contains(string(out), "worktree "+linked.Path+"\n") {
+ t.Fatalf("shared cache retained migrated worktree admin entry:\n%s", out)
+ }
+}
+
func TestCreateWorktreeExcludesOpenCodeSkills(t *testing.T) {
t.Parallel()
sourceRepo := createTestRepo(t)
diff --git a/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md b/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md
index acb6094c93..3a7ada5ba9 100644
--- a/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md
@@ -45,7 +45,7 @@ multica repo checkout <url>
multica repo checkout <url> --ref <branch-or-sha>
```
-`runtime update` and `runtime delete` are writes. Starting a runtime update is limited to its owner or a workspace owner/admin; the original initiator may keep polling that specific in-flight request if their admin role changes. `runtime delete` removes a runtime registration; if active agents are still bound, it refuses unless the user explicitly passes `--cascade`, which archives those agents and cancels their queued/running tasks before deleting the runtime. `repo checkout` creates a git worktree in the task working directory.
+`runtime update` and `runtime delete` are writes. Starting a runtime update is limited to its owner or a workspace owner/admin; the original initiator may keep polling that specific in-flight request if their admin role changes. `runtime delete` removes a runtime registration; if active agents are still bound, it refuses unless the user explicitly passes `--cascade`, which archives those agents and cancels their queued/running tasks before deleting the runtime. `repo checkout` creates a dedicated branch in the task working directory. Most runtimes use a linked worktree; Linux Codex uses task-local Git metadata so its `workspace-write` sandbox can stage and commit without making the shared `.repos` cache writable.
`repo checkout` requires `MULTICA_DAEMON_PORT`; it is intended to run inside a daemon task. If absent, you are not in the normal agent checkout path. When a project `github_repo` resource has `resource_ref.ref`, `repo checkout <url>` uses that ref by default for the current task; an explicit `repo checkout <url> --ref <branch-or-sha>` overrides it.
diff --git a/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md b/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md
index bdd69a8fe4..bcb4290d43 100644
--- a/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md
+++ b/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md
@@ -5,8 +5,9 @@
- `runtime update` posts to `/api/runtimes/{runtime-id}/update`; with `--wait` it polls update status. Initiation enforces runtime-owner or workspace-owner/admin access through `canEditRuntime`; status polling additionally permits that request's immutable initiator so an in-flight poll survives an admin-role change (`server/internal/handler/runtime_update.go` and `runtime.go`).
- `runtime delete` deletes `/api/runtimes/{runtime-id}`; with `--cascade`, it first reads the `runtime_has_active_agents` conflict payload and posts those ids to `/api/runtimes/{runtime-id}/archive-agents-and-delete`.
- `server/cmd/multica/cmd_repo.go` registers `repo checkout <url> [--ref]`.
-- `repo checkout` requires `MULTICA_DAEMON_PORT`, sends `workspace_id`, `workdir`, `ref`, `agent_name`, and `task_id` to local daemon `/repo/checkout`, then prints the checked-out path.
-- `server/internal/daemon/health.go` resolves the checkout ref: request `ref` wins; otherwise it asks `server/internal/daemon/daemon.go` for the current task's project repo default ref.
+- `repo checkout` requires `MULTICA_DAEMON_PORT`, sends `workspace_id`, `workdir`, `ref`, `agent_name`, `task_id`, and the daemon-managed optional `checkout_mode` to local daemon `/repo/checkout`, then prints the checked-out path.
+- `server/internal/daemon/health.go` resolves the checkout ref: request `ref` wins; otherwise it asks `server/internal/daemon/daemon.go` for the current task's project repo default ref. It forwards the validated isolated-checkout mode into `repocache.WorktreeParams`.
+- `server/internal/daemon/daemon.go` injects `MULTICA_REPO_CHECKOUT_MODE=isolated` only for Linux Codex tasks. `server/internal/daemon/repocache/cache.go` implements that mode as a same-filesystem local clone with task-local Git metadata and the real repository as `origin`; other runtimes keep the linked-worktree path.
- `server/cmd/server/router.go` registers daemon APIs under `/api/daemon`, including workspace repos and task claim.
- `server/internal/daemon/daemon.go` claims tasks, prepares workdirs, launches provider CLIs, and reports completion.
- `server/internal/daemon/execenv/runtime_config.go` injects task/project/repo context into agent workdirs.