From 1f633c2f7399c84db832e585d015678a333b4285 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frank=20La=CC=88mmer?= Date: Wed, 28 Oct 2026 20:06:08 +0100 Subject: [PATCH 1/5] MR-496: Add frbit setup agent --remove Undoes frbit setup agent in one command: removes the MCP entry and the skill from the detected agents and signs the CLI out, after a confirmation that --yes skips. The Claude Code plugin and the binary stay in place; the output says how to remove them and where to revoke the MCP grants. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 +- docs/cli.md | 11 ++- internal/cmd/auth/logout/logout.go | 5 ++ internal/cmd/setup/setup.go | 130 ++++++++++++++++++++++++++++- internal/cmd/setup/setup_test.go | 130 ++++++++++++++++++++++++++++- 5 files changed, 276 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 9a96d67..f37ae5f 100644 --- a/README.md +++ b/README.md @@ -89,17 +89,19 @@ just test ## Uninstall -Sign out first, then remove the binary with the counterpart of the install -method: +Undo the agent setup and sign out first, then remove the binary with the +counterpart of the install method: ```sh +frbit setup agent --remove # MCP server, skill and sign-in 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 mcp remove` and `frbit skills remove` undo `frbit setup agent`. The +`frbit setup agent --remove` undoes `frbit setup agent`; `frbit mcp remove` and +`frbit skills remove` undo one half each. The [uninstall guide](https://docs.fortrabbit.com/platform/automation/cli#uninstall) covers the config and cache files that stay behind. diff --git a/docs/cli.md b/docs/cli.md index 4dda55f..d3ee5f5 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -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 stays in place, and the plugin is left to `claude plugin uninstall`: + +```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,7 @@ 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 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/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/setup/setup.go b/internal/cmd/setup/setup.go index a99939b..d9f0a65 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,6 +20,8 @@ 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) } @@ -24,6 +29,8 @@ 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 +57,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 +74,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 +117,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 +176,115 @@ func printSummary( } return cmdutil.PrintOAuthHints(writer, agents) } + +const ( + claudePluginRemoveNotice = "Claude Code: the fortrabbit plugin brings the skill and the MCP server; remove it with `claude plugin uninstall fortrabbit@fortrabbit`." + disconnectHint = "Revoke the MCP grants in the dashboard: https://dash.fortrabbit.com/you/ai-agents" + binaryHint = "Remove the frbit binary: https://docs.fortrabbit.com/platform/automation/cli#uninstall" +) + +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 + } + } + + var registrations []agentmcp.Registration + var removals []agentskills.Removal + // An empty agent list means all agents to the skills service, so skip both lookups. + if len(agents) > 0 { + var err error + if registrations, err = mcp.Inspect(cmd.Context(), agents); err != nil { + return err + } + if removals, err = skills.Removals(false, agents); err != nil { + return err + } + } + var registered []agent.Agent + for _, registration := range registrations { + if registration.Installed { + registered = append(registered, registration.Agent) + } + } + profile, err := cmdutil.Profile(cmd) + if err != nil { + return err + } + _, credentialErr := factory.CredentialStore.Get(profile) + if credentialErr != nil && !errors.Is(credentialErr, credentials.ErrNotFound) { + return credentialErr + } + signedIn := credentialErr == nil + + if len(registered) == 0 && len(removals) == 0 && !signedIn { + _, 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 + } + for _, registration := range 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 removals { + if _, err := fmt.Fprintf(writer, " %-14s skill at %s\n", removal.Agent.Label()+":", removal.Path); err != nil { + return err + } + } + if signedIn { + if _, err := fmt.Fprintf(writer, " %-14s sign-in of profile %q\n", "frbit CLI:", profile); err != nil { + return err + } + } + if !yes { + confirmed, err := cmdutil.Confirm(factory.IOStreams.In, writer, "Continue? [y/N] ") + if err != nil { + return err + } + if !confirmed { + _, err := fmt.Fprintln(writer, "Aborted.") + return err + } + } + + if len(registered) > 0 { + results, err := mcp.Remove(cmd.Context(), 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(removals); err != nil { + return err + } + for _, removal := range removals { + if _, err := fmt.Fprintf(writer, "Removed %s\n", removal.Path); err != nil { + return err + } + } + if signedIn { + if err := logout.Run(factory, cmd); err != nil { + return err + } + } + + _, err = fmt.Fprintf(writer, "Agent setup removed.\n\n%s\n%s\n", disconnectHint, binaryHint) + return err +} diff --git a/internal/cmd/setup/setup_test.go b/internal/cmd/setup/setup_test.go index 754ee43..c456578 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" @@ -19,6 +20,8 @@ import ( type fakeMCPService struct { preflighted []agent.Agent installed []agent.Agent + registered []agent.Agent + removed []agent.Agent claudePlugin bool } @@ -53,7 +56,22 @@ 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 +} + +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 +90,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 +198,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, binaryHint} { + 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) + } +} From a65b75cab8ab6781cece12d6a46894ab6c5ef6f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frank=20La=CC=88mmer?= Date: Wed, 28 Oct 2026 20:38:37 +0100 Subject: [PATCH 2/5] MR-496: Add frbit uninstall Removes the agent setup, the Claude Code plugin, the sign-in, the config and cache folders and the binary in one command, after one confirmation. Homebrew and npm installs go through brew and npm; Windows gets the path to delete, since a running executable stays locked there. Co-Authored-By: Claude Opus 5.5 --- README.md | 19 ++- docs/cli.md | 7 +- internal/agentmcp/service.go | 29 +++- internal/agentmcp/service_test.go | 22 +++ internal/cmd/root/root.go | 1 + internal/cmd/setup/setup.go | 143 +++++++++++------- internal/cmd/setup/setup_test.go | 24 +++- internal/cmd/setup/uninstall.go | 207 +++++++++++++++++++++++++++ internal/cmd/setup/uninstall_test.go | 143 ++++++++++++++++++ 9 files changed, 516 insertions(+), 79 deletions(-) create mode 100644 internal/cmd/setup/uninstall.go create mode 100644 internal/cmd/setup/uninstall_test.go diff --git a/README.md b/README.md index f37ae5f..e7d2da7 100644 --- a/README.md +++ b/README.md @@ -89,21 +89,18 @@ just test ## Uninstall -Undo the agent setup and 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 setup agent --remove # MCP server, skill and sign-in -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 setup agent --remove` undoes `frbit setup agent`; `frbit mcp remove` and -`frbit skills remove` undo one half each. 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 d3ee5f5..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 @@ -368,7 +368,7 @@ When Claude Code has the fortrabbit plugin enabled, `setup agent` and 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 stays in place, and the plugin is left to `claude plugin uninstall`: +binary and the plugin stay; `frbit uninstall` removes them as well: ```sh frbit setup agent --remove @@ -484,6 +484,7 @@ 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 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. | diff --git a/internal/agentmcp/service.go b/internal/agentmcp/service.go index 1c7553f..00870bb 100644 --- a/internal/agentmcp/service.go +++ b/internal/agentmcp/service.go @@ -127,11 +127,16 @@ 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 { + return s.ClaudePluginID(ctx) != "" +} + +// ClaudePluginID returns the enabled fortrabbit plugin as name@marketplace, or "" without one. +// A Claude Code without plugin support, or output that does not parse, counts as no plugin. +func (s *Service) ClaudePluginID(ctx context.Context) string { output, err := s.runner.Run(ctx, "claude", "plugin", "list", "--json") if err != nil { - return false + return "" } if start := strings.Index(output, "["); start > 0 { output = output[start:] @@ -141,15 +146,29 @@ func (s *Service) claudePluginEnabled(ctx context.Context) bool { Enabled bool `json:"enabled"` } if json.Unmarshal([]byte(output), &plugins) != nil { - return false + return "" } for _, plugin := range plugins { name, _, _ := strings.Cut(plugin.ID, "@") if plugin.Enabled && name == ClaudePluginName { - return true + return plugin.ID } } - return false + return "" +} + +// RemoveClaudePlugin uninstalls the plugin, and the fortrabbit marketplace it came from. +// Another marketplace, such as the official one, carries other plugins and stays. +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..a9acd68 100644 --- a/internal/agentmcp/service_test.go +++ b/internal/agentmcp/service_test.go @@ -163,3 +163,25 @@ 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) + } +} 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 d9f0a65..106a70c 100644 --- a/internal/cmd/setup/setup.go +++ b/internal/cmd/setup/setup.go @@ -23,6 +23,8 @@ type mcpService interface { 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 { @@ -178,60 +180,56 @@ func printSummary( } const ( - claudePluginRemoveNotice = "Claude Code: the fortrabbit plugin brings the skill and the MCP server; remove it with `claude plugin uninstall fortrabbit@fortrabbit`." + 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" - binaryHint = "Remove the frbit binary: https://docs.fortrabbit.com/platform/automation/cli#uninstall" + uninstallHint = "Remove the frbit CLI as well: frbit uninstall" ) -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 - } - } +// 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 +} - var registrations []agentmcp.Registration - var removals []agentskills.Removal +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 registrations, err = mcp.Inspect(cmd.Context(), agents); err != nil { - return err + if plan.registrations, err = mcp.Inspect(cmd.Context(), agents); err != nil { + return plan, err } - if removals, err = skills.Removals(false, agents); err != nil { - return err + if plan.removals, err = skills.Removals(false, agents); err != nil { + return plan, err } } - var registered []agent.Agent - for _, registration := range registrations { + for _, registration := range plan.registrations { if registration.Installed { - registered = append(registered, registration.Agent) + plan.registered = append(plan.registered, registration.Agent) } } profile, err := cmdutil.Profile(cmd) if err != nil { - return err + return plan, err } + plan.profile = profile _, credentialErr := factory.CredentialStore.Get(profile) if credentialErr != nil && !errors.Is(credentialErr, credentials.ErrNotFound) { - return credentialErr + return plan, credentialErr } - signedIn := credentialErr == nil + plan.signedIn = credentialErr == nil + return plan, nil +} - if len(registered) == 0 && len(removals) == 0 && !signedIn { - _, err := fmt.Fprintln(writer, "Nothing to remove: no fortrabbit MCP server, skill or sign-in found.") - return err - } +func (p removalPlan) empty() bool { + return len(p.registered) == 0 && len(p.removals) == 0 && !p.signedIn +} - if _, err := fmt.Fprintln(writer, "This removes:"); err != nil { - return err - } - for _, registration := range registrations { +func (p removalPlan) print(writer io.Writer) error { + for _, registration := range p.registrations { if !registration.Installed { continue } @@ -239,29 +237,23 @@ func removeAgentSetup(cmd *cobra.Command, factory *app.Factory, mcp mcpService, return err } } - for _, removal := range removals { + 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 signedIn { - if _, err := fmt.Fprintf(writer, " %-14s sign-in of profile %q\n", "frbit CLI:", profile); err != nil { - return err - } - } - if !yes { - confirmed, err := cmdutil.Confirm(factory.IOStreams.In, writer, "Continue? [y/N] ") - if err != nil { - return err - } - if !confirmed { - _, err := fmt.Fprintln(writer, "Aborted.") + 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 +} - if len(registered) > 0 { - results, err := mcp.Remove(cmd.Context(), registered) +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 } @@ -271,20 +263,63 @@ func removeAgentSetup(cmd *cobra.Command, factory *app.Factory, mcp mcpService, } } } - if err := skills.Remove(removals); err != nil { + if err := skills.Remove(p.removals); err != nil { return err } - for _, removal := range removals { + for _, removal := range p.removals { if _, err := fmt.Fprintf(writer, "Removed %s\n", removal.Path); err != nil { return err } } - if signedIn { - if err := logout.Run(factory, cmd); err != nil { + 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 } } - - _, err = fmt.Fprintf(writer, "Agent setup removed.\n\n%s\n%s\n", disconnectHint, binaryHint) + 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 c456578..d43411e 100644 --- a/internal/cmd/setup/setup_test.go +++ b/internal/cmd/setup/setup_test.go @@ -18,11 +18,12 @@ import ( ) type fakeMCPService struct { - preflighted []agent.Agent - installed []agent.Agent - registered []agent.Agent - removed []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) { @@ -68,6 +69,17 @@ func (s *fakeMCPService) Remove(_ context.Context, agents []agent.Agent) ([]agen 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 @@ -239,7 +251,7 @@ func TestAgentRemoveUndoesTheSetup(t *testing.T) { 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, binaryHint} { + 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) } diff --git a/internal/cmd/setup/uninstall.go b/internal/cmd/setup/uninstall.go new file mode 100644 index 0000000..bcfbda6 --- /dev/null +++ b/internal/cmd/setup/uninstall.go @@ -0,0 +1,207 @@ +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() + // Without Claude Code or Codex there is no agent setup to undo, only the CLI itself. + agents, err := mcp.ResolveAgents(nil) + if err != nil { + agents = 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 + } + 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 + } + } + finalStep, err := removeBinary(cmd.Context(), system, binary) + if err != nil { + return err + } + if _, err := fmt.Fprintf(writer, "frbit uninstalled.\n\n%s\n", disconnectHint); err != nil { + return err + } + if finalStep != "" { + _, err = fmt.Fprintln(writer, finalStep) + } + 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) + } + if resolved, err := filepath.EvalSymlinks(path); err == nil { + path = resolved + } + slashed := filepath.ToSlash(path) + 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) { + 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)) + } + return "", nil + } + // Windows keeps a running executable locked. + if system.goos == "windows" { + return fmt.Sprintf("Delete %s to finish.", binary.path), 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..d0d5f86 --- /dev/null +++ b/internal/cmd/setup/uninstall_test.go @@ -0,0 +1,143 @@ +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 +} + +func (r *recordingRunner) Run(_ context.Context, name string, args ...string) (string, error) { + r.calls = append(r.calls, strings.Join(append([]string{name}, args...), " ")) + 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, "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.run(t, "", &fakeMCPService{}, fakeSkillsService{}, "darwin", "--yes") + if !reflect.DeepEqual(fixture.runner.calls, []string{want}) { + t.Fatalf("calls = %#v, want %q", fixture.runner.calls, want) + } + if !exists(fixture.binary) { + t.Fatalf("%s was deleted by hand", fixture.binary) + } + } +} + +func TestUninstallLeavesTheRunningBinaryToWindowsUsers(t *testing.T) { + fixture := newUninstallFixture(t, "frbit.exe") + output := fixture.run(t, "", &fakeMCPService{}, fakeSkillsService{}, "windows", "--yes") + if !strings.Contains(output, "Delete "+fixture.binary+" to finish.") || !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) + } +} From 8938026207e73a2e111171a71e8f80a8b7cf8fef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frank=20La=CC=88mmer?= Date: Wed, 28 Oct 2026 20:41:06 +0100 Subject: [PATCH 3/5] MR-496: Harden frbit uninstall Removes the binary first, so a failing brew or npm leaves the rest for a retry. Windows gets the brew or npm command to run, as the running executable stays locked there. A disabled plugin is removed too, and skill folders are found without the agent CLI on PATH. Co-Authored-By: Claude Opus 5.5 --- internal/agentmcp/service.go | 25 ++++++++++++-------- internal/agentmcp/service_test.go | 7 ++++++ internal/cmd/setup/uninstall.go | 35 +++++++++++++++++----------- internal/cmd/setup/uninstall_test.go | 8 +++++++ 4 files changed, 52 insertions(+), 23 deletions(-) diff --git a/internal/agentmcp/service.go b/internal/agentmcp/service.go index 00870bb..201570d 100644 --- a/internal/agentmcp/service.go +++ b/internal/agentmcp/service.go @@ -128,15 +128,21 @@ func (s *Service) WithoutClaudePlugin(ctx context.Context, agents []agent.Agent) } func (s *Service) claudePluginEnabled(ctx context.Context) bool { - return s.ClaudePluginID(ctx) != "" + _, enabled := s.claudePlugin(ctx) + return enabled } -// ClaudePluginID returns the enabled fortrabbit plugin as name@marketplace, or "" without one. -// A Claude Code without plugin support, or output that does not parse, counts as no plugin. +// 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 "" + return "", false } if start := strings.Index(output, "["); start > 0 { output = output[start:] @@ -146,19 +152,18 @@ func (s *Service) ClaudePluginID(ctx context.Context) string { Enabled bool `json:"enabled"` } if json.Unmarshal([]byte(output), &plugins) != nil { - return "" + return "", false } for _, plugin := range plugins { name, _, _ := strings.Cut(plugin.ID, "@") - if plugin.Enabled && name == ClaudePluginName { - return plugin.ID + if name == ClaudePluginName { + return plugin.ID, plugin.Enabled } } - return "" + return "", false } -// RemoveClaudePlugin uninstalls the plugin, and the fortrabbit marketplace it came from. -// Another marketplace, such as the official one, carries other plugins and stays. +// 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)) diff --git a/internal/agentmcp/service_test.go b/internal/agentmcp/service_test.go index a9acd68..746e306 100644 --- a/internal/agentmcp/service_test.go +++ b/internal/agentmcp/service_test.go @@ -185,3 +185,10 @@ func TestClaudePluginIDKeepsTheMarketplace(t *testing.T) { 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/setup/uninstall.go b/internal/cmd/setup/uninstall.go index bcfbda6..57cfe42 100644 --- a/internal/cmd/setup/uninstall.go +++ b/internal/cmd/setup/uninstall.go @@ -70,11 +70,7 @@ Lists everything first and asks once. Apps, environments and the account stay.`, func runUninstall(cmd *cobra.Command, factory *app.Factory, mcp mcpService, skills skillsService, system uninstallSystem, yes bool) error { writer := cmd.OutOrStdout() - // Without Claude Code or Codex there is no agent setup to undo, only the CLI itself. - agents, err := mcp.ResolveAgents(nil) - if err != nil { - agents = nil - } + agents, resolveErr := mcp.ResolveAgents(nil) pluginID := "" if slices.Contains(agents, agent.ClaudeCode) { pluginID = mcp.ClaudePluginID(cmd.Context()) @@ -83,6 +79,15 @@ func runUninstall(cmd *cobra.Command, factory *app.Factory, mcp mcpService, skil if err != nil { return err } + // MCP entries need the agent CLI, skill folders do not: look for those regardless. + if resolveErr != nil { + if _, err := fmt.Fprintf(writer, "MCP entries skipped: %v\n", resolveErr); err != nil { + return err + } + 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 { @@ -112,6 +117,11 @@ func runUninstall(cmd *cobra.Command, factory *app.Factory, mcp mcpService, skil return err } + // The binary goes first: a failing brew or npm then leaves the rest in place for a retry. + finalStep, err := removeBinary(cmd.Context(), system, binary) + if err != nil { + return err + } if err := plan.execute(cmd, factory, mcp, skills); err != nil { return err } @@ -131,10 +141,6 @@ func runUninstall(cmd *cobra.Command, factory *app.Factory, mcp mcpService, skil return err } } - finalStep, err := removeBinary(cmd.Context(), system, binary) - if err != nil { - return err - } if _, err := fmt.Fprintf(writer, "frbit uninstalled.\n\n%s\n", disconnectHint); err != nil { return err } @@ -190,16 +196,19 @@ func printBinary(writer io.Writer, binary binaryRemoval) error { // 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("Run %s to finish.", strings.Join(binary.command, " ")), nil + } + return fmt.Sprintf("Delete %s to finish.", 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)) } return "", nil } - // Windows keeps a running executable locked. - if system.goos == "windows" { - return fmt.Sprintf("Delete %s to finish.", binary.path), nil - } if err := os.Remove(binary.path); err != nil && !errors.Is(err, os.ErrNotExist) { return "", fmt.Errorf("remove %s: %w", binary.path, err) } diff --git a/internal/cmd/setup/uninstall_test.go b/internal/cmd/setup/uninstall_test.go index d0d5f86..1789e86 100644 --- a/internal/cmd/setup/uninstall_test.go +++ b/internal/cmd/setup/uninstall_test.go @@ -141,3 +141,11 @@ func TestUninstallAbortsWithoutConfirmation(t *testing.T) { 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, "Run npm uninstall --global @fortrabbit/cli to finish.") || len(fixture.runner.calls) != 0 { + t.Fatalf("output = %q, calls = %#v", output, fixture.runner.calls) + } +} From 7ba7a88d454bdf31b610e3ad2d185abb4226e82a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frank=20La=CC=88mmer?= Date: Wed, 28 Oct 2026 20:55:44 +0100 Subject: [PATCH 4/5] MR-496: Confirm the binary removal in frbit uninstall Co-Authored-By: Claude Opus 5.5 --- internal/cmd/setup/uninstall.go | 5 +++++ internal/cmd/setup/uninstall_test.go | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/internal/cmd/setup/uninstall.go b/internal/cmd/setup/uninstall.go index 57cfe42..c24ae19 100644 --- a/internal/cmd/setup/uninstall.go +++ b/internal/cmd/setup/uninstall.go @@ -122,6 +122,11 @@ func runUninstall(cmd *cobra.Command, factory *app.Factory, mcp mcpService, skil if err != nil { return err } + if finalStep == "" { + if _, err := fmt.Fprintf(writer, "Removed %s\n", binary.path); err != nil { + return err + } + } if err := plan.execute(cmd, factory, mcp, skills); err != nil { return err } diff --git a/internal/cmd/setup/uninstall_test.go b/internal/cmd/setup/uninstall_test.go index 1789e86..e67b0fd 100644 --- a/internal/cmd/setup/uninstall_test.go +++ b/internal/cmd/setup/uninstall_test.go @@ -94,7 +94,7 @@ func TestUninstallRemovesEverything(t *testing.T) { 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, "frbit uninstalled.", disconnectHint} { + 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) } From 7a7a1b5a94ac64bd7289b77ca5e3ffa5eed92720 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frank=20La=CC=88mmer?= Date: Wed, 28 Oct 2026 21:01:34 +0100 Subject: [PATCH 5/5] MR-496: Remove the binary last in frbit uninstall A failure in any earlier step now leaves frbit in place to run again. The binary is checked after brew or npm, since npm succeeds on a pnpm, yarn or bun install it does not own. A symlink on PATH is removed without its target. Skill folders are looked up for every agent, and Windows reports the step left instead of claiming success. Co-Authored-By: Claude Opus 5.5 --- internal/cmd/setup/uninstall.go | 42 ++++++++++---------- internal/cmd/setup/uninstall_test.go | 58 +++++++++++++++++++++++++--- 2 files changed, 73 insertions(+), 27 deletions(-) diff --git a/internal/cmd/setup/uninstall.go b/internal/cmd/setup/uninstall.go index c24ae19..a3f3b94 100644 --- a/internal/cmd/setup/uninstall.go +++ b/internal/cmd/setup/uninstall.go @@ -79,14 +79,14 @@ func runUninstall(cmd *cobra.Command, factory *app.Factory, mcp mcpService, skil if err != nil { return err } - // MCP entries need the agent CLI, skill folders do not: look for those regardless. if resolveErr != nil { if _, err := fmt.Fprintf(writer, "MCP entries skipped: %v\n", resolveErr); err != nil { return err } - if plan.removals, err = skills.Removals(false, []agent.Agent{agent.ClaudeCode, agent.Codex}); 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) @@ -117,16 +117,6 @@ func runUninstall(cmd *cobra.Command, factory *app.Factory, mcp mcpService, skil return err } - // The binary goes first: a failing brew or npm then leaves the rest in place for a retry. - finalStep, err := removeBinary(cmd.Context(), system, binary) - if err != nil { - return err - } - if finalStep == "" { - if _, err := fmt.Fprintf(writer, "Removed %s\n", binary.path); err != nil { - return err - } - } if err := plan.execute(cmd, factory, mcp, skills); err != nil { return err } @@ -146,12 +136,16 @@ func runUninstall(cmd *cobra.Command, factory *app.Factory, mcp mcpService, skil return err } } - if _, err := fmt.Fprintf(writer, "frbit uninstalled.\n\n%s\n", disconnectHint); err != nil { + // 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.Fprintln(writer, 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 } @@ -177,10 +171,12 @@ func locateBinary(executable func() (string, error)) (binaryRemoval, error) { if err != nil { return binaryRemoval{}, fmt.Errorf("find the frbit binary: %w", err) } - if resolved, err := filepath.EvalSymlinks(path); err == nil { - path = resolved + // 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(path) + slashed := filepath.ToSlash(resolved) switch { case strings.Contains(slashed, "/Cellar/frbit/"): return binaryRemoval{path: path, command: []string{"brew", "uninstall", "frbit"}}, nil @@ -204,14 +200,18 @@ func removeBinary(ctx context.Context, system uninstallSystem, binary binaryRemo // Windows keeps a running executable locked, also for brew or npm. if system.goos == "windows" { if binary.command != nil { - return fmt.Sprintf("Run %s to finish.", strings.Join(binary.command, " ")), nil + return fmt.Sprintf("One step left: run %s.", strings.Join(binary.command, " ")), nil } - return fmt.Sprintf("Delete %s to finish.", binary.path), 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) { diff --git a/internal/cmd/setup/uninstall_test.go b/internal/cmd/setup/uninstall_test.go index e67b0fd..e29e612 100644 --- a/internal/cmd/setup/uninstall_test.go +++ b/internal/cmd/setup/uninstall_test.go @@ -17,11 +17,16 @@ import ( ) type recordingRunner struct { - calls []string + 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 } @@ -115,20 +120,18 @@ func TestUninstallUsesThePackageManager(t *testing.T) { "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) } - if !exists(fixture.binary) { - t.Fatalf("%s was deleted by hand", fixture.binary) - } } } func TestUninstallLeavesTheRunningBinaryToWindowsUsers(t *testing.T) { fixture := newUninstallFixture(t, "frbit.exe") output := fixture.run(t, "", &fakeMCPService{}, fakeSkillsService{}, "windows", "--yes") - if !strings.Contains(output, "Delete "+fixture.binary+" to finish.") || !exists(fixture.binary) { + if !strings.Contains(output, "One step left: delete "+fixture.binary+".") || !exists(fixture.binary) { t.Fatalf("output = %q", output) } } @@ -145,7 +148,50 @@ func TestUninstallAbortsWithoutConfirmation(t *testing.T) { 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, "Run npm uninstall --global @fortrabbit/cli to finish.") || len(fixture.runner.calls) != 0 { + 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)) + } +}