From 4ff57b8cbf78a57f1d064e03b28eec9d722cf7dc Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 20 Nov 2026 05:05:17 +0800 Subject: [PATCH] library: a project's own resources are listed apart from what magpie placed, with a source in the CLI's --json (#7245, #7247) ProjectView.Own reads, per kind, what the folder's own files already give agents and magpie didn't write: skills in the skills folders, servers in each agent's project MCP file (name and transport only, never URL, args or env), hooks in .claude/settings.json, settings.local.json and .codex/hooks.json (an entry is magpie's when it equals a HookRecs entry), and subagent files whose hash isn't in AgentFiles. Read-only: a link out of the folder or a file that can't be read is left out. The cards show them under "Project's own", no chips. `magpie library project server|hook|subagent --json` gains `items`, each with source "magpie" or "project"; the old maps stay as they were. Not done: Claude plugins, Pi packages and instructions are not read as the project's own yet; the cards have no "Assigned by MagPie" heading, the chips already say it. Run on mote: gofmt, go vet library, cli, gui; go test ./internal/library and ./internal/cli (whole packages, ok); new TestProjectOwnResources and the CLI source check; GUI project-own (new), project-hooks, project-servers, project-skills-*, project-plugins, i18n-keys in both engines, then every library-* and project-* file once: library-bar-more went red in that run and green alone (load, not filed: it did not touch this change). Not tried: a real project with hundreds of skills (the read is on every state poll of a project folder). --- docs/subsystems/library.md | 2 +- internal/cli/library_project_kind_cli.go | 39 ++- internal/cli/library_project_test.go | 14 ++ internal/gui/assets/plugins/library/client.js | 29 ++- internal/gui/assets/plugins/library/i18n.js | 4 + .../gui/assets/plugins/library/library.css | 3 + internal/gui/tests/project-hooks.test.cjs | 2 +- internal/gui/tests/project-own.test.cjs | 123 ++++++++++ internal/library/project_own.go | 230 ++++++++++++++++++ internal/library/project_plugins_test.go | 36 +++ internal/library/projects.go | 10 +- 11 files changed, 484 insertions(+), 8 deletions(-) create mode 100644 internal/gui/tests/project-own.test.cjs create mode 100644 internal/library/project_own.go diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 6ce647dc4..ec24ea347 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -23,7 +23,7 @@ Pi's extensions and packages. | 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) | | Stopped WSL distro | A stopped distro's agents are no targets: opening their files would start the distro, or the read fails (#3896). While a distro runs, `keepShape` keeps each agent's places and what its MCP file takes in `wsl.json` (`agent.WSLKeep`, key `library:`). While it is stopped, `Read` lists its agents from that (`asleepView`, `asleep: `), ticks as library.json has them; one magpie never saw there is listed only on the rows that name it, as `unseen`, its ticks not shown (cybercaius on Discord: the MCP page knew a distro's agents only once WSL had started). A tick on a stopped agent is kept in library.json as any is (`Takes` accepts one with a known shape; `serversAgents` judges it by `shape.reaches`), nothing is written and nothing in the distro runs; `Woken`, from `KeepLinked`'s loop (and the app's start-up sync), syncs when a distro the library names is seen go from stopped to running (`wsl.exe -l --running`, which starts nothing). The page greys a stopped agent's chip, says so in its tooltip and in one line per distro (`.lib-asleep`); an unseen chip is `aria-disabled` and kept by every click on its row (`keptOf`). The CLI says the same on stderr (`AsleepIn`). Queued, not a start button: a start costs the memory #3896 is about, and All or a bulk tick would start every distro. The Instructions page lists them too (`asleepInstructions`, #4182), at the instructions file the shape keeps, switched on as library.json has them, with what each gets besides (magpie's own folder) and nothing read from the file: its own lines and edits aren't counted then, and its path is plain text, not a reveal, which would open the distro. One switched on whose file magpie never saw is listed as `unseen`, its switch greyed out and kept by every other switch; before, a switch on the page sent the agents without the stopped distro's and took them off. A switch on one is written by `Woken`, which watches a distro named in `Instructions.Agents`, or whose agent still has magpie's part (`Applied.Instructions`), so one switched off has it taken out. The Hooks page lists the stopped agents with a shape as it does while the distro runs (`hooksView`, #4237): greyed, since magpie gives no agent in WSL hooks yet (`wslNoHooks`), and a hook given one says so; there is nothing for `Woken` to write. So does the Subagents page for the kinds it lists (`subagentsView`, `wslNoSubagents`, #4238). | [`wsl_asleep.go`](../../internal/library/wsl_asleep.go), [`targets.go`](../../internal/library/targets.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) | | Sync | `sync` writes each target's instructions and MCP servers. It then takes edits made in agents' skill copies into the library (`takeEdits`) and links or copies the skills. `~/.agents/skills` goes first (`sweepShared`, then `syncShared` for the Put skills in setting), so an agent that reads it gets no second link. Then it syncs projects' skills. | [`sync.go`](../../internal/library/sync.go) | -| Projects | A project (`Project`) is a folder given some of the library's skills and MCP servers, each for some agents. A skill is linked (or copied) into the folder the agent reads a project's skills from (`projectSkillsDirs`): `.claude/skills` for Claude Code, `.qoder/skills` for Qoder and Qoder CN, `.codebuddy/skills` for CodeBuddy Code, `.commandcode/skills` for Command Code, and `.agents/skills` for Codex, Gemini CLI, OpenCode, Pi, Cursor, Copilot CLI, Antigravity, Kimi, Goose, Grok, Droid, Cline and DeepSeek Harness (which reads it, and `.dsh/skills`, at the nearest folder up with a `.git`, else where it runs: a project folder inside a repository but not at its root doesn't reach it, #5172). A server is written into the file the agent reads a project's servers from (`projectMCPFiles`), in the shape its user-wide file has: `.mcp.json` for Claude Code and CodeBuddy Code (CodeBuddy's `mcp.json` when the project has that and no `.mcp.json`, since it reads only the first of the two), `.codex/config.toml`, `.gemini/settings.json`, `.cursor/mcp.json`, `opencode.json`, `.zcode/config.json`, `.pi/mcp.json`, `.qoder/settings.json`'s `mcpServers` for Qoder and Qoder CN, and `.factory/mcp.json` for Droid. Claude Code, Qoder and CodeBuddy ask the user to approve a project's server before using it. Only targets whose vendor source or docs name them are listed (each map's comment cites them); an agent with none (Copilot CLI's MCP, Zed, WorkBuddy, Command Code's MCP, whose `.mcp.json` has its own `transport` shape, DeepSeek Harness's MCP, whose servers are rows in its profiles' patch layers with no project layer) can't be picked for a project (eirc on Discord). `Placed`, `Wrote`, `Made` and `MadeFiles` record what magpie put there, the only things it takes away. Nothing of magpie's goes into the project's git: what it placed is listed in the repository's own `info/exclude` (`writeExclude`, one block per project between `excludeBegin(dir)` and `ignoreEnd`, read by every worktree, never committed), and the project's `.gitignore` is left as it is (a block an older magpie wrote there is taken out, `TestProjectKeptOutOfGitByExclude`). A folder outside git gets no ignore file; once it is `git init`ed, `treesChanged` sees no block and the next `KeepLinked` writes it (`TestProjectOutsideGit`). A project is the global set ± its own (WhyULose0 on X): `ServersOff` and `SkillsOff` turn a global server or skill off in the project for some agents (`ProjectServerOff`, `ProjectSkillsOff`; `POST /api/library/projects/server-off` and `skill-off` with `dir`, `name`/`names`, `agents`; none gives it back). Each is done the way the agent reads it for a folder (`project_scope.go`): Claude Code's record of the project in `~/.claude.json` (`projects[
]`, `claudeRoot`) gets the name in `disabledMcpServers`, where magpie takes out only names it added (`Claude.Off`); Codex gets `[mcp_servers.] enabled = false` in the project's `.codex/config.toml`, only for a server in its own config (`CodexOff`); a skill is `skillOverrides. = "off"` in the project's `.claude/settings.local.json` (`Overrides`), a value the user set there is theirs (`TestProjectServerOff`, `TestProjectSkillOff`). Only those (`ProjectOffAgents`, `ProjectSkillOffAgents`) can take an off, and a skill an agent reaches through the [skill router](skill-router.md) can't; the card shows a global agent that can't as always on, with why. With the [MCP router](mcp-router.md) on, a project that adds or turns off a server the router serves gives Claude Code and Codex their own hub entry, `~` (`projectHubs`): Claude Code's in its record's `mcpServers` (local scope), Codex's in the project's `.codex/config.toml`; the server added isn't written into `.mcp.json` then (`TestProjectSetThroughRouter`). Claude Code keys its record by the repository's main top folder, so a project in a subfolder turns its offs on for the whole repository. A git worktree of the project's repository follows the project (`treeDirs`, `Trees`): the project's folder in each worktree gets the same skills, servers and offs, and is let go when the worktree is removed; `KeepLinked` checks for new ones (`keepProjectTrees`, `TestProjectWorktreeFollows`). A project also takes the library's subagents (jinpwng on X; `Subagents`, `AgentFiles`, [`project_subagents.go`](../../internal/library/project_subagents.go)): one file per subagent in the folder the agent reads a project's subagents from (`projectSubagentDirs`, cited per agent in its comment): `.claude/agents` for Claude Code, `.codex/agents`, `.opencode/agents`, `.gemini/agents`, `.qwen/agents`, `.factory/droids` for Droid, `.cursor/agents` and `.github/agents` for Copilot, in that agent's own format. A file is recorded with its hash (`SubagentFile`) and rewritten or removed only while it is exactly as magpie wrote it, so a same-name file of the user's is never touched (`TestProjectSubagentsLeaveTheUsersFiles`); a subagent renamed in the library is renamed in each project (`TestProjectSubagentsFollowTheLibrary`); the files are kept out of git by the same `info/exclude` block and follow the project's worktrees. `POST /api/library/projects/subagents` with `dir`, `name`/`names`, `agents`; the Subagents tab lists the projects as Skills and MCP do (`project-subagents.test.cjs`). `magpie library project subagent add|rm|agents …` is its CLI (#7248, [`library_project_kind_cli.go`](../../internal/cli/library_project_kind_cli.go), `TestLibraryProjectServerAndSubagentCmd`), and `magpie library project server add|rm|agents …` does the same for a project's servers (`ProjectServer`); an add with no `agents=` is for the agents the project's ones are for already, else every agent here that reads a project's MCP file or subagents folder, and one the project doesn't have is refused. A project also has instructions of its own (VictorHong1022 on X; `Instr`, `InstrAgents`, `InstrFiles`, [`project_instructions.go`](../../internal/library/project_instructions.go)), so the user-wide ones keep only what holds everywhere: one text, written into the file each picked agent reads in the project (`projectInstrNames`, cited per agent in its comment): `CLAUDE.md` (or `.claude/CLAUDE.md` when only that is there) for Claude Code, `AGENTS.override.md` over `AGENTS.md` for Codex and Pi, `GEMINI.md`/`QWEN.md` or the name their settings' `context.fileName` gives, `CODEBUDDY.md`, and `AGENTS.md` for the rest; a file several agents read is written once. Only the part between the user-wide part's two marker lines (`blockBegin`, `blockEnd`) is magpie's, the rest of the file is the user's and keeps its CRLF (`TestProjectInstructionsEachAgentsFile`, `KeepCRLF`); a part edited in the file stays until the project's text changes, and one taken out is written again (`TestProjectInstructionsLeaveTheUsersEdits`). Turned off, the part comes out and a file magpie made goes once nothing else is in it; a made file is kept out of git by the `info/exclude` block; a project file that is an agent's user-wide instructions file (a link, or a project at the home folder) is left alone with a problem (`TestProjectInstructionsNeverAnAgentsOwnFile`); worktrees follow (`TestProjectInstructionsFollowWorktrees`). `POST /api/library/projects/instructions` with `dir` and `instr` and/or `agents`; the Instructions tab lists the projects under the shared set, the page's Save saving a project's text too, first to the agents the shared set is on for (`project-instructions.test.cjs`); `magpie library project instructions [text …|--file f|-|agents a,b|none]` is its CLI. Cursor and Copilot read `CLAUDE.md` as well as `AGENTS.md`, so with Claude Code picked too they may read the text twice. A project also takes whole Claude plugins (jinpwng on X; `Plugins`, `HookRecs`, [`project_plugins.go`](../../internal/library/project_plugins.go)): `ProjectPlugin` sets which agents get a library plugin in the project, and for a sync `syncProject` adds the plugin's skills, servers and subagents to the project's own sets (`withPlugins`, put back as they were after), so each part goes where the project's own do, for the picked agents that take it there, and a part the project also has of its own stays when the plugin goes. Its hooks are written entry by entry into the project's hooks file (`projectHookFiles`): `.claude/settings.local.json` for Claude Code and `.codex/hooks.json` for Codex, through the same `hookWrite` as the user-wide ones, so an entry the user changed is theirs and stays, and taking out one of the plugin's before one of the user's moves the user's Codex trust (`[hooks.state]` in the user-wide config) with it. Codex runs a project's hooks only in a project the user trusts, once reviewed in `/hooks`; the card says so. Pi gets skills and servers; no other agent has a project hooks file magpie knows. A plugin turned off gives the project nothing while off; removing it from the library takes it out of every project (`dropProjectPlugin`). Taking it out is only deleting its `Plugins` entry: what magpie placed or wrote for it comes out by the records each part keeps, and a file magpie made goes once empty (`TestProjectPluginEachPartInTheProject`, `TestProjectPluginWithdrawLeavesTheUsers`, `TestProjectPluginFollowsTheLibrary`, `TestProjectPluginCodexTrustFollows`). `POST /api/library/projects/plugin` with `dir`, `name`, `agents` (none takes it out); the Claude plugins tab lists the projects as the other tabs do (`project-plugins.test.cjs`). A single hook can be given to a project on its own (#7253, `Project.Hooks`, `ProjectHooks`, `magpie library project hook add|rm|agents`, the Hooks tab's project cards, `project-hooks.test.cjs`): `projectHooks` merges it with the plugins' hooks into the same `HookRecs` write, so withdrawing removes only the entries magpie wrote. Plugins Claude Code has installed itself (`~/.claude/plugins/installed_plugins.json`, `View.ClaudeInstalled`) can be turned on for one project too (#7254, [`project_claude_plugins.go`](../../internal/library/project_claude_plugins.go), `project-claude-plugins.test.cjs`): `ProjectClaudePlugin` sets `Project.ClaudePlugins`, and a sync writes `enabledPlugins. = true` into `.claude/settings.local.json`, the file the skill offs and hooks share, so none of the three drops it while another still has a record there. `ClaudeWrote` is the keys magpie wrote; only one still `true` is taken out, and a key the user already had is neither written nor taken out. Only Claude reads it, so the route takes the Claude chip or none. It has no CLI yet. Pi packages and Codex's `.codex-plugin` folders aren't read as plugins. `magpie library project …` (#5193, [`library_project_cli.go`](../../internal/cli/library_project_cli.go)) adds and removes a project and its skills through the same calls as the page (`AddProject`, `RemoveProject`, `ProjectSkills`, `ProjectSkill`, `ProjectCopy`); a skill added with no `agents=` goes to the agents the page's Skills menu picks (those the project's skills are for already, else every agent here with a project skills folder), and one not placed exits 1 with why (`TestLibraryProjectCmd`). A project card's Skills menu lists the skills by source as the Library does (`skillGroups(true)`, whatever sort the list has; one group is the flat list), a heading over each that ticks or unticks the whole group (`group` in `openProtoMenu`, half-ticked while some are in; Elorynth on X, `project-skills-groups.test.cjs`). | [`projects.go`](../../internal/library/projects.go), [`project_mcp.go`](../../internal/library/project_mcp.go), [`project_scope.go`](../../internal/library/project_scope.go), [`project_git.go`](../../internal/library/project_git.go), [`project_instructions.go`](../../internal/library/project_instructions.go), [`project_plugins.go`](../../internal/library/project_plugins.go) | +| Projects | A project (`Project`) is a folder given some of the library's skills and MCP servers, each for some agents. A skill is linked (or copied) into the folder the agent reads a project's skills from (`projectSkillsDirs`): `.claude/skills` for Claude Code, `.qoder/skills` for Qoder and Qoder CN, `.codebuddy/skills` for CodeBuddy Code, `.commandcode/skills` for Command Code, and `.agents/skills` for Codex, Gemini CLI, OpenCode, Pi, Cursor, Copilot CLI, Antigravity, Kimi, Goose, Grok, Droid, Cline and DeepSeek Harness (which reads it, and `.dsh/skills`, at the nearest folder up with a `.git`, else where it runs: a project folder inside a repository but not at its root doesn't reach it, #5172). A server is written into the file the agent reads a project's servers from (`projectMCPFiles`), in the shape its user-wide file has: `.mcp.json` for Claude Code and CodeBuddy Code (CodeBuddy's `mcp.json` when the project has that and no `.mcp.json`, since it reads only the first of the two), `.codex/config.toml`, `.gemini/settings.json`, `.cursor/mcp.json`, `opencode.json`, `.zcode/config.json`, `.pi/mcp.json`, `.qoder/settings.json`'s `mcpServers` for Qoder and Qoder CN, and `.factory/mcp.json` for Droid. Claude Code, Qoder and CodeBuddy ask the user to approve a project's server before using it. Only targets whose vendor source or docs name them are listed (each map's comment cites them); an agent with none (Copilot CLI's MCP, Zed, WorkBuddy, Command Code's MCP, whose `.mcp.json` has its own `transport` shape, DeepSeek Harness's MCP, whose servers are rows in its profiles' patch layers with no project layer) can't be picked for a project (eirc on Discord). `Placed`, `Wrote`, `Made` and `MadeFiles` record what magpie put there, the only things it takes away. Nothing of magpie's goes into the project's git: what it placed is listed in the repository's own `info/exclude` (`writeExclude`, one block per project between `excludeBegin(dir)` and `ignoreEnd`, read by every worktree, never committed), and the project's `.gitignore` is left as it is (a block an older magpie wrote there is taken out, `TestProjectKeptOutOfGitByExclude`). A folder outside git gets no ignore file; once it is `git init`ed, `treesChanged` sees no block and the next `KeepLinked` writes it (`TestProjectOutsideGit`). A project is the global set ± its own (WhyULose0 on X): `ServersOff` and `SkillsOff` turn a global server or skill off in the project for some agents (`ProjectServerOff`, `ProjectSkillsOff`; `POST /api/library/projects/server-off` and `skill-off` with `dir`, `name`/`names`, `agents`; none gives it back). Each is done the way the agent reads it for a folder (`project_scope.go`): Claude Code's record of the project in `~/.claude.json` (`projects[
]`, `claudeRoot`) gets the name in `disabledMcpServers`, where magpie takes out only names it added (`Claude.Off`); Codex gets `[mcp_servers.] enabled = false` in the project's `.codex/config.toml`, only for a server in its own config (`CodexOff`); a skill is `skillOverrides. = "off"` in the project's `.claude/settings.local.json` (`Overrides`), a value the user set there is theirs (`TestProjectServerOff`, `TestProjectSkillOff`). Only those (`ProjectOffAgents`, `ProjectSkillOffAgents`) can take an off, and a skill an agent reaches through the [skill router](skill-router.md) can't; the card shows a global agent that can't as always on, with why. With the [MCP router](mcp-router.md) on, a project that adds or turns off a server the router serves gives Claude Code and Codex their own hub entry, `~` (`projectHubs`): Claude Code's in its record's `mcpServers` (local scope), Codex's in the project's `.codex/config.toml`; the server added isn't written into `.mcp.json` then (`TestProjectSetThroughRouter`). Claude Code keys its record by the repository's main top folder, so a project in a subfolder turns its offs on for the whole repository. A git worktree of the project's repository follows the project (`treeDirs`, `Trees`): the project's folder in each worktree gets the same skills, servers and offs, and is let go when the worktree is removed; `KeepLinked` checks for new ones (`keepProjectTrees`, `TestProjectWorktreeFollows`). A project also takes the library's subagents (jinpwng on X; `Subagents`, `AgentFiles`, [`project_subagents.go`](../../internal/library/project_subagents.go)): one file per subagent in the folder the agent reads a project's subagents from (`projectSubagentDirs`, cited per agent in its comment): `.claude/agents` for Claude Code, `.codex/agents`, `.opencode/agents`, `.gemini/agents`, `.qwen/agents`, `.factory/droids` for Droid, `.cursor/agents` and `.github/agents` for Copilot, in that agent's own format. A file is recorded with its hash (`SubagentFile`) and rewritten or removed only while it is exactly as magpie wrote it, so a same-name file of the user's is never touched (`TestProjectSubagentsLeaveTheUsersFiles`); a subagent renamed in the library is renamed in each project (`TestProjectSubagentsFollowTheLibrary`); the files are kept out of git by the same `info/exclude` block and follow the project's worktrees. `POST /api/library/projects/subagents` with `dir`, `name`/`names`, `agents`; the Subagents tab lists the projects as Skills and MCP do (`project-subagents.test.cjs`). `magpie library project subagent add|rm|agents …` is its CLI (#7248, [`library_project_kind_cli.go`](../../internal/cli/library_project_kind_cli.go), `TestLibraryProjectServerAndSubagentCmd`), and `magpie library project server add|rm|agents …` does the same for a project's servers (`ProjectServer`); an add with no `agents=` is for the agents the project's ones are for already, else every agent here that reads a project's MCP file or subagents folder, and one the project doesn't have is refused. A project also has instructions of its own (VictorHong1022 on X; `Instr`, `InstrAgents`, `InstrFiles`, [`project_instructions.go`](../../internal/library/project_instructions.go)), so the user-wide ones keep only what holds everywhere: one text, written into the file each picked agent reads in the project (`projectInstrNames`, cited per agent in its comment): `CLAUDE.md` (or `.claude/CLAUDE.md` when only that is there) for Claude Code, `AGENTS.override.md` over `AGENTS.md` for Codex and Pi, `GEMINI.md`/`QWEN.md` or the name their settings' `context.fileName` gives, `CODEBUDDY.md`, and `AGENTS.md` for the rest; a file several agents read is written once. Only the part between the user-wide part's two marker lines (`blockBegin`, `blockEnd`) is magpie's, the rest of the file is the user's and keeps its CRLF (`TestProjectInstructionsEachAgentsFile`, `KeepCRLF`); a part edited in the file stays until the project's text changes, and one taken out is written again (`TestProjectInstructionsLeaveTheUsersEdits`). Turned off, the part comes out and a file magpie made goes once nothing else is in it; a made file is kept out of git by the `info/exclude` block; a project file that is an agent's user-wide instructions file (a link, or a project at the home folder) is left alone with a problem (`TestProjectInstructionsNeverAnAgentsOwnFile`); worktrees follow (`TestProjectInstructionsFollowWorktrees`). `POST /api/library/projects/instructions` with `dir` and `instr` and/or `agents`; the Instructions tab lists the projects under the shared set, the page's Save saving a project's text too, first to the agents the shared set is on for (`project-instructions.test.cjs`); `magpie library project instructions [text …|--file f|-|agents a,b|none]` is its CLI. Cursor and Copilot read `CLAUDE.md` as well as `AGENTS.md`, so with Claude Code picked too they may read the text twice. A project also takes whole Claude plugins (jinpwng on X; `Plugins`, `HookRecs`, [`project_plugins.go`](../../internal/library/project_plugins.go)): `ProjectPlugin` sets which agents get a library plugin in the project, and for a sync `syncProject` adds the plugin's skills, servers and subagents to the project's own sets (`withPlugins`, put back as they were after), so each part goes where the project's own do, for the picked agents that take it there, and a part the project also has of its own stays when the plugin goes. Its hooks are written entry by entry into the project's hooks file (`projectHookFiles`): `.claude/settings.local.json` for Claude Code and `.codex/hooks.json` for Codex, through the same `hookWrite` as the user-wide ones, so an entry the user changed is theirs and stays, and taking out one of the plugin's before one of the user's moves the user's Codex trust (`[hooks.state]` in the user-wide config) with it. Codex runs a project's hooks only in a project the user trusts, once reviewed in `/hooks`; the card says so. Pi gets skills and servers; no other agent has a project hooks file magpie knows. A plugin turned off gives the project nothing while off; removing it from the library takes it out of every project (`dropProjectPlugin`). Taking it out is only deleting its `Plugins` entry: what magpie placed or wrote for it comes out by the records each part keeps, and a file magpie made goes once empty (`TestProjectPluginEachPartInTheProject`, `TestProjectPluginWithdrawLeavesTheUsers`, `TestProjectPluginFollowsTheLibrary`, `TestProjectPluginCodexTrustFollows`). `POST /api/library/projects/plugin` with `dir`, `name`, `agents` (none takes it out); the Claude plugins tab lists the projects as the other tabs do (`project-plugins.test.cjs`). What the project's own files already give agents (skills in the skills folders, servers in the agents' project MCP files, hooks in the hooks files, subagent files) that magpie didn't place is read by `ownResources` (`project_own.go`, #7245, #7247) into `ProjectView.Own`: read-only, a server's transport only, never its URL or env; the cards list it under "Project's own" (`project-own.test.cjs`) and `magpie library project server|hook|subagent --json` has `items` with a `source` of `magpie` or `project`. A single hook can be given to a project on its own (#7253, `Project.Hooks`, `ProjectHooks`, `magpie library project hook add|rm|agents`, the Hooks tab's project cards, `project-hooks.test.cjs`): `projectHooks` merges it with the plugins' hooks into the same `HookRecs` write, so withdrawing removes only the entries magpie wrote. Plugins Claude Code has installed itself (`~/.claude/plugins/installed_plugins.json`, `View.ClaudeInstalled`) can be turned on for one project too (#7254, [`project_claude_plugins.go`](../../internal/library/project_claude_plugins.go), `project-claude-plugins.test.cjs`): `ProjectClaudePlugin` sets `Project.ClaudePlugins`, and a sync writes `enabledPlugins. = true` into `.claude/settings.local.json`, the file the skill offs and hooks share, so none of the three drops it while another still has a record there. `ClaudeWrote` is the keys magpie wrote; only one still `true` is taken out, and a key the user already had is neither written nor taken out. Only Claude reads it, so the route takes the Claude chip or none. It has no CLI yet. Pi packages and Codex's `.codex-plugin` folders aren't read as plugins. `magpie library project …` (#5193, [`library_project_cli.go`](../../internal/cli/library_project_cli.go)) adds and removes a project and its skills through the same calls as the page (`AddProject`, `RemoveProject`, `ProjectSkills`, `ProjectSkill`, `ProjectCopy`); a skill added with no `agents=` goes to the agents the page's Skills menu picks (those the project's skills are for already, else every agent here with a project skills folder), and one not placed exits 1 with why (`TestLibraryProjectCmd`). A project card's Skills menu lists the skills by source as the Library does (`skillGroups(true)`, whatever sort the list has; one group is the flat list), a heading over each that ticks or unticks the whole group (`group` in `openProtoMenu`, half-ticked while some are in; Elorynth on X, `project-skills-groups.test.cjs`). | [`projects.go`](../../internal/library/projects.go), [`project_mcp.go`](../../internal/library/project_mcp.go), [`project_scope.go`](../../internal/library/project_scope.go), [`project_git.go`](../../internal/library/project_git.go), [`project_instructions.go`](../../internal/library/project_instructions.go), [`project_plugins.go`](../../internal/library/project_plugins.go) | | Instructions | magpie's part of an agent's instructions file sits between two marker lines. The rest of the file is the user's. Several named sets can be switched between (#106). A set can be kept in a file of the user's own instead of `instruction-sets/` (`InstrSet.File`, 新v学员 on Discord): `~/.agents/AGENTS.md`, which Droid and omp read too. `textPath` reads it, `putText` keeps it aside and writes it but never removes it, removing the set lets go of it, and `linkable` refuses a file magpie writes into (an agent's own instructions, a file with the marker line), the library's own and another set's. The app's `KeepLinked` looks at the file every 30 s and writes a change into the agents (`SyncLinked`). A set's text is read without magpie's part (`setText`), and an agent whose instructions file is, links followed, the file the set on is kept in (`isSetFile`: `instructions.md` linked to `~/.claude/CLAUDE.md`, or both linked to one dotfile) gets no part written into it, and one written before is taken out with every part nested in it: read with its part, each sync wrote the whole file into that part again and it doubled, to gigabytes (#2349, `TestInstructionsSetLinkedToAgentsFile`). `Collect` carries the set's text, not where its file is; `Put` keeps this computer's file for the set and never empties it for a text not carried. Alma's file is `~/.config/alma/USER.md`, which its main chat reads into its system prompt as its owner's profile (0.4.164's `out/main/index.js`; a workspace's `USER.md` is read instead), and whose leading front matter (`name`, `telegram_id`, `discord_id`) is who its bots answer to (#2315, Jie211). The target is a `Profile`: magpie's part goes after the user's, so the front matter stays first, and `ImportInstructions` refuses it, as moving it out would take that front matter out of the file and into every agent's (`TestAlmaInstructionsKeepTheProfile`, `TestAlmaProfileIsNotImported`, `library-alma-profile.test.cjs`). MiniMax Code reads `AGENTS.md` in its data folder (`$MINIMAX_DATA_DIR`, else `~/.minimax`) before every conversation, so its target is that file (`TestMiniMaxCodeInstructions`). WorkBuddy and WorkBuddy AI keep theirs as a string in a JSON file: `personalization.customPrompt` in `app/app-config.json` of their folder, the Custom Instructions of the app's Personalization settings (`Target.Field`, `instr_field.go`). magpie's part goes into that string between the same marker lines, after the user's own prompt, and a `Field` write goes through `edit.SetJSON`, so every other key, its order and its indentation stay as the app wrote them; taking the part back leaves the file as it was, the field (and a `personalization` object nothing else is in) going out when it holds nothing. A file that is not JSON, or a field that holds something other than text, is unknown: it is reported and written over by nothing (`TestWorkBuddyInstructionsAreAJSONField`, `TestWorkBuddyInstructionsFromNothing`, `TestWorkBuddyInstructionsUnreadFileIsLeftAlone`, `TestWorkBuddyInstructionsImport`). The app's config service loads the file as it starts and writes it whole on a save (`AppConfigService`, 5.5.6's app.asar), so a change made while it runs may need a restart of the app, and may be lost to its next save of any setting; this has not been tried against a running app. A file several agents read (agy and Antigravity's app both read `~/.gemini/config/GEMINI.md`) is written for the one of them switched on (`instrOwner`): the one switched off neither empties it nor shows it as edited (vizmoe42 on X, `TestAntigravitySharedInstructionsFile`). | [`instructions.go`](../../internal/library/instructions.go) | | MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. A server's `StartupTimeout` (#3168) goes to Codex alone, as `startup_timeout_sec` in seconds (`RawMcpServerConfig` in codex-rs/config's mcp_types.rs; 0 leaves Codex's own 30s), in the user-wide config.toml and a project's alike. magpie keeps the value it wrote (`Applied.Startup`, `Project.Startup`): one in the entry other than that, or a `startup_timeout_ms`, is the user's and stays as it is (`startupTheirs`), and once it is taken out magpie's goes in again. The editor shows the field only when an agent that takes it is here (`AgentView.Startup`, `mcp_startup_test.go`, `mcp-startup-timeout.test.cjs`). `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only: with each tool's name and the first paragraph of its description (`ToolList`, at most `maxToolList`, a description cut at `maxToolDesc` runes), which the page lists when the server's "N tools" is clicked, following tools/list's `nextCursor` up to `maxToolPages` pages (`listTools`). Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). A command named bare that magpie's PATH lacks is started from where `proc.FindTool` finds it (fnm's Nodes on Windows among the folders), with that folder on the check's PATH, since npx's package runs the node beside it by name (`stdioProgram`, #2685, `TestStdioProgramFindsWhatPathLacks`). The page asks once a session for the servers some agent or project has (`inUse` in plugins/library/client.js); one no agent has shows "not checked" and is checked only when its status is clicked (#1597, `library-mcp-health.test.cjs`). A server checked once is checked again when it changes, its sign-in included, so a server signed in to after a click's "needs sign-in" isn't left showing both (新v学员 on Discord, `mcp-signin-health.test.cjs`). The check sends magpie's sign-in as the gateway does: on a 401 it renews the token once and asks again, and a server that refuses even the renewed token has the sign-in marked run out (`mcpauth.Rejected`, also from the gateway's `/mcp/`), which `ServerHealth.SignIn` carries back so the row's tag says "Sign-in ran out" rather than "Signed in" beside "needs sign-in". A server that refuses the check (401 or 403) but that an agent signed in to on its own is named so (`ServerHealth.AgentSignIn`, `readOwnSignIns` in `mcp_agent_signin.go`): each Claude Code target's `.credentials.json` beside its settings.json, a WSL distro's under the distro's home, is read for a `mcpOAuth` entry of the server's name and URL with a token, and each Codex target's `.credentials.json` beside its config.toml for a flattened entry of them, the file codex-rs falls back to when its config's `mcp_oauth_credentials_store` is `file` or the keyring is missing, whose executor's own entries are no `codex mcp login` (#3508); and the row says "signed in in Claude Code (Ubuntu)" — or Codex — instead of "needs sign-in" (CyberCaius on Discord: signed in to with Claude Code's /mcp in WSL). The tokens are never sent or kept; a file that can't be read or parsed names nobody, a stopped distro isn't started for it, and on a Mac only the file is read, never the Keychain Claude Code keeps them in nor Codex's keyring store. They are part of the check's key, so a sign-in in the agent since is checked anew (`TestCheckNamesAgentsSignedInThemselves`, `library-mcp-health-wsl.test.cjs`). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/` (#615). The editor's Sign in saves the form first only when the sign-in is to another server than the saved one (a new server, a name or URL changed), and its button then reads "Save and sign in"; anything else edited (headers, env, arguments) stays unsaved until Save, so Cancel leaves the server as it was (新v学员 on Discord, `mcp-editor-cancel.test.cjs`). A server whose authorization server refuses magpie's dynamic client registration with 401 or 403 admits only the clients it lists (Figma's, #1619): the sign-in fails with `mcpauth.ErrClientRefused`, which says so and that each agent signs in itself, and the agents keep the server's own address. A server whose authorization server has no registration endpoint at all (GitHub's remote server, 新v学员 on Discord) fails with `mcpauth.ErrNoRegistration`, which says to make an OAuth app with the vendor and give it in the editor; the editor then opens its "OAuth app" fields. The app is the server's `oauth` (`OAuthApp`: `clientId`, `clientSecret`, `callbackPort`, Claude Code's names for `--client-id`, `--client-secret` and `--callback-port`), checked on save (HTTP only, a client ID, a port from 1 to 65535), and `SignInServer` signs in as it through `mcpauth.StartWith` without registering. The callback is Claude Code's, `http://localhost:/callback` (its docs' "Use pre-configured OAuth credentials"; 2.1.296 builds it so), listened for on 127.0.0.1 alone as Claude Code does, so an app made for Claude Code signs magpie in as it is; a server that matches the registered URL exactly refuses another host, which is why Claude Code's 2.1.231 went back to `localhost` from 2.1.229's `127.0.0.1` (`TestAppMadeForClaudeCode`). Without a `callbackPort` the port is any free one, which a loopback callback registered without a port takes (GitHub's, RFC 8252); a fixed `callbackPort` is for a vendor that matches the port too. magpie's own registration, when a server has one, still names `127.0.0.1`. The client secret is kept in library.json, as a header's or env's value is: a backup without keys leaves it out, and `WithSecrets` puts back this computer's secret only for the same client ID; no agent is given the app, and the TUI's editor, which doesn't show it, keeps it. GitHub answers a token request's error with a 200 and `error` in the body (`bad_refresh_token`, `incorrect_client_credentials`), which `tokenRequest` reads as the error it is, and a dead refresh token marks the sign-in run out (`github_app_test.go`, `mcp-oauth-app.test.cjs`). magpie never registers under another client's name; one that reaches the gateway from another machine (a WSL distro under NAT) is given it with the LAN sharing key as its `Authorization` (`agent.KeyAt`), as its models are, which the gateway takes in place of a sign-in and never passes on; turning sharing on or off, or a new key (`access.LANChanged`), writes such entries again. `ConfigOfServers` is the servers picked as an agent's project file (`projectMCPFiles`) would hold them, written by the same code into a folder of its own and read back, with those the agent can't take there named; the page's Copy config… puts it on the clipboard for a project magpie doesn't keep (#1478). The editor's command is a box that wraps, so a long line is read whole, and Enter still saves it (hema_17384 on Discord). Its Form | JSON switch shows the server as JSON in Claude Code's `.mcp.json` shape, the one Copy config… gives for it (`jsonOf` in plugins/library/client.js), with `${NAME}` references as written. An edit there is read as a paste is (`serversIn`) and becomes the form's at once. JSON that isn't one server's keeps the dialog from saving or going back to the form, and counts as unsaved. The note, the agents and sync stay in the form (`library-mcp-json.test.cjs`). A server's and a skill's `Note` (youyo.p_10001 on Discord) is the user's own word on what it is for: one line of at most `maxNote` (200) characters, whitespace run together (`checkNote`), as a hook's description is. The row shows it in place of the command or description, and its tooltip still gives that line. The skills' filter reads it too. A sync carries it (a server whole, a skill as `CarriedSkill.Note`), and no agent is given it, through the MCP router or not (`TestNoteNeverGiven`, `TestNoteCarried`). A skill's is set by itself (`SkillNote`, `skills/note`) from the skill's reader. Each listed tool has a switch: the tools turned off are the server's `DisabledTools`, set by `ServerTools`, and written into each agent given the server that can leave out a single tool (see the constraint below). A server run as `npx -y args` (a registry package, no other npx flag) is given to an agent on this machine as `node args` (`npxDirect`): magpie installs the package with npm into a folder of its own under `mcp-npm` in the background, the next sync writes the node form, and until then, or when npm fails (tried again after an hour), the agent keeps npx. npx otherwise stays as the server's parent for its whole life, a node and two cmd.exe beside each instance on Windows (#3885). An unpinned spec is installed again after a day, as npx would fetch the newer one; an install no library server runs goes a day after its last. The library, a server's check, Copy config… and agents in WSL keep npx (`TestNpxServerRunsByNode`, `TestReadNpx`). A remote server holds several accounts (Elorynth on X), one in use that every agent is given: sets of headers are `Server.Accounts` with `Server.Account` the one in use ("" is the server's own `Headers`), laid over `Headers` by `live` in `through`, `remoteHeaders` and `hubKey`, so a switch rewrites each agent's file (`TestServerAccountsSwitchEveryAgent`); a save from the editor, which doesn't send them, keeps them, and a backup carries no account's key (`TestServerAccountKeysAreSecrets`). magpie's OAuth sign-ins are `mcpauth` records, the one in use at `m[name]` and the others in `Spare` (`Use`, `RemoveAccount`, `StartAccount`), which the gateway's `/mcp/` sends from its next request on; an agent's existing upstream `Mcp-Session-Id` isn't reset by a switch. API `/api/library/mcp-account`; GUI `headerAccounts` and `acctList` (`mcp-accounts.test.cjs`). Agents that read one file (Antigravity and agy: `~/.gemini/config/mcp_config.json`) are written in turn, and the `magpie` entry one wrote there is magpie's for the other too (`sharerWrote`, `TestAntigravitySharedMCPFile`; izhidigua on X: it was taken for a server of the user's own and kept the servers direct). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_npx.go`](../../internal/library/mcp_npx.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go), [`mcp_agent_signin.go`](../../internal/library/mcp_agent_signin.go), [`mcp_copy.go`](../../internal/library/mcp_copy.go), [`mcp_tools_off.go`](../../internal/library/mcp_tools_off.go) | | MCP server on/off | `ServerOn` (`POST /api/library/servers/on` with `name` and `on`, `magpie library mcp off|on `) turns a server off for everyone without removing it (swang20201 on X, Docker gateway mode, where a server ticked for no agent is still given to every app at the MCP router's address). Off, it is `Hidden` with its agents kept in `Paused` and `Agents` empty, as a plugin's server hidden from agents is (`PluginServerOn`, [Plugin tools](plugin-tools.md)): no agent's file has it, no project's (`syncProjectMCP` skips it, keeping the project's own agents for it), no subagent names it (`renderSubagent`), the router lists and calls it for nobody, and a process the router held for it ends, since `Hidden` and `Paused` are part of its `hubKey`. Its command, URL, env, headers, sign-in, `DisabledTools` and note stay in library.json. On, the agents in `Paused` get it back (none when it had none, so the router gives it to other apps again), as before it was turned off; giving it agents (`ServerAgents`, the CLI's `mcp agents`) turns it on with those (`save`), while Turn all on (`EveryServerAgents` with every agent) leaves it off. The row's switch sits after its agent chips (`serverSwitch` in plugins/library/client.js); off, the row is dimmed, its chips take no click, and it is health-checked only on a click (`TestServerOnKeepsAndRestores`, `TestLibraryMCPOffOn`, `library-mcp-on.test.cjs`). The servers off are listed apart, below the ones on, under a Servers turned off (N) fold drawn as Providers' Turned off one (`.fold` in an `.off-head`), folded at first and remembered in localStorage (`magpie.offServersOpen`); while picking (Select) it is held open, so every server picked is in sight (hzlxb on X, `library-mcp-off-fold.test.cjs`). | [`mcp_on.go`](../../internal/library/mcp_on.go), [`project_mcp.go`](../../internal/library/project_mcp.go), [`subagents.go`](../../internal/library/subagents.go) | diff --git a/internal/cli/library_project_kind_cli.go b/internal/cli/library_project_kind_cli.go index 7d576425e..5dbf84d10 100644 --- a/internal/cli/library_project_kind_cli.go +++ b/internal/cli/library_project_kind_cli.go @@ -230,7 +230,7 @@ func (k projectKind) list(typed string, asJSON bool) error { } have := k.of(p) if asJSON { - return printJSON(map[string]any{"dir": p.Dir, "name": p.Name, k.plural: have}) + return printJSON(map[string]any{"dir": p.Dir, "name": p.Name, k.plural: have, "items": k.items(p)}) } names := make([]string, 0, len(have)) for n := range have { @@ -244,7 +244,44 @@ func (k projectKind) list(typed string, asJSON bool) error { for _, n := range names { fmt.Printf(" %s → %s\n", bold.Render(n), strings.Join(have[n], ", ")) } + if own := p.Own[k.plural]; len(own) > 0 { + fmt.Println(" ", muted.Render("the project's own, read-only:")) + for _, r := range own { + fmt.Printf(" %s %s\n", r.Name, muted.Render(strings.TrimSpace(r.Event+" "+r.Path))) + } + } return nil } +// projectItem is one row of a project's list, with where it comes from: +// source "magpie" for what magpie placed (agents says for whom), "project" +// for what the project's own files give (read-only, #7247). +type projectItem struct { + Name string `json:"name"` + Source string `json:"source"` + Agents []string `json:"agents,omitempty"` + Agent string `json:"agent,omitempty"` + Path string `json:"path,omitempty"` + Event string `json:"event,omitempty"` + Transport string `json:"transport,omitempty"` + Description string `json:"description,omitempty"` +} + +func (k projectKind) items(p *library.ProjectView) []projectItem { + have := k.of(p) + names := make([]string, 0, len(have)) + for n := range have { + names = append(names, n) + } + sort.Strings(names) + out := []projectItem{} + for _, n := range names { + out = append(out, projectItem{Name: n, Source: "magpie", Agents: have[n]}) + } + for _, r := range p.Own[k.plural] { + out = append(out, projectItem{Name: r.Name, Source: "project", Agent: r.Agent, Path: r.Path, Event: r.Event, Transport: r.Transport, Description: r.Description}) + } + return out +} + var _ = os.Stdout diff --git a/internal/cli/library_project_test.go b/internal/cli/library_project_test.go index 9292c3998..9d3b37457 100644 --- a/internal/cli/library_project_test.go +++ b/internal/cli/library_project_test.go @@ -404,6 +404,20 @@ func TestLibraryProjectHookCmd(t *testing.T) { if out := must("hook", "."); !strings.Contains(out, "bark") || !strings.Contains(out, "codex") { t.Errorf("list:\n%s", out) } + // each row says where it comes from (#7247): magpie's bark, the project's echo mine + var listed struct { + Items []struct{ Name, Source, Path string } + } + if err := json.Unmarshal([]byte(must("hook", ".", "--json")), &listed); err != nil { + t.Fatal(err) + } + src := map[string]string{} + for _, it := range listed.Items { + src[it.Name] = it.Source + } + if src["bark"] != "magpie" || src["echo mine"] != "project" || len(src) != 2 { + t.Errorf("sources: %+v", listed.Items) + } must("hook", "agents", ".", "bark", "codex") if got := read(".claude/settings.local.json"); strings.Contains(got, "say bark") || !strings.Contains(got, "echo mine") { t.Errorf("claude after agents:\n%s", got) diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 31b70413f..72c882781 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -7165,10 +7165,10 @@ magpie.plugin("library", (ctx) => { card.append(head); if (p.problems?.[""]) card.append(el("div", "lib-err", p.problems[""])); if (!isOpen) return card; - if (mcp) return projectServers(p, card); - if (sub) return projectSubagents(p, card); + if (mcp) return projectOwn(p, "servers", projectServers(p, card)); + if (sub) return projectOwn(p, "subagents", projectSubagents(p, card)); if (plg) return projectPlugins(p, card); - if (hk) return projectHooks(p, card); + if (hk) return projectOwn(p, "hooks", projectHooks(p, card)); if (ins) return projectInstructions(p, card); const opts = el("div", "lib-projopts"); @@ -7211,6 +7211,29 @@ magpie.plugin("library", (ctx) => { card.append(el("p", "lib-aside lib-projfoot", t("Placed in {dirs} of the project and kept out of git, its .gitignore untouched. A folder there that isn't magpie's is left as it is.", { dirs: dirs.join(", ") }))); const skip = shownAgents().filter((a) => a.skills && !a.projectSkills); if (skip.length) card.append(el("p", "lib-aside lib-projfoot", t("{agents} reads no project skills folder magpie knows of.", { agents: skip.map((a) => a.name).join(", ") }))); + return projectOwn(p, "skills", card); + } + + // What the project's own files already give agents, apart from what magpie + // placed (#7245): read-only rows under a heading, no chips, nothing here + // changes or takes them away. + function projectOwn(p, key, card) { + const rows = p.own?.[key] || []; + if (!rows.length) return card; + const box = el("div", "lib-projown"); + box.append(el("div", "lib-projownhead", t("Project's own"))); + for (const r of rows) { + const row = el("div", "row lib-row lib-projskill lib-projownrow"); + const w = el("div", "who"); + w.append(el("div", "name mono", r.name)); + const line = [r.event, r.transport, r.path].filter(Boolean).join(" · "); + const sub = el("div", "sub mono", line); + sub.title = r.description || line; + w.append(sub); + row.append(glyph(GLYPH.folder), w); + box.append(row); + } + card.append(box); return card; } diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 731e834c8..a29450875 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -798,6 +798,7 @@ magpie.strings({ "Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "它的技能、服务器和子代理放在项目自己的那些位置,hooks 写进 .claude/settings.local.json 和 .codex/hooks.json。那里不是 magpie 写的文件、你改过的条目,都保持原样。", "Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex 只在你信任的项目里运行项目的 hooks,并且要先在 /hooks 中审阅。", "Project hooks": "项目 Hooks", + "Project's own": "项目自带", "No hooks yet": "还没有 Hook", "Hide its hooks": "收起它的 Hook", "Pick the hooks it gets": "选择它用的 Hook", @@ -1953,6 +1954,7 @@ magpie.strings({ "Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "它的技能、伺服器和子代理放在專案自己的那些位置,hooks 寫進 .claude/settings.local.json 和 .codex/hooks.json。那裡不是 magpie 寫的檔案、你改過的條目,都保持原樣。", "Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex 只在你信任的專案裡執行專案的 hooks,並且要先在 /hooks 中審閱。", "Project hooks": "專案 Hooks", + "Project's own": "專案自帶", "No hooks yet": "還沒有 Hook", "Hide its hooks": "收起它的 Hook", "Pick the hooks it gets": "選擇它用的 Hook", @@ -3099,6 +3101,7 @@ magpie.strings({ "Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "スキル、サーバー、サブエージェントはプロジェクト自身のものと同じ場所に、フックは .claude/settings.local.json と .codex/hooks.json に書き込まれます。magpie のものではないファイルや、あなたが変更した項目はそのまま残ります。", "Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex は信頼したプロジェクトでのみ、/hooks で確認した後にプロジェクトのフックを実行します。", "Project hooks": "プロジェクトのフック", + "Project's own": "プロジェクト自身のもの", "No hooks yet": "フックはまだありません", "Hide its hooks": "フックを閉じる", "Pick the hooks it gets": "渡すフックを選ぶ", @@ -4250,6 +4253,7 @@ magpie.strings({ "Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "Skills, Server und Subagenten kommen dorthin, wo die eigenen des Projekts liegen, Hooks in .claude/settings.local.json und .codex/hooks.json. Eine Datei dort, die nicht von magpie ist, oder ein Eintrag, den du geändert hast, bleibt, wie er ist.", "Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex führt die Hooks eines Projekts nur in einem Projekt aus, dem du vertraust, und erst, nachdem du sie in /hooks geprüft hast.", "Project hooks": "Projekt-Hooks", + "Project's own": "Eigene des Projekts", "No hooks yet": "Noch keine Hooks", "Hide its hooks": "Hooks ausblenden", "Pick the hooks it gets": "Hooks auswählen", diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css index 3a1197ab4..5e208d3ac 100644 --- a/internal/gui/assets/plugins/library/library.css +++ b/internal/gui/assets/plugins/library/library.css @@ -697,6 +697,9 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col .lib-project .lib-projskill { border-top: 1px solid var(--line-2); } .lib-projfoot { margin: 0; padding: 8px 12px 10px 49px; border-top: 1px solid var(--line-2); } .lib-projfoot + .lib-projfoot { border-top: 0; padding-top: 0; } +.lib-projown { border-top: 1px solid var(--line-2); } +.lib-projownhead { padding: 8px 12px 2px 49px; font-size: 11px; color: var(--muted); } +.lib-projownrow { opacity: .8; } /* the library's skills: a card for each GitHub repository they came from, and one for those on this computer, folded to its heading line */ diff --git a/internal/gui/tests/project-hooks.test.cjs b/internal/gui/tests/project-hooks.test.cjs index 43b693d16..320a141cc 100644 --- a/internal/gui/tests/project-hooks.test.cjs +++ b/internal/gui/tests/project-hooks.test.cjs @@ -88,7 +88,7 @@ const words = { }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { - test(engine + ": a project turns on a plugin Claude Code has installed", async (t) => { + test(engine + ": a project turns a library hook on for the agents that read a project hooks file", async (t) => { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); const errors = []; t.after(async () => { diff --git a/internal/gui/tests/project-own.test.cjs b/internal/gui/tests/project-own.test.cjs new file mode 100644 index 000000000..c34ebbaf7 --- /dev/null +++ b/internal/gui/tests/project-own.test.cjs @@ -0,0 +1,123 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// (#7245, jinpwng on X) A project's card lists what its own files already give +// agents under "Project's own", read-only: no chips, nothing posted. In English +// and Chinese. +// No backend: the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const HOME = "/Users/emo"; +const DIR = HOME + "/code/app"; +const agent = (id, name, more = {}) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json`, ...more }); +const plugin = (name, more) => ({ name, version: "1.0.0", description: "", agents: [], skills: [], mcp: [], hooks: [], subagents: [], ...more }); +const lib = (given) => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [ + agent("claude", "Claude Code", { projectSkills: ".claude/skills", projectMCP: ".mcp.json", projectSubagents: ".claude/agents", projectHooks: ".claude/settings.local.json" }), + agent("codex", "Codex", { projectMCP: ".codex/config.toml", projectSubagents: ".codex/agents", projectHooks: ".codex/hooks.json" }), + agent("pi", "Pi", { projectSkills: ".agents/skills", projectMCP: ".pi/mcp.json" }), + agent("goose", "Goose"), + ], + instructions: { agents: [] }, servers: [], subagents: [], skills: [], foundServers: [], foundSkills: [], + hooks: [{ name: "bark", event: "turn-end", command: "say bark", agents: [] }], hookAgents: [{ id: "claude", file: `${HOME}/.claude/settings.json`, events: ["Stop"] }, { id: "codex", file: `${HOME}/.codex/hooks.json`, events: ["Stop"] }], plugins: [], claudeInstalled: [{ id: "fmt@acme", on: false }, { id: "lint@acme", on: true }], + projects: [{ dir: DIR, name: "app", copy: false, skills: {}, placed: [], servers: {}, subagents: {}, plugins: {}, hooks: given, wrote: {}, own: { hooks: [{ name: "echo mine", path: ".claude/settings.json", agent: "claude", event: "Stop" }] } }], +}); + +function server(lang, posts) { + let given = {}; + return async (route) => { + const req = route.request(), url = new URL(req.url()); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } }); + if (url.pathname === "/api/library") return route.fulfill({ json: lib(given) }); + if (url.pathname === "/api/library/projects/hooks") { + const b = req.postDataJSON(); + posts.push(b); + if (posts.hold) await posts.hold; + given = { ...given, [b.name]: b.agents }; + if (!b.agents.length) delete given[b.name]; + return route.fulfill({ json: { ...lib(given), result: { changed: [], problems: [] } } }); + } + if (url.pathname === "/api/library/native") return route.fulfill({ json: [] }); + if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } }); + if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] }); + if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } }); + if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } }); + if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const scrolled = (page) => page.evaluate(() => [window.scrollX, window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop || e.scrollLeft).map((e) => `${e.className}:${e.scrollTop},${e.scrollLeft}`)].join(" ")); +// a click where the element is, as the reader's: Playwright's own click +// first scrolls it into view +const press = async (page, loc) => { + const b = await loc.boundingBox(); + await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2); +}; +// a chip: the chips fan out under the pointer first, as a reader's hand +// does, and the chip is pressed where it is then +// (a render after the last write may replace it under the pointer, so it +// is found again until it stays) +const box = async (loc) => { + for (;;) { + await loc.waitFor({ state: "visible" }); + const b = await loc.boundingBox(); + if (b) return b; + } +}; +const chip = async (page, loc) => { + const a = await box(loc); + await page.mouse.move(a.x + a.width / 2, a.y + a.height / 2); + await page.waitForTimeout(350); + const b = await box(loc); + await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2); +}; + + +const words = { en: "Project's own", zh: "项目自带" }; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": what the project's own files give is listed read-only", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const errors = []; + t.after(async () => { + if (errors.length) console.log(errors); + await browser.close(); + }); + for (const lang of ["en", "zh"]) { + await t.test(lang, async () => { + const posts = []; + const ctx = await browser.newContext({ viewport: { width: 860, height: 700 } }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "hooks"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, posts)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const card = page.locator("#view-library .lib-project"); + await card.waitFor(); + assert.equal(await card.locator(".lib-projownrow").count(), 0, "closed card"); + await press(page, card.locator(".lib-projhead")); + const own = card.locator(".lib-projownrow"); + await own.waitFor(); + assert.equal((await card.locator(".lib-projownhead").textContent()).trim(), words[lang]); + assert.match(await own.textContent(), /echo mine/); + assert.match(await own.textContent(), /Stop · \.claude\/settings\.json/); + assert.equal(await own.locator(".lib-ag, button").count(), 0, "a read-only row has no chips"); + await press(page, own); + assert.deepEqual(posts, []); + await ctx.close(); + }); + } + }); +} diff --git a/internal/library/project_own.go b/internal/library/project_own.go new file mode 100644 index 000000000..d9c62103e --- /dev/null +++ b/internal/library/project_own.go @@ -0,0 +1,230 @@ +package library + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "slices" + "sort" + "strings" + + "github.com/tidwall/gjson" +) + +// OwnResource is something the project's own files already give an agent, +// that magpie didn't place (#7245, #7247): shown read-only, never changed +// or taken away. Credentials never go in it: a server's URL, arguments and +// environment stay in the project's file, only its transport is read. +type OwnResource struct { + Name string `json:"name"` + Path string `json:"path"` + Agent string `json:"agent,omitempty"` + Event string `json:"event,omitempty"` + Description string `json:"description,omitempty"` + Transport string `json:"transport,omitempty"` +} + +// ownResources reads, by kind (skills, servers, hooks, subagents), what the +// project's folder has that magpie didn't write. A file it can't read or a +// link out of the folder is left out: unknown, never a wrong list. +func (p *Project) ownResources() map[string][]OwnResource { + out := map[string][]OwnResource{} + var dirs []string + for _, rel := range projectSkillsDirs { + if !slices.Contains(dirs, rel) { + dirs = append(dirs, rel) + } + } + sort.Strings(dirs) + for _, rel := range dirs { + out["skills"] = append(out["skills"], p.ownSkills(rel)...) + } + ids := make([]string, 0, len(projectMCPFiles)) + for id := range projectMCPFiles { + ids = append(ids, id) + } + sort.Strings(ids) + seen := map[string]bool{} + for _, id := range ids { + rel, format := p.mcpRel(id) + if seen[rel] { + continue + } + seen[rel] = true + out["servers"] = append(out["servers"], p.ownServers(id, rel, format)...) + } + for _, id := range []string{"claude", "codex"} { + out["hooks"] = append(out["hooks"], p.ownHooks(id)...) + } + ids = ids[:0] + for id := range projectSubagentDirs { + ids = append(ids, id) + } + sort.Strings(ids) + for _, id := range ids { + out["subagents"] = append(out["subagents"], p.ownSubagents(id)...) + } + for k, rows := range out { + if len(rows) == 0 { + delete(out, k) + } + } + return out +} + +func (p *Project) ownSkills(rel string) []OwnResource { + dir := filepath.Join(p.Dir, filepath.FromSlash(rel)) + if p.inside(dir) != nil { + return nil + } + var out []OwnResource + entries, _ := os.ReadDir(dir) + for _, e := range entries { + path := rel + "/" + e.Name() + abs := filepath.Join(dir, e.Name()) + if slices.Contains(p.Placed, path) || ours(abs, e.Name()) || p.inside(abs) != nil { + continue + } + if m, ok := readMeta(abs); ok { + name := e.Name() + if m.Name != "" { + name = m.Name + } + out = append(out, OwnResource{Name: name, Path: path, Description: m.Description}) + } + } + return out +} + +func (p *Project) ownServers(id, rel string, format mcpFormat) []OwnResource { + abs := filepath.Join(p.Dir, filepath.FromSlash(rel)) + if p.inside(abs) != nil || !exists(abs) { + return nil + } + f := &mcpFile{Path: abs, Format: format} + entries, err := f.entries() + if err != nil { + return nil + } + var out []OwnResource + for name, entry := range entries { + if slices.Contains(p.Wrote[rel], name) || id == "codex" && slices.Contains(p.CodexOff, name) { + continue + } + row := OwnResource{Name: name, Path: rel, Agent: id} + if s, ok := f.decode(name, entry); ok { + row.Transport = s.Transport + } + out = append(out, row) + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out +} + +func (p *Project) ownHooks(id string) []OwnResource { + rels := []string{projectHookFiles[id]} + if id == "claude" { + rels = []string{".claude/settings.json", projectHookFiles[id]} + } + var out []OwnResource + for _, rel := range rels { + abs := filepath.Join(p.Dir, filepath.FromSlash(rel)) + if p.inside(abs) != nil || !exists(abs) { + continue + } + doc, err := readHooksFile(abs) + if err != nil { + continue + } + events := gjson.GetBytes(doc, "hooks").Map() + names := make([]string, 0, len(events)) + for ev := range events { + names = append(names, ev) + } + sort.Strings(names) + for _, ev := range names { + list, err := hookList(doc, abs, ev) + if err != nil { + continue + } + for _, raw := range list { + if p.wroteHook(id, ev, raw) { + continue + } + for _, c := range ownHookCommands(raw) { + out = append(out, OwnResource{Name: c, Path: rel, Agent: id, Event: ev}) + } + } + } + } + return out +} + +// wroteHook is whether raw is an entry magpie wrote, byte for byte. +func (p *Project) wroteHook(id, ev string, raw json.RawMessage) bool { + return slices.ContainsFunc(p.HookRecs[id], func(r HookEntry) bool { + return r.Event == ev && sameEntry(r.Entry, raw) + }) +} + +func sameEntry(a, b json.RawMessage) bool { + var x, y bytes.Buffer + if json.Compact(&x, a) != nil || json.Compact(&y, b) != nil { + return false + } + return bytes.Equal(x.Bytes(), y.Bytes()) +} + +// ownHookCommands are the commands an entry runs: its own, or those of the +// group it holds (Claude Code's { matcher, hooks: [...] }). +func ownHookCommands(raw json.RawMessage) []string { + var e struct { + Command string `json:"command"` + Hooks []struct { + Command string `json:"command"` + } `json:"hooks"` + } + if json.Unmarshal(raw, &e) != nil { + return nil + } + var out []string + if e.Command != "" { + out = append(out, e.Command) + } + for _, h := range e.Hooks { + if h.Command != "" { + out = append(out, h.Command) + } + } + return out +} + +func (p *Project) ownSubagents(id string) []OwnResource { + sp := projectSubagentSpec(p, id) + if sp == nil || p.inside(sp.dir) != nil { + return nil + } + var out []OwnResource + entries, _ := os.ReadDir(sp.dir) + for _, e := range entries { + if e.IsDir() || !strings.HasSuffix(e.Name(), sp.ext) { + continue + } + abs := filepath.Join(sp.dir, e.Name()) + rel := p.rel(abs) + body, err := os.ReadFile(abs) + if err != nil || slices.ContainsFunc(p.AgentFiles, func(f SubagentFile) bool { + return f.Path == rel && f.Hash == subagentHash(body) + }) { + continue + } + m := parseMeta(body) + name := m.Name + if name == "" { + name = strings.TrimSuffix(e.Name(), sp.ext) + } + out = append(out, OwnResource{Name: name, Path: rel, Agent: id, Description: m.Description}) + } + return out +} diff --git a/internal/library/project_plugins_test.go b/internal/library/project_plugins_test.go index ad585c44d..57dd4dddd 100644 --- a/internal/library/project_plugins_test.go +++ b/internal/library/project_plugins_test.go @@ -1,8 +1,10 @@ package library import ( + "encoding/json" "os" "path/filepath" + "slices" "strings" "testing" ) @@ -258,3 +260,37 @@ func TestProjectOneHookPerAgent(t *testing.T) { t.Errorf("view after removal: %+v", v.Projects[0].Hooks) } } + +// What the project's own files give agents is listed apart from what magpie +// placed, read-only (#7245, #7247): a hook, server, skill and subagent the +// folder had before, and none of magpie's. +func TestProjectOwnResources(t *testing.T) { + _, a, _ := pluginProjects(t) + ok(t)(SaveHook("", Hook{Name: "bark", Event: "turn-end", Command: "say bark", Agents: []string{}})) + write(t, filepath.Join(a, ".claude/settings.json"), `{"hooks": {"Stop": [{"hooks": [{"type": "command", "command": "echo shared"}]}]}}`) + write(t, filepath.Join(a, ".claude/settings.local.json"), `{"hooks": {"Stop": [{"hooks": [{"type": "command", "command": "echo mine"}]}]}}`) + write(t, filepath.Join(a, ".mcp.json"), `{"mcpServers": {"theirs": {"url": "https://x.test/mcp?key=SECRET"}}}`) + write(t, filepath.Join(a, ".claude/skills/own/SKILL.md"), "---\nname: own\ndescription: Mine.\n---\nbody\n") + write(t, filepath.Join(a, ".claude/agents/rev.md"), "---\nname: rev\ndescription: Reviews.\n---\nbody\n") + ok(t)(ProjectHooks(a, []string{"bark"}, []string{"claude"})) + own := View0(t).Projects[0].Own + var hooks []string + for _, r := range own["hooks"] { + hooks = append(hooks, r.Name) + } + if !slices.Equal(hooks, []string{"echo shared", "echo mine"}) { + t.Errorf("own hooks %v (magpie's say bark must not be one)", hooks) + } + if len(own["servers"]) != 1 || own["servers"][0].Name != "theirs" || own["servers"][0].Transport != "http" { + t.Errorf("own servers %+v", own["servers"]) + } + if b, _ := json.Marshal(own); strings.Contains(string(b), "SECRET") { + t.Errorf("a credential went in the view: %s", b) + } + if len(own["skills"]) != 1 || own["skills"][0].Name != "own" || own["skills"][0].Description != "Mine." { + t.Errorf("own skills %+v", own["skills"]) + } + if len(own["subagents"]) != 1 || own["subagents"][0].Name != "rev" { + t.Errorf("own subagents %+v", own["subagents"]) + } +} diff --git a/internal/library/projects.go b/internal/library/projects.go index 38cbcd652..32157fd74 100644 --- a/internal/library/projects.go +++ b/internal/library/projects.go @@ -658,8 +658,12 @@ type ProjectView struct { ClaudePlugins []string `json:"claudePlugins"` // Hooks are the library's hooks the project has on their own, for // the agents given - Hooks map[string][]string `json:"hooks"` - Missing bool `json:"missing,omitempty"` // the folder is gone + Hooks map[string][]string `json:"hooks"` + // Own are, by kind (skills, servers, hooks, subagents), what the + // project's own files already give agents and magpie didn't place: + // read-only (#7245) + Own map[string][]OwnResource `json:"own,omitempty"` + Missing bool `json:"missing,omitempty"` // the folder is gone // Problems are, by skill ("" for the project's own), what couldn't be done Problems map[string]string `json:"problems,omitempty"` } @@ -711,6 +715,8 @@ func projectViews(l *Library, problems []Problem) []ProjectView { } if fi, err := os.Stat(p.Dir); err != nil || !fi.IsDir() { v.Missing = true + } else { + v.Own = p.ownResources() } for _, x := range problems { if x.Agent == p.Dir {