Files
magpie/internal/library/skill_from_test.go
T
JoeyWu-tech 497100488a provider, library: a .git is a repository only when git takes it for one (#3675)
TestPluginToldWhereTheAgentWorks was red on any machine with an empty
.git above its temp folder. GitOnDisk took the first .git it met going
up as a repository, and on this box /tmp/.git is an empty folder (owned
by nobody), so every folder under /tmp read "yes". git passes such a
folder over and goes on up: git rev-parse under it says "not a git
repository".

GitOnDisk now reads each .git on the way as git's own search does
(repo_discovery_find_dir in git 2.56's setup.c), through GitAt:
- A folder counts when git takes it for a repository (is_git_directory):
  a HEAD git takes (a link into refs/, "ref: refs/...", or a commit's
  id), and objects and refs folders, in the folder its commondir names
  for a linked worktree. Any other folder, an empty one say, is passed
  over and the walk goes on up.
- A file counts when it is "gitdir: <folder>" naming such a folder,
  relative to the .git's own folder (a linked worktree's, a
  submodule's). Any other file, one over git's 1 MB, or one that is
  neither file nor folder is "no": git stops there with "not a git
  repository" (a worktree whose repository has gone) or "invalid
  gitfile format". (git 2.34 passed a .git that is neither file nor
  folder over; 2.55 and 2.56, CI's, stop at it.)
- A .git it can't read is unknown, and the header is left off. git
  passes such a folder over and stops at such a file, but either way
  it can't tell an empty .git from a repository it isn't let into
  (another user's, through a shared magpie), and a failed read is
  unknown here.
A bare repository kept as a folder's .git (git init --bare .git) is
still "yes": git finds one there, though no work tree. Not mirrored:
the filesystem boundary, GIT_CEILING_DIRECTORIES and safe.directory's
ownership check. Cost: the same one stat per folder on the way up; at
a .git, a read of HEAD (255 bytes at most) and stats of commondir,
objects and refs.

What a user sees: a request to a plugin provider from an agent that
doesn't say whether its folder is a repository (Codex, Pi) was told
"yes" for a project under a stray empty .git, under a worktree whose
repository was deleted, or under a .git file that names nothing. The
community ZCode plugin then tells the model "- <git label>: yes" and
Command Code's sends isGitRepo: true, so the model may run git commands
that fail with "not a git repository". They are now told "no", and
with a .git on the way magpie can't read, nothing (ZCode's plugin
leaves the line out, Command Code's sends false). Claude Code's and
OpenCode's requests say it themselves and are passed on as they say it,
so nothing changes for them; Claude Code 2.1.310's own check takes any
.git, an empty one too.

The only caller of GitOnDisk is tellWorkPlace (workdir.go), which needs
no change. The library's skill groups had the same first-.git walk:
gitRepoOf took the first .git within four folders of a linked skill for
its checkout, so an empty one between a skill and its clone left the
skill in no group, and gave one imported from there no From. gitRepoOf
now asks provider.GitAt, passes such a .git over to the clone's, and
reads the origin from the folder GitAt names (a linked worktree's
common one), which replaces gitdirConfig. gitdirConfig also took
"gitdir:" with no space after it, or with spaces around the line,
which git doesn't take; such a .git now traces to nothing, as git finds
nothing there. Checkouts git made are traced as before; the test's
fake ones had only a config and now have a HEAD, objects and refs.
Every other .git folder in the Go code is one a walk skips when it
copies, hashes or checks a skill (carry.go, skillcheck.go, skills.go,
skill_edits.go), or the one magpie removes from its own fetch of a
skill (skillgit.go), not a decision about a repository. The Claude
bridge's claudeWorkDir takes the temp folder for one in no repository;
Claude Code decides that for itself, and its git status is off for
every run (CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS), so it stays.

TestPluginToldWhereTheAgentWorks gets a real repository for "in a
repository" (HEAD, objects, refs; an empty .git was all it had) and a
case under an empty .git in its own temp folder, so it fails without
this on any machine. Its "not in one" cases, and the new provider
tests' "no" ones, still need no repository above the temp folder, as
the test did before. TestGitOnDiskIsWhatGitFinds lays out each kind of
.git by hand; TestGitOnDiskAgreesWithGit asks git rev-parse
--git-common-dir in each of those folders and in ones git made (init,
worktree add, a worktree whose record was removed, --separate-git-dir,
init --bare .git), for yes or no and where;
TestGitOnDiskUnreadIsUnknown locks a .git folder and a worktree's .git
file. provider-plugins.md and library.md say the same.

What was run (tree 9a4504d9, on origin/main 56602426, go1.26.8,
linux/amd64, Linux 5.15), outside graftcp, umask 077, git 2.34.1, with
the box's empty /tmp/.git above the tests' temp folders:
- TestPluginToldWhereTheAgentWorks -count=5, Bun 1.4.2: 5 of 5 ok.
  TestGitOnDisk* and TestSkillRepo*, -count=3: 15 of 15 ok. The same
  and TestPluginToldWhereTheAgentWorks, -race -count=2: 12 of 12, no
  race. internal/library and internal/provider whole: ok.
- 56602426's workplace.go and skill_from.go put back under the new
  tests: TestPluginToldWhereTheAgentWorks red 5 of 5, at
  plugin_workdir_test.go:125 both "not in one" and "not in one, under
  an empty .git": the plugin was told git "yes", want "no";
  TestSkillRepoTraced red, "write-a-prd: repo "", want
  "mattpocock/skills"".
- gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go
  vet for windows, go build -tags nogui for linux and darwin and go
  build for windows: exit 0 each. go vet and go build without the tag
  on linux: exit 1 (no libsoup-3.0 or gio-unix-2.0 here).
- go test -tags nogui -count=1 -timeout 45m ./... (Bun 1.4.2, log
  kept; 8m37s, load 32 at its start): 73 packages ok, and 14 tests red
  in 4 packages, none of them this commit's tests or what they cover.
  internal/gateway ran to its end (504s), so
  TestPluginToldWhereTheAgentWorks passed in it; internal/library and
  internal/provider ok. The reds: agent TestCodexDriftReached and
  TestCodexBehindReverseProxy (#3398); TestInstalledVersion,
  TestCursorFolderFromTheEditorIsNotTheCLI,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir
  and TestZedAppPath (#3141);
  TestReasonixCLIRequiresSupportedNativeVersion and
  TestReasonixCLIRecoversAfterProbeTimeout (#3641: go build's own VCS
  stamping meets the same /tmp/.git, which this doesn't change); edit
  TestWriteAtomicReadOnlyHardLink and testenv TestProgram (umask
  077, #3640); gui TestGatewayHeldByAContainer and
  TestGatewayFixQuitsOnlyAMagpie (#3649).

This commit is 595b361c rebased: the same internal/ patch-id, and
the same row in docs/subsystems/library.md, put in by git's 3-way
merge, as main's 33ccc618 (#2794) rewrote the Skills row, a line of its
context three rows above. The rest is what was run for 595b361c, at
tree d56bed31 on origin/main 098ac969, the same code (not this tree):
- main's GitOnDisk and gitRepoOf under the new tests (098ac969's
  workplace.go and skill_from.go put back):
  TestPluginToldWhereTheAgentWorks -count=5, Bun 1.4.2: red 5 of 5,
  "not in one" and "not in one, under an empty .git" told git "yes".
  With TMPDIR=/var/tmp/3675-clean, no .git above it: red 5 of 5 on the
  new case alone. TestSkillRepoTraced: red, write-a-prd: repo "", want
  "mattpocock/skills".
- Broken by hand, one at a time in workplace.go, each red in the
  GitOnDisk tests on what it breaks, and green again restored:
    any .git folder taken, main's rule for folders: "yes" under an
      empty .git, a zeroed HEAD and a HEAD alone, and for a locked .git
    a gitfile naming no repository, or not a gitfile, walked past:
      "yes" from the repository above it
    HEAD's content not read: "yes" for the zeroed HEAD; objects and
      refs not looked for: "yes" for a HEAD alone
    a HEAD at a commit not taken, or commondir not read: "no" for both
      linked worktrees; a worktree's own folder named, not its common
      one: the repository at .../worktrees/wt where git finds .../.git
    a HEAD linked into refs/ refused: "no"; a relative gitdir read
      from magpie's folder: "no" for the submodule; no 1 MB cap: "yes"
    ENOTDIR taken for a failed read: unknown for a gitfile naming a
      file; a .git it can't read walked past: "no" for both locked ones

Not tried: CI's git 2.55.0 (ubuntu) and 2.56.0 (macOS, Windows) under
TestGitOnDiskAgreesWithGit, which met git 2.34.1 alone; macOS and
Windows at all (Windows CI only compiles the tests); a real ZCode or
Command Code plugin end to end; a shared magpie told another user's
folder; the Library page itself.

Landed by yetone in a batch of Coffemon's patches from the issues.
What was run, go1.26.8, on origin/main cc81ad4ea, then again at
70a0c387c (gofmt, the three vets, the changed tests, umask 077):
- mote (macOS 27): gofmt -l clean; go vet, GOOS=linux go vet -tags
  nogui and GOOS=windows go vet ./...: ok. edit and testenv at umask
  077; agent, provider, library and gateway with an empty .git above
  TMPDIR; davsync, imagemcp, plugin, library, edit, testenv whole; the
  changed tests in agent, provider, gateway and gui; the timing tests
  -count=10 (gateway, davsync, imagemcp) and -count=5 (agent): all ok.
  TestCoreScriptBudget ok: core 1,536,751 of 1,537,034, app.js
  1,312,975 of 1,315,316, no budget raised.
- Red on the old code: on origin/main, TestWriteAtomicReadOnlyHardLink
  at umask 077 and two Reasonix tests under an empty .git; on Linux
  (wsl-run) TestProgram at umask 077 with the old program.go. With
  each fix's code taken back to main's, the Gemini imageConfig tests,
  TestPluginToldWhereTheAgentWorks, TestSkillRepoTraced,
  TestTaggedHooksAlone, TestMainURL/TestMainView and update-auto,
  plugin-github-hooks, plugins-more-discover, plugin-namesake were
  red. Broken by hand: claudeKeyed always true (both
  OwnEndpointNeverAsked tests red), claudeAsk a no-op
  (TestClaudeFirstWriteAsksTheProxy red), GitAt taking any .git folder
  (the three TestGitOnDisk tests red).
- GUI: 123 files (plugins*, update-*, panel/tray/start/context, i18n,
  gui-zh-tw/ja/de and every file that evals app.js parts) in WebKit on
  Linux (wsl-run). 11 files had reds (click-scroll, panel-fold,
  plugin-card-update, plugin-github, plugin-move*, segs-glide,
  tray-totals, update-*), and run again side by side they fail the
  same on origin/main d80d75f30 (79 pass, 26 fail here; 78 and 27
  there). They are click-scroll guards ("the click must not scroll
  the page"), varying by language from run to run (#4385).
  copilot-ghe's route-after-close red is #1949, seen on main 244d80e23
  too. In Chromium on mote, Chromium segfaulted partway through files
  (#4125): context-map, context-scroll-end and context-tune fail the
  same on origin/main 0911a65e7, so the batch's own files
  (plugin-namesake, update-auto, plugins-more-discover,
  plugin-github-hooks) ran in Chromium on Linux: 62 of 62.
- Full suite (go test -tags nogui -count=1 -timeout 45m ./..., mote)
  at 472a0608f (on 70a0c387c): every package ok but internal/gateway,
  whose five reds were #4362's (Antigravity turned-away and
  TestCodexSpentGrokFailingIsTold), fixed on main in d80d75f30. After
  the rebase on 244d80e23 the five pass, and gofmt, the three vets
  and the targeted runs above were run again: ok. In Linux the
  sign-in, copilot, plugin-github*, plugins-more-discover,
  plugin-namesake, plugin-gateway, update-auto, quota-refresh-order
  and i18n files ran in both engines: 475 pass, 4 fail (copilot-ghe
  #1949, plugin-github's click scroll, both red on main too).
- Rebased again on c7171a256, over its budget fix e94bf7a08: gofmt, vet of
  gui, gateway, provider and plugin, TestCoreScriptBudget (core
  1,536,265 of 1,536,586 with the batch's last commit, statusTErr and settingsErr), the Gemini,
  GitOnDisk and plugin tests, and in Linux both engines i18n-keys,
  update-mirror, plugin-namesake, plugins-more-discover,
  plugin-github-hooks and update-auto (138 of 138): ok.
Not tried: the whole GUI suite (mote's WebKit wouldn't launch and its
Chromium segfaulted, #4125); macOS WebKit; the real app's window.
2026-10-30 15:53:22 +08:00

476 lines
21 KiB
Go

package library
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
)
func repoIn(t *testing.T) map[string]string {
t.Helper()
v, err := Read(nil)
if err != nil {
t.Fatal(err)
}
out := map[string]string{}
for _, s := range v.Skills {
out[s.Name] = s.Repo
}
return out
}
// npx skills add with $XDG_STATE_HOME set (@_yukirock on X): the skills
// CLI keeps its lock at $XDG_STATE_HOME/skills/.skill-lock.json and the
// skills in ~/.agents/skills, and each is grouped by the repository that
// lock names. One the older ~/.agents lock alone names is grouped too.
func TestSkillRepoFromXDGLock(t *testing.T) {
h := sandbox(t)
state := filepath.Join(h, "state")
t.Setenv("XDG_STATE_HOME", state)
for _, n := range []string{"grill-me", "tdd", "old"} {
skill(t, filepath.Join(h, ".agents/skills", n), n, n)
os.MkdirAll(filepath.Join(h, ".claude/skills"), 0o755)
dirLink(filepath.Join(h, ".agents/skills", n), filepath.Join(h, ".claude/skills", n))
}
write(t, filepath.Join(state, "skills/.skill-lock.json"), `{"version":3,"skills":{
"grill-me":{"source":"mattpocock/skills","sourceType":"github","sourceUrl":"https://github.com/mattpocock/skills.git"},
"tdd":{"source":"obra/superpowers","sourceType":"github","sourceUrl":"https://github.com/obra/superpowers.git"}}}`)
write(t, filepath.Join(h, ".agents/.skill-lock.json"), `{"version":3,"skills":{
"tdd":{"source":"stale/repo","sourceType":"github"},
"old":{"source":"me/old-skills","sourceType":"github"}}}`)
ok(t)(ImportSkills([]string{"grill-me", "tdd", "old"}))
got := repoIn(t)
for n, r := range map[string]string{"grill-me": "mattpocock/skills", "tdd": "obra/superpowers", "old": "me/old-skills"} {
if got[n] != r {
t.Errorf("%s: repo %q, want %q", n, got[n], r)
}
}
}
// checkout makes dir a git checkout whose config is cfg, with what git
// looks for in its .git (provider.GitAt) as git init lays it out.
func checkout(t *testing.T, dir, cfg string) {
t.Helper()
write(t, filepath.Join(dir, ".git/HEAD"), "ref: refs/heads/main\n")
write(t, filepath.Join(dir, ".git/config"), cfg)
for _, d := range []string{"objects", "refs/heads"} {
if err := os.MkdirAll(filepath.Join(dir, ".git", d), 0o755); err != nil {
t.Fatal(err)
}
}
}
// A skill not installed from GitHub is grouped with the repository it
// came from all the same (White Immortal on Discord): the skills CLI's
// lock names it, or the git checkout it's in, whatever the remote's form,
// and never with a user or token the remote had. The checkout is the one
// git finds, past an empty .git on the way (#3675). A skill in ~/.claude
// kept in git (the user's dotfiles) is not from that repository.
func TestSkillRepoTraced(t *testing.T) {
h := sandbox(t)
// npx skills add mattpocock/skills: in ~/.agents/skills, in its lock
skill(t, filepath.Join(h, ".agents/skills/grill-me"), "grill-me", "Grill")
write(t, filepath.Join(h, ".agents/.skill-lock.json"), `{"version":3,"skills":{
"grill-me":{"source":"mattpocock/skills","sourceType":"github","sourceUrl":"https://github.com/mattpocock/skills.git","skillPath":"skills/grill-me/SKILL.md"},
"tdd":{"source":"x","sourceType":"git","sourceUrl":"git@gitlab.com:team/skills.git"}}}`)
os.MkdirAll(filepath.Join(h, ".claude/skills"), 0o755)
dirLink(filepath.Join(h, ".agents/skills/grill-me"), filepath.Join(h, ".claude/skills/grill-me"))
// a clone of the repository, linked from the library
clone := filepath.Join(h, "code/skills")
skill(t, filepath.Join(clone, "skills/write-a-prd"), "write-a-prd", "PRD")
checkout(t, clone, "[core]\n\tbare = false\n[remote \"upstream\"]\n\turl = https://github.com/other/fork.git\n[remote \"origin\"]\r\n\turl = https://me:ghp_secret@github.com/mattpocock/skills.git\r\n")
// an empty .git between the skill and its clone, which git passes over
if err := os.MkdirAll(filepath.Join(clone, "skills/.git"), 0o755); err != nil {
t.Fatal(err)
}
// a skill that is a clone of its own, moved in
skill(t, filepath.Join(h, ".claude/skills/review"), "review", "Review")
checkout(t, filepath.Join(h, ".claude/skills/review"), "[remote \"origin\"]\n\turl = git@gitlab.com:me/review.git\n")
// ~/.claude in git: the user's dotfiles
checkout(t, filepath.Join(h, ".claude"), "[remote \"origin\"]\n\turl = git@github.com:me/dotfiles.git\n")
skill(t, filepath.Join(h, ".claude/skills/notes"), "notes", "Mine")
ok(t)(ImportSkills([]string{"grill-me", "review", "notes"}))
p, err := ProbeSkills(filepath.Join(clone, "skills/write-a-prd"))
if err != nil || len(p.Candidates) != 1 {
t.Fatalf("probe: %+v %v", p, err)
}
ok(t)(InstallSkills(filepath.Join(clone, "skills/write-a-prd"), []string{p.Candidates[0].Path}, nil))
got := repoIn(t)
want := map[string]string{"grill-me": "mattpocock/skills", "write-a-prd": "mattpocock/skills", "review": "gitlab.com/me/review", "notes": ""}
for n, r := range want {
if got[n] != r {
t.Errorf("%s: repo %q, want %q", n, got[n], r)
}
}
b, _ := os.ReadFile(path())
if strings.Contains(string(b), "ghp_secret") {
t.Error("the remote's token was written down")
}
// the clone moved in kept where it came from
if s := mustLoad(t).skill("review"); s.From != "gitlab.com/me/review" {
t.Errorf("review's From: %q", s.From)
}
}
// A site's kit of skills (npx skills add from a /.well-known/agent-skills/
// index) is one group, by the lock's sourceBaseUrl (#1862, WardLu): the
// reporter's three Feishu skills and two Fish Audio ones, each with a
// sourceUrl of its own, were five groups. Another kit under the same host
// with another base URL stays apart. A lock with no sourceBaseUrl is
// grouped by the base in its sourceUrl, before /.well-known/.
func TestWellKnownKitGrouped(t *testing.T) {
h := sandbox(t)
const feishu = "https://open.feishu.cn/lark-cli/skills/regular"
lock := map[string][2]string{ // name: sourceBaseUrl, sourceUrl
"lark-base": {feishu, feishu + "/.well-known/agent-skills/lark-base.tar.gz"},
"lark-doc": {feishu, feishu + "/.well-known/agent-skills/lark-doc.tar.gz"},
"lark-sheets": {feishu, feishu + "/.well-known/agent-skills/lark-sheets.tar.gz"},
"fish-audio-api": {"https://docs.fish.audio", "https://docs.fish.audio/.well-known/agent-skills/fish-audio-api/skill.md"},
"fish-audio-sdk": {"https://docs.fish.audio/", "https://docs.fish.audio/.well-known/agent-skills/fish-audio-sdk/skill.md"},
// the same host, another kit
"lark-admin": {"https://open.feishu.cn/lark-cli/skills/admin", "https://open.feishu.cn/lark-cli/skills/admin/.well-known/agent-skills/lark-admin.tar.gz"},
// a lock from before sourceBaseUrl
"lark-old": {"", feishu + "/.well-known/agent-skills/lark-old.tar.gz"},
// a kit one folder down a site, which reads like owner/repo
"kit-one": {"https://docs.example.com/kit", "https://docs.example.com/kit/.well-known/agent-skills/kit-one/SKILL.md"},
}
var entries []string
os.MkdirAll(filepath.Join(h, ".claude/skills"), 0o755)
var names []string
for n, u := range lock {
skill(t, filepath.Join(h, ".agents/skills", n), n, "D")
dirLink(filepath.Join(h, ".agents/skills", n), filepath.Join(h, ".claude/skills", n))
base := ""
if u[0] != "" {
base = `,"sourceBaseUrl":"` + u[0] + `"`
}
entries = append(entries, `"`+n+`":{"sourceType":"well-known","sourceUrl":"`+u[1]+`"`+base+`}`)
names = append(names, n)
}
write(t, filepath.Join(h, ".agents/.skill-lock.json"), `{"version":3,"skills":{`+strings.Join(entries, ",")+`}}`)
ok(t)(ImportSkills(names))
got := repoIn(t)
for n, want := range map[string]string{
"lark-base": "open.feishu.cn/lark-cli/skills/regular", "lark-doc": "open.feishu.cn/lark-cli/skills/regular",
"lark-sheets": "open.feishu.cn/lark-cli/skills/regular", "lark-old": "open.feishu.cn/lark-cli/skills/regular",
"fish-audio-api": "docs.fish.audio", "fish-audio-sdk": "docs.fish.audio",
"lark-admin": "open.feishu.cn/lark-cli/skills/admin", "kit-one": "docs.example.com/kit",
} {
if got[n] != want {
t.Errorf("%s: repo %q, want %q", n, got[n], want)
}
}
// Group again fetches GitHub repositories only: none of these is one
var asked []string
oldT := tarballURL
tarballURL = func(repo, ref string) string { asked = append(asked, repo); return "http://127.0.0.1:1/" }
t.Cleanup(func() { tarballURL = oldT })
if _, err := RegroupSkills(); err != nil {
t.Fatal(err)
}
if len(asked) != 0 {
t.Errorf("fetched from GitHub: %v", asked)
}
}
// #1862 (WardLu, v0.1.1223): skills brought into the library before
// well-known kits were grouped by their base kept the lock's key of then
// as their From, each skill's own sourceUrl, and From is read before the
// lock, so Feishu's three were three groups and Fish Audio's two were two
// after the fix. The reporter's lock entries, with From as v0.1.1217's
// ImportSkills wrote it.
func TestWellKnownKitFromBeforeGrouped(t *testing.T) {
h := sandbox(t)
lock := `{"skills":{
"lark-base":{"source":"open.feishu.cn","sourceType":"well-known","sourceUrl":"https://open.feishu.cn/lark-cli/skills/regular/.well-known/agent-skills/lark-base.tar.gz","sourceBaseUrl":"https://open.feishu.cn/lark-cli/skills/regular"},
"lark-doc":{"source":"open.feishu.cn","sourceType":"well-known","sourceUrl":"https://open.feishu.cn/lark-cli/skills/regular/.well-known/agent-skills/lark-doc.tar.gz","sourceBaseUrl":"https://open.feishu.cn/lark-cli/skills/regular"},
"lark-sheets":{"source":"open.feishu.cn","sourceType":"well-known","sourceUrl":"https://open.feishu.cn/lark-cli/skills/regular/.well-known/agent-skills/lark-sheets.tar.gz","sourceBaseUrl":"https://open.feishu.cn/lark-cli/skills/regular"},
"fish-audio-api":{"source":"docs.fish.audio","sourceType":"well-known","sourceUrl":"https://docs.fish.audio/.well-known/agent-skills/fish-audio-api/skill.md","sourceBaseUrl":"https://docs.fish.audio"},
"fish-audio-sdk":{"source":"docs.fish.audio","sourceType":"well-known","sourceUrl":"https://docs.fish.audio/.well-known/agent-skills/fish-audio-sdk/skill.md","sourceBaseUrl":"https://docs.fish.audio"}
}}`
write(t, filepath.Join(h, ".agents/.skill-lock.json"), lock)
before := map[string]string{ // remoteRepo of each sourceUrl, the key before 97dfed0f3
"lark-base": "open.feishu.cn/lark-cli/skills/regular/.well-known/agent-skills/lark-base.tar.gz",
"lark-doc": "open.feishu.cn/lark-cli/skills/regular/.well-known/agent-skills/lark-doc.tar.gz",
"lark-sheets": "open.feishu.cn/lark-cli/skills/regular/.well-known/agent-skills/lark-sheets.tar.gz",
"fish-audio-api": "docs.fish.audio/.well-known/agent-skills/fish-audio-api/skill.md",
"fish-audio-sdk": "docs.fish.audio/.well-known/agent-skills/fish-audio-sdk/skill.md",
}
var names []string
for n := range before {
skill(t, filepath.Join(h, ".agents/skills", n), n, "D")
names = append(names, n)
}
ok(t)(ImportSkills(names))
l := mustLoad(t)
for n, f := range before {
l.skill(n).From = f
}
if err := l.save(); err != nil {
t.Fatal(err)
}
got := repoIn(t)
for n := range before {
want := "docs.fish.audio"
if strings.HasPrefix(n, "lark-") {
want = "open.feishu.cn/lark-cli/skills/regular"
}
if got[n] != want {
t.Errorf("%s: repo %q, want %q", n, got[n], want)
}
}
}
// A well-known kit's base, from the lock's sourceBaseUrl or else its
// sourceUrl; neither an http(s) address, its sourceUrl as a remote.
func TestWellKnownBase(t *testing.T) {
for _, c := range []struct{ base, src, want string }{
{"https://open.feishu.cn/lark-cli/skills/regular", "", "open.feishu.cn/lark-cli/skills/regular"},
{"https://Docs.Fish.Audio/", "", "docs.fish.audio"},
{"https://www.example.com/kit/?v=2", "", "example.com/kit"},
{"https://me:tok@example.com/kit", "", "example.com/kit"},
{"https://example.com/kit/.well-known/agent-skills/index.json", "", "example.com/kit"},
{"", "https://docs.fish.audio/.well-known/agent-skills/fish-audio-api/skill.md", "docs.fish.audio"},
{"not a url", "https://example.com/a/.well-known/agent-skills/x.tar.gz", "example.com/a"},
{"", "https://example.com/team/kit.git", "example.com/team/kit"},
{"file:///etc/kit", "", ""},
{"https://example.com/../etc", "", ""},
} {
if got := wellKnownBase(c.base, c.src); got != c.want {
t.Errorf("%q %q: %q, want %q", c.base, c.src, got, c.want)
}
}
}
// The remote forms git takes, each read as the repository.
func TestRemoteRepo(t *testing.T) {
for in, want := range map[string]string{
"https://github.com/mattpocock/skills": "mattpocock/skills",
"https://www.github.com/mattpocock/skills.git/": "mattpocock/skills",
"git@github.com:mattpocock/skills.git": "mattpocock/skills",
"ssh://git@github.com/mattpocock/skills.git": "mattpocock/skills",
"https://user:tok@github.com/a/b/tree/main/x": "a/b",
"git@gitlab.com:group/sub/proj.git": "gitlab.com/group/sub/proj",
"https://tok@codeberg.org/me/s.git": "codeberg.org/me/s",
"mattpocock/skills": "mattpocock/skills",
"/Users/me/skills": "",
"https://github.com/onlyowner": "",
"https://example.com/../etc": "",
} {
if got := remoteRepo(in); got != want {
t.Errorf("%s: %q, want %q", in, got, want)
}
}
}
// Installing from a repository again groups the skills the library has
// already from it (White Immortal: installed before, from that very
// address): those whose SKILL.md is the repository's own. One of the same
// name that differs is someone else's skill, and stays where it was.
func TestInstallAgainNotesFrom(t *testing.T) {
h := sandbox(t)
newFakeGitHub(t)
// the fake repository's skills/pdf/SKILL.md, as installed by hand
write(t, filepath.Join(h, ".claude/skills/pdf/SKILL.md"), "---\nname: pdf\ndescription: PDFs\n---\n")
ok(t)(ImportSkill("pdf"))
if r := repoIn(t)["pdf"]; r != "" {
t.Fatalf("pdf has a repo before: %q", r)
}
if _, err := ProbeSkills("someone/fromagain"); err != nil {
t.Fatal(err)
}
if r := repoIn(t)["pdf"]; r != "someone/fromagain" {
t.Errorf("pdf after installing from its repository again: %q", r)
}
// another's pdf, not the same file: not noted
h = sandbox(t)
write(t, filepath.Join(h, ".claude/skills/pdf/SKILL.md"), "---\nname: pdf\ndescription: My own\n---\n")
ok(t)(ImportSkill("pdf"))
if _, err := ProbeSkills("someone/notmine"); err != nil {
t.Fatal(err)
}
if r := repoIn(t)["pdf"]; r != "" {
t.Errorf("another's pdf grouped with the repository: %q", r)
}
}
func mustLoad(t *testing.T) *Library {
t.Helper()
l, err := load()
if err != nil {
t.Fatal(err)
}
return l
}
// A pack added a while ago is mostly older copies of its skills (White
// Immortal on Discord: 20 of mattpocock/skills' 38 grouped, the rest
// edited there since). Group again fetches each repository the library
// has skills from, and the skills it has by name that are traced to
// nowhere join the rest of it; one of the user's own it doesn't have, and
// one traced to another repository, stay where they are.
func TestRegroupOlderCopies(t *testing.T) {
h := sandbox(t)
repos := map[string]map[string]string{
"someone/pack": {
"skills/eng/same/SKILL.md": "---\nname: same\ndescription: Same\n---\nBody\n",
"skills/eng/edited/SKILL.md": "---\nname: edited\ndescription: Edited since\n---\nNew body\n",
"skills/misc/later/SKILL.md": "---\nname: later\ndescription: Rewritten\n---\nAll new\n",
"skills/misc/locked/SKILL.md": "---\nname: locked\ndescription: Theirs\n---\n",
},
"other/locked": {"skills/locked/SKILL.md": "---\nname: locked\ndescription: Locked\n---\n"},
}
var asked []string
var amu sync.Mutex
tar := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
repo := strings.TrimPrefix(r.URL.Path, "/tar/")
amu.Lock()
asked = append(asked, repo)
amu.Unlock()
files, ok := repos[repo]
if !ok {
http.NotFound(w, r)
return
}
w.Write(tarball(t, files))
}))
t.Cleanup(tar.Close)
oldT := tarballURL
tarballURL = func(repo, ref string) string { return tar.URL + "/tar/" + repo }
t.Cleanup(func() { tarballURL = oldT })
// the copies as added before: same is the repository's own, edited
// and later older ones, mine the user's own
write(t, filepath.Join(h, ".claude/skills/same/SKILL.md"), repos["someone/pack"]["skills/eng/same/SKILL.md"])
skill(t, filepath.Join(h, ".claude/skills/edited"), "edited", "Edited")
skill(t, filepath.Join(h, ".claude/skills/later"), "later", "Later")
skill(t, filepath.Join(h, ".claude/skills/mine"), "mine", "Mine")
// npx skills add other/locked: traced by the lock
skill(t, filepath.Join(h, ".agents/skills/locked"), "locked", "Locked")
write(t, filepath.Join(h, ".agents/.skill-lock.json"), `{"version":3,"skills":{"locked":{"source":"other/locked","sourceType":"github"}}}`)
dirLink(filepath.Join(h, ".agents/skills/locked"), filepath.Join(h, ".claude/skills/locked"))
ok(t)(ImportSkills([]string{"same", "edited", "later", "mine", "locked"}))
// same grouped before, as installing from the repository again did
l := mustLoad(t)
l.skill("same").From = "someone/pack"
if err := l.save(); err != nil {
t.Fatal(err)
}
if r := repoIn(t)["edited"]; r != "" {
t.Fatalf("edited has a repo before: %q", r)
}
n, err := RegroupSkills()
if err != nil {
t.Fatal(err)
}
got := repoIn(t)
want := map[string]string{"same": "someone/pack", "edited": "someone/pack", "later": "someone/pack", "mine": "", "locked": "other/locked"}
for name, r := range want {
if got[name] != r {
t.Errorf("%s: repo %q, want %q", name, got[name], r)
}
}
if n != 2 {
t.Errorf("grouped %d, want 2", n)
}
amu.Lock()
slices.Sort(asked)
if !slices.Equal(asked, []string{"other/locked", "someone/pack"}) {
t.Errorf("fetched %v", asked)
}
asked = nil
amu.Unlock()
// nothing more to group: none grouped, nothing wrong
if n, err := RegroupSkills(); err != nil || n != 0 {
t.Errorf("again: %d %v", n, err)
}
// GitHub not answering: said, nothing changed
tarballURL = func(repo, ref string) string { return tar.URL + "/tar/gone/" + repo }
if _, err := RegroupSkills(); err == nil {
t.Error("no repository fetched, and no error")
}
if r := repoIn(t)["edited"]; r != "someone/pack" {
t.Errorf("edited after a failed regroup: %q", r)
}
}
// A copy in the library's own folder that is a repository's skill to the
// file is bound to it when that repository is pasted again, and updates
// from there as one installed from it does (RockyShowlle on X: installed
// by hand before, now to sync with upstream). One with a file of the
// user's own beside it, and one linked to the skills CLI's folder, are
// grouped only: the user's file is never written over, and the skills CLI
// keeps what it put in ~/.agents.
func TestPastedRepoBindsSameCopy(t *testing.T) {
h := sandbox(t)
var rmu sync.Mutex
repo := map[string]string{
"skills/same/SKILL.md": "---\nname: same\ndescription: Same\n---\nBody\n",
"skills/same/ref.md": "notes\n",
"skills/extra/SKILL.md": "---\nname: extra\ndescription: Extra\n---\n",
"skills/shared/SKILL.md": "---\nname: shared\ndescription: Shared\n---\n",
}
tar := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rmu.Lock()
defer rmu.Unlock()
w.Write(tarball(t, repo))
}))
t.Cleanup(tar.Close)
oldT := tarballURL
tarballURL = func(repo, ref string) string { return tar.URL + "/tar/" + repo }
t.Cleanup(func() { tarballURL = oldT })
write(t, filepath.Join(h, ".claude/skills/same/SKILL.md"), repo["skills/same/SKILL.md"])
write(t, filepath.Join(h, ".claude/skills/same/ref.md"), repo["skills/same/ref.md"])
write(t, filepath.Join(h, ".claude/skills/extra/SKILL.md"), repo["skills/extra/SKILL.md"])
write(t, filepath.Join(h, ".claude/skills/extra/mine.md"), "my own notes\n")
write(t, filepath.Join(h, ".agents/skills/shared/SKILL.md"), repo["skills/shared/SKILL.md"])
dirLink(filepath.Join(h, ".agents/skills/shared"), filepath.Join(h, ".claude/skills/shared"))
ok(t)(ImportSkills([]string{"same", "extra", "shared"}))
if _, err := ProbeSkills("someone/upstream"); err != nil {
t.Fatal(err)
}
l := mustLoad(t)
if s := l.skill("same"); s.Source == nil || s.Source.Kind != "github" || s.Source.Repo != "someone/upstream" || s.Source.Path != "skills/same" || s.Hash == "" || s.From != "" {
t.Fatalf("same, the repository's to the file: source %+v hash %q from %q", s.Source, s.Hash, s.From)
}
if s := l.skill("extra"); s.Source != nil || s.From != "someone/upstream" {
t.Errorf("extra, with a file of the user's: source %+v from %q", s.Source, s.From)
}
if s := l.skill("shared"); s.Source == nil || s.Source.Kind != "folder" || s.From != "someone/upstream" {
t.Errorf("shared, the skills CLI's: source %+v from %q", s.Source, s.From)
}
if got := repoIn(t); got["same"] != "someone/upstream" || got["extra"] != "someone/upstream" || got["shared"] != "someone/upstream" {
t.Errorf("grouped: %v", got)
}
// upstream changes: the bound copy updates from there
rmu.Lock()
repo["skills/same/SKILL.md"] = "---\nname: same\ndescription: Same\n---\nNew body\n"
rmu.Unlock()
ok(t)(UpdateSkill("same", false))
if b, _ := os.ReadFile(filepath.Join(skillDir("same"), "SKILL.md")); !strings.Contains(string(b), "New body") {
t.Errorf("same after an update: %q", b)
}
if _, err := UpdateSkill("extra", false); err == nil {
t.Error("extra updated from GitHub")
}
if b, _ := os.ReadFile(filepath.Join(skillDir("extra"), "mine.md")); string(b) != "my own notes\n" {
t.Errorf("extra's own file: %q", b)
}
}