@devries-cameron20 / t3code Mirror · read-only / commits / 98a7353735
Fork 0

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 22, 12:00 UTC

perf(server): avoid repeated Git directory discovery during worktree creation (#21337)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com>

Adamulek123 committed Oct 30, 2026 at 21:26 UTC 98a735373523f432a5d5a0b69237020e3641e4d8
2 files changed +476 -18
apps/server/src/vcs/GitVcsDriverCore.test.ts
+426 -2
@@ -5,8 +5,10 @@ import * as NodeURL from "node:url";
5 import * as NodeServices from "@effect/platform-node/NodeServices";
6 import * as HostProcess from "@t3tools/shared/HostProcess";
7 import { assert, it, describe } from "@effect/vitest";
8 +import * as Cause from "effect/Cause";
9 import * as Deferred from "effect/Deferred";
10 import * as Effect from "effect/Effect";
11 +import * as Exit from "effect/Exit";
12 import * as FileSystem from "effect/FileSystem";
13 import * as Fiber from "effect/Fiber";
14 import * as Layer from "effect/Layer";
@@ -49,7 +51,7 @@ const layerServerConfig = ServerConfig.layerTest(process.cwd(), {
51 prefix: "t3-git-vcs-driver-test-",
52 });
53 const layerTest = GitVcsDriver.layer.pipe(
52 - Layer.provide(layerServerConfig),
54 + Layer.provideMerge(layerServerConfig),
55 Layer.provideMerge(NodeServices.layer),
56 );
57
@@ -330,6 +332,415 @@ it.effect("invalidates origin remote cache when a driver mutation adds origin",
332 }).pipe(Effect.provide(layerTest)),
333 );
334
335 +it.effect.each([
336 + { hookExitCode: 0, commonDirFailure: "none" },
337 + { hookExitCode: 1, commonDirFailure: "none" },
338 + { hookExitCode: 0, commonDirFailure: "error" },
339 + { hookExitCode: 1, commonDirFailure: "error" },
340 + { hookExitCode: 0, commonDirFailure: "non-repository" },
341 + { hookExitCode: 1, commonDirFailure: "non-repository" },
342 +])(
343 + "invalidates sibling worktree refs and status after checkout hook exit $hookExitCode with common-dir failure $commonDirFailure",
344 + ({ hookExitCode, commonDirFailure }) =>
345 + Effect.scoped(
346 + Effect.gen(function* () {
347 + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
348 + const spawnedArgs: Array<ReadonlyArray<string>> = [];
349 + let invalidationFailure = "none";
350 + const spawner = ChildProcessSpawner.make((command) =>
351 + Effect.gen(function* () {
352 + if (!ChildProcess.isStandardCommand(command)) {
353 + return yield* Effect.die("expected a standard Git command");
354 + }
355 + spawnedArgs.push(command.args);
356 + if (invalidationFailure !== "none" && command.args.includes("--git-common-dir")) {
357 + if (invalidationFailure === "non-repository") return makeNonRepositoryHandle();
358 + return ChildProcessSpawner.makeHandle({
359 + ...makeNonRepositoryHandle(),
360 + stderr: Stream.encodeText(Stream.make("fatal: could not read repository metadata")),
361 + });
362 + }
363 + return yield* delegate.spawn(command);
364 + }),
365 + );
366 + const driver = yield* makeGitVcsDriverCore().pipe(
367 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
368 + );
369 + const cwd = yield* makeTmpDir();
370 + const { initialBranch } = yield* initRepoWithCommit(cwd);
371 + const path = yield* Path.Path;
372 + const fs = yield* FileSystem.FileSystem;
373 + const siblingPath = path.join(yield* makeTmpDir("git-worktrees-"), "sibling");
374 + yield* git(cwd, ["worktree", "add", "-b", "cache-sibling", siblingPath, "HEAD"]);
375 +
376 + const before = yield* driver.listRefs({ cwd: siblingPath, refresh: true });
377 + assert.isTrue(before.refs.find((ref) => ref.name === "cache-sibling")?.current);
378 + const statusBefore = yield* driver.statusDetailsLocal(siblingPath);
379 + assert.isFalse(statusBefore.hasOriginRemote);
380 + assert.isFalse(statusBefore.isDefaultBranch);
381 + yield* driver.listRefs({ cwd, refresh: true });
382 + yield* git(cwd, ["checkout", "-b", "creator-current"]);
383 + yield* writeTextFile(
384 + cwd,
385 + ".git/hooks/post-checkout",
386 + "#!/bin/sh\n" +
387 + "git remote add origin https://example.invalid/repo.git || exit 2\n" +
388 + "git update-ref refs/remotes/origin/cache-sibling HEAD || exit 2\n" +
389 + "git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/cache-sibling || exit 2\n" +
390 + `exit ${hookExitCode}\n`,
391 + );
392 + yield* fs.chmod(path.join(cwd, ".git/hooks/post-checkout"), 0o755);
393 + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "created");
394 + spawnedArgs.length = 0;
395 + invalidationFailure = commonDirFailure;
396 +
397 + const created = yield* driver
398 + .createWorktree({
399 + cwd,
400 + path: worktreePath,
401 + refName: initialBranch,
402 + newRefName: "feature/cache-created",
403 + })
404 + .pipe(Effect.result);
405 +
406 + assert.equal(Result.isSuccess(created), hookExitCode === 0);
407 + if (Result.isFailure(created)) {
408 + assert.equal(created.failure.operation, "GitVcsDriver.createWorktree");
409 + assert.equal(created.failure.detail, "git worktree add failed");
410 + assert.equal(created.failure.exitCode, hookExitCode);
411 + }
412 + const metadataQueries = spawnedArgs.filter((args) => args.includes("--git-common-dir"));
413 + assert.deepStrictEqual(metadataQueries, [["rev-parse", "--git-common-dir"]]);
414 + assert.isFalse(spawnedArgs.some((args) => args.includes("symbolic-ref")));
415 + invalidationFailure = "none";
416 +
417 + spawnedArgs.length = 0;
418 + const creatorStatus = yield* driver.statusDetailsLocal(cwd);
419 + assert.equal(creatorStatus.branch, "creator-current");
420 + assert.isTrue(spawnedArgs.some((args) => args.includes("--git-common-dir")));
421 + const siblingRefs = yield* driver.listRefs({ cwd: siblingPath });
422 + const createdRef = siblingRefs.refs.find((ref) => ref.name === "feature/cache-created");
423 + assert.isDefined(createdRef?.worktreePath);
424 + assert.equal(
425 + NodeFS.realpathSync.native(createdRef!.worktreePath!),
426 + NodeFS.realpathSync.native(worktreePath),
427 + );
428 + assert.isTrue(siblingRefs.hasPrimaryRemote);
429 + assert.isTrue(siblingRefs.refs.find((ref) => ref.name === "cache-sibling")?.current);
430 + const statusAfter = yield* driver.statusDetailsLocal(siblingPath);
431 + assert.isTrue(statusAfter.hasOriginRemote);
432 + assert.isTrue(statusAfter.isDefaultBranch);
433 + const creatorRefs = yield* driver.listRefs({ cwd });
434 + assert.isTrue(creatorRefs.refs.find((ref) => ref.name === "creator-current")?.current);
435 + assert.isFalse(creatorRefs.refs.find((ref) => ref.name === initialBranch)?.current);
436 + }),
437 + ).pipe(Effect.provide(layerTest)),
438 +);
439 +
440 +it.effect.each(["branch", "detached", "nested", "aliased-root", "aliased-nested"] as const)(
441 + "discovers only the common directory during worktree creation from %s",
442 + (location) =>
443 + Effect.scoped(
444 + Effect.gen(function* () {
445 + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
446 + const spawnedArgs: Array<ReadonlyArray<string>> = [];
447 + const spawner = ChildProcessSpawner.make((command) => {
448 + if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args);
449 + return delegate.spawn(command);
450 + });
451 + const driver = yield* makeGitVcsDriverCore().pipe(
452 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
453 + );
454 + const cwd = yield* makeTmpDir();
455 + const { initialBranch } = yield* initRepoWithCommit(cwd);
456 + const path = yield* Path.Path;
457 + if (location === "detached") yield* git(cwd, ["checkout", "--detach"]);
458 + const isNested = location === "nested" || location === "aliased-nested";
459 + const physicalCwd = isNested ? path.join(cwd, "nested") : cwd;
460 + const fs = yield* FileSystem.FileSystem;
461 + yield* fs.makeDirectory(physicalCwd, { recursive: true });
462 + const isAliased = location === "aliased-root" || location === "aliased-nested";
463 + const creationCwd = isAliased
464 + ? path.join(yield* makeTmpDir("git-alias-"), "link")
465 + : physicalCwd;
466 + if (isAliased) NodeFS.symlinkSync(physicalCwd, creationCwd, "junction");
467 + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "cold");
468 +
469 + yield* driver.createWorktree({
470 + cwd: creationCwd,
471 + path: worktreePath,
472 + refName: initialBranch,
473 + newRefName: "feature/cold",
474 + });
475 +
476 + assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 1);
477 + assert.isFalse(spawnedArgs.some((args) => args.includes("--show-toplevel")));
478 + assert.isFalse(spawnedArgs.some((args) => args.includes("symbolic-ref")));
479 + spawnedArgs.length = 0;
480 + const originalStatus = yield* driver.statusDetailsLocal(creationCwd);
481 + assert.equal(originalStatus.branch, location === "detached" ? null : initialBranch);
482 + const originalRefs = yield* driver.listRefs({ cwd: creationCwd });
483 + assert.equal(originalRefs.isAtRepositoryRoot, !isNested);
484 + assert.deepStrictEqual(
485 + originalRefs.refs.filter((ref) => ref.current).map((ref) => ref.name),
486 + location === "detached" ? [] : [initialBranch],
487 + );
488 + assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 1);
489 + const refs = yield* driver.listRefs({ cwd: worktreePath });
490 + assert.isTrue(refs.refs.find((ref) => ref.name === "feature/cold")?.current);
491 + assert.equal(
492 + yield* git(worktreePath, ["rev-parse", "HEAD"]),
493 + yield* git(cwd, ["rev-parse", "HEAD"]),
494 + );
495 + }),
496 + ).pipe(Effect.provide(layerTest)),
497 +);
498 +
499 +it.effect.each(["bare", "unborn"] as const)(
500 + "invalidates a %s repository after worktree creation",
501 + (state) =>
502 + Effect.scoped(
503 + Effect.gen(function* () {
504 + const source = yield* makeTmpDir();
505 + const cwd = yield* makeTmpDir("git-discovery-fallback-");
506 + if (state === "bare") {
507 + yield* initRepoWithCommit(source);
508 + yield* git(source, ["clone", "--bare", source, cwd]);
509 + } else {
510 + yield* git(cwd, ["init"]);
511 + }
512 + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
513 + const spawnedArgs: Array<ReadonlyArray<string>> = [];
514 + const spawner = ChildProcessSpawner.make((command) => {
515 + if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args);
516 + return delegate.spawn(
517 + state === "bare" ? ChildProcess.setEnv(command, { GIT_DIR: cwd }) : command,
518 + );
519 + });
520 + const driver = yield* makeGitVcsDriverCore().pipe(
521 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
522 + );
523 + const path = yield* Path.Path;
524 + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "fallback");
525 + const result = yield* driver
526 + .createWorktree({
527 + cwd,
528 + path: worktreePath,
529 + refName: "HEAD",
530 + newRefName: "feature/fallback",
531 + })
532 + .pipe(Effect.result);
533 + assert.equal(Result.isSuccess(result), state === "bare");
534 + if (Result.isFailure(result)) {
535 + assert.equal(result.failure.operation, "GitVcsDriver.createWorktree.createBranch");
536 + assert.equal(result.failure.detail, "git worktree add failed");
537 + }
538 + assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 1);
539 + assert.isFalse(spawnedArgs.some((args) => args[0] === "symbolic-ref"));
540 + spawnedArgs.length = 0;
541 + const refs = yield* driver.listRefs({ cwd });
542 + assert.isTrue(refs.isRepo);
543 + if (state === "bare") {
544 + assert.isTrue(refs.refs.some((ref) => ref.name === "feature/fallback"));
545 + } else {
546 + assert.isEmpty(refs.refs);
547 + }
548 + assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 1);
549 + }),
550 + ).pipe(Effect.provide(layerTest)),
551 +);
552 +
553 +it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
554 + "preserves embedded newlines in repository paths after worktree creation",
555 + () =>
556 + Effect.scoped(
557 + Effect.gen(function* () {
558 + const path = yield* Path.Path;
559 + const fs = yield* FileSystem.FileSystem;
560 + const cwd = path.join(yield* makeTmpDir(), "repo\nwith-newline");
561 + yield* fs.makeDirectory(cwd);
562 + const { initialBranch } = yield* initRepoWithCommit(cwd);
563 + const driver = yield* GitVcsDriver.GitVcsDriver;
564 + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "newline");
565 + yield* driver.createWorktree({
566 + cwd,
567 + path: worktreePath,
568 + refName: initialBranch,
569 + newRefName: "feature/newline",
570 + });
571 + const status = yield* driver.statusDetailsLocal(cwd);
572 + assert.equal(status.branch, initialBranch);
573 + const refs = yield* driver.listRefs({ cwd });
574 + assert.isTrue(refs.refs.find((ref) => ref.name === initialBranch)?.current);
575 + assert.isTrue(refs.refs.some((ref) => ref.name === "feature/newline"));
576 + }),
577 + ).pipe(Effect.provide(layerTest)),
578 +);
579 +
580 +it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
581 + "preserves a trailing carriage return in the repository root after creation through an alias",
582 + () =>
583 + Effect.scoped(
584 + Effect.gen(function* () {
585 + const path = yield* Path.Path;
586 + const fs = yield* FileSystem.FileSystem;
587 + const sandbox = yield* makeTmpDir();
588 + const repository = path.join(sandbox, "repo\r");
589 + const cwd = path.join(sandbox, "alias");
590 + yield* fs.makeDirectory(repository);
591 + const { initialBranch } = yield* initRepoWithCommit(repository);
592 + NodeFS.symlinkSync(repository, cwd, "junction");
593 + const driver = yield* GitVcsDriver.GitVcsDriver;
594 + yield* driver.createWorktree({
595 + cwd,
596 + path: path.join(yield* makeTmpDir("git-worktrees-"), "created"),
597 + refName: initialBranch,
598 + newRefName: "feature/carriage-return",
599 + });
600 + const status = yield* driver.statusDetailsLocal(cwd);
601 + assert.equal(status.workingTree.rootPath, NodeFS.realpathSync.native(repository));
602 + assert.equal(status.branch, initialBranch);
603 + const refs = yield* driver.listRefs({ cwd });
604 + assert.isTrue(refs.isAtRepositoryRoot);
605 + assert.isTrue(refs.refs.some((ref) => ref.name === "feature/carriage-return"));
606 + }),
607 + ).pipe(Effect.provide(layerTest)),
608 +);
609 +
610 +it.effect(
611 + "reads fresh metadata when another mutation completes during common-directory discovery",
612 + () =>
613 + Effect.scoped(
614 + Effect.gen(function* () {
615 + const cwd = yield* makeTmpDir();
616 + yield* initRepoWithCommit(cwd);
617 + const commit = yield* git(cwd, ["rev-parse", "HEAD"]);
618 + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
619 + const discoveryComplete = yield* Deferred.make<void>();
620 + const releaseDiscovery = yield* Deferred.make<void>();
621 + let holdDiscovery = false;
622 + const spawner = ChildProcessSpawner.make((command) =>
623 + Effect.gen(function* () {
624 + const handle = yield* delegate.spawn(command);
625 + if (
626 + !holdDiscovery ||
627 + !ChildProcess.isStandardCommand(command) ||
628 + !command.args.includes("--git-common-dir")
629 + )
630 + return handle;
631 + holdDiscovery = false;
632 + const output = yield* Stream.runCollect(handle.stdout);
633 + yield* handle.exitCode;
634 + yield* Deferred.succeed(discoveryComplete, undefined);
635 + yield* Deferred.await(releaseDiscovery);
636 + return ChildProcessSpawner.makeHandle({
637 + ...handle,
638 + stdout: Stream.fromIterable(output),
639 + });
640 + }),
641 + );
642 + const driver = yield* makeGitVcsDriverCore().pipe(
643 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
644 + );
645 + yield* driver.listRefs({ cwd, refresh: true });
646 + const path = yield* Path.Path;
647 + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "concurrent");
648 + holdDiscovery = true;
649 + const creation = yield* driver
650 + .createWorktree({
651 + cwd,
652 + path: worktreePath,
653 + refName: "HEAD",
654 + newRefName: "feature/concurrent",
655 + })
656 + .pipe(Effect.forkChild({ startImmediately: true }));
657 + yield* Effect.gen(function* () {
658 + yield* Deferred.await(discoveryComplete);
659 + yield* driver.switchRef({ cwd, refName: commit });
660 + }).pipe(Effect.ensuring(Deferred.succeed(releaseDiscovery, undefined)));
661 + const created = yield* Fiber.join(creation);
662 + assert.equal(created.worktree.path, worktreePath);
663 + const refs = yield* driver.listRefs({ cwd });
664 + assert.isEmpty(refs.refs.filter((ref) => ref.current));
665 + assert.isTrue(refs.refs.some((ref) => ref.name === "feature/concurrent"));
666 + assert.equal((yield* driver.statusDetailsLocal(cwd)).branch, null);
667 + }),
668 + ).pipe(Effect.provide(layerTest)),
669 +);
670 +
671 +it.effect("invalidates cached metadata after interrupted worktree creation", () =>
672 + Effect.scoped(
673 + Effect.gen(function* () {
674 + const cwd = yield* makeTmpDir();
675 + yield* initRepoWithCommit(cwd);
676 + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
677 + const discoveryComplete = yield* Deferred.make<void>();
678 + const releaseDiscovery = yield* Deferred.make<void>();
679 + let holdDiscovery = false;
680 + const spawner = ChildProcessSpawner.make((command) =>
681 + Effect.gen(function* () {
682 + const handle = yield* delegate.spawn(command);
683 + if (
684 + !holdDiscovery ||
685 + !ChildProcess.isStandardCommand(command) ||
686 + !command.args.includes("--git-common-dir")
687 + )
688 + return handle;
689 + holdDiscovery = false;
690 + const output = yield* Stream.runCollect(handle.stdout);
691 + yield* handle.exitCode;
692 + yield* Deferred.succeed(discoveryComplete, undefined);
693 + yield* Deferred.await(releaseDiscovery);
694 + return ChildProcessSpawner.makeHandle({ ...handle, stdout: Stream.fromIterable(output) });
695 + }),
696 + );
697 + const driver = yield* makeGitVcsDriverCore().pipe(
698 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
699 + );
700 + yield* driver.listRefs({ cwd, refresh: true });
701 + yield* driver.statusDetailsLocal(cwd);
702 + yield* git(cwd, ["checkout", "-b", "creator-current"]);
703 + const path = yield* Path.Path;
704 + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "interrupted");
705 + holdDiscovery = true;
706 + const creation = yield* driver
707 + .createWorktree({
708 + cwd,
709 + path: worktreePath,
710 + refName: "HEAD",
711 + newRefName: "feature/interrupted",
712 + })
713 + .pipe(Effect.forkChild({ startImmediately: true }));
714 + const cancellation = yield* Effect.gen(function* () {
715 + yield* Deferred.await(discoveryComplete);
716 + return yield* Fiber.interrupt(creation).pipe(Effect.forkChild({ startImmediately: true }));
717 + }).pipe(Effect.ensuring(Deferred.succeed(releaseDiscovery, undefined)));
718 + yield* Fiber.join(cancellation);
719 + const exit = yield* Fiber.await(creation);
720 + assert.isTrue(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause));
721 + const refs = yield* driver.listRefs({ cwd });
722 + assert.isTrue(refs.refs.find((ref) => ref.name === "creator-current")?.current);
723 + const interruptedRef = refs.refs.find((ref) => ref.name === "feature/interrupted");
724 + assert.isDefined(interruptedRef?.worktreePath);
725 + assert.equal(
726 + NodeFS.realpathSync.native(interruptedRef!.worktreePath!),
727 + NodeFS.realpathSync.native(worktreePath),
728 + );
729 + assert.equal((yield* driver.statusDetailsLocal(cwd)).branch, "creator-current");
730 + const nextPath = path.join(yield* makeTmpDir("git-worktrees-"), "after-interruption");
731 + yield* driver.createWorktree({
732 + cwd,
733 + path: nextPath,
734 + refName: "HEAD",
735 + newRefName: "feature/after",
736 + });
737 + assert.isTrue(
738 + (yield* driver.listRefs({ cwd })).refs.some((ref) => ref.name === "feature/after"),
739 + );
740 + }),
741 + ).pipe(Effect.provide(layerTest)),
742 +);
743 +
744 describe("pullCurrentBranch", () => {
745 // A fast-forward that prints over 1 MB takes thousands of files, so the real pull's output is
746 // padded past the cap instead.
@@ -2624,10 +3035,23 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3035 yield* git(repo, ["checkout", "-b", "real-only"]);
3036
3037 // The decoy must exist before the first lookup, which caches repository paths.
2627 - const refs = yield* (yield* GitVcsDriver.GitVcsDriver).listRefs({ cwd: link });
3038 + const driver = yield* GitVcsDriver.GitVcsDriver;
3039 + const refs = yield* driver.listRefs({ cwd: link });
3040 assert.isTrue(refs.isRepo);
3041 assert.isFalse(refs.refs.some((ref) => ref.name === "decoy-only"));
3042 assert.isTrue(refs.refs.some((ref) => ref.name === "real-only"));
3043 +
3044 + yield* driver.createWorktree({
3045 + cwd: link,
3046 + path: pathService.join(yield* makeTmpDir("git-worktrees-"), "real"),
3047 + refName: "real-only",
3048 + newRefName: "feature/real-created",
3049 + });
3050 + const createdRefs = yield* driver.listRefs({ cwd: link });
3051 + assert.isFalse(createdRefs.isAtRepositoryRoot);
3052 + assert.isFalse(createdRefs.refs.some((ref) => ref.name === "decoy-only"));
3053 + assert.isTrue(createdRefs.refs.some((ref) => ref.name === "real-only" && ref.current));
3054 + assert.isTrue(createdRefs.refs.some((ref) => ref.name === "feature/real-created"));
3055 }),
3056 );
3057
apps/server/src/vcs/GitVcsDriverCore.ts
+50 -16
@@ -1371,9 +1371,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1371 }
1372 });
1373
1374 - const resolveRepositoryPathsUncached = Effect.fn("resolveRepositoryPathsUncached")(function* (
1375 - cwd: string,
1376 - ) {
1374 + const readGitCommonDir = Effect.fn("readGitCommonDir")(function* (cwd: string) {
1375 // Git reports relative paths from the physical cwd, which can differ from a symlink.
1376 const commonDirResult = yield* executeGitWithStableDiagnostics(
1377 "GitVcsDriver.resolveRepositoryPaths.commonDir",
@@ -1407,9 +1405,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1405 const resolvedGitCommonDir = path.isAbsolute(commonDirOutput)
1406 ? path.normalize(commonDirOutput)
1407 : path.resolve(physicalCwd, commonDirOutput);
1410 - const gitCommonDir = yield* fileSystem
1408 + return yield* fileSystem
1409 .realPath(resolvedGitCommonDir)
1410 .pipe(Effect.orElseSucceed(() => resolvedGitCommonDir));
1411 + });
1412 +
1413 + const resolveRepositoryPathsUncached = Effect.fn("resolveRepositoryPathsUncached")(function* (
1414 + cwd: string,
1415 + ) {
1416 + const gitCommonDir = yield* readGitCommonDir(cwd);
1417 + if (gitCommonDir === null) return null;
1418 const [worktreeRootResult, currentBranchResult] = yield* Effect.all(
1419 [
1420 executeGit(
@@ -1547,11 +1552,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1552 },
1553 );
1554 const invalidateStatusStaticCaches = Effect.fn("GitVcsDriverCore.invalidateStatusStaticCaches")(
1550 - function* (cwd: string) {
1551 - const repositoryPaths = yield* resolveRepositoryPaths(cwd).pipe(
1552 - Effect.catchTags({ GitCommandError: () => Effect.succeed(null) }),
1553 - );
1554 - const cacheKey = repositoryPaths?.gitCommonDir ?? normalizeRepositoryPathsCacheKey(cwd);
1555 + function* (cwd: string, gitCommonDir?: string | null) {
1556 + const commonDir =
1557 + gitCommonDir === undefined
1558 + ? (yield* resolveRepositoryPaths(cwd).pipe(
1559 + Effect.catchTags({ GitCommandError: () => Effect.succeed(null) }),
1560 + ))?.gitCommonDir
1561 + : gitCommonDir;
1562 + const cacheKey = commonDir ?? normalizeRepositoryPathsCacheKey(cwd);
1563 yield* Cache.invalidate(defaultBranchCache, cacheKey);
1564 yield* Cache.invalidate(originExistsCache, cacheKey);
1565 },
@@ -3943,17 +3951,21 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3951 });
3952 const invalidateListRefsSnapshot = Effect.fn("invalidateListRefsSnapshot")(function* (
3953 cwd: string,
3954 + gitCommonDir?: string | null,
3955 ) {
3956 const repositoryPathsCacheKey = normalizeRepositoryPathsCacheKey(cwd);
3948 - const repositoryPaths = yield* Cache.get(repositoryPathsCache, repositoryPathsCacheKey);
3949 - if (repositoryPaths === null) return;
3950 - const previousGeneration = currentListRefsGeneration(repositoryPaths.gitCommonDir);
3951 - bumpListRefsGeneration(repositoryPaths.gitCommonDir);
3952 - bumpListRefsEpoch(repositoryPaths.gitCommonDir);
3957 + const commonDir =
3958 + gitCommonDir === undefined
3959 + ? (yield* Cache.get(repositoryPathsCache, repositoryPathsCacheKey))?.gitCommonDir
3960 + : gitCommonDir;
3961 + if (commonDir == null) return;
3962 + const previousGeneration = currentListRefsGeneration(commonDir);
3963 + bumpListRefsGeneration(commonDir);
3964 + bumpListRefsEpoch(commonDir);
3965 yield* Cache.invalidate(
3966 listRefsRefreshSnapshotCache,
3967 new GitRefsRefreshCacheKey({
3956 - gitCommonDir: repositoryPaths.gitCommonDir,
3968 + gitCommonDir: commonDir,
3969 generation: previousGeneration,
3970 }),
3971 );
@@ -4824,6 +4836,26 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4836 ]),
4837 ),
4838 );
4839 + const invalidateWorktreeCreationCaches = Effect.fn(
4840 + "GitVcsDriverCore.invalidateWorktreeCreationCaches",
4841 + )(function* (cwd: string) {
4842 + let gitCommonDir = yield* readGitCommonDir(cwd).pipe(
4843 + Effect.catchTags({ GitCommandError: () => Effect.succeed(null) }),
4844 + );
4845 + if (gitCommonDir === null) {
4846 + gitCommonDir = yield* Cache.getOption(
4847 + repositoryPathsCache,
4848 + normalizeRepositoryPathsCacheKey(cwd),
4849 + ).pipe(
4850 + Effect.map((cached) => Option.getOrNull(cached)?.gitCommonDir ?? null),
4851 + Effect.orElseSucceed(() => null),
4852 + );
4853 + }
4854 + yield* Effect.all([
4855 + invalidateListRefsSnapshot(cwd, gitCommonDir).pipe(Effect.ignore),
4856 + invalidateStatusStaticCaches(cwd, gitCommonDir).pipe(Effect.ignore),
4857 + ]);
4858 + });
4859 const initRepoWithListRefsInvalidation: GitVcsDriver.GitVcsDriver["Service"]["initRepo"] = (
4860 input,
4861 ) =>
@@ -4864,7 +4896,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4896 resolveBranchName,
4897 listRefs,
4898 createWorktree: Effect.fnUntraced(function* (input, options) {
4867 - return yield* withListRefsInvalidation(input.cwd, createWorktree(input, options));
4899 + return yield* createWorktree(input, options).pipe(
4900 + Effect.ensuring(invalidateWorktreeCreationCaches(input.cwd)),
4901 + );
4902 }),
4903 fetchRefIntoBranch: Effect.fnUntraced(function* (input) {
4904 return yield* withListRefsInvalidation(input.cwd, fetchRefIntoBranch(input));