package main import ( "bytes" "encoding/json" "fmt" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "strconv" "strings" "testing" "git.unkin.net/unkin/agent-tools/internal/agent" ) // fixture is a bare origin plus a source checkout named "repo" and a worktree // root, wired so managedWorktrees() finds the worktrees created here. type fixture struct { root string bare string srcDir string wtRoot string } func git(t *testing.T, dir string, args ...string) string { t.Helper() cmd := exec.Command("git", args...) cmd.Dir = dir out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("git %s (in %s): %v: %s", strings.Join(args, " "), dir, err, out) } return strings.TrimSpace(string(out)) } func newFixture(t *testing.T) *fixture { t.Helper() root := t.TempDir() f := &fixture{ root: root, bare: filepath.Join(root, "origin.git"), srcDir: filepath.Join(root, "src", "repo"), wtRoot: filepath.Join(root, "worktrees"), } if err := os.MkdirAll(filepath.Join(root, "src"), 0o755); err != nil { t.Fatal(err) } if err := os.MkdirAll(f.wtRoot, 0o755); err != nil { t.Fatal(err) } git(t, root, "init", "--bare", "-b", "main", f.bare) seed := filepath.Join(root, "seed") git(t, root, "init", "-b", "main", seed) identity(t, seed) writeCommit(t, seed, "README.md", "hi\n", "init") git(t, seed, "remote", "add", "origin", f.bare) git(t, seed, "push", "-u", "origin", "main") git(t, filepath.Join(root, "src"), "clone", f.bare, f.srcDir) identity(t, f.srcDir) t.Setenv("AGENTWS_ROOT", f.wtRoot) t.Setenv("AGENTWS_SRC_ROOT", filepath.Join(root, "src")) t.Setenv("AGENTWS_OWNER", "unkin") return f } func identity(t *testing.T, dir string) { t.Helper() git(t, dir, "config", "user.email", "test@example.com") git(t, dir, "config", "user.name", "Test") } func writeCommit(t *testing.T, dir, name, content, msg string) { t.Helper() if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil { t.Fatal(err) } git(t, dir, "add", ".") git(t, dir, "commit", "-m", msg) } // addWorktree creates a managed worktree for branch and returns its path. func (f *fixture) addWorktree(t *testing.T, branch string) string { t.Helper() path := filepath.Join(f.wtRoot, agent.WorktreeDirName("repo", branch)) git(t, f.srcDir, "worktree", "add", path, "-b", branch, "origin/main") identity(t, path) return path } // landUpstream commits content on origin's main, mimicking a squash merge: the // same patch arrives upstream under a different SHA. func (f *fixture) landUpstream(t *testing.T, name, content, msg string) { t.Helper() seed := filepath.Join(f.root, "seed") git(t, seed, "pull", "--ff-only", "origin", "main") writeCommit(t, seed, name, content, msg) git(t, seed, "push", "origin", "main") } // fakeGitea serves the pulls listing for unkin/repo with the given PR bodies. func fakeGitea(t *testing.T, prs ...map[string]any) *httptest.Server { t.Helper() mux := http.NewServeMux() mux.HandleFunc("/api/v1/repos/unkin/repo/pulls", func(w http.ResponseWriter, r *http.Request) { if r.URL.Query().Get("page") != "1" { _, _ = w.Write([]byte("[]")) return } body, err := json.Marshal(prs) if err != nil { t.Errorf("marshal PRs: %v", err) } _, _ = w.Write(body) }) srv := httptest.NewServer(mux) t.Cleanup(srv.Close) return srv } func client(srv *httptest.Server) prLister { return &agent.GiteaClient{BaseURL: srv.URL, HTTP: srv.Client()} } // mergedPR mimics Gitea after a merge: the branch is deleted, so head.ref // becomes refs/pull//head and only head.label still names the branch. func mergedPR(number int, branch string) map[string]any { return map[string]any{ "number": number, "state": "closed", "merged": true, "head": map[string]any{ "ref": "refs/pull/" + strconv.Itoa(number) + "/head", "label": branch, }, } } func withHeadSha(pr map[string]any, sha string) map[string]any { pr["head"].(map[string]any)["sha"] = sha return pr } func openPR(number int, branch string) map[string]any { return map[string]any{ "number": number, "state": "open", "merged": false, "head": map[string]any{"ref": branch, "label": branch}, } } func closedPR(number int, branch string) map[string]any { return map[string]any{ "number": number, "state": "closed", "merged": false, "head": map[string]any{"ref": branch, "label": branch}, } } func run(t *testing.T, prs prLister, apply, keepBranches bool) string { t.Helper() return runOpts(t, prs, pruneOpts{apply: apply, keepBranches: keepBranches}) } func runOpts(t *testing.T, prs prLister, opts pruneOpts) string { t.Helper() var out, errOut bytes.Buffer if err := runPrune(&out, &errOut, prs, opts); err != nil { t.Fatalf("runPrune: %v\n%s%s", err, out.String(), errOut.String()) } return out.String() + errOut.String() } func lineFor(t *testing.T, out, branch string) string { t.Helper() for _, line := range strings.Split(out, "\n") { if fields := strings.Fields(line); len(fields) > 1 && fields[1] == branch { return line } } t.Fatalf("no line for branch %q in:\n%s", branch, out) return "" } // assertVerdict reads the table row for a branch: REPO BRANCH PATH VERDICT REASON. func assertVerdict(t *testing.T, out, branch, verdict, reason string) { t.Helper() line := lineFor(t, out, branch) fields := strings.Fields(line) if len(fields) < 4 || fields[3] != verdict { t.Errorf("branch %s: verdict line %q, want verdict %q", branch, line, verdict) } if reason != "" && !strings.Contains(line, reason) { t.Errorf("branch %s: line %q, want reason containing %q", branch, line, reason) } } func exists(path string) bool { _, err := os.Stat(path) return err == nil } // A merged PR's branch is deleted on merge, so its head.ref reads // refs/pull//head; classification must still see the merge (via head.label) // and remove the branch, not fall through to "no PR". func TestPruneMergedPRWithDeletedBranch(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/merged") writeCommit(t, wt, "m.txt", "m\n", "work") head := git(t, wt, "rev-parse", "HEAD") srv := fakeGitea(t, withHeadSha(mergedPR(3, "benvin/merged"), head)) out := run(t, client(srv), true, false) assertVerdict(t, out, "benvin/merged", verdictRemoveBranch, "PR merged #3") if exists(wt) { t.Errorf("worktree %s should have been removed", wt) } if agent.GitBranchExists(f.srcDir, "benvin/merged") { t.Error("branch of a merged PR should be deleted") } } // The same PR without head.label: matching falls back to head.ref, which no // longer names the branch, so prune must not guess it is merged — the worktree // goes but the branch stays. func TestPruneMergedPRWithoutLabelKeepsBranch(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/merged") writeCommit(t, wt, "m.txt", "m\n", "work") pr := mergedPR(3, "benvin/merged") pr["head"].(map[string]any)["label"] = "" srv := fakeGitea(t, pr) out := run(t, client(srv), true, false) assertVerdict(t, out, "benvin/merged", verdictRemove, "no PR") if !agent.GitBranchExists(f.srcDir, "benvin/merged") { t.Error("branch must survive when the PR could not be matched") } } func TestPruneContainedBranch(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/contained") srv := fakeGitea(t) out := run(t, client(srv), true, false) assertVerdict(t, out, "benvin/contained", verdictRemoveBranch, "contained in origin/main") if exists(wt) { t.Error("contained worktree should have been removed") } if agent.GitBranchExists(f.srcDir, "benvin/contained") { t.Error("contained branch should be deleted") } } // Squash-merged work keeps a local SHA that is not upstream, so only the // patch-equivalence check proves it landed. func TestPruneCherryCleanBranch(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/squashed") writeCommit(t, wt, "s.txt", "same\n", "add s") f.landUpstream(t, "s.txt", "same\n", "squashed s") srv := fakeGitea(t) out := run(t, client(srv), true, false) assertVerdict(t, out, "benvin/squashed", verdictRemoveBranch, "patch-equivalent commits in origin/main history") if agent.GitBranchExists(f.srcDir, "benvin/squashed") { t.Error("cherry-clean branch should be deleted") } } // Uncommitted work outranks every other signal, including a branch that is // otherwise fully contained upstream. func TestPruneNeverTouchesDirtyWorktree(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/dirty") if err := os.WriteFile(filepath.Join(wt, "wip.txt"), []byte("wip\n"), 0o644); err != nil { t.Fatal(err) } srv := fakeGitea(t, mergedPR(4, "benvin/dirty")) out := run(t, client(srv), true, false) assertVerdict(t, out, "benvin/dirty", verdictKeep, "dirty") if !exists(wt) { t.Error("dirty worktree must not be removed") } if !agent.GitBranchExists(f.srcDir, "benvin/dirty") { t.Error("dirty worktree's branch must survive") } } // An open PR is kept even when its commits are already upstream. func TestPruneKeepsOpenPR(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/open") srv := fakeGitea(t, openPR(5, "benvin/open")) out := run(t, client(srv), true, false) assertVerdict(t, out, "benvin/open", verdictKeep, "PR open #5") if !exists(wt) { t.Error("worktree with an open PR must not be removed") } if !agent.GitBranchExists(f.srcDir, "benvin/open") { t.Error("branch with an open PR must not be deleted") } } // Closed-unmerged with the branch still on origin: the work is not lost, so the // local branch goes too. func TestPruneClosedPRWithBranchOnOrigin(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/closed") writeCommit(t, wt, "c.txt", "c\n", "work") git(t, wt, "push", "origin", "benvin/closed") srv := fakeGitea(t, closedPR(6, "benvin/closed")) out := run(t, client(srv), true, false) assertVerdict(t, out, "benvin/closed", verdictRemoveBranch, "PR closed #6, HEAD contained in origin/benvin/closed") if exists(wt) { t.Error("worktree should have been removed") } if agent.GitBranchExists(f.srcDir, "benvin/closed") { t.Error("branch should be deleted while origin still has it") } } // Closed-unmerged with nothing on origin: the commits exist only here, so the // branch is kept and only the worktree goes. func TestPruneClosedPRWithBranchGone(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/orphan") writeCommit(t, wt, "o.txt", "o\n", "work") srv := fakeGitea(t, closedPR(7, "benvin/orphan")) out := run(t, client(srv), true, false) assertVerdict(t, out, "benvin/orphan", verdictRemove, "PR closed #7, branch gone") if exists(wt) { t.Error("worktree should have been removed") } if !agent.GitBranchExists(f.srcDir, "benvin/orphan") { t.Error("branch must survive when origin does not have the commits") } } func TestPruneNoPRKeepsBranch(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/unpushed") writeCommit(t, wt, "u.txt", "u\n", "work") srv := fakeGitea(t) out := run(t, client(srv), true, false) assertVerdict(t, out, "benvin/unpushed", verdictRemove, "no PR") if exists(wt) { t.Error("worktree should have been removed") } if !agent.GitBranchExists(f.srcDir, "benvin/unpushed") { t.Error("branch with unproven work must survive") } } // The default run reports and changes nothing. func TestPruneDryRunChangesNothing(t *testing.T) { f := newFixture(t) contained := f.addWorktree(t, "benvin/contained") merged := f.addWorktree(t, "benvin/merged") writeCommit(t, merged, "m.txt", "m\n", "work") head := git(t, merged, "rev-parse", "HEAD") srv := fakeGitea(t, withHeadSha(mergedPR(8, "benvin/merged"), head)) out := run(t, client(srv), false, false) if !strings.Contains(out, "dry run") { t.Errorf("dry-run output should say so:\n%s", out) } assertVerdict(t, out, "benvin/contained", verdictRemoveBranch, "contained") assertVerdict(t, out, "benvin/merged", verdictRemoveBranch, "PR merged #8") if !exists(contained) || !exists(merged) { t.Error("dry run must not remove worktrees") } if !agent.GitBranchExists(f.srcDir, "benvin/contained") || !agent.GitBranchExists(f.srcDir, "benvin/merged") { t.Error("dry run must not delete branches") } } // --keep-branches removes worktrees but leaves every branch alone, and the // printed verdict says so. func TestPruneKeepBranches(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/contained") srv := fakeGitea(t) out := run(t, client(srv), true, true) assertVerdict(t, out, "benvin/contained", verdictRemove, "contained") if strings.Contains(out, verdictRemoveBranch) { t.Errorf("--keep-branches must not print a branch-deleting verdict:\n%s", out) } if exists(wt) { t.Error("worktree should have been removed") } if !agent.GitBranchExists(f.srcDir, "benvin/contained") { t.Error("--keep-branches must not delete the branch") } } // With Gitea unreachable prune falls back to the git signals: provably-upstream // work is still cleaned up, and anything unproven keeps its branch. func TestPruneDegradesWhenGiteaUnreachable(t *testing.T) { f := newFixture(t) contained := f.addWorktree(t, "benvin/contained") unproven := f.addWorktree(t, "benvin/unproven") writeCommit(t, unproven, "u.txt", "u\n", "work") dead := httptest.NewServer(http.NewServeMux()) c := &agent.GiteaClient{BaseURL: dead.URL, HTTP: dead.Client()} dead.Close() out := run(t, c, true, false) if !strings.Contains(out, "git signals only") { t.Errorf("output should note the Gitea failure:\n%s", out) } assertVerdict(t, out, "benvin/contained", verdictRemoveBranch, "contained") assertVerdict(t, out, "benvin/unproven", verdictRemove, "PR state unknown") if exists(contained) || exists(unproven) { t.Error("both worktrees should have been removed") } if agent.GitBranchExists(f.srcDir, "benvin/contained") { t.Error("contained branch is safe to delete without Gitea") } if !agent.GitBranchExists(f.srcDir, "benvin/unproven") { t.Error("unproven branch must survive an unreachable Gitea") } } func TestPruneNoWorktrees(t *testing.T) { newFixture(t) srv := fakeGitea(t) if out := run(t, client(srv), true, false); !strings.Contains(out, "no managed worktrees") { t.Errorf("output = %q", out) } } // Commits made after the PR merged exist nowhere else, so a merged PR alone // must not authorise deleting the branch. func TestPruneMergedPRWithCommitsAfterMerge(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/ahead") writeCommit(t, wt, "a.txt", "a\n", "merged work") merged := git(t, wt, "rev-parse", "HEAD") writeCommit(t, wt, "b.txt", "b\n", "work after the merge") srv := fakeGitea(t, withHeadSha(mergedPR(9, "benvin/ahead"), merged)) out := run(t, client(srv), true, false) assertVerdict(t, out, "benvin/ahead", verdictRemove, "PR merged #9") if exists(wt) { t.Error("worktree should have been removed") } if !agent.GitBranchExists(f.srcDir, "benvin/ahead") { t.Error("branch with commits beyond the merged head must survive") } } // HEAD proven contained in the merged head still loses its branch. func TestPruneMergedPRContainedInMergedHead(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/landed") writeCommit(t, wt, "a.txt", "a\n", "work") head := git(t, wt, "rev-parse", "HEAD") srv := fakeGitea(t, withHeadSha(mergedPR(10, "benvin/landed"), head)) out := run(t, client(srv), true, false) assertVerdict(t, out, "benvin/landed", verdictRemoveBranch, "HEAD contained in the merged head") if exists(wt) { t.Error("worktree should have been removed") } if agent.GitBranchExists(f.srcDir, "benvin/landed") { t.Error("branch contained in the merged head should be deleted") } } // A surviving remote branch only covers what was pushed to it; later local // commits keep the branch. func TestPruneClosedPRWithCommitsBeyondOrigin(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/beyond") writeCommit(t, wt, "c.txt", "c\n", "pushed work") git(t, wt, "push", "origin", "benvin/beyond") writeCommit(t, wt, "d.txt", "d\n", "local only") srv := fakeGitea(t, closedPR(11, "benvin/beyond")) out := run(t, client(srv), true, false) assertVerdict(t, out, "benvin/beyond", verdictRemove, "local commits not on origin/benvin/beyond") if exists(wt) { t.Error("worktree should have been removed") } if !agent.GitBranchExists(f.srcDir, "benvin/beyond") { t.Error("branch with commits beyond origin must survive") } } // truncatedLister stands in for a repo with more PRs than the listing cap. type truncatedLister struct{ prs []agent.PullRequest } func (l truncatedLister) ListPRs(string, string) ([]agent.PullRequest, error) { return l.prs, fmt.Errorf("unkin/repo: %w after 1000 pull requests", agent.ErrPRListTruncated) } // A truncated listing still classifies the PRs it saw, but a branch missing // from it reads as unknown rather than as having no PR. func TestPruneWarnsOnTruncatedPRListing(t *testing.T) { f := newFixture(t) listed := f.addWorktree(t, "benvin/listed") writeCommit(t, listed, "a.txt", "a\n", "work") head := git(t, listed, "rev-parse", "HEAD") unlisted := f.addWorktree(t, "benvin/unlisted") writeCommit(t, unlisted, "b.txt", "b\n", "work") var pr agent.PullRequest pr.Number, pr.State, pr.Merged = 12, "closed", true pr.Head.Label, pr.Head.Sha = "benvin/listed", head out := run(t, truncatedLister{prs: []agent.PullRequest{pr}}, true, false) if !strings.Contains(out, "truncated") || !strings.Contains(out, "older PRs unseen") { t.Errorf("output should warn about the truncated listing:\n%s", out) } assertVerdict(t, out, "benvin/listed", verdictRemoveBranch, "PR merged #12") assertVerdict(t, out, "benvin/unlisted", verdictRemove, "PR state unknown") if agent.GitBranchExists(f.srcDir, "benvin/listed") { t.Error("branch of a merged PR seen in the listing should be deleted") } if !agent.GitBranchExists(f.srcDir, "benvin/unlisted") { t.Error("branch missing from a truncated listing must survive") } } // breakRemote points origin at a path that does not exist, so every fetch fails. func (f *fixture) breakRemote(t *testing.T) { t.Helper() git(t, f.srcDir, "remote", "set-url", "origin", filepath.Join(f.root, "missing.git")) } // applyUnreachable applies the plan against a repo whose remote is unreachable. // The post-removal refresh fetch fails, so runPrune must report an error; the // classification and the removals it authorised happen regardless. func applyUnreachable(t *testing.T, prs prLister) string { t.Helper() var out, errOut bytes.Buffer err := runPrune(&out, &errOut, prs, pruneOpts{apply: true}) if err == nil { t.Fatalf("expected the refresh fetch to fail against a missing remote:\n%s", out.String()) } return out.String() + errOut.String() } // staleFixture builds a repo where origin/ covers HEAD for a closed and // a merged PR. Deleting the branches on origin makes those tracking refs stale: // a pruning fetch would drop them, so they only prove anything while a fetch // this run confirms they are still there. func staleFixture(t *testing.T, deleteUpstream bool) (*fixture, *httptest.Server, string, string) { t.Helper() f := newFixture(t) closed := f.addWorktree(t, "benvin/stale-closed") writeCommit(t, closed, "c.txt", "c\n", "work") git(t, closed, "push", "origin", "benvin/stale-closed") merged := f.addWorktree(t, "benvin/stale-merged") writeCommit(t, merged, "m.txt", "m\n", "work") git(t, merged, "push", "origin", "benvin/stale-merged") if deleteUpstream { git(t, f.bare, "update-ref", "-d", "refs/heads/benvin/stale-closed") git(t, f.bare, "update-ref", "-d", "refs/heads/benvin/stale-merged") } // The merged head is an older commit, so only origin/ covers HEAD. base := git(t, f.srcDir, "rev-parse", "origin/main") srv := fakeGitea(t, closedPR(20, "benvin/stale-closed"), withHeadSha(mergedPR(21, "benvin/stale-merged"), base), ) return f, srv, closed, merged } // A tracking ref this run's fetch could not confirm is not evidence: the branch // may already be gone upstream, and the next successful --prune deletes the ref. // Both worktrees go, both branches stay. func TestPruneFailedFetchDistrustsStaleRemoteBranch(t *testing.T) { f, srv, closed, merged := staleFixture(t, true) f.breakRemote(t) out := run(t, client(srv), false, false) if !strings.Contains(out, "remote state unverified") { t.Errorf("output should report the failed fetch:\n%s", out) } assertVerdict(t, out, "benvin/stale-closed", verdictRemove, "PR closed #20, fetch failed so origin/benvin/stale-closed is unverified") assertVerdict(t, out, "benvin/stale-merged", verdictRemove, "PR merged #21, fetch failed so origin/benvin/stale-merged is unverified") for _, b := range []string{"benvin/stale-closed", "benvin/stale-merged"} { if !agent.GitRemoteBranchExists(f.srcDir, "origin", b) { t.Fatalf("fixture: origin/%s should still be present as a stale ref", b) } } applyUnreachable(t, client(srv)) if exists(closed) || exists(merged) { t.Error("both worktrees should have been removed") } for _, b := range []string{"benvin/stale-closed", "benvin/stale-merged"} { if !agent.GitBranchExists(f.srcDir, b) { t.Errorf("branch %s must survive an unverified origin", b) } } } // The control for the case above: with the fetch working and the branches still // on origin, the same shape still loses both branches. func TestPruneSuccessfulFetchTrustsRemoteBranch(t *testing.T) { f, srv, closed, merged := staleFixture(t, false) out := run(t, client(srv), true, false) assertVerdict(t, out, "benvin/stale-closed", verdictRemoveBranch, "PR closed #20, HEAD contained in origin/benvin/stale-closed") assertVerdict(t, out, "benvin/stale-merged", verdictRemoveBranch, "PR merged #21, HEAD contained in origin/benvin/stale-merged") if exists(closed) || exists(merged) { t.Error("both worktrees should have been removed") } for _, b := range []string{"benvin/stale-closed", "benvin/stale-merged"} { if agent.GitBranchExists(f.srcDir, b) { t.Errorf("branch %s should be deleted while origin still has it", b) } } } // Proofs that read only local objects and the merged head SHA from the API do // not depend on the fetch, so a failed fetch must not suppress them. func TestPruneFailedFetchKeepsFetchIndependentProofs(t *testing.T) { f := newFixture(t) contained := f.addWorktree(t, "benvin/contained") landed := f.addWorktree(t, "benvin/landed") writeCommit(t, landed, "a.txt", "a\n", "work") head := git(t, landed, "rev-parse", "HEAD") f.breakRemote(t) srv := fakeGitea(t, withHeadSha(mergedPR(22, "benvin/landed"), head)) out := applyUnreachable(t, client(srv)) assertVerdict(t, out, "benvin/contained", verdictRemoveBranch, "contained in origin/main") assertVerdict(t, out, "benvin/landed", verdictRemoveBranch, "PR merged #22, HEAD contained in the merged head") if exists(contained) || exists(landed) { t.Error("both worktrees should have been removed") } for _, b := range []string{"benvin/contained", "benvin/landed"} { if agent.GitBranchExists(f.srcDir, b) { t.Errorf("branch %s is proven without the fetch and should be deleted", b) } } } // Managed repos are not all under AGENTWS_OWNER, so the Gitea path comes from // origin's URL; a non-Gitea remote falls back to the configured owner. func TestRepoPathFollowsOrigin(t *testing.T) { t.Setenv("AGENTWS_OWNER", "unkin") dir := t.TempDir() git(t, dir, "init", "-b", "main", ".") git(t, dir, "remote", "add", "origin", "https://git.unkin.net/unkinben/dotfiles.git") if got := repoPath(dir, "dotfiles"); got != "unkinben/dotfiles" { t.Errorf("repoPath = %q, want unkinben/dotfiles", got) } git(t, dir, "remote", "set-url", "origin", filepath.Join(dir, "origin.git")) if got := repoPath(dir, "dotfiles"); got != "unkin/dotfiles" { t.Errorf("repoPath for a local remote = %q, want unkin/dotfiles", got) } } // --- discovery beyond the worktree root ----------------------------------- // gitAllow runs git and returns its combined output without failing the test, // for commands that are expected to stop mid-way (e.g. an interrupted rebase). func gitAllow(t *testing.T, dir string, args ...string) string { t.Helper() cmd := exec.Command("git", args...) cmd.Dir = dir out, _ := cmd.CombinedOutput() return strings.TrimSpace(string(out)) } // addManualWorktree creates a worktree outside the worktree root, the way a // person would by hand, so only `git worktree list` can find it. func (f *fixture) addManualWorktree(t *testing.T, branch string) string { t.Helper() path := filepath.Join(f.root, "manual", agent.SanitizeBranch(branch)) git(t, f.srcDir, "worktree", "add", path, "-b", branch, "origin/main") identity(t, path) return path } // A hand-made worktree outside the worktree root is still classified, but the // default run refuses to remove it: that needs --include-unmanaged. func TestPruneReportsUnmanagedWorktreeButKeepsIt(t *testing.T) { f := newFixture(t) manual := f.addManualWorktree(t, "benvin/by-hand") srv := fakeGitea(t) out := runOpts(t, client(srv), pruneOpts{apply: true}) assertVerdict(t, out, "benvin/by-hand", verdictRemoveBranch, "contained in origin/main") if !strings.Contains(out, "--include-unmanaged") { t.Errorf("output should name the flag that would remove it:\n%s", out) } if !exists(manual) { t.Error("an unmanaged worktree must survive without --include-unmanaged") } if !agent.GitBranchExists(f.srcDir, "benvin/by-hand") { t.Error("an unmanaged worktree's branch must survive too") } } func TestPruneRemovesUnmanagedWorktreeWithFlag(t *testing.T) { f := newFixture(t) manual := f.addManualWorktree(t, "benvin/by-hand") srv := fakeGitea(t) out := runOpts(t, client(srv), pruneOpts{apply: true, includeUnmanaged: true}) assertVerdict(t, out, "benvin/by-hand", verdictRemoveBranch, "contained in origin/main") if exists(manual) { t.Error("--include-unmanaged should have removed the worktree") } } // --include-unmanaged only lifts the location gate. A keep verdict is a separate // gate, so a dirty hand-made worktree still needs --include-keep to be touched. func TestPruneIncludeUnmanagedStillObeysKeep(t *testing.T) { f := newFixture(t) manual := f.addManualWorktree(t, "benvin/by-hand") if err := os.WriteFile(filepath.Join(manual, "scratch.txt"), []byte("wip\n"), 0o644); err != nil { t.Fatal(err) } srv := fakeGitea(t) out := runOpts(t, client(srv), pruneOpts{apply: true, includeUnmanaged: true}) assertVerdict(t, out, "benvin/by-hand", verdictKeep, "dirty") if !exists(filepath.Join(manual, "scratch.txt")) { t.Error("--include-unmanaged must not remove a worktree classified keep") } } // A worktree whose directory was deleted leaves only a registration behind: // there is nothing to lose, so it is prunable outright. func TestPruneStaleRegistrationWithMissingDirectory(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/vanished") writeCommit(t, wt, "v.txt", "v\n", "work") if err := os.RemoveAll(wt); err != nil { t.Fatal(err) } srv := fakeGitea(t) out := runOpts(t, client(srv), pruneOpts{apply: true}) assertVerdict(t, out, "benvin/vanished", verdictRemove, "working tree gone") wts, err := agent.GitWorktreeList(f.srcDir) if err != nil { t.Fatal(err) } for _, w := range wts { if w.Path == wt { t.Errorf("registration for %s should have been pruned: %+v", wt, w) } } if !agent.GitBranchExists(f.srcDir, "benvin/vanished") { t.Error("pruning a registration must not delete the branch") } } // A directory under the worktree root whose backing repo is gone cannot be // inspected by git at all, so prune deletes the leftover directory. func TestPruneOrphanedDirectoryWhenRepoIsGone(t *testing.T) { f := newFixture(t) other := filepath.Join(f.root, "src", "other") git(t, filepath.Join(f.root, "src"), "clone", f.bare, other) identity(t, other) orphan := filepath.Join(f.wtRoot, agent.WorktreeDirName("other", "benvin/orphaned")) git(t, other, "worktree", "add", orphan, "-b", "benvin/orphaned", "origin/main") if err := os.RemoveAll(other); err != nil { t.Fatal(err) } srv := fakeGitea(t) out := runOpts(t, client(srv), pruneOpts{apply: true}) assertVerdict(t, out, "-", verdictRemove, "backing repo gone") if exists(orphan) { t.Error("an orphaned worktree directory should have been deleted") } } // addForeignWorktree clones a second repo under the source root and gives it a // worktree under the worktree root, so it can be broken without touching the // fixture's own repo. It returns the clone and the worktree path. func (f *fixture) addForeignWorktree(t *testing.T, repo, branch string) (string, string) { t.Helper() src := filepath.Join(f.root, "src", repo) git(t, filepath.Join(f.root, "src"), "clone", f.bare, src) identity(t, src) wt := filepath.Join(f.wtRoot, agent.WorktreeDirName(repo, branch)) git(t, src, "worktree", "add", wt, "-b", branch, "origin/main") return src, wt } // The regression this guards: git failing for a reason that is not "the backing // repo is gone" used to be read as orphan, and orphan deletes the directory // outright. Here the git dir is still on disk — only its commondir pointer is // broken, as a half-written or momentarily unreachable repo would be — so the // verdict must be keep and the directory must survive a --yes run. func TestPruneKeepsWorktreeWhenGitFailsButRepoExists(t *testing.T) { f := newFixture(t) src, wt := f.addForeignWorktree(t, "other", "benvin/unreadable") writeCommit(t, wt, "u.txt", "u\n", "work") gitDir, err := agent.GitDir(wt) if err != nil { t.Fatal(err) } if err := os.Remove(filepath.Join(gitDir, "commondir")); err != nil { t.Fatal(err) } if _, err := agent.GitCurrentBranch(wt); err == nil { t.Fatal("fixture did not break git in the worktree") } if !exists(gitDir) || !exists(filepath.Join(src, ".git")) { t.Fatal("fixture removed the backing repo; it must still be present") } srv := fakeGitea(t) out := runOpts(t, client(srv), pruneOpts{apply: true}) assertVerdict(t, out, "-", verdictKeep, "inspection failed") if !exists(wt) { t.Error("a worktree git could not be read must not be deleted") } } // The same rule one step further in: the registration is gone but the repo is // not, so the directory is still recoverable and must not be deleted. func TestPruneKeepsWorktreeWhenOnlyRegistrationIsGone(t *testing.T) { f := newFixture(t) src, wt := f.addForeignWorktree(t, "other", "benvin/deregistered") gitDir, err := agent.GitDir(wt) if err != nil { t.Fatal(err) } if err := os.RemoveAll(gitDir); err != nil { t.Fatal(err) } if !exists(filepath.Join(src, ".git")) { t.Fatal("fixture removed the backing repo; it must still be present") } srv := fakeGitea(t) out := runOpts(t, client(srv), pruneOpts{apply: true}) assertVerdict(t, out, "-", verdictKeep, "inspection failed") if !exists(wt) { t.Error("a worktree whose repo still exists must not be deleted") } } // --include-keep overrides a keep, but it must not become a second route to the // deletion finding #1 closed: with no readable git state there is nothing to // remove through, so the removal fails loudly and the directory stays. func TestPruneIncludeKeepDoesNotDeleteUnreadableWorktree(t *testing.T) { f := newFixture(t) _, wt := f.addForeignWorktree(t, "other", "benvin/forced") gitDir, err := agent.GitDir(wt) if err != nil { t.Fatal(err) } if err := os.Remove(filepath.Join(gitDir, "commondir")); err != nil { t.Fatal(err) } var out, errOut bytes.Buffer err = runPrune(&out, &errOut, client(fakeGitea(t)), pruneOpts{apply: true, includeKeep: true}) if err == nil { t.Error("forcing removal of an unreadable worktree should fail, not succeed silently") } if !exists(wt) { t.Error("--include-keep must not delete a worktree whose git state is unknown") } } // --- safety signals ------------------------------------------------------- // An interrupted rebase holds sequencer state that exists nowhere else, and it // detaches HEAD while it runs, so it must outrank every other signal. func TestPruneKeepsInterruptedRebase(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/rebasing") writeCommit(t, wt, "r.txt", "r\n", "work") gitAllow(t, wt, "rebase", "--exec", "false", "origin/main") if op, err := agent.GitInProgressOp(wt); err != nil || op != "rebase" { t.Fatalf("fixture did not leave a rebase in progress: op=%q err=%v", op, err) } srv := fakeGitea(t) out := runOpts(t, client(srv), pruneOpts{apply: true}) assertVerdict(t, out, "HEAD", verdictKeep, "rebase in progress") if !exists(wt) { t.Error("a worktree mid-rebase must not be removed") } } // A half-finished cherry-pick is the same case with a branch still checked out, // so the sequencer check has to run before the dirty check can mask it. func TestPruneKeepsInterruptedCherryPick(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/picking") gitDir, err := agent.GitDir(wt) if err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(gitDir, "CHERRY_PICK_HEAD"), []byte(git(t, wt, "rev-parse", "HEAD")+"\n"), 0o644); err != nil { t.Fatal(err) } srv := fakeGitea(t) out := runOpts(t, client(srv), pruneOpts{apply: true}) assertVerdict(t, out, "benvin/picking", verdictKeep, "cherry-pick in progress") if !exists(wt) { t.Error("a worktree mid-cherry-pick must not be removed") } } // A detached HEAD has no branch to carry its commits, so unique work there is // unrecoverable once the worktree goes. func TestPruneKeepsDetachedHeadWithUniqueCommits(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/detaching") writeCommit(t, wt, "d.txt", "d\n", "work") git(t, wt, "checkout", "--detach") git(t, f.srcDir, "branch", "-D", "benvin/detaching") srv := fakeGitea(t) out := runOpts(t, client(srv), pruneOpts{apply: true}) assertVerdict(t, out, "HEAD", verdictKeep, "detached HEAD carrying 1 commit on no remote") if !exists(wt) { t.Error("a detached worktree with unique commits must not be removed") } } // A detached HEAD whose commit is already upstream is safe to drop, but there is // no branch to delete, so the verdict must not promise one. func TestPruneDetachedHeadContainedUpstream(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/detached-clean") git(t, wt, "checkout", "--detach") git(t, f.srcDir, "branch", "-D", "benvin/detached-clean") srv := fakeGitea(t) out := runOpts(t, client(srv), pruneOpts{apply: true}) assertVerdict(t, out, "HEAD", verdictRemove, "contained in origin/main") if strings.Contains(out, verdictRemoveBranch) { t.Errorf("a detached worktree has no branch to delete:\n%s", out) } if exists(wt) { t.Error("a detached worktree contained upstream should have been removed") } } // git refuses to drop a locked worktree, and so does prune. func TestPruneKeepsLockedWorktree(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/locked") git(t, f.srcDir, "worktree", "lock", wt) srv := fakeGitea(t) out := runOpts(t, client(srv), pruneOpts{apply: true}) assertVerdict(t, out, "benvin/locked", verdictKeep, "locked") if !exists(wt) { t.Error("a locked worktree must not be removed") } } // Unproven work is only safe to abandon because the branch keeps it, so the // reason has to say so rather than leaving the operator to guess. func TestPruneReasonNamesRetainedBranch(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/unpushed") writeCommit(t, wt, "u.txt", "u\n", "work") srv := fakeGitea(t) out := runOpts(t, client(srv), pruneOpts{}) assertVerdict(t, out, "benvin/unpushed", verdictRemove, "1 commit on no remote so branch benvin/unpushed is kept") if !exists(wt) { t.Error("a dry run must not remove anything") } } // --- flags ---------------------------------------------------------------- // --include-keep is the only way past a keep verdict, and even then the branch // stays, so the commits survive the worktree. func TestPruneIncludeKeepRemovesDirtyWorktreeButNotItsBranch(t *testing.T) { f := newFixture(t) wt := f.addWorktree(t, "benvin/dirty") writeCommit(t, wt, "d.txt", "d\n", "work") if err := os.WriteFile(filepath.Join(wt, "wip.txt"), []byte("wip\n"), 0o644); err != nil { t.Fatal(err) } srv := fakeGitea(t) out := runOpts(t, client(srv), pruneOpts{apply: true, includeKeep: true}) assertVerdict(t, out, "benvin/dirty", verdictKeep, "dirty") if !strings.Contains(out, "--include-keep") { t.Errorf("forcing a keep should warn it is doing so:\n%s", out) } if exists(wt) { t.Error("--include-keep should have removed the dirty worktree") } if !agent.GitBranchExists(f.srcDir, "benvin/dirty") { t.Error("--include-keep must never delete a branch") } } // --no-fetch means origin's refs are whatever is already on disk, so a tracking // ref cannot prove the work survives: the branch is kept. func TestPruneNoFetchDistrustsTrackingRefs(t *testing.T) { f, srv, closed, _ := staleFixture(t, true) out := runOpts(t, client(srv), pruneOpts{apply: true, noFetch: true}) if !strings.Contains(out, "--no-fetch") { t.Errorf("output should record that the fetch was skipped:\n%s", out) } assertVerdict(t, out, "benvin/stale-closed", verdictRemove, "is unverified") if exists(closed) { t.Error("worktree should have been removed") } if !agent.GitBranchExists(f.srcDir, "benvin/stale-closed") { t.Error("an unverified tracking ref must not authorise deleting the branch") } } // --json puts the machine-readable document on stdout alone, with the same // verdicts the table shows. func TestPruneJSONOutput(t *testing.T) { f := newFixture(t) contained := f.addWorktree(t, "benvin/contained") dirty := f.addWorktree(t, "benvin/dirty") if err := os.WriteFile(filepath.Join(dirty, "wip.txt"), []byte("wip\n"), 0o644); err != nil { t.Fatal(err) } srv := fakeGitea(t) var out, errOut bytes.Buffer if err := runPrune(&out, &errOut, client(srv), pruneOpts{jsonOut: true}); err != nil { t.Fatalf("runPrune: %v", err) } var entries []reportEntry if err := json.Unmarshal(out.Bytes(), &entries); err != nil { t.Fatalf("stdout is not JSON (%v): %s", err, out.String()) } byBranch := map[string]reportEntry{} for _, e := range entries { byBranch[e.Branch] = e } if got := byBranch["benvin/contained"]; got.Verdict != verdictRemoveBranch || got.Path != contained || !got.Managed || got.Applied { t.Errorf("contained entry = %+v", got) } if got := byBranch["benvin/dirty"]; got.Verdict != verdictKeep || got.Reason != "dirty" { t.Errorf("dirty entry = %+v", got) } if !exists(contained) { t.Error("a --json dry run must not remove anything") } _ = f } // A directory in the source root can itself be a linked worktree. Enumerating // from there lists the repo's real checkout, which must never be offered up for // removal — discovery normalises each candidate to its main checkout instead. func TestPruneNeverOffersAMainCheckout(t *testing.T) { f := newFixture(t) sibling := filepath.Join(f.root, "src", "repo-sibling") git(t, f.srcDir, "worktree", "add", sibling, "-b", "benvin/sibling", "origin/main") identity(t, sibling) srv := fakeGitea(t) out := runOpts(t, client(srv), pruneOpts{}) for _, line := range strings.Split(out, "\n") { if fields := strings.Fields(line); len(fields) > 2 && fields[2] == f.srcDir { t.Errorf("main checkout %s must not be classified: %q", f.srcDir, line) } } assertVerdict(t, out, "benvin/sibling", verdictRemoveBranch, "contained in origin/main") if strings.Contains(out, "\tmain\t") || lineForBranch(out, "main") != "" { t.Errorf("the default branch's own checkout must not appear:\n%s", out) } } // lineForBranch is lineFor without the fatal, for asserting a row is absent. func lineForBranch(out, branch string) string { for _, line := range strings.Split(out, "\n") { if fields := strings.Fields(line); len(fields) > 1 && fields[1] == branch { return line } } return "" }