diff --git a/README.md b/README.md index 9a96d67..e7d2da7 100644 --- a/README.md +++ b/README.md @@ -89,19 +89,18 @@ just test ## Uninstall -Sign out first, then remove the binary with the counterpart of the install -method: +One command removes the agent setup, the Claude Code plugin, the sign-in, the +config and cache folders and the binary. It lists everything and asks first: ```sh -frbit auth logout # repeat with --profile per profile -rm "$(command -v frbit)" # install script or release archive -brew uninstall frbit # Homebrew -npm uninstall --global @fortrabbit/cli # npm +frbit uninstall ``` -`frbit mcp remove` and `frbit skills remove` undo `frbit setup agent`. The -[uninstall guide](https://docs.fortrabbit.com/platform/automation/cli#uninstall) -covers the config and cache files that stay behind. +A Homebrew or npm install is removed through `brew` or `npm`. On Windows the +running binary cannot delete itself; the command names the file to delete. +Other profiles than the selected one: `frbit auth logout --profile ` +first. To keep the CLI and only undo `frbit setup agent`, run +`frbit setup agent --remove`. ## Development diff --git a/docs/cli.md b/docs/cli.md index 4dda55f..d5dda7a 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -88,9 +88,9 @@ printf '%s' "$FRBIT_TOKEN" | frbit auth login --token-stdin ## Uninstall -Sign out while the binary is still in place. `frbit auth logout` revokes a browser sign-in and removes the stored credential for the selected profile; repeat it with `--profile` for every profile in use. An agent setup is undone with `frbit mcp remove` and `frbit skills remove`. +`frbit uninstall` removes everything fortrabbit put on the machine for coding agents: the MCP server and the skill in Claude Code and Codex, the Claude Code plugin, the sign-in of the selected profile, the config and cache folders, and the binary. It lists everything and asks once; `--yes` skips the question. A Homebrew or npm install is removed with `brew uninstall frbit` or `npm uninstall --global @fortrabbit/cli`. On Windows, delete the binary yourself afterwards: a running executable cannot delete itself. Repeat `frbit auth logout --profile ` for other profiles before. -Then remove the CLI with the counterpart of the install method: +By hand, with the counterpart of the install method: ```sh rm "$(command -v frbit)" # install script or release archive @@ -366,6 +366,15 @@ the skills, including project-scoped skills or GitHub Copilot skills, use the When Claude Code has the fortrabbit plugin enabled, `setup agent` and `mcp install` skip Claude Code: the plugin brings its own skill and MCP server. +Undo the setup with `--remove`. It lists the MCP entries, skills and the CLI +sign-in it will remove and asks before it does; `--yes` skips the question. The +binary and the plugin stay; `frbit uninstall` removes them as well: + +```sh +frbit setup agent --remove +frbit setup agent --remove --agent codex --yes +``` + ## MCP server Manage the MCP registration independently when you do not want to change the @@ -475,7 +484,8 @@ frbit --profile work auth logout | `frbit people list` / `get ` | List or get people. `list` accepts repeatable `--id`. | | `frbit teams list` / `get ` / `delete ` | List, get, or delete teams. | | `frbit payment-methods list` / `get ` / `delete ` | List, get, or delete payment methods. | -| `frbit setup agent` | Register the remote MCP server and install skills for detected agents. Accepts repeatable `--agent`. | +| `frbit uninstall` | Remove the agent setup, the Claude Code plugin, the sign-in, the config and cache folders and the binary after confirmation. Accepts `--yes`. | +| `frbit setup agent` | Register the remote MCP server and install skills for detected agents. Accepts repeatable `--agent`; `--remove` undoes it and signs out. | | `frbit mcp install` | Register or update the named fortrabbit MCP entry. Accepts repeatable `--agent`. | | `frbit mcp list` | List the fortrabbit MCP status, URL, and agent configuration paths. | | `frbit mcp remove` | List and remove the named fortrabbit MCP entry after confirmation. Accepts `--yes`. | diff --git a/internal/agentmcp/service.go b/internal/agentmcp/service.go index 1c7553f..201570d 100644 --- a/internal/agentmcp/service.go +++ b/internal/agentmcp/service.go @@ -127,11 +127,22 @@ func (s *Service) WithoutClaudePlugin(ctx context.Context, agents []agent.Agent) }), true } -// A Claude Code without plugin support, or output that does not parse, counts as no plugin. func (s *Service) claudePluginEnabled(ctx context.Context) bool { + _, enabled := s.claudePlugin(ctx) + return enabled +} + +// ClaudePluginID returns the installed fortrabbit plugin as name@marketplace, enabled or not. +func (s *Service) ClaudePluginID(ctx context.Context) string { + id, _ := s.claudePlugin(ctx) + return id +} + +// A Claude Code without plugin support, or output that does not parse, counts as no plugin. +func (s *Service) claudePlugin(ctx context.Context) (string, bool) { output, err := s.runner.Run(ctx, "claude", "plugin", "list", "--json") if err != nil { - return false + return "", false } if start := strings.Index(output, "["); start > 0 { output = output[start:] @@ -141,15 +152,28 @@ func (s *Service) claudePluginEnabled(ctx context.Context) bool { Enabled bool `json:"enabled"` } if json.Unmarshal([]byte(output), &plugins) != nil { - return false + return "", false } for _, plugin := range plugins { name, _, _ := strings.Cut(plugin.ID, "@") - if plugin.Enabled && name == ClaudePluginName { - return true + if name == ClaudePluginName { + return plugin.ID, plugin.Enabled } } - return false + return "", false +} + +// RemoveClaudePlugin uninstalls the plugin; only the fortrabbit marketplace goes with it. +func (s *Service) RemoveClaudePlugin(ctx context.Context, pluginID string) error { + if output, err := s.runner.Run(ctx, "claude", "plugin", "uninstall", pluginID); err != nil { + return fmt.Errorf("uninstall the Claude Code plugin %s: %w: %s", pluginID, err, strings.TrimSpace(output)) + } + if _, marketplace, _ := strings.Cut(pluginID, "@"); marketplace == ClaudePluginName { + if output, err := s.runner.Run(ctx, "claude", "plugin", "marketplace", "remove", marketplace); err != nil { + return fmt.Errorf("remove the Claude Code marketplace %s: %w: %s", marketplace, err, strings.TrimSpace(output)) + } + } + return nil } func (s *Service) Inspect(ctx context.Context, agents []agent.Agent) ([]Registration, error) { diff --git a/internal/agentmcp/service_test.go b/internal/agentmcp/service_test.go index b51af75..746e306 100644 --- a/internal/agentmcp/service_test.go +++ b/internal/agentmcp/service_test.go @@ -163,3 +163,32 @@ func TestPreflightReportsMissingAgentCLI(t *testing.T) { t.Fatalf("error = %v", err) } } + +func TestRemoveClaudePlugin(t *testing.T) { + for id, want := range map[string][]string{ + "fortrabbit@fortrabbit": {"claude plugin uninstall fortrabbit@fortrabbit", "claude plugin marketplace remove fortrabbit"}, + "fortrabbit@claude-plugins-official": {"claude plugin uninstall fortrabbit@claude-plugins-official"}, + } { + runner := &fakeRunner{} + if err := testService(runner).RemoveClaudePlugin(context.Background(), id); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(runner.calls, want) { + t.Fatalf("%s: calls = %#v, want %#v", id, runner.calls, want) + } + } +} + +func TestClaudePluginIDKeepsTheMarketplace(t *testing.T) { + runner := &fakeRunner{responses: map[string]fakeResponse{"claude plugin list --json": {output: `[{"id":"fortrabbit@claude-plugins-official","enabled":true}]`}}} + if id := testService(runner).ClaudePluginID(context.Background()); id != "fortrabbit@claude-plugins-official" { + t.Fatalf("id = %q", id) + } +} + +func TestClaudePluginIDFindsADisabledPlugin(t *testing.T) { + runner := &fakeRunner{responses: map[string]fakeResponse{"claude plugin list --json": {output: `[{"id":"fortrabbit@fortrabbit","enabled":false}]`}}} + if id := testService(runner).ClaudePluginID(context.Background()); id != "fortrabbit@fortrabbit" { + t.Fatalf("id = %q", id) + } +} diff --git a/internal/cmd/auth/logout/logout.go b/internal/cmd/auth/logout/logout.go index 9633fb6..eea0c6a 100644 --- a/internal/cmd/auth/logout/logout.go +++ b/internal/cmd/auth/logout/logout.go @@ -43,6 +43,11 @@ func NewCmdLogout(factory *app.Factory, runF func(*Options) error) *cobra.Comman } } +// Run signs the selected profile out the same way frbit auth logout does. +func Run(factory *app.Factory, command *cobra.Command) error { + return run(&Options{Factory: factory, Command: command}) +} + func run(options *Options) error { command := options.Command profile, err := cmdutil.Profile(command) diff --git a/internal/cmd/root/root.go b/internal/cmd/root/root.go index d868794..894dea6 100644 --- a/internal/cmd/root/root.go +++ b/internal/cmd/root/root.go @@ -45,6 +45,7 @@ func NewCmdRoot(factory *app.Factory) *cobra.Command { apps.NewCmdApps(factory), mcp.NewCmdMCP(factory, nil), setup.NewCmdSetup(factory, nil, nil), + setup.NewCmdUninstall(factory), skills.NewCmdSkills(factory, nil), environments.NewCmdEnvironments(factory), resource.NewCmdGroup(factory, deploymentSpec()), diff --git a/internal/cmd/setup/setup.go b/internal/cmd/setup/setup.go index a99939b..106a70c 100644 --- a/internal/cmd/setup/setup.go +++ b/internal/cmd/setup/setup.go @@ -2,6 +2,7 @@ package setup import ( "context" + "errors" "fmt" "io" @@ -9,7 +10,9 @@ import ( "github.com/fortrabbit/frbit-cli/internal/agentmcp" "github.com/fortrabbit/frbit-cli/internal/agentskills" "github.com/fortrabbit/frbit-cli/internal/app" + "github.com/fortrabbit/frbit-cli/internal/cmd/auth/logout" "github.com/fortrabbit/frbit-cli/internal/cmdutil" + "github.com/fortrabbit/frbit-cli/internal/credentials" "github.com/spf13/cobra" ) @@ -17,13 +20,19 @@ type mcpService interface { ResolveAgents([]agent.Agent) ([]agent.Agent, error) Preflight([]agent.Agent) error Install(context.Context, []agent.Agent) ([]agentmcp.Result, error) + Inspect(context.Context, []agent.Agent) ([]agentmcp.Registration, error) + Remove(context.Context, []agent.Agent) ([]agentmcp.Result, error) WithoutClaudePlugin(context.Context, []agent.Agent) ([]agent.Agent, bool) + ClaudePluginID(context.Context) string + RemoveClaudePlugin(context.Context, string) error } type skillsService interface { InstallTargets(bool, []agentskills.Agent) ([]agentskills.Target, error) LatestRelease(context.Context) (agentskills.Release, error) InstallRelease(context.Context, agentskills.Release, []agentskills.Target) ([]agentskills.Installation, error) + Removals(bool, []agentskills.Agent) ([]agentskills.Removal, error) + Remove([]agentskills.Removal) error } func NewCmdSetup(factory *app.Factory, mcp mcpService, skills skillsService) *cobra.Command { @@ -50,10 +59,14 @@ func NewCmdSetup(factory *app.Factory, mcp mcpService, skills skillsService) *co func newCmdAgent(factory *app.Factory, mcp mcpService, skills skillsService) *cobra.Command { var agentValues []string + var remove, yes bool command := &cobra.Command{ Use: "agent", Short: "Register MCP and install skills for coding agents", - Args: cobra.NoArgs, + Long: `Register the fortrabbit MCP server and install the fortrabbit skill for Claude Code and Codex. + +With --remove, undo both and sign the CLI out. The frbit binary stays in place.`, + Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { requested, err := agentmcp.ParseAgents(agentValues) if err != nil { @@ -63,6 +76,9 @@ func newCmdAgent(factory *app.Factory, mcp mcpService, skills skillsService) *co if err != nil { return err } + if remove { + return removeAgentSetup(cmd, factory, mcp, skills, agents, yes) + } // Validate every native agent CLI before writing either integration. if err := mcp.Preflight(agents); err != nil { return err @@ -103,6 +119,8 @@ func newCmdAgent(factory *app.Factory, mcp mcpService, skills skillsService) *co }, } command.Flags().StringArrayVar(&agentValues, "agent", nil, "Target agent (claude-code or codex); repeat to target more than one") + command.Flags().BoolVar(&remove, "remove", false, "Remove the MCP server and the skill, and sign the CLI out") + command.Flags().BoolVarP(&yes, "yes", "y", false, "Remove without prompting for confirmation") return command } @@ -160,3 +178,148 @@ func printSummary( } return cmdutil.PrintOAuthHints(writer, agents) } + +const ( + claudePluginRemoveNotice = "Claude Code: the fortrabbit plugin brings the skill and the MCP server; frbit uninstall removes it too." + disconnectHint = "Revoke the MCP grants in the dashboard: https://dash.fortrabbit.com/you/ai-agents" + uninstallHint = "Remove the frbit CLI as well: frbit uninstall" +) + +// removalPlan is what frbit setup agent put on this machine, found before anything is removed. +type removalPlan struct { + registrations []agentmcp.Registration + registered []agent.Agent + removals []agentskills.Removal + profile string + signedIn bool +} + +func planRemoval(cmd *cobra.Command, factory *app.Factory, mcp mcpService, skills skillsService, agents []agent.Agent) (removalPlan, error) { + plan := removalPlan{} + // An empty agent list means all agents to the skills service, so skip both lookups. + if len(agents) > 0 { + var err error + if plan.registrations, err = mcp.Inspect(cmd.Context(), agents); err != nil { + return plan, err + } + if plan.removals, err = skills.Removals(false, agents); err != nil { + return plan, err + } + } + for _, registration := range plan.registrations { + if registration.Installed { + plan.registered = append(plan.registered, registration.Agent) + } + } + profile, err := cmdutil.Profile(cmd) + if err != nil { + return plan, err + } + plan.profile = profile + _, credentialErr := factory.CredentialStore.Get(profile) + if credentialErr != nil && !errors.Is(credentialErr, credentials.ErrNotFound) { + return plan, credentialErr + } + plan.signedIn = credentialErr == nil + return plan, nil +} + +func (p removalPlan) empty() bool { + return len(p.registered) == 0 && len(p.removals) == 0 && !p.signedIn +} + +func (p removalPlan) print(writer io.Writer) error { + for _, registration := range p.registrations { + if !registration.Installed { + continue + } + if _, err := fmt.Fprintf(writer, " %-14s MCP server in %s\n", registration.Agent.Label()+":", registration.ConfigPath); err != nil { + return err + } + } + for _, removal := range p.removals { + if _, err := fmt.Fprintf(writer, " %-14s skill at %s\n", removal.Agent.Label()+":", removal.Path); err != nil { + return err + } + } + if p.signedIn { + if _, err := fmt.Fprintf(writer, " %-14s sign-in of profile %q\n", "frbit CLI:", p.profile); err != nil { + return err + } + } + return nil +} + +func (p removalPlan) execute(cmd *cobra.Command, factory *app.Factory, mcp mcpService, skills skillsService) error { + writer := cmd.OutOrStdout() + if len(p.registered) > 0 { + results, err := mcp.Remove(cmd.Context(), p.registered) + if err != nil { + return err + } + for _, result := range results { + if _, err := fmt.Fprintf(writer, "Removed the MCP server from %s\n", result.Agent.Label()); err != nil { + return err + } + } + } + if err := skills.Remove(p.removals); err != nil { + return err + } + for _, removal := range p.removals { + if _, err := fmt.Fprintf(writer, "Removed %s\n", removal.Path); err != nil { + return err + } + } + if p.signedIn { + return logout.Run(factory, cmd) + } + return nil +} + +func confirmRemoval(factory *app.Factory, writer io.Writer, yes bool) (bool, error) { + if yes { + return true, nil + } + confirmed, err := cmdutil.Confirm(factory.IOStreams.In, writer, "Continue? [y/N] ") + if err != nil || confirmed { + return confirmed, err + } + _, err = fmt.Fprintln(writer, "Aborted.") + return false, err +} + +func removeAgentSetup(cmd *cobra.Command, factory *app.Factory, mcp mcpService, skills skillsService, agents []agent.Agent, yes bool) error { + writer := cmd.OutOrStdout() + if err := mcp.Preflight(agents); err != nil { + return err + } + agents, pluginEnabled := mcp.WithoutClaudePlugin(cmd.Context(), agents) + if pluginEnabled { + if _, err := fmt.Fprintln(writer, claudePluginRemoveNotice); err != nil { + return err + } + } + plan, err := planRemoval(cmd, factory, mcp, skills, agents) + if err != nil { + return err + } + if plan.empty() { + _, err := fmt.Fprintln(writer, "Nothing to remove: no fortrabbit MCP server, skill or sign-in found.") + return err + } + if _, err := fmt.Fprintln(writer, "This removes:"); err != nil { + return err + } + if err := plan.print(writer); err != nil { + return err + } + if confirmed, err := confirmRemoval(factory, writer, yes); err != nil || !confirmed { + return err + } + if err := plan.execute(cmd, factory, mcp, skills); err != nil { + return err + } + _, err = fmt.Fprintf(writer, "Agent setup removed.\n\n%s\n%s\n", disconnectHint, uninstallHint) + return err +} diff --git a/internal/cmd/setup/setup_test.go b/internal/cmd/setup/setup_test.go index 754ee43..d43411e 100644 --- a/internal/cmd/setup/setup_test.go +++ b/internal/cmd/setup/setup_test.go @@ -3,7 +3,8 @@ package setup import ( "bytes" "context" - "errors" + "path/filepath" + "slices" "strings" "testing" @@ -17,9 +18,12 @@ import ( ) type fakeMCPService struct { - preflighted []agent.Agent - installed []agent.Agent - claudePlugin bool + preflighted []agent.Agent + installed []agent.Agent + registered []agent.Agent + removed []agent.Agent + removedPlugin string + claudePlugin bool } func (s *fakeMCPService) ResolveAgents(requested []agent.Agent) ([]agent.Agent, error) { @@ -53,7 +57,33 @@ func (s *fakeMCPService) Install(_ context.Context, agents []agent.Agent) ([]age return results, nil } -type fakeSkillsService struct{} +func (s *fakeMCPService) Inspect(_ context.Context, agents []agent.Agent) ([]agentmcp.Registration, error) { + registrations := make([]agentmcp.Registration, 0, len(agents)) + for _, target := range agents { + registrations = append(registrations, agentmcp.Registration{Agent: target, Installed: slices.Contains(s.registered, target), ConfigPath: "/config/" + string(target)}) + } + return registrations, nil +} +func (s *fakeMCPService) Remove(_ context.Context, agents []agent.Agent) ([]agentmcp.Result, error) { + s.removed = append([]agent.Agent(nil), agents...) + return nil, nil +} + +func (s *fakeMCPService) ClaudePluginID(context.Context) string { + if s.claudePlugin { + return "fortrabbit@fortrabbit" + } + return "" +} +func (s *fakeMCPService) RemoveClaudePlugin(_ context.Context, pluginID string) error { + s.removedPlugin = pluginID + return nil +} + +type fakeSkillsService struct { + installed []agent.Agent + removed *[]agentskills.Removal +} func (fakeSkillsService) InstallTargets(_ bool, agents []agentskills.Agent) ([]agentskills.Target, error) { targets := make([]agentskills.Target, 0, len(agents)) @@ -72,13 +102,31 @@ func (fakeSkillsService) InstallRelease(_ context.Context, release agentskills.R } return installations, nil } +func (s fakeSkillsService) Removals(_ bool, agents []agentskills.Agent) ([]agentskills.Removal, error) { + if len(agents) == 0 { + agents = []agentskills.Agent{agent.ClaudeCode, agent.Codex} + } + var removals []agentskills.Removal + for _, target := range agents { + if slices.Contains(s.installed, target) { + removals = append(removals, agentskills.Removal{Agent: target, Path: "/skills/" + string(target), Directory: true}) + } + } + return removals, nil +} +func (s fakeSkillsService) Remove(removals []agentskills.Removal) error { + if s.removed != nil { + *s.removed = append(*s.removed, removals...) + } + return nil +} type missingCredentials struct{} var _ credentials.Store = missingCredentials{} func (missingCredentials) Get(string) (credentials.Credential, error) { - return credentials.Credential{}, errors.New("missing") + return credentials.Credential{}, credentials.ErrNotFound } func (missingCredentials) Set(string, credentials.Credential) error { return nil } func (missingCredentials) Delete(string) error { return nil } @@ -162,3 +210,91 @@ func TestAgentSetupStopsWhenOnlyClaudeCodeHasThePlugin(t *testing.T) { t.Fatalf("installed = %#v", mcp.installed) } } + +type storedCredentials struct { + deleted *bool +} + +func (storedCredentials) Get(string) (credentials.Credential, error) { + return credentials.APIToken("token"), nil +} +func (storedCredentials) Set(string, credentials.Credential) error { return nil } +func (s storedCredentials) Delete(string) error { + *s.deleted = true + return nil +} + +func runRemove(t *testing.T, store credentials.Store, input string, mcp *fakeMCPService, skills fakeSkillsService, args ...string) string { + t.Helper() + output := &bytes.Buffer{} + factory := &app.Factory{ + IOStreams: iostreams.IOStreams{In: strings.NewReader(input), Out: output, ErrOut: output}, + CredentialStore: store, + CredentialLockPath: filepath.Join(t.TempDir(), "credentials.lock"), + Version: "test", + } + root := &cobra.Command{Use: "frbit"} + root.PersistentFlags().String("profile", app.DefaultProfile, "Credential profile") + root.AddCommand(NewCmdSetup(factory, mcp, skills)) + root.SetOut(output) + root.SetErr(output) + root.SetArgs(append([]string{"setup", "agent", "--remove"}, args...)) + if err := root.Execute(); err != nil { + t.Fatal(err) + } + return output.String() +} + +func TestAgentRemoveUndoesTheSetup(t *testing.T) { + deleted := false + removed := []agentskills.Removal{} + mcp := &fakeMCPService{registered: []agent.Agent{agent.ClaudeCode, agent.Codex}} + skills := fakeSkillsService{installed: []agent.Agent{agent.Codex}, removed: &removed} + output := runRemove(t, storedCredentials{deleted: &deleted}, "", mcp, skills, "--yes") + for _, expected := range []string{"MCP server in /config/codex", "skill at /skills/codex", "Agent setup removed.", disconnectHint, uninstallHint} { + if !strings.Contains(output, expected) { + t.Fatalf("output %q does not contain %q", output, expected) + } + } + if len(mcp.removed) != 2 || len(removed) != 1 || !deleted { + t.Fatalf("mcp removed = %#v, skills removed = %#v, signed out = %v", mcp.removed, removed, deleted) + } +} + +func TestAgentRemoveAbortsWithoutConfirmation(t *testing.T) { + deleted := false + removed := []agentskills.Removal{} + mcp := &fakeMCPService{registered: []agent.Agent{agent.Codex}} + output := runRemove(t, storedCredentials{deleted: &deleted}, "n\n", mcp, fakeSkillsService{removed: &removed}) + if !strings.Contains(output, "Aborted.") || mcp.removed != nil || len(removed) != 0 || deleted { + t.Fatalf("output = %q, mcp removed = %#v, skills removed = %#v, signed out = %v", output, mcp.removed, removed, deleted) + } +} + +func TestAgentRemoveReportsNothingToRemove(t *testing.T) { + output := runRemove(t, missingCredentials{}, "", &fakeMCPService{}, fakeSkillsService{}) + if !strings.Contains(output, "Nothing to remove") { + t.Fatalf("output = %q", output) + } +} + +func TestAgentRemoveLeavesTheClaudePluginToClaude(t *testing.T) { + mcp := &fakeMCPService{claudePlugin: true, registered: []agent.Agent{agent.ClaudeCode, agent.Codex}} + output := runRemove(t, missingCredentials{}, "", mcp, fakeSkillsService{}, "--yes") + if !strings.Contains(output, claudePluginRemoveNotice) { + t.Fatalf("output %q does not contain the plugin notice", output) + } + if len(mcp.removed) != 1 || mcp.removed[0] != agent.Codex { + t.Fatalf("removed = %#v", mcp.removed) + } +} + +func TestAgentRemoveKeepsCodexWhenOnlyClaudeCodeHasThePlugin(t *testing.T) { + removed := []agentskills.Removal{} + mcp := &fakeMCPService{claudePlugin: true, registered: []agent.Agent{agent.Codex}} + skills := fakeSkillsService{installed: []agent.Agent{agent.Codex}, removed: &removed} + output := runRemove(t, missingCredentials{}, "", mcp, skills, "--agent", "claude-code", "--yes") + if !strings.Contains(output, "Nothing to remove") || mcp.removed != nil || len(removed) != 0 { + t.Fatalf("output = %q, mcp removed = %#v, skills removed = %#v", output, mcp.removed, removed) + } +} diff --git a/internal/cmd/setup/uninstall.go b/internal/cmd/setup/uninstall.go new file mode 100644 index 0000000..a3f3b94 --- /dev/null +++ b/internal/cmd/setup/uninstall.go @@ -0,0 +1,221 @@ +package setup + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + + "github.com/fortrabbit/frbit-cli/internal/agent" + "github.com/fortrabbit/frbit-cli/internal/agentmcp" + "github.com/fortrabbit/frbit-cli/internal/agentskills" + "github.com/fortrabbit/frbit-cli/internal/app" + "github.com/spf13/cobra" +) + +type uninstallSystem struct { + executable func() (string, error) + cacheDir func() (string, error) + runner agentmcp.Runner + goos string +} + +// binaryRemoval removes the binary with the package manager that installed it, or deletes the file. +type binaryRemoval struct { + path string + command []string +} + +func NewCmdUninstall(factory *app.Factory) *cobra.Command { + return newCmdUninstall(factory, nil, nil, uninstallSystem{ + executable: os.Executable, + cacheDir: os.UserCacheDir, + runner: agentmcp.ExecRunner{}, + goos: runtime.GOOS, + }) +} + +func newCmdUninstall(factory *app.Factory, mcp mcpService, skills skillsService, system uninstallSystem) *cobra.Command { + if mcp == nil { + mcp = agentmcp.NewService(agentmcp.Options{}) + } + if skills == nil { + skills = agentskills.NewService(agentskills.Options{ + HTTPClient: factory.HTTPClient, + UserAgent: fmt.Sprintf("frbit/%s", factory.Version), + }) + } + var yes bool + command := &cobra.Command{ + Use: "uninstall", + Short: "Remove the agent setup and the frbit CLI", + Long: `Remove everything fortrabbit put on this machine for coding agents: the MCP server and the +skill in Claude Code and Codex, the Claude Code plugin, the CLI sign-in, the config and cache +folders, and the frbit binary. A Homebrew or npm install is removed with brew or npm. + +Lists everything first and asks once. Apps, environments and the account stay.`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + return runUninstall(cmd, factory, mcp, skills, system, yes) + }, + } + command.Flags().BoolVarP(&yes, "yes", "y", false, "Remove without prompting for confirmation") + return command +} + +func runUninstall(cmd *cobra.Command, factory *app.Factory, mcp mcpService, skills skillsService, system uninstallSystem, yes bool) error { + writer := cmd.OutOrStdout() + agents, resolveErr := mcp.ResolveAgents(nil) + pluginID := "" + if slices.Contains(agents, agent.ClaudeCode) { + pluginID = mcp.ClaudePluginID(cmd.Context()) + } + plan, err := planRemoval(cmd, factory, mcp, skills, agents) + if err != nil { + return err + } + if resolveErr != nil { + if _, err := fmt.Fprintf(writer, "MCP entries skipped: %v\n", resolveErr); err != nil { + return err + } + } + // MCP entries need the agent CLI, skill folders do not: look for every agent's skill. + if plan.removals, err = skills.Removals(false, []agent.Agent{agent.ClaudeCode, agent.Codex}); err != nil { + return err + } + folders := existingFolders(factory, system) + binary, err := locateBinary(system.executable) + if err != nil { + return err + } + + if _, err := fmt.Fprintln(writer, "This removes:"); err != nil { + return err + } + if err := plan.print(writer); err != nil { + return err + } + if pluginID != "" { + if _, err := fmt.Fprintf(writer, " %-14s plugin %s\n", agent.ClaudeCode.Label()+":", pluginID); err != nil { + return err + } + } + for _, folder := range folders { + if _, err := fmt.Fprintf(writer, " %-14s %s\n", "frbit CLI:", folder); err != nil { + return err + } + } + if err := printBinary(writer, binary); err != nil { + return err + } + if confirmed, err := confirmRemoval(factory, writer, yes); err != nil || !confirmed { + return err + } + + if err := plan.execute(cmd, factory, mcp, skills); err != nil { + return err + } + if pluginID != "" { + if err := mcp.RemoveClaudePlugin(cmd.Context(), pluginID); err != nil { + return err + } + if _, err := fmt.Fprintf(writer, "Removed the Claude Code plugin %s\n", pluginID); err != nil { + return err + } + } + for _, folder := range folders { + if err := os.RemoveAll(folder); err != nil { + return fmt.Errorf("remove %s: %w", folder, err) + } + if _, err := fmt.Fprintf(writer, "Removed %s\n", folder); err != nil { + return err + } + } + // The binary goes last, so any failure above leaves frbit in place to run again. + finalStep, err := removeBinary(cmd.Context(), system, binary) + if err != nil { + return err + } + if finalStep != "" { + _, err = fmt.Fprintf(writer, "%s\n\n%s\n", finalStep, disconnectHint) + return err + } + _, err = fmt.Fprintf(writer, "Removed %s\nfrbit uninstalled.\n\n%s\n", binary.path, disconnectHint) + return err +} + +func existingFolders(factory *app.Factory, system uninstallSystem) []string { + var candidates []string + if factory.CredentialLockPath != "" { + candidates = append(candidates, filepath.Dir(factory.CredentialLockPath)) + } + if cacheDir, err := system.cacheDir(); err == nil { + candidates = append(candidates, filepath.Join(cacheDir, "frbit")) + } + var folders []string + for _, candidate := range candidates { + if _, err := os.Stat(candidate); err == nil { + folders = append(folders, candidate) + } + } + return folders +} + +func locateBinary(executable func() (string, error)) (binaryRemoval, error) { + path, err := executable() + if err != nil { + return binaryRemoval{}, fmt.Errorf("find the frbit binary: %w", err) + } + // Detect the package manager on the real file, but delete the path itself: a symlink goes, its target stays. + resolved := path + if target, err := filepath.EvalSymlinks(path); err == nil { + resolved = target + } + slashed := filepath.ToSlash(resolved) + switch { + case strings.Contains(slashed, "/Cellar/frbit/"): + return binaryRemoval{path: path, command: []string{"brew", "uninstall", "frbit"}}, nil + case strings.Contains(slashed, "/node_modules/@fortrabbit/"): + return binaryRemoval{path: path, command: []string{"npm", "uninstall", "--global", "@fortrabbit/cli"}}, nil + } + return binaryRemoval{path: path}, nil +} + +func printBinary(writer io.Writer, binary binaryRemoval) error { + via := "" + if binary.command != nil { + via = fmt.Sprintf(" (%s)", strings.Join(binary.command, " ")) + } + _, err := fmt.Fprintf(writer, " %-14s binary at %s%s\n", "frbit CLI:", binary.path, via) + return err +} + +// removeBinary returns the step left to the person when the binary cannot remove itself. +func removeBinary(ctx context.Context, system uninstallSystem, binary binaryRemoval) (string, error) { + // Windows keeps a running executable locked, also for brew or npm. + if system.goos == "windows" { + if binary.command != nil { + return fmt.Sprintf("One step left: run %s.", strings.Join(binary.command, " ")), nil + } + return fmt.Sprintf("One step left: delete %s.", binary.path), nil + } + if binary.command != nil { + if output, err := system.runner.Run(ctx, binary.command[0], binary.command[1:]...); err != nil { + return "", fmt.Errorf("%s: %w: %s", strings.Join(binary.command, " "), err, strings.TrimSpace(output)) + } + // pnpm, yarn and bun use the same node_modules layout, and npm succeeds on a package it does not own. + if _, err := os.Stat(binary.path); err == nil { + return "", fmt.Errorf("%s is still in place after %s; remove it with the package manager that installed it", binary.path, strings.Join(binary.command, " ")) + } + return "", nil + } + if err := os.Remove(binary.path); err != nil && !errors.Is(err, os.ErrNotExist) { + return "", fmt.Errorf("remove %s: %w", binary.path, err) + } + return "", nil +} diff --git a/internal/cmd/setup/uninstall_test.go b/internal/cmd/setup/uninstall_test.go new file mode 100644 index 0000000..e29e612 --- /dev/null +++ b/internal/cmd/setup/uninstall_test.go @@ -0,0 +1,197 @@ +package setup + +import ( + "bytes" + "context" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/fortrabbit/frbit-cli/internal/agent" + "github.com/fortrabbit/frbit-cli/internal/agentskills" + "github.com/fortrabbit/frbit-cli/internal/app" + "github.com/fortrabbit/frbit-cli/internal/iostreams" + "github.com/spf13/cobra" +) + +type recordingRunner struct { + calls []string + remove string +} + +// Run stands in for brew or npm, which delete the binary. +func (r *recordingRunner) Run(_ context.Context, name string, args ...string) (string, error) { + r.calls = append(r.calls, strings.Join(append([]string{name}, args...), " ")) + if r.remove != "" { + _ = os.Remove(r.remove) + } + return "", nil +} + +type uninstallFixture struct { + configDir string + cacheDir string + binary string + runner *recordingRunner +} + +func newUninstallFixture(t *testing.T, binaryPath string) uninstallFixture { + t.Helper() + // macOS hands out temp dirs behind the /var symlink, which locateBinary resolves. + root, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + fixture := uninstallFixture{ + configDir: filepath.Join(root, "config", "frbit"), + cacheDir: filepath.Join(root, "cache"), + binary: filepath.Join(root, binaryPath), + runner: &recordingRunner{}, + } + for _, path := range []string{filepath.Join(fixture.configDir, "config.json"), filepath.Join(fixture.cacheDir, "frbit", "update-check.json"), fixture.binary} { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + } + return fixture +} + +func (f uninstallFixture) run(t *testing.T, input string, mcp *fakeMCPService, skills fakeSkillsService, goos string, args ...string) string { + t.Helper() + output := &bytes.Buffer{} + factory := &app.Factory{ + IOStreams: iostreams.IOStreams{In: strings.NewReader(input), Out: output, ErrOut: output}, + CredentialStore: missingCredentials{}, + CredentialLockPath: filepath.Join(f.configDir, "credentials.lock"), + Version: "test", + } + system := uninstallSystem{ + executable: func() (string, error) { return f.binary, nil }, + cacheDir: func() (string, error) { return f.cacheDir, nil }, + runner: f.runner, + goos: goos, + } + root := &cobra.Command{Use: "frbit"} + root.PersistentFlags().String("profile", app.DefaultProfile, "Credential profile") + root.AddCommand(newCmdUninstall(factory, mcp, skills, system)) + root.SetOut(output) + root.SetErr(output) + root.SetArgs(append([]string{"uninstall"}, args...)) + if err := root.Execute(); err != nil { + t.Fatal(err) + } + return output.String() +} + +func exists(path string) bool { + _, err := os.Stat(path) + return err == nil +} + +func TestUninstallRemovesEverything(t *testing.T) { + fixture := newUninstallFixture(t, "bin/frbit") + removed := []agentskills.Removal{} + mcp := &fakeMCPService{claudePlugin: true, registered: []agent.Agent{agent.Codex}} + skills := fakeSkillsService{installed: []agent.Agent{agent.Codex}, removed: &removed} + output := fixture.run(t, "", mcp, skills, "darwin", "--yes") + for _, expected := range []string{"plugin fortrabbit@fortrabbit", "binary at " + fixture.binary, "Removed " + fixture.binary + "\n", "frbit uninstalled.", disconnectHint} { + if !strings.Contains(output, expected) { + t.Fatalf("output %q does not contain %q", output, expected) + } + } + if mcp.removedPlugin != "fortrabbit@fortrabbit" || len(mcp.removed) != 1 || len(removed) != 1 { + t.Fatalf("plugin = %q, mcp removed = %#v, skills removed = %#v", mcp.removedPlugin, mcp.removed, removed) + } + for _, path := range []string{fixture.configDir, filepath.Join(fixture.cacheDir, "frbit"), fixture.binary} { + if exists(path) { + t.Fatalf("%s still exists", path) + } + } +} + +func TestUninstallUsesThePackageManager(t *testing.T) { + for binaryPath, want := range map[string]string{ + "homebrew/Cellar/frbit/1.10.0/bin/frbit": "brew uninstall frbit", + "lib/node_modules/@fortrabbit/cli-darwin-arm64/bin/frbit": "npm uninstall --global @fortrabbit/cli", + } { + fixture := newUninstallFixture(t, binaryPath) + fixture.runner.remove = fixture.binary + fixture.run(t, "", &fakeMCPService{}, fakeSkillsService{}, "darwin", "--yes") + if !reflect.DeepEqual(fixture.runner.calls, []string{want}) { + t.Fatalf("calls = %#v, want %q", fixture.runner.calls, want) + } + } +} + +func TestUninstallLeavesTheRunningBinaryToWindowsUsers(t *testing.T) { + fixture := newUninstallFixture(t, "frbit.exe") + output := fixture.run(t, "", &fakeMCPService{}, fakeSkillsService{}, "windows", "--yes") + if !strings.Contains(output, "One step left: delete "+fixture.binary+".") || !exists(fixture.binary) { + t.Fatalf("output = %q", output) + } +} + +func TestUninstallAbortsWithoutConfirmation(t *testing.T) { + fixture := newUninstallFixture(t, "bin/frbit") + mcp := &fakeMCPService{claudePlugin: true} + output := fixture.run(t, "n\n", mcp, fakeSkillsService{}, "darwin") + if !strings.Contains(output, "Aborted.") || mcp.removedPlugin != "" || !exists(fixture.binary) || !exists(fixture.configDir) { + t.Fatalf("output = %q", output) + } +} + +func TestUninstallLeavesNpmToWindowsUsers(t *testing.T) { + fixture := newUninstallFixture(t, "node_modules/@fortrabbit/cli-win32-x64/bin/frbit.exe") + output := fixture.run(t, "", &fakeMCPService{}, fakeSkillsService{}, "windows", "--yes") + if !strings.Contains(output, "One step left: run npm uninstall --global @fortrabbit/cli.") || len(fixture.runner.calls) != 0 { + t.Fatalf("output = %q, calls = %#v", output, fixture.runner.calls) + } +} + +func TestUninstallFailsWhenThePackageManagerLeavesTheBinary(t *testing.T) { + fixture := newUninstallFixture(t, "pnpm/global/node_modules/@fortrabbit/cli-darwin-arm64/bin/frbit") + output := &bytes.Buffer{} + factory := &app.Factory{ + IOStreams: iostreams.IOStreams{In: strings.NewReader(""), Out: output, ErrOut: output}, + CredentialStore: missingCredentials{}, + CredentialLockPath: filepath.Join(fixture.configDir, "credentials.lock"), + } + system := uninstallSystem{ + executable: func() (string, error) { return fixture.binary, nil }, + cacheDir: func() (string, error) { return fixture.cacheDir, nil }, + runner: fixture.runner, + goos: "darwin", + } + root := &cobra.Command{Use: "frbit"} + root.PersistentFlags().String("profile", app.DefaultProfile, "Credential profile") + root.AddCommand(newCmdUninstall(factory, &fakeMCPService{}, fakeSkillsService{}, system)) + root.SetOut(output) + root.SetErr(output) + root.SetArgs([]string{"uninstall", "--yes"}) + err := root.Execute() + if err == nil || !strings.Contains(err.Error(), "still in place") || strings.Contains(output.String(), "frbit uninstalled.") { + t.Fatalf("err = %v, output = %q", err, output.String()) + } +} + +func TestUninstallRemovesASymlinkButNotItsTarget(t *testing.T) { + fixture := newUninstallFixture(t, "build/frbit") + link := filepath.Join(filepath.Dir(filepath.Dir(fixture.binary)), "bin", "frbit") + if err := os.MkdirAll(filepath.Dir(link), 0o700); err != nil { + t.Fatal(err) + } + if err := os.Symlink(fixture.binary, link); err != nil { + t.Fatal(err) + } + target := fixture.binary + fixture.binary = link + fixture.run(t, "", &fakeMCPService{}, fakeSkillsService{}, "darwin", "--yes") + if _, err := os.Lstat(link); err == nil || !exists(target) { + t.Fatalf("link removed = %v, target kept = %v", err != nil, exists(target)) + } +}