diff --git a/cmd/bd/worktree_cmd.go b/cmd/bd/worktree_cmd.go index b25eb7afb..203869dc8 100644 --- a/cmd/bd/worktree_cmd.go +++ b/cmd/bd/worktree_cmd.go @@ -21,6 +21,7 @@ import ( "github.com/steveyegge/beads/internal/git" "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" + "github.com/steveyegge/beads/internal/worktreeremove" ) // WorktreeInfo contains information about a git worktree @@ -129,142 +130,6 @@ func init() { rootCmd.AddCommand(worktreeCmd) } -type singleWorktreeStringFlag struct { - name string - value string - set bool -} - -func (flag *singleWorktreeStringFlag) Set(value string) error { - if flag.set { - return fmt.Errorf("--%s may be specified only once", flag.name) - } - flag.set = true - if value == "" { - return fmt.Errorf("--%s requires a non-empty value", flag.name) - } - flag.value = value - return nil -} - -func (flag *singleWorktreeStringFlag) String() string { - return flag.value -} - -func (flag *singleWorktreeStringFlag) Type() string { - return "string" -} - -type singleWorktreeBoolFlag struct { - name string - value bool - set bool -} - -func (flag *singleWorktreeBoolFlag) Set(value string) error { - if flag.set { - return fmt.Errorf("--%s may be specified only once", flag.name) - } - flag.set = true - parsed, err := strconv.ParseBool(value) - if err != nil { - return fmt.Errorf("invalid boolean value %q", value) - } - flag.value = parsed - return nil -} - -func (flag *singleWorktreeBoolFlag) String() string { - return strconv.FormatBool(flag.value) -} - -func (flag *singleWorktreeBoolFlag) Type() string { - return "bool" -} - -func (flag *singleWorktreeBoolFlag) IsBoolFlag() bool { - return true -} - -type worktreeRemoveOptions struct { - force singleWorktreeBoolFlag - mergedInto singleWorktreeStringFlag -} - -func (options *worktreeRemoveOptions) validate() error { - if options.force.set && options.mergedInto.set { - return fmt.Errorf("--force and --merged-into cannot be used together") - } - return nil -} - -func newWorktreeRemoveCommand() *cobra.Command { - return newWorktreeRemoveCommandWithHooks(worktreeRemoveHooks{}) -} - -func newWorktreeRemoveCommandWithHook(beforeFinalCheck func() error) *cobra.Command { - return newWorktreeRemoveCommandWithHooks(worktreeRemoveHooks{ - beforeFinalCheck: beforeFinalCheck, - }) -} - -type worktreeRemoveHooks struct { - afterTargetResolution func() error - beforeFinalCheck func() error - beforeRemove func() error - afterRemoval func() error -} - -func newWorktreeRemoveCommandWithHooks(hooks worktreeRemoveHooks) *cobra.Command { - options := &worktreeRemoveOptions{ - force: singleWorktreeBoolFlag{name: "force"}, - mergedInto: singleWorktreeStringFlag{name: "merged-into"}, - } - - command := &cobra.Command{ - Use: "remove ", - Short: "Remove a worktree with safety checks", - Long: `Remove a registered git worktree with fail-closed safety checks. - -Without --force, the target must be clean and its pinned HEAD must be contained -in either the configured upstream or the single comparator selected by ---merged-into. Comparators may be full refs, unambiguous short ref names, or -full commit object IDs. Revision expressions and worktree-local pseudorefs such -as HEAD and ORIG_HEAD are rejected. - ---force skips cleanliness and containment requirements, but it does not skip -registered-identity and concurrent-change checks. --force and --merged-into -are mutually exclusive, and each flag may be specified at most once. - -Worktree removal and .gitignore cleanup are not atomic. If removal succeeds but -cleanup fails, this command returns an error that explicitly reports the -worktree as removed; it does not claim or attempt a rollback. - -Examples: - bd worktree remove feature-auth # Check the configured upstream - bd worktree remove feature-auth --merged-into main # Check containment in main - bd worktree remove feature-auth --force # Skip clean/containment checks`, - Args: func(cmd *cobra.Command, args []string) error { - if err := cobra.ExactArgs(1)(cmd, args); err != nil { - return err - } - return options.validate() - }, - SilenceUsage: true, - SilenceErrors: true, - RunE: func(cmd *cobra.Command, args []string) error { - return runWorktreeRemove(cmd, args, options, hooks) - }, - } - - command.Flags().Var(&options.force, "force", "Skip cleanliness and containment checks") - command.Flags().Lookup("force").NoOptDefVal = "true" - command.Flags().Var(&options.mergedInto, "merged-into", "Require worktree HEAD to be contained in this ref") - return command -} - -var worktreeRemoveCmd = newWorktreeRemoveCommand() - // repairWorktreeBeadsPermissions applies FixBeadsDirPermissions to worktreePath/.beads when // the directory exists. Git worktree checkout can leave tracked .beads/ at permissive modes. func repairWorktreeBeadsPermissions(worktreePath string) { @@ -460,78 +325,18 @@ func runWorktreeRemove( } }() - ctx := cmd.Context() - plan, err := prepareWorktreeRemoval( - ctx, - args[0], - options, - hooks.afterTargetResolution, - ) - if err != nil { - return fmt.Errorf("cannot prepare worktree removal: %w", err) - } - - if hooks.beforeFinalCheck != nil { - if err := hooks.beforeFinalCheck(); err != nil { - return fmt.Errorf("worktree removal interrupted before final safety check: %w", err) - } - } - - if err := plan.revalidate(ctx); err != nil { - return fmt.Errorf("worktree changed before removal: %w; nothing was removed", err) - } - - if hooks.beforeRemove != nil { - if err := hooks.beforeRemove(); err != nil { - return fmt.Errorf("worktree removal interrupted before the destructive operation: %w", err) - } - } - - // Git uses core.ignorecase while selecting a registration by path. The - // target path comes from the exact registry spelling, so force ordinal - // matching for the destructive command: a concurrent disappearance or - // config change must not redirect removal to a case-variant sibling. - removeArgs := []string{"-c", "core.ignorecase=false", "worktree", "remove"} + mode := worktreeremove.Normal if options.force.value { - removeArgs = append(removeArgs, "--force") + mode = worktreeremove.Force } - removeArgs = append(removeArgs, "--", plan.target.path) - output, err := plan.git.combinedOutput(ctx, plan.executionRoot, removeArgs...) - if err != nil { - return plan.classifyRemovalFailure(ctx, err, output) - } - - if hooks.afterRemoval != nil { - if err := hooks.afterRemoval(); err != nil { - return &worktreeRemovalPartialError{ - path: plan.target.path, - stage: "post-removal processing", - err: err, - } - } - } - - if plan.gitignoreCleanup != nil { - if err := plan.gitignoreCleanup.apply(); err != nil { - return &worktreeRemovalPartialError{ - path: plan.target.path, - stage: ".gitignore cleanup", - err: err, - } - } - } - - if jsonOutput { - result := map[string]interface{}{ - "removed": plan.target.path, - } - encoder := json.NewEncoder(os.Stdout) - encoder.SetIndent("", " ") - return encoder.Encode(result) - } - - fmt.Printf("%s Removed worktree: %s\n", ui.RenderPass("✓"), plan.target.path) - return nil + adapter := &gitWorktreeRemovalAdapter{name: args[0], options: options, hooks: hooks} + return runWorktreeRemovalOrchestration( + cmd.Context(), + worktreeRemovalRequest{mode: mode}, + adapter, + adapter, + cliWorktreeRemovalPresenter{}, + ) } type worktreeRemovalPartialError struct { @@ -1376,6 +1181,8 @@ type worktreeRemovalPlan struct { comparator *pinnedWorktreeComparator force bool gitignoreCleanup *gitignoreCleanupPlan + prepareFacts worktreeremove.PrepareFacts + prepareErr error } func prepareWorktreeRemoval( @@ -1410,11 +1217,19 @@ func prepareWorktreeRemoval( if err != nil { return nil, err } + plan := &worktreeRemovalPlan{ + force: options.force.value, + prepareFacts: worktreeremove.PrepareFacts{ + Registration: worktreeremove.Present, + }, + } if targetEntry.isMain { - return nil, fmt.Errorf("cannot remove the primary worktree") + plan.prepareFacts.Target = worktreeremove.PrimaryWorktree + return plan, nil } if sameWorktreePath(targetEntry.path, currentRoot) { - return nil, fmt.Errorf("cannot remove the worktree containing the running command") + plan.prepareFacts.Target = worktreeremove.CurrentWorktree + return plan, nil } if afterTargetResolution != nil { if err := afterTargetResolution(); err != nil { @@ -1438,15 +1253,7 @@ func prepareWorktreeRemoval( if err != nil { return nil, err } - if !sameWorktreePath(target.commonDir, mainCommonDir) { - return nil, fmt.Errorf( - "target common git directory %q does not match repository %q", - target.commonDir, - mainCommonDir, - ) - } - - plan := &worktreeRemovalPlan{ + plan = &worktreeRemovalPlan{ git: gitRunner, executionRoot: filepath.Clean(mainWorktree.path), mainWorktree: filepath.Clean(mainWorktree.path), @@ -1454,43 +1261,84 @@ func prepareWorktreeRemoval( target: target, force: options.force.value, } + status := worktreeremove.Clean + if target.status != "" { + status = worktreeremove.Dirty + } + plan.prepareFacts = worktreeremove.PrepareFacts{ + Registration: worktreeremove.Present, + Target: worktreeremove.RegisteredTarget, + RegisteredPath: target.path, + TargetDir: worktreeremove.Present, + GitAdminDir: worktreeremove.Present, + GitMarker: worktreeremove.Present, + CommonDir: worktreeremove.Matched, + Head: worktreeremove.Present, + Status: status, + ManagedIgnore: worktreeremove.IgnoreAbsent, + } + if !sameWorktreePath(target.commonDir, mainCommonDir) { + plan.prepareFacts.CommonDir = worktreeremove.Unmatched + plan.prepareErr = fmt.Errorf( + "target common git directory %q does not match repository %q", + target.commonDir, + mainCommonDir, + ) + return plan, nil + } if relative, inside := relativeWorktreePath(plan.mainWorktree, target.path); inside { plan.gitignoreCleanup, err = prepareGitignoreCleanup(plan.mainWorktree, relative) if err != nil { return nil, fmt.Errorf("cannot safely prepare .gitignore cleanup: %w", err) } + if plan.gitignoreCleanup != nil { + plan.prepareFacts.ManagedIgnore = worktreeremove.IgnoreManaged + plan.prepareFacts.ManagedIgnoreEntry = plan.gitignoreCleanup.entry + } } - if !options.force.value { - if target.status != "" { - return nil, fmt.Errorf("worktree contains modified, untracked, or ignored files") - } - - var comparator pinnedWorktreeComparator - if options.mergedInto.set { - comparator, err = resolveExplicitWorktreeComparator( - ctx, - gitRunner, - plan.executionRoot, - target, - options.mergedInto.value, - ) - } else { - comparator, err = resolveUpstreamWorktreeComparator( - ctx, - gitRunner, - plan.executionRoot, - target, - ) - } - if err != nil { - return nil, err - } - if err := verifyWorktreeContainment(ctx, gitRunner, plan.executionRoot, target.headOID, comparator); err != nil { - return nil, err - } - plan.comparator = &comparator + if options.force.value { + plan.prepareFacts.Comparator = worktreeremove.ComparatorNotRequired + plan.prepareFacts.Containment = worktreeremove.ContainmentNotRequired + return plan, nil } + if target.status != "" { + return plan, nil + } + + var comparator pinnedWorktreeComparator + if options.mergedInto.set { + comparator, err = resolveExplicitWorktreeComparator( + ctx, + gitRunner, + plan.executionRoot, + target, + options.mergedInto.value, + ) + } else { + comparator, err = resolveUpstreamWorktreeComparator( + ctx, + gitRunner, + plan.executionRoot, + target, + ) + } + if err != nil { + plan.prepareFacts.Comparator = worktreeremove.ComparatorMissing + plan.prepareErr = err + return plan, nil + } + plan.prepareFacts.Comparator = worktreeremove.ComparatorAvailable + containment, err := verifyWorktreeContainment(ctx, gitRunner, plan.executionRoot, target.headOID, comparator) + plan.prepareFacts.Containment = containment + if err != nil { + if containment == worktreeremove.ContainmentUnknown { + return nil, err + } + plan.prepareErr = err + return plan, nil + } + plan.comparator = &comparator return plan, nil } @@ -1506,86 +1354,140 @@ func relativeWorktreePath(root, target string) (string, bool) { return filepath.ToSlash(relative), true } -func (plan *worktreeRemovalPlan) revalidate(ctx context.Context) error { +type worktreeRevalidationObservation struct { + facts worktreeremove.RevalidationFacts + err error +} + +func (plan *worktreeRemovalPlan) observeRevalidation(ctx context.Context) worktreeRevalidationObservation { + facts := worktreeremove.RevalidationFacts{} worktrees, err := listRegisteredWorktrees(ctx, plan.git, plan.executionRoot) if err != nil { - return err + return worktreeRevalidationObservation{facts: facts, err: err} } currentEntry, found := findRegisteredWorktreeByPath(worktrees, plan.target.path) if !found { - return fmt.Errorf("target is no longer registered at %s", plan.target.path) + facts.Registration = worktreeremove.InvariantChanged + return worktreeRevalidationObservation{facts: facts, err: fmt.Errorf("target is no longer registered at %s", plan.target.path)} } if worktreeRegistryIdentity(currentEntry) != plan.target.registryID { - return fmt.Errorf("registered target identity changed") + facts.Registration = worktreeremove.InvariantChanged + if currentEntry.locked != plan.target.locked || currentEntry.lockReason != plan.target.lockReason || + currentEntry.prunable != plan.target.prunable || currentEntry.pruneReason != plan.target.pruneReason { + facts.LockPrune = worktreeremove.InvariantChanged + } + return worktreeRevalidationObservation{facts: facts, err: fmt.Errorf("registered target identity changed")} } + facts.Registration = worktreeremove.InvariantStable + facts.LockPrune = worktreeremove.InvariantStable + facts.TargetPath = worktreeremove.InvariantStable currentTarget, err := inspectWorktreeTarget(ctx, plan.git, currentEntry) if err != nil { - return err + return worktreeRevalidationObservation{facts: facts, err: err} } if !sameWorktreePath(currentTarget.gitDir, plan.target.gitDir) { - return fmt.Errorf("target git directory changed") + facts.GitAdminDirectory = worktreeremove.InvariantChanged + return worktreeRevalidationObservation{facts: facts, err: fmt.Errorf("target git directory changed")} } + facts.GitAdminDirectory = worktreeremove.InvariantStable if !sameWorktreePath(currentTarget.commonDir, plan.commonDir) { - return fmt.Errorf("target common git directory changed") + facts.CommonDirectory = worktreeremove.InvariantChanged + return worktreeRevalidationObservation{facts: facts, err: fmt.Errorf("target common git directory changed")} } + facts.CommonDirectory = worktreeremove.InvariantStable if currentTarget.headOID != plan.target.headOID { - return fmt.Errorf("target HEAD changed from %s to %s", plan.target.headOID, currentTarget.headOID) + facts.Head = worktreeremove.InvariantChanged + return worktreeRevalidationObservation{facts: facts, err: fmt.Errorf("target HEAD changed from %s to %s", plan.target.headOID, currentTarget.headOID)} } + facts.Head = worktreeremove.InvariantStable if currentTarget.status != plan.target.status { - return fmt.Errorf("target cleanliness changed") + if (currentTarget.status == "") != (plan.target.status == "") { + facts.Cleanliness = worktreeremove.InvariantChanged + } else { + facts.Cleanliness = worktreeremove.InvariantStable + } + facts.StatusBytes = worktreeremove.InvariantChanged + return worktreeRevalidationObservation{facts: facts, err: fmt.Errorf("target cleanliness changed")} } + facts.Cleanliness = worktreeremove.InvariantStable + facts.StatusBytes = worktreeremove.InvariantStable if currentTarget.statusFingerprint != plan.target.statusFingerprint { - return fmt.Errorf("target changed files changed") + facts.DirtyFileFingerprint = worktreeremove.InvariantChanged + return worktreeRevalidationObservation{facts: facts, err: fmt.Errorf("target changed files changed")} } + facts.DirtyFileFingerprint = worktreeremove.InvariantStable if !plan.force && currentTarget.status != "" { - return fmt.Errorf("target is no longer clean") + facts.Cleanliness = worktreeremove.InvariantChanged + return worktreeRevalidationObservation{facts: facts, err: fmt.Errorf("target is no longer clean")} } if !os.SameFile(currentTarget.pathInfo, plan.target.pathInfo) || !samePinnedFileMetadata(currentTarget.pathInfo, plan.target.pathInfo) { - return fmt.Errorf("target directory identity changed") + facts.TargetDirectory = worktreeremove.InvariantChanged + return worktreeRevalidationObservation{facts: facts, err: fmt.Errorf("target directory identity changed")} } + facts.TargetDirectory = worktreeremove.InvariantStable if !os.SameFile(currentTarget.gitDirInfo, plan.target.gitDirInfo) || !samePinnedFileMetadata(currentTarget.gitDirInfo, plan.target.gitDirInfo) { - return fmt.Errorf("target git directory identity changed") + facts.GitAdminDirectory = worktreeremove.InvariantChanged + return worktreeRevalidationObservation{facts: facts, err: fmt.Errorf("target git directory identity changed")} } + facts.GitAdminDirectory = worktreeremove.InvariantStable if !os.SameFile(currentTarget.gitMarkerInfo, plan.target.gitMarkerInfo) || !samePinnedFileMetadata(currentTarget.gitMarkerInfo, plan.target.gitMarkerInfo) { - return fmt.Errorf("target git marker identity changed") + facts.GitMarker = worktreeremove.InvariantChanged + return worktreeRevalidationObservation{facts: facts, err: fmt.Errorf("target git marker identity changed")} } + facts.GitMarker = worktreeremove.InvariantStable if currentTarget.gitDirFingerprint != plan.target.gitDirFingerprint { - return fmt.Errorf("target git directory identity changed (contents mismatch)") + facts.GitAdminDirectoryBytes = worktreeremove.InvariantChanged + return worktreeRevalidationObservation{facts: facts, err: fmt.Errorf("target git directory identity changed (contents mismatch)")} } + facts.GitAdminDirectoryBytes = worktreeremove.InvariantStable if currentTarget.gitMarkerFingerprint != plan.target.gitMarkerFingerprint { - return fmt.Errorf("registered target identity changed (git marker mismatch)") + facts.GitMarkerBytes = worktreeremove.InvariantChanged + return worktreeRevalidationObservation{facts: facts, err: fmt.Errorf("registered target identity changed (git marker mismatch)")} } + facts.GitMarkerBytes = worktreeremove.InvariantStable if plan.gitignoreCleanup != nil { if err := plan.gitignoreCleanup.validate(); err != nil { - return fmt.Errorf(".gitignore changed before removal: %w", err) + facts.ManagedIgnore = worktreeremove.InvariantChanged + return worktreeRevalidationObservation{facts: facts, err: fmt.Errorf(".gitignore changed before removal: %w", err)} } } + facts.ManagedIgnore = worktreeremove.InvariantStable if plan.comparator == nil { - return nil + facts.Comparator = worktreeremove.InvariantNotRequired + facts.Containment = worktreeremove.InvariantNotRequired + return worktreeRevalidationObservation{facts: facts} } currentComparator, err := plan.resolveComparator(ctx, currentTarget) if err != nil { - return err + return worktreeRevalidationObservation{facts: facts, err: err} } if currentComparator != *plan.comparator { - return fmt.Errorf( + facts.Comparator = worktreeremove.InvariantChanged + return worktreeRevalidationObservation{facts: facts, err: fmt.Errorf( "comparison target changed (was %s, now %s)", plan.comparator.oid, currentComparator.oid, - ) + )} } - return verifyWorktreeContainment( + facts.Comparator = worktreeremove.InvariantStable + _, err = verifyWorktreeContainment( ctx, plan.git, plan.executionRoot, currentTarget.headOID, currentComparator, ) + if err != nil { + facts.Containment = worktreeremove.InvariantChanged + return worktreeRevalidationObservation{facts: facts, err: err} + } + facts.Containment = worktreeremove.InvariantStable + return worktreeRevalidationObservation{facts: facts} } func samePinnedFileMetadata(current, pinned os.FileInfo) bool { @@ -1595,14 +1497,72 @@ func samePinnedFileMetadata(current, pinned os.FileInfo) bool { current.ModTime().Equal(pinned.ModTime()) } -func (plan *worktreeRemovalPlan) classifyRemovalFailure( - ctx context.Context, +type worktreeRemovalFailureObservation struct { + facts worktreeremove.FailureFacts + reinspectionErr error + state string +} + +func (plan *worktreeRemovalPlan) observeRemovalFailure(ctx context.Context) worktreeRemovalFailureObservation { + reinspection := plan.observeRevalidation(ctx) + + worktrees, listErr := listRegisteredWorktrees(ctx, plan.git, plan.executionRoot) + registered := false + registration := worktreeremove.PresenceUnknown + if listErr == nil { + _, registered = findRegisteredWorktreeByPath(worktrees, plan.target.path) + if registered { + registration = worktreeremove.Present + } else { + registration = worktreeremove.Missing + } + } + _, pathErr := os.Lstat(plan.target.path) + pathExists := pathErr == nil + pathPresence := worktreeremove.PresenceUnknown + if pathErr == nil { + pathPresence = worktreeremove.Present + } else if os.IsNotExist(pathErr) { + pathPresence = worktreeremove.Missing + } + if pathErr != nil && !os.IsNotExist(pathErr) { + pathExists = true + } + + state := fmt.Sprintf("registered=%t, path_exists=%t", registered, pathExists) + if listErr != nil { + state += fmt.Sprintf(", registry inspection failed: %v", listErr) + } + if pathErr != nil && !os.IsNotExist(pathErr) { + state += fmt.Sprintf(", path inspection failed: %v", pathErr) + } + return worktreeRemovalFailureObservation{ + facts: worktreeremove.FailureFacts{ + Revalidation: reinspection.facts, + RevalidationResult: revalidationResult(reinspection.err), + Registration: registration, + TargetPath: pathPresence, + }, + reinspectionErr: reinspection.err, + state: state, + } +} + +func revalidationResult(err error) worktreeremove.RevalidationResult { + if err != nil { + return worktreeremove.RevalidationFailed + } + return worktreeremove.RevalidationPassed +} + +func formatWorktreeRemovalFailure( + kind worktreeremove.FailureKind, + observation worktreeRemovalFailureObservation, removeErr error, output []byte, ) error { - reinspectionErr := plan.revalidate(ctx) diagnostic := strings.TrimSpace(string(output)) - if reinspectionErr == nil { + if kind == worktreeremove.UnchangedFailure { if diagnostic == "" { return fmt.Errorf( "git worktree remove failed, but the target was revalidated unchanged: %w", @@ -1615,38 +1575,19 @@ func (plan *worktreeRemovalPlan) classifyRemovalFailure( diagnostic, ) } - - worktrees, listErr := listRegisteredWorktrees(ctx, plan.git, plan.executionRoot) - registered := false - if listErr == nil { - _, registered = findRegisteredWorktreeByPath(worktrees, plan.target.path) - } - _, pathErr := os.Lstat(plan.target.path) - pathExists := pathErr == nil - if pathErr != nil && !os.IsNotExist(pathErr) { - pathExists = true - } - - state := fmt.Sprintf("registered=%t, path_exists=%t", registered, pathExists) - if listErr != nil { - state += fmt.Sprintf(", registry inspection failed: %v", listErr) - } - if pathErr != nil && !os.IsNotExist(pathErr) { - state += fmt.Sprintf(", path inspection failed: %v", pathErr) - } if diagnostic == "" { return fmt.Errorf( "git worktree remove failed and target state is partial or indeterminate (%s): %w; reinspection: %v", - state, + observation.state, removeErr, - reinspectionErr, + observation.reinspectionErr, ) } return fmt.Errorf( "git worktree remove failed and target state is partial or indeterminate (%s): %w; reinspection: %v\n%s", - state, + observation.state, removeErr, - reinspectionErr, + observation.reinspectionErr, diagnostic, ) } @@ -2039,7 +1980,7 @@ func verifyWorktreeContainment( executionRoot string, headOID string, comparator pinnedWorktreeComparator, -) error { +) (worktreeremove.Containment, error) { output, err := git.output( ctx, executionRoot, @@ -2049,21 +1990,21 @@ func verifyWorktreeContainment( comparator.oid, ) if err == nil { - return nil + return worktreeremove.Contained, nil } var exitError *exec.ExitError if errors.As(err, &exitError) && exitError.ExitCode() == 1 { if comparator.explicit { - return fmt.Errorf( + return worktreeremove.NotContained, fmt.Errorf( "worktree HEAD %s is not contained in --merged-into value %q at %s", headOID, comparator.selector, comparator.oid, ) } - return fmt.Errorf("worktree has commits not contained in its configured upstream") + return worktreeremove.NotContained, fmt.Errorf("worktree has commits not contained in its configured upstream") } - return fmt.Errorf( + return worktreeremove.ContainmentUnknown, fmt.Errorf( "failed to verify worktree containment (%s in %s): %w\n%s", headOID, comparator.oid, @@ -2159,6 +2100,7 @@ func isIgnoredByGit(ctx context.Context, repoRoot, entry string) (bool, error) { type gitignoreCleanupPlan struct { repoRoot string path string + entry string info os.FileInfo original []byte updated []byte @@ -2193,6 +2135,7 @@ func prepareGitignoreCleanup(repoRoot, entry string) (*gitignoreCleanupPlan, err return &gitignoreCleanupPlan{ repoRoot: repoRoot, path: gitignorePath, + entry: entry, info: info, original: content, updated: updated, diff --git a/cmd/bd/worktree_remove_cmd.go b/cmd/bd/worktree_remove_cmd.go new file mode 100644 index 000000000..6901bf9ea --- /dev/null +++ b/cmd/bd/worktree_remove_cmd.go @@ -0,0 +1,257 @@ +package main + +import ( + "context" + "errors" + "fmt" + "strconv" + + "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/worktreeremove" +) + +type singleWorktreeStringFlag struct { + name string + value string + set bool +} + +func (flag *singleWorktreeStringFlag) Set(value string) error { + if flag.set { + return fmt.Errorf("--%s may be specified only once", flag.name) + } + flag.set = true + if value == "" { + return fmt.Errorf("--%s requires a non-empty value", flag.name) + } + flag.value = value + return nil +} + +func (flag *singleWorktreeStringFlag) String() string { return flag.value } + +func (flag *singleWorktreeStringFlag) Type() string { return "string" } + +type singleWorktreeBoolFlag struct { + name string + value bool + set bool +} + +func (flag *singleWorktreeBoolFlag) Set(value string) error { + if flag.set { + return fmt.Errorf("--%s may be specified only once", flag.name) + } + flag.set = true + parsed, err := strconv.ParseBool(value) + if err != nil { + return fmt.Errorf("invalid boolean value %q", value) + } + flag.value = parsed + return nil +} + +func (flag *singleWorktreeBoolFlag) String() string { return strconv.FormatBool(flag.value) } + +func (flag *singleWorktreeBoolFlag) Type() string { return "bool" } + +func (flag *singleWorktreeBoolFlag) IsBoolFlag() bool { return true } + +type worktreeRemoveOptions struct { + force singleWorktreeBoolFlag + mergedInto singleWorktreeStringFlag +} + +func (options *worktreeRemoveOptions) validate() error { + if options.force.set && options.mergedInto.set { + return fmt.Errorf("--force and --merged-into cannot be used together") + } + return nil +} + +func newWorktreeRemoveCommand() *cobra.Command { + return newWorktreeRemoveCommandWithHooks(worktreeRemoveHooks{}) +} + +func newWorktreeRemoveCommandWithHook(beforeFinalCheck func() error) *cobra.Command { + return newWorktreeRemoveCommandWithHooks(worktreeRemoveHooks{beforeFinalCheck: beforeFinalCheck}) +} + +type worktreeRemoveHooks struct { + afterTargetResolution func() error + beforeFinalCheck func() error + beforeRemove func() error + afterRemoval func() error +} + +func newWorktreeRemoveCommandWithHooks(hooks worktreeRemoveHooks) *cobra.Command { + options := &worktreeRemoveOptions{ + force: singleWorktreeBoolFlag{name: "force"}, + mergedInto: singleWorktreeStringFlag{name: "merged-into"}, + } + command := &cobra.Command{ + Use: "remove ", + Short: "Remove a worktree with safety checks", + Long: `Remove a registered git worktree with fail-closed safety checks. + +Without --force, the target must be clean and its pinned HEAD must be contained +in either the configured upstream or the single comparator selected by +--merged-into. Comparators may be full refs, unambiguous short ref names, or +full commit object IDs. Revision expressions and worktree-local pseudorefs such +as HEAD and ORIG_HEAD are rejected. + +--force skips cleanliness and containment requirements, but it does not skip +registered-identity and concurrent-change checks. --force and --merged-into +are mutually exclusive, and each flag may be specified at most once. + +Worktree removal and .gitignore cleanup are not atomic. If removal succeeds but +cleanup fails, this command returns an error that explicitly reports the +worktree as removed; it does not claim or attempt a rollback. + +Examples: + bd worktree remove feature-auth # Check the configured upstream + bd worktree remove feature-auth --merged-into main # Check containment in main + bd worktree remove feature-auth --force # Skip clean/containment checks`, + Args: func(cmd *cobra.Command, args []string) error { + if err := cobra.ExactArgs(1)(cmd, args); err != nil { + return err + } + return options.validate() + }, + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + return runWorktreeRemove(cmd, args, options, hooks) + }, + } + command.Flags().Var(&options.force, "force", "Skip cleanliness and containment checks") + command.Flags().Lookup("force").NoOptDefVal = "true" + command.Flags().Var(&options.mergedInto, "merged-into", "Require worktree HEAD to be contained in this ref") + return command +} + +var worktreeRemoveCmd = newWorktreeRemoveCommand() + +// worktreeRemovalRequest contains the command-selected policy mode. The Git +// adapter resolves the registered target independently from this request. +type worktreeRemovalRequest struct{ mode worktreeremove.Mode } + +// worktreeRemovalApproval contains adapter observations for the policy. The +// policy, not the observer, constructs the destructive mutation and cleanup. +type worktreeRemovalApproval struct { + facts worktreeremove.PrepareFacts + prepareErr error +} + +type worktreeRemovalRevalidation struct { + facts worktreeremove.RevalidationFacts + err error +} + +// worktreeRemovalObserver collects typed policy facts without performing the +// destructive Git operation. +type worktreeRemovalObserver interface { + Prepare(context.Context, worktreeRemovalRequest) (worktreeRemovalApproval, error) + Revalidate(context.Context, worktreeRemovalApproval) (worktreeRemovalRevalidation, error) + Failure(context.Context, worktreeRemovalApproval, error) (worktreeRemovalFailure, error) +} + +// worktreeRemovalFailure retains command-edge diagnostics while keeping its +// state classification in the typed policy facts. +type worktreeRemovalFailure struct { + facts worktreeremove.FailureFacts + render func(worktreeremove.FailureKind, error) error +} + +// worktreeRemovalPreMutationError marks an interruption before Git receives +// the destructive command, so it must not enter post-failure reinspection. +type worktreeRemovalPreMutationError struct{ err error } + +func (err *worktreeRemovalPreMutationError) Error() string { return err.err.Error() } + +func (err *worktreeRemovalPreMutationError) Unwrap() error { return err.err } + +// worktreeRemovalMutator performs only operations approved by the policy. +type worktreeRemovalMutator interface { + Remove(context.Context, worktreeremove.Mutation) error + Cleanup(context.Context, worktreeremove.Cleanup) error +} + +// worktreeRemovalPresenter renders command outcomes after mutation state is +// known. It intentionally does not observe the filesystem or Git. +type worktreeRemovalPresenter interface { + Removed(worktreeremove.Mutation) error + Failure(worktreeremove.FailureKind, error) +} + +// runWorktreeRemovalOrchestration sequences the three policy phases around +// the destructive mutation. Adapter-private filesystem evidence never crosses +// this boundary; only typed facts and the approved mutation do. +func runWorktreeRemovalOrchestration( + ctx context.Context, + request worktreeRemovalRequest, + observer worktreeRemovalObserver, + mutator worktreeRemovalMutator, + presenter worktreeRemovalPresenter, +) error { + approval, err := observer.Prepare(ctx, request) + if err != nil { + return fmt.Errorf("cannot prepare worktree removal: %w", err) + } + plan, err := worktreeremove.Prepare(worktreeremove.Request{Mode: request.mode}, approval.facts) + if err != nil { + if approval.prepareErr != nil { + return fmt.Errorf("cannot prepare worktree removal: %w", approval.prepareErr) + } + return fmt.Errorf("cannot prepare worktree removal: %w", err) + } + if approval.prepareErr != nil { + return fmt.Errorf("cannot prepare worktree removal: %w", approval.prepareErr) + } + mutation := plan.Mutation() + cleanup, requiresCleanup := plan.Cleanup() + + revalidation, err := observer.Revalidate(ctx, approval) + if err != nil { + return err + } + if err := worktreeremove.Revalidate(plan, revalidation.facts); err != nil { + if revalidation.err != nil { + return fmt.Errorf("worktree changed before removal: %w; nothing was removed", revalidation.err) + } + return err + } + if revalidation.err != nil { + return fmt.Errorf("worktree changed before removal: %w; nothing was removed", revalidation.err) + } + + if err := mutator.Remove(ctx, mutation); err != nil { + var partial *worktreeRemovalPartialError + if errors.As(err, &partial) { + return err + } + var interrupted *worktreeRemovalPreMutationError + if errors.As(err, &interrupted) { + return err + } + failureObservation, failureErr := observer.Failure(ctx, approval, err) + if failureErr != nil { + return failureErr + } + failure, classifyErr := worktreeremove.ClassifyFailure(plan, failureObservation.facts, err) + if classifyErr != nil { + return fmt.Errorf("cannot classify worktree removal failure: %w", classifyErr) + } + presenter.Failure(failure.Kind, failure.RemoveErr) + if failureObservation.render != nil { + return failureObservation.render(failure.Kind, failure.RemoveErr) + } + return fmt.Errorf("git worktree remove failed: %w", failure.RemoveErr) + } + if requiresCleanup { + if err := mutator.Cleanup(ctx, cleanup); err != nil { + return err + } + } + return presenter.Removed(mutation) +} diff --git a/cmd/bd/worktree_remove_cmd_test.go b/cmd/bd/worktree_remove_cmd_test.go new file mode 100644 index 000000000..449b4bdf6 --- /dev/null +++ b/cmd/bd/worktree_remove_cmd_test.go @@ -0,0 +1,343 @@ +package main + +import ( + "context" + "errors" + "os" + "path/filepath" + "reflect" + "runtime" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/worktreeremove" +) + +func TestWorktreeRemovalCommandRecordsApprovedOperations(t *testing.T) { + observer := &recordingWorktreeRemovalObserver{ + prepare: worktreeremove.PrepareFacts{ + Registration: worktreeremove.Present, + Target: worktreeremove.RegisteredTarget, + RegisteredPath: "/exact/registry/path", + TargetDir: worktreeremove.Present, + GitAdminDir: worktreeremove.Present, + GitMarker: worktreeremove.Present, + CommonDir: worktreeremove.Matched, + Head: worktreeremove.Present, + Status: worktreeremove.Clean, + Comparator: worktreeremove.ComparatorNotRequired, + Containment: worktreeremove.ContainmentNotRequired, + ManagedIgnore: worktreeremove.IgnoreManaged, + ManagedIgnoreEntry: "nested/lane", + }, + revalidation: []worktreeremove.RevalidationFacts{worktreeRemovalRevalidationFacts(worktreeremove.Force)}, + } + mutator := &recordingWorktreeRemovalMutator{} + presenter := &recordingWorktreeRemovalPresenter{} + + err := runWorktreeRemovalOrchestration( + context.Background(), + worktreeRemovalRequest{mode: worktreeremove.Force}, + observer, + mutator, + presenter, + ) + if err != nil { + t.Fatalf("runWorktreeRemovalOrchestration() error = %v", err) + } + + if want := []string{"prepare", "revalidate"}; !reflect.DeepEqual(observer.operations, want) { + t.Fatalf("observer operations = %#v, want %#v", observer.operations, want) + } + if want := []worktreeremove.Mutation{{TargetPath: "/exact/registry/path", Force: true}}; !reflect.DeepEqual(mutator.removals, want) { + t.Fatalf("removals = %#v, want %#v", mutator.removals, want) + } + if want := []worktreeremove.Cleanup{{Entry: "nested/lane"}}; !reflect.DeepEqual(mutator.cleanups, want) { + t.Fatalf("cleanups = %#v, want %#v", mutator.cleanups, want) + } + if want := []string{"removed"}; !reflect.DeepEqual(presenter.events, want) { + t.Fatalf("presentation = %#v, want %#v", presenter.events, want) + } +} + +func TestWorktreeRemovalCommandRefusesBeforeMutation(t *testing.T) { + observer := &recordingWorktreeRemovalObserver{ + prepare: worktreeremove.PrepareFacts{ + Registration: worktreeremove.Present, + Target: worktreeremove.PrimaryWorktree, + RegisteredPath: "/exact/registry/path", + TargetDir: worktreeremove.Present, + GitAdminDir: worktreeremove.Present, + GitMarker: worktreeremove.Present, + CommonDir: worktreeremove.Matched, + Head: worktreeremove.Present, + Status: worktreeremove.Clean, + Comparator: worktreeremove.ComparatorAvailable, + Containment: worktreeremove.Contained, + ManagedIgnore: worktreeremove.IgnoreAbsent, + }, + } + mutator := &recordingWorktreeRemovalMutator{} + presenter := &recordingWorktreeRemovalPresenter{} + + err := runWorktreeRemovalOrchestration( + context.Background(), + worktreeRemovalRequest{mode: worktreeremove.Normal}, + observer, + mutator, + presenter, + ) + if err == nil || err.Error() != "cannot prepare worktree removal: cannot remove the primary worktree" { + t.Fatalf("runWorktreeRemovalOrchestration() error = %v", err) + } + if want := []string{"prepare"}; !reflect.DeepEqual(observer.operations, want) { + t.Fatalf("observer operations = %#v, want %#v", observer.operations, want) + } + if len(mutator.removals) != 0 || len(mutator.cleanups) != 0 { + t.Fatalf("mutations = %#v / %#v, want none", mutator.removals, mutator.cleanups) + } + if len(presenter.events) != 0 { + t.Fatalf("presentation = %#v, want none", presenter.events) + } +} + +func TestWorktreeRemovalOrchestrationPresentsPartialRemoveFailure(t *testing.T) { + removeErr := errors.New("remove failed") + observer := &recordingWorktreeRemovalObserver{ + prepare: worktreeremove.PrepareFacts{ + Registration: worktreeremove.Present, + Target: worktreeremove.RegisteredTarget, + RegisteredPath: "/exact/registry/path", + TargetDir: worktreeremove.Present, + GitAdminDir: worktreeremove.Present, + GitMarker: worktreeremove.Present, + CommonDir: worktreeremove.Matched, + Head: worktreeremove.Present, + Status: worktreeremove.Clean, + Comparator: worktreeremove.ComparatorAvailable, + Containment: worktreeremove.Contained, + ManagedIgnore: worktreeremove.IgnoreAbsent, + }, + revalidation: []worktreeremove.RevalidationFacts{worktreeRemovalRevalidationFacts(worktreeremove.Normal)}, + failure: []worktreeremove.FailureFacts{{ + Revalidation: worktreeRemovalRevalidationFacts(worktreeremove.Normal), + Registration: worktreeremove.Missing, + TargetPath: worktreeremove.Missing, + }}, + } + mutator := &recordingWorktreeRemovalMutator{removeErr: removeErr} + presenter := &recordingWorktreeRemovalPresenter{} + + err := runWorktreeRemovalOrchestration( + context.Background(), + worktreeRemovalRequest{mode: worktreeremove.Normal}, + observer, + mutator, + presenter, + ) + if !errors.Is(err, removeErr) { + t.Fatalf("runWorktreeRemovalOrchestration() error = %v, want wrapped %v", err, removeErr) + } + if want := []string{"prepare", "revalidate", "failure"}; !reflect.DeepEqual(observer.operations, want) { + t.Fatalf("observer operations = %#v, want %#v", observer.operations, want) + } + if want := []worktreeremove.Mutation{{TargetPath: "/exact/registry/path", Force: false}}; !reflect.DeepEqual(mutator.removals, want) { + t.Fatalf("removals = %#v, want %#v", mutator.removals, want) + } + if want := []string{"partial failure"}; !reflect.DeepEqual(presenter.events, want) { + t.Fatalf("presentation = %#v, want %#v", presenter.events, want) + } +} + +func TestWorktreeRemovalCommandUsesPolicyPinnedMutation(t *testing.T) { + observer := &recordingWorktreeRemovalObserver{ + prepare: worktreeRemovalFacts(worktreeremove.IgnoreAbsent), + revalidation: []worktreeremove.RevalidationFacts{worktreeRemovalRevalidationFacts(worktreeremove.Normal)}, + } + mutator := &recordingWorktreeRemovalMutator{} + + err := runWorktreeRemovalOrchestration( + context.Background(), + worktreeRemovalRequest{mode: worktreeremove.Normal}, + observer, + mutator, + &recordingWorktreeRemovalPresenter{}, + ) + if err != nil { + t.Fatalf("runWorktreeRemovalOrchestration() error = %v", err) + } + if want := []worktreeremove.Mutation{{TargetPath: "/exact/registry/path", Force: false}}; !reflect.DeepEqual(mutator.removals, want) { + t.Fatalf("removals = %#v, want %#v", mutator.removals, want) + } +} + +func TestWorktreeRemovalCommandRefusesStaleApprovalAndPrepareDiagnostic(t *testing.T) { + for _, tt := range []struct { + name string + prepareErr error + revalidateErr error + change func(*worktreeremove.RevalidationFacts) + want string + }{ + { + name: "stale target", + change: func(f *worktreeremove.RevalidationFacts) { f.TargetPath = worktreeremove.InvariantChanged }, + want: "worktree changed before removal", + }, + { + name: "prepare diagnostic", + prepareErr: errors.New("adapter preparation diagnostic"), + want: "adapter preparation diagnostic", + }, + { + name: "stable facts with diagnostic", + revalidateErr: errors.New("adapter revalidation diagnostic"), + want: "adapter revalidation diagnostic", + }, + } { + t.Run(tt.name, func(t *testing.T) { + facts := worktreeRemovalRevalidationFacts(worktreeremove.Normal) + if tt.change != nil { + tt.change(&facts) + } + observer := &recordingWorktreeRemovalObserver{ + prepare: worktreeRemovalFacts(worktreeremove.IgnoreAbsent), + prepareErr: tt.prepareErr, + revalidateErr: tt.revalidateErr, + revalidation: []worktreeremove.RevalidationFacts{facts}, + } + mutator := &recordingWorktreeRemovalMutator{} + err := runWorktreeRemovalOrchestration(context.Background(), worktreeRemovalRequest{mode: worktreeremove.Normal}, observer, mutator, &recordingWorktreeRemovalPresenter{}) + if err == nil || !strings.Contains(err.Error(), tt.want) { + t.Fatalf("runWorktreeRemovalOrchestration() error = %v, want %q", err, tt.want) + } + if len(mutator.removals) != 0 { + t.Fatalf("removals = %#v, want none", mutator.removals) + } + }) + } +} + +func TestWorktreeRemovalGitAdapterUsesExactApprovedArgs(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the recording git executable is a POSIX shell script") + } + dir := t.TempDir() + argsPath := filepath.Join(dir, "args") + gitPath := filepath.Join(dir, "git") + if err := os.WriteFile(gitPath, []byte("#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$WORKTREE_REMOVE_ARGS_FILE\"\n"), 0755); err != nil { + t.Fatalf("write recording git: %v", err) + } + adapter := &gitWorktreeRemovalAdapter{plan: &worktreeRemovalPlan{ + git: &worktreeRemovalGit{executable: gitPath, env: []string{"WORKTREE_REMOVE_ARGS_FILE=" + argsPath}}, + executionRoot: dir, + target: pinnedWorktreeTarget{path: "/exact/registered path"}, + force: true, + }} + mutation := worktreeremove.Mutation{TargetPath: "/exact/registered path", Force: true} + if err := adapter.Remove(context.Background(), mutation); err != nil { + t.Fatalf("Remove() error = %v", err) + } + got, err := os.ReadFile(argsPath) + if err != nil { + t.Fatalf("read recorded git arguments: %v", err) + } + if want := "-c\ncore.hooksPath=\n-c\ncore.fsmonitor=false\n-c\ncore.ignorecase=false\nworktree\nremove\n--force\n--\n/exact/registered path\n"; string(got) != want { + t.Fatalf("git arguments = %q, want %q", got, want) + } + + if err := adapter.Remove(context.Background(), worktreeremove.Mutation{TargetPath: "/forged/path", Force: true}); err == nil { + t.Fatal("Remove() accepted a forged target path") + } + adapter.plan.gitignoreCleanup = &gitignoreCleanupPlan{entry: "nested/lane"} + if err := adapter.Cleanup(context.Background(), worktreeremove.Cleanup{Entry: "other/lane"}); err == nil { + t.Fatal("Cleanup() accepted a forged managed-ignore entry") + } +} + +type recordingWorktreeRemovalObserver struct { + prepare worktreeremove.PrepareFacts + prepareErr error + revalidateErr error + revalidation []worktreeremove.RevalidationFacts + failure []worktreeremove.FailureFacts + operations []string +} + +func (r *recordingWorktreeRemovalObserver) Prepare(_ context.Context, request worktreeRemovalRequest) (worktreeRemovalApproval, error) { + r.operations = append(r.operations, "prepare") + return worktreeRemovalApproval{ + facts: r.prepare, + prepareErr: r.prepareErr, + }, nil +} + +func worktreeRemovalFacts(ignore worktreeremove.IgnoreKind) worktreeremove.PrepareFacts { + return worktreeremove.PrepareFacts{ + Registration: worktreeremove.Present, Target: worktreeremove.RegisteredTarget, RegisteredPath: "/exact/registry/path", + TargetDir: worktreeremove.Present, GitAdminDir: worktreeremove.Present, + GitMarker: worktreeremove.Present, CommonDir: worktreeremove.Matched, + Head: worktreeremove.Present, Status: worktreeremove.Clean, + Comparator: worktreeremove.ComparatorAvailable, Containment: worktreeremove.Contained, + ManagedIgnore: ignore, + } +} + +func worktreeRemovalRevalidationFacts(mode worktreeremove.Mode) worktreeremove.RevalidationFacts { + facts := worktreeremove.RevalidationFacts{Registration: worktreeremove.InvariantStable, LockPrune: worktreeremove.InvariantStable, TargetPath: worktreeremove.InvariantStable, TargetDirectory: worktreeremove.InvariantStable, GitAdminDirectory: worktreeremove.InvariantStable, GitAdminDirectoryBytes: worktreeremove.InvariantStable, GitMarker: worktreeremove.InvariantStable, GitMarkerBytes: worktreeremove.InvariantStable, CommonDirectory: worktreeremove.InvariantStable, Head: worktreeremove.InvariantStable, Cleanliness: worktreeremove.InvariantStable, StatusBytes: worktreeremove.InvariantStable, DirtyFileFingerprint: worktreeremove.InvariantStable, Comparator: worktreeremove.InvariantStable, Containment: worktreeremove.InvariantStable, ManagedIgnore: worktreeremove.InvariantStable} + if mode == worktreeremove.Force { + facts.Comparator, facts.Containment = worktreeremove.InvariantNotRequired, worktreeremove.InvariantNotRequired + } + return facts +} + +func (r *recordingWorktreeRemovalObserver) Revalidate(context.Context, worktreeRemovalApproval) (worktreeRemovalRevalidation, error) { + r.operations = append(r.operations, "revalidate") + if len(r.revalidation) == 0 { + return worktreeRemovalRevalidation{}, errors.New("missing revalidation fact") + } + fact := r.revalidation[0] + r.revalidation = r.revalidation[1:] + return worktreeRemovalRevalidation{facts: fact, err: r.revalidateErr}, nil +} + +func (r *recordingWorktreeRemovalObserver) Failure(context.Context, worktreeRemovalApproval, error) (worktreeRemovalFailure, error) { + r.operations = append(r.operations, "failure") + if len(r.failure) == 0 { + return worktreeRemovalFailure{}, errors.New("missing failure fact") + } + fact := r.failure[0] + r.failure = r.failure[1:] + return worktreeRemovalFailure{facts: fact}, nil +} + +type recordingWorktreeRemovalMutator struct { + removeErr error + removals []worktreeremove.Mutation + cleanups []worktreeremove.Cleanup +} + +func (r *recordingWorktreeRemovalMutator) Remove(_ context.Context, mutation worktreeremove.Mutation) error { + r.removals = append(r.removals, mutation) + return r.removeErr +} + +func (r *recordingWorktreeRemovalMutator) Cleanup(_ context.Context, cleanup worktreeremove.Cleanup) error { + r.cleanups = append(r.cleanups, cleanup) + return nil +} + +type recordingWorktreeRemovalPresenter struct{ events []string } + +func (r *recordingWorktreeRemovalPresenter) Removed(worktreeremove.Mutation) error { + r.events = append(r.events, "removed") + return nil +} + +func (r *recordingWorktreeRemovalPresenter) Failure(kind worktreeremove.FailureKind, _ error) { + if kind == worktreeremove.PartialFailure { + r.events = append(r.events, "partial failure") + return + } + r.events = append(r.events, "unchanged failure") +} diff --git a/cmd/bd/worktree_remove_git.go b/cmd/bd/worktree_remove_git.go new file mode 100644 index 000000000..226cacf8a --- /dev/null +++ b/cmd/bd/worktree_remove_git.go @@ -0,0 +1,131 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "os" + + "github.com/steveyegge/beads/internal/ui" + "github.com/steveyegge/beads/internal/worktreeremove" +) + +// gitWorktreeRemovalAdapter confines worktree-removal Git and filesystem +// observations to the command edge. The policy package receives only tags; +// FileInfo values, paths, bytes, and fingerprints remain in its plan. +type gitWorktreeRemovalAdapter struct { + name string + options *worktreeRemoveOptions + hooks worktreeRemoveHooks + plan *worktreeRemovalPlan + output []byte +} + +func (adapter *gitWorktreeRemovalAdapter) Prepare( + ctx context.Context, + _ worktreeRemovalRequest, +) (worktreeRemovalApproval, error) { + plan, err := prepareWorktreeRemoval(ctx, adapter.name, adapter.options, adapter.hooks.afterTargetResolution) + if err != nil { + return worktreeRemovalApproval{}, err + } + adapter.plan = plan + + return worktreeRemovalApproval{ + facts: plan.prepareFacts, + prepareErr: plan.prepareErr, + }, nil +} + +func (adapter *gitWorktreeRemovalAdapter) Revalidate( + ctx context.Context, + _ worktreeRemovalApproval, +) (worktreeRemovalRevalidation, error) { + if adapter.hooks.beforeFinalCheck != nil { + if err := adapter.hooks.beforeFinalCheck(); err != nil { + return worktreeRemovalRevalidation{}, fmt.Errorf("worktree removal interrupted before final safety check: %w", err) + } + } + observation := adapter.plan.observeRevalidation(ctx) + return worktreeRemovalRevalidation{facts: observation.facts, err: observation.err}, nil +} + +func (adapter *gitWorktreeRemovalAdapter) Remove(ctx context.Context, mutation worktreeremove.Mutation) error { + if adapter.plan == nil || mutation.TargetPath != adapter.plan.target.path || mutation.Force != adapter.plan.force { + return fmt.Errorf("cannot remove worktree with an unapproved mutation") + } + if adapter.hooks.beforeRemove != nil { + if err := adapter.hooks.beforeRemove(); err != nil { + return &worktreeRemovalPreMutationError{ + err: fmt.Errorf("worktree removal interrupted before the destructive operation: %w", err), + } + } + } + + args := []string{"-c", "core.ignorecase=false", "worktree", "remove"} + if mutation.Force { + args = append(args, "--force") + } + args = append(args, "--", mutation.TargetPath) + output, err := adapter.plan.git.combinedOutput(ctx, adapter.plan.executionRoot, args...) + adapter.output = output + if err != nil { + return err + } + if adapter.hooks.afterRemoval != nil { + if err := adapter.hooks.afterRemoval(); err != nil { + return &worktreeRemovalPartialError{ + path: mutation.TargetPath, + stage: "post-removal processing", + err: err, + } + } + } + return nil +} + +func (adapter *gitWorktreeRemovalAdapter) Failure( + ctx context.Context, + _ worktreeRemovalApproval, + removeErr error, +) (worktreeRemovalFailure, error) { + observation := adapter.plan.observeRemovalFailure(ctx) + return worktreeRemovalFailure{ + facts: observation.facts, + render: func(kind worktreeremove.FailureKind, removeErr error) error { + return formatWorktreeRemovalFailure(kind, observation, removeErr, adapter.output) + }, + }, nil +} + +func (adapter *gitWorktreeRemovalAdapter) Cleanup(_ context.Context, cleanup worktreeremove.Cleanup) error { + if adapter.plan == nil || adapter.plan.gitignoreCleanup == nil || cleanup.Entry != adapter.plan.gitignoreCleanup.entry { + return fmt.Errorf("cannot clean managed ignore entry without its approved identity") + } + if cleanup.Entry == "" { + return nil + } + if err := adapter.plan.gitignoreCleanup.apply(); err != nil { + return &worktreeRemovalPartialError{ + path: adapter.plan.target.path, + stage: ".gitignore cleanup", + err: err, + } + } + return nil +} + +type cliWorktreeRemovalPresenter struct{} + +func (cliWorktreeRemovalPresenter) Removed(mutation worktreeremove.Mutation) error { + if jsonOutput { + result := map[string]interface{}{"removed": mutation.TargetPath} + encoder := json.NewEncoder(os.Stdout) + encoder.SetIndent("", " ") + return encoder.Encode(result) + } + fmt.Printf("%s Removed worktree: %s\n", ui.RenderPass("✓"), mutation.TargetPath) + return nil +} + +func (cliWorktreeRemovalPresenter) Failure(worktreeremove.FailureKind, error) {} diff --git a/internal/worktreeremove/policy.go b/internal/worktreeremove/policy.go new file mode 100644 index 000000000..ebbbea2f0 --- /dev/null +++ b/internal/worktreeremove/policy.go @@ -0,0 +1,341 @@ +// Package worktreeremove contains the side-effect-free safety policy for +// worktree removal. Git and filesystem observations are deliberately kept at +// the command adapter boundary. +package worktreeremove + +import "fmt" + +// Mode controls which safety checks are required. +type Mode uint8 + +const ( + // ModeUnknown is an unvalidated caller request. + ModeUnknown Mode = iota + // Normal requires cleanliness and containment. + Normal + // Force bypasses cleanliness and containment, but never identity checks. + Force +) + +// TargetKind identifies the target relative to the command and registry. +type TargetKind uint8 + +const ( + // TargetUnknown is an incomplete target observation. + TargetUnknown TargetKind = iota + // RegisteredTarget is a removable, non-primary registered target. + RegisteredTarget + // PrimaryWorktree is the primary registry entry. + PrimaryWorktree + // CurrentWorktree contains the running command. + CurrentWorktree +) + +// Match records an explicit identity comparison result. +type Match uint8 + +const ( + // MatchUnknown is an incomplete identity comparison. + MatchUnknown Match = iota + // Matched means both identities resolved to the same object. + Matched + // Unmatched means both identities were present but distinct. + Unmatched +) + +// Presence records whether a required observed object was present. +type Presence uint8 + +const ( + // PresenceUnknown is an incomplete presence observation. + PresenceUnknown Presence = iota + // Present means the object was observed by the adapter. + Present + // Missing means the object was not present at the observation point. + Missing +) + +// Status records the inspected cleanliness result. +type Status uint8 + +const ( + // StatusUnknown is an incomplete cleanliness observation. + StatusUnknown Status = iota + // Clean has no modified, untracked, or ignored entries. + Clean + // Dirty has at least one modified, untracked, or ignored entry. + Dirty +) + +// ComparatorKind records comparator resolution without using absent strings. +type ComparatorKind uint8 + +const ( + // ComparatorUnknown is an incomplete comparator observation. + ComparatorUnknown ComparatorKind = iota + // ComparatorAvailable is a resolved independent comparison target. + ComparatorAvailable + // ComparatorMissing has no usable configured or explicit comparator. + ComparatorMissing + // ComparatorNotRequired was deliberately not resolved because force mode + // bypasses containment. + ComparatorNotRequired +) + +// Containment records the merge-base safety result. +type Containment uint8 + +const ( + // ContainmentUnknown is an incomplete containment observation. + ContainmentUnknown Containment = iota + // Contained means target HEAD is an ancestor of the comparator. + Contained + // NotContained means the comparator does not contain target HEAD. + NotContained + // ContainmentNotRequired was deliberately not checked because force mode + // bypasses containment. + ContainmentNotRequired +) + +// IgnoreKind records managed .gitignore ownership. +type IgnoreKind uint8 + +const ( + // IgnoreUnknown is an incomplete managed-ignore observation. + IgnoreUnknown IgnoreKind = iota + // IgnoreAbsent means no managed cleanup is required. + IgnoreAbsent + // IgnoreManaged means a prepared managed entry must be cleaned up. + IgnoreManaged +) + +// PrepareFacts are typed results gathered before the first safety decision. +// RegisteredPath and ManagedIgnoreEntry are exact adapter-observed identities; +// filesystem handles, bytes, and fingerprints stay at the adapter edge. +type PrepareFacts struct { + Registration Presence + Target TargetKind + RegisteredPath string + TargetDir Presence + GitAdminDir Presence + GitMarker Presence + CommonDir Match + Head Presence + Status Status + Comparator ComparatorKind + Containment Containment + ManagedIgnore IgnoreKind + ManagedIgnoreEntry string +} + +// Request is the caller-selected policy input. +type Request struct{ Mode Mode } + +// Mutation is the only destructive operation a prepared plan authorizes. +type Mutation struct { + TargetPath string + Force bool +} + +// Cleanup is the only managed-ignore cleanup a prepared plan authorizes. +type Cleanup struct{ Entry string } + +// Plan is an opaque approval from Prepare and must be revalidated immediately +// before the destructive mutation. +type Plan struct { + approved bool + mode Mode + targetPath string + managedIgnoreEntry string +} + +// Mutation returns the exact destructive operation approved by Prepare. +func (plan Plan) Mutation() Mutation { + return Mutation{TargetPath: plan.targetPath, Force: plan.mode == Force} +} + +// Cleanup returns the exact managed-ignore cleanup approved by Prepare. +func (plan Plan) Cleanup() (Cleanup, bool) { + if plan.managedIgnoreEntry == "" { + return Cleanup{}, false + } + return Cleanup{Entry: plan.managedIgnoreEntry}, true +} + +func (plan Plan) valid() bool { + return plan.approved && (plan.mode == Normal || plan.mode == Force) && plan.targetPath != "" +} + +// Prepare validates the initial observations and returns an approved plan. +func Prepare(request Request, facts PrepareFacts) (Plan, error) { + if request.Mode != Normal && request.Mode != Force { + return Plan{}, fmt.Errorf("worktree removal mode is absent or invalid") + } + switch facts.Target { + case PrimaryWorktree: + return Plan{}, fmt.Errorf("cannot remove the primary worktree") + case CurrentWorktree: + return Plan{}, fmt.Errorf("cannot remove the worktree containing the running command") + case RegisteredTarget: + default: + return Plan{}, fmt.Errorf("registered worktree target is absent or invalid") + } + if facts.Registration != Present || facts.RegisteredPath == "" || + facts.TargetDir != Present || facts.GitAdminDir != Present || + facts.GitMarker != Present || facts.Head != Present { + return Plan{}, fmt.Errorf("registered worktree target is absent or invalid") + } + if facts.CommonDir != Matched { + return Plan{}, fmt.Errorf("target common git directory does not match repository") + } + if facts.Status != Clean && facts.Status != Dirty { + return Plan{}, fmt.Errorf("worktree cleanliness observation is absent or invalid") + } + if facts.ManagedIgnore != IgnoreAbsent && facts.ManagedIgnore != IgnoreManaged { + return Plan{}, fmt.Errorf("managed ignore observation is absent or invalid") + } + if (facts.ManagedIgnore == IgnoreManaged) != (facts.ManagedIgnoreEntry != "") { + return Plan{}, fmt.Errorf("managed ignore cleanup identity is absent or invalid") + } + if request.Mode != Force { + if facts.Status != Clean { + return Plan{}, fmt.Errorf("worktree contains modified, untracked, or ignored files") + } + if facts.Comparator != ComparatorAvailable && facts.Comparator != ComparatorMissing && facts.Comparator != ComparatorNotRequired { + return Plan{}, fmt.Errorf("worktree comparison target observation is absent or invalid") + } + if facts.Comparator != ComparatorAvailable { + return Plan{}, fmt.Errorf("cannot verify unpushed commits: no comparison target is available") + } + if facts.Containment != Contained && facts.Containment != NotContained && facts.Containment != ContainmentNotRequired { + return Plan{}, fmt.Errorf("worktree containment observation is absent or invalid") + } + if facts.Containment != Contained { + return Plan{}, fmt.Errorf("worktree HEAD is not contained in the comparison target") + } + } else if facts.Comparator != ComparatorNotRequired || facts.Containment != ContainmentNotRequired { + return Plan{}, fmt.Errorf("worktree force-mode comparison observations are inconsistent") + } + plan := Plan{approved: true, mode: request.Mode, targetPath: facts.RegisteredPath} + if facts.ManagedIgnore == IgnoreManaged { + plan.managedIgnoreEntry = facts.ManagedIgnoreEntry + } + return plan, nil +} + +// InvariantState is the adapter's raw observation of one independently +// revalidated invariant. +type InvariantState uint8 + +const ( + // InvariantUnknown means the adapter could not complete the observation. + InvariantUnknown InvariantState = iota + // InvariantStable means the current observation matches preparation. + InvariantStable + // InvariantChanged means the current observation differs from preparation. + InvariantChanged + // InvariantNotRequired means force mode deliberately bypassed this check. + InvariantNotRequired +) + +// RevalidationFacts records every safety invariant independently. No adapter +// outcome may stand in for these raw observations. +type RevalidationFacts struct { + Registration InvariantState + LockPrune InvariantState + TargetPath InvariantState + TargetDirectory InvariantState + GitAdminDirectory InvariantState + GitAdminDirectoryBytes InvariantState + GitMarker InvariantState + GitMarkerBytes InvariantState + CommonDirectory InvariantState + Head InvariantState + Cleanliness InvariantState + StatusBytes InvariantState + DirtyFileFingerprint InvariantState + Comparator InvariantState + Containment InvariantState + ManagedIgnore InvariantState +} + +func revalidationValid(plan Plan, facts RevalidationFacts) bool { + for _, state := range []InvariantState{ + facts.Registration, facts.LockPrune, facts.TargetPath, facts.TargetDirectory, + facts.GitAdminDirectory, facts.GitAdminDirectoryBytes, facts.GitMarker, + facts.GitMarkerBytes, facts.CommonDirectory, facts.Head, facts.Cleanliness, + facts.StatusBytes, facts.DirtyFileFingerprint, facts.ManagedIgnore, + } { + if state != InvariantStable { + return false + } + } + if plan.mode == Normal { + return facts.Comparator == InvariantStable && facts.Containment == InvariantStable + } + return (facts.Comparator == InvariantStable || facts.Comparator == InvariantNotRequired) && + (facts.Containment == InvariantStable || facts.Containment == InvariantNotRequired) +} + +// Revalidate refuses every unknown or changed invariant observed after +// Prepare. A zero or otherwise unapproved plan is always refused. +func Revalidate(plan Plan, facts RevalidationFacts) error { + if !plan.valid() { + return fmt.Errorf("worktree removal approval is absent or invalid") + } + if !revalidationValid(plan, facts) { + return fmt.Errorf("worktree changed before removal") + } + return nil +} + +// RevalidationResult records whether reinspection completed without an +// adapter-side diagnostic after a failed removal. +type RevalidationResult uint8 + +const ( + // RevalidationResultUnknown means reinspection did not report a result. + RevalidationResultUnknown RevalidationResult = iota + // RevalidationPassed means reinspection completed without a diagnostic. + RevalidationPassed + // RevalidationFailed means reinspection produced an adapter diagnostic. + RevalidationFailed +) + +// FailureFacts are raw post-failure observations. Registry and target path +// presence are recorded separately from complete revalidation evidence. +type FailureFacts struct { + Revalidation RevalidationFacts + RevalidationResult RevalidationResult + Registration Presence + TargetPath Presence +} + +// FailureKind classifies the presentation branch for a remove error. +type FailureKind uint8 + +const ( + UnchangedFailure FailureKind = iota + PartialFailure +) + +// Failure is the pure classification returned after a mutation error. +type Failure struct { + Kind FailureKind + RemoveErr error +} + +// ClassifyFailure distinguishes a safely unchanged target from partial or +// indeterminate state. Presentation retains diagnostics at the command edge. +func ClassifyFailure(plan Plan, facts FailureFacts, removeErr error) (Failure, error) { + if !plan.valid() { + return Failure{}, fmt.Errorf("worktree removal approval is absent or invalid") + } + if removeErr == nil { + return Failure{}, fmt.Errorf("worktree removal failure is absent or invalid") + } + if facts.RevalidationResult == RevalidationPassed && facts.Registration == Present && facts.TargetPath == Present && revalidationValid(plan, facts.Revalidation) { + return Failure{Kind: UnchangedFailure, RemoveErr: removeErr}, nil + } + return Failure{Kind: PartialFailure, RemoveErr: removeErr}, nil +} diff --git a/internal/worktreeremove/policy_test.go b/internal/worktreeremove/policy_test.go new file mode 100644 index 000000000..6016e4e93 --- /dev/null +++ b/internal/worktreeremove/policy_test.go @@ -0,0 +1,200 @@ +package worktreeremove + +import ( + "strings" + "testing" +) + +func TestPrepareRefusesUnsafeTargetsInExistingOrder(t *testing.T) { + base := prepareFacts() + for _, tt := range []struct { + name string + set func(*PrepareFacts) + want string + }{ + {"primary", func(f *PrepareFacts) { f.Target = PrimaryWorktree }, "cannot remove the primary worktree"}, + {"current", func(f *PrepareFacts) { f.Target = CurrentWorktree }, "cannot remove the worktree containing the running command"}, + {"common directory", func(f *PrepareFacts) { f.CommonDir = Unmatched }, "target common git directory"}, + {"missing registered path", func(f *PrepareFacts) { f.RegisteredPath = "" }, "registered worktree target"}, + {"missing cleanup identity", func(f *PrepareFacts) { f.ManagedIgnore, f.ManagedIgnoreEntry = IgnoreManaged, "" }, "managed ignore cleanup identity"}, + } { + t.Run(tt.name, func(t *testing.T) { + facts := base + tt.set(&facts) + _, err := Prepare(Request{Mode: Normal}, facts) + if err == nil || !strings.Contains(err.Error(), tt.want) { + t.Fatalf("Prepare() error = %v, want %q", err, tt.want) + } + }) + } +} + +func TestPrepareCleanlinessAndContainmentRespectForce(t *testing.T) { + for _, tt := range []struct { + name string + req Request + set func(*PrepareFacts) + want string + }{ + {"dirty refused", Request{Mode: Normal}, func(f *PrepareFacts) { f.Status = Dirty }, "modified, untracked, or ignored"}, + {"dirty forced", Request{Mode: Force}, func(f *PrepareFacts) { + f.Status, f.Comparator, f.Containment = Dirty, ComparatorNotRequired, ContainmentNotRequired + }, ""}, + {"comparator required", Request{Mode: Normal}, func(f *PrepareFacts) { f.Comparator = ComparatorMissing }, "cannot verify unpushed commits"}, + {"not contained", Request{Mode: Normal}, func(f *PrepareFacts) { f.Containment = NotContained }, "not contained"}, + {"force marks comparison not required", Request{Mode: Force}, func(f *PrepareFacts) { f.Comparator, f.Containment = ComparatorNotRequired, ContainmentNotRequired }, ""}, + } { + t.Run(tt.name, func(t *testing.T) { + facts := prepareFacts() + tt.set(&facts) + _, err := Prepare(tt.req, facts) + if tt.want == "" { + if err != nil { + t.Fatalf("Prepare() error = %v", err) + } + return + } + if err == nil || !strings.Contains(err.Error(), tt.want) { + t.Fatalf("Prepare() error = %v, want %q", err, tt.want) + } + }) + } +} + +func TestPrepareRefusesZeroValueOrIncompleteFacts(t *testing.T) { + if _, err := Prepare(Request{}, PrepareFacts{}); err == nil { + t.Fatal("Prepare() accepted zero-value request and facts") + } + for _, tt := range []struct { + name string + set func(*PrepareFacts) + }{ + {"registration", func(f *PrepareFacts) { f.Registration = PresenceUnknown }}, + {"target", func(f *PrepareFacts) { f.Target = TargetUnknown }}, + {"registered path", func(f *PrepareFacts) { f.RegisteredPath = "" }}, + {"target directory", func(f *PrepareFacts) { f.TargetDir = PresenceUnknown }}, + {"git admin directory", func(f *PrepareFacts) { f.GitAdminDir = PresenceUnknown }}, + {"git marker", func(f *PrepareFacts) { f.GitMarker = PresenceUnknown }}, + {"common dir", func(f *PrepareFacts) { f.CommonDir = MatchUnknown }}, + {"head", func(f *PrepareFacts) { f.Head = PresenceUnknown }}, + {"status", func(f *PrepareFacts) { f.Status = StatusUnknown }}, + {"managed ignore", func(f *PrepareFacts) { f.ManagedIgnore = IgnoreUnknown }}, + } { + t.Run(tt.name, func(t *testing.T) { + facts := prepareFacts() + tt.set(&facts) + if _, err := Prepare(Request{Mode: Force}, facts); err == nil { + t.Fatal("Prepare() accepted incomplete facts in force mode") + } + }) + } +} + +func TestRevalidateRefusesZeroUnknownAndChangedInvariant(t *testing.T) { + plan, err := Prepare(Request{Mode: Normal}, prepareFacts()) + if err != nil { + t.Fatal(err) + } + if err := Revalidate(Plan{}, revalidationFacts(Normal)); err == nil { + t.Fatal("Revalidate() accepted zero plan") + } + for _, tt := range []struct { + name string + set func(*RevalidationFacts, InvariantState) + }{ + {"registration", func(f *RevalidationFacts, s InvariantState) { f.Registration = s }}, + {"lock prune", func(f *RevalidationFacts, s InvariantState) { f.LockPrune = s }}, + {"target path", func(f *RevalidationFacts, s InvariantState) { f.TargetPath = s }}, + {"target directory", func(f *RevalidationFacts, s InvariantState) { f.TargetDirectory = s }}, + {"git directory", func(f *RevalidationFacts, s InvariantState) { f.GitAdminDirectory = s }}, + {"git directory bytes", func(f *RevalidationFacts, s InvariantState) { f.GitAdminDirectoryBytes = s }}, + {"git marker", func(f *RevalidationFacts, s InvariantState) { f.GitMarker = s }}, + {"git marker bytes", func(f *RevalidationFacts, s InvariantState) { f.GitMarkerBytes = s }}, + {"common directory", func(f *RevalidationFacts, s InvariantState) { f.CommonDirectory = s }}, + {"head", func(f *RevalidationFacts, s InvariantState) { f.Head = s }}, + {"cleanliness", func(f *RevalidationFacts, s InvariantState) { f.Cleanliness = s }}, + {"status bytes", func(f *RevalidationFacts, s InvariantState) { f.StatusBytes = s }}, + {"dirty fingerprint", func(f *RevalidationFacts, s InvariantState) { f.DirtyFileFingerprint = s }}, + {"comparator", func(f *RevalidationFacts, s InvariantState) { f.Comparator = s }}, + {"containment", func(f *RevalidationFacts, s InvariantState) { f.Containment = s }}, + {"managed ignore", func(f *RevalidationFacts, s InvariantState) { f.ManagedIgnore = s }}, + } { + for _, state := range []InvariantState{InvariantUnknown, InvariantChanged} { + t.Run(tt.name+"/"+invariantName(state), func(t *testing.T) { + facts := revalidationFacts(Normal) + tt.set(&facts, state) + if err := Revalidate(plan, facts); err == nil { + t.Fatal("Revalidate() accepted incomplete or changed invariant") + } + }) + } + } + facts := revalidationFacts(Force) + facts.Head = InvariantNotRequired + if err := Revalidate(mustPrepare(t, Request{Mode: Force}, forcePrepareFacts()), facts); err == nil { + t.Fatal("Revalidate() accepted an unobserved required force invariant") + } +} + +func TestClassifyFailureUsesRawPostFailureEvidence(t *testing.T) { + plan, err := Prepare(Request{Mode: Normal}, prepareFacts()) + if err != nil { + t.Fatal(err) + } + removeErr := assertErr{} + stable := FailureFacts{Revalidation: revalidationFacts(Normal), RevalidationResult: RevalidationPassed, Registration: Present, TargetPath: Present} + if got, err := ClassifyFailure(plan, stable, removeErr); err != nil || got.Kind != UnchangedFailure { + t.Fatalf("stable failure = (%#v, %v), want unchanged", got, err) + } + for _, facts := range []FailureFacts{ + {Revalidation: revalidationFacts(Normal), Registration: Missing, TargetPath: Present}, + {Revalidation: revalidationFacts(Normal), Registration: Present, TargetPath: Missing}, + {Revalidation: revalidationFacts(Normal), RevalidationResult: RevalidationFailed, Registration: Present, TargetPath: Present}, + func() FailureFacts { f := stable; f.Revalidation.Head = InvariantUnknown; return f }(), + } { + if got, err := ClassifyFailure(plan, facts, removeErr); err != nil || got.Kind != PartialFailure { + t.Fatalf("indeterminate failure = (%#v, %v), want partial", got, err) + } + } + if _, err := ClassifyFailure(Plan{}, stable, removeErr); err == nil { + t.Fatal("ClassifyFailure() accepted zero plan") + } +} + +func prepareFacts() PrepareFacts { + return PrepareFacts{Registration: Present, Target: RegisteredTarget, RegisteredPath: "/exact/registry/path", TargetDir: Present, GitAdminDir: Present, GitMarker: Present, CommonDir: Matched, Head: Present, Status: Clean, Comparator: ComparatorAvailable, Containment: Contained, ManagedIgnore: IgnoreAbsent} +} + +func forcePrepareFacts() PrepareFacts { + facts := prepareFacts() + facts.Comparator, facts.Containment = ComparatorNotRequired, ContainmentNotRequired + return facts +} + +func mustPrepare(t *testing.T, request Request, facts PrepareFacts) Plan { + t.Helper() + plan, err := Prepare(request, facts) + if err != nil { + t.Fatal(err) + } + return plan +} + +func revalidationFacts(mode Mode) RevalidationFacts { + facts := RevalidationFacts{Registration: InvariantStable, LockPrune: InvariantStable, TargetPath: InvariantStable, TargetDirectory: InvariantStable, GitAdminDirectory: InvariantStable, GitAdminDirectoryBytes: InvariantStable, GitMarker: InvariantStable, GitMarkerBytes: InvariantStable, CommonDirectory: InvariantStable, Head: InvariantStable, Cleanliness: InvariantStable, StatusBytes: InvariantStable, DirtyFileFingerprint: InvariantStable, Comparator: InvariantStable, Containment: InvariantStable, ManagedIgnore: InvariantStable} + if mode == Force { + facts.Comparator, facts.Containment = InvariantNotRequired, InvariantNotRequired + } + return facts +} + +func invariantName(state InvariantState) string { + if state == InvariantUnknown { + return "unknown" + } + return "changed" +} + +type assertErr struct{} + +func (assertErr) Error() string { return "remove failed" }