# Files changed · PR \#17197 · pingdotgg/t3code

[View on GitCafe](https://git.cafe/pingdotgg/t3code/pull/17197/diffs)

Repository: [pingdotgg/t3code](https://git.cafe/pingdotgg/t3code)

Visibility: public

[fix\(server\): bulk worktree launches no longer fail on Git races](https://git.cafe/pingdotgg/t3code/pull/17197.md)

Version: 19

Head commit: 8ad9910844fe3a0117e6cac1787e71509d91dfda

Base commit: e5ea25d1292e5342db8508bf48ded67b88b82b82

Comparison base: 59a3f52ad332bc93f3fe20e3c634da474d203cab

Showing up to 20 entries from this revision. If the pull request changes, reopen the first page before continuing.

## apps/server/src/orchestration-v2/ThreadLaunchService.test.ts

Status: modified; +280; −0

```diff
@@ -34,6 +34,7 @@
 import * as Exit from "effect/Exit";
 import * as Layer from "effect/Layer";
 import * as Option from "effect/Option";
+import * as Path from "effect/Path";
 import * as Ref from "effect/Ref";
 import * as Result from "effect/Result";
 import * as Stream from "effect/Stream";
@@ -1018,6 +1019,238 @@
   }).pipe(Effect.provide(harness.layer));
 });
 
+it.effect.each([false, true])(
+  "bulk launches preserve occupied work while creating independent worktrees (startFromOrigin: %s)",
+  (startFromOrigin) =>
+    Effect.gen(function* () {
+      const driver = yield* GitVcsDriver.GitVcsDriver;
+      const fs = yield* FileSystem.FileSystem;
+      const path = yield* Path.Path;
+      const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "launch-worktree-collisions-" });
+      const worktreesDirectory = yield* fs.makeTempDirectoryScoped({ prefix: "launch-worktrees-" });
+      const git = (args: ReadonlyArray<string>) =>
+        driver.execute({ operation: "ThreadLaunchService.test", cwd, args });
+      yield* git(["init", "--initial-branch=main"]);
+      yield* git([
+        "-c",
+        "user.name=Test",
+        "-c",
+        "user.email=test@example.com",
+        "commit",
+        "--allow-empty",
+        "-m",
+        "initial",
+      ]);
+      const localHead = (yield* git(["rev-parse", "HEAD"])).stdout.trim();
+      let remoteHead = localHead;
+      if (startFromOrigin) {
+        const remote = yield* fs.makeTempDirectoryScoped({ prefix: "launch-bulk-remote-" });
+        yield* git(["init", "--bare", remote]);
+        yield* git(["remote", "add", "origin", remote]);
+        yield* git(["push", "-u", "origin", "main"]);
+        yield* git([
+          "-c",
+          "user.name=Test",
+          "-c",
+          "user.email=test@example.com",
+          "commit",
+          "--allow-empty",
+          "-m",
+          "remote advance",
+        ]);
+        remoteHead = (yield* git(["rev-parse", "HEAD"])).stdout.trim();
+        yield* git(["push", "origin", "main"]);
+        yield* git(["reset", "--hard", localHead]);
+        yield* git(["update-ref", "-d", "refs/remotes/origin/main"]);
+      }
+      yield* git(["config", "branch.autoSetupMerge", "always"]);
+      const existingPath = path.join(worktreesDirectory, "existing");
+      yield* driver.createWorktree({
+        cwd,
+        refName: "main",
+        newRefName: "feature/shared",
+        path: existingPath,
+      });
+      yield* fs.writeFileString(path.join(existingPath, "keep.txt"), "existing uncommitted work");
+      const occupiedPath = path.join(worktreesDirectory, path.basename(cwd), "feature-shared-1");
+      yield* fs.makeDirectory(occupiedPath, { recursive: true });
+      yield* fs.writeFileString(path.join(occupiedPath, "keep.txt"), "unrelated directory");
+      const harness = makeHarness({
+        git: {
+          resolveWorktreeBaseRemote: (input) => driver.resolveWorktreeBaseRemote({ ...input, cwd }),
+        },
+        fetchWorktreeBaseCommit: (input) => driver.fetchWorktreeBaseCommit({ ...input, cwd }),
+        createWorktree: (input, options) =>
+          driver.createWorktree({ ...input, cwd }, { ...options, worktreesDirectory }),
+      });
+      yield* Effect.gen(function* () {
+        const launches = yield* ThreadLaunch.ThreadLaunchService;
+        const threads = yield* ThreadManagement.ThreadManagementService;
+        const launched = yield* Effect.all(
+          Array.from({ length: 6 }, (_, index) => {
+            const command = `command:launch:bulk-${index}`;
+            return launches
+              .launch(
+                launchInput({
+                  command,
+                  thread: `thread:launch:bulk-${index}`,
+                  message: "Independent work",
+                  workspace: {
+                    type: "worktree",
+                    baseRef: "main",
+                    branch: "feature/shared",
+                    startFromOrigin,
+                  },
+                }),
+              )
+              .pipe(
+                Effect.flatMap((result) =>
+                  threads.streamStoredEventsFrom({ threadId: result.threadId }).pipe(
+                    Stream.filter(
+                      (stored) =>
+                        (stored.commandId === CommandId.make(`${command}:release`) ||
+                          stored.commandId === CommandId.make(`${command}:fail`)) &&
+                        stored.event.type === "run.updated",
+                    ),
+                    Stream.runHead,
+                    Effect.andThen(threads.getThreadProjection(result.threadId)),
+                  ),
+                ),
+              );
+          }),
+          { concurrency: "unbounded" },
+        );
+        assert.equal(new Set(launched.map((projection) => projection.thread.branch)).size, 6);
+        assert.equal(new Set(launched.map((projection) => projection.thread.worktreePath)).size, 6);
+        for (const projection of launched) {
+          assert.equal(
+            projection.runs[0]?.status,
+            "starting",
+            projection.turnItems.find((item) => item.type === "error")?.failure.message,
+          );
+          assert.isTrue(yield* fs.exists(projection.thread.worktreePath!));
+          const base = yield* git(["config", `branch.${projection.thread.branch}.t3-merge-base`]);
+          assert.equal(base.stdout.trim(), "main");
+          const head = yield* driver.execute({
+            operation: "ThreadLaunchService.test",
+            cwd: projection.thread.worktreePath!,
+            args: ["rev-parse", "HEAD"],
+          });
+          assert.equal(head.stdout.trim(), remoteHead);
+          if (startFromOrigin) {
+            const comparison = yield* git([
+              "config",
+              `branch.${projection.thread.branch}.t3-merge-base-ref`,
+            ]);
+            assert.equal(comparison.stdout.trim(), "refs/remotes/origin/main");
+          } else {
+            const upstream = yield* git([
+              "rev-parse",
+              "--abbrev-ref",
+              `${projection.thread.branch}@{upstream}`,
+            ]);
+            assert.equal(upstream.stdout.trim(), "main");
+          }
+        }
+        assert.deepEqual(
+          launched.map((projection) => projection.thread.branch).toSorted(),
+          Array.from({ length: 6 }, (_, index) => `feature/shared-${index + 2}`).toSorted(),
+        );
+        assert.equal(
+          yield* fs.readFileString(path.join(existingPath, "keep.txt")),
+          "existing uncommitted work",
+        );
+        assert.equal(
+          yield* fs.readFileString(path.join(occupiedPath, "keep.txt")),
+          "unrelated directory",
+        );
+        assert.equal(harness.removeWorktree.mock.calls.length, 0);
+        assert.equal((yield* git(["rev-parse", "main"])).stdout.trim(), localHead);
+      }).pipe(Effect.provide(harness.layer));
+    }).pipe(
+      Effect.provide(
+        GitVcsDriver.layer.pipe(
+          Layer.provide(
+            ServerConfig.layerTest(process.cwd(), { prefix: "launch-collision-test-" }),
+          ),
+          Layer.provideMerge(NodeServices.layer),
+        ),
+      ),
+    ),
+);
+
+it.effect("bounds collision retries and recovers the same failed run on Retry", () => {
+  let fails = true;
+  let attempts = 0;
+  const harness = makeHarness({
+    createWorktree: (input) => {
+      if (++attempts > 103) return Effect.die("worktree collision retries did not stop");
+      return fails || input.newRefName === "my-feature"
+        ? Effect.fail(
+            new GitCommandError({
+              operation: "GitVcsDriver.createWorktree",
+              command: "git",
+              cwd: project.workspaceRoot,
+              detail: "git worktree add failed",
+              reason: "branch_already_exists",
+              exitCode: 128,
+            }),
+          )
+        : Effect.succeed({
+            worktree: { path: "/repo-worktrees/recovered", refName: input.newRefName! },
+          });
+    },
+  });
+  return Effect.gen(function* () {
+    const launches = yield* ThreadLaunch.ThreadLaunchService;
+    const threads = yield* ThreadManagement.ThreadManagementService;
+    const launched = yield* launches.launch(
+      launchInput({
+        command: "command:launch:taken-retry",
+        thread: "thread:launch:taken-retry",
+        message: "Retry me",
+        workspace: { type: "worktree", baseRef: "main", branch: "my-feature" },
+      }),
+    );
+    yield* threads.streamStoredEventsFrom({ threadId: launched.threadId }).pipe(
+      Stream.filter(
+        (stored) =>
+          stored.commandId === CommandId.make("command:launch:taken-retry:fail") &&
+          stored.event.type === "run.updated",
+      ),
+      Stream.runHead,
+    );
+    const failed = yield* threads.getThreadProjection(launched.threadId);
+    assert.equal(failed.runs[0]?.status, "failed");
+    assert.isAbove(attempts, 1);
+    assert.isAtMost(attempts, 101);
+    assert.equal(harness.runSetup.mock.calls.length, 0);
+    assert.equal(harness.removeWorktree.mock.calls.length, 0);
+    fails = false;
+    yield* launches.retryPreparation({
+      commandId: CommandId.make("command:launch:taken-retry:retry"),
+      threadId: launched.threadId,
+      runId: failed.runs[0]!.id,
+    });
+    yield* threads.streamStoredEventsFrom({ threadId: launched.threadId }).pipe(
+      Stream.filter(
+        (stored) =>
+          stored.commandId === CommandId.make("command:launch:taken-retry:retry:release") &&
+          stored.event.type === "run.updated",
+      ),
+      Stream.runHead,
+    );
+    const recovered = yield* threads.getThreadProjection(launched.threadId);
+    assert.equal(recovered.runs.length, 1);
+    assert.equal(recovered.runs[0]!.id, failed.runs[0]!.id);
+    assert.equal(recovered.messages.length, 1);
+    assert.equal(recovered.runs[0]?.status, "starting");
+    assert.equal(recovered.thread.branch, "my-feature-1");
+    assert.equal(recovered.thread.worktreePath, "/repo-worktrees/recovered");
+    assert.equal(recovered.turnItems.find((item) => item.type === "error")?.status, "cancelled");
+  }).pipe(Effect.provide(harness.layer));
+});
+
 it.effect.each(["stable", "upstream/release"])(
   "launches from %s with the fetched commit and remote PR base",
   (baseRef) =>
@@ -1336,6 +1569,53 @@
   },
 );
 
+it.effect("removes a worktree that failed before the thread recorded it without retrying", () => {
+  const harness = makeHarness({
+    createWorktree: (_input, options) =>
+      (options?.progress?.onWorktreeClaimed?.("/repo-worktrees/partial") ?? Effect.void).pipe(
+        Effect.andThen(
+          Effect.fail(
+            new GitCommandError({
+              operation: "GitVcsDriver.createWorktree.configureBaseRef",
+              command: "git",
+              cwd: project.workspaceRoot,
+              detail: "checkout failed",
+              reason: "branch_already_exists",
+            }),
+          ),
+        ),
+      ),
+  });
+  return Effect.gen(function* () {
+    const launches = yield* ThreadLaunch.ThreadLaunchService;
+    const threads = yield* ThreadManagement.ThreadManagementService;
+    const launched = yield* launches.launch(
+      launchInput({
+        command: "command:launch:partial-worktree",
+        thread: "thread:launch:partial-worktree",
+        message: "Partial checkout",
+        workspace: { type: "worktree", baseRef: "main" },
+      }),
+    );
+    yield* threads.streamStoredEventsFrom({ threadId: launched.threadId }).pipe(
+      Stream.filter(
+        (stored) =>
+          stored.commandId === CommandId.make("command:launch:partial-worktree:fail") &&
+          stored.event.type === "run.updated",
+      ),
+      Stream.runHead,
+    );
+    const projection = yield* threads.getThreadProjection(launched.threadId);
+    assert.equal(projection.runs[0]?.status, "failed");
+    assert.equal(projection.thread.worktreePath, null);
+    assert.equal(harness.createWorktree.mock.calls.length, 1);
+    assert.deepEqual(
+      harness.removeWorktree.mock.calls.map(([input]) => input.path),
+      ["/repo-worktrees/partial"],
+    );
+  }).pipe(Effect.provide(harness.layer));
+});
+
 it.effect("replays a server-allocated launch", () =>
   Effect.gen(function* () {
     const setupEntered = yield* Deferred.make<void>();
```

## apps/server/src/orchestration-v2/ThreadLaunchService.ts

Status: modified; +35; −5

```diff
@@ -423,12 +423,12 @@
           branch = flattenTemporaryWorktreeBranchName(branch);
         }
         yield* setupTracker.stageStatus(threadId, "checkout", "running");
+        const createWorktree = (newRefName: string) =>
+          git.createWorktree(
-        const worktree = yield* git
-          .createWorktree(
             {
               cwd: project.workspaceRoot,
               refName: startRef,
-              newRefName: branch!,
+              newRefName,
               baseRefName,
               path: null,
             },
@@ -442,8 +442,38 @@
                   setupTracker.stage(threadId, "checkout", { percent: progress.percent }),
               },
             },
+          );
+        const desiredBranch = branch!;
-          )
-          .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
+        // Git claims the branch atomically. A preflight check alone would race
+        // with other launches, and retries must also escape leftover branches
+        // and directories from earlier attempts without touching those checkouts.
+        // Taken names get the same `-1`, `-2` suffixes renames use.
+        const worktree = yield* Effect.gen(function* () {
+          let candidate = desiredBranch;
+          for (let attempt = 1; ; attempt += 1) {
+            const result = yield* createWorktree(candidate).pipe(
+              Effect.catchTags({
+                GitCommandError: (error) =>
+                  attempt <= 100 &&
+                  createdWorktreePath === null &&
+                  (error.reason === "branch_already_exists" ||
+                    error.reason === "path_already_exists")
+                    ? Effect.succeed(null)
+                    : Effect.fail(error),
+              }),
+            );
+            if (result !== null) return result;
+            if (isTemporaryWorktreeBranch(desiredBranch)) {
+              const uuid = yield* randomUuidV4;
+              candidate = buildTemporaryWorktreeBranchName(() => uuid.replaceAll("-", ""));
+              if (!desiredBranch.includes("/")) {
+                candidate = flattenTemporaryWorktreeBranchName(candidate);
+              }
+            } else {
+              candidate = `${desiredBranch}-${attempt}`;
+            }
+          }
+        }).pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
         worktreePath = worktree.worktree.path;
         branch = worktree.worktree.refName;
         createdWorktreePath = worktreePath;
```

## apps/server/src/vcs/GitVcsDriverCore.test.ts

Status: modified; +207; −54

```diff
@@ -704,6 +704,30 @@
         paths.map((listed) => NodeFS.realpathSync.native(listed)),
         worktreePath,
       );
+      yield* writeTextFile(
+        cwd,
+        ".git/hooks/post-checkout",
+        "#!/bin/sh\ngit branch feature/old-git\n",
+      );
+      const fileSystem = yield* FileSystem.FileSystem;
+      yield* fileSystem.chmod(cwd + "/.git/hooks/post-checkout", 0o755);
+      const failedPath = cwd + "/failed-hook";
+      const claimed: string[] = [];
+      const failed = yield* driver
+        .createWorktree(
+          { cwd, path: failedPath, refName: "HEAD", newRefName: "feature/old-git-hook" },
+          {
+            progress: {
+              onWorktreeClaimed: (path) =>
+                Effect.sync(() => {
+                  claimed.push(path);
+                }),
+            },
+          },
+        )
+        .pipe(Effect.result);
+      assert.isTrue(Result.isFailure(failed));
+      assert.deepEqual(claimed, [failedPath]);
     }),
   ).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))),
 );
@@ -1071,7 +1095,9 @@
           const spawner = ChildProcessSpawner.make((command) => {
             if (
               ChildProcess.isStandardCommand(command) &&
-              (command.args.includes("worktree") || command.args[0] === "checkout")
+              (command.args.includes("worktree") ||
+                command.args[0] === "branch" ||
+                command.args[0] === "checkout")
             ) {
               locales.push(command.options.env?.LC_ALL);
             }
@@ -2938,6 +2964,37 @@
       }),
     );
 
+    it.effect("gives concurrent renames to one name distinct suffixes and keeps their config", () =>
+      Effect.gen(function* () {
+        const cwd = yield* makeTmpDir();
+        yield* initRepoWithCommit(cwd);
+        const driver = yield* GitVcsDriver.GitVcsDriver;
+        const sources = Array.from({ length: 6 }, (_, index) => `t3/source-${index}`);
+        for (const source of sources) {
+          yield* driver.createRef({ cwd, refName: source });
+          yield* git(cwd, ["config", `branch.${source}.gh-merge-base`, "main"]);
+        }
+
+        const renamed = yield* Effect.forEach(
+          sources,
+          (oldBranch) => driver.renameBranch({ cwd, oldBranch, newBranch: "feature/shared" }),
+          { concurrency: "unbounded" },
+        );
+
+        assert.deepEqual(renamed.map((result) => result.branch).toSorted(), [
+          "feature/shared",
+          "feature/shared-1",
+          "feature/shared-2",
+          "feature/shared-3",
+          "feature/shared-4",
+          "feature/shared-5",
+        ]);
+        for (const { branch } of renamed) {
+          assert.equal(yield* git(cwd, ["config", `branch.${branch}.gh-merge-base`]), "main");
+        }
+      }),
+    );
+
     it.effect("rejects a missing branch without restoring a matching dirty file", () =>
       Effect.gen(function* () {
         const cwd = yield* makeTmpDir();
@@ -3031,63 +3088,90 @@
   });
 
   describe("worktree operations", () => {
+    it.effect.each([false, true])(
+      "reports checkout ownership when a post-checkout hook fails: %s",
+      (failHook) =>
+        Effect.gen(function* () {
+          const cwd = yield* makeTmpDir();
+          const { initialBranch } = yield* initRepoWithCommit(cwd);
+          const fs = yield* FileSystem.FileSystem;
+          const path = yield* Path.Path;
+          const driver = yield* GitVcsDriver.GitVcsDriver;
+          yield* git(cwd, ["config", "filter.test.smudge", "sed s/original/filtered/g"]);
+          yield* writeTextFile(cwd, ".gitattributes", "asset.txt filter=test\n");
+          yield* writeTextFile(cwd, "asset.txt", "original\n");
+          yield* git(cwd, ["add", "."]);
+          yield* git(cwd, ["commit", "-m", "filtered asset"]);
+          yield* writeTextFile(
+            cwd,
+            ".git/hooks/post-checkout",
+            `#!/bin/sh
+git config checkout.workers > checkout-workers
+${failHook ? `git branch ${initialBranch}` : "exit 0"}
+`,
+          );
+          yield* fs.chmod(path.join(cwd, ".git/hooks/post-checkout"), 0o755);
+          const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "parallel");
-    it.effect("uses parallel checkout without skipping filters or hooks", () =>
-      Effect.gen(function* () {
-        const cwd = yield* makeTmpDir();
-        const { initialBranch } = yield* initRepoWithCommit(cwd);
-        const fs = yield* FileSystem.FileSystem;
-        const path = yield* Path.Path;
-        const driver = yield* GitVcsDriver.GitVcsDriver;
-        yield* git(cwd, ["config", "filter.test.smudge", "sed s/original/filtered/g"]);
-        yield* writeTextFile(cwd, ".gitattributes", "asset.txt filter=test\n");
-        yield* writeTextFile(cwd, "asset.txt", "original\n");
-        yield* git(cwd, ["add", "."]);
-        yield* git(cwd, ["commit", "-m", "filtered asset"]);
-        yield* writeTextFile(
-          cwd,
-          ".git/hooks/post-checkout",
-          "#!/bin/sh\ngit config checkout.workers > checkout-workers\nexit 0\n",
-        );
-        yield* fs.chmod(path.join(cwd, ".git/hooks/post-checkout"), 0o755);
-        const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "parallel");
 
-        yield* driver.createWorktree({
-          cwd,
-          path: worktreePath,
-          refName: initialBranch,
-          newRefName: "feature/parallel",
-          baseRefName: initialBranch,
-        });
+          const claimed: string[] = [];
+          const result = yield* Effect.result(
+            driver.createWorktree(
+              {
+                cwd,
+                path: worktreePath,
+                refName: initialBranch,
+                newRefName: "feature/parallel",
+                baseRefName: initialBranch,
+              },
+              {
+                progress: {
+                  onWorktreeClaimed: (path) =>
+                    Effect.sync(() => {
+                      claimed.push(path);
+                    }),
+                },
+              },
+            ),
+          );
+          assert.equal(Result.isFailure(result), failHook);
+          assert.deepEqual(claimed, [worktreePath]);
 
+          assert.notInclude(yield* git(cwd, ["worktree", "list", "--porcelain"]), "locked");
+          assert.equal(
+            yield* fs.readFileString(path.join(worktreePath, "checkout-workers")),
+            "0\n",
+          );
+          assert.equal(
+            yield* fs.readFileString(path.join(worktreePath, "asset.txt")),
+            "filtered\n",
+          );
-        assert.notInclude(yield* git(cwd, ["worktree", "list", "--porcelain"]), "locked");
-        assert.equal(yield* fs.readFileString(path.join(worktreePath, "checkout-workers")), "0\n");
-        assert.equal(yield* fs.readFileString(path.join(worktreePath, "asset.txt")), "filtered\n");
+          assert.equal(
+            yield* git(worktreePath, ["rev-parse", "HEAD"]),
+            yield* git(cwd, ["rev-parse", "HEAD"]),
+          );
+          if (failHook) return;
-        assert.equal(
-          yield* git(worktreePath, ["rev-parse", "HEAD"]),
-          yield* git(cwd, ["rev-parse", "HEAD"]),
-        );
-        assert.equal(
-          yield* git(cwd, ["config", "branch.feature/parallel.t3-merge-base"]),
-          initialBranch,
-        );
-        for (const [configured, expected] of [
-          ["1", "1"],
-          ["", "0"],
-        ] as const) {
-          yield* git(cwd, ["config", "checkout.workers", configured]);
-          const configuredPath = path.join(yield* makeTmpDir("git-worktrees-"), "configured");
-          yield* driver.createWorktree({
-            cwd,
-            path: configuredPath,
-            refName: initialBranch,
-            newRefName: `feature/configured-${expected}`,
-          });
           assert.equal(
-            yield* fs.readFileString(path.join(configuredPath, "checkout-workers")),
-            `${expected}\n`,
+            yield* git(cwd, ["config", "branch.feature/parallel.t3-merge-base"]),
+            initialBranch,
           );
-        }
-      }),
+          for (const [configured, expected] of [
+            ["1", "1"],
+            ["", "0"],
+          ] as const) {
+            yield* git(cwd, ["config", "checkout.workers", configured]);
+            const configuredPath = path.join(yield* makeTmpDir("git-worktrees-"), "configured");
+            yield* driver.createWorktree({
+              cwd,
+              path: configuredPath,
+              refName: initialBranch,
+              newRefName: `feature/configured-${expected}`,
+            });
+            assert.equal(
+              yield* fs.readFileString(path.join(configuredPath, "checkout-workers")),
+              `${expected}\n`,
+            );
+          }
+        }),
     );
     it.effect.each(["commit", "short-commit", "tag", "revision"] as const)(
       "creates a worktree from a %s without recording it as a PR base",
@@ -3951,6 +4035,75 @@
   });
 
   describe("remote operations", () => {
+    it.effect.each(["public", "launch-base"] as const)(
+      "shares one running fetch between concurrent %s callers",
+      (caller) =>
+        Effect.gen(function* () {
+          const cwd = yield* makeTmpDir();
+          const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
+          const started = yield* Deferred.make<void>();
+          const release = yield* Deferred.make<void>();
+          let fetches = 0;
+          const spawner = ChildProcessSpawner.make((command) =>
+            Effect.gen(function* () {
+              if (!ChildProcess.isStandardCommand(command))
+                return yield* Effect.die("unexpected command");
+              if (command.args[0] === "remote") return makeSuccessfulHandle("upstream\n");
+              if (command.args[0] === "for-each-ref")
+                return makeSuccessfulHandle("refs/heads/stable\tupstream\trefs/heads/release\n");
+              if (command.args[0] === "rev-parse") return makeSuccessfulHandle("remote-head\n");
+              if (command.args[0] !== "fetch") return yield* delegate.spawn(command);
+              assert.deepEqual(command.args, [
+                "fetch",
+                "--quiet",
+                "--",
+                "upstream",
+                "+refs/heads/release:refs/remotes/upstream/release",
+              ]);
+              fetches += 1;
+              yield* Deferred.succeed(started, undefined);
+              return ChildProcessSpawner.makeHandle({
+                ...makeSuccessfulHandle(""),
+                exitCode: Deferred.await(release).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
+              });
+            }),
+          );
+          const driver = yield* makeGitVcsDriverCore().pipe(
+            Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
+            Effect.provide(layerServerConfig),
+          );
+          const fetch =
+            caller === "public"
+              ? driver
+                  .fetchRemote({ cwd, remoteName: "upstream", refName: "upstream/release" })
+                  .pipe(Effect.as(null))
+              : driver.fetchWorktreeBaseCommit({ cwd, refName: "stable" });
+          const first = yield* fetch.pipe(Effect.forkChild({ startImmediately: true }));
+          yield* Deferred.await(started);
+          const joined = yield* Effect.forEach(Array.from({ length: 5 }), () =>
+            fetch.pipe(Effect.forkChild({ startImmediately: true })),
+          );
+          yield* Deferred.succeed(release, undefined);
+          const result = yield* Fiber.join(first);
+          assert.deepEqual(
+            result,
+            caller === "public"
+              ? null
+              : { commitSha: "remote-head", remoteRefName: "upstream/release" },
+          );
+          const results = yield* Effect.forEach(joined, Fiber.join);
+          assert.deepEqual(
+            results,
+            Array.from({ length: 5 }, () => result),
+          );
+          assert.equal(fetches, 1);
+
+          // A finished fetch is not reused.
+          yield* fetch;
+          assert.equal(fetches, 2);
+        }),
+    );
+
     it.effect("creates a worktree from the latest fetched remote commit", () =>
       Effect.gen(function* () {
         const cwd = yield* makeTmpDir();
```

## apps/server/src/vcs/GitVcsDriverCore.ts

Status: modified; +125; −41

```diff
@@ -33,6 +33,7 @@
 } from "@t3tools/contracts";
 import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
 import * as HostProcess from "@t3tools/shared/HostProcess";
+import * as KeyedLock from "@t3tools/shared/KeyedLock";
 import { compactTraceAttributes } from "@t3tools/shared/observability";
 import { decodeJsonResult } from "@t3tools/shared/schemaJson";
 import { resolveSpawnCommand } from "@t3tools/shared/shell";
@@ -145,6 +146,12 @@
   remoteName: string;
 }> {}
 
+class FetchRemoteKey extends Data.Class<{
+  cwd: string;
+  remoteName: string;
+  refName: string | undefined;
+}> {}
+
 function statusUpstreamRefreshFailureCooldown(consecutiveFailures: number): Duration.Duration {
   const exponent = Math.max(0, consecutiveFailures - 1);
   const cooldownMs =
@@ -435,6 +442,11 @@
   [/would clobber existing tag/i, "tag_would_be_clobbered"],
   [/is already (?:used by worktree at|checked out at)/i, "branch_checked_out_in_worktree"],
   [/a branch named .+ already exists/i, "branch_already_exists"],
+  // Concurrent branch creation can pass Git's first existence check and lose
+  // the atomic ref claim instead. Restrict this to heads, not tag collisions.
+  [/cannot lock ref 'refs\/heads\/[^']+': reference already exists/i, "branch_already_exists"],
+  // ssh names the methods it tried, so the parenthesized list varies:
+  // `(publickey)`, `(publickey,password)`, `(keyboard-interactive)`.
   [
     /(?:authentication failed|could not read Username|could not read Password|permission denied \([a-z-]+(?:,[a-z-]+)*\)|permission denied, please try again)/i,
     "authentication_failed",
@@ -930,6 +942,9 @@
   const serviceScope = yield* Effect.scope;
   const statusFetches = new Map<string, Fiber.Fiber<void, GitCommandError>>();
   const statusFetchProcesses = yield* Semaphore.make(4);
+  // Worktrees share one Git config, and Git fails rather than waits when its
+  // lock is held. Config writes take this per-repository lock instead.
+  const configLocks = yield* KeyedLock.make<string>();
 
   const executeRaw: GitVcsDriver.GitVcsDriver["Service"]["execute"] = Effect.fnUntraced(
     function* (input) {
@@ -3700,9 +3715,20 @@
       }
       worktreePath = path.join(parentDir, repoName, sanitizedBranch);
     }
-    const args = input.newRefName
+    if (input.newRefName) {
+      // Branch creation may write upstream config. Keep it under the same lock
+      // as renames, but leave the expensive checkout outside the lock.
-      ? ["worktree", "add", "-b", input.newRefName, "--", worktreePath, input.refName]
-      : ["worktree", "add", "--", worktreePath, input.refName];
+      yield* configLocks.withLock(
+        yield* resolveGitCommonDir(input.cwd),
+        executeGitWithStableDiagnostics(
+          "GitVcsDriver.createWorktree.createBranch",
+          input.cwd,
+          ["branch", "--", input.newRefName, input.refName === "-" ? "@{-1}" : input.refName],
+          { fallbackErrorDetail: "git worktree add failed" },
+        ),
+      );
+    }
+    const args = ["worktree", "add", "--", worktreePath, targetBranch];
     const progress = options?.progress;
     const onCheckoutProgress = progress?.onCheckoutProgress;
 
@@ -3728,6 +3754,29 @@
             }
           : {}),
       },
+    ).pipe(
+      Effect.tapError(() =>
+        Effect.gen(function* () {
+          if (!input.newRefName || !progress?.onWorktreeClaimed) return;
+          // A failing post-checkout hook can leave a registered checkout despite Git's exit code.
+          const registered = yield* executeWorktreeList(
+            "GitVcsDriver.createWorktree.checkClaim",
+            input.cwd,
+            [],
+          ).pipe(
+            Effect.map((result) => result.stdout),
+            Effect.orElseSucceed(() => ""),
+          );
+          const claimedPath = parseWorktreeBranchPaths(registered).get(input.newRefName);
+          if (claimedPath === undefined) return;
+          const physicalPath = yield* fileSystem
+            .realPath(worktreePath)
+            .pipe(Effect.orElseSucceed(() => worktreePath));
+          if (path.normalize(claimedPath) === path.normalize(physicalPath)) {
+            yield* progress.onWorktreeClaimed(worktreePath);
+          }
+        }),
+      ),
     );
 
     if (progress?.onWorktreeClaimed) {
@@ -3804,28 +3853,33 @@
     if (newRefName && input.baseRefName) {
       const base = yield* resolveBranchBase(input.cwd, input.baseRefName);
       if (base) {
+        yield* configLocks
-        yield* Effect.gen(function* () {
-          yield* runGit("GitVcsDriver.createWorktree.configureBaseRef", input.cwd, [
+          .withLock(
+            yield* resolveGitCommonDir(input.cwd),
+            Effect.gen(function* () {
+              yield* runGit("GitVcsDriver.createWorktree.configureBaseRef", input.cwd, [
+                "config",
-            "config",
-            branchBaseConfigKey(newRefName),
-            base.branchName,
-          ]);
-          if (base.baseRef.startsWith("refs/remotes/")) {
-            // The base key names a branch on the host; this one keeps the remote it came from.
-            yield* runGit("GitVcsDriver.createWorktree.configureComparisonRef", input.cwd, [
-              "config",
-              `branch.${input.newRefName}.t3-merge-base-ref`,
-              base.baseRef,
-            ]);
-          }
-        }).pipe(
-          Effect.catchTags({
-            GitCommandError: () =>
-              Effect.logWarning(
-                "worktree base-ref configuration failed; using base-branch fallback",
-              ),
-          }),
-        );
+                branchBaseConfigKey(newRefName),
+                base.branchName,
+              ]);
+              if (base.baseRef.startsWith("refs/remotes/")) {
+                // The base key names a branch on the host; this one keeps the remote it came from.
+                yield* runGit("GitVcsDriver.createWorktree.configureComparisonRef", input.cwd, [
+                  "config",
+                  `branch.${input.newRefName}.t3-merge-base-ref`,
+                  base.baseRef,
+                ]);
+              }
+            }),
+          )
+          .pipe(
+            Effect.catchTags({
+              GitCommandError: () =>
+                Effect.logWarning(
+                  "worktree base-ref configuration failed; using base-branch fallback",
+                ),
+            }),
+          );
       }
     }
 
@@ -4014,6 +4068,26 @@
       stderrLength: result.stderr.length,
     });
   });
+  // Concurrent fetches of one ref race for the same ref lock and all but one
+  // fail, as when many threads launch from one base at once. Callers that
+  // arrive while a fetch is running share it instead.
+  const fetchRemoteInFlight = yield* Cache.makeWith(
+    ({ refName, ...input }: FetchRemoteKey) =>
+      fetchRemote(refName === undefined ? input : { ...input, refName }),
+    {
+      capacity: Number.POSITIVE_INFINITY,
+      timeToLive: () => Duration.zero,
+    },
+  );
+  const fetchRemoteShared = (input: GitVcsDriver.GitFetchRemoteInput) =>
+    Cache.get(
+      fetchRemoteInFlight,
+      new FetchRemoteKey({
+        cwd: input.cwd,
+        remoteName: input.remoteName,
+        refName: input.refName,
+      }),
+    );
 
   const resolveRemoteTrackingCommit: GitVcsDriver.GitVcsDriver["Service"]["resolveRemoteTrackingCommit"] =
     Effect.fn("resolveRemoteTrackingCommit")(function* (input) {
@@ -4077,7 +4151,7 @@
       const { remoteName, branchName } = target;
       const remoteRefName = `${remoteName}/${branchName}`;
       // A missing remote branch can leave a stale tracking ref; never resolve it.
+      if (!(yield* fetchRemoteShared({ cwd: input.cwd, remoteName, refName: remoteRefName }))) {
-      if (!(yield* fetchRemote({ cwd: input.cwd, remoteName, refName: remoteRefName }))) {
         return null;
       }
       const resolved = yield* executeGit(
@@ -4250,21 +4324,29 @@
     if (input.oldBranch === input.newBranch) {
       return { branch: input.newBranch };
     }
+    // `git branch -m` moves the branch's config section after the ref, so a
+    // lost config lock cannot be retried. The lock also keeps concurrent
+    // renames to one name from picking the same free suffix.
+    return yield* configLocks.withLock(
+      yield* resolveGitCommonDir(input.cwd),
+      Effect.gen(function* () {
+        const targetBranch = input.exactName
+          ? input.newBranch
+          : yield* resolveAvailableBranchName(input.cwd, input.newBranch);
+
+        yield* executeGit(
+          "GitVcsDriver.renameBranch",
+          input.cwd,
-    const targetBranch = input.exactName
+          ["branch", "-m", "--", input.oldBranch, targetBranch],
+          {
+            timeoutMs: 10_000,
+            fallbackErrorDetail: "git branch rename failed",
+          },
+        );
-      ? input.newBranch
-      : yield* resolveAvailableBranchName(input.cwd, input.newBranch);
 
-    yield* executeGit(
-      "GitVcsDriver.renameBranch",
-      input.cwd,
-      ["branch", "-m", "--", input.oldBranch, targetBranch],
-      {
-        timeoutMs: 10_000,
-        fallbackErrorDetail: "git branch rename failed",
-      },
+        return { branch: targetBranch };
+      }),
     );
-
-    return { branch: targetBranch };
   });
 
   const switchRef: GitVcsDriver.GitVcsDriver["Service"]["switchRef"] = Effect.fn("switchRef")(
@@ -4482,11 +4564,13 @@
     fetchRemote: Effect.fnUntraced(function* (input) {
       return yield* withListRefsInvalidation(
         input.cwd,
-        fetchRemote(input).pipe(
+        fetchRemoteShared(input).pipe(
           Effect.flatMap((fetched) =>
             fetched
               ? Effect.void
+              : fetchRemoteShared({ cwd: input.cwd, remoteName: input.remoteName }).pipe(
+                  Effect.asVoid,
-              : fetchRemote({ cwd: input.cwd, remoteName: input.remoteName }).pipe(Effect.asVoid),
+                ),
           ),
         ),
       );
```
