library: Variables are carried in backups and sync, keys only with keys (onducoder on X)

A skill's key set once as a Library variable (ANYSEARCH_API_KEY and the
like) now goes with the library: Bundle.Env carries name, value and agents
(nil from an older magpie, and Put then keeps this computer's). It follows
how servers' tokens are carried: a backup or sync without keys keeps the
names and empties every value (whatever the name, since a variable's name
says nothing of its value), WithSecrets fills them from this computer's, and
one with keys is sealed under its passphrase. A variable with no value is
not written into an agent (syncEnv), and a value the user set in the agent's
file is still never overridden. Not built: showing the variables a skill
needs on its sheet; nothing in a SKILL.md says them reliably.

Run (mote): go test ./internal/library ./internal/backup ./internal/davsync
ok; gofmt clean; go vet darwin, windows, linux -tags nogui clean.
Broken by hand: WithoutSecrets leaving the value turns TestEnvIsCarried red.
Not tried: real Claude Code / Codex reading the carried key; a real WebDAV
or S3 round trip; the full suite; GUI tests (no GUI file touched).
This commit is contained in:
yetone
2026-11-12 02:59:41 +08:00
parent 4b29709eca
commit 5d5d57cbbb
4 changed files with 111 additions and 2 deletions
+2 -1
View File
@@ -34,7 +34,7 @@ Pi's extensions and packages.
| Skill groups | The page groups skills by `SkillView.Repo`, the repository each came from (`tracer.repoOf`): its GitHub source, CC Switch's `Origin`, `From`, the skills CLI's lock or the git checkout a linked folder is in. That checkout is the one git finds (`provider.GitAt` in `gitRepoOf`): an empty `.git` between the skill and its checkout is passed over, as git passes it over, and a `.git` file that names no repository (a worktree left behind) is none (#3675, `TestSkillRepoTraced`). A lock entry of `sourceType: well-known` (a site's kit at its `/.well-known/agent-skills/`) is grouped by its `sourceBaseUrl` as host/path (`wellKnownBase`), not by each skill's own `sourceUrl`: Feishu's lark-* skills are one group and Fish Audio's another, while two kits under one host with different base URLs stay apart. An older entry with no base URL takes the part of its `sourceUrl` before `/.well-known/`, and one with neither is grouped by its `sourceUrl` as before. Such a kit is never fetched from GitHub by Group again, even when it reads like owner/repo (a GitHub owner has no dot), and its heading's link opens the site (#1862, `TestWellKnownKitGrouped`). `From` is written when a repository is probed (installing from it again, `noteFrom`): for a skill with the very same `SKILL.md`, and for one traced to nowhere by a name the repository has when the library has others from there, since a pack added a while ago is mostly older copies edited there since (White Immortal on Discord: 20 of mattpocock/skills' 38). Group again (`RegroupSkills`, `POST /api/library/skills/regroup`) fetches each GitHub repository the skills are traced to and does the same; it fails only when none could be fetched. A skill traced to another repository is never moved. A group's (or part's, or the Select bar's) agent chips count, give and take only the skills magpie decides for each agent: one kept in `~/.agents/skills` is in `SkillView.Always` for the agents that read that folder themselves, so a chip's `agents-some` for such an agent leaves it out, its tooltip and the status after a click say how many it still reads itself, and an agent that reads every one of them itself has a lit, locked chip as the row's is, which sends nothing (`groupChips` in plugins/library/client.js). The heading says how many of its skills are in `~/.agents/skills`. A row's locked chip is lit with a lock on its corner, not greyed like a chip that can't be given the skill (#1862, `skill-group-shared.test.cjs`). Collapse all / Expand all, beside the sort, folds or opens every group the list shows at once (`foldAllButton`): without a filter it sets each group's kept fold (`magpie.libSkillFolds`), as a click on each heading would; while filtering, only the groups the filter shows, till the filter changes (`unfiltered`), leaving the kept folds alone. It reads Collapse all while any shown group is open, is hidden with fewer than two groups (A→Z, or a filter one group matches), leaves a part's own fold as it is and sends nothing (#1862, `skill-fold-all.test.cjs`). | [`skill_from.go`](../../internal/library/skill_from.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) |
| Skill updates | A skill from GitHub (`kind: github`, a market install among them) keeps the commit it was fetched at and `Hash`, the hash of its files as fetched. `CheckSkills` asks GitHub for each one's last commit and keeps the result in memory; `View.CheckDue` says none was checked since magpie started, or not for `checkEvery` (12 hours), and the page then checks by itself as the skills open (#1449). `editState` says a skill was changed here when the library's folder no longer hashes to `Hash` (`.DS_Store` aside), or an agent's copy was edited since its mark and not yet taken in; the view's `edited` says so. What installing a skill's dependencies or running it writes in its folder is no change (`fromInstall`: `node_modules`, `.venv`, `venv`, `__pycache__`, `.pytest_cache`, `.mypy_cache`, `.ruff_cache` folders, `*.pyc`/`*.pyo`, and `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `bun.lock`, `bun.lockb`, `uv.lock` written again; ggbr on Discord): `Own` is the hash of the files as fetched leaving those aside (`ownHash`), and `onlyInstalled` compares the folder with it, or for a skill fetched before `Own` was kept with `Hash` (so a lock file the install wrote again still reads as changed until its next update). An update carries those entries over to the version fetched where it has none of its own (`carryInstalled`), so they aren't installed again. `UpdateSkill` refuses such a skill with `*EditedError` unless told to replace it (the page's own Update asks first; the CLI takes `--replace-edits`), and `UpdateSkills`/`UpdateSomeSkills` leave it as it is, in `Unupdated`. A replaced version that was changed, or that can't be told (no `Hash`), is moved to the backups (`keepReplaced`). Skills the skills CLI manages (`npx skills`, `~/.agents/.skill-lock.json`, or `$XDG_STATE_HOME/skills/.skill-lock.json` when that is set, both read with the XDG one winning) are only grouped: the CLI updates them (`npx skills update`). A linked folder, a skill imported from an agent and a `From`-only skill have no remote to check; one CC Switch installed (`Origin`) can be updated by hand but isn't checked. A skill from another git repository (`kind: git`) keeps the repository's head commit it was fetched at in `Commit`, and `Hash`. A check runs `git ls-remote` for the ref (`gitRemoteHead`): the same head is current; another one is fetched shallowly, once per repository and ref in a check, and the skill's folder hashed, so a commit that left the skill as it was is current and its head is kept as `Commit` (`checkGitSkill`). Its `*EditedError` and the page's Changed here, Update and the question before replacing a change name that repository, not GitHub (`editedError`, `skill-git-source.test.cjs`). New skills in such a repository are found from its fetch (`findNewGit`, above); Group again, icons and the market are GitHub's only. A skill whose source was read whole and no longer has its folder or `SKILL.md` was removed there (`goneFrom`; スライム on Discord): `UpdateSkill` returns `*GoneError`, `UpdateSkills`/`UpdateSomeSkills` list it in `Result.Gone`, not `Unupdated`, and a check gives it status `gone`. Each records `Skill.Gone` (the view's `gone`), cleared when a check or an update finds it there again. A fetch that failed, a skill left out of a fetch as too big (`leftOutAt`) and a folder that can't be read are unknown, never gone. Nothing is taken out by itself: `RemoveGoneSkills` (`POST /api/library/skills/remove-gone`, `magpie library skill rm --gone [--yes]`, the TUI's `d` on the row) takes the ones named, or every one marked, as `RemoveSkills` does, folders to the backups, and keeps one found in its source again. The page tags such a row Removed upstream with no Update, says them apart from failures after Update all, and offers Clean up N in the group's heading (in the bar with one group), which asks first, naming each one and which was changed here (`confirmRemoveGone`, `skill-gone.test.cjs`). | [`skill_changed.go`](../../internal/library/skill_changed.go), [`skillcheck.go`](../../internal/library/skillcheck.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skills.go`](../../internal/library/skills.go) |
| Hooks | A `Hook` (#1790) is a command, an event, an optional matcher, a timeout and the agents ticked for it. Its optional `Description` (#2011) says what it is for in any language, since its name is letters, digits, - and _: one line of at most `maxHookDescription` (200) characters, shown under the name; only library.json keeps it, and no agent is given it. Its event is portable (`HookEvents`: turn-end, after-tool, before-tool, prompt, session-start, each under the agent's own name) or an agent's own (`"codex:PermissionRequest"`), which only that agent is given. A portable tool event can be narrowed to shell or edit tools, each agent's own tool names for them. A session-start hook can be narrowed to some starts (#5604, NEKO-CwC: re-inject a file after compaction alone), one or more of `HookStarts` (startup, resume, clear, compact, fork, Claude Code's words) joined by `|`; `startMatcher` writes each agent's own matcher for them. Claude Code and Codex take the starts as written (Codex reads a `|` list as exact names). Gemini CLI has startup, resume and clear only and compares its matcher whole, so it takes one of them. Grok has `new` (startup and /clear) and `load` (resume), so it takes exactly one of those groups. Cursor's sessionStart takes no matcher. Starts an agent doesn't have are dropped, and one that has all that are left is given the hook whole. An agent that can't run it at exactly the starts picked is refused with why, as for any other per-agent limit: never widened to every start, which would run it at the starts the user narrowed away (a fork per subagent), nor written with a matcher it never matches. The written matcher is in `Applied.Hooks`, so an agent's own edit of the entry is still theirs. `HookAgentView.Starts` lists the matchers each agent takes, and the editor's At which starts app menu greys the chips of those that can't. A bundle carrying a narrowed hook to a magpie before this writes it whole. `syncHooks` writes each into the agent's own file and shape (`hookSpecOf`): Claude Code `<claude dir>/settings.json`, Codex `hooks.json` beside its config.toml, Gemini CLI `~/.gemini/settings.json` (timeout in ms), Cursor `~/.cursor/hooks.json` (flat entries, `version: 1`), and Grok Build `~/.grok/config.toml` and Grok App `agent-home/config.toml` as `[[hooks.<Event>]]` array tables with a `[[hooks.<Event>.hooks]]` child. Grok Build and Grok App run the one CLI, so a `grok:<Event>` own event goes to both (`sameHookFamily`). Every other agent, and an agent in WSL, is refused with why, and the page greys its chip with that reason. The page also says when an agent has every hook turned off (`hooksOff`: Claude Code's `disableAllHooks`, Gemini's `hooksConfig.enabled`, Codex's `[features] hooks`). | [`hooks.go`](../../internal/library/hooks.go) |
| Variables | An `EnvVar` (paopao_baobao on X) is a name, a value and the agents ticked for it (`internal/library/env.go`). Claude Code gets it in `settings.json`'s `env`, Codex in `config.toml`'s `[shell_environment_policy.set]` (`envFile`, `writeEnv`); an agent with no such setting is greyed on the tab, saying why. `syncEnv` records what it wrote in `Applied.Env` and never overrides the user: a name the file already sets to another value is left as it is and reported as a problem on the row (`env:<name>`), and a recorded value the user changed in the file is theirs from then on (the record is dropped, a removal or a turn-off leaves it). Turning an agent off or removing the variable takes out only the recorded, unchanged value. Codex's spelling is respected: a `set` sub-table or an inline `set = {…}` is edited, a dotted spelling is refused with `left as it is`. An unreadable or wrongly typed file is an error, never empty, and nothing is written. Names are `[A-Za-z_][A-Za-z0-9_]*`, at most 128, values at most 8192 bytes. Variables are not carried in backups or a WebDAV bundle (`carry.go` names its fields). Tests: `TestEnvWrittenAndTakenOut`, `TestEnvNeverOverridesTheUsers`, `TestEnvValueChanged`, `TestEnvCodexInlineSet`, `TestEnvUnreadableFileLeftAlone`, `TestEnvChecked`, `library-env.test.cjs`. |
| Variables | An `EnvVar` (paopao_baobao on X) is a name, a value and the agents ticked for it (`internal/library/env.go`). Claude Code gets it in `settings.json`'s `env`, Codex in `config.toml`'s `[shell_environment_policy.set]` (`envFile`, `writeEnv`); an agent with no such setting is greyed on the tab, saying why. `syncEnv` records what it wrote in `Applied.Env` and never overrides the user: a name the file already sets to another value is left as it is and reported as a problem on the row (`env:<name>`), and a recorded value the user changed in the file is theirs from then on (the record is dropped, a removal or a turn-off leaves it). Turning an agent off or removing the variable takes out only the recorded, unchanged value. Codex's spelling is respected: a `set` sub-table or an inline `set = {…}` is edited, a dotted spelling is refused with `left as it is`. An unreadable or wrongly typed file is an error, never empty, and nothing is written. Names are `[A-Za-z_][A-Za-z0-9_]*`, at most 128, values at most 8192 bytes. Variables are carried with the library (see below). Tests: `TestEnvWrittenAndTakenOut`, `TestEnvNeverOverridesTheUsers`, `TestEnvValueChanged`, `TestEnvCodexInlineSet`, `TestEnvUnreadableFileLeftAlone`, `TestEnvChecked`, `library-env.test.cjs`. |
| Subagents | A `Subagent` (#2283) is a name (lowercase letters, digits and -), a one-line description, a prompt, and the library's skills and MCP servers it uses, given to the agents ticked for it. `syncSubagents` writes it as a file of its own in each agent's user-level folder, in that agent's format (`subagentSpecOf`): Markdown with YAML front matter in `~/.claude/agents` (with `skills` and `mcpServers`), `~/.factory/droids` (with `mcpServers`), `~/.config/opencode/agents` (`mode: subagent`), `~/.gemini/agents`, `~/.qwen/agents`, `~/.grok/agents`, `~/.cursor/agents` and `~/.copilot/agents` (`<name>.agent.md`); a TOML role (`name`, `description`, `model` when set, `developer_instructions`) in `$CODEX_HOME/agents`. Skills and servers are named only where the agent's file can name them, and only those the library has. A subagent's optional `Model` (a model or routing group of Codex's list, `subagentModels` in `/api/library`) is written only into Codex's role (luckymanjc on Discord): the role file is a config layer, and Codex lays its `model` over the one its lead names in spawn_agent (`apply_spawn_agent_role` after `apply_requested_spawn_agent_model_overrides` in codex-rs `core/src/agent/child_config.rs`), so the subagent's requests carry it and the gateway routes them as any other. Codex's subagent model on the Agents page (`CodexSubagentModel`), when set, still rewrites every subagent's request, and the editor says so. Without one, a Codex subagent runs on the model its lead names, else the lead's own. The page lists, per agent, whether it binds skills, servers and a model (`SubagentAgentView`), names the agents that run a subagent on their own pick, and greys out an agent that takes none. | [`subagents.go`](../../internal/library/subagents.go) |
| Claude plugins | A `Plugin` (FakeshadowzZ on X) is a Claude Code plugin kept as one item: `.claude-plugin/plugin.json`, `skills/<name>/SKILL.md`, `agents/*.md`, `hooks/hooks.json` and `.mcp.json`, from a folder, a git address or a marketplace.json (`ProbePlugins`, `InstallPlugins`; a marketplace entry with a relative path, or a github/url/git source, is fetched when installed). Its files are copied to `<library>/plugins/<name>`; `${CLAUDE_PLUGIN_ROOT}` is that folder and `${CLAUDE_PLUGIN_DATA}` is `<library>/plugin-data/<name>`, which an update keeps. Its parts are ordinary library skills, MCP servers, hooks and subagents, each tagged `Bundle: <plugin>`, so every agent gets them through the code of its kind and the old tabs go on working; the plugin holds the names, its agents and `Off`. `PluginAgents` sets every part's agents, `PluginOn` clears them (kept in `Agents` for turning it on again) or gives them back, `RemovePlugin` removes the parts, and `UpdatePlugin` reads the source again. A hook whose Claude event and matcher have a portable event becomes it (Stop turn-end, PostToolUse after-tool, PreToolUse before-tool, UserPromptSubmit prompt, SessionStart session-start; Bash is shell, Edit/Write/MultiEdit is edit); any other event is `claude:<Event>`, for Claude Code only. Subagents go to the agents in `SubagentAgents`. A part whose name the library has gets the prefix `<plugin>-`: the user's own item is never written over or removed. Slash commands, LSP servers and hooks that aren't a command are listed in `Left` and shown, not carried. A backup file carries the parts but not the plugin record or its folder, so on another computer they are ordinary items whose `${CLAUDE_PLUGIN_ROOT}` paths don't exist (`TestPluginImportCarryOnOffRemove`, `TestPluginNameClashKeepsTheUsersOwn`, `TestPluginMarketplaceAndUpdate`, `TestPluginRefusesWhatIsNone`, `library-plugins.test.cjs`). | [`plugin.go`](../../internal/library/plugin.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) |
| Backups | Before a change first writes an agent file, `backups` copies it to `BackupDir`, one folder per change. The last `keepBackups` (30) changes are kept. The Backups button at the top of every tab, beside Library folder, opens that folder (`libHead`; Dade on Discord found it at the foot of a long page). | [`backup.go`](../../internal/library/backup.go) |
@@ -99,6 +99,7 @@ Pi's extensions and packages.
- 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) 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 carried library (backup, WebDAV, S3) carries the variables (`Bundle.Env`: name, value, agents ticked; onducoder on X: a skill's key set once, on every computer), never `Applied.Env`. Nil in a bundle from a magpie before they were carried, and `Put` then keeps this computer's. A copy without keys keeps the names and empties every value, whatever the name (`WithoutSecrets`; a variable's name says nothing of its value), and `WithSecrets` fills them from this computer's. `syncEnv` writes nothing for a variable with no value. A backup with keys is sealed under its passphrase, as the servers' tokens are. `TestEnvIsCarried`.
- 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.
+58
View File
@@ -37,6 +37,10 @@ type Bundle struct {
// 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"`
// Env is nil in a bundle from a magpie before variables were carried:
// Put keeps this computer's. Applied.Env stays out. A backup made
// without keys carries the names with empty values (WithoutSecrets).
Env *[]*EnvVar `json:"env,omitempty"`
}
// CarriedSkill is a skill with its folder's files.
@@ -130,6 +134,13 @@ func Collect() (*Bundle, error) {
hooks = append(hooks, &c)
}
b.Hooks = &hooks
envs := []*EnvVar{}
for _, e := range sorted(l.Env, func(e *EnvVar) string { return e.Name }) {
c := *e
c.Agents = orNone(slices.Sorted(slices.Values(e.Agents)))
envs = append(envs, &c)
}
b.Env = &envs
return b, nil
}
@@ -280,6 +291,21 @@ func (b *Bundle) check() error {
seen[s.Name] = true
}
}
if b.Env != nil {
seen := map[string]bool{}
for _, e := range *b.Env {
if e == nil {
return fmt.Errorf("an empty variable")
}
if err := e.check(); err != nil {
return err
}
if seen[e.Name] {
return fmt.Errorf("the variable %s twice", e.Name)
}
seen[e.Name] = true
}
}
if b.Hooks != nil {
seen := map[string]bool{}
for _, h := range *b.Hooks {
@@ -314,6 +340,17 @@ func localFile(rel string) bool {
// WithoutSecrets empties the values of the servers' environment variables
// and headers that secret says hold one; their names stay, to be filled in.
func (b *Bundle) WithoutSecrets(secret func(string) bool) {
// a variable's name says nothing of what its value is: every value
// goes, the names stay
if b.Env != nil {
envs := []*EnvVar{}
for _, e := range *b.Env {
c := *e
c.Value = ""
envs = append(envs, &c)
}
b.Env = &envs
}
for i, s := range b.MCP {
c := *s
c.Env, c.Headers = blank(s.Env, secret), blank(s.Headers, secret)
@@ -355,6 +392,17 @@ func (b *Bundle) WithSecrets(have *Bundle, secret func(string) bool) *Bundle {
}
out := *b
out.MCP = nil
if b.Env != nil && have.Env != nil {
envs := []*EnvVar{}
for _, e := range *b.Env {
c := *e
if i := slices.IndexFunc(*have.Env, func(h *EnvVar) bool { return h.Name == e.Name }); i >= 0 && c.Value == "" {
c.Value = (*have.Env)[i].Value
}
envs = append(envs, &c)
}
out.Env = &envs
}
for _, s := range b.MCP {
c := *s
i := slices.IndexFunc(have.MCP, func(h *Server) bool { return h.Name == s.Name })
@@ -561,6 +609,16 @@ func Put(b *Bundle) (*Result, error) {
}
l.Hooks = hooks
}
// variables the same way: Applied.Env decides what is taken out
if b.Env != nil {
envs := []*EnvVar{}
for _, e := range *b.Env {
c := *e
c.Agents = slices.Clone(orNone(e.Agents))
envs = append(envs, &c)
}
l.Env = envs
}
return nil
})
}
+2 -1
View File
@@ -252,7 +252,8 @@ func (l *Library) syncEnv(t *Target, b *backups, res *Result) {
a := l.applied(id)
want := map[string]string{}
for _, e := range l.Env {
if slices.Contains(e.Agents, id) {
// no value is a variable carried without its key: nothing to give
if slices.Contains(e.Agents, id) && e.Value != "" {
want[e.Name] = e.Value
}
}
+49
View File
@@ -1,6 +1,7 @@
package library
import (
"os"
"path/filepath"
"strings"
"testing"
@@ -198,3 +199,51 @@ func TestEnvChecked(t *testing.T) {
}
}
}
// A variable is carried with the library (anysearch's key, onducoder on
// X). A copy without keys carries its name and no value, and putting it
// neither blanks the key kept here nor writes an empty value into an agent.
func TestEnvIsCarried(t *testing.T) {
h := sandbox(t)
settings := filepath.Join(h, ".claude/settings.json")
ok(t)(SaveEnv("", EnvVar{Name: "ANYSEARCH_API_KEY", Value: "sk-secret", Agents: []string{"claude"}}))
keyed, err := Collect()
if err != nil || keyed.Env == nil || len(*keyed.Env) != 1 || (*keyed.Env)[0].Value != "sk-secret" {
t.Fatalf("carried: %+v %v", keyed.Env, err)
}
bare, _ := Collect()
bare.WithoutSecrets(func(string) bool { return false }) // whatever the name
if v := (*bare.Env)[0]; v.Name != "ANYSEARCH_API_KEY" || v.Value != "" {
t.Fatalf("the key went with a copy without keys: %+v", v)
}
if strings.Contains(mustJSON(t, bare), "sk-secret") {
t.Fatal("the key is in a bundle without keys")
}
// this computer's key survives a copy without keys
ok(t)(Put(bare.WithSecrets(keyed, func(string) bool { return false })))
if got := claudeEnv(t, settings); got["ANYSEARCH_API_KEY"] != "sk-secret" {
t.Fatalf("the key here was blanked: %v", got)
}
// a computer with none gets the name, and nothing is written for it
h2 := sandbox(t)
ok(t)(Put(bare))
l, _ := Collect()
if len(*l.Env) != 1 || (*l.Env)[0].Value != "" {
t.Fatalf("name not carried: %+v", l.Env)
}
if _, err := os.Stat(filepath.Join(h2, ".claude/settings.json")); err == nil && strings.Contains(read(t, filepath.Join(h2, ".claude/settings.json")), "ANYSEARCH") {
t.Fatal("an empty value was written into the agent")
}
// a copy with keys brings the key
ok(t)(Put(keyed))
if got := claudeEnv(t, filepath.Join(h2, ".claude/settings.json")); got["ANYSEARCH_API_KEY"] != "sk-secret" {
t.Fatalf("the key didn't arrive: %v", got)
}
// one from a magpie that didn't carry them leaves this computer's alone
old := *keyed
old.Env = nil
ok(t)(Put(&old))
if l, _ := Collect(); len(*l.Env) != 1 {
t.Fatal("variables lost to an old bundle")
}
}