Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6491 fix(daemon): give each task an exclusively claimed env root (#7347)
Bohan Jiang3622db21cf90
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex c7cc62c89d..02f430f8ec 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -5,10 +5,12 @@ package execenvimport ("encoding/json"+ "errors""fmt""log/slog""os""path/filepath"+ "strings""time""github.com/multica-ai/multica/server/internal/runtimeapps"@@ -318,7 +320,7 @@ func PredictRootDir(workspacesRoot, workspaceID, taskID string) string {if workspacesRoot == "" || workspaceID == "" || taskID == "" {return ""}- return filepath.Join(workspacesRoot, workspaceID, shortID(taskID))+ return filepath.Join(workspacesRoot, workspaceID, taskKey(taskID))}// Prepare creates an isolated execution environment for a task.@@ -335,7 +337,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {return nil, fmt.Errorf("execenv: task ID is required")}- envRoot := filepath.Join(params.WorkspacesRoot, params.WorkspaceID, shortID(params.TaskID))+ envRoot := PredictRootDir(params.WorkspacesRoot, params.WorkspaceID, params.TaskID)// Self-heal the root-level daemon marker on every task start so a marker// removed while the daemon runs is restored before the agent spawns. The@@ -347,10 +349,31 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {logger.Warn("execenv: workspaces root marker not written; fail-closed guard limited to the task workdir", "error", err)}- // Remove existing env if present (defensive — task IDs are unique).- if _, err := os.Stat(envRoot); err == nil {- if err := os.RemoveAll(envRoot); err != nil {- return nil, fmt.Errorf("execenv: remove existing env: %w", err)+ // Take exclusive ownership of the env root before touching anything in it.+ // What follows wipes the directory, and while the segment was a UUIDv7+ // prefix that routinely wiped a live sibling task's workdir, worktree and+ // task-scoped config (#7326). taskKey now reads the id's random tail, which+ // makes a shared path improbable rather than impossible — so prove+ // ownership instead of assuming it. A task that refuses to start is+ // recoverable; one that deletes a running sibling's uncommitted work is not.+ //+ // claimEnvRoot is the only thing standing between two same-key tasks, so it+ // has to be atomic end to end: a read-then-delete would let both pass the+ // check and one still delete the other. Once claimed, the claim is held for+ // the rest of Prepare — the reset below clears the directory's CONTENTS and+ // leaves the marker in place, so there is never a moment where the env root+ // looks unowned to a racing task.+ fresh, err := claimEnvRoot(envRoot, params.TaskID)+ if err != nil {+ return nil, fmt.Errorf("execenv: %w", err)+ }+ // Not fresh means this task already owned the directory — a rerun, which is+ // meant to start from a clean tree. Reuse of a PRIOR task's directory never+ // reaches here; that is Reuse, which takes an explicit WorkDir and deletes+ // nothing.+ if !fresh {+ if err := resetEnvRootContents(envRoot); err != nil {+ return nil, fmt.Errorf("execenv: reset existing env: %w", err)}}@@ -1097,3 +1120,137 @@ func (env *Environment) Cleanup(removeAll bool) error {}return nil}++// envRootOwnerFile records which task an env root belongs to. Creating it with+// O_EXCL is the atomic step that decides which of two same-key tasks owns the+// directory, and it is the proof Prepare needs before wiping a directory that+// another task may still be executing in (#7326).+const envRootOwnerFile = ".task_owner"++// claimEnvRoot atomically establishes that taskID owns envRoot.+//+// fresh is true when this call created the claim and the directory is the+// caller's to populate; false when taskID already owned it, i.e. a rerun that+// may reset its own tree. Any other owner is an error, and so is a directory+// that holds content but names no owner — refusing to guess is the whole point+// of the marker.+//+// Atomicity comes from two filesystem primitives rather than a lock: os.Mkdir+// fails if the directory exists, and O_EXCL fails if the marker exists. Exactly+// one racing caller can win each, and a caller that wins neither never reaches+// the destructive path. The emptiness check below only decides whether a+// caller may ATTEMPT a claim; O_EXCL alone decides who gets it.+func claimEnvRoot(envRoot, taskID string) (fresh bool, err error) {+ if err := os.MkdirAll(filepath.Dir(envRoot), 0o755); err != nil {+ return false, fmt.Errorf("create workspace directory: %w", err)+ }++ switch err := os.Mkdir(envRoot, 0o755); {+ case err == nil:+ // We created the directory, so nothing of anyone's can be inside it.+ if err := writeEnvRootOwnerExclusive(envRoot, taskID); err != nil {+ return false, err+ }+ return true, nil+ case !errors.Is(err, os.ErrExist):+ return false, fmt.Errorf("create env root %s: %w", envRoot, err)+ }++ // The directory already existed. Who owns it?+ owner, err := readEnvRootOwner(envRoot)+ if err != nil {+ return false, fmt.Errorf("read env root owner for %s: %w", envRoot, err)+ }+ switch {+ case owner == taskID:+ return false, nil+ case owner != "":+ return false, fmt.Errorf("env root %s belongs to task %s; refusing to reset it for task %s", envRoot, owner, taskID)+ }++ // No owner. A directory holding work is never ours to take — the marker is+ // written before any content, so the only unowned directory that can be+ // safely claimed is an empty one (a crash between Mkdir and the marker+ // write). Anything else fails closed and waits for a human.+ empty, err := dirIsEmpty(envRoot)+ if err != nil {+ return false, fmt.Errorf("inspect env root %s: %w", envRoot, err)+ }+ if !empty {+ return false, fmt.Errorf("env root %s already holds files but names no owning task; refusing to delete it", envRoot)+ }+ if err := writeEnvRootOwnerExclusive(envRoot, taskID); err != nil {+ // Lost the race for an empty directory: whoever won owns it now.+ return false, err+ }+ return true, nil+}++// writeEnvRootOwnerExclusive creates the owner marker, failing if one already+// exists. This is the atomic arbiter between two racing claims.+func writeEnvRootOwnerExclusive(envRoot, taskID string) error {+ path := filepath.Join(envRoot, envRootOwnerFile)+ f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)+ if errors.Is(err, os.ErrExist) {+ owner, readErr := readEnvRootOwner(envRoot)+ if readErr != nil {+ return fmt.Errorf("read env root owner for %s: %w", envRoot, readErr)+ }+ if owner == taskID {+ return nil+ }+ return fmt.Errorf("env root %s was claimed by task %s while task %s was starting", envRoot, owner, taskID)+ }+ if err != nil {+ return fmt.Errorf("claim env root %s: %w", envRoot, err)+ }+ if _, err := f.WriteString(taskID); err != nil {+ f.Close()+ return fmt.Errorf("record env root owner for %s: %w", envRoot, err)+ }+ return f.Close()+}++// readEnvRootOwner returns the task id that owns envRoot, or "" when no marker+// is present. An unreadable marker is an error, not an empty owner: treating it+// as unowned would hand the caller a licence to delete the very directory it+// could not identify.+func readEnvRootOwner(envRoot string) (string, error) {+ b, err := os.ReadFile(filepath.Join(envRoot, envRootOwnerFile))+ if errors.Is(err, os.ErrNotExist) {+ return "", nil+ }+ if err != nil {+ return "", err+ }+ return strings.TrimSpace(string(b)), nil+}++// resetEnvRootContents empties an env root the caller already owns, keeping the+// directory and its owner marker. Removing and recreating the directory instead+// would drop the claim for as long as the recreate takes, which is exactly the+// window claimEnvRoot exists to close.+func resetEnvRootContents(envRoot string) error {+ entries, err := os.ReadDir(envRoot)+ if err != nil {+ return err+ }+ for _, e := range entries {+ if e.Name() == envRootOwnerFile {+ continue+ }+ if err := os.RemoveAll(filepath.Join(envRoot, e.Name())); err != nil {+ return err+ }+ }+ return nil+}++// dirIsEmpty reports whether dir has no entries at all.+func dirIsEmpty(dir string) (bool, error) {+ entries, err := os.ReadDir(dir)+ if err != nil {+ return false, err+ }+ return len(entries) == 0, nil+}diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.goindex faad1ef6b5..13d55351a8 100644--- a/server/internal/daemon/execenv/execenv_test.go+++ b/server/internal/daemon/execenv/execenv_test.go@@ -10,6 +10,7 @@ import ("path/filepath""runtime""strings"+ "sync""testing")@@ -41,7 +42,7 @@ func TestShortID(t *testing.T) {func TestPredictRootDir(t *testing.T) {t.Parallel()got := PredictRootDir("/root", "ws-uuid", "a1b2c3d4-e5f6-7890-abcd-ef1234567890")- want := filepath.Join("/root", "ws-uuid", "a1b2c3d4")+ want := filepath.Join("/root", "ws-uuid", "ef1234567890")if got != want {t.Errorf("PredictRootDir = %q, want %q", got, want)}@@ -6147,3 +6148,316 @@ func TestEnvironmentCleanupStandardModeRemovesWorkdir(t *testing.T) {t.Fatalf("output/ removed by partial cleanup: %v", err)}}++// TestPredictRootDirDistinctForSharedUUIDv7Prefix is the regression guard for+// #7326. Task ids are UUIDv7: the first 8 hex chars are the high 32 bits of a+// 48-bit millisecond timestamp, so they only advance once every 2^16 ms+// (~65.5s). Every task started inside one such window shares that prefix.+// While the env root used the prefix, the second task's Prepare deleted the+// first task's live directory — identity files, worktree and all.+//+// The three ids below are the ones from the bug report, ~4.7s apart.+func TestPredictRootDirDistinctForSharedUUIDv7Prefix(t *testing.T) {+ t.Parallel()+ ids := []string{+ "01a01ec0-e69d-7000-8000-000000000001",+ "01a01ec0-f014-7000-8000-000000000002",+ "01a01ec0-f927-7000-8000-000000000003",+ }+ seen := make(map[string]string, len(ids))+ for _, id := range ids {+ root := PredictRootDir("/root", "ws-uuid", id)+ if prev, dup := seen[root]; dup {+ t.Fatalf("tasks %s and %s share env root %q — a truncated task id is back", prev, id, root)+ }+ seen[root] = id+ }+}++// TestLocalWorktreeBranchDistinctForSharedUUIDv7Prefix covers the same+// truncation in the branch name: two concurrent tasks for one agent would+// otherwise both ask git for agent/<name>/<same-prefix>.+func TestLocalWorktreeBranchDistinctForSharedUUIDv7Prefix(t *testing.T) {+ t.Parallel()+ a := fmt.Sprintf("agent/%s/%s", sanitizeName("Reviewer"), taskKey("01a01ec0-e69d-7000-8000-000000000001"))+ b := fmt.Sprintf("agent/%s/%s", sanitizeName("Reviewer"), taskKey("01a01ec0-f014-7000-8000-000000000002"))+ if a == b {+ t.Fatalf("both tasks resolved to branch %q", a)+ }+}++// TestPrepareDoesNotDeleteConcurrentTaskEnv is the behavioural half of the+// #7326 regression. Prepare removes an existing env root before recreating it,+// which is correct only while that path belongs exclusively to the task being+// prepared. With an 8-char UUIDv7 prefix it did not: task B's Prepare ran+// os.RemoveAll over task A's *running* env root, destroying its identity+// files, worktree and task-scoped config while A was still executing.+func TestPrepareDoesNotDeleteConcurrentTaskEnv(t *testing.T) {+ t.Parallel()+ workspacesRoot := t.TempDir()++ // Same first 8 hex chars — i.e. created inside the same ~65.5s window.+ const (+ taskA = "01a01ec0-e69d-7000-8000-000000000001"+ taskB = "01a01ec0-f014-7000-8000-000000000002"+ )++ envA, err := Prepare(PrepareParams{+ WorkspacesRoot: workspacesRoot,+ WorkspaceID: "ws-collision",+ TaskID: taskA,+ AgentName: "Agent A",+ Task: TaskContextForEnv{IssueID: taskA},+ }, testLogger())+ if err != nil {+ t.Fatalf("Prepare task A: %v", err)+ }+ defer envA.Cleanup(true)++ // A marker standing in for everything a live task owns under its env root.+ marker := filepath.Join(envA.WorkDir, "task-a-work.txt")+ if err := os.WriteFile(marker, []byte("A"), 0o644); err != nil {+ t.Fatalf("seed task A work: %v", err)+ }++ envB, err := Prepare(PrepareParams{+ WorkspacesRoot: workspacesRoot,+ WorkspaceID: "ws-collision",+ TaskID: taskB,+ AgentName: "Agent B",+ Task: TaskContextForEnv{IssueID: taskB},+ }, testLogger())+ if err != nil {+ t.Fatalf("Prepare task B: %v", err)+ }+ defer envB.Cleanup(true)++ if envA.RootDir == envB.RootDir {+ t.Fatalf("both tasks share env root %q", envA.RootDir)+ }+ if _, err := os.Stat(marker); err != nil {+ t.Fatalf("task B's Prepare destroyed task A's live env root: %v", err)+ }+}++// TestTaskKeyReadsTheRandomTail pins the two properties the env-root and+// branch segments depend on, which pull in opposite directions.+//+// Length: the full 32-char id pushed a branch ref past Windows MAX_PATH+// ("cannot lock ref ...: Filename too long") because the ref is a path under+// .git/refs/heads/ inside an already-deep task checkout. Keep it bounded.+//+// End: the segment must come from the id's random tail. UUIDv7 puts a+// millisecond timestamp in front, so a leading slice is shared by every task+// created in the same ~65.5s window (#7326) — short AND leading is the one+// combination that reintroduces the bug.+func TestTaskKeyReadsTheRandomTail(t *testing.T) {+ t.Parallel()+ const id = "01a01ec0-e69d-7000-8000-0123456789ab"+ got := taskKey(id)+ if len(got) != taskKeyLen {+ t.Fatalf("taskKey(%q) = %q (len %d), want len %d — long segments overflow MAX_PATH on Windows", id, got, len(got), taskKeyLen)+ }+ if want := "0123456789ab"; got != want {+ t.Fatalf("taskKey(%q) = %q, want %q — the segment must come from the random tail, not the timestamp head", id, got, want)+ }+ if short := taskKey("abc"); short != "abc" {+ t.Fatalf("taskKey on a sub-length input = %q, want it returned as-is", short)+ }+}++// TestPrepareRefusesEnvRootOwnedByAnotherTask covers the guard that makes the+// os.RemoveAll in Prepare safe. taskKey makes a shared env root improbable but+// not impossible, and the cost of being wrong is deleting a running task's+// work — so a foreign owner must stop Prepare rather than be overwritten.+func TestPrepareRefusesEnvRootOwnedByAnotherTask(t *testing.T) {+ t.Parallel()+ workspacesRoot := t.TempDir()+ const taskID = "01a01ec0-e69d-7000-8000-0123456789ab"++ envRoot := PredictRootDir(workspacesRoot, "ws-owned", taskID)+ if err := os.MkdirAll(filepath.Join(envRoot, "workdir"), 0o755); err != nil {+ t.Fatalf("seed env root: %v", err)+ }+ if err := writeEnvRootOwnerExclusive(envRoot, "11111111-2222-3333-4444-555555555555"); err != nil {+ t.Fatalf("seed owner: %v", err)+ }+ survivor := filepath.Join(envRoot, "workdir", "other-task-work.txt")+ if err := os.WriteFile(survivor, []byte("keep me"), 0o644); err != nil {+ t.Fatalf("seed work: %v", err)+ }++ _, err := Prepare(PrepareParams{+ WorkspacesRoot: workspacesRoot,+ WorkspaceID: "ws-owned",+ TaskID: taskID,+ AgentName: "Intruder",+ Task: TaskContextForEnv{IssueID: taskID},+ }, testLogger())+ if err == nil {+ t.Fatal("Prepare accepted an env root owned by another task")+ }+ if !strings.Contains(err.Error(), "belongs to task") {+ t.Fatalf("error = %v, want it to name the owning task", err)+ }+ if _, statErr := os.Stat(survivor); statErr != nil {+ t.Fatalf("Prepare deleted the other task's work despite failing: %v", statErr)+ }+}++// TestPrepareResetsItsOwnEnvRoot is the other half: a rerun of the SAME task+// owns the path and must still get a clean directory.+func TestPrepareResetsItsOwnEnvRoot(t *testing.T) {+ t.Parallel()+ workspacesRoot := t.TempDir()+ const taskID = "01a01ec0-e69d-7000-8000-0123456789ab"++ first, err := Prepare(PrepareParams{+ WorkspacesRoot: workspacesRoot,+ WorkspaceID: "ws-rerun",+ TaskID: taskID,+ AgentName: "Rerun",+ Task: TaskContextForEnv{IssueID: taskID},+ }, testLogger())+ if err != nil {+ t.Fatalf("first Prepare: %v", err)+ }+ stale := filepath.Join(first.WorkDir, "stale.txt")+ if err := os.WriteFile(stale, []byte("from the previous run"), 0o644); err != nil {+ t.Fatalf("seed stale file: %v", err)+ }++ second, err := Prepare(PrepareParams{+ WorkspacesRoot: workspacesRoot,+ WorkspaceID: "ws-rerun",+ TaskID: taskID,+ AgentName: "Rerun",+ Task: TaskContextForEnv{IssueID: taskID},+ }, testLogger())+ if err != nil {+ t.Fatalf("rerun Prepare rejected the task's own env root: %v", err)+ }+ defer second.Cleanup(true)+ if _, statErr := os.Stat(stale); !os.IsNotExist(statErr) {+ t.Fatalf("rerun did not reset the env root; stale file still present (%v)", statErr)+ }+}++// TestPrepareConcurrentSameKeyTasksClaimExclusively is the race the previous+// ownership check missed. It read the marker, then deleted, then wrote — three+// steps, so two tasks sharing a taskKey could both observe "no owner", and the+// slower one would still os.RemoveAll the faster one's live directory.+//+// Both ids below end in the same 12 hex chars, so they resolve to one env root.+// Started together, exactly one must win: the other has to fail without+// touching the winner's tree.+func TestPrepareConcurrentSameKeyTasksClaimExclusively(t *testing.T) {+ t.Parallel()+ workspacesRoot := t.TempDir()+ ids := []string{+ "aaaaaaaa-1111-2222-3333-0123456789ab",+ "bbbbbbbb-4444-5555-6666-0123456789ab",+ }+ if taskKey(ids[0]) != taskKey(ids[1]) {+ t.Fatalf("fixture ids no longer collide: %q vs %q", taskKey(ids[0]), taskKey(ids[1]))+ }++ var start sync.WaitGroup+ start.Add(1)+ var done sync.WaitGroup+ envs := make([]*Environment, len(ids))+ errs := make([]error, len(ids))+ for i, id := range ids {+ done.Add(1)+ go func() {+ defer done.Done()+ start.Wait() // release both goroutines into Prepare together+ envs[i], errs[i] = Prepare(PrepareParams{+ WorkspacesRoot: workspacesRoot,+ WorkspaceID: "ws-race",+ TaskID: id,+ AgentName: "Racer",+ Task: TaskContextForEnv{IssueID: id},+ }, testLogger())+ }()+ }+ start.Done()+ done.Wait()++ winner := -1+ for i := range ids {+ if errs[i] == nil {+ if winner >= 0 {+ t.Fatalf("both tasks claimed the same env root: %s and %s", ids[winner], ids[i])+ }+ winner = i+ }+ }+ if winner < 0 {+ t.Fatalf("neither task started: %v / %v", errs[0], errs[1])+ }+ loser := 1 - winner+ if !strings.Contains(errs[loser].Error(), "env root") {+ t.Fatalf("loser failed for an unrelated reason: %v", errs[loser])+ }+ defer envs[winner].Cleanup(true)++ // The winner's environment must be intact and still its own.+ if _, err := os.Stat(envs[winner].WorkDir); err != nil {+ t.Fatalf("winner %s lost its workdir to the loser: %v", ids[winner], err)+ }+ owner, err := readEnvRootOwner(envs[winner].RootDir)+ if err != nil {+ t.Fatalf("read owner: %v", err)+ }+ if owner != ids[winner] {+ t.Fatalf("env root owner = %q, want the winning task %q", owner, ids[winner])+ }+}++// TestClaimEnvRootRefusesUnownedDirectoryWithContent covers the other way the+// marker can be missing: a directory that holds files but names no task. The+// marker is written before any content, so this is not a shape Prepare+// produces — and guessing that it is abandoned would mean deleting work whose+// owner we could not identify.+func TestClaimEnvRootRefusesUnownedDirectoryWithContent(t *testing.T) {+ t.Parallel()+ envRoot := filepath.Join(t.TempDir(), "ws", "0123456789ab")+ if err := os.MkdirAll(filepath.Join(envRoot, "workdir"), 0o755); err != nil {+ t.Fatalf("seed: %v", err)+ }+ if err := os.WriteFile(filepath.Join(envRoot, "workdir", "work.txt"), []byte("x"), 0o644); err != nil {+ t.Fatalf("seed: %v", err)+ }++ if _, err := claimEnvRoot(envRoot, "aaaaaaaa-1111-2222-3333-0123456789ab"); err == nil {+ t.Fatal("claimEnvRoot took a directory holding files with no owner")+ } else if !strings.Contains(err.Error(), "names no owning task") {+ t.Fatalf("error = %v, want it to explain the missing owner", err)+ }+ if _, err := os.Stat(filepath.Join(envRoot, "workdir", "work.txt")); err != nil {+ t.Fatalf("claimEnvRoot deleted the content it refused to claim: %v", err)+ }+}++// TestClaimEnvRootAdoptsEmptyDirectory is the self-heal counterpart: a crash+// between Mkdir and the marker write leaves an empty directory, which holds no+// work and must not wedge the task forever.+func TestClaimEnvRootAdoptsEmptyDirectory(t *testing.T) {+ t.Parallel()+ envRoot := filepath.Join(t.TempDir(), "ws", "0123456789ab")+ if err := os.MkdirAll(envRoot, 0o755); err != nil {+ t.Fatalf("seed: %v", err)+ }+ const id = "aaaaaaaa-1111-2222-3333-0123456789ab"+ fresh, err := claimEnvRoot(envRoot, id)+ if err != nil {+ t.Fatalf("claimEnvRoot on an empty directory: %v", err)+ }+ if !fresh {+ t.Fatal("adopting an empty directory should report a fresh claim")+ }+ if owner, _ := readEnvRootOwner(envRoot); owner != id {+ t.Fatalf("owner = %q, want %q", owner, id)+ }+}diff --git a/server/internal/daemon/execenv/git.go b/server/internal/daemon/execenv/git.goindex 456b497a92..227bb3de5f 100644--- a/server/internal/daemon/execenv/git.go+++ b/server/internal/daemon/execenv/git.go@@ -183,7 +183,40 @@ func repoNameFromURL(url string) string {return name}+// taskKeyLen is how many hex chars of the task id identify a task in a path or+// a branch name. Every char here is spent twice — the env root prefixes the+// agent's whole workdir, and the branch name becomes a path under+// .git/refs/heads/ inside that workdir — and Windows still enforces MAX_PATH+// (260). The full 32-char id overflows it on a deep checkout, so the segment+// stays short and buys its uniqueness from entropy instead of length.+const taskKeyLen = 12++// taskKey returns the segment identifying a task in a path or branch name: the+// LAST taskKeyLen hex chars of the id.+//+// Which end matters more than how many chars. Task ids are UUIDv7 — 48 bits of+// millisecond timestamp, then randomness. The leading 8 hex chars are the high+// 32 bits of that timestamp, so they only advance once every 2^16 ms (~65.5s):+// taking them from the front gave every task started inside one such window an+// identical segment, and therefore one shared env root. That is not a rare hash+// collision, it is the common case, and it made Prepare's "remove existing env"+// step delete a concurrently running task's directory (#7326).+//+// The tail is drawn from the id's random field, so 12 chars carry 48 random+// bits. Prepare additionally refuses to delete an env root another task owns,+// so even an improbable clash fails closed instead of destroying work.+//+// Use shortID for logs, never for identity.+func taskKey(uuid string) string {+ s := strings.ReplaceAll(uuid, "-", "")+ if len(s) > taskKeyLen {+ return s[len(s)-taskKeyLen:]+ }+ return s+}+// shortID returns the first 8 characters of a UUID string (dashes stripped).+// Display and logging only — see taskKey for anything that must be unique.func shortID(uuid string) string {s := strings.ReplaceAll(uuid, "-", "")if len(s) > 8 {diff --git a/server/internal/daemon/execenv/local_worktree.go b/server/internal/daemon/execenv/local_worktree.goindex 4e9049b497..7c42898658 100644--- a/server/internal/daemon/execenv/local_worktree.go+++ b/server/internal/daemon/execenv/local_worktree.go@@ -213,7 +213,7 @@ func PrepareLocalWorktree(params LocalWorktreeParams, logger *slog.Logger) (*Loc"so the worktree would not match what you have on disk: %w", gitRoot, stashErr)}- branch := fmt.Sprintf("agent/%s/%s", sanitizeName(params.AgentName), shortID(params.TaskID))+ branch := fmt.Sprintf("agent/%s/%s", sanitizeName(params.AgentName), taskKey(params.TaskID))actualBranch, err := addLocalWorktree(gitRoot, worktreePath, branch, headSHA)if err != nil {return nil, errdiff --git a/server/internal/daemon/execenv/local_worktree_test.go b/server/internal/daemon/execenv/local_worktree_test.goindex 30613f5572..c59830bb74 100644--- a/server/internal/daemon/execenv/local_worktree_test.go+++ b/server/internal/daemon/execenv/local_worktree_test.go@@ -621,8 +621,8 @@ func TestPrepareWorktreeModeUsesPerIssueCodexSessionStore(t *testing.T) {// Two turns on the same issue, different task IDs — the shape of a// follow-up comment.- first := prepareTurn("aaaa1111-2222-3333-4444-555566667777")- second := prepareTurn("bbbb1111-2222-3333-4444-555566667777")+ first := prepareTurn("aaaa1111-2222-3333-4444-5555666677aa")+ second := prepareTurn("bbbb1111-2222-3333-4444-5555666677bb")sessionsOf := func(env *Environment) string {t.Helper()@@ -640,7 +640,7 @@ func TestPrepareWorktreeModeUsesPerIssueCodexSessionStore(t *testing.T) {firstSessions, secondSessions)}// And it must be the stable per-issue store, not a task-local directory.- if strings.Contains(firstSessions, shortID("aaaa1111-2222-3333-4444-555566667777")) {+ if strings.Contains(firstSessions, taskKey("aaaa1111-2222-3333-4444-5555666677aa")) {t.Errorf("sessions dir is task-scoped (%s); it will not survive the next turn", firstSessions)}}diff --git a/server/internal/daemon/execenv/openclaw_config_test.go b/server/internal/daemon/execenv/openclaw_config_test.goindex 682a958a5e..55d6f21037 100644--- a/server/internal/daemon/execenv/openclaw_config_test.go+++ b/server/internal/daemon/execenv/openclaw_config_test.go@@ -1356,10 +1356,10 @@ func TestPrepareEnvironmentNonOpenclawSkipsConfig(t *testing.T) {stub := installOpenclawStub(t, map[string]openclawResponse{})taskIDs := map[string]string{- "claude": "aaaaaaaa-1111-2222-3333-444444444444",- "opencode": "bbbbbbbb-1111-2222-3333-444444444444",- "hermes": "cccccccc-1111-2222-3333-444444444444",- "kiro": "dddddddd-1111-2222-3333-444444444444",+ "claude": "aaaaaaaa-1111-2222-3333-4444444444aa",+ "opencode": "bbbbbbbb-1111-2222-3333-4444444444bb",+ "hermes": "cccccccc-1111-2222-3333-4444444444cc",+ "kiro": "dddddddd-1111-2222-3333-4444444444dd",}for provider, taskID := range taskIDs {t.Run(provider, func(t *testing.T) {diff --git a/server/internal/daemon/repocache/cache.go b/server/internal/daemon/repocache/cache.goindex 5b0c8b852b..66ff323cd7 100644--- a/server/internal/daemon/repocache/cache.go+++ b/server/internal/daemon/repocache/cache.go@@ -829,8 +829,8 @@ func (c *Cache) CreateWorktreeContext(ctx context.Context, params WorktreeParamsreturn 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))+ // Build branch name: agent/{sanitized-name}/{task-id}+ branchName := fmt.Sprintf("agent/%s/%s", sanitizeName(params.AgentName), taskKey(params.TaskID))// Derive directory name from repo URL.dirName := repoNameFromURL(params.RepoURL)@@ -1782,7 +1782,26 @@ func sanitizeName(name string) string {return s}+// taskKeyLen mirrors execenv.taskKeyLen — see that constant for why the+// segment is short: a branch name becomes a path under .git/refs/heads/ inside+// the task checkout, and Windows enforces MAX_PATH there.+const taskKeyLen = 12++// taskKey returns the git-safe branch segment identifying a task: the LAST+// taskKeyLen hex chars of the id. Mirrors execenv.taskKey — a UUIDv7's LEADING+// 8 hex chars are timestamp bits that only advance every ~65.5s, so taking the+// front gave two concurrently created tasks the same branch name (#7326). The+// tail is random.+func taskKey(uuid string) string {+ s := strings.ReplaceAll(uuid, "-", "")+ if len(s) > taskKeyLen {+ return s[len(s)-taskKeyLen:]+ }+ return s+}+// shortID returns the first 8 characters of a UUID string (dashes stripped).+// Display and logging only — see taskKey for anything that must be unique.func shortID(uuid string) string {s := strings.ReplaceAll(uuid, "-", "")if len(s) > 8 {diff --git a/server/internal/daemon/repocache/cache_test.go b/server/internal/daemon/repocache/cache_test.goindex 478985f878..5ad84af709 100644--- a/server/internal/daemon/repocache/cache_test.go+++ b/server/internal/daemon/repocache/cache_test.go@@ -3,6 +3,7 @@ package repocacheimport ("context""errors"+ "fmt""io/fs""log/slog""os"@@ -2156,3 +2157,40 @@ func TestBarePathIsIndependentOfExistence(t *testing.T) {t.Error("Lookup must still report an uncached repo as absent")}}++// TestTaskKeyMatchesExecenvContract pins this package's copy of the task-segment+// rule. execenv, repocache and the agent handler each carry one — execenv owns+// the canonical taskKey, and the handler has a contract test against+// PredictRootDir, but this copy had none and could drift silently.+//+// Both properties matter. The segment must come from the id's random TAIL:+// UUIDv7 leads with a millisecond timestamp, so a leading slice is identical+// for every task created in the same ~65.5s window, which gave two concurrent+// tasks of one agent the same branch name (#7326). And it must stay SHORT: a+// branch name becomes a path under .git/refs/heads/ inside the task checkout,+// where Windows enforces MAX_PATH.+func TestTaskKeyMatchesExecenvContract(t *testing.T) {+ t.Parallel()+ const id = "01a01ec0-e69d-7000-8000-0123456789ab"+ if got, want := taskKey(id), "0123456789ab"; got != want {+ t.Fatalf("taskKey(%q) = %q, want %q — the segment must be the random tail, not the timestamp head", id, got, want)+ }+ if got := taskKey(id); len(got) != taskKeyLen {+ t.Fatalf("taskKey len = %d, want %d — long segments overflow MAX_PATH on Windows", len(got), taskKeyLen)+ }+ if got := taskKey("abc"); got != "abc" {+ t.Fatalf("taskKey on a sub-length input = %q, want it returned as-is", got)+ }+}++// TestBranchNameDistinctForSharedUUIDv7Prefix is the branch-name half of the+// #7326 regression: two tasks created inside one timestamp window must not ask+// git for the same ref.+func TestBranchNameDistinctForSharedUUIDv7Prefix(t *testing.T) {+ t.Parallel()+ a := fmt.Sprintf("agent/%s/%s", sanitizeName("Windows Codex"), taskKey("01a01ec0-e69d-7000-8000-000000000001"))+ b := fmt.Sprintf("agent/%s/%s", sanitizeName("Windows Codex"), taskKey("01a01ec0-f014-7000-8000-000000000002"))+ if a == b {+ t.Fatalf("both tasks resolved to branch %q", a)+ }+}diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 5aacee3734..fe95754a29 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -775,8 +775,8 @@ func taskToResponse(t db.AgentTaskQueue, workspaceID string) AgentTaskResponse {//// Returns empty when work_dir is empty, or when stripping leaves nothing// (i.e. work_dir was exactly the user's home — rendering nothing is-// preferable to a chip that says `<name>`). shortTaskID() must stay in-// lock-step with server/internal/daemon/execenv/git.go:shortID — both+// preferable to a chip that says `<name>`). taskDirSegment() must stay in+// lock-step with server/internal/daemon/execenv/git.go:taskKey — both// consume the same task UUID; if that helper changes, this one must too// or the envRoot match silently degrades to the local_directory fallback.func relativeWorkDir(workDir, workspaceID, taskID string) string {@@ -788,7 +788,7 @@ func relativeWorkDir(workDir, workspaceID, taskID string) string {normalized := strings.ReplaceAll(workDir, "\\", "/")if workspaceID != "" && taskID != "" {- envRootSuffix := workspaceID + "/" + shortTaskID(taskID)+ envRootSuffix := workspaceID + "/" + taskDirSegment(taskID)if idx := strings.Index(normalized, envRootSuffix); idx >= 0 {return normalized[idx:]}@@ -801,14 +801,21 @@ func relativeWorkDir(workDir, workspaceID, taskID string) string {return basename(normalized)}-// shortTaskID mirrors execenv.shortID — first 8 hex chars of the UUID-// with dashes stripped. Kept inline here so the agent handler has zero-// imports from the daemon package (which would create an unwanted cycle-// between handler and daemon).-func shortTaskID(uuid string) string {+// taskDirSegmentLen and taskDirSegment mirror execenv.taskKeyLen /+// execenv.taskKey — the LAST 12 hex chars of the task id. Kept inline here so+// the agent handler has zero imports from the daemon package (which would+// create an unwanted cycle between handler and daemon).+//+// It must keep taking the TAIL. A UUIDv7's leading hex chars are timestamp+// bits shared by every task created within ~65.5s (#7326); the daemon stopped+// reading from that end, and this reconstruction only matches while both sides+// agree.+const taskDirSegmentLen = 12++func taskDirSegment(uuid string) string {s := strings.ReplaceAll(uuid, "-", "")- if len(s) > 8 {- return s[:8]+ if len(s) > taskDirSegmentLen {+ return s[len(s)-taskDirSegmentLen:]}return s}diff --git a/server/internal/handler/agent_work_dir_test.go b/server/internal/handler/agent_work_dir_test.goindex a5810750a9..3775ed3aab 100644--- a/server/internal/handler/agent_work_dir_test.go+++ b/server/internal/handler/agent_work_dir_test.go@@ -25,6 +25,10 @@ func TestRelativeWorkDir(t *testing.T) {const (wsID = "a05b0e10-ee7a-4603-a72d-a548b2390cb2"taskID = "5c57b65b-ee7a-4603-a72d-a548b2390cb2"+ // The env-root segment is the TAIL of the task id, not a leading+ // prefix: UUIDv7 puts a timestamp in front, so a leading slice is+ // shared by every task created in the same ~65.5s window (#7326).+ taskSeg = "a548b2390cb2")tests := []struct {@@ -43,17 +47,17 @@ func TestRelativeWorkDir(t *testing.T) {},{name: "standard envRoot path strips workspaces root",- workDir: "/Users/alice/multica_workspaces/" + wsID + "/5c57b65b/workdir",+ workDir: "/Users/alice/multica_workspaces/" + wsID + "/" + taskSeg + "/workdir",wsID: wsID,taskID: taskID,- expected: wsID + "/5c57b65b/workdir",+ expected: wsID + "/" + taskSeg + "/workdir",},{name: "standard envRoot path without trailing workdir",- workDir: "/Users/alice/multica_workspaces/" + wsID + "/5c57b65b",+ workDir: "/Users/alice/multica_workspaces/" + wsID + "/" + taskSeg,wsID: wsID,taskID: taskID,- expected: wsID + "/5c57b65b",+ expected: wsID + "/" + taskSeg,},{name: "local_directory path under /Users home is stripped",@@ -134,31 +138,31 @@ func TestRelativeWorkDir(t *testing.T) {},{name: "Windows backslash separators are normalized",- workDir: `C:\Users\alice\multica_workspaces\` + wsID + `\5c57b65b\workdir`,+ workDir: `C:\Users\alice\multica_workspaces\` + wsID + `\` + taskSeg + `\workdir`,wsID: wsID,taskID: taskID,- expected: wsID + "/5c57b65b/workdir",+ expected: wsID + "/" + taskSeg + "/workdir",},{name: "missing workspace_id under home strips home prefix instead of envRoot",- workDir: "/Users/alice/multica_workspaces/" + wsID + "/5c57b65b/workdir",+ workDir: "/Users/alice/multica_workspaces/" + wsID + "/" + taskSeg + "/workdir",wsID: "",taskID: taskID,- expected: "multica_workspaces/" + wsID + "/5c57b65b/workdir",+ expected: "multica_workspaces/" + wsID + "/" + taskSeg + "/workdir",},{name: "missing task_id under home strips home prefix instead of envRoot",- workDir: "/Users/alice/multica_workspaces/" + wsID + "/5c57b65b/workdir",+ workDir: "/Users/alice/multica_workspaces/" + wsID + "/" + taskSeg + "/workdir",wsID: wsID,taskID: "",- expected: "multica_workspaces/" + wsID + "/5c57b65b/workdir",+ expected: "multica_workspaces/" + wsID + "/" + taskSeg + "/workdir",},{name: "trailing slash on envRoot path is preserved in returned suffix",- workDir: "/Users/alice/multica_workspaces/" + wsID + "/5c57b65b/workdir/",+ workDir: "/Users/alice/multica_workspaces/" + wsID + "/" + taskSeg + "/workdir/",wsID: wsID,taskID: taskID,- expected: wsID + "/5c57b65b/workdir/",+ expected: wsID + "/" + taskSeg + "/workdir/",},{name: "wsID prefix appearing elsewhere falls back to basename when not under home",@@ -203,22 +207,22 @@ func TestTaskToResponseDerivesPrivateDurableWorkDir(t *testing.T) {}}-// TestShortTaskIDMatchesDaemon pins shortTaskID() to execenv.PredictRootDir's-// path layout. Both helpers consume the same task UUID; if the daemon's-// shortID logic drifts, this test trips loudly instead of letting the UI-// silently fall back to the "tail two segments" branch. Without this guard,-// a daemon-side change to, say, a 12-char prefix would not break a build —-// it would just quietly degrade every standard-task work_dir chip into the-// local_directory fallback.-func TestShortTaskIDMatchesDaemon(t *testing.T) {+// TestTaskDirSegmentMatchesDaemon pins taskDirSegment() to+// execenv.PredictRootDir's path layout. Both helpers consume the same task+// UUID; if the daemon's taskKey logic drifts, this test trips loudly instead+// of letting the UI silently fall back to the "tail two segments" branch.+// Without this guard, a daemon-side change back to a truncated prefix would+// not break a build — it would just quietly degrade every standard-task+// work_dir chip into the local_directory fallback.+func TestTaskDirSegmentMatchesDaemon(t *testing.T) {const (workspacesRoot = "/tmp/workspaces"workspaceID = "a05b0e10-ee7a-4603-a72d-a548b2390cb2"taskID = "5c57b65b-ee7a-4603-a72d-a548b2390cb2")daemonRoot := execenv.PredictRootDir(workspacesRoot, workspaceID, taskID)- expected := workspacesRoot + "/" + workspaceID + "/" + shortTaskID(taskID)+ expected := workspacesRoot + "/" + workspaceID + "/" + taskDirSegment(taskID)if daemonRoot != expected {- t.Fatalf("daemon PredictRootDir = %q, handler-side reconstruction = %q — shortTaskID is out of sync with execenv.shortID", daemonRoot, expected)+ t.Fatalf("daemon PredictRootDir = %q, handler-side reconstruction = %q — taskDirSegment is out of sync with execenv.taskKey", daemonRoot, expected)}}