library: Rules, a folder of rules given to Claude Code, Cline and Kiro CLI (JonahFu on X)

JonahFu asked on X (tweet 2123237371739316685) for Claude's rules
folder in the Library. A new Rules tab keeps rules once and gives each
to the agents ticked for it, in the folder each reads by itself:

- Claude Code: <claude dir>/rules/<name>.md. `paths` is the only
  front matter key it reads (code.claude.com/docs/en/memory). Checked
  on real 2.1.327 in a sandbox: it reads every .md under the folder,
  loads one without paths at launch, and one with paths when
  Read/Write/Edit touches a matching file.
- Cline: <cline dir>/rules (CLINE_DIR, else ~/.cline). Cline 3.0.70
  reads every rule always and has no paths key, so a rule with paths
  isn't written for it; the agent gets a problem and the editor says
  why under the paths.
- Kiro CLI: ~/.kiro/steering, `inclusion: fileMatch` +
  `fileMatchPattern` for paths, else always. A rule named "agents" is
  refused there (it would be AGENTS.md on a disk that ignores case).
- Not listed: Cursor (user rules live in its settings; .cursor/rules is
  per project), Codex (its rules are execpolicy), Droid (command
  permissions), Gemini CLI, Qwen Code and OpenCode (no rules folder).

A body starting with --- gets an empty front matter first. Files are
recorded with their hash in Applied.Rules through the same
syncOwnFiles as subagents and slash commands: a file of the user's own
by that name, or one magpie wrote that the user edited, is never
written over or taken away. Bundles (backup, WebDAV) carry rules; a
bundle from an older magpie leaves this computer's alone. The editor
lists each agent's file to reveal. No CLI yet.

docs/subsystems/library.md: a Rules row and its tests.

Run (mica-run, at this tree):
- go vet -tags nogui ./internal/library ./internal/gui ./internal/davsync
  ./internal/cli: ok. gofmt -l: none.
- go test -tags nogui -timeout 45m ./internal/library ./internal/davsync:
  ok (TestRulesEachAgentsFile, TestRulesKeptToTheirPaths,
  TestRulesLeaveTheUsersFiles, TestRuleCheck, TestRulesCarried).
- node --test library-rules, library-subagents, library-commands,
  library-hooks, library-loading, library-groups, i18n-keys,
  i18n-en-no-cjk (Chromium and WebKit, 420 and 1100 wide, en zh zh-TW
  ja de): 78 of 78.
- The full suite and cross-OS vet ran at the next commit, which this
  one is under.
- Real use: Claude Code 2.1.327 in a sandbox HOME loaded a rule without
  paths at launch and one with paths only on touching a match; a
  sandbox magpie on mica wrote ~/.claude/rules/go-style.md with
  paths: ["**/*.go"].
Not tried: Cline and Kiro CLI loading the files for real, project-level
rules (.claude/rules in a repository), Copilot and CodeBuddy (not
verified, not listed), Windows and Linux.
This commit is contained in:
yetone
2026-11-19 12:20:02 +08:00
parent 567ba3a277
commit 3132fa1cd9
20 changed files with 1212 additions and 25 deletions
+7 -2
View File
@@ -1,9 +1,10 @@
# Library: instructions, MCP servers, skills, hooks, subagents, slash commands, RTK and billion-context
# Library: instructions, MCP servers, skills, hooks, subagents, slash commands, rules, RTK and billion-context
The library keeps what every agent should know in one place: the
instructions each agent reads before a conversation, the MCP servers it can
call, the skills it can load, the hooks it runs at points of its turn, and
the subagents it can hand a task to, and the slash commands typed into it.
the subagents it can hand a task to, the slash commands typed into it,
and the rules it reads from its folder of rules.
magpie writes these into each agent's own
files in that agent's format, and takes back only what it wrote. Everything
else in those files stays as it was. Package `internal/library` also gives
@@ -40,6 +41,7 @@ Pi's extensions and packages.
| Subagents from a repository | The Subagents tab's find line (CHENGJIAHEGOXIS on X: msitarzewski/agency-agents) takes what the skill installer does, owner/repo, a GitHub or GitLab link to the repository, a folder or a file in it, any git address, or a folder here, and fetches it the same way (`fetchSourceRoot`, shared with `resolvePluginRoot`; `tooBig` refuses a whole repository too big to download and asks for its folder's link). `ProbeSubagents` lists each Markdown file with front matter that has a description (`readSubagentAt`): its name is the slug of `name` (`subagentName`), else the file's own name when it sits in an `agents` or `droids` folder; its description is folded to one line of at most 1000 characters; the body is the prompt. Every other key (`color`, `emoji`, `vibe`, `tools`, `author`, `model`, …) is dropped, a Codex TOML role is not read, and a skill's folder (one with a SKILL.md) and `.git`, `.github`, `node_modules` are skipped. Of two files with one name the shallower is taken and the other is listed in `Left` with why, as is one `Subagent.check` refuses (a reserved name). `ImportSubagents` (`POST /api/library/subagents/probe`, then `subagents/import` with `source`, `paths`, `agents`) adds the picked ones for the agents ticked, recording where each came from (`From`, a `Source` with the file's path) and the hash of its description and prompt as imported (`FromHash`). Imported again, from the repository's link or a folder's or a file's, a subagent from the same file is `have` when it is the same, `update` when upstream changed and the library's still matches `FromHash` (its description and prompt are replaced, its agents, skills, servers and model kept), and `edited` when the user changed it here (`SaveSubagent` keeps `From`; it is left as it is). A name the library has for another subagent is never written over: the import takes the next free `name-N`. A carried library carries `From`. The page lists what was found to pick from, with Select all, a filter past eight, a tag for each state and the files left out (`TestSubagentsFromAgencyAgents`, `TestSubagentImportLeavesTheUsersOwn`, `TestSubagentImportAgainUpdates`, `TestSubagentsFromAFolder`, `library-subagents-import.test.cjs`; the fixture is agency-agents' own files in `testdata/agency-agents`). | [`subagent_import.go`](../../internal/library/subagent_import.go), [`plugin.go`](../../internal/library/plugin.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) |
| Slash commands | A `Command` (miantiao_me on X) is a name (lowercase letters, digits, - and _), a one-line description and a prompt, given to the agents ticked for it, and typed as /name there. The prompt says `$ARGUMENTS` for every word typed after the name and `$1`, `$2`… for the first, second… of them. `syncCommands` writes it as a file of its own in each agent's user-level folder, in that agent's shape (`commandSpecOf`): `<claude dir>/commands/<name>.md` (front matter `description`; `$n` becomes Claude Code's `$ARGUMENTS[n-1]`, counted from 0), OpenCode's `commands/<name>.md` beside its config and Pi's `<agent dir>/prompts/<name>.md` (`$ARGUMENTS` and `$n` as magpie's), `~/.gemini/commands/<name>.toml` (`description`, `prompt`, `$ARGUMENTS` as `{{args}}`), Qwen Code's `commands/<name>.md` (`{{args}}`) and `~/.factory/commands/<name>.md` (`$ARGUMENTS`). Gemini CLI, Qwen Code and Droid take no words by place, so a command that uses `$1`… isn't written for them: the agent gets a problem, the editor names them under the prompt while it uses one, and the tab says so under the list. Codex is listed but greyed: Codex 0.165 has no loader of `~/.codex/prompts` any more, its skills took their place. An agent in a WSL distro gets none. The page lists, per agent, its folder and whether it takes `$1`… (`CommandAgentView`). There is no CLI for them yet. | [`commands.go`](../../internal/library/commands.go), `TestCommandsEachAgentsFile`, `TestCommandsWordsByPlace` |
| Slash commands from the agents | The Slash commands tab's "Find in agents" (miantiao_me on X: "can the ones I defined in Pi be imported?") lists the commands the user already made in each agent here (`ProbeCommands`), read where that agent reads them, at the folder's top only: Pi's `prompts/*.md`, Claude Code's `commands/*.md`, OpenCode's `commands/*.md` and `command/*.md`, Gemini CLI's `commands/*.toml`, Qwen Code's `commands/*.md` and `*.toml` (its FileCommandLoader reads both) and Droid's `commands/*.md`. The file's name is the command's; the description is the front matter's (a TOML's `description`), the prompt the body (a TOML's `prompt`), and each agent's way of saying the words typed in reads back as magpie's: Claude Code's `$ARGUMENTS[n]` and `$n`, counted from 0, as `$n+1` (the `\$0` magpie writes as `$0`), Pi's `$@` and Gemini's and Qwen's `{{args}}` as `$ARGUMENTS`; Pi's `${@:N}` is left as written. A name magpie can't take, a file over 1 MB or one with no prompt is listed as left out, with why. A file magpie wrote, still as it wrote it (`Applied.Commands`), isn't listed. One name saying the same in several agents is one candidate for all of them; saying different things, each is listed, tagged, and only one can be picked. A name the library has saying the same is tagged and joins (the import ticks these agents too); one the library has for another command can't be picked, and the user's file stays as it is. `ImportCommands` takes the paths picked, reads them again, and ticks the agents each was found in. Each command keeps the files it came from (`Command.Taken`, per agent: path, bytes, and a hash of what they said): while the command says the same, `syncCommands` writes those bytes at that path, so `syncOwnFiles` takes the user's own file as magpie's byte for byte, and nothing is doubled or written over (OpenCode's `command/` file stays there). After an edit here, the command is written in the agent's shape at the same path when its extension is the one magpie writes, else at magpie's own path. A rename drops `Taken`. Unticking or removing an imported command takes its file away, into the backups, as with any file of magpie's. `Taken` is this computer's: never in `Bundle.Commands` or the page's view, and a bundle put here keeps it for a command of the same name. | [`command_import.go`](../../internal/library/command_import.go), `TestCommandImportPiPrompts` (Pi's own `.pi/prompts` files in `testdata/pi-prompts`), `TestCommandImportArgs`, `TestCommandImportByName`, `TestCommandImportNotCarried`, `library-commands-import.test.cjs` |
| Rules | A `Rule` (JonahFu on X) is a name (as a slash command's), a Markdown body and, if wanted, `Paths`: globs, one a line in the editor, that keep it to the files they match. `syncRules` writes it as `<name>.md` in each ticked agent's own folder of rules (`ruleSpecOf`), through the shared `syncOwnFiles`: Claude Code's `<claude dir>/rules` (front matter `paths`, the only key it reads; checked against the memory docs and v2.1.327, which reads every .md under the folder, loads one without `paths` at launch and one with them when Read/Write/Edit touches a match), Cline's `<cline dir>/rules` (CLINE_DIR, else ~/.cline; Cline 3.0.70 reads every rule always and has no paths key, so a rule with paths isn't written for it: the agent gets a problem (`noPaths`), and the editor names it under the paths) and Kiro CLI's steering folder beside its AGENTS.md (`inclusion: fileMatch` and `fileMatchPattern` for paths, else always; a rule called `agents` is refused there, as it would be AGENTS.md on a disk that ignores case). A body starting with `---` gets an empty front matter first, so it isn't read as one. Cursor (user rules live in its settings, `.cursor/rules` is per project), Codex (its rules are execpolicy) and Droid (command permissions) read no such folder and aren't listed; nor are Gemini CLI, Qwen Code and OpenCode, which read only their instructions file. An agent in a WSL distro gets none. The editor lists each agent's file as a path to show (`revealable`). Bundles carry them as slash commands; there is no CLI yet. | [`rules.go`](../../internal/library/rules.go), `TestRulesEachAgentsFile`, `TestRulesKeptToTheirPaths`, `TestRulesLeaveTheUsersFiles`, `TestRulesCarried`, `library-rules.test.cjs` |
| 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. No agent sets either variable outside Claude Code's plugin runtime, so every reference is resolved before a part is written out ([`plugin_env.go`](../../internal/library/plugin_env.go)): `${NAME}`/`$NAME` in a hook command, a server's command, args and env, a subagent's prompt and a copied SKILL.md become the folder; a hook program's own read (`process.env.NAME`, `Bun.env`, `Deno.env.get`, Python's `os.environ`/`os.getenv`, Ruby's `ENV`) becomes a quoted string literal of the folder with forward slashes, and PowerShell's `$env:NAME` and cmd's `%NAME%` the folder (ponytail's hooks threw at every start without it, @AXmake110 on X); a command server is given both variables in its env, as Claude Code gives them. Parts a magpie before this wrote with the variables in them are resolved at load (`healPluginRefs`) and written out again at the next sync; a SKILL.md copied before is fixed by Update or a reinstall. Exec-form hooks (`args`) and `CLAUDE_PLUGIN_OPTION_<KEY>` are not carried yet (#6682). 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 plugin goes to another computer whole, by sync or a backup file (#6685, JJasonsun on Discord; [`plugin_carry.go`](../../internal/library/plugin_carry.go)): `Bundle.Plugins` carries each record (name, version, source, pick, agents, `Off`, and the parts taken out by hand), never its parts, which name this computer's folder. A plugin from a GitHub or git link goes as that source, and the other computer installs it from there as `UpdatePlugin` does, outside the library's lock; one it can't fetch yet is kept with `Pending`, its old parts if any, and a problem, the row says so, and Update or the next sync tries again. A plugin from a folder, or a link holding a sign-in (whose link isn't carried), goes with its files, on the skills' budget, and is installed from them. Either way that computer reads the parts again, so every hook, server and skill names its own `<library>/plugins/<name>`, Windows' too. A plugin the bundle no longer has is removed with its folder. A bundle from a magpie before this has no `plugins`, and this computer's plugins keep their parts over the same-named items it carries. A marketplace entry's own fields (`strict: false`) aren't carried, so a local marketplace plugin is read from its files alone there. A plugin installed from a marketplace under a name other than its manifest's names that folder in its parts too (`TestPluginCarriedWhole`, `TestPluginCarriedBySource`, `TestPluginOldBundleKeepsPlugins`, `TestPluginMarketplaceNameIsItsFolder`, davsync's `TestSyncLibraryPlugins`, `TestPluginImportCarryOnOffRemove`, `TestPluginHookReadsRootFromItsProgram`, `TestPluginHookWrittenBeforeIsResolved`, `TestPluginPartsGetItsFolders`, `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) |
| RTK | `SetRTK` runs rtk's own installer (`rtk init -g …`) for an agent being switched on. For one being switched off, it removes exactly what the installer wrote, using magpie's own code, which works even with rtk gone. An rtk.exe in one of winget's folders that winget has no record of (`winget list` says so, or its records name another folder; netube99 on X, 0x8A150014) is upgraded from rtk's own Windows release over the file a `WinGet\Links` link points to, not by `winget upgrade`. `ReadRTK` reads each agent's files to say which have the hook. An agent gone for its CLI (`CLIMissing`, #2254) isn't offered rtk, but one that still has the hook is listed so it can be taken out. `rtkSpec.blocked` stops the installer where it would break an agent. `rtkSpec.env` tells the installer the agent's folder where rtk would pick another: Hermes Agent's is `appdir.HermesHome` (`%LOCALAPPDATA%\hermes` on Windows), which rtk is given as `HERMES_HOME`, since rtk 0.51 knows only `$HERMES_HOME` and `~/.hermes`. Antigravity CLI (`agy`, #2202) gets rtk 0.51's own plugin for Antigravity, `plugins/rtk` in its global customization folder `~/.gemini/config` (`plugin.json`, `hooks.json` with `PreToolUse` → `rtk hook antigravity`, `rules/AGENTS.md`), which `agy plugin list` lists; switching it off takes that one folder out. rtk 0.50 knows Antigravity only per project and fails `rtk init -g --agent antigravity`, so an older rtk is `blocked` (`agyBlocked`) and the row says to update RTK. OpenCode 2 loads only the plugin rtk 0.52 on writes (one default object with `id` and `setup()`, rtk-ai/rtk#4187); an older rtk's plugin is for OpenCode 1 and OpenCode 2 refuses it, so with an OpenCode 2 here an older rtk is `blocked` (`openCodeBlocked`) and the row says to update RTK (#2295). Under OpenCode 2, an old plugin left from before an rtk update counts as off once the rtk here can write the new one (`openCodeHas`), so switching it on writes the new one over it; with an older rtk it counts as on, so it can be switched off. Factory's Droid (lml0664 on Discord) gets rtk's own `rtk init -g --agent droid`, given Droid's folder as `FACTORY_HOME_OVERRIDE`; rtk puts its `Execute` group (`rtk hook droid`) in the root `hooks.json`, or in `settings.json`'s `hooks.PreToolUse` where Droid's hooks already are, so `droidHookFiles` reads and switches off all three places rtk 1.1.0 may use (`hooks.json`, `hooks/hooks.json`, `settings.json`), leaving the user's own hooks. rtk before 0.44 has no Droid agent, so it is `blocked` (`droidBlocked`). A detected agent RTK has no hook for at all is still listed, from `rtkNoHook`, with the reason and a switch that can't be turned on (dsh: its hooks can allow or deny a command but not rewrite it, and `rtk init` has no `--agent dsh`; Grok Build and Grok App: `rtk init` has no Grok or Grok App agent, so both are listed with the switch off; Qoder and Qoder CN: rtk 1.1.0 has no Qoder agent; Cline and Kimi Code: `rtk init --agent cline|kimi` writes only one project's `.clinerules` or `AGENTS.md`, instructions with no hook, and Kimi's refuses `-g`). RTK 1.1.0's Trae, Windsurf, Kilo Code and Mistral Vibe have no magpie agent. The page's No RTK hook tag gives each agent's own reason and rtk-ai/rtk issue (`rtkNoHookWhy` in plugins/library/client.js: dsh #3847, Grok Build and Grok App #2136, Qoder and Qoder CN #1327, Cline #3841), and an agent with no entry gets no link; `TestRTKNoHookIssuesAreEachAgents` fails when the page and `rtkNoHook` cite different issues, or two agents cite the same ones without a reason in `sharedRTKIssues`. | [`rtk.go`](../../internal/library/rtk.go) |
@@ -115,6 +117,7 @@ Pi's extensions and packages.
- Reading the page never waits on reading skills through (#541). `Read` compares an agent's own skill with the same name in another agent (`sameTree`) and hashes each library skill given as a copy (`hashFiles`, for `behind`). Both are kept against a stamp of the folders (each file's and link's path, type, size and mtime, `stamper` in [`treememo.go`](../../internal/library/treememo.go)), taken by the same walk that compares or hashes them, before a file is opened; a later read walks the folder without opening a file, and while the stamps match reuses the answer. Only an answer from a whole read of folders untouched for `settleFor` (3s) is kept: a folder that couldn't be walked or read, or was written a moment ago, is read again next time, never taken as unchanged. A rewrite that keeps a file's size and mtime isn't seen. `Glance` (`GET /api/library?glance=1`) is the page without those two, marked `partial`; the page draws it first, then the whole read, which runs `behind` and `foundSkills` after the library's lock is let go, so a change doesn't wait on them either.
- A read of the page (`Read`, `Glance`) follows the links on the way to a few hundred paths, most of them many times over: each agent's skills folder for each skill, CC Switch's and the shared folder for each source. While the read holds the lock, `resolve` looks at each entry on the way once (`lookPart` in [`linkmemo.go`](../../internal/library/linkmemo.go)): one `Lstat`, and a `Readlink` for a link. Nothing is kept past the read, so a link made or moved on disk between two visits shows on the second. An entry that couldn't be looked at for another reason than its not being there is unknown and looked at again. One read had taken ~10,000 looks; on oxyuan's Windows machine that was ~1.3s a visit (#1771).
- A slash command file is recorded as a subagent's is (`Applied.Commands`, through the shared `syncOwnFiles`): magpie writes over or takes away only a file still exactly as it wrote it, an edited one is the user's from then on, a file of the user's own by the name is never written over (the agent gets a problem), one whose bytes are what magpie would write is taken as magpie's, and one of magpie's the user deleted is written again. A carried library carries the commands (`Bundle.Commands`: name, description, prompt, agents ticked), never `Applied.Commands`; nil keeps this computer's, and an empty list hashes as before the field (`TestCommandsLeaveTheUsersFiles`, `TestCommandsCarried`).
- A rule file is recorded the same way (`Applied.Rules`): a file of the user's own by the name, or one magpie wrote that the user edited, is never written over nor taken away, and the agent gets a problem ("has a rule of its own at …"). Kiro CLI's steering/AGENTS.md is the instructions', never a rule's. A rule that gains paths takes magpie's own Cline file away, as it would now say the wrong thing.
- Skills installed together (`InstallSkills`, `InstallMarketSkill`, `AddNewSkills`, through `installFrom` and `installChange`) install each on its own. One the library lists from the same source, or a folder in the library's own skills folder holding exactly that skill's files (left by an install that stopped before the library was saved), is had already and goes in `Result.Had`. Its files are never written, so the user's edits stay. Another skill by that name, listed or only in the folder, is left as it is. One from GitHub or another git repository then goes in beside it under a name of its own (mora1n on Discord: anthropics/skills' and openai/skills' `skill-creator` are two skills): the name with its source's owner added (`skill-creator-openai`), then owner and repository, the repository, then a number, at most 64 bytes (`freeSkillName` in [`skill_beside.go`](../../internal/library/skill_beside.go)). The library's copy of its `SKILL.md` gives that name too (`nameSkill`, only the front matter's top-level `name:` line), so an agent never sees two skills by one name; `Skill.Called` keeps the name its `SKILL.md` gave. Its hash is of the renamed copy, and a check or update compares what it fetches named the same way (`fetchedHash`), so it reads as unchanged and an update keeps the name. Being had is decided by source, not name (`hadSkill`): the same source under any name here, or a skill with no source (taken in from an agent's folder) by that name holding the very same files. A probe's candidate says which (`Candidate.Have`, `Candidate.As`), the page and the TUI show "in the library as …" or "adds as …", the market's had check matches by name only a skill with no repository (`haveSkill`), and the new-skills check no longer drops a skill because its name is taken. A repository is one source however it was added: GitHub's `owner/repo` and its git address (`git@github.com:owner/repo.git`, `https://github.com/owner/repo.git`) match, as do a git repository's https, SSH and `.git`-less addresses (`sameRepo`, `sameGitRepo`). A skill the library has from another folder of that repository that the repository no longer has is that skill moved into a group there (`skills/pdf` to `skills/documents/pdf`), and follows it (`movedIn`); another skill by that name from another folder of the same repository goes in beside it under the folder's name (`blog-writing`, `besideName`). A library skill with no source of its own is linked to the repository rather than put beside when it is traced there (`followsHere`: `From`, the skills CLI's lock, or the git checkout its folder is in, looked for in its folder and the four above it, as deep as a probe looks, in `gitRepoOf`). A copy that went in beside itself before (its `Called` is the name of a skill from the same folder of that repository, by either address, of one that moved into a group there, or of the library's own skill traced there) is folded back into that skill by `foldBeside`: on every change and on the next read of the page (`readView`, which then syncs the agents at once), so upgrading alone mends it (Refeccd on X). The copy's files, named as the skill, replace the skill's, its agents are added, and both old folders go to the backups (`TestSkillBesideItselfFoldsBack`, `TestSkillBesideItselfFoldsOnRead`, `TestGitHubRepoByGitAddressIsHad`, `TestGitHubCopyByGitAddressFoldsBack`, `TestCheckoutSkillFourDeepIsTraced`). Otherwise a skill already in the library keeps its name, folder and links. A folder of the user's own is linked as it is, so its `SKILL.md` can't be named apart: one by a taken name, or a folder that can't be read, goes in `Result.Skipped` with why (`TestSameNameFromAnotherSourceGoesInBeside`, `TestSameFilesByNameAreHad`, `TestInstallSetPutsAnotherByTheSameNameBeside`, `TestAddFromLibraryFolderKeepsIt`). The rest are installed and named in `Result.Installed`. Only when nothing was installed or had does the change fail, with the first reason.
- A skill the library has from a folder of the user's, or took in from an agent's folder, has nothing to update from, though it often came from GitHub (biubiu8802 on X: downloaded from there, then added from its folder). Installing that skill from GitHub links the two when it is that skill: traced to that repository, or traced nowhere with the same description in its SKILL.md (`followsHere`, `linkSkill` in [`skill_link.go`](../../internal/library/skill_link.go)): the library's skill keeps its name, agents and links, takes GitHub's files and GitHub as its `Source` (`skillUpdate.apply` with `adopt`, as an update of a CC Switch skill does), and a check and an update cover it from then on. The library's link to a folder elsewhere is all that goes; that folder stays as it is. A copy of the library's own whose files aren't GitHub's goes to the backups (`keepReplaced`), as `UpdateSkill` with replace keeps an edited one. One whose files are GitHub's to the file only takes the source, and so does one had by the very same files (`hadSkill`). The install names it in `Result.Linked`, and in `Result.LinkedKept` when its files were kept; a probe's candidate says so first (`Candidate.Links`), and the page tags the row "links to GitHub" and says both after the install (`skill-install-link.test.cjs`), the TUI likewise. A skill traced to another repository (`tracer.repoOf`: `From`, CC Switch's record, the skills CLI's lock, a git checkout) and an untraced one that describes something else are other skills by that name, and the GitHub one goes in beside them as above (`TestInstallSetPutsAnotherByTheSameNameBeside`); a skill from GitHub or git is never taken over (`TestFolderSkillFollowsGitHub`, `TestOwnSkillFollowsGitHubKeepsItsFiles`, `TestSkillFromElsewhereIsNotLinked`). The market's had check is unchanged: it still counts such a skill as had by its name.
@@ -123,6 +126,8 @@ Pi's extensions and packages.
```sh
go test -tags nogui ./internal/library -run 'TestPlugin|TestGit|TestInstallFromGitRepo|TestReadLooksAtEachFolderOnce|TestLinkChangedBetweenVisitsShows|TestUnreadablePartIsLookedAtAgain|TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestWSLPiMCP|TestWSLMCPSiblings|TestServer|TestHub|TestImportServer|TestCheck|TestInstructions|TestInstructionsSetLinkedToAgentsFile|TestInstructionSets|TestTakesAlma|TestAlma|TestLinkedSet|TestLinkRefused|TestSkill|TestRemoveFoundSkill|TestInstallSet|TestInstallLists|TestEverySkillAgents|TestEveryServerAgents|TestSomeServersAgents|TestRemoveServers|TestRTK|TestEnvRefs|TestDshRefRoundTrip|TestDshImportKeepsJS|TestAgentMCPFiles|TestCodeBuddyMCPFile|TestZedMCP|TestOwnServerFromElsewhereRunsThisMagpie|TestUsersOwnServerStaysAsItIs|TestCarriedOwnServerIsEachComputersMagpie|TestCarry|TestPageReadDoesntReadUnchangedSkillsAgain|TestJustWrittenSkillIsReadAgain|TestUnreadableSkillIsntRememberedAsDifferent|TestGlanceLeavesOutTheAgentsSkills|TestPluginAgent|TestPluginMCPFormatsAreWritten|TestToolsOff|TestOffList|TestHooks|TestSubagent|TestCheckRenewsMagpiesSignIn|TestCheckWSLOnlyServerInItsDistro|TestCheckWindowsServerHere|TestCheckMixedServerEachSide|TestCheckSaysSignInRanOut|TestCheckNamesAgentsSignedInThemselves|TestSignInAsTheUsersOwnApp|TestOAuthAppChecked|TestOAuthAppSecretCarried|TestGoneAgentListedToTakeOut|TestUpdateFindsSkillsRemovedUpstream|TestGoneFromNeedsTheSourceRead'
go test -tags nogui ./internal/library -run 'TestCommand'
go test -tags nogui ./internal/library -run 'TestRule'
node --test internal/gui/tests/library-rules.test.cjs
go test -tags nogui ./internal/library -run 'TestSkillOffHere|TestLocalServerNotCarried|TestPutKeepsLocalServer|TestPutSameNameAsLocal|TestServerHere'
go test -tags nogui ./internal/backup -run 'TestRestoreKeepsLocalServer|TestBackupFileCarriesSubagents|TestBackupFileCarriesHooks'
go test -tags nogui ./internal/library -run 'TestHandOver|TestSharedUnderAnotherName|TestSharedAgentsSkills'
+3
View File
@@ -85,6 +85,9 @@ func backupCmd(args []string) error {
if l.Commands != nil && len(*l.Commands) > 0 {
fmt.Printf(", %d slash commands", len(*l.Commands))
}
if l.Rules != nil && len(*l.Rules) > 0 {
fmt.Printf(", %d rules", len(*l.Rules))
}
if l.Hooks != nil && len(*l.Hooks) > 0 {
fmt.Printf(", %d hooks", len(*l.Hooks))
}
+6 -1
View File
@@ -988,6 +988,11 @@ func hashes(b backup.Bundle) map[string]string {
c.Commands = nil
lib = &c
}
if lib != nil && lib.Rules != nil && len(*lib.Rules) == 0 { // as before them, without one
c := *lib
c.Rules = nil
lib = &c
}
if lib != nil && lib.Hooks != nil && len(*lib.Hooks) == 0 { // as before them, without one
c := *lib
c.Hooks = nil
@@ -1066,7 +1071,7 @@ func unset(b backup.Bundle, p string) bool {
}
}
return len(l.MCP) == 0 && len(l.Skills) == 0 &&
(l.Subagents == nil || len(*l.Subagents) == 0) && (l.Commands == nil || len(*l.Commands) == 0) && (l.Hooks == nil || len(*l.Hooks) == 0) &&
(l.Subagents == nil || len(*l.Subagents) == 0) && (l.Commands == nil || len(*l.Commands) == 0) && (l.Rules == nil || len(*l.Rules) == 0) && (l.Hooks == nil || len(*l.Hooks) == 0) &&
(l.Bili == nil || strings.TrimSpace(*l.Bili) == "") && l.ClaudePlugins == nil && (l.Plugins == nil || len(*l.Plugins) == 0)
}
return false
+3 -1
View File
@@ -5,7 +5,7 @@
// The sections a page's list is cut into, by tab id: a section none of whose
// tabs shows has no name (app.js navSubs), as does a list of one section.
window.NAV_SUB_GROUPS = {
library: { instructions: "Every agent", memory: "Every agent", mcp: "Every agent", skills: "Every agent", hooks: "Every agent", env: "Every agent", subagents: "Every agent", commands: "Every agent", plugins: "One agent", pi: "One agent", rtk: "magpie", bili: "magpie" },
library: { instructions: "Every agent", memory: "Every agent", mcp: "Every agent", skills: "Every agent", hooks: "Every agent", env: "Every agent", subagents: "Every agent", commands: "Every agent", rules: "Every agent", plugins: "One agent", pi: "One agent", rtk: "magpie", bili: "magpie" },
};
// the tabs [tab, its place in the strip, its section's name where one starts],
// in sections in order, each in the strip's order
@@ -57,6 +57,8 @@ window.NAV_SUB_IC = {
subagents: "M6 3a2.2 2.2 0 1 0 0 4.4A2.2 2.2 0 0 0 6 3z M2 13c.5-2.2 2-3.4 4-3.4s3.5 1.2 4 3.4 M11.5 7.5a1.5 1.5 0 1 0 0 .01 M10.2 12.5c.3-1.3 1.1-2 2.3-2s1.6.5 1.9 1.4",
// a slash in a key, as a command is typed
commands: "M4.5 3h7A1.5 1.5 0 0 1 13 4.5v7a1.5 1.5 0 0 1-1.5 1.5h-7A1.5 1.5 0 0 1 3 11.5v-7A1.5 1.5 0 0 1 4.5 3z M9.6 5.4l-3.2 5.2",
// a page with a check: a rule the agent keeps to
rules: "M4 2.5h8v11H4z M6 5.5h4 M6 8h4 M6 10.8l1 1 2-2",
rtk: "M2.5 3.5h11v9h-11z M5 6.5l1.5 1.5L5 9.5 M8.5 9.5h2.5",
bili: "M8 2v4 M6 4.2 8 6l2-1.8 M8 14v-4 M6 11.8 8 10l2 1.8 M3 8h10",
pi: "M8 2.5l5 2.5v6L8 13.5 3 11V5z M3 5l5 2.5L13 5 M8 7.5v6",
+144 -5
View File
@@ -58,6 +58,8 @@ magpie.plugin("library", (ctx) => {
subagent: "M6 3a2.2 2.2 0 1 0 0 4.4A2.2 2.2 0 0 0 6 3z M2 13c.5-2.2 2-3.4 4-3.4s3.5 1.2 4 3.4 M11.5 7.5a1.5 1.5 0 1 0 0 .01 M10.2 12.5c.3-1.3 1.1-2 2.3-2s1.6.5 1.9 1.4",
// a slash in a key, as a command is typed
command: "M4.5 3h7A1.5 1.5 0 0 1 13 4.5v7a1.5 1.5 0 0 1-1.5 1.5h-7A1.5 1.5 0 0 1 3 11.5v-7A1.5 1.5 0 0 1 4.5 3z M9.6 5.4l-3.2 5.2",
// a page with a ruled line and a check: a rule the agent keeps to
rule: "M4 2.5h8v11H4z M6 5.5h4 M6 8h4 M6 10.8l1 1 2-2",
// a clock with an arrow going back round it, as macOS draws backups
backup: "M3.2 8a4.8 4.8 0 1 0 1.4-3.4 M2.8 2.6v2.4h2.4 M8 5.3V8l1.9 1.2",
power: "M8 2.5v5 M4.7 4.6a4.8 4.8 0 1 0 6.6 0",
@@ -569,7 +571,7 @@ magpie.plugin("library", (ctx) => {
// What All did, said of the item: on for how many of the agents it went
// to, and which of them couldn't be given it, and why.
function reportAll(v, me) {
const what = ({ servers: "mcp:", hooks: "hook:", env: "env:", subagents: "subagent:", commands: "command:" }[me.list] || "skill:") + me.name;
const what = ({ servers: "mcp:", hooks: "hook:", env: "env:", subagents: "subagent:", commands: "command:", rules: "rule:" }[me.list] || "skill:") + me.name;
const shown = [...me.box.children].filter((x) => isChip(x) && !cannot(x)).flatMap((x) => idsOf(x).filter((id) => !x.dataset.fixed?.split("\t").includes(id)));
const n = shown.filter((id) => me.want.includes(id)).length;
const bad = (v.result?.problems || []).filter((p) => p.what === what && shown.includes(p.agent));
@@ -855,7 +857,7 @@ magpie.plugin("library", (ctx) => {
ul.append(li);
}
if (ul.childElementCount) card.append(ul);
const tabNames = { instructions: t("Instructions"), mcp: t("MCP servers"), skills: t("Skills"), hooks: t("Hooks"), env: t("Environment variables"), subagents: t("Subagents"), commands: t("Slash commands"), plugins: t("Claude plugins") };
const tabNames = { instructions: t("Instructions"), mcp: t("MCP servers"), skills: t("Skills"), hooks: t("Hooks"), env: t("Environment variables"), subagents: t("Subagents"), commands: t("Slash commands"), rules: t("Rules"), plugins: t("Claude plugins") };
const others = Object.keys(away).filter((k) => k in tabNames);
if (others.length) {
const more = el("div", "lib-problems-away");
@@ -891,7 +893,7 @@ magpie.plugin("library", (ctx) => {
}
// the tab a problem is about; "" is one shown on every tab
function problemTab(what) {
return { instructions: "instructions", mcp: "mcp", skill: "skills", skills: "skills", project: "skills", hook: "hooks", hooks: "hooks", env: "env", subagent: "subagents", command: "commands", plugin: "plugins" }[what.split(":")[0]] || "";
return { instructions: "instructions", mcp: "mcp", skill: "skills", skills: "skills", project: "skills", hook: "hooks", hooks: "hooks", env: "env", subagent: "subagents", command: "commands", rule: "rules", plugin: "plugins" }[what.split(":")[0]] || "";
}
function problemWhat(what) {
const [kind, ...rest] = what.split(":");
@@ -902,6 +904,7 @@ magpie.plugin("library", (ctx) => {
if (kind === "hook") return t("Hook {name}", { name });
if (kind === "subagent") return t("Subagent {name}", { name });
if (kind === "command") return t("Slash command {name}", { name: "/" + name });
if (kind === "rule") return t("Rule {name}", { name });
if (kind === "project") return name ? t("Skill {name}", { name }) : t("The project");
return what;
}
@@ -1012,6 +1015,7 @@ magpie.plugin("library", (ctx) => {
["env", t("Environment variables") + n("env")],
["subagents", t("Subagents") + n("subagents")],
["commands", t("Slash commands") + n("commands")],
["rules", t("Rules") + n("rules")],
["plugins", t("Claude plugins") + n("plugins")],
["rtk", "RTK"],
["bili", "billion-context"],
@@ -1075,7 +1079,7 @@ magpie.plugin("library", (ctx) => {
if (agentless() && (!tabPicked || !AGENTLESS_TABS.includes(tab))) tab = "mcp";
// Pi's tab only while a Pi is here; the pick is kept for when one is
else if (tab === "pi" && !hasPi()) tab = "instructions";
const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length, env: (lib.env || []).length, subagents: (lib.subagents || []).length, commands: (lib.commands || []).length, plugins: (lib.plugins || []).length });
const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length, env: (lib.env || []).length, subagents: (lib.subagents || []).length, commands: (lib.commands || []).length, rules: (lib.rules || []).length, plugins: (lib.plugins || []).length });
page.append(head);
head.classList.toggle("stuck", top > 0);
// what changed in a tab is drawn in place: only another tab (or the
@@ -1096,6 +1100,7 @@ magpie.plugin("library", (ctx) => {
else if (tab === "env") renderEnv(body);
else if (tab === "subagents") renderSubagents(body);
else if (tab === "commands") renderCommands(body);
else if (tab === "rules") renderRules(body);
else if (tab === "plugins") renderPlugins(body);
else renderSkills(body);
page.append(body);
@@ -1132,7 +1137,7 @@ magpie.plugin("library", (ctx) => {
if (JSON.stringify(follow) !== JSON.stringify(was) && lib && page.isConnected) render();
}
function followNote() {
const part = tab === "memory" ? "memory" : ["instructions", "mcp", "skills", "hooks", "env", "subagents", "commands", "plugins"].includes(tab) ? "library" : "";
const part = tab === "memory" ? "memory" : ["instructions", "mcp", "skills", "hooks", "env", "subagents", "commands", "rules", "plugins"].includes(tab) ? "library" : "";
if (!part || !follow?.[part]) return null;
const p = el("p", "lib-intro lib-follow", t("This computer follows the server: what you change here is replaced by the next sync.") + " ");
const go = button(t("Sync settings"), "link", (e) => openSettingsAt(e, "sync", "#syncList .sync-follows"));
@@ -5454,6 +5459,140 @@ magpie.plugin("library", (ctx) => {
if (!c) requestAnimationFrame(() => name.focus());
}
// ---------- rules ----------
// A rule (JonahFu on X) is a Markdown file of instructions an agent reads
// from its own folder of rules: Claude Code's ~/.claude/rules, Cline's
// rules, Kiro CLI's steering. One kept to some files (paths) is read
// only when the agent works on one of them, by those that can; Cline
// reads every rule always, so it isn't given one with paths (rules.go).
const ruleAgentOf = (id) => (lib.ruleAgents || []).find((x) => x.id === id);
const ruleAgents = () => shownAgents().filter((a) => ruleAgentOf(a.id));
// why a can't be given a rule, or ""
const ruleBlocked = (a) => {
const ra = ruleAgentOf(a.id);
if (ra && !ra.no) return "";
if (ra?.wsl) return t("magpie gives rules only to agents on this computer, not yet to {agent} in WSL", { agent: a.name });
return t("{agent} reads no rules magpie can write", { agent: a.name });
};
// the agents of ids that read every rule always
const noRulePaths = (all, ids) => all.filter((a) => ids.includes(a.id) && !ruleBlocked(a) && !ruleAgentOf(a.id).paths);
const rulePaths = (v) => [...new Set(v.split("\n").map((x) => x.trim()).filter(Boolean))];
function renderRules(body) {
body.append(intro(t("A rule is a Markdown file of instructions an agent reads from its own folder of rules. Add it once and magpie writes it into each agent you pick.")));
const all = ruleAgents();
const rules = lib.rules || [];
if (!rules.length) {
body.append(empty(t("No rules in the library yet"), t("Add one, and pick the agents that get it."), button(t("+ Add rule"), "action", () => editRule(null))));
} else {
const list = el("div", "list lib-list");
list.append(...[...rules].sort((a, b) => a.name.localeCompare(b.name)).map((r) => ruleRow(r, all)));
body.append(list);
const after = el("div", "after-list");
after.append(button(t("+ Add rule"), "", () => editRule(null)));
body.append(after);
}
const skip = all.filter((a) => ruleAgentOf(a.id).no);
if (skip.length) body.append(el("p", "lib-aside lib-rules-no", t("magpie can't give rules to {agents}: their chips are greyed, and say why.", { agents: skip.map((a) => a.name).join(", ") })));
}
function ruleRow(r, all) {
const row = el("div", "row lib-row click lib-rule");
const who = el("div", "who");
who.append(el("div", "name mono", r.name));
const sub = r.paths?.length ? r.paths.join(" · ") : (r.body || "").split("\n").map((x) => x.replace(/^#+\s*/, "").trim()).find(Boolean) || "";
if (sub) who.append(el("div", "lib-ruledesc" + (r.paths?.length ? " mono" : ""), sub));
row.append(glyph(GLYPH.rule), who,
agentChips(all, r.agents, chipsChange("rules/agents", r.name, "rules", (x) => ruleRow(x, all)), { problems: r.problems, blocked: ruleBlocked, all: true }));
row.onclick = () => editRule(r);
row.title = t("Edit {name}", { name: r.name });
return row;
}
function editRule(r) {
const all = ruleAgents();
const d = r ? { name: r.name, paths: (r.paths || []).join("\n"), body: r.body, agents: [...(r.agents || [])] }
: { name: "", paths: "", body: "", agents: all.filter((a) => !ruleBlocked(a)).map((a) => a.id) };
const ed = el("div", "editor lib-editor lib-ruleedit");
const head = el("div", "ehead");
head.append(glyph(GLYPH.rule), el("b", "", r ? r.name : t("New rule")));
ed.append(head);
const err = el("div", "editor-error");
const name = field2(d.name, t("e.g. testing"), (v) => { d.name = v.trim(); });
name.classList.add("mono");
ed.append(...field(t("Name"), name, t("The file's name: lowercase letters, digits, - and _")));
const box = (cls, value, placeholder, rows, max) => {
const ta = el("textarea", "lib-text small " + cls);
ta.value = value;
ta.placeholder = placeholder;
ta.spellcheck = false;
ta.rows = rows;
ta.maxLength = max;
ta.onkeydown = (e) => { e.stopPropagation(); if (e.isComposing || e.keyCode === 229) return; if (e.key === "Escape") closeLibModal(); };
autosize(ta, rows * 20);
return ta;
};
const text = box("lib-rulebody", d.body, t("e.g. Run the tests before saying a change works."), 6, 100000);
text.oninput = () => { d.body = text.value; };
ed.append(...field(t("Rule"), text));
const agentsBox = el("div");
ed.append(...field(t("Agents"), agentsBox));
// where each agent has it: a file to open, or to edit with an agent
const files = el("div", "lib-rulefiles");
for (const [id, f] of Object.entries(r?.files || {}).sort(([a], [b]) => nameOf(a).localeCompare(nameOf(b)))) {
const line = el("div", "lib-rulefile");
line.append(el("span", "note", nameOf(id)), pathLink(f));
files.append(line);
}
if (files.childElementCount) ed.append(...field(t("Files"), files));
// kept to some files: rarely, so under Advanced, open while it is
const more = el("details", "more advanced lib-rulemore");
more.open = !!d.paths;
more.append(el("summary", "", t("Advanced")));
const inner = el("div", "inner");
const paths = box("lib-rulepaths mono", d.paths, "src/api/**/*.ts", 2, 25000);
const pathsHint = el("div", "hint lib-rulehint-paths");
paths.oninput = () => { d.paths = paths.value; drawHint(); };
const [ml, mw] = field(t("Only for files"), paths, t("One glob a line. Empty: read in every conversation"));
mw.append(pathsHint);
inner.append(ml, mw);
more.append(inner);
ed.append(more, err);
function drawHint() {
const no = rulePaths(d.paths).length ? noRulePaths(all, d.agents) : [];
pathsHint.textContent = no.length ? t("Not written for {agents}: they read every rule in every conversation", { agents: no.map((a) => a.name).join(", ") }) : "";
}
function drawAgents() {
agentsBox.replaceChildren(agentChips(all, d.agents, (next) => { d.agents = next; drawAgents(); }, { names: true, blocked: ruleBlocked, all: true }));
drawHint();
}
drawAgents();
const bar = el("div", "bar");
if (r) bar.append(button(t("Remove from the library"), "danger", async () => {
if (!await confirmRemoval(r.name, "It will be removed from the library and the agents it was given to.")) return;
if (await change("rules/remove", { name: r.name }, t("{name} is out of the library and the agents it was given to", { name: r.name }))) closeLibModal(true);
}));
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal));
const save = async () => {
err.textContent = "";
try {
const rule = { name: d.name, paths: rulePaths(d.paths), body: d.body, agents: d.agents.filter((id) => !ruleBlocked(agentOf(id) || { id })) };
take(await api("library/rules/save", { old: r ? r.name : "", rule }));
report(lib.result, r ? t("{name} saved", { name: rule.name }) : "");
closeLibModal(true);
render();
} catch (e) { err.textContent = e.message; }
};
bar.append(button(r ? t("Save") : t("Add"), "primary", save));
ed.append(bar);
const original = JSON.stringify(d);
modal = { save, dirty: () => JSON.stringify(d) !== original };
openLib(ed);
if (!r) requestAnimationFrame(() => name.focus());
}
// ---------- Claude plugins ----------
// A Claude Code plugin kept as one item (FakeshadowzZ on X): its skills,
@@ -192,6 +192,20 @@ magpie.strings({
"{agents} take only $ARGUMENTS, all the words at once: a command that uses $1, $2… isn't written for them.": "{agents} 只支持 $ARGUMENTS(一次取全部参数):用到 $1、$2… 的命令不会写入它们。",
"magpie can't give slash commands to {agents}: their chips are greyed, and say why.": "magpie 无法给 {agents} 写入斜杠命令:它们的标签为灰色,并说明了原因。",
"New slash command": "新建斜杠命令",
"Rule {name}": "规则 {name}",
"magpie gives rules only to agents on this computer, not yet to {agent} in WSL": "magpie 目前只给这台电脑上的 Agent 写规则,还不支持 WSL 里的 {agent}",
"{agent} reads no rules magpie can write": "{agent} 不读取 magpie 能写的规则",
"A rule is a Markdown file of instructions an agent reads from its own folder of rules. Add it once and magpie writes it into each agent you pick.": "规则是一份 Markdown 指令文件,Agent 会从自己的规则文件夹里读取。在这里添加一次,magpie 会把它写进你选中的每个 Agent。",
"No rules in the library yet": "资源库里还没有规则",
"+ Add rule": "+ 添加规则",
"magpie can't give rules to {agents}: their chips are greyed, and say why.": "magpie 无法给 {agents} 写规则:它们的标签是灰色的,并说明了原因。",
"New rule": "新建规则",
"e.g. testing": "例如 testing",
"The file's name: lowercase letters, digits, - and _": "文件名:小写字母、数字、- 和 _",
"e.g. Run the tests before saying a change works.": "例如:说改动可用之前先跑测试。",
"Only for files": "仅用于这些文件",
"One glob a line. Empty: read in every conversation": "每行一个 glob。留空:每次对话都读取",
"Not written for {agents}: they read every rule in every conversation": "不会写给 {agents}:它们每次对话都会读取所有规则",
"e.g. review": "例如 review",
"Typed as /name: lowercase letters, digits, - and _": "以 /名称 输入:小写字母、数字、- 和 _",
"e.g. Review a diff for bugs": "例如 检查一个 diff 中的 bug",
@@ -1305,6 +1319,20 @@ magpie.strings({
"{agents} take only $ARGUMENTS, all the words at once: a command that uses $1, $2… isn't written for them.": "{agents} 只支援 $ARGUMENTS(一次取全部參數):用到 $1、$2… 的命令不會寫入它們。",
"magpie can't give slash commands to {agents}: their chips are greyed, and say why.": "magpie 無法給 {agents} 寫入斜線命令:它們的標籤為灰色,並說明了原因。",
"New slash command": "新增斜線命令",
"Rule {name}": "規則 {name}",
"magpie gives rules only to agents on this computer, not yet to {agent} in WSL": "magpie 目前只給這台電腦上的 Agent 寫規則,還不支援 WSL 裡的 {agent}",
"{agent} reads no rules magpie can write": "{agent} 不讀取 magpie 能寫的規則",
"A rule is a Markdown file of instructions an agent reads from its own folder of rules. Add it once and magpie writes it into each agent you pick.": "規則是一份 Markdown 指令檔,Agent 會從自己的規則資料夾裡讀取。在這裡新增一次,magpie 會把它寫進你選取的每個 Agent。",
"No rules in the library yet": "資源庫裡還沒有規則",
"+ Add rule": "+ 新增規則",
"magpie can't give rules to {agents}: their chips are greyed, and say why.": "magpie 無法給 {agents} 寫規則:它們的標籤是灰色的,並說明了原因。",
"New rule": "新增規則",
"e.g. testing": "例如 testing",
"The file's name: lowercase letters, digits, - and _": "檔名:小寫字母、數字、- 和 _",
"e.g. Run the tests before saying a change works.": "例如:說改動可用之前先跑測試。",
"Only for files": "僅用於這些檔案",
"One glob a line. Empty: read in every conversation": "每行一個 glob。留空:每次對話都讀取",
"Not written for {agents}: they read every rule in every conversation": "不會寫給 {agents}:它們每次對話都會讀取所有規則",
"e.g. review": "例如 review",
"Typed as /name: lowercase letters, digits, - and _": "以 /名稱 輸入:小寫字母、數字、- 和 _",
"e.g. Review a diff for bugs": "例如 檢查一個 diff 中的 bug",
@@ -2418,6 +2446,20 @@ magpie.strings({
"{agents} take only $ARGUMENTS, all the words at once: a command that uses $1, $2… isn't written for them.": "{agents} は $ARGUMENTS(すべての引数をまとめて)のみ対応です:$1、$2… を使うコマンドは書き込まれません。",
"magpie can't give slash commands to {agents}: their chips are greyed, and say why.": "magpie は {agents} にスラッシュコマンドを書き込めません:チップはグレー表示で、理由が表示されます。",
"New slash command": "新しいスラッシュコマンド",
"Rule {name}": "ルール {name}",
"magpie gives rules only to agents on this computer, not yet to {agent} in WSL": "magpie がルールを書けるのはこのコンピュータ上のエージェントだけで、WSL の {agent} にはまだ書けません",
"{agent} reads no rules magpie can write": "{agent} は magpie が書けるルールを読みません",
"A rule is a Markdown file of instructions an agent reads from its own folder of rules. Add it once and magpie writes it into each agent you pick.": "ルールは、エージェントが自分のルールフォルダから読む Markdown の指示ファイルです。ここで一度追加すれば、magpie が選んだ各エージェントに書き込みます。",
"No rules in the library yet": "ライブラリにはまだルールがありません",
"+ Add rule": "+ ルールを追加",
"magpie can't give rules to {agents}: their chips are greyed, and say why.": "magpie は {agents} にルールを書けません。チップはグレー表示で、理由が表示されます。",
"New rule": "新しいルール",
"e.g. testing": "例: testing",
"The file's name: lowercase letters, digits, - and _": "ファイル名:英小文字、数字、- と _",
"e.g. Run the tests before saying a change works.": "例:変更が動くと言う前にテストを実行する。",
"Only for files": "対象のファイル",
"One glob a line. Empty: read in every conversation": "1 行に 1 つの glob。空なら毎回の会話で読まれます",
"Not written for {agents}: they read every rule in every conversation": "{agents} には書かれません。毎回の会話ですべてのルールを読むためです",
"e.g. review": "例:review",
"Typed as /name: lowercase letters, digits, - and _": "/名前 で入力:小文字、数字、- と _",
"e.g. Review a diff for bugs": "例:diff のバグを確認する",
@@ -3531,6 +3573,20 @@ magpie.strings({
"{agents} take only $ARGUMENTS, all the words at once: a command that uses $1, $2… isn't written for them.": "{agents} kennen nur $ARGUMENTS, alle Wörter auf einmal: ein Befehl mit $1, $2… wird für sie nicht geschrieben.",
"magpie can't give slash commands to {agents}: their chips are greyed, and say why.": "magpie kann {agents} keine Slash-Befehle geben: ihre Chips sind ausgegraut und sagen, warum.",
"New slash command": "Neuer Slash-Befehl",
"Rule {name}": "Regel {name}",
"magpie gives rules only to agents on this computer, not yet to {agent} in WSL": "magpie gibt Regeln bisher nur Agenten auf diesem Computer, noch nicht {agent} in WSL",
"{agent} reads no rules magpie can write": "{agent} liest keine Regeln, die magpie schreiben kann",
"A rule is a Markdown file of instructions an agent reads from its own folder of rules. Add it once and magpie writes it into each agent you pick.": "Eine Regel ist eine Markdown-Datei mit Anweisungen, die ein Agent aus seinem eigenen Regelordner liest. Einmal hinzugefügt, schreibt magpie sie in jeden gewählten Agenten.",
"No rules in the library yet": "Noch keine Regeln in der Bibliothek",
"+ Add rule": "+ Regel hinzufügen",
"magpie can't give rules to {agents}: their chips are greyed, and say why.": "magpie kann {agents} keine Regeln geben: Ihre Chips sind ausgegraut und sagen, warum.",
"New rule": "Neue Regel",
"e.g. testing": "z. B. testing",
"The file's name: lowercase letters, digits, - and _": "Der Dateiname: Kleinbuchstaben, Ziffern, - und _",
"e.g. Run the tests before saying a change works.": "z. B. Führe die Tests aus, bevor du sagst, dass eine Änderung funktioniert.",
"Only for files": "Nur für Dateien",
"One glob a line. Empty: read in every conversation": "Ein Glob pro Zeile. Leer: in jedem Gespräch gelesen",
"Not written for {agents}: they read every rule in every conversation": "Nicht für {agents} geschrieben: Sie lesen jede Regel in jedem Gespräch",
"e.g. review": "z. B. review",
"Typed as /name: lowercase letters, digits, - and _": "Eingegeben als /Name: Kleinbuchstaben, Ziffern, - und _",
"e.g. Review a diff for bugs": "z. B. Einen Diff auf Fehler prüfen",
@@ -976,3 +976,13 @@ input.lib-memq:focus, input.lib-memtags:focus, input.lib-memwhy:focus { border-c
.lib-bili-phil .lib-acts { justify-content: flex-end; }
/* the servers turned off, folded below the ones on, as Providers' */
#view-library .lib-offhead .fold:disabled { cursor: default; opacity: 1; }
.lib-rule > .who { flex-basis: 240px; }
.lib-rule .lib-ruledesc { font-size: 12px; line-height: 1.45; color: var(--fg-2); white-space: normal; overflow-wrap: anywhere; margin-top: 1px; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; }
.lib-ruleedit .lib-rulebody, .lib-ruleedit .lib-rulepaths { width: 100%; box-sizing: border-box; resize: none; font: inherit; font-size: 12.5px; line-height: 1.45; }
.lib-ruleedit .lib-rulepaths { font-family: var(--code-font, var(--code)); font-size: 12px; }
.lib-ruleedit .lib-rulebody { max-height: 40vh; overflow-y: auto; }
.lib-ruleedit .hint:empty { display: none; }
.lib-rulefiles { display: grid; gap: 4px; min-width: 0; }
.lib-rulefile { display: flex; align-items: baseline; gap: 8px; min-width: 0; flex-wrap: wrap; }
.lib-rulefile > .note { flex: none; font-size: 12px; color: var(--fg-2); }
.lib-rulefile > .lib-path { min-width: 0; white-space: normal; overflow-wrap: anywhere; }
+12
View File
@@ -161,6 +161,11 @@ func revealable(v *library.View) []string {
for _, s := range v.FoundSkills {
out = append(out, s.Link, s.Shared)
}
for _, r := range v.Rules {
for _, f := range r.Files {
out = append(out, f)
}
}
for _, p := range v.Projects {
out = append(out, p.Dir)
for _, e := range p.Placed {
@@ -713,6 +718,7 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
// a subagent saved (#2283)
Subagent library.Subagent
Command library.Command
Rule library.Rule
Agent string // the agent whose own skill is in the library's way
App string // the app the MCP hub is added to (servers/hub-open)
Note string // what the MCP router says of itself (servers/hub-note), or a skill's note (skills/note)
@@ -828,6 +834,12 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
res, err = library.CommandAgentsSet(in.Name, in.Agents)
case "commands/remove":
res, err = library.RemoveCommands([]string{in.Name})
case "rules/save":
res, err = library.SaveRule(in.Old, in.Rule)
case "rules/agents":
res, err = library.RuleAgentsSet(in.Name, in.Agents)
case "rules/remove":
res, err = library.RemoveRules([]string{in.Name})
case "commands/import":
res, err = library.ImportCommands(in.Paths)
case "subagents/import":
+2 -2
View File
@@ -161,11 +161,11 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const row = (name) => v.locator(".lib-command").filter({ has: page.locator(".name", { hasText: new RegExp("^/" + name + "$") }) });
const agentsOf = (name) => state.commands.find((s) => s.name === name)?.agents;
// the tab, with its count, between Subagents and Claude plugins
// the tab, with its count, between Subagents and Rules
const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim());
const at = tabs.indexOf(w("Slash commands") + " · 1");
assert(at > 0, tabs.join("|"));
assert.deepEqual(tabs.slice(at - 1, at + 2), [w("Subagents"), w("Slash commands") + " · 1", w("Claude plugins")]);
assert.deepEqual(tabs.slice(at - 1, at + 2), [w("Subagents"), w("Slash commands") + " · 1", w("Rules")]);
assert.equal((await row("review").locator(".lib-commanddesc").textContent()).trim(), LONG);
await wrapped(page, 420);
// Gemini takes only $ARGUMENTS, and review uses $1
+7 -7
View File
@@ -79,14 +79,14 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
t.after(() => context.close());
await page.waitForFunction(() => document.querySelector("#side .nav-sub .nav-sl"));
const rows = await order(page);
assert.equal(rows.length, 15, rows.join(","));
assert.equal(rows.length, 16, rows.join(","));
assert.deepEqual(rows.filter((x) => x[0] === "#"), ["#" + a, "#" + b, "#" + c]);
// the order inside each: the shared eight, then Claude's and Pi's, then magpie's
// the order inside each: the shared nine, then Claude's and Pi's, then magpie's
assert.equal(rows[0], "#" + a);
assert.equal(rows[9], "#" + b);
assert.equal(rows[12], "#" + c);
assert.equal(rows[10], "#" + b);
assert.equal(rows[13], "#" + c);
// a name is no tab: picking by keyboard skips it, the rows are still the tabs
assert.equal(await page.locator("#side .nav-sub .nav-s").count(), 12);
assert.equal(await page.locator("#side .nav-sub .nav-s").count(), 13);
// the page's own strip is as it was: no names in it
assert.equal(await page.locator("#view-library .lib-tabs .nav-sl").count(), 0);
// the name is quiet: the muted ink, no left border, no ground
@@ -105,11 +105,11 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await page.waitForFunction(() => document.querySelector("#side .nav-sub .nav-sl"));
// Claude plugins and Pi packages hidden: "One agent" has nothing to list
await page.evaluate(() => { for (const b of document.querySelectorAll("#view-library .lib-tabs button")) if (["plugins", "pi"].includes(b.dataset.seg)) b.hidden = true; navSubs(); });
await page.waitForFunction(() => !document.querySelector("#side .nav-sub .nav-s[data-of]") || document.querySelectorAll("#side .nav-sub .nav-s").length === 10);
await page.waitForFunction(() => !document.querySelector("#side .nav-sub .nav-s[data-of]") || document.querySelectorAll("#side .nav-sub .nav-s").length === 11);
assert.deepEqual(await heads(page), ["Every agent", "magpie"]);
// one section left: no names at all
await page.evaluate(() => { for (const b of document.querySelectorAll("#view-library .lib-tabs button")) if (["rtk", "bili"].includes(b.dataset.seg)) b.hidden = true; navSubs(); });
await page.waitForFunction(() => document.querySelectorAll("#side .nav-sub .nav-s").length === 8);
await page.waitForFunction(() => document.querySelectorAll("#side .nav-sub .nav-s").length === 9);
assert.deepEqual(await heads(page), []);
});
+1 -1
View File
@@ -152,7 +152,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// the tab, with its count, between Skills and Subagents
const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim());
assert.deepEqual(tabs.slice(3, 10), [w("Skills"), w("Hooks") + " · 2", w("Environment variables"), w("Subagents"), w("Slash commands"), w("Claude plugins"), "RTK"]);
assert.deepEqual(tabs.slice(3, 11), [w("Skills"), w("Hooks") + " · 2", w("Environment variables"), w("Subagents"), w("Slash commands"), w("Rules"), w("Claude plugins"), "RTK"]);
// each hook says when it runs, in words, and what it runs
assert.equal((await row("fmt").locator(".lib-hookev").textContent()).trim(), w("After a tool runs") + " · " + w("File edits"));
assert.equal((await row("bark").locator(".lib-hookev").textContent()).trim(), w("When a turn ends"));
+2 -2
View File
@@ -73,7 +73,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(await skel.getAttribute("aria-busy"), "true");
const tabs = v.locator(".lib-head .lib-tabs .opt");
assert.deepEqual(await tabs.allTextContents(), ["Instructions", "Memory", "MCP servers", "Skills", "Hooks", "Environment variables", "Subagents", "Slash commands", "Claude plugins", "RTK", "billion-context"]);
assert.deepEqual(await tabs.allTextContents(), ["Instructions", "Memory", "MCP servers", "Skills", "Hooks", "Environment variables", "Subagents", "Slash commands", "Rules", "Claude plugins", "RTK", "billion-context"]);
assert.equal(await v.locator(".lib-tabs .opt.on").textContent(), "Skills");
assert.ok(await v.locator(".lib-head .lib-more").isDisabled(), "the folder waits for the library");
// Skills in outline: rows with a switch, no section heading
@@ -90,7 +90,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
open();
await v.locator(".lib-head .lib-more:not([disabled])").waitFor();
assert.equal(await v.locator(".lib-skel").count(), 0, "the outline goes");
assert.deepEqual(await v.locator(".lib-tabs .opt").allTextContents(), ["Instructions", "Memory", "MCP servers · 1", "Skills · 1", "Hooks", "Environment variables", "Subagents", "Slash commands", "Claude plugins", "RTK", "billion-context", "Pi packages"]);
assert.deepEqual(await v.locator(".lib-tabs .opt").allTextContents(), ["Instructions", "Memory", "MCP servers · 1", "Skills · 1", "Hooks", "Environment variables", "Subagents", "Slash commands", "Rules", "Claude plugins", "RTK", "billion-context", "Pi packages"]);
assert.equal(await v.locator(".lib-tabs .opt.on").textContent(), "Instructions");
assert.equal(await v.locator(".lib-head .lib-more").getAttribute("title"), "~/.magpie/library");
const after = await v.locator(".lib-tabs").boundingBox();
+257
View File
@@ -0,0 +1,257 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// JonahFu on X: Rules, a Library tab after Slash commands. A rule (a
// name and a Markdown body, kept to some files by globs if wanted) is
// kept once and given to the agents that read a folder of rules: Claude
// Code, Cline and Kiro CLI. Its row shows the name and its paths, or its
// first line. Agents magpie can't give rules to (an agent in WSL) have
// greyed chips that say why, post nothing, and an aside names them. A
// row's chip posts rules/agents. Add opens the editor with every agent
// that can take one picked: the paths are folded under Advanced; a hint
// names the agents picked that read every rule always (Cline) while the
// rule has paths; Save posts rules/save with one glob a line. A row
// opens it again, Advanced open when it has paths, with each agent's
// file as a path to show; Remove asks first, then posts rules/remove.
// At 420 and 1100 wide in en, zh, zh-TW, ja and de: no sideways scroll,
// and what each click pressed stays where it was on the screen.
// 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 { strings } = require("./strings.cjs");
const assets = path.resolve(__dirname, "../assets");
const HOME = "/Users/jonah";
const agent = (id, name, more = {}) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json`, ...more });
const WSL = "claude@wsl:Ubuntu";
const RULE_AGENTS = [
{ id: "claude", dir: `${HOME}/.claude/rules`, paths: true },
{ id: "cline", dir: `${HOME}/.cline/rules` },
{ id: "kiro-cli", dir: `${HOME}/.kiro/steering`, paths: true },
{ id: WSL, wsl: true, no: "magpie gives no rules to an agent in WSL yet" },
];
const API = `${HOME}/.claude/rules/api.md`;
const rule = (name, paths, body, agents, files) => ({ name, paths, body, agents, files });
const lib = (rules) => ({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [agent("claude", "Claude Code"), agent("codex", "Codex"), agent("cline", "Cline"), agent("kiro-cli", "Kiro CLI"), agent(WSL, "Claude Code (Ubuntu)")],
instructions: { agents: [] }, servers: [], skills: [], foundServers: [], projects: [], foundSkills: [], problems: [],
hooks: [], hookAgents: [], subagents: [], subagentAgents: [], commands: [], commandAgents: [], rules, ruleAgents: RULE_AGENTS,
});
let I18N;
// the words the page says in lang; a string missing from a language fails
function tr(lang, key, vars = {}) {
let s = key;
if (lang !== "en") {
assert.equal(typeof I18N[lang][key], "string", `${lang} has no ${JSON.stringify(key)}`);
s = I18N[lang][key];
}
return s.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m));
}
function server(lang, state, posts) {
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
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 json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/library") return json(lib(state.rules));
if (url.pathname.startsWith("/api/library/") && req.method() === "POST") {
const body = req.postDataJSON(), what = url.pathname.replace("/api/library/", "");
posts.push({ what, body });
if (what === "reveal") return json({});
if (what === "rules/agents") state.rules = state.rules.map((x) => (x.name === body.name ? { ...x, agents: body.agents } : x));
if (what === "rules/save") state.rules = [...state.rules.filter((x) => x.name !== body.old), body.rule];
if (what === "rules/remove") state.rules = state.rules.filter((x) => x.name !== body.name);
return json({ ...lib(state.rules), result: { changed: ["claude"] } });
}
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true } });
if (url.pathname.startsWith("/api/")) return json({});
if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" });
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
// a click where the button is, as the reader's, and what was clicked stays
// where it was on the screen while the click redraws around it
const press = async (page, loc) => {
await page.waitForFunction(() => !document.querySelector("#view-library").getAnimations({ subtree: true }).some((a) => a.effect?.getComputedTiming().endTime !== Infinity));
const b = await loc.boundingBox();
const sel = String(loc);
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
await page.waitForTimeout(250);
if (!(await loc.count())) return;
const a = await loc.boundingBox();
if (a && a.width) assert(Math.abs(a.y - b.y) <= 1, `${sel} moved on the screen from ${Math.round(b.y)} to ${Math.round(a.y)}`);
};
const settled = (page) => page.waitForFunction(() => !document.querySelector("#modal").getAnimations({ subtree: true }).length);
// nothing wider than the window: the page, the Library, its rows and dialog
const sideways = (page) => page.evaluate(() => {
const over = [];
const w = document.documentElement.clientWidth;
if (document.documentElement.scrollWidth > w) over.push("page " + document.documentElement.scrollWidth);
const v = document.querySelector("#view-library");
if (v.scrollWidth > v.clientWidth + 1) over.push("library " + v.scrollWidth + ">" + v.clientWidth);
for (const e of document.querySelectorAll("#view-library .lib-rule, #view-library .lib-aside, #view-library .lib-tabs, #modal .lib-ruleedit *")) {
const r = e.getBoundingClientRect();
if (r.width && (r.right > w + 0.5 || r.left < -0.5)) over.push((e.className || e.tagName) + " " + Math.round(r.left) + "–" + Math.round(r.right));
}
return over;
});
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": the Library's Rules tab", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
I18N = strings().I18N; // i18n.js's and the plugins'
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
t.after(() => browser.close());
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
await t.test(lang, async () => {
const w = (key, vars) => tr(lang, key, vars);
const state = { rules: [rule("api", ["src/api/**/*.ts", "docs/**/*.md"], "# API\n\nEvery endpoint validates its input.", ["claude", "kiro-cli"], { claude: API, "kiro-cli": `${HOME}/.kiro/steering/api.md` }), rule("style", [], "## Style\n\nTabs, not spaces.", ["claude"], { claude: `${HOME}/.claude/rules/style.md` })] };
const posts = [], errors = [];
const open = async (width) => {
const ctx = await browser.newContext({ viewport: { width, height: 1000 }, reducedMotion: "reduce" });
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "rules"); } catch {} });
const page = await ctx.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => errors.push(e.message));
page.on("dialog", (d) => { errors.push("a browser dialog: " + d.message()); d.dismiss(); });
await page.route("**/*", server(lang, state, posts));
await page.goto("http://magpie.test/");
await page.locator('button[data-view="library"]').click();
await page.locator("#view-library .lib-rule").first().waitFor();
return { ctx, page };
};
// 1100 wide: the list, and the editor
{
const { ctx, page } = await open(1100);
assert.deepEqual(await sideways(page), [], "sideways scroll with the list at 1100");
await press(page, page.locator("#view-library .lib-rule").first());
await page.locator("#modal .lib-ruleedit").waitFor();
await settled(page);
assert.deepEqual(await sideways(page), [], "sideways scroll in the editor at 1100");
await ctx.close();
posts.length = 0;
}
const { ctx, page } = await open(420);
const v = page.locator("#view-library");
const row = (name) => v.locator(".lib-rule").filter({ has: page.locator(".name", { hasText: new RegExp("^" + name + "$") }) });
const agentsOf = (name) => state.rules.find((s) => s.name === name)?.agents;
assert.deepEqual(await sideways(page), [], "sideways scroll with the list at 420");
// the tab, with its count, between Slash commands and Claude plugins
const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim());
const at = tabs.indexOf(w("Rules") + " · 2");
assert(at > 0, tabs.join("|"));
assert.deepEqual(tabs.slice(at - 1, at + 2), [w("Slash commands"), w("Rules") + " · 2", w("Claude plugins")]);
// a rule kept to files shows them under its name
assert.equal((await row("api").locator(".lib-ruledesc").textContent()).trim(), "src/api/**/*.ts · docs/**/*.md");
// one with none, its first line
assert.equal((await row("style").locator(".lib-ruledesc").textContent()).trim(), "Style");
await v.locator(".lib-rules-no").filter({ hasText: w("magpie can't give rules to {agents}: their chips are greyed, and say why.", { agents: "Claude Code (Ubuntu)" }) }).waitFor();
// Codex reads no folder of rules: no chip at all
assert.equal(await row("api").locator('.lib-ag[data-agent="codex"]').count(), 0);
// the agent in WSL: greyed, says why, and a click posts nothing
const wsl = row("api").locator(`.lib-ag[data-agent="${WSL}"]`);
assert.equal(await wsl.getAttribute("aria-disabled"), "true");
assert.equal(await wsl.getAttribute("title"), w("magpie gives rules only to agents on this computer, not yet to {agent} in WSL", { agent: "Claude Code (Ubuntu)" }));
await press(page, wsl);
await page.waitForTimeout(150);
assert.deepEqual(posts, [], "a greyed chip posted");
// a row's chip gives it to Cline
await press(page, row("api").locator('.lib-ag[data-agent="cline"]'));
await page.waitForFunction(() => document.querySelector('#view-library .lib-rule .lib-ag[data-agent="cline"][aria-pressed="true"]'));
await page.waitForTimeout(200);
assert.deepEqual(posts.shift(), { what: "rules/agents", body: { name: "api", agents: ["claude", "kiro-cli", "cline"] } });
assert.deepEqual(agentsOf("api"), ["claude", "kiro-cli", "cline"]);
// Add: the editor, every agent that can take it picked, the paths folded
await press(page, v.locator(".after-list button"));
const ed = page.locator("#modal .lib-ruleedit");
await ed.waitFor();
await settled(page);
assert.equal(await page.locator("#modal select").count(), 0, "a native <select>");
assert.equal((await ed.locator(".ehead b").textContent()).trim(), w("New rule"));
const edChip = (id) => ed.locator(`.lib-ag[data-agent="${id}"]`);
for (const id of ["claude", "cline", "kiro-cli"]) assert.equal(await edChip(id).getAttribute("aria-pressed"), "true", id);
assert.equal(await edChip(WSL).getAttribute("aria-pressed"), "false");
const more = ed.locator("details.lib-rulemore");
assert.equal(await more.evaluate((d) => d.open), false, "Advanced open on a new rule");
assert.equal(await ed.locator(".lib-rulefiles").count(), 0, "files listed for a rule not saved");
await ed.locator("input").first().fill("testing");
const body = ed.locator(".lib-rulebody");
await body.click();
await page.keyboard.type("Run the tests first.");
// the body's Enter is a new line, not a save
await page.keyboard.press("Enter");
await page.keyboard.type("测试要覆盖边界。");
await page.waitForTimeout(150);
assert.deepEqual(posts, [], "the body's Enter saved");
await more.locator("summary").click();
const paths = ed.locator(".lib-rulepaths");
const hint = ed.locator(".lib-rulehint-paths");
assert.equal((await hint.textContent()).trim(), "", "a hint with no paths");
await paths.fill("**/*_test.go\n\n **/*.test.ts \n**/*_test.go");
// the hint names the agents picked that read every rule always
assert.equal((await hint.textContent()).trim(), w("Not written for {agents}: they read every rule in every conversation", { agents: "Cline" }));
await edChip("cline").click();
assert.equal((await hint.textContent()).trim(), "");
assert.deepEqual(await sideways(page), [], "sideways scroll in the editor");
await ed.locator(".bar button.primary").click();
await ed.waitFor({ state: "detached" });
assert.deepEqual(posts.shift(), { what: "rules/save", body: { old: "", rule: { name: "testing", paths: ["**/*_test.go", "**/*.test.ts"], body: "Run the tests first.\n测试要覆盖边界。", agents: ["claude", "kiro-cli"] } } });
await row("testing").waitFor();
// a row opens it again: Advanced open for its paths, and each
// agent's file a path to show
await press(page, row("api"));
await ed.waitFor();
await settled(page);
assert.equal((await ed.locator(".ehead b").textContent()).trim(), "api");
assert.equal(await ed.locator(".lib-rulebody").inputValue(), "# API\n\nEvery endpoint validates its input.");
assert.equal(await more.evaluate((d) => d.open), true, "Advanced closed on a rule with paths");
assert.equal(await paths.inputValue(), "src/api/**/*.ts\ndocs/**/*.md");
assert.equal((await hint.textContent()).trim(), w("Not written for {agents}: they read every rule in every conversation", { agents: "Cline" }));
const files = ed.locator(".lib-rulefile .lib-path");
assert.deepEqual((await files.allTextContents()).map((x) => x.trim()).sort(), ["~/.claude/rules/api.md", "~/.kiro/steering/api.md"]);
await files.filter({ hasText: "~/.claude/rules/api.md" }).click();
await page.waitForTimeout(150);
assert.deepEqual(posts.shift(), { what: "reveal", body: { path: API } });
assert.deepEqual(await sideways(page), [], "sideways scroll in the editor with files");
await ed.locator(".bar button.danger").click();
const sheet = page.locator("dialog.action-confirm");
await sheet.waitFor();
await sheet.locator("button", { hasText: w("Cancel") }).click();
await sheet.waitFor({ state: "detached" });
await page.waitForTimeout(150);
assert.deepEqual(posts, [], "Cancel posts nothing");
await ed.locator(".bar button.danger").click();
await sheet.waitFor();
await sheet.locator("button.danger-fill").click();
await ed.waitFor({ state: "detached" });
assert.deepEqual(posts.shift(), { what: "rules/remove", body: { name: "api" } });
assert.equal(await row("api").count(), 0);
await row("testing").waitFor();
assert.deepEqual(posts, []);
assert.deepEqual(errors, []);
await ctx.close();
});
}
});
}
@@ -172,7 +172,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// the tab, with its count, between Hooks and RTK
const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim());
assert.deepEqual(tabs.slice(4, 10), [w("Hooks"), w("Environment variables"), w("Subagents") + " · 1", w("Slash commands"), w("Claude plugins"), "RTK"]);
assert.deepEqual(tabs.slice(4, 11), [w("Hooks"), w("Environment variables"), w("Subagents") + " · 1", w("Slash commands"), w("Rules"), w("Claude plugins"), "RTK"]);
// the row: what it is for, and what it binds
assert.equal((await row("reviewer").locator(".lib-subagentdesc").textContent()).trim(), LONG);
assert.equal((await row("reviewer").locator(".lib-subagentuses").textContent()).trim(), w("Skills: {names}", { names: "tdd" }) + " · " + w("MCP servers: {names}", { names: "github" }));
+37
View File
@@ -36,6 +36,9 @@ type Bundle struct {
// Commands are nil in a bundle from a magpie before slash commands,
// as Subagents are: Put keeps this computer's.
Commands *[]*Command `json:"commands,omitempty"`
// Rules are nil in a bundle from a magpie before rules, as Subagents
// are: Put keeps this computer's.
Rules *[]*Rule `json:"rules,omitempty"`
// Hooks are nil in a bundle from a magpie before they were carried,
// as Subagents are: Put keeps this computer's. Applied.Hooks, the
// entries magpie wrote into each agent here, stays out.
@@ -223,6 +226,14 @@ func Collect() (*Bundle, error) {
cmds = append(cmds, &x)
}
b.Commands = &cmds
rules := []*Rule{}
for _, r := range sorted(l.Rules, func(r *Rule) string { return r.Name }) {
x := *r
x.Paths = slices.Clone(r.Paths)
x.Agents = orNone(slices.Sorted(slices.Values(r.Agents)))
rules = append(rules, &x)
}
b.Rules = &rules
hooks := []*Hook{}
for _, h := range sorted(l.Hooks, func(h *Hook) string { return h.Name }) {
if l.ownedPart(h.Bundle) {
@@ -408,6 +419,22 @@ func (b *Bundle) check() error {
seen[c.Name] = true
}
}
if b.Rules != nil {
seen := map[string]bool{}
for _, r := range *b.Rules {
if r == nil {
return fmt.Errorf("an empty rule")
}
// the agents are left as they come, as a subagent's are
if !commandNameRe.MatchString(r.Name) {
return fmt.Errorf("the rule name %q", r.Name)
}
if seen[r.Name] {
return fmt.Errorf("the rule %s twice", r.Name)
}
seen[r.Name] = true
}
}
if b.Env != nil {
seen := map[string]bool{}
for _, e := range *b.Env {
@@ -819,6 +846,16 @@ func Put(b *Bundle) (*Result, error) {
}
l.Commands = cmds
}
// rules the same way: Applied.Rules decides
if b.Rules != nil {
rules := []*Rule{}
for _, r := range *b.Rules {
x := *r
x.Paths, x.Agents = slices.Clone(r.Paths), slices.Clone(orNone(r.Agents))
rules = append(rules, &x)
}
l.Rules = rules
}
// the same for hooks: Applied.Hooks decides, entry by entry,
// what magpie takes out of each agent's file here
if b.Hooks != nil {
+11 -1
View File
@@ -38,6 +38,9 @@ type Library struct {
// Commands are slash commands the agents ticked for each are given
// (commands.go)
Commands []*Command `json:"commands,omitempty"`
// Rules are files of guidance given to the agents ticked for each,
// in their own folder of rules (rules.go)
Rules []*Rule `json:"rules,omitempty"`
// Plugins are the Claude Code plugins kept as one item each: its
// skills, servers, hooks and subagents are the items above marked
// with its name (plugin.go)
@@ -166,6 +169,9 @@ type Applied struct {
// Commands are the files magpie wrote for the slash commands, kept as
// Subagents are
Commands []SubagentFile `json:"commands,omitempty"`
// Rules are the files magpie wrote for the rules, kept as Subagents
// are
Rules []SubagentFile `json:"rules,omitempty"`
// Startup is, for each server, the startup timeout magpie wrote in its
// entry (Codex's startup_timeout_sec): one there other than this is
// the user's
@@ -192,7 +198,7 @@ type Applied struct {
func (a *Applied) empty() bool {
return !a.Instructions && a.InstrHash == "" && len(a.MCP) == 0 && len(a.Skills) == 0 &&
len(a.ToolsOff) == 0 && len(a.ToolRules) == 0 && len(a.Hooks) == 0 && len(a.Env) == 0 &&
len(a.Subagents) == 0 && len(a.Commands) == 0 && len(a.Startup) == 0 && len(a.Picked) == 0 && !a.Router && len(a.RouterRules) == 0 && len(a.RouterCommands) == 0
len(a.Subagents) == 0 && len(a.Commands) == 0 && len(a.Rules) == 0 && len(a.Startup) == 0 && len(a.Picked) == 0 && !a.Router && len(a.RouterRules) == 0 && len(a.RouterCommands) == 0
}
var mu lock // one change at a time, from the page or the CLI's process
@@ -260,6 +266,10 @@ func (l *Library) save() error {
for _, c := range l.Commands {
c.Agents = orNone(c.Agents)
}
sort.Slice(l.Rules, func(i, j int) bool { return l.Rules[i].Name < l.Rules[j].Name })
for _, r := range l.Rules {
r.Agents = orNone(r.Agents)
}
// an entry with nothing in it is no record of what magpie wrote, and
// is not kept: a sync that only looked at an agent used to leave one
// behind, one per agent, and the write its save brought into a file
+360
View File
@@ -0,0 +1,360 @@
package library
import (
"errors"
"fmt"
"path/filepath"
"slices"
"strings"
"github.com/yetone/magpie/internal/agent"
)
// Rules are Markdown files of guidance kept once and given to the agents
// ticked for each, in the folder of rules each reads by itself
// (JonahFu on X: Claude Code's rules folder). A rule may name the files
// it is about (Paths, globs): the agent then reads it only while working
// on a file that matches, instead of in every conversation. Each agent's
// folder and shape, read from its docs and source:
//
// Claude Code <claude dir>/rules/<name>.md paths: [globs] in the frontmatter; one without loads at launch
// (code.claude.com/docs/en/memory; 2.1.327's binary reads <config home>/rules, every .md under it)
// Cline <cline dir>/rules/<name>.md always read: Cline's rules take no paths (CLI 3.0.70's
// e1(): ~/.cline/rules, ~/Cline/Rules…; name, enabled, disabled its only keys)
// Kiro CLI ~/.kiro/steering/<name>.md inclusion: fileMatch and fileMatchPattern: [globs] for paths,
// always included otherwise (kiro.dev/docs/steering)
//
// A rule with paths isn't written for Cline, which would read it in every
// conversation: the page says why. Cursor keeps its user rules in its own
// settings (only a project has .cursor/rules), Codex's rules are command
// policies and Droid's command permissions, and Gemini CLI, Qwen Code and
// OpenCode read no folder of rules: none of them is listed. What magpie
// wrote is recorded file by file with its hash (Applied.Rules), as
// subagents' and slash commands' are (syncOwnFiles): a file still as
// magpie wrote it is magpie's to rewrite or remove, one the user changed
// is theirs from then on, and a file by that name magpie didn't write is
// never touched.
// Rule is a file of guidance the agents ticked for it are given.
type Rule struct {
Name string `json:"name"`
// Paths are the globs of the files it is about, relative to the
// project; none: it is read in every conversation
Paths []string `json:"paths,omitempty"`
Body string `json:"body"`
Agents []string `json:"agents"`
}
const (
maxRuleBody = 100_000
maxRulePaths = 50
maxRulePath = 500
)
// RuleAgents are the agents a rule can be given, in the order the page
// lists them.
var RuleAgents = []string{"claude", "cline", "kiro-cli"}
// ruleSpec is where an agent keeps its rules and how it reads one.
type ruleSpec struct {
dir string
// paths: it reads a rule only for the files its globs match
paths bool
render func(r *Rule) []byte
}
func (sp *ruleSpec) path(name string) string { return filepath.Join(sp.dir, name+".md") }
// wslNoRules is why an agent in WSL is given no rules, its distro running
// or not.
const wslNoRules = "magpie gives no rules to an agent in WSL yet"
// plainRule is a rule's body as a file with no frontmatter of its own: one
// that starts with --- is given an empty frontmatter first, or the agent
// would take its first lines for one.
func plainRule(body string) []byte {
if strings.HasPrefix(body, "---") {
return frontmatter(nil, body)
}
return []byte(strings.TrimRight(body, "\n") + "\n")
}
func ruleSpecOf(t *Target) (*ruleSpec, string) {
a := t.Agent
if a.WSL != "" {
return nil, wslNoRules
}
switch a.ID {
case "claude":
return &ruleSpec{dir: filepath.Join(claudeDir(), "rules"), paths: true, render: func(r *Rule) []byte {
if len(r.Paths) == 0 {
return plainRule(r.Body)
}
return frontmatter([][2]string{{"paths", yamlList(r.Paths)}}, r.Body)
}}, ""
case "cline":
return &ruleSpec{dir: filepath.Join(a.Dir, "rules"), render: func(r *Rule) []byte { return plainRule(r.Body) }}, ""
case "kiro-cli":
// beside the AGENTS.md magpie gives it its instructions in
dir := filepath.Join(home(), ".kiro", "steering")
if t.Instructions != "" {
dir = filepath.Dir(t.Instructions)
}
return &ruleSpec{dir: dir, paths: true, render: func(r *Rule) []byte {
if len(r.Paths) == 0 {
return plainRule(r.Body)
}
return frontmatter([][2]string{{"inclusion", "fileMatch"}, {"fileMatchPattern", yamlList(r.Paths)}}, r.Body)
}}, ""
}
return nil, "magpie can't give " + a.Name + " rules: it reads none from a folder of its own"
}
// noPaths is why an agent that reads every rule always isn't given one
// that names its files.
func noPaths(name string) error {
return fmt.Errorf("%s reads every rule in every conversation: it can't keep one to the files it names", name)
}
// kiroAgents is why Kiro CLI isn't given a rule called agents: its file
// would be the AGENTS.md magpie gives Kiro its instructions in, on a disk
// that tells no case apart.
const kiroAgents = "Kiro CLI keeps its instructions in steering/AGENTS.md: give this rule another name"
func (r *Rule) check() error {
if !commandNameRe.MatchString(r.Name) {
return fmt.Errorf("rule name %q: use lowercase letters, digits, - and _, at most 64, not starting or ending with - or _", r.Name)
}
if strings.TrimSpace(r.Body) == "" {
return errors.New("a rule needs what it says")
}
if len(r.Body) > maxRuleBody {
return fmt.Errorf("a rule is at most %d bytes", maxRuleBody)
}
if len(r.Paths) > maxRulePaths {
return fmt.Errorf("a rule names at most %d paths", maxRulePaths)
}
for _, p := range r.Paths {
if p == "" || len(p) > maxRulePath || strings.ContainsAny(p, "\n\r") {
return fmt.Errorf("the path %q: one glob a line, at most %d characters", p, maxRulePath)
}
}
for _, a := range r.Agents {
if base, _, _ := strings.Cut(a, "@wsl:"); !slices.Contains(RuleAgents, base) {
return fmt.Errorf("%s can't be given rules", a)
}
}
return nil
}
func (l *Library) rule(name string) *Rule {
for _, r := range l.Rules {
if r.Name == name {
return r
}
}
return nil
}
// ruleWhyNot is why the agent can't have this rule, or "".
func ruleWhyNot(t *Target, sp *ruleSpec, r *Rule) string {
switch {
case !sp.paths && len(r.Paths) > 0:
return noPaths(t.Agent.Name).Error()
case t.Agent.ID == "kiro-cli" && r.Name == "agents":
return kiroAgents
}
return ""
}
func (l *Library) syncRules(t *Target, b *backups, res *Result) {
id := t.Agent.ID
a := l.applied(id)
var want []*Rule
for _, r := range l.Rules {
if slices.Contains(r.Agents, id) {
want = append(want, r)
}
}
if len(a.Rules) == 0 && len(want) == 0 {
return
}
sp, why := ruleSpecOf(t)
if sp == nil {
for _, r := range want {
res.fail(id, "rule:"+r.Name, errors.New(why))
}
return
}
var files []ownFile
for _, r := range want {
if why := ruleWhyNot(t, sp, r); why != "" {
// not written: what magpie wrote of it before goes
res.fail(id, "rule:"+r.Name, errors.New(why))
continue
}
files = append(files, ownFile{name: r.Name, path: sp.path(r.Name), body: func() []byte { return sp.render(r) }})
}
a.Rules = syncOwnFiles(t, "rule", a.Rules, files, b, res)
}
// ---- changes ---------------------------------------------------------------
// cleanPaths are the globs as kept: one a line, each trimmed, no blank one
// and none twice, in the order given.
func cleanPaths(ps []string) []string {
var out []string
for _, p := range ps {
for _, x := range strings.Split(strings.ReplaceAll(p, "\r\n", "\n"), "\n") {
if x = strings.TrimSpace(x); x != "" && !slices.Contains(out, x) {
out = append(out, x)
}
}
}
return out
}
// SaveRule adds a rule, or replaces the one called old (renaming it: the
// files magpie wrote by the old name go).
func SaveRule(old string, r Rule) (*Result, error) {
r.Name = strings.TrimSpace(r.Name)
r.Paths = cleanPaths(r.Paths)
r.Body = strings.TrimRight(strings.ReplaceAll(r.Body, "\r\n", "\n"), " \n\t")
if err := r.check(); err != nil {
return nil, err
}
return change(func(l *Library) error {
if r.Name != old && l.rule(r.Name) != nil {
return fmt.Errorf("the library already has a rule called %s", r.Name)
}
if old != "" {
i := slices.IndexFunc(l.Rules, func(x *Rule) bool { return x.Name == old })
if i < 0 {
return fmt.Errorf("no rule called %s", old)
}
l.Rules = slices.Delete(l.Rules, i, i+1)
}
r.Agents = orNone(slices.Compact(slices.Sorted(slices.Values(r.Agents))))
l.Rules = append(l.Rules, &r)
return nil
})
}
// RuleAgentsSet sets which agents get a rule.
func RuleAgentsSet(name string, agents []string) (*Result, error) {
return change(func(l *Library) error {
r := l.rule(name)
if r == nil {
return fmt.Errorf("no rule called %s", name)
}
x := *r
x.Agents = agents
if err := x.check(); err != nil {
return err
}
r.Agents = orNone(slices.Compact(slices.Sorted(slices.Values(agents))))
return nil
})
}
// RemoveRules takes the rules named out of the library, and the files
// magpie wrote of them, still as it wrote them, out of every agent.
func RemoveRules(names []string) (*Result, error) {
if len(names) == 0 {
return nil, errors.New("no rules to remove")
}
return change(func(l *Library) error {
for _, n := range names {
if l.rule(n) == nil {
return fmt.Errorf("no rule called %s", n)
}
}
l.Rules = slices.DeleteFunc(l.Rules, func(r *Rule) bool { return slices.Contains(names, r.Name) })
return nil
})
}
// ---- the page --------------------------------------------------------------
// RuleView is a library rule, and where each agent has it.
type RuleView struct {
*Rule
// Files are, for each agent it was written to, the file
Files map[string]string `json:"files,omitempty"`
// Problems are the agents it couldn't be given to, and why
Problems map[string]string `json:"problems,omitempty"`
}
// RuleAgentView is an agent the Rules tab lists.
type RuleAgentView struct {
ID string `json:"id"`
// Dir is where its rules are; No is why magpie can't give it any
Dir string `json:"dir,omitempty"`
No string `json:"no,omitempty"`
WSL bool `json:"wsl,omitempty"`
// Paths: it keeps a rule to the files it names; one without reads
// every rule always
Paths bool `json:"paths,omitempty"`
}
// rulesView is the Rules page for these agents, and those in stopped WSL
// distros (asleep), greyed as while their distro runs.
func (l *Library) rulesView(targets []*Target, asleep []*agent.Agent, of func(string) map[string]string) ([]RuleView, []RuleAgentView) {
agents := []RuleAgentView{}
type known struct {
t *Target
sp *ruleSpec
}
byID := map[string]known{}
for _, t := range targets {
if base, _, _ := strings.Cut(t.Agent.ID, "@wsl:"); !slices.Contains(RuleAgents, base) {
continue
}
sp, why := ruleSpecOf(t)
av := RuleAgentView{ID: t.Agent.ID, No: why, WSL: t.Agent.WSL != ""}
if sp != nil {
av.Dir, av.Paths = sp.dir, sp.paths
byID[t.Agent.ID] = known{t, sp}
}
agents = append(agents, av)
}
for _, a := range asleep {
if base, _, _ := strings.Cut(a.ID, "@wsl:"); slices.Contains(RuleAgents, base) && shapeOf(a) != nil {
agents = append(agents, RuleAgentView{ID: a.ID, No: wslNoRules, WSL: true})
}
}
views := []RuleView{}
for _, r := range l.Rules {
x := *r
x.Agents = orNone(x.Agents)
rv := RuleView{Rule: &x, Problems: of("rule:" + r.Name)}
for id, a := range l.Applied {
for _, f := range a.Rules {
if f.Name == r.Name && slices.Contains(r.Agents, id) {
if rv.Files == nil {
rv.Files = map[string]string{}
}
rv.Files[id] = f.Path
}
}
}
for _, av := range agents {
if !slices.Contains(r.Agents, av.ID) || rv.Problems[av.ID] != "" {
continue
}
why := av.No
if k, ok := byID[av.ID]; ok && why == "" {
why = ruleWhyNot(k.t, k.sp, r)
}
if why == "" {
continue
}
if rv.Problems == nil {
rv.Problems = map[string]string{}
}
rv.Problems[av.ID] = why
}
views = append(views, rv)
}
return views, agents
}
+285
View File
@@ -0,0 +1,285 @@
package library
import (
"os"
"path/filepath"
"slices"
"strings"
"testing"
)
// ruleAgents puts every agent that takes rules in the sandbox, and says
// where each keeps one called name.
func ruleAgents(t *testing.T, h, name string) map[string]string {
t.Helper()
write(t, filepath.Join(h, ".cline/data/globalState.json"), "")
holdCLI(t, h, "cline")
holdCLI(t, h, "kiro-cli")
return map[string]string{
"claude": filepath.Join(h, ".claude/rules", name+".md"),
"cline": filepath.Join(h, ".cline/rules", name+".md"),
"kiro-cli": filepath.Join(h, ".kiro/steering", name+".md"),
}
}
func ruleProblems(res *Result) map[string]string {
m := map[string]string{}
for _, p := range res.Problems {
if strings.HasPrefix(p.What, "rule:") {
m[p.Agent] = p.Error
}
}
return m
}
// A rule with no paths is a plain Markdown file in each agent's own
// folder of rules, read in every conversation.
func TestRulesEachAgentsFile(t *testing.T) {
h := sandbox(t)
files := ruleAgents(t, h, "style")
r := Rule{Name: "style", Body: "# Style\r\n\r\nTabs, not spaces.\n\n", Agents: []string{"claude", "cline", "kiro-cli"}}
res, err := SaveRule("", r)
if err != nil {
t.Fatal(err)
}
if p := ruleProblems(res); len(p) != 0 {
t.Fatalf("problems: %+v", p)
}
for id, f := range files {
if got := read(t, f); got != "# Style\n\nTabs, not spaces.\n" {
t.Errorf("%s's %s: %q", id, f, got)
}
}
v, err := Read(nil)
if err != nil {
t.Fatal(err)
}
if len(v.Rules) != 1 || len(v.Rules[0].Files) != 3 || len(v.Rules[0].Problems) != 0 {
t.Errorf("view: %+v", v.Rules)
}
var listed []string
for _, av := range v.RuleAgents {
listed = append(listed, av.ID)
if av.Paths != (av.ID != "cline") || av.No != "" || av.Dir != filepath.Dir(files[av.ID]) {
t.Errorf("agent view %+v", av)
}
}
slices.Sort(listed)
if !slices.Equal(listed, []string{"claude", "cline", "kiro-cli"}) {
t.Errorf("agents listed: %v", listed)
}
// a body that starts with --- isn't read as a frontmatter
r.Body = "--- a line ---\nmore"
ok(t)(SaveRule("style", r))
if got := read(t, files["claude"]); got != "---\n---\n\n--- a line ---\nmore\n" {
t.Errorf("claude's: %q", got)
}
// unticked: its file goes; renamed: the old name's go
ok(t)(RuleAgentsSet("style", []string{"claude", "kiro-cli"}))
if _, err := os.Stat(files["cline"]); !os.IsNotExist(err) {
t.Errorf("cline's file after untick: %v", err)
}
r.Name, r.Agents = "tabs", []string{"claude", "kiro-cli"}
ok(t)(SaveRule("style", r))
if read(t, files["claude"]) != "" || read(t, files["kiro-cli"]) != "" {
t.Error("the old name's files stayed")
}
tabs := filepath.Join(h, ".claude/rules/tabs.md")
if read(t, tabs) == "" {
t.Error("no tabs.md")
}
// a file the user deleted comes back on the next sync
os.Remove(tabs)
ok(t)(Sync())
if read(t, tabs) == "" {
t.Error("the deleted file wasn't written again")
}
ok(t)(RemoveRules([]string{"tabs"}))
for _, f := range []string{tabs, filepath.Join(h, ".kiro/steering/tabs.md")} {
if _, err := os.Stat(f); !os.IsNotExist(err) {
t.Errorf("%s after remove: %v", f, err)
}
}
// Kiro's instructions file is no rule's
if _, err := os.Stat(filepath.Join(h, ".kiro/steering")); err != nil {
t.Errorf("kiro's steering folder: %v", err)
}
}
// A rule kept to some files: Claude Code reads paths, Kiro CLI a
// fileMatch inclusion; Cline, which reads every rule always, gets no file
// and the page says why.
func TestRulesKeptToTheirPaths(t *testing.T) {
h := sandbox(t)
files := ruleAgents(t, h, "api")
r := Rule{Name: "api", Paths: []string{" src/api/**/*.ts \n\n*.md", "src/api/**/*.ts"}, Body: "Every endpoint validates its input.", Agents: []string{"claude", "cline", "kiro-cli"}}
res, err := SaveRule("", r)
if err != nil {
t.Fatal(err)
}
if got := read(t, files["claude"]); got != "---\npaths: [\"src/api/**/*.ts\", \"*.md\"]\n---\n\nEvery endpoint validates its input.\n" {
t.Errorf("claude's: %q", got)
}
if got := read(t, files["kiro-cli"]); got != "---\ninclusion: fileMatch\nfileMatchPattern: [\"src/api/**/*.ts\", \"*.md\"]\n---\n\nEvery endpoint validates its input.\n" {
t.Errorf("kiro's: %q", got)
}
if _, err := os.Stat(files["cline"]); !os.IsNotExist(err) {
t.Errorf("cline was given a rule it would read always: %v", err)
}
if p := ruleProblems(res); len(p) != 1 || !strings.Contains(p["cline"], "every conversation") {
t.Errorf("problems: %+v", p)
}
v, err := Read(nil)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(v.Rules[0].Paths, []string{"src/api/**/*.ts", "*.md"}) || !strings.Contains(v.Rules[0].Problems["cline"], "every conversation") {
t.Errorf("view: %+v", v.Rules[0])
}
// no paths any more: Cline gets it, and the problem is gone
r.Paths = nil
res, err = SaveRule("api", r)
if err != nil {
t.Fatal(err)
}
if p := ruleProblems(res); len(p) != 0 {
t.Errorf("problems: %+v", p)
}
if got := read(t, files["cline"]); got != "Every endpoint validates its input.\n" {
t.Errorf("cline's: %q", got)
}
// paths again: magpie's Cline file goes, for it would say the wrong thing
r.Paths = []string{"*.go"}
if _, err := SaveRule("api", r); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(files["cline"]); !os.IsNotExist(err) {
t.Errorf("cline's stale file stayed: %v", err)
}
}
// A rule file of the user's own by the same name is never written over
// nor taken away; one magpie wrote that the user edited is theirs from
// then on. Kiro CLI's AGENTS.md, magpie's instructions there, is no
// rule's to take.
func TestRulesLeaveTheUsersFiles(t *testing.T) {
h := sandbox(t)
files := ruleAgents(t, h, "style")
mine := "My own style.\n"
write(t, files["claude"], mine)
r := Rule{Name: "style", Body: "Tabs.", Agents: []string{"claude", "cline"}}
res, err := SaveRule("", r)
if err != nil {
t.Fatal(err)
}
if p := ruleProblems(res); len(p) != 1 || !strings.Contains(p["claude"], "has a rule of its own at "+files["claude"]) {
t.Fatalf("problems: %+v", res.Problems)
}
if read(t, files["claude"]) != mine {
t.Fatal("the user's own file was written over")
}
edited := read(t, files["cline"]) + "And no trailing spaces.\n"
write(t, files["cline"], edited)
r.Body = "Tabs, always."
res, err = SaveRule("style", r)
if err != nil {
t.Fatal(err)
}
if read(t, files["cline"]) != edited {
t.Error("the user's edit was written over")
}
if !strings.Contains(ruleProblems(res)["cline"], "of its own") {
t.Errorf("problems: %+v", res.Problems)
}
if _, err := RemoveRules([]string{"style"}); err != nil {
t.Fatal(err)
}
if read(t, files["cline"]) != edited || read(t, files["claude"]) != mine {
t.Error("removing took the user's files")
}
l, _ := load()
for id, a := range l.Applied {
if len(a.Rules) != 0 {
t.Errorf("%s still records %+v", id, a.Rules)
}
}
shared := "Be brief."
ok(t)(SaveInstructions(InstructionsChange{Shared: &shared, Agents: []string{"kiro-cli"}}))
res, err = SaveRule("", Rule{Name: "agents", Body: "Not the instructions.", Agents: []string{"kiro-cli", "claude"}})
if err != nil {
t.Fatal(err)
}
if p := ruleProblems(res); p["kiro-cli"] != kiroAgents {
t.Errorf("problems: %+v", p)
}
if got := read(t, filepath.Join(h, ".kiro/steering/AGENTS.md")); !strings.Contains(got, "Be brief.") || strings.Contains(got, "Not the instructions.") {
t.Errorf("kiro's instructions: %q", got)
}
if read(t, filepath.Join(h, ".claude/rules/agents.md")) != "Not the instructions.\n" {
t.Error("claude has no agents.md")
}
}
func TestRuleCheck(t *testing.T) {
sandbox(t)
for _, r := range []Rule{
{Name: "", Body: "x"},
{Name: "Style", Body: "x"},
{Name: "a/b", Body: "x"},
{Name: "style", Body: " \n"},
{Name: "style", Body: "x", Agents: []string{"cursor"}},
{Name: "style", Body: "x", Agents: []string{"codex"}},
{Name: "style", Body: "x", Paths: []string{strings.Repeat("a", maxRulePath+1)}},
{Name: "style", Body: strings.Repeat("a", maxRuleBody+1)},
} {
if _, err := SaveRule("", r); err == nil {
t.Errorf("%+v was taken", r.Name)
}
}
ok(t)(SaveRule("", Rule{Name: "r", Body: "x"}))
if _, err := SaveRule("", Rule{Name: "r", Body: "y"}); err == nil {
t.Error("a second rule called r")
}
}
// Carried to another computer, the rules come along; a bundle from a
// magpie before them keeps this computer's.
func TestRulesCarried(t *testing.T) {
h := sandbox(t)
ruleAgents(t, h, "style")
ok(t)(SaveRule("", Rule{Name: "style", Paths: []string{"*.go"}, Body: "gofmt.", Agents: []string{"claude"}}))
b, err := Collect()
if err != nil {
t.Fatal(err)
}
if b.Rules == nil || len(*b.Rules) != 1 || (*b.Rules)[0].Name != "style" {
t.Fatalf("collected: %+v", b.Rules)
}
old := *b
old.Rules = nil
ok(t)(RemoveRules([]string{"style"}))
ok(t)(SaveRule("", Rule{Name: "here", Body: "x", Agents: []string{"claude"}}))
if _, err := Put(&old); err != nil {
t.Fatal(err)
}
l, _ := load()
if len(l.Rules) != 1 || l.Rules[0].Name != "here" {
t.Errorf("an older bundle took this computer's rules: %+v", l.Rules)
}
if _, err := Put(b); err != nil {
t.Fatal(err)
}
l, _ = load()
if len(l.Rules) != 1 || l.Rules[0].Name != "style" {
t.Errorf("after put: %+v", l.Rules)
}
if got := read(t, filepath.Join(h, ".claude/rules/style.md")); got != "---\npaths: [\"*.go\"]\n---\n\ngofmt.\n" {
t.Errorf("claude's file after put: %q", got)
}
if _, err := os.Stat(filepath.Join(h, ".claude/rules/here.md")); !os.IsNotExist(err) {
t.Errorf("here.md stayed: %v", err)
}
}
+1 -1
View File
@@ -418,7 +418,7 @@ func syncOwnFiles(t *Target, noun string, had []SubagentFile, want []ownFile, b
}
// ownNoun is how a problem names what is in the agent's way.
var ownNoun = map[string]string{"subagent": "subagent", "command": "slash command"}
var ownNoun = map[string]string{"subagent": "subagent", "command": "slash command", "rule": "rule"}
// ---- changes ---------------------------------------------------------------
+7 -1
View File
@@ -120,6 +120,7 @@ func syncSteps(all, gone []*Target, b *backups, res *Result) []func(*Library) {
l.syncEnv(t, b, res)
l.syncSubagents(t, b, res)
l.syncCommands(t, b, res)
l.syncRules(t, b, res)
})
}
// an edit made in an agent's copy of a skill goes to the library first,
@@ -548,7 +549,11 @@ type View struct {
// the agents that can take them do with them
Commands []CommandView `json:"commands"`
CommandAgents []CommandAgentView `json:"commandAgents"`
FoundServers []Found `json:"foundServers"`
// Rules are the library's rules, and RuleAgents what the agents that
// can take them do with them (rules.go)
Rules []RuleView `json:"rules"`
RuleAgents []RuleAgentView `json:"ruleAgents"`
FoundServers []Found `json:"foundServers"`
// Plugins are the plugins kept as one item each (plugin.go)
Plugins []PluginView `json:"plugins"`
Skills []SkillView `json:"skills"`
@@ -795,6 +800,7 @@ func readView(problems []Problem, glance bool) (*View, error) {
v.Env, v.EnvAgents = l.envView(append(slices.Clone(targets), gone...), of)
v.Subagents, v.SubagentAgents = l.subagentsView(targets, asleep, of)
v.Commands, v.CommandAgents = l.commandsView(targets, asleep, of)
v.Rules, v.RuleAgents = l.rulesView(targets, asleep, of)
v.Plugins = l.pluginsView()
tr := &tracer{}
for _, s := range l.Skills {