Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
52.2 KB
Raw Blame
package daemon

import (
	"os"
	"path/filepath"
	"reflect"
	"runtime"
	"testing"
)

func writeTestLocalSkill(t *testing.T, root, rel string, files map[string]string) string {
	t.Helper()

	skillDir := filepath.Join(root, filepath.FromSlash(rel))
	if err := os.MkdirAll(skillDir, 0o755); err != nil {
		t.Fatalf("mkdir skill dir: %v", err)
	}
	for path, content := range files {
		fullPath := filepath.Join(skillDir, filepath.FromSlash(path))
		if err := os.MkdirAll(filepath.Dir(fullPath), 0o755); err != nil {
			t.Fatalf("mkdir parents for %s: %v", path, err)
		}
		if err := os.WriteFile(fullPath, []byte(content), 0o644); err != nil {
			t.Fatalf("write %s: %v", path, err)
		}
	}
	return skillDir
}

// setTestUserHome redirects every environment variable used by Go and the
// runtime home resolvers on supported platforms. HOME alone is not enough on
// Windows: os.UserHomeDir reads USERPROFILE and Hermes uses LOCALAPPDATA.
func setTestUserHome(t *testing.T, home string) {
	t.Helper()
	redirectTestHome(t, home)
	t.Setenv("LOCALAPPDATA", filepath.Join(home, "AppData", "Local"))
}

func testDefaultHermesHome(home string) string {
	if runtime.GOOS == "windows" {
		return filepath.Join(home, "AppData", "Local", "hermes")
	}
	return filepath.Join(home, ".hermes")
}

func writeTestClaudePlugin(t *testing.T, home, id, name string, enabled bool) string {
	t.Helper()
	installPath := filepath.Join(home, ".claude", "plugins", "cache", name, "1.0.0")
	if err := os.MkdirAll(filepath.Join(installPath, ".claude-plugin"), 0o755); err != nil {
		t.Fatal(err)
	}
	manifest := `{"name":"` + name + `","skills":"./skills","mcpServers":"./mcp.json"}`
	if err := os.WriteFile(filepath.Join(installPath, ".claude-plugin", "plugin.json"), []byte(manifest), 0o644); err != nil {
		t.Fatal(err)
	}
	if err := os.MkdirAll(filepath.Join(home, ".claude", "plugins"), 0o755); err != nil {
		t.Fatal(err)
	}
	installed := `{"version":2,"plugins":{"` + id + `":[{"scope":"user","installPath":"` + installPath + `"}]}}`
	if err := os.WriteFile(filepath.Join(home, ".claude", "plugins", "installed_plugins.json"), []byte(installed), 0o644); err != nil {
		t.Fatal(err)
	}
	if err := os.MkdirAll(filepath.Join(home, ".claude"), 0o755); err != nil {
		t.Fatal(err)
	}
	settings := `{"enabledPlugins":{"` + id + `":` + map[bool]string{true: "true", false: "false"}[enabled] + `}}`
	if err := os.WriteFile(filepath.Join(home, ".claude", "settings.json"), []byte(settings), 0o644); err != nil {
		t.Fatal(err)
	}
	return installPath
}

func TestListRuntimeLocalSkills_Claude(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	writeTestLocalSkill(t, filepath.Join(home, ".claude", "skills"), "review-helper", map[string]string{
		"SKILL.md":           "---\nname: Review Helper\ndescription: Review pull requests\n---\n# Review Helper\n",
		"templates/check.md": "checklist",
		"LICENSE":            "ignored",
		".secret":            "ignored",
	})

	skills, supported, err := listRuntimeLocalSkills("claude")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	if !supported {
		t.Fatal("claude should be supported")
	}
	if len(skills) != 1 {
		t.Fatalf("expected 1 skill, got %d", len(skills))
	}

	skill := skills[0]
	if skill.Key != "review-helper" {
		t.Fatalf("key = %q, want review-helper", skill.Key)
	}
	if skill.Name != "Review Helper" {
		t.Fatalf("name = %q, want Review Helper", skill.Name)
	}
	if skill.Description != "Review pull requests" {
		t.Fatalf("description = %q", skill.Description)
	}
	// 2 = supporting file (templates/check.md) + SKILL.md itself.
	// Bundle file count purposely excludes SKILL.md (it travels in
	// `Content`) but the summary count adds it back so the user sees
	// the real total.
	if skill.FileCount != 2 {
		t.Fatalf("file_count = %d, want 2", skill.FileCount)
	}
	if skill.SourcePath != "~/.claude/skills/review-helper" {
		t.Fatalf("source_path = %q", skill.SourcePath)
	}
	if !skill.CanDisable {
		t.Fatal("claude runtime skill should be controllable")
	}
}

func TestListRuntimeLocalSkills_Mcode(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	writeTestLocalSkill(t, filepath.Join(home, ".minimax", "skills"), "mcode-review", map[string]string{
		"SKILL.md": "---\nname: MCode Review\ndescription: Review code with MiniMax Code\n---\n",
	})

	skills, supported, err := listRuntimeLocalSkills("mcode")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	if !supported || len(skills) != 1 {
		t.Fatalf("supported=%v skills=%#v", supported, skills)
	}
	if skills[0].SourcePath != "~/.minimax/skills/mcode-review" {
		t.Fatalf("source_path = %q", skills[0].SourcePath)
	}
}

// TestListRuntimeLocalSkills_Codebuddy is the regression guard for a bug
// where CodeBuddy was treated as a drop-in alias for Claude and local
// (user-level) skills were discovered from ~/.claude/skills. CodeBuddy Code
// is a Claude Code fork but ships its own native config directory and does
// NOT read ~/.claude/skills by default — see
// https://www.codebuddy.ai/docs/cli/skills ("User-level Skills:
// ~/.codebuddy/skills/"). Discovery must use ~/.codebuddy/skills instead.
func TestListRuntimeLocalSkills_Codebuddy(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	writeTestLocalSkill(t, filepath.Join(home, ".codebuddy", "skills"), "review-helper", map[string]string{
		"SKILL.md": "---\nname: CodeBuddy Review\ndescription: Review code with CodeBuddy\n---\n# CodeBuddy Review\n",
	})
	// ~/.claude/skills is not a CodeBuddy discovery root, so this must not
	// appear for the codebuddy provider.
	writeTestLocalSkill(t, filepath.Join(home, ".claude", "skills"), "review-helper", map[string]string{
		"SKILL.md": "---\nname: Claude Review\ndescription: Should not appear for codebuddy\n---\n# Claude Review\n",
	})

	skills, supported, err := listRuntimeLocalSkills("codebuddy")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	if !supported {
		t.Fatal("codebuddy should be supported")
	}
	if len(skills) != 1 {
		t.Fatalf("expected 1 skill, got %d: %+v", len(skills), skills)
	}

	skill := skills[0]
	if skill.Key != "review-helper" {
		t.Fatalf("key = %q, want review-helper", skill.Key)
	}
	if skill.Name != "CodeBuddy Review" {
		t.Fatalf("name = %q, want CodeBuddy Review", skill.Name)
	}
	if skill.SourcePath != "~/.codebuddy/skills/review-helper" {
		t.Fatalf("source_path = %q, want ~/.codebuddy/skills/review-helper", skill.SourcePath)
	}
	if skill.CanDisable {
		t.Fatal("codebuddy runtime skill controls are not supported yet")
	}
}

func TestRuntimeLocalSkills_CodebuddyExcludesClaudePluginSkills(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	writeTestLocalSkill(t, filepath.Join(home, ".codebuddy", "skills"), "codebuddy-only", map[string]string{
		"SKILL.md": "---\nname: CodeBuddy Only\n---\n",
	})
	installPath := writeTestClaudePlugin(t, home, "paper-desktop@paper", "paper-desktop", true)
	writeTestLocalSkill(t, filepath.Join(installPath, "skills"), "design-to-code", map[string]string{
		"SKILL.md": "---\nname: Claude Plugin Skill\n---\n",
	})

	skills, supported, err := listRuntimeLocalSkills("codebuddy")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	if !supported {
		t.Fatal("codebuddy should be supported")
	}
	if len(skills) != 1 || skills[0].Key != "codebuddy-only" {
		t.Fatalf("CodeBuddy must not list Claude plugin skills, got %#v", skills)
	}

	bundle, supported, err := loadRuntimeLocalSkillBundle("codebuddy", "paper-desktop:design-to-code")
	if !supported {
		t.Fatal("codebuddy should be supported for import")
	}
	if err == nil || err.Error() != "local skill not found" {
		t.Fatalf("load Claude plugin skill for CodeBuddy err = %v, want local skill not found", err)
	}
	if bundle != nil {
		t.Fatalf("load Claude plugin skill for CodeBuddy bundle = %#v, want nil", bundle)
	}
}

func TestListRuntimeLocalSkills_ClaudeEnabledPlugin(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)
	installPath := writeTestClaudePlugin(t, home, "paper-desktop@paper", "paper-desktop", true)
	writeTestLocalSkill(t, filepath.Join(installPath, "skills"), "design-to-code", map[string]string{
		"SKILL.md": "---\nname: Design to code\ndescription: Turn a design into code\n---\n# Design\n",
	})

	skills, supported, err := listRuntimeLocalSkills("claude")
	if err != nil {
		t.Fatal(err)
	}
	if !supported || len(skills) != 1 {
		t.Fatalf("supported=%v skills=%#v", supported, skills)
	}
	got := skills[0]
	if got.Key != "paper-desktop:design-to-code" || got.Name != "paper-desktop:design-to-code" {
		t.Fatalf("plugin skill identity = %#v", got)
	}
	if got.Root != localSkillRootPlugin || got.Plugin != "paper-desktop@paper" {
		t.Fatalf("plugin skill origin = %#v", got)
	}

	bundle, supported, err := loadRuntimeLocalSkillBundle("claude", got.Key)
	if err != nil || !supported {
		t.Fatalf("load plugin bundle: supported=%v err=%v", supported, err)
	}
	if bundle.Name != got.Key || bundle.Description != "Turn a design into code" {
		t.Fatalf("plugin bundle = %#v", bundle)
	}
}

func TestListRuntimeLocalSkills_ClaudeDisabledPluginIsHidden(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)
	installPath := writeTestClaudePlugin(t, home, "paper-desktop@paper", "paper-desktop", false)
	writeTestLocalSkill(t, filepath.Join(installPath, "skills"), "design-to-code", map[string]string{
		"SKILL.md": "---\nname: Design to code\n---\n",
	})

	skills, supported, err := listRuntimeLocalSkills("claude")
	if err != nil || !supported {
		t.Fatalf("supported=%v err=%v", supported, err)
	}
	if len(skills) != 0 {
		t.Fatalf("disabled plugin skills should be hidden, got %#v", skills)
	}
}

func TestListRuntimeLocalSkills_Kiro(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	writeTestLocalSkill(t, filepath.Join(home, ".kiro", "skills"), "review-helper", map[string]string{
		"SKILL.md": "---\nname: Kiro Review\ndescription: Review code with Kiro\n---\n# Kiro Review\n",
	})

	skills, supported, err := listRuntimeLocalSkills("kiro")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	if !supported {
		t.Fatal("kiro should be supported")
	}
	if len(skills) != 1 {
		t.Fatalf("expected 1 skill, got %d", len(skills))
	}
	if skills[0].Key != "review-helper" {
		t.Fatalf("key = %q, want review-helper", skills[0].Key)
	}
	if skills[0].Name != "Kiro Review" {
		t.Fatalf("name = %q, want Kiro Review", skills[0].Name)
	}
	if skills[0].SourcePath != "~/.kiro/skills/review-helper" {
		t.Fatalf("source_path = %q", skills[0].SourcePath)
	}
}

func TestLocalSkills_DiscoversACPProviderRoots(t *testing.T) {
	tests := []struct {
		provider string
		root     string
		wantPath string
		wantName string
	}{
		{
			provider: "hermes",
			root:     filepath.Join(".hermes", "skills"),
			wantPath: "~/.hermes/skills/review-helper",
			wantName: "Hermes Review",
		},
		{
			provider: "kimi",
			root:     filepath.Join(".kimi", "skills"),
			wantPath: "~/.kimi/skills/review-helper",
			wantName: "Kimi Review",
		},
		{
			provider: "reasonix",
			root:     filepath.Join(".reasonix", "skills"),
			wantPath: "~/.reasonix/skills/review-helper",
			wantName: "Reasonix Review",
		},
		{
			provider: "dsh",
			root:     filepath.Join(".dsh", "skills"),
			wantPath: "~/.dsh/skills/review-helper",
			wantName: "DSH Review",
		},
		{
			provider: "qoder",
			root:     filepath.Join(".qoder", "skills"),
			wantPath: "~/.qoder/skills/review-helper",
			wantName: "Qoder Review",
		},
		{
			provider: "qoderclicn",
			root:     filepath.Join(".qoder-cn", "skills"),
			wantPath: "~/.qoder-cn/skills/review-helper",
			wantName: "Qoder CN Review",
		},
		{
			provider: "qwen",
			root:     filepath.Join(".qwen", "skills"),
			wantPath: "~/.qwen/skills/review-helper",
			wantName: "Qwen Review",
		},
		{
			provider: "grok",
			root:     filepath.Join(".grok", "skills"),
			wantPath: "~/.grok/skills/review-helper",
			wantName: "Grok Review",
		},
	}

	for _, tc := range tests {
		t.Run(tc.provider, func(t *testing.T) {
			home := t.TempDir()
			setTestUserHome(t, home)
			root := filepath.Join(home, tc.root)
			wantPath := tc.wantPath
			if tc.provider == "grok" {
				t.Setenv("GROK_HOME", "")
			}
			if tc.provider == "qwen" {
				t.Setenv("QWEN_HOME", "")
			}
			if tc.provider == "reasonix" {
				t.Setenv("REASONIX_HOME", "")
			}
			if tc.provider == "dsh" {
				t.Setenv("DSH_HOME", "")
			}
			if tc.provider == "hermes" {
				t.Setenv("HERMES_HOME", "")
				root = filepath.Join(testDefaultHermesHome(home), "skills")
				wantPath = relativizeHomePath(filepath.Join(root, "review-helper"))
			}

			writeTestLocalSkill(t, root, "review-helper", map[string]string{
				"SKILL.md": "---\nname: " + tc.wantName + "\ndescription: Review code\n---\n# Review\n",
				"notes.md": "notes",
			})

			skills, supported, err := listRuntimeLocalSkills(tc.provider)
			if err != nil {
				t.Fatalf("listRuntimeLocalSkills: %v", err)
			}
			if !supported {
				t.Fatalf("%s should be supported", tc.provider)
			}
			if len(skills) != 1 {
				t.Fatalf("expected 1 skill, got %d (%v)", len(skills), skills)
			}
			if skills[0].Key != "review-helper" {
				t.Fatalf("key = %q, want review-helper", skills[0].Key)
			}
			if skills[0].Name != tc.wantName {
				t.Fatalf("name = %q, want %q", skills[0].Name, tc.wantName)
			}
			if skills[0].Root != localSkillRootProvider {
				t.Fatalf("root = %q, want %q", skills[0].Root, localSkillRootProvider)
			}
			if skills[0].SourcePath != wantPath {
				t.Fatalf("source_path = %q, want %q", skills[0].SourcePath, wantPath)
			}

			bundle, supported, err := loadRuntimeLocalSkillBundle(tc.provider, "review-helper")
			if err != nil {
				t.Fatalf("loadRuntimeLocalSkillBundle: %v", err)
			}
			if !supported {
				t.Fatalf("%s should be supported for import", tc.provider)
			}
			if bundle.Name != tc.wantName {
				t.Fatalf("bundle name = %q, want %q", bundle.Name, tc.wantName)
			}
			if bundle.SourcePath != wantPath {
				t.Fatalf("bundle source_path = %q, want %q", bundle.SourcePath, wantPath)
			}
			if len(bundle.Files) != 1 {
				t.Fatalf("expected 1 supporting file, got %d", len(bundle.Files))
			}
		})
	}
}

// Hermes discovery must scan the home a Hermes task actually runs against, not
// a hardcoded ~/.hermes: otherwise the skills Hermes loads never appear in the
// Skills tab or the import dialog (GH #8310). The Windows default
// (%LOCALAPPDATA%\hermes) comes from the same resolver and is covered by
// execenv's TestPlatformDefaultHermesHome.
func TestListRuntimeLocalSkills_HermesFollowsTaskHome(t *testing.T) {
	tests := []struct {
		name string
		// setup configures the Hermes home and returns the skills dir a task
		// would read; "" means no provider root should be scanned.
		setup func(t *testing.T, hermesHome string) string
	}{
		{
			name: "explicit HERMES_HOME",
			setup: func(t *testing.T, _ string) string {
				hermesHome := filepath.Join(t.TempDir(), "custom-hermes")
				t.Setenv("HERMES_HOME", hermesHome)
				return filepath.Join(hermesHome, "skills")
			},
		},
		{
			name: "sticky active profile",
			setup: func(t *testing.T, hermesHome string) string {
				writeTestHermesActiveProfile(t, hermesHome, "work")
				return filepath.Join(hermesHome, "profiles", "work", "skills")
			},
		},
		{
			// Hermes refuses to start under a reserved sticky profile, so there
			// is no home whose skills it would load.
			name: "invalid sticky active profile",
			setup: func(t *testing.T, hermesHome string) string {
				writeTestHermesActiveProfile(t, hermesHome, "hermes")
				return ""
			},
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			home := t.TempDir()
			setTestUserHome(t, home)
			t.Setenv("HERMES_HOME", "")
			hermesHome := testDefaultHermesHome(home)
			skillsDir := tc.setup(t, hermesHome)

			// A skill in the default Hermes home that the task-side resolver does
			// not read must not be surfaced when another home/profile is selected.
			writeTestLocalSkill(t, filepath.Join(hermesHome, "skills"), "wrong-home", map[string]string{
				"SKILL.md": "---\nname: Wrong Home\n---\n# Wrong\n",
			})
			writeTestLocalSkill(t, filepath.Join(home, ".agents", "skills"), "shared-helper", map[string]string{
				"SKILL.md": "---\nname: Shared Helper\n---\n# Shared\n",
			})
			wantKeys := []string{"shared-helper"}
			if skillsDir != "" {
				writeTestLocalSkill(t, skillsDir, "review-helper", map[string]string{
					"SKILL.md": "---\nname: Hermes Home Review\n---\n# Review\n",
				})
				wantKeys = []string{"review-helper", "shared-helper"}
			}

			skills, supported, err := listRuntimeLocalSkills("hermes")
			if err != nil {
				t.Fatalf("listRuntimeLocalSkills: %v", err)
			}
			if !supported {
				t.Fatal("hermes should be supported")
			}
			gotKeys := make([]string, 0, len(skills))
			for _, s := range skills {
				gotKeys = append(gotKeys, s.Key)
			}
			if !reflect.DeepEqual(gotKeys, wantKeys) {
				t.Fatalf("keys = %v, want %v", gotKeys, wantKeys)
			}
			if skillsDir == "" {
				return
			}
			if skills[0].Root != localSkillRootProvider {
				t.Fatalf("root = %q, want %q", skills[0].Root, localSkillRootProvider)
			}
			if want := relativizeHomePath(filepath.Join(skillsDir, "review-helper")); skills[0].SourcePath != want {
				t.Fatalf("source_path = %q, want %q", skills[0].SourcePath, want)
			}

			bundle, supported, err := loadRuntimeLocalSkillBundle("hermes", "review-helper")
			if err != nil {
				t.Fatalf("loadRuntimeLocalSkillBundle: %v", err)
			}
			if !supported || bundle == nil || bundle.Name != "Hermes Home Review" {
				t.Fatalf("unexpected bundle: supported=%v bundle=%+v", supported, bundle)
			}
		})
	}
}

func writeTestHermesActiveProfile(t *testing.T, hermesHome, name string) {
	t.Helper()
	if err := os.MkdirAll(hermesHome, 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(hermesHome, "active_profile"), []byte(name+"\n"), 0o644); err != nil {
		t.Fatal(err)
	}
}

func TestListRuntimeLocalSkills_GrokUsesGROKHOME(t *testing.T) {
	home := t.TempDir()
	grokHome := filepath.Join(t.TempDir(), "custom-grok-home")
	redirectTestHome(t, home)
	t.Setenv("GROK_HOME", grokHome)
	writeTestLocalSkill(t, filepath.Join(grokHome, "skills"), "review-helper", map[string]string{
		"SKILL.md": "---\nname: Grok Home Review\ndescription: Review code\n---\n# Review\n",
	})
	writeTestLocalSkill(t, filepath.Join(home, ".grok", "skills"), "wrong-home", map[string]string{
		"SKILL.md": "---\nname: Wrong Home\n---\n# Wrong\n",
	})

	skills, supported, err := listRuntimeLocalSkills("grok")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	if !supported {
		t.Fatal("grok should be supported")
	}
	if len(skills) != 1 || skills[0].Key != "review-helper" {
		t.Fatalf("expected only GROK_HOME skill, got %+v", skills)
	}
	if skills[0].SourcePath != filepath.ToSlash(filepath.Join(grokHome, "skills", "review-helper")) {
		t.Fatalf("source_path = %q, want custom GROK_HOME path", skills[0].SourcePath)
	}

	bundle, supported, err := loadRuntimeLocalSkillBundle("grok", "review-helper")
	if err != nil {
		t.Fatalf("loadRuntimeLocalSkillBundle: %v", err)
	}
	if !supported || bundle == nil || bundle.Name != "Grok Home Review" {
		t.Fatalf("unexpected bundle: supported=%v bundle=%+v", supported, bundle)
	}
}

func TestListRuntimeLocalSkills_QwenUsesQWENHOME(t *testing.T) {
	home := t.TempDir()
	qwenHome := filepath.Join(t.TempDir(), "custom-qwen-home")
	redirectTestHome(t, home)
	t.Setenv("QWEN_HOME", qwenHome)
	writeTestLocalSkill(t, filepath.Join(qwenHome, "skills"), "review-helper", map[string]string{
		"SKILL.md": "---\nname: Qwen Home Review\ndescription: Review code\n---\n# Review\n",
	})
	writeTestLocalSkill(t, filepath.Join(home, ".qwen", "skills"), "wrong-home", map[string]string{
		"SKILL.md": "---\nname: Wrong Home\n---\n# Wrong\n",
	})

	skills, supported, err := listRuntimeLocalSkills("qwen")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	if !supported {
		t.Fatal("qwen should be supported")
	}
	if len(skills) != 1 || skills[0].Key != "review-helper" {
		t.Fatalf("expected only QWEN_HOME skill, got %+v", skills)
	}
	if skills[0].SourcePath != filepath.ToSlash(filepath.Join(qwenHome, "skills", "review-helper")) {
		t.Fatalf("source_path = %q, want custom QWEN_HOME path", skills[0].SourcePath)
	}

	bundle, supported, err := loadRuntimeLocalSkillBundle("qwen", "review-helper")
	if err != nil {
		t.Fatalf("loadRuntimeLocalSkillBundle: %v", err)
	}
	if !supported || bundle == nil || bundle.Name != "Qwen Home Review" {
		t.Fatalf("unexpected bundle: supported=%v bundle=%+v", supported, bundle)
	}
}

// Skill installers (for example lark-cli) place every skill at a shared
// location like ~/.agents/skills/<name> and symlink each one into the
// runtime root (~/.claude/skills/<name>). The previous filepath.WalkDir
// path filtered every symlink out via os.ModeSymlink, so users with
// dozens of installed skills only saw the few they had cloned in place.
// listRuntimeLocalSkills must follow those symlinks.
func TestListRuntimeLocalSkills_FollowsSymlinkedSkillDirs(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	// Real skill lives outside the runtime root.
	target := writeTestLocalSkill(t, filepath.Join(home, ".agents", "skills"), "lark-doc", map[string]string{
		"SKILL.md":  "---\nname: Lark Doc\ndescription: Drive lark docs\n---\n# Lark Doc\n",
		"helper.md": "stub",
	})

	// Runtime root points at it via symlink, the way installers ship it.
	skillsRoot := filepath.Join(home, ".claude", "skills")
	if err := os.MkdirAll(skillsRoot, 0o755); err != nil {
		t.Fatalf("mkdir skills root: %v", err)
	}
	if err := os.Symlink(target, filepath.Join(skillsRoot, "lark-doc")); err != nil {
		t.Fatalf("symlink: %v", err)
	}

	// Sanity: also seed a regular non-symlink skill so we know enumeration
	// returns both, in stable order.
	writeTestLocalSkill(t, skillsRoot, "review-helper", map[string]string{
		"SKILL.md": "---\nname: Review Helper\n---\n",
	})

	skills, supported, err := listRuntimeLocalSkills("claude")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	if !supported {
		t.Fatal("claude should be supported")
	}
	if len(skills) != 2 {
		t.Fatalf("expected 2 skills, got %d (%v)", len(skills), skills)
	}

	bySymlinkKey := skills[0]
	if bySymlinkKey.Key != "lark-doc" {
		bySymlinkKey = skills[1]
	}
	if bySymlinkKey.Key != "lark-doc" {
		t.Fatalf("symlinked skill missing from result: %v", skills)
	}
	if bySymlinkKey.Name != "Lark Doc" {
		t.Fatalf("symlinked skill name = %q, want Lark Doc", bySymlinkKey.Name)
	}
	// Source path is reported relative to the *runtime root* (~/.claude/...),
	// not the resolved target — that's what the user expects to see in the
	// import dialog and matches the non-symlink case.
	if bySymlinkKey.SourcePath != "~/.claude/skills/lark-doc" {
		t.Fatalf("symlinked skill source_path = %q", bySymlinkKey.SourcePath)
	}
}

func TestListRuntimeLocalSkills_CodexUsesSharedCODEXHOME(t *testing.T) {
	home := t.TempDir()
	codexHome := t.TempDir()
	redirectTestHome(t, home)
	t.Setenv("CODEX_HOME", codexHome)

	writeTestLocalSkill(t, filepath.Join(codexHome, "skills"), "debugger", map[string]string{
		"SKILL.md": "# Debugger\n",
	})
	writeTestLocalSkill(t, filepath.Join(home, ".codex", "skills"), "wrong-home", map[string]string{
		"SKILL.md": "# Wrong Home\n",
	})

	skills, supported, err := listRuntimeLocalSkills("codex")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	if !supported {
		t.Fatal("codex should be supported")
	}
	if len(skills) != 1 {
		t.Fatalf("expected 1 skill, got %d", len(skills))
	}
	if skills[0].Key != "debugger" {
		t.Fatalf("key = %q, want debugger", skills[0].Key)
	}
	if skills[0].SourcePath != filepath.Join(codexHome, "skills", "debugger") {
		t.Fatalf("source_path = %q", skills[0].SourcePath)
	}
}

// opencode (and possibly future providers) lay skills out one level deep,
// e.g. ~/.config/opencode/skills/release/reporter/SKILL.md.
// loadRuntimeLocalSkillBundle already accepts that nested key, so the list
// endpoint must surface those skills too — otherwise the import dialog
// hides skills the load endpoint can fetch and users can't pick them.
//
// The walker also has to short-circuit at the outermost SKILL.md it finds:
// nested SKILL.md files inside an already-registered skill (e.g. inside
// `top/SKILL.md`'s own template tree) are part of the parent skill's
// bundle, not separate skills.
func TestListRuntimeLocalSkills_DescendsIntoNestedSkillDirs(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	root := filepath.Join(home, ".config", "opencode", "skills")

	// Top-level skill — should register at key="top" and its child SKILL.md
	// must NOT register as a separate skill.
	writeTestLocalSkill(t, root, "top", map[string]string{
		"SKILL.md":           "---\nname: Top\n---\n",
		"templates/SKILL.md": "not a real skill — sub-template that happens to share the filename",
	})

	// Nested skill — only valid SKILL.md is at depth 2.
	writeTestLocalSkill(t, root, "release/reporter", map[string]string{
		"SKILL.md": "---\nname: Release Reporter\n---\n",
	})

	skills, supported, err := listRuntimeLocalSkills("opencode")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	if !supported {
		t.Fatal("opencode should be supported")
	}

	keys := make([]string, 0, len(skills))
	for _, s := range skills {
		keys = append(keys, s.Key)
	}
	// Two registered skills, "top" and "release/reporter" — and crucially
	// NOT "top/templates" (the inner SKILL.md must be ignored once the
	// parent qualified).
	wantKeys := []string{"release/reporter", "top"}
	if !reflect.DeepEqual(keys, wantKeys) {
		t.Fatalf("keys = %v, want %v", keys, wantKeys)
	}
}

func TestLoadRuntimeLocalSkillBundle_OpenCode(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	writeTestLocalSkill(t, filepath.Join(home, ".config", "opencode", "skills"), "release/reporter", map[string]string{
		"SKILL.md":           "---\nname: Release Reporter\ndescription: Summarize release notes\n---\n# Release Reporter\n",
		"docs/template.md":   "template body",
		"examples/sample.md": "sample body",
	})

	bundle, supported, err := loadRuntimeLocalSkillBundle("opencode", "release/reporter")
	if err != nil {
		t.Fatalf("loadRuntimeLocalSkillBundle: %v", err)
	}
	if !supported {
		t.Fatal("opencode should be supported")
	}
	if bundle.Name != "Release Reporter" {
		t.Fatalf("name = %q", bundle.Name)
	}
	if bundle.Description != "Summarize release notes" {
		t.Fatalf("description = %q", bundle.Description)
	}
	if len(bundle.Files) != 2 {
		t.Fatalf("expected 2 supporting files, got %d", len(bundle.Files))
	}
	if bundle.Files[0].Path != "docs/template.md" || bundle.Files[0].Content != "template body" {
		t.Fatalf("unexpected first file: %+v", bundle.Files[0])
	}
	if bundle.Files[1].Path != "examples/sample.md" || bundle.Files[1].Content != "sample body" {
		t.Fatalf("unexpected second file: %+v", bundle.Files[1])
	}
	if bundle.SourcePath != "~/.config/opencode/skills/release/reporter" {
		t.Fatalf("source_path = %q", bundle.SourcePath)
	}
}

func TestListRuntimeLocalSkills_OpenClaw(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	writeTestLocalSkill(t, filepath.Join(home, ".openclaw", "skills"), "planner", map[string]string{
		"SKILL.md": "# Planner\n",
	})

	skills, supported, err := listRuntimeLocalSkills("openclaw")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	if !supported {
		t.Fatal("openclaw should be supported")
	}
	if len(skills) != 1 {
		t.Fatalf("expected 1 skill, got %d", len(skills))
	}
	if skills[0].SourcePath != "~/.openclaw/skills/planner" {
		t.Fatalf("source_path = %q", skills[0].SourcePath)
	}
}

func TestLoadRuntimeLocalSkillBundle_Cursor(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	writeTestLocalSkill(t, filepath.Join(home, ".cursor", "skills"), "docs-helper", map[string]string{
		"SKILL.md":         "---\nname: Docs Helper\n---\n# Docs Helper\n",
		"notes/tips.md":    "tips",
		"examples/a.txt":   "example",
		".hidden/skip.txt": "ignore",
	})

	bundle, supported, err := loadRuntimeLocalSkillBundle("cursor", "docs-helper")
	if err != nil {
		t.Fatalf("loadRuntimeLocalSkillBundle: %v", err)
	}
	if !supported {
		t.Fatal("cursor should be supported")
	}
	if bundle.Name != "Docs Helper" {
		t.Fatalf("name = %q", bundle.Name)
	}
	if len(bundle.Files) != 2 {
		t.Fatalf("expected 2 files, got %d", len(bundle.Files))
	}
	if bundle.SourcePath != "~/.cursor/skills/docs-helper" {
		t.Fatalf("source_path = %q", bundle.SourcePath)
	}
}

// ---------------------------------------------------------------------------
// Multi-root discovery: provider root + universal ~/.agents/skills (MUL-3333)
// ---------------------------------------------------------------------------

// A skill that lives only in the universal ~/.agents/skills root (no provider
// directory at all) must be discovered and tagged Root="universal".
func TestListRuntimeLocalSkills_DiscoversUniversalAgentsRoot(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	writeTestLocalSkill(t, filepath.Join(home, ".agents", "skills"), "universal-helper", map[string]string{
		"SKILL.md":     "---\nname: Universal Helper\ndescription: Cross-tool skill\n---\n# Universal Helper\n",
		"docs/info.md": "info",
	})

	skills, supported, err := listRuntimeLocalSkills("claude")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	if !supported {
		t.Fatal("claude should be supported")
	}
	if len(skills) != 1 {
		t.Fatalf("expected 1 skill, got %d (%v)", len(skills), skills)
	}
	if skills[0].Key != "universal-helper" {
		t.Fatalf("key = %q, want universal-helper", skills[0].Key)
	}
	if skills[0].Name != "Universal Helper" {
		t.Fatalf("name = %q, want Universal Helper", skills[0].Name)
	}
	if skills[0].Root != localSkillRootUniversal {
		t.Fatalf("root = %q, want %q", skills[0].Root, localSkillRootUniversal)
	}
	if skills[0].SourcePath != "~/.agents/skills/universal-helper" {
		t.Fatalf("source_path = %q", skills[0].SourcePath)
	}
	// 2 = supporting file (docs/info.md) + SKILL.md.
	if skills[0].FileCount != 2 {
		t.Fatalf("file_count = %d, want 2", skills[0].FileCount)
	}
}

// A skill discovered under ~/.agents/skills must be importable, not just
// listable — otherwise the import dialog shows a skill the load endpoint
// can't fetch.
func TestLoadRuntimeLocalSkillBundle_ImportsFromUniversalRoot(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	writeTestLocalSkill(t, filepath.Join(home, ".agents", "skills"), "shared-skill", map[string]string{
		"SKILL.md":        "---\nname: Shared Skill\ndescription: Imported from agents root\n---\n# Shared Skill\n",
		"examples/use.md": "usage",
		"scripts/run.sh":  "echo hi",
	})

	bundle, supported, err := loadRuntimeLocalSkillBundle("claude", "shared-skill")
	if err != nil {
		t.Fatalf("loadRuntimeLocalSkillBundle: %v", err)
	}
	if !supported {
		t.Fatal("claude should be supported")
	}
	if bundle.Name != "Shared Skill" {
		t.Fatalf("name = %q, want Shared Skill", bundle.Name)
	}
	if len(bundle.Files) != 2 {
		t.Fatalf("expected 2 supporting files, got %d", len(bundle.Files))
	}
	if bundle.SourcePath != "~/.agents/skills/shared-skill" {
		t.Fatalf("source_path = %q", bundle.SourcePath)
	}
}

// When the same key exists in BOTH the provider root and the universal root,
// the provider root wins: its SourcePath, Root tag and content are preserved
// and the universal copy is dropped. This is the backward-compatibility
// guarantee — adding the universal root never changes what an existing
// provider-root key resolves to.
func TestLocalSkills_ProviderRootWinsOnKeyConflict(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	writeTestLocalSkill(t, filepath.Join(home, ".claude", "skills"), "dup", map[string]string{
		"SKILL.md": "---\nname: Provider Copy\n---\n# provider\n",
	})
	writeTestLocalSkill(t, filepath.Join(home, ".agents", "skills"), "dup", map[string]string{
		"SKILL.md": "---\nname: Universal Copy\n---\n# universal\n",
	})

	skills, _, err := listRuntimeLocalSkills("claude")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	if len(skills) != 1 {
		t.Fatalf("expected 1 deduped skill, got %d (%v)", len(skills), skills)
	}
	if skills[0].Name != "Provider Copy" {
		t.Fatalf("name = %q, want Provider Copy (provider root must win)", skills[0].Name)
	}
	if skills[0].Root != localSkillRootProvider {
		t.Fatalf("root = %q, want %q", skills[0].Root, localSkillRootProvider)
	}
	if skills[0].SourcePath != "~/.claude/skills/dup" {
		t.Fatalf("source_path = %q, want provider path", skills[0].SourcePath)
	}

	// Load must resolve to the provider copy too, matching the list.
	bundle, _, err := loadRuntimeLocalSkillBundle("claude", "dup")
	if err != nil {
		t.Fatalf("loadRuntimeLocalSkillBundle: %v", err)
	}
	if bundle.Name != "Provider Copy" {
		t.Fatalf("bundle name = %q, want Provider Copy", bundle.Name)
	}
	if bundle.SourcePath != "~/.claude/skills/dup" {
		t.Fatalf("bundle source_path = %q, want provider path", bundle.SourcePath)
	}
}

// Both roots contribute their non-conflicting skills, merged and sorted once.
func TestListRuntimeLocalSkills_MergesBothRoots(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	writeTestLocalSkill(t, filepath.Join(home, ".claude", "skills"), "provider-only", map[string]string{
		"SKILL.md": "---\nname: Provider Only\n---\n",
	})
	writeTestLocalSkill(t, filepath.Join(home, ".agents", "skills"), "universal-only", map[string]string{
		"SKILL.md": "---\nname: Universal Only\n---\n",
	})

	skills, _, err := listRuntimeLocalSkills("claude")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	keys := make([]string, 0, len(skills))
	roots := make(map[string]string)
	for _, s := range skills {
		keys = append(keys, s.Key)
		roots[s.Key] = s.Root
	}
	// Sorted once after merge: "provider-only" < "universal-only".
	wantKeys := []string{"provider-only", "universal-only"}
	if !reflect.DeepEqual(keys, wantKeys) {
		t.Fatalf("keys = %v, want %v", keys, wantKeys)
	}
	if roots["provider-only"] != localSkillRootProvider {
		t.Fatalf("provider-only root = %q", roots["provider-only"])
	}
	if roots["universal-only"] != localSkillRootUniversal {
		t.Fatalf("universal-only root = %q", roots["universal-only"])
	}
}

// A missing universal root is not an error: discovery still returns the
// provider-root skills. (Mirror of the original single-root "missing root
// returns empty" guarantee, now per-root.)
func TestListRuntimeLocalSkills_MissingUniversalRootIsNotAnError(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	writeTestLocalSkill(t, filepath.Join(home, ".claude", "skills"), "only-provider", map[string]string{
		"SKILL.md": "---\nname: Only Provider\n---\n",
	})
	// No ~/.agents/skills created.

	skills, supported, err := listRuntimeLocalSkills("claude")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	if !supported {
		t.Fatal("claude should be supported")
	}
	if len(skills) != 1 || skills[0].Key != "only-provider" {
		t.Fatalf("expected only-provider, got %v", skills)
	}
}

// Both roots missing → empty list, no error.
func TestListRuntimeLocalSkills_BothRootsMissing(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	skills, supported, err := listRuntimeLocalSkills("claude")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	if !supported {
		t.Fatal("claude should be supported")
	}
	if len(skills) != 0 {
		t.Fatalf("expected empty, got %v", skills)
	}
}

// Nested layouts (a skill two levels deep) work in the universal root too.
func TestListRuntimeLocalSkills_NestedSkillInUniversalRoot(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	writeTestLocalSkill(t, filepath.Join(home, ".agents", "skills"), "release/reporter", map[string]string{
		"SKILL.md": "---\nname: Release Reporter\n---\n",
	})

	skills, _, err := listRuntimeLocalSkills("opencode")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	if len(skills) != 1 || skills[0].Key != "release/reporter" {
		t.Fatalf("expected release/reporter, got %v", skills)
	}
	if skills[0].Root != localSkillRootUniversal {
		t.Fatalf("root = %q, want %q", skills[0].Root, localSkillRootUniversal)
	}

	bundle, _, err := loadRuntimeLocalSkillBundle("opencode", "release/reporter")
	if err != nil {
		t.Fatalf("loadRuntimeLocalSkillBundle: %v", err)
	}
	if bundle.Name != "Release Reporter" {
		t.Fatalf("bundle name = %q", bundle.Name)
	}
}

// loadRuntimeLocalSkillBundle falls through to the universal root only when
// the provider root genuinely lacks the key (IsNotExist).
func TestLoadRuntimeLocalSkillBundle_FallsThroughToUniversalOnNotExist(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	// Provider root exists but does NOT contain "only-universal".
	writeTestLocalSkill(t, filepath.Join(home, ".claude", "skills"), "something-else", map[string]string{
		"SKILL.md": "---\nname: Something Else\n---\n",
	})
	writeTestLocalSkill(t, filepath.Join(home, ".agents", "skills"), "only-universal", map[string]string{
		"SKILL.md": "---\nname: Only Universal\n---\n# only universal\n",
	})

	bundle, _, err := loadRuntimeLocalSkillBundle("claude", "only-universal")
	if err != nil {
		t.Fatalf("loadRuntimeLocalSkillBundle: %v", err)
	}
	if bundle.Name != "Only Universal" {
		t.Fatalf("name = %q, want Only Universal", bundle.Name)
	}
	if bundle.SourcePath != "~/.agents/skills/only-universal" {
		t.Fatalf("source_path = %q", bundle.SourcePath)
	}
}

// When the provider root HAS the key but reading its SKILL.md fails for a
// reason other than IsNotExist, loadRuntimeLocalSkillBundle must return that
// error instead of silently loading a different same-key skill from the
// universal root. Here we make ~/.claude/skills/clash/SKILL.md a directory so
// the read fails ("is a directory") while the dir itself exists.
func TestLoadRuntimeLocalSkillBundle_DoesNotMaskReadErrorWithUniversalFallback(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	clashDir := filepath.Join(home, ".claude", "skills", "clash")
	if err := os.MkdirAll(filepath.Join(clashDir, "SKILL.md"), 0o755); err != nil {
		t.Fatalf("mkdir SKILL.md-as-dir: %v", err)
	}
	// A valid same-key skill in the universal root that must NOT be used.
	writeTestLocalSkill(t, filepath.Join(home, ".agents", "skills"), "clash", map[string]string{
		"SKILL.md": "---\nname: Universal Clash\n---\n",
	})

	bundle, _, err := loadRuntimeLocalSkillBundle("claude", "clash")
	if err == nil {
		t.Fatalf("expected an error, got bundle %+v", bundle)
	}
	if bundle != nil {
		t.Fatalf("expected nil bundle on error, got %+v", bundle)
	}
}

// A user can deliberately expose one on-disk skill under two names by
// symlinking ~/.claude/skills/bar -> ~/.agents/skills/foo. Because each root
// keeps its OWN `visited` set, the list returns both `bar` (from the claude
// root) and `foo` (from the agents root). A shared visited set would drop one.
func TestListRuntimeLocalSkills_PerRootVisitedAllowsCrossRootSymlinkAlias(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	target := writeTestLocalSkill(t, filepath.Join(home, ".agents", "skills"), "foo", map[string]string{
		"SKILL.md": "---\nname: Foo\n---\n",
	})

	claudeRoot := filepath.Join(home, ".claude", "skills")
	if err := os.MkdirAll(claudeRoot, 0o755); err != nil {
		t.Fatalf("mkdir claude root: %v", err)
	}
	if err := os.Symlink(target, filepath.Join(claudeRoot, "bar")); err != nil {
		t.Fatalf("symlink: %v", err)
	}

	skills, _, err := listRuntimeLocalSkills("claude")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	keys := make([]string, 0, len(skills))
	roots := make(map[string]string)
	for _, s := range skills {
		keys = append(keys, s.Key)
		roots[s.Key] = s.Root
	}
	wantKeys := []string{"bar", "foo"}
	if !reflect.DeepEqual(keys, wantKeys) {
		t.Fatalf("keys = %v, want %v (per-root visited must not collapse the alias)", keys, wantKeys)
	}
	if roots["bar"] != localSkillRootProvider {
		t.Fatalf("bar root = %q, want provider", roots["bar"])
	}
	if roots["foo"] != localSkillRootUniversal {
		t.Fatalf("foo root = %q, want universal", roots["foo"])
	}
}

// Regression (大彪): a provider-root directory that shares a skill's key but
// contains NO SKILL.md must not shadow a valid universal-root skill at the
// same key. listRuntimeLocalSkills descends past the invalid provider dir and
// surfaces the universal skill, so loadRuntimeLocalSkillBundle MUST resolve to
// that same universal skill — not error out on the invalid provider dir.
// Before the fix, load only fell through on os.IsNotExist for the skill
// directory, so an existing-but-invalid provider dir made list and load
// disagree.
func TestLoadRuntimeLocalSkillBundle_ProviderDirWithoutSkillMdFallsThrough(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	// Provider root has a same-key directory but NO SKILL.md (just a stray
	// file), so it is NOT a valid skill.
	writeTestLocalSkill(t, filepath.Join(home, ".claude", "skills"), "shadowed", map[string]string{
		"notes.md": "not a skill — no SKILL.md here",
	})
	// Universal root has the real skill at the same key.
	writeTestLocalSkill(t, filepath.Join(home, ".agents", "skills"), "shadowed", map[string]string{
		"SKILL.md":     "---\nname: Real Shadowed\ndescription: The valid one\n---\n# Real Shadowed\n",
		"docs/info.md": "info",
	})

	// list must surface exactly the universal skill at key "shadowed".
	skills, _, err := listRuntimeLocalSkills("claude")
	if err != nil {
		t.Fatalf("listRuntimeLocalSkills: %v", err)
	}
	if len(skills) != 1 {
		t.Fatalf("expected 1 skill, got %d (%v)", len(skills), skills)
	}
	if skills[0].Key != "shadowed" || skills[0].Root != localSkillRootUniversal {
		t.Fatalf("list surfaced %+v, want key=shadowed root=universal", skills[0])
	}
	if skills[0].SourcePath != "~/.agents/skills/shadowed" {
		t.Fatalf("list source_path = %q, want ~/.agents/skills/shadowed", skills[0].SourcePath)
	}

	// load must resolve to the SAME universal skill list showed — not error on
	// the invalid provider dir.
	bundle, _, err := loadRuntimeLocalSkillBundle("claude", "shadowed")
	if err != nil {
		t.Fatalf("loadRuntimeLocalSkillBundle: %v (load disagreed with list)", err)
	}
	if bundle.Name != "Real Shadowed" {
		t.Fatalf("bundle name = %q, want Real Shadowed", bundle.Name)
	}
	if bundle.SourcePath != "~/.agents/skills/shadowed" {
		t.Fatalf("bundle source_path = %q, want ~/.agents/skills/shadowed", bundle.SourcePath)
	}
}

// A provider-root entry that exists at the key but is NOT a directory (a plain
// file) likewise must not shadow a valid universal skill — list never surfaces
// a non-dir, so load must fall through too.
func TestLoadRuntimeLocalSkillBundle_ProviderNonDirFallsThrough(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)

	claudeRoot := filepath.Join(home, ".claude", "skills")
	if err := os.MkdirAll(claudeRoot, 0o755); err != nil {
		t.Fatalf("mkdir claude root: %v", err)
	}
	// A plain file where the skill dir would be.
	if err := os.WriteFile(filepath.Join(claudeRoot, "filish"), []byte("x"), 0o644); err != nil {
		t.Fatalf("write file: %v", err)
	}
	writeTestLocalSkill(t, filepath.Join(home, ".agents", "skills"), "filish", map[string]string{
		"SKILL.md": "---\nname: Filish\n---\n# Filish\n",
	})

	bundle, _, err := loadRuntimeLocalSkillBundle("claude", "filish")
	if err != nil {
		t.Fatalf("loadRuntimeLocalSkillBundle: %v", err)
	}
	if bundle.Name != "Filish" || bundle.SourcePath != "~/.agents/skills/filish" {
		t.Fatalf("bundle = %+v, want universal Filish", bundle)
	}

}

// invalidUTF8Docx is a .docx prefix (PK zip magic) followed by bytes that are
// not valid UTF-8. Carrying this through SkillFileData.Content is exactly the
// corruption in #7143: encoding/json rewrites each invalid byte to U+FFFD, so
// the file written back into the task environment no longer opens.
const invalidUTF8Docx = "PK\x03\x04\x14\x00\x06\x00\xff\xfe\x80\x81payload"

func TestCollectLocalSkillFiles_SkipsBinarySupportingFiles(t *testing.T) {
	root := t.TempDir()
	skillDir := writeTestLocalSkill(t, root, "docs", map[string]string{
		"SKILL.md":               "---\nname: docs\n---\nbody\n",
		"references/notes.md":    "# notes\n",
		"references/report.docx": invalidUTF8Docx,
		"assets/logo.png":        "\x89PNG\r\n\x1a\n\x00\x00\x00",
	})

	files, err := collectLocalSkillFiles(skillDir, true)
	if err != nil {
		t.Fatalf("collectLocalSkillFiles: %v", err)
	}

	paths := make([]string, 0, len(files))
	for _, f := range files {
		paths = append(paths, f.Path)
	}
	want := []string{"references/notes.md"}
	if !reflect.DeepEqual(paths, want) {
		t.Fatalf("collected paths = %v, want %v", paths, want)
	}

	// The text file that survives must survive byte-for-byte.
	if files[0].Content != "# notes\n" {
		t.Errorf("text content = %q, want %q", files[0].Content, "# notes\n")
	}
}

func TestCollectLocalSkillFiles_BinarySkipIsConsistentAcrossPasses(t *testing.T) {
	// Discovery reports the bundle with includeContent=false and sync uploads
	// it with includeContent=true. If only one pass skipped binary files the
	// two would disagree on what the bundle contains. This must hold both for
	// a listed binary extension and for one caught only by the content-level
	// UTF-8 check — the discovery pass has to actually read the file to make
	// the same call the sync pass makes.
	root := t.TempDir()
	skillDir := writeTestLocalSkill(t, root, "docs", map[string]string{
		"SKILL.md":                  "---\nname: docs\n---\nbody\n",
		"references/notes.md":       "# notes\n",
		"references/report.docx":    invalidUTF8Docx,
		"weights/model.safetensors": invalidUTF8Bytes,
	})

	listed, err := collectLocalSkillFiles(skillDir, false)
	if err != nil {
		t.Fatalf("collectLocalSkillFiles(includeContent=false): %v", err)
	}
	synced, err := collectLocalSkillFiles(skillDir, true)
	if err != nil {
		t.Fatalf("collectLocalSkillFiles(includeContent=true): %v", err)
	}

	listedPaths := make([]string, 0, len(listed))
	for _, f := range listed {
		listedPaths = append(listedPaths, f.Path)
	}
	syncedPaths := make([]string, 0, len(synced))
	for _, f := range synced {
		syncedPaths = append(syncedPaths, f.Path)
	}
	if !reflect.DeepEqual(listedPaths, syncedPaths) {
		t.Fatalf("discovery pass = %v, sync pass = %v; passes must agree", listedPaths, syncedPaths)
	}
	want := []string{"references/notes.md"}
	if !reflect.DeepEqual(listedPaths, want) {
		t.Fatalf("collected paths = %v, want %v", listedPaths, want)
	}
}

// invalidUTF8Bytes carries no listed binary extension's magic — it exists to
// prove the content-level check, not the extension list, is what catches it.
const invalidUTF8Bytes = "\xff\xfe\x00\x01payload\x80\x81"

// Bohan-J's review on #7175: the extension blacklist alone doesn't close the
// root cause. A binary file with an unlisted extension must still be caught
// by the content-level utf8.Valid check.
func TestCollectLocalSkillFiles_SkipsUnlistedBinaryExtension(t *testing.T) {
	root := t.TempDir()
	skillDir := writeTestLocalSkill(t, root, "docs", map[string]string{
		"SKILL.md":                  "---\nname: docs\n---\nbody\n",
		"references/notes.md":       "# notes\n",
		"weights/model.safetensors": invalidUTF8Bytes,
		"data/table.parquet":        invalidUTF8Bytes,
		"blob.bin":                  invalidUTF8Bytes,
	})

	files, err := collectLocalSkillFiles(skillDir, true)
	if err != nil {
		t.Fatalf("collectLocalSkillFiles: %v", err)
	}

	paths := make([]string, 0, len(files))
	for _, f := range files {
		paths = append(paths, f.Path)
	}
	want := []string{"references/notes.md"}
	if !reflect.DeepEqual(paths, want) {
		t.Fatalf("collected paths = %v, want %v — an unlisted binary extension must still be caught by the content check", paths, want)
	}
}

// A binary file with no extension at all must be caught the same way.
func TestCollectLocalSkillFiles_SkipsInvalidUTF8WithNoExtension(t *testing.T) {
	root := t.TempDir()
	skillDir := writeTestLocalSkill(t, root, "docs", map[string]string{
		"SKILL.md":            "---\nname: docs\n---\nbody\n",
		"references/notes.md": "# notes\n",
		"references/README":   invalidUTF8Bytes,
	})

	files, err := collectLocalSkillFiles(skillDir, true)
	if err != nil {
		t.Fatalf("collectLocalSkillFiles: %v", err)
	}

	paths := make([]string, 0, len(files))
	for _, f := range files {
		paths = append(paths, f.Path)
	}
	want := []string{"references/notes.md"}
	if !reflect.DeepEqual(paths, want) {
		t.Fatalf("collected paths = %v, want %v — a no-extension binary file must still be caught by the content check", paths, want)
	}
}

// validUTF8WithNUL is UTF-16LE encoding of "Hello": every byte is a valid
// single-byte UTF-8 sequence (printable ASCII or NUL), so utf8.Valid alone
// would accept it — multica-eve's review on #7175 flagged this as a
// realistic byte-integrity hole: the server-side import path
// (server/internal/handler/skill_create.go's sanitizeNullBytes) strips every
// 0x00, so a file like this still comes back different from what went in.
const validUTF8WithNUL = "H\x00e\x00l\x00l\x00o\x00"

// A file with an unlisted extension that is valid UTF-8 but contains an
// embedded NUL must still be caught — utf8.Valid alone is not sufficient.
func TestCollectLocalSkillFiles_SkipsUnlistedExtensionWithEmbeddedNUL(t *testing.T) {
	root := t.TempDir()
	skillDir := writeTestLocalSkill(t, root, "docs", map[string]string{
		"SKILL.md":            "---\nname: docs\n---\nbody\n",
		"references/notes.md": "# notes\n",
		"weights/model.dat":   validUTF8WithNUL,
	})

	files, err := collectLocalSkillFiles(skillDir, true)
	if err != nil {
		t.Fatalf("collectLocalSkillFiles: %v", err)
	}

	paths := make([]string, 0, len(files))
	for _, f := range files {
		paths = append(paths, f.Path)
	}
	want := []string{"references/notes.md"}
	if !reflect.DeepEqual(paths, want) {
		t.Fatalf("collected paths = %v, want %v — valid UTF-8 with an embedded NUL must still be caught", paths, want)
	}
}

// A no-extension file with the same valid-UTF-8-but-NUL-containing content
// must be caught the same way.
func TestCollectLocalSkillFiles_SkipsNoExtensionWithEmbeddedNUL(t *testing.T) {
	root := t.TempDir()
	skillDir := writeTestLocalSkill(t, root, "docs", map[string]string{
		"SKILL.md":             "---\nname: docs\n---\nbody\n",
		"references/notes.md":  "# notes\n",
		"references/UTF16NAME": validUTF8WithNUL,
	})

	files, err := collectLocalSkillFiles(skillDir, true)
	if err != nil {
		t.Fatalf("collectLocalSkillFiles: %v", err)
	}

	paths := make([]string, 0, len(files))
	for _, f := range files {
		paths = append(paths, f.Path)
	}
	want := []string{"references/notes.md"}
	if !reflect.DeepEqual(paths, want) {
		t.Fatalf("collected paths = %v, want %v — a no-extension file with an embedded NUL must still be caught", paths, want)
	}
}

// A valid-UTF-8 text file — including one with an extension the blacklist
// doesn't recognize, and one with no extension at all — must still pass
// through untouched. The content check must not over-trigger on ordinary
// text.
func TestCollectLocalSkillFiles_ValidUTF8TextPassesThroughUntouched(t *testing.T) {
	root := t.TempDir()
	body := "# Notes\n\nContém acentos e emoji 🎉 — não é binário.\n"
	skillDir := writeTestLocalSkill(t, root, "docs", map[string]string{
		"SKILL.md":  "---\nname: docs\n---\nbody\n",
		"notes.txt": body,
		"data.csv":  "a,b,c\n1,2,3\n",
		"config":    "key=value\n",
	})

	files, err := collectLocalSkillFiles(skillDir, true)
	if err != nil {
		t.Fatalf("collectLocalSkillFiles: %v", err)
	}
	if len(files) != 3 {
		t.Fatalf("expected all 3 valid-UTF-8 supporting files to pass through, got %d: %+v", len(files), files)
	}
	for _, f := range files {
		if f.Path == "notes.txt" && f.Content != body {
			t.Errorf("notes.txt content = %q, want %q", f.Content, body)
		}
	}
}

func TestClaudeLocalSkillsUseDaemonConfigRootForListAndImport(t *testing.T) {
	home := t.TempDir()
	redirectTestHome(t, home)
	isolatedHome := t.TempDir()
	configDir := filepath.Join(isolatedHome, ".claude")
	t.Setenv("CLAUDE_CONFIG_DIR", configDir)
	skillFiles := map[string]string{"SKILL.md": "---\nname: Fixture\ndescription: Fixture\n---\nFixture\n"}
	writeTestLocalSkill(t, filepath.Join(home, ".claude", "skills"), "host-skill", skillFiles)
	writeTestLocalSkill(t, filepath.Join(configDir, "skills"), "isolated-skill", skillFiles)
	installPath := writeTestClaudePlugin(t, isolatedHome, "example@fixture", "example", true)
	writeTestLocalSkill(t, filepath.Join(installPath, "skills"), "plugin-skill", skillFiles)

	skills, supported, err := listRuntimeLocalSkills("claude")
	if err != nil || !supported || len(skills) != 2 {
		t.Fatalf("list: supported=%v err=%v skills=%+v", supported, err, skills)
	}
	for _, key := range []string{"isolated-skill", "example:plugin-skill"} {
		found := false
		for _, skill := range skills {
			found = found || skill.Key == key
		}
		if !found {
			t.Errorf("missing %q in list: %+v", key, skills)
		}
		if bundle, _, err := loadRuntimeLocalSkillBundle("claude", key); err != nil || bundle == nil {
			t.Errorf("load %q: bundle=%v err=%v", key, bundle, err)
		}
	}
}