Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): bound Windows repository cache paths (MUL-9367) (#10702)
Bohan Jiang2096bd38aef6
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 23d4d19582..9d5deeb4af 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -783,16 +783,15 @@ jobs:# objects are private copies rather than NTFS hard links sharing one# file and one security descriptor with the daemon-owned cache. The# cross-volume test covers what a hard link cannot express at all.- # Scoped to the two windows-tagged tests by exact name. A prefix match- # also caught the package's cross-platform isolated-checkout test,- # which cannot run here: repocache derives a cache directory name from- # the full source repo path, so a t.TempDir() path that already embeds- # a long test name doubles and blows past MAX_PATH. That test belongs- # to the ubuntu backend job, which runs the whole package.+ # Exact names keep unrelated package tests out of this Windows check.# -v so a skip (single-volume runner) is visible instead of passing# silently as "ok".run: go test ./internal/daemon/repocache -v -run '^(TestIsolatedCheckoutIsCommittableOnWindows|TestIsolatedCheckoutAcrossVolumesOnWindows)$' -count=1 -timeout=5m+ - name: Test Windows long repository URL checkout and cache upgrade+ working-directory: server+ run: go test ./internal/daemon/repocache -v -run '^(TestCheckoutLongRepoURL|TestMigrateUnusedLegacyCache|TestMigrationDoesNotOverwriteExistingDestination|TestMigrationKeepsLockedWorktree|TestMigrationFailureKeepsUsableLegacyCache|TestMigrationFailureRespectsCancellation|TestCreateWorktreeFailureDoesNotLeakBranch)$' -count=1 -timeout=5m+- name: Test Windows directory-junction link safetyworking-directory: server# MUL-6000: the per-task codex-home links the user's real skills intodiff --git a/apps/docs/content/docs/daemon-runtimes.fr.mdx b/apps/docs/content/docs/daemon-runtimes.fr.mdxindex 2dd496ace5..bf5e1daa55 100644--- a/apps/docs/content/docs/daemon-runtimes.fr.mdx+++ b/apps/docs/content/docs/daemon-runtimes.fr.mdx@@ -155,6 +155,8 @@ Le daemon ne supprime jamais le répertoire local du projet. Le répertoire de sLe daemon garde un cache de dépôt nu par dépôt de l'espace de travail, sous `.repos/<id-espace-de-travail>/` dans la racine des espaces de travail. Les exécutions du même espace de travail sur cette machine le partagent : chaque checkout crée un git worktree à partir du cache et ne récupère que les nouveaux commits, sans recloner. Les exécutions Codex sous Linux et Windows font exception et reçoivent un clone autonome avec `.git` dans le répertoire de travail, car le bac à sable workspace-write de Codex laisse en lecture seule les métadonnées Git situées hors du répertoire de travail.+Les nouveaux noms de répertoire de cache utilisent jusqu'à 16 caractères ASCII du nom du dépôt et un hachage de 12 caractères, pour qu'une longue URL distante n'allonge pas les chemins des métadonnées Git sous Windows. Lors d'une synchronisation ou d'un checkout, un cache existant passe au nom court si aucun worktree enregistré ne reste après nettoyage des entrées obsolètes et si la destination n'existe pas. Son contenu est conservé sans nouveau clonage. Les caches avec des worktrees enregistrés gardent leur chemin d'origine afin de préserver les checkouts liés. Si la migration échoue, le daemon enregistre un avertissement et continue d'utiliser le cache existant ; une opération ultérieure pourra réessayer.+Un cache n'est supprimé que si les trois conditions sont réunies : aucun espace de travail ni projet ne référence plus le dépôt, aucun worktree ne subsiste, et aucune exécution n'en a fait de checkout depuis 30 jours. Il est recloné au besoin. Après avoir supprimé les branches d'agent périmées, le daemon exécute `git reflog expire --expire=30.days --all` et `git gc --prune=30.days` sur le cache quand aucune exécution n'est en cours.### Sessions, mémoire et répertoires temporairesdiff --git a/apps/docs/content/docs/daemon-runtimes.ja.mdx b/apps/docs/content/docs/daemon-runtimes.ja.mdxindex 2b7054dc65..d52c4680f5 100644--- a/apps/docs/content/docs/daemon-runtimes.ja.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ja.mdx@@ -155,6 +155,8 @@ Multica が管理する作業ディレクトリを使う未アーカイブのチデーモンはワークスペースのリポジトリごとにベアリポジトリのキャッシュを 1 つ持ちます。場所は作業ディレクトリのルート下の `.repos/<ワークスペース ID>/` です。このコンピューター上の同じワークスペースの実行はこれを共有し、チェックアウトのたびにキャッシュから git worktree を作り、新しいコミットだけを取得します。再クローンはしません。例外は Linux と Windows の Codex 実行で、作業ディレクトリ内に `.git` を持つ独立したクローンを受け取ります。Codex の workspace-write サンドボックスでは、作業ディレクトリ外の Git メタデータが読み取り専用になるためです。+新しいキャッシュのディレクトリ名には、リポジトリ名から最大 16 個の ASCII 文字と 12 桁のハッシュを使います。長いリモート URL でも Windows 上の Git メタデータのパスが長くならないようにするためです。同期またはチェックアウト時に古い登録情報を整理し、登録済み worktree が残っておらず、移動先が存在しなければ、既存のキャッシュを短い名前に移動します。内容は保持され、再クローンは不要です。登録済み worktree があるキャッシュは、リンク済みチェックアウトを維持するため元のパスを使い続けます。移動に失敗した場合は警告を記録して既存のキャッシュを使い続け、次回以降に再試行します。+キャッシュが削除されるのは、どのワークスペースやプロジェクトからもリポジトリが参照されず、worktree が残っておらず、30 日間どの実行もそこからチェックアウトしていない、という 3 つがそろったときだけです。必要になれば再びクローンされます。古いエージェントブランチを消したあと、デーモンは実行中の実行がないときにキャッシュに対して `git reflog expire --expire=30.days --all` と `git gc --prune=30.days` を実行します。### セッション、メモリ、一時ディレクトリdiff --git a/apps/docs/content/docs/daemon-runtimes.ko.mdx b/apps/docs/content/docs/daemon-runtimes.ko.mdxindex 208b716e1c..700468c168 100644--- a/apps/docs/content/docs/daemon-runtimes.ko.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ko.mdx@@ -155,6 +155,8 @@ CodeBuddy, Kimi CLI, Pi는 시작할 때 사용자 수준 설정을 직접 읽데몬은 워크스페이스 저장소마다 bare 저장소 캐시를 하나 둡니다. 위치는 작업 디렉터리 루트 아래의 `.repos/<워크스페이스 ID>/`입니다. 이 컴퓨터에서 같은 워크스페이스의 실행은 이 캐시를 함께 쓰며, 체크아웃할 때마다 캐시에서 git worktree를 만들고 새 커밋만 가져옵니다. 다시 클론하지 않습니다. 예외는 Linux와 Windows의 Codex 실행으로, 작업 디렉터리 안에 `.git`이 있는 독립 클론을 받습니다. Codex의 workspace-write 샌드박스에서는 작업 디렉터리 밖의 Git 메타데이터가 읽기 전용이기 때문입니다.+새 캐시 디렉터리 이름은 저장소 이름에서 최대 16개의 ASCII 문자와 12자리 해시를 사용하므로, 긴 원격 URL이 Windows의 Git 메타데이터 경로를 늘리지 않습니다. 동기화나 체크아웃 시 오래된 등록 정보를 정리한 뒤 등록된 worktree가 없고 대상 디렉터리도 없으면 기존 캐시를 짧은 이름으로 옮깁니다. 내용은 보존되며 다시 클론하지 않습니다. 등록된 worktree가 있는 캐시는 연결된 체크아웃이 계속 작동하도록 원래 경로를 유지합니다. 이동에 실패하면 경고를 기록하고 기존 캐시를 계속 사용하며, 이후 작업에서 다시 시도할 수 있습니다.+캐시는 세 가지가 모두 충족될 때만 삭제됩니다. 어떤 워크스페이스나 프로젝트도 이 저장소를 참조하지 않고, 남은 worktree가 없고, 30일 동안 어떤 실행도 이 캐시에서 체크아웃하지 않았을 때입니다. 필요하면 다시 클론됩니다. 오래된 에이전트 브랜치를 지운 뒤에는 진행 중인 실행이 없을 때 캐시에 `git reflog expire --expire=30.days --all`과 `git gc --prune=30.days`를 실행합니다.### 세션, 메모리, 임시 디렉터리diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdxindex efb27af355..c13751701b 100644--- a/apps/docs/content/docs/daemon-runtimes.mdx+++ b/apps/docs/content/docs/daemon-runtimes.mdx@@ -155,6 +155,8 @@ A run on a project's local directory works in your own directory, which the daemThe daemon keeps one bare-repository cache per workspace repository, under `.repos/<workspace-id>/` in the workspaces root. Runs of the same workspace on this computer share it: each checkout creates a git worktree from the cache and only fetches new commits instead of cloning again. Codex runs on Linux and Windows are the exception and get a standalone clone with `.git` inside the work directory, because Codex's workspace-write sandbox leaves Git metadata outside the work directory read-only.+New cache directory names use up to 16 ASCII characters from the repository name plus a 12-character hash, keeping long remote URLs from lengthening Git's metadata paths on Windows. During sync or checkout, an existing cache moves to the short name if no registered worktrees remain after pruning stale entries and the destination does not exist. Its contents are preserved without cloning again. Caches with registered worktrees keep their original paths so linked checkouts continue working. If migration fails, the daemon logs a warning and continues using the existing cache; a later attempt can retry.+A cache is removed only when all three hold: no workspace or project references the repository any more, no worktrees remain, and no run has checked out from it for 30 days. It is cloned again when needed. After removing stale agent branches, the daemon runs `git reflog expire --expire=30.days --all` and `git gc --prune=30.days` on the cache while no runs are executing.### Sessions, memory, and temporary directoriesdiff --git a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdxindex 5494b2bcdd..c2b9c6b621 100644--- a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx@@ -156,6 +156,8 @@ CodeBuddy、Kimi CLI 和 Pi 啟動時會自己載入使用者級配置,並與守護程序為每個工作區的倉庫保留一份裸倉庫快取,位置在工作目錄根目錄下的 `.repos/<工作區 ID>/`。這臺電腦上同一工作區的執行共用這份快取:每次檢出從快取建立 git worktree,只拉取新提交,不重新克隆。Linux 和 Windows 上的 Codex 執行例外,會從快取得到一份 `.git` 在工作目錄內的獨立克隆,因為在 Codex 的 workspace-write 沙箱下,工作目錄外的 Git 後設資料是只讀的。+新快取目錄名稱採用倉庫名稱中最多 16 個 ASCII 字元加 12 位雜湊,避免過長的遠端位址拉長 Windows 上的 Git 後設資料路徑。同步或檢出時,既有快取若在清理失效記錄後沒有已註冊的 worktree,且目標目錄不存在,就會遷移至短名稱,保留全部內容,無須重新克隆。仍有 worktree 註冊的快取保留原路徑,確保關聯檢出繼續可用。遷移失敗時,守護程序會記錄警告並繼續使用既有快取,後續操作可重試遷移。+快取在三個條件同時滿足時刪除:已經沒有工作區或專案引用這個倉庫,沒有剩餘 worktree,並且 30 天內沒有執行從它檢出。之後需要時會重新克隆。清理刪掉過期的 AI 代理分支後,守護程序會在沒有執行執行時對快取執行 `git reflog expire --expire=30.days --all` 和 `git gc --prune=30.days`。### 會話、記憶與臨時目錄diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdxindex d68a8c19ec..bbe0009305 100644--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx@@ -156,6 +156,8 @@ CodeBuddy、Kimi CLI 和 Pi 启动时会自己加载用户级配置,并与 Mul守护进程为每个工作区的仓库保留一份裸仓库缓存,位置在工作目录根目录下的 `.repos/<工作区 ID>/`。这台电脑上同一工作区的运行共用这份缓存:每次检出从缓存创建 git worktree,只拉取新提交,不重新克隆。Linux 和 Windows 上的 Codex 运行例外,会从缓存得到一份 `.git` 在工作目录内的独立克隆,因为在 Codex 的 workspace-write 沙箱下,工作目录外的 Git 元数据是只读的。+新缓存目录名采用仓库名中最多 16 个 ASCII 字符加 12 位哈希,避免长远端地址拉长 Windows 上的 Git 元数据路径。同步或检出时,已有缓存若在清理失效记录后没有已注册的 worktree,且目标目录不存在,就会迁移到短名称,保留全部内容,无需重新克隆。仍有 worktree 注册的缓存保留原路径,确保关联检出继续可用。迁移失败时,守护进程会记录警告并继续使用已有缓存,后续操作可重试迁移。+缓存在三个条件同时满足时删除:已经没有工作区或项目引用这个仓库,没有剩余 worktree,并且 30 天内没有运行从它检出。之后需要时会重新克隆。清理删掉过期的智能体分支后,守护进程会在没有运行执行时对缓存运行 `git reflog expire --expire=30.days --all` 和 `git gc --prune=30.days`。### 会话、记忆与临时目录diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 6813770245..2dcb051c4f 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -3398,13 +3398,18 @@ func (d *Daemon) repoBarePathIsLive(barePath string) bool {d.mu.Lock()defer d.mu.Unlock()for workspaceID, ws := range d.workspaces {+ matches := func(url string) bool {+ path := d.repoCache.BarePath(workspaceID, url)+ return filepath.Dir(path) == filepath.Dir(barePath) &&+ repocache.BareDirMatchesURL(filepath.Base(barePath), url)+ }for url := range ws.allowedRepoURLs {- if d.repoCache.BarePath(workspaceID, url) == barePath {+ if matches(url) {return true}}for url := range ws.taskRepoURLs {- if d.repoCache.BarePath(workspaceID, url) == barePath {+ if matches(url) {return true}}diff --git a/server/internal/daemon/gc_repo_evict_test.go b/server/internal/daemon/gc_repo_evict_test.goindex 45bd92352d..9d70cabd67 100644--- a/server/internal/daemon/gc_repo_evict_test.go+++ b/server/internal/daemon/gc_repo_evict_test.go@@ -10,6 +10,43 @@ import (const testRepoURL = "https://example.com/acme/widgets.git"+func TestEvictRepoCachePreservesBothCacheNames(t *testing.T) {+ t.Parallel()+ d := newGCTestDaemon(t, http.NewServeMux())+ d.cfg.GCRepoTTL = 24 * time.Hour+ const wsID = "11111111-1111-1111-1111-111111111111"+ shortPath := newEvictTestRepo(t, d, wsID, testRepoURL)+ legacyPath := filepath.Join(filepath.Dir(shortPath), "example.com+acme+widgets.git")+ runGitForGC(t, "", "clone", "--bare", shortPath, legacyPath)+ for _, path := range []string{shortPath, legacyPath} {+ writeLastUsed(t, path, time.Now().Add(-48*time.Hour))+ }+ for _, taskRepo := range []bool{false, true} {+ attachRepo(d, wsID, testRepoURL)+ if taskRepo {+ d.mu.Lock()+ d.workspaces[wsID].allowedRepoURLs = nil+ d.workspaces[wsID].taskRepoURLs = map[string]struct{}{testRepoURL: {}}+ d.mu.Unlock()+ }+ for _, path := range []string{shortPath, legacyPath} {+ if !d.repoBarePathIsLive(path) {+ t.Fatalf("attached cache is not live (task repo=%t): %s", taskRepo, path)+ }+ foreignRoot := filepath.Join(t.TempDir(), wsID, filepath.Base(path))+ if d.repoBarePathIsLive(foreignRoot) {+ t.Fatalf("cache outside this daemon's root is live: %s", foreignRoot)+ }+ }+ runRepoGC(d)+ for _, path := range []string{shortPath, legacyPath} {+ if _, err := os.Stat(filepath.Join(path, "HEAD")); err != nil {+ t.Fatalf("attached cache was evicted: %s: %v", path, err)+ }+ }+ }+}+// newEvictTestRepo clones a bare repo into the exact cache path the daemon// would use for repoURL, so the live-set lookup (which is keyed on that path)// lines up with what is on disk.diff --git a/server/internal/daemon/repocache/cache.go b/server/internal/daemon/repocache/cache.goindex c12f66ef2f..b58c18686a 100644--- a/server/internal/daemon/repocache/cache.go+++ b/server/internal/daemon/repocache/cache.go@@ -4,6 +4,7 @@ package repocacheimport ("context"+ "crypto/sha256""errors""fmt""log/slog"@@ -171,8 +172,9 @@ type CachedRepo struct {// Cache manages bare git clones for workspace repositories.type Cache struct {- root string // base directory for all caches (e.g. ~/multica_workspaces/.repos)- logger *slog.Logger+ root string // base directory for all caches (e.g. ~/multica_workspaces/.repos)+ logger *slog.Logger+ renameCache func(string, string) error// repoLocks maps bare repo path → dedicated mutex. Any mutating operation// on a given bare repo (clone, fetch, worktree add, ref update) must// hold its lock — git's own lockfiles (packed-refs.lock, config.lock,@@ -312,7 +314,7 @@ func (l *repoLock) cancelMaintenanceAndWait() {// New creates a new repo cache rooted at the given directory.func New(root string, logger *slog.Logger) *Cache {- return &Cache{root: root, logger: logger}+ return &Cache{root: root, logger: logger, renameCache: os.Rename}}// lockForRepo returns the mutex dedicated to the given bare repo path. See@@ -326,6 +328,30 @@ func (c *Cache) lockForRepo(barePath string) *repoLock {return actual.(*repoLock)}+// URL-based operations hold both path locks, always short then legacy. This+// serializes a rename with callers already waiting on either path and with+// GC, whose maintenance callbacks lock the directory they found on disk.+func (c *Cache) lockRepoURLContext(ctx context.Context, workspaceID, repoURL string) (func(), error) {+ shortPath := filepath.Join(c.root, workspaceID, bareDirName(repoURL))+ legacyPath := filepath.Join(c.root, workspaceID, legacyBareDirName(repoURL))+ shortLock := c.lockForRepo(shortPath)+ if err := shortLock.LockContext(ctx); err != nil {+ return nil, err+ }+ if shortPath == legacyPath {+ return shortLock.Unlock, nil+ }+ legacyLock := c.lockForRepo(legacyPath)+ if err := legacyLock.LockContext(ctx); err != nil {+ shortLock.Unlock()+ return nil, err+ }+ return func() {+ legacyLock.Unlock()+ shortLock.Unlock()+ }, nil+}+// Activity reports aggregate repository coordination without exposing cache// paths. It is safe to call while operations are starting or finishing.func (c *Cache) Activity() Activity {@@ -382,12 +408,18 @@ func (c *Cache) SyncContext(ctx context.Context, workspaceID string, repos []Repif repo.URL == "" {continue}- barePath := filepath.Join(wsDir, bareDirName(repo.URL))-- repoLock := c.lockForRepo(barePath)- if err := repoLock.LockContext(ctx); err != nil {+ unlock, err := c.lockRepoURLContext(ctx, workspaceID, repo.URL)+ if err != nil {return err}+ barePath, err := c.prepareBarePathContext(ctx, workspaceID, repo.URL)+ if err != nil {+ unlock()+ if firstErr == nil {+ firstErr = err+ }+ continue+ }if isBareRepo(barePath) {// Already cached — fetch latest.c.logger.Info("repo cache: fetching", "url", repo.URL, "path", barePath)@@ -408,7 +440,7 @@ func (c *Cache) SyncContext(ctx context.Context, workspaceID string, repos []Rep}}}- repoLock.Unlock()+ unlock()}return firstErr}@@ -428,9 +460,61 @@ func (c *Cache) Lookup(workspaceID, url string) string {// question, which the GC needs to map a set of live repo URLs onto the// directories it is about to consider evicting.func (c *Cache) BarePath(workspaceID, url string) string {+ // Existing worktrees contain absolute pointers into the legacy cache.+ // Reuse it in place so upgrades never break running tasks.+ legacyPath := filepath.Join(c.root, workspaceID, legacyBareDirName(url))+ if isBareRepo(legacyPath) {+ return legacyPath+ }return filepath.Join(c.root, workspaceID, bareDirName(url))}+// prepareBarePathContext must run with both URL path locks held. Resolve the+// path after taking the locks: another caller may have migrated it while we+// waited. Registered worktrees contain absolute pointers into their cache,+// so only an unused cache can be renamed, and an existing destination wins.+// Migration is best-effort; failures must not block a usable legacy cache.+func (c *Cache) prepareBarePathContext(ctx context.Context, workspaceID, repoURL string) (string, error) {+ if err := ctx.Err(); err != nil {+ return "", context.Cause(ctx)+ }+ path := c.BarePath(workspaceID, repoURL)+ shortPath := filepath.Join(c.root, workspaceID, bareDirName(repoURL))+ if path == shortPath {+ return path, nil+ }+ keepLegacy := func(err error) (string, error) {+ if ctx.Err() != nil {+ return "", context.Cause(ctx)+ }+ c.logger.Warn("repo cache: migration deferred; continuing with legacy cache", "path", path, "error", err)+ return path, nil+ }+ if _, err := os.Lstat(shortPath); err == nil {+ return path, nil+ } else if !os.IsNotExist(err) {+ return keepLegacy(fmt.Errorf("inspect short cache path: %w", err))+ }+ if out, err := runGitCombinedOutputContext(ctx, "-C", path, "worktree", "prune", "--expire=now"); err != nil {+ return keepLegacy(fmt.Errorf("prune worktrees before cache migration: %s: %w", strings.TrimSpace(string(out)), err))+ }+ entries, err := os.ReadDir(filepath.Join(path, "worktrees"))+ if err != nil && !os.IsNotExist(err) {+ return keepLegacy(fmt.Errorf("inspect worktrees before cache migration: %w", err))+ }+ if len(entries) != 0 {+ return path, nil+ }+ if err := ctx.Err(); err != nil {+ return "", context.Cause(ctx)+ }+ if err := c.renameCache(path, shortPath); err != nil {+ return keepLegacy(fmt.Errorf("migrate unused repo cache from %s to %s: %w", path, shortPath, err))+ }+ c.logger.Info("repo cache: shortened unused legacy cache path", "old_path", path, "path", shortPath)+ return shortPath, nil+}+// lastUsedFile records the last time a task asked for a worktree from this// bare repo. It lives inside the bare repo so it is removed with it.//@@ -514,8 +598,38 @@ func (c *Cache) Fetch(barePath string) error {})}-// bareDirName returns a filesystem-safe, collision-free directory name for-// the bare clone of rawURL. The name is built from the host plus each+// bareDirName bounds the cache name to 33 ASCII bytes, leaving room for+// Git's worktree administration files on Windows. Hash the legacy identity+// so equivalent HTTPS and SSH URLs still share one cache on every platform.+func bareDirName(rawURL string) string {+ identity := legacyBareDirName(rawURL)+ hash := sha256.Sum256([]byte(identity))+ name := strings.TrimSuffix(identity, ".git")+ name = name[strings.LastIndex(name, "+")+1:]+ name = strings.Map(func(ch rune) rune {+ if ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9' || ch == '-' || ch == '_' {+ return ch+ }+ return '-'+ }, name)+ if len(name) > 16 {+ name = name[:16]+ }+ if name = strings.Trim(name, "-"); name == "" {+ name = "repo"+ }+ return fmt.Sprintf("%s-%x.git", name, hash[:6])+}++// BareDirMatchesURL recognizes both cache naming schemes without requiring+// either directory to exist. GC must protect both if old and new daemons+// have populated caches for the same repository.+func BareDirMatchesURL(dirName, repoURL string) bool {+ return repoURL != "" && (dirName == bareDirName(repoURL) || dirName == legacyBareDirName(repoURL))+}++// legacyBareDirName preserves the identity and on-disk names used before+// bounded cache names. The name is built from the host plus each// path segment, joined by '+'. '+' is disallowed in GitHub and GitLab// path segments, so two URLs produce the same name only if they point at// the same repository on the same host.@@ -531,7 +645,7 @@ func (c *Cache) Fetch(barePath string) error {// ssh://[email protected]:22/g/s/r.git -> gitlab.example.com%3A22+g+s+r.git// [email protected]:org/repo.git -> gitlab.example.com-22+org+repo.git// my-repo -> my-repo.git (bare name fallback)-func bareDirName(rawURL string) string {+func legacyBareDirName(rawURL string) string {rawURL = strings.TrimRight(rawURL, "/")host, path := splitHostAndPath(rawURL)@@ -802,21 +916,15 @@ func (c *Cache) CreateWorktree(params WorktreeParams) (*WorktreeResult, error) {// lock is held, so a client that times out behind maintenance cannot leave a// late, unwanted checkout.func (c *Cache) CreateWorktreeContext(ctx context.Context, params WorktreeParams) (*WorktreeResult, error) {- barePath := c.Lookup(params.WorkspaceID, params.RepoURL)- if barePath == "" {- return nil, fmt.Errorf("repo not found in cache: %s (workspace: %s)", params.RepoURL, params.WorkspaceID)- }-// Serialize concurrent CreateWorktree calls on the same bare repo. Git's// own lockfiles (packed-refs.lock, config.lock, worktree admin dirs)// can't tolerate parallel fetch + worktree mutations on the same repo.- repoLock := c.lockForRepo(barePath)lockCtx := ctxcancel := func() {}if params.LockWaitTimeout > 0 {lockCtx, cancel = context.WithTimeout(ctx, params.LockWaitTimeout)}- err := repoLock.LockContext(lockCtx)+ unlock, err := c.lockRepoURLContext(lockCtx, params.WorkspaceID, params.RepoURL)cancel()if err != nil {if ctx.Err() == nil && errors.Is(err, context.DeadlineExceeded) {@@ -824,10 +932,17 @@ func (c *Cache) CreateWorktreeContext(ctx context.Context, params WorktreeParams}return nil, err}- defer repoLock.Unlock()+ defer unlock()if err := ctx.Err(); err != nil {return nil, context.Cause(ctx)}+ barePath, err := c.prepareBarePathContext(ctx, params.WorkspaceID, params.RepoURL)+ if err != nil {+ return nil, err+ }+ if !isBareRepo(barePath) {+ return nil, fmt.Errorf("repo not found in cache: %s (workspace: %s)", params.RepoURL, params.WorkspaceID)+ }// Stamp before doing the work, not after: a task asking for a worktree is// what "this cache is still wanted" means, whether or not the checkout@@ -1168,7 +1283,7 @@ func isolatedCheckoutOriginContext(ctx context.Context, path string) (string, er// barePath. Caches are keyed by bareDirName, so URL spellings that share a// cache count as the same repository.func isolatedOriginCachedAt(origin, barePath string) bool {- return origin != "" && bareDirName(origin) == filepath.Base(barePath)+ return BareDirMatchesURL(filepath.Base(barePath), origin)}func linkedWorktreeCommonDirContext(ctx context.Context, checkoutPath string) (string, error) {@@ -1489,27 +1604,61 @@ func createWorktreeContext(ctx context.Context, gitRoot, worktreePath, branchNamreturn "", fmt.Errorf("worktree path already exists and is not a valid git worktree: %s", worktreePath)}- err := runWorktreeAddContext(ctx, gitRoot, worktreePath, branchName, baseRef)+ branchExisted, err := worktreeBranchExistsContext(ctx, gitRoot, branchName)+ if err != nil {+ return "", err+ }+ err = runWorktreeAddContext(ctx, gitRoot, worktreePath, branchName, baseRef)if err != nil && isBranchCollisionError(err) {// Branch name collision: append timestamp and retry once.branchName = fmt.Sprintf("%s-%d", branchName, time.Now().Unix())+ branchExisted, err = worktreeBranchExistsContext(ctx, gitRoot, branchName)+ if err != nil {+ return "", err+ }err = runWorktreeAddContext(ctx, gitRoot, worktreePath, branchName, baseRef)}if err != nil {// A cancelled git is killed before it can clean up, and the leftover// tree would otherwise be reused by every later checkout of this- // workdir. Any other failure leaves the path alone: the pre-check only- // holds under this repo's lock, and a repo from another cache with the- // same basename may have created the path since (see- // createIsolatedCheckoutContext).+ // workdir. For ordinary failures, remove only a checkout whose+ // registration proves it belongs to this cache and path: another cache+ // with the same basename may have created the path since the pre-check.if ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {removePartialWorktree(gitRoot, worktreePath)+ } else if adminDir, ok := worktreeAdminDir(worktreePath); ok && samePath(filepath.Dir(adminDir), filepath.Join(gitRoot, "worktrees")) {+ if owner, ok := worktreeRegistrationOwner(adminDir); ok && samePath(owner, worktreePath) {+ removePartialWorktree(gitRoot, worktreePath)+ }+ }+ // worktree add -b can create its branch before failing. Never delete a+ // pre-existing branch, including a collision on the timestamp retry.+ // Use a fresh, bounded context so cancellation cannot skip rollback.+ if !branchExisted {+ _ = runGitWithTimeoutContext(context.Background(), 5*time.Second, "-C", gitRoot, "branch", "-D", branchName)}return "", err}return branchName, nil}+// A failed/cancelled probe is not evidence that a branch was absent: rollback+// must never delete an existing branch because Git could not inspect it.+func worktreeBranchExistsContext(ctx context.Context, gitRoot, branchName string) (bool, error) {+ err := runGitContext(ctx, "-C", gitRoot, "show-ref", "--verify", "--quiet", "refs/heads/"+branchName)+ if err == nil {+ return true, nil+ }+ if ctx.Err() != nil {+ return false, context.Cause(ctx)+ }+ var exitErr *exec.ExitError+ if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 {+ return false, nil+ }+ return false, fmt.Errorf("inspect worktree branch: %w", err)+}+// removePartialWorktree removes a checkout a cancelled `git worktree add` left// behind, with its registration in gitRoot. A tree whose .git file points into// another bare cache belongs to someone else and is kept.diff --git a/server/internal/daemon/repocache/cache_migration_test.go b/server/internal/daemon/repocache/cache_migration_test.gonew file mode 100644index 0000000000..43eb37d161--- /dev/null+++ b/server/internal/daemon/repocache/cache_migration_test.go@@ -0,0 +1,328 @@+package repocache++import (+ "context"+ "errors"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++const migrationRepoURL = "http://tfs.example.internal:8080/tfs/engineering-collection/engineering-project/_git/enterprise-repository-client"+const migrationWorkspaceID = "11111111-1111-1111-1111-111111111111"++func seedLegacyEnterpriseCache(t *testing.T) (*Cache, string, string) {+ t.Helper()+ return seedLegacyCache(t, migrationRepoURL)+}++func seedLegacyCache(t *testing.T, repoURL string) (*Cache, string, string) {+ t.Helper()+ source := createTestRepo(t)+ root, err := os.MkdirTemp("", "mc-")+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = os.RemoveAll(root) })+ workspacesRoot := filepath.Join(root, strings.Repeat("w", max(1, 65-len(root)-1)))+ cache := New(filepath.Join(workspacesRoot, ".repos"), testLogger())+ legacyPath := filepath.Join(cache.root, migrationWorkspaceID, legacyBareDirName(repoURL))+ if err := os.MkdirAll(filepath.Dir(legacyPath), 0o755); err != nil {+ t.Fatal(err)+ }+ // Reported installations enable core.longpaths. Allow the fixture to+ // write loose objects at the old path before testing Git's separate+ // worktree metadata limits. Keep all origin traffic local.+ if out, err := runGitCombinedOutput("-c", "core.longpaths=true", "clone", "--bare", "--config", "core.longpaths=true", source, legacyPath); err != nil {+ t.Fatalf("seed legacy cache: %s: %v", out, err)+ }+ if err := ensureRemoteTrackingLayout(legacyPath); err != nil {+ t.Fatal(err)+ }+ return cache, legacyPath, filepath.Join(root, "workdir")+}++func assertWorktreeCache(t *testing.T, worktreePath, barePath string) string {+ t.Helper()+ admin := worktreeRegistration(t, worktreePath)+ actual, err := os.Stat(filepath.Dir(admin))+ if err != nil {+ t.Fatal(err)+ }+ expected, err := os.Stat(filepath.Join(barePath, "worktrees"))+ if err != nil {+ t.Fatal(err)+ }+ // Git may expand a Windows 8.3 temp path to its long spelling. Compare+ // directory identity so aliases still require the exact expected cache.+ if !os.SameFile(actual, expected) {+ t.Fatalf("worktree registration %s does not belong to cache %s", admin, barePath)+ }+ return admin+}++func TestMigrationFailureKeepsUsableLegacyCache(t *testing.T) {+ t.Parallel()+ for _, onSync := range []bool{false, true} {+ name := "checkout"+ if onSync {+ name = "sync"+ }+ t.Run(name, func(t *testing.T) {+ const repoURL = "https://github.com/org/repo.git"+ cache, legacyPath, workDir := seedLegacyCache(t, repoURL)+ attempted := false+ cache.renameCache = func(string, string) error {+ attempted = true+ return os.ErrPermission+ }+ if onSync {+ if err := cache.Sync(migrationWorkspaceID, []RepoInfo{{URL: repoURL}}); err != nil {+ t.Fatalf("usable legacy cache failed sync after rename denial: %v", err)+ }+ }+ result, err := cache.CreateWorktree(WorktreeParams{+ WorkspaceID: migrationWorkspaceID,+ RepoURL: repoURL,+ WorkDir: workDir,+ AgentName: "test",+ TaskID: "12345678-0000-0000-0000-000000000000",+ })+ if err != nil {+ t.Fatalf("usable legacy cache failed checkout after rename denial: %v", err)+ }+ if !attempted || cache.Lookup(migrationWorkspaceID, repoURL) != legacyPath {+ t.Fatal("rename denial did not retain the legacy cache")+ }+ assertWorktreeCache(t, result.Path, legacyPath)+ if got, want := gitHead(t, result.Path), gitRefCommit(t, legacyPath, getRemoteDefaultBranch(legacyPath)); got != want {+ t.Fatalf("checkout has %s, want %s", got, want)+ }+ cache.renameCache = os.Rename+ if err := runGit("-C", legacyPath, "worktree", "remove", "--force", result.Path); err != nil {+ t.Fatal(err)+ }+ if err := cache.Sync(migrationWorkspaceID, []RepoInfo{{URL: repoURL}}); err != nil {+ t.Fatalf("migration retry failed: %v", err)+ }+ shortPath := filepath.Join(cache.root, migrationWorkspaceID, bareDirName(repoURL))+ if got := cache.Lookup(migrationWorkspaceID, repoURL); got != shortPath {+ t.Fatalf("migration retry used %s, want %s", got, shortPath)+ }+ })+ }+}++func TestMigrationFailureRespectsCancellation(t *testing.T) {+ t.Parallel()+ const repoURL = "https://github.com/org/repo.git"+ cache, legacyPath, workDir := seedLegacyCache(t, repoURL)+ ctx, cancel := context.WithCancel(t.Context())+ defer cancel()+ cache.renameCache = func(string, string) error {+ cancel()+ return os.ErrPermission+ }+ _, err := cache.CreateWorktreeContext(ctx, WorktreeParams{+ WorkspaceID: migrationWorkspaceID,+ RepoURL: repoURL,+ WorkDir: workDir,+ })+ if !errors.Is(err, context.Canceled) {+ t.Fatalf("checkout error = %v, want cancellation", err)+ }+ if got := cache.Lookup(migrationWorkspaceID, repoURL); got != legacyPath {+ t.Fatalf("cancelled migration changed the cache path: %s", got)+ }+ if _, err := os.Stat(filepath.Join(workDir, "repo")); !os.IsNotExist(err) {+ t.Fatalf("cancelled migration started a checkout: %v", err)+ }+}++func TestMigrateUnusedLegacyCache(t *testing.T) {+ t.Parallel()+ for _, onSync := range []bool{false, true} {+ name := "checkout"+ if onSync {+ name = "sync"+ }+ t.Run(name, func(t *testing.T) {+ cache, legacyPath, workDir := seedLegacyEnterpriseCache(t)+ baseRef := getRemoteDefaultBranch(legacyPath)+ commit := gitRefCommit(t, legacyPath, baseRef)+ if err := runGit("-C", legacyPath, "branch", "retained", baseRef); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(legacyPath, "retained.txt"), []byte("keep cache contents"), 0o644); err != nil {+ t.Fatal(err)+ }+ // A failed checkout may have left a recent, incomplete registration.+ stale := filepath.Join(legacyPath, "worktrees", "stale")+ if err := os.MkdirAll(stale, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(stale, "gitdir"), []byte(filepath.Join(workDir, "missing", ".git")+"\n"), 0o644); err != nil {+ t.Fatal(err)+ }+ shortPath := filepath.Join(cache.root, migrationWorkspaceID, bareDirName(migrationRepoURL))+ if onSync {+ if err := cache.Sync(migrationWorkspaceID, []RepoInfo{{URL: migrationRepoURL}}); err != nil {+ t.Fatal(err)+ }+ if got := cache.Lookup(migrationWorkspaceID, migrationRepoURL); got != shortPath {+ t.Fatalf("sync left the cache at %s, want %s", got, shortPath)+ }+ }+ result, err := cache.CreateWorktree(WorktreeParams{+ WorkspaceID: migrationWorkspaceID,+ RepoURL: migrationRepoURL,+ WorkDir: workDir,+ AgentName: "test",+ TaskID: "12345678-0000-0000-0000-000000000000",+ })+ if err != nil {+ t.Fatalf("checkout from legacy cache: %v", err)+ }+ if got := cache.Lookup(migrationWorkspaceID, migrationRepoURL); got != shortPath {+ t.Fatalf("checkout left the cache at %s, want %s", got, shortPath)+ }+ if _, err := os.Stat(legacyPath); !os.IsNotExist(err) {+ t.Fatalf("legacy directory survived migration: %v", err)+ }+ if data, err := os.ReadFile(filepath.Join(shortPath, "retained.txt")); err != nil || string(data) != "keep cache contents" {+ t.Fatalf("migration lost cache contents: %q, %v", data, err)+ }+ if got := gitRefCommit(t, shortPath, "refs/heads/retained"); got != commit {+ t.Fatalf("migration lost a local branch: %s, want %s", got, commit)+ }+ if got := gitHead(t, result.Path); got != commit {+ t.Fatalf("checkout has %s, want %s", got, commit)+ }+ admin := assertWorktreeCache(t, result.Path, shortPath)+ if len(filepath.Join(admin, "index")) >= 260 {+ t.Fatalf("migrated checkout exceeds MAX_PATH: %s", admin)+ }+ })+ }+}++func TestCacheWaitersResolvePathAfterMigration(t *testing.T) {+ t.Parallel()+ source := createTestRepo(t)+ cache := New(t.TempDir(), testLogger())+ legacyPath := filepath.Join(cache.root, "ws", legacyBareDirName(source))+ shortPath := filepath.Join(cache.root, "ws", bareDirName(source))+ if err := os.MkdirAll(filepath.Dir(legacyPath), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := gitCloneBareContext(context.Background(), source, legacyPath); err != nil {+ t.Fatal(err)+ }+ workDir := t.TempDir()+ lock := cache.lockForRepo(legacyPath)+ lock.Lock()+ locked := true+ defer func() {+ if locked {+ lock.Unlock()+ }+ }()+ ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)+ defer cancel()+ done := make(chan error, 2)+ go func() { done <- cache.SyncContext(ctx, "ws", []RepoInfo{{URL: source}}) }()+ go func() {+ _, err := cache.CreateWorktreeContext(ctx, WorktreeParams{+ WorkspaceID: "ws",+ RepoURL: source,+ WorkDir: workDir,+ AgentName: "test",+ TaskID: "12345678-0000-0000-0000-000000000000",+ })+ done <- err+ }()+ for cache.Activity().ForegroundWaiters < 2 {+ select {+ case <-ctx.Done():+ t.Fatal("operations did not queue behind the cache lock")+ case <-time.After(time.Millisecond):+ }+ }+ // Model another holder completing the rename while these callers wait.+ if err := os.Rename(legacyPath, shortPath); err != nil {+ t.Fatal(err)+ }+ lock.Unlock()+ locked = false+ for range 2 {+ if err := <-done; err != nil {+ t.Fatalf("operation used a stale cache path: %v", err)+ }+ }+ if _, err := os.Stat(legacyPath); !os.IsNotExist(err) {+ t.Fatalf("waiting Sync recreated the old cache: %v", err)+ }+}++func TestMigrationDoesNotOverwriteExistingDestination(t *testing.T) {+ t.Parallel()+ cache, legacyPath, _ := seedLegacyEnterpriseCache(t)+ shortPath := filepath.Join(cache.root, migrationWorkspaceID, bareDirName(migrationRepoURL))+ if err := os.MkdirAll(shortPath, 0o755); err != nil {+ t.Fatal(err)+ }+ marker := filepath.Join(shortPath, "keep.txt")+ if err := os.WriteFile(marker, []byte("existing destination"), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := cache.Sync(migrationWorkspaceID, []RepoInfo{{URL: migrationRepoURL}}); err != nil {+ t.Fatal(err)+ }+ if got := cache.Lookup(migrationWorkspaceID, migrationRepoURL); got != legacyPath {+ t.Fatalf("existing destination replaced legacy cache: %s", got)+ }+ if data, err := os.ReadFile(marker); err != nil || string(data) != "existing destination" {+ t.Fatalf("existing destination changed: %q, %v", data, err)+ }+}++func TestMigrationKeepsLockedWorktree(t *testing.T) {+ t.Parallel()+ source := createTestRepo(t)+ root, err := os.MkdirTemp("", "mc-")+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = os.RemoveAll(root) })+ cache := New(filepath.Join(root, "repos"), testLogger())+ legacyPath := filepath.Join(cache.root, "ws", legacyBareDirName(source))+ if err := os.MkdirAll(filepath.Dir(legacyPath), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := gitCloneBareContext(context.Background(), source, legacyPath); err != nil {+ t.Fatal(err)+ }+ path := filepath.Join(root, "checkout")+ if _, err := createWorktreeContext(context.Background(), legacyPath, path, "agent/test/locked", getRemoteDefaultBranch(legacyPath)); err != nil {+ t.Fatal(err)+ }+ if err := runGit("-C", legacyPath, "worktree", "lock", path); err != nil {+ t.Fatal(err)+ }+ // Git's lock protects a checkout on an offline/removable volume as well+ // as a present one. Pruning must retain it and prevent cache migration.+ if err := os.RemoveAll(path); err != nil {+ t.Fatal(err)+ }+ if err := cache.Sync("ws", []RepoInfo{{URL: source}}); err != nil {+ t.Fatal(err)+ }+ if got := cache.Lookup("ws", source); got != legacyPath {+ t.Fatalf("locked worktree lost its cache: %s", got)+ }+ if _, err := os.Stat(filepath.Join(cache.root, "ws", bareDirName(source))); !os.IsNotExist(err) {+ t.Fatalf("locked worktree allowed migration: %v", err)+ }+}diff --git a/server/internal/daemon/repocache/cache_paths_test.go b/server/internal/daemon/repocache/cache_paths_test.gonew file mode 100644index 0000000000..b14f660145--- /dev/null+++ b/server/internal/daemon/repocache/cache_paths_test.go@@ -0,0 +1,248 @@+package repocache++import (+ "context"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func TestBareDirNameBounded(t *testing.T) {+ t.Parallel()+ for _, repoURL := range []string{+ "http://tfs.example.internal:8080/tfs/engineering-collection/engineering-project/_git/enterprise-repository-client",+ "https://example.com/" + strings.Repeat("namespace/", 30) + strings.Repeat("repository", 30),+ "https://example.com/" + strings.Repeat("仓库", 30),+ } {+ name := bareDirName(repoURL)+ if len(name) > 33 || !strings.HasSuffix(name, ".git") {+ t.Errorf("cache name %q must fit 33 bytes and end in .git", name)+ }+ for _, ch := range name {+ if !(ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9' || strings.ContainsRune("-_.", ch)) {+ t.Errorf("cache name %q contains an unsafe character %q", name, ch)+ break+ }+ }+ }+}++func TestCheckoutReusesLegacyCache(t *testing.T) {+ t.Parallel()+ for _, isolated := range []bool{false, true} {+ name := "linked"+ if isolated {+ name = "isolated"+ }+ t.Run(name, func(t *testing.T) {+ source := createTestRepo(t)+ cache := New(t.TempDir(), testLogger())+ legacyPath := filepath.Join(cache.root, "ws", legacyBareDirName(source))+ if err := os.MkdirAll(filepath.Dir(legacyPath), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := gitCloneBareContext(context.Background(), source, legacyPath); err != nil {+ t.Fatal(err)+ }+ params := WorktreeParams{+ WorkspaceID: "ws",+ RepoURL: source,+ WorkDir: t.TempDir(),+ AgentName: "test",+ TaskID: "12345678-0000-0000-0000-000000000000",+ IsolatedGitMetadata: isolated,+ }+ // Seed the checkout as an older daemon would, before migration exists.+ path := filepath.Join(params.WorkDir, repoNameFromURL(source))+ branch := "agent/test/" + taskKey(params.TaskID)+ baseRef := getRemoteDefaultBranch(legacyPath)+ result := &WorktreeResult{Path: path, BranchName: branch}+ var err error+ if isolated {+ result, err = cache.createOrUpdateIsolatedCheckoutContext(context.Background(), legacyPath, source, path, branch, baseRef, false)+ } else {+ _, err = createWorktreeContext(context.Background(), legacyPath, path, branch, baseRef)+ }+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(result.Path, "local.txt"), []byte("uncommitted work"), 0o644); err != nil {+ t.Fatal(err)+ }+ // Linked metadata pins the cache in place. Isolated metadata does+ // not depend on its old path, so that cache may be migrated.+ cache = New(cache.root, testLogger())+ if err := cache.Sync("ws", []RepoInfo{{URL: source}}); err != nil {+ t.Fatal(err)+ }+ shortPath := filepath.Join(cache.root, "ws", bareDirName(source))+ wantPath, absentPath := legacyPath, shortPath+ if isolated {+ wantPath, absentPath = shortPath, legacyPath+ }+ if got := cache.Lookup("ws", source); got != wantPath {+ t.Fatalf("cache path = %s, want %s", got, wantPath)+ }+ if _, err := os.Stat(absentPath); !os.IsNotExist(err) {+ t.Fatalf("upgrade created a duplicate cache: %v", err)+ }+ kept, err := cache.CreateWorktree(params)+ if err != nil {+ t.Fatalf("reuse legacy checkout: %v", err)+ }+ if kept.Path != result.Path || kept.BranchName != result.BranchName || kept.Kept == "" {+ t.Fatalf("legacy checkout was replaced: %+v", kept)+ }+ if data, err := os.ReadFile(filepath.Join(kept.Path, "local.txt")); err != nil || string(data) != "uncommitted work" {+ t.Fatalf("local work changed: %q, %v", data, err)+ }+ })+ }+}++func TestBareDirNameCanonicalURLForms(t *testing.T) {+ t.Parallel()+ for _, repoURL := range []string{+ "https://github.com/org/my-repo.git",+ "https://GITHUB.COM/org/my-repo/",+ "[email protected]:org/my-repo",+ "ssh://[email protected]/org/my-repo.git",+ } {+ if got, want := bareDirName(repoURL), "my-repo-b98ef226e6b8.git"; got != want {+ t.Errorf("bareDirName(%q) = %q, want %q", repoURL, got, want)+ }+ }+}++func TestCreateWorktreeHookFailureRollsBack(t *testing.T) {+ t.Parallel()+ source := createTestRepo(t)+ cache := New(t.TempDir(), testLogger())+ if err := cache.Sync("ws", []RepoInfo{{URL: source}}); err != nil {+ t.Fatal(err)+ }+ barePath := cache.Lookup("ws", source)+ hook := filepath.Join(barePath, "hooks", "post-checkout")+ if err := os.WriteFile(hook, []byte("#!/bin/sh\nexit 1\n"), 0o755); err != nil {+ t.Fatal(err)+ }+ path := filepath.Join(t.TempDir(), "checkout")+ const branch = "agent/test/failed-hook"+ baseRef := getRemoteDefaultBranch(barePath)+ if _, err := createWorktreeContext(context.Background(), barePath, path, branch, baseRef); err == nil {+ t.Fatal("checkout with a failing hook must fail")+ }+ if _, err := os.Stat(path); !os.IsNotExist(err) {+ t.Fatalf("partial checkout survived hook failure: %v", err)+ }+ if gitRefExistsContext(context.Background(), barePath, "refs/heads/"+branch) {+ t.Fatal("new branch survived hook failure")+ }+ if err := os.Remove(hook); err != nil {+ t.Fatal(err)+ }+ if got, err := createWorktreeContext(context.Background(), barePath, path, branch, baseRef); err != nil || got != branch {+ t.Fatalf("retry after hook failure = %q, %v", got, err)+ }+}++func TestCreateWorktreeFailureDoesNotLeakBranch(t *testing.T) {+ t.Parallel()+ for _, collision := range []bool{false, true} {+ name := "new branch"+ if collision {+ name = "existing branch"+ }+ t.Run(name, func(t *testing.T) {+ source := createTestRepo(t)+ cache := New(t.TempDir(), testLogger())+ if err := cache.Sync("ws", []RepoInfo{{URL: source}}); err != nil {+ t.Fatal(err)+ }+ barePath := cache.Lookup("ws", source)+ baseRef := getRemoteDefaultBranch(barePath)+ const branch = "agent/test/failed-checkout"+ if collision {+ if err := runGit("-C", barePath, "branch", branch, baseRef); err != nil {+ t.Fatal(err)+ }+ }+ before, err := runGitOutput("-C", barePath, "for-each-ref", "--format=%(refname) %(objectname)", "refs/heads/")+ if err != nil {+ t.Fatal(err)+ }+ // Git creates the branch before trying to make the checkout directory.+ parent := filepath.Join(t.TempDir(), "blocked")+ if err := os.WriteFile(parent, []byte("keep me"), 0o644); err != nil {+ t.Fatal(err)+ }+ path := filepath.Join(parent, "checkout")+ if _, err := createWorktreeContext(context.Background(), barePath, path, branch, baseRef); err == nil {+ t.Fatal("checkout through a file must fail")+ }+ after, err := runGitOutput("-C", barePath, "for-each-ref", "--format=%(refname) %(objectname)", "refs/heads/")+ if err != nil {+ t.Fatal(err)+ }+ if string(after) != string(before) {+ t.Fatalf("failed checkout changed branches:\nbefore: %s\nafter: %s", before, after)+ }+ if data, err := os.ReadFile(parent); err != nil || string(data) != "keep me" {+ t.Fatalf("failed checkout modified the blocking file: %q, %v", data, err)+ }+ if err := os.Remove(parent); err != nil {+ t.Fatal(err)+ }+ if _, err := createWorktreeContext(context.Background(), barePath, path, branch, baseRef); err != nil {+ t.Fatalf("retry failed: %v", err)+ }+ })+ }+}++func TestCheckoutLongRepoURL(t *testing.T) {+ clearGitConfigEnv(t)+ source := createTestRepo(t)+ const repoURL = "http://tfs.example.internal:8080/tfs/engineering-collection/engineering-project/_git/enterprise-repository-client"+ // Keep the remote local while exercising the enterprise URL through Sync,+ // Lookup, fetch and linked-worktree creation, including on Windows CI.+ t.Setenv("GIT_CONFIG_COUNT", "1")+ t.Setenv("GIT_CONFIG_KEY_0", "url."+filepath.ToSlash(source)+".insteadOf")+ t.Setenv("GIT_CONFIG_VALUE_0", repoURL)+ root, err := os.MkdirTemp("", "mc-")+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = os.RemoveAll(root) })+ workspacesRoot := filepath.Join(root, strings.Repeat("w", max(1, 65-len(root)-1)))+ cache := New(filepath.Join(workspacesRoot, ".repos"), testLogger())+ const wsID = "11111111-1111-1111-1111-111111111111"+ if err := cache.Sync(wsID, []RepoInfo{{URL: repoURL}}); err != nil {+ t.Fatalf("sync long URL: %v", err)+ }+ barePath := cache.Lookup(wsID, repoURL)+ if len(barePath) >= 210 {+ t.Fatalf("cache path exceeds Git's reported path budget: %s (%d)", barePath, len(barePath))+ }+ result, err := cache.CreateWorktree(WorktreeParams{+ WorkspaceID: wsID,+ RepoURL: repoURL,+ WorkDir: filepath.Join(root, "workdir"),+ AgentName: "test",+ TaskID: "12345678-0000-0000-0000-000000000000",+ })+ if err != nil {+ t.Fatalf("checkout long URL: %v", err)+ }+ if filepath.Base(result.Path) != "enterprise-repository-client" {+ t.Fatalf("checkout changed the visible repository name: %s", result.Path)+ }+ admin := worktreeRegistration(t, result.Path)+ if index := filepath.Join(admin, "index"); len(index) >= 260 {+ t.Fatalf("worktree index exceeds MAX_PATH: %s (%d)", index, len(index))+ }+ if got := gitHead(t, result.Path); got != gitHead(t, source) {+ t.Fatalf("checkout has %s, want source HEAD", got)+ }+}diff --git a/server/internal/daemon/repocache/cache_test.go b/server/internal/daemon/repocache/cache_test.goindex a76c9db144..ec745acf4a 100644--- a/server/internal/daemon/repocache/cache_test.go+++ b/server/internal/daemon/repocache/cache_test.go@@ -398,7 +398,7 @@ func TestCreateWorktreeContextCancelsRunningGitProcessTree(t *testing.T) {}}-func TestBareDirName(t *testing.T) {+func TestLegacyBareDirName(t *testing.T) {t.Parallel()tests := []struct {input, want string@@ -417,8 +417,8 @@ func TestBareDirName(t *testing.T) {{"", "repo.git"},}for _, tt := range tests {- if got := bareDirName(tt.input); got != tt.want {- t.Errorf("bareDirName(%q) = %q, want %q", tt.input, got, tt.want)+ if got := legacyBareDirName(tt.input); got != tt.want {+ t.Errorf("legacyBareDirName(%q) = %q, want %q", tt.input, got, tt.want)}}}