Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion cli/cmd/agentplugins/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
6 changes: 5 additions & 1 deletion cli/internal/agentpluginscli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
}

Expand Down
163 changes: 163 additions & 0 deletions cli/internal/agentpluginscli/project_claude_interrupt_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
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, whether or not its
// effect already landed; removal has no later verification to fall back on.
func TestProjectClaudeUnclosedInterruptedCommandKeepsAttempt(t *testing.T) {
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)
}
})
}
}

// 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
}
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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 {
Expand Down Expand Up @@ -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)
Expand All @@ -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)
}
Expand All @@ -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
Expand All @@ -125,13 +124,42 @@ 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})
if err != nil {
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)
Expand Down
40 changes: 39 additions & 1 deletion cli/internal/agentpluginscli/read.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(app, state))}
selected := (*domain.Installation)(nil)
if len(args) == 1 {
installation, err := selectInstallation(state, args[0])
Expand Down Expand Up @@ -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"))
}
Expand Down Expand Up @@ -203,6 +204,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 unresolved[binding.NativeActivationAttempt] {
// 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) {
Expand Down Expand Up @@ -326,6 +332,38 @@ func doctorScopeFlag(binding domain.ClientBinding) string {
return ""
}

// 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 {
attempt := binding.NativeActivationAttempt
if attempt != "" && binding.PendingNativeIntent == nil && !journaled[attempt] {
attempts[attempt] = true
}
}
}
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}
}
8 changes: 7 additions & 1 deletion docs/NATIVE_SETUP_COMPLETION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading