fix(tasks): recover cleanup preparation for missing worktrees (#3541)

This commit is contained in:
Carlos Florêncio
2026-09-09 10:31:00 +01:00
committed by GitHub
parent d1eb5280a2
commit 48f6c773dc
14 changed files with 1293 additions and 25 deletions
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/google/uuid"
@@ -398,7 +399,9 @@ func (s *Service) processTaskResourceCleanupJob(ctx context.Context, id string)
continue
}
if snapshot.WorktreeHeadOIDs != nil {
wt.CleanupHeadOID = snapshot.WorktreeHeadOIDs[wt.ID]
cleanupHeadOID, found := snapshot.WorktreeHeadOIDs[wt.ID]
wt.CleanupHeadOID = cleanupHeadOID
wt.CleanupHeadOIDUnavailable = !found || strings.TrimSpace(cleanupHeadOID) == ""
}
if snapshot.WorktreeTaskDirNames != nil {
wt.TaskDirName = snapshot.WorktreeTaskDirNames[wt.ID]
@@ -0,0 +1,335 @@
package service
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/kandev/kandev/internal/task/models"
sqliterepo "github.com/kandev/kandev/internal/task/repository/sqlite"
"github.com/kandev/kandev/internal/worktree"
)
type missingWorktreeCleanupFixture struct {
taskID string
manager *worktree.Manager
repositoryA string
worktreeA *worktree.Worktree
repositoryB string
worktreeB *worktree.Worktree
}
func TestPrepareTaskResourceCleanup_MissingWorktree(t *testing.T) {
ctx := context.Background()
taskSvc, repo := setupOfficeTest(t)
taskSvc.StopTaskResourceCleanupWorker()
fixture := newMissingWorktreeCleanupFixture(t, repo, "task-prepare-missing-worktree")
taskSvc.SetWorktreeCleanup(fixture.manager)
const operationID = "cascade_delete:missing-worktree:task-prepare-missing-worktree"
if err := taskSvc.PrepareTaskResourceCleanup(
ctx,
fixture.taskID,
models.TaskResourceCleanupTriggerCascadeDelete,
operationID,
true,
); err != nil {
t.Fatalf("PrepareTaskResourceCleanup: %v", err)
}
job, err := repo.GetTaskResourceCleanupJobByOperationID(ctx, operationID)
if err != nil {
t.Fatalf("GetTaskResourceCleanupJobByOperationID: %v", err)
}
if job.State != models.TaskResourceCleanupState("prepared") {
t.Fatalf("cleanup state = %q, want prepared", job.State)
}
var snapshot taskResourceCleanupSnapshot
if err := json.Unmarshal([]byte(job.ResourceSnapshot), &snapshot); err != nil {
t.Fatalf("decode cleanup snapshot: %v", err)
}
if len(snapshot.Worktrees) != 2 {
t.Fatalf("snapshot worktrees = %d, want both repositories: %+v", len(snapshot.Worktrees), snapshot.Worktrees)
}
if len(snapshot.WorktreeHeadOIDs) != 1 {
t.Fatalf("snapshot worktree identities = %#v, want only the surviving branch", snapshot.WorktreeHeadOIDs)
}
if _, ok := snapshot.WorktreeHeadOIDs[fixture.worktreeA.ID]; ok {
t.Fatalf("snapshot invented an identity for absent worktree %q: %#v", fixture.worktreeA.ID, snapshot.WorktreeHeadOIDs)
}
if got := snapshot.WorktreeHeadOIDs[fixture.worktreeB.ID]; got == "" {
t.Fatalf("snapshot omitted surviving worktree %q identity", fixture.worktreeB.ID)
}
task, err := repo.GetTask(ctx, fixture.taskID)
if err != nil {
t.Fatalf("GetTask: %v", err)
}
if task.ArchivedAt != nil {
t.Fatal("preparation mutated the task before the lifecycle mutation")
}
}
func TestTaskLifecycleCleanup_MissingWorktree(t *testing.T) {
tests := []struct {
name string
trigger models.TaskResourceCleanupTrigger
mutate func(context.Context, *Service, *sqliterepo.Repository, string) error
preserveBranch bool
}{
{
name: "direct archive",
trigger: models.TaskResourceCleanupTriggerArchive,
mutate: func(ctx context.Context, svc *Service, _ *sqliterepo.Repository, taskID string) error {
return svc.ArchiveTask(ctx, taskID)
},
preserveBranch: true,
},
{
name: "direct delete",
trigger: models.TaskResourceCleanupTriggerDelete,
mutate: func(ctx context.Context, svc *Service, _ *sqliterepo.Repository, taskID string) error {
return svc.DeleteTask(ctx, taskID)
},
},
{
name: "cascade archive",
trigger: models.TaskResourceCleanupTriggerCascadeArchive,
mutate: func(ctx context.Context, svc *Service, repo *sqliterepo.Repository, taskID string) error {
handoff := NewHandoffService(repo, repo, nil, nil, nil, nil)
handoff.SetTaskResourceCleaner(svc)
_, err := handoff.ArchiveTaskTree(ctx, taskID, true)
return err
},
preserveBranch: true,
},
{
name: "cascade delete",
trigger: models.TaskResourceCleanupTriggerCascadeDelete,
mutate: func(ctx context.Context, svc *Service, repo *sqliterepo.Repository, taskID string) error {
handoff := NewHandoffService(repo, repo, nil, nil, nil, nil)
handoff.SetTaskResourceCleaner(svc)
_, err := handoff.DeleteTaskTree(ctx, taskID, true)
return err
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
ctx := context.Background()
taskSvc, repo := setupOfficeTest(t)
taskSvc.StopTaskResourceCleanupWorker()
fixture := newMissingWorktreeCleanupFixture(t, repo, "task-lifecycle-missing-worktree")
taskSvc.SetWorktreeCleanup(fixture.manager)
if test.preserveBranch {
taskSvc.SetEnvironmentDestroyer(&archiveManagerEnvironmentDestroyer{mgr: fixture.manager})
} else {
taskSvc.SetEnvironmentDestroyer(&managerEnvironmentDestroyer{mgr: fixture.manager})
}
if err := test.mutate(ctx, taskSvc, repo, fixture.taskID); err != nil {
t.Fatalf("lifecycle mutation: %v", err)
}
job := latestCleanupJob(t, repo, fixture.taskID, test.trigger)
if job.State != models.TaskResourceCleanupStatePending {
t.Fatalf("cleanup state after mutation = %q, want pending", job.State)
}
if err := taskSvc.processTaskResourceCleanupJob(ctx, job.ID); err != nil {
t.Fatalf("processTaskResourceCleanupJob: %v", err)
}
job, err := repo.GetTaskResourceCleanupJob(ctx, job.ID)
if err != nil {
t.Fatalf("reload cleanup job: %v", err)
}
if job.State != models.TaskResourceCleanupStateSucceeded {
t.Fatalf("cleanup state = %q, want succeeded", job.State)
}
if _, statErr := os.Stat(fixture.worktreeA.Path); !os.IsNotExist(statErr) {
t.Errorf("absent worktree path was not absent after cleanup: %v", statErr)
}
if _, statErr := os.Stat(fixture.worktreeB.Path); !os.IsNotExist(statErr) {
t.Errorf("healthy worktree path remains after cleanup: %v", statErr)
}
assertNoWorktreeRegistration(t, fixture.repositoryA, fixture.worktreeA.Path)
assertNoWorktreeRegistration(t, fixture.repositoryB, fixture.worktreeB.Path)
branchOutput := strings.TrimSpace(string(runGitTestCmd(
t, fixture.repositoryB, "branch", "--list", fixture.worktreeB.Branch,
)))
if test.preserveBranch && branchOutput == "" {
t.Fatalf("archive cleanup deleted surviving branch %q", fixture.worktreeB.Branch)
}
if !test.preserveBranch && branchOutput != "" {
t.Fatalf("delete cleanup retained branch %q", fixture.worktreeB.Branch)
}
})
}
}
func TestTaskLifecycleCleanup_MissingWorktree_ReplacementBranchStaysRetryable(t *testing.T) {
ctx := context.Background()
taskSvc, repo := setupOfficeTest(t)
taskSvc.StopTaskResourceCleanupWorker()
fixture := newMissingWorktreeCleanupFixture(t, repo, "task-replacement-after-preparation")
taskSvc.SetWorktreeCleanup(fixture.manager)
taskSvc.SetEnvironmentDestroyer(&managerEnvironmentDestroyer{mgr: fixture.manager})
const operationID = "delete:replacement-after-preparation"
if err := taskSvc.PrepareTaskResourceCleanup(
ctx, fixture.taskID, models.TaskResourceCleanupTriggerDelete, operationID, true,
); err != nil {
t.Fatalf("PrepareTaskResourceCleanup: %v", err)
}
runGitTestCmd(t, fixture.repositoryA, "branch", fixture.worktreeA.Branch, "main")
if err := taskSvc.StartPreparedTaskResourceCleanup(ctx, operationID); err != nil {
t.Fatalf("StartPreparedTaskResourceCleanup: %v", err)
}
job := latestCleanupJob(t, repo, fixture.taskID, models.TaskResourceCleanupTriggerDelete)
if err := taskSvc.processTaskResourceCleanupJob(ctx, job.ID); err == nil {
t.Fatal("processTaskResourceCleanupJob error = nil, want replacement-branch safety error")
}
job, err := repo.GetTaskResourceCleanupJob(ctx, job.ID)
if err != nil {
t.Fatalf("reload cleanup job: %v", err)
}
if job.State != models.TaskResourceCleanupStateRetryWait {
t.Fatalf("cleanup state = %q, want retry_wait", job.State)
}
if got := strings.TrimSpace(string(runGitTestCmd(
t, fixture.repositoryA, "branch", "--list", fixture.worktreeA.Branch,
))); got == "" {
t.Fatalf("replacement branch %q was deleted after preparation", fixture.worktreeA.Branch)
}
}
func TestTaskLifecycleCleanup_MissingWorktree_ReplacementCheckoutStaysRetryable(t *testing.T) {
ctx := context.Background()
taskSvc, repo := setupOfficeTest(t)
taskSvc.StopTaskResourceCleanupWorker()
fixture := newMissingWorktreeCleanupFixture(t, repo, "task-replacement-checkout-after-preparation")
taskSvc.SetWorktreeCleanup(fixture.manager)
taskSvc.SetEnvironmentDestroyer(&archiveManagerEnvironmentDestroyer{mgr: fixture.manager})
const operationID = "archive:replacement-checkout-after-preparation"
if err := taskSvc.PrepareTaskResourceCleanup(
ctx, fixture.taskID, models.TaskResourceCleanupTriggerArchive, operationID, true,
); err != nil {
t.Fatalf("PrepareTaskResourceCleanup: %v", err)
}
if err := repo.ArchiveTask(ctx, fixture.taskID); err != nil {
t.Fatalf("ArchiveTask mutation: %v", err)
}
runGitTestCmd(t, fixture.repositoryA, "branch", fixture.worktreeA.Branch, "main")
runGitTestCmd(t, fixture.repositoryA, "worktree", "add", fixture.worktreeA.Path, fixture.worktreeA.Branch)
if err := taskSvc.StartPreparedTaskResourceCleanup(ctx, operationID); err != nil {
t.Fatalf("StartPreparedTaskResourceCleanup: %v", err)
}
job := latestCleanupJob(t, repo, fixture.taskID, models.TaskResourceCleanupTriggerArchive)
if err := taskSvc.processTaskResourceCleanupJob(ctx, job.ID); err == nil {
t.Fatal("processTaskResourceCleanupJob error = nil, want replacement-checkout safety error")
}
job, err := repo.GetTaskResourceCleanupJob(ctx, job.ID)
if err != nil {
t.Fatalf("reload cleanup job: %v", err)
}
if job.State != models.TaskResourceCleanupStateRetryWait {
t.Fatalf("cleanup state = %q, want retry_wait", job.State)
}
if _, err := os.Stat(fixture.worktreeA.Path); err != nil {
t.Fatalf("replacement checkout was removed after preparation: %v", err)
}
if got := strings.TrimSpace(string(runGitTestCmd(
t, fixture.repositoryA, "branch", "--list", fixture.worktreeA.Branch,
))); got == "" {
t.Fatalf("replacement branch %q was removed after preparation", fixture.worktreeA.Branch)
}
}
func newMissingWorktreeCleanupFixture(
t *testing.T,
repo *sqliterepo.Repository,
taskID string,
) *missingWorktreeCleanupFixture {
t.Helper()
ctx := context.Background()
sessionID := "session-" + taskID
environmentID := "env-" + taskID
seedCleanupTaskAndSession(t, repo, taskID, sessionID)
repositoryA := initSimpleGitRepo(t)
repositoryB := initSimpleGitRepo(t)
workspaceID := "ws-" + taskID
for id, path := range map[string]string{"repo-a-" + taskID: repositoryA, "repo-b-" + taskID: repositoryB} {
if err := repo.CreateRepository(ctx, &models.Repository{
ID: id, WorkspaceID: workspaceID, Name: id, SourceType: "local", LocalPath: path,
}); err != nil {
t.Fatalf("CreateRepository %s: %v", id, err)
}
}
if err := repo.CreateTaskEnvironment(ctx, &models.TaskEnvironment{
ID: environmentID, TaskID: taskID, ExecutorType: "worktree",
WorkspacePath: filepath.Join(t.TempDir(), "environment"), Status: models.TaskEnvironmentStatusReady,
}); err != nil {
t.Fatalf("CreateTaskEnvironment: %v", err)
}
session, err := repo.GetTaskSession(ctx, sessionID)
if err != nil {
t.Fatalf("GetTaskSession: %v", err)
}
session.TaskEnvironmentID = environmentID
if err := repo.UpdateTaskSession(ctx, session); err != nil {
t.Fatalf("UpdateTaskSession: %v", err)
}
manager := newCleanupTestWorktreeManager(t, repo)
worktreeA, err := manager.Create(ctx, worktree.CreateRequest{
TaskID: taskID, SessionID: sessionID, TaskEnvironmentID: environmentID,
TaskTitle: "Missing worktree cleanup", RepositoryID: "repo-a-" + taskID, RepositoryPath: repositoryA,
BaseBranch: "main", TaskDirName: taskID, RepoName: "repo-a",
})
if err != nil {
t.Fatalf("create worktree A: %v", err)
}
worktreeB, err := manager.Create(ctx, worktree.CreateRequest{
TaskID: taskID, SessionID: sessionID, TaskEnvironmentID: environmentID,
TaskTitle: "Missing worktree cleanup", RepositoryID: "repo-b-" + taskID, RepositoryPath: repositoryB,
BaseBranch: "main", TaskDirName: taskID, RepoName: "repo-b",
})
if err != nil {
t.Fatalf("create worktree B: %v", err)
}
runGitTestCmd(t, repositoryA, "worktree", "remove", "--force", worktreeA.Path)
runGitTestCmd(t, repositoryA, "branch", "-D", worktreeA.Branch)
return &missingWorktreeCleanupFixture{
taskID: taskID, manager: manager,
repositoryA: repositoryA, worktreeA: worktreeA,
repositoryB: repositoryB, worktreeB: worktreeB,
}
}
func latestCleanupJob(
t *testing.T,
repo *sqliterepo.Repository,
taskID string,
trigger models.TaskResourceCleanupTrigger,
) *models.TaskResourceCleanupJob {
t.Helper()
var jobID string
if err := repo.DB().QueryRowContext(context.Background(), `
SELECT id FROM task_resource_cleanup_jobs
WHERE task_id = ? AND trigger = ?
ORDER BY created_at DESC LIMIT 1
`, taskID, trigger).Scan(&jobID); err != nil {
t.Fatalf("load cleanup job: %v", err)
}
job, err := repo.GetTaskResourceCleanupJob(context.Background(), jobID)
if err != nil {
t.Fatalf("GetTaskResourceCleanupJob: %v", err)
}
return job
}
@@ -3626,7 +3626,11 @@ func (s *Service) cleanupDestructiveTaskResources(
return append(errs, cause)
}
if len(preserveExecutorRows) == 0 && !skipOwnedEnvironment {
errs = append(errs, s.cleanupTaskEnvironment(ctx, taskID, envCleanup)...)
environmentCleanup := envCleanup
if s.canBatchCleanupTaskWorktrees(envCleanup) {
environmentCleanup.env = taskEnvironmentWithoutSnapshotWorktrees(envCleanup.env, worktrees)
}
errs = append(errs, s.cleanupTaskEnvironment(ctx, taskID, environmentCleanup)...)
if cause := context.Cause(ctx); cause != nil {
return append(errs, cause)
}
@@ -3676,6 +3680,53 @@ func (s *Service) cleanupDestructiveTaskResources(
return errs
}
func (s *Service) canBatchCleanupTaskWorktrees(cleanup taskEnvironmentCleanup) bool {
if s.worktreeCleanup == nil {
return false
}
if cleanup.preserveBranches {
_, ok := s.worktreeCleanup.(WorktreeArchiveBatchCleaner)
return ok
}
if cleanup.discardWorktreeChanges {
_, ok := s.worktreeCleanup.(WorktreeBatchCleanerWithOptions)
return ok
}
_, ok := s.worktreeCleanup.(WorktreeBatchCleaner)
return ok
}
func taskEnvironmentWithoutSnapshotWorktrees(
env *models.TaskEnvironment, worktrees []*worktree.Worktree,
) *models.TaskEnvironment {
if env == nil || len(worktrees) == 0 {
return env
}
worktreeIDs := make(map[string]struct{}, len(worktrees))
for _, wt := range worktrees {
if wt != nil && wt.ID != "" {
worktreeIDs[wt.ID] = struct{}{}
}
}
if len(worktreeIDs) == 0 {
return env
}
clone := *env
clone.Repos = make([]*models.TaskEnvironmentRepo, len(env.Repos))
for i, repo := range env.Repos {
if repo == nil {
continue
}
repoClone := *repo
if _, ok := worktreeIDs[repo.WorktreeID]; ok {
repoClone.WorktreeID = ""
}
clone.Repos[i] = &repoClone
}
return &clone
}
func (s *Service) filterSharedWorktreesForTaskCleanup(
ctx context.Context,
taskID string,
@@ -220,7 +220,7 @@ func (m *Manager) enrichCleanupWorktreeFromCache(wt *Worktree) {
if wt.BaseBranch == "" {
wt.BaseBranch = cached.BaseBranch
}
if wt.CleanupHeadOID == "" {
if wt.CleanupHeadOID == "" && !wt.CleanupHeadOIDUnavailable {
wt.CleanupHeadOID = cached.CleanupHeadOID
}
}
@@ -242,28 +242,45 @@ func (m *Manager) CaptureCleanupHeadOIDs(ctx context.Context, worktrees []*Workt
// fail closed instead of rejecting the task mutation itself.
continue
}
identityPath := wt.Path
info, statErr := os.Stat(wt.Path)
if statErr != nil && !errors.Is(statErr, os.ErrNotExist) {
return nil, fmt.Errorf("capture cleanup identity for %s: %w", wt.ID, statErr)
}
if statErr != nil || !info.IsDir() {
if wt.Branch == "" {
continue
}
identityPath = wt.RepositoryPath
}
args := []string{"rev-parse", "--verify", "HEAD^{commit}"}
if identityPath == wt.RepositoryPath {
args = []string{"rev-parse", "--verify", "refs/heads/" + wt.Branch + "^{commit}"}
}
output, err := m.runBoundedGitInspect(ctx, identityPath, args...)
pathPresent, err := cleanupPathPresent(wt.Path)
if err != nil {
return nil, fmt.Errorf("capture cleanup identity for %s: %w", wt.ID, err)
}
oid := strings.TrimSpace(output)
if oid == "" {
return nil, fmt.Errorf("capture cleanup identity for %s returned an empty commit", wt.ID)
if !pathPresent {
branch := strings.TrimSpace(wt.Branch)
if branch == "" {
m.logger.Warn("cleanup worktree path is absent and branch is unknown",
zap.String("task_id", wt.TaskID),
zap.String("worktree_id", wt.ID),
zap.String("repository_path", wt.RepositoryPath),
zap.String("reason", "empty branch on environment row"))
continue
}
branchRef := "refs/heads/" + branch
oid, found, err := m.captureCleanupBranchOID(ctx, wt.RepositoryPath, branchRef)
if err != nil {
return nil, fmt.Errorf("capture cleanup identity for %s: %w", wt.ID, err)
}
if !found {
m.logger.Warn("cleanup worktree path and branch are absent",
zap.String("task_id", wt.TaskID),
zap.String("worktree_id", wt.ID),
zap.String("repository_path", wt.RepositoryPath),
zap.String("branch", branch),
zap.String("reason", "local branch ref not found"))
continue
}
identities[wt.ID] = oid
continue
}
output, err := m.runBoundedGitInspect(ctx, wt.Path, "rev-parse", "--verify", "HEAD^{commit}")
if err != nil {
return nil, fmt.Errorf("capture cleanup identity for %s: %w", wt.ID, err)
}
oid, err := parseCleanupCommitOID(output)
if err != nil {
return nil, fmt.Errorf("capture cleanup identity for %s: %w", wt.ID, err)
}
identities[wt.ID] = oid
}
@@ -132,6 +132,9 @@ func (m *Manager) cleanupBranchIdentity(
branchRef = "refs/heads/" + wt.Branch
}
expectedOID := strings.TrimSpace(wt.CleanupHeadOID)
if wt.CleanupHeadOIDUnavailable && pathPresent {
return "", "", fmt.Errorf("cleanup worktree path %q reappeared without immutable expected commit", wt.Path)
}
if expectedOID == "" && pathPresent {
output, err := m.runBoundedGitInspect(ctx, wt.Path, "rev-parse", "--verify", "HEAD^{commit}")
if err != nil {
@@ -0,0 +1,76 @@
package worktree
import (
"context"
"encoding/hex"
"fmt"
"strings"
)
const cleanupBranchRefFormat = "--format=%(refname)%00%(objectname)%00%(objecttype)"
func (m *Manager) captureCleanupBranchOID(
ctx context.Context, repositoryPath, branchRef string,
) (string, bool, error) {
output, err := m.runBoundedGitInspect(
ctx, repositoryPath, "for-each-ref", cleanupBranchRefFormat, branchRef,
)
if err != nil {
return "", false, fmt.Errorf("inspect local branch %q: %w", branchRef, err)
}
return parseCleanupBranchRefOutput(output, branchRef)
}
func parseCleanupBranchRefOutput(output, wantedRef string) (string, bool, error) {
if output == "" {
return "", false, nil
}
lines := strings.Split(output, "\n")
if lines[len(lines)-1] == "" {
lines = lines[:len(lines)-1]
}
if len(lines) == 0 {
return "", false, nil
}
var oid string
for _, line := range lines {
line = strings.TrimSuffix(line, "\r")
fields := strings.Split(line, "\x00")
if len(fields) != 3 || !strings.HasPrefix(fields[0], "refs/") || fields[1] == "" || fields[2] == "" {
return "", false, fmt.Errorf("malformed local branch inspection output")
}
// Validate every returned line for fail-closed safety; skip non-matching refs.
if fields[2] != "commit" {
return "", false, fmt.Errorf("local branch %q resolved to object type %q", fields[0], fields[2])
}
if !validCleanupCommitOID(fields[1]) {
return "", false, fmt.Errorf("local branch %q returned an invalid commit %q", fields[0], fields[1])
}
if fields[0] != wantedRef {
continue
}
if oid != "" {
return "", false, fmt.Errorf("local branch %q was returned more than once", wantedRef)
}
oid = fields[1]
}
return oid, oid != "", nil
}
func parseCleanupCommitOID(output string) (string, error) {
output = strings.TrimSuffix(output, "\n")
output = strings.TrimSuffix(output, "\r")
if !validCleanupCommitOID(output) {
return "", fmt.Errorf("returned invalid commit identity")
}
return output, nil
}
func validCleanupCommitOID(oid string) bool {
if len(oid) != 40 && len(oid) != 64 {
return false
}
_, err := hex.DecodeString(oid)
return err == nil
}
@@ -0,0 +1,301 @@
package worktree
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestCaptureCleanupHeadOIDs_MissingWorktree(t *testing.T) {
repoPath := initGitRepoForWorktreeTest(t)
mgr, err := NewManager(newTestConfig(t), newMockStore(), newTestLogger())
if err != nil {
t.Fatalf("NewManager failed: %v", err)
}
healthyPath := filepath.Join(t.TempDir(), "healthy")
runGit(t, repoPath, "worktree", "add", healthyPath, "feature/pr-branch")
healthyOID := strings.TrimSpace(runGit(t, healthyPath, "rev-parse", "HEAD"))
mainOID := strings.TrimSpace(runGit(t, repoPath, "rev-parse", "main"))
survivingBranch := "feature/missing-surviving"
packedBranch := "feature/missing-packed"
descendantBranch := "feature/missing-descendant/child"
tagOnlyBranch := "feature/tag-only"
for _, branch := range []string{survivingBranch, packedBranch, descendantBranch} {
runGit(t, repoPath, "branch", branch, "main")
}
runGit(t, repoPath, "tag", tagOnlyBranch, "main")
runGit(t, repoPath, "pack-refs", "--all")
worktrees := []*Worktree{
{
ID: "missing-first",
RepositoryPath: repoPath,
Path: filepath.Join(t.TempDir(), "missing-first"),
Branch: "feature/missing-descendant",
},
{
ID: "healthy",
RepositoryPath: repoPath,
Path: healthyPath,
Branch: "feature/pr-branch",
},
{
ID: "surviving-branch",
RepositoryPath: repoPath,
Path: filepath.Join(t.TempDir(), "surviving-branch"),
Branch: survivingBranch,
},
{
ID: "packed-branch",
RepositoryPath: repoPath,
Path: filepath.Join(t.TempDir(), "packed-branch"),
Branch: packedBranch,
},
{
ID: "descendant-only",
RepositoryPath: repoPath,
Path: filepath.Join(t.TempDir(), "descendant-only"),
Branch: "feature/missing-descendant",
},
{
ID: "tag-only",
RepositoryPath: repoPath,
Path: filepath.Join(t.TempDir(), "tag-only"),
Branch: tagOnlyBranch,
},
{
ID: "missing-last",
RepositoryPath: repoPath,
Path: filepath.Join(t.TempDir(), "missing-last"),
Branch: "feature/not-present",
},
{
ID: "no-branch",
RepositoryPath: repoPath,
Path: filepath.Join(t.TempDir(), "no-branch"),
},
}
refsBefore := strings.TrimSpace(runGit(t, repoPath, "show-ref", "--heads"))
got, err := mgr.CaptureCleanupHeadOIDs(context.Background(), worktrees)
if err != nil {
t.Fatalf("CaptureCleanupHeadOIDs() unexpected error: %v", err)
}
want := map[string]string{
"healthy": healthyOID,
"surviving-branch": mainOID,
"packed-branch": mainOID,
}
if len(got) != len(want) {
t.Fatalf("captured %d identities, want %d: %#v", len(got), len(want), got)
}
for id, wantOID := range want {
if got[id] != wantOID {
t.Errorf("identity[%q] = %q, want %q", id, got[id], wantOID)
}
}
for _, id := range []string{"missing-first", "descendant-only", "tag-only", "missing-last", "no-branch"} {
if _, ok := got[id]; ok {
t.Errorf("identity[%q] unexpectedly captured for an absent exact branch", id)
}
}
refsAfter := strings.TrimSpace(runGit(t, repoPath, "show-ref", "--heads"))
if refsAfter != refsBefore {
t.Fatalf("branch refs changed during capture:\nbefore:\n%s\nafter:\n%s", refsBefore, refsAfter)
}
for _, wt := range worktrees {
if wt.Path == "" || wt.RepositoryPath == "" {
t.Fatalf("test worktree %q is incomplete", wt.ID)
}
if wt.Branch == "" {
continue
}
if _, err := os.Lstat(wt.Path); err == nil && wt.ID != "healthy" {
t.Errorf("capture unexpectedly created path for %q", wt.ID)
}
}
}
func TestCaptureCleanupHeadOIDs_FailsClosed(t *testing.T) {
t.Run("invalid repository", func(t *testing.T) {
mgr := newCaptureTestManager(t)
_, err := mgr.CaptureCleanupHeadOIDs(context.Background(), []*Worktree{{
ID: "invalid-repository",
RepositoryPath: t.TempDir(),
Path: filepath.Join(t.TempDir(), "missing"),
Branch: "feature/missing",
}})
if err == nil {
t.Fatal("CaptureCleanupHeadOIDs() error = nil, want invalid repository error")
}
})
t.Run("git unavailable", func(t *testing.T) {
repoPath := initGitRepoForWorktreeTest(t)
t.Setenv("PATH", t.TempDir())
mgr := newCaptureTestManager(t)
_, err := mgr.CaptureCleanupHeadOIDs(context.Background(), []*Worktree{{
ID: "git-unavailable",
RepositoryPath: repoPath,
Path: filepath.Join(t.TempDir(), "missing"),
Branch: "feature/missing",
}})
if err == nil {
t.Fatal("CaptureCleanupHeadOIDs() error = nil, want unavailable git error")
}
})
for _, tc := range []struct {
name string
scriptBody string
}{
{
name: "unexpected diagnostic",
scriptBody: `
case "${1:-}" in
for-each-ref)
echo "warning: ref database is stale" >&2
exit 0
;;
*)
exit 0
;;
esac
`,
},
{
name: "malformed ref record",
scriptBody: `
printf 'refs/heads/feature/missing\000not-an-object\000commit\n'
exit 0
`,
},
{
name: "missing object",
scriptBody: `
printf 'refs/heads/feature/missing\000aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\000unknown\n'
exit 0
`,
},
} {
t.Run(tc.name, func(t *testing.T) {
scriptDir := writeFakeGitScript(t, tc.scriptBody)
t.Setenv("PATH", scriptDir+string(os.PathListSeparator)+os.Getenv("PATH"))
mgr := newCaptureTestManager(t)
_, err := mgr.CaptureCleanupHeadOIDs(context.Background(), []*Worktree{{
ID: "invalid-output",
RepositoryPath: t.TempDir(),
Path: filepath.Join(t.TempDir(), "missing"),
Branch: "feature/missing",
}})
if err == nil {
t.Fatal("CaptureCleanupHeadOIDs() error = nil, want malformed Git output error")
}
})
}
t.Run("canceled", func(t *testing.T) {
scriptDir := writeFakeGitScript(t, `
sleep 30
`)
t.Setenv("PATH", scriptDir+string(os.PathListSeparator)+os.Getenv("PATH"))
mgr := newCaptureTestManager(t)
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := mgr.CaptureCleanupHeadOIDs(ctx, []*Worktree{{
ID: "canceled",
RepositoryPath: t.TempDir(),
Path: filepath.Join(t.TempDir(), "missing"),
Branch: "feature/missing",
}})
if err == nil {
t.Fatal("CaptureCleanupHeadOIDs() error = nil, want cancellation error")
}
})
t.Run("bounded timeout", func(t *testing.T) {
scriptDir := writeFakeGitScript(t, `
sleep 30
`)
t.Setenv("PATH", scriptDir+string(os.PathListSeparator)+os.Getenv("PATH"))
mgr := newCaptureTestManager(t)
mgr.inspectTimeout = 100 * time.Millisecond
start := time.Now()
_, err := mgr.CaptureCleanupHeadOIDs(context.Background(), []*Worktree{{
ID: "timeout",
RepositoryPath: t.TempDir(),
Path: filepath.Join(t.TempDir(), "missing"),
Branch: "feature/missing",
}})
if err == nil {
t.Fatal("CaptureCleanupHeadOIDs() error = nil, want timeout error")
}
if elapsed := time.Since(start); elapsed > 2*time.Second {
t.Fatalf("CaptureCleanupHeadOIDs() took %v, want less than two seconds", elapsed)
}
})
t.Run("regular file", func(t *testing.T) {
path := filepath.Join(t.TempDir(), "regular-file")
if err := os.WriteFile(path, []byte("not a worktree"), 0644); err != nil {
t.Fatalf("write regular file: %v", err)
}
mgr := newCaptureTestManager(t)
_, err := mgr.CaptureCleanupHeadOIDs(context.Background(), []*Worktree{{
ID: "regular-file",
RepositoryPath: t.TempDir(),
Path: path,
Branch: "feature/missing",
}})
if err == nil {
t.Fatal("CaptureCleanupHeadOIDs() error = nil, want regular-file error")
}
})
t.Run("symlink", func(t *testing.T) {
path := filepath.Join(t.TempDir(), "symlink")
if err := os.Symlink(t.TempDir(), path); err != nil {
t.Skipf("symlinks unavailable: %v", err)
}
mgr := newCaptureTestManager(t)
_, err := mgr.CaptureCleanupHeadOIDs(context.Background(), []*Worktree{{
ID: "symlink",
RepositoryPath: t.TempDir(),
Path: path,
Branch: "feature/missing",
}})
if err == nil {
t.Fatal("CaptureCleanupHeadOIDs() error = nil, want symlink error")
}
})
t.Run("filesystem error", func(t *testing.T) {
mgr := newCaptureTestManager(t)
_, err := mgr.CaptureCleanupHeadOIDs(context.Background(), []*Worktree{{
ID: "filesystem-error",
RepositoryPath: t.TempDir(),
Path: "invalid\x00path",
Branch: "feature/missing",
}})
if err == nil {
t.Fatal("CaptureCleanupHeadOIDs() error = nil, want filesystem error")
}
})
}
func newCaptureTestManager(t *testing.T) *Manager {
t.Helper()
mgr, err := NewManager(newTestConfig(t), newMockStore(), newTestLogger())
if err != nil {
t.Fatalf("NewManager failed: %v", err)
}
return mgr
}
@@ -78,6 +78,11 @@ type Worktree struct {
// closed if the recorded path or branch advanced before teardown.
CleanupHeadOID string `json:"-"`
// CleanupHeadOIDUnavailable indicates that the current durable cleanup
// snapshot intentionally omitted this worktree's commit identity. It is
// internal provenance, so it is rebuilt when a snapshot is loaded.
CleanupHeadOIDUnavailable bool `json:"-"`
// BaseBranch is the branch this worktree was created from.
BaseBranch string `json:"base_branch"`
@@ -0,0 +1,201 @@
---
created: 2026-09-09
status: done
requirements:
- REQ-TASKS-RUNTIME-CLEANUP-001
system_design:
- ../../specs/tasks/system-design/runtime-cleanup.md
- ../../specs/tasks/system-design/runtime-cleanup-preparation.md
legacy_specs: []
---
# Implementation Plan: Missing Worktree Cleanup Preparation
## Overview
[Issue #3531](https://github.com/kdlbs/kandev/issues/3531) reports blocked task
archive and deletion after external worktree removal. The issue is assigned to
`carlosflorencio`.
One sequential work order corrects preparation and proves the complete task
lifecycle. The implementation and validation are complete. The investigation used revision
`ecd3efc01b819615e1eb3219d774dfb0e3a44cfd`.
The [preparation design](../../specs/tasks/system-design/runtime-cleanup-preparation.md)
defines the missing-resource boundary. The task system owns cleanup preparation and
the durable resource snapshot. Workspace ownership and deletion safeguards
remain governed by the existing design and ADRs.
## Confirmed root cause
`CaptureCleanupHeadOIDs` already checks the worktree path with `os.Stat`.
For an absent directory, it resolves `refs/heads/<branch>^{commit}` from the
parent repository. If the branch is also absent, Git exits 128.
`captureWorktreeCleanupHeadOIDs` propagates the error through
`PrepareTaskResourceCleanupWithOptions` before task mutation.
Preparation reserves a `prepared` cleanup job before identity capture. The
capture error prevents replacement of its placeholder snapshot. This explains
the reported `prepared` jobs with zero worker attempts.
The current failure does not require Git to run inside the missing directory.
The fallback branch lookup alone reproduces the reported error.
## Reproduction evidence
A temporary test used the real task service, SQLite repository, worktree
manager, and disposable Git repositories. It created an active worktree row,
removed the checkout through Git, and retained the database inventory.
Command, from `apps/backend`:
```bash
rtk go test -tags fts5 ./internal/task/service -run '^TestRepro3531_PrepareMissingWorktree$' -count=1 -v
```
- `branch_present` passed preparation after directory removal.
- `branch_absent` failed after removal of the local branch as well.
- The failure contained `capture worktree cleanup identities` and `exit status 128`.
- A second diagnostic proved that `CleanupWorktrees` already accepts the fully
absent resource without a captured commit identity.
A separate Git probe established these results on Git 2.47.3:
| Probe result | Exit | Combined output |
| --- | --- | --- |
| Exact branch present | 0 | Ref name, object ID, and `commit` |
| Exact branch absent | 0 | Empty |
| Broken ref | 0 | Warning text |
| Ref points to missing object | 128 | Fatal diagnostic |
The probe used `for-each-ref` with
`--format=%(refname)%00%(objectname)%00%(objecttype)` and the full branch ref.
Its four diagnostic cases passed. A quiet `show-ref --verify` probe returned
the same exit code for a missing ref and a broken ref, so it is unsuitable here.
Temporary tests and their fixture data were removed after diagnosis. No user
instance or database was modified. The permanent regression must first fail
against unchanged production code during implementation.
## Scope
### In scope
- Preparation for absent worktrees with either surviving or absent branches.
- Complete snapshots for tasks with healthy and absent repository worktrees.
- Direct and cascade archive/delete through the real services and cleanup worker.
- Error classification and existing ownership, branch, and path safeguards.
### Out of scope
- Recreating missing worktrees or recovering externally deleted commits.
- Automatic database repair, schema changes, or removal of historical jobs.
- Relaxing cleanup audits or treating generic Git errors as absence.
- New UI controls, translations, runtime flags, or executor behavior.
## Technical approach
The correction belongs in
`apps/backend/internal/worktree/manager_cleanup.go:CaptureCleanupHeadOIDs`,
with strict ref and object-ID parsing in the adjacent
`manager_cleanup_capture.go` helper file.
Use the existing `cleanupPathPresent` classification for physical paths.
Keep existing handling for incomplete legacy inventory metadata.
For absent paths with a recorded branch, use a bounded exact-ref probe through
`runBoundedGitInspect`. The structured `for-each-ref` form above supports old
Git versions without the newer `show-ref --exists` option.
Git patterns can include descendant refs. Compare the returned full ref name
exactly, as specified in the [Git documentation](https://git-scm.com/docs/git-for-each-ref).
Parse only complete records with a nonempty object ID and object type `commit`.
Reject unexpected output, including warnings on stderr combined by the runner.
A successful response without the exact ref establishes absence.
An exact branch result supplies its immutable commit identity.
An absent branch omits only its identity-map entry and emits a bounded warning
with the task/worktree IDs and the absence reason.
At execution, snapshot worktrees use the identity-aware batch cleanup path. The
task-environment teardown path skips those same worktree IDs so its legacy
ID-only destroyer cannot adopt a checkout that reappeared after preparation.
The worker keeps such a replacement retryable when no immutable identity is
available.
Do not use `Manager.branchExists` to establish absence in preparation.
That helper currently maps generic command failures to `false` outside timeout
handling. Changing its wider behavior is outside this repair.
Keep the full `Worktrees` snapshot and the existing service error propagation.
`manager_cleanup_audit.go` remains the authority for destructive worker actions.
No early row deletion, broad Git prune, or new cleanup status is required.
Related decisions:
- [Fail-closed cleanup](../../decisions/0009-fail-closed-gc-semantics.md).
- [Task-owned worktree lifetime](../../decisions/2026-08-08-task-owned-worktree-lifetime.md).
This repair applies those boundaries without a new architectural decision.
## Tests
| Acceptance criteria | Permanent evidence |
| --- | --- |
| .9, .13 | `manager_cleanup_capture_test.go`: `TestCaptureCleanupHeadOIDs_MissingWorktree` |
| .9, .12 | `manager_cleanup_capture_test.go`: `TestCaptureCleanupHeadOIDs_FailsClosed` |
| .6, .13 | `resource_cleanup_missing_worktree_test.go`: `TestPrepareTaskResourceCleanup_MissingWorktree` |
| .6, .7, .9, .13 | Same file: `TestTaskLifecycleCleanup_MissingWorktree` |
| .9, .13 | Same file: `TestTaskLifecycleCleanup_MissingWorktree_ReplacementBranchStaysRetryable` |
All criterion suffixes refer to `AC-TASKS-RUNTIME-CLEANUP-001`.
The work order defines the case matrix, worker assertions, and exact commands.
New test files avoid the existing oversized `resource_cleanup_jobs_test.go`.
## E2E tests
The backend integration matrix reproduces the missing-resource defect through
real lifecycle services and durable cleanup. Existing browser flows provide
end-to-end evidence for unchanged controls:
- `tests/kanban/card-menu-delete-archive.spec.ts`, project `chromium`: archive
and delete remove the card. Maps to .13 with the backend matrix.
- `tests/task/mobile-archive-task-redirect.spec.ts`, project `mobile-chrome`:
cascade archive preserves usable navigation. Maps to .13 with the backend matrix.
These browser tests are smoke coverage, not independent reproductions of the
missing-worktree state. No new layout or touch behavior requires a mobile design.
## Work orders
- [done] [Task 01: Recover cleanup preparation for absent worktrees](task-01-recover-preparation.md)
## Verification results
Diagnosis: real service reproduction failed as expected, with the surviving-branch
control passing. Existing execution accepted the fully absent resource.
The structured-ref diagnostic passed all four cases.
Design validation passed: `lint-spec-files.py --all`, all 30 specification-linter
tests, and `git diff --check`.
Implementation and its regression/E2E checks are complete. The manager capture
matrix and lifecycle regressions pass in normal and race-enabled runs. The
existing browser smoke flows pass with 5 Chromium tests and 1 mobile-Chromium
test. The changed-code Go lint reports 0 issues; the specification linter and
diff check also pass.
## Documentation impact
Internal requirements and design describe the preparation contract explicitly.
Public docs need no change during this design turn. The repair adds no operator
action or public interface, and restores the existing cleanup intent.
## Risks
- Treating a warning or generic Git failure as absence can hide damaged metadata.
- Dropping the worktree snapshot entry can lose registration and row cleanup.
- A directory or branch can reappear between preparation and execution.
Existing worker identity audits must remain active.
- Stale registrations without verifiable identity remain retryable by design.
- Historical prepared-job reconciliation remains unchanged.
- The WSL host was not reproduced. The same failure reproduced on Linux through
the platform-independent Go/Git path.
@@ -0,0 +1,207 @@
---
id: "01-recover-preparation"
title: "Recover cleanup preparation for absent worktrees"
status: done
wave: 1
depends_on: []
plan: "plan.md"
requirements:
- REQ-TASKS-RUNTIME-CLEANUP-001
acceptance_criteria:
- AC-TASKS-RUNTIME-CLEANUP-001.6
- AC-TASKS-RUNTIME-CLEANUP-001.7
- AC-TASKS-RUNTIME-CLEANUP-001.9
- AC-TASKS-RUNTIME-CLEANUP-001.12
- AC-TASKS-RUNTIME-CLEANUP-001.13
system_design:
- ../../specs/tasks/system-design/runtime-cleanup.md
- ../../specs/tasks/system-design/runtime-cleanup-preparation.md
---
# Task 01: Recover cleanup preparation for absent worktrees
## Summary
Preparation accepts confirmed absence without losing the durable worktree
snapshot. Existing cleanup audits still protect resources that remain or reappear.
## In scope
- Classify physical paths before identity capture.
- Capture surviving branch commits through a bounded exact-ref inspection.
- Omit an identity only after a successful absence result.
- Add manager and lifecycle regressions before the production correction.
- Run the targeted backend and existing browser checks.
## Out of scope
- SQL changes, new cleanup snapshot fields, and historical-job repair.
- Changes to worker ownership rules or general `branchExists` behavior.
- Production frontend changes or new browser fixture infrastructure.
## Acceptance
1. Absent worktree directories and branches permit direct and cascade
archive/delete. A healthy sibling repository retains its snapshot identity.
2. Preparation preserves inventory rows and snapshots until normal lifecycle
cleanup. Broken refs, filesystem errors, Git failures, and cancellation
cannot establish absence.
3. The worker completes fully absent resources and retains archive recovery
metadata. Existing dirty, shared, unique-commit, and replacement safeguards pass.
Snapshot worktrees do not bypass identity-aware batch cleanup through the
legacy environment destroyer.
## Implementation sequence
1. Mark this work order `in_progress`.
2. Add the manager and lifecycle regressions in the new test files.
3. Run the regressions against unchanged production code.
4. Record the missing-branch preparation failure.
5. Correct `CaptureCleanupHeadOIDs` with a small private helper where needed.
6. Run the commands in Verification.
7. Record results in this file and the plan.
8. Mark this work order `done` after all required checks pass.
## Regression matrix
`TestCaptureCleanupHeadOIDs_MissingWorktree` covers:
- A healthy checkout, an absent checkout with a surviving branch, and a fully
absent checkout/branch/registration.
- A mixed batch with an absent resource first and last.
- Exact branch names versus descendant refs, packed refs, and an absent branch
that has a tag with the same short name.
- Retained worktree records, unchanged files/refs, and the expected identity map.
`TestCaptureCleanupHeadOIDs_FailsClosed` covers:
- An inaccessible or invalid parent repository and an unavailable Git command.
- A broken ref, a ref pointing at a missing object, and unexpected diagnostic output.
- Context cancellation and a bounded inspection timeout.
- A regular file or symbolic link at the recorded checkout path.
- Filesystem errors other than absence. Probe permission enforcement before
relying on mode bits in a privileged test environment.
`TestPrepareTaskResourceCleanup_MissingWorktree` uses `setupOfficeTest`,
`newCleanupTestWorktreeManager`, and real Git fixtures. Keep the worker stopped
during snapshot assertions. The fixture creates two repository rows in one
environment and leaves both active after external removal of one checkout.
Use `git worktree remove` and branch removal only inside disposable test roots.
The test covers both cascade triggers and inspects the durable snapshot. Both
worktree entries remain present, and the healthy repository retains its commit.
The absent branch contributes no invented commit. Preparation leaves the task
unmodified and the job prepared until the lifecycle mutation commits.
`TestTaskLifecycleCleanup_MissingWorktree` covers direct `ArchiveTask` and
`DeleteTask`, plus `ArchiveTaskTree` and `DeleteTaskTree`. Use the real
`HandoffService` wiring from the existing cascade tests.
Run the durable worker and verify the terminal result. Archive preserves the
environment, repository history, and healthy branch. Delete completes cleanup
after task-row removal. Fully absent resources must not cause `retry_wait`.
A healthy sibling still receives its normal cleanup disposition.
Add a race scenario that creates a replacement branch after preparation.
Deletion must preserve the new branch without an immutable captured identity.
Retain the existing stale-registration refusal and branch-preserving archive behavior.
## Verification
From `apps/backend`, run the new regressions before the correction:
```bash
rtk go test -tags fts5 ./internal/worktree -run '^TestCaptureCleanupHeadOIDs_' -count=1 -v
rtk go test -tags fts5 ./internal/task/service -run '^(TestPrepareTaskResourceCleanup_MissingWorktree|TestTaskLifecycleCleanup_MissingWorktree|TestTaskLifecycleCleanup_MissingWorktree_ReplacementBranchStaysRetryable|TestTaskLifecycleCleanup_MissingWorktree_ReplacementCheckoutStaysRetryable)$' -count=1 -v
```
After the correction, run the focused checks from `apps/backend`:
```bash
rtk go test -race -tags fts5 ./internal/worktree -run '^(TestCaptureCleanupHeadOIDs_|TestCleanupWorktrees)' -count=1
rtk go test -race -tags fts5 ./internal/task/service -run '^(TestPrepareTaskResourceCleanup_MissingWorktree|TestTaskLifecycleCleanup_MissingWorktree|TestTaskLifecycleCleanup_MissingWorktree_ReplacementBranchStaysRetryable|TestTaskLifecycleCleanup_MissingWorktree_ReplacementCheckoutStaysRetryable|TestPreparedCascadeCleanupSnapshotPersistsWorktreeTaskDirNames|TestArchiveAndDeleteCleanupRemainPreparedUntilMutationCommits|TestTaskResourceCleanupMissingResourcesSucceed|TestUnarchiveCancelsAndJoinsClaimedArchiveCleanup)$' -count=1
```
Before the first package command in a fresh worktree, run from `apps`:
```bash
rtk pnpm install --frozen-lockfile
```
Run the existing browser flows sequentially from `apps/web`:
```bash
rtk pnpm e2e:run --project chromium tests/kanban/card-menu-delete-archive.spec.ts
rtk pnpm e2e:run --project mobile-chrome tests/task/mobile-archive-task-redirect.spec.ts
```
The managed runner rebuilds production artifacts and cleans its isolated
runtime. Record discovered test counts and results. Do not overlap suites or
add worker overrides.
From the repository root:
```bash
rtk python3 scripts/lint-spec-files.py --all
rtk git diff --check
```
## Files likely touched
- `apps/backend/internal/worktree/manager_cleanup.go`
- `apps/backend/internal/worktree/manager_cleanup_capture.go` (new)
- `apps/backend/internal/worktree/manager_cleanup_capture_test.go` (new)
- `apps/backend/internal/task/service/resource_cleanup_missing_worktree_test.go` (new)
- `docs/plans/missing-worktree-cleanup-preparation/plan.md`
- This work order.
## Dependencies
None. Implement in the primary conversation after an explicit implementation request.
## Risks
- The runner combines stderr and stdout. Warning text must fail structured parsing.
- Git ref patterns also match descendants. Only an exact ref supplies identity.
- Early row deletion can lose archive recovery data and bypass worker audits.
- Test fixtures must create valid environment paths and link sessions to their environment.
- Existing large test files must not grow beyond repository limits.
## Parallelism
`sequential`
## Inputs
- [Requirements](../../specs/tasks/requirements/runtime-cleanup.md), criteria .6, .7, .9, .12, and .13.
- [Preparation design](../../specs/tasks/system-design/runtime-cleanup-preparation.md).
- [Runtime cleanup design](../../specs/tasks/system-design/runtime-cleanup.md).
- `manager_cleanup_audit.go`: `cleanupPathPresent` and `cleanupBranchIdentity`.
- `manager_cleanup_recovery_test.go`: missing paths, changed identities, and unique work.
- `resource_cleanup_jobs.go`: preparation, snapshot persistence, and activation.
- `resource_cleanup_jobs_test.go`: snapshot and cascade fixtures.
- `resource_cleanup_task_owned_test.go`: real repository and worktree-manager fixtures.
- [Git ref enumeration](https://git-scm.com/docs/git-for-each-ref).
## Results
Implemented and verified. `CaptureCleanupHeadOIDs` now classifies the recorded
path with `Lstat`, uses bounded exact-ref enumeration for an absent directory,
and omits only a confirmed-absent local branch identity. Strict parsing rejects
diagnostics, malformed records, missing objects, invalid commit IDs, and
non-commit refs. The full worktree inventory remains in the durable snapshot.
The worker marks omitted identities as unavailable, fails closed when a
replacement checkout reappears, and routes snapshot worktrees through the
identity-aware batch cleaner instead of the legacy environment destroyer.
Validation completed:
- `go test -tags fts5` manager capture regressions pass.
- `go test -tags fts5` preparation and direct/cascade lifecycle regressions pass,
including replacement-branch and replacement-checkout retry safety.
- The required worktree race matrix passes in 34 seconds.
- The required service race matrix passes in 13 seconds.
- Chromium card-menu archive/delete flow passes 5 tests.
- Mobile-Chromium archive redirect flow passes 1 test.
- `python3 scripts/lint-spec-files.py --all`, `git diff --check`, and changed-code
`golangci-lint` pass; the latter reports 0 issues.
+1
View File
@@ -152,6 +152,7 @@ signals, and task-scoped scheduling contracts.
- [Task plan append-mode write](system-design/plan-write-append-mode.md)
- [Task plan append-mode agent text](system-design/plan-write-append-mode-agent-text.md)
- [Task Runtime Cleanup](system-design/runtime-cleanup.md)
- [Task Cleanup Preparation](system-design/runtime-cleanup-preparation.md)
- [Task Terminal Persistence](system-design/task-terminal-persistence.md)
- [Runtime Task-State Publication Order](system-design/runtime-state-publication-order.md)
- [Queued Run Scheduling](system-design/run-scheduling.md)
@@ -2,7 +2,7 @@
status: draft
system: tasks
created: 2026-06-22
updated: 2026-09-05
updated: 2026-09-09
owners:
- cfl
---
@@ -46,3 +46,11 @@ and safe when runtimes or task rows are already gone.
reference exists, and all ownership, path, registration, branch, and commit
identity checks pass. The existing unique branch preservation rule shall
remain active.
- **AC-TASKS-RUNTIME-CLEANUP-001.13:** When a recorded worktree directory and
its local branch are absent, cleanup preparation shall permit task archive
or deletion. This applies to direct and cascade operations, including tasks
with other healthy repositories. Remaining resources shall retain their
ownership checks and cleanup guarantees. If the omitted identity's path or
registration reappears before execution, cleanup shall remain retryable and
shall not adopt the live checkout without an immutable identity captured
during preparation.
@@ -0,0 +1,57 @@
---
status: draft
system: tasks
requirements:
- REQ-TASKS-RUNTIME-CLEANUP-001
created: 2026-09-09
updated: 2026-09-09
owners:
- cfl
---
# Task Cleanup Preparation
## Boundary and requirement mapping
This design extends [Task Runtime Cleanup](runtime-cleanup.md) at the
preparation boundary. It implements AC-TASKS-RUNTIME-CLEANUP-001.9 and
AC-TASKS-RUNTIME-CLEANUP-001.13. The task system owns preparation because its
cleanup snapshot must survive task deletion.
## Identity capture
`worktree.Manager.CaptureCleanupHeadOIDs` distinguishes an absent path from
filesystem errors, symbolic links, and non-directory replacements. An existing
checkout supplies its commit identity through the bounded Git inspection path.
An absent checkout requires an exact local branch inspection in the parent
repository. A surviving branch supplies its commit identity for later audits.
Only a successful inspection that finds no exact branch permits omission of
that worktree's commit identity. Git exit 128, diagnostic text, cancellation,
and repository access errors do not establish absence. A quiet ref probe that
also classifies broken refs as absent cannot authorize this omission.
## Persistence
Preparation retains the worktree in the durable snapshot. It does not mark
repository rows deleted, remove registrations, or remove branches. Other
repositories still contribute their own commit identities.
The existing snapshot represents the absent identity through an omitted map
entry. This correction requires no schema migration, new snapshot field, or
change to prepared-job activation and reconciliation.
## Execution and recovery
The cleanup worker revalidates the recorded resource through its existing
path, registration, branch, commit, and shared-reference audits. An absent
path, branch, and registration complete through the existing idempotent path.
Competing or unverifiable registrations remain retryable. Worktrees present in
the durable snapshot are sent through the identity-aware batch cleaner; task
environment teardown does not send those same IDs through its legacy ID-only
destroyer. A replacement branch or checkout without the required immutable
identity cannot authorize destructive cleanup. Archive retains its existing
branch-preservation disposition.
These checks preserve the [fail-closed cleanup decision](../../../decisions/0009-fail-closed-gc-semantics.md)
and [task-owned worktree lifetime](../../../decisions/2026-08-08-task-owned-worktree-lifetime.md).
@@ -4,7 +4,7 @@ system: tasks
requirements:
- REQ-TASKS-RUNTIME-CLEANUP-001
created: 2026-06-22
updated: 2026-09-05
updated: 2026-09-09
owners:
- cfl
---
@@ -12,7 +12,7 @@ owners:
## Purpose and boundaries
This design record preserves the technical source for the capability mapped to REQ-TASKS-RUNTIME-CLEANUP-001 while the task system completes its migration.
This design defines task runtime cleanup for REQ-TASKS-RUNTIME-CLEANUP-001.
## Requirement mapping
@@ -158,6 +158,9 @@ owner rows after capturing its cleanup snapshot.
## Data Model
Preparation with absent resources follows
[Cleanup preparation](runtime-cleanup-preparation.md).
### `executors_running`
`executors_running` remains the durable runtime ownership table and the source of