gunk-dev/the-valley

cleanup.go

source601b054bc28emain's published tip history
11.8 KiB
1package cmd
2
3import (
4 "context"
5 "fmt"
6 "io"
7 "log/slog"
8 "os"
9
10 "the-valley/flow/internal/consult"
11 "the-valley/flow/internal/git"
12 "the-valley/flow/internal/integration"
13 "the-valley/flow/internal/run"
14 "the-valley/flow/internal/tmux"
15 "github.com/spf13/cobra"
16)
17
18var cleanupCmd = &cobra.Command{
19 Use: "cleanup <run-id> | --done | --all",
20 Short: "Remove worktrees, panes, and state",
21 Long: `Cleans up a run by killing its tmux pane, removing its worktree,
22deleting local branches, and removing state files.
23
24Use --done to clean up what's finished: the runs whose PR or change is
25merged, closed, integrated, withdrawn or gone, as klaus status shows them,
26and the older runs of a PR or change still open. It keeps the latest run of
27each open PR or change, a run that needs attention, and a running run, and
28prints a line for each run it removes or keeps, with why.
29
30Use --all to clean up all runs, and the session's consult thread snapshots
31(see klaus consult --repo) not in use; a thread makes a new one on its next
32turn. Runs with active tmux panes are skipped by default; pass --force to
33remove them anyway. With --all, the detached
34agents tmux session is removed too — but only once no remaining run holds a
35pane in it and no pane in it is still running a command, so a session with
36live agents is never torn down.
37
38Each run cleanup removes leaves its cost and duration in the session's
39ledger, so klaus status and the dashboard still count them.`,
40 RunE: func(cmd *cobra.Command, args []string) error {
41 all, _ := cmd.Flags().GetBool("all")
42 done, _ := cmd.Flags().GetBool("done")
43 force, _ := cmd.Flags().GetBool("force")
44 ctx := cmd.Context()
45 tmuxClient := tmux.NewExecClient()
46 gitClient := git.NewExecClient()
47
48 root, _ := git.RepoRoot() // may be empty outside a repo
49
50 deps := DefaultCleanupDeps(tmuxClient)
51
52 store, err := sessionStore()
53 if err != nil {
54 return err
55 }
56
57 if done {
58 if all || len(args) > 0 {
59 return fmt.Errorf("--done takes no run ID and not --all")
60 }
61 return cleanupDone(ctx, root, store, gitClient, force, deps, tmuxClient)
62 }
63 if all {
64 if hs, ok := store.(*run.HomeDirStore); ok {
65 removeConsultSnapshots(ctx, consult.NewStore(hs.BaseDir()), cmd.OutOrStdout())
66 }
67 return cleanupAll(ctx, root, store, gitClient, force, deps, tmuxClient)
68 }
69
70 if len(args) != 1 {
71 return fmt.Errorf("usage: klaus cleanup <run-id>, klaus cleanup --done or klaus cleanup --all")
72 }
73
74 return cleanupOne(ctx, root, store, gitClient, args[0], force, deps, tmuxClient)
75 },
76}
77
78func cleanupAll(ctx context.Context, root string, store run.StateStore, gitClient git.Client, force bool, deps CleanupDeps, tc tmux.Client) error {
79 states, err := store.List()
80 if err != nil {
81 return err
82 }
83 if len(states) == 0 {
84 fmt.Println("No runs to clean up.")
85 return nil
86 }
87 for _, s := range states {
88 if err := ctx.Err(); err != nil {
89 return err
90 }
91 if err := cleanupOne(ctx, root, store, gitClient, s.ID, force, deps, tc); err != nil {
92 fmt.Printf(" warning: failed to clean up %s: %v\n", s.ID, err)
93 }
94 }
95 killEmptyAgentsSession(ctx, store, tc)
96 return nil
97}
98
99// CleanupDeps holds dependencies for cleanup operations.
100type CleanupDeps struct {
101 IsRunActive func(state *run.State) bool
102}
103
104// DefaultCleanupDeps returns CleanupDeps wired to real implementations.
105func DefaultCleanupDeps(tc tmux.Client) CleanupDeps {
106 return CleanupDeps{
107 IsRunActive: func(state *run.State) bool {
108 return defaultIsRunActive(state, tc)
109 },
110 }
111}
112
113// defaultIsRunActive reports whether the run has a live, non-idle tmux pane or is the current session.
114func defaultIsRunActive(state *run.State, tc tmux.Client) bool {
115 ctx := context.Background()
116 if state.Type == "session" {
117 if sid := os.Getenv(sessionIDEnv); sid != "" && state.ID == sid {
118 return true
119 }
120 }
121
122 if state.IsAgentRunningWith(run.TmuxDepsFor(ctx, tc)) {
123 return true
124 }
125
126 if state.DashboardPane != nil && tc.PaneExists(ctx, *state.DashboardPane) {
127 return true
128 }
129 return false
130}
131
132func cleanupOne(ctx context.Context, root string, store run.StateStore, gitClient git.Client, id string, force bool, deps CleanupDeps, tc tmux.Client) error {
133 return cleanupOneTo(os.Stdout, ctx, root, store, gitClient, id, force, deps, tc)
134}
135
136// cleanupOneTo is cleanupOne, reporting to w.
137func cleanupOneTo(w io.Writer, ctx context.Context, root string, store run.StateStore, gitClient git.Client, id string, force bool, deps CleanupDeps, tc tmux.Client) error {
138 state, err := store.Load(id)
139 if err != nil {
140 return fmt.Errorf("no run found with id: %s", id)
141 }
142
143 if !force && deps.IsRunActive(state) {
144 fmt.Fprintf(w, "skipping %s (still running) — use --force to remove\n", id)
145 return nil
146 }
147
148 fmt.Fprintf(w, "Cleaning up %s...\n", id)
149
150 // Kill tmux pane if alive
151 if state.TmuxPane != nil && tc.PaneExists(ctx, *state.TmuxPane) {
152 if err := tc.KillPane(ctx, *state.TmuxPane); err == nil {
153 fmt.Fprintln(w, " killed tmux pane")
154 } else {
155 slog.Warn("failed to kill tmux pane", "id", id, "pane", *state.TmuxPane, "err", err)
156 }
157 }
158
159 // Kill dashboard pane if alive
160 if state.DashboardPane != nil && tc.PaneExists(ctx, *state.DashboardPane) {
161 if err := tc.KillPane(ctx, *state.DashboardPane); err == nil {
162 fmt.Fprintln(w, " killed dashboard pane")
163 } else {
164 slog.Warn("failed to kill dashboard pane", "id", id, "pane", *state.DashboardPane, "err", err)
165 }
166 }
167
168 // For cross-repo runs, git ops target the clone dir instead of the host root
169 gitRoot := root
170 if state.CloneDir != nil {
171 gitRoot = *state.CloneDir
172 }
173
174 // Remove worktree
175 if state.Worktree != "" {
176 if err := gitClient.WorktreeRemove(ctx, gitRoot, state.Worktree); err == nil {
177 fmt.Fprintln(w, " removed worktree")
178 } else {
179 slog.Warn("failed to remove worktree", "id", id, "worktree", state.Worktree, "err", err)
180 }
181 }
182 removeScratchDir(store, id)
183
184 // Delete local branch
185 if state.Branch != "" {
186 if err := gitClient.BranchDelete(ctx, gitRoot, state.Branch); err == nil {
187 fmt.Fprintln(w, " deleted local branch")
188 } else {
189 slog.Warn("failed to delete local branch", "id", id, "branch", state.Branch, "err", err)
190 }
191 }
192
193 // Keep its spend in the session's totals, then remove its state file.
194 if hs, ok := store.(*run.HomeDirStore); ok && state.Type != "session" {
195 if err := run.RecordCleared(hs.BaseDir(), state); err != nil {
196 return fmt.Errorf("recording %s's spend: %w", id, err)
197 }
198 }
199 if err := store.Delete(id); err == nil {
200 fmt.Fprintln(w, " removed state file")
201 } else {
202 slog.Warn("failed to remove state file", "id", id, "err", err)
203 }
204
205 fmt.Fprintln(w, " done.")
206 return nil
207}
208
209func init() {
210 cleanupCmd.Flags().Bool("all", false, "Clean up all runs")
211 cleanupCmd.Flags().Bool("done", false, "Clean up the runs of finished PRs and changes, and older runs of open ones")
212 cleanupCmd.Flags().Bool("force", false, "Remove runs even if they are still running")
213 rootCmd.AddCommand(cleanupCmd)
214}
215
216// doneGroup is the runs of one PR or change, as klaus status or the
217// dashboard groups them.
218type doneGroup struct {
219 label string // the PR's number, the change's handle or its change ID's prefix
220 // finished is merged, closed, integrated, withdrawn or gone once the PR
221 // or change is finished; "" while it is open.
222 finished string
223 runs []*run.State
224}
225
226// doneVerdict is what cleanup --done does with one run, and why.
227type doneVerdict struct {
228 state *run.State
229 remove bool
230 why string
231}
232
233// planDone decides, for each run of groups and each run of none (loose),
234// whether cleanup --done removes it: every run of a finished PR or change,
235// and every older run of an open one; a group may be one finished run with
236// neither, as a pushed branch that landed. It keeps the latest run of an open PR
237// or change, a run that is running or needs attention, and a loose run.
238func planDone(groups []doneGroup, loose []*run.State, running, attention func(*run.State) bool) []doneVerdict {
239 var out []doneVerdict
240 for _, g := range groups {
241 var latest *run.State
242 for _, s := range g.runs {
243 if latest == nil || createdBefore(latest, s) {
244 latest = s
245 }
246 }
247 for _, s := range g.runs {
248 v := doneVerdict{state: s}
249 switch {
250 case running(s):
251 v.why = "running, on " + g.label
252 case attention(s):
253 v.why = "needs attention, on " + g.label
254 case g.finished != "":
255 v.remove, v.why = true, g.label+" "+g.finished
256 case s == latest:
257 v.why = "latest run of " + g.label + ", still open"
258 default:
259 v.remove, v.why = true, "older run of "+g.label
260 }
261 out = append(out, v)
262 }
263 }
264 for _, s := range loose {
265 why := "no PR or change"
266 if running(s) {
267 why = "running"
268 }
269 out = append(out, doneVerdict{state: s, why: why})
270 }
271 return out
272}
273
274// finishedStatus is a finished PR's or change's word for a run status, ""
275// when the status leaves the PR or change open.
276func finishedStatus(status string) string {
277 switch status {
278 case "merged", "closed", "integrated", "withdrawn":
279 return status
280 case "branch-gone":
281 return "gone"
282 }
283 return ""
284}
285
286// finishedVerdict is a finished change's word for its active version's
287// verdict, "" while the change is open.
288func finishedVerdict(v integration.Verdict) string {
289 switch {
290 case v.Landed():
291 return "integrated"
292 case v == integration.Withdrawn:
293 return "withdrawn"
294 case v == integration.Gone:
295 return "gone"
296 }
297 return ""
298}
299
300// cleanupDone removes the runs planDone picks, judged as klaus status
301// judges them, and says what it removed and kept.
302func cleanupDone(ctx context.Context, root string, store run.StateStore, gitClient git.Client, force bool, deps CleanupDeps, tc tmux.Client) error {
303 states, err := store.List()
304 if err != nil {
305 return err
306 }
307 var listed []*run.State
308 for _, s := range states {
309 if s.Type != "session" {
310 listed = append(listed, s)
311 }
312 }
313 if len(listed) == 0 {
314 fmt.Println("No runs to clean up.")
315 return nil
316 }
317 statuses, report, err := runStanding(ctx, store, listed)
318 if err != nil {
319 return err
320 }
321 status := make(map[*run.State]string, len(listed))
322 for i, s := range listed {
323 status[s] = statuses[i]
324 }
325 changeOf := changeKeys(listed)
326 prs, handles := changePRs(listed), changeHandles(listed, report.Changes)
327 byKey := make(map[string]*doneGroup)
328 var groups []*doneGroup
329 var loose []*run.State
330 for _, s := range listed {
331 key := ""
332 if k, ok := changeOf(s); ok {
333 key = k.Repo + "@" + k.ChangeID
334 } else if s.PRURL != nil {
335 key = *s.PRURL
336 } else if finishedStatus(status[s]) != "" {
337 key = s.ID // a branch pushed without a PR or change, landed or gone
338 }
339 if key == "" {
340 loose = append(loose, s)
341 continue
342 }
343 g := byKey[key]
344 if g == nil {
345 g = &doneGroup{label: changeLabel(s, changeOf, prs, handles)}
346 if g.label == "-" {
347 g.label = "its branch"
348 }
349 byKey[key] = g
350 groups = append(groups, g)
351 }
352 g.runs = append(g.runs, s)
353 }
354 for _, g := range groups {
355 // A change the valley lists is finished as its active version
356 // stands; otherwise as its newest run with a PR or a push does.
357 var newest *run.State
358 for _, s := range g.runs {
359 if view := report.Changes[valleyKey(s)]; view.Change != nil {
360 g.finished, newest = finishedVerdict(view.Verdict), nil
361 break
362 }
363 if (s.PRURL != nil || s.PushedSHA != nil || s.Type == "track") && (newest == nil || createdBefore(newest, s)) {
364 newest = s
365 }
366 }
367 if newest != nil {
368 g.finished = finishedStatus(status[newest])
369 }
370 }
371 plain := make([]doneGroup, len(groups))
372 for i, g := range groups {
373 plain[i] = *g
374 }
375 plan := planDone(plain, loose,
376 func(s *run.State) bool { return status[s] == "running" || deps.IsRunActive(s) },
377 func(s *run.State) bool { return status[s] == "needs-attention" })
378 for _, v := range plan {
379 if err := ctx.Err(); err != nil {
380 return err
381 }
382 if !v.remove {
383 fmt.Printf("kept %s %s\n", v.state.ID, v.why)
384 continue
385 }
386 fmt.Printf("removed %s %s\n", v.state.ID, v.why)
387 if err := cleanupOneTo(io.Discard, ctx, root, store, gitClient, v.state.ID, force, deps, tc); err != nil {
388 fmt.Printf(" warning: failed to clean up %s: %v\n", v.state.ID, err)
389 }
390 }
391 return nil
392}