library: a skill from a folder follows GitHub once installed from there (biubiu8802 on X)

biubiu8802 (X, 2119602075864903924) downloaded a skill from GitHub and
put it in the Library from its folder, so it had nothing to update from
and no way to link it to GitHub. Installing it from its GitHub link now
links the two, the way an update of a CC Switch skill already does: the
library's skill by that name takes GitHub's files and GitHub as its
source. A check and an update cover it from then on, and the agents'
links keep pointing at it. When its own files aren't GitHub's, they go to
the backups like UpdateSkill's replace does, and the result says so. A
folder of the user's it was linked to stays as it is.

followsHere (skill_link.go) decides it. It links only a skill with no
remote source that wasn't renamed and is that skill: it traces to this
repository (CC Switch, the skills CLI's lock, a git checkout, From), or
it traces nowhere and its SKILL.md has the same description as GitHub's,
as an older download of it does. One traced to another repository, or
an untraced one that describes something else (mora1n's case,
TestInstallSetPutsAnotherByTheSameNameBeside), still goes in beside it
(skill_beside.go). A had skill with
the same files and no source is bound to the GitHub source it was found
in, so a later install of another repository's skill by that name goes
beside it, not over it (TestSameFilesByNameAreHad).

The probe marks such a candidate links:true. The GUI's Add list tags it
"links to GitHub" with a tooltip, and the report names "updates from
GitHub now" and "files of their own kept with the backups". The TUI's
probe list and result line say the same. The new strings are in zh,
zh-TW, ja and de.

Run on mote (macOS), on 64ecd0f69, then rebased on 8a58c0e30, whose
new commits touch none of internal/library, the TUI's library or the
library page:
- gofmt -l clean; go vet ./..., GOOS=windows go vet ./...,
  GOOS=linux go vet -tags nogui ./..., GOOS=linux go build -tags nogui
  ./..., GOOS=windows go build ./... all ok
- go test ./internal/library/... ok at this tree; ./internal/tui/...,
  ./internal/cli/... and ./internal/gui/ ok at the tree before the
  description check (that change touches internal/library only)
- GUI (chromium + webkit, 5 languages, wide and narrow):
  skill-install-link (new), skill-install-beside, skill-install-skip,
  skill-install-agents-all, skill-git-source, skill-too-big,
  provider-discovery, i18n-en-no-cjk pass. i18n-keys' "a plugin's words
  are its own" is red on main for three strings this change doesn't
  touch, already filed: #5332/#5327 ("View routing"), #5482 ("Use the
  library's"), #5426 ("No session ID").

Broken by hand: without the description check (the first version),
TestInstallSetPutsAnotherByTheSameNameBeside is red (caveman taken over).
followsHere returning false always turns
TestFolderSkillFollowsGitHub red (probed As:pdf-pro-biubiu) and
TestOwnSkillFollowsGitHubKeepsItsFiles red (linked [] kept []).

Not run: the full go test ./... suite. mote's suite lock had a queue
waiting up to 16h, so this change ran the packages it touches.
No real GitHub install either: the tests use a fake tarball server. Not
tried on Windows or Linux. The market's had-check (haveSkill) is
unchanged: a market skill with a folder copy by that name still counts
as had.
This commit is contained in:
yetone
2026-11-09 11:29:51 +08:00
parent 8a58c0e307
commit dc098c1e82
10 changed files with 396 additions and 6 deletions
+1
View File
@@ -92,6 +92,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
- 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).
- 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 skill already in the library keeps its name, folder and links; nothing is renamed after the fact. 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.
## Verification
@@ -592,10 +592,13 @@ magpie.plugin("library", (ctx) => {
// skills installed together (lc on Discord): those the library had
// already, and those left out because another by that name is in the
// way, are named, beside how many were installed
const had = res.had || [], skipped = res.skipped || [];
if (had.length || skipped.length) {
const had = res.had || [], skipped = res.skipped || [], linked = res.linked || [];
if (had.length || skipped.length || linked.length) {
const n = res.installed?.length || 0, parts = [];
if (n) parts.push(n === 1 ? t("1 skill installed") : t("{n} skills installed", { n }));
// a skill from a folder, linked to the one installed (skill_link.go)
if (linked.length) parts.push(t("updates from GitHub now: {names}", { names: linked.join(", ") }));
if (res.linkedKept?.length) parts.push(t("files of their own kept with the backups: {names}", { names: res.linkedKept.join(", ") }));
if (had.length) parts.push(t("already in the library: {names}", { names: had.join(", ") }));
for (const p of skipped) parts.push(t("{name} skipped: {error}", { name: p.what.replace(/^skill:/, ""), error: p.error }));
status(parts.join(" · "), skipped.length ? "warn" : "ok", skipped.length ? 12000 : 6000);
@@ -5617,6 +5620,9 @@ magpie.plugin("library", (ctx) => {
// this one is in the library, or goes in beside it, by its own
if (x.have && x.as) r.append(tag(t("In the library as {name}", { name: x.as }), "lib-as", t("In the library as {name}", { name: x.as })));
else if (x.have) r.append(tag(t("in the library"), ""));
// the library's by that name came from a folder (biubiu8802 on
// X): this one takes its place, and it follows GitHub from then on
else if (x.links) r.append(tag(t("links to GitHub"), "lib-as", t("The library's {name} came from a folder. This one takes its place and it updates from GitHub from then on; files of its own that differ are kept with the backups.", { name: x.name })));
else if (x.as) r.append(tag(t("adds as {name}", { name: x.as }), "lib-as", t("The library has another skill called {name}, from elsewhere. This one goes in beside it as {as}.", { name: x.name, as: x.as })));
list.append(r);
}
@@ -673,6 +673,8 @@ magpie.strings({
"1 skill installed": "已安装 1 个技能",
"{n} skills installed": "已安装 {n} 个技能",
"already in the library: {names}": "资源库里已有:{names}",
"updates from GitHub now: {names}": "现在从 GitHub 更新:{names}",
"files of their own kept with the backups: {names}": "原有文件已保留在备份里:{names}",
"{name} skipped: {error}": "已跳过 {name}:{error}",
"Install 1 skill": "安装 1 个技能",
"Install {n} skills": "安装 {n} 个技能",
@@ -803,6 +805,8 @@ magpie.strings({
"Remote · sign-in": "远程 · 需登录",
"In the library as {name}": "已在资源库中,名为 {name}",
"adds as {name}": "将添加为 {name}",
"links to GitHub": "链接到 GitHub",
"The library's {name} came from a folder. This one takes its place and it updates from GitHub from then on; files of its own that differ are kept with the backups.": "资源库里的 {name} 来自一个文件夹。这个会取代它,之后它从 GitHub 更新;与此不同的原有文件会保留在备份里。",
"The library has another skill called {name}, from elsewhere. This one goes in beside it as {as}.": "资源库里已有一个来自别处、同样叫 {name} 的技能。这一个会以 {as} 为名,和它并存。",
"Needs {what} to add": "添加时需要 {what}",
"Add…": "添加…",
@@ -916,6 +920,8 @@ magpie.strings({
"What the subagent is told before its task": "子代理開始任務前收到的指示",
"You are a careful code reviewer…": "你是一位細心的程式碼審閱者……",
"already in the library: {names}": "資源庫裡已有:{names}",
"updates from GitHub now: {names}": "現在從 GitHub 更新:{names}",
"files of their own kept with the backups: {names}": "原有檔案已保留在備份裡:{names}",
"{name} skipped: {error}": "已略過 {name}:{error}",
"Give skills as": "Skills 啟用方式",
"Each agent is given one server, magpie, in place of these. magpie runs each server once for all of them and hands each call to it, as server__tool. Restart an agent for it to read the change.": "每個 Agent 只拿到一個伺服器 magpie,代替這些伺服器。magpie 為所有 Agent 只執行每個伺服器一次,把每次呼叫轉給它,工具名稱為 server__tool。重新啟動 Agent 後生效。",
@@ -1626,6 +1632,8 @@ magpie.strings({
"Remote · sign-in": "遠端 · 需登入",
"In the library as {name}": "已在資源庫中,名為 {name}",
"adds as {name}": "將新增為 {name}",
"links to GitHub": "連結到 GitHub",
"The library's {name} came from a folder. This one takes its place and it updates from GitHub from then on; files of its own that differ are kept with the backups.": "資源庫裡的 {name} 來自一個資料夾。這個會取代它,之後它從 GitHub 更新;與此不同的原有檔案會保留在備份裡。",
"The library has another skill called {name}, from elsewhere. This one goes in beside it as {as}.": "資源庫裡已有一個來自別處、同樣叫 {name} 的技能。這一個會以 {as} 為名,和它並存。",
"Needs {what} to add": "新增時需要 {what}",
"Add…": "新增…",
@@ -2318,6 +2326,8 @@ magpie.strings({
"1 skill installed": "1 個のスキルをインストールしました",
"{n} skills installed": "{n} 個のスキルをインストールしました",
"already in the library: {names}": "ライブラリにすでにあります:{names}",
"updates from GitHub now: {names}": "今後は GitHub から更新:{names}",
"files of their own kept with the backups: {names}": "元のファイルはバックアップに保存:{names}",
"{name} skipped: {error}": "{name} はスキップしました:{error}",
"Install 1 skill": "1 個のスキルをインストール",
"Install {n} skills": "{n} 個のスキルをインストール",
@@ -2448,6 +2458,8 @@ magpie.strings({
"Remote · sign-in": "リモート · サインイン",
"In the library as {name}": "ライブラリに {name} として登録済み",
"adds as {name}": "{name} として追加",
"links to GitHub": "GitHub にリンク",
"The library's {name} came from a folder. This one takes its place and it updates from GitHub from then on; files of its own that differ are kept with the backups.": "ライブラリの {name} はフォルダから追加されたものです。これがその代わりになり、以後は GitHub から更新されます。異なる元のファイルはバックアップに保存されます。",
"The library has another skill called {name}, from elsewhere. This one goes in beside it as {as}.": "ライブラリには別の場所から入れた {name} という名前のスキルがすでにあります。このスキルは {as} として並べて追加されます。",
"Needs {what} to add": "追加には {what} が必要です",
"Add…": "追加…",
@@ -3141,6 +3153,8 @@ magpie.strings({
"1 skill installed": "1 Skill installiert",
"{n} skills installed": "{n} Skills installiert",
"already in the library: {names}": "bereits in der Bibliothek: {names}",
"updates from GitHub now: {names}": "wird jetzt von GitHub aktualisiert: {names}",
"files of their own kept with the backups: {names}": "eigene Dateien in den Backups behalten: {names}",
"{name} skipped: {error}": "{name} übersprungen: {error}",
"Install 1 skill": "1 Skill installieren",
"Install {n} skills": "{n} Skills installieren",
@@ -3271,6 +3285,8 @@ magpie.strings({
"Remote · sign-in": "Remote · Anmeldung",
"In the library as {name}": "In der Bibliothek als {name}",
"adds as {name}": "wird als {name} hinzugefügt",
"links to GitHub": "mit GitHub verknüpfen",
"The library's {name} came from a folder. This one takes its place and it updates from GitHub from then on; files of its own that differ are kept with the backups.": "{name} in der Bibliothek stammt aus einem Ordner. Dieser Skill tritt an seine Stelle und wird ab dann von GitHub aktualisiert; abweichende eigene Dateien bleiben in den Backups.",
"The library has another skill called {name}, from elsewhere. This one goes in beside it as {as}.": "Die Bibliothek hat schon einen anderen Skill namens {name} aus einer anderen Quelle. Dieser kommt als {as} daneben hinzu.",
"Needs {what} to add": "Zum Hinzufügen wird {what} benötigt",
"Add…": "Hinzufügen…",
@@ -0,0 +1,110 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// biubiu8802 on X: a skill downloaded from GitHub and added to the library
// from its folder couldn't follow GitHub. Installing it from GitHub links
// the library's to it (skill_link.go): the list of what the repository has
// says so before the click, "links to GitHub", with what happens in its
// title, the skill is picked for you, and after the install the status
// says it updates from GitHub now and its own files went to the backups.
// Every language, wide and narrow. No backend: the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const HOME = "/Users/biubiu";
const probe = {
source: "biubiu/skills", kind: "github", candidates: [
{ path: "skills/pdf-pro", name: "pdf-pro", description: "PDFs, v2", have: false, links: true },
],
};
const lib = () => ({
dir: `${HOME}/.config/magpie/library`, backups: `${HOME}/.config/magpie/backups`, home: HOME,
agents: [{ id: "claude", name: "Claude Code", icon: "", skills: `${HOME}/.claude/skills` }],
instructions: { agents: [] }, servers: [], skills: [], foundServers: [], projects: [], foundSkills: [],
});
function server(lang, posts) {
return async (route) => {
const req = route.request(), url = new URL(req.url());
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } });
if (url.pathname === "/api/library") return route.fulfill({ json: lib() });
if (url.pathname === "/api/library/skills/probe") return route.fulfill({ json: probe });
if (url.pathname === "/api/library/skills/install") {
posts.push(req.postDataJSON().paths);
return route.fulfill({ json: { ...lib(), result: { changed: ["claude"], problems: [], installed: [], had: [], skipped: [], linked: ["pdf-pro"], linkedKept: ["pdf-pro"] } } });
}
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });
if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} });
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const words = {
en: { tag: "links to GitHub", why: "The library's pdf-pro came from a folder. This one takes its place and it updates from GitHub from then on; files of its own that differ are kept with the backups.", done: "updates from GitHub now: pdf-pro · files of their own kept with the backups: pdf-pro" },
zh: { tag: "链接到 GitHub", why: "资源库里的 pdf-pro 来自一个文件夹。这个会取代它,之后它从 GitHub 更新;与此不同的原有文件会保留在备份里。", done: "现在从 GitHub 更新:pdf-pro · 原有文件已保留在备份里:pdf-pro" },
"zh-TW": { tag: "連結到 GitHub", why: "資源庫裡的 pdf-pro 來自一個資料夾。這個會取代它,之後它從 GitHub 更新;與此不同的原有檔案會保留在備份裡。", done: "現在從 GitHub 更新:pdf-pro · 原有檔案已保留在備份裡:pdf-pro" },
ja: { tag: "GitHub にリンク", why: "ライブラリの pdf-pro はフォルダから追加されたものです。これがその代わりになり、以後は GitHub から更新されます。異なる元のファイルはバックアップに保存されます。", done: "今後は GitHub から更新:pdf-pro · 元のファイルはバックアップに保存:pdf-pro" },
de: { tag: "mit GitHub verknüpfen", why: "pdf-pro in der Bibliothek stammt aus einem Ordner. Dieser Skill tritt an seine Stelle und wird ab dann von GitHub aktualisiert; abweichende eigene Dateien bleiben in den Backups.", done: "wird jetzt von GitHub aktualisiert: pdf-pro · eigene Dateien in den Backups behalten: pdf-pro" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a skill the library has from a folder is linked to GitHub by installing it from there", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const errors = [];
t.after(async () => {
if (errors.length) console.log(errors);
await browser.close();
});
const run = async (lang, width) => {
const posts = [];
const ctx = await browser.newContext({ viewport: { width, height: 800 } });
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "skills"); } catch {} });
const page = await ctx.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, posts));
await page.goto("http://magpie.test/");
await page.locator('button[data-view="library"]').click();
const src = page.locator('#view-library input[data-lib="source"]');
await src.fill("biubiu/skills");
await src.press("Enter");
const row = page.locator("#view-library .lib-pick");
await row.first().waitFor();
const w = words[lang];
const tag = row.locator(".lib-tag");
assert.equal((await tag.textContent()).trim(), w.tag);
assert.equal(await tag.getAttribute("title"), w.why);
const fit = await row.evaluate((r) => {
const b = r.querySelector(".lib-tag").getBoundingClientRect(), box = r.getBoundingClientRect();
return { inside: b.right <= box.right + 0.5, over: r.closest(".lib-picks").scrollWidth - r.closest(".lib-picks").clientWidth };
});
assert.equal(fit.inside, true, "the tag stays in its row");
assert.equal(fit.over, 0, "the list doesn't scroll sideways");
assert.equal(await row.locator("input").isChecked(), true, "picked for you");
await page.locator("#view-library .lib-probefoot button.primary").click();
await page.waitForTimeout(300);
assert.deepEqual(posts, [["skills/pdf-pro"]]);
const status = page.locator("#status");
assert.equal((await status.textContent()).trim(), w.done);
await ctx.close();
};
for (const lang of Object.keys(words)) {
await t.test(lang + ", wide", () => run(lang, 980));
await t.test(lang + ", narrow", () => run(lang, 420));
}
assert.deepEqual(errors, []);
});
}
+5 -1
View File
@@ -160,7 +160,11 @@ func TestSameFilesByNameAreHad(t *testing.T) {
if len(r.Installed) != 0 || !slices.Equal(r.Had, []string{"skill-creator"}) {
t.Errorf("installed %v had %v", r.Installed, r.Had)
}
// another one by that name, with no source, is another skill
// the one had is acme's now, and updates from there; another by that
// name from elsewhere is another skill
if l, _ := load(); l.skill("skill-creator").Source == nil || l.skill("skill-creator").Source.Repo != "acme/skills" {
t.Errorf("the one had is %+v", l.skill("skill-creator").Source)
}
r = ok(t)(InstallSkills("openai/skills", []string{"skills/skill-creator"}, nil))
if !slices.Equal(r.Installed, []string{"skill-creator-openai"}) {
t.Errorf("openai's: installed %v had %v", r.Installed, r.Had)
+69
View File
@@ -0,0 +1,69 @@
package library
import (
"slices"
"strings"
)
// A skill the library has from a folder of the user's, or took in from an
// agent's folder, has nothing to be updated from. Many of them came from
// GitHub to begin with: downloaded from there and brought into the
// library (biubiu8802 on X, wishing it could follow GitHub). Installing
// that skill from GitHub links the two, as an update of one CC Switch
// installed does (ccswitch.go): the library's skill by that name takes
// GitHub's files and GitHub as its source, so a check and an update cover
// it from then on, and the agents' links to it go on pointing at it. Its
// own files, when they aren't GitHub's to the file, go to the backups, as
// an update that replaces an edited skill keeps it (UpdateSkill); a folder
// of the user's it was linked to is left as it is, and only the library's
// link to it goes.
// followsHere is whether installing from src the skill fetched at from
// links the library's skill s, which has its name, to it. It must be that
// skill: traced to that repository, or traced nowhere and saying it does
// the same thing (its SKILL.md's description, as an older download of it
// does). One traced to another repository, or one of the user's own that
// describes something else, is another skill by that name, and goes in
// beside it (skill_beside.go, TestInstallSetPutsAnotherByTheSameNameBeside).
func followsHere(s *Skill, src Source, from string) bool {
if src.Kind != "github" || s.Source.remote() || s.Called != "" {
return false
}
// where it is traced to: CC Switch's record, the skills CLI's lock,
// the git checkout its folder is in, or the repository it was grouped
// with (skill_from.go)
if r := (&tracer{}).repoOf(s); r != "" {
return strings.EqualFold(r, src.Repo)
}
here, ok := readMeta(skillDir(s.Name))
there, ok2 := readMeta(from)
return ok && ok2 && here.Description != "" && here.Description == there.Description
}
// linkSkill puts the skill fetched at from, at path of src, in the place
// of the library's skill s, which then updates from src. The agents named
// get it too. kept is whether s's own files weren't the fetched ones and
// went to the backups.
func (l *Library) linkSkill(s *Skill, src Source, path, from string, agents []string) (kept bool, err error) {
src.Path = path
dir := skillDir(s.Name)
if linked(dir) || !sameTree(dir, from) {
kept = !linked(dir)
up := &skillUpdate{name: s.Name, src: &src, adopt: true, from: from}
if err := up.apply(l, Targets()); err != nil {
return false, err
}
} else {
// its files are the source's already: only where it updates from
// is new
s.Hash, s.Own, s.Commit = hashDir(dir), ownHash(dir), ""
forgetCheck(s.Name)
}
s.Source, s.From, s.Gone = &src, "", ""
for _, a := range agents {
if !slices.Contains(s.Agents, a) {
s.Agents = append(s.Agents, a)
}
}
return kept, nil
}
+132
View File
@@ -0,0 +1,132 @@
package library
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"testing"
)
// biubiuRepo serves biubiu/skills with a pdf-pro skill in skills/, as
// GitHub has it now.
func biubiuRepo(t *testing.T) {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.HasPrefix(r.URL.Path, "/biubiu/skills/") {
http.NotFound(w, r)
return
}
w.Write(tarball(t, map[string]string{
"skills/pdf-pro/SKILL.md": "---\nname: pdf-pro\ndescription: Fill and read PDFs\n---\nv2\n",
"skills/pdf-pro/forms.md": "forms v2",
}))
}))
t.Cleanup(srv.Close)
old := tarballURL
tarballURL = func(repo, ref string) string { return srv.URL + "/" + repo + "/" + ref }
t.Cleanup(func() { tarballURL = old })
}
// linkedToGitHub checks that the library's pdf-pro is the one from
// biubiu/skills now, with GitHub's files in its own folder, and that
// it's the only pdf-pro: none went in beside it.
func linkedToGitHub(t *testing.T, h string) {
t.Helper()
l, _ := load()
s := l.skill("pdf-pro")
if s == nil || s.Source == nil || s.Source.Kind != "github" || s.Source.Repo != "biubiu/skills" || s.Source.Path != "skills/pdf-pro" {
t.Fatalf("the library's pdf-pro is %+v", s)
}
if len(l.Skills) != 1 {
t.Errorf("the library has %d skills", len(l.Skills))
}
if fi, err := os.Lstat(skillDir("pdf-pro")); err != nil || linkEntry(fi) {
t.Errorf("the library's pdf-pro is a link still: %v", err)
}
if got := read(t, filepath.Join(skillDir("pdf-pro"), "forms.md")); got != "forms v2" {
t.Errorf("the library's forms.md: %q", got)
}
// the agent's link goes on pointing at it
if got := read(t, filepath.Join(h, ".claude/skills/pdf-pro/SKILL.md")); !strings.Contains(got, "v2") {
t.Errorf("claude's pdf-pro: %q", got)
}
// and it updates from GitHub like one installed from there
ok(t)(UpdateSkill("pdf-pro", false))
}
// biubiu8802 on X: a skill downloaded from GitHub and added to the
// library from its folder couldn't follow GitHub. Installing it from
// GitHub links the library's to it: GitHub's files take its place and it
// updates from there, and the user's folder is left as it is.
func TestFolderSkillFollowsGitHub(t *testing.T) {
h := sandbox(t)
biubiuRepo(t)
dl := filepath.Join(h, "Downloads", "pdf-pro")
write(t, filepath.Join(dl, "SKILL.md"), "---\nname: pdf-pro\ndescription: Fill and read PDFs\n---\nv1\n")
ok(t)(InstallSkills(dl, []string{""}, []string{"claude"}))
p, err := ProbeSkills("biubiu/skills")
if err != nil {
t.Fatal(err)
}
if len(p.Candidates) != 1 || !p.Candidates[0].Links || p.Candidates[0].Have || p.Candidates[0].As != "" {
t.Fatalf("probed as %+v", p.Candidates)
}
r := ok(t)(InstallSkills("biubiu/skills", []string{"skills/pdf-pro"}, []string{"claude"}))
if !slices.Equal(r.Linked, []string{"pdf-pro"}) || len(r.LinkedKept) != 0 || len(r.Installed) != 0 || len(r.Skipped) != 0 {
t.Fatalf("linked %v kept %v installed %v skipped %+v", r.Linked, r.LinkedKept, r.Installed, r.Skipped)
}
linkedToGitHub(t, h)
if got := read(t, filepath.Join(dl, "SKILL.md")); !strings.Contains(got, "v1") {
t.Errorf("the user's folder changed: %q", got)
}
}
// One taken into the library from an agent's folder is the library's own
// copy: linked to GitHub, its files that aren't GitHub's go to the
// backups, and the result says so.
func TestOwnSkillFollowsGitHubKeepsItsFiles(t *testing.T) {
h := sandbox(t)
biubiuRepo(t)
write(t, filepath.Join(h, ".claude/skills/pdf-pro/SKILL.md"), "---\nname: pdf-pro\ndescription: Fill and read PDFs\n---\nmy edit\n")
ok(t)(ImportSkill("pdf-pro"))
r := ok(t)(InstallSkills("biubiu/skills", []string{"skills/pdf-pro"}, nil))
if !slices.Equal(r.Linked, []string{"pdf-pro"}) || !slices.Equal(r.LinkedKept, []string{"pdf-pro"}) {
t.Fatalf("linked %v kept %v", r.Linked, r.LinkedKept)
}
linkedToGitHub(t, h)
kept, _ := filepath.Glob(filepath.Join(BackupDir(), "*", "library", "skills", "pdf-pro", "SKILL.md"))
if len(kept) != 1 || !strings.Contains(read(t, kept[0]), "my edit") {
t.Errorf("the user's own version wasn't kept: %v", kept)
}
}
// One known to come from another repository is another skill by that
// name, even when it says it does the same: it is left as it is, and
// GitHub's goes in beside it. One traced nowhere that describes something
// else is TestInstallSetPutsAnotherByTheSameNameBeside's.
func TestSkillFromElsewhereIsNotLinked(t *testing.T) {
h := sandbox(t)
biubiuRepo(t)
dl := filepath.Join(h, "Downloads", "pdf-pro")
write(t, filepath.Join(dl, "SKILL.md"), "---\nname: pdf-pro\ndescription: Fill and read PDFs\n---\nsomeone else's\n")
ok(t)(InstallSkills(dl, []string{""}, nil))
mu.Lock()
l, _ := load()
l.skill("pdf-pro").From = "acme/skills"
l.save()
mu.Unlock()
r := ok(t)(InstallSkills("biubiu/skills", []string{"skills/pdf-pro"}, nil))
if len(r.Linked) != 0 || !slices.Equal(r.Installed, []string{"pdf-pro-biubiu"}) {
t.Fatalf("linked %v installed %v", r.Linked, r.Installed)
}
l, _ = load()
if s := l.skill("pdf-pro"); s.Source == nil || s.Source.Kind != "folder" {
t.Errorf("the folder's pdf-pro is %+v", s.Source)
}
}
+38 -3
View File
@@ -958,6 +958,11 @@ type Candidate struct {
// As is the name the library has it by, or would add it by, when
// that isn't Name: another skill from elsewhere has that name
As string `json:"as,omitempty"`
// Links is that the library's skill by its name came from a folder
// or an agent, not from anywhere it can be updated from: installing
// this one puts its files and source in that one's place, so it
// updates from here (skill_link.go)
Links bool `json:"links,omitempty"`
}
// Probe is what was found at a source.
@@ -1444,8 +1449,10 @@ func probeSkills(input, name string) (*Probe, error) {
if s.Name != c.Name {
p.Candidates[i].As = s.Name
}
} else if l.skill(c.Name) != nil {
if p.src.remote() {
} else if s := l.skill(c.Name); s != nil {
if followsHere(s, p.src, from) {
p.Candidates[i].Links = true
} else if p.src.remote() {
p.Candidates[i].As = l.freeSkillName(c.Name, p.src)
} else {
// a folder of the user's isn't added beside it
@@ -1502,6 +1509,10 @@ func InstallSkills(input string, paths, agents []string) (*Result, error) {
type installed struct {
added, had []string
skipped []Problem
// linked are the skills the library had from a folder that follow the
// source now (skill_link.go), and kept those of them whose own files
// weren't the source's: they went to the backups
linked, kept []string
}
func (in *installed) skip(name string, err error) {
@@ -1518,13 +1529,14 @@ func installChange(f func(l *Library, in *installed) error) (*Result, error) {
if err := f(l, in); err != nil {
return err
}
if len(in.added) == 0 && len(in.had) == 0 && len(in.skipped) > 0 {
if len(in.added) == 0 && len(in.had) == 0 && len(in.linked) == 0 && len(in.skipped) > 0 {
return errors.New(in.skipped[0].Error)
}
return nil
})
if res != nil {
res.Installed, res.Had, res.Skipped = in.added, in.had, in.skipped
res.Linked, res.LinkedKept = in.linked, in.kept
}
return res, err
}
@@ -1573,11 +1585,34 @@ func installFrom(l *Library, p *Probe, paths, agents []string, shown bool, in *i
// here; another by that name goes in beside it, by a name of its
// own (skill_beside.go)
if s := l.hadSkill(src, c, from); s != nil {
// one of the library's own by its name, the very same files,
// is that skill, and updates from there from now on (as
// noteFrom binds it when probed): another by that name from
// elsewhere goes in beside it, not in its place
if s.Source == nil && src.Kind == "github" && !linked(skillDir(s.Name)) {
if _, err := l.linkSkill(s, src, c.Path, from, nil); err != nil {
in.skip(c.Name, err)
continue
}
}
in.had = append(in.had, s.Name)
l.offered(p, c.Path, shown)
continue
}
name := c.Name
if s := l.skill(name); s != nil && followsHere(s, src, from) {
kept, err := l.linkSkill(s, src, c.Path, from, agents)
if err != nil {
in.skip(c.Name, err)
continue
}
in.linked = append(in.linked, name)
if kept {
in.kept = append(in.kept, name)
}
l.offered(p, c.Path, shown)
continue
}
if l.skill(name) != nil {
// the user's own folder is linked as it is, and its SKILL.md
// can't be named apart from the other: an agent would see two
+6
View File
@@ -43,6 +43,12 @@ type Result struct {
Installed []string `json:"installed,omitempty"`
Had []string `json:"had,omitempty"`
Skipped []Problem `json:"skipped,omitempty"`
// Linked are, for skills installed from GitHub, the ones the library
// had from a folder by that name that now follow GitHub, with its
// files (skill_link.go); LinkedKept those of them whose own files
// weren't GitHub's, kept with the backups
Linked []string `json:"linked,omitempty"`
LinkedKept []string `json:"linkedKept,omitempty"`
// dropped are the servers taken out of an agent's config, as it had
// them, whose processes go once no agent runs them (mcp_reap.go)
dropped []*Server
+11
View File
@@ -246,6 +246,13 @@ func libSaid(res *library.Result, done string) (string, bool) {
if len(res.Installed) == 0 && len(res.Had) > 0 {
done = strings.Join(res.Had, ", ") + " in the library already"
}
// a skill from a folder, linked to the one installed (skill_link.go)
if len(res.Installed) == 0 && len(res.Linked) > 0 {
done = strings.Join(res.Linked, ", ") + " updates from GitHub now"
}
if len(res.LinkedKept) > 0 {
done += " · files of their own kept with the backups: " + strings.Join(res.LinkedKept, ", ")
}
for _, p := range res.Skipped {
done += " · " + strings.TrimPrefix(p.What, "skill:") + " skipped: " + p.Error
}
@@ -456,6 +463,10 @@ func (m *model) openProbe(p *library.Probe) {
note = "in the library as " + c.As + " · " + note
case c.Have:
note = "in the library already · " + note
case c.Links:
// the library's by its name came from a folder: this one
// takes its place, and it updates from GitHub from then on
note = "links the library's to GitHub · " + note
case c.As != "":
// another skill from elsewhere has its name
note = "adds as " + c.As + " · " + note