diff --git a/internal/agent/rewire.go b/internal/agent/rewire.go index c50bd752b..6c0bd84c3 100644 --- a/internal/agent/rewire.go +++ b/internal/agent/rewire.go @@ -2,10 +2,7 @@ package agent import ( "context" - "encoding/json" "fmt" - "os" - "path/filepath" "strings" ) @@ -130,7 +127,7 @@ const wiredAt = ".wired_at" // stashPut writes the stash as m has it. func stashPut(m map[string]string) { - b, _ := json.MarshalIndent(m, "", " ") - os.MkdirAll(filepath.Dir(stashPath()), 0o755) - os.WriteFile(stashPath(), b, 0o600) + stashMu.Lock() + defer stashMu.Unlock() + stashWrite(m) } diff --git a/internal/agent/stash.go b/internal/agent/stash.go index 2176c44d9..578f94592 100644 --- a/internal/agent/stash.go +++ b/internal/agent/stash.go @@ -2,14 +2,29 @@ package agent import ( "encoding/json" + "errors" + "io/fs" + "log" "os" "path/filepath" + "sync" + "time" + "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/provider" ) // The stash remembers what an agent's config said before magpie pointed it // at the gateway, so switching back restores it instead of guessing. +// +// stash.json holds every agent's originals, so a change to it is read, +// changed and written under stashMu, and written whole (edit.WriteAtomic): +// two changes at once, or one cut short, never leave it half there, which +// the next change read as no stash and wrote back over every agent's. A +// file that doesn't parse (edited by hand, or half written by an older +// magpie) is copied aside before it is written over, so what it held can +// still be got back. +var stashMu sync.Mutex func stashPath() string { return filepath.Join(filepath.Dir(provider.Path()), "stash.json") } @@ -21,7 +36,46 @@ func stashLoad() map[string]string { return out } +// stashWrite writes m as the stash, a file there that doesn't parse kept +// aside first. The caller holds stashMu. +func stashWrite(m map[string]string) error { + b, err := json.MarshalIndent(m, "", " ") + if err != nil { + return err + } + p := stashPath() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + return err + } + keepUnreadStash(p) + // made 0600 first: WriteAtomic keeps a file's mode, and the stash holds + // keys + if f, err := os.OpenFile(p, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600); err == nil { + f.Close() + } else if !errors.Is(err, fs.ErrExist) { + return err + } + return edit.WriteAtomic(p, b) +} + +// keepUnreadStash copies a stash.json that doesn't parse aside before it is +// written over. +func keepUnreadStash(path string) { + b, err := os.ReadFile(path) + if err != nil || len(b) == 0 || json.Valid(b) { + return + } + bad := path + ".bad-" + time.Now().Format("20060102-150405.000000000") + if err := os.WriteFile(bad, b, 0o600); err != nil { + log.Printf("stash.json doesn't parse and couldn't be kept: %v", err) + return + } + log.Printf("stash.json didn't parse; it is kept as %s", filepath.Base(bad)) +} + func stash(kv map[string]string) { + stashMu.Lock() + defer stashMu.Unlock() m := stashLoad() for k, v := range kv { if v == "" { @@ -30,28 +84,28 @@ func stash(kv map[string]string) { m[k] = v } } - b, _ := json.MarshalIndent(m, "", " ") - os.MkdirAll(filepath.Dir(stashPath()), 0o755) - os.WriteFile(stashPath(), b, 0o600) + stashWrite(m) } // forget drops stashed values without restoring them. func forget(keys ...string) { + stashMu.Lock() + defer stashMu.Unlock() m := stashLoad() for _, k := range keys { delete(m, k) } - b, _ := json.MarshalIndent(m, "", " ") - os.WriteFile(stashPath(), b, 0o600) + stashWrite(m) } func unstash(key string) string { + stashMu.Lock() + defer stashMu.Unlock() m := stashLoad() v := m[key] if v != "" { delete(m, key) - b, _ := json.MarshalIndent(m, "", " ") - os.WriteFile(stashPath(), b, 0o600) + stashWrite(m) } return v } diff --git a/internal/agent/stash_test.go b/internal/agent/stash_test.go new file mode 100644 index 000000000..99ef62f02 --- /dev/null +++ b/internal/agent/stash_test.go @@ -0,0 +1,71 @@ +package agent + +import ( + "fmt" + "os" + "path/filepath" + "runtime" + "sync" + "testing" +) + +func stashHome(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) +} + +// Every agent's originals are in one stash.json, and each agent's connect +// and disconnect read, change and write it: two at once (the GUI's Connect +// all, a gateway move setting every agent again) must keep both changes. +func TestStashKeepsChangesMadeAtOnce(t *testing.T) { + stashHome(t) + var wg sync.WaitGroup + for i := range 40 { + wg.Add(1) + go func() { + defer wg.Done() + stash(map[string]string{fmt.Sprintf("agent%d.was", i): "theirs"}) + }() + } + wg.Wait() + if n := len(stashLoad()); n != 40 { + t.Fatalf("%d of 40 agents' originals kept", n) + } +} + +// A stash.json that doesn't parse is read as no stash, and the next change +// writes over it: what it held, every agent's originals, is copied aside +// first, so it can still be got back. +func TestUnreadStashKeptAside(t *testing.T) { + stashHome(t) + p := stashPath() + os.MkdirAll(filepath.Dir(p), 0o755) + half := `{"claude.was": "sk-their-own", "codex.wa` + if err := os.WriteFile(p, []byte(half), 0o600); err != nil { + t.Fatal(err) + } + stash(map[string]string{"pi.was": "x"}) + if got := stashLoad(); got["pi.was"] != "x" { + t.Fatalf("stash after the change: %v", got) + } + bad, _ := filepath.Glob(p + ".bad-*") + if len(bad) != 1 { + t.Fatalf("kept aside: %v", bad) + } + if b, _ := os.ReadFile(bad[0]); string(b) != half { + t.Fatalf("kept aside as %q", b) + } + // a stash that parses is written over as before, nothing more kept + forget("pi.was") + if more, _ := filepath.Glob(p + ".bad-*"); len(more) != 1 { + t.Fatalf("kept aside after a good write: %v", more) + } + if fi, err := os.Stat(p); err != nil { + t.Fatal(err) + } else if runtime.GOOS != "windows" && fi.Mode().Perm() != 0o600 { + t.Fatalf("stash.json is %v; it holds keys", fi.Mode().Perm()) + } +} diff --git a/internal/agent/stepcode.go b/internal/agent/stepcode.go index 6e14077e7..9bf727390 100644 --- a/internal/agent/stepcode.go +++ b/internal/agent/stepcode.go @@ -207,6 +207,8 @@ func loadStepcodeState(at place) (*stepcodeState, error) { } func stepcodeStoreState(at place, state *stepcodeState) error { + stashMu.Lock() + defer stashMu.Unlock() m, err := stepcodeReadStash() if err != nil { return err @@ -221,22 +223,7 @@ func stepcodeStoreState(at place, state *stepcodeState) error { } m[key] = string(b) } - data, err := json.MarshalIndent(m, "", " ") - if err != nil { - return err - } - if err := os.MkdirAll(filepath.Dir(stashPath()), 0o700); err != nil { - return err - } - f, err := os.OpenFile(stashPath(), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) - if err == nil { - if err := f.Close(); err != nil { - return err - } - } else if !errors.Is(err, fs.ErrExist) { - return err - } - return edit.WriteAtomic(stashPath(), data) + return stashWrite(m) } func stepcodeStartup(cfg stepcodeTOML) string {