library: sync and backup files carry the hooks

VincentChan on Discord (v0.1.3005) said part of the Library doesn't reach
his other computer through sync. Checked kind by kind what the library part
of a bundle carries: instructions (each set's text, a linked set's file text,
the agents ticked, each agent's own addition), MCP servers, skills and
subagents all go. Hooks didn't: library.Bundle had no field for them, so a
hook made on one computer never reached the other, by WebDAV/S3/GitHub sync
or a backup file.

- library.Bundle.Hooks (*[]*Hook): name, description, event, matcher,
  command, timeout, agents ticked. Collect always sets it, empty too.
  Applied.Hooks (the entries magpie wrote into each agent here) stays out:
  each computer writes them on the sync Put runs, beside the user's own
  hooks, and records its own entries, so an entry the user edited there
  stays theirs.
- Put replaces the hooks with the bundle's, so one taken out on one
  computer goes from the others. A nil list (a bundle from a magpie before
  this) keeps this computer's.
- check refuses a hook with no name, no command, or named twice. The event
  and agents are carried as they come: an event a newer magpie knows is a
  problem on the agent here, not a refused library.
- davsync: an empty list hashes as before the field, so upgrading with no
  hooks syncs nothing.
- The CLI's backup line counts hooks; the GUI's sync/export/import ticks
  say "instructions, MCP servers, skills, hooks and subagents" in every
  language.
- library.md and sync-backup.md updated, and they now name what stays
  this computer's own: projects, skill groups, CopySkills/SkillHow,
  SharedSkills, MCPHub.

Instructions: two sandbox computers through the fake DAV server carried a
named set and a change to it, a set linked to ~/.agents/AGENTS.md and a
hand edit of that file, both computers having their own text first, an
agent's own addition, and an agent installed after the first sync. All
reached the second computer's CLAUDE.md/AGENTS.md (exploration tests, not
kept). So no instructions change here; what VincentChan saw is not
reproduced yet.

Run (worktree at 0e55a7593; origin/main bf60ea596's two commits touch
none of these files):
- mote: go test -tags nogui ./internal/backup ./internal/davsync
  ./internal/cli ./internal/library ok; go vet -tags nogui for darwin,
  GOOS=linux and GOOS=windows on the four packages ok; gofmt -l clean;
  go test ./internal/gui -run 'TestCoreScriptBudget|Words|I18n|Builtins' ok
- GUI (wsl-run, Linux): i18n-keys, github-sync, s3-sync, sync-*,
  webdav-settings-refresh, library-backups-top, gui-de, gui-ja, gui-zh-tw:
  187/187

Broken by hand: with Collect not setting Hooks, Put ignoring them and the
hash not dropping an empty list (the old code), TestCarryHooks,
TestCarryOldBundleKeepsHooks, TestCarryNewerHooks,
TestBackupFileCarriesHooks, TestSyncHooks and TestNoHooksHashAsBefore
went red.

Not tried: a real WebDAV/S3/GitHub remote between two real computers;
Windows and Linux runs of the Go packages.
This commit is contained in:
yetone
2026-11-05 11:29:20 +08:00
parent bf60ea5968
commit 47d5839397
10 changed files with 353 additions and 19 deletions
+4 -4
View File
@@ -82,8 +82,8 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
- An agent with no place for an item is refused by `Takes`, never recorded as given it. The refusal lists the agents here that take that item (`takenBy`), and says where it goes instead (`noPlace`): OpenChamber reads OpenCode's global AGENTS.md, skills folder and opencode.json (its server's `shared.js`), so it gets them from OpenCode; Claude Desktop's chat keeps its instructions in its own settings, with the Claude account, and its Code tab reads Claude Code's. A plugin's agent is refused an item its `agent.library` names no place for, and the refusal names the key its plugin would set.
- Removing RTK never uses `rtk init --uninstall`. That command deletes Gemini's `GEMINI.md` whole and removes Claude Code, OpenCode and Cursor together.
- A hook is recorded entry by entry, as written (`Applied.Hooks`, compared as canonical JSON). magpie takes out only an entry still exactly as it wrote it; one the user edited is theirs from then on, and the user's own hooks beside it stay. A hooks file that doesn't parse is a problem and is never written. Codex keeps each hook's trust in config.toml as `[hooks.state."<path>:<event>:<group>:<handler>"]`, keyed by position, so when magpie takes a group out `codexRekey` moves the user's trust for the groups after it to their new place.
- A carried library (backup, WebDAV, S3, profile bundles) doesn't carry hooks yet.
- A subagent file is recorded by the hash of what magpie wrote (`Applied.Subagents`). magpie writes over or takes away only a file still exactly as it wrote it; one the user edited is theirs from then on, and the page says so. A file of the user's own by the same name is never written over: the agent gets a problem instead. A file of magpie's the user deleted is written again on the next sync. Cursor's `~/.cursor/agents` is read by the Cursor app only; the cursor-agent CLI reads only a project's `.cursor/agents`. An agent in a WSL distro gets no subagents, nor do agents with no user-level subagent folder (Kimi, Goose, Crush, Qoder, CodeBuddy, iFlow, Kiro). A carried library carries the subagents (`Bundle.Subagents`: name, description, prompt, skills and servers named, agents ticked; xixi_Sean_ on X), never `Applied.Subagents`: each computer writes them into its own agents at the sync `Put` runs and records its own files, so a file the user edited there, or one of theirs by the name, stays theirs as above. `Put` replaces the subagents with the bundle's, so one taken out on one computer goes from the others; a bundle without the field, from a magpie before it, is unknown and keeps the ones here (nil, where Collect always carries a list). Agent ids are carried as they come, one a newer magpie gives subagents to included; a name that isn't one refuses the bundle. An empty list hashes as before the field, so a computer with none sees no change to sync (`TestCarrySubagents`, `TestCarryOldBundleKeepsSubagents`, `TestCarrySubagentKeepsUsersFiles`, `TestCarryNewerSubagents`, `TestBackupFileCarriesSubagents`, `TestSyncSubagents`, `TestNoSubagentsHashAsBefore`). Hooks aren't carried.
- A carried library (backup, WebDAV, S3) carries the hooks (`Bundle.Hooks`: name, description, event, matcher, command, timeout, agents ticked; VincentChan on Discord), never `Applied.Hooks`: each computer writes them into its own agents at the sync `Put` runs, beside the user's own hooks there, and records its own entries, so an entry the user edited there stays theirs as above. `Put` replaces the hooks with the bundle's, so one taken out on one computer goes from the others; a bundle without the field, from a magpie before it, keeps the ones here. The event and agents are carried as they come: an event this magpie doesn't know is a problem on the agent it is given to, not a refused library; a hook with no name or command, or named twice, refuses the bundle. An empty list hashes as before the field (`TestCarryHooks`, `TestCarryOldBundleKeepsHooks`, `TestCarryNewerHooks`, `TestBackupFileCarriesHooks`, `TestSyncHooks`, `TestNoHooksHashAsBefore`). Not carried, as this computer's own: projects (folders here), skill groups, `CopySkills`/`SkillHow`, `SharedSkills` and `MCPHub`.
- A subagent file is recorded by the hash of what magpie wrote (`Applied.Subagents`). magpie writes over or takes away only a file still exactly as it wrote it; one the user edited is theirs from then on, and the page says so. A file of the user's own by the same name is never written over: the agent gets a problem instead. A file of magpie's the user deleted is written again on the next sync. Cursor's `~/.cursor/agents` is read by the Cursor app only; the cursor-agent CLI reads only a project's `.cursor/agents`. An agent in a WSL distro gets no subagents, nor do agents with no user-level subagent folder (Kimi, Goose, Crush, Qoder, CodeBuddy, iFlow, Kiro). A carried library carries the subagents (`Bundle.Subagents`: name, description, prompt, skills and servers named, agents ticked; xixi_Sean_ on X), never `Applied.Subagents`: each computer writes them into its own agents at the sync `Put` runs and records its own files, so a file the user edited there, or one of theirs by the name, stays theirs as above. `Put` replaces the subagents with the bundle's, so one taken out on one computer goes from the others; a bundle without the field, from a magpie before it, is unknown and keeps the ones here (nil, where Collect always carries a list). Agent ids are carried as they come, one a newer magpie gives subagents to included; a name that isn't one refuses the bundle. An empty list hashes as before the field, so a computer with none sees no change to sync (`TestCarrySubagents`, `TestCarryOldBundleKeepsSubagents`, `TestCarrySubagentKeepsUsersFiles`, `TestCarryNewerSubagents`, `TestBackupFileCarriesSubagents`, `TestSyncSubagents`, `TestNoSubagentsHashAsBefore`).
- CC Switch's own skills folder is only ever read.
- Reading the page never waits on reading skills through (#541). `Read` compares an agent's own skill with the same name in another agent (`sameTree`) and hashes each library skill given as a copy (`hashFiles`, for `behind`). Both are kept against a stamp of the folders (each file's and link's path, type, size and mtime, `stamper` in [`treememo.go`](../../internal/library/treememo.go)), taken by the same walk that compares or hashes them, before a file is opened; a later read walks the folder without opening a file, and while the stamps match reuses the answer. Only an answer from a whole read of folders untouched for `settleFor` (3s) is kept: a folder that couldn't be walked or read, or was written a moment ago, is read again next time, never taken as unchanged. A rewrite that keeps a file's size and mtime isn't seen. `Glance` (`GET /api/library?glance=1`) is the page without those two, marked `partial`; the page draws it first, then the whole read, which runs `behind` and `foundSkills` after the library's lock is let go, so a change doesn't wait on them either.
- A read of the page (`Read`, `Glance`) follows the links on the way to a few hundred paths, most of them many times over: each agent's skills folder for each skill, CC Switch's and the shared folder for each source. While the read holds the lock, `resolve` looks at each entry on the way once (`lookPart` in [`linkmemo.go`](../../internal/library/linkmemo.go)): one `Lstat`, and a `Readlink` for a link. Nothing is kept past the read, so a link made or moved on disk between two visits shows on the second. An entry that couldn't be looked at for another reason than its not being there is unknown and looked at again. One read had taken ~10,000 looks; on oxyuan's Windows machine that was ~1.3s a visit (#1771).
@@ -94,9 +94,9 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
```sh
go test -tags nogui ./internal/library -run 'TestGit|TestInstallFromGitRepo|TestReadLooksAtEachFolderOnce|TestLinkChangedBetweenVisitsShows|TestUnreadablePartIsLookedAtAgain|TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestWSLPiMCP|TestWSLMCPSiblings|TestServer|TestHub|TestImportServer|TestCheck|TestInstructions|TestInstructionsSetLinkedToAgentsFile|TestInstructionSets|TestTakesAlma|TestAlma|TestLinkedSet|TestLinkRefused|TestSkill|TestRemoveFoundSkill|TestInstallSet|TestInstallLists|TestEverySkillAgents|TestEveryServerAgents|TestSomeServersAgents|TestRemoveServers|TestRTK|TestEnvRefs|TestDshRefRoundTrip|TestDshImportKeepsJS|TestAgentMCPFiles|TestCodeBuddyMCPFile|TestZedMCP|TestOwnServerFromElsewhereRunsThisMagpie|TestUsersOwnServerStaysAsItIs|TestCarriedOwnServerIsEachComputersMagpie|TestCarry|TestPageReadDoesntReadUnchangedSkillsAgain|TestJustWrittenSkillIsReadAgain|TestUnreadableSkillIsntRememberedAsDifferent|TestGlanceLeavesOutTheAgentsSkills|TestPluginAgent|TestPluginMCPFormatsAreWritten|TestToolsOff|TestOffList|TestHooks|TestSubagent|TestCheckRenewsMagpiesSignIn|TestCheckWSLOnlyServerInItsDistro|TestCheckWindowsServerHere|TestCheckMixedServerEachSide|TestCheckSaysSignInRanOut|TestCheckNamesAgentsSignedInThemselves|TestSignInAsTheUsersOwnApp|TestOAuthAppChecked|TestOAuthAppSecretCarried|TestGoneAgentListedToTakeOut|TestUpdateFindsSkillsRemovedUpstream|TestGoneFromNeedsTheSourceRead'
go test -tags nogui ./internal/library -run 'TestSkillOffHere|TestLocalServerNotCarried|TestPutKeepsLocalServer|TestPutSameNameAsLocal'
go test -tags nogui ./internal/backup -run 'TestRestoreKeepsLocalServer|TestBackupFileCarriesSubagents'
go test -tags nogui ./internal/backup -run 'TestRestoreKeepsLocalServer|TestBackupFileCarriesSubagents|TestBackupFileCarriesHooks'
go test -tags nogui ./internal/library -run 'TestHandOver|TestSharedUnderAnotherName|TestSharedAgentsSkills'
go test -tags nogui ./internal/davsync -run 'TestSkillOffHereThroughSync|TestLocalServerThroughSync|TestSyncSubagents|TestNoSubagentsHashAsBefore'
go test -tags nogui ./internal/davsync -run 'TestSkillOffHereThroughSync|TestLocalServerThroughSync|TestSyncSubagents|TestNoSubagentsHashAsBefore|TestSyncHooks|TestNoHooksHashAsBefore'
go test -tags nogui ./internal/cli -run 'TestLibrarySkillRm|TestLibrarySkillHandOver'
go test -race ./internal/mcpauth
go test -tags nogui ./internal/library
+6
View File
@@ -333,6 +333,12 @@ library with none hashes as it did before, so upgrading syncs nothing
(`TestSyncSubagents`, `TestNoSubagentsHashAsBefore`,
`TestBackupFileCarriesSubagents`).
The hooks go the same way (`library.Bundle.Hooks`): each computer writes
them into its agents beside the user's own hooks and records its own
entries, an older bundle with no list keeps this computer's, and a library
with none hashes as before (`TestSyncHooks`, `TestNoHooksHashAsBefore`,
`TestBackupFileCarriesHooks`).
## Verification
```sh
+55
View File
@@ -0,0 +1,55 @@
package backup
import (
"testing"
"github.com/yetone/magpie/internal/library"
)
// A backup file carries the library's hooks, and restoring it on another
// computer puts them in its library; an older file, made before hooks were
// carried, leaves the ones there.
func TestBackupFileCarriesHooks(t *testing.T) {
home(t)
if _, err := library.SaveHook("", library.Hook{Name: "done", Event: "turn-end", Command: "echo done", Agents: []string{"claude"}}); err != nil {
t.Fatal(err)
}
b, err := Collect(false, "test")
if err != nil {
t.Fatal(err)
}
data, _ := Seal(b, "pw")
old := b
lib := *b.Library
lib.Hooks = nil // as a magpie before them sealed it
old.Library = &lib
older, _ := Seal(old, "pw")
home(t)
if _, err := library.SaveHook("", library.Hook{Name: "mine", Event: "prompt", Command: "echo mine", Agents: []string{}}); err != nil {
t.Fatal(err)
}
got, _ := Open(older, "pw")
if _, err := Restore(got, All); err != nil {
t.Fatal(err)
}
names := func() []string {
l, _ := library.Collect()
var n []string
for _, h := range *l.Hooks {
n = append(n, h.Name)
}
return n
}
if n := names(); len(n) != 1 || n[0] != "mine" {
t.Fatalf("an older file changed the hooks: %v", n)
}
got, _ = Open(data, "pw")
if r, err := Restore(got, All); err != nil || !r.Library {
t.Fatalf("restore: %+v %v", r, err)
}
l, _ := library.Collect()
if h := *l.Hooks; len(h) != 1 || h[0].Name != "done" || h[0].Command != "echo done" || len(h[0].Agents) != 1 || h[0].Agents[0] != "claude" {
t.Fatalf("hooks restored: %+v", h)
}
}
+3
View File
@@ -75,6 +75,9 @@ func backupCmd(args []string) error {
if l.Subagents != nil && len(*l.Subagents) > 0 {
fmt.Printf(", %d subagents", len(*l.Subagents))
}
if l.Hooks != nil && len(*l.Hooks) > 0 {
fmt.Printf(", %d hooks", len(*l.Hooks))
}
}
if s := b.SignIns; s != nil {
fmt.Printf("; %d sign-ins", len(s.Logins)+len(s.Plugins))
+5
View File
@@ -866,6 +866,11 @@ func hashes(b backup.Bundle) map[string]string {
c.Subagents = nil
lib = &c
}
if lib != nil && lib.Hooks != nil && len(*lib.Hooks) == 0 { // as before them, without one
c := *lib
c.Hooks = nil
lib = &c
}
out := map[string]string{
"providers": h(providers),
"settings": settingsHash,
+81
View File
@@ -0,0 +1,81 @@
package davsync
import (
"context"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/backup"
"github.com/yetone/magpie/internal/library"
)
// A hook made on one computer is written into the other's agents by its
// next sync, and taken out of them when the first takes it out.
func TestSyncHooks(t *testing.T) {
fake := &fakeDAV{files: map[string][]byte{}, etags: map[string]string{}, dirs: map[string]bool{"/dav": true}}
srv := httptest.NewServer(fake)
defer srv.Close()
ctx := context.Background()
cfg := Config{URL: srv.URL + "/dav/", User: "me", Password: "pw", Passphrase: "correct horse", Keys: true, Agents: true}
now := func(t *testing.T) {
t.Helper()
if err := Now(ctx); err != nil {
t.Fatal(err)
}
if v := Status(); v.Error != "" {
t.Fatalf("sync: %+v", v)
}
}
a, b := newComputer(t), newComputer(t)
a.use(t)
os.MkdirAll(filepath.Join(string(a), ".claude"), 0o755)
if _, err := library.SaveHook("", library.Hook{Name: "done", Event: "turn-end", Command: "echo done", Agents: []string{"claude"}}); err != nil {
t.Fatal(err)
}
Configure(cfg)
now(t)
b.use(t)
os.MkdirAll(filepath.Join(string(b), ".claude"), 0o755)
Configure(cfg)
now(t)
settings := filepath.Join(string(b), ".claude", "settings.json")
if s, _ := os.ReadFile(settings); !strings.Contains(string(s), "echo done") {
t.Fatalf("b's Claude Code wasn't given the hook: %q", s)
}
puts := fake.puts
now(t)
if fake.puts != puts {
t.Fatalf("b pushed back the hooks it brought in (%d puts)", fake.puts-puts)
}
a.use(t)
if _, err := library.RemoveHooks([]string{"done"}); err != nil {
t.Fatal(err)
}
now(t)
b.use(t)
now(t)
if s, _ := os.ReadFile(settings); strings.Contains(string(s), "echo done") {
t.Errorf("the hook is still in b's Claude Code after a took it out: %q", s)
}
}
// A library with no hooks hashes as it did before they were carried, so a
// magpie that starts carrying them doesn't see a change to sync.
func TestNoHooksHashAsBefore(t *testing.T) {
none := []*library.Hook{}
with := backup.Bundle{Library: &library.Bundle{MCP: []*library.Server{}, Skills: []*library.CarriedSkill{}, Hooks: &none}}
before := backup.Bundle{Library: &library.Bundle{MCP: []*library.Server{}, Skills: []*library.CarriedSkill{}}}
if hashes(with)["library"] != hashes(before)["library"] {
t.Error("an empty list of hooks changed the library's hash")
}
one := []*library.Hook{{Name: "done", Event: "turn-end", Command: "echo done"}}
with.Library.Hooks = &one
if hashes(with)["library"] == hashes(before)["library"] {
t.Error("a hook didn't change the library's hash")
}
}
+12 -12
View File
@@ -2910,7 +2910,7 @@ const I18N = {
"the same on every computer": "每台电脑上都一样",
"Providers' API keys": "供应商的 API Key",
"Agents' models": "各 agent 选的模型",
"Library: instructions, MCP servers, skills and subagents": "资源库:指令、MCP 服务器、技能和子代理",
"Library: instructions, MCP servers, skills, hooks and subagents": "资源库:指令、MCP 服务器、技能、Hooks 和子代理",
"Usage: this computer's calls, for the Usage page on the others": "用量:本机的请求,在其他电脑的用量页里显示",
"Usage goes as a file a day: times, tokens, models and costs, never what was said. Turn it on on each computer that shares its own.": "用量每天一个文件:时间、token、模型和费用,不含对话内容。每台要共享用量的电脑都需各自打开。",
"usage": "用量",
@@ -2941,13 +2941,13 @@ const I18N = {
"Pick a passphrase: the file is sealed with it": "请设置口令:文件会用它加密",
"passphrase": "口令", "again": "再输入一次",
"With the providers' API keys": "包含供应商的 API Key",
"With the library: instructions, MCP servers, skills and subagents": "包含资源库:指令、MCP 服务器、技能和子代理",
"With the library: instructions, MCP servers, skills, hooks and subagents": "包含资源库:指令、MCP 服务器、技能、Hooks 和子代理",
"Needed to open the file. Subscriptions aren't in it: sign in to them on the other computer.": "打开文件时需要。订阅账号不在其中,请在另一台电脑上各自登录。",
"The two passphrases differ": "两次输入的口令不一致",
"Saved to {path}": "已保存到 {path}",
"No file chosen": "未选择文件", "Choose…": "选择…", "File": "文件",
"Set the agents' models too": "同时设置各 agent 的模型",
"Bring in the library too: instructions, MCP servers, skills and subagents": "同时导入资源库:指令、MCP 服务器、技能和子代理",
"Bring in the library too: instructions, MCP servers, skills, hooks and subagents": "同时导入资源库:指令、MCP 服务器、技能、Hooks 和子代理",
"Providers with the same id are replaced; one that came without a key keeps the key it has here. The library replaces the one here, which is kept with its backups.": "同 id 的供应商会被替换;不带 Key 的保留本机已有的 Key。资源库将替换本机资源库,原内容保存在备份中。",
"Choose a file first": "请先选择文件",
"Providers: {added} added, {replaced} replaced; {profiles} profiles; {agents} agent settings changed": "供应商:新增 {added} 个,替换 {replaced} 个;Profile {profiles} 个;agent 设置改动 {agents} 项",
@@ -7498,7 +7498,7 @@ const I18N = {
"the same on every computer": "每臺電腦上都一樣",
"Providers' API keys": "供應商的 API Key",
"Agents' models": "各 agent 選的模型",
"Library: instructions, MCP servers, skills and subagents": "資源庫:指令、MCP 伺服器、技能和子代理",
"Library: instructions, MCP servers, skills, hooks and subagents": "資源庫:指令、MCP 伺服器、技能、Hooks 和子代理",
"Usage: this computer's calls, for the Usage page on the others": "用量:本機的請求,在其他電腦的用量頁裡顯示",
"Usage goes as a file a day: times, tokens, models and costs, never what was said. Turn it on on each computer that shares its own.": "用量每天一個檔案:時間、token、模型和費用,不含對話內容。每臺要共享用量的電腦都需各自開啟。",
"usage": "用量",
@@ -7537,7 +7537,7 @@ const I18N = {
"passphrase": "口令",
"again": "再輸入一次",
"With the providers' API keys": "包含供應商的 API Key",
"With the library: instructions, MCP servers, skills and subagents": "包含資源庫:指令、MCP 伺服器、技能和子代理",
"With the library: instructions, MCP servers, skills, hooks and subagents": "包含資源庫:指令、MCP 伺服器、技能、Hooks 和子代理",
"Needed to open the file. Subscriptions aren't in it: sign in to them on the other computer.": "開啟檔案時需要。訂閱帳號不在其中,請在另一臺電腦上各自登入。",
"The two passphrases differ": "兩次輸入的口令不一致",
"Saved to {path}": "已儲存到 {path}",
@@ -7545,7 +7545,7 @@ const I18N = {
"Choose…": "選擇…",
"File": "檔案",
"Set the agents' models too": "同時設定各 agent 的模型",
"Bring in the library too: instructions, MCP servers, skills and subagents": "同時匯入資源庫:指令、MCP 伺服器、技能和子代理",
"Bring in the library too: instructions, MCP servers, skills, hooks and subagents": "同時匯入資源庫:指令、MCP 伺服器、技能、Hooks 和子代理",
"Providers with the same id are replaced; one that came without a key keeps the key it has here. The library replaces the one here, which is kept with its backups.": "同 id 的供應商會被替換;不帶 Key 的保留本機已有的 Key。資源庫將替換本機資源庫,原內容儲存在備份中。",
"Choose a file first": "請先選擇檔案",
"Providers: {added} added, {replaced} replaced; {profiles} profiles; {agents} agent settings changed": "供應商:新增 {added} 個,替換 {replaced} 個;Profile {profiles} 個;agent 設定改動 {agents} 項",
@@ -12095,7 +12095,7 @@ const I18N = {
"the same on every computer": "すべてのコンピューターで共通",
"Providers' API keys": "プロバイダの APIキー",
"Agents' models": "エージェントのモデル",
"Library: instructions, MCP servers, skills and subagents": "ライブラリ:指示、MCP サーバー、スキル、サブエージェント",
"Library: instructions, MCP servers, skills, hooks and subagents": "ライブラリ:指示、MCP サーバー、スキル、フック、サブエージェント",
"Usage: this computer's calls, for the Usage page on the others": "使用量:このコンピューターの呼び出し(他のコンピューターの「使用量」ページ用)",
"Usage goes as a file a day: times, tokens, models and costs, never what was said. Turn it on on each computer that shares its own.": "使用量は1日1ファイルで送られます:時刻、トークン、モデル、費用のみで、会話内容は含みません。自分の使用量を共有する各コンピューターでオンにしてください。",
"usage": "使用量",
@@ -12134,7 +12134,7 @@ const I18N = {
"passphrase": "パスフレーズ",
"again": "もう一度",
"With the providers' API keys": "プロバイダの APIキーを含める",
"With the library: instructions, MCP servers, skills and subagents": "ライブラリを含める:指示、MCP サーバー、スキル、サブエージェント",
"With the library: instructions, MCP servers, skills, hooks and subagents": "ライブラリを含める:指示、MCP サーバー、スキル、フック、サブエージェント",
"Needed to open the file. Subscriptions aren't in it: sign in to them on the other computer.": "ファイルを開くときに必要です。サブスクリプションは含まれないため、別のコンピューターでサインインしてください。",
"The two passphrases differ": "2つのパスフレーズが一致しません",
"Saved to {path}": "{path} に保存しました",
@@ -12142,7 +12142,7 @@ const I18N = {
"Choose…": "選択…",
"File": "ファイル",
"Set the agents' models too": "エージェントのモデルも設定する",
"Bring in the library too: instructions, MCP servers, skills and subagents": "ライブラリも取り込む:指示、MCP サーバー、スキル、サブエージェント",
"Bring in the library too: instructions, MCP servers, skills, hooks and subagents": "ライブラリも取り込む:指示、MCP サーバー、スキル、フック、サブエージェント",
"Providers with the same id are replaced; one that came without a key keeps the key it has here. The library replaces the one here, which is kept with its backups.": "同じ ID のプロバイダは置き換えられます。キーなしで来たものはここにあるキーを保持します。ライブラリはここのものを置き換え、置き換えられたものはバックアップとともに保持されます。",
"Choose a file first": "先にファイルを選んでください",
"Providers: {added} added, {replaced} replaced; {profiles} profiles; {agents} agent settings changed": "プロバイダ:{added} 件追加、{replaced} 件置換。プロファイル {profiles} 件。エージェント設定 {agents} 件を変更",
@@ -16703,7 +16703,7 @@ const I18N = {
"the same on every computer": "auf jedem Computer gleich",
"Providers' API keys": "API-Schlüssel der Anbieter",
"Agents' models": "Modelle der Agenten",
"Library: instructions, MCP servers, skills and subagents": "Bibliothek: Anweisungen, MCP-Server, Skills und Subagenten",
"Library: instructions, MCP servers, skills, hooks and subagents": "Bibliothek: Anweisungen, MCP-Server, Skills, Hooks und Subagenten",
"Usage: this computer's calls, for the Usage page on the others": "Nutzung: Aufrufe dieses Computers, für die Seite „Nutzung“ auf den anderen",
"Usage goes as a file a day: times, tokens, models and costs, never what was said. Turn it on on each computer that shares its own.": "Die Nutzung wird als eine Datei pro Tag übertragen: Zeiten, Token, Modelle und Kosten, nie die Inhalte. Auf jedem Computer einschalten, der seine eigene teilt.",
"usage": "Nutzung",
@@ -16742,7 +16742,7 @@ const I18N = {
"passphrase": "Passphrase",
"again": "wiederholen",
"With the providers' API keys": "Mit den API-Schlüsseln der Anbieter",
"With the library: instructions, MCP servers, skills and subagents": "Mit der Bibliothek: Anweisungen, MCP-Server, Skills und Subagenten",
"With the library: instructions, MCP servers, skills, hooks and subagents": "Mit der Bibliothek: Anweisungen, MCP-Server, Skills, Hooks und Subagenten",
"Needed to open the file. Subscriptions aren't in it: sign in to them on the other computer.": "Wird zum Öffnen der Datei benötigt. Abos sind nicht enthalten: Melden Sie sich auf dem anderen Computer bei ihnen an.",
"The two passphrases differ": "Die beiden Passphrasen stimmen nicht überein",
"Saved to {path}": "Gespeichert unter {path}",
@@ -16750,7 +16750,7 @@ const I18N = {
"Choose…": "Auswählen…",
"File": "Datei",
"Set the agents' models too": "Auch die Modelle der Agenten setzen",
"Bring in the library too: instructions, MCP servers, skills and subagents": "Auch die Bibliothek importieren: Anweisungen, MCP-Server, Skills und Subagenten",
"Bring in the library too: instructions, MCP servers, skills, hooks and subagents": "Auch die Bibliothek importieren: Anweisungen, MCP-Server, Skills, Hooks und Subagenten",
"Providers with the same id are replaced; one that came without a key keeps the key it has here. The library replaces the one here, which is kept with its backups.": "Anbieter mit gleicher ID werden ersetzt; einer ohne Schlüssel behält den hier vorhandenen Schlüssel. Die Bibliothek ersetzt die hiesige, die in den Backups erhalten bleibt.",
"Choose a file first": "Wählen Sie zuerst eine Datei",
"Providers: {added} added, {replaced} replaced; {profiles} profiles; {agents} agent settings changed": "Anbieter: {added} hinzugefügt, {replaced} ersetzt; {profiles} Profile; {agents} Agenteneinstellungen geändert",
+3 -3
View File
@@ -33,7 +33,7 @@ window.davForm = function (v) {
const phrase = input("", v.passphraseSet ? saved : t("the same on every computer"), "password");
const [keysL, keys] = tick(t("Providers' API keys"), v.keys !== false);
const [agentsL, agents] = tick(t("Agents' models"), v.agents !== false);
const [libL, lib] = tick(t("Library: instructions, MCP servers, skills and subagents"), v.library !== false);
const [libL, lib] = tick(t("Library: instructions, MCP servers, skills, hooks and subagents"), v.library !== false);
// usage: off unless picked, each computer its own (#542)
const [useL, use] = tick(t("Usage: this computer's calls, for the Usage page on the others"), !!v.usage);
// sign-ins: off unless picked, sealed with the passphrase like the rest
@@ -116,7 +116,7 @@ window.exportForm = function () {
const p1 = input("", t("passphrase"), "password");
const p2 = input("", t("again"), "password");
const [keysL, keys] = tick(t("With the providers' API keys"), true);
const [libL, lib] = tick(t("With the library: instructions, MCP servers, skills and subagents"), true);
const [libL, lib] = tick(t("With the library: instructions, MCP servers, skills, hooks and subagents"), true);
// sign-ins: off unless picked (qianxunji, curtinp118 on Discord)
const [siL, si] = tick(t("With the sign-ins: subscription accounts and plugin sign-ins"), false);
const what = el("div", "stack");
@@ -179,7 +179,7 @@ window.importForm = function () {
pf.append(name, pick, file);
const pass = input("", t("passphrase"), "password");
const [agentsL, agents] = tick(t("Set the agents' models too"), true);
const [libL, lib] = tick(t("Bring in the library too: instructions, MCP servers, skills and subagents"), true);
const [libL, lib] = tick(t("Bring in the library too: instructions, MCP servers, skills, hooks and subagents"), true);
const [siL, si] = tick(t("Bring in the sign-ins too, when the file has them"), true);
const what = el("div", "stack");
what.append(agentsL, libL, siL);
+43
View File
@@ -33,6 +33,10 @@ type Bundle struct {
// carried, which knew nothing of this computer's: Put keeps them. Collect
// always sets it, empty too, so taking the last one out is carried.
Subagents *[]*Subagent `json:"subagents,omitempty"`
// Hooks are nil in a bundle from a magpie before they were carried,
// as Subagents are: Put keeps this computer's. Applied.Hooks, the
// entries magpie wrote into each agent here, stays out.
Hooks *[]*Hook `json:"hooks,omitempty"`
}
// CarriedSkill is a skill with its folder's files.
@@ -117,6 +121,13 @@ func Collect() (*Bundle, error) {
subs = append(subs, &c)
}
b.Subagents = &subs
hooks := []*Hook{}
for _, h := range sorted(l.Hooks, func(h *Hook) string { return h.Name }) {
c := *h
c.Agents = orNone(slices.Sorted(slices.Values(h.Agents)))
hooks = append(hooks, &c)
}
b.Hooks = &hooks
return b, nil
}
@@ -264,6 +275,27 @@ func (b *Bundle) check() error {
seen[s.Name] = true
}
}
if b.Hooks != nil {
seen := map[string]bool{}
for _, h := range *b.Hooks {
if h == nil {
return fmt.Errorf("an empty hook")
}
// the event and agents are left as they come: one a newer
// magpie knows and this one doesn't is a problem on the
// agent it is given to (syncHooks), not a refused library
if err := checkName("hook", h.Name); err != nil {
return err
}
if strings.TrimSpace(h.Command) == "" {
return fmt.Errorf("the hook %s has no command", h.Name)
}
if seen[h.Name] {
return fmt.Errorf("the hook %s twice", h.Name)
}
seen[h.Name] = true
}
}
return nil
}
@@ -501,6 +533,17 @@ func Put(b *Bundle) (*Result, error) {
}
l.Subagents = subs
}
// the same for hooks: Applied.Hooks decides, entry by entry,
// what magpie takes out of each agent's file here
if b.Hooks != nil {
hooks := []*Hook{}
for _, h := range *b.Hooks {
c := *h
c.Agents = slices.Clone(orNone(h.Agents))
hooks = append(hooks, &c)
}
l.Hooks = hooks
}
return nil
})
}
+141
View File
@@ -0,0 +1,141 @@
package library
import (
"encoding/json"
"path/filepath"
"strings"
"testing"
)
// A hook goes with the library to another computer, which writes it into
// its agents beside the user's own hooks there; what magpie wrote into the
// first computer's agents stays out of the bundle; taking it out on one
// takes magpie's entry out on the other and leaves the user's.
func TestCarryHooks(t *testing.T) {
sandbox(t)
ok(t)(SaveHook("", Hook{Name: "bark", Description: "Ping my phone", Event: "turn-end", Command: "curl -s https://api.day.app/KEY/done",
Timeout: 10, Agents: []string{"codex", "claude"}}))
b, err := Collect()
if err != nil {
t.Fatal(err)
}
carried := mustJSON(t, b)
var raw struct {
Hooks []map[string]any `json:"hooks"`
}
json.Unmarshal([]byte(carried), &raw)
if len(raw.Hooks) != 1 {
t.Fatalf("hooks carried: %s", carried)
}
if got := raw.Hooks[0]; got["name"] != "bark" || got["event"] != "turn-end" || got["description"] != "Ping my phone" ||
got["command"] != "curl -s https://api.day.app/KEY/done" || got["timeout"] != float64(10) || mustJSON(t, got["agents"]) != `["claude","codex"]` {
t.Errorf("the hook carried: %v", got)
}
if strings.Contains(carried, "applied") || strings.Contains(carried, `"entry"`) {
t.Errorf("what magpie wrote here is carried:\n%s", carried)
}
h2 := sandbox(t)
settings := filepath.Join(h2, ".claude/settings.json")
write(t, settings, `{"model": "opus", "hooks": {"Stop": [{"hooks": [{"type": "command", "command": "say my own"}]}]}}`)
r := putJSON(t, carried)
for _, p := range r.Problems {
if strings.HasPrefix(p.What, "hook") {
t.Errorf("a problem: %+v", p)
}
}
if got := hooksOf(t, settings, "Stop"); len(got) != 2 || !strings.Contains(got[0], "say my own") || !strings.Contains(got[1], "api.day.app") {
t.Errorf("claude's Stop on the second computer: %v", got)
}
if got := hooksOf(t, filepath.Join(h2, ".codex/hooks.json"), "Stop"); len(got) != 1 || !strings.Contains(got[0], "api.day.app") {
t.Errorf("codex's Stop on the second computer: %v", got)
}
// the first computer takes it out
none := []*Hook{}
b.Hooks = &none
putJSON(t, mustJSON(t, b))
if got := hooksOf(t, settings, "Stop"); len(got) != 1 || !strings.Contains(got[0], "say my own") {
t.Errorf("after the hook was taken out, claude's Stop: %v", got)
}
if !strings.Contains(read(t, settings), `"model": "opus"`) {
t.Errorf("the user's settings changed:\n%s", read(t, settings))
}
}
// A bundle from a magpie before hooks were carried has none, and knew
// nothing of this computer's: they stay.
func TestCarryOldBundleKeepsHooks(t *testing.T) {
sandbox(t)
ok(t)(SaveServer("", Server{Name: "github", Transport: "stdio", Command: "npx", Agents: []string{"claude"}}))
b, err := Collect()
if err != nil || b == nil {
t.Fatal(b, err)
}
b.Hooks = nil
old := mustJSON(t, b)
if strings.Contains(old, `"hooks"`) {
t.Fatalf("not as an older magpie wrote it: %s", old)
}
h := sandbox(t)
ok(t)(SaveHook("", Hook{Name: "mine", Event: "turn-end", Command: "say mine", Agents: []string{"claude"}}))
putJSON(t, old)
l, err := Collect()
if err != nil {
t.Fatal(err)
}
if l.Hooks == nil || len(*l.Hooks) != 1 || (*l.Hooks)[0].Name != "mine" {
t.Fatalf("an older bundle changed the hooks: %s", mustJSON(t, l.Hooks))
}
if got := hooksOf(t, filepath.Join(h, ".claude/settings.json"), "Stop"); len(got) != 1 {
t.Errorf("claude's Stop: %v", got)
}
}
// A hook on an event a newer magpie knows and this one doesn't is carried
// as it comes: the agent it is given to has a problem, and the rest of the
// library comes in. A hook with no name or command, or one named twice,
// refuses the bundle.
func TestCarryNewerHooks(t *testing.T) {
sandbox(t)
ok(t)(SaveServer("", Server{Name: "github", Transport: "stdio", Command: "npx", Agents: []string{"claude"}}))
b, err := Collect()
if err != nil || b == nil {
t.Fatal(b, err)
}
hooks := []*Hook{
{Name: "later", Event: "turn-later", Command: "say later", Agents: []string{"claude", "newagent"}},
{Name: "done", Event: "turn-end", Command: "say done", Agents: []string{"claude"}},
}
b.Hooks = &hooks
h := sandbox(t)
r := putJSON(t, mustJSON(t, b))
if got := hooksOf(t, filepath.Join(h, ".claude/settings.json"), "Stop"); len(got) != 1 || !strings.Contains(got[0], "say done") {
t.Errorf("claude's Stop: %v", got)
}
found := false
for _, p := range r.Problems {
found = found || p.What == "hook:later"
}
if !found {
t.Errorf("no problem for the event this magpie doesn't know: %+v", r.Problems)
}
l, _ := Collect()
if len(*l.Hooks) != 2 || (*l.Hooks)[1].Name != "later" || mustJSON(t, (*l.Hooks)[1].Agents) != `["claude","newagent"]` {
t.Errorf("not kept as it came: %s", mustJSON(t, l.Hooks))
}
for _, bad := range [][]*Hook{
{{Name: "a b", Event: "turn-end", Command: "x"}},
{{Name: "x", Event: "turn-end", Command: " "}},
{{Name: "x", Event: "turn-end", Command: "x"}, {Name: "x", Event: "prompt", Command: "y"}},
{nil},
} {
b.Hooks = &bad
var in Bundle
json.Unmarshal([]byte(mustJSON(t, b)), &in)
if _, err := Put(&in); err == nil {
t.Errorf("put %s", mustJSON(t, bad))
}
}
}