Skip to content
Open
105 changes: 87 additions & 18 deletions cmd/goblins/cleanup.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,18 @@ import (

"github.com/fpresta0607/code-goblins/internal/cleanup"
"github.com/fpresta0607/code-goblins/internal/execx"
"github.com/fpresta0607/code-goblins/internal/gatedb"
"github.com/fpresta0607/code-goblins/internal/githubapi"
"github.com/fpresta0607/code-goblins/internal/herdr"
"github.com/fpresta0607/code-goblins/internal/home"
"github.com/fpresta0607/code-goblins/internal/pipeline"
"github.com/fpresta0607/code-goblins/internal/state"
"github.com/fpresta0607/code-goblins/internal/supervisor"
"github.com/fpresta0607/code-goblins/internal/tickets"
"github.com/fpresta0607/code-goblins/internal/worktree"
)

const cleanupUsage = `usage: goblins cleanup <id> [--force-archive]
const cleanupUsage = `usage: goblins cleanup <id> [--force-archive] [--keep-issue-open <issue>... --reason "<why>"]

Close the task tab and return one clean, proven-inactive task worktree,
removing the worktree and pruning its Git administrative entry.
Expand All @@ -29,16 +33,44 @@ task against every other command while it runs, so a pause, a resume, a
kill or a switch of the task that starts meanwhile is refused, and it is
refused itself, before it removes anything, while one of those is in flight.

It refuses as well, naming each, while an issue the task names is still
open on GitHub: an issue its brief names in its Task or Acceptance criteria
or in a section added to it under a heading "## ADDED", one its gate runs were started to close with --closes, and one its pull
requests name, which GitHub links them to close or their body names after
a closing word or "Part of". An issue GitHub reports gone, as a deleted
issue or a mistyped number is, refuses it too, named apart as gone on
GitHub, and so does a task whose issues cannot be read. Close each open
issue once its work is on its project's main, or retire the task with an
open or gone issue by --keep-issue-open <issue>, written owner/name#N or as
its address, once for each, with --reason "<why>", which the task's status
log records for each kept issue. goblins kill, which stops work unfinished,
does not check issues.

--force-archive retires a task whose worktree can no longer be validated (a
directory pinned by a dead handle, or already gone). It archives the task
record and leaves the directory untouched - nothing on disk is deleted - and
still refuses a pane with a live agent and a gate run that is still open or
cannot be read, as cleanup does. A paused task's run is the one its pause
saved, read whatever state the worktree is in; the worktree's branch's run
is read as well while the folder is still a Git worktree, so a worktree gone,
or a folder no longer a Git worktree, with no saved run names no run.
still refuses a pane with a live agent, a gate run that is still open or
cannot be read, and an open issue, as cleanup does. A paused task's run is
the one its pause saved, read whatever state the worktree is in; the
worktree's branch's run is read as well while the folder is still a Git
worktree, so a worktree gone, or a folder no longer a Git worktree, with no
saved run names no run.
`

// cleanupRequest is one retirement of a task: goblins cleanup's, which keeps
// the task while an issue it names is open unless the CEO keeps the issue
// open with a reason, or goblins kill's, which stops work unfinished and so
// checks no issue.
type cleanupRequest struct {
ID string
ForceArchive bool
ShouldCheckIssues bool
// KeepOpen are the open issues, each owner/name#N, the task retires with,
// and KeepReason is why.
KeepOpen []string
KeepReason string
}

// runCleanup returns one validated task's worktree through the guarded
// cleanup service. It accepts only a local task ID, never a raw path or an
// explicit Herdr target.
Expand All @@ -52,26 +84,51 @@ func runCleanup(args []string, stdout, stderr io.Writer, runtime commandRuntime)
fmt.Fprint(stdout, cleanupUsage)
return 0
}
var id string
force := false
for _, arg := range args {
request := cleanupRequest{ShouldCheckIssues: true}
isReasonGiven := false
for index := 0; index < len(args); index++ {
arg := args[index]
switch {
case arg == "--force-archive":
force = true
request.ForceArchive = true
case arg == "--keep-issue-open" || arg == "--reason":
if index+1 == len(args) {
fmt.Fprintf(stderr, "goblins cleanup: %s needs a value\n", arg)
return 2
}
index++
if arg == "--reason" {
request.KeepReason, isReasonGiven = strings.TrimSpace(args[index]), true
continue
}
issue, isIssue := tickets.ParseIssueRef(args[index])
if !isIssue {
fmt.Fprintf(stderr, "goblins cleanup: --keep-issue-open %q is not an issue: write it owner/name#N or as its address\n", args[index])
return 2
}
request.KeepOpen = append(request.KeepOpen, issue.String())
case strings.HasPrefix(arg, "-"):
fmt.Fprintf(stderr, "goblins cleanup: unknown flag %q\n", arg)
return 2
case id == "":
id = arg
case request.ID == "":
request.ID = arg
default:
fmt.Fprintln(stderr, "goblins cleanup: unexpected arguments")
return 2
}
}
if id == "" {
if request.ID == "" {
fmt.Fprintln(stderr, "goblins cleanup: task ID is required")
return 2
}
if len(request.KeepOpen) > 0 && request.KeepReason == "" {
fmt.Fprintln(stderr, `goblins cleanup: --keep-issue-open needs --reason "<why>", which the task records`)
return 2
}
if isReasonGiven && len(request.KeepOpen) == 0 {
fmt.Fprintln(stderr, "goblins cleanup: --reason says why an issue is kept open, so it needs --keep-issue-open <issue>")
return 2
}
if runtime.resolveHome == nil || runtime.cleanup == nil {
fmt.Fprintln(stderr, "goblins cleanup: command runtime is incomplete")
return 1
Expand All @@ -85,7 +142,7 @@ func runCleanup(args []string, stdout, stderr io.Writer, runtime commandRuntime)
fmt.Fprintln(stderr, "goblins cleanup: not a primary home")
return 1
}
output, err := runtime.cleanup(context.Background(), h, id, force)
output, err := runtime.cleanup(context.Background(), h, request)
if err != nil {
fmt.Fprintln(stderr, err)
return 1
Expand All @@ -94,16 +151,19 @@ func runCleanup(args []string, stdout, stderr io.Writer, runtime commandRuntime)
return 0
}

// defaultCleanup builds the production cleanup service for one invocation.
func defaultCleanup(ctx context.Context, h home.Home, id string, forceArchive bool) (string, error) {
// defaultCleanup builds the production cleanup service for one invocation;
// github reads the issues of a request that checks them.
func defaultCleanup(ctx context.Context, h home.Home, request cleanupRequest, github *githubapi.Client) (string, error) {
commands := execx.OSRunner{}
service := cleanup.Service{
StateDir: h.State,
Data: h.Data,
Commands: commands,
Terminal: &herdr.Client{Commands: commands, Session: herdrSession()},
Worktrees: worktree.Service{Commands: commands},
ForceArchive: forceArchive,
ForceArchive: request.ForceArchive,
KeepOpen: request.KeepOpen,
KeepReason: request.KeepReason,

EndLeft: func(ctx context.Context, meta state.TaskMeta) ([]string, error) {
return endLeftProcesses(ctx, h, meta)
Expand All @@ -114,7 +174,16 @@ func defaultCleanup(ctx context.Context, h home.Home, id string, forceArchive bo
},
OpenGateRun: openGateRun(h),
}
result, err := service.Cleanup(ctx, id)
if request.ShouldCheckIssues {
gate := pipeline.Reader{Commands: gatedb.Runner{Next: commands}}
root, err := pipeline.DefaultRoot()
if err != nil {
return "", fmt.Errorf("cleanup: find the gate's home, whose runs say which issues the task closes: %w", err)
}
gate.Root = root
service.OpenIssues = openTaskIssues(h, tickets.GitHub{Commands: commands, API: github}, gate)
}
result, err := service.Cleanup(ctx, request.ID)
if err != nil {
return "", err
}
Expand Down
115 changes: 110 additions & 5 deletions cmd/goblins/cleanup_kill_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@ import (
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"testing"

"github.com/fpresta0607/code-goblins/internal/execx"
"github.com/fpresta0607/code-goblins/internal/fsx"
"github.com/fpresta0607/code-goblins/internal/githubtest"
"github.com/fpresta0607/code-goblins/internal/herdr"
"github.com/fpresta0607/code-goblins/internal/home"
"github.com/fpresta0607/code-goblins/internal/lifecycle"
Expand All @@ -26,7 +29,12 @@ import (
func killedTask(t *testing.T) (home.Home, state.TaskMeta) {
t.Helper()
t.Setenv("NM_HOME", t.TempDir())
root := t.TempDir()
// git reports the canonical path of a checkout, so the task's paths are
// built from the canonical temp root, not a short name or a link to it.
root, err := fsx.Canonical(t.TempDir())
if err != nil {
t.Fatal(err)
}
git := func(dir string, args ...string) {
t.Helper()
command := exec.Command("git", args...)
Expand Down Expand Up @@ -96,7 +104,7 @@ func TestACleanupOfAPausedGoblinHandsItsKeptMessagesToTheCEO(t *testing.T) {
pausedWithKeptMessage(t, h, meta)

// Act
output, err := defaultCleanup(t.Context(), h, meta.ID, false)
output, err := defaultCleanup(t.Context(), h, cleanupRequest{ID: meta.ID}, nil)

// Assert
if err != nil {
Expand All @@ -122,7 +130,7 @@ func TestAKillOfAPausedGoblinHandsItsKeptMessagesToTheCEOOnce(t *testing.T) {
service := lifecycle.Service{StateDir: h.State, Operations: lifecycle.Operations{
Stop: func(context.Context, state.TaskMeta, *state.Lifecycle) ([]string, error) { return nil, nil },
Archive: func(ctx context.Context, meta state.TaskMeta, _ *state.Lifecycle) (lifecycle.Preservation, error) {
_, err := defaultCleanup(ctx, h, meta.ID, false)
_, err := defaultCleanup(ctx, h, cleanupRequest{ID: meta.ID}, nil)
return lifecycle.Preservation{}, err
},
Notify: func(state.Lifecycle) error { return nil },
Expand Down Expand Up @@ -164,7 +172,7 @@ func TestKillStillArchivesThroughItsOwnCleanup(t *testing.T) {
heldDuringArchive = append(heldDuringArchive, name)
}
}
_, err := defaultCleanup(ctx, h, meta.ID, false)
_, err := defaultCleanup(ctx, h, cleanupRequest{ID: meta.ID}, nil)
return lifecycle.Preservation{}, err
},
Notify: func(state.Lifecycle) error { return nil },
Expand Down Expand Up @@ -193,6 +201,101 @@ func TestKillStillArchivesThroughItsOwnCleanup(t *testing.T) {
}
}

// goblins cleanup reads the issues its task names through the production
// service, refusing while one is open and retiring the task with it kept open
// for a reason the status log records, while goblins kill, which stops work
// unfinished, reads none, so it retires a task whose issues cannot be read.
func TestCleanupChecksTheIssuesItsTaskNamesAndKillDoesNot(t *testing.T) {
const issue = "acme/widgets#7"
withOpenIssue := func(t *testing.T) (home.Home, state.TaskMeta) {
t.Helper()
h, meta := killedTask(t)
writeFixtureFile(t, filepath.Join(h.Data, meta.ID, "brief.md"), "# Brief g1\n\n## Task\n\nFix https://github.com/acme/widgets/issues/7.\n")
return h, meta
}
github := githubtest.Client(taskIssuesGitHub{states: map[string]string{issue: "open"}})

t.Run("goblins cleanup refuses while the issue is open", func(t *testing.T) {
// Arrange
h, meta := withOpenIssue(t)

// Act
_, err := defaultCleanup(t.Context(), h, cleanupRequest{ID: meta.ID, ShouldCheckIssues: true}, github)

// Assert
if err == nil || !strings.Contains(err.Error(), "names the open issue(s) "+issue) {
t.Fatalf("the cleanup = %v, want a refusal naming %s", err, issue)
}
if _, err := state.ReadTaskMeta(h.State, meta.ID); err != nil {
t.Errorf("the task record after a refused cleanup: %v, want it kept", err)
}
})
t.Run("goblins cleanup refuses while an issue only an added brief section names is open", func(t *testing.T) {
// Arrange
h, meta := killedTask(t)
writeFixtureFile(t, filepath.Join(h.Data, meta.ID, "brief.md"), "# Brief g1\n\n## Task\n\nTidy the docs.\n\n## ADDED 2026-11-19 - the stats page\nIssue: https://github.com/acme/widgets/issues/7.\nThe other task (#185) adds a picker, so leave it.\n")

// Act
_, err := defaultCleanup(t.Context(), h, cleanupRequest{ID: meta.ID, ShouldCheckIssues: true}, github)

// Assert
if err == nil || !strings.Contains(err.Error(), "names the open issue(s) "+issue) {
t.Fatalf("the cleanup = %v, want a refusal naming %s", err, issue)
}
if strings.Contains(err.Error(), "#185") {
t.Errorf("the cleanup refusal %v names #185, a bare number in the added section's prose", err)
}
if _, err := state.ReadTaskMeta(h.State, meta.ID); err != nil {
t.Errorf("the task record after a refused cleanup: %v, want it kept", err)
}
})
t.Run("goblins cleanup retires the task with the issue kept open and records why", func(t *testing.T) {
// Arrange
h, meta := withOpenIssue(t)
request := cleanupRequest{ID: meta.ID, ShouldCheckIssues: true, KeepOpen: []string{issue}, KeepReason: "task g2 carries it on"}

// Act
output, err := defaultCleanup(t.Context(), h, request, github)

// Assert
if err != nil {
t.Fatalf("the cleanup = %q, %v, want the task retired", output, err)
}
status, err := state.TailStatus(h.State, meta.ID, 10)
if err != nil || !slices.ContainsFunc(status, func(line string) bool {
_, event := state.SplitStatus(line)
return event == "issue-kept-open: "+issue+": task g2 carries it on"
}) {
t.Errorf("status = %q, %v; want the kept issue recorded with its reason", status, err)
}
if _, err := state.ReadTaskMeta(h.State, meta.ID); !errors.Is(err, os.ErrNotExist) {
t.Errorf("the task record after the cleanup: %v, want it retired", err)
}
})
t.Run("goblins kill retires a task whose issues cannot even be read", func(t *testing.T) {
// Arrange: the brief the record names is a folder, so a kill that read
// the task's issues would refuse there, before it could ask GitHub
// anything.
h, meta := killedTask(t)
meta.Brief = t.TempDir()
if err := state.WriteTaskMeta(h.State, meta); err != nil {
t.Fatal(err)
}
t.Setenv("GOBLINS_VERIFY_DIR", t.TempDir())

// Act
record, err := defaultTaskLifecycle(t.Context(), h, lifecycle.Request{ID: meta.ID, Generation: meta.SpawnGen, Operation: "kill-1", Action: "stop", Reason: "Requested by the operator", IsWatched: true}, "")

// Assert
if err != nil || record.Phase != "stopped" {
t.Fatalf("the kill = phase %q, %v, want the task retired\nproblems: %s", record.Phase, err, strings.Join(record.Problems, "; "))
}
if _, err := state.ReadTaskMeta(h.State, meta.ID); !errors.Is(err, os.ErrNotExist) {
t.Errorf("the task record after the kill: %v, want it retired", err)
}
})
}

// A pause leaves its goblin's gate run running, so goblins cleanup, and the
// sweep's cleanup of a task it found, read the task's gate run before they
// change anything. A run that completed or was cancelled, as a landed or
Expand Down Expand Up @@ -221,7 +324,9 @@ func TestCleanupReadsTheTaskBranchsGateRunBeforeRetiringIt(t *testing.T) {
name string
clean func(ctx context.Context, h home.Home, id string, forceArchive bool) (string, error)
}{
{name: "goblins cleanup", clean: defaultCleanup},
{name: "goblins cleanup", clean: func(ctx context.Context, h home.Home, id string, forceArchive bool) (string, error) {
return defaultCleanup(ctx, h, cleanupRequest{ID: id, ForceArchive: forceArchive}, nil)
}},
{name: "goblins reap", clean: func(ctx context.Context, h home.Home, id string, forceArchive bool) (string, error) {
return reapCleanup(ctx, h, &herdr.Client{Commands: execx.OSRunner{}, Session: herdrSession()}, id, forceArchive)
}},
Expand Down
Loading
Loading