Add agentws prune #13

Merged
benvin merged 3 commits from benvin/agentws-prune into main 2026-09-10 21:50:20 +10:00
11 changed files with 1156 additions and 2 deletions
Showing only changes of commit 4bbeaae8f0 - Show all commits
+8 -1
View File
@@ -19,7 +19,7 @@ like repospawner can run these tools as itself.
repos into the source root (`~/src/prodenv/<repo>`), creates worktrees under
the worktree root (`~/.cache/agentws/<repo>__<branch>`), and authenticates
clone/fetch/push via an ephemeral credential helper. Subcommands: `new`,
`list`, `rm`, `clean`, `token`, `credential`.
`list`, `rm`, `prune`, `clean`, `token`, `credential`.
All tools are separate `main` packages under `cmd/` and share the
`internal/agent` package (Vault AppRole login, Gitea REST client, PR-ref
@@ -31,6 +31,7 @@ parsing, watch-state comparison, git worktree helpers).
cmd/agentpr/main.go # agentpr CLI (pr create / pr comment / whoami)
cmd/watchpr/main.go # watchpr CLI (poll + meaningful-change exit)
cmd/agentws/main.go # agentws CLI (new / list / rm / clean / token / credential)
cmd/agentws/prune.go # agentws prune (classify worktrees, remove the safe ones)
cmd/agentvault/main.go # agentvault CLI (seed-outpost / seed-oauth)
internal/agent/ # shared plumbing:
token.go # env config + in-process Gitea-token cache
@@ -186,5 +187,11 @@ wrapped per stage (login / read denied / write denied) via `ErrVaultDenied`.
`seed-oauth` reports key names only.
- `--rotate` regenerates the `client_secret` too, which then no longer matches
the IdP provider unless that is rotated alongside.
- `agentws prune` is a dry run unless `--yes`. It matches a branch to its PR on
`head.label`: Gitea rewrites `head.ref` to `refs/pull/<n>/head` once the branch
is deleted, which merging does, so `head.ref` matching misses every merged PR.
Git signals (`merge-base --is-ancestor`, `git cherry`) are authoritative and
offline-safe; an unreachable Gitea only means no branch gets deleted without
git proof.
- CI "combined status" comes from `/commits/{sha}/status`; an empty head SHA
yields an empty state without an API call.
+25
View File
@@ -104,6 +104,11 @@ agentws list
agentws rm benvin/my-change
agentws rm ~/.cache/agentws/argocd-apps__benvin-my-change --delete-branch
# Classify every managed worktree; dry run unless --yes is given
agentws prune
agentws prune --yes
agentws prune --yes --keep-branches
# Remove every managed worktree and prune each source repo
agentws clean
@@ -111,6 +116,26 @@ agentws clean
agentws token
```
### prune
`agentws prune` decides, per worktree, whether its work is safely upstream:
| Signal (first match wins) | Verdict |
|---|---|
| uncommitted or untracked changes | keep |
| branch has an open PR | keep |
| tip contained in `origin/<default>`, or `git cherry` finds no unmerged patch, or its PR is merged | remove worktree + local branch |
| PR closed unmerged and the branch is still on origin | remove worktree + local branch |
| anything else | remove worktree, keep the branch |
The git checks are authoritative and work offline: these repos squash-merge, so
a merged branch's commits carry different SHAs upstream and a plain
`rev-list origin/<default>..HEAD` count proves nothing. Gitea PR state only adds
to the git answer — when it cannot be reached, prune says so and never deletes a
branch it could not prove. Matching a branch to its PR uses `head.label`, since
Gitea rewrites `head.ref` to `refs/pull/<n>/head` once the branch is deleted on
merge.
### Auth / credential-helper design
Gitea tokens minted from Vault are short-lived (~1h), so `agentws` never
+2
View File
@@ -13,6 +13,7 @@
// agentws new <repo> [--branch benvin/<name>] [--from <base-branch>]
// agentws list
// agentws rm <path-or-branch> [--delete-branch]
// agentws prune [--yes] [--keep-branches]
// agentws clean
// agentws token
// agentws credential get # git credential-helper protocol on stdin
@@ -54,6 +55,7 @@ func newRootCmd() *cobra.Command {
newNewCmd(),
newListCmd(),
newRmCmd(),
newPruneCmd(),
newCleanCmd(),
newTokenCmd(),
newCredentialCmd(),
+250
View File
@@ -0,0 +1,250 @@
package main
import (
"errors"
"fmt"
"io"
"path/filepath"
"sort"
"git.unkin.net/unkin/agent-tools/internal/agent"
"github.com/spf13/cobra"
)
// Verdicts a worktree can be classified into.
const (
verdictKeep = "keep"
verdictRemove = "remove"
verdictRemoveBranch = "remove+branch"
)
// prLister is the slice of the Gitea client prune needs, so tests can drive
// classification without a live server.
type prLister interface {
ListPRs(repoPath, state string) ([]agent.PullRequest, error)
}
type pruneResult struct {
wt managedWt
verdict string
reason string
}
// repoCtx is the per-repo state classification is decided against.
type repoCtx struct {
srcDir string
defBranch string
prs map[string]agent.PullRequest
prsKnown bool
}
func newPruneCmd() *cobra.Command {
var apply, keepBranches bool
cmd := &cobra.Command{
Use: "prune",
Short: "Classify managed worktrees and remove the ones whose work is safely upstream",
Long: "prune inspects every managed worktree, classifies it against git and its Gitea\npull request, and removes the ones whose work is provably upstream. It is a dry\nrun unless --yes is given.",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
return runPrune(cmd.OutOrStdout(), pruneClient(), apply, keepBranches)
},
}
f := cmd.Flags()
f.BoolVar(&apply, "yes", false, "Actually remove worktrees (default is a dry run)")
f.BoolVar(&keepBranches, "keep-branches", false, "Never delete a local branch, whatever the classification")
return cmd
}
// pruneClient builds a Gitea client, falling back to anonymous access when no
// token can be minted; prune degrades to git-only signals if that fails too.
func pruneClient() prLister {
tok, err := agent.GiteaToken()
if err != nil {
tok = ""
}
return agent.NewGiteaClient(tok)
}
func runPrune(out io.Writer, prs prLister, apply, keepBranches bool) error {
managed, err := managedWorktrees()
if err != nil {
return err
}
if len(managed) == 0 {
_, _ = fmt.Fprintln(out, "no managed worktrees")
return nil
}
byRepo := map[string][]managedWt{}
for _, w := range managed {
byRepo[w.srcDir] = append(byRepo[w.srcDir], w)
}
srcDirs := make([]string, 0, len(byRepo))
for dir := range byRepo {
srcDirs = append(srcDirs, dir)
}
sort.Strings(srcDirs)
var results []pruneResult
for _, srcDir := range srcDirs {
ctx, err := newRepoCtx(out, prs, srcDir)
if err != nil {
for _, w := range byRepo[srcDir] {
results = append(results, pruneResult{wt: w, verdict: verdictKeep, reason: "repo state unknown: " + err.Error()})
}
continue
}
for _, w := range byRepo[srcDir] {
res, err := classify(w, ctx)
if err != nil {
res = pruneResult{wt: w, verdict: verdictKeep, reason: "inspection failed: " + err.Error()}
}
results = append(results, res)
}
}
for _, r := range results {
_, _ = fmt.Fprintf(out, "%-44s %-34s %-14s %s\n", filepath.Base(r.wt.path), r.wt.branch, r.verdict, r.reason)
}
if !apply {
_, _ = fmt.Fprintln(out, "dry run: nothing removed (pass --yes to apply)")
return nil
}
var errs []error
for _, r := range results {
if r.verdict == verdictKeep {
continue
}
deleteBranch := r.verdict == verdictRemoveBranch && !keepBranches
if err := removeWorktree(out, r.wt, deleteBranch); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", r.wt.path, err))
}
}
return errors.Join(errs...)
}
// newRepoCtx refreshes a source repo and collects the signals prune classifies
// against. A failed fetch or an unreachable Gitea is reported and tolerated:
// the git-only signals still work offline.
func newRepoCtx(out io.Writer, prs prLister, srcDir string) (repoCtx, error) {
ctx := repoCtx{srcDir: srcDir, prs: map[string]agent.PullRequest{}}
repo := filepath.Base(srcDir)
if err := agent.GitFetchPrune(srcDir, "origin", credentialHelperArgs()...); err != nil {
_, _ = fmt.Fprintf(out, "warn: fetch %s: %v (using local refs)\n", repo, err)
}
def, err := agent.GitRemoteDefaultBranch(srcDir, "origin")
if err != nil {
return repoCtx{}, err
}
ctx.defBranch = def
if prs == nil {
return ctx, nil
}
list, err := prs.ListPRs(repoPath(srcDir, repo), "all")
if err != nil {
_, _ = fmt.Fprintf(out, "warn: list PRs for %s: %v (git signals only)\n", repo, err)
return ctx, nil
}
ctx.prs = prsByBranch(list)
ctx.prsKnown = true
return ctx, nil
}
// repoPath is the Gitea "owner/repo" for a checkout, read from origin's URL
// because not every managed repo lives under AGENTWS_OWNER.
func repoPath(srcDir, repo string) string {
url, err := agent.GitRemoteURL(srcDir, "origin")
if err == nil && agent.RemoteHost(url) == giteaHost() {
if path, err := agent.RepoPathFromRemoteURL(url); err == nil {
return path
}
}
return owner() + "/" + repo
}
// prsByBranch indexes PRs by head branch, preferring an open PR and otherwise
// the most recent one when a branch has been used more than once.
func prsByBranch(list []agent.PullRequest) map[string]agent.PullRequest {
out := map[string]agent.PullRequest{}
for _, pr := range list {
branch := agent.PRHeadBranch(pr)
if branch == "" {
continue
}
if cur, ok := out[branch]; ok && !supersedes(pr, cur) {
continue
}
out[branch] = pr
}
return out
}
func supersedes(a, b agent.PullRequest) bool {
if a.IsOpen() != b.IsOpen() {
return a.IsOpen()
}
if a.Merged != b.Merged {
return a.Merged
}
return a.Number > b.Number
}
// classify applies the prune precedence: dirty and open-PR worktrees are kept,
// provably-upstream work loses its branch too, and anything unproven keeps its
// branch so no commits become unreachable.
func classify(wt managedWt, ctx repoCtx) (pruneResult, error) {
res := pruneResult{wt: wt}
dirty, err := agent.GitIsDirty(wt.path)
if err != nil {
return res, err
}
if dirty {
res.verdict, res.reason = verdictKeep, "dirty"
return res, nil
}
pr, hasPR := ctx.prs[wt.branch]
if hasPR && pr.IsOpen() {
res.verdict, res.reason = verdictKeep, fmt.Sprintf("PR open #%d", pr.Number)
return res, nil
}
upstream := "origin/" + ctx.defBranch
contained, err := agent.GitIsAncestor(wt.path, "HEAD", upstream)
if err != nil {
return res, err
}
if contained {
res.verdict, res.reason = verdictRemoveBranch, "contained in "+upstream
return res, nil
}
unmerged, err := agent.GitUnmergedCommits(wt.path, upstream, "HEAD")
if err != nil {
return res, err
}
if unmerged == 0 {
res.verdict, res.reason = verdictRemoveBranch, "cherry-clean against "+upstream
return res, nil
}
if hasPR && pr.Merged {
res.verdict, res.reason = verdictRemoveBranch, fmt.Sprintf("PR merged #%d", pr.Number)
return res, nil
}
if hasPR {
if agent.GitRemoteBranchExists(ctx.srcDir, "origin", wt.branch) {
res.verdict, res.reason = verdictRemoveBranch, fmt.Sprintf("PR closed #%d, branch on origin", pr.Number)
return res, nil
}
res.verdict, res.reason = verdictRemove, fmt.Sprintf("PR closed #%d, branch gone", pr.Number)
return res, nil
}
res.verdict = verdictRemove
res.reason = "no PR"
if !ctx.prsKnown {
res.reason = "PR state unknown"
}
return res, nil
}
+456
View File
@@ -0,0 +1,456 @@
package main
import (
"bytes"
"encoding/json"
"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/<n>/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 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()
var out bytes.Buffer
if err := runPrune(&out, prs, apply, keepBranches); err != nil {
t.Fatalf("runPrune: %v\n%s", err, out.String())
}
return out.String()
}
func lineFor(t *testing.T, out, branch string) string {
t.Helper()
for _, line := range strings.Split(out, "\n") {
if strings.Contains(line, " "+branch+" ") {
return line
}
}
t.Fatalf("no line for branch %q in:\n%s", branch, out)
return ""
}
func assertVerdict(t *testing.T, out, branch, verdict, reason string) {
t.Helper()
line := lineFor(t, out, branch)
fields := strings.Fields(line)
if len(fields) < 3 || fields[2] != 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/<n>/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")
srv := fakeGitea(t, mergedPR(3, "benvin/merged"))
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, "cherry-clean")
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, branch on origin")
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")
srv := fakeGitea(t, mergedPR(8, "benvin/merged"))
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.
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", verdictRemoveBranch, "contained")
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)
}
}
// 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)
}
}
+71
View File
@@ -3,6 +3,7 @@ package agent
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
@@ -219,6 +220,76 @@ func TestFetchStateFailsOnNon404StatusError(t *testing.T) {
}
}
// Gitea rewrites head.ref to "refs/pull/<n>/head" once the PR's branch is
// deleted, which merging does in these repos. Matching a branch against
// head.ref alone therefore finds nothing for every merged PR; head.label keeps
// the original name.
func TestPRHeadBranch(t *testing.T) {
tests := []struct {
name string
ref, label string
want string
}{
{"merged, branch deleted", "refs/pull/12/head", "benvin/merged", "benvin/merged"},
{"open PR", "benvin/open", "benvin/open", "benvin/open"},
{"fully qualified ref", "refs/heads/benvin/x", "", "benvin/x"},
{"no label falls back to ref", "benvin/y", "", "benvin/y"},
{"cross-repo label", "benvin/z", "someone:benvin/z", "benvin/z"},
{"nothing usable", "refs/pull/12/head", "", ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var pr PullRequest
pr.Head.Ref = tt.ref
pr.Head.Label = tt.label
if got := PRHeadBranch(pr); got != tt.want {
t.Errorf("PRHeadBranch(ref=%q,label=%q) = %q, want %q", tt.ref, tt.label, got, tt.want)
}
})
}
}
func TestListPRsPaginates(t *testing.T) {
var pages []string
mux := http.NewServeMux()
mux.HandleFunc("/api/v1/repos/unkin/repo/pulls", func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
pages = append(pages, q.Get("page"))
if q.Get("state") != "all" {
t.Errorf("state = %q, want all", q.Get("state"))
}
if q.Get("page") == "1" {
full := make([]string, 0, prPageSize)
for i := 0; i < prPageSize; i++ {
full = append(full, fmt.Sprintf(`{"number":%d,"state":"closed","merged":true,"head":{"ref":"refs/pull/%d/head","label":"benvin/b%d"}}`, i+1, i+1, i+1))
}
_, _ = io.WriteString(w, "["+strings.Join(full, ",")+"]")
return
}
_, _ = io.WriteString(w, `[{"number":99,"state":"open","head":{"ref":"benvin/last","label":"benvin/last"}}]`)
})
srv := httptest.NewServer(mux)
defer srv.Close()
c := &GiteaClient{BaseURL: srv.URL, HTTP: srv.Client()}
prs, err := c.ListPRs("unkin/repo", "all")
if err != nil {
t.Fatalf("ListPRs: %v", err)
}
if len(prs) != prPageSize+1 {
t.Fatalf("got %d PRs, want %d", len(prs), prPageSize+1)
}
if len(pages) != 2 || pages[0] != "1" || pages[1] != "2" {
t.Errorf("pages requested = %v, want [1 2]", pages)
}
if got := PRHeadBranch(prs[0]); got != "benvin/b1" {
t.Errorf("first PR head branch = %q, want benvin/b1", got)
}
if !prs[len(prs)-1].IsOpen() {
t.Error("last PR should be open")
}
}
func TestGiteaAPIError(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/api/v1/repos/unkin/repo/pulls", func(w http.ResponseWriter, r *http.Request) {
+67
View File
@@ -2,6 +2,7 @@ package agent
import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
@@ -67,6 +68,14 @@ func GitFetch(repoDir, remote string, globalArgs ...string) error {
return err
}
// GitFetchPrune runs `git fetch --prune <remote>` in repoDir so remote-tracking
// refs for branches deleted on the remote (e.g. after a merge) disappear.
func GitFetchPrune(repoDir, remote string, globalArgs ...string) error {
args := append(append([]string{}, globalArgs...), "fetch", "--prune", remote)
_, err := runGit(repoDir, args...)
return err
}
// GitRemoteDefaultBranch returns the short name of remote's default branch
// (e.g. "main") by resolving refs/remotes/<remote>/HEAD.
func GitRemoteDefaultBranch(repoDir, remote string) (string, error) {
@@ -83,6 +92,64 @@ func GitBranchExists(repoDir, branch string) bool {
return err == nil
}
// GitRemoteURL returns the configured URL for a remote.
func GitRemoteURL(repoDir, remote string) (string, error) {
return runGit(repoDir, "remote", "get-url", remote)
}
// GitRemoteBranchExists reports whether a remote-tracking ref for branch exists
// (accurate only after a pruning fetch).
func GitRemoteBranchExists(repoDir, remote, branch string) bool {
_, err := runGit(repoDir, "show-ref", "--verify", "--quiet", "refs/remotes/"+remote+"/"+branch)
return err == nil
}
// GitIsDirty reports whether the checkout at dir has uncommitted or untracked
// changes.
func GitIsDirty(dir string) (bool, error) {
out, err := runGit(dir, "status", "--porcelain")
if err != nil {
return false, err
}
return strings.TrimSpace(out) != "", nil
}
// GitIsAncestor reports whether ancestor is reachable from descendant.
func GitIsAncestor(repoDir, ancestor, descendant string) (bool, error) {
cmd := exec.Command("git", "merge-base", "--is-ancestor", ancestor, descendant)
cmd.Dir = repoDir
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
// Exit 1 is the documented "not an ancestor" answer; anything else is a
// real failure (bad ref, not a repo).
var exitErr *exec.ExitError
if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 {
return false, nil
}
return false, fmt.Errorf("git merge-base --is-ancestor %s %s: %w: %s",
ancestor, descendant, err, strings.TrimSpace(stderr.String()))
}
return true, nil
}
// GitUnmergedCommits counts commits on head whose patch has no equivalent on
// upstream, using `git cherry` so squash- and rebase-merged work is recognised
// despite its rewritten SHAs.
func GitUnmergedCommits(repoDir, upstream, head string) (int, error) {
out, err := runGit(repoDir, "cherry", upstream, head)
if err != nil {
return 0, err
}
n := 0
for _, line := range strings.Split(out, "\n") {
if strings.HasPrefix(strings.TrimSpace(line), "+") {
n++
}
}
return n, nil
}
// GitWorktreeAdd adds a worktree at path checked out to branch. When the branch
// already exists it is reused; otherwise it is created from startPoint.
func GitWorktreeAdd(repoDir, path, branch, startPoint string) error {
+128
View File
@@ -185,6 +185,134 @@ func TestGitWorktreeLifecycle(t *testing.T) {
}
}
// commit writes a file and commits it, returning the new HEAD sha.
func commit(t *testing.T, dir, name, content, msg string) string {
t.Helper()
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil {
t.Fatal(err)
}
if _, err := runGit(dir, "add", "."); err != nil {
t.Fatalf("add: %v", err)
}
if _, err := runGit(dir, "commit", "-m", msg); err != nil {
t.Fatalf("commit: %v", err)
}
sha, err := runGit(dir, "rev-parse", "HEAD")
if err != nil {
t.Fatalf("rev-parse: %v", err)
}
return sha
}
func TestGitIsAncestor(t *testing.T) {
srcDir := newTempRepos(t)
base, err := runGit(srcDir, "rev-parse", "HEAD")
if err != nil {
t.Fatal(err)
}
tip := commit(t, srcDir, "a.txt", "a\n", "add a")
if ok, err := GitIsAncestor(srcDir, base, tip); err != nil || !ok {
t.Errorf("GitIsAncestor(base, tip) = %v, %v; want true", ok, err)
}
if ok, err := GitIsAncestor(srcDir, tip, base); err != nil || ok {
t.Errorf("GitIsAncestor(tip, base) = %v, %v; want false with no error", ok, err)
}
if _, err := GitIsAncestor(srcDir, "no-such-ref", tip); err == nil {
t.Error("GitIsAncestor with a bogus ref should error, not report false")
}
}
// These repos squash-merge, so merged work keeps its local SHA while the
// upstream commit is a different one carrying the same patch. `git cherry` must
// see that as merged even though the SHAs differ.
func TestGitUnmergedCommitsIgnoresRewrittenSHAs(t *testing.T) {
srcDir := newTempRepos(t)
if _, err := runGit(srcDir, "checkout", "-b", "feature"); err != nil {
t.Fatalf("checkout: %v", err)
}
commit(t, srcDir, "f.txt", "hello\n", "add f")
n, err := GitUnmergedCommits(srcDir, "origin/main", "HEAD")
if err != nil {
t.Fatalf("GitUnmergedCommits: %v", err)
}
if n != 1 {
t.Fatalf("unmerged before upstream landing = %d, want 1", n)
}
// Land the same patch upstream under a different SHA.
if _, err := runGit(srcDir, "checkout", "main"); err != nil {
t.Fatalf("checkout main: %v", err)
}
commit(t, srcDir, "f.txt", "hello\n", "squashed f")
if _, err := runGit(srcDir, "push", "origin", "main"); err != nil {
t.Fatalf("push: %v", err)
}
if err := GitFetchPrune(srcDir, "origin"); err != nil {
t.Fatalf("GitFetchPrune: %v", err)
}
if ok, err := GitIsAncestor(srcDir, "feature", "origin/main"); err != nil || ok {
t.Fatalf("squash-merged branch must not be an ancestor: %v, %v", ok, err)
}
n, err = GitUnmergedCommits(srcDir, "origin/main", "feature")
if err != nil {
t.Fatalf("GitUnmergedCommits: %v", err)
}
if n != 0 {
t.Errorf("unmerged after upstream landing = %d, want 0", n)
}
}
func TestGitIsDirty(t *testing.T) {
srcDir := newTempRepos(t)
if dirty, err := GitIsDirty(srcDir); err != nil || dirty {
t.Fatalf("clean checkout reported dirty=%v, err=%v", dirty, err)
}
if err := os.WriteFile(filepath.Join(srcDir, "scratch.txt"), []byte("wip\n"), 0o644); err != nil {
t.Fatal(err)
}
if dirty, err := GitIsDirty(srcDir); err != nil || !dirty {
t.Errorf("untracked file must count as dirty: dirty=%v, err=%v", dirty, err)
}
}
func TestGitRemoteBranchExists(t *testing.T) {
srcDir := newTempRepos(t)
if !GitRemoteBranchExists(srcDir, "origin", "main") {
t.Error("origin/main should exist")
}
if GitRemoteBranchExists(srcDir, "origin", "benvin/nope") {
t.Error("origin/benvin/nope should not exist")
}
if _, err := runGit(srcDir, "checkout", "-b", "benvin/pushed"); err != nil {
t.Fatalf("checkout: %v", err)
}
commit(t, srcDir, "p.txt", "p\n", "add p")
if _, err := runGit(srcDir, "push", "origin", "benvin/pushed"); err != nil {
t.Fatalf("push: %v", err)
}
if err := GitFetchPrune(srcDir, "origin"); err != nil {
t.Fatalf("GitFetchPrune: %v", err)
}
if !GitRemoteBranchExists(srcDir, "origin", "benvin/pushed") {
t.Error("pushed branch should have a remote-tracking ref")
}
if _, err := runGit(srcDir, "push", "origin", "--delete", "benvin/pushed"); err != nil {
t.Fatalf("delete remote branch: %v", err)
}
if err := GitFetchPrune(srcDir, "origin"); err != nil {
t.Fatalf("GitFetchPrune: %v", err)
}
if GitRemoteBranchExists(srcDir, "origin", "benvin/pushed") {
t.Error("a pruning fetch must drop the tracking ref for a deleted remote branch")
}
}
// resolve canonicalizes a path (temp dirs may live behind symlinks like /var).
func resolve(t *testing.T, p string) string {
t.Helper()
+54 -1
View File
@@ -137,10 +137,63 @@ type PullRequest struct {
Mergeable bool `json:"mergeable"`
HTMLURL string `json:"html_url"`
Head struct {
Sha string `json:"sha"`
Sha string `json:"sha"`
Ref string `json:"ref"`
Label string `json:"label"`
} `json:"head"`
}
// prPageSize is the per-page limit for the pulls listing; maxPRPages caps how
// far back a listing walks.
const (
prPageSize = 50
maxPRPages = 20
)
// ListPRs lists a repo's pull requests in the given state ("open", "closed" or
// "all"), following pagination.
func (c *GiteaClient) ListPRs(repoPath, state string) ([]PullRequest, error) {
if state == "" {
state = "all"
}
var all []PullRequest
for page := 1; page <= maxPRPages; page++ {
var batch []PullRequest
path := fmt.Sprintf("/api/v1/repos/%s/pulls?state=%s&limit=%d&page=%d", repoPath, state, prPageSize, page)
if err := c.do(http.MethodGet, path, nil, &batch); err != nil {
return nil, err
}
all = append(all, batch...)
if len(batch) < prPageSize {
break
}
}
return all, nil
}
// PRHeadBranch returns the branch a PR was opened from. Gitea rewrites head.ref
// to "refs/pull/<n>/head" once the branch is deleted (which merging does), so
// head.label — which keeps the original name — is authoritative.
func PRHeadBranch(pr PullRequest) string {
if label := pr.Head.Label; label != "" && !strings.HasPrefix(label, "refs/pull/") {
// Cross-repo PRs label as "<owner>:<branch>".
if _, branch, ok := strings.Cut(label, ":"); ok {
return branch
}
return label
}
ref := pr.Head.Ref
if strings.HasPrefix(ref, "refs/pull/") {
return ""
}
return strings.TrimPrefix(ref, "refs/heads/")
}
// IsOpen reports whether a PR is still open (not merged, not closed).
func (pr PullRequest) IsOpen() bool {
return pr.State == "open" && !pr.Merged
}
// CreatePROptions are the fields for opening a PR.
type CreatePROptions struct {
Base string `json:"base"`
+46
View File
@@ -68,6 +68,52 @@ func ParseDurationFlag(flag, value string) (time.Duration, error) {
return d, nil
}
// RemoteHost returns the host a git remote URL points at, or "" for a local
// path remote.
func RemoteHost(remote string) string {
s := strings.TrimSpace(remote)
if _, after, ok := strings.Cut(s, "://"); ok {
host, _, _ := strings.Cut(after, "/")
if _, bare, ok := strings.Cut(host, "@"); ok {
host = bare
}
return host
}
if strings.HasPrefix(s, "/") || strings.HasPrefix(s, ".") {
return ""
}
host, _, ok := strings.Cut(s, ":")
if !ok {
return ""
}
if _, bare, ok := strings.Cut(host, "@"); ok {
host = bare
}
return host
}
// RepoPathFromRemoteURL extracts the "owner/repo" API path from a git remote
// URL, accepting both https and scp-style ssh forms.
func RepoPathFromRemoteURL(remote string) (string, error) {
s := strings.TrimSuffix(strings.TrimSuffix(strings.TrimSpace(remote), "/"), ".git")
switch {
case strings.Contains(s, "://"):
_, after, _ := strings.Cut(s, "://")
_, path, ok := strings.Cut(after, "/")
if !ok {
return "", fmt.Errorf("remote URL %q has no repo path", remote)
}
s = path
case strings.Contains(s, ":"):
_, s, _ = strings.Cut(s, ":")
}
parts := strings.Split(strings.Trim(s, "/"), "/")
if len(parts) < 2 || parts[len(parts)-2] == "" || parts[len(parts)-1] == "" {
return "", fmt.Errorf("remote URL %q is not owner/repo shaped", remote)
}
return parts[len(parts)-2] + "/" + parts[len(parts)-1], nil
}
// ParseRepo validates and splits an "owner/repo" string.
func ParseRepo(s string) (owner, repo string, err error) {
s = strings.TrimSpace(s)
+49
View File
@@ -132,3 +132,52 @@ func TestParseDurationFlagErrorMessage(t *testing.T) {
}
}
}
// Not every managed repo lives under the default owner, so the API path comes
// from origin's URL rather than the directory name.
func TestRepoPathFromRemoteURL(t *testing.T) {
tests := []struct {
in string
want string
}{
{"https://git.unkin.net/unkin/agent-tools.git", "unkin/agent-tools"},
{"https://git.unkin.net/unkinben/dotfiles.git", "unkinben/dotfiles"},
{"https://git.unkin.net/unkin/agent-tools", "unkin/agent-tools"},
{"https://user@git.unkin.net/unkin/agent-tools.git", "unkin/agent-tools"},
{"ssh://git@git.unkin.net:2222/unkin/agent-tools.git", "unkin/agent-tools"},
{"git@git.unkin.net:unkin/agent-tools.git", "unkin/agent-tools"},
}
for _, tt := range tests {
got, err := RepoPathFromRemoteURL(tt.in)
if err != nil {
t.Errorf("RepoPathFromRemoteURL(%q): %v", tt.in, err)
continue
}
if got != tt.want {
t.Errorf("RepoPathFromRemoteURL(%q) = %q, want %q", tt.in, got, tt.want)
}
}
for _, bad := range []string{"", "https://git.unkin.net", "agent-tools"} {
if got, err := RepoPathFromRemoteURL(bad); err == nil {
t.Errorf("RepoPathFromRemoteURL(%q) = %q, want error", bad, got)
}
}
}
func TestRemoteHost(t *testing.T) {
tests := []struct {
in, want string
}{
{"https://git.unkin.net/unkin/repo.git", "git.unkin.net"},
{"https://user@git.unkin.net/unkin/repo.git", "git.unkin.net"},
{"ssh://git@git.unkin.net:2222/unkin/repo.git", "git.unkin.net:2222"},
{"git@git.unkin.net:unkin/repo.git", "git.unkin.net"},
{"/tmp/fixture/origin.git", ""},
{"../other/origin.git", ""},
}
for _, tt := range tests {
if got := RemoteHost(tt.in); got != tt.want {
t.Errorf("RemoteHost(%q) = %q, want %q", tt.in, got, tt.want)
}
}
}