Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
1988 lines (1868 loc) · 65.1 KB
/
Copy pathmain.go
File metadata and controls
1988 lines (1868 loc) · 65.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// agentyard scans every git worktree under a root folder, classifies each one
// (merged / open PR / safe to delete / keep), tracks the open PRs you authored
// and your Claude Code / Codex sessions, and serves it all as one HTML page —
// on this Mac, or on the LAN over mDNS. cli.go holds the commands; this file
// is the scanner and the web server.
package main
import (
"bytes"
"context"
"crypto/sha256"
_ "embed"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"hash/fnv"
"html/template"
"io/fs"
"log"
"net"
"net/http"
"net/netip"
"net/url"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
)
// Serve flags live on their own FlagSet so every subcommand can parse its own;
// the pointers keep their defaults when nothing is parsed (tests, demo).
var (
home, _ = os.UserHomeDir()
serveFlags = flag.NewFlagSet("serve", flag.ContinueOnError)
flagRoot = serveFlags.String("root", filepath.Join(home, "Projects"), "folder to search for repositories")
flagDepth = serveFlags.Int("depth", 5, "max folder depth below -root to look for repositories")
flagListen = serveFlags.String("listen", defaultListen, "HTTP listen address (\":80\" serves the whole LAN)")
flagInterval = serveFlags.Duration("interval", 5*time.Minute, "rescan interval")
flagSizeTTL = serveFlags.Duration("size-ttl", 30*time.Minute, "how long a measured worktree size is reused")
flagMDNS = serveFlags.String("mdns", "", "publish as http://<name>.local over mDNS (empty: off; ignored on loopback)")
flagOnce = serveFlags.Bool("once", false, "scan once, print the worktree JSON to stdout and exit")
flagSummary = serveFlags.String("summary", "off", "summary provider: off, auto, claude or codex")
flagSummaryAt = serveFlags.String("summary-at", "07:00", "daily summary time (local HH:MM)")
flagSummaryModel = serveFlags.String("summary-model", "", "summary model (default: haiku for Claude, gpt-6-luna for Codex)")
)
const (
defaultPort = 4777
defaultListen = "127.0.0.1:4777"
)
// ---------------------------------------------------------------- model
type PR struct {
Number int `json:"number"`
State string `json:"state"`
IsDraft bool `json:"isDraft"`
HeadRefOid string `json:"headRefOid"`
URL string `json:"url"`
Title string `json:"title"`
}
type Worktree struct {
Path string `json:"path"`
Folder string `json:"folder"`
Branch string `json:"branch"`
Sha string `json:"sha"`
SizeKB int64 `json:"sizeKB"`
Modified int `json:"modified"`
Untracked int `json:"untracked"`
Unpushed int `json:"unpushed"`
InDefault bool `json:"inDefault"`
RemoteBranch bool `json:"remoteBranch"`
BranchURL string `json:"branchURL,omitempty"`
PR *PR `json:"pr,omitempty"`
PRRel string `json:"prRel,omitempty"` // same | behind | diverged | unknown
LastCommit time.Time `json:"lastCommit"`
LastActive time.Time `json:"lastActive"` // newest of commit, index and changed-file mtimes
Prunable bool `json:"prunable"`
InUse []Use `json:"inUse,omitempty"`
// Submodules counts initialized submodules, each checked to hold no work
// its remote lacks; git removes such a worktree only with --force.
Submodules int `json:"submodules,omitempty"`
// ContentRef is the remote ref whose tree already holds all of the worktree's
// local work (uncommitted files and unpushed commits); see contentMatch.
// ContentInDefault says that ref is the default branch.
ContentRef string `json:"contentRef,omitempty"`
ContentInDefault bool `json:"contentInDefault,omitempty"`
ContentHistory bool `json:"contentHistory,omitempty"` // matched only as older versions in ContentRef's history
Ignored []string `json:"ignored,omitempty"` // ignored files a removal deletes; checked only when reclaimable
Hazard string `json:"hazard,omitempty"` // work a removal would lose that status can't see
Verdict string `json:"verdict"`
Reason string `json:"reason"`
// RemoveCmd is the copyable command that removes a reclaimable worktree:
// agentyard remove, which re-checks it when it runs. A bare git command
// would skip the in-use check, and for one with uncommitted files or
// commits only its HEAD holds, every other check too.
RemoveCmd string `json:"removeCmd,omitempty"`
headOnly bool // detached, with commits no branch, tag or remote has
ignoredSum string // digest of every ignored entry, submodules' too, for removal plans
submoduleSum string // the submodules' part of ignoredSum, which a removal re-checks last
}
type Repo struct {
Path string `json:"path"`
Slug string `json:"slug"`
Default string `json:"default"`
Errors []string `json:"errors,omitempty"`
Worktrees []*Worktree `json:"worktrees"`
}
type Group struct {
Name string `json:"name"`
Anchor string `json:"anchor,omitempty"`
Count int `json:"count"`
SizeKB int64 `json:"sizeKB"`
ReclaimKB int64 `json:"reclaimKB"`
Verdicts []int `json:"verdicts"` // indexed like verdicts
}
type Snapshot struct {
Version string `json:"version,omitempty"`
Started time.Time `json:"started,omitempty"` // when the scan began; At is when it ended
At time.Time `json:"at"`
Took time.Duration `json:"took"`
Repos []*Repo `json:"repos"`
ByRepo []*Group `json:"byRepo"`
ByFolder []*Group `json:"byFolder"`
Total *Group `json:"total"`
DiskFree uint64 `json:"diskFree"`
DiskTotal uint64 `json:"diskTotal"`
Errors []string `json:"errors,omitempty"`
}
// Verdicts in display order. Only merged work is
// safe to delete — being pushed somewhere does not make a branch disposable.
var verdicts = []struct {
Key, Label string
Reclaimable bool
}{
{"merged", "Safe to delete", true},
{"prunable", "Prunable", true},
{"inuse", "In use", false},
{"unmerged", "Not merged", false},
{"open", "Open PR", false},
{"keep", "Keep", false},
}
func verdictIndex(v string) int {
for i, x := range verdicts {
if x.Key == v {
return i
}
}
return len(verdicts)
}
func reclaimable(v string) bool {
i := verdictIndex(v)
return i < len(verdicts) && verdicts[i].Reclaimable
}
// verdictLabel is a verdict's human name; an unknown key (say, from a cache
// written by another version) is shown as itself.
func verdictLabel(v string) string {
if i := verdictIndex(v); i < len(verdicts) {
return verdicts[i].Label
}
return v
}
// ---------------------------------------------------------------- exec
func run(timeout time.Duration, dir, name string, args ...string) (string, error) {
return runEnv(timeout, dir, nil, name, args...)
}
// runEnv is run with extra environment variables, which win over inherited ones.
func runEnv(timeout time.Duration, dir string, env []string, name string, args ...string) (string, error) {
return runInput(timeout, dir, env, "", name, args...)
}
// runInput is runEnv with input on the command's standard input.
func runInput(timeout time.Duration, dir string, env []string, input, name string, args ...string) (string, error) {
return execute(timeout, dir, os.Environ(), env, input, name, args...)
}
// runIsolated is runEnv without any GIT_ variable this process inherited
// (GIT_CONFIG_PARAMETERS, GIT_COMMON_DIR, GIT_OBJECT_DIRECTORY…), so only env
// says which repository and settings git uses.
func runIsolated(timeout time.Duration, dir string, env []string, name string, args ...string) (string, error) {
var base []string
for _, kv := range os.Environ() {
if !strings.HasPrefix(kv, "GIT_") {
base = append(base, kv)
}
}
return execute(timeout, dir, base, env, "", name, args...)
}
// commandError preserves the deadline and final stderr line for provider callers.
type commandError struct {
Err error
LastLine string
message string
}
func (e *commandError) Error() string { return e.message }
func (e *commandError) Unwrap() error { return e.Err }
func execute(timeout time.Duration, dir string, base, env []string, input, name string, args ...string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
cmd := exec.CommandContext(ctx, name, args...)
cmd.Dir = dir
// A killed command's children (a filter, ssh) can hold its pipes open;
// stop waiting for them soon after.
cmd.WaitDelay = 5 * time.Second
if input != "" {
cmd.Stdin = strings.NewReader(input)
}
// GIT_OPTIONAL_LOCKS=0: `git status` must never take index.lock, or it races
// with whatever is committing in that worktree at the same moment.
cmd.Env = append(append(base,
"GIT_OPTIONAL_LOCKS=0", "GIT_TERMINAL_PROMPT=0", "GH_PROMPT_DISABLED=1", "LC_ALL=C",
"GIT_SSH_COMMAND=ssh -o BatchMode=yes -o ConnectTimeout=10"), env...)
var out, stderr bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &stderr
if err := cmd.Run(); err != nil {
// The last line, unless git said fatal:/error: earlier; its hint lines
// ("use 'remove -f -f'") are not the reason.
lines := strings.Split(strings.TrimSpace(stderr.String()), "\n")
last := lines[len(lines)-1]
msg := last
for _, l := range lines {
if strings.HasPrefix(l, "fatal: ") || strings.HasPrefix(l, "error: ") {
msg = l
}
}
if ctx.Err() != nil {
err = ctx.Err()
}
first := ""
if len(args) > 0 {
first = args[0]
}
return out.String(), &commandError{Err: err, LastLine: last, message: fmt.Sprintf("%s %s: %v %s", name, first, err, msg)}
}
return out.String(), nil
}
// gitTimeout bounds one git command in a scan.
const gitTimeout = 30 * time.Second
func git(dir string, args ...string) (string, error) { return run(gitTimeout, dir, "git", args...) }
// gitOK reports a command's exit status as a bool (for --is-ancestor, cat-file -e …).
func gitOK(dir string, args ...string) bool { _, err := git(dir, args...); return err == nil }
// ---------------------------------------------------------------- discovery
// skipDirs are dependency and build output: never a repository, too big to
// walk, and regenerated rather than written by hand.
var skipDirs = map[string]bool{
"node_modules": true, ".venv": true, "venv": true, "vendor": true, "dist": true, "build": true,
"target": true, ".next": true, ".cache": true, "__pycache__": true, "Pods": true, "DerivedData": true,
".terraform": true, ".turbo": true, ".nx": true,
}
// discoverRepos returns every repository under root that has at least one
// linked worktree registered (a .git directory with a worktrees/ subfolder).
func discoverRepos(root string, maxDepth int) []string {
base := strings.Count(filepath.Clean(root), string(os.PathSeparator))
var repos []string
filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
if d != nil && d.IsDir() {
return fs.SkipDir
}
return nil
}
if !d.IsDir() {
return nil
}
if d.Name() == ".git" {
if fi, err := os.Stat(filepath.Join(p, "worktrees")); err == nil && fi.IsDir() {
repos = append(repos, filepath.Dir(p))
}
return fs.SkipDir
}
if skipDirs[d.Name()] || strings.Count(p, string(os.PathSeparator))-base >= maxDepth {
return fs.SkipDir
}
return nil
})
return repos
}
// ---------------------------------------------------------------- sizes
type sizeCache struct {
mu sync.Mutex
m map[string]sizeEntry
}
type sizeEntry struct {
kb int64
at time.Time
}
func (c *sizeCache) get(path string) (int64, bool) {
c.mu.Lock()
defer c.mu.Unlock()
e, ok := c.m[path]
return e.kb, ok && time.Since(e.at) < *flagSizeTTL
}
func (c *sizeCache) measure(path string) int64 {
out, _ := run(3*time.Minute, "", "du", "-sk", path) // du exits 1 on unreadable files but still prints a total
kb, _ := strconv.ParseInt(strings.Fields(out + " 0")[0], 10, 64)
c.mu.Lock()
c.m[path] = sizeEntry{kb, time.Now()}
c.mu.Unlock()
return kb
}
// seed takes every size in snap, stamped at, so a scan re-runs git but not du.
func (c *sizeCache) seed(snap *Snapshot, at time.Time) {
c.mu.Lock()
defer c.mu.Unlock()
for _, r := range snap.Repos {
for _, w := range r.Worktrees {
c.m[w.Path] = sizeEntry{w.SizeKB, at}
}
}
}
func (c *sizeCache) retain(live map[string]bool) {
c.mu.Lock()
defer c.mu.Unlock()
for p := range c.m {
if !live[p] {
delete(c.m, p)
}
}
}
// ---------------------------------------------------------------- repo scan
var (
githubRe = regexp.MustCompile(`github\.com[:/]([^/]+/[^/]+?)(\.git)?/?$`)
prRefRe = regexp.MustCompile(`^pr-(\d+)$`)
shellSafeRe = regexp.MustCompile(`^[A-Za-z0-9_./~@%+=:,-]+$`)
nonAlnumRe = regexp.MustCompile(`[^A-Za-z0-9]+`)
)
type wtEntry struct {
path, sha, branch string
prunable bool
}
func listWorktrees(repo string) ([]wtEntry, error) {
out, err := git(repo, "worktree", "list", "--porcelain")
if err != nil {
return nil, err
}
var list []wtEntry
for _, block := range strings.Split(strings.TrimSpace(out), "\n\n") {
var e wtEntry
for _, line := range strings.Split(block, "\n") {
k, v, _ := strings.Cut(line, " ")
switch k {
case "worktree":
e.path = v
case "HEAD":
e.sha = v
case "branch":
e.branch = strings.TrimPrefix(v, "refs/heads/")
case "detached":
e.branch = "(detached)"
case "prunable":
e.prunable = true
case "bare":
e.path = ""
}
}
list = append(list, e)
}
if len(list) > 0 {
list = list[1:] // first entry is the main working tree
}
return list, nil
}
func fetch(repo, slug string, patient bool) error {
args := fetchArgs(slug)
// Retry: a DNS blip (e.g. a VPN re-establishing its tunnel) fails a
// fetch for a few seconds and would otherwise leave the repo stale for a cycle.
var err error
waits := []time.Duration{0, 10 * time.Second, 30 * time.Second}
if !patient {
waits = waits[:1]
}
for attempt, wait := range waits {
time.Sleep(wait)
if _, err = run(3*time.Minute, repo, "git", args...); err == nil {
return nil
}
log.Printf("fetch %s attempt %d: %v", filepath.Base(repo), attempt+1, err)
}
return err
}
// fetchArgs fetches origin's branches into refs/remotes/origin/, pruning.
func fetchArgs(slug string) []string {
args := []string{"-c", "gc.auto=0", "-c", "maintenance.auto=false"}
if slug != "" {
// HTTPS through gh's token: the SSH key is not SSO-authorised for every org.
return append(args, "-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential",
"fetch", "--prune", "--quiet", "--no-write-fetch-head", "--no-recurse-submodules",
"https://github.com/"+slug+".git", "+refs/heads/*:refs/remotes/origin/*")
}
return append(args, "fetch", "--prune", "--quiet", "--no-write-fetch-head", "--no-recurse-submodules", "origin")
}
// fetchGitDir fetches the branches of a submodule repository's origin into
// refs/remotes/origin/, whatever its configured refspecs, and nothing else:
// no tags, so no local tag is pruned. url is origin's URL.
func fetchGitDir(dirs []string, url string) error {
from := url
args := []string{"-c", "gc.auto=0", "-c", "maintenance.auto=false", "-c", "fetch.pruneTags=false", "-c", "remote.origin.pruneTags=false"}
if m := githubRe.FindStringSubmatch(url); m != nil {
// HTTPS through gh's token, as fetch does.
from = "https://github.com/" + m[1] + ".git"
args = append(args, "-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential")
}
args = append(args, "fetch", "--prune", "--no-tags", "--quiet", "--no-write-fetch-head", "--no-recurse-submodules",
from, "+refs/heads/*:refs/remotes/origin/*")
_, err := run(3*time.Minute, "", "git", append(dirs, args...)...)
return err
}
func defaultBranch(repo string) string {
if out, err := git(repo, "symbolic-ref", "--short", "refs/remotes/origin/HEAD"); err == nil {
return strings.TrimSpace(out)
}
for _, b := range []string{"origin/main", "origin/master"} {
if gitOK(repo, "rev-parse", "-q", "--verify", b) {
return b
}
}
return ""
}
func gqlString(s string) string { b, _ := json.Marshal(s); return string(b) }
// fetchPRs looks up the newest PR for every branch in one GraphQL request.
func fetchPRs(slug string, branches []string) (map[string]*PR, error) {
owner, name, _ := strings.Cut(slug, "/")
var q strings.Builder
fmt.Fprintf(&q, "query{repository(owner:%s,name:%s){", gqlString(owner), gqlString(name))
for i, br := range branches {
if m := prRefRe.FindStringSubmatch(br); m != nil {
fmt.Fprintf(&q, "b%d:pullRequest(number:%s){...F}", i, m[1])
} else {
fmt.Fprintf(&q, "b%d:pullRequests(headRefName:%s,first:1,states:[OPEN,CLOSED,MERGED],orderBy:{field:CREATED_AT,direction:DESC}){nodes{...F}}", i, gqlString(br))
}
}
q.WriteString("}} fragment F on PullRequest{number state isDraft headRefOid url title}")
out, err := run(time.Minute, "", "gh", "api", "graphql", "-f", "query="+q.String())
var resp struct {
Data struct {
Repository map[string]json.RawMessage `json:"repository"`
} `json:"data"`
}
if jerr := json.Unmarshal([]byte(out), &resp); jerr != nil {
if err == nil {
err = jerr
}
return nil, err
}
prs := map[string]*PR{}
for i, br := range branches {
raw := resp.Data.Repository["b"+strconv.Itoa(i)]
var conn struct {
Nodes *[]PR `json:"nodes"`
}
var pr PR
if json.Unmarshal(raw, &conn) == nil && conn.Nodes != nil {
if len(*conn.Nodes) > 0 {
pr = (*conn.Nodes)[0]
}
} else {
json.Unmarshal(raw, &pr)
}
if pr.Number > 0 {
prs[br] = &pr
}
}
return prs, nil // partial GraphQL errors still leave usable data
}
func branchURL(slug, branch string) string {
parts := strings.Split(branch, "/")
for i, p := range parts {
parts[i] = url.PathEscape(p)
}
return "https://github.com/" + slug + "/tree/" + strings.Join(parts, "/")
}
// scanRepo scans one repository. patient retries a failed fetch for about 40
// seconds; a removal's fresh scan is not patient, and a failed fetch makes it
// refuse anything whose safety depends on remote refs.
func scanRepo(path string, sizes *sizeCache, patient bool, uses *usage) *Repo {
r := &Repo{Path: path}
if out, err := git(path, "remote", "get-url", "origin"); err == nil {
if m := githubRe.FindStringSubmatch(strings.TrimSpace(out)); m != nil {
r.Slug = m[1]
}
}
entries, err := listWorktrees(path)
if err != nil {
r.Errors = append(r.Errors, err.Error())
return r
}
if len(entries) == 0 {
return r
}
if err := fetch(path, r.Slug, patient); err != nil {
r.Errors = append(r.Errors, "fetch: "+err.Error())
}
r.Default = defaultBranch(path)
remote := map[string]bool{}
if out, err := git(path, "for-each-ref", "--format=%(refname:strip=3)", "refs/remotes/origin"); err == nil {
for _, b := range strings.Fields(out) {
remote[b] = true
}
}
var prs map[string]*PR
if r.Slug != "" {
var branches []string
seen := map[string]bool{}
for _, e := range entries {
if e.branch != "" && e.branch != "(detached)" && !seen[e.branch] {
seen[e.branch] = true
branches = append(branches, e.branch)
}
}
if len(branches) > 0 {
if prs, err = fetchPRs(r.Slug, branches); err != nil {
r.Errors = append(r.Errors, "PR lookup: "+err.Error())
}
}
}
r.Worktrees = make([]*Worktree, len(entries))
var wg sync.WaitGroup
sem := make(chan struct{}, 4)
for i, e := range entries {
wg.Add(1)
go func() {
defer wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
r.Worktrees[i] = scanWorktree(r, e, remote, prs, sizes, !patient, uses)
}()
}
wg.Wait()
return r
}
// lastActive is when the worktree was last touched: its newest commit, the
// index (rewritten by checkout, add and commit) or an uncommitted file.
func lastActive(wt string, commit time.Time, changed []string) time.Time {
t := commit
newer := func(p string) {
if fi, err := os.Stat(p); err == nil && fi.ModTime().After(t) {
t = fi.ModTime()
}
}
if b, err := os.ReadFile(filepath.Join(wt, ".git")); err == nil {
if dir, ok := strings.CutPrefix(strings.TrimSpace(string(b)), "gitdir: "); ok {
newer(filepath.Join(dir, "index"))
}
}
for i, p := range changed {
if i == 300 {
break
}
newer(filepath.Join(wt, p))
}
return t
}
func repoActive(r *Repo) (t time.Time) {
for _, w := range r.Worktrees {
if w.LastActive.After(t) {
t = w.LastActive
}
}
return
}
// fresh is a removal's fresh scan: submodules are fetched before they are
// trusted (see submoduleState).
func scanWorktree(r *Repo, e wtEntry, remote map[string]bool, prs map[string]*PR, sizes *sizeCache, fresh bool, uses *usage) *Worktree {
w := &Worktree{Path: e.path, Folder: filepath.Dir(e.path), Branch: e.branch, Sha: e.sha, Prunable: e.prunable}
switch _, err := os.Stat(e.path); {
case errors.Is(err, fs.ErrNotExist):
w.Prunable = true
case err == nil && w.Prunable:
// git calls it prunable (its .git file is gone, say), yet the folder and
// whatever is in it are still there.
w.Prunable, w.Hazard = false, "git calls it prunable, but its folder is still there"
w.InUse = uses.of(w.Path)
judge(r.Path, w)
return w
case err != nil:
// Unreadable is not gone, whatever git says: the folder may still hold work.
w.Prunable, w.Hazard = false, "cannot read the folder: "+err.Error()
w.InUse = uses.of(w.Path)
judge(r.Path, w)
return w
}
if w.Prunable {
if w.Hazard = orphaned(r.Path, e.sha); w.Hazard == "" {
w.Hazard = orphanedModules(r.Path, e.path, fresh)
}
judge(r.Path, w)
return w
}
var changed []string
// normal, whatever status.showUntrackedFiles says: "no" would hide them.
if out, err := git(e.path, "status", "--porcelain", "--untracked-files=normal"); err == nil {
for _, line := range strings.Split(out, "\n") {
switch {
case len(line) < 4:
continue
case strings.HasPrefix(line, "??"):
w.Untracked++
default:
w.Modified++
}
if _, to, ok := strings.Cut(line[3:], " -> "); ok {
line = " " + to
}
changed = append(changed, strings.Trim(line[3:], `"`))
}
}
if out, err := git(e.path, "log", "-1", "--format=%ct", e.sha); err == nil {
if ts, err := strconv.ParseInt(strings.TrimSpace(out), 10, 64); err == nil {
w.LastCommit = time.Unix(ts, 0)
}
}
w.LastActive = lastActive(e.path, w.LastCommit, changed)
if out, err := git(e.path, "rev-list", "--count", e.sha, "--not", "--remotes"); err == nil {
w.Unpushed, _ = strconv.Atoi(strings.TrimSpace(out))
}
if e.branch == "(detached)" && w.Unpushed > 0 {
// Removing the worktree deletes HEAD's reflog, the only thing holding these.
out, err := git(e.path, "rev-list", "--count", e.sha, "--not", "--branches", "--tags", "--remotes")
w.headOnly = err != nil || strings.TrimSpace(out) != "0"
}
if r.Default != "" {
w.InDefault = gitOK(r.Path, "merge-base", "--is-ancestor", e.sha, r.Default)
}
if e.branch != "(detached)" && remote[e.branch] && r.Slug != "" {
w.RemoteBranch, w.BranchURL = true, branchURL(r.Slug, e.branch)
}
if pr := prs[e.branch]; pr != nil {
w.PR = pr
switch {
case pr.HeadRefOid == e.sha:
w.PRRel = "same"
case !gitOK(r.Path, "cat-file", "-e", pr.HeadRefOid+"^{commit}"):
w.PRRel = "unknown"
case gitOK(r.Path, "merge-base", "--is-ancestor", e.sha, pr.HeadRefOid):
w.PRRel = "behind"
default:
w.PRRel = "diverged"
}
}
if kb, fresh := sizes.get(e.path); fresh {
w.SizeKB = kb
} else {
w.SizeKB = sizes.measure(e.path)
}
if hasLocalWork(w) {
matchContent(r, w, remote)
}
judge(r.Path, w)
if reclaimable(w.Verdict) {
// Only now: the walk is worth its cost just for worktrees that could go.
w.Ignored, w.ignoredSum, w.Hazard = ignoredContent(e.path)
if w.Hazard == "" {
w.Hazard = trackedHazard(e.path)
}
if w.Hazard == "" {
var ign []string
var sum string
w.Submodules, ign, sum, w.Hazard = submoduleState(e.path, fresh)
w.Ignored = append(w.Ignored, ign...)
w.submoduleSum = sum
if sum != "" {
w.ignoredSum += "+" + sum
}
}
judge(r.Path, w)
}
w.InUse = uses.of(w.Path)
judge(r.Path, w)
return w
}
// orphaned says why pruning a gone worktree would lose commits: a detached
// HEAD's commits are reachable only from the registration a prune deletes.
func orphaned(repo, sha string) string {
if sha == "" {
return "folder is gone and git does not say which commit it was on"
}
out, err := git(repo, "rev-list", "--count", sha, "--not", "--branches", "--tags", "--remotes")
if err != nil {
return "folder is gone and its commits could not be checked: " + err.Error()
}
if n, _ := strconv.Atoi(strings.TrimSpace(out)); n > 0 {
return "folder is gone, but " + counted(n, "commit is", "commits are") +
" reachable only from its HEAD; keep them with: git -C " + shellQuote(repo) + " branch <name> " + sha
}
return ""
}
const ignoredShown = 20 // ignored entries kept per worktree
// ignoredContent is what `git worktree remove` deletes without asking:
// ignored files, which git status never shows. skipDirs output is left out of
// the list as regenerable, but not out of the checks. sum is a digest of every
// ignored entry, so a removal plan notices one that appeared since.
//
// Another checkout or worktree anywhere in an ignored folder would go too, so
// it is a hazard. git finds those itself: listing ignored files one by one, it
// stops at each nested repository and lists it as "path/", whatever the case
// of its .git and however deep under node_modules or vendor it sits.
func ignoredContent(wt string) (ignored []string, sum, hazard string) {
out, err := git(wt, "ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--directory")
if err != nil {
return nil, "", "cannot list its ignored files: " + err.Error()
}
h := sha256.New()
more := 0
for _, p := range strings.Split(out, "\x00") {
h.Write([]byte(p + "\x00"))
name := strings.TrimSuffix(p, "/")
if base := filepath.Base(name); name == "" || skipDirs[base] || base == ".DS_Store" {
continue
}
if len(ignored) < ignoredShown {
ignored = append(ignored, p)
} else {
more++
}
}
if more > 0 {
ignored = append(ignored, fmt.Sprintf("… %d more", more))
}
all, err := git(wt, "ls-files", "-z", "--others", "--ignored", "--exclude-standard")
if err != nil {
return ignored, "", "cannot check its ignored files for nested checkouts: " + err.Error()
}
h.Write([]byte("\x00\x00"))
for _, p := range strings.Split(all, "\x00") {
if strings.HasSuffix(p, "/") {
return ignored, "", "another git checkout sits in its ignored folder " + p + ", and removing this worktree would delete it"
}
// Every file counts, so one new inside an ignored folder changes the
// sum too; build and dependency output, rewritten all the time, does not.
if !inSkipDir(p) {
h.Write([]byte(p + "\x00"))
}
}
return ignored, hex.EncodeToString(h.Sum(nil)), ""
}
// inSkipDir says p lies in build or dependency output (skipDirs).
func inSkipDir(p string) bool {
for _, part := range strings.Split(p, "/") {
if skipDirs[part] || part == ".DS_Store" {
return true
}
}
return false
}
// trackedHazard is tracked work that git status cannot see: a file on disk
// marked assume-unchanged or skip-worktree (status skips it). Submodules, whose
// files and commits are another repository's, are submoduleState's.
func trackedHazard(wt string) string {
out, err := git(wt, "ls-files", "-z", "-v", "-s")
if err != nil {
return "cannot list its tracked files: " + err.Error()
}
for _, rec := range strings.Split(out, "\x00") {
meta, path, ok := strings.Cut(rec, "\t") // "<tag> <mode> <object> <stage>\t<path>"
f := strings.Fields(meta)
if !ok || len(f) < 2 {
continue
}
onDisk := func(p string) bool { _, err := os.Lstat(filepath.Join(wt, p)); return err == nil }
switch tag := f[0]; {
case tag != strings.ToUpper(tag) && onDisk(path):
return path + " is marked assume-unchanged, so git cannot see edits to it"
case tag == "S" && onDisk(path):
return path + " is marked skip-worktree but is on disk, so git cannot see edits to it"
}
}
return filterHazard(wt, out)
}
// filterHazard names a tracked file that goes through a clean filter: git
// compares what the filter makes of it, so bytes the filter drops (a
// notebook's outputs, say) are on disk only. Git LFS's filter keeps every
// byte. listing is ls-files -z -v -s output.
func filterHazard(wt, listing string) string {
var paths strings.Builder
for _, rec := range strings.Split(listing, "\x00") {
if _, path, ok := strings.Cut(rec, "\t"); ok {
paths.WriteString(path + "\x00")
}
}
if paths.Len() == 0 {
return ""
}
out, err := runInput(gitTimeout, wt, nil, paths.String(), "git", "check-attr", "-z", "--stdin", "filter")
if err != nil {
return "cannot read its files' attributes: " + err.Error()
}
f := strings.Split(out, "\x00") // path, attribute, value, …
for i := 0; i+2 < len(f); i += 3 {
switch v := f[i+2]; v {
case "unspecified", "unset", "lfs":
default:
return f[i] + " goes through the " + v + " clean filter, so git cannot see all of what is on disk"
}
}
return ""
}
// judge gives a scanned worktree its verdict and, when it can go, the command
// that removes it. A hazard outranks everything: it is work git status and
// the commit checks can't see.
func judge(repo string, w *Worktree) {
w.RemoveCmd = ""
switch {
case w.Hazard != "":
w.Verdict, w.Reason = "keep", w.Hazard
case w.Prunable:
w.Verdict, w.Reason = "prunable", "folder is gone; registration is stale"
default:
classify(w)
}
if !w.Prunable && reclaimable(w.Verdict) && len(w.InUse) > 0 {
w.Reason = inUseReason(w.InUse) + "; otherwise " + verdictLabel(w.Verdict) + " (" + strings.TrimPrefix(w.Reason, "merged: ") + ")"
w.Verdict = "inuse"
}
if !reclaimable(w.Verdict) {
return
}
w.RemoveCmd = "agentyard remove " + shellQuote(w.Path)
if len(w.Ignored) > 0 {
w.Reason += " · removing also deletes ignored " + strings.Join(w.Ignored, ", ")
}
}
// checkedRemoval says a reclaimable worktree may go only through
// removal.remove, which re-checks it at that moment and removes it with
// --force where git would refuse: it has uncommitted files (re-proven to be in
// the default branch, with a copy kept under refs/agentyard/removed/), a
// detached HEAD with commits nothing else holds (copy kept too), or
// initialized submodules (each re-checked for work its remote lacks). Such a
// worktree gets no copyable command: run later, a command would skip every one
// of those checks.
func checkedRemoval(w *Worktree) bool {
return !w.Prunable && (keepsCopy(w) || w.Submodules > 0)
}
// keepsCopy says a checked removal first snapshots the worktree under
// refs/agentyard/removed/: what it deletes is not all in a remote branch's tip.
func keepsCopy(w *Worktree) bool { return w.Modified+w.Untracked > 0 || w.headOnly }
// forceRemove says git needs --force for w, which only removal.remove passes,
// after its checks: uncommitted files or submodules make git refuse otherwise.
func forceRemove(w *Worktree) bool { return w.Modified+w.Untracked > 0 || w.Submodules > 0 }
// removeArgs is the one git command that removes a reclaimable worktree;
// only removal.remove runs it, after its checks. Without force git still
// refuses changes, untracked files and locks. force is for removal.remove
// alone, after its checks (once: a locked worktree is still refused). For a
// prunable worktree it drops just that registration, where `worktree prune`
// would take every stale one.
func removeArgs(repo string, w *Worktree, force bool) []string {
// git's own check of the files honors status.showUntrackedFiles; "no"
// would let it delete untracked files.
if force {
return []string{"git", "-c", "status.showUntrackedFiles=normal", "-C", repo, "worktree", "remove", "--force", w.Path}
}
return []string{"git", "-c", "status.showUntrackedFiles=normal", "-C", repo, "worktree", "remove", w.Path}
}
// contentWhere says where the worktree's local changes already are.
func contentWhere(w *Worktree) string {
if w.ContentHistory {
return w.ContentRef + "'s history"
}
return w.ContentRef
}
// unpushedWork is local commits that neither a remote nor the PR has by hash.
// A merged branch counts as pushed when HEAD is contained in its PR, because
// squash-merged branches are deleted from the remote after merge.
func unpushedWork(w *Worktree) bool {
inPR := w.PR != nil && (w.PRRel == "same" || w.PRRel == "behind")
return w.Unpushed > 0 && !inPR
}
// hasLocalWork is what the hash and status checks would keep the worktree for.
func hasLocalWork(w *Worktree) bool { return w.Modified+w.Untracked > 0 || unpushedWork(w) }
// matchContent records which remote ref, if any, already has the worktree's
// local work by content.
func matchContent(r *Repo, w *Worktree, remote map[string]bool) {
w.ContentRef, w.ContentHistory = contentMatch(r.Path, w, r.Default, remote)
w.ContentInDefault = w.ContentRef != "" && w.ContentRef == r.Default
}
// classify decides whether the worktree can go. Only merged work is reclaimable.
// Keep means the worktree holds something no remote has: uncommitted files or
// local commits whose content (not just whose hash) is missing from every
// candidate ref contentMatch tried.
//
// Uncommitted files are deleted with the worktree, so they may make it Safe
// to delete only when they are in the default branch itself; elsewhere
// (another branch, a PR head) they are not merged, whatever HEAD is.
func classify(w *Worktree) {
covered := w.ContentRef != ""
unpushed := unpushedWork(w)
dirty := w.Modified+w.Untracked > 0
settled := !dirty || w.ContentInDefault // no uncommitted file outside the default branch
switch {
case dirty && !covered:
var parts []string
if w.Modified > 0 {
parts = append(parts, fmt.Sprintf("%d modified", w.Modified))
}
if w.Untracked > 0 {
parts = append(parts, fmt.Sprintf("%d untracked", w.Untracked))
}
w.Verdict, w.Reason = "keep", "uncommitted: "+strings.Join(parts, ", ")
case unpushed && !covered:
w.Verdict, w.Reason = "keep", counted(w.Unpushed, "commit exists", "commits exist")+" only locally"
case w.PR != nil && w.PR.State == "OPEN":
w.Verdict, w.Reason = "open", "PR in review; fully pushed"
if w.PR.IsDraft {
w.Reason = "draft PR; fully pushed"
}
if hasLocalWork(w) {
w.Reason += "; local changes already on " + contentWhere(w)
}
case w.PR != nil && w.PR.State == "MERGED" && settled:
w.Verdict, w.Reason = "merged", "merged: PR merged"
if hasLocalWork(w) {
w.Reason += "; local changes already on " + contentWhere(w)
}
case w.ContentInDefault && hasLocalWork(w):
w.Verdict, w.Reason = "merged", "merged: every local change is already in "+contentWhere(w)
case w.InDefault && settled:
w.Verdict, w.Reason = "merged", "merged: no PR, HEAD already in default branch"
case w.PR != nil && w.PR.State == "MERGED":
w.Verdict, w.Reason = "unmerged", "PR merged, but uncommitted changes are only on "+contentWhere(w)+", not in the default branch"
case w.PR != nil && w.PR.State == "CLOSED":
w.Verdict, w.Reason = "unmerged", "PR closed without merging"
if hasLocalWork(w) {
w.Reason += "; local changes already on " + contentWhere(w)
}
case covered && hasLocalWork(w):
w.Verdict, w.Reason = "unmerged", "no PR; local changes already on "+contentWhere(w)
case !w.RemoteBranch: