library: a project's claudePlugins and pi read in another build's shapes (#7282)

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).
This commit is contained in:
yetone
2026-11-20 12:06:44 +08:00
parent 06db81530e
commit 57c90f9f27
5 changed files with 216 additions and 1 deletions
File diff suppressed because one or more lines are too long
+3
View File
@@ -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'))
}
+119
View File
@@ -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)
}
+90
View File
@@ -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)
}
}
+3
View File
@@ -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