diff --git a/docs/subsystems/sync-backup.md b/docs/subsystems/sync-backup.md index 5eea0a68d..ceea7b16c 100644 --- a/docs/subsystems/sync-backup.md +++ b/docs/subsystems/sync-backup.md @@ -537,6 +537,35 @@ running bilis are asked to reload after one is written the file `billion-context.json`, added, changed or removed (`TestBiliFileInPreview`). +Claude Code's own plugins, the ones installed through its `/plugin` +marketplaces (`library.Bundle.ClaudePlugins`, +[`claude_plugins.go`](../../internal/library/claude_plugins.go)), go in the +library part too. What goes is each marketplace's source (from +`plugins/known_marketplaces.json` and settings.json's +`extraKnownMarketplaces`, with only `source` and `autoUpdate` kept) and the +plugin ids settings.json's `enabledPlugins` has on, under +`CLAUDE_CONFIG_DIR` when it is set. `installLocation`, `installPath` and the +downloaded code in `plugins/marketplaces` and `plugins/cache` stay: they are +this computer's, and Claude Code fetches them again from the sources. A +marketplace from a local folder or file, or one whose source has a user or +token in a URL or request headers, is not carried, and neither are its +plugins. Claude Code adds `claude-plugins-official` itself, so only its +plugins go. On the other computer they are added to settings.json's +`extraKnownMarketplaces` and `enabledPlugins`, the setup Claude Code +installs from at its next interactive start (tried with 2.1.319 in a +sandbox; `claude -p` does not install). Claude Code's own +`known_marketplaces.json` and `installed_plugins.json` are never written. +The file is patched in place (comments and other keys kept) and renamed in +from a temporary file, and the one it replaces is kept with the backups. +It only adds: a marketplace known here under that name, and a plugin with +any value here (turned off too), stay as they are, so a plugin removed on +one computer is not removed on the others. A settings.json either side +can't read is neither carried as none nor written over. A computer with no +such plugins carries none and hashes as before (`TestClaudePluginsCollected`, +`TestClaudePluginsNoneOrUnknown`, `TestClaudePluginsPut`, +`TestClaudePluginsInLibraryPart`). The preview names each marketplace and +plugin (`TestClaudePluginsInPreview`). + ## Verification ```sh diff --git a/internal/davsync/claude_plugins_test.go b/internal/davsync/claude_plugins_test.go new file mode 100644 index 000000000..e167155bb --- /dev/null +++ b/internal/davsync/claude_plugins_test.go @@ -0,0 +1,58 @@ +package davsync + +import ( + "encoding/json" + "slices" + "testing" + + "github.com/yetone/magpie/internal/backup" + "github.com/yetone/magpie/internal/library" +) + +// A library that holds only Claude Code's plugins is the user's, not an +// unset part a joining computer's library would be taken over by +// (#5642), and adding a plugin changes the library's hash. +func TestClaudePluginsInLibraryPart(t *testing.T) { + empty := func() backup.Bundle { + return backup.Bundle{Library: &library.Bundle{MCP: []*library.Server{}, Skills: []*library.CarriedSkill{}}} + } + with := empty() + with.Library.ClaudePlugins = &library.ClaudePlugins{Enabled: []string{"frontend-design@claude-plugins-official"}} + if unset(with, "library") { + t.Error("a library with Claude Code's plugins said unset") + } + if hashes(with)["library"] == hashes(empty())["library"] { + t.Error("Claude Code's plugins didn't change the library's hash") + } +} + +// The sync's preview names each marketplace and plugin it would add. +func TestClaudePluginsInPreview(t *testing.T) { + at := func(cp *library.ClaudePlugins) backup.Bundle { + return backup.Bundle{Library: &library.Bundle{MCP: []*library.Server{}, Skills: []*library.CarriedSkill{}, ClaudePlugins: cp}} + } + to := &library.ClaudePlugins{ + Marketplaces: map[string]json.RawMessage{"claude-code-plugins": json.RawMessage(`{"source":{"source":"github","repo":"anthropics/claude-code"}}`)}, + Enabled: []string{"commit-commands@claude-code-plugins"}, + } + got := diffItems(itemsOf(at(nil), "library"), itemsOf(at(to), "library")) + want := []Item{ + {Kind: "claudeMarketplace", Name: "claude-code-plugins", Change: "added"}, + {Kind: "claudePlugin", Name: "commit-commands@claude-code-plugins", Change: "added"}, + } + slices.SortFunc(got, func(a, b Item) int { + if a.Kind < b.Kind { + return -1 + } + if a.Kind > b.Kind { + return 1 + } + return 0 + }) + if !slices.Equal(got, want) { + t.Errorf("preview: %+v", got) + } + if got := diffItems(itemsOf(at(to), "library"), itemsOf(at(to), "library")); len(got) != 0 { + t.Errorf("the same plugins: %+v", got) + } +} diff --git a/internal/davsync/davsync.go b/internal/davsync/davsync.go index 2564e31b7..93ae03908 100644 --- a/internal/davsync/davsync.go +++ b/internal/davsync/davsync.go @@ -1035,7 +1035,7 @@ func unset(b backup.Bundle, p string) bool { } return len(l.MCP) == 0 && len(l.Skills) == 0 && (l.Subagents == nil || len(*l.Subagents) == 0) && (l.Commands == nil || len(*l.Commands) == 0) && (l.Hooks == nil || len(*l.Hooks) == 0) && - (l.Bili == nil || strings.TrimSpace(*l.Bili) == "") + (l.Bili == nil || strings.TrimSpace(*l.Bili) == "") && l.ClaudePlugins == nil } return false } diff --git a/internal/davsync/plan.go b/internal/davsync/plan.go index a26d7fe80..a25f4e3dd 100644 --- a/internal/davsync/plan.go +++ b/internal/davsync/plan.go @@ -12,6 +12,7 @@ import ( "time" "github.com/yetone/magpie/internal/backup" + "github.com/yetone/magpie/internal/library" "github.com/yetone/magpie/internal/memory" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/settings" @@ -277,6 +278,19 @@ func itemsOf(b backup.Bundle, p string) map[string]item { out["bili\x00"] = item{Kind: "file", Name: "billion-context.json", Raw: string(v)} continue } + // Claude Code's own plugins: each marketplace by its name, each + // plugin by its id + if k == "claudePlugins" { + var cp library.ClaudePlugins + json.Unmarshal(v, &cp) + for name, m := range cp.Marketplaces { + out["claudeMarketplace\x00"+name] = item{Kind: "claudeMarketplace", Name: name, Raw: string(m)} + } + for _, id := range cp.Enabled { + out["claudePlugin\x00"+id] = item{Kind: "claudePlugin", Name: id, Raw: "true"} + } + continue + } flatten(out, k, x) } } diff --git a/internal/library/carry.go b/internal/library/carry.go index 29bd148cc..be8411cba 100644 --- a/internal/library/carry.go +++ b/internal/library/carry.go @@ -49,6 +49,12 @@ type Bundle struct { // this computer has none or it can't be read, and in a bundle from a // magpie before it was carried: Put keeps this computer's then. Bili *string `json:"bili,omitempty"` + // ClaudePlugins are the marketplaces and plugins installed in Claude + // Code itself (claude_plugins.go). nil when there are none, or they + // can't be read, and in a bundle from a magpie before them: Put adds + // nothing then. Put only adds, so one computer's never takes away + // another's. + ClaudePlugins *ClaudePlugins `json:"claudePlugins,omitempty"` } // CarriedSkill is a skill with its folder's files. @@ -171,6 +177,7 @@ func Collect() (*Bundle, error) { } b.Env = &envs b.Bili = carriedBili() + b.ClaudePlugins = carriedClaudePlugins() return b, nil } @@ -701,6 +708,11 @@ func Put(b *Bundle) (*Result, error) { } biliWrote = wrote } + if b.ClaudePlugins != nil { + if err := putClaudePlugins(b.ClaudePlugins, kept); err != nil { + return err + } + } return nil }) if err == nil && biliWrote { @@ -781,8 +793,8 @@ func isDir(p string) bool { } // Changed is when the library was last changed: library.json, or a file -// of its own (links not followed), or billion-context.json, which a -// sync carries with it. +// of its own (links not followed), or billion-context.json or Claude +// Code's plugin records, which a sync carries with it. func Changed() time.Time { var t time.Time if fi, err := os.Stat(path()); err == nil { @@ -791,6 +803,9 @@ func Changed() time.Time { if b := biliChanged(); b.After(t) { t = b } + if c := claudePluginsChanged(); c.After(t) { + t = c + } filepath.WalkDir(Dir(), func(p string, d fs.DirEntry, err error) error { if err != nil { return nil diff --git a/internal/library/claude_plugins.go b/internal/library/claude_plugins.go new file mode 100644 index 000000000..4074ab2e4 --- /dev/null +++ b/internal/library/claude_plugins.go @@ -0,0 +1,232 @@ +package library + +import ( + "encoding/json" + "errors" + "log" + "maps" + "os" + "path/filepath" + "slices" + "strings" + "time" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/lazyre" +) + +// Claude Code's own plugins, the ones installed in Claude Code through its +// /plugin marketplaces (AXmake110 on X), go with the library: the +// marketplaces it knows and the plugins turned on for the user, so a +// computer that syncs ends up with the same plugins. They are not the +// library's plugin bundles (plugin.go), which magpie keeps and gives to +// every agent itself. +// +// Claude Code keeps them in its folder (claudeDir, CLAUDE_CONFIG_DIR too): +// +// plugins/known_marketplaces.json {name: {source: {source: "github", repo}, installLocation, lastUpdated}} +// plugins/installed_plugins.json {version: 2, plugins: {"p@m": [{scope, installPath, version, …}]}} +// settings.json enabledPlugins: {"p@m": true}, extraKnownMarketplaces: {name: {source}} +// +// What is carried is each marketplace's source and the user's enabled +// plugin ids. installLocation, installPath and the downloaded code in +// plugins/marketplaces and plugins/cache are this computer's, and Claude +// Code fetches them again from the sources. On the other computer they +// are written where Claude Code reads a declared setup from: +// settings.json's extraKnownMarketplaces and enabledPlugins. At its next +// interactive start Claude Code clones the marketplaces and installs the +// plugins into its own files (tried with Claude Code 2.1.319 in a sandbox +// CLAUDE_CONFIG_DIR: commit-commands@claude-code-plugins installed from +// those two settings alone; `claude -p` does not install them). +// +// Only adding: a marketplace or plugin the other computer has under that +// name, enabled or turned off there, stays as it is there, and a plugin +// removed on one computer is not removed on the others. +type ClaudePlugins struct { + // Marketplaces are by name, each as extraKnownMarketplaces holds one: + // {"source": {…}} and its autoUpdate when set. + Marketplaces map[string]json.RawMessage `json:"marketplaces,omitempty"` + // Enabled are the plugins turned on for the user, as plugin@marketplace. + Enabled []string `json:"enabled,omitempty"` +} + +// claudeOfficial is the marketplace Claude Code adds by itself: its +// plugins are carried, the marketplace is not (a settings entry under its +// name adds nothing, as Claude Code says). +const claudeOfficial = "claude-plugins-official" + +func claudeSettings() string { return filepath.Join(claudeDir(), "settings.json") } +func claudeMarketplaces() string { + return filepath.Join(claudeDir(), "plugins", "known_marketplaces.json") +} +func claudeInstalled() string { return filepath.Join(claudeDir(), "plugins", "installed_plugins.json") } + +// readClaudeJSON is a file of Claude Code's as JSON: nil when there is +// none or it is empty, an error when it can't be read as an object. +func readClaudeJSON(path string) ([]byte, error) { + doc, err := readHooksFile(path) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + return doc, err +} + +// userinfo is a URL with a user (and maybe a password or token) in it. +var userinfo = lazyre.New(`(?i)[a-z][a-z0-9+.-]*://[^/\s"@]+@`) + +// portableMarketplace is a marketplace's entry as it goes, or false when it +// stays on this computer: a folder or a file of this computer's, or a +// source with a sign-in in it (a token in a git URL, a request header). +func portableMarketplace(entry gjson.Result) (json.RawMessage, bool) { + src := entry.Get("source") + if !src.IsObject() { + return nil, false + } + switch src.Get("source").String() { + case "", "directory", "file": + return nil, false + } + if src.Get("path").Exists() || src.Get("headers").Exists() || userinfo.Regexp().MatchString(src.Raw) { + return nil, false + } + out := map[string]json.RawMessage{"source": json.RawMessage(src.Raw)} + if a := entry.Get("autoUpdate"); a.IsBool() { + out["autoUpdate"] = json.RawMessage(a.Raw) + } + j, err := json.Marshal(out) + if err != nil { + return nil, false + } + return j, true +} + +// carriedClaudePlugins is this computer's Claude Code plugins as they go, +// nil when there are none, or when a file of them can't be read: unknown +// is never carried as none. +func carriedClaudePlugins() *ClaudePlugins { + known, err := readClaudeJSON(claudeMarketplaces()) + if err != nil { + return nil + } + set, err := readClaudeJSON(claudeSettings()) + if err != nil { + return nil + } + cp := &ClaudePlugins{Marketplaces: map[string]json.RawMessage{}} + add := func(r gjson.Result) { + r.ForEach(func(k, v gjson.Result) bool { + name := k.String() + if _, ok := cp.Marketplaces[name]; ok || name == claudeOfficial { + return true + } + if j, ok := portableMarketplace(v); ok { + cp.Marketplaces[name] = j + } + return true + }) + } + add(gjson.GetBytes(set, "extraKnownMarketplaces")) + add(gjson.ParseBytes(known)) + gjson.GetBytes(set, "enabledPlugins").ForEach(func(k, v gjson.Result) bool { + id := k.String() + _, m, ok := strings.Cut(id, "@") + if !ok || v.Type != gjson.True { + return true + } + if _, carried := cp.Marketplaces[m]; carried || m == claudeOfficial { + cp.Enabled = append(cp.Enabled, id) + } + return true + }) + slices.Sort(cp.Enabled) + if len(cp.Enabled) == 0 && len(cp.Marketplaces) == 0 { + return nil + } + if len(cp.Marketplaces) == 0 { + cp.Marketplaces = nil + } + return cp +} + +// claudePluginsChanged is when Claude Code last added or took away a +// marketplace or a plugin here, zero when it never did. +func claudePluginsChanged() time.Time { + var t time.Time + for _, p := range []string{claudeMarketplaces(), claudeInstalled()} { + if fi, err := os.Stat(p); err == nil && fi.ModTime().After(t) { + t = fi.ModTime() + } + } + return t +} + +// putClaudePlugins adds to Claude Code's settings.json the marketplaces and +// enabled plugins cp carries that it doesn't have yet, written the way +// Claude Code writes it (a temp file renamed in, every other setting as +// it was); the file it replaces is kept with the change's backups. A +// marketplace this computer knows under that name, and a plugin it has +// any value for (turned off here too), is left as it is. A settings.json +// or known_marketplaces.json that can't be read is not written to. +func putClaudePlugins(cp *ClaudePlugins, kept *backups) error { + p := claudeSettings() + set, err := readClaudeJSON(p) + if err != nil { + log.Printf("library: Claude Code's plugins not added: %v", err) + return nil + } + known, err := readClaudeJSON(claudeMarketplaces()) + if err != nil { + log.Printf("library: Claude Code's plugins not added: %v", err) + return nil + } + have := func(name string) bool { + return name == claudeOfficial || gjson.GetBytes(set, "extraKnownMarketplaces."+gjson.Escape(name)).Exists() || + gjson.GetBytes(known, gjson.Escape(name)).Exists() + } + var kvs []edit.KV + came := map[string]bool{} // the carried marketplaces fit to add + for _, name := range slices.Sorted(maps.Keys(cp.Marketplaces)) { + var v any + if strings.TrimSpace(name) == "" || json.Unmarshal(cp.Marketplaces[name], &v) != nil { + continue + } + if _, ok := portableMarketplace(gjson.ParseBytes(cp.Marketplaces[name])); !ok { + continue + } + came[name] = true + if !have(name) { + kvs = append(kvs, edit.KV{Path: "extraKnownMarketplaces." + gjson.Escape(name), Value: v}) + } + } + for _, id := range cp.Enabled { + _, m, ok := strings.Cut(id, "@") + if !ok || gjson.GetBytes(set, "enabledPlugins."+gjson.Escape(id)).Exists() { + continue + } + if !came[m] && !have(m) { + continue + } + kvs = append(kvs, edit.KV{Path: "enabledPlugins." + gjson.Escape(id), Value: true}) + } + if len(kvs) == 0 { + return nil + } + raw, err := edit.Read(p) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + out, err := edit.PatchJSON(raw, kvs, nil) + if err != nil { + log.Printf("library: Claude Code's plugins not added to %s: %v", p, err) + return nil + } + if err := kept.keep("claude", p); err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + return err + } + return edit.WriteAtomic(p, out) +} diff --git a/internal/library/claude_plugins_test.go b/internal/library/claude_plugins_test.go new file mode 100644 index 000000000..c3f86a22e --- /dev/null +++ b/internal/library/claude_plugins_test.go @@ -0,0 +1,204 @@ +package library + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/tidwall/gjson" +) + +// claudePluginsSandbox is a sandbox whose Claude Code folder is moved by +// CLAUDE_CONFIG_DIR, as a user may have it. +func claudePluginsSandbox(t *testing.T) string { + t.Helper() + h := sandbox(t) + d := filepath.Join(h, "cc-config") + t.Setenv("CLAUDE_CONFIG_DIR", d) + shared := "Use tabs." + ok(t)(SaveInstructions(InstructionsChange{Shared: &shared, Agents: []string{"claude"}})) + return d +} + +// The files as Claude Code 2.1.319 wrote them in a sandbox after +// `/plugin marketplace add` and `/plugin install`: absolute paths of this +// computer's, a marketplace from a local folder, one from a git URL with +// a token in it, and one from GitHub. +const ( + ccKnownFixture = `{ + "claude-plugins-official": {"source": {"source": "github", "repo": "anthropics/claude-plugins-official"}, "installLocation": "/Users/a/.claude/plugins/marketplaces/claude-plugins-official", "lastUpdated": "2026-11-14T10:00:00.000Z"}, + "claude-code-plugins": {"source": {"source": "github", "repo": "anthropics/claude-code"}, "installLocation": "/Users/a/.claude/plugins/marketplaces/claude-code-plugins", "lastUpdated": "2026-11-14T10:00:00.000Z"}, + "mine": {"source": {"source": "directory", "path": "/Users/a/src/my-market"}, "installLocation": "/Users/a/src/my-market", "lastUpdated": "2026-11-14T10:00:00.000Z"}, + "corp": {"source": {"source": "git", "url": "https://x-token:ghp_SECRET123@git.corp.example/plugins.git"}, "installLocation": "/Users/a/.claude/plugins/marketplaces/corp", "lastUpdated": "2026-11-14T10:00:00.000Z"} +}` + ccInstalledFixture = `{"version": 2, "plugins": { + "commit-commands@claude-code-plugins": [{"scope": "user", "installPath": "/Users/a/.claude/plugins/cache/claude-code-plugins/commit-commands/1.0.0", "version": "1.0.0", "installedAt": "2026-11-14T10:00:00.000Z", "lastUpdated": "2026-11-14T10:00:00.000Z"}] +}}` + ccSettingsFixture = `{ + "model": "opus", + "enabledPlugins": { + "commit-commands@claude-code-plugins": true, + "pr-review-toolkit@claude-code-plugins": false, + "frontend-design@claude-plugins-official": true, + "local-tool@mine": true, + "secret-tool@corp": true + }, + "extraKnownMarketplaces": { + "team": {"source": {"source": "github", "repo": "acme/claude-plugins"}, "autoUpdate": true} + } +}` +) + +// TestClaudePluginsCollected (AXmake110 on X): a sync carries the +// marketplaces Claude Code knows and the plugins turned on, leaving out +// this computer's paths, a local folder's marketplace and a source with a +// sign-in in it. +func TestClaudePluginsCollected(t *testing.T) { + d := claudePluginsSandbox(t) + write(t, filepath.Join(d, "plugins", "known_marketplaces.json"), ccKnownFixture) + write(t, filepath.Join(d, "plugins", "installed_plugins.json"), ccInstalledFixture) + write(t, filepath.Join(d, "settings.json"), ccSettingsFixture) + b, err := Collect() + if err != nil { + t.Fatal(err) + } + if b.ClaudePlugins == nil { + t.Fatal("Claude Code's plugins not carried") + } + j := mustJSON(t, b) + for _, bad := range []string{"/Users/a", "installLocation", "installPath", "ghp_SECRET123", "my-market", "lastUpdated"} { + if strings.Contains(j, bad) { + t.Errorf("carried %q:\n%s", bad, j) + } + } + cp := b.ClaudePlugins + var names []string + for n := range cp.Marketplaces { + names = append(names, n) + } + if len(cp.Marketplaces) != 2 || cp.Marketplaces["claude-code-plugins"] == nil || cp.Marketplaces["team"] == nil { + t.Errorf("marketplaces carried: %v", names) + } + if r := gjson.GetBytes(cp.Marketplaces["claude-code-plugins"], "source.repo").String(); r != "anthropics/claude-code" { + t.Errorf("claude-code-plugins carried as %s", cp.Marketplaces["claude-code-plugins"]) + } + if !gjson.GetBytes(cp.Marketplaces["team"], "autoUpdate").Bool() { + t.Errorf("team's autoUpdate lost: %s", cp.Marketplaces["team"]) + } + want := []string{"commit-commands@claude-code-plugins", "frontend-design@claude-plugins-official"} + if strings.Join(cp.Enabled, ",") != strings.Join(want, ",") { + t.Errorf("enabled carried: %v, want %v", cp.Enabled, want) + } +} + +// TestClaudePluginsNoneOrUnknown: a computer with no Claude Code plugins +// carries none (its library part is as before), and one whose settings +// can't be read carries nothing rather than "none". +func TestClaudePluginsNoneOrUnknown(t *testing.T) { + d := claudePluginsSandbox(t) + write(t, filepath.Join(d, "settings.json"), `{"model": "opus"}`) + write(t, filepath.Join(d, "plugins", "known_marketplaces.json"), `{"claude-plugins-official": {"source": {"source": "github", "repo": "anthropics/claude-plugins-official"}}}`) + if b, err := Collect(); err != nil || b.ClaudePlugins != nil { + t.Fatalf("nothing of the user's carried as %+v (%v)", b.ClaudePlugins, err) + } + write(t, filepath.Join(d, "settings.json"), `{"enabledPlugins": {"commit-commands@claude-code-plugins": tr`) + if b, err := Collect(); err != nil || b.ClaudePlugins != nil { + t.Fatalf("unreadable settings carried as %+v (%v)", b.ClaudePlugins, err) + } +} + +// TestClaudePluginsPut: on the other computer the marketplaces and +// plugins are added to settings.json, where Claude Code installs them +// from at its next start. What the user has there stays: their other +// settings, a plugin they turned off, a marketplace they know under that +// name. Claude Code's own files are not written. +func TestClaudePluginsPut(t *testing.T) { + claudePluginsSandbox(t) + in := Bundle{ClaudePlugins: &ClaudePlugins{ + Marketplaces: map[string]json.RawMessage{ + "claude-code-plugins": json.RawMessage(`{"source":{"source":"github","repo":"anthropics/claude-code"}}`), + "team": json.RawMessage(`{"source":{"source":"github","repo":"acme/claude-plugins"},"autoUpdate":true}`), + "evil": json.RawMessage(`{"source":{"source":"directory","path":"/Users/a/x"}}`), + }, + Enabled: []string{"commit-commands@claude-code-plugins", "frontend-design@claude-plugins-official", "off-here@team", "x@evil", "y@nowhere"}, + }} + b, err := Collect() + if err != nil { + t.Fatal(err) + } + in.Instructions = b.Instructions + in.Skills = b.Skills + + d := os.Getenv("CLAUDE_CONFIG_DIR") + mine := "{\n // mine\n \"model\": \"sonnet\",\n \"enabledPlugins\": {\"off-here@team\": false},\n \"extraKnownMarketplaces\": {\"team\": {\"source\": {\"source\": \"github\", \"repo\": \"me/my-team\"}}}\n}\n" + write(t, filepath.Join(d, "settings.json"), mine) + ok(t)(Put(&in)) + got := read(t, filepath.Join(d, "settings.json")) + if !strings.Contains(got, "// mine") { + t.Errorf("settings.json rewritten whole:\n%s", got) + } + j := settingsOf(t, got) + checks := map[string]string{ + "model": "sonnet", + "enabledPlugins.off-here@team": "false", + "enabledPlugins.commit-commands@claude-code-plugins": "true", + "enabledPlugins.frontend-design@claude-plugins-official": "true", + "extraKnownMarketplaces.team.source.repo": "me/my-team", + "extraKnownMarketplaces.claude-code-plugins.source.repo": "anthropics/claude-code", + } + for path, want := range checks { + if v := j.Get(gjsonPath(path)).String(); v != want { + t.Errorf("%s = %q, want %q:\n%s", path, v, want, got) + } + } + for _, gone := range []string{"enabledPlugins.x@evil", "enabledPlugins.y@nowhere", "extraKnownMarketplaces.evil"} { + if j.Get(gjsonPath(gone)).Exists() { + t.Errorf("%s added:\n%s", gone, got) + } + } + for _, f := range []string{"known_marketplaces.json", "installed_plugins.json"} { + if _, err := os.Stat(filepath.Join(d, "plugins", f)); err == nil { + t.Errorf("Claude Code's own %s written", f) + } + } + + // again: nothing more to add, the file is left as it is + before := got + ok(t)(Put(&in)) + if after := read(t, filepath.Join(d, "settings.json")); after != before { + t.Errorf("a second sync changed settings.json:\n%s", after) + } + + // a settings.json that can't be read is not written over + broken := `{"model": "sonnet", "enabledPlugins": {` + write(t, filepath.Join(d, "settings.json"), broken) + ok(t)(Put(&in)) + if after := read(t, filepath.Join(d, "settings.json")); after != broken { + t.Errorf("unreadable settings.json written over:\n%s", after) + } +} + +func settingsOf(t *testing.T, s string) gjson.Result { + t.Helper() + var v any + clean := strings.ReplaceAll(s, "// mine", "") + if err := json.Unmarshal([]byte(clean), &v); err != nil { + t.Fatalf("%v:\n%s", err, s) + } + return gjson.Parse(clean) +} + +// gjsonPath escapes the @ and dots of a plugin id inside a dotted path +// written plainly in a test: only the first segment is a key of its own. +func gjsonPath(p string) string { + head, rest, ok := strings.Cut(p, ".") + if !ok { + return gjson.Escape(p) + } + if head == "enabledPlugins" { + return head + "." + gjson.Escape(rest) + } + return p +}