package server import ( "bytes" "context" "fmt" "os" "os/exec" "path/filepath" "strings" "time" ) func discoverStorageWorktrees(ctx context.Context, roots, protected []string) ([]storageWorktree, []string) { seenRepos := map[string]bool{} seenTrees := map[string]bool{} trees := []storageWorktree{} problems := []string{} for index, root := range roots { if index >= 256 { problems = append(problems, "Workspace discovery limit reached") break } root = filepath.Clean(root) if _, err := os.Stat(root); os.IsNotExist(err) { continue } common, err := storageGit(ctx, root, "rev-parse", "--git-common-dir") if err != nil { continue } // A recorded workspace need not be a Git repository. common = resolveGitPath(root, common) common, err = filepath.EvalSymlinks(common) if err != nil { problems = append(problems, err.Error()) continue } if seenRepos[common] { continue } seenRepos[common] = true if len(seenRepos) > 64 { problems = append(problems, "Repository discovery limit reached") break } listing, err := storageGit(ctx, root, "worktree", "list", "--porcelain", "-z") if err != nil { problems = append(problems, err.Error()) continue } repository := common for _, record := range strings.Split(listing, "\x00\x00") { fields := strings.Split(record, "\x00") if len(fields) > 0 && strings.HasPrefix(fields[0], "worktree ") { candidate := strings.TrimPrefix(fields[0], "worktree ") if info, err := os.Lstat(filepath.Join(candidate, ".git")); err == nil && info.IsDir() { repository = candidate break } } } for _, record := range strings.Split(listing, "\x00\x00") { fields := strings.Split(record, "\x00") if len(fields) == 0 || !strings.HasPrefix(fields[0], "worktree ") { continue } path := strings.TrimPrefix(fields[0], "worktree ") if seenTrees[path] { continue } seenTrees[path] = true if len(trees) >= 512 { problems = append(problems, "Worktree discovery limit reached") return protectNestedStorageWorktrees(ctx, trees, roots, seenTrees, problems), problems } // The primary checkout has a .git directory; linked worktrees have a file. gitInfo, err := os.Lstat(filepath.Join(path, ".git")) if err != nil || !gitInfo.Mode().IsRegular() { continue } tree := storageWorktree{Path: path, Repository: repository, knownRoots: roots} for _, field := range fields[1:] { if strings.HasPrefix(field, "branch ") { tree.Branch = strings.TrimPrefix(field, "branch refs/heads/") } if field == "locked" || strings.HasPrefix(field, "locked ") { tree.locked = true } } if info, err := os.Stat(path); err == nil { tree.ModifiedAt = info.ModTime().UTC() } tree.Reason = storageWorktreeProtection(ctx, tree, protected) tree.Eligible = tree.Reason == "" trees = append(trees, tree) } } return protectNestedStorageWorktrees(ctx, trees, roots, seenTrees, problems), problems } // Eligibility is deliberately conservative: no forced removal, branch deletion, // or deletion of a workspace whose work has not reached the repository's main. func storageWorktreeProtection(ctx context.Context, tree storageWorktree, protected []string) string { if tree.locked { return "Git worktree is locked" } root, err := filepath.EvalSymlinks(tree.Path) if err != nil || root != filepath.Clean(tree.Path) { return "Worktree path is unavailable or indirect" } for _, path := range protected { if path == "" { continue } absolute, err := storageCanonicalPath(path) if err != nil { return "Protected workspace path is unresolved" } if root == absolute || pathWithin(root, absolute) || pathWithin(absolute, root) { return "Workspace is in use by a run or open chat" } } info, err := os.Lstat(filepath.Join(root, ".git")) if err != nil || !info.Mode().IsRegular() { return "Primary checkout or invalid linked worktree" } gitDir, err := storageGit(ctx, root, "rev-parse", "--git-dir") if err != nil { return "Worktree metadata unavailable" } common, err := storageGit(ctx, root, "rev-parse", "--git-common-dir") if err != nil { return "Repository metadata unavailable" } gitDir, err = canonicalDirectory(resolveGitPath(root, gitDir)) if err != nil { return "Worktree metadata unavailable" } common, err = canonicalDirectory(resolveGitPath(root, common)) if err != nil || !pathWithin(filepath.Join(common, "worktrees"), gitDir) { return "Unverified linked worktree" } if _, err := os.Stat(filepath.Join(gitDir, "locked")); err == nil { return "Git worktree is locked" } if reason := storageNestedProtection(ctx, root, tree.knownRoots); reason != "" { return reason } currentBranch, _ := storageGit(ctx, root, "symbolic-ref", "--quiet", "--short", "HEAD") if currentBranch == "main" || currentBranch == "master" { return "Main branch checkout" } top, err := storageGit(ctx, root, "rev-parse", "--show-toplevel") if err != nil || top != root { return "Worktree root is not verified" } status, err := storageGit(ctx, root, "status", "--porcelain", "--untracked-files=all") if err != nil { return "Git status unavailable" } if status != "" { return "Uncommitted or untracked work" } if _, err := storageGit(ctx, root, "merge-base", "--is-ancestor", "HEAD", "refs/heads/main"); err != nil { return "Work is not fully merged into main" } return "" } func removeStorageWorktree(ctx context.Context, tree storageWorktree, protected []string) error { if reason := storageWorktreeProtection(ctx, tree, protected); reason != "" { return fmt.Errorf("worktree protected: %s", reason) } _, err := storageGit(ctx, tree.Repository, "worktree", "remove", "--", tree.Path) return err } // Git subprocesses have both time and output bounds; no user shell is invoked. func storageGit(ctx context.Context, directory string, args ...string) (string, error) { ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() command := exec.CommandContext(ctx, "git", append([]string{"-C", directory}, args...)...) var out storageGitBuffer command.Stdout = &out command.Stderr = &out if err := command.Run(); err != nil { return "", fmt.Errorf("git %s in %s: %w", strings.Join(args, " "), directory, err) } return strings.TrimSpace(out.String()), nil } type storageGitBuffer struct{ bytes.Buffer } func (b *storageGitBuffer) Write(data []byte) (int, error) { if b.Len()+len(data) > 1<<20 { return 0, fmt.Errorf("git output limit reached") } return b.Buffer.Write(data) } // Resolve aliases even when the protected directory is a future child path. func storageCanonicalPath(path string) (string, error) { absolute, err := filepath.Abs(path) if err != nil { return "", err } current := absolute for { resolved, err := filepath.EvalSymlinks(current) if err == nil { relative, err := filepath.Rel(current, absolute) if err != nil { return "", err } return filepath.Join(resolved, relative), nil } parent := filepath.Dir(current) if parent == current { return "", err } current = parent } }