diff --git a/apps/backend/cmd/kandev/worktree.go b/apps/backend/cmd/kandev/worktree.go index d3d1507089..a93d1982a8 100644 --- a/apps/backend/cmd/kandev/worktree.go +++ b/apps/backend/cmd/kandev/worktree.go @@ -2,6 +2,9 @@ package main import ( "context" + "fmt" + "os/exec" + "strings" "github.com/kandev/kandev/internal/agent/lifecycle" "github.com/kandev/kandev/internal/common/config" @@ -67,6 +70,12 @@ func provideWorktreeManager(dbPool *db.Pool, cfg *config.Config, log *logger.Log lifecycleMgr.SetBootMessageService(&bootMsgAdapter{svc: taskSvc}) } taskSvc.SetWorktreeCleanup(manager) + if lifecycleMgr != nil { + taskSvc.SetEnvironmentDestroyer(&environmentDestroyerAdapter{ + lifecycle: lifecycleMgr, + worktrees: manager, + }) + } // Wire script message handler with adapters taskSvcAdapter := &taskServiceAdapter{svc: taskSvc} @@ -86,3 +95,47 @@ func provideWorktreeManager(dbPool *db.Pool, cfg *config.Config, log *logger.Log return manager, recreator, cleanup, nil } + +// environmentDestroyerAdapter implements taskservice.EnvironmentDestroyer by +// delegating to the lifecycle Manager (for containers/sandboxes) and the worktree +// Manager (for worktrees). Branch is preserved on worktree removal so unpushed +// work is never silently dropped. +type environmentDestroyerAdapter struct { + lifecycle *lifecycle.Manager + worktrees *worktree.Manager +} + +func (a *environmentDestroyerAdapter) DestroyContainer(ctx context.Context, containerID string) error { + return a.lifecycle.DestroyContainer(ctx, containerID) +} + +func (a *environmentDestroyerAdapter) DestroySandbox(ctx context.Context, sandboxID, executionID string) error { + return a.lifecycle.DestroySandbox(ctx, sandboxID, executionID) +} + +func (a *environmentDestroyerAdapter) DestroyWorktree(ctx context.Context, worktreeID string) error { + // removeBranch=false: preserve the branch so unpushed work isn't lost. + return a.worktrees.RemoveByID(ctx, worktreeID, false) +} + +func (a *environmentDestroyerAdapter) PushEnvironmentBranch(ctx context.Context, env *models.TaskEnvironment) error { + // For host-side worktrees we can push directly. Container/sandbox workspaces + // would require an active agentctl client — not wired yet, surface a clear + // error so the user knows to push manually. + if env.WorktreePath == "" { + return fmt.Errorf("push-before-reset is not supported for this environment type; please push manually first") + } + branch := strings.TrimSpace(env.WorktreeBranch) + var cmd *exec.Cmd + if branch == "" { + cmd = exec.CommandContext(ctx, "git", "push") + } else { + cmd = exec.CommandContext(ctx, "git", "push", "origin", branch) + } + cmd.Dir = env.WorktreePath + out, err := cmd.CombinedOutput() + if err != nil { + return fmt.Errorf("git push failed: %s: %w", strings.TrimSpace(string(out)), err) + } + return nil +} diff --git a/apps/backend/internal/agent/lifecycle/manager_environment.go b/apps/backend/internal/agent/lifecycle/manager_environment.go new file mode 100644 index 0000000000..a88f0f0707 --- /dev/null +++ b/apps/backend/internal/agent/lifecycle/manager_environment.go @@ -0,0 +1,52 @@ +package lifecycle + +import ( + "context" + "fmt" + + "github.com/kandev/kandev/internal/agent/executor" +) + +// DestroyContainer removes a Docker container (forcefully, along with its filesystem). +// Used by Reset Environment to tear down the container layer without touching worktrees +// or sprite sandboxes. +func (m *Manager) DestroyContainer(ctx context.Context, containerID string) error { + if containerID == "" { + return nil + } + backend, err := m.executorRegistry.GetBackend(executor.NameDocker) + if err != nil { + return fmt.Errorf("docker backend unavailable: %w", err) + } + dockerExec, ok := backend.(*DockerExecutor) + if !ok { + return fmt.Errorf("docker backend has unexpected type %T", backend) + } + cm := dockerExec.ContainerMgr() + if cm == nil { + return fmt.Errorf("docker container manager not initialized") + } + return cm.RemoveContainer(ctx, containerID, true) +} + +// DestroySandbox destroys a Sprites sandbox by name. The executionID is used to +// resolve a cached API token when one exists; if no token is cached, the sprite's +// metadata-resolver fallback kicks in. +func (m *Manager) DestroySandbox(ctx context.Context, sandboxID, executionID string) error { + if sandboxID == "" { + return nil + } + backend, err := m.executorRegistry.GetBackend(executor.NameSprites) + if err != nil { + return fmt.Errorf("sprites backend unavailable: %w", err) + } + spritesExec, ok := backend.(*SpritesExecutor) + if !ok { + return fmt.Errorf("sprites backend has unexpected type %T", backend) + } + instance := &ExecutorInstance{ + InstanceID: executionID, + Metadata: map[string]interface{}{"sprite_name": sandboxID}, + } + return spritesExec.StopInstance(ctx, instance, true) +} diff --git a/apps/backend/internal/task/handlers/task_environment_handlers.go b/apps/backend/internal/task/handlers/task_environment_handlers.go index 9a75b19e96..de6ea62ece 100644 --- a/apps/backend/internal/task/handlers/task_environment_handlers.go +++ b/apps/backend/internal/task/handlers/task_environment_handlers.go @@ -1,9 +1,13 @@ package handlers import ( + "errors" "net/http" "github.com/gin-gonic/gin" + "go.uber.org/zap" + + "github.com/kandev/kandev/internal/task/service" ) func (h *TaskHandlers) httpGetTaskEnvironment(c *gin.Context) { @@ -19,3 +23,31 @@ func (h *TaskHandlers) httpGetTaskEnvironment(c *gin.Context) { } c.JSON(http.StatusOK, env.ToAPI()) } + +type resetEnvironmentRequest struct { + PushBranch bool `json:"push_branch"` +} + +func (h *TaskHandlers) httpResetTaskEnvironment(c *gin.Context) { + taskID := c.Param("id") + var body resetEnvironmentRequest + // Body is optional; ignore bind errors so an empty POST works. + _ = c.ShouldBindJSON(&body) + + err := h.service.ResetTaskEnvironment(c.Request.Context(), taskID, service.ResetOptions{ + PushBranch: body.PushBranch, + }) + switch { + case err == nil: + c.JSON(http.StatusOK, gin.H{"success": true}) + case errors.Is(err, service.ErrNoEnvironment): + c.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) + case errors.Is(err, service.ErrSessionRunning): + c.JSON(http.StatusConflict, gin.H{"error": err.Error()}) + default: + h.logger.Error("reset task environment failed", + zap.String("task_id", taskID), + zap.Error(err)) + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } +} diff --git a/apps/backend/internal/task/handlers/task_handlers.go b/apps/backend/internal/task/handlers/task_handlers.go index f0ba66a05f..b304e63d5c 100644 --- a/apps/backend/internal/task/handlers/task_handlers.go +++ b/apps/backend/internal/task/handlers/task_handlers.go @@ -71,6 +71,7 @@ func (h *TaskHandlers) registerHTTP(router *gin.Engine) { api.GET("/tasks/:id/sessions", h.httpListTaskSessions) api.POST("/tasks/:id/sessions/ensure", h.httpEnsureTaskSession) api.GET("/tasks/:id/environment", h.httpGetTaskEnvironment) + api.POST("/tasks/:id/environment/reset", h.httpResetTaskEnvironment) api.GET("/task-sessions/:id/turns", h.httpListSessionTurns) api.POST("/tasks", h.httpCreateTask) api.PATCH("/tasks/:id", h.httpUpdateTask) diff --git a/apps/backend/internal/task/service/service.go b/apps/backend/internal/task/service/service.go index 322e6f815a..273b6237c0 100644 --- a/apps/backend/internal/task/service/service.go +++ b/apps/backend/internal/task/service/service.go @@ -112,30 +112,32 @@ type Repos struct { // Service provides task business logic type Service struct { - workspaces repository.WorkspaceRepository - tasks repository.TaskRepository - taskRepos repository.TaskRepoRepository - workflows repository.WorkflowRepository - messages repository.MessageRepository - turns repository.TurnRepository - sessions repository.SessionRepository - gitSnapshots repository.GitSnapshotRepository - repoEntities repository.RepositoryEntityRepository - executors repository.ExecutorRepository - environments repository.EnvironmentRepository - taskEnvironments repository.TaskEnvironmentRepository - reviews repository.ReviewRepository - eventBus bus.EventBus - logger *logger.Logger - discoveryConfig RepositoryDiscoveryConfig - worktreeCleanup WorktreeCleanup - executionStopper TaskExecutionStopper - gitArchiveCapture GitArchiveCapture - workflowStepCreator WorkflowStepCreator - workflowStepGetter WorkflowStepGetter - startStepResolver StartStepResolver - quickChatDir string // Directory for quick-chat workspaces (e.g., ~/.kandev/quick-chat) - branchFetcher *branchFetcher + workspaces repository.WorkspaceRepository + tasks repository.TaskRepository + taskRepos repository.TaskRepoRepository + workflows repository.WorkflowRepository + messages repository.MessageRepository + turns repository.TurnRepository + sessions repository.SessionRepository + gitSnapshots repository.GitSnapshotRepository + repoEntities repository.RepositoryEntityRepository + executors repository.ExecutorRepository + environments repository.EnvironmentRepository + taskEnvironments repository.TaskEnvironmentRepository + reviews repository.ReviewRepository + eventBus bus.EventBus + logger *logger.Logger + discoveryConfig RepositoryDiscoveryConfig + worktreeCleanup WorktreeCleanup + executionStopper TaskExecutionStopper + gitArchiveCapture GitArchiveCapture + workflowStepCreator WorkflowStepCreator + workflowStepGetter WorkflowStepGetter + startStepResolver StartStepResolver + quickChatDir string // Directory for quick-chat workspaces (e.g., ~/.kandev/quick-chat) + branchFetcher *branchFetcher + envDestroyer EnvironmentDestroyer + sessionRunningChecker SessionRunningChecker } // NewService creates a new task service diff --git a/apps/backend/internal/task/service/service_task_environments.go b/apps/backend/internal/task/service/service_task_environments.go index dd2e3de239..52fd59fef2 100644 --- a/apps/backend/internal/task/service/service_task_environments.go +++ b/apps/backend/internal/task/service/service_task_environments.go @@ -2,12 +2,187 @@ package service import ( "context" + "errors" + "fmt" + + "go.uber.org/zap" "github.com/kandev/kandev/internal/task/models" ) +// EnvironmentDestroyer tears down the runtime resources recorded on a TaskEnvironment. +// Implemented by an adapter over the lifecycle.Manager and worktree.Manager. +// Worktree destruction preserves the underlying branch — user data that hasn't been +// pushed is never deleted by reset. +type EnvironmentDestroyer interface { + DestroyContainer(ctx context.Context, containerID string) error + DestroySandbox(ctx context.Context, sandboxID, executionID string) error + DestroyWorktree(ctx context.Context, worktreeID string) error + // PushEnvironmentBranch best-effort pushes the current branch of the environment's + // workspace to its upstream. Returns an error if the push fails; callers can decide + // whether to abort the reset on failure. + PushEnvironmentBranch(ctx context.Context, env *models.TaskEnvironment) error +} + +// ResetOptions controls destructive behavior of ResetTaskEnvironment. +type ResetOptions struct { + // PushBranch runs `git push` on the environment's current branch before teardown. + // If the push fails, ResetTaskEnvironment aborts and the environment stays intact. + PushBranch bool +} + +// SessionRunningChecker reports whether a session has a live executor running. +// Used by ResetTaskEnvironment to block resets when the user still has an agent +// attached to the environment. +type SessionRunningChecker interface { + IsAnySessionRunningForTask(ctx context.Context, taskID string) (bool, error) +} + +// ErrSessionRunning is returned by ResetTaskEnvironment when at least one session +// on the task is still actively running and the caller must stop it first. +var ErrSessionRunning = errors.New("active session is running on this task; stop it before resetting the environment") + +// ErrNoEnvironment is returned when the task has no TaskEnvironment to reset. +var ErrNoEnvironment = errors.New("no environment exists for this task") + +// SetEnvironmentDestroyer wires the runtime-resource destroyer used by ResetTaskEnvironment. +func (s *Service) SetEnvironmentDestroyer(d EnvironmentDestroyer) { + s.envDestroyer = d +} + +// SetSessionRunningChecker wires a custom running-session guard. When unset, the +// service falls back to a default implementation over the existing session repo. +func (s *Service) SetSessionRunningChecker(c SessionRunningChecker) { + s.sessionRunningChecker = c +} + +// checkAnySessionRunning delegates to the configured checker or falls back to +// the default (session has an ExecutorRunning row). +func (s *Service) checkAnySessionRunning(ctx context.Context, taskID string) (bool, error) { + if s.sessionRunningChecker != nil { + return s.sessionRunningChecker.IsAnySessionRunningForTask(ctx, taskID) + } + return s.isAnySessionRunning(ctx, taskID) +} + +// isAnySessionRunning is the default SessionRunningChecker: a session is running +// if it has an ExecutorRunning row in the repo. +func (s *Service) isAnySessionRunning(ctx context.Context, taskID string) (bool, error) { + sessions, err := s.sessions.ListTaskSessions(ctx, taskID) + if err != nil { + return false, err + } + for _, sess := range sessions { + if sess == nil { + continue + } + running, err := s.executors.GetExecutorRunningBySessionID(ctx, sess.ID) + if err != nil { + if errors.Is(err, models.ErrExecutorRunningNotFound) { + continue + } + return false, err + } + if running != nil { + return true, nil + } + } + return false, nil +} + // GetTaskEnvironmentByTaskID returns the active task environment for a task. // Returns nil if no environment exists yet. func (s *Service) GetTaskEnvironmentByTaskID(ctx context.Context, taskID string) (*models.TaskEnvironment, error) { return s.taskEnvironments.GetTaskEnvironmentByTaskID(ctx, taskID) } + +// ResetTaskEnvironment tears down the task's current environment (container/sandbox/worktree) +// and deletes the TaskEnvironment row, so the next session launch starts fresh. +// +// Guards: +// - No environment → ErrNoEnvironment +// - Any session on the task is actively running → ErrSessionRunning +// +// Cleanup is best-effort per resource. If any resource fails to destroy, the +// TaskEnvironment row is preserved so the user can retry. Success deletes the row. +// +// If opts.PushBranch is set, the branch is pushed before teardown; a failed push +// aborts the reset and leaves the environment intact so the user can investigate. +func (s *Service) ResetTaskEnvironment(ctx context.Context, taskID string, opts ResetOptions) error { + env, err := s.taskEnvironments.GetTaskEnvironmentByTaskID(ctx, taskID) + if err != nil { + return fmt.Errorf("lookup environment: %w", err) + } + if env == nil { + return ErrNoEnvironment + } + + running, err := s.checkAnySessionRunning(ctx, taskID) + if err != nil { + s.logger.Warn("failed to check running sessions before reset, continuing", + zap.String("task_id", taskID), + zap.Error(err)) + } else if running { + return ErrSessionRunning + } + + s.logger.Info("resetting task environment", + zap.String("task_id", taskID), + zap.String("env_id", env.ID), + zap.String("executor_type", env.ExecutorType), + zap.String("container_id", env.ContainerID), + zap.String("sandbox_id", env.SandboxID), + zap.String("worktree_id", env.WorktreeID), + zap.Bool("push_branch", opts.PushBranch)) + + if opts.PushBranch { + if s.envDestroyer == nil { + return fmt.Errorf("environment destroyer not configured; cannot push branch") + } + if err := s.envDestroyer.PushEnvironmentBranch(ctx, env); err != nil { + return fmt.Errorf("push branch before reset: %w", err) + } + } + + if err := s.teardownEnvironmentResources(ctx, env); err != nil { + return err + } + + if err := s.taskEnvironments.DeleteTaskEnvironment(ctx, env.ID); err != nil { + return fmt.Errorf("delete task environment row: %w", err) + } + s.logger.Info("task environment reset complete", + zap.String("task_id", taskID), + zap.String("env_id", env.ID)) + return nil +} + +// teardownEnvironmentResources destroys runtime resources (container/sandbox/worktree) +// recorded on a TaskEnvironment. On any failure, the caller should preserve the row. +func (s *Service) teardownEnvironmentResources(ctx context.Context, env *models.TaskEnvironment) error { + if env.ContainerID != "" { + if s.envDestroyer == nil { + return fmt.Errorf("environment destroyer not configured; cannot remove container") + } + if err := s.envDestroyer.DestroyContainer(ctx, env.ContainerID); err != nil { + return fmt.Errorf("destroy container %s: %w", env.ContainerID, err) + } + } + if env.SandboxID != "" { + if s.envDestroyer == nil { + return fmt.Errorf("environment destroyer not configured; cannot destroy sandbox") + } + if err := s.envDestroyer.DestroySandbox(ctx, env.SandboxID, env.AgentExecutionID); err != nil { + return fmt.Errorf("destroy sandbox %s: %w", env.SandboxID, err) + } + } + if env.WorktreeID != "" { + if s.envDestroyer == nil { + return fmt.Errorf("environment destroyer not configured; cannot remove worktree") + } + if err := s.envDestroyer.DestroyWorktree(ctx, env.WorktreeID); err != nil { + return fmt.Errorf("destroy worktree %s: %w", env.WorktreeID, err) + } + } + return nil +} diff --git a/apps/backend/internal/task/service/service_task_environments_test.go b/apps/backend/internal/task/service/service_task_environments_test.go new file mode 100644 index 0000000000..e380fc5fd5 --- /dev/null +++ b/apps/backend/internal/task/service/service_task_environments_test.go @@ -0,0 +1,188 @@ +package service + +import ( + "context" + "errors" + "testing" + + "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/task/models" +) + +type stubEnvRepo struct { + env *models.TaskEnvironment + deleted bool + getErr error + delErr error +} + +func (s *stubEnvRepo) CreateTaskEnvironment(context.Context, *models.TaskEnvironment) error { + return nil +} +func (s *stubEnvRepo) GetTaskEnvironment(context.Context, string) (*models.TaskEnvironment, error) { + return s.env, s.getErr +} +func (s *stubEnvRepo) GetTaskEnvironmentByTaskID(context.Context, string) (*models.TaskEnvironment, error) { + return s.env, s.getErr +} +func (s *stubEnvRepo) UpdateTaskEnvironment(context.Context, *models.TaskEnvironment) error { + return nil +} +func (s *stubEnvRepo) DeleteTaskEnvironment(context.Context, string) error { + if s.delErr != nil { + return s.delErr + } + s.deleted = true + return nil +} +func (s *stubEnvRepo) DeleteTaskEnvironmentsByTask(context.Context, string) error { return nil } + +type stubDestroyer struct { + containerCalls []string + sandboxCalls []string + worktreeCalls []string + pushCalls int + containerErr error + sandboxErr error + worktreeErr error + pushErr error +} + +func (s *stubDestroyer) DestroyContainer(_ context.Context, id string) error { + s.containerCalls = append(s.containerCalls, id) + return s.containerErr +} +func (s *stubDestroyer) DestroySandbox(_ context.Context, id, _ string) error { + s.sandboxCalls = append(s.sandboxCalls, id) + return s.sandboxErr +} +func (s *stubDestroyer) DestroyWorktree(_ context.Context, id string) error { + s.worktreeCalls = append(s.worktreeCalls, id) + return s.worktreeErr +} +func (s *stubDestroyer) PushEnvironmentBranch(context.Context, *models.TaskEnvironment) error { + s.pushCalls++ + return s.pushErr +} + +type stubRunningChecker struct { + running bool + err error +} + +func (s *stubRunningChecker) IsAnySessionRunningForTask(context.Context, string) (bool, error) { + return s.running, s.err +} + +func newResetTestService(t *testing.T, repo *stubEnvRepo) *Service { + t.Helper() + log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"}) + if err != nil { + t.Fatalf("failed to create logger: %v", err) + } + return &Service{ + logger: log, + taskEnvironments: repo, + } +} + +func TestResetTaskEnvironment_NoEnvironment(t *testing.T) { + svc := newResetTestService(t, &stubEnvRepo{env: nil}) + err := svc.ResetTaskEnvironment(context.Background(), "task-1", ResetOptions{}) + if !errors.Is(err, ErrNoEnvironment) { + t.Fatalf("expected ErrNoEnvironment, got %v", err) + } +} + +func TestResetTaskEnvironment_SessionRunningBlocks(t *testing.T) { + repo := &stubEnvRepo{env: &models.TaskEnvironment{ID: "env-1", TaskID: "task-1", ContainerID: "c"}} + svc := newResetTestService(t, repo) + svc.SetSessionRunningChecker(&stubRunningChecker{running: true}) + svc.SetEnvironmentDestroyer(&stubDestroyer{}) + + err := svc.ResetTaskEnvironment(context.Background(), "task-1", ResetOptions{}) + if !errors.Is(err, ErrSessionRunning) { + t.Fatalf("expected ErrSessionRunning, got %v", err) + } + if repo.deleted { + t.Error("expected environment row to be preserved when session is running") + } +} + +func TestResetTaskEnvironment_DestroysEachResourceTypeAndDeletesRow(t *testing.T) { + repo := &stubEnvRepo{env: &models.TaskEnvironment{ + ID: "env-1", + TaskID: "task-1", + ContainerID: "container-abc", + SandboxID: "sandbox-xyz", + WorktreeID: "wt-1", + AgentExecutionID: "exec-1", + }} + destroyer := &stubDestroyer{} + svc := newResetTestService(t, repo) + svc.SetSessionRunningChecker(&stubRunningChecker{running: false}) + svc.SetEnvironmentDestroyer(destroyer) + + if err := svc.ResetTaskEnvironment(context.Background(), "task-1", ResetOptions{}); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !repo.deleted { + t.Error("expected environment row to be deleted") + } + if len(destroyer.containerCalls) != 1 || destroyer.containerCalls[0] != "container-abc" { + t.Errorf("expected 1 container destroy call, got %v", destroyer.containerCalls) + } + if len(destroyer.sandboxCalls) != 1 || destroyer.sandboxCalls[0] != "sandbox-xyz" { + t.Errorf("expected 1 sandbox destroy call, got %v", destroyer.sandboxCalls) + } + if len(destroyer.worktreeCalls) != 1 || destroyer.worktreeCalls[0] != "wt-1" { + t.Errorf("expected 1 worktree destroy call, got %v", destroyer.worktreeCalls) + } +} + +func TestResetTaskEnvironment_ContainerDestroyFailurePreservesRow(t *testing.T) { + repo := &stubEnvRepo{env: &models.TaskEnvironment{ + ID: "env-1", + TaskID: "task-1", + ContainerID: "container-abc", + }} + destroyer := &stubDestroyer{containerErr: errors.New("docker unreachable")} + svc := newResetTestService(t, repo) + svc.SetSessionRunningChecker(&stubRunningChecker{running: false}) + svc.SetEnvironmentDestroyer(destroyer) + + err := svc.ResetTaskEnvironment(context.Background(), "task-1", ResetOptions{}) + if err == nil { + t.Fatal("expected error when container destroy fails") + } + if repo.deleted { + t.Error("expected environment row to be preserved when destroy fails") + } +} + +func TestResetTaskEnvironment_PushBranchFailureAbortsResetBeforeTeardown(t *testing.T) { + repo := &stubEnvRepo{env: &models.TaskEnvironment{ + ID: "env-1", + TaskID: "task-1", + WorktreeID: "wt-1", + WorktreePath: "/tmp/worktree", + }} + destroyer := &stubDestroyer{pushErr: errors.New("remote rejected")} + svc := newResetTestService(t, repo) + svc.SetSessionRunningChecker(&stubRunningChecker{running: false}) + svc.SetEnvironmentDestroyer(destroyer) + + err := svc.ResetTaskEnvironment(context.Background(), "task-1", ResetOptions{PushBranch: true}) + if err == nil { + t.Fatal("expected error when push fails") + } + if destroyer.pushCalls != 1 { + t.Errorf("expected push to be attempted once, got %d", destroyer.pushCalls) + } + if len(destroyer.worktreeCalls) != 0 { + t.Error("expected teardown to be skipped when push fails") + } + if repo.deleted { + t.Error("expected environment row to be preserved when push fails") + } +}