The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 12:15 UTC
fix(server): re-base worktree launches whose recorded base ref does not resolve (#31747)
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>
sgoley committed
Nov 14, 2026 at 22:33 UTC
fb749693143ac3bbe3fc33c38489c02ef4e69ba2
3 files changed
+229
apps/server/src/git/GitWorkflowService.ts
+11
@@ -122,6 +122,10 @@ export class GitWorkflowService extends Context.Service<
122
{ readonly commitSha: string; readonly remoteRefName: string } | null,
123
GitCommandError
124
>;
125
+ readonly resolveDefaultBranchName: (
126
+ cwd: string,
127
+ remoteName: string,
128
+ ) => Effect.Effect<string | null, GitCommandError>;
129
readonly removeWorktree: (
130
input: VcsRemoveWorktreeInput,
131
) => Effect.Effect<void, GitCommandError>;
@@ -499,6 +503,13 @@ export const make = Effect.gen(function* () {
503
);
504
},
505
),
506
+ resolveDefaultBranchName: Effect.fn("GitWorkflowService.resolveDefaultBranchName")(
507
+ function (cwd, remoteName) {
508
+ return ensureGitCommand("GitWorkflowService.resolveDefaultBranchName", cwd).pipe(
509
+ Effect.andThen(git.resolveDefaultBranchName(cwd, remoteName)),
510
+ );
511
+ },
512
+ ),
513
removeWorktree: Effect.fn("GitWorkflowService.removeWorktree")(function (input) {
514
return ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
515
Effect.andThen(git.removeWorktree(input)),
apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+137
@@ -222,6 +222,8 @@ function makeHarness(options: HarnessOptions = {}) {
222
hasCommit: options.hasCommit ?? (() => Effect.succeed(false)),
223
currentBranch: () => Effect.succeed(null),
224
resolveWorktreeBaseRemote: () => Effect.succeed({ remoteName: "origin", branchName: "main" }),
225
+ resolvePrimaryRemoteName: () => Effect.succeed("origin"),
226
+ resolveDefaultBranchName: () => Effect.succeed("main"),
227
remoteExists: options.remoteExists ?? (() => Effect.succeed(true)),
228
remoteBranchExists: () => Effect.succeed(true),
229
listLocalBranchNames: () => Effect.succeed([]),
@@ -1362,6 +1364,140 @@ it.effect.each(["stable", "upstream/release"])(
1364
),
1365
);
1366
1367
+const withRealGitRepo = <A, E, R>(
1368
+ run: (repo: {
1369
+ readonly directory: string;
1370
+ readonly cwd: string;
1371
+ readonly worktreePath: string;
1372
+ readonly command: (
1373
+ at: string,
1374
+ args: string[],
1375
+ ) => ReturnType<GitVcsDriver.GitVcsDriver["Service"]["execute"]>;
1376
+ readonly harness: (options?: HarnessOptions) => ReturnType<typeof makeHarness>;
1377
+ }) => Effect.Effect<A, E, R>,
1378
+) =>
1379
+ Effect.gen(function* () {
1380
+ const fs = yield* FileSystem.FileSystem;
1381
+ const git = yield* GitVcsDriver.GitVcsDriver;
1382
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "launch-base-fallback-" });
1383
+ const cwd = `${directory}/repo`;
1384
+ const worktreePath = `${directory}/worktree`;
1385
+ yield* fs.makeDirectory(cwd);
1386
+ const command = (at: string, args: string[]) =>
1387
+ git.execute({ operation: "launch-test", cwd: at, args });
1388
+ yield* command(cwd, ["init", "-b", "beta"]);
1389
+ yield* command(cwd, ["config", "user.name", "Test"]);
1390
+ yield* command(cwd, ["config", "user.email", "test@example.test"]);
1391
+ const harness = (options: HarnessOptions = {}) =>
1392
+ makeHarness({
1393
+ hasCommit: ({ refName }) =>
1394
+ command(cwd, ["rev-parse", "--verify", `${refName}^{commit}`]).pipe(
1395
+ Effect.as(true),
1396
+ Effect.orElseSucceed(() => false),
1397
+ ),
1398
+ fetchWorktreeBaseCommit: (input) => git.fetchWorktreeBaseCommit({ ...input, cwd }),
1399
+ createWorktree: (input, progress) =>
1400
+ git.createWorktree({ ...input, cwd, path: worktreePath }, progress),
1401
+ ...options,
1402
+ git: {
1403
+ resolveWorktreeBaseRemote: (input) => git.resolveWorktreeBaseRemote({ ...input, cwd }),
1404
+ resolvePrimaryRemoteName: () => git.resolvePrimaryRemoteName(cwd),
1405
+ resolveDefaultBranchName: (_cwd, remoteName) =>
1406
+ git.resolveDefaultBranchName(cwd, remoteName),
1407
+ currentBranch: () =>
1408
+ command(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]).pipe(
1409
+ Effect.map((result) => result.stdout.trim() || null),
1410
+ Effect.orElseSucceed(() => null),
1411
+ ),
1412
+ hasRefNamed: () => Effect.succeed(false),
1413
+ ...options.git,
1414
+ },
1415
+ });
1416
+ return yield* run({ directory, cwd, worktreePath, command, harness });
1417
+ }).pipe(
1418
+ Effect.provide(
1419
+ GitVcsDriver.layer.pipe(
1420
+ Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "launch-base-git-" })),
1421
+ Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
1422
+ ),
1423
+ ),
1424
+ );
1425
+
1426
+const launchFromBase = (harness: ReturnType<typeof makeHarness>, baseRef: string) =>
1427
+ Effect.gen(function* () {
1428
+ const launches = yield* ThreadLaunch.ThreadLaunchService;
1429
+ const launched = yield* launches.launch(
1430
+ launchInput({
1431
+ command: "command:launch:base-fallback",
1432
+ thread: "thread:launch:base-fallback",
1433
+ message: "Build the feature",
1434
+ workspace: { type: "worktree", baseRef, branch: "feature", startFromOrigin: true },
1435
+ }),
1436
+ );
1437
+ const projection = yield* preparationSettled(launched.threadId);
1438
+ assert.equal(projection.runs[0]?.status, "starting");
1439
+ }).pipe(Effect.provide(harness.layer));
1440
+
1441
+it.effect("re-bases a stored base that no longer exists on the remote default branch", () =>
1442
+ withRealGitRepo(({ directory, cwd, worktreePath, command, harness }) =>
1443
+ Effect.gen(function* () {
1444
+ const remote = `${directory}/remote.git`;
1445
+ yield* command(cwd, ["commit", "--allow-empty", "-m", "initial"]);
1446
+ yield* command(cwd, ["init", "--bare", remote]);
1447
+ yield* command(cwd, ["remote", "add", "origin", remote]);
1448
+ yield* command(cwd, ["push", "-u", "origin", "beta"]);
1449
+ yield* command(cwd, ["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/beta"]);
1450
+ const remoteHead = (yield* command(cwd, ["rev-parse", "beta"])).stdout.trim();
1451
+ yield* command(cwd, ["checkout", "--detach"]);
1452
+ yield* command(cwd, ["commit", "--allow-empty", "-m", "local only"]);
1453
+
1454
+ // Tasks saved before the base followed the default branch still record "main".
1455
+ yield* launchFromBase(harness(), "main");
1456
+ assert.equal((yield* command(worktreePath, ["rev-parse", "HEAD"])).stdout.trim(), remoteHead);
1457
+ }),
1458
+ ),
1459
+);
1460
+
1461
+it.effect("keeps a `:/` commit-search base instead of re-basing", () =>
1462
+ withRealGitRepo(({ cwd, worktreePath, command, harness }) =>
1463
+ Effect.gen(function* () {
1464
+ yield* command(cwd, ["commit", "--allow-empty", "-m", "searched base"]);
1465
+ const searchedHead = (yield* command(cwd, ["rev-parse", "HEAD"])).stdout.trim();
1466
+ yield* command(cwd, ["commit", "--allow-empty", "-m", "later work"]);
1467
+
1468
+ yield* launchFromBase(harness(), ":/searched");
1469
+ assert.equal(
1470
+ (yield* command(worktreePath, ["rev-parse", "HEAD"])).stdout.trim(),
1471
+ searchedHead,
1472
+ );
1473
+ }),
1474
+ ),
1475
+);
1476
+
1477
+it.effect("skips a stale tracking ref when the remote reports the base branch is gone", () =>
1478
+ withRealGitRepo(({ cwd, worktreePath, command, harness }) =>
1479
+ Effect.gen(function* () {
1480
+ yield* command(cwd, ["commit", "--allow-empty", "-m", "stale point"]);
1481
+ const staleHead = (yield* command(cwd, ["rev-parse", "HEAD"])).stdout.trim();
1482
+ yield* command(cwd, ["commit", "--allow-empty", "-m", "current work"]);
1483
+ const betaHead = (yield* command(cwd, ["rev-parse", "HEAD"])).stdout.trim();
1484
+ // The deleted remote branch leaves its tracking ref (and origin/HEAD) behind.
1485
+ yield* command(cwd, ["update-ref", "refs/remotes/origin/gone", staleHead]);
1486
+ yield* command(cwd, ["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/gone"]);
1487
+
1488
+ yield* launchFromBase(
1489
+ harness({
1490
+ // A completed fetch that found no branch, as when the branch was deleted.
1491
+ fetchWorktreeBaseCommit: () => Effect.succeed(null),
1492
+ git: { resolvePrimaryRemoteName: () => Effect.succeed("origin") },
1493
+ }),
1494
+ "main",
1495
+ );
1496
+ assert.equal((yield* command(worktreePath, ["rev-parse", "HEAD"])).stdout.trim(), betaHead);
1497
+ }),
1498
+ ),
1499
+);
1500
+
1501
it.effect("fetches the origin base from the remote it already resolved", () => {
1502
let fetchInput: Deferred.Deferred<unknown> | null = null;
1503
const harness = makeHarness({
@@ -2189,6 +2325,7 @@ it.effect(
2325
fetched.push(refName);
2326
return null;
2327
}),
2328
+ hasCommit: ({ refName }) => Effect.succeed(refName === "main"),
2329
runSetup: () =>
2330
Deferred.succeed(setupEntered, undefined).pipe(
2331
Effect.andThen(Deferred.await(allowSetup)),
apps/server/src/orchestration-v2/ThreadLaunchService.ts
+81
@@ -447,6 +447,55 @@ const make = Effect.gen(function* () {
447
);
448
});
449
450
+ /**
451
+ * A recorded worktree strategy can outlive the ref it names: tasks saved before
452
+ * the base followed the repo's default branch kept `"main"`, and a base branch
453
+ * can be deleted after it was recorded. Re-base on the remote's default branch,
454
+ * then on the checked-out commit, instead of failing every launch.
455
+ */
456
+ const worktreeFallbackBase = Effect.fn("ThreadLaunchService.worktreeFallbackBase")(function* (
457
+ cwd: string,
458
+ remoteName: string | null,
459
+ ) {
460
+ if (remoteName !== null) {
461
+ const defaultBranch = yield* git.resolveDefaultBranchName(cwd, remoteName);
462
+ if (defaultBranch !== null) {
463
+ // Fetch freshens the default branch the way the recorded base would have been.
464
+ const remoteBase = yield* git
465
+ .fetchWorktreeBaseCommit({
466
+ cwd,
467
+ refName: defaultBranch,
468
+ remote: { remoteName, branchName: defaultBranch },
469
+ })
470
+ .pipe(
471
+ Effect.map((base) => ({ fetchFailed: false as const, base })),
472
+ Effect.orElseSucceed(() => ({ fetchFailed: true as const, base: null })),
473
+ );
474
+ if (remoteBase.base !== null) {
475
+ return {
476
+ startRef: remoteBase.base.commitSha,
477
+ baseRefName: `refs/remotes/${remoteBase.base.remoteRefName}`,
478
+ };
479
+ }
480
+ // A completed fetch that found no branch means the branch is gone and its
481
+ // tracking ref is stale; only a failed fetch can fall back to it.
482
+ if (remoteBase.fetchFailed) {
483
+ const trackingRef = `refs/remotes/${remoteName}/${defaultBranch}`;
484
+ if (yield* git.hasCommit({ cwd, refName: trackingRef })) {
485
+ return { startRef: trackingRef, baseRefName: trackingRef };
486
+ }
487
+ }
488
+ }
489
+ }
490
+ const currentBranch = yield* git.currentBranch(cwd);
491
+ if (currentBranch !== null) {
492
+ return { startRef: currentBranch, baseRefName: currentBranch };
493
+ }
494
+ return (yield* git.hasCommit({ cwd, refName: "HEAD" }))
495
+ ? { startRef: "HEAD", baseRefName: "HEAD" }
496
+ : null;
497
+ });
498
+
499
const prepareInBackground = Effect.fn("ThreadLaunchService.prepareInBackground")(function* (
500
input: PreparationInput,
501
threadId: ThreadId,
@@ -579,6 +628,7 @@ const make = Effect.gen(function* () {
628
: null;
629
const shouldFetch = remote !== null;
630
yield* setupTracker.stageStatus(threadId, "fetch", shouldFetch ? "running" : "skipped");
631
+ let fetchedBase = false;
632
if (remote !== null) {
633
const remoteBase = yield* git
634
.fetchWorktreeBaseCommit({
@@ -590,9 +640,40 @@ const make = Effect.gen(function* () {
640
if (remoteBase !== null) {
641
startRef = remoteBase.commitSha;
642
baseRefName = `refs/remotes/${remoteBase.remoteRefName}`;
643
+ fetchedBase = true;
644
}
645
}
646
if (shouldFetch) yield* setupTracker.stageStatus(threadId, "fetch", "done");
647
+ // `:/text` bases are commit searches, not refs; `hasCommit` treats the appended
648
+ // `^{commit}` as part of the pattern (same guard as checkWorktreeBase).
649
+ const recordedBaseResolves =
650
+ fetchedBase ||
651
+ startRef.startsWith(":") ||
652
+ (yield* git
653
+ .hasCommit({
654
+ cwd: project.workspaceRoot,
655
+ // `git worktree add` reads `-` as the previous checkout.
656
+ refName: startRef === "-" ? "@{-1}" : startRef,
657
+ })
658
+ .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))));
659
+ if (!recordedBaseResolves) {
660
+ const remoteName =
661
+ remote?.remoteName ??
662
+ (yield* git
663
+ .resolvePrimaryRemoteName(project.workspaceRoot)
664
+ .pipe(Effect.orElseSucceed(() => null)));
665
+ const fallback = yield* worktreeFallbackBase(project.workspaceRoot, remoteName).pipe(
666
+ Effect.orElseSucceed(() => null),
667
+ );
668
+ if (fallback !== null) {
669
+ startRef = fallback.startRef;
670
+ baseRefName = fallback.baseRefName;
671
+ yield* setupTracker.update(threadId, (snapshot) => ({
672
+ ...snapshot,
673
+ baseRef: fallback.baseRefName,
674
+ }));
675
+ }
676
+ }
677
if (branch !== null && (generatedTemporaryBranch || isTemporaryWorktreeBranch(branch))) {
678
const parts = branch.split("/");
679
for (let depth = 1; depth < parts.length; depth++) {