From 57c90f9f2742f7335cf391f637e1ec1e02ca28ae Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 20 Nov 2026 11:23:07 +0800 Subject: [PATCH] library: a project's claudePlugins and pi read in another build's shapes (#7282) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A library.json whose project had "pi": {"npm:example": ["pi"]} or "claudePlugins": {"demo@local": true}, as another build of magpie wrote them, failed the whole library's read ("cannot unmarshal array … pi … type string"): `magpie library project --json` exited 1, /api/library answered 400, and no change could be made (jinpwng, v0.1.4573). - Project.UnmarshalJSON reads claudePlugins as a list or as a map of id to on: true is in the list, false is left out, since magpie only turns a plugin on and writes nothing for one off. pi is read as source to "on"/"off", or to the agents it is for (some: on, none: off), or to a boolean. - A read changes nothing. The first write after such a read keeps the file's bytes as library.json.before-reshape (reshapedCopy, never over an existing copy; one that can't be made stops the write), then writes magpie's shape. - Any other shape still fails the read, and nothing is written over it. Run (mote): go test ./internal/library -run 'TestProjectReadsOtherShapes|TestProjectExportApply|TestProjectPi|TestProjectClaudePlugin' -count=1: ok; the full suite is in the push record. Broken by hand (mica): with UnmarshalJSON renamed away, TestProjectReadsOtherShapes is red with the reporter's own error, "json: cannot unmarshal array into Go struct field Project.projects.pi of type string". Not tried: the reporter's own r11 file; a preview of the conversion before it is written (the kept copy is the way back). --- docs/subsystems/library.md | 2 +- internal/library/library.go | 3 + internal/library/project_shapes.go | 119 ++++++++++++++++++++++++ internal/library/project_shapes_test.go | 90 ++++++++++++++++++ internal/library/projects.go | 3 + 5 files changed, 216 insertions(+), 1 deletion(-) create mode 100644 internal/library/project_shapes.go create mode 100644 internal/library/project_shapes_test.go diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 538ed3821..cfc759a07 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -17,7 +17,7 @@ Pi's extensions and packages. | Part | Responsibility | Source | | --- | --- | --- | -| library.json | `Library` holds the instruction sets, the MCP servers, the skills, the projects, skill groups and copy settings. `Applied` records what magpie last wrote into each agent, so it only ever takes away its own. The instruction texts and skill folders live under `Dir` (`library/` in magpie's config folder). | [`library.go`](../../internal/library/library.go) | +| library.json | `Library` holds the instruction sets, the MCP servers, the skills, the projects, skill groups and copy settings. `Applied` records what magpie last wrote into each agent, so it only ever takes away its own. The instruction texts and skill folders live under `Dir` (`library/` in magpie's config folder). A project's `claudePlugins` and `pi` are read in another build's shapes too (`Project.UnmarshalJSON`; jinpwng, #7282): a map of plugin id to on (true in the list, false left out, as magpie turns on only) and a map of Pi source to its agents (some: "on", none: "off") or to a boolean. A read changes nothing; the first write keeps the bytes it had as `library.json.before-reshape` (`reshapedCopy`; one that can't be made stops the write), then writes magpie's shape. Any other shape still fails the read, and nothing is written over it (`TestProjectReadsOtherShapes`). | [`library.go`](../../internal/library/library.go), [`project_shapes.go`](../../internal/library/project_shapes.go) | | A Remote magpie's skills and prompts | A Remote magpie provider's editor has a switch, Use its skills and prompts (`borrowOn` in library.json, `SetBorrow`; KoiLx0 on X: manage them once on the remote machine). The remote serves its Library at `GET /v1/magpie/library` (`gateway.SharedLibrary` = `library.Shared`, to `local` or `sharedWith` callers; a held key is refused; no MCP servers, which the MCP switch covers; borrowed items are never passed on). `keepBorrowed` (10 minutes, and once on switching on) fetches it with the provider's key (`provider.RemoteLibrary`) and `Borrow` adds each skill and each instruction set as `remote--`, recording a hash of what it wrote (`Borrowed`). It only ever changes what still matches that hash: a skill or set of the user's by the same name, one the user edited, and one the user removed after it was taken stay as they are (`Kept`, shown under the switch); an update or a drop moves the old copy to the backups; switching off takes out what is unchanged. The first set becomes the active one only when nothing is active. A remote whose page shows no agent (a container, a NAS, gateway mode: `NoAgentsShown`, set by `gui.gatewayMode`) has its skills and prompts ticked for none there, so it says so (`Bundle.NoAgents`), and `Borrow` gives such a new item ticked for none to the agents here that take skills or instructions and aren't hidden (`givenHere`); one ticked for agents keeps them (fenglian980510 on X, `TestBorrowFromAMagpieWithNoAgents`). The remote's page shows its Skills and Instructions with nothing of agents for this (`library-agentless-skills.test.cjs`). `Collect`/`Put` (sync backups) still carry borrowed items as ordinary ones. | [`borrow.go`](../../internal/library/borrow.go), [`remote_library.go`](../../internal/provider/remote_library.go), `TestBorrowRemoteLibrary` | | One change | `change` locks the library, loads it, applies one edit, saves, syncs every agent and saves again. Every exported mutation (`SaveServer`, `InstallSkills`, `SetSkillHow` and the rest) goes through it. One change runs at a time, whether from the page or the CLI. | [`library.go`](../../internal/library/library.go) | | Targets | `Targets` lists the detected agents (`agent.Detected`), a folder an agent shares with its vendor's other app when only that app is here (`agent.SharedHere`: the Cursor editor's `~/.cursor`, whose `mcp.json` and skills it reads, listed as Cursor; `TestCursorEditorAloneKeepsItsLibraryRow`; and `~/.copilot` or `$COPILOT_HOME`, listed as GitHub Copilot, whose `copilot-instructions.md` Copilot CLI, VS Code and GitHub Copilot's JetBrains plugin all read as the user's own instructions, kept with VS Code, VS Code Insiders or the plugin alone here even before the folder is (`agent.SharedRead`, `sharedApp`; @codealc on X, `TestCopilotVSCodeAloneGetsInstructions`), plus apps like Claude Desktop, with where each keeps its instructions file (and an `Override` it reads instead), its MCP file and its skills folder. An agent whose CLI is gone (`CLIMissing`: an uninstall that left the folder behind, #2177, #2254) is no target: it is given nothing it can't read. One whose vendor's other app still reads the folder (`SharedRead`: VS Code for `~/.copilot`) stays one (`TestCopilotCLIGoneVSCodeKeepsTheRow`). One that isn't a target but still has skills, servers or hooks magpie gave it (in `Applied`: a tick a synced library brought for an agent this computer never gave anything is no reason to list it, `TestGoneAgentWithOnlySyncedTicksIsNotListed`; izhidigua on X) is held (`held`, a `Target` with `Gone`): a sync takes edits from its copies and then only takes out of it (`syncSkills`, `syncMCP` and `syncHooks` give a gone target nothing new), and `Read` lists it with `gone: true` while it has any. On a row, an agent's profiles (`hermes#name`, `omp#name`, `claude#name`, `qwenpaw#id`, WSL ones included) are one chip with a count, when an agent has more than one (`profileChip` in plugins/library/client.js, Yanzhongixuy on X: about twenty identical Hermes glyphs on every skill row); a click opens the app menu to pick profiles singly, and All still means every profile (`library-profile-chip.test.cjs`). A repository's, part's or pick's heading folds them the same way (`groupChips` sets `change.rows`; its chip is half lit when a profile has some of the skills), and the profiles chip takes part in the row's fan like any other (`[data-members]` in library.css), so the hand stays in line (Yanzhongixuy on X, 0.1.3926; `library-profile-group.test.cjs`). How far the chips close up with many agents (#936) is set in whole pixels from each row's width by one ResizeObserver (`handGap` in plugins/library/client.js), never in container units, which made every chip's style be worked out again on each step of a window resize: about 0.5s a step at 196 skills of 24 agents (lexrus on X; `skill-name-many-agents.test.cjs`). The page shows a gone agent's chip only on the rows of what it has, lit, so a click takes it out (`withGone` in plugins/library/client.js), leaves it out of All, the per-agent How sheet and every picker, and lists it in By agent as Not installed here with Turn all on off (@jiahao_jayden on X: an uninstalled WorkBuddy was on every skill's row; `TestGoneAgentListedToTakeOut`, `library-gone-agents.test.cjs`). On a Mac WorkBuddy and WorkBuddy AI are detected by their apps' bundle ids (`com.tencent.workbuddy.mac`, `com.workbuddy.workbuddy-ai`, `macBundle`), not by `~/.workbuddy`, which an uninstall leaves and magpie itself writes into (`TestWorkBuddyOnMacIsItsApp`); off a Mac the folder still counts. `everyTarget` keeps it for the guards that refuse an agent's own places: a project folder whose skills folder or MCP file is the agent's, and an instruction set kept in its instructions file. An agent in a running WSL distro has its places under the distro's home (`wslTargetOf`): Claude Code, Codex, Pi, OmO, Gemini CLI, Antigravity CLI, Crush, Cline, CodeBuddy Code, Kimi Code and Goose each by its own rule, never reading this machine's variables (Kimi Code's and Goose's shared `~/.agents/skills` there isn't given), Pi's MCP file chosen by `piMCP` as on this machine from the version the distro's `pi --version` gave its probe (`InstalledVersion`) and the distro's npm folders (`wslPiRoots`; leokon on Discord: only the Windows Pi was offered MCP servers, `TestWSLPiMCP`, `TestWSLMCPSiblings`), and every agent that keeps all of them in its own folder (Hermes Agent, omp, OpenCode, Droid and the rest of `ownFolder`, #1323) by the same rule as on this machine, its MCP file marked as WSL's so a Windows program isn't given to it. A place below a folder the distro has as a link is opened where the link leads (`wslOpen`, agent-wiring's WSL folders that are links, #4502); a link the distro couldn't resolve gives that agent one `wsl` problem and nothing is written to it (`TestWSLFolderIsALinkToC`, `TestWSLFolderLinkUnresolved`). An agent a plugin adds (`a.Plugin`) has the places its plugin's `agent.library` names (`pluginTarget`): an instructions file, an MCP file in one of `agentplug.MCPFormats` (each the `mcpFormat` of the agent it is named for, `pluginMCP`) and a skills folder, `~` and `$VAR` expanded as its config is; one that names none is no target. Before, a plugin's agent got models and keys only. Every built-in agent is a target or is in `noLibrary` with why: OpenBot was added with neither and was in no picker (SSNQT on X), so `TestEveryAgentInLibrary` fails a new agent until it gets one (34 were in no picker when it landed, listed there under #5897). | [`targets.go`](../../internal/library/targets.go) | diff --git a/internal/library/library.go b/internal/library/library.go index 7e6d88cd0..180abadcc 100644 --- a/internal/library/library.go +++ b/internal/library/library.go @@ -296,6 +296,9 @@ func (l *Library) save() error { if err != nil { return err } + if err := l.reshapedCopy(); err != nil { + return fmt.Errorf("keeping %s before writing it in magpie's shape: %w", path(), err) + } return edit.WriteAtomic(path(), append(b, '\n')) } diff --git a/internal/library/project_shapes.go b/internal/library/project_shapes.go new file mode 100644 index 000000000..0c23875c1 --- /dev/null +++ b/internal/library/project_shapes.go @@ -0,0 +1,119 @@ +package library + +import ( + "encoding/json" + "fmt" + "os" + "slices" + "sort" +) + +// A project's claudePlugins and pi read in the shapes another build of +// magpie wrote them in too (#7282, jinpwng): claudePlugins as a map of +// plugin id to on (true) or off, pi as a map of source to the agents it is +// for. One of them used to fail the whole library's read, so nothing could +// be changed. They're read as magpie's own shapes: a plugin on is in the +// list, one off is left out, as magpie turns on only and writes nothing for +// it; a Pi source for some agent is "on", for none "off". The file is +// untouched until magpie next writes it, and then the bytes it had are +// kept beside it first, as library.json.before-reshape (reshapedCopy). +func (p *Project) UnmarshalJSON(b []byte) error { + type plain Project + x := struct { + *plain + ClaudePlugins json.RawMessage `json:"claudePlugins,omitempty"` + Pi json.RawMessage `json:"pi,omitempty"` + }{plain: (*plain)(p)} + if err := json.Unmarshal(b, &x); err != nil { + return err + } + p.ClaudePlugins, p.Pi = nil, nil + if on, other, err := readClaudePlugins(x.ClaudePlugins); err != nil { + return fmt.Errorf("project %s: claudePlugins: %w", p.Dir, err) + } else { + p.ClaudePlugins, p.reshaped = on, p.reshaped || other + } + if pi, other, err := readProjectPi(x.Pi); err != nil { + return fmt.Errorf("project %s: pi: %w", p.Dir, err) + } else { + p.Pi, p.reshaped = pi, p.reshaped || other + } + return nil +} + +func nullish(b json.RawMessage) bool { return len(b) == 0 || string(b) == "null" } + +// readClaudePlugins: a list of ids, or a map of id to whether it's on +func readClaudePlugins(b json.RawMessage) (on []string, other bool, err error) { + if nullish(b) { + return nil, false, nil + } + if json.Unmarshal(b, &on) == nil { + return on, false, nil + } + var m map[string]bool + if err := json.Unmarshal(b, &m); err != nil { + return nil, false, fmt.Errorf("neither a list of plugin ids nor a map of id to on") + } + for id, yes := range m { + if yes { + on = append(on, id) + } + } + sort.Strings(on) + return on, true, nil +} + +// readProjectPi: a map of source to "on" or "off", or to the agents it is +// for (a list), or to on (a boolean) +func readProjectPi(b json.RawMessage) (pi map[string]string, other bool, err error) { + if nullish(b) { + return nil, false, nil + } + if json.Unmarshal(b, &pi) == nil { + return pi, false, nil + } + var m map[string]json.RawMessage + if err := json.Unmarshal(b, &m); err != nil { + return nil, false, fmt.Errorf("not a map of Pi source to its state") + } + pi = make(map[string]string, len(m)) + for src, v := range m { + var s string + var agents []string + var yes bool + switch { + case json.Unmarshal(v, &s) == nil: + pi[src] = s + case json.Unmarshal(v, &agents) == nil: + pi[src] = map[bool]string{true: "on", false: "off"}[len(slices.DeleteFunc(agents, func(a string) bool { return a == "" })) > 0] + case json.Unmarshal(v, &yes) == nil: + pi[src] = map[bool]string{true: "on", false: "off"}[yes] + default: + return nil, false, fmt.Errorf("%s: %s is neither a state, a list of agents nor on/off", src, v) + } + } + return pi, true, nil +} + +// reshapedCopy keeps the library file's bytes before the first write that +// would put a project read in another shape (Project.UnmarshalJSON) in +// magpie's own, unless a copy is there already. A copy that can't be made +// stops the write: the file stays as it was. +func (l *Library) reshapedCopy() error { + if !slices.ContainsFunc(l.Projects, func(p *Project) bool { return p.reshaped }) { + return nil + } + to := path() + ".before-reshape" + if _, err := os.Stat(to); err == nil { + return nil + } + b, err := os.ReadFile(path()) + if err != nil { + if os.IsNotExist(err) { + return nil + } + return err + } + return os.WriteFile(to, b, 0o600) +} diff --git a/internal/library/project_shapes_test.go b/internal/library/project_shapes_test.go new file mode 100644 index 000000000..c5ae1ba8c --- /dev/null +++ b/internal/library/project_shapes_test.go @@ -0,0 +1,90 @@ +package library + +import ( + "encoding/json" + "os" + "path/filepath" + "reflect" + "strings" + "testing" +) + +// #7282 (jinpwng): a project whose pi maps a source to its agents, or whose +// claudePlugins maps an id to on, as another build wrote them, made the +// whole library unreadable, and no change could be made. Both are read as +// magpie's shapes; the file's bytes stay until a change, which keeps them +// beside it first and then writes magpie's shape. A shape that is neither +// still fails the read, and a write leaves the file alone. +func TestProjectReadsOtherShapes(t *testing.T) { + sandbox(t) + dir := filepath.Join(t.TempDir(), "a") + gitInit(t, dir) + other := filepath.Join(t.TempDir(), "b") + gitInit(t, other) + if err := os.MkdirAll(filepath.Dir(path()), 0o700); err != nil { + t.Fatal(err) + } + put := func(project string) []byte { + t.Helper() + b := []byte(`{"projects":[` + project + `]}` + "\n") + if err := os.WriteFile(path(), b, 0o600); err != nil { + t.Fatal(err) + } + return b + } + q, _ := json.Marshal(dir) + + was := put(`{"dir":` + string(q) + `,"pi":{"npm:example":["pi"],"npm:none":[],"git:github.com/x/y":"off"},"claudePlugins":{"demo@local":true,"off@local":false}}`) + l, err := loadLocked() + if err != nil { + t.Fatalf("the library isn't read: %v", err) + } + p := l.project(dir) + if p == nil { + t.Fatal("the project is gone") + } + if want := map[string]string{"npm:example": "on", "npm:none": "off", "git:github.com/x/y": "off"}; !reflect.DeepEqual(p.Pi, want) { + t.Errorf("pi = %v, want %v", p.Pi, want) + } + if want := []string{"demo@local"}; !reflect.DeepEqual(p.ClaudePlugins, want) { + t.Errorf("claudePlugins = %v, want %v", p.ClaudePlugins, want) + } + if b, _ := os.ReadFile(path()); string(b) != string(was) { + t.Errorf("a read changed the file:\n%s", b) + } + + // an unrelated change goes through, the old bytes kept first + ok(t)(AddProject(other)) + if b, err := os.ReadFile(path() + ".before-reshape"); err != nil || string(b) != string(was) { + t.Errorf("the file as it was isn't kept (%v):\n%s", err, b) + } + b, _ := os.ReadFile(path()) + for _, s := range []string{`"npm:example": "on"`, `"claudePlugins": [`, `"demo@local"`} { + if !strings.Contains(string(b), s) { + t.Errorf("the file isn't in magpie's shape (%s):\n%s", s, b) + } + } + if strings.Contains(string(b), "off@local") { + t.Errorf("a plugin that was off is turned on:\n%s", b) + } + // written once in magpie's shape, a later write keeps no new copy + if err := os.Remove(path() + ".before-reshape"); err != nil { + t.Fatal(err) + } + ok(t)(ProjectPi(other, "npm:later", "on")) + if _, err := os.Stat(path() + ".before-reshape"); err == nil { + t.Error("a library in magpie's shape is copied again") + } + + // neither shape: unknown, and nothing is written over it + bad := put(`{"dir":` + string(q) + `,"claudePlugins":"demo@local"}`) + if _, err := loadLocked(); err == nil { + t.Error("a claudePlugins that is a string is read") + } + if _, err := AddProject(other); err == nil { + t.Error("a change went through over an unreadable library") + } + if b, _ := os.ReadFile(path()); string(b) != string(bad) { + t.Errorf("an unreadable library was written over:\n%s", b) + } +} diff --git a/internal/library/projects.go b/internal/library/projects.go index 3238c1915..79e9fd715 100644 --- a/internal/library/projects.go +++ b/internal/library/projects.go @@ -92,6 +92,9 @@ type Project struct { // (project_pi.go) Pi map[string]string `json:"pi,omitempty"` PiRecs []PiRec `json:"piRecs,omitempty"` + // reshaped: claudePlugins or pi was read in another build's shape + // (project_shapes.go) + reshaped bool } // projectSkillsDirs is where, in a project, each agent reads skills of its