Files
skillshare/internal/plugin/service_test.go
T
Rusty Shackleford da3383ed5f fix(plugins): separate shared intent from local installation state (#660)
* fix(plugins): separate shared intent from machine-local receipts

Shared configs currently carry native paths, reviewed snapshots and pending
failures, so one host can publish local progress over another host's target
selection. Persist versioned declarations separately from local applied and
pending receipts, and reconcile reviewed installs, imports and cleanup against
this machine's native inventory without rewriting intent during sync/update.

Keep snapshot names and adapter safeguards, move the operation lock locally,
validate legacy adoption with local evidence, and invalidate approval on local
state or native-context changes. Preserve source recipes after native adoption,
require local import for absent native-only targets, and document the shared
writer upgrade boundary in schemas and translated references.

Cover two-host behavior, generated legacy fixtures, failure/recovery, stale
intent, cleanup, npm recipes and the existing CLI/API/UI consumers with focused
resource-capped tests. Fixes #651.

* fix(plugins): preserve intent and ownership across host transitions

Repeat-add must retain shared target selection, and update previews must resolve
the requested ref before reviewing fresh or replacement installs. Keep disabled
targets on the uninstall path and reject refs unsupported by native-only/npm
intent before they can produce invalid shared declarations.

Block changed-context add/import before Pi registration preparation so a new
account cannot overwrite the old receipt. Preserve unresolved legacy bindings
as passive private proof candidates before rewriting shared YAML, retaining
original intent/store for later verified adoption and cleanup. Never compose
these hints as executable state, and persist their explicit resolution.

Cover the five review classes, native/private failure boundaries, requested-ref
retry, and original-context hint proofs with isolated focused regressions.
Keep local format v1 and baseline account validation unchanged. Refs #651.

* fix(plugins): allow receipt-only orphan cleanup to complete

An installation already removed on this host can retain a local receipt when
another host removes or replaces shared intent. Sync correctly plans forget,
but native command verification rejects that metadata-only action and blocks
all targets before the receipt can be cleared.

Exclude forget from native command verification while retaining host inventory
checks and OMP scoped cleanup preparation. The existing completion path then
persists receipt deletion, including pending work and passive legacy hints.

Cover the cross-host disable/re-enable/remove walk, five native adapters,
failed work with a legacy hint, and absent source replacement alongside a
healthy target. Assert Apply completion, unchanged shared bytes/mtime, and a
quiet second sync. Refs #651.

* fix(plugin): reconcile ref intent across inventory consumers

Validate explicit ref changes before disabled targets can save them and reuse
one reviewed discovery throughout a preview. Surface shared ref changes as local
reconciliation work while preserving the applied native identity and receipts.

Reuse scoped legacy proofs for Pi extension ownership and make full inventory
the dashboard's authoritative package/host pair. Cover invalid and replacement
refs, read-only ownership, and shared-state properties without new persisted
state or dependencies.

* test(plugin): repair and consolidate host-state fixtures

Create source intent and a pending imported Claude update through supported
operations so direct and batch updates exercise the intended fixture. Keep the
marketplace-loss case locally owned before testing its skipped reinstall.

Consolidate cross-host repeat-add and requested-ref replacement/orphan retries
at their existing owners, retaining failure recovery and shared-byte checks.
Trim duplicate HTTP and translated-text assertions from consumer tests.

* fix(plugin): reconcile legacy snapshot reads and native imports

Resolve legacy snapshot ownership through existing scoped proofs before listing,
reading or discovering cached source files. Keep adoption read-only and limit
proof work to the requested package and targets; current receipts need no CLI.

Only preserve reviewed source metadata on reimport when intent remains source
managed. Native-only intent must not resurrect an older Git source after a
same-ID local import. Retain identity mismatch and reviewed-source safeguards.

Remove the unused source-folding helper left by the old shared runtime writer.

* Preserve reviewed package versions locally

* Fix reviewed package version lifecycle

* fix(plugin): report missing local imports in doctor

Show the local-import instruction instead of claiming a skipped imported
plugin is healthy. Preserve the missing-CLI warning and shared config bytes.

Keep fixture native settings inside scratch XDG directories and serialize
the fake CLI calls used by concurrent inventories. Update assertions to
separate shared declarations from local versions and native IDs, and align
the raw-write audit with private plugin state and operation locks.

* test(plugin): use declarations for doctor source fixture

The missing-CLI case has no native ID, so encode it with the version 2
declaration schema. Keep the native-only import case in legacy syntax.

* fix(plugin): install shared sources from reviewed snapshots

When a source target is already declared, first sync must install its
reviewed local snapshot even if the native client has a package from the
same marketplace. Keep explicit add adoption and native-only import intact.

Extend the existing two-host adoption check to cover an independent native
installation on the second host and verify a quiet subsequent sync.

* fix(plugin): preserve reviewed retries and native collision boundaries

Retry a pending source update through the existing reviewed update path,
so a rolled-back native failure cannot clear progress at the old snapshot.
Record default-source versions for add, sync, and update while retaining
the recipe fingerprint and generic-version checks for target overrides.

Keep explicit native adoption, but block shared Claude sources when an
independent same-name native plugin could shadow their hooks. Extract the
existing adoption decision so the preview function becomes smaller.

* test(plugin): respect OMP update safety in version control

Check generic and target versions during review, then confirm the existing
OMP upgrade guard preserves the installed and default-source versions.

* fix(plugin): declare first local native imports explicitly

A first local import into a shared source target now changes that target
to native-only intent while preserving its sync selection. Verified source
reimports retain their reviewed source and the preview discloses conversion.

Cover the explicit import, local sync, and other-host cleanup flow, and
remove the unconsumed internal observation assertion from the OMP test.

* docs(plugin): explain first local import intent changes

Describe the shared native-only target conversion and its effect on other
machines, while distinguishing verified source reimports.

* fix(plugin): verify checked sources before native reinstalls

A checked update that becomes an install after native removal must still
match the source digest the user approved. Reject moved or unchecked
sources before native work, and allow a stable approved reinstall.

Clear completed reinstalls from dashboard update availability while keeping
failed targets available for retry. Cover both native presence states in
the existing checked-update tests and the dashboard outcome rule.

* fix(plugin): guard replacement before cleanup

* fix(plugin): refresh discovery for each manager action

A later Add action must review the current source even when the manager
previously observed that source. Keep discovery sharing across one action
while ending its cache before the next wizard invocation.

Exercise a fresh source version after an earlier Add preview without TTY
input or native writes, using an unavailable client to stop at review.

* test(plugin): cover desired checks and final update outcomes

Consolidate checked batch approval and dashboard completion tests while
retaining removed-native, digest, version and approval controls. Reproduce
stale shared recipes and failed or unfinished replacement installs.

* test(plugin): make stale source discovery observable

Remove the old repository before native-only and npm desired checks so
those existing cases cannot pass by reading the applied source.

* fix(plugin): check desired source and final outcome

* test(plugin): bind checked updates to the observed recipe

Reproduce a shared candidate change with equal version, commit and digest,
and preserve a freshly checked replacement whose native ID differs. Use
actual check observations in approval and native update controls, reject
missing source identity, and verify the UI carries the observation through.

* fix(plugin): bind checked update to source recipe

* fix(ui): classify npm recipes as Pi packages

* fix(plugin): retain legacy removal intent during migration

Omit pending removals from shared declarations while retaining original local ownership proof so sync retries cleanup.

Verification: focused regression passed in an isolated Linux Codex container, not the devcontainer (GOMAXPROCS=4, -p=4).

* fix(plugin): keep imports local to an existing shared recipe

Adopt a native installation into its local receipt without converting the shared source target or removing other machines installations.

Verification: focused import regressions passed in an isolated Linux Codex container, not the devcontainer (GOMAXPROCS=4, -p=4).

* fix(plugin): capture legacy evidence on first read

Persist passive hints before another machine writes v2 and save verified adoption on reads. Apply reuses preview receipts instead of querying every legacy binding again. Document the per-machine pre-migration read.

Verification: migration regressions passed in isolated Linux Codex container runs, not the devcontainer (GOMAXPROCS=4, -p=4).

* fix(plugin): target named declarations in interactive imports

Offer unresolved package names in dashboard and TUI imports and pass the selected name in single and batch requests. Drop display-only rendered assertions.

Verification: 47 UI tests passed with at most four workers in an isolated Linux Codex container, not the devcontainer.

* fix(plugin): localize shared intent plan guidance

Add message keys for local imports, account changes, cleanup and native collisions across all dashboard locales. Localized guidance contains no CLI flags.

Verification: failing localization regression now passes in an isolated Linux Codex container, not the devcontainer (GOMAXPROCS=4, -p=4).

* refactor(plugin): reuse preview inventory and guard apply boundaries

Capture hints on first load without persisting in-memory adoption during preview, keeping approval revisions stable. Apply reuses preview inventory. Reuse accountEnv and guard applyChange plus native write boundaries without inspecting argv.

Verification: migration, receipt, account and sync regressions passed in an isolated Linux Codex container, not the devcontainer (GOMAXPROCS=4, -p=4).

* test(plugin): organize host state coverage around lifecycle scenarios

Group migration, ref drift, account context and cleanup tests behind shared host fixtures and public Preview/Apply assertions. Cover Codex, Cursor, Antigravity and project scopes; add second-machine doctor coverage and the two-machine runbook. Consolidate package-version tests and remove the unused private-record fixture.

Verification: focused plugin regressions passed in an isolated Linux Codex container, not the devcontainer (GOMAXPROCS=4, -p=4).

* docs(plugin): explain local imports and per-machine migration

Document local receipts, per-machine review and commit pinning, config-path state identity and the required legacy read on every machine. Align sharing, doctor, troubleshooting, file-layout and four translated plugin references; restore schema editing guidance.

Verification: context-router check passed. Runtime verification uses an isolated Linux Codex container, not the devcontainer.

* refactor(plugin): separate unrelated review scope

Move project OMP configuration, plugin list ordering, and npm Pi classification to independent local branches based on upstream/main. Keep the shared intent change focused and cover named import selection in the pure flow helper.

The three local branches have passing builds in a Linux Codex container, not the devcontainer, with isolated test homes and capped parallelism.

* perf(plugin): avoid recapturing v2 state on reads

Only compare and persist passive migration hints when legacy bindings exist. Native v2 reads need no state serialization for migration.

Verification: pending removal and first-read/import regressions passed in a Linux Codex container, not the devcontainer, with isolated HOME/XDG/TMPDIR and GOMAXPROCS=4 GOFLAGS=-p=4.

* docs(plugin): clarify native marketplace repair after import

A local import receipt is not a reviewed reinstall source. Correct the remaining troubleshooting instruction and its four translations to require native-client repair, and align the nearby code comment.

Validation: checked against prepareChange, context-router check and git diff --check passed. Verification for this review ran in a Linux Codex container, not the devcontainer.

* fix(plugins): preserve local ownership across shared intent changes

Retain completed legacy migration markers so unchanged v1 YAML cannot
uninstall a later manual reinstall. Serialize read-side hint persistence
with native operations and keep local imports when shared recipes change.
Require explicit dashboard import names and validate recipe identities.

Correct schema descriptions, messages, CLI ref status, translated migration
guidance and runbooks. Add failing-first Preview/Apply regressions and a
real two-ssenv CLI lifecycle script.

* fix(plugins): preserve migration history and show retained import guidance

Mark existing legacy hints and receipts as captured before cleanup so state
from the previous serializer cannot re-adopt a later manual installation.
Keep recipe-change guidance in unchanged sync outcomes and visible dashboard
rows, and resolve nested OpenCode entries through their package manifest.

Cover public migration, ref, account, import and message contracts across
adapters. Correct the real two-host Cursor assertions, explicit dashboard
selection flow, and remaining localized guidance.

* fix(plugins): retain explicit OpenCode entry during import matching

Standalone OpenCode packages can rely on a reviewed explicit entry rather
than an SDK dependency. Preserve that entry when reading native package
identity so matching nested imports remain supported.

* fix(plugins): preserve migrated imports and verify native entry identity

Recognize older native-only receipts by their existing declaration
fingerprint so remote source recipe edits cannot replace migrated imports.
Keep managed npm receipts distinct through their source fingerprints.

Only borrow an ancestor OpenCode package identity when its resolved entry
is the actual registered file. Retain nested and explicit entry support.
Add public two-host migration and mismatching-entry regressions.

* fix(plugins): retain imported ownership through repeated adds

Persist inferred imported ownership when a matching add refreshes the
receipt intent, so later shared recipe changes still preserve local
native installations. Keep the legacy replacement regression aligned
with that ownership contract while retaining removed-intent cleanup.

Reject missing or unstatable absolute OpenCode entries before identity
matching rather than falling back to the file name. Cover both paths
through public Preview and Apply regressions.

* test(plugins): isolate OpenCode adapter fixtures from host config

Keep native registration fixtures inside their fake agent home by setting
XDG_CONFIG_HOME and clearing inherited OpenCode overrides. Ambient config
writes can otherwise leak into config-discovery tests in other packages.

Cover the XDG, file, directory and inline override cases with temporary
config sentinels, while retaining the existing MCP listing expectation.

* fix(plugin): let local imports return to the shared source

Add a local unimport action that removes only this machine’s installation and receipt while preserving the shared source declaration. Keep retained-import guidance visible across matching adds, list, doctor and dashboard consumers.

Avoid idle OMP guidance and unchanged legacy-read locks, preserve localized errors, keep import identity checks offline, and normalize OpenCode drive URLs. Cover the A/B transition and align translations, runbooks and environment cleanup.

* fix(plugin): complete unimport validation and guidance

Reject missing targets before planning local unimports and share per-target eligibility with the wizard. Make native uninstall effects explicit in help and translated docs, preserve structured update guidance, and cover error paths and shell completion.
2026-10-31 04:23:20 +08:00

1200 lines
48 KiB
Go

package plugin
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"testing"
)
func fixture(t *testing.T) string {
t.Helper()
root := t.TempDir()
for name, content := range map[string]string{".claude-plugin/plugin.json": `{"name":"demo","version":"1.0.0"}`, ".codex-plugin/plugin.json": `{"name":"demo","version":"1.0.0","skills":"./skills"}`, "skills/demo/SKILL.md": "---\nname: demo\ndescription: Demo\n---\nHello"} {
p := filepath.Join(root, name)
if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(content), 0644); err != nil {
t.Fatal(err)
}
}
return root
}
func TestDiscoverPreservesComponentsAndLeavesOutEscapes(t *testing.T) {
root := fixture(t)
d, err := Discover(context.Background(), root)
if err != nil {
t.Fatal(err)
}
if len(d.Candidates) != 1 || len(d.Candidates[0].Targets) != 6 {
t.Fatalf("unexpected discovery: %+v", d)
}
if err := os.Symlink("/etc/passwd", filepath.Join(root, "escape")); err != nil {
t.Fatal(err)
}
if escaped, err := Discover(context.Background(), root); err != nil || escaped.Digest != d.Digest || len(escaped.Warnings) != 1 {
t.Fatalf("external symlink not left out: %+v %v", escaped, err)
}
}
func TestNativeInventoryStrict(t *testing.T) {
for _, target := range []string{"claude", "codex"} {
if _, err := parseInventory(target, []byte(`{"unexpected":[]}`), ""); err == nil {
t.Fatal("unknown schema accepted")
}
}
items, err := parseInventory("codex", []byte(`{"installed":[{"pluginId":"demo@market","name":"demo","marketplaceName":"market","installed":true,"enabled":false,"version":"1"}],"available":[]}`), "")
if err != nil || len(items) != 1 || items[0].Enabled {
t.Fatalf("%+v %v", items, err)
}
}
func TestClaudeInventoryIgnoresOtherScopesBeforeValidating(t *testing.T) {
data := []byte(`[{"id":"demo@market","scope":"user"},{"id":"(suppressed)@skills-dir","scope":"project","projectPath":"/home/me"}]`)
items, err := parseInventory("claude", data, "")
if err != nil || len(items) != 1 || items[0].ID != "demo@market" {
t.Fatalf("%+v %v", items, err)
}
if _, err := parseInventory("claude", data, "/home/me"); err == nil {
t.Fatal("unsupported identifier in the active project accepted")
}
}
func TestPreviewCancelStaleAndPartialRetry(t *testing.T) {
root := fixture(t)
home := t.TempDir()
config := filepath.Join(home, "config.yaml")
if err := os.WriteFile(config, []byte("# keep me\nmode: merge\n"), 0644); err != nil {
t.Fatal(err)
}
installed := map[string][]Installed{"claude": {}, "codex": {}}
failCodex := true
mutations := 0
runner := func(ctx context.Context, dir string, env []string, bin string, args ...string) ([]byte, error) {
joined := strings.Join(args, " ")
if joined == "--version" {
return []byte("test-version"), nil
}
if strings.Contains(joined, "--help") {
return []byte("install add remove uninstall update enable disable --json --scope"), nil
}
if joined == "plugin list --json" {
if bin == "codex" {
return json.Marshal(map[string]any{"installed": installed[bin], "available": []any{}})
}
return json.Marshal(installed[bin])
}
if joined == "plugin marketplace list --json" {
if bin == "codex" {
return []byte(`{"marketplaces":[]}`), nil
}
return []byte(`[]`), nil
}
mutations++
if bin == "codex" && failCodex {
return nil, fmt.Errorf("offline")
}
if len(args) > 2 && (args[1] == "install" || args[1] == "add") {
installed[bin] = append(installed[bin], Installed{ID: args[2], PluginID: args[2], Installed: true, Enabled: true, Scope: "user"})
}
return []byte(`{}`), nil
}
s := &Service{ConfigPath: config, StateDir: filepath.Join(home, "state"), Run: runner}
req := Request{Action: "add", Source: root, Plugin: "demo", Targets: []string{"claude", "codex"}}
p, err := s.Preview(context.Background(), req)
if err != nil {
t.Fatal(err)
}
if mutations != 0 {
t.Fatal("preview mutated native state")
}
if _, err := os.Stat(s.StateDir); !os.IsNotExist(err) {
t.Fatal("preview created state")
}
if err := os.WriteFile(config, []byte("# changed\nmode: merge\n"), 0644); err != nil {
t.Fatal(err)
}
if _, err := s.Apply(context.Background(), req, p.Revision); err == nil {
t.Fatal("stale preview accepted")
}
p, err = s.Preview(context.Background(), req)
if err != nil {
t.Fatal(err)
}
result, err := s.Apply(context.Background(), req, p.Revision)
if err == nil || len(result.Results) != 2 {
t.Fatalf("expected partial result: %+v %v", result, err)
}
failCodex = false
req = Request{Action: "sync"}
p, err = s.Preview(context.Background(), req)
if err != nil {
t.Fatal(err)
}
before := mutations
result, err = s.Apply(context.Background(), req, p.Revision)
if err != nil {
t.Fatal(err)
}
if mutations-before != 2 {
t.Fatalf("retry repeated successful target: %d", mutations-before)
}
data, _ := os.ReadFile(config)
if !strings.Contains(string(data), "# changed") {
t.Fatal("lost user comment")
}
}
func TestProjectCodexNeverFallsBackToGlobal(t *testing.T) {
s := &Service{ConfigPath: filepath.Join(t.TempDir(), "config.yaml"), ProjectRoot: t.TempDir(), StateDir: t.TempDir()}
p, err := s.Preview(context.Background(), Request{Action: "add", Source: fixture(t), Plugin: "demo", Targets: []string{"codex"}})
if err != nil {
t.Fatal(err)
}
if !p.Blocked {
t.Fatal("project Codex install was not blocked")
}
}
func TestSyncSelectionDoesNotToggleNativeEnabledState(t *testing.T) {
dir := t.TempDir()
config := filepath.Join(dir, "config.yaml")
err := os.WriteFile(config, []byte("plugins:\n packages:\n demo:\n bindings:\n codex:\n id: demo@market\n"), 0600)
if err != nil {
t.Fatal(err)
}
installed := true
mutations := []string{}
s := &Service{ConfigPath: config, StateDir: filepath.Join(dir, "state"), Run: func(ctx context.Context, dir string, env []string, target string, args ...string) ([]byte, error) {
joined := strings.Join(args, " ")
if joined == "--version" {
return []byte("0.154.0"), nil
}
if strings.Contains(joined, "--help") {
return []byte("--json"), nil
}
if joined == "plugin list --json" {
if installed {
return []byte(`{"installed":[{"pluginId":"demo@market","installed":true,"enabled":false}],"available":[]}`), nil
}
return []byte(`{"installed":[],"available":[]}`), nil
}
if joined == "plugin marketplace list --json" {
return []byte(`{"marketplaces":[{"name":"market","root":"/market"}]}`), nil
}
mutations = append(mutations, joined)
if strings.HasPrefix(joined, "plugin remove") {
installed = false
}
if strings.HasPrefix(joined, "plugin add") {
installed = true
}
return []byte(`{}`), nil
}}
apply := func(action string) {
t.Helper()
r := Request{Action: action, Name: "demo", Targets: []string{"codex"}}
p, e := s.Preview(context.Background(), r)
if e != nil {
t.Fatal(e)
}
if _, e = s.Apply(context.Background(), r, p.Revision); e != nil {
t.Fatal(e)
}
}
apply("disable")
if len(mutations) != 0 || !installed {
t.Fatal("deselect changed native installation")
}
apply("sync")
if installed {
t.Fatal("sync did not remove excluded plugin")
}
d, err := s.load()
if err != nil {
t.Fatal(err)
}
b, ok := d.packages["demo"].Bindings["codex"]
if !ok || b.Selected() {
t.Fatal("excluded definition was lost")
}
apply("enable")
if installed {
t.Fatal("select installed immediately")
}
apply("sync")
if !installed {
t.Fatal("sync did not restore installation")
}
if len(mutations) != 2 || strings.Contains(strings.Join(mutations, " "), "enable") {
t.Fatalf("unexpected native mutation: %v", mutations)
}
}
func TestAddWithoutTargetsKeepsPackageForLater(t *testing.T) {
root := fixture(t)
s, installed, mutations := fakeClaude(t)
apply := func(r Request) *Plan {
t.Helper()
p, err := s.Preview(context.Background(), r)
if err != nil {
t.Fatal(err)
}
if _, err := s.Apply(context.Background(), r, p.Revision); err != nil {
t.Fatal(err)
}
return p
}
writeFile(t, root, ".codex-plugin/plugin.json", `{"name":"demo","version":"1.0.0","skills":"./skills","interface":{"logo":"./logo.png"}}`)
writeFile(t, root, "logo.png", "png")
p := apply(Request{Action: "add", Source: root, Plugin: "demo"})
if len(p.Changes) != 1 || p.Changes[0].Action != "record" || *mutations != 0 {
t.Fatalf("add without targets touched an Agent: %+v %d", p.Changes, *mutations)
}
d, _ := s.load()
if pack, ok := d.packages["demo"]; !ok || pack.Source == "" || len(pack.Bindings) != 0 {
t.Fatalf("package not kept for later: %+v", d.packages)
}
if p.Changes[0].Logo != "data:image/png;base64,cG5n" {
t.Fatalf("preview lost the Codex logo: %q", p.Changes[0].Logo)
}
if d.packages["demo"].Version != "1.0.0" {
t.Fatalf("lost local reviewed version: %+v", d.packages["demo"])
}
shared, err := decodeDocument(d.raw, nil)
if err != nil || len(shared.legacy) != 0 || shared.intent["demo"].Source != root {
t.Fatalf("shared intent cached local metadata: %s %v", d.raw, err)
}
apply(Request{Action: "add", Name: "demo", Source: root, Plugin: "demo", Targets: []string{"claude"}})
apply(Request{Action: "remove", Name: "demo", Targets: []string{"claude"}})
if d, _ = s.load(); len(*installed) != 0 || d.packages["demo"].Source == "" {
t.Fatalf("removing the last Agent dropped the package: %+v %+v", *installed, d.packages)
}
apply(Request{Action: "remove", Name: "demo"})
if d, _ = s.load(); len(d.packages) != 0 {
t.Fatalf("remove kept the package: %+v", d.packages)
}
}
// fakeClaude answers like a Claude Code CLI with an empty inventory, and counts the calls that change it.
func fakeClaude(t *testing.T) (*Service, *[]Installed, *int) {
home := t.TempDir()
installed := []Installed{}
mutations := 0
s := &Service{ConfigPath: filepath.Join(home, "config.yaml"), StateDir: filepath.Join(home, "state"), Run: func(ctx context.Context, dir string, env []string, bin string, args ...string) ([]byte, error) {
joined := strings.Join(args, " ")
switch {
case joined == "--version":
return []byte("test-version"), nil
case strings.Contains(joined, "--help"):
return []byte("install add remove uninstall update enable disable --json --scope"), nil
case joined == "plugin list --json":
return json.Marshal(installed)
case joined == "plugin marketplace list --json":
return []byte(`[]`), nil
}
mutations++
if len(args) > 2 && args[1] == "install" {
installed = append(installed, Installed{ID: args[2], PluginID: args[2], Installed: true, Enabled: true, Scope: "user"})
}
if len(args) > 2 && args[1] == "uninstall" {
installed = []Installed{}
}
return []byte(`{}`), nil
}}
return s, &installed, &mutations
}
func TestCheckReportsTheSourceVersion(t *testing.T) {
root := fixture(t)
s, _, _ := fakeClaude(t)
r := Request{Action: "add", Source: root, Plugin: "demo", Targets: []string{"claude"}}
p, err := s.Preview(context.Background(), r)
if err != nil {
t.Fatal(err)
}
if _, err := s.Apply(context.Background(), r, p.Revision); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, ".claude-plugin/plugin.json"), []byte(`{"name":"demo","version":"1.1.0"}`), 0644); err != nil {
t.Fatal(err)
}
p, err = s.Preview(context.Background(), Request{Action: "check"})
if err != nil || len(p.Changes) != 1 || p.Changes[0].Action != "update-available" || p.Changes[0].Binding.Version != "1.1.0" {
t.Fatalf("check did not report the new version: %+v %v", p, err)
}
}
// A local directory has no commit: the digest is all that tells the content the check saw
// from what an update would install, so the check must carry it.
func TestCheckCarriesTheSourceDigestTheUpdateWouldInstall(t *testing.T) {
root := fixture(t)
s, _, _ := fakeClaude(t)
r := Request{Action: "add", Source: root, Plugin: "demo", Targets: []string{"claude"}}
p, err := s.Preview(context.Background(), r)
if err != nil {
t.Fatal(err)
}
if _, err := s.Apply(context.Background(), r, p.Revision); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "skills", "extra.md"), []byte("changed"), 0644); err != nil {
t.Fatal(err)
}
check, err := s.Preview(context.Background(), Request{Action: "check"})
if err != nil || len(check.Changes) != 1 || check.Changes[0].Action != "update-available" {
t.Fatalf("check did not report the change: %+v %v", check, err)
}
update, err := s.Preview(context.Background(), Request{Action: "update", Name: "demo", Targets: []string{"claude"}})
if err != nil || len(update.Changes) != 1 {
t.Fatalf("update preview: %+v %v", update, err)
}
if got, want := check.Changes[0].Binding.Digest, update.Changes[0].Binding.Digest; got == "" || got != want {
t.Fatalf("check digest %q, update digest %q", got, want)
}
}
func TestManagedMarketplaceNameShowsThePlugin(t *testing.T) {
root := fixture(t)
for _, manifest := range []string{".claude-plugin/plugin.json", ".codex-plugin/plugin.json"} {
if err := os.WriteFile(filepath.Join(root, manifest), []byte(`{"name":"my.demo","version":"1.0.0"}`), 0644); err != nil {
t.Fatal(err)
}
}
s, _, _ := fakeClaude(t)
p, err := s.Preview(context.Background(), Request{Action: "add", Source: root, Plugin: "my.demo", Targets: []string{"claude"}})
if err != nil || len(p.Changes) != 1 {
t.Fatalf("preview failed: %+v %v", p, err)
}
// Codex rejects marketplace names outside ASCII letters, digits, `_`, and `-`.
if id := p.Changes[0].ID; !regexp.MustCompile(`^my\.demo@skillshare-my-demo-[0-9a-f]{16}$`).MatchString(id) {
t.Fatalf("marketplace name does not show the plugin: %s", id)
}
}
func TestFailedNativeCommandOutcomeCarriesItsKey(t *testing.T) {
s, _, _ := fakeClaude(t)
run := s.Run
s.Run = func(ctx context.Context, dir string, env []string, bin string, args ...string) ([]byte, error) {
if len(args) > 1 && args[1] == "install" && !slices.Contains(args, "--help") {
return nil, agentError{key: "plugins.error.commandFailed", message: "claude command failed"}
}
return run(ctx, dir, env, bin, args...)
}
r := Request{Action: "add", Source: fixture(t), Plugin: "demo", Targets: []string{"claude"}}
p, err := s.Preview(context.Background(), r)
if err != nil {
t.Fatal(err)
}
result, err := s.Apply(context.Background(), r, p.Revision)
if result == nil || len(result.Results) != 1 || result.Results[0].MessageKey != "plugins.error.commandFailed" {
t.Fatalf("failed outcome lost its translation key: %+v %v", result, err)
}
}
func TestExcludingAManagedPluginRemovesItsMarketplace(t *testing.T) {
agents := &fakeAgents{version: "1.0.0"}
s := agents.service(t)
applyPluginRequest(t, s, Request{Action: "add", Source: fixture(t), Targets: []string{"claude", "codex"}})
if len(agents.markets["claude"]) != 1 || len(agents.markets["codex"]) != 1 {
t.Fatalf("install did not register marketplaces: %v", agents.markets)
}
applyPluginRequest(t, s, Request{Action: "disable", Name: "demo", Targets: []string{"claude", "codex"}})
applyPluginRequest(t, s, Request{Action: "sync"})
if len(agents.markets["claude"]) != 0 || len(agents.markets["codex"]) != 0 {
t.Fatalf("Skillshare marketplaces were left behind: %v", agents.markets)
}
}
func TestAddingAClaudePluginNamedLikeASkillFolderExplainsTheClash(t *testing.T) {
agents := &fakeAgents{installed: map[string][]Installed{"claude": {{ID: "demo@skills-dir", PluginID: "demo@skills-dir", Installed: true, Enabled: true, Scope: "user"}}}}
s := agents.service(t)
p, err := s.Preview(context.Background(), Request{Action: "add", Source: fixture(t), Targets: []string{"claude"}})
if err != nil || len(p.Changes) != 1 || p.Changes[0].Action != "install" || p.Changes[0].MessageKey != "plugins.note.skillsDirClash" {
t.Fatalf("preview did not explain the skill folder clash: %+v %v", p, err)
}
}
// legacyBinding records a plugin under the older skillshare-<hash> marketplace name, whose
// marketplace is still registered although the plugin itself is gone.
func legacyBinding(t *testing.T, s *Service, agents *fakeAgents, extra string) Binding {
t.Helper()
b := Binding{ID: "demo@skillshare-0123456789abcdef", Source: "https://example.com/demo", Plugin: "demo"}
writePluginFile(t, filepath.Dir(s.ConfigPath), "config.yaml", "plugins:\n packages:\n demo:\n bindings:\n claude:\n id: "+b.ID+"\n source: "+b.Source+"\n plugin: demo\n"+extra)
agents.market("claude")["skillshare-0123456789abcdef"] = s.snapshotPath(b, "claude")
seedLocalBinding(t, s, "demo", "claude", b)
return b
}
func TestExcludingAPluginAlreadyGoneStillRemovesItsMarketplace(t *testing.T) {
agents := &fakeAgents{}
s := agents.service(t)
legacyBinding(t, s, agents, " sync: false\n")
p, err := s.Preview(context.Background(), Request{Action: "sync"})
if err != nil || len(p.Changes) != 1 || p.Changes[0].Action != "uninstall" || p.Changes[0].MessageKey != "plugins.note.marketplaceCleanup" {
t.Fatalf("sync did not plan the marketplace cleanup: %+v %v", p, err)
}
applyPluginRequest(t, s, Request{Action: "sync"})
if len(agents.markets["claude"]) != 0 || !slices.Equal(agents.commands, []string{"claude plugin marketplace remove skillshare-0123456789abcdef"}) {
t.Fatalf("cleanup ran %q, left %v", agents.commands, agents.markets)
}
}
func TestRemovingAPluginAlreadyGoneRemovesItsMarketplace(t *testing.T) {
agents := &fakeAgents{}
s := agents.service(t)
legacyBinding(t, s, agents, "")
applyPluginRequest(t, s, Request{Action: "remove", Name: "demo"})
inv, err := s.Packages()
if err != nil || len(agents.markets["claude"]) != 0 || len(inv.Packages) != 0 {
t.Fatalf("remove left %v, packages %v, err %v", agents.markets, inv, err)
}
}
func TestFailedMarketplaceCleanupIsRetriedOnTheNextSync(t *testing.T) {
agents := &fakeAgents{version: "1.0.0"}
s := agents.service(t)
applyPluginRequest(t, s, Request{Action: "add", Source: fixture(t), Targets: []string{"claude"}})
applyPluginRequest(t, s, Request{Action: "disable", Name: "demo", Targets: []string{"claude"}})
agents.failRemove = 1
r := Request{Action: "sync"}
p, err := s.Preview(context.Background(), r)
if err != nil {
t.Fatal(err)
}
result, _ := s.Apply(context.Background(), r, p.Revision)
if result == nil || len(result.Results) != 1 || result.Results[0].MessageKey != "plugins.error.marketplaceCleanup" {
t.Fatalf("cleanup failure was not reported: %+v", result)
}
applyPluginRequest(t, s, r)
if len(agents.markets["claude"]) != 0 {
t.Fatalf("retry left %v", agents.markets)
}
}
func TestMarketplaceStillRegisteredAfterRemovalIsReported(t *testing.T) {
agents := &fakeAgents{stuck: true}
s := agents.service(t)
legacyBinding(t, s, agents, " sync: false\n")
r := Request{Action: "sync"}
p, err := s.Preview(context.Background(), r)
if err != nil {
t.Fatal(err)
}
if _, err := s.Apply(context.Background(), r, p.Revision); err == nil {
t.Fatal("a marketplace that survived removal was reported as removed")
}
}
func TestForeignMarketplaceWithTheSameNameIsLeftAlone(t *testing.T) {
agents := &fakeAgents{}
s := agents.service(t)
legacyBinding(t, s, agents, " sync: false\n")
agents.market("claude")["skillshare-0123456789abcdef"] = "/elsewhere"
applyPluginRequest(t, s, Request{Action: "sync"})
if len(agents.commands) != 0 || agents.markets["claude"]["skillshare-0123456789abcdef"] != "/elsewhere" {
t.Fatalf("foreign marketplace was touched: %q %v", agents.commands, agents.markets)
}
}
func TestRemoveKeepsTheBindingWhileMarketplacesAreUnknown(t *testing.T) {
agents := &fakeAgents{}
s := agents.service(t)
legacyBinding(t, s, agents, "")
run := s.Run
s.Run = func(ctx context.Context, dir string, env []string, bin string, args ...string) ([]byte, error) {
if strings.Join(args, " ") == "plugin marketplace list --json" {
return []byte(`not json`), nil
}
return run(ctx, dir, env, bin, args...)
}
r := Request{Action: "remove", Name: "demo"}
p, err := s.Preview(context.Background(), r)
if err != nil || len(p.Changes) == 0 || p.Changes[0].Action != "remove" {
t.Fatalf("remove forgot a binding whose marketplace may remain: %+v %v", p, err)
}
_, _ = s.Apply(context.Background(), r, p.Revision)
if inv, err := s.Packages(); err != nil || len(inv.Packages) != 1 {
t.Fatalf("binding was dropped before its marketplace cleanup: %+v %v", inv, err)
}
}
func TestHostReportsOnlyItsOwnManagedMarketplaces(t *testing.T) {
agents := &fakeAgents{}
s := agents.service(t)
b := legacyBinding(t, s, agents, "")
agents.market("claude")["skillshare-foreign"] = "/elsewhere/skillshare-foreign"
agents.market("claude")["team"] = filepath.Join(filepath.Dir(s.snapshotPath(b, "claude")), "team")
if got := s.host(context.Background(), "claude").ManagedMarketplaces; !slices.Equal(got, []string{"skillshare-0123456789abcdef"}) {
t.Fatalf("managed marketplaces = %v", got)
}
}
func TestMarketplaceAlsoDeclaredAtAnotherPathIsNotRemoved(t *testing.T) {
agents := &fakeAgents{}
s := agents.service(t)
b := legacyBinding(t, s, agents, " sync: false\n")
run := s.Run
s.Run = func(ctx context.Context, dir string, env []string, bin string, args ...string) ([]byte, error) {
if strings.Join(args, " ") == "plugin marketplace list --json" {
return json.Marshal([]map[string]string{{"name": "skillshare-0123456789abcdef", "installLocation": s.snapshotPath(b, "claude")}, {"name": "skillshare-0123456789abcdef", "installLocation": "/elsewhere"}})
}
return run(ctx, dir, env, bin, args...)
}
r := Request{Action: "sync"}
p, err := s.Preview(context.Background(), r)
if err != nil {
t.Fatal(err)
}
result, _ := s.Apply(context.Background(), r, p.Revision)
if slices.ContainsFunc(agents.commands, func(c string) bool { return strings.Contains(c, "marketplace remove") }) || result == nil || len(result.Results) != 1 || result.Results[0].MessageKey != "plugins.error.marketplaceCleanup" {
t.Fatalf("removed a marketplace also declared elsewhere: %q %+v", agents.commands, result)
}
}
func TestSyncSkipsAnImportWhoseNativeMarketplaceIsGone(t *testing.T) {
agents := &fakeAgents{installed: map[string][]Installed{"claude": {{ID: "demo@team", Scope: "user", Installed: true}}}, markets: map[string]map[string]string{"claude": {"team": "/team"}}}
s := agents.service(t)
applyPluginRequest(t, s, Request{Action: "import", From: "claude", Plugin: "demo@team"})
if b := readState(t, s).state.Bindings["demo"]["claude"]; b.Applied == nil || b.Applied.Binding.ID != "demo@team" || b.Legacy != nil {
t.Fatal("fixture lacks a locally owned imported receipt")
}
delete(agents.market("claude"), "team")
agents.installed["claude"] = nil
p, err := s.Preview(context.Background(), Request{Action: "sync"})
if err != nil || p.Blocked || len(p.Changes) != 1 || p.Changes[0].Action != "skip" || p.Changes[0].MessageKey != "plugins.skip.marketplaceGone" {
t.Fatalf("sync did not skip the import: %+v %v", p, err)
}
applyPluginRequest(t, s, Request{Action: "sync"})
if len(agents.commands) != 0 {
t.Fatalf("skipped import still ran %q", agents.commands)
}
}
func TestUpdateRegistersAMissingManagedMarketplaceAgain(t *testing.T) {
agents := &fakeAgents{version: "1.0.0"}
s := agents.service(t)
source := fixture(t)
applyPluginRequest(t, s, Request{Action: "add", Source: source, Targets: []string{"claude"}})
agents.markets["claude"] = nil
bumpDemo(t, source, agents)
applyPluginRequest(t, s, Request{Action: "update", Name: "demo", Targets: []string{"claude"}})
if len(agents.markets["claude"]) != 1 || !strings.HasPrefix(agents.commands[0], "claude plugin marketplace add ") {
t.Fatalf("update did not register the marketplace again: %q", agents.commands)
}
}
// homeFixture places the fixture under HOME so its source can be spelled ~/plug.
func homeFixture(t *testing.T) string {
t.Helper()
source := filepath.Join(os.Getenv("HOME"), "plug")
if err := os.CopyFS(source, os.DirFS(fixture(t))); err != nil {
t.Fatal(err)
}
return source
}
func TestSavingPluginsWritesThroughASymlinkedConfig(t *testing.T) {
agents := &fakeAgents{version: "1.0.0"}
s := agents.service(t)
shared := filepath.Join(os.Getenv("HOME"), "dotfiles", "skillshare.yaml")
writeFile(t, filepath.Dir(shared), "skillshare.yaml", "preserve_tilde_on_save: true\n")
if err := os.Symlink(shared, s.ConfigPath); err != nil {
t.Fatal(err)
}
applyPluginRequest(t, s, Request{Action: "add", Source: homeFixture(t), Targets: []string{"claude"}})
if info, err := os.Lstat(s.ConfigPath); err != nil || info.Mode()&os.ModeSymlink == 0 {
t.Fatalf("config.yaml is no longer a symlink: %v", err)
}
data, _ := os.ReadFile(shared)
if !strings.Contains(string(data), "source: ~/plug") || strings.Contains(string(data), os.Getenv("HOME")) {
t.Fatalf("shared config not updated with a ~ source:\n%s", data)
}
}
func TestUpdateAcceptsASourceSpelledWithTilde(t *testing.T) {
agents := &fakeAgents{version: "1.0.0"}
s := agents.service(t)
source := homeFixture(t)
applyPluginRequest(t, s, Request{Action: "add", Source: source, Targets: []string{"claude"}})
data, _ := os.ReadFile(s.ConfigPath)
writeFile(t, filepath.Dir(s.ConfigPath), "config.yaml", strings.ReplaceAll(string(data), source, "~/plug"))
bumpDemo(t, source, agents)
applyPluginRequest(t, s, Request{Action: "update", Name: "demo", Targets: []string{"claude"}})
}
func TestRecordedSourceDoesNotBlockAnotherDistribution(t *testing.T) {
s, _, _ := fakeClaude(t)
r := Request{Action: "add", Source: fixture(t), Plugin: "demo"}
p, err := s.Preview(context.Background(), r)
if err != nil {
t.Fatal(err)
}
if _, err := s.Apply(context.Background(), r, p.Revision); err != nil {
t.Fatal(err)
}
p, err = s.Preview(context.Background(), Request{Action: "add", Source: fixture(t), Plugin: "demo", Name: "demo", Targets: []string{"claude"}})
if err != nil || p.Blocked {
t.Fatalf("another source for one Agent was blocked: %+v %v", p, err)
}
}
// fakeAgents installs plugins like Claude and Codex: installing or updating puts the
// marketplace's current version in place, and Codex's add always enables the plugin.
type fakeAgents struct {
version string
installed map[string][]Installed
// markets maps each Agent to the root of every marketplace registered with it.
markets map[string]map[string]string
// failRemove fails that many marketplace removals; stuck keeps the registration anyway,
// as a copy declared in another Claude settings scope does.
failRemove int
stuck bool
commands []string
}
func (f *fakeAgents) market(bin string) map[string]string {
if f.markets[bin] == nil {
f.markets[bin] = map[string]string{}
}
return f.markets[bin]
}
func (f *fakeAgents) service(t *testing.T) *Service {
t.Helper()
home := t.TempDir()
t.Setenv("HOME", home)
if f.installed == nil {
f.installed = map[string][]Installed{}
}
if f.markets == nil {
f.markets = map[string]map[string]string{}
}
s := &Service{ConfigPath: filepath.Join(home, "config.yaml"), StateDir: filepath.Join(home, "state")}
s.Run = func(_ context.Context, dir string, _ []string, bin string, args ...string) ([]byte, error) {
command := strings.Join(args, " ")
switch {
case command == "--version":
if bin == "omp" {
return []byte("omp/18.8.7"), nil
}
return []byte("test"), nil
case strings.Contains(command, "--help"):
return []byte("--json --scope upgrade"), nil
case command == "plugin list --json" && bin == "codex":
return json.Marshal(map[string]any{"installed": f.installed[bin], "available": []any{}})
case command == "plugin list --json" && bin == "omp":
// omp plugin list --json: npm/link plugins, then marketplace summaries per scope.
npm, market := []map[string]any{}, []map[string]any{}
for _, i := range f.installed[bin] {
if !validID(i.ID) {
npm = append(npm, map[string]any{"name": i.ID, "version": i.Version, "enabled": i.Enabled, "manifest": map[string]any{}})
continue
}
scope := i.Scope
if scope == "" {
scope = "user"
}
market = append(market, map[string]any{"id": i.ID, "scope": scope, "entries": []map[string]any{{"scope": scope, "installPath": ompCachePath(filepath.Join(os.Getenv("HOME"), ".omp/plugins/cache/plugins"), i.ID, i.Version), "version": i.Version, "enabled": i.Enabled}}})
}
return json.Marshal(map[string]any{"npm": npm, "marketplace": market})
case command == "plugin marketplace list" && bin == "omp":
var text strings.Builder
text.WriteString("Configured Marketplaces:\n\n")
for name, root := range f.market(bin) {
text.WriteString(" \x1b[36m" + name + "\x1b[39m \x1b[2m" + root + "\x1b[22m\n")
}
return []byte(text.String()), nil
case command == "plugin list --json":
return json.Marshal(append([]Installed{}, f.installed[bin]...))
case command == "plugin marketplace list --json":
list := []map[string]string{}
for name, root := range f.market(bin) {
if bin == "codex" {
list = append(list, map[string]string{"name": name, "root": root})
} else {
list = append(list, map[string]string{"name": name, "installLocation": root})
}
}
if bin == "codex" {
return json.Marshal(map[string]any{"marketplaces": list})
}
return json.Marshal(list)
}
f.commands = append(f.commands, bin+" "+command)
switch {
case args[1] == "marketplace" && args[2] == "add":
f.market(bin)[filepath.Base(args[3])] = args[3]
case args[1] == "marketplace" && args[2] == "remove":
if f.failRemove > 0 {
f.failRemove--
return nil, agentError{key: "plugins.error.commandFailed", message: bin + " command failed"}
}
// Like Claude, a scoped removal fails when only known_marketplaces.json records it.
if slices.Contains(args, "--scope") {
return nil, agentError{key: "plugins.error.commandFailed", message: "Marketplace '" + args[3] + "' is not declared in user settings"}
}
if !f.stuck {
delete(f.market(bin), args[3])
}
case args[1] == "add" || args[1] == "install" || args[1] == "update" || args[1] == "upgrade":
scope := "user"
if i := slices.Index(args, "--scope"); i >= 0 {
scope = args[i+1]
}
enabled := true
// OMP's upgrade reinstalls from the marketplace and keeps a disabled plugin disabled.
if args[1] == "upgrade" {
for _, i := range f.installed[bin] {
if i.ID == args[2] {
enabled = i.Enabled
}
}
}
f.installed[bin] = []Installed{{ID: args[2], PluginID: args[2], Installed: true, Enabled: enabled, Version: f.version, Scope: scope, ProjectPath: dir}}
case args[1] == "remove" || args[1] == "uninstall":
f.installed[bin] = nil
}
return []byte(`{}`), nil
}
return s
}
// bumpDemo releases version 2.0.0 of the fixture's plugin.
func bumpDemo(t *testing.T, source string, agents *fakeAgents) {
t.Helper()
writeFile(t, source, ".claude-plugin/plugin.json", `{"name":"demo","version":"2.0.0"}`)
writeFile(t, source, ".codex-plugin/plugin.json", `{"name":"demo","version":"2.0.0","skills":"./skills"}`)
agents.version, agents.commands = "2.0.0", nil
}
// Codex has no update command, so an update adds the plugin again from the new snapshot.
func TestCodexUpdateAddsThePluginAgain(t *testing.T) {
agents := &fakeAgents{version: "1.0.0"}
s := agents.service(t)
source := fixture(t)
applyPluginRequest(t, s, Request{Action: "add", Source: source, Targets: []string{"codex"}})
bumpDemo(t, source, agents)
applyPluginRequest(t, s, Request{Action: "update", Name: "demo", Targets: []string{"codex"}})
if len(agents.commands) != 1 || !strings.HasPrefix(agents.commands[0], "codex plugin add demo@") {
t.Fatalf("commands: %q", agents.commands)
}
}
// Adding would turn a plugin disabled in Codex back on, so the update skips it, and the
// other Agents of the plugin are still updated.
func TestCodexUpdateSkipsADisabledPlugin(t *testing.T) {
agents := &fakeAgents{version: "1.0.0"}
s := agents.service(t)
source := fixture(t)
applyPluginRequest(t, s, Request{Action: "add", Source: source, Targets: []string{"claude", "codex"}})
agents.installed["codex"][0].Enabled = false
bumpDemo(t, source, agents)
applyPluginRequest(t, s, Request{Action: "update", Name: "demo", Targets: []string{"claude", "codex"}})
if slices.ContainsFunc(agents.commands, func(c string) bool { return strings.HasPrefix(c, "codex ") }) || !slices.Contains(agents.commands, "claude plugin update "+agents.installed["claude"][0].ID+" --scope user --json") {
t.Fatalf("commands: %q", agents.commands)
}
}
// An imported plugin has no reviewed source; Codex upgrades it with its marketplace.
func TestCodexUpdateOfAnImportUpgradesItsMarketplace(t *testing.T) {
agents := &fakeAgents{installed: map[string][]Installed{"codex": {{PluginID: "demo@team", Installed: true, Enabled: true, Version: "1.0.0"}}}, markets: map[string]map[string]string{"codex": {"team": "/team"}}}
s := agents.service(t)
applyPluginRequest(t, s, Request{Action: "import", From: "codex", Plugin: "demo@team"})
agents.commands = nil
applyPluginRequest(t, s, Request{Action: "update", Name: "demo", Targets: []string{"codex"}})
if !slices.Equal(agents.commands, []string{"codex plugin marketplace upgrade team"}) {
t.Fatalf("commands: %q", agents.commands)
}
}
// importedDemo imports demo@team from Claude into a package that also has a source, as when
// another Agent was added from it, and leaves the Claude update pending at 1.0.0.
func importedDemo(t *testing.T) (*Service, *fakeAgents) {
t.Helper()
agents := &fakeAgents{version: "2.0.0", installed: map[string][]Installed{"claude": {{ID: "demo@team", PluginID: "demo@team", Installed: true, Enabled: true, Version: "1.0.0", Scope: "user"}}}, markets: map[string]map[string]string{"claude": {"team": "/team"}}}
s := agents.service(t)
applyPluginRequest(t, s, Request{Action: "import", From: "claude", Plugin: "demo@team"})
source := fixture(t)
applyPluginRequest(t, s, Request{Action: "add", Name: "demo", Source: source})
run := s.Run
s.Run = func(ctx context.Context, dir string, env []string, bin string, args ...string) ([]byte, error) {
if bin == "claude" && len(args) > 1 && args[0] == "plugin" && args[1] == "update" && !slices.Contains(args, "--help") {
return nil, fmt.Errorf("native update failed")
}
return run(ctx, dir, env, bin, args...)
}
applyFailure(t, s, Request{Action: "update", Name: "demo", Targets: []string{"claude"}})
s.Run = run
cfg := readState(t, s)
pack := cfg.packages["demo"]
local := cfg.state.Bindings["demo"]["claude"]
if pack.Source != source || pack.Bindings["claude"].Source != "" || !pack.Bindings["claude"].Imported {
t.Fatal("fixture lacks source intent with an imported Claude override")
}
if local.Applied == nil || local.Pending == nil || local.Pending.Action != "update" || local.Pending.Binding.Version != "1.0.0" || local.Pending.Intent != cfg.intent["demo"].Bindings["claude"].fingerprint() {
t.Fatal("fixture lacks a pending owned Claude update at 1.0.0")
}
if len(cfg.state.Bindings["demo"]) != 1 {
t.Fatal("fixture includes a foreign target receipt")
}
return s, agents
}
func loadBinding(t *testing.T, s *Service) Binding {
t.Helper()
cfg, err := s.load()
if err != nil {
t.Fatal(err)
}
return cfg.packages["demo"].Bindings["claude"]
}
// An imported plugin updates to whatever its native marketplace now holds, and records it.
func TestClaudeUpdateOfAnImportRecordsTheVersionItInstalled(t *testing.T) {
s, _ := importedDemo(t)
applyPluginRequest(t, s, Request{Action: "update", Name: "demo", Targets: []string{"claude"}})
if b := loadBinding(t, s); b.Version != "2.0.0" || b.Pending != "" {
t.Fatalf("binding: %+v", b)
}
}
// The dashboard's batch update takes the same path for an import.
func TestBatchUpdateOfAnImportRecordsTheVersionItInstalled(t *testing.T) {
s, _ := importedDemo(t)
unlock, err := s.Lock()
if err != nil {
t.Fatal(err)
}
defer unlock()
check, err := s.Preview(context.Background(), Request{Action: "check", Name: "demo"})
if err != nil || len(check.Changes) != 1 {
t.Fatalf("check: %+v %v", check, err)
}
if _, err := updateDemo(s, map[string]Seen{"claude": checkedObservation(t, check.Changes[0].Binding)}); err != nil {
t.Fatal(err)
}
if b := loadBinding(t, s); b.Version != "2.0.0" || b.Pending != "" {
t.Fatalf("binding: %+v", b)
}
}
// Importing again records the version the native client has now, not the one first imported.
func TestImportAgainRecordsTheInstalledVersion(t *testing.T) {
agents := &fakeAgents{installed: map[string][]Installed{"claude": {{ID: "demo@team", PluginID: "demo@team", Installed: true, Enabled: true, Version: "1.0.0", Scope: "user"}}}, markets: map[string]map[string]string{"claude": {"team": "/team"}}}
s := agents.service(t)
applyPluginRequest(t, s, Request{Action: "import", From: "claude", Plugin: "demo@team"})
agents.installed["claude"][0].Version = "2.0.0"
applyPluginRequest(t, s, Request{Action: "import", From: "claude", Plugin: "demo@team"})
if cfg, _ := s.load(); cfg.packages["demo"].Bindings["claude"].Version != "2.0.0" {
t.Fatalf("binding: %+v", cfg.packages["demo"].Bindings["claude"])
}
}
// A binding added from a source keeps the version Skillshare reviewed when imported again.
func TestImportAgainKeepsTheReviewedVersion(t *testing.T) {
agents := &fakeAgents{version: "1.0.0"}
s := agents.service(t)
applyPluginRequest(t, s, Request{Action: "add", Source: fixture(t), Targets: []string{"claude"}})
agents.installed["claude"][0].Version = "native-1"
applyPluginRequest(t, s, Request{Action: "import", From: "claude", Plugin: agents.installed["claude"][0].ID, Name: "demo"})
if b := loadBinding(t, s); b.Version != "1.0.0" {
t.Fatalf("binding: %+v", b)
}
}
// A skipped update stays pending, so a later sync still knows the plugin is behind.
func TestSkippedUpdateStaysPending(t *testing.T) {
agents := &fakeAgents{version: "1.0.0"}
s := agents.service(t)
source := fixture(t)
applyPluginRequest(t, s, Request{Action: "add", Source: source, Targets: []string{"codex"}})
cfg, err := s.load()
if err != nil {
t.Fatal(err)
}
pack := cfg.packages["demo"]
b := pack.Bindings["codex"]
b.Pending = "update"
pack.Bindings["codex"] = b
cfg.packages["demo"] = pack
local := cfg.state.Bindings["demo"]["codex"]
local.Pending = &receipt{Intent: cfg.intent["demo"].Bindings["codex"].fingerprint(), Store: s.storeIdentity("codex"), Binding: b, Action: "update"}
cfg.putLocal("demo", "codex", local)
if err := s.saveState(cfg); err != nil {
t.Fatal(err)
}
agents.installed["codex"][0].Enabled = false
applyPluginRequest(t, s, Request{Action: "sync"})
if cfg, _ = s.load(); cfg.packages["demo"].Bindings["codex"].Pending != "update" {
t.Fatalf("pending cleared: %+v", cfg.packages["demo"].Bindings["codex"])
}
}
func TestCanonicalSourceExpandsBareTilde(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
if got := canonicalSource("~"); got != home {
t.Fatalf("canonicalSource(~) = %q, want %q", got, home)
}
}
func TestSavingPluginsCreatesTheTargetOfADanglingSymlink(t *testing.T) {
agents := &fakeAgents{version: "1.0.0"}
s := agents.service(t)
shared := filepath.Join(os.Getenv("HOME"), "dotfiles", "skillshare.yaml")
if err := os.Symlink(shared, s.ConfigPath); err != nil {
t.Fatal(err)
}
applyPluginRequest(t, s, Request{Action: "add", Source: fixture(t), Targets: []string{"claude"}})
if info, err := os.Lstat(s.ConfigPath); err != nil || info.Mode()&os.ModeSymlink == 0 {
t.Fatalf("config.yaml is no longer a symlink: %v", err)
}
if data, err := os.ReadFile(shared); err != nil || !strings.Contains(string(data), "plugins:") {
t.Fatalf("symlink target not written: %v\n%s", err, data)
}
}
// bumpedDemo is demo added at 1.0.0 whose source now offers 2.0.0, under the lock a batch holds.
func bumpedDemo(t *testing.T) (*Service, *fakeAgents) {
t.Helper()
agents := &fakeAgents{version: "1.0.0"}
s := agents.service(t)
source := fixture(t)
applyPluginRequest(t, s, Request{Action: "add", Source: source, Targets: []string{"claude"}})
bumpDemo(t, source, agents)
unlock, err := s.Lock()
if err != nil {
t.Fatal(err)
}
t.Cleanup(unlock)
return s, agents
}
// checkedObservation crosses the same JSON boundary as the dashboard's observed binding.
func checkedObservation(t *testing.T, binding Binding) Seen {
t.Helper()
raw, err := json.Marshal(binding)
if err != nil {
t.Fatal(err)
}
var observed Seen
if err := json.Unmarshal(raw, &observed); err != nil {
t.Fatal(err)
}
return observed
}
func updateDemo(s *Service, seen map[string]Seen) (*Result, error) {
_, result, err := s.updateLocked(context.Background(), UpdateItem{Name: "demo", Targets: []string{"claude"}, Seen: seen}, func(*Plan) {})
return result, err
}
// Batch updates may install only the source the user approved, including a missing native installation.
func TestBatchUpdateUsesOnlyTheSourceTheCheckShowed(t *testing.T) {
for _, scenario := range []string{"version moved", "content moved", "no approval", "missing identity", "matching approval"} {
for _, missing := range []bool{false, true} {
t.Run(scenario+"/"+map[bool]string{false: "present", true: "removed"}[missing], func(t *testing.T) {
s, agents := bumpedDemo(t)
checked, err := s.Preview(context.Background(), Request{Action: "check", Name: "demo"})
if err != nil || len(checked.Changes) != 1 || checked.Changes[0].Action != "update-available" {
t.Fatalf("check: %+v %v", checked, err)
}
binding := checked.Changes[0].Binding
seen := map[string]Seen{"claude": checkedObservation(t, binding)}
switch scenario {
case "version moved":
moved := seen["claude"]
moved.Version = "1.5.0"
seen["claude"] = moved
case "content moved":
writeFile(t, binding.Source, "skills/demo/SKILL.md", "source changed after approval")
case "no approval":
seen = nil
case "missing identity":
seen["claude"] = Seen{Version: binding.Version, Commit: binding.Commit, Digest: binding.Digest}
}
if missing {
agents.installed["claude"] = nil
}
same := unchanged(t, s.ConfigPath, s.statePath())
result, err := updateDemo(s, seen)
if scenario != "matching approval" {
if err != ErrSourceMoved || len(agents.commands) != 0 {
t.Fatalf("unapproved source: %v, commands %q", err, agents.commands)
}
same()
return
}
if err != nil || len(result.Results) != 1 || result.Results[0].Status != "installed" {
t.Fatalf("approved update: %+v %v", result, err)
}
installed := readState(t, s).packages["demo"].Bindings["claude"]
if installed.Digest != binding.Digest || installed.Version != binding.Version || !s.ownedSnapshot(installed, "claude") {
t.Fatalf("update lost approved source: %+v", installed)
}
})
}
}
}
// A stop lets the plugin under way finish, starts no other, and a failed one still counts.
func TestBatchUpdateStartsNoPluginAfterAStop(t *testing.T) {
s, _ := bumpedDemo(t)
var started, ended []string
failed := s.UpdateBatch(context.Background(), Batch{
Items: []UpdateItem{{Name: "missing", Targets: []string{"claude"}}, {Name: "demo", Targets: []string{"claude"}}},
Stopped: func() bool { return len(started) > 0 },
Around: func(update func()) { update() },
Started: func(name string) { started = append(started, name) },
Planned: func(string, *Plan) {},
Ended: func(name string, _ *Plan, _ *Result, _ error) { ended = append(ended, name) },
})
if failed != 1 || !slices.Equal(ended, []string{"missing"}) {
t.Fatalf("failed %d, ended %q", failed, ended)
}
}
func TestPluginUpdateAllValidationAndPartialFailureIsolation(t *testing.T) {
agents := &fakeAgents{version: "1.0.0"}
s := agents.service(t)
sourceA := fixture(t)
sourceB := t.TempDir()
writeFile(t, sourceB, ".claude-plugin/plugin.json", `{"name":"other","version":"1.0.0","skills":"./skills"}`)
writeFile(t, sourceB, "skills/other/SKILL.md", "---\nname: other\n---\nother")
applyPluginRequest(t, s, Request{Action: "add", Source: sourceA, Targets: []string{"claude", "omp"}})
applyPluginRequest(t, s, Request{Action: "add", Source: sourceB, Targets: []string{"claude"}})
for _, bad := range []Request{
{Action: "update"},
{Action: "update", Name: "demo", All: true},
{Action: "update", SourceRef: "main", All: true},
{Action: "sync", All: true},
} {
if _, err := s.Preview(context.Background(), bad); err == nil {
t.Fatalf("expected validation error for %+v", bad)
}
}
// Bump both sources and update all in one pass.
bumpDemo(t, sourceA, agents)
writeFile(t, sourceB, ".claude-plugin/plugin.json", `{"name":"other","version":"2.0.0","skills":"./skills"}`)
writeFile(t, sourceB, "skills/other/SKILL.md", "---\nname: other\n---\nother v2")
same := unchanged(t, s.ConfigPath)
applyPluginRequest(t, s, Request{Action: "update", All: true})
same()
cfg, err := s.load()
if err != nil {
t.Fatal(err)
}
if cfg.packages["demo"].Bindings["claude"].Version != "2.0.0" || cfg.packages["other"].Bindings["claude"].Version != "2.0.0" {
t.Fatalf("update --all did not update all packages: %+v", cfg.packages)
}
// Remove sourceA on disk so its discovery fails, while bumping sourceB to 3.0.0.
if err := os.RemoveAll(sourceA); err != nil {
t.Fatal(err)
}
writeFile(t, sourceB, ".claude-plugin/plugin.json", `{"name":"other","version":"3.0.0","skills":"./skills"}`)
writeFile(t, sourceB, "skills/other/SKILL.md", "---\nname: other\n---\nother v3")
agents.version = "3.0.0"
var result *Result
var applyErr error
_ = s.WithDiscoveryCache(func() error {
req := Request{Action: "update", All: true}
p, pErr := s.Preview(context.Background(), req)
if pErr != nil {
t.Fatalf("preview --all should isolate source error, got: %v", pErr)
}
if p.Blocked {
t.Fatalf("preview --all should not be blocked by one broken source: %+v", p.Changes)
}
result, applyErr = s.Apply(context.Background(), req, p.Revision)
return nil
})
if applyErr == nil {
t.Fatalf("expected partial failure error from Apply when a source failed discovery, got nil (result=%+v)", result)
}
same()
cfg, err = s.load()
if err != nil {
t.Fatal(err)
}
if cfg.packages["other"].Bindings["claude"].Version != "3.0.0" {
t.Fatalf("healthy package was not updated during partial failure: %+v", cfg.packages["other"])
}
if cfg.packages["demo"].Bindings["claude"].Version != "2.0.0" || cfg.packages["demo"].Bindings["claude"].Pending != "" {
t.Fatalf("failed package binding should remain untouched at 2.0.0: %+v", cfg.packages["demo"])
}
}
func TestPluginUpdateAllOnSharedHostIsolatesMissingSource(t *testing.T) {
for _, existing := range []bool{false, true} {
t.Run(map[bool]string{false: "fresh", true: "replacement"}[existing], func(t *testing.T) {
var aCalls, bCalls []string
a := fakePiNpm(t, &aCalls)
broken, healthy := hostStatePiSource(t), t.TempDir()
writeFile(t, healthy, "package.json", `{"name":"other","version":"1.0.0","keywords":["pi-package"]}`)
writeFile(t, healthy, "extensions/other.ts", "export default () => {}")
applyPluginRequest(t, a, Request{Action: "add", Source: broken, Targets: []string{"pi"}})
applyPluginRequest(t, a, Request{Action: "add", Source: healthy, Targets: []string{"pi"}})
shared, _ := os.ReadFile(a.ConfigPath)
b := fakePiNpm(t, &bCalls)
writePluginFile(t, filepath.Dir(b.ConfigPath), filepath.Base(b.ConfigPath), string(shared))
oldID := ""
if existing {
applyPluginRequest(t, b, Request{Action: "sync"})
oldID = readState(t, b).state.Bindings["demo"]["pi"].Applied.Binding.ID
repairHost(t, a)
applyPluginRequest(t, a, Request{Action: "remove", Name: "demo", Targets: []string{"pi"}})
broken = hostStatePiSource(t)
applyPluginRequest(t, a, Request{Action: "add", Name: "demo", Source: broken, Targets: []string{"pi"}})
shared, _ = os.ReadFile(a.ConfigPath)
writePluginFile(t, filepath.Dir(b.ConfigPath), filepath.Base(b.ConfigPath), string(shared))
repairHost(t, b)
}
writeFile(t, healthy, "package.json", `{"name":"other","version":"2.0.0","keywords":["pi-package"]}`)
if err := os.RemoveAll(broken); err != nil {
t.Fatal(err)
}
same := unchanged(t, b.ConfigPath)
_ = b.WithDiscoveryCache(func() error {
request := Request{Action: "update", All: true}
plan, err := b.Preview(context.Background(), request)
if err != nil || plan.Blocked {
t.Fatalf("shared host --all did not isolate missing source: %+v %v", plan, err)
}
result, err := b.Apply(context.Background(), request, plan.Revision)
if err == nil || result == nil {
t.Fatalf("missing source did not report partial failure: %+v %v", result, err)
}
return nil
})
d := readState(t, b)
if d.packages["other"].Bindings["pi"].ID == "" || d.packages["other"].Bindings["pi"].Version != "2.0.0" {
t.Fatalf("shared host --all skipped healthy source: %+v", d.packages)
}
local := d.state.Bindings["demo"]["pi"]
if existing {
if local.Applied == nil || local.Applied.Binding.ID != oldID || local.Pending != nil || !slices.ContainsFunc(b.host(context.Background(), "pi").Installed, func(i Installed) bool { return i.ID == oldID }) {
t.Fatalf("failed replacement changed the previous native installation: %+v", local)
}
} else if len(d.state.Bindings["demo"]) != 0 {
t.Fatalf("missing source acquired a receipt: %+v", local)
}
same()
})
}
}