fix(uninstall): refuse skills at followed link roots

A root skill discovered through a followed source link occupies the link entry itself. Moving that entry to trash silently unlinks every nested skill instead of removing one skill.

Share the root-skill guard across single and batch API handlers and CLI uninstall, report the unlink action clearly, and preserve explicit unlink and nested skill removal.
This commit is contained in:
Willie
2026-10-05 20:02:58 +08:00
parent 53303ebe8a
commit cd6e0165dd
14 changed files with 152 additions and 14 deletions
+2 -2
View File
@@ -220,11 +220,11 @@ func resolveGroupSkills(group, sourceDir string, walks ...sourcewalk.Options) ([
}
// A followed first-level link is the user's own checkout: --group would
// move every skill out of it, while `uninstall <link>` removes only the
// move every skill out of it, while `unlink <link>` removes only the
// link entry. Refuse the ambiguous form.
if len(walks) > 0 && utils.PathsEqual(utils.ResolveSymlink(filepath.Dir(groupPath)), utils.ResolveSymlink(sourceDir)) {
if _, followed := walks[0].Follow.Resolve(groupPath); followed {
return nil, fmt.Errorf("group '%s' is a followed source link; run `skillshare uninstall %s` to remove the link, or name its skills", group, group)
return nil, fmt.Errorf("group '%s' is a followed source link; run `skillshare unlink %s` to remove the link, or name its skills", group, group)
}
}
walkRoot, logicalRoot, err := resolveGroupWalk(groupPath, sourceDir, walks)
+4 -3
View File
@@ -1,6 +1,7 @@
package main
import (
"errors"
"fmt"
"path/filepath"
"strings"
@@ -113,7 +114,7 @@ func performUninstallQuiet(target *uninstallTarget, sourceDir, trashDir string,
groupSkillCount = len(countGroupSkills(target.path))
}
if err := sourcefs.CheckMoveOut(sourceDir, target.path, follow); err != nil {
if err := sourcefs.CheckSkillMoveOut(sourceDir, target.path, follow); err != nil {
return "", err
}
if _, err := trash.MoveToTrash(target.path, target.name, trashDir); err != nil {
@@ -132,7 +133,7 @@ func performUninstallQuiet(target *uninstallTarget, sourceDir, trashDir string,
// performUninstall moves the skill to trash (verbose single-target output).
// Note: .gitignore cleanup is handled in batch by the caller.
func performUninstall(target *uninstallTarget, mode *uninstallMode) error {
if err := sourcefs.CheckMoveOut(mode.sourceDir, target.path, mode.walk.Follow); err != nil {
if err := sourcefs.CheckSkillMoveOut(mode.sourceDir, target.path, mode.walk.Follow); err != nil {
return err
}
if _, err := trash.MoveToTrash(target.path, target.name, mode.trashDir); err != nil {
@@ -489,7 +490,7 @@ func runUninstallSkills(opts *uninstallOptions, mode *uninstallMode, rawArgs []s
}
if err := performUninstall(t, mode); err != nil {
failed = append(failed, fmt.Sprintf("%s: %v", t.name, err))
if mode.reportAfterFinalize {
if mode.reportAfterFinalize || errors.Is(err, sourcefs.ErrLinkedSkillRoot) {
ui.Warning("Failed to uninstall %s: %v", t.name, err)
}
} else {
+7 -2
View File
@@ -1,6 +1,7 @@
package server
import (
"errors"
"fmt"
"log"
"net/http"
@@ -558,8 +559,12 @@ func (s *Server) handleUninstallSkill(w http.ResponseWriter, r *http.Request) {
return
}
if err := sourcefs.CheckMoveOut(source, d.SourcePath, walk.Follow); err != nil {
writeError(w, http.StatusConflict, err.Error())
if err := sourcefs.CheckSkillMoveOut(source, d.SourcePath, walk.Follow); err != nil {
status := http.StatusConflict
if errors.Is(err, sourcefs.ErrLinkedSkillRoot) {
status = http.StatusBadRequest
}
writeError(w, status, err.Error())
return
}
trashName := baseName
+1 -1
View File
@@ -280,7 +280,7 @@ func (s *Server) handleBatchUninstallSkills(w http.ResponseWriter, body batchUni
continue
}
if err := sourcefs.CheckMoveOut(source, skill.SourcePath, walk.Follow); err != nil {
if err := sourcefs.CheckSkillMoveOut(source, skill.SourcePath, walk.Follow); err != nil {
res.Success = false
res.Error = err.Error()
results = append(results, res)
@@ -13,6 +13,7 @@ import (
"skillshare/internal/config"
"skillshare/internal/trash"
"skillshare/internal/utils"
)
func uninstallLinkedSkill(t *testing.T, s *Server, name string, batch bool) (*httptest.ResponseRecorder, bool) {
@@ -111,6 +112,51 @@ func TestHandleUninstallSkill_FollowedLink(t *testing.T) {
testUninstallFollowedLink(t, false)
}
func TestHandleUninstallSkill_FollowedLinkRootRefused(t *testing.T) {
for _, batch := range []bool{false, true} {
for _, project := range []bool{false, true} {
for _, name := range []string{"_dev", "dev"} {
t.Run(map[bool]string{false: "single", true: "batch"}[batch]+"/"+map[bool]string{false: "global", true: "project"}[project]+"/"+name, func(t *testing.T) {
s, src := newTestServer(t)
if project {
src = t.TempDir()
s = NewProject(s.cfg, &config.ProjectConfig{
Sources: config.ProjectSources{Skills: src}, FollowSourceLinks: true,
}, t.TempDir(), "127.0.0.1:0", "", "")
} else {
s.cfg.FollowSourceLinks = true
}
if err := s.saveConfig(); err != nil {
t.Fatal(err)
}
target := t.TempDir()
addSkill(t, target, ".")
addSkill(t, target, "child")
link := filepath.Join(src, name)
if err := os.Symlink(target, link); err != nil {
t.Fatal(err)
}
rr, success := uninstallLinkedSkill(t, s, name, batch)
if success || (!batch && rr.Code != http.StatusBadRequest) || !strings.Contains(rr.Body.String(), name+" is the linked folder itself; use unlink to remove the link") {
t.Fatalf("expected linked root refusal: %d: %s", rr.Code, rr.Body.String())
}
if !utils.IsSymlinkOrJunction(link) {
t.Fatal("link was removed")
}
for _, rel := range []string{"SKILL.md", "child/SKILL.md"} {
if _, err := os.Stat(filepath.Join(link, filepath.FromSlash(rel))); err != nil {
t.Fatalf("skill disappeared through link: %s: %v", rel, err)
}
}
if items := trash.List(s.trashBase()); len(items) != 0 {
t.Fatalf("linked root moved to trash: %+v", items)
}
})
}
}
}
}
func TestHandleUninstallSkill_ExactNameBeforeLinkedBasename(t *testing.T) {
s, src := newTestServer(t)
addSkill(t, src, "foo")
+21
View File
@@ -117,6 +117,27 @@ func TestFollowKeepsLinkEntrySemantics(t *testing.T) {
}
}
func TestCheckSkillMoveOut_RefusesFollowedRootSkill(t *testing.T) {
r, _, ext := followFixture(t)
follow := sourcewalk.NewFollow(r.Dir(), nil)
link := filepath.Join(r.Dir(), "_f")
if err := CheckSkillMoveOut(r.Dir(), link, follow); !errors.Is(err, ErrLinkedSkillRoot) {
t.Fatalf("root skill move = %v, want ErrLinkedSkillRoot", err)
}
if err := CheckSkillMoveOut(r.Dir(), filepath.Join(link, "child"), follow); err != nil {
t.Fatalf("nested skill move: %v", err)
}
if err := CheckMoveOut(r.Dir(), link, follow); err != nil {
t.Fatalf("explicit link move: %v", err)
}
if err := os.Remove(filepath.Join(ext, "SKILL.md")); err != nil {
t.Fatal(err)
}
if err := CheckSkillMoveOut(r.Dir(), link, follow); err != nil {
t.Fatalf("container link move: %v", err)
}
}
func TestNoPolicyKeepsRefusals(t *testing.T) {
_, plain, _ := followFixture(t)
name := filepath.Join("_f", "child", "SKILL.md")
+23
View File
@@ -34,6 +34,9 @@ import (
// components is a link.
var ErrLink = errors.New("path is a link")
// ErrLinkedSkillRoot means a skill uninstall would remove its source link.
var ErrLinkedSkillRoot = errors.New("linked folder itself; use unlink to remove the link")
// LinkError reports the component of a path that is a link.
type LinkError struct {
Path string // the link, as an absolute path under the source root
@@ -97,6 +100,17 @@ func MkdirAllIn(dir, name string, follow ...*sourcewalk.Follow) error {
// refused. Path itself may be a link; a rename moves the link, never its
// target.
func CheckMoveOut(dir, path string, follow ...*sourcewalk.Follow) error {
return checkMoveOut(dir, path, false, follow...)
}
// CheckSkillMoveOut also refuses a followed link whose target root is a skill.
// Moving that entry would unlink the whole folder instead of removing a skill.
// Explicit unlink operations use CheckMoveOut instead.
func CheckSkillMoveOut(dir, path string, follow ...*sourcewalk.Follow) error {
return checkMoveOut(dir, path, true, follow...)
}
func checkMoveOut(dir, path string, skill bool, follow ...*sourcewalk.Follow) error {
r, err := Open(dir, follow...)
if err != nil {
return err
@@ -106,6 +120,15 @@ func CheckMoveOut(dir, path string, follow ...*sourcewalk.Follow) error {
if err != nil {
return err
}
if skill && !strings.ContainsRune(rel, filepath.Separator) {
if _, followed := r.follow.Resolve(path); followed {
if _, err := os.Stat(filepath.Join(path, "SKILL.md")); err == nil {
return fmt.Errorf("%s is the %w", rel, ErrLinkedSkillRoot)
} else if !os.IsNotExist(err) {
return err
}
}
}
return r.CheckParent(rel)
}
@@ -5,11 +5,43 @@ package integration
import (
"os"
"path/filepath"
"strings"
"testing"
"skillshare/internal/testutil"
"skillshare/internal/utils"
)
func TestUninstall_FollowedLinkRootSkillRefused(t *testing.T) {
for _, args := range [][]string{{"dev"}, {"--all"}, {"dev", "--json"}} {
t.Run(strings.Join(args, "_"), func(t *testing.T) {
sb := testutil.NewSandbox(t)
defer sb.Cleanup()
checkout := filepath.Join(sb.Root, "code", "dev-skills")
sb.WriteFile(filepath.Join(checkout, "SKILL.md"), "---\nname: dev\n---\n# dev")
sb.WriteFile(filepath.Join(checkout, "child", "SKILL.md"), "---\nname: child\n---\n# child")
link := filepath.Join(sb.SourcePath, "dev")
sb.CreateSymlink(checkout, link)
sb.WriteConfig("source: " + sb.SourcePath + "\nfollow_source_links: true\ntargets: {}\n")
result := sb.RunCLI(append([]string{"uninstall", "--force"}, args...)...)
result.AssertFailure(t)
result.AssertAnyOutputContains(t, "dev is the linked folder itself; use unlink to remove the link")
if !utils.IsSymlinkOrJunction(link) {
t.Fatal("link was removed")
}
for _, rel := range []string{"SKILL.md", "child/SKILL.md"} {
if !sb.FileExists(filepath.Join(link, filepath.FromSlash(rel))) {
t.Fatalf("skill disappeared through link: %s", rel)
}
}
sb.RunCLI("unlink", "dev").AssertSuccess(t)
if utils.IsSymlinkOrJunction(link) || !sb.FileExists(filepath.Join(checkout, "SKILL.md")) {
t.Fatal("unlink did not remove only the link")
}
})
}
}
func TestUninstall_NestedSkillBelowFollowedSourceLink(t *testing.T) {
for _, follow := range []bool{true, false} {
sb := testutil.NewSandbox(t)
+3 -1
View File
@@ -103,7 +103,9 @@ Glob matching is case-insensitive: `"Core-*"` matches `core-auth`, `CORE-DB`, et
Glob patterns match against **top-level directory names** in the source folder. Nested skills (e.g. `frontend/react-hooks`) are not matched by `"react-*"` — use `--group frontend` to target skills within a subdirectory.
:::
`--group` refuses a [followed source link](../targets/configuration.md#follow_source_links) such as `_dev-skills`, because it would move every skill out of the real checkout. Use `skillshare uninstall _dev-skills` to remove the link entry, or name the skills (`skillshare uninstall _dev-skills/foo`) to trash them from the checkout.
`--group` refuses a [followed source link](../targets/configuration.md#follow_source_links) such as `_dev-skills`, because it would move every skill out of the real checkout. Use `skillshare unlink _dev-skills` to remove the link entry, or name the skills (`skillshare uninstall _dev-skills/foo`) to trash them from the checkout.
If the linked folder itself contains `SKILL.md`, uninstall refuses that root skill: moving it would remove the link and hide all nested skills. Use [`unlink`](./unlink.md) to remove only the link; the checkout stays untouched.
## Remove All
@@ -103,7 +103,9 @@ Glob マッチングは大文字・小文字を区別しません: `"Core-*"`
Glob パターンは source フォルダ内の**トップレベルのディレクトリ名**に対してマッチします。ネストされた skill(例: `frontend/react-hooks`)は `"react-*"` にマッチしません — サブディレクトリ内の skill を対象にするには `--group frontend` を使ってください。
:::
`--group` は `_dev-skills` のような[たどられた source リンク](../targets/configuration.md#follow_source_links)を拒否します。実際のチェックアウトからすべての skill を移動してしまうためです。リンクのエントリを削除するには `skillshare uninstall _dev-skills` を使い、チェックアウトから skill を trash に移動するには skill を名前で指定してください(`skillshare uninstall _dev-skills/foo`)。
`--group` は `_dev-skills` のような[たどられた source リンク](../targets/configuration.md#follow_source_links)を拒否します。実際のチェックアウトからすべての skill を移動してしまうためです。リンクのエントリを削除するには `skillshare unlink _dev-skills` を使い、チェックアウトから skill を trash に移動するには skill を名前で指定してください(`skillshare uninstall _dev-skills/foo`)。
リンク先フォルダーの直下に `SKILL.md` がある場合、そのルート skill の uninstall は拒否されます。移動するとリンクが削除され、入れ子の skill もすべて見えなくなるためです。[`unlink`](./unlink.md) でリンクだけを削除してください。チェックアウトは変更されません。
## すべて削除
@@ -103,7 +103,9 @@ Glob 매칭은 대소문자를 구분하지 않습니다: `"Core-*"`는 `core-au
Glob 패턴은 source 폴더 내의 **최상위 디렉터리 이름**에만 매칭됩니다. 중첩된 skill(예: `frontend/react-hooks`)은 `"react-*"`로 매칭되지 않습니다 — 하위 디렉터리 내의 skill을 대상으로 하려면 `--group frontend`를 사용하세요.
:::
`--group`은 `_dev-skills` 같은 [따라간 source 링크](../targets/configuration.md#follow_source_links)를 거부합니다. 실제 checkout에서 모든 skill을 옮겨 버리기 때문입니다. 링크 항목을 제거하려면 `skillshare uninstall _dev-skills`를 사용하고, checkout에서 휴지통으로 보내려면 skill 이름을 지정하세요(`skillshare uninstall _dev-skills/foo`).
`--group`은 `_dev-skills` 같은 [따라간 source 링크](../targets/configuration.md#follow_source_links)를 거부합니다. 실제 checkout에서 모든 skill을 옮겨 버리기 때문입니다. 링크 항목을 제거하려면 `skillshare unlink _dev-skills`를 사용하고, checkout에서 휴지통으로 보내려면 skill 이름을 지정하세요(`skillshare uninstall _dev-skills/foo`).
링크된 폴더 바로 아래에 `SKILL.md`가 있으면 해당 루트 skill의 uninstall을 거부합니다. 이동하면 링크가 제거되어 중첩된 skill도 모두 보이지 않게 되기 때문입니다. [`unlink`](./unlink.md)로 링크만 제거하세요. checkout은 변경되지 않습니다.
## Remove All
@@ -105,7 +105,9 @@ Glob 模式只匹配 source 文件夹中的**顶层目录名**。嵌套的 skill
不会被 `"react-*"` 匹配到——请使用 `--group frontend` 来定位某个子目录中的 skills。
:::
`--group` 会拒绝像 `_dev-skills` 这样[被跟随的 source link](../targets/configuration.md#follow_source_links),因为它会把真实 checkout 中的所有 skills 都移走。移除链接条目请用 `skillshare uninstall _dev-skills`,或按名称指定 skills(`skillshare uninstall _dev-skills/foo`)把它们从 checkout 移到 trash。
`--group` 会拒绝像 `_dev-skills` 这样[被跟随的 source link](../targets/configuration.md#follow_source_links),因为它会把真实 checkout 中的所有 skills 都移走。移除链接条目请用 `skillshare unlink _dev-skills`,或按名称指定 skills(`skillshare uninstall _dev-skills/foo`)把它们从 checkout 移到 trash。
如果链接文件夹的根目录包含 `SKILL.md`,uninstall 会拒绝移除该根级 skill,因为移动它会移除链接,让所有嵌套 skills 也从列表中消失。请用 [`unlink`](./unlink.md) 只移除链接,checkout 保持不变。
## 移除全部
@@ -103,7 +103,9 @@ Glob 比對不分大小寫:`"Core-*"` 會比對到 `core-auth`、`CORE-DB` 等
Glob patterns 只會比對 source 資料夾中的**頂層目錄名稱**。巢狀 skills(例如 `frontend/react-hooks`)不會被 `"react-*"` 比對到 — 請用 `--group frontend` 來鎖定子目錄中的 skills。
:::
`--group` 會拒絕像 `_dev-skills` 這樣[已跟進的 source 連結](../targets/configuration.md#follow_source_links),因為它會把每個 skill 都從真實的 checkout 移出。要移除連結項目請用 `skillshare uninstall _dev-skills`,或指定 skill 名稱(`skillshare uninstall _dev-skills/foo`)把它們從 checkout 丟進垃圾桶。
`--group` 會拒絕像 `_dev-skills` 這樣[已跟進的 source 連結](../targets/configuration.md#follow_source_links),因為它會把每個 skill 都從真實的 checkout 移出。要移除連結項目請用 `skillshare unlink _dev-skills`,或指定 skill 名稱(`skillshare uninstall _dev-skills/foo`)把它們從 checkout 丟進垃圾桶。
如果連結資料夾的根目錄包含 `SKILL.md`,uninstall 會拒絕移除該根層 skill,因為移動它會移除連結,讓所有巢狀 skills 也從列表消失。請用 [`unlink`](./unlink.md) 只移除連結,checkout 保持不變。
## 移除全部
+1 -1
View File
@@ -54,7 +54,7 @@ Source-link endpoints (skills only, in the dashboard's current global/project mo
Both call `internal/sourcelink`, share the uninstall routes' middleware, and return guard refusals as HTTP 400 with the core reason in the string `error` field. `enable: true` persists `follow_source_links` in the current config and refreshes the follow snapshot. The skills page's **Link folder** dialog offers that setting only while it is off. `GET /api/resources` adds optional `linkName` and `linkTarget` fields to skills beneath a followed first-level source link; the target is resolved by the same discovery policy, and skipped links are not identified as followed. Linked groups use a link icon and muted target path in list/cards headers; the icon-only **Unlink** button changes from a link icon to an unlink icon on hover or focus. Tree rows use a link icon and keep the target and secondary **Unlink** action in the detail pane. Linked groups have no Update repo action or group context menu; the Updates tab covers followed checkouts. Unlink confirms target preservation, affected skills on the next sync, and Trash-page recovery before sending a request; linked skill uninstall confirms that the selected skills move out of the linked folder into trash.
`DELETE /api/resources/{name}` and `POST /api/uninstall/batch` (`{names: [flatName], kind?: "skill", force?: bool}`) resolve individual skills beneath followed first-level links with the same follow policy as discovery, before applying tracked-repo restrictions. They move only the selected skill through `sourcefs.CheckMoveOut`, preserving its logical path (for example, `_dev-skills/foo`) in trash for policy-aware restore. The link and sibling skills stay in place. Real tracked-repo members remain protected, and links skipped by the policy are not treated as followed. Single uninstall returns `{success, name, movedToTrash}`; batch returns per-name `results` and a `summary` with `succeeded` and `failed` counts.
`DELETE /api/resources/{name}` and `POST /api/uninstall/batch` (`{names: [flatName], kind?: "skill", force?: bool}`) resolve individual skills beneath followed first-level links with the same follow policy as discovery, before applying tracked-repo restrictions. They move only the selected skill through `sourcefs.CheckSkillMoveOut`, preserving its logical path (for example, `_dev-skills/foo`) in trash for policy-aware restore. A skill at the link target's root is refused with `is the linked folder itself; use unlink to remove the link` (single HTTP 400, batch per-item error), as in CLI uninstall; explicit unlink uses `CheckMoveOut` and moves only the link. The link and sibling skills stay in place. Real tracked-repo members remain protected, and links skipped by the policy are not treated as followed. Single uninstall returns `{success, name, movedToTrash}`; batch returns per-name `results` and a `summary` with `succeeded` and `failed` counts.
`POST /api/trash/{name}/restore` restores skills using the current global/project follow policy. A logical name such as `_dev-skills/foo` restores into the link target when the policy follows that link; with `follow_source_links` off, it returns HTTP 500 with the existing `is a link; edit its target directly` refusal and preserves the trash entry. Link names do not determine permission to follow. Agent restore is unchanged.