diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 1f4ee4c80..7fa94ba3c 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -23,7 +23,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. | MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. A server's `StartupTimeout` (#3168) goes to Codex alone, as `startup_timeout_sec` in seconds (`RawMcpServerConfig` in codex-rs/config's mcp_types.rs; 0 leaves Codex's own 30s), in the user-wide config.toml and a project's alike. magpie keeps the value it wrote (`Applied.Startup`, `Project.Startup`): one in the entry other than that, or a `startup_timeout_ms`, is the user's and stays as it is (`startupTheirs`), and once it is taken out magpie's goes in again. The editor shows the field only when an agent that takes it is here (`AgentView.Startup`, `mcp_startup_test.go`, `mcp-startup-timeout.test.cjs`). `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only: with each tool's name and the first paragraph of its description (`ToolList`, at most `maxToolList`, a description cut at `maxToolDesc` runes), which the page lists when the server's "N tools" is clicked, following tools/list's `nextCursor` up to `maxToolPages` pages (`listTools`). Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). A command named bare that magpie's PATH lacks is started from where `proc.FindTool` finds it (fnm's Nodes on Windows among the folders), with that folder on the check's PATH, since npx's package runs the node beside it by name (`stdioProgram`, #2685, `TestStdioProgramFindsWhatPathLacks`). The page asks once a session for the servers some agent or project has (`inUse` in plugins/library/client.js); one no agent has shows "not checked" and is checked only when its status is clicked (#1597, `library-mcp-health.test.cjs`). A server checked once is checked again when it changes, its sign-in included, so a server signed in to after a click's "needs sign-in" isn't left showing both (新v学员 on Discord, `mcp-signin-health.test.cjs`). The check sends magpie's sign-in as the gateway does: on a 401 it renews the token once and asks again, and a server that refuses even the renewed token has the sign-in marked run out (`mcpauth.Rejected`, also from the gateway's `/mcp/`), which `ServerHealth.SignIn` carries back so the row's tag says "Sign-in ran out" rather than "Signed in" beside "needs sign-in". A server that refuses the check (401 or 403) but that an agent signed in to on its own is named so (`ServerHealth.AgentSignIn`, `readOwnSignIns` in `mcp_agent_signin.go`): each Claude Code target's `.credentials.json` beside its settings.json, a WSL distro's under the distro's home, is read for a `mcpOAuth` entry of the server's name and URL with a token, and each Codex target's `.credentials.json` beside its config.toml for a flattened entry of them, the file codex-rs falls back to when its config's `mcp_oauth_credentials_store` is `file` or the keyring is missing, whose executor's own entries are no `codex mcp login` (#3508); and the row says "signed in in Claude Code (Ubuntu)" — or Codex — instead of "needs sign-in" (CyberCaius on Discord: signed in to with Claude Code's /mcp in WSL). The tokens are never sent or kept; a file that can't be read or parsed names nobody, a stopped distro isn't started for it, and on a Mac only the file is read, never the Keychain Claude Code keeps them in nor Codex's keyring store. They are part of the check's key, so a sign-in in the agent since is checked anew (`TestCheckNamesAgentsSignedInThemselves`, `library-mcp-health-wsl.test.cjs`). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/` (#615). The editor's Sign in saves the form first only when the sign-in is to another server than the saved one (a new server, a name or URL changed), and its button then reads "Save and sign in"; anything else edited (headers, env, arguments) stays unsaved until Save, so Cancel leaves the server as it was (新v学员 on Discord, `mcp-editor-cancel.test.cjs`). A server whose authorization server refuses magpie's dynamic client registration with 401 or 403 admits only the clients it lists (Figma's, #1619): the sign-in fails with `mcpauth.ErrClientRefused`, which says so and that each agent signs in itself, and the agents keep the server's own address. A server whose authorization server has no registration endpoint at all (GitHub's remote server, 新v学员 on Discord) fails with `mcpauth.ErrNoRegistration`, which says to make an OAuth app with the vendor and give it in the editor; the editor then opens its "OAuth app" fields. The app is the server's `oauth` (`OAuthApp`: `clientId`, `clientSecret`, `callbackPort`, Claude Code's names for `--client-id`, `--client-secret` and `--callback-port`), checked on save (HTTP only, a client ID, a port from 1 to 65535), and `SignInServer` signs in as it through `mcpauth.StartWith` without registering. The callback is Claude Code's, `http://localhost:/callback` (its docs' "Use pre-configured OAuth credentials"; 2.1.296 builds it so), listened for on 127.0.0.1 alone as Claude Code does, so an app made for Claude Code signs magpie in as it is; a server that matches the registered URL exactly refuses another host, which is why Claude Code's 2.1.231 went back to `localhost` from 2.1.229's `127.0.0.1` (`TestAppMadeForClaudeCode`). Without a `callbackPort` the port is any free one, which a loopback callback registered without a port takes (GitHub's, RFC 8252); a fixed `callbackPort` is for a vendor that matches the port too. magpie's own registration, when a server has one, still names `127.0.0.1`. The client secret is kept in library.json, as a header's or env's value is: a backup without keys leaves it out, and `WithSecrets` puts back this computer's secret only for the same client ID; no agent is given the app, and the TUI's editor, which doesn't show it, keeps it. GitHub answers a token request's error with a 200 and `error` in the body (`bad_refresh_token`, `incorrect_client_credentials`), which `tokenRequest` reads as the error it is, and a dead refresh token marks the sign-in run out (`github_app_test.go`, `mcp-oauth-app.test.cjs`). magpie never registers under another client's name; one that reaches the gateway from another machine (a WSL distro under NAT) is given it with the LAN sharing key as its `Authorization` (`agent.KeyAt`), as its models are, which the gateway takes in place of a sign-in and never passes on; turning sharing on or off, or a new key (`access.LANChanged`), writes such entries again. `ConfigOfServers` is the servers picked as an agent's project file (`projectMCPFiles`) would hold them, written by the same code into a folder of its own and read back, with those the agent can't take there named; the page's Copy config… puts it on the clipboard for a project magpie doesn't keep (#1478). Each listed tool has a switch: the tools turned off are the server's `DisabledTools`, set by `ServerTools`, and written into each agent given the server that can leave out a single tool (see the constraint below). A server run as `npx -y args` (a registry package, no other npx flag) is given to an agent on this machine as `node args` (`npxDirect`): magpie installs the package with npm into a folder of its own under `mcp-npm` in the background, the next sync writes the node form, and until then, or when npm fails (tried again after an hour), the agent keeps npx. npx otherwise stays as the server's parent for its whole life, a node and two cmd.exe beside each instance on Windows (#3885). An unpinned spec is installed again after a day, as npx would fetch the newer one; an install no library server runs goes a day after its last. The library, a server's check, Copy config… and agents in WSL keep npx (`TestNpxServerRunsByNode`, `TestReadNpx`). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_npx.go`](../../internal/library/mcp_npx.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go), [`mcp_agent_signin.go`](../../internal/library/mcp_agent_signin.go), [`mcp_copy.go`](../../internal/library/mcp_copy.go), [`mcp_tools_off.go`](../../internal/library/mcp_tools_off.go) | | MCP router | With `MCPHub` on, `syncMCP` gives each agent that can take it one entry, `magpie`, at the gateway's `/mcp/magpie/hub/`, in place of the servers ticked for it; magpie runs those servers itself, once for every agent. | [MCP router](mcp-router.md), [`mcp_hub.go`](../../internal/library/mcp_hub.go) | | MCP market | `MarketServers` lists the featured servers that match a search, then the MCP Registry's; a search that is an address (a repository, a page, an endpoint, a package; `market_addr.go`) finds the ones at it, and `CustomAt` offers one to fill in by hand when none is. The registry lists no server by a repository's folder, so a GitHub address naming one (`#subdirectory=`, `/tree//…`, `parseRepoAt`) is read first: the folder's `pyproject.toml` names the program, and the README's `"env": {…}` examples the keys, offered as `uvx --from git+https://github.com/o/r#subdirectory=p ` (`fromRepo`, CyberCaius on Discord: volcengine/mcp-server's askecho search). A bare repository is read so only when the registry has nothing at it, and a PyPI page, or a one-word search naming mcp the registry lists nothing by, asks PyPI (`fromPyPI`, `uvx `). Of several README keys none is required, since a README often has the user pick one way to sign in (`envInputs`; `TestMarketServerInRepoFolder`). Only Python projects are read from a folder; a Node one there still gets the blank form. | [`market.go`](../../internal/library/market.go), [`market_repo.go`](../../internal/library/market_repo.go) | -| Skills | A skill is a folder with a `SKILL.md`. It goes by the `name` its front matter gives, made fit for a file name (ASCII letters, digits, `_` and `-`); a name that would lose a letter or digit that way (one in another script, `CTF•密码学`) or none goes by its folder's name instead, and a skill at a repository's top by the repository's (`nameFor`, `srcFolder`). Two skills a probe names alike are listed once (`unhiddenFirst`), so names that fell to `CTF`, `Strix` and nothing listed asdfgh1445/ctf-super-hub's 35 skills as 16 (tnt1223 on Discord, `TestSkillsNamedInAnotherScriptAllListed`). It comes from GitHub, from any other git repository, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. A git repository (`kind: git`, sunset on Discord: GitLab, a company's own GitLab) is any https, http, ssh or `file://` address, `git@host:group/repo.git`, a bare `host.name/group/repo`, or a GitLab or Gitea page of a folder (`/-/tree//`, `/-/blob/…`, `/src/branch/…`; a branch with a `/` in its name is read as its first segment) (`gitSource`). It is fetched by the user's own `git` (`proc.FindTool`), so their credential helpers and SSH keys reach an intranet host: `git init`, then `fetch --depth 1 --no-tags -- ` and `checkout FETCH_HEAD` into a `magpie-skill-*` folder, then its `.git` is removed (`fetchGit`). What the user typed is data: an address starting with `-` and a `transport::` address (`ext::`, `fd::`, `file::`) are refused before git runs, the address follows `--`, git runs with `protocol.ext.allow=never` and `core.symlinks=false`, no shell, `GIT_TERMINAL_PROMPT=0` and (unless the user set an SSH command) `ssh -o BatchMode=yes`, so a sign-in it can't make fails instead of waiting. An address with a password or token in it is refused: library.json is shown and backed up. Git missing, a sign-in refused, a host key unknown, a branch missing and a host unreachable each say so (`gitError`; `TestGitSourceReads`, `TestInstallFromGitRepo`, `TestGitTreeURLInstallsFolder`, `TestGitMissingSaysSo`, `TestGitSignInRefusedSaysSo`, `TestGitRefusesOptionsAndTransports`, `TestGitErrorsSaid`). Each agent gets a link or a marked copy (#896, `SkillHow`). An agent in a WSL distro always gets a copy. A copy's mark keeps the hash of what was copied, so a sync knows a copy unchanged since then is current without reading its files (`copyIsFresh`, #1031); other copies are hashed. A skill an agent has of its own (`foundSkills`, the page's "In your agents") is brought in with `ImportSkill`, or taken out of every agent that has it with `RemoveFoundSkill` (#1303): its folders and copies of the very same files, its shared `~/.agents/skills` entry and a folder of it in the library's own folder go to the backups, its links are taken away, and a folder elsewhere it only links to, or another skill by that name, stays. Several go at once with `RemoveFoundSkills` (`POST /api/library/skills/remove-found-some`, wongxy on Discord): the "In your agents" heading's own Select picks them, and Remove… asks once, naming the count, before one change takes each out as `RemoveFoundSkill` would. A name that can't be taken out is left as it was, in `Result.Unremoved`, and stays picked with its error in its row's place (`foundErrs`); when none can go the change fails and nothing is touched. This Select and the library's are never on together: while one is on the other is dimmed, saying why, so neither click takes the other's bar away from above the pointer (`TestRemoveFoundSkills`, `found-skill-pick-remove.test.cjs`). A repository is fetched as one tarball of at most `maxFetch` (200 MB); a bigger one is fetched file by file from its tree (`fetchSkillFiles`), only as far as the caller reads: a link to a folder and an update ask GitHub for that folder's own list (`treeUnder`, git's `ref:path`; the whole list when that fails), the market fetches only the skills whose folder is the one it installs (#2794, sickn33/agentic-awesome-skills' 8,589 skills are 287 MB together), and a fetcher keeps such a part apart from another skill's of the same repository, which would otherwise read as removed (`fetcher.get`, `TestMarketSkillFromAHugeRepository`). GitHub's list is read up to `maxTree` (64 MB; that repository's is 11 MB) and an answer over the cap a caller gives `apiGet`, or one cut off, is an error saying so, never a body cut short for JSON to trip on (ye4241's `TestRepoTreeBigList`, `TestApiGetWholeAnswer`); a list GitHub truncated itself is too big (`TestTruncatedListIsTooBig`). And a skill over 200 MB on its own is left out rather than failing the rest: the probe lists the others and names it in `Probe.Left`, under the list in the page and in the TUI's flash. Only when every skill is too big does the fetch fail (#2062, mikubaka88/CCFA-Skills' 297 MB ccf-paper-writer; `TestOneSkillTooBigLeavesTheOthers`, `skill-too-big.test.cjs`). A probe keeps its download for the install from it for 15 minutes (`keepProbe`, `probeLife`), and removes it when it is probed again or that time is up, not at the next probe, which may never come. A download a magpie that quit left in the temp dir goes at the next probe once it is an hour old (`sweepStaleDownloads`). The package's TestMain gives the tests a temp dir of their own and fails a run that leaves a `magpie-skill-*` in it (#2321, `TestProbeDownloadEndsWithIt`, `TestStaleDownloadsSwept`). | [`skilltree.go`](../../internal/library/skilltree.go), [`skills.go`](../../internal/library/skills.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skill_how.go`](../../internal/library/skill_how.go), [`skill_edits.go`](../../internal/library/skill_edits.go), [`skill_from.go`](../../internal/library/skill_from.go), [`skill_beside.go`](../../internal/library/skill_beside.go) | +| Skills | A skill is a folder with a `SKILL.md`. It goes by the `name` its front matter gives, made fit for a file name (ASCII letters, digits, `_` and `-`); a name that would lose a letter or digit that way (one in another script, `CTF•密码学`) or none goes by its folder's name instead, and a skill at a repository's top by the repository's (`nameFor`, `srcFolder`). Two skills a probe names alike are listed once (`unhiddenFirst`), so names that fell to `CTF`, `Strix` and nothing listed asdfgh1445/ctf-super-hub's 35 skills as 16 (tnt1223 on Discord, `TestSkillsNamedInAnotherScriptAllListed`). It comes from GitHub, from any other git repository, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. A git repository (`kind: git`, sunset on Discord: GitLab, a company's own GitLab) is any https, http, ssh or `file://` address, `git@host:group/repo.git`, a bare `host.name/group/repo`, or a GitLab or Gitea page of a folder (`/-/tree//`, `/-/blob/…`, `/src/branch/…`; a branch with a `/` in its name is read as its first segment) (`gitSource`). It is fetched by the user's own `git` (`proc.FindTool`), so their credential helpers and SSH keys reach an intranet host: `git init`, then `fetch --depth 1 --no-tags -- ` and `checkout FETCH_HEAD` into a `magpie-skill-*` folder, then its `.git` is removed (`fetchGit`). What the user typed is data: an address starting with `-` and a `transport::` address (`ext::`, `fd::`, `file::`) are refused before git runs, the address follows `--`, git runs with `protocol.ext.allow=never` and `core.symlinks=false`, no shell, `GIT_TERMINAL_PROMPT=0` and (unless the user set an SSH command) `ssh -o BatchMode=yes`, so a sign-in it can't make fails instead of waiting. An address with a password or token in it is refused: library.json is shown and backed up. Git missing, a sign-in refused, a host key unknown, a branch missing and a host unreachable each say so (`gitError`; `TestGitSourceReads`, `TestInstallFromGitRepo`, `TestGitTreeURLInstallsFolder`, `TestGitMissingSaysSo`, `TestGitSignInRefusedSaysSo`, `TestGitRefusesOptionsAndTransports`, `TestGitErrorsSaid`). Each agent gets a link or a marked copy (#896, `SkillHow`). An agent in a WSL distro gets a link too, to the distro's one copy of the skill, magpie's, in `~/.local/share/magpie/skills` (`Target.Store`, `storeSkill`; cutemmuu on X): the distro can't follow a link to the library's folder on Windows, and a link Windows makes through `\\wsl.localhost` is an empty folder in the distro, which in turn shows Windows its own links as entries it can't read, follow or remove, so the link is made, read and taken away in the distro by wsl.exe (`agent.WSLSymlink`, `WSLReadlink`, `WSLRemoveLink`; `TestWSLLinksLive` and `TestWSLSkillsLinkedLive` on a real distro with `MAGPIE_WSL_TEST_DISTRO`). An edit made through the link is in the distro's copy, which `takeEdits` reads as any copy of magpie's (`TestWSLEditThroughLinkReachesTheLibrary`); a copy no agent there links to or is given any more goes, to the backups when edited (`sweepWSLStores`, `TestWSLStoreSweepKeepsEdits`); a folder there that isn't magpie's is never touched, and each agent it is in the way of says so. The copy isn't put in the distro's `~/.agents/skills`, since every agent there reading that folder would get each skill, ticked for it or not. An agent set to copies gets one of its own, as does one whose skills folder or the store is on a Windows drive (#4502), where the distro's link is one Windows can't read. A copy an agent there was given before is made a link on the next sync, its edit taken first and a losing edit set aside (`wslRelink`, `TestWSLOldCopiesBecomeLinks`). A copy's mark keeps the hash of what was copied, so a sync knows a copy unchanged since then is current without reading its files (`copyIsFresh`, #1031); other copies are hashed. A skill an agent has of its own (`foundSkills`, the page's "In your agents") is brought in with `ImportSkill`, or taken out of every agent that has it with `RemoveFoundSkill` (#1303): its folders and copies of the very same files, its shared `~/.agents/skills` entry and a folder of it in the library's own folder go to the backups, its links are taken away, and a folder elsewhere it only links to, or another skill by that name, stays. Several go at once with `RemoveFoundSkills` (`POST /api/library/skills/remove-found-some`, wongxy on Discord): the "In your agents" heading's own Select picks them, and Remove… asks once, naming the count, before one change takes each out as `RemoveFoundSkill` would. A name that can't be taken out is left as it was, in `Result.Unremoved`, and stays picked with its error in its row's place (`foundErrs`); when none can go the change fails and nothing is touched. This Select and the library's are never on together: while one is on the other is dimmed, saying why, so neither click takes the other's bar away from above the pointer (`TestRemoveFoundSkills`, `found-skill-pick-remove.test.cjs`). A repository is fetched as one tarball of at most `maxFetch` (200 MB); a bigger one is fetched file by file from its tree (`fetchSkillFiles`), only as far as the caller reads: a link to a folder and an update ask GitHub for that folder's own list (`treeUnder`, git's `ref:path`; the whole list when that fails), the market fetches only the skills whose folder is the one it installs (#2794, sickn33/agentic-awesome-skills' 8,589 skills are 287 MB together), and a fetcher keeps such a part apart from another skill's of the same repository, which would otherwise read as removed (`fetcher.get`, `TestMarketSkillFromAHugeRepository`). GitHub's list is read up to `maxTree` (64 MB; that repository's is 11 MB) and an answer over the cap a caller gives `apiGet`, or one cut off, is an error saying so, never a body cut short for JSON to trip on (ye4241's `TestRepoTreeBigList`, `TestApiGetWholeAnswer`); a list GitHub truncated itself is too big (`TestTruncatedListIsTooBig`). And a skill over 200 MB on its own is left out rather than failing the rest: the probe lists the others and names it in `Probe.Left`, under the list in the page and in the TUI's flash. Only when every skill is too big does the fetch fail (#2062, mikubaka88/CCFA-Skills' 297 MB ccf-paper-writer; `TestOneSkillTooBigLeavesTheOthers`, `skill-too-big.test.cjs`). A probe keeps its download for the install from it for 15 minutes (`keepProbe`, `probeLife`), and removes it when it is probed again or that time is up, not at the next probe, which may never come. A download a magpie that quit left in the temp dir goes at the next probe once it is an hour old (`sweepStaleDownloads`). The package's TestMain gives the tests a temp dir of their own and fails a run that leaves a `magpie-skill-*` in it (#2321, `TestProbeDownloadEndsWithIt`, `TestStaleDownloadsSwept`). | [`skilltree.go`](../../internal/library/skilltree.go), [`skills.go`](../../internal/library/skills.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skill_how.go`](../../internal/library/skill_how.go), [`skill_edits.go`](../../internal/library/skill_edits.go), [`skill_from.go`](../../internal/library/skill_from.go), [`skill_beside.go`](../../internal/library/skill_beside.go) | | Skills market | `MarketSkills` lists skills.sh's most installed and what its search finds. magpie's own skills (`featuredSkills`), in [magpie-community/plugins](https://github.com/magpie-community/plugins/tree/main/skills), go first, marked official: `magpie-setup` has an agent set magpie up as the user asks through its commands (providers, accounts, agents, routing groups and rules, gateway keys and limits, models, the library), and `magpie-quota` lets an agent read `magpie quota --json` and wait with `magpie quota wait`. Their commands live in magpie's CLI, so a change to a command either uses gets the skill updated in that repository. Until skills.sh lists one it has no count of installs and no skills.sh link (`featured`). `InstallMarketSkill` installs any of them from its repository. | [`market.go`](../../internal/library/market.go) | | Skills a repository added | A check for updates (`CheckSkills`) also asks, for each GitHub repository and ref the library has skills from, GitHub's list of its files (`repoTree`, one API request, free when the ETag still matches). Only when that list has a skill folder beside the installed ones (under `newBase`, their deepest common folder) that the library doesn't have and hasn't offered does `findNew` fetch the repository for the skills' names and descriptions. `SeenSkills` records per `repo@ref` the paths the install picker showed and the ones set aside, so they aren't offered again. The finds live in memory (`newFound`) and reach the page as `View.NewSkills`; `AddNewSkills` gives each to the agents that have its repository's other skills, and `IgnoreNewSkills` sets it aside (`/api/library/skills/{add-new,ignore-new}`). | [`skillnew.go`](../../internal/library/skillnew.go), [`skillcheck.go`](../../internal/library/skillcheck.go) | | Skill groups | The page groups skills by `SkillView.Repo`, the repository each came from (`tracer.repoOf`): its GitHub source, CC Switch's `Origin`, `From`, the skills CLI's lock or the git checkout a linked folder is in. That checkout is the one git finds (`provider.GitAt` in `gitRepoOf`): an empty `.git` between the skill and its checkout is passed over, as git passes it over, and a `.git` file that names no repository (a worktree left behind) is none (#3675, `TestSkillRepoTraced`). A lock entry of `sourceType: well-known` (a site's kit at its `/.well-known/agent-skills/`) is grouped by its `sourceBaseUrl` as host/path (`wellKnownBase`), not by each skill's own `sourceUrl`: Feishu's lark-* skills are one group and Fish Audio's another, while two kits under one host with different base URLs stay apart. An older entry with no base URL takes the part of its `sourceUrl` before `/.well-known/`, and one with neither is grouped by its `sourceUrl` as before. Such a kit is never fetched from GitHub by Group again, even when it reads like owner/repo (a GitHub owner has no dot), and its heading's link opens the site (#1862, `TestWellKnownKitGrouped`). `From` is written when a repository is probed (installing from it again, `noteFrom`): for a skill with the very same `SKILL.md`, and for one traced to nowhere by a name the repository has when the library has others from there, since a pack added a while ago is mostly older copies edited there since (White Immortal on Discord: 20 of mattpocock/skills' 38). Group again (`RegroupSkills`, `POST /api/library/skills/regroup`) fetches each GitHub repository the skills are traced to and does the same; it fails only when none could be fetched. A skill traced to another repository is never moved. A group's (or part's, or the Select bar's) agent chips count, give and take only the skills magpie decides for each agent: one kept in `~/.agents/skills` is in `SkillView.Always` for the agents that read that folder themselves, so a chip's `agents-some` for such an agent leaves it out, its tooltip and the status after a click say how many it still reads itself, and an agent that reads every one of them itself has a lit, locked chip as the row's is, which sends nothing (`groupChips` in plugins/library/client.js). The heading says how many of its skills are in `~/.agents/skills`. A row's locked chip is lit with a lock on its corner, not greyed like a chip that can't be given the skill (#1862, `skill-group-shared.test.cjs`). Collapse all / Expand all, beside the sort, folds or opens every group the list shows at once (`foldAllButton`): without a filter it sets each group's kept fold (`magpie.libSkillFolds`), as a click on each heading would; while filtering, only the groups the filter shows, till the filter changes (`unfiltered`), leaving the kept folds alone. It reads Collapse all while any shown group is open, is hidden with fewer than two groups (A→Z, or a filter one group matches), leaves a part's own fold as it is and sends nothing (#1862, `skill-fold-all.test.cjs`). | [`skill_from.go`](../../internal/library/skill_from.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) | diff --git a/internal/agent/wsl_fake.go b/internal/agent/wsl_fake.go index 5c20dcdc8..e544fa9e0 100644 --- a/internal/agent/wsl_fake.go +++ b/internal/agent/wsl_fake.go @@ -2,6 +2,8 @@ package agent import ( "errors" + "fmt" + "os" "path/filepath" "strings" "sync" @@ -15,7 +17,7 @@ import ( // magpie remembers of WSL is forgotten, before and after; the returned // func puts everything back. func FakeWSL(probes, roots map[string]string) func() { - on, run, root := wslOn, wslRun, wslRoot + on, run, root, exec := wslOn, wslRun, wslRoot, wslExec reset := func() { wsl.Lock() wsl.seen, wsl.at, wsl.runAt, wsl.names, wsl.running, wsl.probed, wsl.failed, wsl.dirty = nil, time.Time{}, time.Time{}, nil, nil, nil, nil, false @@ -62,8 +64,20 @@ func FakeWSL(probes, roots map[string]string) func() { return nil, errors.New("unexpected wsl.exe " + strings.Join(args, " ")) } wslRoot = func(name string) string { return roots[name] } + wslExec = func(name string, argv ...string) ([]byte, error) { + fakeCalls.Lock() + fakeCalls.in[name]++ + fakeCalls.Unlock() + return fakeLinks(roots[name], argv) + } + links.Lock() + links.m = nil + links.Unlock() return func() { - wslOn, wslRun, wslRoot = on, run, root + wslOn, wslRun, wslRoot, wslExec = on, run, root, exec + links.Lock() + links.m = nil + links.Unlock() fakeStop = nil reset() } @@ -116,3 +130,64 @@ func FakeWSLDrives(roots map[string]string) func() { } return func() { wslDrive = was } } + +// fakeLinks does what wsl_links.go's scripts do in a distro opened at +// root, on this system's own links: a link the distro would lead to +// /home/me/x leads to root's home/me/x here, which this system follows. +func fakeLinks(root string, argv []string) ([]byte, error) { + if len(argv) < 5 || argv[0] != "sh" || argv[1] != "-c" { + return nil, errors.New("unexpected command in WSL: " + strings.Join(argv, " ")) + } + at := func(linux string) string { return filepath.Join(root, filepath.FromSlash(linux)) } + args := argv[4:] + switch argv[2] { + case wslLinkScript: + to, link := at(args[0]), at(args[1]) + if fi, err := os.Lstat(link); err == nil && fi.Mode()&os.ModeSymlink == 0 { + return []byte(args[1] + " is not a link"), errors.New("exit status 3") + } + if err := os.MkdirAll(filepath.Dir(link), 0o755); err != nil { + return nil, err + } + os.Remove(link) + return nil, os.Symlink(to, link) + case wslUnlinkScript: + p := at(args[0]) + fi, err := os.Lstat(p) + if err != nil { + return nil, nil + } + if fi.Mode()&os.ModeSymlink == 0 { + return []byte(args[0] + " is not a link"), errors.New("exit status 3") + } + return nil, os.Remove(p) + case wslLinksScript: + es, _ := os.ReadDir(at(args[0])) + var b strings.Builder + for _, e := range es { + if to, err := os.Readlink(filepath.Join(at(args[0]), e.Name())); err == nil { + // spelt as the distro spells it + if rel, ok := strings.CutPrefix(to, root); ok { + to = filepath.ToSlash(rel) + } + fmt.Fprintf(&b, "%s\t%s\n", e.Name(), to) + } + } + return []byte(b.String()), nil + } + return nil, errors.New("unexpected script in WSL: " + argv[2]) +} + +// realWSLRun is wsl.exe itself, for FakeWSLRealLinks. +var realWSLRun = wslRun + +// FakeWSLRealLinks, for a test on Windows with a real distro behind +// FakeWSL's root (\\wsl.localhost\), has the links in it made, +// read and removed by the real wsl.exe, in that distro alone. +func FakeWSLRealLinks() (restore func()) { + exec := wslExec + wslExec = func(distro string, argv ...string) ([]byte, error) { + return realWSLRun(30*time.Second, append([]string{"-d", distro, "--exec"}, argv...)...) + } + return func() { wslExec = exec } +} diff --git a/internal/agent/wsl_links.go b/internal/agent/wsl_links.go new file mode 100644 index 000000000..7d0581857 --- /dev/null +++ b/internal/agent/wsl_links.go @@ -0,0 +1,209 @@ +package agent + +// Links in a WSL distro, made, read and taken away from inside it. +// +// Through \\wsl.localhost Windows sees a link the distro has as an entry +// it can't follow: Lstat says it is there (Go reports it irregular), but +// Readlink fails ("Incorrect function"), and opening, listing or removing +// it says it isn't there. A link Windows makes there (os.Symlink) is an +// empty folder in the distro, not a link at all. So magpie makes, reads +// and removes a distro's links with wsl.exe, in the distro, where they are +// read (tried on Windows 11 with WSL 2 and Ubuntu 24.04). + +import ( + "errors" + "path" + "strings" + "sync" + "time" +) + +// wslExec runs argv in the distro; a var for tests. +var wslExec = func(distro string, argv ...string) ([]byte, error) { + return wslRun(30*time.Second, append([]string{"-d", distro, "--exec"}, argv...)...) +} + +// distroAt is the running distro local, a path as magpie opens it, is in: +// under its root, or under where one of its Links leads (distro.native). +func distroAt(local string) (distro, bool) { + wsl.Lock() + defer wsl.Unlock() + // a command run in a stopped distro would start it (wslUp) + wslRunningLocked() + for name, d := range wsl.seen { + if d == nil || d.Root == "" || !wsl.running[name] { + continue + } + if _, ok := below(local, d.Root); ok { + return *d, true + } + for _, to := range d.Links { + if to == "" { + continue + } + if _, ok := below(local, d.where(to)); ok { + return *d, true + } + } + } + return distro{}, false +} + +// agentDistro is the distro a's files are in, as last probed. +func agentDistro(a *Agent) (distro, error) { + if a == nil || a.WSL == "" { + return distro{}, errors.New("not an agent in WSL") + } + wsl.Lock() + d := wsl.seen[a.WSL] + wsl.Unlock() + if d == nil || d.Root == "" { + return distro{}, errors.New("WSL " + a.WSL + " hasn't been looked in") + } + return *d, nil +} + +// wslLinkScript makes $2 a link to $1: in place of a link there, never of +// a folder or file, which it refuses with 3 (said on stdout, which is +// what wslRun reads). +const wslLinkScript = `if [ -e "$2" ] && [ ! -L "$2" ]; then echo "$2 is not a link"; exit 3; fi +mkdir -p -- "$(dirname -- "$2")" && ln -sfn -- "$1" "$2"` + +// wslUnlinkScript removes $1 when it is a link, and nothing else. +const wslUnlinkScript = `if [ -L "$1" ]; then rm -f -- "$1"; elif [ -e "$1" ]; then echo "$1 is not a link"; exit 3; fi` + +// wslLinksScript lists the links in the folder $1, one name, a tab and +// where it leads to a line. +const wslLinksScript = `for f in "$1"/* "$1"/.[!.]*; do [ -L "$f" ] && printf '%s\t%s\n' "${f##*/}" "$(readlink -- "$f")"; done; true` + +// WSLSymlink makes link a link to target, both in a's distro as magpie +// opens them, from inside the distro: a link the agent there follows. A +// link at link already is replaced; a folder or file there is refused. +func WSLSymlink(a *Agent, target, link string) error { + d, err := agentDistro(a) + if err != nil { + return err + } + out, err := wslExec(d.Name, "sh", "-c", wslLinkScript, "sh", d.native(target), d.native(link)) + forgetLinks(link) + if err != nil { + return wslFailed("link "+d.native(link), out, err) + } + return nil +} + +// WSLRemoveLink takes the link at local, a path in a running distro as +// magpie opens it, away from inside the distro; what it leads to stays. +// Anything there but a link is refused. +func WSLRemoveLink(local string) error { + d, ok := distroAt(local) + if !ok { + return errors.New(local + " isn't in a running WSL distro") + } + out, err := wslExec(d.Name, "sh", "-c", wslUnlinkScript, "sh", d.native(local)) + forgetLinks(local) + if err != nil { + return wslFailed("remove "+d.native(local), out, err) + } + return nil +} + +func wslFailed(what string, out []byte, err error) error { + if s := strings.TrimSpace(string(out)); s != "" { + return errors.New(what + " in WSL: " + s) + } + return errors.New(what + " in WSL: " + err.Error()) +} + +// links keeps each folder's links as the distro listed them, for +// linksAge: a page read looks at every agent's skills, each a wsl.exe +// otherwise. +var links struct { + sync.Mutex + m map[string]linkList +} + +type linkList struct { + at time.Time + to map[string]string // by name, as the distro spells where it leads +} + +const linksAge = 3 * time.Second + +// forgetLinks drops what was listed of the folder local is in. +func forgetLinks(local string) { + dir, _ := splitLocal(local) + links.Lock() + delete(links.m, strings.ToLower(dir)) + links.Unlock() +} + +// splitLocal is local's folder and name, cut at its last separator. +func splitLocal(local string) (string, string) { + i := strings.LastIndexAny(local, `\/`) + if i < 0 { + return "", local + } + return local[:i], local[i+1:] +} + +// WSLReadlink is where the link at local, a path in a running distro as +// magpie opens it, leads, as magpie opens that: false when local is in no +// running distro or isn't a link there. It is asked where Windows can't +// read the link itself (Readlink fails through \\wsl.localhost). +func WSLReadlink(local string) (string, bool) { + d, ok := distroAt(local) + if !ok { + return "", false + } + dir, name := splitLocal(local) + key := strings.ToLower(dir) + links.Lock() + l, ok := links.m[key] + links.Unlock() + if !ok || time.Since(l.at) > linksAge { + out, err := wslExec(d.Name, "sh", "-c", wslLinksScript, "sh", d.native(dir)) + if err != nil { + return "", false + } + l = linkList{at: time.Now(), to: parseLinks(string(out))} + links.Lock() + if links.m == nil { + links.m = map[string]linkList{} + } + links.m[key] = l + links.Unlock() + } + to, ok := l.to[name] + if !ok || to == "" { + return "", false + } + if !strings.HasPrefix(to, "/") { + to = path.Join(d.native(dir), to) + } + return d.where(path.Clean(to)), true +} + +// parseLinks reads wslLinksScript's lines. +func parseLinks(out string) map[string]string { + m := map[string]string{} + for _, line := range strings.Split(strings.ReplaceAll(out, "\r\n", "\n"), "\n") { + if name, to, ok := strings.Cut(line, "\t"); ok && name != "" { + m[name] = to + } + } + return m +} + +// WSLInDistro is whether local, a path of a's as magpie opens it, is in +// the distro's own files (under \\wsl.localhost\), not on a +// Windows drive a link there leads to: where the distro can make a link +// magpie reads back. +func WSLInDistro(a *Agent, local string) bool { + d, err := agentDistro(a) + if err != nil || local == "" { + return false + } + _, ok := below(local, d.Root) + return ok +} diff --git a/internal/agent/wsl_links_test.go b/internal/agent/wsl_links_test.go new file mode 100644 index 000000000..f2005196c --- /dev/null +++ b/internal/agent/wsl_links_test.go @@ -0,0 +1,139 @@ +package agent + +import ( + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" + "time" +) + +// A link made in a distro (WSLSymlink) is read back where Windows can't +// read it (WSLReadlink), made again over itself, never over a folder, and +// taken away alone (WSLRemoveLink), what it leads to left as it is. +func TestWSLLinks(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the fake distro's links are this system's") + } + root := t.TempDir() + t.Cleanup(FakeWSL(map[string]string{"U": "home:/home/me\ndir:.codex\n"}, map[string]string{"U": root})) + wslDistros() + a := &Agent{ID: "codex@wsl:U", WSL: "U"} + home := filepath.Join(root, "home", "me") + store := filepath.Join(home, ".local", "share", "magpie", "skills", "pdf") + if err := os.MkdirAll(store, 0o755); err != nil { + t.Fatal(err) + } + link := filepath.Join(home, ".codex", "skills", "pdf") + for range 2 { + if err := WSLSymlink(a, store, link); err != nil { + t.Fatal(err) + } + } + if got, ok := WSLReadlink(link); !ok || got != store { + t.Fatalf("read back: %q %v", got, ok) + } + if _, ok := WSLReadlink(filepath.Join(home, ".codex", "skills", "none")); ok { + t.Error("a name that isn't there read as a link") + } + if _, ok := WSLReadlink(filepath.Join(t.TempDir(), "x")); ok { + t.Error("a path in no distro read as a link") + } + if err := WSLSymlink(a, store, filepath.Dir(store)); err == nil || !strings.Contains(err.Error(), "is not a link") { + t.Errorf("a link made over a folder: %v", err) + } + if err := WSLRemoveLink(store); err == nil { + t.Error("a folder removed as a link") + } + if err := WSLRemoveLink(link); err != nil { + t.Fatal(err) + } + if _, err := os.Lstat(link); !os.IsNotExist(err) { + t.Errorf("the link is still there: %v", err) + } + if _, ok := WSLReadlink(link); ok { + t.Error("a link taken away still reads as one") + } + if _, err := os.Stat(store); err != nil { + t.Errorf("what it led to went with it: %v", err) + } +} + +// On a real WSL: MAGPIE_WSL_TEST_DISTRO names the distro, and the test +// works only in a folder of its own it makes in /tmp there. What Windows +// can't do through \\wsl.localhost (read, follow or remove a link the +// distro has) is done in the distro, and the distro follows the link. +func TestWSLLinksLive(t *testing.T) { + name := os.Getenv("MAGPIE_WSL_TEST_DISTRO") + if name == "" || runtime.GOOS != "windows" { + t.Skip("MAGPIE_WSL_TEST_DISTRO not set") + } + t.Setenv("PATH", filepath.Join(os.Getenv("SystemRoot"), "System32")+string(os.PathListSeparator)+os.Getenv("PATH")) + base := "/tmp/magpie-wsl-links-" + strconv.FormatInt(time.Now().UnixNano(), 36) + sh := func(script string, args ...string) string { + t.Helper() + out, err := realWSLRun(30*time.Second, append([]string{"-d", name, "--exec", "sh", "-c", script, "sh"}, args...)...) + if err != nil { + t.Fatalf("%s: %v %s", script, err, out) + } + return strings.TrimSpace(string(out)) + } + sh(`mkdir -p -- "$1/store/pdf" && printf 'Read PDFs' > "$1/store/pdf/SKILL.md"`, base) + t.Cleanup(func() { sh(`rm -rf -- "$1"`, base) }) + wsl.Lock() + seen, running, runAt, runOK := wsl.seen, wsl.running, wsl.runAt, wsl.runOK + wsl.seen = map[string]*distro{name: {Name: name, Home: base, Root: wslRoot(name)}} + wsl.running, wsl.runAt, wsl.runOK = map[string]bool{name: true}, time.Now(), true + wsl.Unlock() + t.Cleanup(func() { + wsl.Lock() + wsl.seen, wsl.running, wsl.runAt, wsl.runOK = seen, running, runAt, runOK + wsl.Unlock() + }) + d := wsl.seen[name] + a := &Agent{ID: "codex@wsl:" + name, WSL: name} + store, link := d.where(base+"/store/pdf"), d.where(base+"/agent/skills/pdf") + if b, err := os.ReadFile(filepath.Join(store, "SKILL.md")); err != nil || string(b) != "Read PDFs" { + t.Fatalf("the distro's folder through %s: %q %v", d.Root, b, err) + } + for range 2 { + if err := WSLSymlink(a, store, link); err != nil { + t.Fatal(err) + } + } + if got := sh(`readlink -- "$1"`, base+"/agent/skills/pdf"); got != base+"/store/pdf" { + t.Fatalf("the distro's link leads to %q", got) + } + if got := sh(`cat -- "$1/SKILL.md"`, base+"/agent/skills/pdf"); got != "Read PDFs" { + t.Fatalf("the distro reads through the link: %q", got) + } + // what Windows makes of it, as the library meets it + fi, err := os.Lstat(link) + t.Logf("Windows' Lstat of the link: %v %v", fi, err) + if err != nil { + t.Fatalf("Windows doesn't see the link: %v", err) + } + if _, err := os.Readlink(link); err == nil { + t.Log("Windows reads the link itself") + } + if got, ok := WSLReadlink(link); !ok || !strings.EqualFold(filepath.Clean(got), filepath.Clean(store)) { + t.Fatalf("read back %q %v, want %q", got, ok, store) + } + if err := WSLSymlink(a, store, filepath.Dir(store)); err == nil || !strings.Contains(err.Error(), "is not a link") { + t.Errorf("a link made over a folder: %v", err) + } + if err := WSLRemoveLink(store); err == nil { + t.Error("a folder removed as a link") + } + if err := WSLRemoveLink(link); err != nil { + t.Fatal(err) + } + if got := sh(`[ -e "$1" ] || [ -L "$1" ] && echo there || echo gone`, base+"/agent/skills/pdf"); got != "gone" { + t.Errorf("the link: %s", got) + } + if got := sh(`cat -- "$1/SKILL.md"`, base+"/store/pdf"); got != "Read PDFs" { + t.Errorf("what it led to: %q", got) + } +} diff --git a/internal/library/library.go b/internal/library/library.go index 364aca6e9..892651dcd 100644 --- a/internal/library/library.go +++ b/internal/library/library.go @@ -80,6 +80,9 @@ type Library struct { // blockedSkills are copies takeEdits couldn't scan, kept in place for // this sync rather than replaced or removed. Keys are physical paths. blockedSkills map[string]bool + // stored are the skills this sync made sure of in a WSL distro's + // store, by path (storeSkill), with what went wrong + stored map[string]error } // Instructions are one shared text, and for each agent whether it gets it diff --git a/internal/library/linkmemo.go b/internal/library/linkmemo.go index 41292dbf0..1edc9ed4e 100644 --- a/internal/library/linkmemo.go +++ b/internal/library/linkmemo.go @@ -18,6 +18,8 @@ import ( "os" "sync" "sync/atomic" + + "github.com/yetone/magpie/internal/agent" ) // part is what one entry on the way to a path is: there or not, and @@ -67,6 +69,9 @@ func lookPart(p string) part { return e } +// wslReadlink is agent.WSLReadlink; a var for tests. +var wslReadlink = agent.WSLReadlink + // lookAt is statPart; a test counts the looks var lookAt = statPart @@ -83,6 +88,12 @@ func statPart(p string) (e part, sure bool) { } to, err := os.Readlink(p) if err != nil || to == "" { + // a link a WSL distro has, which Windows can't read through + // \\wsl.localhost: the distro says where it leads + // (agent.WSLReadlink) + if w, ok := wslReadlink(p); ok { + return part{there: true, link: true, to: w}, true + } // a link that can't be read is taken as an entry of its own, as // before; but it isn't kept return part{there: true}, false diff --git a/internal/library/skill_edits.go b/internal/library/skill_edits.go index b7c778e68..fd69dbcf6 100644 --- a/internal/library/skill_edits.go +++ b/internal/library/skill_edits.go @@ -48,6 +48,11 @@ func (l *Library) takeEdits(targets []*Target, res *Result) { continue } p := filepath.Join(t.Skills, s.Name) + // an agent in WSL linked to magpie's copy there: an edit made + // through the link is in that copy (wsl_skills.go) + if t.Store != "" && ours(p, s.Name) && linked(p) { + p = filepath.Join(t.Store, s.Name) + } if !ours(p, s.Name) || linked(p) || seen[realDir(p)] { continue } diff --git a/internal/library/skills.go b/internal/library/skills.go index 3b8de4de3..17a67cf8d 100644 --- a/internal/library/skills.go +++ b/internal/library/skills.go @@ -22,6 +22,7 @@ import ( "time" "unicode" + "github.com/yetone/magpie/internal/agent" "github.com/yetone/magpie/internal/source" "gopkg.in/yaml.v3" ) @@ -203,13 +204,14 @@ const marker = ".magpie-library" // ours reports whether the entry at p is magpie's link (or copy) of the // library's skill by that name. func ours(p, name string) bool { - fi, err := os.Lstat(p) - if err != nil { - return false + // a link in a WSL distro is read there (linkTarget), Windows can't; + // one to magpie's copy in the distro is magpie's (wsl_skills.go) + if to, ok := linkTarget(p); ok { + return filepath.Clean(to) == filepath.Clean(skillDir(name)) || inWSLStore(to, name) } - if linkEntry(fi) { - to, err := os.Readlink(p) - return err == nil && filepath.Clean(to) == filepath.Clean(skillDir(name)) + fi, err := os.Lstat(p) + if err != nil || linkEntry(fi) { + return false } if fi.IsDir() { _, err := os.Stat(filepath.Join(p, marker)) @@ -404,7 +406,15 @@ func unlink(p string) error { return nil } if linkEntry(fi) { - return os.Remove(p) + err := os.Remove(p) + // a link a WSL distro has can't be removed from Windows: the + // distro removes it + if err != nil { + if _, ok := wslReadlink(p); ok { + return agent.WSLRemoveLink(p) + } + } + return err } return os.RemoveAll(p) } @@ -628,6 +638,20 @@ func (l *Library) syncSkills(t *Target, res *Result, all []*Target) { } continue } + // in a WSL distro, magpie's one copy there is what the agent's + // link leads to (wsl_skills.go): made, or made again, first + if t.Store != "" && !cp { + if made, err := l.storeSkill(t, s.Name); err != nil { + res.fail(id, "skill:"+s.Name, err) + if ours(p, s.Name) && !slices.Contains(mine, s.Name) { + mine = append(mine, s.Name) + } + continue + } else if made && ours(p, s.Name) && linked(p) { + // what its link leads to is new + res.changed(id) + } + } // kept in ~/.agents/skills under another name (sharedEntry): the // agent whose folder that is has it there already, and a link by // this name too would be the skill twice for every reader of it @@ -660,7 +684,11 @@ func (l *Library) syncSkills(t *Target, res *Result, all []*Target) { // (#896), unless no link can be made here (Windows without the // right to), where the copy stays if ours(p, s.Name) && !cp && !linked(p) { - if ok, err := relink(id, p, s.Name); err != nil { + rl := relink + if t.Store != "" { + rl = l.wslRelink(t) + } + if ok, err := rl(id, p, s.Name); err != nil { res.fail(id, "skill:"+s.Name, err) continue } else if ok { @@ -707,6 +735,8 @@ func (l *Library) syncSkills(t *Target, res *Result, all []*Target) { put := link if cp { put = copyIn + } else if t.Store != "" { + put = func(p, name string) error { return agent.WSLSymlink(t.Agent, filepath.Join(t.Store, name), p) } } if err := put(p, s.Name); err != nil { res.fail(id, "skill:"+s.Name, err) diff --git a/internal/library/skills_copy_test.go b/internal/library/skills_copy_test.go index cabd805d6..fa7bf86f3 100644 --- a/internal/library/skills_copy_test.go +++ b/internal/library/skills_copy_test.go @@ -155,7 +155,7 @@ func TestSkillCopySwapSurvivesAnUndeletableFile(t *testing.T) { } } -// An agent in WSL (a t.Copy target) gets its copy made again through the +// An agent in WSL set to take copies gets its copy made again through the // same swap: with a file in its old copy that can't be removed, it still // gets the whole new copy, magpie still knows it for its own, and the // leftover is cleared by a later sync. @@ -170,6 +170,7 @@ func TestWSLSkillCopySwapSurvivesAnUndeletableFile(t *testing.T) { src := filepath.Join(home(), "src", "skills") skill(t, filepath.Join(src, "pdf"), "pdf", "Read PDFs") write(t, filepath.Join(src, "pdf/sub/forms.md"), "forms one") + ok(t)(SetSkillHow(wslCodex, HowCopy)) ok(t)(InstallSkills(src, []string{"pdf"}, []string{wslCodex})) p := filepath.Join(h, ".codex/skills/pdf") if linked(p) || !ours(p, "pdf") || read(t, filepath.Join(p, "sub/forms.md")) != "forms one" { diff --git a/internal/library/sync.go b/internal/library/sync.go index 43bd3fa35..a136832ac 100644 --- a/internal/library/sync.go +++ b/internal/library/sync.go @@ -133,6 +133,8 @@ func syncSteps(all, gone []*Target, b *backups, res *Result) []func(*Library) { } } } + // magpie's copies in a WSL distro no agent there is linked to any more + steps = append(steps, func(l *Library) { l.sweepWSLStores(append(slices.Clone(all), gone...), res) }) return append(steps, func(l *Library) { l.syncProjects(res) }) } diff --git a/internal/library/targets.go b/internal/library/targets.go index b9de6c031..85a674280 100644 --- a/internal/library/targets.go +++ b/internal/library/targets.go @@ -38,9 +38,15 @@ type Target struct { // Note is what the page says of the agent's instructions file. Note string // Copy is an agent that gets a copy of each skill, made again when - // the library's changes, rather than a link: one in a WSL distro, - // which can't follow a link to a Windows folder. + // the library's changes, rather than a link: one in a WSL distro whose + // skills folder is on a Windows drive (wslStored). Copy bool + // Store, for an agent in a WSL distro, is magpie's folder there + // (wslStoreRel) holding one copy of each skill given to the distro's + // agents, as magpie opens it: each agent gets a link the distro makes + // to that copy, as it can't follow one to a Windows folder + // (wsl_skills.go). + Store string // Desktop are Claude Desktop's skills-plugin folders, one for each // account (desktop_skills.go): each gets a copy of the skills and their // entries in its manifest.json. Skills is the first one's skills. @@ -635,13 +641,14 @@ func pluginTarget(a *agent.Agent) *Target { // distro is stopped, which opening them would start (asked again here: the // agent may have been made before the user stopped it). What is written is // the same as for this machine's agent: nothing in it names a place on -// Windows, and each skill is a copy. +// Windows, and each skill is a link the distro makes to magpie's one copy +// of it there (wsl_skills.go). func wslTargetOf(a *agent.Agent) *Target { h := a.Home if h == "" || !agent.WSLRunning(a.WSL) { return nil } - t := &Target{Agent: a, Copy: true} + t := &Target{Agent: a} // a folder there that is a link is opened where it leads (#4502) j := func(elem ...string) string { return wslOpen(t, filepath.Join(elem...)) } id, _, _ := strings.Cut(a.ID, "@") @@ -721,6 +728,7 @@ func wslTargetOf(a *agent.Agent) *Target { return wslOwnFolder(a) } wslOpened(t) + wslStored(t, h) if t.MCP != nil { // a Windows program isn't given to it (mcpFile.side) t.MCP.WSL, t.MCP.Distro, t.MCP.Home = true, a.WSL, linuxHome(h) @@ -789,8 +797,9 @@ func wslOwnFolder(a *agent.Agent) *Target { if t == nil { return nil } - t.Agent, t.Copy = a, true + t.Agent, t.Copy = a, false wslOpened(t) + wslStored(t, a.Home) if t.MCP != nil { t.MCP.WSL, t.MCP.Distro, t.MCP.Home = true, a.WSL, linuxHome(a.Home) } diff --git a/internal/library/wsl_asleep.go b/internal/library/wsl_asleep.go index 7e71b17f2..30e68a75e 100644 --- a/internal/library/wsl_asleep.go +++ b/internal/library/wsl_asleep.go @@ -115,9 +115,9 @@ func (l *Library) asleepView(a *agent.Agent) (AgentView, bool) { av.MCP, av.Skills, av.SkillsAlso, av.MCPVia = sh.MCP, sh.Skills, sh.SkillsAlso, sh.MCPVia av.NoSSE, av.NoRemote, av.NoEnvRefs, av.ToolsOff, av.Startup = sh.NoSSE, sh.NoRemote, sh.NoEnvRefs, sh.ToolsOff, sh.Startup if sh.Skills != "" { - // a WSL agent takes copies only (Target.Copy) + // as a running one's: links to magpie's copy there, or copies _, av.HowOwn = l.SkillHow[a.ID] - av.How, av.MustCopy = HowCopy, true + av.How = l.howOf(a.ID) } return av, true } diff --git a/internal/library/wsl_mcp_test.go b/internal/library/wsl_mcp_test.go index e3ada6321..0bd80242e 100644 --- a/internal/library/wsl_mcp_test.go +++ b/internal/library/wsl_mcp_test.go @@ -127,7 +127,7 @@ func TestWSLMCPSiblings(t *testing.T) { t.Errorf("%s isn't a target: %v", id, ids(Targets())) continue } - if tg.MCP == nil || tg.MCP.Path != filepath.Join(h, f) || !tg.MCP.WSL || tg.MCP.Distro != "Ubuntu" || !tg.Copy { + if tg.MCP == nil || tg.MCP.Path != filepath.Join(h, f) || !tg.MCP.WSL || tg.MCP.Distro != "Ubuntu" || tg.Copy || tg.Skills != "" && tg.Store == "" { t.Errorf("%s: mcp %+v", id, tg.MCP) } // nothing it is given is this machine's diff --git a/internal/library/wsl_own_test.go b/internal/library/wsl_own_test.go index aef2fe314..4853f3085 100644 --- a/internal/library/wsl_own_test.go +++ b/internal/library/wsl_own_test.go @@ -39,7 +39,7 @@ func TestWSLOwnFolderTargets(t *testing.T) { t.Errorf("%s isn't a target: %v", id, ids(Targets())) continue } - if tg.MCP == nil || tg.MCP.Path != filepath.Join(h, w[0]) || !tg.MCP.WSL || tg.MCP.Distro != "Ubuntu" || tg.Skills != filepath.Join(h, w[1]) || !tg.Copy || tg.Agent.ID != id { + if tg.MCP == nil || tg.MCP.Path != filepath.Join(h, w[0]) || !tg.MCP.WSL || tg.MCP.Distro != "Ubuntu" || tg.Skills != filepath.Join(h, w[1]) || tg.Copy || tg.Store != filepath.Join(h, ".local/share/magpie/skills") || tg.Agent.ID != id { t.Errorf("%s: %+v (mcp %+v)", id, tg, tg.MCP) } } @@ -52,8 +52,8 @@ func TestWSLOwnFolderTargets(t *testing.T) { skill(t, filepath.Join(src, "pdf"), "pdf", "Read PDFs") ok(t)(InstallSkills(src, []string{"pdf"}, []string{hermes})) p := filepath.Join(h, ".hermes", "skills", "pdf") - if fi, err := os.Lstat(p); err != nil || !fi.IsDir() || !ours(p, "pdf") { - t.Fatalf("hermes@wsl has no copy of the skill: %v", err) + if to, err := os.Readlink(p); err != nil || to != filepath.Join(h, ".local/share/magpie/skills/pdf") || !ours(p, "pdf") { + t.Fatalf("hermes@wsl has no link to the distro's copy of the skill: %q %v", to, err) } if _, err := os.Lstat(filepath.Join(home(), ".hermes", "skills", "pdf")); !os.IsNotExist(err) { t.Errorf("this machine's Hermes got it: %v", err) diff --git a/internal/library/wsl_skills.go b/internal/library/wsl_skills.go new file mode 100644 index 000000000..93850b207 --- /dev/null +++ b/internal/library/wsl_skills.go @@ -0,0 +1,193 @@ +package library + +// Skills in a WSL distro (cutemmuu on X). An agent there can't follow a +// link to the library's folder on Windows, and Windows can't make a link +// there that the distro follows (one os.Symlink makes through +// \\wsl.localhost is an empty folder in the distro), so each agent in a +// distro used to get a copy of its own of every skill. Now the distro +// holds one copy of each skill its agents are given, magpie's, in +// ~/.local/share/magpie/skills (Target.Store); each agent there gets a +// link to it, made in the distro by wsl.exe (agent.WSLSymlink), as an +// agent on Windows gets one to the library's folder. An edit made in an +// agent through its link is in that copy, which takeEdits looks at as it +// does at any copy of magpie's. An agent set to take copies (SkillHow) +// still gets a copy of its own. +// +// The copy isn't put in the distro's ~/.agents/skills: every agent there +// that reads that folder would find each skill in it, ticked for it or +// not, and the ticks are per agent. + +import ( + "errors" + "os" + "path/filepath" + "strings" + + "github.com/yetone/magpie/internal/agent" +) + +// wslStoreRel is magpie's folder for skills in a distro, below its home. +var wslStoreRel = []string{".local", "share", "magpie", "skills"} + +// wslStored gives t, an agent's target in a WSL distro whose home magpie +// opens at home, the distro's store of skills, unless it has no skills. +// An agent whose skills folder is on a Windows drive (its folder a link +// to /mnt/c/…, #4502), or a store that is, keeps copies of its own: a +// link the distro makes there is one Windows can neither read nor follow. +func wslStored(t *Target, home string) { + if t.Skills == "" || home == "" { + return + } + store := wslOpen(t, filepath.Join(append([]string{home}, wslStoreRel...)...)) + if !agent.WSLInDistro(t.Agent, t.Skills) || !agent.WSLInDistro(t.Agent, store) { + t.Copy = true + return + } + t.Store = store +} + +// inWSLStore is whether to, a path as magpie opens it, is a skill by that +// name in a distro's store: what magpie's link in an agent there leads to. +func inWSLStore(to, name string) bool { + parts := strings.FieldsFunc(filepath.ToSlash(to), func(r rune) bool { return r == '/' || r == '\\' }) + n := len(parts) + if n < len(wslStoreRel)+1 || parts[n-1] != name { + return false + } + for i, p := range wslStoreRel { + if !strings.EqualFold(parts[n-1-len(wslStoreRel)+i], p) { + return false + } + } + return true +} + +// storeSkill makes the distro's copy of the skill (t.Store), or makes it +// again when the library's has changed since; looked at once a sync step +// for each store, and changed says this call made it. A folder there +// that isn't magpie's copy is never touched. +func (l *Library) storeSkill(t *Target, name string) (changed bool, err error) { + p := filepath.Join(t.Store, name) + key := strings.ToLower(p) + if err, ok := l.stored[key]; ok { + return false, err + } + changed, err = func() (bool, error) { + fi, err := os.Lstat(p) + if err != nil { + return true, copyIn(p, name) + } + if !fi.IsDir() || !ours(p, name) { + return false, errors.New(p + " is in the way of magpie's copy of " + name + " in WSL") + } + dropOld(p, name) + h := l.libHash(name) + if h == "" { + return false, nil + } + current, err := copyIsFresh(p, h, l.untouched[p]) + if err != nil || current { + return false, err + } + return true, copyIn(p, name) + }() + if l.stored == nil { + l.stored = map[string]error{} + } + l.stored[key] = err + return changed && err == nil, err +} + +// wslRelink is relink for t, an agent in a WSL distro: its copy of the +// skill made a link the distro makes to the distro's copy (storeSkill). +// The copy is moved aside first, since the distro won't put a link in a +// folder's place, and put back when no link can be made. A copy that +// differs from the library's skill (edited, and its edit lost) is kept +// aside with the backups rather than lost. +func (l *Library) wslRelink(t *Target) func(id, p, name string) (bool, error) { + return func(id, p, name string) (bool, error) { + current, err := copyIsFresh(p, l.libHash(name), l.untouched[p]) + if err != nil { + return false, err + } + old := oldPath(p, name) + if err := os.Rename(p, old); err != nil { + return false, err + } + if err := agent.WSLSymlink(t.Agent, filepath.Join(t.Store, name), p); err != nil { + if back := os.Rename(old, p); back != nil { + return false, errors.Join(err, back) + } + return false, err + } + if current { + // best effort: what's left is tried again on the next sync + os.RemoveAll(old) + } else if _, err := setAside(id, old); err != nil { + return true, err + } + return true, nil + } +} + +// sweepWSLStores takes out of each distro's store the copies no agent +// there has a link to, or is given, any more. A copy edited since magpie +// made it is kept aside with the backups. A store with an agent that +// couldn't be reached is left as it is: that agent may still link to any. +func (l *Library) sweepWSLStores(targets []*Target, res *Result) { + type store struct { + path string + owner string + keep map[string]bool + frozen bool + } + stores := map[string]*store{} + for _, t := range targets { + if t.Store == "" { + continue + } + key := strings.ToLower(t.Store) + s := stores[key] + if s == nil { + s = &store{path: t.Store, owner: t.Agent.ID, keep: map[string]bool{}} + stores[key] = s + } + if t.Unreached != nil { + s.frozen = true + } + for _, sk := range l.Skills { + if sk.gives(t.Agent.ID) { + s.keep[sk.Name] = true + } + } + for _, name := range l.applied(t.Agent.ID).Skills { + s.keep[name] = true + } + } + for _, s := range stores { + if s.frozen { + continue + } + es, err := os.ReadDir(s.path) + if err != nil { + continue + } + for _, e := range es { + name := e.Name() + p := filepath.Join(s.path, name) + if strings.HasPrefix(name, ".") || s.keep[name] || !ours(p, name) || linked(p) { + continue + } + dropOld(p, name) + h, _ := markedHash(p) + if h != "" && hashDir(p) == h { + err = os.RemoveAll(p) + } else { + _, err = setAside(s.owner, p) + } + if err != nil { + res.fail(s.owner, "skill:"+name, err) + } + } + } +} diff --git a/internal/library/wsl_skills_test.go b/internal/library/wsl_skills_test.go new file mode 100644 index 000000000..7e64a72df --- /dev/null +++ b/internal/library/wsl_skills_test.go @@ -0,0 +1,229 @@ +package library + +import ( + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/agent" +) + +// The copies each agent in WSL got of its own before (cutemmuu on X) are +// links to the distro's one copy after the next sync: one edited in an +// agent, its edit the newest, goes to the library and every agent first; +// one whose edit lost is kept with the backups; a skill folder of the +// user's own beside them, and one they put where magpie's copy goes, are +// never touched. +func TestWSLOldCopiesBecomeLinks(t *testing.T) { + h := wslSandbox(t) + src := filepath.Join(home(), "src", "skills") + skill(t, filepath.Join(src, "pdf"), "pdf", "Read PDFs") + skill(t, filepath.Join(src, "csv"), "csv", "Read CSVs") + // what magpie gave them before: a marked copy in each + for _, id := range []string{wslCodex, wslClaude, wslPi} { + ok(t)(SetSkillHow(id, HowCopy)) + } + ok(t)(InstallSkills(src, []string{"pdf", "csv"}, []string{"claude", wslCodex, wslClaude, wslPi})) + cx, cl, pi := filepath.Join(h, ".codex/skills"), filepath.Join(h, ".claude/skills"), filepath.Join(h, ".pi/agent/skills") + for _, d := range []string{cx, cl, pi} { + if isLink(t, filepath.Join(d, "pdf")) || !ours(filepath.Join(d, "pdf"), "pdf") { + t.Fatalf("%s: no copy of the old kind to start from", d) + } + } + // Codex's pdf edited in the distro; Claude Code's csv edited, then the + // library's after it, so Claude Code's loses + time.Sleep(20 * time.Millisecond) + write(t, filepath.Join(cx, "pdf/SKILL.md"), "---\nname: pdf\ndescription: Edited in WSL Codex\n---\n") + write(t, filepath.Join(cl, "csv/SKILL.md"), "---\nname: csv\ndescription: Edited in WSL Claude\n---\n") + time.Sleep(20 * time.Millisecond) + write(t, filepath.Join(src, "csv/SKILL.md"), "---\nname: csv\ndescription: Edited by hand\n---\n") + // the user's own skill beside them, and a folder of theirs where + // magpie's copy of pdf would go + write(t, filepath.Join(cl, "mine/SKILL.md"), "---\nname: mine\ndescription: Mine\n---\n") + store := filepath.Join(h, ".local/share/magpie/skills") + write(t, filepath.Join(store, "csv/SKILL.md"), "the user's own csv") + + // the update: no way of their own set any more, as a user who never + // picked one has + var problems []Problem + for _, id := range []string{wslCodex, wslClaude, wslPi} { + res, err := SetSkillHow(id, "") + if err != nil { + t.Fatal(err) + } + problems = append(problems, res.Problems...) + } + // the user's csv in magpie's place is said, for each agent given csv + for _, p := range problems { + if p.What != "skill:csv" || !strings.Contains(p.Error, "in the way of magpie's copy of csv") { + t.Errorf("problem: %+v", p) + } + } + t.Logf("problems: %+v", problems) + for _, d := range []string{cx, cl, pi} { + p := filepath.Join(d, "pdf") + if to, err := os.Readlink(p); err != nil || to != filepath.Join(store, "pdf") { + t.Errorf("%s: not a link to the distro's copy: %q %v", p, to, err) + } + if s := read(t, filepath.Join(p, "SKILL.md")); !strings.Contains(s, "Edited in WSL Codex") { + t.Errorf("%s lost Codex's edit:\n%s", p, s) + } + } + if s := read(t, filepath.Join(src, "pdf/SKILL.md")); !strings.Contains(s, "Edited in WSL Codex") { + t.Errorf("the library didn't take Codex's edit:\n%s", s) + } + if !backedUp(t, "Edited in WSL Claude") { + t.Error("Claude Code's edit, which lost, wasn't kept") + } + if s := read(t, filepath.Join(h, ".claude/skills/mine/SKILL.md")); !strings.Contains(s, "Mine") { + t.Errorf("the user's own skill: %q", s) + } + // csv's place in the store is the user's: nothing is put there, and + // the agents keep what they had of it + if s := read(t, filepath.Join(store, "csv/SKILL.md")); s != "the user's own csv" { + t.Errorf("the user's folder in magpie's place was written over: %q", s) + } + for _, d := range []string{cx, cl, pi} { + if p := filepath.Join(d, "csv"); isLink(t, p) || !ours(p, "csv") { + t.Errorf("%s: what it had of csv is gone", p) + } + } + if s := read(t, filepath.Join(home(), ".claude/skills/pdf/SKILL.md")); !strings.Contains(s, "Edited in WSL Codex") { + t.Errorf("this machine's Claude Code:\n%s", s) + } +} + +// "User edits it, then sync": an edit made in an agent in WSL, through its +// link, is in the distro's copy, and the sync takes it into the library +// rather than making the copy again over it; every agent has it after. +func TestWSLEditThroughLinkReachesTheLibrary(t *testing.T) { + h := wslSandbox(t) + src := filepath.Join(home(), "src", "skills") + skill(t, filepath.Join(src, "pdf"), "pdf", "Read PDFs") + ok(t)(InstallSkills(src, []string{"pdf"}, []string{"claude", wslCodex, wslClaude})) + time.Sleep(20 * time.Millisecond) + write(t, filepath.Join(h, ".codex/skills/pdf/SKILL.md"), "---\nname: pdf\ndescription: Edited through the link\n---\n") + for range 2 { // a sync, and the one of the next start + ok(t)(Sync()) + for _, p := range []string{filepath.Join(src, "pdf"), filepath.Join(home(), ".claude/skills/pdf"), filepath.Join(h, ".claude/skills/pdf")} { + if s := read(t, filepath.Join(p, "SKILL.md")); !strings.Contains(s, "Edited through the link") { + t.Fatalf("%s after a sync:\n%s", p, s) + } + } + } + if !isLink(t, filepath.Join(h, ".codex/skills/pdf")) { + t.Error("Codex's link was made a copy") + } +} + +// A skill an agent in WSL had of its own, the very same files, gives way +// to the link, kept aside; and a skill no agent there is given any more +// that was edited in the distro's copy is kept, not deleted. +func TestWSLStoreSweepKeepsEdits(t *testing.T) { + h := wslSandbox(t) + src := filepath.Join(home(), "src", "skills") + skill(t, filepath.Join(src, "pdf"), "pdf", "Read PDFs") + ok(t)(InstallSkills(src, []string{"pdf"}, []string{wslCodex})) + store := filepath.Join(h, ".local/share/magpie/skills/pdf") + // edited in the distro's copy and unticked in one change: the edit is + // taken first, then the copy goes + time.Sleep(20 * time.Millisecond) + write(t, filepath.Join(store, "SKILL.md"), "---\nname: pdf\ndescription: Edited in the store\n---\n") + ok(t)(SkillAgents("pdf", []string{})) + if _, err := os.Lstat(store); !os.IsNotExist(err) { + t.Errorf("the distro's copy is still there: %v", err) + } + if s := read(t, filepath.Join(src, "pdf/SKILL.md")); !strings.Contains(s, "Edited in the store") && !backedUp(t, "Edited in the store") { + t.Error("the edit in the distro's copy was lost") + } +} + +// On a real WSL (MAGPIE_WSL_TEST_DISTRO, on Windows): the agents of a +// distro whose home is a folder of the test's own in /tmp there get links +// the distro makes and follows, which magpie reads back through wsl.exe +// (Windows can't), so a sync with nothing new changes nothing; an edit +// made in the distro's copy reaches the library; a way of copies takes +// the link away for a copy and back; unticked, the links and the copy go. +func TestWSLSkillsLinkedLive(t *testing.T) { + name := os.Getenv("MAGPIE_WSL_TEST_DISTRO") + if name == "" || runtime.GOOS != "windows" { + t.Skip("MAGPIE_WSL_TEST_DISTRO not set") + } + t.Setenv("PATH", filepath.Join(os.Getenv("SystemRoot"), "System32")+string(os.PathListSeparator)+os.Getenv("PATH")) + sh := func(script string, args ...string) string { + t.Helper() + cmd := exec.Command("wsl.exe", append([]string{"-d", name, "--exec", "sh", "-c", script, "sh"}, args...)...) + cmd.Env = append(os.Environ(), "WSL_UTF8=1") + out, err := cmd.Output() + if err != nil { + t.Fatalf("%s: %v %s", script, err, out) + } + return strings.TrimSpace(string(out)) + } + base := "/tmp/magpie-wsl-skills-" + strconv.FormatInt(time.Now().UnixNano(), 36) + sh(`mkdir -p -- "$1/.codex" "$1/.claude" && printf 'model = "m"\n' > "$1/.codex/config.toml" && printf '{}\n' > "$1/.claude/settings.json"`, base) + t.Cleanup(func() { sh(`rm -rf -- "$1"`, base) }) + sandbox(t) + // the real wsl.exe, after the sandbox's PATH + t.Setenv("PATH", filepath.Join(os.Getenv("SystemRoot"), "System32")+string(os.PathListSeparator)+os.Getenv("PATH")) + root := `\\wsl.localhost\` + name + if _, err := os.Stat(root + `\`); err != nil { + root = `\\wsl$\` + name + } + t.Cleanup(agent.FakeWSL(map[string]string{name: "home:" + base + "\ndir:.codex\ndir:.claude\n"}, map[string]string{name: root})) + t.Cleanup(agent.FakeWSLRealLinks()) + codex, claude := "codex@wsl:"+name, "claude@wsl:"+name + h := filepath.Join(root, filepath.FromSlash(base)) + + src := filepath.Join(home(), "src", "skills") + skill(t, filepath.Join(src, "pdf"), "pdf", "Read PDFs") + ok(t)(InstallSkills(src, []string{"pdf"}, []string{"claude", codex, claude})) + for _, d := range []string{"/.codex/skills/pdf", "/.claude/skills/pdf"} { + if got := sh(`readlink -- "$1"`, base+d); got != base+"/.local/share/magpie/skills/pdf" { + t.Fatalf("%s leads to %q", d, got) + } + if got := sh(`cat -- "$1/SKILL.md"`, base+d); !strings.Contains(got, "Read PDFs") { + t.Fatalf("the distro reads through %s: %q", d, got) + } + if p := filepath.Join(h, filepath.FromSlash(d)); !ours(p, "pdf") || !linked(p) { + t.Fatalf("%s isn't magpie's link, as Windows reads it", p) + } + } + if res := ok(t)(Sync()); len(res.Changed) != 0 { + t.Errorf("a sync with nothing new wrote %v", res.Changed) + } + if v := viewOf(t, codex); v == nil || v.How != HowLink || v.MustCopy { + t.Errorf("Codex's row: %+v", v) + } + + // "user edits it, then sync", in the distro, through the link + time.Sleep(1100 * time.Millisecond) + sh(`printf -- '---\nname: pdf\ndescription: Edited in WSL\n---\n' > "$1/SKILL.md"`, base+"/.codex/skills/pdf") + ok(t)(Sync()) + for _, p := range []string{filepath.Join(src, "pdf"), filepath.Join(home(), ".claude/skills/pdf")} { + if s := read(t, filepath.Join(p, "SKILL.md")); !strings.Contains(s, "Edited in WSL") { + t.Errorf("%s after the edit in WSL:\n%s", p, s) + } + } + + // copies for Codex: its link goes for a copy, and back + ok(t)(SetSkillHow(codex, HowCopy)) + if got := sh(`[ -L "$1" ] && echo link || { [ -f "$1/.magpie-library" ] && echo copy; }`, base+"/.codex/skills/pdf"); got != "copy" { + t.Fatalf("Codex given copies has %q", got) + } + ok(t)(SetSkillHow(codex, "")) + if got := sh(`readlink -- "$1"`, base+"/.codex/skills/pdf"); got != base+"/.local/share/magpie/skills/pdf" { + t.Fatalf("Codex's copy made a link again leads to %q", got) + } + + ok(t)(SkillAgents("pdf", []string{"claude"})) + if got := sh(`for p in "$@"; do { [ -e "$p" ] || [ -L "$p" ]; } && echo "$p"; done; true`, + base+"/.codex/skills/pdf", base+"/.claude/skills/pdf", base+"/.local/share/magpie/skills/pdf"); got != "" { + t.Errorf("still there once unticked: %s", got) + } +} diff --git a/internal/library/wsl_test.go b/internal/library/wsl_test.go index c9a0daa9c..629f4afd6 100644 --- a/internal/library/wsl_test.go +++ b/internal/library/wsl_test.go @@ -61,7 +61,7 @@ func TestWSLTargets(t *testing.T) { } return filepath.Join(h, rel) } - if tg.Instructions != at(w[0]) || mcp != at(w[1]) || tg.Skills != at(w[2]) || !tg.Copy { + if tg.Instructions != at(w[0]) || mcp != at(w[1]) || tg.Skills != at(w[2]) || tg.Copy || tg.Store != at(".local/share/magpie/skills") { t.Errorf("%s: %+v (mcp %s)", id, tg, mcp) } } @@ -76,19 +76,25 @@ func TestWSLTargets(t *testing.T) { } } -// A skill reaches an agent in WSL as a copy — a link to a Windows folder -// is nothing it can follow — which is copied again when the library's -// changes, and taken away with the rest. -func TestWSLSkillsCopied(t *testing.T) { +// A skill reaches the agents in WSL as one copy in the distro, magpie's +// (~/.local/share/magpie/skills) — a link to a Windows folder is nothing +// they can follow — and each agent there a link the distro makes to it +// (cutemmuu on X). The copy is made again when the library's changes, +// and taken away once no agent there has it. +func TestWSLSkillsLinked(t *testing.T) { h := wslSandbox(t) src := filepath.Join(home(), "src", "skills") skill(t, filepath.Join(src, "pdf"), "pdf", "Read PDFs") ok(t)(InstallSkills(src, []string{"pdf"}, []string{"claude", wslCodex, wslClaude, wslPi})) + store := filepath.Join(h, ".local/share/magpie/skills/pdf") + if fi, err := os.Lstat(store); err != nil || !fi.IsDir() || !ours(store, "pdf") || !strings.Contains(read(t, filepath.Join(store, "SKILL.md")), "Read PDFs") { + t.Fatalf("no copy of magpie's in the distro: %v %v", fi, err) + } for _, d := range []string{".codex/skills/pdf", ".claude/skills/pdf", ".pi/agent/skills/pdf"} { p := filepath.Join(h, d) - fi, err := os.Lstat(p) - if err != nil || !fi.IsDir() { - t.Fatalf("%s: not a folder: %v", d, err) + to, err := os.Readlink(p) + if err != nil || to != store { + t.Fatalf("%s: not a link to the distro's copy: %q %v", d, to, err) } if !strings.Contains(read(t, filepath.Join(p, "SKILL.md")), "Read PDFs") || read(t, filepath.Join(p, "scripts/run.sh")) != "echo hi\n" || !ours(p, "pdf") { t.Errorf("%s isn't the library's skill", d) @@ -123,9 +129,16 @@ func TestWSLSkillsCopied(t *testing.T) { if _, err := os.Lstat(filepath.Join(h, ".codex/skills/pdf")); !os.IsNotExist(err) { t.Errorf("codex@wsl still has it: %v", err) } - if !ours(filepath.Join(h, ".claude/skills/pdf"), "pdf") { + if !ours(filepath.Join(h, ".claude/skills/pdf"), "pdf") || !ours(store, "pdf") { t.Error("claude@wsl lost it") } + // no agent in the distro given it: its copy there goes too + ok(t)(SkillAgents("pdf", []string{"claude"})) + for _, p := range []string{filepath.Join(h, ".claude/skills/pdf"), store} { + if _, err := os.Lstat(p); !os.IsNotExist(err) { + t.Errorf("%s is still there: %v", p, err) + } + } } // MCP servers are written into the distro's files in each agent's own @@ -341,7 +354,7 @@ func TestWSLStoppedListedAndQueued(t *testing.T) { if cx == nil { t.Fatal("a stopped distro's Codex isn't listed") } - if cx.Asleep != distro || cx.Unseen || cx.MCP != filepath.Join(h, ".codex", "config.toml") || cx.Skills != filepath.Join(h, ".codex", "skills") || !cx.NoSSE || !cx.MustCopy || cx.How != HowCopy { + if cx.Asleep != distro || cx.Unseen || cx.MCP != filepath.Join(h, ".codex", "config.toml") || cx.Skills != filepath.Join(h, ".codex", "skills") || !cx.NoSSE || cx.MustCopy || cx.How != HowLink { t.Errorf("Codex while stopped: %+v", *cx) } if cl := viewOf(t, wslClaude); cl == nil || cl.Asleep != distro || cl.MCP != filepath.Join(h, ".claude.json") || cl.NoSSE {