Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): isolate cached worktree Git identities (MUL-7423) (#8470)
Jiayuan Zhang080b118f07c2
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex ac2dbb17ce..be618070c0 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -243,6 +243,35 @@ make stop-worktree # stopmake check-worktree # verify```+### Git Identity in Managed Task Checkouts++`multica repo checkout` uses the user's system/global Git identity, including+conditional includes evaluated in the checkout. Agent names determine branch+names, not commit authors. The optional `Co-authored-by` trailer is independent+of author and committer identity.++Linked worktrees mask the shared cache's `user`, `author`, and `committer`+name/email settings with private defaults in `multica-identity.config`, included+first by their `config.worktree`. Repeating checkout refreshes these defaults;+explicit worktree settings and Git command/environment overrides take precedence.+Conditional identities are snapshots: switching branches or changing global+config takes effect in these defaults on the next checkout call, not at commit time.+Use `git config --worktree user.name "Your Name"` and+`git config --worktree user.email "[email protected]"` for an intentional checkout+override. Plain `git config` and `--local` write to the shared cache in linked+worktrees. Isolated clones already have private config and retain it unchanged.+If no user identity is configured, commits fail instead of using a stale cache+identity; configure an explicit worktree identity before committing.++Existing linked checkouts receive the protection on their next checkout call,+including calls that keep local work. Residual shared identity is masked, not+deleted: changing it would change other running tasks. Existing tasks that never+repeat checkout remain unprotected until they do. Enabling `worktreeConfig`+moves `core.bare`/`core.worktree` to the bare repository's own `config.worktree`+without changing other worktrees' effective settings. The files are standard Git+config; older daemons leave them in place, but do not refresh identity defaults+or protect newly created worktrees. No pushed commit history is rewritten.+### Removing a WorktreeGit does not provide a `pre-worktree-remove` hook. Use the repository wrapperdiff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex 78b63704c8..afbae026b0 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -277,6 +277,7 @@ func writeAvailableCommands(b *strings.Builder, ctx TaskContextForEnv) {b.WriteString("- `multica issue children <id> [--output json]` — list a parent's sub-issues grouped by stage.\n")b.WriteString("- `multica issue comment add <issue-id> [--content \"...\" | --content-file <path> | --content-stdin] [--parent <comment-id>] [--attachment <path>]` — post a comment. Agent-authored bodies MUST use `--content-file`; see `## Comment Formatting` for why. `multica issue comment add --help` for full flags.\n")b.WriteString("- `multica repo checkout <url> [--ref <branch-or-sha>] [--fresh]` — repository checkout on a dedicated branch. Re-running it keeps an existing checkout that has uncommitted or unpushed work, or is already on this task's branch, and only fetches. `--fresh` discards uncommitted and untracked files and starts a new branch; commits stay on the old branch, but push any you still need first.\n\n")+ b.WriteString("Git commits use the user's configured identity. Preserve it unless the user requests another identity. In a managed checkout, use `git config --worktree user.name` / `user.email` for an intentional task-local override; plain `git config` or `--local` can write into a shared cache and affect other tasks. Never change global Git identity for a task.\n\n")// Squad maintenance is squad-leader surface: an agent that leads no squad// has no squad to change roles in, so this shipped to every run as dead// weight (MUL-5442). IsSquadLeader is a PER-TASK role (the daemon derivesdiff --git a/server/internal/daemon/repocache/cache.go b/server/internal/daemon/repocache/cache.goindex e1587de109..3d754246c1 100644--- a/server/internal/daemon/repocache/cache.go+++ b/server/internal/daemon/repocache/cache.go@@ -889,6 +889,9 @@ func (c *Cache) CreateWorktreeContext(ctx context.Context, params WorktreeParamsfor _, pattern := range agentGitExcludePatterns {_ = excludeFromGitContext(ctx, worktreePath, pattern)}+ if err := isolateWorktreeIdentityContext(ctx, barePath, worktreePath); err != nil {+ return nil, fmt.Errorf("isolate checkout Git identity: %w", err)+ }c.applyCoAuthoredBySettingContext(ctx, worktreePath, params)if err := ctx.Err(); err != nil {return nil, context.Cause(ctx)@@ -910,6 +913,10 @@ func (c *Cache) CreateWorktreeContext(ctx context.Context, params WorktreeParams_ = excludeFromGitContext(ctx, worktreePath, pattern)}+ if err := isolateWorktreeIdentityContext(ctx, barePath, worktreePath); err != nil {+ return nil, fmt.Errorf("isolate checkout Git identity: %w", err)+ }+// Reconcile the Co-authored-by hook and the workspace's recorded// setting. The hook lives in the bare repo's shared hooks dir, so we// must actively remove it when disabled — otherwise a previously@@ -936,6 +943,10 @@ func (c *Cache) CreateWorktreeContext(ctx context.Context, params WorktreeParams_ = excludeFromGitContext(ctx, worktreePath, pattern)}+ if err := isolateWorktreeIdentityContext(ctx, barePath, worktreePath); err != nil {+ return nil, fmt.Errorf("isolate checkout Git identity: %w", err)+ }+// Reconcile the Co-authored-by hook and the workspace's recorded setting.// See the existing-worktree branch above for why removal is required when// the setting is disabled.diff --git a/server/internal/daemon/repocache/identity.go b/server/internal/daemon/repocache/identity.gonew file mode 100644index 0000000000..48e09425a1--- /dev/null+++ b/server/internal/daemon/repocache/identity.go@@ -0,0 +1,195 @@+package repocache++import (+ "context"+ "errors"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+)++const identityConfigInclude = "# Multica identity defaults; explicit worktree settings below take precedence.\n[include]\n\tpath = multica-identity.config\n"++// isolateWorktreeIdentityContext masks identity inherited from the shared cache+// without rewriting it: other, possibly running, worktrees must not change.+// The user's system/global config (including conditional includes evaluated in+// this checkout) supplies the defaults. Explicit worktree config and Git's+// command/environment overrides retain their normal precedence. AgentName is+// deliberately not an author identity, and the co-author hook is independent.+//+// Defaults live in an include before the user's worktree settings, so a later+// checkout can refresh them without overwriting intentional task-local values.+// Missing identities are masked with empty values: fail at commit time rather+// than silently attribute work to the shared cache's previous author.+func isolateWorktreeIdentityContext(ctx context.Context, barePath, checkoutPath string) error {+ if !isGitWorktree(checkoutPath) {+ // Isolated clones already have private config and do not copy the+ // cache's identity. Preserve their intentional repository identity.+ return nil+ }+ out, err := runGitOutputContext(ctx, "-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 err := enableWorktreeConfigContext(ctx, barePath); err != nil {+ return err+ }+ out, err = runGitOutputContext(ctx, "-C", checkoutPath, "rev-parse", "--absolute-git-dir")+ if err != nil {+ return fmt.Errorf("resolve worktree config directory: %w", err)+ }+ gitDir := strings.TrimSpace(string(out))+ out, err = runGitOutputContext(ctx, "-C", checkoutPath, "config", "--null", "--show-scope", "--includes", "--get-regexp", `^(user|author|committer)\.(name|email)$`)+ var exitErr *exec.ExitError+ if err != nil && !(errors.As(err, &exitErr) && exitErr.ExitCode() == 1) {+ return fmt.Errorf("read user Git identity: %w", err)+ }+ values := make(map[string]string)+ fields := strings.Split(string(out), "\x00")+ for i := 0; i+1 < len(fields); i += 2 {+ if fields[i] != "global" && fields[i] != "system" {+ continue+ }+ key, value, _ := strings.Cut(fields[i+1], "\n")+ values[key] = value+ }+ var config strings.Builder+ for _, section := range []string{"user", "author", "committer"} {+ fmt.Fprintf(&config, "[%s]\n", section)+ for _, field := range []string{"name", "email"} {+ // Empty author/committer fields fall back to user.* in Git.+ fmt.Fprintf(&config, "\t%s = %s\n", field, quoteGitConfig(values[section+"."+field]))+ }+ }+ if err := editGitConfigFile(filepath.Join(gitDir, "multica-identity.config"), func(_ []byte, _ string) ([]byte, error) {+ return []byte(config.String()), nil+ }); err != nil {+ return err+ }+ return editGitConfigFile(filepath.Join(gitDir, "config.worktree"), func(contents []byte, _ string) ([]byte, error) {+ if strings.HasPrefix(string(contents), identityConfigInclude) {+ return contents, nil+ }+ return append([]byte(identityConfigInclude), contents...), nil+ })+}++func quoteGitConfig(value string) string {+ replacer := strings.NewReplacer("\\", "\\\\", "\"", "\\\"", "\n", "\\n", "\t", "\\t", "\b", "\\b")+ return "\"" + replacer.Replace(value) + "\""+}++// Git requires core.bare/core.worktree to move to the main worktree's config+// when enabling worktreeConfig. Publish the extension and removal together so+// existing linked worktrees never see the bare cache's core.bare=true applied+// to themselves. No shared identity keys are removed or rewritten.+func enableWorktreeConfigContext(ctx context.Context, barePath string) error {+ configPath := filepath.Join(barePath, "config")+ // Once migrated, identity setup only needs private worktree files. Do not+ // compete with agent-side git config writers for the common config lock.+ if enabled, err := worktreeConfigEnabledContext(ctx, configPath); err != nil || enabled {+ return err+ }+ return editGitConfigFile(configPath, func(contents []byte, lockPath string) ([]byte, error) {+ // Another writer may have enabled it before we acquired the lock.+ if enabled, err := worktreeConfigEnabledContext(ctx, lockPath); err != nil || enabled {+ return contents, err+ }+ for _, key := range []string{"core.bare", "core.worktree"} {+ out, err := runGitOutputContext(ctx, "config", "--file", lockPath, "--get", key)+ var exitErr *exec.ExitError+ if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 {+ continue+ }+ if err != nil {+ return nil, err+ }+ value := strings.TrimSuffix(string(out), "\n")+ if err := runGitContext(ctx, "config", "--file", filepath.Join(barePath, "config.worktree"), key, value); err != nil {+ return nil, err+ }+ if err := runGitContext(ctx, "config", "--file", lockPath, "--unset-all", key); err != nil {+ return nil, err+ }+ }+ if err := runGitContext(ctx, "config", "--file", lockPath, "extensions.worktreeConfig", "true"); err != nil {+ return nil, err+ }+ return os.ReadFile(lockPath)+ })+}++func worktreeConfigEnabledContext(ctx context.Context, path string) (bool, error) {+ out, err := runGitOutputContext(ctx, "config", "--file", path, "--bool", "--get", "extensions.worktreeConfig")+ var exitErr *exec.ExitError+ if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 {+ return false, nil+ }+ return strings.TrimSpace(string(out)) == "true", err+}++// Follow Git's lockfile protocol and atomically publish a complete config.+// This also respects concurrent user `git config` writes outside our repo lock.+func editGitConfigFile(path string, edit func([]byte, string) ([]byte, error)) error {+ return editGitConfigFileWithRename(path, edit, os.Rename)+}++// The rename argument lets tests place another writer exactly at lock handoff.+func editGitConfigFileWithRename(path string, edit func([]byte, string) ([]byte, error), rename func(string, string) error) error {+ lockPath := path + ".lock"+ f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)+ if err != nil {+ return fmt.Errorf("lock Git config: %w", err)+ }+ owned := true+ defer func() {+ if owned {+ _ = os.Remove(lockPath)+ }+ }()+ contents, err := os.ReadFile(path)+ if err != nil && !os.IsNotExist(err) {+ f.Close()+ return err+ }+ if info, err := os.Stat(path); err == nil {+ if err := f.Chmod(info.Mode().Perm()); err != nil {+ f.Close()+ return err+ }+ }+ _, writeErr := f.Write(contents)+ closeErr := f.Close()+ if writeErr != nil {+ return writeErr+ }+ if closeErr != nil {+ return closeErr+ }+ updated, err := edit(contents, lockPath)+ if err != nil {+ return err+ }+ if string(contents) == string(updated) {+ return nil+ }+ if err := os.WriteFile(lockPath, updated, 0o600); err != nil {+ return err+ }+ if err := rename(lockPath, path); err != nil {+ return err+ }+ // Rename consumes our lock. Its old path may already belong to another+ // writer, so deferred cleanup must only unlink on rollback, never publish.+ owned = false+ return nil+}diff --git a/server/internal/daemon/repocache/identity_test.go b/server/internal/daemon/repocache/identity_test.gonew file mode 100644index 0000000000..23c943e1a7--- /dev/null+++ b/server/internal/daemon/repocache/identity_test.go@@ -0,0 +1,362 @@+package repocache++import (+ "context"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "testing"+)++func identityTestEnvironment(t *testing.T) string {+ t.Helper()+ for _, key := range []string{"GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", "GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL", "GIT_CONFIG_COUNT", "GIT_CONFIG_PARAMETERS"} {+ t.Setenv(key, "")+ if err := os.Unsetenv(key); err != nil {+ t.Fatal(err)+ }+ }+ global := filepath.Join(t.TempDir(), "gitconfig")+ t.Setenv("GIT_CONFIG_GLOBAL", global)+ t.Setenv("GIT_CONFIG_NOSYSTEM", "1")+ gitIdentityCommand(t, "config", "--global", "user.name", "User")+ gitIdentityCommand(t, "config", "--global", "user.email", "[email protected]")+ return global+}++func gitIdentityCommand(t *testing.T, args ...string) string {+ t.Helper()+ out, err := runGitCombinedOutput(args...)+ if err != nil {+ t.Fatalf("git %v: %s: %v", args, out, err)+ }+ return strings.TrimSpace(string(out))+}++func assertCommitIdentity(t *testing.T, path, name, email string) {+ t.Helper()+ gitIdentityCommand(t, "-C", path, "commit", "--allow-empty", "-m", "identity regression")+ got := gitIdentityCommand(t, "-C", path, "log", "-1", "--format=%an <%ae>|%cn <%ce>")+ want := fmt.Sprintf("%s <%s>|%s <%s>", name, email, name, email)+ if got != want {+ t.Fatalf("commit identity = %q, want %q", got, want)+ }+}++func polluteCacheIdentity(t *testing.T, path string) {+ t.Helper()+ for _, section := range []string{"user", "author", "committer"} {+ gitIdentityCommand(t, "-C", path, "config", "--local", section+".name", "Old Agent")+ gitIdentityCommand(t, "-C", path, "config", "--local", section+".email", "[email protected]")+ }+}++func TestCheckoutIdentityIgnoresSharedCache(t *testing.T) {+ global := identityTestEnvironment(t)+ before, _ := os.ReadFile(global)+ for _, mode := range checkoutModes {+ t.Run(mode.name, func(t *testing.T) {+ f := newExistingCheckoutFixture(t, mode.isolated)+ bare := f.cache.Lookup("ws-1", f.source)+ polluteCacheIdentity(t, bare)+ first := f.checkout(t, firstTaskID, false)+ assertCommitIdentity(t, first.Path, "User", "[email protected]")+ // Reuse, including the keep-local-work branch, must retain isolation.+ again := f.checkout(t, secondTaskID, false)+ assertCommitIdentity(t, again.Path, "User", "[email protected]")+ if got := gitIdentityCommand(t, "-C", bare, "config", "--local", "user.name"); got != "Old Agent" {+ t.Fatalf("shared identity was changed: %q", got)+ }+ })+ }+ after, _ := os.ReadFile(global)+ if string(after) != string(before) {+ t.Fatal("checkout changed global Git config")+ }+}++func TestCheckoutIdentityConcurrentTasksAndOverrides(t *testing.T) {+ identityTestEnvironment(t)+ f := newExistingCheckoutFixture(t, false)+ bare := f.cache.Lookup("ws-1", f.source)+ polluteCacheIdentity(t, bare)+ var wg sync.WaitGroup+ results := make([]*WorktreeResult, 2)+ errs := make([]error, 2)+ params := make([]WorktreeParams, 2)+ for i := range params {+ params[i] = WorktreeParams{WorkspaceID: "ws-1", RepoURL: f.source, WorkDir: t.TempDir(), AgentName: "Agent", TaskID: fmt.Sprintf("task-%d", i)}+ wg.Add(1)+ go func() {+ defer wg.Done()+ results[i], errs[i] = f.cache.CreateWorktree(params[i])+ }()+ }+ wg.Wait()+ for _, err := range errs {+ if err != nil {+ t.Fatal(err)+ }+ }+ gitIdentityCommand(t, "-C", results[0].Path, "config", "--worktree", "user.name", "Task A")+ gitIdentityCommand(t, "-C", results[0].Path, "config", "--worktree", "user.email", "[email protected]")+ // A plain `git config` still writes shared config in linked worktrees.+ // Even such a later write must not change another protected task.+ gitIdentityCommand(t, "-C", results[0].Path, "config", "user.name", "Later contamination")+ assertCommitIdentity(t, results[0].Path, "Task A", "[email protected]")+ assertCommitIdentity(t, results[1].Path, "User", "[email protected]")+ gitIdentityCommand(t, "config", "--global", "user.name", "Updated User")+ for i := range params {+ if _, err := f.cache.CreateWorktree(params[i]); err != nil {+ t.Fatal(err)+ }+ }+ assertCommitIdentity(t, results[0].Path, "Task A", "[email protected]")+ assertCommitIdentity(t, results[1].Path, "Updated User", "[email protected]")+}++func TestCheckoutIdentityMigratesExistingWorktree(t *testing.T) {+ identityTestEnvironment(t)+ for _, enabled := range []bool{false, true} {+ t.Run(fmt.Sprintf("worktreeConfig=%v", enabled), func(t *testing.T) {+ f := newExistingCheckoutFixture(t, false)+ bare := f.cache.Lookup("ws-1", f.source)+ polluteCacheIdentity(t, bare)+ path := filepath.Join(f.workDir, repoNameFromURL(f.source))+ gitIdentityCommand(t, "-C", bare, "worktree", "add", "-b", taskBranchName(firstTaskID), path)+ other := filepath.Join(t.TempDir(), "active")+ gitIdentityCommand(t, "-C", bare, "worktree", "add", "-b", "other-active-task", other)+ if enabled {+ // Model caches already using the extension before this fix.+ gitIdentityCommand(t, "-C", bare, "config", "core.bare", "false")+ gitIdentityCommand(t, "-C", bare, "config", "extensions.worktreeConfig", "true")+ gitIdentityCommand(t, "-C", path, "config", "--worktree", "user.name", "Intentional")+ gitIdentityCommand(t, "-C", path, "config", "--worktree", "user.email", "[email protected]")+ }+ result := f.checkout(t, firstTaskID, false)+ if enabled {+ assertCommitIdentity(t, result.Path, "Intentional", "[email protected]")+ } else {+ assertCommitIdentity(t, result.Path, "User", "[email protected]")+ if got := gitIdentityCommand(t, "-C", bare, "rev-parse", "--is-bare-repository"); got != "true" {+ t.Fatalf("cache stopped being bare: %s", got)+ }+ }+ // Do not mutate another active checkout's effective identity or+ // turn it into a bare repository while enabling the extension.+ assertCommitIdentity(t, other, "Old Agent", "[email protected]")+ })+ }+}++func TestCheckoutIdentityUserConfigAndCoauthor(t *testing.T) {+ identityTestEnvironment(t)+ f := newExistingCheckoutFixture(t, false)+ bare := f.cache.Lookup("ws-1", f.source)+ polluteCacheIdentity(t, bare)+ include := filepath.Join(t.TempDir(), "identity.config")+ gitIdentityCommand(t, "config", "--file", include, "user.name", "Conditional User")+ gitIdentityCommand(t, "config", "--file", include, "author.name", "Explicit Author")+ gitIdentityCommand(t, "config", "--global", "includeIf.onbranch:agent/**.path", filepath.ToSlash(include))+ for _, enabled := range []bool{true, false} {+ params := WorktreeParams{WorkspaceID: "ws-1", RepoURL: f.source, WorkDir: f.workDir, AgentName: "Agent", TaskID: firstTaskID, CoAuthoredByEnabled: enabled}+ result, err := f.cache.CreateWorktree(params)+ if err != nil {+ t.Fatal(err)+ }+ gitIdentityCommand(t, "-C", result.Path, "commit", "--allow-empty", "-m", "coauthor identity")+ got := gitIdentityCommand(t, "-C", result.Path, "log", "-1", "--format=%an <%ae>|%cn <%ce>")+ if got != "Explicit Author <[email protected]>|Conditional User <[email protected]>" {+ t.Fatalf("conditional user/author identity = %q", got)+ }+ body := gitIdentityCommand(t, "-C", result.Path, "log", "-1", "--format=%B")+ if strings.Contains(body, "Co-authored-by: multica-agent <[email protected]>") != enabled {+ t.Fatalf("coauthor enabled=%v, commit body: %s", enabled, body)+ }+ }+ // Explicit environment values remain Git's highest-priority identity.+ t.Setenv("GIT_AUTHOR_NAME", "Environment")+ t.Setenv("GIT_AUTHOR_EMAIL", "[email protected]")+ t.Setenv("GIT_COMMITTER_NAME", "Environment")+ t.Setenv("GIT_COMMITTER_EMAIL", "[email protected]")+ assertCommitIdentity(t, filepath.Join(f.workDir, repoNameFromURL(f.source)), "Environment", "[email protected]")+}++func TestCheckoutIdentityWithoutUserFailsClosed(t *testing.T) {+ global := identityTestEnvironment(t)+ if err := os.WriteFile(global, nil, 0o600); err != nil {+ t.Fatal(err)+ }+ f := newExistingCheckoutFixture(t, false)+ polluteCacheIdentity(t, f.cache.Lookup("ws-1", f.source))+ result := f.checkout(t, firstTaskID, false)+ if out, err := runGitCombinedOutput("-C", result.Path, "commit", "--allow-empty", "-m", "must not use cache author"); err == nil {+ t.Fatalf("commit succeeded without a configured identity: %s", out)+ }+ // Setting an explicit worktree identity restores ordinary commits.+ gitIdentityCommand(t, "-C", result.Path, "config", "--worktree", "user.name", "Configured")+ gitIdentityCommand(t, "-C", result.Path, "config", "--worktree", "user.email", "[email protected]")+ assertCommitIdentity(t, result.Path, "Configured", "[email protected]")+}++func TestIsolatedCheckoutPreservesIntentionalIdentity(t *testing.T) {+ identityTestEnvironment(t)+ f := newExistingCheckoutFixture(t, true)+ result := f.checkout(t, firstTaskID, false)+ gitIdentityCommand(t, "-C", result.Path, "config", "user.name", "Local User")+ gitIdentityCommand(t, "-C", result.Path, "config", "user.email", "[email protected]")+ f.checkout(t, firstTaskID, false)+ assertCommitIdentity(t, result.Path, "Local User", "[email protected]")+}++func TestCheckoutIdentityConfigLockFailureIsRetryable(t *testing.T) {+ identityTestEnvironment(t)+ f := newExistingCheckoutFixture(t, false)+ result := f.checkout(t, firstTaskID, false)+ gitDir := gitIdentityCommand(t, "-C", result.Path, "rev-parse", "--absolute-git-dir")+ lock := filepath.Join(gitDir, "config.worktree.lock")+ if err := os.WriteFile(lock, []byte("another writer"), 0o600); err != nil {+ t.Fatal(err)+ }+ _, err := f.cache.CreateWorktree(WorktreeParams{WorkspaceID: "ws-1", RepoURL: f.source, WorkDir: f.workDir, AgentName: "Agent", TaskID: firstTaskID})+ if err == nil || !strings.Contains(err.Error(), "lock Git config") {+ t.Fatalf("checkout error = %v, want config lock failure", err)+ }+ contents, err := os.ReadFile(lock)+ if err != nil || string(contents) != "another writer" {+ t.Fatalf("another writer's lock changed: %s, %v", contents, err)+ }+ assertCommitIdentity(t, result.Path, "User", "[email protected]")+ if err := os.Remove(lock); err != nil {+ t.Fatal(err)+ }+ f.checkout(t, firstTaskID, false)+}++func TestCheckoutIdentityRejectsForeignWorktree(t *testing.T) {+ identityTestEnvironment(t)+ f := newExistingCheckoutFixture(t, false)+ foreign := filepath.Join(t.TempDir(), "foreign")+ gitIdentityCommand(t, "-C", f.source, "worktree", "add", "-b", "foreign", foreign)+ err := isolateWorktreeIdentityContext(context.Background(), f.cache.Lookup("ws-1", f.source), foreign)+ if err == nil || !strings.Contains(err.Error(), "does not match cache") {+ t.Fatalf("identity isolation error = %v, want foreign repository rejection", err)+ }+ gitDir := gitIdentityCommand(t, "-C", foreign, "rev-parse", "--absolute-git-dir")+ if _, err := os.Stat(filepath.Join(gitDir, "config.worktree")); !os.IsNotExist(err) {+ t.Fatalf("foreign worktree config was written: %v", err)+ }+}++func TestCheckoutIdentityEnabledWithSharedConfigLocked(t *testing.T) {+ identityTestEnvironment(t)+ f := newExistingCheckoutFixture(t, false)+ first := f.checkout(t, firstTaskID, false)+ firstWorkDir := f.workDir+ f.workDir = t.TempDir()+ second := f.checkout(t, secondTaskID, false)+ secondWorkDir := f.workDir+ bare := f.cache.Lookup("ws-1", f.source)+ lockPath := filepath.Join(bare, "config.lock")+ lock, err := os.OpenFile(lockPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := lock.WriteString("sibling writer"); err != nil {+ lock.Close()+ t.Fatal(err)+ }+ if err := lock.Close(); err != nil {+ t.Fatal(err)+ }+ defer os.Remove(lockPath)++ // Reusing either checkout needs no common config write after migration.+ // Create them before taking the lock: Git itself can require that lock+ // when initially recording the new branches' upstream configuration.+ f.workDir = firstWorkDir+ f.checkout(t, firstTaskID, false)+ f.workDir = secondWorkDir+ f.checkout(t, secondTaskID, false)+ for _, path := range []string{first.Path, second.Path} {+ assertCommitIdentity(t, path, "User", "[email protected]")+ }+ contents, err := os.ReadFile(lockPath)+ if err != nil || string(contents) != "sibling writer" {+ t.Fatalf("sibling writer's lock changed: %q, %v", contents, err)+ }+}++func TestEditGitConfigFilePreservesNextWriterLock(t *testing.T) {+ path := filepath.Join(t.TempDir(), "config")+ lockPath := path + ".lock"+ err := editGitConfigFileWithRename(path, func([]byte, string) ([]byte, error) {+ return []byte("[user]\nname = User\n"), nil+ }, func(oldPath, newPath string) error {+ if err := os.Rename(oldPath, newPath); err != nil {+ return err+ }+ // A subsequent writer can acquire the path immediately after rename,+ // before the publisher returns and its deferred cleanup runs.+ next, err := os.OpenFile(lockPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)+ if err != nil {+ return err+ }+ _, writeErr := next.WriteString("next writer")+ closeErr := next.Close()+ return errors.Join(writeErr, closeErr)+ })+ if err != nil {+ t.Fatal(err)+ }+ contents, err := os.ReadFile(lockPath)+ if err != nil || string(contents) != "next writer" {+ t.Fatalf("next writer's lock changed: %q, %v", contents, err)+ }+ if third, err := os.OpenFile(lockPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600); !os.IsExist(err) {+ if third != nil {+ third.Close()+ }+ t.Fatalf("third writer should remain excluded, got %v", err)+ }+}++func TestEditGitConfigFileRollback(t *testing.T) {+ for _, outcome := range []string{"unchanged", "edit error", "rename error"} {+ t.Run(outcome, func(t *testing.T) {+ path := filepath.Join(t.TempDir(), "config")+ original := "[user]\nname = Original\n"+ if err := os.WriteFile(path, []byte(original), 0o600); err != nil {+ t.Fatal(err)+ }+ failure := errors.New("injected failure")+ err := editGitConfigFileWithRename(path, func(contents []byte, _ string) ([]byte, error) {+ if outcome == "unchanged" {+ return contents, nil+ }+ if outcome == "edit error" {+ return nil, failure+ }+ return []byte("[user]\nname = Updated\n"), nil+ }, func(string, string) error {+ if outcome != "rename error" {+ t.Fatal("unexpected publish on rollback path")+ }+ return failure+ })+ if outcome == "unchanged" && err != nil || outcome != "unchanged" && !errors.Is(err, failure) {+ t.Fatalf("edit error = %v for %s", err, outcome)+ }+ contents, err := os.ReadFile(path)+ if err != nil || string(contents) != original {+ t.Fatalf("config changed on rollback: %q, %v", contents, err)+ }+ if _, err := os.Stat(path + ".lock"); !os.IsNotExist(err) {+ t.Fatalf("owned lock not cleaned up: %v", err)+ }+ })+ }+}