From 7599056760494e96c34351915501030c051f9648 Mon Sep 17 00:00:00 2001 From: iliya Date: Tue, 17 Nov 2026 02:55:09 +0200 Subject: [PATCH 1/5] fix(install): resume Claude project native calls after an interrupt Ctrl+C or SIGTERM during any of the four Claude Code project calls (plugin marketplace add, plugin install, plugin uninstall, plugin marketplace remove) left the binding with a native activation attempt and no persisted intent. Every later add, update, repair and remove was refused for good, doctor showed no open recovery and suggested commands that were refused as well. When such a call fails and its process tree was reaped, the Claude adapter now reads Claude's own registry once more in a short context detached from the cancellation. An exact install or any state the next install or removal accepts (registration, installation index and owned cache all verified) becomes a certain effect, so the attempt is closed and the same command continues. A partial removal is reported as settled progress: the core keeps the recorded ownership, marks the binding failed and clears the attempt. A child whose cleanup is not proven, a failed re-read or an unrecognized state keep the attempt blocked as before; a CLI killed with SIGKILL stays blocked too. The install preflight also accepts the owned cache Claude marks orphaned on uninstall, so an update interrupted between uninstall and install resumes. Doctor now counts an unresolved native attempt as an open recovery operation and stops suggesting commands that refuse it. --- cli/cmd/agentplugins/main.go | 4 +- cli/internal/agentpluginscli/cli_test.go | 6 +- .../project_claude_interrupt_test.go | 150 ++++++++++++++++++ .../project_claude_prepared_update_test.go | 70 +++++--- cli/internal/agentpluginscli/read.go | 31 +++- .../claude/project_marketplace_lifecycle.go | 88 ++++++---- .../project_marketplace_observation_test.go | 9 +- .../claude/project_marketplace_orphan.go | 12 +- .../claude/project_marketplace_settle.go | 83 ++++++++++ .../agentplugins/domain/clients_runtime.go | 16 +- .../usecase/native_remove_attempt.go | 59 ++++++- .../usecase/remove_group_native.go | 2 +- .../agentplugins/usecase/remove_session.go | 2 +- 13 files changed, 458 insertions(+), 74 deletions(-) create mode 100644 cli/internal/agentpluginscli/project_claude_interrupt_test.go create mode 100644 install/integrationctl/agentplugins/clients/claude/project_marketplace_settle.go diff --git a/cli/cmd/agentplugins/main.go b/cli/cmd/agentplugins/main.go index 9f3ba2ffb7..aef50741d0 100644 --- a/cli/cmd/agentplugins/main.go +++ b/cli/cmd/agentplugins/main.go @@ -110,7 +110,9 @@ func run() error { } } if err != nil && ctx.Err() != nil { - err = fmt.Errorf("%w\ninterrupted: run the same command again to resume", err) + // A client change the installer could not confirm is never resumed blindly; + // doctor reports it as an open recovery operation instead. + err = fmt.Errorf("%w\ninterrupted: run the same command again to resume; `agentplugins doctor` lists anything it cannot resume", err) } return err } diff --git a/cli/internal/agentpluginscli/cli_test.go b/cli/internal/agentpluginscli/cli_test.go index e291cf8f34..d90b992c99 100644 --- a/cli/internal/agentpluginscli/cli_test.go +++ b/cli/internal/agentpluginscli/cli_test.go @@ -3195,6 +3195,10 @@ func (fixture cliFixture) execute(terminal bool, args ...string) (string, string } func (fixture cliFixture) executeInput(terminal bool, input string, args ...string) (string, string, error) { + return fixture.executeContext(context.Background(), terminal, input, args...) +} + +func (fixture cliFixture) executeContext(ctx context.Context, terminal bool, input string, args ...string) (string, string, error) { var stdout, stderr bytes.Buffer app := fixture.app app.Input = strings.NewReader(input) @@ -3203,7 +3207,7 @@ func (fixture cliFixture) executeInput(terminal bool, input string, args ...stri app.Terminal = terminal command := NewRoot(app) command.SetArgs(args) - err := command.ExecuteContext(context.Background()) + err := command.ExecuteContext(ctx) return stdout.String(), stderr.String(), err } diff --git a/cli/internal/agentpluginscli/project_claude_interrupt_test.go b/cli/internal/agentpluginscli/project_claude_interrupt_test.go new file mode 100644 index 0000000000..37d97fb864 --- /dev/null +++ b/cli/internal/agentpluginscli/project_claude_interrupt_test.go @@ -0,0 +1,150 @@ +package agentpluginscli + +import ( + "context" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + legacyports "github.com/777genius/plugin-kit-ai/install/integrationctl/ports" +) + +// claudeCLIInterrupt models Ctrl+C or SIGTERM arriving while one native Claude +// command runs: the command context is canceled and the child is stopped +// either before its effect or just after the effect already landed. +type claudeCLIInterrupt struct { + args []string + landed bool + // unclosed reports a child whose process-tree cleanup was not proven. + unclosed bool + cancel context.CancelFunc +} + +func (i *claudeCLIInterrupt) matches(args []string) bool { + return i != nil && len(args) >= len(i.args) && reflect.DeepEqual(args[:len(i.args)], i.args) +} + +func (i *claudeCLIInterrupt) fire(r *preparedClaudeCLIRunner, args []string) (legacyports.CommandResult, error) { + if i.landed { + if _, err := r.marketplaceCommand(args); err != nil { + r.t.Fatal(err) + } + } + i.cancel() + return legacyports.CommandResult{CleanupComplete: !i.unclosed}, context.Canceled +} + +func (fixture projectClaudeCLI) runProject(ctx context.Context, args ...string) (string, error) { + args = append(args, "--target", "claude", "--scope", "project", "--project-root", fixture.project, "--yes", "--format", "json") + stdout, stderr, err := fixture.executeContext(ctx, false, "", args...) + return stdout + stderr, err +} + +// nativeAttempt returns the retained native attempt marker of the only binding. +func (fixture projectClaudeCLI) nativeAttempt(t *testing.T) (string, bool) { + t.Helper() + state, err := fixture.store.Load() + if err != nil { + t.Fatal(err) + } + for _, installation := range state.Installations { + for _, binding := range installation.Clients { + return binding.NativeActivationAttempt, true + } + } + return "", false +} + +func (fixture projectClaudeCLI) knownMarketplaces(t *testing.T) int { + t.Helper() + return len(fixture.runner.readObject(filepath.Join(fixture.client.ConfigRoot, "plugins", "known_marketplaces.json"))) +} + +// An interrupted native Claude command must not strand the project binding +// behind an unresolved attempt: the same command converges afterwards. +func TestProjectClaudeInterruptedNativeCommandResumesWithSameCommand(t *testing.T) { + for _, tc := range []struct { + name, command string + args []string + landed bool + }{ + {"add/marketplace-add", "add", []string{"plugin", "marketplace", "add"}, false}, + {"add/install-landed", "add", []string{"plugin", "install"}, true}, + {"update/uninstall-landed", "update", []string{"plugin", "uninstall"}, true}, + {"update/install", "update", []string{"plugin", "install"}, false}, + {"remove/uninstall", "remove", []string{"plugin", "uninstall"}, false}, + {"remove/uninstall-landed", "remove", []string{"plugin", "uninstall"}, true}, + {"remove/marketplace-remove-landed", "remove", []string{"plugin", "marketplace", "remove"}, true}, + } { + t.Run(tc.name, func(t *testing.T) { + fixture, args := interruptedProjectClaudeCommand(t, tc.command, &claudeCLIInterrupt{args: tc.args, landed: tc.landed}) + if attempt, _ := fixture.nativeAttempt(t); attempt != "" { + t.Fatalf("closed interrupted command retained native attempt %s", attempt) + } + if out, err := fixture.runProject(context.Background(), args...); err != nil { + t.Fatalf("same command did not resume: %v\n%s", err, out) + } + listed := len(fixture.runner.marketplaceListing()) + attempt, bound := fixture.nativeAttempt(t) + if tc.command == "remove" && (bound || listed != 0 || fixture.knownMarketplaces(t) != 0) || + tc.command != "remove" && (!bound || attempt != "" || listed != 1) { + t.Fatalf("resumed %s did not converge: bound=%v attempt=%q listed=%d", tc.command, bound, attempt, listed) + } + }) + } +} + +// A child whose cleanup is not proven may still be writing. Its attempt stays +// unresolved and blocks blind retry, exactly as before. +func TestProjectClaudeUnclosedInterruptedCommandKeepsAttempt(t *testing.T) { + fixture, args := interruptedProjectClaudeCommand(t, "add", &claudeCLIInterrupt{args: []string{"plugin", "install"}, unclosed: true}) + attempt, _ := fixture.nativeAttempt(t) + if attempt == "" { + t.Fatal("unclosed native command was resolved without proof") + } + out, err := fixture.runProject(context.Background(), args...) + if err == nil || !strings.Contains(out+err.Error(), attempt) { + t.Fatalf("retry ignored the unresolved attempt: %v\n%s", err, out) + } + // Doctor reports the open attempt and suggests no command that refuses it. + doctor, _, err := fixture.execute(false, "doctor", "--target", "claude", "--scope", "project", "--project-root", fixture.project, "--format", "json") + if err != nil || !strings.Contains(doctor, `"open_operation_count":1`) || !strings.Contains(doctor, "native_attempt_unresolved") || strings.Contains(doctor, "rerun the same") { + t.Fatalf("doctor misreported the unresolved attempt: %v\n%s", err, doctor) + } +} + +// interruptedProjectClaudeCommand prepares the binding for command, then runs +// it once with interrupt armed and returns the command for the retry. +func interruptedProjectClaudeCommand(t *testing.T, command string, interrupt *claudeCLIInterrupt) (projectClaudeCLI, []string) { + t.Helper() + fixture := newProjectClaudeCLI(t) + pkg := writeCLIPlugin(t) + skill := filepath.Join(pkg, "skills", "guide", "SKILL.md") + writeSkill := func(marker string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(skill), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(skill, []byte("---\nname: guide\ndescription: Inert marker\n---\n"+marker+"\n"), 0600); err != nil { + t.Fatal(err) + } + } + writeSkill("version one") + args := map[string][]string{"add": {"add", pkg, "--no-save"}, "update": {"update", "demo"}, "remove": {"remove", "demo"}}[command] + if command != "add" { + if out, err := fixture.runProject(context.Background(), "add", pkg, "--no-save"); err != nil { + t.Fatalf("initial add: %v\n%s", err, out) + } + writeSkill("version two") + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + interrupt.cancel = cancel + fixture.runner.interrupt = interrupt + if out, err := fixture.runProject(ctx, args...); err == nil || fixture.runner.interrupt != nil { + t.Fatalf("interrupted %s was not interrupted: %v\n%s", command, err, out) + } + return fixture, args +} diff --git a/cli/internal/agentpluginscli/project_claude_prepared_update_test.go b/cli/internal/agentpluginscli/project_claude_prepared_update_test.go index c3be9916ed..f41439f385 100644 --- a/cli/internal/agentpluginscli/project_claude_prepared_update_test.go +++ b/cli/internal/agentpluginscli/project_claude_prepared_update_test.go @@ -26,6 +26,8 @@ type preparedClaudeCLIRunner struct { t *testing.T project, user, executable string calls, mutations int + // interrupt, when set, fires once on the first matching native mutation. + interrupt *claudeCLIInterrupt } func (r *preparedClaudeCLIRunner) Run(_ context.Context, cmd legacyports.Command) (legacyports.CommandResult, error) { @@ -44,6 +46,11 @@ func (r *preparedClaudeCLIRunner) Run(_ context.Context, cmd legacyports.Command } r.calls++ if !reflect.DeepEqual(cmd.Argv[1:], []string{"plugin", "list", "--json"}) { + if r.interrupt.matches(cmd.Argv[1:]) { + interrupt := r.interrupt + r.interrupt = nil + return interrupt.fire(r, cmd.Argv[1:]) + } return r.marketplaceCommand(cmd.Argv[1:]) } if listed := r.marketplaceListing(); len(listed) != 0 { @@ -71,10 +78,18 @@ func (r *preparedClaudeCLIRunner) Run(_ context.Context, cmd legacyports.Command return legacyports.CommandResult{Stdout: []byte(`[{"id":"(suppressed)@skills-dir","version":"unknown","scope":"project","enabled":false,"installPath":"","notes":["1 project-scope directory under ./.claude/skills/ that may load as a plugin was skipped because this workspace was not trusted when plugins were scanned. After accepting the trust dialog, run /reload-plugins (or relaunch) to load what qualifies."]}]`)}, nil } -// The public saved-binding update command uses grouped activation even for one -// target. The runner models the observed native marketplace files and commands; -// real executable evidence is retained separately. -func TestProjectClaudePreparedCLIGroupedUpdateReportsActualMutation(t *testing.T) { +// projectClaudeCLI is the public CLI composed for one Claude Code project +// whose native marketplace commands are modeled by preparedClaudeCLIRunner. +type projectClaudeCLI struct { + cliFixture + client domain.DetectedClient + project string + userState string + runner *preparedClaudeCLIRunner +} + +func newProjectClaudeCLI(t *testing.T) projectClaudeCLI { + t.Helper() client := fixtureClient(t, domain.ClientClaude) f := newCLIFixture(t, []domain.DetectedClient{client}) physicalRoot, resolveErr := filepath.EvalSymlinks(f.root) @@ -83,8 +98,7 @@ func TestProjectClaudePreparedCLIGroupedUpdateReportsActualMutation(t *testing.T } f.root = physicalRoot project := filepath.Join(f.root, "A") - other := filepath.Join(f.root, "B") - for _, p := range []string{project, other, client.ConfigRoot} { + for _, p := range []string{project, client.ConfigRoot} { if err := os.MkdirAll(p, 0700); err != nil { t.Fatal(err) } @@ -95,21 +109,6 @@ func TestProjectClaudePreparedCLIGroupedUpdateReportsActualMutation(t *testing.T } f.app.Detector = staticDetector{clients: []domain.DetectedClient{client}} userState := f.store.Path - projectForeign := filepath.Join(project, ".claude", "settings.local.json") - for _, p := range []string{filepath.Join(client.ConfigRoot, "foreign.json"), filepath.Join(other, ".claude", "settings.local.json"), filepath.Join(other, ".uap", "state-v2.json"), userState, projectForeign} { - if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(p, []byte("preserve exact foreign bytes\n"), 0600); err != nil { - t.Fatal(err) - } - } - foreign := map[string]string{} - for _, p := range []string{client.ConfigRoot, other, userState, projectForeign} { - for name, body := range preparedClaudeCLIFiles(t, p) { - foreign[name] = body - } - } stateRoot := filepath.Join(project, ".uap") f.store = statev2.Store{Path: filepath.Join(stateRoot, "state-v2.json"), ProjectRoot: project} f.app.Scope, f.app.ProjectRoot = domain.ScopeProject, project @@ -125,6 +124,7 @@ func TestProjectClaudePreparedCLIGroupedUpdateReportsActualMutation(t *testing.T f.app.Lifecycle.Activator = providerstest.NewActivator(providers.Activator{Runner: runner}) f.app.Lifecycle.NativeObserver = providerstest.NewObserver(providers.NativeIdentityObserver{Runner: runner, Stager: f.app.Lifecycle.Stager}) f.app.Lifecycle.Lock = processlock.Lock{Path: filepath.Join(stateRoot, "mutation.lock")} + f.app.Lifecycle.PluginData = providers.PluginDataManager{Base: filepath.Join(stateRoot, "plugin-data")} f.app.Lifecycle.Kernel = transaction.Kernel{StateStore: f.store, Directory: dirswap.Manager{JournalDir: filepath.Join(stateRoot, "operations-v2")}} var err error f.app.Installer, err = installer.New(installer.Config{ProjectRoot: project, StateRoot: stateRoot, Registry: f.app.ClientRegistry, Runner: runner, HelperExecutable: client.ExecutablePath, EnableNativeObserver: true, TrustedLocalPackages: true}) @@ -132,6 +132,34 @@ func TestProjectClaudePreparedCLIGroupedUpdateReportsActualMutation(t *testing.T t.Fatal(err) } f.app.Lifecycle.CheckNamespace = f.app.Installer.CheckProjectNamespace + return projectClaudeCLI{cliFixture: f, client: client, project: project, userState: userState, runner: runner} +} + +// The public saved-binding update command uses grouped activation even for one +// target. The runner models the observed native marketplace files and commands; +// real executable evidence is retained separately. +func TestProjectClaudePreparedCLIGroupedUpdateReportsActualMutation(t *testing.T) { + fixture := newProjectClaudeCLI(t) + f, client, project, runner, userState := fixture.cliFixture, fixture.client, fixture.project, fixture.runner, fixture.userState + other := filepath.Join(f.root, "B") + if err := os.MkdirAll(other, 0700); err != nil { + t.Fatal(err) + } + projectForeign := filepath.Join(project, ".claude", "settings.local.json") + for _, p := range []string{filepath.Join(client.ConfigRoot, "foreign.json"), filepath.Join(other, ".claude", "settings.local.json"), filepath.Join(other, ".uap", "state-v2.json"), userState, projectForeign} { + if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte("preserve exact foreign bytes\n"), 0600); err != nil { + t.Fatal(err) + } + } + foreign := map[string]string{} + for _, p := range []string{client.ConfigRoot, other, userState, projectForeign} { + for name, body := range preparedClaudeCLIFiles(t, p) { + foreign[name] = body + } + } pkg := writeCLIPlugin(t) if err := os.MkdirAll(filepath.Join(pkg, "skills", "guide"), 0700); err != nil { t.Fatal(err) diff --git a/cli/internal/agentpluginscli/read.go b/cli/internal/agentpluginscli/read.go index 1b482242f5..8073e0fa67 100644 --- a/cli/internal/agentpluginscli/read.go +++ b/cli/internal/agentpluginscli/read.go @@ -64,7 +64,7 @@ func runDoctor(ctx context.Context, cmd *cobra.Command, app App, opts *options, ProjectReadiness []projectReadinessRecord `json:"project_readiness"` Findings []doctorFinding `json:"findings"` }{ReadOnly: true, ToolVersion: normalizedToolVersion(app.Version), SupportedClients: doctorSupportedClients(), Clients: publicClients, - InstallationCount: len(publicInstallations(state, false)), OpenOperationCount: len(open)} + InstallationCount: len(publicInstallations(state, false)), OpenOperationCount: len(open) + len(unresolvedNativeAttempts(state))} selected := (*domain.Installation)(nil) if len(args) == 1 { installation, err := selectInstallation(state, args[0]) @@ -203,6 +203,11 @@ func doctorFindings(ctx context.Context, app App, detected []domain.DetectedClie if !plansWithoutHostPresence(bindingClient) && (!visible || (client.Status != domain.DetectionDetected && client.DetectionError == nil)) { findings = append(findings, scopedFinding("degraded", "client_not_visible", installation, binding.ClientID, "the package is tracked but no current client visibility evidence was detected", "install or launch the client so its CLI, desktop application, or configuration directory is visible, then rerun doctor")) } + if unresolvedNativeAttempt(binding) { + // Every lifecycle command refuses this binding, so none is suggested. + findings = append(findings, unresolvedNativeAttemptFinding(installation, binding)) + continue + } if requiresPersonalMapping(bindingClient) { inventoryCurrent := packageInventoryAppliesToBinding(installation, binding) if inventoryCurrent && installation.Package.Inventory.MCPPresent && (!installation.Package.Inventory.AppPresent || len(installation.Package.Inventory.AppBindings) == 0) { @@ -326,6 +331,30 @@ func doctorScopeFlag(binding domain.ClientBinding) string { return "" } +// unresolvedNativeAttempt reports a client change whose effect was never +// confirmed and that has no persisted intent a recovery could reconcile. +func unresolvedNativeAttempt(binding domain.ClientBinding) bool { + return binding.NativeActivationAttempt != "" && binding.PendingNativeIntent == nil +} + +func unresolvedNativeAttempts(state domain.StateFileV2) []string { + var attempts []string + for _, installation := range state.Installations { + for _, binding := range installation.Clients { + if unresolvedNativeAttempt(binding) { + attempts = append(attempts, binding.NativeActivationAttempt) + } + } + } + return attempts +} + +func unresolvedNativeAttemptFinding(installation domain.Installation, binding domain.ClientBinding) doctorFinding { + return scopedFinding("degraded", "native_attempt_unresolved", installation, binding.ClientID, + fmt.Sprintf("an interrupted client change (native attempt %s) was not confirmed; add, update, repair and remove refuse this target", binding.NativeActivationAttempt), + "make sure no client command from the interrupted run is still running, then compare the client's own plugin list with this target; agentplugins cannot confirm this attempt automatically, so keep state-v2.json for manual recovery") +} + func degradedFinding(code, subject, message, action string) doctorFinding { return doctorFinding{Status: "degraded", Code: code, Subject: subject, Message: message, RecoveryAction: action} } diff --git a/install/integrationctl/agentplugins/clients/claude/project_marketplace_lifecycle.go b/install/integrationctl/agentplugins/clients/claude/project_marketplace_lifecycle.go index be65674f49..ac14f282ff 100644 --- a/install/integrationctl/agentplugins/clients/claude/project_marketplace_lifecycle.go +++ b/install/integrationctl/agentplugins/clients/claude/project_marketplace_lifecycle.go @@ -62,6 +62,7 @@ func activateClaudeProjectMarketplace(ctx context.Context, env clients.Env, requ return fail(fmt.Errorf("%w: exact Claude project plugin content is not enabled", shared.ErrRecognizedNegativeEvidence)) } if err := installClaudeProjectMarketplace(ctx, env, request, command, registered, observation.state, &outcome.NativeEffect); err != nil { + settleClaudeProjectInstall(ctx, env, request, command, claudeProjectState{state: observation.state, registered: registered}, &outcome, err) return fail(err) } listed, err := runPreparedClaudeList(ctx, env, command) @@ -85,22 +86,35 @@ func claudeProjectInstallPreflight(ctx context.Context, env clients.Env, request if err != nil { return nil, false, claudeMarketplaceObservation{}, err } - observation := inspectClaudeMarketplacePlugin(listed.Stdout, request.DeclaredName, request.Plan.PhysicalArtifactID, request.Plan.ActivePath, request.Plan.TargetContext.ProjectRoot, request.Client.ConfigRoot, "") - if observation.state == projectListUnknown || observation.state == projectListForeign || observation.state != projectListAbsent && !registered { - return nil, false, observation, fmt.Errorf("the Claude project plugin registration does not match the owned source") - } if registered && !request.Replacing && !request.VerifyOnly { - return nil, false, observation, fmt.Errorf("the Claude project marketplace was registered before this installation") + return nil, false, claudeMarketplaceObservation{}, fmt.Errorf("the Claude project marketplace was registered before this installation") } - err = verifyClaudeProjectBindings(request.Client.ConfigRoot, request.DeclaredName, request.Plan.PhysicalArtifactID, request.Plan.TargetContext.ProjectRoot, observation.cache) + observation, err := inspectClaudeProjectInstall(ctx, request, listed.Stdout, registered) + return listed.Stdout, registered, observation, err +} + +// inspectClaudeProjectInstall classifies one fresh listing together with the +// owned registration, the native installation index and every owned cache. Only +// a state accepted here can be continued by a later exact installation. +func inspectClaudeProjectInstall(ctx context.Context, request domain.ActivationRequest, body []byte, registered bool) (claudeMarketplaceObservation, error) { + observation := inspectClaudeMarketplacePlugin(body, request.DeclaredName, request.Plan.PhysicalArtifactID, request.Plan.ActivePath, request.Plan.TargetContext.ProjectRoot, request.Client.ConfigRoot, "") + if observation.state == projectListUnknown || observation.state == projectListForeign || observation.state != projectListAbsent && !registered { + return observation, fmt.Errorf("the Claude project plugin registration does not match the owned source") + } + err := verifyClaudeProjectBindings(request.Client.ConfigRoot, request.DeclaredName, request.Plan.PhysicalArtifactID, request.Plan.TargetContext.ProjectRoot, observation.cache) if err == nil && observation.cache != "" { err = verifyClaudeProjectCache(ctx, request.Client.ConfigRoot, request.DeclaredName, request.Plan.PhysicalArtifactID, request.Plan.TargetContext.ProjectRoot, observation.cache, request.PreviousNativeObjects, false) } if err == nil { cache := filepath.Join(request.Client.ConfigRoot, "plugins", "cache", ProjectMarketplaceName(request.Plan.PhysicalArtifactID, request.Plan.TargetContext.ProjectRoot), request.DeclaredName, claudeProjectVersion(request.Plan.DeclaredVersion)) err = verifyClaudeProjectCache(ctx, request.Client.ConfigRoot, request.DeclaredName, request.Plan.PhysicalArtifactID, request.Plan.TargetContext.ProjectRoot, cache, request.PreviousNativeObjects, true) + if err != nil && observation.state == projectListAbsent { + // An update interrupted after Claude's own uninstall leaves the owned + // cache marked orphaned; the reinstall refreshes exactly that cache. + err = verifyClaudeOwnedCache(ctx, request.Client.ConfigRoot, request.DeclaredName, request.Plan.PhysicalArtifactID, request.Plan.TargetContext.ProjectRoot, cache, request.PreviousNativeObjects, true) + } } - return listed.Stdout, registered, observation, err + return observation, err } func verifyClaudeProjectInstalled(ctx context.Context, request domain.ActivationRequest, body []byte) error { @@ -140,42 +154,60 @@ func installClaudeProjectMarketplace(ctx context.Context, env clients.Env, reque func deactivateClaudeProjectMarketplace(ctx context.Context, env clients.Env, request domain.DeactivationRequest, body []byte) (domain.DeactivationOutcome, error) { outcome := shared.StartedDeactivation() outcome.NativeEffect = domain.NativeEffectUnchanged + before, err := inspectClaudeProjectRemoval(ctx, request, body) + if err != nil { + return outcome, err + } + command, err := claudeProjectListCommand(request.BackendExecutable, request.Client, request.TargetContext, request.NativeRegistryRoot, request.ManagedArtifactPath) + if err != nil { + return outcome, err + } + settle := func(cause error) (domain.DeactivationOutcome, error) { + settleClaudeProjectRemoval(ctx, env, request, command, before, &outcome, cause) + return outcome, cause + } + if err := uninstallClaudeProjectMarketplace(ctx, env, request, command, before.state, before.registered, &outcome.NativeEffect); err != nil { + return settle(err) + } + if err := verifyClaudeProjectBindings(request.Client.ConfigRoot, request.DeclaredName, request.PhysicalArtifactID, request.TargetContext.ProjectRoot, ""); err != nil { + return settle(err) + } + effect := outcome.NativeEffect + if err := removeClaudeProjectCache(ctx, request, before.cache, &outcome.NativeEffect); err != nil { + if outcome.NativeEffect == effect { + // The cache retirement had not started; only Claude's own commands acted. + return settle(err) + } + return outcome, err + } + outcome.ExternalRemovalComplete = true + return outcome, nil +} + +// inspectClaudeProjectRemoval reads the exact owned native state a removal acts +// on: listing, registration, installation index and the owned cache receipt. +func inspectClaudeProjectRemoval(ctx context.Context, request domain.DeactivationRequest, body []byte) (claudeProjectState, error) { observed := inspectClaudeMarketplacePlugin(body, request.DeclaredName, request.PhysicalArtifactID, request.ManagedArtifactPath, request.TargetContext.ProjectRoot, request.Client.ConfigRoot, "") registered, err := claudeProjectMarketplaceRegistered(request.Client.ConfigRoot, request.ManagedArtifactPath, request.PhysicalArtifactID) if err != nil { - return outcome, err + return claudeProjectState{}, err } if observed.state == projectListUnknown || observed.state == projectListForeign || observed.state != projectListAbsent && !registered { - return outcome, fmt.Errorf("the Claude project identity is not exact before removal") + return claudeProjectState{}, fmt.Errorf("the Claude project identity is not exact before removal") } if err := verifyClaudeProjectBindings(request.Client.ConfigRoot, request.DeclaredName, request.PhysicalArtifactID, request.TargetContext.ProjectRoot, observed.cache); err != nil { - return outcome, err + return claudeProjectState{}, err } if observed.cache != "" { if err := verifyClaudeProjectCache(ctx, request.Client.ConfigRoot, request.DeclaredName, request.PhysicalArtifactID, request.TargetContext.ProjectRoot, observed.cache, request.NativeObjects, false); err != nil { - return outcome, err + return claudeProjectState{}, err } } cache, err := claudeProjectRemovalCache(ctx, request, observed.state == projectListAbsent) if err != nil { - return outcome, err - } - command, err := claudeProjectListCommand(request.BackendExecutable, request.Client, request.TargetContext, request.NativeRegistryRoot, request.ManagedArtifactPath) - if err != nil { - return outcome, err - } - err = uninstallClaudeProjectMarketplace(ctx, env, request, command, observed.state, registered, &outcome.NativeEffect) - if err != nil { - return outcome, err + return claudeProjectState{}, err } - if err := verifyClaudeProjectBindings(request.Client.ConfigRoot, request.DeclaredName, request.PhysicalArtifactID, request.TargetContext.ProjectRoot, ""); err != nil { - return outcome, err - } - if err := removeClaudeProjectCache(ctx, request, cache, &outcome.NativeEffect); err != nil { - return outcome, err - } - outcome.ExternalRemovalComplete = true - return outcome, nil + return claudeProjectState{state: observed.state, registered: registered, cache: cache}, nil } func uninstallClaudeProjectMarketplace(ctx context.Context, env clients.Env, request domain.DeactivationRequest, command legacyports.Command, state projectListState, registered bool, effect *domain.NativeEffectState) error { diff --git a/install/integrationctl/agentplugins/clients/claude/project_marketplace_observation_test.go b/install/integrationctl/agentplugins/clients/claude/project_marketplace_observation_test.go index 339a9e335c..0471e16190 100644 --- a/install/integrationctl/agentplugins/clients/claude/project_marketplace_observation_test.go +++ b/install/integrationctl/agentplugins/clients/claude/project_marketplace_observation_test.go @@ -138,9 +138,12 @@ func TestClaudeProjectMarketplaceFailureEffectsAndReadOnlyVerification(t *testin return legacyports.CommandResult{NoChildStarted: condition != "unknown-child"}, fmt.Errorf("inert native failure") }) out, err := New().Activate(t.Context(), clients.Env{Runner: runner}, request) - want := domain.NativeEffectUnchanged - if condition == "unknown-child" || condition == "after-marketplace" { - want = domain.NativeEffectUncertain + // A started child without proven cleanup stays uncertain. A closed + // failed install is re-read: the registered, uninstalled marketplace + // is a certain committed state that a later installation continues. + want := map[string]domain.NativeEffectState{"unknown-child": domain.NativeEffectUncertain, "after-marketplace": domain.NativeEffectCommitted}[condition] + if want == "" { + want = domain.NativeEffectUnchanged } if err == nil || out.NativeEffect != want || len(out.NativeObjects) != 0 { t.Fatalf("failure effect=%+v error=%v", out, err) diff --git a/install/integrationctl/agentplugins/clients/claude/project_marketplace_orphan.go b/install/integrationctl/agentplugins/clients/claude/project_marketplace_orphan.go index f734212519..6030524123 100644 --- a/install/integrationctl/agentplugins/clients/claude/project_marketplace_orphan.go +++ b/install/integrationctl/agentplugins/clients/claude/project_marketplace_orphan.go @@ -18,17 +18,23 @@ import ( const claudeOrphanedMarker = ".orphaned_at" func verifyClaudeProjectRemovalCache(ctx context.Context, request domain.DeactivationRequest, cache string, allowOrphan bool) error { - if err := pathpolicy.RequireContainedChild(request.Client.ConfigRoot, cache); err != nil { + return verifyClaudeOwnedCache(ctx, request.Client.ConfigRoot, request.DeclaredName, request.PhysicalArtifactID, request.TargetContext.ProjectRoot, cache, request.NativeObjects, allowOrphan) +} + +// verifyClaudeOwnedCache accepts an absent cache, the exact owned cache, or, +// after native absence, the same owned cache marked orphaned by Claude itself. +func verifyClaudeOwnedCache(ctx context.Context, configRoot, name, physical, project, cache string, objects []domain.NativeObjectOwnership, allowOrphan bool) error { + if err := pathpolicy.RequireContainedChild(configRoot, cache); err != nil { return err } if err := rejectClaudeCacheExcludedEntries(ctx, cache); err != nil { return err } - err := verifyClaudeProjectCache(ctx, request.Client.ConfigRoot, request.DeclaredName, request.PhysicalArtifactID, request.TargetContext.ProjectRoot, cache, request.NativeObjects, true) + err := verifyClaudeProjectCache(ctx, configRoot, name, physical, project, cache, objects, true) if err == nil || !allowOrphan { return err } - receipt, receiptErr := claudeProjectCacheReceipt(request.DeclaredName, request.PhysicalArtifactID, request.TargetContext.ProjectRoot, cache, request.NativeObjects) + receipt, receiptErr := claudeProjectCacheReceipt(name, physical, project, cache, objects) if receiptErr != nil { return receiptErr } diff --git a/install/integrationctl/agentplugins/clients/claude/project_marketplace_settle.go b/install/integrationctl/agentplugins/clients/claude/project_marketplace_settle.go new file mode 100644 index 0000000000..b369945292 --- /dev/null +++ b/install/integrationctl/agentplugins/clients/claude/project_marketplace_settle.go @@ -0,0 +1,83 @@ +package claude + +import ( + "context" + "time" + + "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/clients" + "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/domain" + legacyports "github.com/777genius/plugin-kit-ai/install/integrationctl/ports" +) + +// claudeSettleTimeout bounds the single read-only listing that settles a +// failed or interrupted Claude command after cancellation. +const claudeSettleTimeout = 15 * time.Second + +// claudeProjectState is the exact native project state one lifecycle step +// observed before acting on it. +type claudeProjectState struct { + state projectListState + registered bool + cache string +} + +// settleClaudeProjectInstall resolves the effect of a failed or interrupted +// Claude install command. Its process tree was reaped, so Claude's own +// registry is stable and is read once more, detached from the caller's +// cancellation. Only an exact install or a state that a later installation +// accepts becomes certain; anything else keeps the uncertain attempt. +func settleClaudeProjectInstall(ctx context.Context, env clients.Env, request domain.ActivationRequest, command legacyports.Command, before claudeProjectState, outcome *domain.ActivationOutcome, cause error) { + if outcome.NativeEffect != domain.NativeEffectUncertain || domain.IsUnclosedClientProbe(cause) { + return + } + observeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), claudeSettleTimeout) + defer cancel() + listed, err := runPreparedClaudeList(observeCtx, env, command) + if err != nil { + return + } + if verifyClaudeProjectInstalled(observeCtx, request, listed.Stdout) == nil { + outcome.NativeEffect = domain.NativeEffectCommitted + outcome.NativeObjects = append([]domain.NativeObjectOwnership(nil), request.Delivery.NativeObjects...) + return + } + registered, err := claudeProjectMarketplaceRegistered(request.Client.ConfigRoot, request.Plan.ActivePath, request.Plan.PhysicalArtifactID) + if err != nil { + return + } + observation, err := inspectClaudeProjectInstall(observeCtx, request, listed.Stdout, registered) + if err != nil { + return + } + // Recorded ownership (the previous cache receipt) still matches the client. + outcome.NativeEffect = domain.NativeEffectCommitted + if registered == before.registered && observation.state == before.state { + outcome.NativeEffect = domain.NativeEffectUnchanged + } +} + +// settleClaudeProjectRemoval is the removal counterpart. A state identical to +// the one removal started from is unchanged. Any other state the removal +// itself accepts is settled partial progress: every recorded native object is +// still exact, so the core may clear its attempt and a retry continues. +func settleClaudeProjectRemoval(ctx context.Context, env clients.Env, request domain.DeactivationRequest, command legacyports.Command, before claudeProjectState, outcome *domain.DeactivationOutcome, cause error) { + if outcome.NativeEffect == domain.NativeEffectUnchanged || domain.IsUnclosedClientProbe(cause) { + return + } + observeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), claudeSettleTimeout) + defer cancel() + listed, err := runPreparedClaudeList(observeCtx, env, command) + if err != nil { + return + } + after, err := inspectClaudeProjectRemoval(observeCtx, request, listed.Stdout) + if err != nil { + return + } + if after == before { + outcome.NativeEffect = domain.NativeEffectUnchanged + return + } + outcome.NativeEffect = domain.NativeEffectCommitted + outcome.SettledPartialRemoval = true +} diff --git a/install/integrationctl/agentplugins/domain/clients_runtime.go b/install/integrationctl/agentplugins/domain/clients_runtime.go index 626409f50e..54fa692203 100644 --- a/install/integrationctl/agentplugins/domain/clients_runtime.go +++ b/install/integrationctl/agentplugins/domain/clients_runtime.go @@ -211,12 +211,16 @@ type DeactivationRequest struct { type DeactivationOutcome struct { // NativeEffect is transient evidence of a native transaction's actual // effects. An ordinary error never establishes that removal was unchanged. - NativeEffect NativeEffectState `json:"-"` - Activation ActivationState `json:"activation"` - ArtifactRemovalAllowed bool `json:"artifact_removal_allowed"` - ExternalRemovalComplete bool `json:"external_removal_complete"` - UserActions []string `json:"user_actions,omitempty"` - LocalActions []string `json:"-"` + NativeEffect NativeEffectState `json:"-"` + // SettledPartialRemoval qualifies a committed effect of a failed removal: + // the adapter re-read the client after its processes closed and every + // recorded native object is still exactly owned, so no attempt stays open. + SettledPartialRemoval bool `json:"-"` + Activation ActivationState `json:"activation"` + ArtifactRemovalAllowed bool `json:"artifact_removal_allowed"` + ExternalRemovalComplete bool `json:"external_removal_complete"` + UserActions []string `json:"user_actions,omitempty"` + LocalActions []string `json:"-"` } func supportsLocalDelivery(id ClientID) bool { return id == ClientVSCode } diff --git a/install/integrationctl/agentplugins/usecase/native_remove_attempt.go b/install/integrationctl/agentplugins/usecase/native_remove_attempt.go index 4fcd2d2dc9..d637465613 100644 --- a/install/integrationctl/agentplugins/usecase/native_remove_attempt.go +++ b/install/integrationctl/agentplugins/usecase/native_remove_attempt.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "reflect" + "time" "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/domain" "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/transaction" @@ -55,25 +56,67 @@ func (service Service) beginNativeRemovalAttempt(installationID, bindingID strin return service.beginNativeAttemptWithPredecessor(installationID, bindingID, domain.NativeIntentRemove, client.SelectedDelivery, client.LocalEntryObservation.Clone(), &predecessor) } -// acknowledgeUnchangedRemoval aborts only an owned attempt whose callback -// positively proved no native effect. Unknown errors retain the recovery guard. +// acknowledgeCertainRemoval closes an owned attempt whose failed callback +// positively proved its effect: no native effect restores the predecessor, and +// settled partial progress keeps its exact ownership but records that the +// client is no longer verified. Unknown errors retain the recovery guard. // The mutation lock is held by Remove/RemoveGroup across comparison and save; // persistence uses the kernel's existing visibility and durability handling. -func (service Service) acknowledgeUnchangedRemoval(attempt *nativeRemovalAttempt, outcome domain.DeactivationOutcome, removalErr error) error { - if removalErr == nil || attempt == nil || outcome.NativeEffect != domain.NativeEffectUnchanged { +func (service Service) acknowledgeCertainRemoval(attempt *nativeRemovalAttempt, outcome domain.DeactivationOutcome, removalErr error) error { + settled := outcome.NativeEffect == domain.NativeEffectCommitted && outcome.SettledPartialRemoval + if removalErr == nil || attempt == nil || outcome.NativeEffect != domain.NativeEffectUnchanged && !settled { return removalErr } current, err := service.StateStore.Load() if err != nil { - return errors.Join(removalErr, fmt.Errorf("inspect unchanged native removal %s: %w", attempt.attemptID, err)) + return errors.Join(removalErr, fmt.Errorf("inspect certain native removal %s: %w", attempt.attemptID, err)) } if !reflect.DeepEqual(current, attempt.attempted) { - return errors.Join(removalErr, fmt.Errorf("unchanged native removal %s changed frozen predecessor; retain uncertainty", attempt.attemptID)) + return errors.Join(removalErr, fmt.Errorf("certain native removal %s changed frozen predecessor; retain uncertainty", attempt.attemptID)) + } + decision := attempt.before + if settled { + decision = attempt.partialRemovalDecision(service.now()) } kernel := service.Kernel kernel.StateStore = service.StateStore - if err := kernel.PersistStateDecision(attempt.attempted, attempt.before); err != nil { - return errors.Join(removalErr, fmt.Errorf("acknowledge unchanged native removal %s: %w", attempt.attemptID, err)) + if err := kernel.PersistStateDecision(attempt.attempted, decision); err != nil { + return errors.Join(removalErr, fmt.Errorf("acknowledge certain native removal %s: %w", attempt.attemptID, err)) } return removalErr } + +// partialRemovalDecision is the predecessor state with the attempted binding +// marked failed: its client registration changed, its recorded objects did not. +func (attempt *nativeRemovalAttempt) partialRemovalDecision(now time.Time) domain.StateFileV2 { + decision := attempt.before + decision.Installations = append([]domain.Installation(nil), decision.Installations...) + for i, installation := range decision.Installations { + key := attempt.bindingID(installation.InstallationID) + if _, found := installation.Clients[key]; !found { + continue + } + installation.Clients = cloneClientBindings(installation.Clients) + client := installation.Clients[key] + client.Activation, client.Verification = domain.ActivationFailed, domain.VerificationFailed + client.UpdatedAt = now.Format(time.RFC3339Nano) + installation.Clients[key], installation.UpdatedAt = client, client.UpdatedAt + decision.Installations[i] = installation + } + return decision +} + +// bindingID names the binding that carries this attempt's marker. +func (attempt *nativeRemovalAttempt) bindingID(installationID string) string { + for _, installation := range attempt.attempted.Installations { + if installation.InstallationID != installationID { + continue + } + for key, binding := range installation.Clients { + if binding.NativeActivationAttempt == attempt.attemptID { + return key + } + } + } + return "" +} diff --git a/install/integrationctl/agentplugins/usecase/remove_group_native.go b/install/integrationctl/agentplugins/usecase/remove_group_native.go index cbb15bdf75..2617acc477 100644 --- a/install/integrationctl/agentplugins/usecase/remove_group_native.go +++ b/install/integrationctl/agentplugins/usecase/remove_group_native.go @@ -38,7 +38,7 @@ func (session *removeGroupSession) removeGroupNative() error { } if err != nil { session.markNativeDeactivationFailed(item, externalCompleted) - err = session.service.acknowledgeUnchangedRemoval(attempt, outcome, err) + err = session.service.acknowledgeCertainRemoval(attempt, outcome, err) return fmt.Errorf("external deactivation failed; managed materialization was retained for repair: %w", err) } if nativeAttempt { diff --git a/install/integrationctl/agentplugins/usecase/remove_session.go b/install/integrationctl/agentplugins/usecase/remove_session.go index 26a93a227b..e6e78599a2 100644 --- a/install/integrationctl/agentplugins/usecase/remove_session.go +++ b/install/integrationctl/agentplugins/usecase/remove_session.go @@ -98,7 +98,7 @@ func (session *removeSession) deactivateRemoveTarget() error { }) session.result.Deactivation = deactivation if err != nil { - return session.service.acknowledgeUnchangedRemoval(attempt, deactivation, err) + return session.service.acknowledgeCertainRemoval(attempt, deactivation, err) } if err == nil && nativeAttempt { if persistErr := session.service.completeNativeRemoval(session.ctx, session.installation.InstallationID, session.clientKey, deactivation.ExternalRemovalComplete); persistErr != nil { From d1e358a83f3c972e8bebf91aa36b5bc655ed7701 Mon Sep 17 00:00:00 2001 From: iliya Date: Tue, 17 Nov 2026 03:36:36 +0200 Subject: [PATCH 2/5] test(install): pin unclosed Claude removal and settled removal acknowledgement An interrupted Claude project removal whose client cleanup is not proven must keep its attempt, both before and after the native uninstall landed; the removal settle has no later verification to fall back on. The core acknowledgement of a settled partial removal is covered directly: it clears the attempt, marks the binding failed and keeps its ownership and package, while an uncertain effect, a committed effect without the settled proof or a changed predecessor keep the attempt. --- .../project_claude_interrupt_test.go | 41 ++++++++----- .../usecase/native_remove_no_effect_test.go | 58 ++++++++++++++++++- 2 files changed, 84 insertions(+), 15 deletions(-) diff --git a/cli/internal/agentpluginscli/project_claude_interrupt_test.go b/cli/internal/agentpluginscli/project_claude_interrupt_test.go index 37d97fb864..4b2fad3aa4 100644 --- a/cli/internal/agentpluginscli/project_claude_interrupt_test.go +++ b/cli/internal/agentpluginscli/project_claude_interrupt_test.go @@ -97,21 +97,34 @@ func TestProjectClaudeInterruptedNativeCommandResumesWithSameCommand(t *testing. } // A child whose cleanup is not proven may still be writing. Its attempt stays -// unresolved and blocks blind retry, exactly as before. +// unresolved and blocks blind retry, exactly as before, whether or not its +// effect already landed; removal has no later verification to fall back on. func TestProjectClaudeUnclosedInterruptedCommandKeepsAttempt(t *testing.T) { - fixture, args := interruptedProjectClaudeCommand(t, "add", &claudeCLIInterrupt{args: []string{"plugin", "install"}, unclosed: true}) - attempt, _ := fixture.nativeAttempt(t) - if attempt == "" { - t.Fatal("unclosed native command was resolved without proof") - } - out, err := fixture.runProject(context.Background(), args...) - if err == nil || !strings.Contains(out+err.Error(), attempt) { - t.Fatalf("retry ignored the unresolved attempt: %v\n%s", err, out) - } - // Doctor reports the open attempt and suggests no command that refuses it. - doctor, _, err := fixture.execute(false, "doctor", "--target", "claude", "--scope", "project", "--project-root", fixture.project, "--format", "json") - if err != nil || !strings.Contains(doctor, `"open_operation_count":1`) || !strings.Contains(doctor, "native_attempt_unresolved") || strings.Contains(doctor, "rerun the same") { - t.Fatalf("doctor misreported the unresolved attempt: %v\n%s", err, doctor) + for _, tc := range []struct { + name, command string + args []string + landed bool + }{ + {"add/install", "add", []string{"plugin", "install"}, false}, + {"remove/uninstall", "remove", []string{"plugin", "uninstall"}, false}, + {"remove/uninstall-landed", "remove", []string{"plugin", "uninstall"}, true}, + } { + t.Run(tc.name, func(t *testing.T) { + fixture, args := interruptedProjectClaudeCommand(t, tc.command, &claudeCLIInterrupt{args: tc.args, landed: tc.landed, unclosed: true}) + attempt, _ := fixture.nativeAttempt(t) + if attempt == "" { + t.Fatal("unclosed native command was resolved without proof") + } + out, err := fixture.runProject(context.Background(), args...) + if err == nil || !strings.Contains(out+err.Error(), attempt) { + t.Fatalf("retry ignored the unresolved attempt: %v\n%s", err, out) + } + // Doctor reports the open attempt and suggests no command that refuses it. + doctor, _, err := fixture.execute(false, "doctor", "--target", "claude", "--scope", "project", "--project-root", fixture.project, "--format", "json") + if err != nil || !strings.Contains(doctor, `"open_operation_count":1`) || !strings.Contains(doctor, "native_attempt_unresolved") || strings.Contains(doctor, "rerun the same") { + t.Fatalf("doctor misreported the unresolved attempt: %v\n%s", err, doctor) + } + }) } } diff --git a/install/integrationctl/agentplugins/usecase/native_remove_no_effect_test.go b/install/integrationctl/agentplugins/usecase/native_remove_no_effect_test.go index 87d88fc633..9b404b5c0d 100644 --- a/install/integrationctl/agentplugins/usecase/native_remove_no_effect_test.go +++ b/install/integrationctl/agentplugins/usecase/native_remove_no_effect_test.go @@ -8,6 +8,7 @@ import ( "fmt" "os" "path/filepath" + "reflect" "strings" "testing" @@ -89,6 +90,7 @@ type removalNoEffectControl struct { store transaction.StateStore t *testing.T effect domain.NativeEffectState + settled bool change string cause error called bool @@ -137,7 +139,7 @@ func (a *removalNoEffectControl) Deactivate(ctx context.Context, req domain.Deac a.t.Fatal(err) } a.called = true - return domain.DeactivationOutcome{NativeEffect: a.effect}, a.cause + return domain.DeactivationOutcome{NativeEffect: a.effect, SettledPartialRemoval: a.settled}, a.cause } type removalNoEffectFailStore struct { @@ -273,3 +275,57 @@ func TestNativeRemovalAttemptRejectsChangedSourcePredecessor(t *testing.T) { t.Fatal("pre-attempt refusal overwrote newer source authority or published a marker") } } + +// A failed removal whose adapter proved settled partial progress closes its +// attempt: the binding keeps its exact ownership and package and is marked +// failed. Any weaker proof or a changed predecessor keeps the attempt. +func TestNativeRemovalSettledPartialProgressClosesAttempt(t *testing.T) { + for _, grouped := range []bool{false, true} { + for _, mode := range []string{"settled", "settled-uncertain", "committed-unsettled", "settled-source-changed"} { + t.Run(fmt.Sprintf("grouped-%t/%s", grouped, mode), func(t *testing.T) { + service, _, id, client := removeNoEffectFixture(t) + before, err := service.StateStore.Load() + if err != nil { + t.Fatal(err) + } + cause := errors.New("injected interrupted removal") + control := &removalNoEffectControl{inner: service.Activator, store: service.StateStore, t: t, effect: domain.NativeEffectCommitted, settled: true, cause: cause} + switch mode { + case "settled-uncertain": + control.effect = domain.NativeEffectUncertain + case "committed-unsettled": + control.settled = false + case "settled-source-changed": + control.change = "source" + } + service.Activator = control + if err := removeNoEffectCall(t, service, id, client, grouped); !errors.Is(err, cause) || !control.called { + t.Fatalf("lost interrupted removal cause: %v", err) + } + after, err := service.StateStore.Load() + if err != nil { + t.Fatal(err) + } + assertSettledRemoval(t, mode == "settled", onlyBinding(before.Installations[0]), onlyBinding(after.Installations[0])) + }) + } + } +} + +func assertSettledRemoval(t *testing.T, settled bool, before, after domain.ClientBinding) { + t.Helper() + if _, err := os.Stat(after.TargetLocator); err != nil { + t.Fatalf("partial removal lost the managed package: %v", err) + } + if !settled { + if after.NativeActivationAttempt == "" { + t.Fatalf("attempt cleared without settled proof: %+v", after) + } + return + } + want := before + want.Activation, want.Verification, want.UpdatedAt = domain.ActivationFailed, domain.VerificationFailed, after.UpdatedAt + if after.NativeActivationAttempt != "" || !reflect.DeepEqual(after, want) { + t.Fatalf("settled partial removal changed more than its lifecycle:\nwant=%+v\ngot=%+v", want, after) + } +} From dca08ffdb297ff1bfd71812cf1a71b53ce95c039 Mon Sep 17 00:00:00 2001 From: iliya Date: Tue, 17 Nov 2026 03:36:38 +0200 Subject: [PATCH 3/5] fix(cli): report only journal-less native attempts as unresolved in doctor OpenCode and Grok record native transitions in a journal that the next mutation replays, so their attempts are not stuck and the manual recovery advice was wrong for them. Doctor now skips attempts the native transition observer reports with a journal root. --- cli/internal/agentpluginscli/read.go | 33 ++++++++++++++++++---------- 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/cli/internal/agentpluginscli/read.go b/cli/internal/agentpluginscli/read.go index 8073e0fa67..f22a2f29a0 100644 --- a/cli/internal/agentpluginscli/read.go +++ b/cli/internal/agentpluginscli/read.go @@ -64,7 +64,7 @@ func runDoctor(ctx context.Context, cmd *cobra.Command, app App, opts *options, ProjectReadiness []projectReadinessRecord `json:"project_readiness"` Findings []doctorFinding `json:"findings"` }{ReadOnly: true, ToolVersion: normalizedToolVersion(app.Version), SupportedClients: doctorSupportedClients(), Clients: publicClients, - InstallationCount: len(publicInstallations(state, false)), OpenOperationCount: len(open) + len(unresolvedNativeAttempts(state))} + InstallationCount: len(publicInstallations(state, false)), OpenOperationCount: len(open) + len(unresolvedNativeAttempts(app, state))} selected := (*domain.Installation)(nil) if len(args) == 1 { installation, err := selectInstallation(state, args[0]) @@ -176,6 +176,7 @@ func doctorFindings(ctx context.Context, app App, detected []domain.DetectedClie findings = append(findings, doctorFinding{Status: "unknown", Code: "client_detection_failed", ClientID: string(client.ClientID), Message: "client configuration could not be inspected safely", RecoveryAction: "correct the client profile configuration and rerun doctor"}) } } + unresolved := unresolvedNativeAttempts(app, state) if len(open) > 0 { findings = append(findings, degradedFinding("open_recovery_operations", "operations", "an interrupted managed-directory operation requires recovery", "rerun the intended add, update, or remove command to perform transactional recovery")) } @@ -203,7 +204,7 @@ func doctorFindings(ctx context.Context, app App, detected []domain.DetectedClie if !plansWithoutHostPresence(bindingClient) && (!visible || (client.Status != domain.DetectionDetected && client.DetectionError == nil)) { findings = append(findings, scopedFinding("degraded", "client_not_visible", installation, binding.ClientID, "the package is tracked but no current client visibility evidence was detected", "install or launch the client so its CLI, desktop application, or configuration directory is visible, then rerun doctor")) } - if unresolvedNativeAttempt(binding) { + if unresolved[binding.NativeActivationAttempt] { // Every lifecycle command refuses this binding, so none is suggested. findings = append(findings, unresolvedNativeAttemptFinding(installation, binding)) continue @@ -331,18 +332,26 @@ func doctorScopeFlag(binding domain.ClientBinding) string { return "" } -// unresolvedNativeAttempt reports a client change whose effect was never -// confirmed and that has no persisted intent a recovery could reconcile. -func unresolvedNativeAttempt(binding domain.ClientBinding) bool { - return binding.NativeActivationAttempt != "" && binding.PendingNativeIntent == nil -} - -func unresolvedNativeAttempts(state domain.StateFileV2) []string { - var attempts []string +// unresolvedNativeAttempts lists client changes whose effect was never +// confirmed and that neither a persisted intent nor a native transition +// journal (replayed by the next mutation) can reconcile. Every lifecycle +// command refuses their bindings. A failed journal read reports them all. +func unresolvedNativeAttempts(app App, state domain.StateFileV2) map[string]bool { + journaled := map[string]bool{} + if observer, ok := app.Lifecycle.Kernel.NativeRecovery.(ports.NativeTransitionObserver); ok { + pending, _ := observer.Pending() + for _, item := range pending { + if item.Root != "" { + journaled[item.OperationID] = true + } + } + } + attempts := map[string]bool{} for _, installation := range state.Installations { for _, binding := range installation.Clients { - if unresolvedNativeAttempt(binding) { - attempts = append(attempts, binding.NativeActivationAttempt) + attempt := binding.NativeActivationAttempt + if attempt != "" && binding.PendingNativeIntent == nil && !journaled[attempt] { + attempts[attempt] = true } } } From 8d8cab076889d32700385905074dbff8d76f68a0 Mon Sep 17 00:00:00 2001 From: iliya Date: Tue, 17 Nov 2026 03:36:40 +0200 Subject: [PATCH 4/5] fix(install): bound the Claude settle read like any probe and announce interrupts The single read after an interrupted Claude command used its own 15 second limit, shorter than the usual 60 second listing budget, so a slow machine could keep the attempt blocked. It now uses the ordinary probe bound and only detaches the caller's cancellation. After the first interrupt the CLI says it is finishing the current client step and restores default signal handling, so another interrupt stops it at once instead of being silently ignored. The native setup rule now names the one exception to "no probe after an uncertain effect": one read-only registry read after a proven closed process tree, reporting only an exactly recognized state. --- cli/cmd/agentplugins/main.go | 23 +++++++++++++++++++ docs/NATIVE_SETUP_COMPLETION.md | 8 ++++++- .../claude/project_marketplace_settle.go | 13 ++++------- .../agentplugins/usecase/native_attempt.go | 3 ++- 4 files changed, 36 insertions(+), 11 deletions(-) diff --git a/cli/cmd/agentplugins/main.go b/cli/cmd/agentplugins/main.go index aef50741d0..6bba40e49e 100644 --- a/cli/cmd/agentplugins/main.go +++ b/cli/cmd/agentplugins/main.go @@ -5,6 +5,7 @@ import ( "crypto/ed25519" "encoding/base64" "fmt" + "io" "net/http" "net/url" "os" @@ -97,6 +98,7 @@ func run() error { } ctx, stop := installerSignalContext(context.Background()) defer stop() + defer watchInterrupt(ctx, stop, os.Stderr)() // Preserve the real os.Stdout *os.File for native TTY detection. An // io.Writer counter here silently downgrades rich prompts to plain input. root := agentpluginscli.NewRoot(app) @@ -130,6 +132,27 @@ func installerSignalContext(parent context.Context) (context.Context, context.Ca return signal.NotifyContext(parent, signals...) } +// watchInterrupt says once that the interrupted command is still finishing +// (recording or re-reading the client's state) and restores default signal +// handling, so a second interrupt stops at once instead of being swallowed. +// The returned release must run before stop: a normal exit prints nothing. +func watchInterrupt(ctx context.Context, stop context.CancelFunc, out io.Writer) func() { + finished := make(chan struct{}) + go func() { + select { + case <-finished: + case <-ctx.Done(): + select { + case <-finished: + default: + stop() + _, _ = fmt.Fprintln(out, "agentplugins: interrupted; finishing the current client step safely (interrupt again to stop at once)") + } + } + }() + return func() { close(finished) } +} + func resolveAgentpluginsRoots() (string, string, error) { home, err := os.UserHomeDir() if err != nil || strings.TrimSpace(home) == "" { diff --git a/docs/NATIVE_SETUP_COMPLETION.md b/docs/NATIVE_SETUP_COMPLETION.md index 08d571d0c3..328e7ad376 100644 --- a/docs/NATIVE_SETUP_COMPLETION.md +++ b/docs/NATIVE_SETUP_COMPLETION.md @@ -24,7 +24,13 @@ their existing behavior. An unclosed probe stops subsequent client mutations. Trust and approval preferences survive plugin removal. Updates preserve unrelated settings through locked conditional file transactions. A failed write or rollback retains its observed native effect; an uncertain effect cannot be reported as -unchanged or followed by another native probe. Cursor writes only the approval +unchanged or followed by another native probe. The one exception is a failed or +interrupted client command whose whole process tree was proven closed (Claude +Code project `plugin marketplace add`, `plugin install`, `plugin uninstall`, +`plugin marketplace remove`): the adapter may read the client's own registry +once, read-only, and report only an exactly recognized state. Unproven process +cleanup, a failed read or an unrecognized state stay uncertain and keep blocking +the next mutation. Cursor writes only the approval store and never invokes native `mcp enable`, which can clear explicit disablement. Existing deny settings are preserved and checked again before readiness is reported. Unknown schemas, foreign ownership and uncertain cleanup never become diff --git a/install/integrationctl/agentplugins/clients/claude/project_marketplace_settle.go b/install/integrationctl/agentplugins/clients/claude/project_marketplace_settle.go index b369945292..d9d1856b31 100644 --- a/install/integrationctl/agentplugins/clients/claude/project_marketplace_settle.go +++ b/install/integrationctl/agentplugins/clients/claude/project_marketplace_settle.go @@ -2,17 +2,12 @@ package claude import ( "context" - "time" "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/clients" "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/domain" legacyports "github.com/777genius/plugin-kit-ai/install/integrationctl/ports" ) -// claudeSettleTimeout bounds the single read-only listing that settles a -// failed or interrupted Claude command after cancellation. -const claudeSettleTimeout = 15 * time.Second - // claudeProjectState is the exact native project state one lifecycle step // observed before acting on it. type claudeProjectState struct { @@ -30,8 +25,9 @@ func settleClaudeProjectInstall(ctx context.Context, env clients.Env, request do if outcome.NativeEffect != domain.NativeEffectUncertain || domain.IsUnclosedClientProbe(cause) { return } - observeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), claudeSettleTimeout) - defer cancel() + // The listing keeps the ordinary ClaudeProbeTimeout bound; only the + // caller's cancellation is detached for this one read. + observeCtx := context.WithoutCancel(ctx) listed, err := runPreparedClaudeList(observeCtx, env, command) if err != nil { return @@ -64,8 +60,7 @@ func settleClaudeProjectRemoval(ctx context.Context, env clients.Env, request do if outcome.NativeEffect == domain.NativeEffectUnchanged || domain.IsUnclosedClientProbe(cause) { return } - observeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), claudeSettleTimeout) - defer cancel() + observeCtx := context.WithoutCancel(ctx) listed, err := runPreparedClaudeList(observeCtx, env, command) if err != nil { return diff --git a/install/integrationctl/agentplugins/usecase/native_attempt.go b/install/integrationctl/agentplugins/usecase/native_attempt.go index dedf4db8d1..5cc4c0b0e9 100644 --- a/install/integrationctl/agentplugins/usecase/native_attempt.go +++ b/install/integrationctl/agentplugins/usecase/native_attempt.go @@ -158,7 +158,8 @@ func (service Service) activateWithNativeAttempt(ctx context.Context, installati // completeNativeRemoval records a known deactivation before a later managed // directory transaction. A failed Deactivate leaves the attempt marker in -// place, because a partial native write cannot safely be inferred away. +// place, because a partial native write cannot safely be inferred away; only +// an adapter-proven effect is closed by acknowledgeCertainRemoval. func (service Service) completeNativeRemoval(ctx context.Context, installationID, bindingID string, removed bool) error { state, err := service.StateStore.Load() if err != nil { From 97ec8ce7599de32b33c1054f6384c94ab309af07 Mon Sep 17 00:00:00 2001 From: iliya Date: Tue, 17 Nov 2026 03:51:55 +0200 Subject: [PATCH 5/5] fix(cli): drop the extra interrupt notice and signal reset Writing a notice to stderr on the first interrupt could raise SIGPIPE when stderr is piped (for example `2>&1 | tee`) and stop the CLI before it recorded the client state, and restoring default handling after the first signal let a later SIGTERM or SIGHUP kill it the same way. Interrupt handling is back to a single cancellation for every signal; the closing hint is still printed only after the command has returned. --- cli/cmd/agentplugins/main.go | 23 ----------------------- 1 file changed, 23 deletions(-) diff --git a/cli/cmd/agentplugins/main.go b/cli/cmd/agentplugins/main.go index 6bba40e49e..aef50741d0 100644 --- a/cli/cmd/agentplugins/main.go +++ b/cli/cmd/agentplugins/main.go @@ -5,7 +5,6 @@ import ( "crypto/ed25519" "encoding/base64" "fmt" - "io" "net/http" "net/url" "os" @@ -98,7 +97,6 @@ func run() error { } ctx, stop := installerSignalContext(context.Background()) defer stop() - defer watchInterrupt(ctx, stop, os.Stderr)() // Preserve the real os.Stdout *os.File for native TTY detection. An // io.Writer counter here silently downgrades rich prompts to plain input. root := agentpluginscli.NewRoot(app) @@ -132,27 +130,6 @@ func installerSignalContext(parent context.Context) (context.Context, context.Ca return signal.NotifyContext(parent, signals...) } -// watchInterrupt says once that the interrupted command is still finishing -// (recording or re-reading the client's state) and restores default signal -// handling, so a second interrupt stops at once instead of being swallowed. -// The returned release must run before stop: a normal exit prints nothing. -func watchInterrupt(ctx context.Context, stop context.CancelFunc, out io.Writer) func() { - finished := make(chan struct{}) - go func() { - select { - case <-finished: - case <-ctx.Done(): - select { - case <-finished: - default: - stop() - _, _ = fmt.Fprintln(out, "agentplugins: interrupted; finishing the current client step safely (interrupt again to stop at once)") - } - } - }() - return func() { close(finished) } -} - func resolveAgentpluginsRoots() (string, string, error) { home, err := os.UserHomeDir() if err != nil || strings.TrimSpace(home) == "" {